Open History to see the last commit
1/** Decisions use facts read under the subscription lock, including database-
2 * computed deadlines. No local clock or process owns durable subscription state. */
3export type WakeState = 'ready' | 'delivered' | 'completed' | 'expired' | 'fenced'
4export type LeaseState = { readonly phase: 'free' } | { readonly phase: 'held' | 'expired'; readonly holder: string; readonly until: Date }
5export function leaseState(row: { readonly holder: string | null; readonly lease_until: Date | null; readonly lease_valid?: boolean | null }): LeaseState {
6 if (row.holder === null && row.lease_until === null) return { phase: 'free' }
7 if (row.holder === null || row.lease_until === null) throw new Error('Subscription lease has no owner or deadline')
8 return { phase: row.lease_valid ? 'held' : 'expired', holder: row.holder, until: row.lease_until }
9}
10export type DeliveryInput = {
11 readonly retryDue: boolean
12 readonly wake: { readonly phase: 'none'; readonly pending: boolean }
13 | { readonly phase: 'published' }
14 | { readonly phase: 'delivery'; readonly state: WakeState; readonly available: boolean }
15}
16export function decideDelivery(input: DeliveryInput): 'wait-for-claim' | 'idle' | 'backoff' | 'issue' | 'wait-for-delivery' | 'deliver' {
17 if (input.wake.phase === 'published') return 'wait-for-claim'
18 if (input.wake.phase === 'none' && !input.wake.pending) return 'idle'
19 if (!input.retryDue) return 'backoff'
20 if (input.wake.phase === 'none') return 'issue'
21 if (input.wake.state !== 'ready' || !input.wake.available) return 'wait-for-delivery'
22 return 'deliver'
23}
24export function decideCompletion(input: {
25 readonly deleted: boolean; readonly currentWake: string | null; readonly wakeId: string
26 readonly leaseHeld: boolean; readonly currentClaim: string | null; readonly claim: string
27 readonly ok: boolean; readonly done: boolean
28}): 'ignore' | 'retry' | 'complete' | 'await-callback' {
29 if (input.deleted || input.currentWake !== input.wakeId || !input.leaseHeld || input.currentClaim !== input.claim) return 'ignore'
30 if (!input.ok) return 'retry'
31 return input.done ? 'complete' : 'await-callback'
32}
33export function decideMembership(input: {
34 readonly streamId: string; readonly activeId: string | undefined; readonly full: boolean
35 readonly member: { readonly stream_id: string | null; readonly explicit_link: boolean } | undefined
36}): 'ignore' | 'retire' | 'defer' | 'insert' | 'replace' | 'advance' {
37 if (input.activeId !== input.streamId) return input.member?.stream_id === input.streamId ? 'retire' : 'ignore'
38 if (!input.member) return input.full ? 'defer' : 'insert'
39 return input.member.stream_id === input.streamId ? 'advance' : 'replace'
40}