Skip to content

Use Promise chaining to enforce read/write queue#699

Merged
delucis merged 2 commits into
boardgameio:masterfrom
jabza:jabza/FlatFile-Queue
May 17, 2020
Merged

Use Promise chaining to enforce read/write queue#699
delucis merged 2 commits into
boardgameio:masterfrom
jabza:jabza/FlatFile-Queue

Conversation

@jabza
Copy link
Copy Markdown
Contributor

@jabza jabza commented May 16, 2020

A problem in node-persist, used by FlatFile, means multiple async read/writes to the same file are allowed (no file-locking) and can and does cause corruption (which may or may not be caught) in higher frequency situations.

This PR uses a Promise chain to ensure only one async read/write is performed at a time. The queue is rather crude, but does guarantee no multiple writes (if only one FlatFile instance is being used on that directory).

In the future it would be nice to have Promise chain per-file, or seek alternatives to node-persist.
However, for now, this solution has been working for my own project and it's probably worth the added protection vs the potential performance loss.

Checklist

  • Use a separate branch in your local repo (not master).
  • Test coverage is 100% (or you have a story for why it's ok).

Closes #694

Copy link
Copy Markdown
Member

@delucis delucis left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @jabza! Do you think we could add a layer of abstraction to make this less verbose?

Something like:

this.request = <T extends any = any>(action: () => Promise<T>): Promise<T> => {
  this.requests = this.requests.then(action, action);
  return this.requests
}

So we can use it like this:

result.state = (await this.request(() => this.games.getItem(gameID))) as State;

Or even better in terms of code clarity might be if you created a separate wrapper for get and set, so we could just do:

result.state = (await this.getRequest(gameID)) as State;

What do you think?

@jabza
Copy link
Copy Markdown
Contributor Author

jabza commented May 17, 2020

Went with your first option. Pushed that change now

Copy link
Copy Markdown
Member

@delucis delucis left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good. Thank you!

@delucis delucis merged commit 3a622f1 into boardgameio:master May 17, 2020
jabza pushed a commit to jabza/boardgame.io that referenced this pull request May 20, 2020
Use Promise chaining to enforce read/write queue (boardgameio#699)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

FlatFile save corruption "..does not look like a valid storage file ...FSReqCallback.readFileAfterClose "

2 participants