Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadStream.ts

96 lines3.3 KB

1import type {
2 OrchestrationV2ThreadProjection,
3 OrchestrationV2ThreadStreamItem,
4} from "@t3tools/contracts";
5​
6import { buildBoundedThreadProjection } from "./threadHistoryPaging.ts";
7import { projectThreadProjectionForWire } from "./WireProjection.ts";
8​
9/** Maximum number of reducer applications allowed during a thread resume. */
10export const THREAD_RESUME_MAX_REPLAY_EVENTS = 128;
11​
12/** Maximum encoded event JSON allowed during a thread resume. */
13export const THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES = 1_048_576;
14​
15/**
16 * Maximum aggregate persisted payload JSON decoded for one thread resume.
17 * Keep the original preflight budget: decoded objects and temporary strings
18 * cost more than their stored JSON, even if wire projection shrinks them later.
19 */
20export const THREAD_RESUME_MAX_RAW_PAYLOAD_BYTES = 1_048_576;
21​
22/** Resource-safety check applied before persisted replay payloads are decoded. */
23export function isThreadReplayRawPayloadSafe(rawPayloadBytes: number): boolean {
24 return rawPayloadBytes <= THREAD_RESUME_MAX_RAW_PAYLOAD_BYTES;
26​
27/** Encoded payload cost after events have been projected for the wire. */
28export function threadReplayEncodedBytes(items: ReadonlyArray<unknown>): number {
29 let total = 0;
30 for (const item of items) {
31 const encoded = JSON.stringify(item);
32 total += Buffer.byteLength(encoded ?? "", "utf8");
33 }
34 return total;
36​
37type ThreadSnapshotStreamItem = Extract<
38 OrchestrationV2ThreadStreamItem,
39 { readonly kind: "snapshot" }
40>;
41​
42/** Build the same bounded, wire-projected snapshot for every socket fallback path. */
43export function buildBoundedThreadStreamSnapshot(input: {
44 readonly snapshotSequence: number;
45 readonly projection: OrchestrationV2ThreadProjection;
46}): ThreadSnapshotStreamItem {
47 const bounded = buildBoundedThreadProjection({
48 snapshotSequence: input.snapshotSequence,
49 projection: projectThreadProjectionForWire(input.projection),
50 });
51 return {
52 kind: "snapshot",
53 snapshotSequence: input.snapshotSequence,
54 projection: bounded.projection,
55 historyCursor: bounded.historyCursor,
56 hasMoreHistory: bounded.hasMoreHistory,
57 latestLocalTurnOrdinal: bounded.latestLocalTurnOrdinal,
58 payloadBudgetExceeded: bounded.payloadBudgetExceeded,
59 };
61​
62export type ThreadResumePlan =
63 | {
64 readonly mode: "replay";
65 readonly afterSequence: number;
66 readonly throughSequence: number;
67 }
68 | { readonly mode: "snapshot" };
69​
70/**
71 * Decide whether a thread subscription should replay the event gap after the
72 * client's cursor or send a fresh snapshot instead.
73 *
74 * A client cursor above the high water mark is stale or invalid. Event count
75 * limits reducer churn while encoded bytes limit a small number of large
76 * updates. Either excess is cheaper to replace with one current snapshot.
77 */
78export function decideThreadResume(input: {
79 readonly afterSequence: number;
80 readonly highWater: number;
81 readonly replayEventCount: number;
82 readonly replayEncodedBytes: number;
83}): ThreadResumePlan {
84 if (
85 input.afterSequence > input.highWater ||
86 input.replayEventCount > THREAD_RESUME_MAX_REPLAY_EVENTS ||
87 input.replayEncodedBytes > THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES
88 ) {
89 return { mode: "snapshot" };
90 }
91 return {
92 mode: "replay",
93 afterSequence: input.afterSequence,
94 throughSequence: input.highWater,
95 };