-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
feat: add useWebLocks (Web Locks API) and useLeaderElection #4574
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
d--j
wants to merge
1
commit into
vueuse:main
Choose a base branch
from
d--j:useOnceInAllTabs
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
<script setup lang="ts"> | ||
import { formatTimeAgo, useBroadcastChannel, useIntervalFn, useLeaderElection, useNow } from '@vueuse/core' | ||
import { computed, ref, watch } from 'vue' | ||
|
||
const { isSupported, isLeader, asLeader } = useLeaderElection({ name: 'vueuse-demo-shared-session' }) | ||
interface Session { expires: number, username: string } | ||
const { data, post } = useBroadcastChannel<Session | null | undefined, Session | null>({ name: 'vueuse-demo-shared-session' }) | ||
const now = useNow({ interval: 1000 }) | ||
const { pause, resume, isActive } = useIntervalFn(() => { | ||
if (data.value === null) { | ||
pause() | ||
return | ||
} | ||
asLeader(async (signal) => { | ||
if (data.value === undefined || data.value!.expires > Date.now() - 1000 * 60) { | ||
pause() | ||
try { | ||
// const newSession = await (await fetch('/refresh/session', { signal, credentials: 'include' })).json() as Session | ||
const newSession = { expires: now.value.getTime() + 1000 * 60 * 2, username: 'demo-user' } | ||
data.value = newSession | ||
post(newSession) | ||
} | ||
finally { | ||
resume() | ||
} | ||
} | ||
}) | ||
}) | ||
function login() { | ||
const newSession = { expires: now.value.getTime() + 1000 * 60 * 2, username: 'demo-user' } | ||
data.value = newSession | ||
post(newSession) | ||
} | ||
function logout() { | ||
data.value = null | ||
post(null) | ||
} | ||
const isLoggedIn = computed(() => !!data.value?.username) | ||
const expires = computed(() => { | ||
const _ = now.value | ||
if (data.value?.expires) { | ||
formatTimeAgo(new Date(data.value?.expires)) | ||
} | ||
return '' | ||
}) | ||
watch(isLeader, (leader) => { | ||
if (leader) { | ||
resume() | ||
} | ||
else { | ||
pause() | ||
} | ||
}) | ||
const message = ref('') | ||
</script> | ||
|
||
<template> | ||
<div> | ||
<p>isSupported: <BooleanDisplay :value="isSupported" class="font-bold" /></p> | ||
<p>isLeader: <BooleanDisplay :value="isLeader" class="font-bold" /></p> | ||
<p>isActive: <BooleanDisplay :value="isActive" class="font-bold" /></p> | ||
<p>isLoggedIn: <BooleanDisplay :value="isLoggedIn" class="font-bold" /></p> | ||
<p>expires: {{ expires }}</p> | ||
<p>data: {{ data }}</p> | ||
</div> | ||
|
||
<div v-if="isSupported"> | ||
<div class="flex gap-2"> | ||
<p>💡</p> | ||
<p class="flex-1"> | ||
Please open this page in at least two tabs.<br> | ||
Close and open tabs or change pages in them to see that only one tab will be the leader. | ||
</p> | ||
</div> | ||
<button :disabled="isLoggedIn" @click="login"> | ||
Login | ||
</button> | ||
<button :disabled="!isLoggedIn" @click="logout"> | ||
Logout | ||
</button> | ||
<span class="ml-2"> | ||
{{ message }} | ||
</span> | ||
</div> | ||
<div v-else> | ||
Aww, snap! The Web Locks API is not supported in your browser. | ||
</div> | ||
</template> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,90 @@ | ||
import { mount } from '@vue/test-utils' | ||
import { useLeaderElection, useWebLocksAbortScopeDisposed } from '@vueuse/core' | ||
import { promiseTimeout } from '@vueuse/shared' | ||
import { describe, expect, it } from 'vitest' | ||
import { type Ref, ref } from 'vue' | ||
|
||
function nextFrame() { | ||
return promiseTimeout(15) // we assume that browser can handle lock requests in this time | ||
} | ||
|
||
describe('useLeaderElection', () => { | ||
it('should be supported', () => { | ||
const { isSupported } = useLeaderElection({ name: 'vitest-leader-1' }) | ||
expect(isSupported.value).toBe(true) | ||
}) | ||
it('should work as expected', async () => { | ||
const component = { | ||
template: '<span></span>', | ||
setup() { | ||
const { isSupported, isLeader } = useLeaderElection({ name: 'vitest-leader-2' }) | ||
return { isSupported, isLeader } | ||
}, | ||
} | ||
const wrapper1 = mount(component) | ||
const vm1 = wrapper1.vm | ||
expect(vm1.isSupported).toBe(true) | ||
await nextFrame() | ||
expect(vm1.isLeader).toBe(true) | ||
const wrapper2 = mount(component) | ||
const vm2 = wrapper2.vm | ||
expect(vm2.isSupported).toBe(true) | ||
await nextFrame() | ||
expect(vm2.isLeader).toBe(false) | ||
wrapper1.unmount() | ||
wrapper2.unmount() | ||
const wrapper3 = mount(component) | ||
const vm3 = wrapper3.vm | ||
expect(vm3.isSupported).toBe(true) | ||
await nextFrame() | ||
expect(vm3.isLeader).toBe(true) | ||
wrapper3.unmount() | ||
}) | ||
it('should support dynamic names', async () => { | ||
let capturedName: Ref<string> | ||
const component = { | ||
template: '<span></span>', | ||
setup() { | ||
const name = ref('vitest-leader-3') | ||
const { isSupported, isLeader } = useLeaderElection({ name }) | ||
capturedName = name | ||
return { isSupported, isLeader } | ||
}, | ||
} | ||
const wrapper1 = mount(component) | ||
const vm1 = wrapper1.vm | ||
expect(vm1.isSupported).toBe(true) | ||
await nextFrame() | ||
expect(vm1.isLeader).toBe(true) | ||
capturedName!.value = 'vitest-leader-4' | ||
// isLeader is false right after the name change | ||
expect(vm1.isLeader).toBe(false) | ||
await nextFrame() | ||
expect(vm1.isLeader).toBe(true) | ||
wrapper1.unmount() | ||
}) | ||
it('should abort the workload signal on scope dispose', async () => { | ||
let capturedAsLeader: ReturnType<typeof useLeaderElection>['asLeader'] | ||
const component = { | ||
template: '<span></span>', | ||
setup() { | ||
const { isSupported, asLeader } = useLeaderElection({ name: 'vitest-leader-3' }) | ||
capturedAsLeader = asLeader | ||
return { isSupported } | ||
}, | ||
} | ||
const wrapper1 = mount(component) | ||
const vm1 = wrapper1.vm | ||
expect(vm1.isSupported).toBe(true) | ||
await nextFrame() | ||
expect(capturedAsLeader!(() => {})).toBe(true) | ||
let capturesReason | ||
capturedAsLeader!(async (signal) => { | ||
await promiseTimeout(250) | ||
capturesReason = signal?.reason | ||
}) | ||
wrapper1.unmount() | ||
await promiseTimeout(300) | ||
expect(capturesReason).toBe(useWebLocksAbortScopeDisposed) | ||
}) | ||
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
--- | ||
category: Browser | ||
--- | ||
|
||
# useLeaderElection | ||
|
||
Uses the [Web Locks API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Locks_API) to elect one tab as leader. | ||
|
||
Use this composable to e.g. refresh a session only once even when multiple tabs of your application are open or multiple worker are running. | ||
|
||
## Usage | ||
|
||
```ts | ||
import { useLeaderElection } from '@vueuse/core' | ||
|
||
const { asLeader, isElected, isSupported } = useLeaderElection({ name: 'lock-name' }) | ||
// … later in your component | ||
asLeader(() => { | ||
/* your code that only needs to be executed in one tab */ | ||
}) | ||
``` | ||
|
||
### Example: Shared Session | ||
|
||
You can combine `useLeaderElection` with `useBroadcastChannel` to keep a shared session among all open tabs of your application. | ||
If you log out in one tab you will be logged out in all tabs. Only one tab is responsible to refresh the shared session | ||
periodically: | ||
|
||
```ts | ||
import { useBroadcastChannel, useIntervalFn, useLeaderElection } from '@vueuse/core' | ||
import { computed, watch } from 'vue' | ||
|
||
const { asLeader, isLeader } = useLeaderElection({ name: 'shared-session' }) | ||
interface Session { expires: number, username: string } | ||
const { data, post } = useBroadcastChannel<Session | null | undefined, Session | null>({ name: 'shared-session' }) | ||
const { pause, resume } = useIntervalFn(() => { | ||
if (data.value === null) { | ||
pause() | ||
return | ||
} | ||
asLeader(async (signal) => { | ||
if (data.value === undefined || data.value?.expires > Date.now() - 1000 * 60 * 5) { | ||
pause() | ||
try { | ||
const newSession = (await fetch('/refresh/session', { signal, credentials: 'include' })).json() | ||
data.value = newSession | ||
post(newSession) | ||
} | ||
finally { | ||
resume() | ||
} | ||
} | ||
}) | ||
}) | ||
function logout() { | ||
data.value = null | ||
post(null) | ||
} | ||
const isLoggedIn = computed(() => !!data.value?.username) | ||
watch(isLeader, (leader) => { | ||
if (leader) { | ||
resume() | ||
} | ||
else { | ||
pause() | ||
} | ||
}) | ||
``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
import { describe, expect, it, vi } from 'vitest' | ||
import { useLeaderElection } from '.' | ||
|
||
describe('useLeaderElection', () => { | ||
it('should be defined', () => { | ||
expect(useLeaderElection).toBeDefined() | ||
}) | ||
|
||
it('should be doing work', () => { | ||
const { asLeader } = useLeaderElection({ name: 'vitest-use-once-in-all-tabs' }) | ||
|
||
const fn = vi.fn() | ||
asLeader(fn) | ||
expect(fn).toHaveBeenCalledTimes(1) | ||
}) | ||
|
||
it('should not be supported', () => { | ||
const { isSupported } = useLeaderElection({ name: 'vitest-use-once-in-all-tabs' }) | ||
expect(isSupported.value).toBe(false) | ||
}) | ||
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
import type { ComputedRef, MaybeRefOrGetter, Ref, WatchOptionsBase } from 'vue' | ||
import type { ConfigurableNavigator } from '../_configurable' | ||
import { tryOnScopeDispose } from '@vueuse/shared' | ||
import { readonly, ref, toValue, watchEffect } from 'vue' | ||
import { defaultNavigator } from '../_configurable' | ||
import { isExpectedWebLockRejection, useWebLocks } from '../useWebLocks' | ||
|
||
export interface UseLeaderElectionOptions<Keys extends string = string> extends ConfigurableNavigator, WatchOptionsBase { | ||
/** | ||
* The name of the lock that gets used to elect the one tab that does the work. | ||
* Needs to be uniq throughout the origin. | ||
*/ | ||
name: MaybeRefOrGetter<Keys> | ||
} | ||
|
||
export interface UseLeaderElectionReturn { | ||
/** | ||
* Returns whether the Web Locks API is supported by the current browser. | ||
*/ | ||
isSupported: ComputedRef<boolean> | ||
|
||
/** | ||
* Reactive boolean that tracks whether the current tab was elected as the one tab to do the work. | ||
* If the tab was elected as leader it will stay the leader until the current scope gets disposed. | ||
* Then a new tab becomes the leader. isElected will only ever transition from `false` to `true` in | ||
* the lifetime of a component (when the lock name does not dynamically change). | ||
*/ | ||
isLeader: Readonly<Ref<boolean>> | ||
|
||
/** | ||
* Executes the workload function if the Web Locks API is not supported or if the current tab is the elected tab. | ||
* The workload function gets passed a signal that gets aborted when the scope gets disposed/we stop being the leader. | ||
* `signal` will be `undefined` when `isSupported` is `false`. | ||
* | ||
* @return `true` when the workload function was executed `false` otherwise. | ||
*/ | ||
asLeader: (workload: (signal?: AbortSignal) => void) => boolean | ||
} | ||
|
||
/** | ||
* Ensure that code gets executed only in one of many tabs. | ||
* | ||
* @see https://vueuse.org/useLeaderElection/ | ||
* @param [options] | ||
*/ | ||
export function useLeaderElection<Keys extends string = string>(options: UseLeaderElectionOptions<Keys>): UseLeaderElectionReturn { | ||
const { | ||
name, | ||
navigator = defaultNavigator, | ||
flush = 'sync', | ||
} = options | ||
const { isSupported, request } = useWebLocks<Record<string, void>>({ navigator }) | ||
const isLeader = ref(false) | ||
let currentSignal: AbortSignal | undefined | ||
const asLeader = (workload: (signal?: AbortSignal) => void) => { | ||
if ((isSupported.value && isLeader.value) || !isSupported.value) { | ||
workload(currentSignal) | ||
return true | ||
} | ||
else { | ||
return false | ||
} | ||
} | ||
if (isSupported.value) { | ||
let currentLock: (() => void) | undefined | ||
const stopWatch = watchEffect(() => { | ||
if (currentLock) { | ||
isLeader.value = false | ||
currentSignal = undefined | ||
currentLock() | ||
currentLock = undefined | ||
} | ||
request(toValue(name), (signal) => { | ||
currentSignal = signal | ||
isLeader.value = true | ||
return new Promise((resolve) => { | ||
currentLock = resolve | ||
}) | ||
}).catch((error) => { | ||
if (!isExpectedWebLockRejection(error)) { | ||
// can be InvalidStateError, SecurityError, or NotSupportedError | ||
// see https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request#exceptions | ||
throw error | ||
} | ||
}) | ||
}, { flush }) | ||
tryOnScopeDispose(stopWatch) | ||
} | ||
|
||
return { isSupported, isLeader: readonly(isLeader), asLeader } | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.