supabase / auth-js

An isomorphic Javascript library for Supabase Auth.
MIT License
357 stars 160 forks source link

feat: add experimental lock option with no-op default #731

Closed hf closed 1 year ago

hf commented 1 year ago

Adds an @experimental lock option and uses it in _useSession. This can be used to test out different lock implementations before committing to a default one within this library.

It includes an implementation of a broadcastLock which can be used as a value to lock but is not done by default intentionally. This is an experimental API that is bound to have changes and potentially serious bugs. Once it has been well tested by the team and others it is likely to be promoted to the default option.

broadcastLock

Uses a BroadcastChannel to serialize access to a named critical section. The lock has three states: Acquiring, Backoff and Acquired.

When in the Acquiring state, a message is broadcast I will acquire the lock! and a timeout is started. If any message is received in this state, the lock immediately moves to the Backoff state. If no message is received, the lock moves to the Acquired state. It is assumed that if two messages are posted simultaneously at the channel, that both locks will receive the other's message.

When in the Backoff state, the lock sleeps for random amount of time before moving back in the Acquiring state. Each time it enters this state, it waits exponentially longer than the last time.

When in the Acquired state, the lock broadcasts I have the lock, please wait!. If any message is received on the channel, I have the lock! is broadcast immediately. The sender of the first I will acquire the lock! message received in this state will be sent the Go message after the operation is done which gives it priority over all other competing locks. This helps reduce the time needed for the locks to identify who should go next. Once the operation is done, the lock stops replying with I have the lock, please wait! messages on the channel.

Illustration of how `broadcastLock` works

hf commented 1 year ago

I will actually re-open with the broadcastLock in a new PR and just the locking code here.