MatthewWid / better-sse

⬆ Dead simple, dependency-less, spec-compliant server-sent events implementation for Node, written in TypeScript.
MIT License
485 stars 14 forks source link

Event batching #42

Closed MatthewWid closed 11 months ago

MatthewWid commented 2 years ago

Add a mechanism that allows the user to batch events emitted with push over time and then emit them all at once.

This will allow users with more advanced use-cases to optimise their code if they are submitting a large number of events in a short period of time, minimising the number of calls to res.write.

This will also be used in the new history API (#16) to batch the mass number of event emissions when sending missed events back to the client.

There are some options for what this API can look like listed below.


The first is having a stateful tracking of when batching is turned on or off and then disabling the no-oping the dispatch method while it is enabled:

session.beginBatch();
...
session.endBatch();

This is likely the most complex option to implement and may have a negative performance impact as every call to the data-writing methods will now have to check if batching is enabled or not.


The second option is to allow the user to provide a callback and have any method calls made within that callback be batched internally and then flushed upon completion:

session.batch(() => {
    ...
    session.push("Hello world");
    ...
});

The third is adding a new Batched class which stores the original session and provides special versions of all the helper methods (push, stream and iterate). This is accessed via a user-given callback on the Session class.

session.batch((batched) => {
    ...
    batched.push("Hello world");
    ...
});

This is the easiest to implement and likely the most performant, though may be a little confusing when you need to access non-helper methods as Batched won't be a sub-class of Session, so you'll need to use the original session instance instead.

MatthewWid commented 11 months ago

Implemented in v0.10.0