The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { makePostgresState, type PostgresStateOptions } from "@alchemy.run/sql/PostgresState"; |
| 2 | import { describe, expect, it } from "@alchemy.run/test"; |
| 3 | import * as PgClient from "@effect/sql-pg/PgClient"; |
| 4 | import { StateStoreError, type StateService } from "alchemy/State/State"; |
| 5 | import * as Config from "effect/Config"; |
| 6 | import * as Deferred from "effect/Deferred"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Fiber from "effect/Fiber"; |
| 9 | import * as Reactivity from "effect/reactivity/Reactivity"; |
| 10 | import * as Redacted from "effect/Redacted"; |
| 11 | import * as SqlClient from "effect/sql/SqlClient"; |
| 12 | import type * as SqlConnection from "effect/sql/SqlConnection"; |
| 13 | import * as SqlError from "effect/sql/SqlError"; |
| 14 | import * as Stream from "effect/Stream"; |
| 15 | |
| 16 | interface FakeQuery { |
| 17 | text: string; |
| 18 | values: ReadonlyArray<unknown>; |
| 19 | } |
| 20 | |
| 21 | interface FakeConnection extends SqlConnection.Connection { |
| 22 | queries: FakeQuery[]; |
| 23 | released: boolean; |
| 24 | } |
| 25 | |
| 26 | const unsupported = (operation: string) => |
| 27 | Effect.die(new Error(`fake postgres does not support ${operation}`)); |
| 28 | |
| 29 | const sqlFailure = (message: string) => |
| 30 | new SqlError.SqlError({ |
| 31 | reason: new SqlError.ConnectionError({ |
| 32 | cause: new Error(message), |
| 33 | message, |
| 34 | operation: "execute", |
| 35 | }), |
| 36 | }); |
| 37 | |
| 38 | /** |
| 39 | * Hermetic fake of the `@effect/sql` driver surface the store uses: a real |
| 40 | * `SqlClient` built on the real `@effect/sql-pg` statement compiler, whose |
| 41 | * connections are in-memory. It recognizes the store's fixed SQL statements |
| 42 | * and keeps rows in in-memory maps, so tests exercise the real store logic |
| 43 | * (lock acquisition, lease guard, encoding) without a database. |
| 44 | * |
| 45 | * Every acquired connection records its own queries and answers |
| 46 | * `pg_backend_pid()` with its own id, so tests can prove which connection |
| 47 | * ran what and can tell a pool apart from a single shared connection. |
| 48 | * |
| 49 | * What this fake cannot do is model a real pool: `singleConnection: true` |
| 50 | * reproduces `PgClient.makeClient`/`fromClient`, where reserving and |
| 51 | * running a plain statement both land on the same connection, but nothing |
| 52 | * here reproduces pool exhaustion, queueing, or a killed backend. That is |
| 53 | * why the store asks Postgres itself which backend answered the liveness |
| 54 | * check instead of trusting the client to hand out a second connection. |
| 55 | */ |
| 56 | const makeFakePostgres = (options: { singleConnection?: boolean } = {}) => { |
| 57 | const resources = new Map<string, unknown>(); |
| 58 | const outputs = new Map<string, unknown>(); |
| 59 | const connections: FakeConnection[] = []; |
| 60 | const control = { |
| 61 | lockAcquired: true, |
| 62 | lockLive: true, |
| 63 | lockQueries: 0, |
| 64 | failLockQuery: false, |
| 65 | // Holds the lock query in flight: `started` fires when the store issues |
| 66 | // it, and it only answers once `release` completes. |
| 67 | lockGate: undefined as |
| 68 | | { started: Deferred.Deferred<void>; release: Deferred.Deferred<void> } |
| 69 | | undefined, |
| 70 | }; |
| 71 | |
| 72 | const resourceKey = (stack: unknown, stage: unknown, fqn: unknown) => `${stack} ${stage} ${fqn}`; |
| 73 | const outputKey = (stack: unknown, stage: unknown) => `${stack} ${stage}`; |
| 74 | |
| 75 | const rows = ( |
| 76 | values: ReadonlyArray<SqlConnection.Row>, |
| 77 | ): Effect.Effect<ReadonlyArray<SqlConnection.Row>, SqlError.SqlError> => Effect.succeed(values); |
| 78 | |
| 79 | const handle = ( |
| 80 | text: string, |
| 81 | values: ReadonlyArray<unknown>, |
| 82 | backendPid: number, |
| 83 | ): Effect.Effect<ReadonlyArray<SqlConnection.Row>, SqlError.SqlError> => { |
| 84 | const sql = text.replaceAll(/\s+/g, " ").trim().toLowerCase(); |
| 85 | if (sql === "begin" || sql === "commit" || sql === "rollback") { |
| 86 | return rows([]); |
| 87 | } |
| 88 | if (sql.includes("pg_try_advisory_lock")) { |
| 89 | control.lockQueries += 1; |
| 90 | if (control.failLockQuery) { |
| 91 | return Effect.fail(sqlFailure("connection terminated unexpectedly")); |
| 92 | } |
| 93 | const acquired = rows([{ acquired: control.lockAcquired, pid: backendPid }]); |
| 94 | const gate = control.lockGate; |
| 95 | return gate === undefined |
| 96 | ? acquired |
| 97 | : Effect.sync(() => { |
| 98 | Deferred.doneUnsafe(gate.started, Effect.void); |
| 99 | }).pipe(Effect.andThen(Deferred.await(gate.release)), Effect.andThen(acquired)); |
| 100 | } |
| 101 | if (sql.includes("pg_advisory_xact_lock")) { |
| 102 | return rows([{}]); |
| 103 | } |
| 104 | if (sql.includes("pg_advisory_unlock")) { |
| 105 | return rows([{}]); |
| 106 | } |
| 107 | if (sql.includes("from pg_locks")) { |
| 108 | return rows([{ live: control.lockLive, checker_pid: backendPid }]); |
| 109 | } |
| 110 | if (sql.startsWith("create table")) { |
| 111 | return rows([]); |
| 112 | } |
| 113 | if (sql.startsWith("insert into alchemy_resource_state")) { |
| 114 | const [stack, stage, fqn, json] = values; |
| 115 | resources.set(resourceKey(stack, stage, fqn), JSON.parse(String(json))); |
| 116 | return rows([]); |
| 117 | } |
| 118 | if (sql.startsWith("insert into alchemy_stack_output")) { |
| 119 | const [stack, stage, json] = values; |
| 120 | outputs.set(outputKey(stack, stage), JSON.parse(String(json))); |
| 121 | return rows([]); |
| 122 | } |
| 123 | if (sql.includes("value ->> 'status'")) { |
| 124 | const [stack, stage] = values; |
| 125 | return rows( |
| 126 | Array.from(resources.entries()) |
| 127 | .filter(([key]) => key.startsWith(`${stack} ${stage} `)) |
| 128 | .map(([, value]) => ({ value })) |
| 129 | .filter((row) => (row.value as { status?: string } | undefined)?.status === "replaced"), |
| 130 | ); |
| 131 | } |
| 132 | if (sql.startsWith("select value from alchemy_resource_state")) { |
| 133 | const [stack, stage, fqn] = values; |
| 134 | const value = resources.get(resourceKey(stack, stage, fqn)); |
| 135 | return rows(value === undefined ? [] : [{ value }]); |
| 136 | } |
| 137 | if (sql.startsWith("select value from alchemy_stack_output")) { |
| 138 | const [stack, stage] = values; |
| 139 | const value = outputs.get(outputKey(stack, stage)); |
| 140 | return rows(value === undefined ? [] : [{ value }]); |
| 141 | } |
| 142 | if (sql.startsWith("select fqn from alchemy_resource_state")) { |
| 143 | const [stack, stage] = values; |
| 144 | return rows( |
| 145 | Array.from(resources.keys()) |
| 146 | .filter((key) => key.startsWith(`${stack} ${stage} `)) |
| 147 | .map((key) => ({ fqn: key.split(" ")[2] })) |
| 148 | .sort((a, b) => String(a.fqn).localeCompare(String(b.fqn))), |
| 149 | ); |
| 150 | } |
| 151 | if (sql.startsWith("select stack from alchemy_resource_state")) { |
| 152 | const stacks = new Set<string>(); |
| 153 | for (const key of resources.keys()) stacks.add(key.split(" ")[0]!); |
| 154 | for (const key of outputs.keys()) stacks.add(key.split(" ")[0]!); |
| 155 | return rows( |
| 156 | Array.from(stacks) |
| 157 | .sort() |
| 158 | .map((stack) => ({ stack })), |
| 159 | ); |
| 160 | } |
| 161 | if (sql.startsWith("select stage from alchemy_resource_state")) { |
| 162 | const [stack] = values; |
| 163 | const stages = new Set<string>(); |
| 164 | for (const key of resources.keys()) { |
| 165 | const [s, stage] = key.split(" "); |
| 166 | if (s === stack) stages.add(stage!); |
| 167 | } |
| 168 | for (const key of outputs.keys()) { |
| 169 | const [s, stage] = key.split(" "); |
| 170 | if (s === stack) stages.add(stage!); |
| 171 | } |
| 172 | return rows( |
| 173 | Array.from(stages) |
| 174 | .sort() |
| 175 | .map((stage) => ({ stage })), |
| 176 | ); |
| 177 | } |
| 178 | if (sql.startsWith("delete from alchemy_resource_state")) { |
| 179 | const [stack, stage, fqn] = values; |
| 180 | if (fqn !== undefined) { |
| 181 | resources.delete(resourceKey(stack, stage, fqn)); |
| 182 | } else if (stage !== undefined) { |
| 183 | for (const key of Array.from(resources.keys())) { |
| 184 | if (key.startsWith(`${stack} ${stage} `)) { |
| 185 | resources.delete(key); |
| 186 | } |
| 187 | } |
| 188 | } else { |
| 189 | for (const key of Array.from(resources.keys())) { |
| 190 | if (key.startsWith(`${stack} `)) resources.delete(key); |
| 191 | } |
| 192 | } |
| 193 | return rows([]); |
| 194 | } |
| 195 | if (sql.startsWith("delete from alchemy_stack_output")) { |
| 196 | const [stack, stage] = values; |
| 197 | for (const key of Array.from(outputs.keys())) { |
| 198 | const [s, keyStage] = key.split(" "); |
| 199 | if (s === stack && (stage === undefined || keyStage === stage)) { |
| 200 | outputs.delete(key); |
| 201 | } |
| 202 | } |
| 203 | return rows([]); |
| 204 | } |
| 205 | return Effect.die(new Error(`fake postgres does not recognize: ${sql}`)); |
| 206 | }; |
| 207 | |
| 208 | let nextBackendPid = 100; |
| 209 | |
| 210 | const makeConnection = (): FakeConnection => { |
| 211 | const queries: FakeQuery[] = []; |
| 212 | const backendPid = nextBackendPid++; |
| 213 | const execute = (text: string, values: ReadonlyArray<unknown>) => |
| 214 | Effect.suspend(() => { |
| 215 | queries.push({ text, values }); |
| 216 | return handle(text, values, backendPid); |
| 217 | }); |
| 218 | const connection: FakeConnection = { |
| 219 | queries, |
| 220 | released: false, |
| 221 | execute, |
| 222 | executeUnprepared: execute, |
| 223 | executeRaw: execute, |
| 224 | executeValues: () => unsupported("executeValues"), |
| 225 | executeValuesUnprepared: () => unsupported("executeValuesUnprepared"), |
| 226 | executeStream: () => Stream.fromEffect(unsupported("executeStream")), |
| 227 | }; |
| 228 | connections.push(connection); |
| 229 | return connection; |
| 230 | }; |
| 231 | |
| 232 | // A scoped acquirer, exactly like a pool's: every acquisition hands out a |
| 233 | // fresh connection and marks it released when its scope closes. With |
| 234 | // `singleConnection`, every acquisition returns the same connection — |
| 235 | // what `PgClient.makeClient` does, where `reserve` and plain statements |
| 236 | // share one backend. |
| 237 | const shared = options.singleConnection ? makeConnection() : undefined; |
| 238 | const acquirer: SqlConnection.Acquirer = |
| 239 | shared === undefined |
| 240 | ? Effect.acquireRelease(Effect.sync(makeConnection), (connection) => |
| 241 | Effect.sync(() => { |
| 242 | connection.released = true; |
| 243 | }), |
| 244 | ) |
| 245 | : Effect.succeed(shared); |
| 246 | |
| 247 | const client = SqlClient.make({ |
| 248 | acquirer, |
| 249 | compiler: PgClient.makeCompiler(), |
| 250 | driver: "pg", |
| 251 | spanAttributes: [], |
| 252 | }).pipe(Effect.provide(Reactivity.layer)); |
| 253 | |
| 254 | return { client, connections, resources, outputs, control }; |
| 255 | }; |
| 256 | |
| 257 | const connectionRunning = ( |
| 258 | connections: FakeConnection[], |
| 259 | fragment: string, |
| 260 | ): FakeConnection | undefined => |
| 261 | connections.find((connection) => |
| 262 | connection.queries.some((query) => query.text.includes(fragment)), |
| 263 | ); |
| 264 | |
| 265 | type FakePostgres = ReturnType<typeof makeFakePostgres>; |
| 266 | |
| 267 | const withStore = <A, E>( |
| 268 | fake: FakePostgres, |
| 269 | options: Omit<PostgresStateOptions, "client">, |
| 270 | use: (store: StateService) => Effect.Effect<A, E>, |
| 271 | ): Effect.Effect<A, E | StateStoreError> => |
| 272 | Effect.gen(function* () { |
| 273 | const scope = yield* Effect.scope; |
| 274 | const store = yield* makePostgresState({ ...options, client: yield* fake.client }, scope); |
| 275 | return yield* use(store); |
| 276 | }).pipe(Effect.scoped); |
| 277 | |
| 278 | /** Builds the store without a client, to exercise option validation. */ |
| 279 | const withoutClient = <A, E, E2>( |
| 280 | options: PostgresStateOptions<E2>, |
| 281 | use: (store: StateService) => Effect.Effect<A, E>, |
| 282 | ): Effect.Effect<A, E | StateStoreError> => |
| 283 | Effect.gen(function* () { |
| 284 | const scope = yield* Effect.scope; |
| 285 | const store = yield* makePostgresState(options, scope); |
| 286 | return yield* use(store); |
| 287 | }).pipe(Effect.scoped); |
| 288 | |
| 289 | const request = { stack: "app", stage: "prod", fqn: "app/prod/db" }; |
| 290 | |
| 291 | const sampleState = { |
| 292 | kind: "resource", |
| 293 | status: "created", |
| 294 | logicalId: "db", |
| 295 | output: { password: Redacted.make("s3cret") }, |
| 296 | } as never; |
| 297 | |
| 298 | describe("Postgres state store", { tags: ["unit", "local"] }, () => { |
| 299 | it.effect("requires exactly one of client or url", () => { |
| 300 | const fake = makeFakePostgres(); |
| 301 | return Effect.gen(function* () { |
| 302 | const neither = yield* withoutClient({}, (store) => store.get(request)).pipe(Effect.flip); |
| 303 | expect(neither).toBeInstanceOf(StateStoreError); |
| 304 | expect(neither.message).toContain("exactly one of `client` or `url`"); |
| 305 | |
| 306 | const both = yield* withStore( |
| 307 | fake, |
| 308 | { url: Redacted.make("postgres://localhost/state") }, |
| 309 | (store) => store.get(request), |
| 310 | ).pipe(Effect.flip); |
| 311 | expect(both).toBeInstanceOf(StateStoreError); |
| 312 | expect((both as StateStoreError).message).toContain("exactly one of `client` or `url`"); |
| 313 | }); |
| 314 | }); |
| 315 | |
| 316 | it.effect("reports an unresolvable url config as a state store error", () => { |
| 317 | // `url` accepts any Effect of a Redacted string, so |
| 318 | // `Config.Redacted(...)` can be passed straight through; a missing |
| 319 | // variable surfaces as a StateStoreError like any other failure. |
| 320 | return withoutClient( |
| 321 | { url: Config.Redacted("ALCHEMY_TEST_MISSING_STATE_DATABASE_URL") }, |
| 322 | (store) => store.get(request), |
| 323 | ).pipe( |
| 324 | Effect.flip, |
| 325 | Effect.map((error) => { |
| 326 | expect(error).toBeInstanceOf(StateStoreError); |
| 327 | expect(error.message).toContain("ALCHEMY_TEST_MISSING_STATE_DATABASE_URL"); |
| 328 | }), |
| 329 | ); |
| 330 | }); |
| 331 | |
| 332 | it.effect("round-trips resource state including Redacted values", () => { |
| 333 | const fake = makeFakePostgres(); |
| 334 | return withStore(fake, {}, (store) => |
| 335 | Effect.gen(function* () { |
| 336 | expect(yield* store.get(request)).toBeUndefined(); |
| 337 | |
| 338 | yield* store.set({ ...request, value: sampleState }); |
| 339 | const revived = (yield* store.get(request)) as { |
| 340 | status: string; |
| 341 | output: { password: Redacted.Redacted<string> }; |
| 342 | }; |
| 343 | |
| 344 | expect(revived.status).toBe("created"); |
| 345 | expect(Redacted.isRedacted(revived.output.password)).toBe(true); |
| 346 | expect(Redacted.value(revived.output.password)).toBe("s3cret"); |
| 347 | |
| 348 | // The jsonb column stores the encoded (redaction-marked) form, so |
| 349 | // the raw secret round-trips through encodeState, not plain JSON. |
| 350 | const stored = fake.resources.get("app prod app/prod/db"); |
| 351 | expect(JSON.stringify(stored)).toContain("__redacted__"); |
| 352 | }), |
| 353 | ); |
| 354 | }); |
| 355 | |
| 356 | it.effect("serializes the schema migration under an advisory lock", () => { |
| 357 | const fake = makeFakePostgres(); |
| 358 | return withStore(fake, {}, (store) => |
| 359 | Effect.gen(function* () { |
| 360 | yield* store.get(request); |
| 361 | |
| 362 | const migration = connectionRunning(fake.connections, "create table"); |
| 363 | expect(migration).toBeDefined(); |
| 364 | const statements = migration!.queries.map((query) => |
| 365 | query.text.replaceAll(/\s+/g, " ").trim().toLowerCase(), |
| 366 | ); |
| 367 | expect(statements[0]).toBe("begin"); |
| 368 | expect(statements[1]).toContain("pg_advisory_xact_lock"); |
| 369 | expect(migration!.queries[1]?.values).toEqual(["alchemy:schema"]); |
| 370 | expect(statements[2]).toContain("create table if not exists alchemy_resource_state"); |
| 371 | expect(statements[3]).toContain("create table if not exists alchemy_stack_output"); |
| 372 | expect(statements[4]).toBe("commit"); |
| 373 | expect(migration!.released).toBe(true); |
| 374 | }), |
| 375 | ); |
| 376 | }); |
| 377 | |
| 378 | it.effect("acquires the advisory lock once per stack/stage", () => { |
| 379 | const fake = makeFakePostgres(); |
| 380 | return withStore(fake, {}, (store) => |
| 381 | Effect.gen(function* () { |
| 382 | yield* store.set({ ...request, value: sampleState }); |
| 383 | yield* store.get(request); |
| 384 | yield* store.list(request); |
| 385 | yield* store.setOutput({ ...request, value: { url: "https://x" } }); |
| 386 | expect(yield* store.getOutput(request)).toEqual({ url: "https://x" }); |
| 387 | |
| 388 | expect(fake.control.lockQueries).toBe(1); |
| 389 | const lock = connectionRunning(fake.connections, "pg_try_advisory_lock"); |
| 390 | expect(lock?.queries[0]?.values).toEqual(["alchemy:app/prod"]); |
| 391 | }), |
| 392 | ); |
| 393 | }); |
| 394 | |
| 395 | it.effect("never runs the lease check on the reserved lock connection", () => { |
| 396 | const fake = makeFakePostgres(); |
| 397 | return withStore(fake, { leaseCheckTtlMs: 0 }, (store) => |
| 398 | Effect.gen(function* () { |
| 399 | yield* store.set({ ...request, value: sampleState }); |
| 400 | yield* store.get(request); |
| 401 | |
| 402 | const lock = connectionRunning(fake.connections, "pg_try_advisory_lock"); |
| 403 | expect(lock).toBeDefined(); |
| 404 | // The reserved connection only ever takes the lock; the liveness |
| 405 | // check must ask a different backend, because the reserved |
| 406 | // connection cannot reliably report on itself once its backend |
| 407 | // has been killed server-side. |
| 408 | expect(lock!.queries.some((query) => query.text.includes("pg_locks"))).toBe(false); |
| 409 | expect( |
| 410 | fake.connections |
| 411 | .filter((connection) => connection !== lock) |
| 412 | .some((connection) => |
| 413 | connection.queries.some((query) => query.text.includes("pg_locks")), |
| 414 | ), |
| 415 | ).toBe(true); |
| 416 | }), |
| 417 | ); |
| 418 | }); |
| 419 | |
| 420 | it.effect("refuses a client that cannot verify the lock independently", () => { |
| 421 | // A single-connection client routes the liveness check straight back to |
| 422 | // the backend holding the lock, which cannot vouch for itself. The |
| 423 | // store notices because the check reports its own backend pid. |
| 424 | const fake = makeFakePostgres({ singleConnection: true }); |
| 425 | return withStore(fake, { leaseCheckTtlMs: 0 }, (store) => |
| 426 | Effect.gen(function* () { |
| 427 | const error = yield* store.get(request).pipe(Effect.flip); |
| 428 | expect(error).toBeInstanceOf(StateStoreError); |
| 429 | expect(error.message).toContain("cannot be verified"); |
| 430 | expect(error.message).toContain("not pool-backed"); |
| 431 | }), |
| 432 | ); |
| 433 | }); |
| 434 | |
| 435 | it.effect("prefixes the lock key with lockKeyPrefix", () => { |
| 436 | const fake = makeFakePostgres(); |
| 437 | return withStore(fake, { lockKeyPrefix: "my-app" }, (store) => |
| 438 | Effect.gen(function* () { |
| 439 | yield* store.get(request); |
| 440 | const lock = connectionRunning(fake.connections, "pg_try_advisory_lock"); |
| 441 | expect(lock?.queries[0]?.values).toEqual(["my-app:app/prod"]); |
| 442 | }), |
| 443 | ); |
| 444 | }); |
| 445 | |
| 446 | it.effect("fails immediately when another deploy holds the lock", () => { |
| 447 | const fake = makeFakePostgres(); |
| 448 | fake.control.lockAcquired = false; |
| 449 | return withStore(fake, {}, (store) => |
| 450 | Effect.gen(function* () { |
| 451 | const result = yield* store.get(request).pipe(Effect.flip); |
| 452 | expect(result).toBeInstanceOf(StateStoreError); |
| 453 | expect(result.message).toContain("another deploy holds the Postgres state lock"); |
| 454 | // The reserved connection is released on contention. |
| 455 | const lock = connectionRunning(fake.connections, "pg_try_advisory_lock"); |
| 456 | expect(lock?.released).toBe(true); |
| 457 | }), |
| 458 | ); |
| 459 | }); |
| 460 | |
| 461 | it.effect("releases the reserved connection when the lock query fails", () => { |
| 462 | const fake = makeFakePostgres(); |
| 463 | // The lock attempt fails at the driver, so the reserved connection must |
| 464 | // go back to the pool rather than leak. |
| 465 | fake.control.failLockQuery = true; |
| 466 | return withStore(fake, {}, (store) => |
| 467 | Effect.gen(function* () { |
| 468 | const error = yield* store.get(request).pipe(Effect.flip); |
| 469 | expect(error).toBeInstanceOf(StateStoreError); |
| 470 | expect(error.message).toContain("connection terminated unexpectedly"); |
| 471 | |
| 472 | const lock = connectionRunning(fake.connections, "pg_try_advisory_lock"); |
| 473 | expect(lock?.released).toBe(true); |
| 474 | }), |
| 475 | ); |
| 476 | }); |
| 477 | |
| 478 | it.effect("registers the unlock finalizer even when interrupted mid-acquisition", () => { |
| 479 | const fake = makeFakePostgres(); |
| 480 | return Effect.gen(function* () { |
| 481 | const started = yield* Deferred.make<void>(); |
| 482 | const release = yield* Deferred.make<void>(); |
| 483 | fake.control.lockGate = { started, release }; |
| 484 | |
| 485 | const fiber = yield* withStore(fake, {}, (store) => store.get(request)).pipe( |
| 486 | Effect.forkChild({ startImmediately: true }), |
| 487 | ); |
| 488 | |
| 489 | // Interrupt while the lock query is still in flight. Taking the |
| 490 | // lock and registering its unlock finalizer is uninterruptible, so |
| 491 | // the store must finish both before the interruption is honored — |
| 492 | // otherwise the session lock would stay held on a connection handed |
| 493 | // back to the pool, and every later deploy of this stack/stage |
| 494 | // would fail on it. |
| 495 | yield* Deferred.await(started); |
| 496 | const interrupting = yield* Fiber.interrupt(fiber).pipe( |
| 497 | Effect.forkChild({ startImmediately: true }), |
| 498 | ); |
| 499 | yield* Deferred.succeed(release, undefined); |
| 500 | yield* Fiber.join(interrupting); |
| 501 | |
| 502 | const lock = connectionRunning(fake.connections, "pg_try_advisory_lock"); |
| 503 | expect(lock).toBeDefined(); |
| 504 | expect(lock!.queries.some((query) => query.text.includes("pg_advisory_unlock"))).toBe(true); |
| 505 | expect(lock!.released).toBe(true); |
| 506 | }); |
| 507 | }); |
| 508 | |
| 509 | it.effect("unlocks and releases the lock connection on scope close", () => { |
| 510 | const fake = makeFakePostgres(); |
| 511 | return withStore(fake, {}, (store) => store.set({ ...request, value: sampleState })).pipe( |
| 512 | Effect.andThen( |
| 513 | Effect.sync(() => { |
| 514 | const lock = connectionRunning(fake.connections, "pg_try_advisory_lock"); |
| 515 | expect(lock).toBeDefined(); |
| 516 | expect(lock!.queries.some((query) => query.text.includes("pg_advisory_unlock"))).toBe( |
| 517 | true, |
| 518 | ); |
| 519 | expect(lock!.released).toBe(true); |
| 520 | }), |
| 521 | ), |
| 522 | ); |
| 523 | }); |
| 524 | |
| 525 | it.effect("fails loudly when the lock lease is lost mid-run", () => { |
| 526 | const fake = makeFakePostgres(); |
| 527 | return withStore(fake, { leaseCheckTtlMs: 0 }, (store) => |
| 528 | Effect.gen(function* () { |
| 529 | yield* store.set({ ...request, value: sampleState }); |
| 530 | |
| 531 | fake.control.lockLive = false; |
| 532 | const result = yield* store.get(request).pipe(Effect.flip); |
| 533 | expect(result).toBeInstanceOf(StateStoreError); |
| 534 | expect(result.message).toContain("was lost mid-run"); |
| 535 | |
| 536 | // Stage-less operations re-verify held leases too. |
| 537 | const listResult = yield* store.listStacks().pipe(Effect.flip); |
| 538 | expect(listResult.message).toContain("was lost mid-run"); |
| 539 | }), |
| 540 | ); |
| 541 | }); |
| 542 | |
| 543 | it.effect("filters replaced resources in SQL", () => { |
| 544 | const fake = makeFakePostgres(); |
| 545 | return withStore(fake, {}, (store) => |
| 546 | Effect.gen(function* () { |
| 547 | yield* store.set({ ...request, value: sampleState }); |
| 548 | yield* store.set({ |
| 549 | ...request, |
| 550 | fqn: "app/prod/old", |
| 551 | value: { ...(sampleState as object), status: "replaced" } as never, |
| 552 | }); |
| 553 | |
| 554 | const replaced = yield* store.getReplacedResources(request); |
| 555 | expect(replaced).toHaveLength(1); |
| 556 | expect(replaced[0]?.status).toBe("replaced"); |
| 557 | }), |
| 558 | ); |
| 559 | }); |
| 560 | |
| 561 | it.effect("lists stacks, stages, and fqns", () => { |
| 562 | const fake = makeFakePostgres(); |
| 563 | return withStore(fake, {}, (store) => |
| 564 | Effect.gen(function* () { |
| 565 | yield* store.set({ ...request, value: sampleState }); |
| 566 | yield* store.set({ ...request, fqn: "app/prod/api", value: sampleState }); |
| 567 | yield* store.setOutput({ stack: "other", stage: "dev", value: { ok: true } }); |
| 568 | |
| 569 | expect(yield* store.listStacks()).toEqual(["app", "other"]); |
| 570 | expect(yield* store.listStages("app")).toEqual(["prod"]); |
| 571 | expect(yield* store.list(request)).toEqual(["app/prod/api", "app/prod/db"]); |
| 572 | }), |
| 573 | ); |
| 574 | }); |
| 575 | |
| 576 | it.effect("deleteStack removes resource rows and stack outputs", () => { |
| 577 | const fake = makeFakePostgres(); |
| 578 | return withStore(fake, {}, (store) => |
| 579 | Effect.gen(function* () { |
| 580 | yield* store.set({ ...request, value: sampleState }); |
| 581 | yield* store.setOutput({ ...request, value: { ok: true } }); |
| 582 | |
| 583 | yield* store.deleteStack({ stack: "app", stage: "prod" }); |
| 584 | expect(yield* store.get(request)).toBeUndefined(); |
| 585 | expect(yield* store.getOutput(request)).toBeUndefined(); |
| 586 | |
| 587 | yield* store.set({ ...request, value: sampleState }); |
| 588 | yield* store.deleteStack({ stack: "app" }); |
| 589 | expect(fake.resources.size).toBe(0); |
| 590 | expect(fake.outputs.size).toBe(0); |
| 591 | }), |
| 592 | ); |
| 593 | }); |
| 594 | |
| 595 | it.effect("stage-less deleteStack locks every stage before deleting", () => { |
| 596 | const fake = makeFakePostgres(); |
| 597 | // Rows written by an earlier run: this store has not touched the stack |
| 598 | // yet, so it holds no leases when deleteStack starts. |
| 599 | fake.resources.set("app prod app/prod/db", { status: "created" }); |
| 600 | fake.outputs.set("app prod", { ok: true }); |
| 601 | |
| 602 | return withStore(fake, {}, (store) => |
| 603 | Effect.gen(function* () { |
| 604 | yield* store.deleteStack({ stack: "app" }); |
| 605 | |
| 606 | const lock = connectionRunning(fake.connections, "pg_try_advisory_lock"); |
| 607 | expect(lock?.queries[0]?.values).toEqual(["alchemy:app/prod"]); |
| 608 | expect(fake.resources.size).toBe(0); |
| 609 | expect(fake.outputs.size).toBe(0); |
| 610 | }), |
| 611 | ); |
| 612 | }); |
| 613 | |
| 614 | it.effect("delete removes a single resource", () => { |
| 615 | const fake = makeFakePostgres(); |
| 616 | return withStore(fake, {}, (store) => |
| 617 | Effect.gen(function* () { |
| 618 | yield* store.set({ ...request, value: sampleState }); |
| 619 | yield* store.delete(request); |
| 620 | expect(yield* store.get(request)).toBeUndefined(); |
| 621 | }), |
| 622 | ); |
| 623 | }); |
| 624 | }); |