@xynolog/core 0.8.0 → 0.8.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +40 -37
- package/dist/chunk-NZ7SRPXU.js +18100 -0
- package/dist/chunk-NZ7SRPXU.js.map +1 -0
- package/dist/{chunk-JVQYMUSA.js → chunk-PT6P47KV.js} +44 -23
- package/dist/chunk-PT6P47KV.js.map +1 -0
- package/dist/index.d.ts +14207 -3614
- package/dist/index.js +1003 -49
- package/dist/index.js.map +1 -1
- package/dist/openapi.js.map +1 -1
- package/dist/testing/axioms.js +9 -6
- package/dist/testing/axioms.js.map +1 -1
- package/dist/testing.d.ts +33 -10
- package/dist/testing.js +2 -2
- package/package.json +5 -1
- package/dist/chunk-JVQYMUSA.js.map +0 -1
- package/dist/chunk-VWT5CTL7.js +0 -6387
- package/dist/chunk-VWT5CTL7.js.map +0 -1
package/dist/openapi.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/protocol-limits.ts"],"names":[],"mappings":";
|
|
1
|
+
{"version":3,"sources":["../src/protocol-limits.ts"],"names":[],"mappings":";AAIO,IAAM,eAAA,GAAkB;AAAA,EAC7B,wBAAA,EAA0B;AAAA,IACxB,YAAA,EAAc;AAAA,GAChB;AAAA,EACA,qBAAA,EAAuB;AAAA,IACrB,YAAA,EAAc,OAAA;AAAA,IACd,gBAAA,EAAkB,EAAA;AAAA,IAClB,qBAAA,EAAuB,EAAA;AAAA,IACvB,iBAAA,EAAmB,QAAA;AAAA,IACnB,kBAAA,EAAoB,GAAA;AAAA,IACpB,mBAAA,EAAqB;AAAA,MACnB,QAAA,EAAU,EAAA;AAAA,MACV,KAAA,EAAO;AAAA,QACL,iBAAA,EAAmB,WAAA;AAAA,QACnB,gBAAA,EAAkB;AAAA;AACpB,KACF;AAAA,IACA,kBAAA,EAAoB;AAAA,GACtB;AAAA,EACA,gBAAA,EAAkB;AAAA,IAChB,YAAA,EAAc,OAAA;AAAA,IACd,YAAA,EAAc,GAAA;AAAA,IACd,kBAAA,EAAoB,GAAA;AAAA,IACpB,iBAAA,EAAmB;AAAA,MACjB,QAAA,EAAU;AAAA,QACR,SAAA,EAAW,GAAA;AAAA,QACX,KAAA,EAAO;AAAA,OACT;AAAA,MACA,KAAA,EAAO;AAAA,QACL,iBAAA,EAAmB,WAAA;AAAA,QACnB,gBAAA,EAAkB;AAAA;AACpB;AACF;AAEJ;AAGO,IAAM,UAAA,GAAa;AAAA,EACxB,4BAAA,EAA8B,GAAA;AAAA,EAC9B,oCAAA,EAAsC,GAAA;AAAA,EACtC,4BAAA,EAA8B;AAChC","file":"openapi.js","sourcesContent":["// Generated from protocol/specs/src/openapi.json and the files it names; do not edit.\n// Regenerate: make generate (codegen/lib/limits/limits.ml)\n\n/** Each operation's `x-xynolog-limits`, by `METHOD path`. */\nexport const operationLimits = {\n 'POST /api/tokens/media': {\n maxBodyBytes: 1048576,\n },\n 'POST /bus/subscribe': {\n maxBodyBytes: 1048576,\n heartbeatSeconds: 15,\n replyRetentionSeconds: 60,\n pendingWriteBytes: 16777216,\n replayBufferEvents: 1000,\n streamsPerPrincipal: {\n baseline: 64,\n roles: {\n 'xynolog-service': 'unlimited',\n 'xynolog-worker': 'unlimited',\n },\n },\n streamLeaseSeconds: 30,\n },\n 'POST /bus/emit': {\n maxBodyBytes: 4194304,\n claimSeconds: 900,\n idempotencySeconds: 600,\n emitsPerPrincipal: {\n baseline: {\n perSecond: 100,\n burst: 500,\n },\n roles: {\n 'xynolog-service': 'unlimited',\n 'xynolog-worker': 'unlimited',\n },\n },\n },\n} as const;\n\n/** Each schema property's `maxItems`, by `Schema.property`. */\nexport const itemLimits = {\n 'BrowseProfilesRequest.dids': 500,\n 'BusSubscribeRequest.pendingReplies': 256,\n 'BusSubscribeRequest.scoped': 512,\n} as const;\n"]}
|
package/dist/testing/axioms.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { FaultyTransport } from '../chunk-
|
|
2
|
-
import { BRIDGED_CHANNELS } from '../chunk-
|
|
1
|
+
import { FaultyTransport } from '../chunk-PT6P47KV.js';
|
|
2
|
+
import { BRIDGED_CHANNELS } from '../chunk-NZ7SRPXU.js';
|
|
3
3
|
import * as fc2 from 'fast-check';
|
|
4
4
|
import { Subject } from 'rxjs';
|
|
5
5
|
|
|
@@ -40,7 +40,8 @@ function assertStateUnitAxioms(spec) {
|
|
|
40
40
|
fc2.assert(prop, { numRuns });
|
|
41
41
|
} catch (e) {
|
|
42
42
|
throw new Error(
|
|
43
|
-
`${axiom}: ${e instanceof Error ? e.message : String(e)}
|
|
43
|
+
`${axiom}: ${e instanceof Error ? e.message : String(e)}`,
|
|
44
|
+
{ cause: e }
|
|
44
45
|
);
|
|
45
46
|
}
|
|
46
47
|
};
|
|
@@ -246,9 +247,11 @@ async function runLabeled(fallback, slot, assertion) {
|
|
|
246
247
|
await assertion();
|
|
247
248
|
} catch (e) {
|
|
248
249
|
const detail = e instanceof Error ? e.message : String(e);
|
|
249
|
-
if (slot.violation)
|
|
250
|
-
|
|
251
|
-
|
|
250
|
+
if (slot.violation) {
|
|
251
|
+
throw new Error(`${slot.violation.message}
|
|
252
|
+
${detail}`, { cause: e });
|
|
253
|
+
}
|
|
254
|
+
throw new Error(`${fallback}: ${detail}`, { cause: e });
|
|
252
255
|
}
|
|
253
256
|
}
|
|
254
257
|
function capturing(slot, block) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/state-unit-axioms.ts","../../src/testing-kit.ts","../../src/liveness-axioms.ts"],"names":["fc"],"mappings":";;;;;AAsCO,SAAS,YAAA,GAA6B;AAC3C,EAAA,IAAI,CAAA,GAAI,CAAA;AACR,EAAA,OAAO;AAAA,IACL,OAAA,GAAU;AACR,MAAA,CAAA,IAAK,CAAA;AAAA,IACP,CAAA;AAAA,IACA,IAAI,YAAA,GAAe;AACjB,MAAA,OAAO,CAAA;AAAA,IACT;AAAA,GACF;AAC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,EAAA,GAAK,IAAI,CAAC,CAAA,CAAA;AAChB,cAAA,OAAA,CAAQ,KAAK,EAAE,CAAA;AACf,cAAA,OAAA,CAAQ,MAAM,EAAE,CAAA;AAAA,YAClB,CAAA,MAAO;AACL,cAAA,MAAM,QAAQ,UAAA,EAAW;AAAA,YAC3B;AAAA,UAGF;AACA,UAAA,OAAO,OAAA,CAAQ,MAAA,IAAS,IAAK,KAAA,CAAM,CAAC,CAAA,CAAA;AAEpC,UAAA,SAAA,CAAU,MAAM,MAAM;AACpB,YAAA,KAAA,MAAW,MAAM,OAAA,EAAS;AACxB,cAAA,MAAM,IAAI,SAAA,CAAU,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,KAAM,EAAE,CAAA,CAAE,MAAA;AAC5C,cAAA,IAAI,MAAM,CAAA,EAAG;AACX,gBAAA,MAAM,IAAI,KAAA;AAAA,kBACR,mBAAc,EAAE,CAAA,qCAAA,EAA8B,GAAA,CAAI,IAAA,CAAK,GAAG,CAAC,CAAA,wEAAA;AAAA,iBAE7D;AAAA,cACF;AACA,cAAA,IAAI,IAAI,CAAA,EAAG;AACT,gBAAA,MAAM,IAAI,KAAA;AAAA,kBACR,CAAA,gBAAA,EAAc,EAAE,CAAA,iBAAA,EAAe,CAAC,sBAAiB,GAAA,CAAI,IAAA,CAAK,GAAG,CAAC,CAAA,gCAAA;AAAA,iBAChE;AAAA,cACF;AAAA,YACF;AAAA,UACF,CAAC,CAAA;AAAA,QACH,CAAA,SAAE;AACA,UAAA,GAAA,CAAI,WAAA,EAAY;AAChB,UAAA,OAAA,CAAQ,QAAA,IAAW;AAAA,QACrB;AAAA,MACF,CAAC,CAAA;AAAA,MACD,EAAE,OAAA,EAAS,IAAA,CAAK,OAAA,IAAW,EAAA;AAAG;AAChC,GACF;AACF","file":"axioms.js","sourcesContent":["/**\n * Executable enforcement of the StateUnit pattern — the runtime twin of\n * https://github.com/xynolog/docs/blob/main/builder/STATE-UNITS.md. The `StateUnit` interface's own comment notes\n * the pattern is convention; this file makes it executable.\n *\n * `assertStateUnitAxioms(spec)` runs every applicable axiom against a factory in\n * one shot, throwing a labeled Error on the first violation (the axiom id is in\n * the message). It is framework-agnostic on purpose — only `rxjs` + `fast-check`,\n * no `vitest` — so it ships through `@xynolog/core/testing` and any package's test\n * runner can invoke it from a single `it(...)` per state unit. It lives in core\n * (not sdk) so even packages below sdk (e.g. `http-transport`) can use it without\n * a dependency cycle.\n *\n * Axioms (random-input dimension; fast-check):\n * A5 dispose() is idempotent and total (n ∈ [1,20] calls never throw)\n * A5b post-dispose inertness — every public method is a no-op after dispose\n * A6 every pre-dispose subscriber (k ∈ [1,10]) sees `complete` on dispose\n * X3-runtime instance isolation — driving one instance never moves another's surfaces\n * Structural assertions (single-shot):\n * X1 no raw Subject on the public surface\n * A7-passed disposing the unit must NOT dispose an injected dependency\n * A7-owned disposing the unit MUST dispose its internally-constructed children\n */\n\nimport * as fc from 'fast-check';\nimport { Subject, type Observable } from 'rxjs';\nimport type { StateUnit } from './state-unit';\n\n/**\n * A disposable stand-in for an injected dependency. Pass one as a unit's\n * constructor arg, then list it in `setup().passedIn` so A7-passed can assert\n * the unit never disposed it. Counts calls so A7-passed also holds under the\n * repeated-dispose stress of A5.\n */\nexport interface DisposeProbe extends StateUnit {\n readonly disposeCount: number;\n}\n\nexport function disposeProbe(): DisposeProbe {\n let n = 0;\n return {\n dispose() {\n n += 1;\n },\n get disposeCount() {\n return n;\n },\n };\n}\n\ntype SetupResult<T extends StateUnit> =\n T | { unit: T; passedIn?: readonly DisposeProbe[]; teardown?: () => void };\n\nexport interface StateUnitAxiomSpec<T extends StateUnit> {\n /**\n * Build a FRESH unit. Called many times (fast-check re-runs), so it must\n * return an independent instance each call. Return the bare unit, or an object\n * carrying the injected `passedIn` probes (A7-passed) and a `teardown` to\n * release per-instance resources (e.g. a mock bus).\n */\n setup: () => SetupResult<T>;\n /** Owned public Observables — Subjects the unit completes on dispose (A6, X3, post-dispose inertness). */\n surfaces?: (unit: T) => readonly Observable<unknown>[];\n /** Public input methods as zero-arg callers (A5b post-dispose, X3 drive). */\n invocations?: (unit: T) => readonly (() => unknown)[];\n /** Surfaces of internally-constructed children — must complete when the outer disposes (A7-owned). */\n ownedChildSurfaces?: (unit: T) => readonly Observable<unknown>[];\n /** fast-check run budget per property (default 30). */\n numRuns?: number;\n}\n\ninterface Normalized<T extends StateUnit> {\n unit: T;\n passedIn: readonly DisposeProbe[];\n teardown: () => void;\n}\n\nfunction normalize<T extends StateUnit>(r: SetupResult<T>): Normalized<T> {\n if (r && typeof r === 'object' && 'unit' in r) {\n return {\n unit: r.unit,\n passedIn: r.passedIn ?? [],\n teardown: r.teardown ?? (() => {}),\n };\n }\n return { unit: r as T, passedIn: [], teardown: () => {} };\n}\n\nfunction swallowAsync(value: unknown): void {\n if (\n value &&\n typeof value === 'object' &&\n typeof (value as { then?: unknown }).then === 'function'\n ) {\n (value as Promise<unknown>).then(undefined, () => {});\n }\n}\n\n/**\n * Run every applicable axiom against `spec`. Throws a labeled Error on the first\n * violation. Axioms whose accessors are omitted are skipped (e.g. A7-passed\n * runs only when `setup` returns `passedIn`; A6 only when `surfaces` is given).\n */\nexport function assertStateUnitAxioms<T extends StateUnit>(\n spec: StateUnitAxiomSpec<T>,\n): void {\n const numRuns = spec.numRuns ?? 30;\n const fresh = (): Normalized<T> => normalize(spec.setup());\n\n // fast-check's default falsification message is just \"Property failed after N\n // tests {seed}\" — it drops the thrown axiom id. Prepend the axiom so a real\n // failure names itself; the seed/shrink detail is preserved.\n const run = (axiom: string, prop: Parameters<typeof fc.assert>[0]): void => {\n try {\n fc.assert(prop, { numRuns });\n } catch (e) {\n throw new Error(\n `${axiom}: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n };\n\n // X1 — no raw *origin* Subject on the public surface (expose `.asObservable()`).\n // Flag only origin Subjects — `new Subject` / `new BehaviorSubject`, the unit's own\n // state, where `.source` is undefined. Derived `AnonymousSubject`s from `Subject.lift`\n // (`shareReplay().pipe(...)`) carry a `.source` and are inert sinks (`.next()` does\n // nothing useful) — idiomatic, not the forgotten-internal-Subject smell — so exclude them.\n {\n const { unit, teardown } = fresh();\n for (const [key, value] of Object.entries(unit)) {\n if (\n value instanceof Subject &&\n (value as { source?: unknown }).source === undefined\n ) {\n throw new Error(\n `X1: public field \"${key}\" is a raw Subject — expose it via .asObservable()`,\n );\n }\n }\n unit.dispose();\n teardown();\n }\n\n // A7-passed — disposing the unit must NOT dispose an injected dependency.\n {\n const { unit, passedIn, teardown } = fresh();\n unit.dispose();\n passedIn.forEach((probe, i) => {\n if (probe.disposeCount > 0) {\n throw new Error(\n `A7-passed: the unit disposed injected dependency #${i} (it doesn't own it)`,\n );\n }\n });\n teardown();\n }\n\n // A5 — dispose() idempotent & total: n calls never throw; injected deps stay untouched.\n run(\n 'A5',\n fc.property(fc.integer({ min: 1, max: 20 }), (n) => {\n const { unit, passedIn, teardown } = fresh();\n for (let i = 0; i < n; i++) unit.dispose();\n passedIn.forEach((probe, i) => {\n if (probe.disposeCount > 0) {\n throw new Error(\n `injected dependency #${i} disposed under ${n} dispose() calls`,\n );\n }\n });\n teardown();\n }),\n );\n\n // A6 — k pre-dispose subscribers on each owned surface all see `complete` on dispose.\n if (spec.surfaces) {\n const surfaces = spec.surfaces;\n run(\n 'A6',\n fc.property(fc.integer({ min: 1, max: 10 }), (k) => {\n const { unit, teardown } = fresh();\n const completed: boolean[] = [];\n const subs = surfaces(unit).flatMap((o) =>\n Array.from({ length: k }, () => {\n const idx = completed.push(false) - 1;\n return o.subscribe({\n complete: () => {\n completed[idx] = true;\n },\n });\n }),\n );\n unit.dispose();\n completed.forEach((seen, idx) => {\n if (!seen)\n throw new Error(\n `a subscriber did not see complete on dispose (k=${k}, sub #${idx})`,\n );\n });\n subs.forEach((s) => s.unsubscribe());\n teardown();\n }),\n );\n }\n\n // A5b — post-dispose inertness: every public method is a no-op (no throw) after dispose.\n if (spec.invocations) {\n const invocations = spec.invocations;\n run(\n 'A5b',\n fc.property(fc.array(fc.nat(), { maxLength: 12 }), (seq) => {\n const { unit, teardown } = fresh();\n const callers = invocations(unit);\n unit.dispose();\n for (const raw of seq) {\n if (callers.length === 0) break;\n swallowAsync(callers[raw % callers.length]());\n }\n teardown();\n }),\n );\n }\n\n // X3-runtime — instance isolation: driving instance A never moves instance B's surfaces.\n if (spec.surfaces && spec.invocations) {\n const surfaces = spec.surfaces;\n const invocations = spec.invocations;\n run(\n 'X3-runtime',\n fc.property(fc.array(fc.nat(), { minLength: 1, maxLength: 8 }), (seq) => {\n const a = fresh();\n const b = fresh();\n const bSurfaces = surfaces(b.unit);\n const bCounts = bSurfaces.map(() => 0);\n const bSubs = bSurfaces.map((o, i) =>\n o.subscribe(() => {\n bCounts[i] += 1;\n }),\n );\n const baseline = bCounts.slice(); // initial replay captured synchronously above\n const aCallers = invocations(a.unit);\n for (const raw of seq) {\n if (aCallers.length === 0) break;\n swallowAsync(aCallers[raw % aCallers.length]());\n }\n bCounts.forEach((count, i) => {\n if (count !== baseline[i]) {\n throw new Error(\n `driving instance A perturbed instance B's surface #${i}`,\n );\n }\n });\n bSubs.forEach((s) => s.unsubscribe());\n a.unit.dispose();\n b.unit.dispose();\n a.teardown();\n b.teardown();\n }),\n );\n }\n\n // A7-owned — internally-constructed children are disposed (their surfaces complete) on outer dispose.\n if (spec.ownedChildSurfaces) {\n const { unit, teardown } = fresh();\n const childSurfaces = spec.ownedChildSurfaces(unit);\n const completed = childSurfaces.map(() => false);\n const subs = childSurfaces.map((o, i) =>\n o.subscribe({\n complete: () => {\n completed[i] = true;\n },\n }),\n );\n unit.dispose();\n completed.forEach((seen, i) => {\n if (!seen)\n throw new Error(\n `A7-owned: owned child surface #${i} did not complete on outer dispose`,\n );\n });\n subs.forEach((s) => s.unsubscribe());\n teardown();\n }\n\n // Post-dispose surface inertness: a NEW subscription after dispose completes with no `next`.\n if (spec.surfaces) {\n const { unit, teardown } = fresh();\n unit.dispose();\n spec.surfaces(unit).forEach((o, i) => {\n let nexts = 0;\n let done = false;\n o.subscribe({\n next: () => {\n nexts += 1;\n },\n complete: () => {\n done = true;\n },\n }).unsubscribe();\n if (nexts > 0)\n throw new Error(\n `A5b/inert: owned surface #${i} emitted a value after dispose`,\n );\n if (!done)\n throw new Error(\n `A5b/inert: owned surface #${i} did not complete after dispose`,\n );\n });\n teardown();\n }\n}\n","// ⚠ GENERATED FILE — do not edit.\n//\n// Authority: protocol/specs/src/client/testing.json\n// Regenerate: make generate (codegen/lib/testing/typescript.ml)\n\nimport type { Arbitrary } from 'fast-check';\nimport type { Observable } from 'rxjs';\nimport type { BusOperationKey } from './bus-operations';\nimport type { FaultyTransport } from './faulty-transport';\n\nexport type FaultAction =\n /** The request's reply is delivered. */\n | { kind: 'deliver' }\n /** The request's reply is lost. */\n | { kind: 'drop-reply' }\n /** The request's reply is delivered after `ms` milliseconds. */\n | { kind: 'delay'; ms: number }\n /** The request's reply is delivered twice. */\n | { kind: 'duplicate-reply' }\n /** The emit itself is refused: the request never reaches the gateway. */\n | { kind: 'reject-emit' };\n\n/** The delays a drawn fault is of, in milliseconds. */\nexport const DELAY_MS = { minimum: 0, maximum: 5 } as const;\n\n/** How many faults a drawn schedule is of. */\nexport const SCHEDULE_LENGTH = { minimum: 1, maximum: 8 } as const;\n\n/** How many times its reckoned bound a case is given: the room a scheduler's jitter takes. */\nexport const SLACK = 4;\n\n/** One step of an interleaving: a write, or a client-initiated transition. */\nexport const DELIVERY_OPS = ['write', 'transition'] as const;\n\nexport type DeliveryOp = (typeof DELIVERY_OPS)[number];\n\n/** One request the transport was sent. */\nexport interface RequestLogEntry {\n channel: BusOperationKey;\n action: FaultAction;\n correlationId: string | undefined;\n retryKey: string;\n payload: Record<string, unknown>;\n}\n\n/** What one fresh run of a composition exposes to the axioms. */\nexport interface LivenessScenario {\n outputs: readonly Observable<unknown>[];\n settlements?: readonly Promise<unknown>[];\n teardown?: () => void;\n}\n\n/** A composition, and the schedules it is run under. */\nexport interface LivenessSpec {\n setup: (\n transport: FaultyTransport,\n ) => LivenessScenario | Promise<LivenessScenario>;\n timeoutMs: number;\n retryBudget?: number;\n cases?: number;\n schedules?: Arbitrary<readonly FaultAction[]>;\n makeResponse?: (\n operation: string,\n payload: Record<string, unknown>,\n ) => unknown;\n}\n","/**\n * Executable enforcement of the liveness axioms, and the composition-level sibling of\n * `assertStateUnitAxioms` (state-unit-axioms.ts). Where the StateUnit axioms\n * make *per-unit* wrongness mechanically detectable, these make *silence*\n * detectable: every existing enforcement tier is safety (nothing wrong is\n * delivered); these assert liveness (something is eventually delivered).\n *\n * Axioms (fault-schedule dimension; fast-check):\n * L1 Subscriber liveness — every output emits next|error within the bound,\n * under any fault schedule. Error is a permitted outcome; the forbidden\n * fourth state is pending-forever.\n * L2 Request settlement — every awaited path settles within the bound;\n * re-issues per logical request stay within the retry budget (B14: one);\n * a faulted request must be re-issued or surfaced, never swallowed.\n * L3 Delivery across lifecycle transitions — every event written to a live\n * connection reaches the output exactly once, wherever a client-initiated\n * transition (handover / reconnect / scope change) lands. Retirement is\n * by drain, never by abort (TRANSPORT-HTTP.md, Abort discipline).\n *\n * Framework-agnostic on purpose — only `rxjs` + `fast-check`, no `vitest` — so\n * it ships through `@xynolog/core/testing` and any package's test runner can\n * invoke it. An L1/L2 case waits out its whole bound in real time before it\n * judges, so a request sent again after every output has spoken is counted;\n * properties keep the bound small by passing a small explicit `timeoutMs` to\n * `Bus.request` — no `Date.now`, no 30 s real waits.\n */\n\nimport * as fc from 'fast-check';\nimport type { Observable, Subscription } from 'rxjs';\nimport { BRIDGED_CHANNELS } from './bridging';\nimport { FaultyTransport } from './faulty-transport';\nimport {\n DELAY_MS,\n DELIVERY_OPS,\n SCHEDULE_LENGTH,\n SLACK,\n type DeliveryOp,\n type FaultAction,\n type LivenessSpec,\n} from './testing-kit';\n\n// ── L1/L2: liveness over a composition on FaultyTransport ────────────────\n\n/** A fault of each kind, as likely as the others; a delay is of `DELAY_MS`. */\nconst FAULT_DRAWS: {\n [K in FaultAction['kind']]: fc.Arbitrary<Extract<FaultAction, { kind: K }>>;\n} = {\n deliver: fc.constant({ kind: 'deliver' }),\n 'drop-reply': fc.constant({ kind: 'drop-reply' }),\n delay: fc\n .integer({ min: DELAY_MS.minimum, max: DELAY_MS.maximum })\n .map((ms) => ({ kind: 'delay', ms })),\n 'duplicate-reply': fc.constant({ kind: 'duplicate-reply' }),\n 'reject-emit': fc.constant({ kind: 'reject-emit' }),\n};\n\nexport function arbFaultAction(): fc.Arbitrary<FaultAction> {\n return fc.oneof(...Object.values(FAULT_DRAWS));\n}\n\nexport function arbFaultSchedule(): fc.Arbitrary<readonly FaultAction[]> {\n return fc.array(arbFaultAction(), {\n minLength: SCHEDULE_LENGTH.minimum,\n maxLength: SCHEDULE_LENGTH.maximum,\n });\n}\n\nfunction describeSchedule(schedule: readonly FaultAction[]): string {\n return schedule\n .map((a) => (a.kind === 'delay' ? `delay(${a.ms})` : a.kind))\n .join(',');\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Sibling of state-unit-axioms' `run`, adapted for properties that check more\n * than one axiom: fast-check's falsification message carries the seed and\n * counterexample but not the thrown axiom id (fc v4 moves the inner error to\n * `cause`), so the property captures its own labeled violation into `slot`\n * and the wrapper re-throws with the axiom id leading and fc's detail after.\n */\nasync function runLabeled(\n fallback: string,\n slot: { violation: Error | null },\n assertion: () => Promise<void>,\n): Promise<void> {\n try {\n await assertion();\n } catch (e) {\n const detail = e instanceof Error ? e.message : String(e);\n if (slot.violation) throw new Error(`${slot.violation.message}\\n${detail}`);\n throw new Error(`${fallback}: ${detail}`);\n }\n}\n\n/** Wrap a check block so its labeled throw lands in `slot` before falsifying. */\nfunction capturing(slot: { violation: Error | null }, block: () => void): void {\n try {\n block();\n } catch (e) {\n slot.violation = e instanceof Error ? e : new Error(String(e));\n throw e;\n }\n}\n\n/**\n * Run L1 + L2 against `spec` across `spec.cases` fault schedules (25 unless\n * given), drawn from `spec.schedules` or `arbFaultSchedule`. A case's bound is\n * (timeoutMs × (1 + retryBudget) + Σdelays) × SLACK, and the retry budget is\n * one re-issue (B14) unless given. Throws a labeled Error (`L1: …` / `L2: …`)\n * on the first violation.\n */\nexport async function assertLivenessAxioms(spec: LivenessSpec): Promise<void> {\n const retryBudget = spec.retryBudget ?? 1;\n const schedules = spec.schedules ?? arbFaultSchedule();\n\n const slot = { violation: null as Error | null };\n await runLabeled('liveness', slot, () =>\n fc.assert(\n fc.asyncProperty(schedules, async (schedule) => {\n const delayTotal = schedule.reduce(\n (n, a) => n + (a.kind === 'delay' ? a.ms : 0),\n 0,\n );\n const bound = (spec.timeoutMs * (1 + retryBudget) + delayTotal) * SLACK;\n const transport = new FaultyTransport({\n channels: BRIDGED_CHANNELS,\n schedule,\n ...(spec.makeResponse ? { makeResponse: spec.makeResponse } : {}),\n });\n const scenario = await spec.setup(transport);\n const outputs = scenario.outputs;\n const settlements = scenario.settlements ?? [];\n\n // Subscribe every output (that's what makes a live query live) and\n // track notifications; track settlement of every awaited path.\n const notified: boolean[] = outputs.map(() => false);\n const settled: boolean[] = settlements.map(() => false);\n const subs: Subscription[] = outputs.map((o, i) =>\n o.subscribe({\n next: () => {\n notified[i] = true;\n },\n error: () => {\n notified[i] = true;\n },\n }),\n );\n settlements.forEach((p, i) => {\n p.then(\n () => {\n settled[i] = true;\n },\n () => {\n settled[i] = true;\n },\n );\n });\n\n // The whole bound, even once everything has spoken: a request sent\n // again after that still counts against the retry budget.\n await sleep(bound);\n\n try {\n // L2 first: when it applies it names the mechanism (swallow, budget,\n // unsettled await); L1 below is the broader every-output net. All-\n // outputs-silent is a subset of any-output-silent, so checking L1\n // first would shadow the sharper L2 diagnoses entirely.\n capturing(slot, () => {\n // L2 — settlement: every awaited path settled.\n settled.forEach((seen, i) => {\n if (!seen) {\n throw new Error(\n `L2: settlement #${i} did not settle within ${bound}ms ` +\n `under schedule ⟨${describeSchedule(schedule)}⟩ — the forbidden fourth state`,\n );\n }\n });\n\n // L2 — retry accounting over the transport's request log.\n const issues = new Map<\n string,\n { count: number; lastFaulted: boolean }\n >();\n for (const entry of transport.requestLog) {\n const prior = issues.get(entry.retryKey) ?? {\n count: 0,\n lastFaulted: false,\n };\n issues.set(entry.retryKey, {\n count: prior.count + 1,\n lastFaulted:\n entry.action.kind === 'drop-reply' ||\n entry.action.kind === 'reject-emit',\n });\n }\n for (const [key, { count, lastFaulted }] of issues) {\n if (count > 1 + retryBudget) {\n throw new Error(\n `L2: request ⟨${key}⟩ issued ${count} times — exceeds the retry budget ` +\n `(1 + ${retryBudget}) under schedule ⟨${describeSchedule(schedule)}⟩`,\n );\n }\n // Swallow detection: the final issue of a logical request was\n // faulted, the composition had retry budget left but didn't use\n // it, and no output surfaced anything — the rejection went into\n // a void (the `catch(() => {})` B14 rules out).\n if (\n lastFaulted &&\n count <= retryBudget &&\n outputs.length > 0 &&\n !notified.some(Boolean)\n ) {\n throw new Error(\n `L2: faulted request ⟨${key}⟩ was neither re-issued nor surfaced ` +\n `under schedule ⟨${describeSchedule(schedule)}⟩ — rejection swallowed`,\n );\n }\n }\n\n // L1 — every subscription saw next|error; pending-forever is the bug.\n notified.forEach((seen, i) => {\n if (!seen) {\n throw new Error(\n `L1: output #${i} received no next/error within ${bound}ms ` +\n `under schedule ⟨${describeSchedule(schedule)}⟩ — silently pending`,\n );\n }\n });\n });\n } finally {\n subs.forEach((s) => s.unsubscribe());\n scenario.teardown?.();\n transport.dispose();\n }\n }),\n { numRuns: spec.cases ?? 25 },\n ),\n );\n}\n\n// ── L3: exactly-once delivery across client-initiated transitions ────────\n\n/**\n * A connection-stream-shaped subject: something that accepts writes to the\n * live connection, can be told to transition (handover / reconnect / scope\n * change), and exposes the subscriber-facing output. The http-transport\n * actor's property suite adapts the real actor's mock-connection harness to\n * this shape; the teeth tests drive deliberately-broken doubles.\n */\nexport interface DeliverySubject {\n /** Write the event with this id to the currently-live connection. */\n write: (eventId: string) => void;\n /** Client-initiated lifecycle transition. */\n transition: () => void | Promise<void>;\n /** Subscriber-facing output; each emission is a delivered event id. */\n output$: Observable<string>;\n /**\n * Drain pending asynchronous delivery at end of sequence (a live connection\n * eventually flushes). Default: one macrotask tick.\n */\n settle?: () => Promise<void>;\n teardown?: () => void;\n}\n\nexport interface DeliveryAxiomSpec {\n /** Build a FRESH subject. Called per run. */\n setup: () => DeliverySubject;\n /** Override the generated op sequences (teeth tests pin one). */\n opsArb?: fc.Arbitrary<readonly DeliveryOp[]>;\n /** Max generated sequence length (default 12). */\n maxOps?: number;\n /** fast-check run budget (default 50 — these runs are cheap). */\n numRuns?: number;\n}\n\nexport function arbDeliveryOps(\n maxOps = 12,\n): fc.Arbitrary<readonly DeliveryOp[]> {\n return (\n fc\n .array(fc.constantFrom(...DELIVERY_OPS), {\n minLength: 1,\n maxLength: maxOps,\n })\n // A sequence with no write asserts nothing — always exercise delivery.\n .map((ops) =>\n ops.includes('write') ? ops : ([...ops, 'write'] as const),\n )\n );\n}\n\n/**\n * Run L3 against `spec` across generated write/transition interleavings.\n * Throws a labeled Error (`L3: …`) on the first violation: an event written\n * to a live connection delivered zero times (lost — retired by abort instead\n * of drain) or more than once (duplicate).\n */\nexport async function assertExactlyOnceDelivery(\n spec: DeliveryAxiomSpec,\n): Promise<void> {\n const opsArb = spec.opsArb ?? arbDeliveryOps(spec.maxOps ?? 12);\n\n const slot = { violation: null as Error | null };\n await runLabeled('L3', slot, () =>\n fc.assert(\n fc.asyncProperty(opsArb, async (ops) => {\n const subject = spec.setup();\n const delivered: string[] = [];\n const sub = subject.output$.subscribe((id) => delivered.push(id));\n const written: string[] = [];\n try {\n for (let i = 0; i < ops.length; i++) {\n if (ops[i] === 'write') {\n const id = `e${i}`;\n written.push(id);\n subject.write(id);\n } else {\n await subject.transition();\n }\n // Deliberately no settling between ops: the interesting races are\n // transitions landing before a write's asynchronous delivery.\n }\n await (subject.settle?.() ?? sleep(0));\n\n capturing(slot, () => {\n for (const id of written) {\n const n = delivered.filter((d) => d === id).length;\n if (n === 0) {\n throw new Error(\n `L3: event ⟨${id}⟩ delivered 0 times under ⟨${ops.join(',')}⟩ — ` +\n `lost across a transition (retire by drain, never by abort)`,\n );\n }\n if (n > 1) {\n throw new Error(\n `L3: event ⟨${id}⟩ delivered ${n} times under ⟨${ops.join(',')}⟩ — duplicate delivery`,\n );\n }\n }\n });\n } finally {\n sub.unsubscribe();\n subject.teardown?.();\n }\n }),\n { numRuns: spec.numRuns ?? 50 },\n ),\n );\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/state-unit-axioms.ts","../../src/testing-kit.ts","../../src/liveness-axioms.ts"],"names":["fc"],"mappings":";;;;;AAsCO,SAAS,YAAA,GAA6B;AAC3C,EAAA,IAAI,CAAA,GAAI,CAAA;AACR,EAAA,OAAO;AAAA,IACL,OAAA,GAAU;AACR,MAAA,CAAA,IAAK,CAAA;AAAA,IACP,CAAA;AAAA,IACA,IAAI,YAAA,GAAe;AACjB,MAAA,OAAO,CAAA;AAAA,IACT;AAAA,GACF;AACF;AA6BA,SAAS,UAA+B,CAAA,EAAkC;AACxE,EAAA,IAAI,CAAA,IAAK,OAAO,CAAA,KAAM,QAAA,IAAY,UAAU,CAAA,EAAG;AAC7C,IAAA,OAAO;AAAA,MACL,MAAM,CAAA,CAAE,IAAA;AAAA,MACR,QAAA,EAAU,CAAA,CAAE,QAAA,IAAY,EAAC;AAAA,MACzB,QAAA,EAAU,CAAA,CAAE,QAAA,KAAa,MAAM;AAAA,MAAC,CAAA;AAAA,KAClC;AAAA,EACF;AACA,EAAA,OAAO,EAAE,IAAA,EAAM,CAAA,EAAQ,UAAU,EAAC,EAAG,UAAU,MAAM;AAAA,EAAC,CAAA,EAAE;AAC1D;AAEA,SAAS,aAAa,KAAA,EAAsB;AAC1C,EAAA,IACE,SACA,OAAO,KAAA,KAAU,YACjB,OAAQ,KAAA,CAA6B,SAAS,UAAA,EAC9C;AACA,IAAC,KAAA,CAA2B,IAAA,CAAK,MAAA,EAAW,MAAM;AAA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AAA,IAAI,MAAM,CAAA,EAAG;AACX,gBAAA,MAAM,IAAI,KAAA;AAAA,kBACR,mBAAc,EAAE,CAAA,qCAAA,EAA8B,GAAA,CAAI,IAAA,CAAK,GAAG,CAAC,CAAA,wEAAA;AAAA,iBAE7D;AAAA,cACF;AACA,cAAA,IAAI,IAAI,CAAA,EAAG;AACT,gBAAA,MAAM,IAAI,KAAA;AAAA,kBACR,CAAA,gBAAA,EAAc,EAAE,CAAA,iBAAA,EAAe,CAAC,sBAAiB,GAAA,CAAI,IAAA,CAAK,GAAG,CAAC,CAAA,gCAAA;AAAA,iBAChE;AAAA,cACF;AAAA,YACF;AAAA,UACF,CAAC,CAAA;AAAA,QACH,CAAA,SAAE;AACA,UAAA,GAAA,CAAI,WAAA,EAAY;AAChB,UAAA,OAAA,CAAQ,QAAA,IAAW;AAAA,QACrB;AAAA,MACF,CAAC,CAAA;AAAA,MACD,EAAE,OAAA,EAAS,IAAA,CAAK,OAAA,IAAW,EAAA;AAAG;AAChC,GACF;AACF","file":"axioms.js","sourcesContent":["/**\n * Executable enforcement of the StateUnit pattern — the runtime twin of\n * https://github.com/xynolog/docs/blob/main/builder/STATE-UNITS.md. The `StateUnit` interface's own comment notes\n * the pattern is convention; this file makes it executable.\n *\n * `assertStateUnitAxioms(spec)` runs every applicable axiom against a factory in\n * one shot, throwing a labeled Error on the first violation (the axiom id is in\n * the message). It is framework-agnostic on purpose — only `rxjs` + `fast-check`,\n * no `vitest` — so it ships through `@xynolog/core/testing` and any package's test\n * runner can invoke it from a single `it(...)` per state unit. It lives in core\n * (not sdk) so even packages below sdk (e.g. `http-transport`) can use it without\n * a dependency cycle.\n *\n * Axioms (random-input dimension; fast-check):\n * A5 dispose() is idempotent and total (n ∈ [1,20] calls never throw)\n * A5b post-dispose inertness — every public method is a no-op after dispose\n * A6 every pre-dispose subscriber (k ∈ [1,10]) sees `complete` on dispose\n * X3-runtime instance isolation — driving one instance never moves another's surfaces\n * Structural assertions (single-shot):\n * X1 no raw Subject on the public surface\n * A7-passed disposing the unit must NOT dispose an injected dependency\n * A7-owned disposing the unit MUST dispose its internally-constructed children\n */\n\nimport * as fc from 'fast-check';\nimport { Subject, type Observable } from 'rxjs';\nimport type { StateUnit } from './state-unit';\n\n/**\n * A disposable stand-in for an injected dependency. Pass one as a unit's\n * constructor arg, then list it in `setup().passedIn` so A7-passed can assert\n * the unit never disposed it. Counts calls so A7-passed also holds under the\n * repeated-dispose stress of A5.\n */\nexport interface DisposeProbe extends StateUnit {\n readonly disposeCount: number;\n}\n\nexport function disposeProbe(): DisposeProbe {\n let n = 0;\n return {\n dispose() {\n n += 1;\n },\n get disposeCount() {\n return n;\n },\n };\n}\n\ntype SetupResult<T extends StateUnit> =\n T | { unit: T; passedIn?: readonly DisposeProbe[]; teardown?: () => void };\n\nexport interface StateUnitAxiomSpec<T extends StateUnit> {\n /**\n * Build a FRESH unit. Called many times (fast-check re-runs), so it must\n * return an independent instance each call. Return the bare unit, or an object\n * carrying the injected `passedIn` probes (A7-passed) and a `teardown` to\n * release per-instance resources (e.g. a mock bus).\n */\n setup: () => SetupResult<T>;\n /** Owned public Observables — Subjects the unit completes on dispose (A6, X3, post-dispose inertness). */\n surfaces?: (unit: T) => readonly Observable<unknown>[];\n /** Public input methods as zero-arg callers (A5b post-dispose, X3 drive). */\n invocations?: (unit: T) => readonly (() => unknown)[];\n /** Surfaces of internally-constructed children — must complete when the outer disposes (A7-owned). */\n ownedChildSurfaces?: (unit: T) => readonly Observable<unknown>[];\n /** fast-check run budget per property (default 30). */\n numRuns?: number;\n}\n\ninterface Normalized<T extends StateUnit> {\n unit: T;\n passedIn: readonly DisposeProbe[];\n teardown: () => void;\n}\n\nfunction normalize<T extends StateUnit>(r: SetupResult<T>): Normalized<T> {\n if (r && typeof r === 'object' && 'unit' in r) {\n return {\n unit: r.unit,\n passedIn: r.passedIn ?? [],\n teardown: r.teardown ?? (() => {}),\n };\n }\n return { unit: r as T, passedIn: [], teardown: () => {} };\n}\n\nfunction swallowAsync(value: unknown): void {\n if (\n value &&\n typeof value === 'object' &&\n typeof (value as { then?: unknown }).then === 'function'\n ) {\n (value as Promise<unknown>).then(undefined, () => {});\n }\n}\n\n/**\n * Run every applicable axiom against `spec`. Throws a labeled Error on the first\n * violation. Axioms whose accessors are omitted are skipped (e.g. A7-passed\n * runs only when `setup` returns `passedIn`; A6 only when `surfaces` is given).\n */\nexport function assertStateUnitAxioms<T extends StateUnit>(\n spec: StateUnitAxiomSpec<T>,\n): void {\n const numRuns = spec.numRuns ?? 30;\n const fresh = (): Normalized<T> => normalize(spec.setup());\n\n // fast-check's default falsification message is just \"Property failed after N\n // tests {seed}\" — it drops the thrown axiom id. Prepend the axiom so a real\n // failure names itself; the seed/shrink detail is preserved.\n const run = (axiom: string, prop: Parameters<typeof fc.assert>[0]): void => {\n try {\n fc.assert(prop, { numRuns });\n } catch (e) {\n throw new Error(\n `${axiom}: ${e instanceof Error ? e.message : String(e)}`,\n { cause: e },\n );\n }\n };\n\n // X1 — no raw *origin* Subject on the public surface (expose `.asObservable()`).\n // Flag only origin Subjects — `new Subject` / `new BehaviorSubject`, the unit's own\n // state, where `.source` is undefined. Derived `AnonymousSubject`s from `Subject.lift`\n // (`shareReplay().pipe(...)`) carry a `.source` and are inert sinks (`.next()` does\n // nothing useful) — idiomatic, not the forgotten-internal-Subject smell — so exclude them.\n {\n const { unit, teardown } = fresh();\n for (const [key, value] of Object.entries(unit)) {\n if (\n value instanceof Subject &&\n (value as { source?: unknown }).source === undefined\n ) {\n throw new Error(\n `X1: public field \"${key}\" is a raw Subject — expose it via .asObservable()`,\n );\n }\n }\n unit.dispose();\n teardown();\n }\n\n // A7-passed — disposing the unit must NOT dispose an injected dependency.\n {\n const { unit, passedIn, teardown } = fresh();\n unit.dispose();\n passedIn.forEach((probe, i) => {\n if (probe.disposeCount > 0) {\n throw new Error(\n `A7-passed: the unit disposed injected dependency #${i} (it doesn't own it)`,\n );\n }\n });\n teardown();\n }\n\n // A5 — dispose() idempotent & total: n calls never throw; injected deps stay untouched.\n run(\n 'A5',\n fc.property(fc.integer({ min: 1, max: 20 }), (n) => {\n const { unit, passedIn, teardown } = fresh();\n for (let i = 0; i < n; i++) unit.dispose();\n passedIn.forEach((probe, i) => {\n if (probe.disposeCount > 0) {\n throw new Error(\n `injected dependency #${i} disposed under ${n} dispose() calls`,\n );\n }\n });\n teardown();\n }),\n );\n\n // A6 — k pre-dispose subscribers on each owned surface all see `complete` on dispose.\n if (spec.surfaces) {\n const surfaces = spec.surfaces;\n run(\n 'A6',\n fc.property(fc.integer({ min: 1, max: 10 }), (k) => {\n const { unit, teardown } = fresh();\n const completed: boolean[] = [];\n const subs = surfaces(unit).flatMap((o) =>\n Array.from({ length: k }, () => {\n const idx = completed.push(false) - 1;\n return o.subscribe({\n complete: () => {\n completed[idx] = true;\n },\n });\n }),\n );\n unit.dispose();\n completed.forEach((seen, idx) => {\n if (!seen)\n throw new Error(\n `a subscriber did not see complete on dispose (k=${k}, sub #${idx})`,\n );\n });\n subs.forEach((s) => s.unsubscribe());\n teardown();\n }),\n );\n }\n\n // A5b — post-dispose inertness: every public method is a no-op (no throw) after dispose.\n if (spec.invocations) {\n const invocations = spec.invocations;\n run(\n 'A5b',\n fc.property(fc.array(fc.nat(), { maxLength: 12 }), (seq) => {\n const { unit, teardown } = fresh();\n const callers = invocations(unit);\n unit.dispose();\n for (const raw of seq) {\n if (callers.length === 0) break;\n swallowAsync(callers[raw % callers.length]());\n }\n teardown();\n }),\n );\n }\n\n // X3-runtime — instance isolation: driving instance A never moves instance B's surfaces.\n if (spec.surfaces && spec.invocations) {\n const surfaces = spec.surfaces;\n const invocations = spec.invocations;\n run(\n 'X3-runtime',\n fc.property(fc.array(fc.nat(), { minLength: 1, maxLength: 8 }), (seq) => {\n const a = fresh();\n const b = fresh();\n const bSurfaces = surfaces(b.unit);\n const bCounts = bSurfaces.map(() => 0);\n const bSubs = bSurfaces.map((o, i) =>\n o.subscribe(() => {\n bCounts[i] += 1;\n }),\n );\n const baseline = bCounts.slice(); // initial replay captured synchronously above\n const aCallers = invocations(a.unit);\n for (const raw of seq) {\n if (aCallers.length === 0) break;\n swallowAsync(aCallers[raw % aCallers.length]());\n }\n bCounts.forEach((count, i) => {\n if (count !== baseline[i]) {\n throw new Error(\n `driving instance A perturbed instance B's surface #${i}`,\n );\n }\n });\n bSubs.forEach((s) => s.unsubscribe());\n a.unit.dispose();\n b.unit.dispose();\n a.teardown();\n b.teardown();\n }),\n );\n }\n\n // A7-owned — internally-constructed children are disposed (their surfaces complete) on outer dispose.\n if (spec.ownedChildSurfaces) {\n const { unit, teardown } = fresh();\n const childSurfaces = spec.ownedChildSurfaces(unit);\n const completed = childSurfaces.map(() => false);\n const subs = childSurfaces.map((o, i) =>\n o.subscribe({\n complete: () => {\n completed[i] = true;\n },\n }),\n );\n unit.dispose();\n completed.forEach((seen, i) => {\n if (!seen)\n throw new Error(\n `A7-owned: owned child surface #${i} did not complete on outer dispose`,\n );\n });\n subs.forEach((s) => s.unsubscribe());\n teardown();\n }\n\n // Post-dispose surface inertness: a NEW subscription after dispose completes with no `next`.\n if (spec.surfaces) {\n const { unit, teardown } = fresh();\n unit.dispose();\n spec.surfaces(unit).forEach((o, i) => {\n let nexts = 0;\n let done = false;\n o.subscribe({\n next: () => {\n nexts += 1;\n },\n complete: () => {\n done = true;\n },\n }).unsubscribe();\n if (nexts > 0)\n throw new Error(\n `A5b/inert: owned surface #${i} emitted a value after dispose`,\n );\n if (!done)\n throw new Error(\n `A5b/inert: owned surface #${i} did not complete after dispose`,\n );\n });\n teardown();\n }\n}\n","// Generated from protocol/specs/src/client/testing.json; do not edit.\n// Regenerate: make generate (codegen/lib/testing/typescript.ml)\n\nimport type { Arbitrary } from 'fast-check';\nimport type { Observable } from 'rxjs';\nimport type { BusOperationKey } from './bus-operations';\nimport type { FaultyTransport } from './faulty-transport';\n\nexport type FaultAction =\n /** The request's reply is delivered. */\n | { kind: 'deliver' }\n /** The request's reply is lost. */\n | { kind: 'drop-reply' }\n /** The request's reply is delivered after `ms` milliseconds. */\n | { kind: 'delay'; ms: number }\n /** The request's reply is delivered twice. */\n | { kind: 'duplicate-reply' }\n /** The emit itself is refused: the request never reaches the gateway. */\n | { kind: 'reject-emit' };\n\n/** The delays a drawn fault is of, in milliseconds. */\nexport const DELAY_MS = { minimum: 0, maximum: 5 } as const;\n\n/** How many faults a drawn schedule is of. */\nexport const SCHEDULE_LENGTH = { minimum: 1, maximum: 8 } as const;\n\n/** How many times its reckoned bound a case is given: the room a scheduler's jitter takes. */\nexport const SLACK = 4;\n\n/** One step of an interleaving: a write, or a client-initiated transition. */\nexport const DELIVERY_OPS = ['write', 'transition'] as const;\n\nexport type DeliveryOp = (typeof DELIVERY_OPS)[number];\n\n/** One request the transport was sent. */\nexport interface RequestLogEntry {\n channel: BusOperationKey;\n action: FaultAction;\n correlationId: string | undefined;\n retryKey: string;\n payload: Record<string, unknown>;\n}\n\n/** What one fresh run of a composition exposes to the axioms. */\nexport interface LivenessScenario {\n outputs: readonly Observable<unknown>[];\n settlements?: readonly Promise<unknown>[];\n teardown?: () => void;\n}\n\n/** A composition, and the schedules it is run under. */\nexport interface LivenessSpec {\n setup: (\n transport: FaultyTransport,\n ) => LivenessScenario | Promise<LivenessScenario>;\n timeoutMs: number;\n retryBudget?: number;\n cases?: number;\n schedules?: Arbitrary<readonly FaultAction[]>;\n makeResponse?: (\n operation: string,\n payload: Record<string, unknown>,\n ) => unknown;\n}\n","/**\n * Executable enforcement of the liveness axioms, and the composition-level sibling of\n * `assertStateUnitAxioms` (state-unit-axioms.ts). Where the StateUnit axioms\n * make *per-unit* wrongness mechanically detectable, these make *silence*\n * detectable: every existing enforcement tier is safety (nothing wrong is\n * delivered); these assert liveness (something is eventually delivered).\n *\n * Axioms (fault-schedule dimension; fast-check):\n * L1 Subscriber liveness — every output emits next|error within the bound,\n * under any fault schedule. Error is a permitted outcome; the forbidden\n * fourth state is pending-forever.\n * L2 Request settlement — every awaited path settles within the bound;\n * re-issues per logical request stay within the retry budget (B14: one);\n * a faulted request must be re-issued or surfaced, never swallowed.\n * L3 Delivery across lifecycle transitions — every event written to a live\n * connection reaches the output exactly once, wherever a client-initiated\n * transition (handover / reconnect / scope change) lands. Retirement is\n * by drain, never by abort (TRANSPORT-HTTP.md, Abort discipline).\n *\n * Framework-agnostic on purpose — only `rxjs` + `fast-check`, no `vitest` — so\n * it ships through `@xynolog/core/testing` and any package's test runner can\n * invoke it. An L1/L2 case waits out its whole bound in real time before it\n * judges, so a request sent again after every output has spoken is counted;\n * properties keep the bound small by passing a small explicit `timeoutMs` to\n * `Bus.request` — no `Date.now`, no 30 s real waits.\n */\n\nimport * as fc from 'fast-check';\nimport type { Observable, Subscription } from 'rxjs';\nimport { BRIDGED_CHANNELS } from './bridging';\nimport { FaultyTransport } from './faulty-transport';\nimport {\n DELAY_MS,\n DELIVERY_OPS,\n SCHEDULE_LENGTH,\n SLACK,\n type DeliveryOp,\n type FaultAction,\n type LivenessSpec,\n} from './testing-kit';\n\n// ── L1/L2: liveness over a composition on FaultyTransport ────────────────\n\n/** A fault of each kind, as likely as the others; a delay is of `DELAY_MS`. */\nconst FAULT_DRAWS: {\n [K in FaultAction['kind']]: fc.Arbitrary<Extract<FaultAction, { kind: K }>>;\n} = {\n deliver: fc.constant({ kind: 'deliver' }),\n 'drop-reply': fc.constant({ kind: 'drop-reply' }),\n delay: fc\n .integer({ min: DELAY_MS.minimum, max: DELAY_MS.maximum })\n .map((ms) => ({ kind: 'delay', ms })),\n 'duplicate-reply': fc.constant({ kind: 'duplicate-reply' }),\n 'reject-emit': fc.constant({ kind: 'reject-emit' }),\n};\n\nexport function arbFaultAction(): fc.Arbitrary<FaultAction> {\n return fc.oneof(...Object.values(FAULT_DRAWS));\n}\n\nexport function arbFaultSchedule(): fc.Arbitrary<readonly FaultAction[]> {\n return fc.array(arbFaultAction(), {\n minLength: SCHEDULE_LENGTH.minimum,\n maxLength: SCHEDULE_LENGTH.maximum,\n });\n}\n\nfunction describeSchedule(schedule: readonly FaultAction[]): string {\n return schedule\n .map((a) => (a.kind === 'delay' ? `delay(${a.ms})` : a.kind))\n .join(',');\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Sibling of state-unit-axioms' `run`, adapted for properties that check more\n * than one axiom: fast-check's falsification message carries the seed and\n * counterexample but not the thrown axiom id (fc v4 moves the inner error to\n * `cause`), so the property captures its own labeled violation into `slot`\n * and the wrapper re-throws with the axiom id leading and fc's detail after.\n */\nasync function runLabeled(\n fallback: string,\n slot: { violation: Error | null },\n assertion: () => Promise<void>,\n): Promise<void> {\n try {\n await assertion();\n } catch (e) {\n const detail = e instanceof Error ? e.message : String(e);\n if (slot.violation) {\n throw new Error(`${slot.violation.message}\\n${detail}`, { cause: e });\n }\n throw new Error(`${fallback}: ${detail}`, { cause: e });\n }\n}\n\n/** Wrap a check block so its labeled throw lands in `slot` before falsifying. */\nfunction capturing(slot: { violation: Error | null }, block: () => void): void {\n try {\n block();\n } catch (e) {\n slot.violation = e instanceof Error ? e : new Error(String(e));\n throw e;\n }\n}\n\n/**\n * Run L1 + L2 against `spec` across `spec.cases` fault schedules (25 unless\n * given), drawn from `spec.schedules` or `arbFaultSchedule`. A case's bound is\n * (timeoutMs × (1 + retryBudget) + Σdelays) × SLACK, and the retry budget is\n * one re-issue (B14) unless given. Throws a labeled Error (`L1: …` / `L2: …`)\n * on the first violation.\n */\nexport async function assertLivenessAxioms(spec: LivenessSpec): Promise<void> {\n const retryBudget = spec.retryBudget ?? 1;\n const schedules = spec.schedules ?? arbFaultSchedule();\n\n const slot = { violation: null as Error | null };\n await runLabeled('liveness', slot, () =>\n fc.assert(\n fc.asyncProperty(schedules, async (schedule) => {\n const delayTotal = schedule.reduce(\n (n, a) => n + (a.kind === 'delay' ? a.ms : 0),\n 0,\n );\n const bound = (spec.timeoutMs * (1 + retryBudget) + delayTotal) * SLACK;\n const transport = new FaultyTransport({\n channels: BRIDGED_CHANNELS,\n schedule,\n ...(spec.makeResponse ? { makeResponse: spec.makeResponse } : {}),\n });\n const scenario = await spec.setup(transport);\n const outputs = scenario.outputs;\n const settlements = scenario.settlements ?? [];\n\n // Subscribe every output (that's what makes a live query live) and\n // track notifications; track settlement of every awaited path.\n const notified: boolean[] = outputs.map(() => false);\n const settled: boolean[] = settlements.map(() => false);\n const subs: Subscription[] = outputs.map((o, i) =>\n o.subscribe({\n next: () => {\n notified[i] = true;\n },\n error: () => {\n notified[i] = true;\n },\n }),\n );\n settlements.forEach((p, i) => {\n p.then(\n () => {\n settled[i] = true;\n },\n () => {\n settled[i] = true;\n },\n );\n });\n\n // The whole bound, even once everything has spoken: a request sent\n // again after that still counts against the retry budget.\n await sleep(bound);\n\n try {\n // L2 first: when it applies it names the mechanism (swallow, budget,\n // unsettled await); L1 below is the broader every-output net. All-\n // outputs-silent is a subset of any-output-silent, so checking L1\n // first would shadow the sharper L2 diagnoses entirely.\n capturing(slot, () => {\n // L2 — settlement: every awaited path settled.\n settled.forEach((seen, i) => {\n if (!seen) {\n throw new Error(\n `L2: settlement #${i} did not settle within ${bound}ms ` +\n `under schedule ⟨${describeSchedule(schedule)}⟩ — the forbidden fourth state`,\n );\n }\n });\n\n // L2 — retry accounting over the transport's request log.\n const issues = new Map<\n string,\n { count: number; lastFaulted: boolean }\n >();\n for (const entry of transport.requestLog) {\n const prior = issues.get(entry.retryKey) ?? {\n count: 0,\n lastFaulted: false,\n };\n issues.set(entry.retryKey, {\n count: prior.count + 1,\n lastFaulted:\n entry.action.kind === 'drop-reply' ||\n entry.action.kind === 'reject-emit',\n });\n }\n for (const [key, { count, lastFaulted }] of issues) {\n if (count > 1 + retryBudget) {\n throw new Error(\n `L2: request ⟨${key}⟩ issued ${count} times — exceeds the retry budget ` +\n `(1 + ${retryBudget}) under schedule ⟨${describeSchedule(schedule)}⟩`,\n );\n }\n // Swallow detection: the final issue of a logical request was\n // faulted, the composition had retry budget left but didn't use\n // it, and no output surfaced anything — the rejection went into\n // a void (the `catch(() => {})` B14 rules out).\n if (\n lastFaulted &&\n count <= retryBudget &&\n outputs.length > 0 &&\n !notified.some(Boolean)\n ) {\n throw new Error(\n `L2: faulted request ⟨${key}⟩ was neither re-issued nor surfaced ` +\n `under schedule ⟨${describeSchedule(schedule)}⟩ — rejection swallowed`,\n );\n }\n }\n\n // L1 — every subscription saw next|error; pending-forever is the bug.\n notified.forEach((seen, i) => {\n if (!seen) {\n throw new Error(\n `L1: output #${i} received no next/error within ${bound}ms ` +\n `under schedule ⟨${describeSchedule(schedule)}⟩ — silently pending`,\n );\n }\n });\n });\n } finally {\n subs.forEach((s) => s.unsubscribe());\n scenario.teardown?.();\n transport.dispose();\n }\n }),\n { numRuns: spec.cases ?? 25 },\n ),\n );\n}\n\n// ── L3: exactly-once delivery across client-initiated transitions ────────\n\n/**\n * A connection-stream-shaped subject: something that accepts writes to the\n * live connection, can be told to transition (handover / reconnect / scope\n * change), and exposes the subscriber-facing output. The http-transport\n * actor's property suite adapts the real actor's mock-connection harness to\n * this shape; the teeth tests drive deliberately-broken doubles.\n */\nexport interface DeliverySubject {\n /** Write the event with this id to the currently-live connection. */\n write: (eventId: string) => void;\n /** Client-initiated lifecycle transition. */\n transition: () => void | Promise<void>;\n /** Subscriber-facing output; each emission is a delivered event id. */\n output$: Observable<string>;\n /**\n * Drain pending asynchronous delivery at end of sequence (a live connection\n * eventually flushes). Default: one macrotask tick.\n */\n settle?: () => Promise<void>;\n teardown?: () => void;\n}\n\nexport interface DeliveryAxiomSpec {\n /** Build a FRESH subject. Called per run. */\n setup: () => DeliverySubject;\n /** Override the generated op sequences (teeth tests pin one). */\n opsArb?: fc.Arbitrary<readonly DeliveryOp[]>;\n /** Max generated sequence length (default 12). */\n maxOps?: number;\n /** fast-check run budget (default 50 — these runs are cheap). */\n numRuns?: number;\n}\n\nexport function arbDeliveryOps(\n maxOps = 12,\n): fc.Arbitrary<readonly DeliveryOp[]> {\n return (\n fc\n .array(fc.constantFrom(...DELIVERY_OPS), {\n minLength: 1,\n maxLength: maxOps,\n })\n // A sequence with no write asserts nothing — always exercise delivery.\n .map((ops) =>\n ops.includes('write') ? ops : ([...ops, 'write'] as const),\n )\n );\n}\n\n/**\n * Run L3 against `spec` across generated write/transition interleavings.\n * Throws a labeled Error (`L3: …`) on the first violation: an event written\n * to a live connection delivered zero times (lost — retired by abort instead\n * of drain) or more than once (duplicate).\n */\nexport async function assertExactlyOnceDelivery(\n spec: DeliveryAxiomSpec,\n): Promise<void> {\n const opsArb = spec.opsArb ?? arbDeliveryOps(spec.maxOps ?? 12);\n\n const slot = { violation: null as Error | null };\n await runLabeled('L3', slot, () =>\n fc.assert(\n fc.asyncProperty(opsArb, async (ops) => {\n const subject = spec.setup();\n const delivered: string[] = [];\n const sub = subject.output$.subscribe((id) => delivered.push(id));\n const written: string[] = [];\n try {\n for (let i = 0; i < ops.length; i++) {\n if (ops[i] === 'write') {\n const id = `e${i}`;\n written.push(id);\n subject.write(id);\n } else {\n await subject.transition();\n }\n // Deliberately no settling between ops: the interesting races are\n // transitions landing before a write's asynchronous delivery.\n }\n await (subject.settle?.() ?? sleep(0));\n\n capturing(slot, () => {\n for (const id of written) {\n const n = delivered.filter((d) => d === id).length;\n if (n === 0) {\n throw new Error(\n `L3: event ⟨${id}⟩ delivered 0 times under ⟨${ops.join(',')}⟩ — ` +\n `lost across a transition (retire by drain, never by abort)`,\n );\n }\n if (n > 1) {\n throw new Error(\n `L3: event ⟨${id}⟩ delivered ${n} times under ⟨${ops.join(',')}⟩ — duplicate delivery`,\n );\n }\n }\n });\n } finally {\n sub.unsubscribe();\n subject.teardown?.();\n }\n }),\n { numRuns: spec.numRuns ?? 50 },\n ),\n );\n}\n"]}
|
package/dist/testing.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { BehaviorSubject, Observable } from 'rxjs';
|
|
2
|
-
import { ITransport, BaseUrl,
|
|
2
|
+
import { ITransport, BaseUrl, TransportError, RequestLogEntry, EventMap, FaultAction, BusOperationKey, Envelope, Refused, Frame, ResourceId, EventBus } from '@xynolog/core';
|
|
3
3
|
export { FaultAction, RequestLogEntry } from '@xynolog/core';
|
|
4
4
|
|
|
5
5
|
/**
|
|
@@ -15,6 +15,16 @@ export { FaultAction, RequestLogEntry } from '@xynolog/core';
|
|
|
15
15
|
* including `http-transport`, below sdk — can consume it via
|
|
16
16
|
* `@xynolog/core/testing` without a dependency cycle.
|
|
17
17
|
*
|
|
18
|
+
* Each frame emitted is relayed back in the trace it was sent under, the
|
|
19
|
+
* active trace at the emit (`activeTrace`), as a gateway relays a frame in
|
|
20
|
+
* the trace its sender put on it; a reply carries none. Each frame its
|
|
21
|
+
* stream carries arrives as a frame a wire transport reads arrives: its
|
|
22
|
+
* arrival is marked in the trace it was sent under (`arrived`, the
|
|
23
|
+
* `bus.recv:{channel}` span `@xynolog/observability` registers), and it is
|
|
24
|
+
* delivered in the trace that gives. So a job a claim is answered with is in
|
|
25
|
+
* the trace its reply's arrival began when the installed tracer records that
|
|
26
|
+
* span, as it is over the wire (WORKER-CONTRACT T1).
|
|
27
|
+
*
|
|
18
28
|
* Deterministic-by-construction: no `Date.now`, no randomness of its own —
|
|
19
29
|
* all variation comes in through the schedule (fast-check owns the seed).
|
|
20
30
|
* Time is real `setTimeout` at millisecond scale; properties pass a small
|
|
@@ -40,7 +50,8 @@ interface FaultyTransportConfig {
|
|
|
40
50
|
/**
|
|
41
51
|
* Synthesize the `response` value for a delivered reply. Return `undefined`
|
|
42
52
|
* for a void ack (a reply that carries no `response`). Default:
|
|
43
|
-
* `refuseUnscriptedOperation`, which throws naming the
|
|
53
|
+
* `refuseUnscriptedOperation`, which throws a `TransportError` naming the
|
|
54
|
+
* operation.
|
|
44
55
|
*/
|
|
45
56
|
makeResponse?: (operation: BusOperationKey, payload: Record<string, unknown>) => unknown;
|
|
46
57
|
}
|
|
@@ -65,7 +76,7 @@ declare function refuseUnscriptedOperation(operation: string): never;
|
|
|
65
76
|
declare function retryKeyOf(channel: string, payload: Record<string, unknown>): string;
|
|
66
77
|
declare class FaultyTransport implements ITransport {
|
|
67
78
|
readonly baseUrl: BaseUrl;
|
|
68
|
-
readonly state$: BehaviorSubject<
|
|
79
|
+
readonly state$: BehaviorSubject<"initial" | "connecting" | "open" | "reconnecting" | "degraded" | "unauthenticated" | "closed">;
|
|
69
80
|
private readonly failures;
|
|
70
81
|
/**
|
|
71
82
|
* The failures `fail` reports. Of those reported before its first reader,
|
|
@@ -73,10 +84,10 @@ declare class FaultyTransport implements ITransport {
|
|
|
73
84
|
* order reported; what is still kept when the transport is disposed is
|
|
74
85
|
* dropped.
|
|
75
86
|
*/
|
|
76
|
-
readonly errors$: Observable<
|
|
87
|
+
readonly errors$: Observable<TransportError>;
|
|
77
88
|
/** Every request-channel emit, in order — the L2 accounting surface. */
|
|
78
89
|
readonly requestLog: RequestLogEntry[];
|
|
79
|
-
/** Every frame
|
|
90
|
+
/** Every frame its stream carries, a request's echo and its reply included, as it arrived (`arrive`). */
|
|
80
91
|
private readonly bus;
|
|
81
92
|
private readonly channels;
|
|
82
93
|
/** The resources whose scopes are held, each with how many hold it. */
|
|
@@ -107,10 +118,10 @@ declare class FaultyTransport implements ITransport {
|
|
|
107
118
|
* Report `error` on `errors$`, as a transport reports a request the
|
|
108
119
|
* gateway refused. A disposed transport reports nothing.
|
|
109
120
|
*/
|
|
110
|
-
fail(error:
|
|
111
|
-
emit<K extends keyof EventMap>(channel: K, payload: EventMap[K], envelope?:
|
|
112
|
-
on<K extends keyof EventMap>(channel: K, handler: (payload: EventMap[K] |
|
|
113
|
-
stream<K extends keyof EventMap>(channel: K): Observable<EventMap[K] |
|
|
121
|
+
fail(error: TransportError): void;
|
|
122
|
+
emit<K extends keyof EventMap>(channel: K, payload: EventMap[K], envelope?: Envelope): Promise<number | undefined>;
|
|
123
|
+
on<K extends keyof EventMap>(channel: K, handler: (payload: EventMap[K] | Refused) => void): () => void;
|
|
124
|
+
stream<K extends keyof EventMap>(channel: K): Observable<EventMap[K] | Refused>;
|
|
114
125
|
/**
|
|
115
126
|
* The frames on the channel that a wire transport's stream would carry: one
|
|
116
127
|
* of no scope on a channel this transport was given, and one of a
|
|
@@ -124,7 +135,19 @@ declare class FaultyTransport implements ITransport {
|
|
|
124
135
|
* not given is refused at the call, as `bus.unsubscribed`: a frame on it
|
|
125
136
|
* could never arrive.
|
|
126
137
|
*/
|
|
127
|
-
frames<K extends keyof EventMap>(channel: K): Observable<
|
|
138
|
+
frames<K extends keyof EventMap>(channel: K): Observable<Frame<EventMap[K] | Refused>>;
|
|
139
|
+
/**
|
|
140
|
+
* Whether its stream carries a frame on `channel`, on `scope`: one of no
|
|
141
|
+
* scope on a channel this transport was given, and one of a resource's
|
|
142
|
+
* scope on a resource-scoped channel while that scope is held.
|
|
143
|
+
*/
|
|
144
|
+
private carries;
|
|
145
|
+
/**
|
|
146
|
+
* A frame `frame`, sent under its `trace`, arriving on the stream: one the
|
|
147
|
+
* stream does not carry reaches nobody, and one it carries has its arrival
|
|
148
|
+
* marked (`arrived`) and is delivered in the trace that gives.
|
|
149
|
+
*/
|
|
150
|
+
private arrive;
|
|
128
151
|
/**
|
|
129
152
|
* Whether the channels this transport was given name `channel`, as a wire
|
|
130
153
|
* transport answers for its stream's global set: a request whose replies
|
package/dist/testing.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { FaultyTransport, refuseUnscriptedOperation, retryKeyOf } from './chunk-
|
|
2
|
-
import './chunk-
|
|
1
|
+
export { FaultyTransport, refuseUnscriptedOperation, retryKeyOf } from './chunk-PT6P47KV.js';
|
|
2
|
+
import './chunk-NZ7SRPXU.js';
|
|
3
3
|
//# sourceMappingURL=testing.js.map
|
|
4
4
|
//# sourceMappingURL=testing.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xynolog/core",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.2",
|
|
4
4
|
"description": "Core types and domain logic for Xynolog - Resource, Annotation, and Graph models",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -47,6 +47,10 @@
|
|
|
47
47
|
"url": "git+https://github.com/xynolog/sdk.git",
|
|
48
48
|
"directory": "typescript/core"
|
|
49
49
|
},
|
|
50
|
+
"homepage": "https://github.com/xynolog/sdk#readme",
|
|
51
|
+
"bugs": {
|
|
52
|
+
"url": "https://github.com/xynolog/sdk/issues"
|
|
53
|
+
},
|
|
50
54
|
"scripts": {
|
|
51
55
|
"typecheck": "tsc --noEmit",
|
|
52
56
|
"build": "npm run typecheck && tsup && tsc -p tsconfig.build.json && rollup -c rollup.dts.config.mjs && rm -rf dist-types",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/faulty-transport.ts"],"names":[],"mappings":";;;;AAmFO,SAAS,0BAA0B,SAAA,EAA0B;AAClE,EAAA,MAAM,IAAI,KAAA;AAAA,IACR,CAAA,wCAAA,EAA2C,SAAS,CAAA,yCAAA,EACT,SAAS,CAAA,sDAAA;AAAA,GAEtD;AACF;AAEA,SAAS,YAAY,OAAA,EAA6C;AAChE,EAAA,OAAO,OAAA,IAAW,cAAA;AACpB;AAKO,SAAS,UAAA,CACd,SACA,OAAA,EACQ;AACR,EAAA,MAAM,OAAA,GAAU,MAAA,CAAO,OAAA,CAAQ,OAAO,CAAA,CACnC,MAAA,CAAO,CAAC,CAAC,CAAC,CAAA,KAAM,CAAA,KAAM,WAAA,IAAe,CAAA,KAAM,UAAU,CAAA,CACrD,IAAA,CAAK,CAAC,CAAC,CAAC,CAAA,EAAG,CAAC,CAAC,CAAA,KAAO,CAAA,GAAI,CAAA,GAAI,EAAA,GAAK,CAAE,CAAA;AACtC,EAAA,OAAO,GAAG,OAAO,CAAA,CAAA,EAAI,IAAA,CAAK,SAAA,CAAU,OAAO,CAAC,CAAA,CAAA;AAC9C;AAEO,IAAM,kBAAN,MAA4C;AAAA,EACxC,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A;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,WAAW,GAAA,EAAqB;AAC9B,IAAA,WAAA;AAAA,MACE,IAAA;AAAA,MACA;AAAA;AAAA,QAEE,IAAA,EAAM,CAAC,OAAA,EAAS,OAAA,EAAS,aACvB,GAAA,CAAI,IAAA;AAAA,UACF,OAAA;AAAA,UACA,UAAA,CAAW,OAAA,EAAS,OAAA,EAAS,QAAA,CAAS,aAAa,CAAA;AAAA,UACnD;AAAA;AACF,OACJ;AAAA,MACA,CAAC,GAAG,IAAA,CAAK,QAAA,EAAU,GAAG,wBAAwB,CAAA;AAAA;AAAA,MAE9C,CAAC,SAAS,KAAA,KAAU;AAClB,QAAA,MAAM,IAAI,KAAA;AAAA,UACR,kCAAkC,OAAiB,CAAA,OAAA,CAAA;AAAA,UACnD,EAAE,OAAO,KAAA;AAAM,SACjB;AAAA,MACF;AAAA,KACF;AAAA,EACF;AAAA;AAAA,EAIA,OAAA,GAAgB;AACd,IAAA,IAAI,KAAK,QAAA,EAAU;AACnB,IAAA,IAAA,CAAK,QAAA,GAAW,IAAA;AAChB,IAAA,IAAA,CAAK,eAAe,KAAA,EAAM;AAC1B,IAAA,KAAA,MAAW,CAAA,IAAK,IAAA,CAAK,MAAA,EAAQ,YAAA,CAAa,CAAC,CAAA;AAC3C,IAAA,IAAA,CAAK,OAAO,KAAA,EAAM;AAClB,IAAA,IAAA,CAAK,MAAA,CAAO,KAAK,QAAQ,CAAA;AACzB,IAAA,IAAA,CAAK,OAAO,QAAA,EAAS;AACrB,IAAA,IAAA,CAAK,SAAS,GAAA,EAAI;AAElB,IAAA,IAAA,CAAK,IAAI,OAAA,EAAQ;AAAA,EACnB;AACF","file":"chunk-JVQYMUSA.js","sourcesContent":["/**\n * FaultyTransport — a seeded, scriptable `ITransport` simulator for the\n * liveness axioms. fast-check draws a fault\n * schedule; the transport applies one `FaultAction` per request-channel emit\n * and synthesizes replies from the `BUS_OPERATIONS` registry, so real\n * compositions (`Bus.request`, SWR caches, live queries) run unmodified against\n * generated wire behavior no hand-written test names.\n *\n * Home is core (not sdk/test-utils) for the same reason as\n * `assertStateUnitAxioms`: it needs only core types, and every layer —\n * including `http-transport`, below sdk — can consume it via\n * `@xynolog/core/testing` without a dependency cycle.\n *\n * Deterministic-by-construction: no `Date.now`, no randomness of its own —\n * all variation comes in through the schedule (fast-check owns the seed).\n * Time is real `setTimeout` at millisecond scale; properties pass a small\n * explicit `timeoutMs` to `Bus.request`, so nothing waits 30 s.\n */\n\nimport { BehaviorSubject, type Observable } from 'rxjs';\nimport { filter, map } from 'rxjs/operators';\nimport type { XynologError } from './errors';\nimport { KeptForFirstReader } from './kept-for-first-reader';\nimport type { BaseUrl } from './branded-types';\nimport { baseUrl as makeBaseUrl } from './branded-types';\nimport type { ResourceId } from './identifiers';\nimport { TRACE_FIELD, USER_FIELD, type EventMap } from './bus-protocol';\nimport type { BusEnvelope, BusFrame } from './event-bus';\nimport type { ConnectionState, ITransport } from './transport';\nimport { EventBus } from './event-bus';\nimport {\n BUS_OPERATIONS,\n REPLY_NAMES,\n type BusOperationKey,\n} from './bus-operations';\nimport { asDeclared, type FrameRefusal } from './bus';\nimport { BusRequestError } from './bus-request';\nimport { RESOURCE_SCOPED_CHANNELS } from './bridged-channels';\nimport { isResourceScopedChannel } from './bridging';\nimport { relayFrames } from './relay-frames';\nimport type { FaultAction, RequestLogEntry } from './testing-kit';\n\nexport interface FaultyTransportConfig {\n /**\n * The global channels this transport is given, as a wire transport is\n * given its stream's: a frame of no scope reaches a reader only on one of\n * them, a request's echo and a reply included; it bridges them, beside the\n * resource-scoped channels, into a client's bus, answers `isSubscribed` for\n * them alone, and assumes none of its own. A full client's test gives it `BRIDGED_CHANNELS`; a worker's,\n * the reply channels it awaits and what its claims read\n * (`JOB_CLAIM_CHANNELS`).\n */\n channels: readonly (keyof EventMap)[];\n /**\n * The i-th request-channel emit applies `schedule[i % schedule.length]`.\n * Empty/omitted → every request delivers.\n */\n schedule?: readonly FaultAction[];\n /**\n * Synthesize the `response` value for a delivered reply. Return `undefined`\n * for a void ack (a reply that carries no `response`). Default:\n * `refuseUnscriptedOperation`, which throws naming the operation.\n */\n makeResponse?: (\n operation: BusOperationKey,\n payload: Record<string, unknown>,\n ) => unknown;\n}\n\n/**\n * The default `makeResponse`: refuse, rather than invent.\n *\n * A `() => ({})` default would answer every unscripted operation with a\n * SUCCESS whose every field is `undefined`. That is not a neutral default —\n * it is a fabricated reply, and it surfaces far from its cause (a caller doing\n * `result.engines.find(...)` reports `undefined is not a function`, naming\n * neither the operation nor the missing script). A shape-correct empty default\n * would be worse still: a hand-written mirror of a wire shape the spec owns,\n * carrying a fallback.\n *\n * So the default names the gap. A test that wants an answer scripts one via\n * `queueReply` or its own `makeResponse`.\n */\nexport function refuseUnscriptedOperation(operation: string): never {\n throw new Error(\n `No response scripted for bus operation \"${operation}\". ` +\n `Script one with transport.queueReply('${operation}', <response>) ` +\n `or pass a makeResponse that handles it.`,\n );\n}\n\nfunction isOperation(channel: string): channel is BusOperationKey {\n return channel in BUS_OPERATIONS;\n}\n\n/** Stable request identity: channel + sorted payload minus per-issue fields.\n * The correlation key is not among them — it rides the envelope, so the\n * payload is stable across retries of the same request. */\nexport function retryKeyOf(\n channel: string,\n payload: Record<string, unknown>,\n): string {\n const entries = Object.entries(payload)\n .filter(([k]) => k !== TRACE_FIELD && k !== USER_FIELD)\n .sort(([a], [b]) => (a < b ? -1 : 1));\n return `${channel} ${JSON.stringify(entries)}`;\n}\n\nexport class FaultyTransport implements ITransport {\n readonly baseUrl: BaseUrl = makeBaseUrl('faulty://simulator');\n readonly state$ = new BehaviorSubject<ConnectionState>('open');\n private readonly failures = new KeptForFirstReader<XynologError>();\n /**\n * The failures `fail` reports. Of those reported before its first reader,\n * the latest `ERRORS_KEPT_FOR_FIRST_READER_COUNT` are kept for it, in the\n * order reported; what is still kept when the transport is disposed is\n * dropped.\n */\n readonly errors$: Observable<XynologError> = this.failures.said$;\n\n /** Every request-channel emit, in order — the L2 accounting surface. */\n readonly requestLog: RequestLogEntry[] = [];\n\n /** Every frame emitted, a request's echo and its reply included: what a reader is given is gated in `frames`. */\n private readonly bus = new EventBus();\n private readonly channels: ReadonlySet<keyof EventMap>;\n /** The resources whose scopes are held, each with how many hold it. */\n private readonly scopeRefCounts = new Map<ResourceId, number>();\n private readonly schedule: readonly FaultAction[];\n private readonly makeResponse: (\n op: BusOperationKey,\n payload: Record<string, unknown>,\n ) => unknown;\n private readonly replyQueues = new Map<BusOperationKey, unknown[]>();\n private requestCount = 0;\n private readonly timers = new Set<ReturnType<typeof setTimeout>>();\n private disposed = false;\n\n constructor(cfg: FaultyTransportConfig) {\n this.channels = new Set(cfg.channels);\n this.schedule = cfg.schedule ?? [];\n this.makeResponse = cfg.makeResponse ?? refuseUnscriptedOperation;\n }\n\n /**\n * Queue responses for `op`, consumed FIFO — one per request that reaches\n * the simulated gateway — before falling back to `makeResponse`. The queue\n * scripts the GATEWAY; the fault schedule scripts the WIRE. Consequences,\n * deliberately: `duplicate-reply` replays one entry's body twice, and a\n * `drop-reply` still consumes its entry (the gateway answered; the wire ate\n * it) — so \"first reply lost, the retry sees the NEXT page\" is expressible.\n * `reject-emit` consumes nothing: that request never reached the gateway.\n *\n * Each entry is a `response`. A reply that names what it answers for beside\n * its response (`REPLY_NAMES`: the resource a context was gathered for, the\n * reference a search was for) takes that from its request, as a gateway's\n * does: a test queues the response alone.\n */\n queueReply(op: BusOperationKey, ...responses: unknown[]): void {\n const q = this.replyQueues.get(op) ?? [];\n q.push(...responses);\n this.replyQueues.set(op, q);\n }\n\n /**\n * Report `error` on `errors$`, as a transport reports a request the\n * gateway refused. A disposed transport reports nothing.\n */\n fail(error: XynologError): void {\n this.failures.say(error);\n }\n\n // ── Bus primitives ──────────────────────────────────────────────────────\n\n async emit<K extends keyof EventMap>(\n channel: K,\n payload: EventMap[K],\n envelope?: BusEnvelope,\n ): Promise<number | undefined> {\n // The double models exactly one connected participant, so a delivered\n // emit reports `1`; post-dispose it is inert and reports no count.\n if (this.disposed) return undefined;\n const name = channel as string;\n if (!isOperation(name)) {\n // Non-request channel: forward as-is (scoped or global).\n const target =\n envelope?.scope === undefined\n ? this.bus\n : this.bus.scope(envelope!.scope);\n // `scope` is not repeated — targeting the scoped bus IS how it is set.\n target.emit(channel, payload, { correlationId: envelope?.correlationId });\n return 1;\n }\n\n const record = payload as Record<string, unknown>;\n const action: FaultAction =\n this.schedule.length === 0\n ? { kind: 'deliver' }\n : this.schedule[this.requestCount % this.schedule.length]!;\n this.requestCount += 1;\n this.requestLog.push({\n channel: name,\n action,\n correlationId: envelope?.correlationId,\n retryKey: retryKeyOf(name, record),\n // Copied at emit time, so a caller that mutates its own payload\n // afterwards cannot rewrite the log; nested objects are shared.\n payload: { ...record },\n });\n\n if (action.kind === 'reject-emit') {\n // Models a /bus/emit 4xx: the request never reaches the bus.\n throw new Error(\n `FaultyTransport: emit rejected by schedule (reject-emit) on ${name}`,\n );\n }\n\n // The request itself is observable (handlers-eye view) to a reader of a\n // transport given its channel, then the simulator plays gateway:\n // synthesize the registry reply per the action. The envelope rides along:\n // a handler watching this double must read the same frame it would across\n // a broker.\n this.bus.emit(channel, payload, envelope);\n\n // The gateway's answer is computed ONCE per request that reaches it —\n // the reply QUEUE scripts the gateway, the fault schedule scripts the\n // wire. So `duplicate-reply` replays the same body twice, and a\n // `drop-reply` still consumes its queue entry: the gateway answered, the\n // wire ate it.\n const queue = this.replyQueues.get(name);\n const response =\n queue && queue.length > 0\n ? queue.shift()\n : this.makeResponse(name, record);\n\n // A reply that names what it answers for names what its request did, as a\n // gateway's does. Refused here, where it rejects the emit, rather than in\n // the reply's own microtask, where nobody is awaiting it.\n const named: Record<string, unknown> = {};\n for (const property of REPLY_NAMES[name]) {\n if (record[property] === undefined) {\n throw new Error(\n `FaultyTransport: the reply to ${name} names \"${property}\", which this request does not state`,\n );\n }\n named[property] = record[property];\n }\n\n const reply = (): void => {\n if (this.disposed) return;\n const replyPayload =\n response === undefined ? { ...named } : { ...named, response };\n const resultChannel = BUS_OPERATIONS[name].result as keyof EventMap;\n // The key rides back on the envelope, never inside the reply payload.\n this.bus.emit(resultChannel, replyPayload as EventMap[keyof EventMap], {\n correlationId: envelope?.correlationId,\n });\n };\n\n switch (action.kind) {\n case 'deliver':\n queueMicrotask(reply);\n break;\n case 'duplicate-reply':\n queueMicrotask(reply);\n queueMicrotask(reply);\n break;\n case 'delay': {\n const t = setTimeout(() => {\n this.timers.delete(t);\n reply();\n }, action.ms);\n this.timers.add(t);\n break;\n }\n case 'drop-reply':\n break;\n }\n return 1;\n }\n\n on<K extends keyof EventMap>(\n channel: K,\n handler: (payload: EventMap[K] | FrameRefusal) => void,\n ): () => void {\n const sub = this.stream(channel).subscribe(handler);\n return () => sub.unsubscribe();\n }\n\n stream<K extends keyof EventMap>(\n channel: K,\n ): Observable<EventMap[K] | FrameRefusal> {\n return this.frames(channel).pipe(map((frame) => frame.payload));\n }\n\n /**\n * The frames on the channel that a wire transport's stream would carry: one\n * of no scope on a channel this transport was given, and one of a\n * resource's scope on a resource-scoped channel while that scope is held.\n * Every other frame is dropped. A stream carries every scope it holds on\n * the one channel, so a reader of one resource's keeps that scope's\n * (`Bus.frames(channel, resourceId)`).\n *\n * A resource-scoped channel is read with no scope held, as a wire\n * transport reads it, and carries nothing until one is. Any other channel\n * not given is refused at the call, as `bus.unsubscribed`: a frame on it\n * could never arrive.\n */\n frames<K extends keyof EventMap>(\n channel: K,\n ): Observable<BusFrame<EventMap[K] | FrameRefusal>> {\n if (!this.channels.has(channel) && !isResourceScopedChannel(channel)) {\n throw new BusRequestError(\n `Transport is not subscribed to ${channel as string} — a frame on it can never arrive on this connection. Give the transport the channel.`,\n 'bus.unsubscribed',\n { channel },\n );\n }\n return this.bus\n .channelStream(channel)\n .pipe(\n filter((frame) =>\n frame.scope === undefined\n ? this.channels.has(channel)\n : isResourceScopedChannel(channel) &&\n this.scopeRefCounts.has(frame.scope),\n ),\n );\n }\n\n /**\n * Whether the channels this transport was given name `channel`, as a wire\n * transport answers for its stream's global set: a request whose replies\n * they do not name fails at once, as `bus.unsubscribed`.\n */\n isSubscribed(channel: keyof EventMap): boolean {\n return this.channels.has(channel);\n }\n\n /**\n * Hold `resourceId`'s scope until the returned release, as a wire\n * transport holds it: each acquisition counts, distinct resources compose,\n * the scope is let go at its last release, and a release is idempotent.\n */\n subscribeToResource(resourceId: ResourceId): () => void {\n this.scopeRefCounts.set(\n resourceId,\n (this.scopeRefCounts.get(resourceId) ?? 0) + 1,\n );\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const holds = this.scopeRefCounts.get(resourceId);\n // None once the transport is disposed, which let every scope go.\n if (holds === undefined) return;\n if (holds > 1) this.scopeRefCounts.set(resourceId, holds - 1);\n else this.scopeRefCounts.delete(resourceId);\n };\n }\n\n /**\n * Correlated-reply tracking, exposed for assertions: `Bus.request` registers\n * each cid here before its emit and releases on settle, so a test can pin\n * the tracked set at any point of a request's lifecycle. This double never\n * drops its stream, so it has nothing to replay, and tracking has no\n * behavioral effect.\n */\n readonly pendingReplies = new Set<string>();\n\n trackReply(correlationId: string): () => void {\n this.pendingReplies.add(correlationId);\n let released = false;\n return () => {\n if (released) return;\n released = true;\n this.pendingReplies.delete(correlationId);\n };\n }\n\n /**\n * Publish on `bus` what `frames` delivers on the channels this transport\n * was given and on the resource-scoped ones, as a wire transport's bridge\n * does: a resource's frame while its scope is held, with no scope, since\n * the relay carries none.\n */\n bridgeInto(bus: EventBus): void {\n relayFrames(\n this,\n {\n // A payload that is not its channel's is published as its refusal, as a wire transport's bridge does.\n emit: (channel, payload, envelope) =>\n bus.emit(\n channel,\n asDeclared(channel, payload, envelope.correlationId),\n envelope,\n ),\n },\n [...this.channels, ...RESOURCE_SCOPED_CHANNELS],\n // `EventBus.emit` is synchronous, so this never fires.\n (channel, error) => {\n throw new Error(\n `FaultyTransport: the bridge of ${channel as string} failed`,\n { cause: error },\n );\n },\n );\n }\n\n // ── Lifecycle ───────────────────────────────────────────────────────────\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.scopeRefCounts.clear();\n for (const t of this.timers) clearTimeout(t);\n this.timers.clear();\n this.state$.next('closed');\n this.state$.complete();\n this.failures.end();\n // Completes every subject: in-flight busRequests resolve `bus.closed`.\n this.bus.destroy();\n }\n}\n"]}
|