Skip to content
Merged
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
1 change: 1 addition & 0 deletions packages/account/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"license": "MIT",
"type": "module",
"exports": {
"./boundedOperation": "./src/core/boundedOperation.ts",
"./session": "./src/core/session.ts",
"./billing": "./src/core/billing/index.ts",
"./firebase": "./src/firebase/index.ts",
Expand Down
78 changes: 78 additions & 0 deletions packages/account/src/core/boundedOperation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { describe, expect, it } from 'vitest'

import { createBoundedOperation } from './boundedOperation.js'

describe('createBoundedOperation', () => {
it('captures a handle that is live until the operation is abandoned', () => {
const operation = createBoundedOperation()
const handle = operation.capture()

expect(handle.live()).toBe(true)
operation.abandon()
expect(
handle.live(),
'a captured attempt must not survive its own abandonment'
).toBe(false)
})

it('invalidates every outstanding handle when abandoned, not only the latest', () => {
const operation = createBoundedOperation()
const first = operation.capture()
const second = operation.capture()

operation.abandon()

expect(first.live()).toBe(false)
expect(
second.live(),
'one abandonment must drop all in-flight attempts, not just the newest'
).toBe(false)
})

it('leaves an earlier handle live when a later capture supersedes nothing', () => {
const operation = createBoundedOperation()
const earlier = operation.capture()
operation.capture()

expect(
earlier.live(),
'capture alone is not invalidation; only abandon ends prior attempts'
).toBe(true)
})

it('keeps each prior cycle dead while the latest capture stays live', () => {
const operation = createBoundedOperation()

const first = operation.capture()
operation.abandon()
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const second = operation.capture()

expect(first.live()).toBe(false)
expect(second.live()).toBe(true)

operation.abandon()
const third = operation.capture()

expect(
second.live(),
'each abandonment must end its own cycle, not only the first'
).toBe(false)
expect(third.live()).toBe(true)
})

it('discards a result that resolves after the operation was abandoned mid-flight', async () => {
const operation = createBoundedOperation()
const handle = operation.capture()

const pendingRead = (async () => {
await Promise.resolve()
return handle.live()
})()
operation.abandon()

expect(
await pendingRead,
'work re-checked across an await must not publish once superseded'
).toBe(false)
})
})
29 changes: 29 additions & 0 deletions packages/account/src/core/boundedOperation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* A monotonic owner for work that outlives an await: each `capture()` snapshots
* the current generation and returns a handle whose `live()` stays true until
* `abandon()` bumps the generation. A flag flip, a reset, or teardown calls
* `abandon()`; the in-flight work re-checks `live()` after every await and drops
* its result once superseded, so a stale sign-in, mint, or fetch can never
* publish for an attempt that no longer owns the outcome.
*/
export interface OperationHandle {
live: () => boolean
}

export interface BoundedOperation {
capture: () => OperationHandle
abandon: () => void
}

export function createBoundedOperation(): BoundedOperation {
let generation = 0
return {
capture() {
const captured = generation

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question (non-blocking): Answering the Review Focus directly — I checked this semantic against the call sites that will adopt it, and it holds for two of the three cleanly:

  • workshop-balance.ts — startGeneration = generation at read start, reset() bumps. Maps onto capture() / abandon() one-to-one.
  • workshop-credits.ts:155,171 — clearTopUpWatch() bumps and then const generation = topUpGeneration. This is already literally abandon() then capture().

The third is where I would like your read. workshop-session-state.ts:256 is const expectedGeneration = ++generation — bump-and-capture fused into one expression, and regionGate.ts:29 has the same ++generation shape. Under this primitive each becomes two calls, and the failure mode is asymmetric: if a migration drops the abandon(), nothing breaks loudly, the prior attempt just silently stays live and a superseded begin() can publish over the new one. It fails open rather than closed, so a review would have to notice the missing line.

Is a supersede() (abandon-then-capture in one call) worth adding for those sites, or do you prefer keeping the two steps explicit so the intent is visible at each call? Happy either way — I only want to make sure the fused sites get deliberate attention in A3b through A3e rather than a mechanical rewrite. Worth noting workshop-session-state.failure.test.ts already pins the latch-reopen behavior, so that migration has a regression net; regionGate.ts does not.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On workshop-session-state, the old ++generation is supersede-then-start, which the migration expresses as operation.abandon() then operation.capture() in the flag watch: abandon bumps the generation so the prior in-flight attempt goes dead, capture snapshots the new one. Same 1:1 mapping as the other two sites, just with the explicit abandon first.

return { live: () => captured === generation }
},
abandon() {
generation += 1
}
}
}
3 changes: 3 additions & 0 deletions packages/account/src/vue/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ export type { PasswordRulesCopy } from './PasswordRules.vue'
export { default as PasswordRules } from './PasswordRules.vue'
export { default as SocialAuthButtons } from './SocialAuthButtons.vue'
export { default as TurnstileWidget } from './TurnstileWidget.vue'
export { createLifecycleScope } from './lifecycleScope'
export type { LifecycleScope } from './lifecycleScope'
export type { RegionGateStatus } from './regionGate'
export { useRegionGate } from './regionGate'
export { useTurnstileGate } from './turnstileGate'
export { useGenerationGuard } from './useGenerationGuard'
80 changes: 80 additions & 0 deletions packages/account/src/vue/lifecycleScope.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { describe, expect, it, vi } from 'vitest'
import { onScopeDispose, ref, watch } from 'vue'

import { createLifecycleScope } from './lifecycleScope'

describe('createLifecycleScope', () => {
it('runs the setup once and ignores a second start while running', () => {
const lifecycle = createLifecycleScope()
const setup = vi.fn()

lifecycle.start(setup)
lifecycle.start(setup)

expect(
setup,
'a module singleton must install its listeners once, not per caller'
).toHaveBeenCalledOnce()
})

it('disposes the running scope so its watchers stop', () => {
const lifecycle = createLifecycleScope()
const source = ref(0)
const seen: number[] = []
lifecycle.start(() => {
watch(source, (value) => seen.push(value), { flush: 'sync' })
})

source.value = 1
lifecycle.stop()
source.value = 2

expect(
seen,
'a disposed scope must not keep reacting to its sources'
).toEqual([1])
})

it('restarts after an explicit stop', () => {
const lifecycle = createLifecycleScope()
const setup = vi.fn()

lifecycle.start(setup)
lifecycle.stop()
lifecycle.start(setup)

expect(
setup,
'stop reopens the latch, so a later start must run setup again'
).toHaveBeenCalledTimes(2)
})

it('reopens the latch when setup throws synchronously', () => {
const lifecycle = createLifecycleScope()
const good = vi.fn()

expect(() =>
lifecycle.start(() => {
throw new Error('install failed')
})
).toThrow('install failed')
lifecycle.start(good)

expect(
good,
'a synchronous install failure disposes its scope and reopens the latch, so the next start still installs'
).toHaveBeenCalledOnce()
})

it('fires scope-disposal hooks registered by the setup on stop', () => {
const lifecycle = createLifecycleScope()
const disposed = vi.fn()
lifecycle.start(() => {
onScopeDispose(disposed)
})

lifecycle.stop()

expect(disposed).toHaveBeenCalledOnce()
})
})
43 changes: 43 additions & 0 deletions packages/account/src/vue/lifecycleScope.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { effectScope } from 'vue'
import type { EffectScope } from 'vue'

/**
* A detached {@link effectScope} for a module singleton that must own its
* watchers' lifetime rather than borrow it from whichever component reaches it
* first. `start` installs the scope once and latches; `stop` disposes it and
* reopens the latch so `start` may be called again.
*
* On the server (`window` undefined) `start` is a no-op that does not latch, so
* the client's first `start` still installs.
*
* `start` is synchronous. A synchronous throw from `setup` disposes the scope,
* reopens the latch, and rethrows, so a failed install leaves no stuck latch or
* leaked effects. Async failures are the setup's own to catch: a `setup` that
* launches a promise catches it and calls `stop` from that handler.
*/
export interface LifecycleScope {
start: (setup: () => void) => void
stop: () => void
}

export function createLifecycleScope(): LifecycleScope {
let scope: EffectScope | undefined
return {
start(setup) {
if (scope || typeof window === 'undefined') return

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (non-blocking): This SSR skip is load-bearing but invisible from the contract. The JSDoc above says "start installs the scope once and latches", and in a browser that is exactly right — but when window is undefined start() runs no setup and does not latch, so every later start() retries and stop() is a no-op. Since apps/website is Astro output: 'static' (astro.config line 17), this branch really does execute at build time, and it is a faithful port of workshop-credits.ts:106 and workshop-session-state.ts:242 — so I am not questioning the behavior, only that the doc does not mention it.

It is also unexercised. Every suite in this repo inherits environment: 'happy-dom' from vite.config.mts:887, and none of the three new suites overrides it, so window is always defined and the right-hand side of this condition is never false under test.

Could we add one sentence to the JSDoc (something like "in a non-browser environment start is a no-op and does not latch") plus a // @vitest-environment node case in lifecycleScope.test.ts? The per-file override is already an established pattern here — apps/website/src/config/workshop-session-state.failure.test.ts:1 uses it.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Documented in the JSDoc: start is a server no-op (window undefined) that does not latch, so the client's first start still installs.

const created = effectScope(true)
scope = created
try {
created.run(setup)
} catch (error) {
created.stop()
scope = undefined
throw error
}
},
stop() {
scope?.stop()
scope = undefined
}
}
}
48 changes: 48 additions & 0 deletions packages/account/src/vue/useGenerationGuard.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { describe, expect, it } from 'vitest'
import { effectScope } from 'vue'

import { useGenerationGuard } from './useGenerationGuard'

describe('useGenerationGuard', () => {
it('abandons every outstanding attempt when its owning scope is disposed', () => {
const scope = effectScope()
const guard = scope.run(() => useGenerationGuard())!
const handle = guard.capture()

expect(handle.live()).toBe(true)
scope.stop()

expect(
handle.live(),
'teardown must invalidate in-flight work so a late resolve cannot act'
).toBe(false)
Comment thread
MaanilVerma marked this conversation as resolved.
Resolved
})

it('invalidates a handle when its scope disposes mid-await', async () => {
const scope = effectScope()
const guard = scope.run(() => useGenerationGuard())!
const handle = guard.capture()

const settled = (async () => {
await Promise.resolve()
return handle.live()
})()
scope.stop()

expect(
await settled,
'a continuation resuming after scope teardown must see a dead handle'
).toBe(false)
})

it('still abandons attempts explicitly before teardown', () => {
const scope = effectScope()
const guard = scope.run(() => useGenerationGuard())!
const handle = guard.capture()

guard.abandon()

expect(handle.live()).toBe(false)
scope.stop()
})
})
19 changes: 19 additions & 0 deletions packages/account/src/vue/useGenerationGuard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { onScopeDispose } from 'vue'

import { createBoundedOperation } from '../core/boundedOperation.js'
import type { BoundedOperation } from '../core/boundedOperation.js'

/**
* A {@link createBoundedOperation} bound to the current Vue scope: when the
* component or effect scope disposes, every outstanding attempt is abandoned,
* so work resolving after teardown cannot act on an owner that is already gone.
*
* Call it from a component `setup` or an active `effectScope`. With no active
* scope `onScopeDispose` no-ops, so it never auto-abandons; use
* {@link createBoundedOperation} directly at module scope instead.
*/
export function useGenerationGuard(): BoundedOperation {
const operation = createBoundedOperation()
onScopeDispose(operation.abandon)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (non-blocking): worth saying in the doc block that this must be called from inside a component setup or an effectScope.

Vue's onScopeDispose warns and returns when there is no active scope, so a caller who reaches for useGenerationGuard() from module scope — the exact place the sibling createBoundedOperation is meant for, and where workshop-session-state.ts uses it in #17645 — gets a guard that silently never auto-abandons, with only a console warning to go on. The failure is quiet: capture()/abandon() keep working, so it looks fine until teardown fails to invalidate anything.

Every call site in this stack is inside a component, so nothing is broken today. A line in the JSDoc naming the requirement (or passing Vue's failSilently flag deliberately) would keep the next caller from picking the wrong one of the two.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 16b423c. Added a JSDoc note that it must run inside a component setup or an active effectScope, and that with no active scope onScopeDispose no-ops so it never auto-abandons — pointing module-scope callers at createBoundedOperation directly instead.

return operation
}
Loading