📜 ⬆️ ⬇️

ShareJS hook logic

There are 4 hooks in the ShareJS commit loop. You can see the implementation of two of them (submit and after submit) in the ShareJS code . And the other two (preValidate and validate) in the code LiveDB .


The sequence for calling hooks is:

  1. ShareJS launches submit middleware, which has access to the operation, collection name, document name (_id for MongoDB) and connect-session. This middleware is launched asynchronously during the initial processing of the operation, before attempting to use it. Thus, in it you can asynchronously get the data needed for access control or manipulate the operation.
  2. LiveDB calls the preValidate method. He gets everything available in the submit middleware, as well as the document before the operation. This method is called synchronously in the process of committing an operation and can be called multiple times.
  3. LiveDB runs the validate method. It works the same as the previous one, only called after the operation with the document has been performed.
  4. ShareJS runs after submit middleware, which receives the same data as submit, and also the document after the operation. It runs asynchronously, immediately after saving the operation and publishing it to subscribers.

')
We spent a lot of time discussing the details of these hooks and we deliberately left them fairly low-level within ShareJS / LiveDB.

LiveDB methods are intentionally synchronized. These methods can be invoked many times during the validation process, because if two different clients change the same document at the same time, the client first wins and subsequent attempts are rejected until the operation is completed. Adding asynchronous calls to get additional data here would be inefficient given that methods can be called multiple times. In addition, it couldn’t be consistently trying to complete the process. Synchronous calls significantly reduce the likelihood of this.

Validation in LiveDB is divided into two methods to avoid permanent, often unnecessary cloning of a document. If you want to have a single validation call with document variants before and after the operation, you can deeply clone the document in preValidate and then use it and the modified version in validate.

The correct method of obtaining additional data for access control is to use Express middleware or ShareJS submit middleware, and add their session, which is transmitted to preValidate / validate.

The current implementation is a bit confusing and ideally racer-access should have a more intuitive API and documentation. I’m happy to make suggestions for improving racer-access, but I don’t think it makes sense to change something in LiveDB.

Source: https://habr.com/ru/post/205220/


All Articles