export type BackendConnectionAttempt = { generation: number promise: Promise | null } export type BackendProcessOwner = { generation: number process: TProcess } export function createBackendConnectionState() { let generation = 0 let process: TProcess | null = null let promise: Promise | null = null return { startAttempt(): BackendConnectionAttempt { return { generation, promise: null } }, setPromise(attempt: BackendConnectionAttempt, nextPromise: Promise): boolean { if (attempt.generation !== generation) { return false } attempt.promise = nextPromise promise = nextPromise return true }, isCurrentAttempt(attempt: BackendConnectionAttempt): boolean { return attempt.generation === generation }, attachProcess( attempt: BackendConnectionAttempt, nextProcess: TProcess ): BackendProcessOwner | null { if (attempt.generation !== generation) { return null } process = nextProcess return { generation, process: nextProcess } }, clearForCurrentProcess(owner: BackendProcessOwner): boolean { if (owner.generation !== generation || owner.process !== process) { return false } process = null promise = null return true }, clearPromiseForAttempt(attempt: BackendConnectionAttempt): boolean { if (attempt.generation !== generation || (promise !== null && attempt.promise !== promise)) { return false } promise = null return true }, getProcess(): TProcess | null { return process }, getPromise(): Promise | null { return promise }, invalidate(): TProcess | null { const currentProcess = process generation += 1 process = null promise = null return currentProcess } } }