Load thread snapshots over HTTP before live sync #3719
Mergedjuliusmarmingemerged 6 commits into
main fromrefs/pull/3719/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- packages/client-runtime/src/state/threadSnapshotHttp.ts line 109Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +106,21 @@106+ threadId: ThreadId,107+ ) => Effect.Effect<Option.Option<OrchestrationThreadDetailSnapshot>>;108+ }109+>()("@t3tools/client-runtime/state/threadSnapshotHttp/ThreadSnapshotLoader") {}110+111+export const threadSnapshotLoaderLayer: Layer.Layer<112+ ThreadSnapshotLoader,113+ never,114+ HttpClient.HttpClient | ManagedRelayDpopSigner115+> = Layer.effect(116+ ThreadSnapshotLoader,117+ Effect.gen(function* () {118+ const httpClient = yield* HttpClient.HttpClient;119+ const signer = yield* ManagedRelayDpopSigner;120+ return ThreadSnapshotLoader.of({121+ load: (prepared: PreparedConnection, threadId: ThreadId) =>122+ fetchEnvironmentThreadSnapshot({ prepared, threadId }).pipe(123+ Effect.map(Option.some<OrchestrationThreadDetailSnapshot>),124+ Effect.provideService(HttpClient.HttpClient, httpClient),125+ Effect.provideService(ManagedRelayDpopSigner, signer),126+ Effect.catchCause((cause) =>@@ -187,11 +190,4 @@187190 );188191189192 yield* setSynchronizing;190- yield* subscribe(191- ORCHESTRATION_WS_METHODS.subscribeThread,192- { threadId },193- {194- onExpectedFailure: setStreamError,195- retryExpectedFailureAfter: "250 millis",196- },197- ).pipe(Stream.runForEach(applyItem), Effect.forkScoped);193+ yield* Effect.forkScoped(
- @@ -1116,0 +1129,21 @@1129+1130+ // When the client already loaded the snapshot over HTTP it passes1131+ // that snapshot's sequence, and we resume the live subscription by1132+ // replaying persisted events after it instead of re-sending the1133+ // (potentially multi-KB) snapshot frame over the socket. The1134+ // catch-up replay + live stream carry the same ordering guarantees1135+ // as the snapshot-then-live path below; overlapping events are1136+ // deduped by sequence on the client.1137+ if (input.afterSequence !== undefined) {1138+ const catchUpStream = orchestrationEngine.readEvents(input.afterSequence).pipe(1139+ Stream.filter(isThisThreadDetailEvent),1140+ Stream.map((event) => ({ kind: "event" as const, event })),1141+ Stream.mapError(1142+ (cause) =>1143+ new OrchestrationGetSnapshotError({1144+ message: `Failed to replay thread ${input.threadId} events`,1145+ cause,1146+ }),1147+ ),1148+ );1149+ return Stream.concat(catchUpStream, liveStream);@@ -1116,0 +1118,21 @@1118+ event.aggregateKind === "thread" &&1119+ event.aggregateId === input.threadId &&1120+ isThreadDetailEvent(event);1121+1122+ const liveStream = orchestrationEngine.streamDomainEvents.pipe(1123+ Stream.filter(isThisThreadDetailEvent),1124+ Stream.map((event) => ({1125+ kind: "event" as const,1126+ event,1127+ })),1128+ );1129+1130+ // When the client already loaded the snapshot over HTTP it passes1131+ // that snapshot's sequence, and we resume the live subscription by1132+ // replaying persisted events after it instead of re-sending the1133+ // (potentially multi-KB) snapshot frame over the socket. The1134+ // catch-up replay + live stream carry the same ordering guarantees1135+ // as the snapshot-then-live path below; overlapping events are1136+ // deduped by sequence on the client.1137+ if (input.afterSequence !== undefined) {1138+ const catchUpStream = orchestrationEngine.readEvents(input.afterSequence).pipe(apps/server/src/orchestration/http.ts line 59OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -38,3 +40,20 @@3840 );3941 }),4042 )43+ .handle(44+ "threadSnapshot",45+ Effect.fn("environment.orchestration.threadSnapshot")(function* (args) {46+ yield* annotateEnvironmentRequest(args.endpoint.name);47+ yield* requireEnvironmentScope(AuthOrchestrationReadScope);48+ const [threadDetail, { snapshotSequence }] = yield* Effect.all([49+ projectionSnapshotQuery.getThreadDetailById(args.params.threadId),50+ projectionSnapshotQuery.getSnapshotSequence(),51+ ]).pipe(52+ Effect.catch((cause) =>53+ failEnvironmentInternal("orchestration_thread_snapshot_failed", cause),54+ ),55+ );56+ if (Option.isNone(threadDetail)) {57+ return yield* failEnvironmentNotFound("thread_not_found");58+ }59+ return { snapshotSequence, thread: threadDetail.value };
- packages/client-runtime/src/state/threadSnapshotHttp.ts line 79Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +94,21 @@94+});95+96+export type FetchEnvironmentThreadSnapshotError = RemoteEnvironmentRequestError;97+98+/**99+ * Loads a thread's detail snapshot over HTTP, returning `Option.none()` when it100+ * cannot be loaded (so the caller falls back to the socket-embedded snapshot).101+ * Decouples the thread state machine from the underlying HTTP + DPoP details and102+ * keeps them out of test contexts.103+ */104+export class ThreadSnapshotLoader extends Context.Service<105+ ThreadSnapshotLoader,106+ {107+ readonly load: (108+ prepared: PreparedConnection,109+ threadId: ThreadId,110+ ) => Effect.Effect<Option.Option<OrchestrationThreadDetailSnapshot>>;111+ }112+>()("@t3tools/client-runtime/state/threadSnapshotHttp/ThreadSnapshotLoader") {}113+114+export const threadSnapshotLoaderLayer: Layer.Layer<
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- @@ -1065,0 +1086,21 @@1086+ return Stream.unwrap(1087+ Effect.gen(function* () {1088+ const liveBuffer = yield* Queue.unbounded<OrchestrationShellStreamItem>();1089+ yield* Effect.forkScoped(1090+ liveStream.pipe(Stream.runForEach((item) => Queue.offer(liveBuffer, item))),1091+ );1092+ const catchUpStream = orchestrationEngine1093+ .readEvents(afterSequence, Number.MAX_SAFE_INTEGER)1094+ .pipe(1095+ Stream.mapEffect(toShellStreamEvent),1096+ Stream.flatMap((event) =>1097+ Option.isSome(event) ? Stream.succeed(event.value) : Stream.empty,1098+ ),1099+ Stream.mapError(1100+ (cause) =>1101+ new OrchestrationGetSnapshotError({1102+ message: "Failed to replay orchestration shell events",1103+ cause,1104+ }),1105+ ),1106+ );
juliusmarminge merged this482d562
juliusmarminge closed this
Sign in to join this conversation.



Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID:
500fc1b7-e1b1-4e76-8444-eeacea5bd39fYou can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands.