Skip to content

Commit 12c9c65

Browse files
effect-botpartmor
andauthored
Separate PersistedQueue SQL migrations from store startup (#11280)
Co-authored-by: Pedro Morales Maries <16372241+partmor@users.noreply.github.com>
1 parent 353f3a7 commit 12c9c65

3 files changed

Lines changed: 176 additions & 12 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"effect": patch
3+
---
4+
5+
Add `PersistedQueue.migrationsSql` and `layerMigrationsSql` to run SQL queue migrations during deployment, and `makeStorageSql` and `layerStorageSql` to start workers without migrating. Existing `makeStoreSql` and `layerStoreSql` callers still migrate on startup.

‎packages/effect/src/persistence/PersistedQueue.ts‎

Lines changed: 128 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,10 @@
1111
* Delivery is at-least-once: a crash between handler success and the
1212
* acknowledgement redelivers the element, so handlers must be idempotent.
1313
*
14+
* `layerStoreSql` and `makeStoreSql` run the queue migrations before building
15+
* the store. To migrate as the schema owner during deployment, use
16+
* `layerMigrationsSql`, then start workers with `layerStorageSql`.
17+
*
1418
* @stability unstable
1519
* @since 4.0.0
1620
*/
@@ -1575,6 +1579,9 @@ export const layerStoreRedis: (
15751579
Redis.Redis
15761580
> = flow(makeStoreRedis, Layer.effect(PersistedQueueStore))
15771581

1582+
const sqlTableName = (options: { readonly tableName?: string | undefined } | undefined) =>
1583+
options?.tableName ?? "effect_queue"
1584+
15781585
/**
15791586
* Creates a SQL-backed `PersistedQueueStore`.
15801587
*
@@ -1594,6 +1601,10 @@ export const layerStoreRedis: (
15941601
* An id re-offered with `deduplicate: "untilExecuted"` keeps only its latest
15951602
* failure.
15961603
*
1604+
* Runs migrations before building the store. The connection needs privileges
1605+
* to apply pending migrations. On PostgreSQL, the migrator takes an
1606+
* `ACCESS EXCLUSIVE` lock on `<tableName>_migrations`, even if none are pending.
1607+
*
15971608
* **Gotchas**
15981609
*
15991610
* An `"untilExecuted"` offer inside a transaction checks the id against that
@@ -1602,24 +1613,60 @@ export const layerStoreRedis: (
16021613
* completed or failed after the first read still looks in flight, so the offer
16031614
* is ignored.
16041615
*
1616+
* @see {@link makeStorageSql} for a store that does not run migrations
1617+
*
16051618
* @stability unstable
16061619
* @category constructors
16071620
* @since 4.0.0
16081621
*/
1609-
export const makeStoreSql: (
1622+
export const makeStoreSql = (
16101623
options?: {
16111624
readonly tableName?: string | undefined
16121625
readonly pollInterval?: Duration.Input | undefined
16131626
readonly lockRefreshInterval?: Duration.Input | undefined
16141627
readonly lockExpiration?: Duration.Input | undefined
16151628
} | undefined
1616-
) => Effect.Effect<
1629+
): Effect.Effect<
16171630
PersistedQueueStore["Service"],
16181631
SqlError,
16191632
SqlClient.SqlClient | Scope.Scope
1633+
> => {
1634+
const tableName = sqlTableName(options)
1635+
return Effect.andThen(runSqlMigrations(tableName), makeStorageSql({ ...options, tableName }))
1636+
}
1637+
1638+
/**
1639+
* Creates a SQL-backed `PersistedQueueStore` without running migrations or
1640+
* checking the schema.
1641+
*
1642+
* **Details**
1643+
*
1644+
* First apply migrations with `layerMigrationsSql` or pass `migrationsSql` to
1645+
* a SQL migrator.
1646+
*
1647+
* The connection needs `SELECT`, `INSERT`, `UPDATE`, and `DELETE` on the
1648+
* queue table, plus `USAGE` on its sequence on PostgreSQL.
1649+
*
1650+
* @see {@link layerStorageSql} for the layer form
1651+
*
1652+
* @stability unstable
1653+
* @category constructors
1654+
* @since 4.1.8
1655+
*/
1656+
export const makeStorageSql: (
1657+
options?: {
1658+
readonly tableName?: string | undefined
1659+
readonly pollInterval?: Duration.Input | undefined
1660+
readonly lockRefreshInterval?: Duration.Input | undefined
1661+
readonly lockExpiration?: Duration.Input | undefined
1662+
} | undefined
1663+
) => Effect.Effect<
1664+
PersistedQueueStore["Service"],
1665+
never,
1666+
SqlClient.SqlClient | Scope.Scope
16201667
> = Effect.fnUntraced(function*(options) {
16211668
const sql = (yield* SqlClient.SqlClient).withoutTransforms()
1622-
const tableName = options?.tableName ?? "effect_queue"
1669+
const tableName = sqlTableName(options)
16231670
const tableNameSql = sql(tableName)
16241671
const pollInterval = Duration.max(
16251672
options?.pollInterval ? Duration.fromInputUnsafe(options.pollInterval) : Duration.millis(1000),
@@ -1635,13 +1682,6 @@ export const makeStoreSql: (
16351682
)
16361683
const ackRetrySchedule = makeAckRetrySchedule(lockExpiration)
16371684

1638-
yield* Effect.orDie(
1639-
Migrator.make({})({
1640-
loader: sqlMigrations(tableName, sql),
1641-
table: `${tableName}_migrations`
1642-
})
1643-
)
1644-
16451685
const sqlNow = sql.onDialectOrElse({
16461686
// GETDATE() rounds to 1/300s and can land in the future, hiding freshly
16471687
// written visible_at values from the poll query
@@ -2193,6 +2233,33 @@ export const makeStoreSql: (
21932233
})
21942234
})
21952235

2236+
/**
2237+
* Returns a migration loader for the SQL queue table, defaulting to
2238+
* `effect_queue`.
2239+
*
2240+
* **Details**
2241+
*
2242+
* Pass the loader to a SQL migrator and set its history table to
2243+
* `<tableName>_migrations` to share history with `layerMigrationsSql` and
2244+
* `makeStoreSql`. The loader uses `SqlClient` to select migrations by dialect.
2245+
*
2246+
* @stability unstable
2247+
* @category migrations
2248+
* @since 4.1.8
2249+
*/
2250+
export const migrationsSql = (
2251+
options?: { readonly tableName?: string | undefined } | undefined
2252+
): Migrator.Loader<SqlClient.SqlClient> => {
2253+
const tableName = sqlTableName(options)
2254+
return Effect.flatMap(SqlClient.SqlClient, (client) => sqlMigrations(tableName, client.withoutTransforms()))
2255+
}
2256+
2257+
const runSqlMigrations = (tableName: string): Effect.Effect<void, never, SqlClient.SqlClient> =>
2258+
Migrator.make({})({
2259+
loader: migrationsSql({ tableName }),
2260+
table: `${tableName}_migrations`
2261+
}).pipe(Effect.asVoid, Effect.orDie)
2262+
21962263
const sqlMigrations = (tableName: string, client: SqlClient.SqlClient) =>
21972264
Migrator.fromRecord({
21982265
"0001_create_table": Effect.gen(function*() {
@@ -2419,6 +2486,8 @@ const sqlMigrations = (tableName: string, client: SqlClient.SqlClient) =>
24192486
WHERE state = 'pending'`
24202487
})
24212488
}),
2489+
// Keep 0003 PostgreSQL-only: recording it on other dialects would require
2490+
// history-table INSERT privileges for previously migrated queues to start.
24222491
...client.onDialectOrElse({
24232492
pg: () => ({
24242493
// Migration 0002 widened the column but not its SERIAL sequence.
@@ -2438,7 +2507,55 @@ const sqlMigrations = (tableName: string, client: SqlClient.SqlClient) =>
24382507
})
24392508

24402509
/**
2441-
* Provides a SQL-backed `PersistedQueueStore` using `makeStoreSql`.
2510+
* Runs the SQL queue migrations without providing a store.
2511+
*
2512+
* **Details**
2513+
*
2514+
* Use a schema-owner connection during deployment, then start workers with
2515+
* `layerStorageSql` and the privileges listed in `makeStorageSql`.
2516+
* Records history in `<tableName>_migrations`. Migration errors become defects.
2517+
*
2518+
* @stability unstable
2519+
* @category layers
2520+
* @since 4.1.8
2521+
*/
2522+
export const layerMigrationsSql = (
2523+
options?: { readonly tableName?: string | undefined } | undefined
2524+
): Layer.Layer<never, never, SqlClient.SqlClient> => Layer.effectDiscard(runSqlMigrations(sqlTableName(options)))
2525+
2526+
/**
2527+
* Provides a SQL-backed `PersistedQueueStore` without running migrations or
2528+
* checking the schema, using `makeStorageSql`.
2529+
*
2530+
* **Details**
2531+
*
2532+
* Apply migrations with `layerMigrationsSql` first. See `makeStorageSql` for
2533+
* the worker connection's required privileges.
2534+
*
2535+
* @stability unstable
2536+
* @category layers
2537+
* @since 4.1.8
2538+
*/
2539+
export const layerStorageSql: (
2540+
options?: {
2541+
readonly tableName?: string | undefined
2542+
readonly pollInterval?: Duration.Input | undefined
2543+
readonly lockRefreshInterval?: Duration.Input | undefined
2544+
readonly lockExpiration?: Duration.Input | undefined
2545+
} | undefined
2546+
) => Layer.Layer<PersistedQueueStore, never, SqlClient.SqlClient> = flow(
2547+
makeStorageSql,
2548+
Layer.effect(PersistedQueueStore)
2549+
)
2550+
2551+
/**
2552+
* Runs migrations and provides a SQL-backed `PersistedQueueStore` using
2553+
* `makeStoreSql`.
2554+
*
2555+
* **Details**
2556+
*
2557+
* See `makeStoreSql` for migration privileges and locking. Use
2558+
* `layerMigrationsSql` and `layerStorageSql` to migrate separately.
24422559
*
24432560
* @stability unstable
24442561
* @category layers

‎packages/sql/pg/test/Persistence.integration.test.ts‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1+
import { PgClient } from "@effect/sql-pg"
12
import { assert, it } from "@effect/vitest"
2-
import { Duration, Effect, Fiber, Latch, Layer, Schema } from "effect"
3+
import { Duration, Effect, Fiber, Latch, Layer, Redacted, Schema } from "effect"
34
import * as PersistedCacheTest from "effect-test/persistence/PersistedCacheTest"
45
import * as PersistedQueueSqlTest from "effect-test/persistence/PersistedQueueSqlTest"
56
import * as PersistedQueueTest from "effect-test/persistence/PersistedQueueTest"
@@ -198,6 +199,47 @@ it.layer(PgContainer.layerClient, { timeout: "30 seconds" })("PersistedQueue SQL
198199
}).pipe(TestClock.withLive), { timeout: 20000 })
199200
})
200201

202+
const appRole = "queue_app"
203+
204+
const AppClient = Layer.unwrap(Effect.gen(function*() {
205+
const container = yield* PgContainer
206+
return PgClient.layer({
207+
host: container.getHost(),
208+
port: container.getPort(),
209+
database: container.getDatabase(),
210+
username: appRole,
211+
password: Redacted.make(appRole)
212+
})
213+
}))
214+
215+
it.layer(PgContainer.layerClient.pipe(Layer.provideMerge(PgContainer.layer)), { timeout: "30 seconds" })(
216+
"PersistedQueue SQL with a DML-only role",
217+
(it) => {
218+
it.effect("starts from a table migrated by an owner connection", () =>
219+
Effect.gen(function*() {
220+
yield* Layer.build(PersistedQueue.layerMigrationsSql())
221+
const sql = yield* SqlClient.SqlClient
222+
// no access to the migration history table
223+
yield* sql.unsafe(`CREATE ROLE ${appRole} LOGIN PASSWORD '${appRole}'`)
224+
yield* sql.unsafe(`GRANT SELECT, INSERT, UPDATE, DELETE ON effect_queue TO ${appRole}`)
225+
yield* sql.unsafe(`GRANT USAGE ON SEQUENCE effect_queue_sequence_seq TO ${appRole}`)
226+
227+
const value = yield* Effect.gen(function*() {
228+
const factory = yield* PersistedQueue.PersistedQueueFactory
229+
const queue = yield* factory.make({ name: "jobs", schema: Schema.String })
230+
yield* queue.offer("job")
231+
return yield* queue.take(Effect.succeed)
232+
}).pipe(
233+
Effect.provide(PersistedQueue.layer.pipe(
234+
Layer.provide(PersistedQueue.layerStorageSql({ pollInterval: "10 millis" })),
235+
Layer.provide(AppClient)
236+
))
237+
)
238+
assert.strictEqual(value, "job")
239+
}).pipe(TestClock.withLive))
240+
}
241+
)
242+
201243
// polls a condition on the live clock until it holds or the rounds run out
202244
const waitFor = Effect.fnUntraced(function*<E>(condition: () => Effect.Effect<boolean, E>) {
203245
for (let i = 0; i < 100; i++) {

0 commit comments

Comments
 (0)