Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/web-locks-leader-takeover.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/offline-transactions': patch
---

Let a follower tab take over when the Web Locks leader releases or closes. A tab that finds the lock held now waits in its queue, then becomes leader and replays the outbox instead of staying online-only until it reloads. A request made right after a release starts a new acquisition, a listener that releases leadership as it is told the tab leads passes the lock on and can queue again at once; with the BroadcastChannel fallback, such a release also leaves no claim or heartbeat behind, and a leadership callback that throws no longer stops the takeover's replay.
10 changes: 10 additions & 0 deletions docs/contributing/oracle-coverage.md
Original file line number Diff line number Diff line change
Expand Up @@ -4241,6 +4241,16 @@ The post-merge review added three missing domains to existing owners:
contribution bag and source-row identity, as well as output length and zero
getter reads. A multiple-key constructed history and duplicate-key/omitted-key
calibration protect that distinction.
- [Web Locks leadership](https://github.com/TanStack/db/blob/main/packages/offline-transactions/tests/web-locks-leader-oracle.property.test.ts)
checks FIFO takeover across three tabs that request, release and close over a
controlled lock manager, including a request renewed after a release in one
turn and a listener that releases, releases and requests again, or throws
when told its tab leads. It does not cover real browser contexts.
- [BroadcastChannel leadership](https://github.com/TanStack/db/blob/main/packages/offline-transactions/tests/broadcast-channel-leader-oracle.property.test.ts)
checks the fallback elector's requests, releases, elections and heartbeats on
one tab against a timeline model, including a listener that releases, or
releases and requests again, when told its tab leads. It does not cover peer
tabs or a real BroadcastChannel.
- [Leadership replay](https://github.com/TanStack/db/blob/main/packages/offline-transactions/tests/leadership-replay-oracle.property.test.ts)
holds real storage-read delivery across successful and permanently rejected
durable removals, with bounded scans, concurrent loads, and unfinished peers.
Expand Down
2 changes: 2 additions & 0 deletions packages/db/tests/oracle-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,8 @@ const staticOracleProperties = [
`offline.leadership.startup`,
`offline.leadership.stale-read`,
`offline.leadership.storage-failure`,
`offline.web-locks-leader`,
`offline.broadcast-channel-leader`,
`offline.serializer.mutation-wire`,
`offline.serializer.date-marker`,
`offline.serializer.version-two`,
Expand Down
10 changes: 10 additions & 0 deletions packages/db/tests/oracle-replay-manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1796,6 +1796,16 @@ const ownerGroups: ReadonlyArray<
`offline`,
`leadership.serial-work leadership.report leadership.delayed-read leadership.startup leadership.stale-read leadership.storage-failure`,
],
[
`offline-transactions/tests/web-locks-leader-oracle.property.test.ts`,
`offline`,
`web-locks-leader`,
],
[
`offline-transactions/tests/broadcast-channel-leader-oracle.property.test.ts`,
`offline`,
`broadcast-channel-leader`,
],
[
`offline-transactions/tests/transaction-serializer-oracle.property.test.ts`,
`offline`,
Expand Down
10 changes: 6 additions & 4 deletions packages/offline-transactions/src/OfflineExecutor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -243,15 +243,17 @@ export class OfflineExecutor {
this.isLeaderState = isLeader
if (!isLeader) this.executor?.pause()

if (this.config.onLeadershipChange) {
this.config.onLeadershipChange(isLeader)
}

// Replay starts first, so a failing application callback cannot
// stop a takeover from sending the outbox.
if (isLeader) {
this.loadAndReplayTransactions().catch((error) => {
console.warn(`Failed to load and replay transactions:`, error)
})
}

if (this.config.onLeadershipChange) {
this.config.onLeadershipChange(isLeader)
}
},
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,13 +96,13 @@ export class BroadcastChannelLeader extends BaseLeaderElection {
})

this.electionTimeout = window.setTimeout(() => {
// Cleared first: a listener told of the claim may start the next one.
this.electionTimeout = null
const timeSinceLastHeartbeat = Date.now() - this.lastLeaderHeartbeat

if (timeSinceLastHeartbeat > this.electionTimeoutMs) {
this.claimLeadership()
}

this.electionTimeout = null
}, this.electionTimeoutMs)
}

Expand All @@ -115,6 +115,8 @@ export class BroadcastChannelLeader extends BaseLeaderElection {

private claimLeadership(): void {
this.notifyLeadershipChange(true)
// A listener may have released already, leaving nothing to announce.
if (!this.isLeaderState) return
this.sendMessage({
type: `leadership-claim`,
tabId: this.tabId,
Expand Down
31 changes: 23 additions & 8 deletions packages/offline-transactions/src/coordination/LeaderElection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ import type { LeaderElection } from '../types'
export abstract class BaseLeaderElection implements LeaderElection {
protected isLeaderState = false
protected listeners: Set<(isLeader: boolean) => void> = new Set()
// The state changes at once; listeners hear changes in order, so one that a
// listener causes waits until every listener heard the current one.
private notifying = false
private readonly queued: Array<boolean> = []

abstract requestLeadership(): Promise<boolean>
abstract releaseLeadership(): void
Expand All @@ -20,16 +24,27 @@ export abstract class BaseLeaderElection implements LeaderElection {
}

protected notifyLeadershipChange(isLeader: boolean): void {
if (this.isLeaderState !== isLeader) {
this.isLeaderState = isLeader

for (const listener of this.listeners) {
try {
listener(isLeader)
} catch (error) {
console.warn(`Leadership change listener error:`, error)
if (this.isLeaderState === isLeader) return
this.isLeaderState = isLeader
this.queued.push(isLeader)
if (this.notifying) return
this.notifying = true
try {
for (
let next = this.queued.shift();
next !== undefined;
next = this.queued.shift()
) {
for (const listener of this.listeners) {
try {
listener(next)
} catch (error) {
console.warn(`Leadership change listener error:`, error)
}
}
}
} finally {
this.notifying = false
}
}
}
130 changes: 83 additions & 47 deletions packages/offline-transactions/src/coordination/WebLocksLeader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ import { BaseLeaderElection } from './LeaderElection'
export class WebLocksLeader extends BaseLeaderElection {
private lockName: string
private releaseLock: (() => void) | null = null
// Set while this tab waits in the lock's queue, to leave it on release.
private waiting: AbortController | undefined
private pendingRequest: Promise<boolean> | null = null
private requestGeneration = 0

constructor(lockName = `offline-executor-leader`) {
super()
Expand All @@ -14,68 +18,100 @@ export class WebLocksLeader extends BaseLeaderElection {
return false
}

if (this.isLeaderState) {
// Possession, not the notified state: a release clears the handle at
// once, while its notification can still wait behind the gain's.
if (this.releaseLock) {
return true
}

try {
// First try to acquire the lock with ifAvailable
const available = await navigator.locks.request(
this.lockName,
{
mode: `exclusive`,
ifAvailable: true,
},
(lock) => {
return lock !== null
},
)
if (this.waiting) {
return false
}

if (!available) {
return false
}
// Requests share one attempt until a release voids it.
if (!this.pendingRequest) {
const attempt = this.acquireOrWait().finally(() => {
if (this.pendingRequest === attempt) this.pendingRequest = null
})
this.pendingRequest = attempt
}
return this.pendingRequest
}

// Set state immediately to prevent duplicate notifications
// when the async lock acquisition calls notifyLeadershipChange(true).
// The guard in notifyLeadershipChange checks `isLeaderState !== isLeader`,
// so setting this to true here prevents the callback from firing again.
this.isLeaderState = true
private async acquireOrWait(): Promise<boolean> {
const generation = this.requestGeneration
try {
return await new Promise<boolean>((resolve, reject) => {
navigator.locks
.request(this.lockName, { ifAvailable: true }, (lock) => {
// Released while this request was pending.
if (generation !== this.requestGeneration) {
resolve(false)
return
}

// Lock is available, now acquire it for real and hold it
navigator.locks.request(
this.lockName,
{
mode: `exclusive`,
},
async (lock) => {
if (lock) {
this.notifyLeadershipChange(true)
// Hold the lock until released
return new Promise<void>((resolve) => {
this.releaseLock = () => {
this.notifyLeadershipChange(false)
resolve()
}
})
}
},
)
if (!lock) {
this.waitForLeadership()
resolve(false)
return
}

return true
// Set state directly: the caller learns this result from the
// returned promise, so it is not a leadership change.
this.isLeaderState = true
resolve(true)
return this.holdLock()
})
.catch(reject)
})
} catch (error) {
if (error instanceof Error && error.name === `AbortError`) {
return false
}
console.warn(`Web Locks leadership request failed:`, error)
return false
}
}

// Queues for the lock, which is granted when the current holder releases it
// or its tab closes.
private waitForLeadership(): void {
const waiting = new AbortController()
this.waiting = waiting
navigator.locks
.request(this.lockName, { signal: waiting.signal }, () => {
// An abort has no effect once the lock is granted.
if (this.waiting !== waiting) return
this.waiting = undefined
// Hold first, so a listener that releases on the gain lets go.
const held = this.holdLock()
this.notifyLeadershipChange(true)
return held
})
.catch((error: unknown) => {
if (waiting.signal.aborted) return
this.waiting = undefined
console.warn(`Web Locks leadership request failed:`, error)
})
}

private holdLock(): Promise<void> {
return new Promise<void>((resolve) => {
this.releaseLock = () => {
this.notifyLeadershipChange(false)
resolve()
}
})
}

releaseLeadership(): void {
if (this.releaseLock) {
this.releaseLock()
this.releaseLock = null
this.requestGeneration++
this.pendingRequest = null
if (this.waiting) {
const waiting = this.waiting
this.waiting = undefined
waiting.abort()
}
const release = this.releaseLock
this.releaseLock = null
release?.()
}

private isWebLocksSupported(): boolean {
Expand Down
Loading