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

ProjectionMaintenance.ts

218 lines8.5 KB

1import { type OrchestrationV2StoredEvent, ThreadId } from "@t3tools/contracts";
2import * as Context from "effect/Context";
3import * as DateTime from "effect/DateTime";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Schema from "effect/Schema";
7import * as Stream from "effect/Stream";
8import * as SqlClient from "effect/unstable/sql/SqlClient";
9​
10import { EventStoreV2 } from "./EventStore.ts";
11import {
12 ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION,
13 ProjectionStoreV2,
14} from "./ProjectionStore.ts";
15​
16export interface ProjectionVerificationV2 {
17 readonly valid: boolean;
18 readonly schemaVersion: number;
19 readonly expectedSequence: number;
20 readonly projectionSequence: number;
21 readonly unreadableThreadIds: ReadonlyArray<ThreadId>;
22 readonly missingThreadIds: ReadonlyArray<ThreadId>;
23 readonly unexpectedThreadIds: ReadonlyArray<ThreadId>;
25​
26export class ProjectionMaintenanceError extends Schema.TaggedErrorClass<ProjectionMaintenanceError>()(
27 "ProjectionMaintenanceError",
28 {
29 operation: Schema.String,
30 cause: Schema.optional(Schema.Defect()),
31 },
32) {}
33​
34export interface ProjectionMaintenanceV2Shape {
35 readonly verify: Effect.Effect<ProjectionVerificationV2, ProjectionMaintenanceError>;
36 readonly rebuild: Effect.Effect<ProjectionVerificationV2, ProjectionMaintenanceError>;
38​
39export class ProjectionMaintenanceV2 extends Context.Service<
40 ProjectionMaintenanceV2,
41 ProjectionMaintenanceV2Shape
42>()("t3/orchestration-v2/ProjectionMaintenance/ProjectionMaintenanceV2") {}
43​
44type ProjectionMetadataRow = {
45 readonly schema_version: number;
46 readonly last_sequence: number;
47};
48​
49export const layer: Layer.Layer<
50 ProjectionMaintenanceV2,
51 never,
52 EventStoreV2 | ProjectionStoreV2 | SqlClient.SqlClient
53> = Layer.effect(
54 ProjectionMaintenanceV2,
55 Effect.gen(function* () {
56 const sql = yield* SqlClient.SqlClient;
57 const eventStore = yield* EventStoreV2;
58 const projectionStore = yield* ProjectionStoreV2;
59​
60 const readAllEvents = Effect.gen(function* () {
61 const events: Array<OrchestrationV2StoredEvent> = [];
62 const pageSize = 500;
63 let afterSequence = 0;
64 while (true) {
65 const page = yield* eventStore.read({ afterSequence, limit: pageSize }).pipe(
66 Stream.runCollect,
67 Effect.map((chunk) => Array.from(chunk)),
68 );
69 events.push(...page);
70 if (page.length < pageSize) {
71 break;
72 }
73 afterSequence = page.at(-1)?.sequence ?? afterSequence;
74 }
75 return events;
76 });
77​
78 /**
79 * EventSink commits the event, its projection updates, and projection metadata in one SQL
80 * transaction. Startup verification therefore checks that transaction boundary and that every
81 * stored projection can be decoded. It intentionally does not replay domain events through a
82 * second projector: doing so creates another implementation of projection semantics that must
83 * evolve in lockstep with ProjectionStore.
84 */
85 const verify = Effect.gen(function* () {
86 const expectedThreadRows = yield* sql<{ readonly thread_id: string }>`
87 SELECT DISTINCT stream_id AS thread_id
88 FROM orchestration_events
89 WHERE application_event_version = 2
90 AND aggregate_kind = 'thread'
91 AND event_type = 'thread.created'
92 ORDER BY stream_id ASC
93 `;
94 const projectionRows = yield* sql<{ readonly thread_id: string }>`
95 SELECT thread_id
96 FROM orchestration_v2_projection_threads
97 ORDER BY thread_id ASC
98 `;
99 const actualIds = projectionRows.map((row) => ThreadId.make(row.thread_id));
100 const expectedIds = expectedThreadRows.map((row) => ThreadId.make(row.thread_id));
101 const actualSet = new Set(actualIds);
102 const expectedSet = new Set(expectedIds);
103 const missingThreadIds = expectedIds.filter((threadId) => !actualSet.has(threadId));
104 const unexpectedThreadIds = actualIds.filter((threadId) => !expectedSet.has(threadId));
105 const unreadableThreadIds = (yield* Effect.forEach(
106 actualIds,
107 (threadId) =>
108 projectionStore.getThreadProjection(threadId).pipe(
109 Effect.as<ThreadId | null>(null),
110 Effect.orElseSucceed((): ThreadId | null => threadId),
111 ),
112 { concurrency: 8 },
113 )).filter((threadId): threadId is ThreadId => threadId !== null);
114 const metadata = yield* sql<ProjectionMetadataRow>`
115 SELECT schema_version, last_sequence
116 FROM orchestration_v2_projection_metadata
117 WHERE projection_name = 'thread-projections'
118 LIMIT 1
119 `;
120 const expectedSequence = yield* eventStore.latestSequence();
121 const schemaVersion = metadata[0]?.schema_version ?? 0;
122 const projectionSequence = metadata[0]?.last_sequence ?? 0;
123 return {
124 valid:
125 schemaVersion === ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION &&
126 projectionSequence === expectedSequence &&
127 missingThreadIds.length === 0 &&
128 unexpectedThreadIds.length === 0 &&
129 unreadableThreadIds.length === 0,
130 schemaVersion,
131 expectedSequence,
132 projectionSequence,
133 unreadableThreadIds,
134 missingThreadIds,
135 unexpectedThreadIds,
136 } satisfies ProjectionVerificationV2;
137 });
138​
139 const rebuild = Effect.gen(function* () {
140 const events = yield* readAllEvents;
141 yield* sql.withTransaction(
142 Effect.gen(function* () {
143 yield* sql`DELETE FROM orchestration_v2_projection_context_transfers`;
144 yield* sql`DELETE FROM orchestration_v2_projection_context_handoffs`;
145 yield* sql`DELETE FROM orchestration_v2_projection_checkpoints`;
146 yield* sql`DELETE FROM orchestration_v2_projection_checkpoint_scopes`;
147 yield* sql`DELETE FROM orchestration_v2_projection_turn_items`;
148 yield* sql`DELETE FROM orchestration_v2_projection_plans`;
149 yield* sql`DELETE FROM orchestration_v2_projection_messages`;
150 yield* sql`DELETE FROM orchestration_v2_projection_runtime_requests`;
151 yield* sql`DELETE FROM orchestration_v2_projection_provider_turns`;
152 yield* sql`DELETE FROM orchestration_v2_projection_provider_threads`;
153 yield* sql`DELETE FROM orchestration_v2_projection_provider_session_bindings`;
154 yield* sql`DELETE FROM orchestration_v2_projection_provider_sessions`;
155 yield* sql`DELETE FROM orchestration_v2_projection_subagents`;
156 yield* sql`DELETE FROM orchestration_v2_projection_nodes`;
157 yield* sql`DELETE FROM orchestration_v2_projection_run_attempts`;
158 yield* sql`DELETE FROM orchestration_v2_projection_runs`;
159 yield* sql`DELETE FROM orchestration_v2_projection_threads`;
160 yield* sql`DELETE FROM orchestration_v2_turn_item_positions`;
161​
162 for (const stored of events) {
163 yield* projectionStore.apply(stored.event);
164 if (stored.event.type === "turn-item.updated") {
165 yield* sql`
166 INSERT INTO orchestration_v2_turn_item_positions (
167 thread_id,
168 turn_item_id,
169 ordinal
170 )
171 VALUES (
172 ${stored.event.threadId},
173 ${stored.event.payload.id},
174 ${stored.event.payload.ordinal}
175 )
176 ON CONFLICT(thread_id, turn_item_id) DO UPDATE SET
177 ordinal = excluded.ordinal
178 `;
179 }
180 }
181 const now = DateTime.formatIso(yield* DateTime.now);
182 const lastSequence = events.at(-1)?.sequence ?? 0;
183 yield* sql`
184 INSERT INTO orchestration_v2_projection_metadata (
185 projection_name,
186 schema_version,
187 last_sequence,
188 updated_at
189 )
190 VALUES (
191 'thread-projections',
192 ${ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION},
193 ${lastSequence},
194 ${now}
195 )
196 ON CONFLICT(projection_name) DO UPDATE SET
197 schema_version = excluded.schema_version,
198 last_sequence = excluded.last_sequence,
199 updated_at = excluded.updated_at
200 `;
201 }),
202 );
203 return yield* verify;
204 });
205​
206 const mapError =
207 (operation: string) =>
208 <A, E, R>(effect: Effect.Effect<A, E, R>) =>
209 effect.pipe(
210 Effect.mapError((cause) => new ProjectionMaintenanceError({ operation, cause })),
211 );
212​
213 return ProjectionMaintenanceV2.of({
214 verify: mapError("verify")(verify),
215 rebuild: mapError("rebuild")(rebuild),
216 });
217 }),
218);