diff --git a/.changeset/cloudflare-durable-object-sql-client.md b/.changeset/cloudflare-durable-object-sql-client.md new file mode 100644 index 00000000000..fa826ec9747 --- /dev/null +++ b/.changeset/cloudflare-durable-object-sql-client.md @@ -0,0 +1,5 @@ +--- +"@effect/platform-cloudflare": patch +--- + +Add a `durableObjectSqlClient` option to `CloudflareCluster.layer` and `AlchemyCloudflareCluster.make` to configure each entity's `DurableObjectSqlClient`, such as `transformResultNames` and `transformQueryNames`. diff --git a/packages/platform/cloudflare/src/AlchemyCloudflareCluster.ts b/packages/platform/cloudflare/src/AlchemyCloudflareCluster.ts index f8c7563fa7b..7e7359264c2 100644 --- a/packages/platform/cloudflare/src/AlchemyCloudflareCluster.ts +++ b/packages/platform/cloudflare/src/AlchemyCloudflareCluster.ts @@ -47,6 +47,7 @@ * @since 4.1.3 */ import * as Cloudflare from "@alchemy.run/cloudflare" +import type { SqliteClientConfig } from "@effect/sql-sqlite-do/SqliteClient" import type * as Entity from "effect/cluster/Entity" import type { Sharding } from "effect/cluster/Sharding" import type * as Duration from "effect/Duration" @@ -120,6 +121,11 @@ export interface MakeOptions { * `CloudflareCluster.LayerOptions`. Defaults to 30 seconds. */ readonly keepAliveHeartbeat?: Duration.Input | undefined + /** + * Options for each entity's `DurableObjectSqlClient`, as in + * `CloudflareCluster.LayerOptions`. + */ + readonly durableObjectSqlClient?: Omit | undefined /** * Restricts all four cluster Durable Object bindings to a Cloudflare * jurisdiction (for example `"eu"`). Opting in does not migrate existing @@ -172,6 +178,7 @@ const makeUnsafe = Effect.fnUntraced(function*(options: MakeOptions `ClusterCron/$ * interrupted request after a restart or deploy. It bounds recovery latency; * it is not a liveness check. * + * `durableObjectSqlClient` configures each entity's `DurableObjectSqlClient`, + * such as `transformResultNames` and `transformQueryNames`. The adapter + * supplies the storage. + * * @stability experimental * @category layers * @since 4.1.3 @@ -154,6 +159,7 @@ export interface LayerOptions { readonly queueNamespace: DurableObjectNamespace readonly singletonNamespace: DurableObjectNamespace readonly keepAliveHeartbeat?: Duration.Input | undefined + readonly durableObjectSqlClient?: Omit | undefined } const notImplemented = (method: string) => @@ -533,7 +539,14 @@ const make = Effect.fnUntraced(function*(options: LayerOptions) { return yield* unknownEntity(entity) } const context = yield* Effect.context() - const registration = { entity, build: build as any, options: buildOptions, context, keepAliveHeartbeat } + const registration = { + entity, + build: build as any, + options: buildOptions, + context, + keepAliveHeartbeat, + durableObjectSqlClient: options.durableObjectSqlClient + } if (!registerEntityHandler(entity.type, registration)) return if (!declared) entities.set(entity.type, entity) yield* Effect.addFinalizer(() => diff --git a/packages/platform/cloudflare/src/internal/alchemyCluster.ts b/packages/platform/cloudflare/src/internal/alchemyCluster.ts index abcc50f617c..cbc703001c0 100644 --- a/packages/platform/cloudflare/src/internal/alchemyCluster.ts +++ b/packages/platform/cloudflare/src/internal/alchemyCluster.ts @@ -6,6 +6,7 @@ * * @internal */ +import type { SqliteClientConfig } from "@effect/sql-sqlite-do/SqliteClient" import type * as Entity from "effect/cluster/Entity" import * as Context from "effect/Context" import type * as Duration from "effect/Duration" @@ -28,6 +29,7 @@ export interface ClusterHandleOptions { readonly layer: Layer.Layer readonly env: Record readonly keepAliveHeartbeat?: Duration.Input | undefined + readonly durableObjectSqlClient?: Omit | undefined readonly jurisdiction?: DurableObjectJurisdiction | undefined } @@ -63,7 +65,8 @@ export const makeClusterHandle = Effect.fnUntraced(function*(options: ClusterHan workflowNamespace, queueNamespace, singletonNamespace, - keepAliveHeartbeat: options.keepAliveHeartbeat + keepAliveHeartbeat: options.keepAliveHeartbeat, + durableObjectSqlClient: options.durableObjectSqlClient })) ), scope diff --git a/packages/platform/cloudflare/src/internal/entityRegistry.ts b/packages/platform/cloudflare/src/internal/entityRegistry.ts index 31abd07badc..1488ec161a2 100644 --- a/packages/platform/cloudflare/src/internal/entityRegistry.ts +++ b/packages/platform/cloudflare/src/internal/entityRegistry.ts @@ -1,4 +1,5 @@ /** @internal */ +import type { SqliteClientConfig } from "@effect/sql-sqlite-do/SqliteClient" import type * as Entity from "effect/cluster/Entity" import type * as Context from "effect/Context" import type * as Effect from "effect/Effect" @@ -16,6 +17,8 @@ export interface EntityRegistration { readonly context: Context.Context /** Interval of the keep-alive heartbeat alarm, in milliseconds. */ readonly keepAliveHeartbeat: number + /** Options for the entity's `DurableObjectSqlClient`. */ + readonly durableObjectSqlClient?: Omit | undefined } const registry = makeRegistry() diff --git a/packages/platform/cloudflare/src/internal/entityRuntime.ts b/packages/platform/cloudflare/src/internal/entityRuntime.ts index 19fe5780880..dc425d3bdd5 100644 --- a/packages/platform/cloudflare/src/internal/entityRuntime.ts +++ b/packages/platform/cloudflare/src/internal/entityRuntime.ts @@ -207,7 +207,10 @@ export const makeEntityRuntime = Effect.fnUntraced(function*( } const { handlers, server } = yield* Effect.gen(function*() { if (entitySql !== undefined) { - context = Context.merge(context, yield* Scope.provide(entitySql.make, scope)) + context = Context.merge( + context, + yield* Scope.provide(entitySql.make(registration.durableObjectSqlClient), scope) + ) } const handlers = yield* Effect.provideContext(registration.build, context) // The server sees each handler's result before it takes a permit; a diff --git a/packages/platform/cloudflare/src/internal/entitySql.ts b/packages/platform/cloudflare/src/internal/entitySql.ts index 6aaec3a4319..73950dc3215 100644 --- a/packages/platform/cloudflare/src/internal/entitySql.ts +++ b/packages/platform/cloudflare/src/internal/entitySql.ts @@ -23,7 +23,9 @@ import { DurableObjectSqlClient } from "../CloudflareCluster.ts" /** @internal */ export interface EntitySql { /** Builds the client for one handler build, closed with that build's scope. */ - readonly make: Effect.Effect, never, Scope.Scope> + readonly make: ( + config: Omit | undefined + ) => Effect.Effect, never, Scope.Scope> /** Runs a mailbox write once no user transaction is open. */ readonly guard: (effect: Effect.Effect) => Effect.Effect } @@ -37,21 +39,22 @@ const InUserTransaction = Context.Reference( export const makeEntitySql = (storage: DurableObjectStorage): EntitySql => { const gate = Semaphore.makeUnsafe(1) - const make = Effect.map( - Effect.provideServiceEffect(SqliteClient.make({ storage }), Reactivity.Reactivity, Reactivity.make), - (client) => { - // Nested transactions reuse the outer storage transaction, so only the - // outermost one takes the gate. - const withTransaction = client.withTransaction - const gated: SqlClient.SqlClient["withTransaction"] = (effect) => - Effect.withFiber((fiber) => - fiber.getRef(InUserTransaction) - ? withTransaction(effect) - : Semaphore.withPermit(gate, withTransaction(Effect.provideService(effect, InUserTransaction, true))) - ) - return Context.make(DurableObjectSqlClient, Object.assign(client, { withTransaction: gated })) - } - ) + const make: EntitySql["make"] = (config) => + Effect.map( + Effect.provideServiceEffect(SqliteClient.make({ ...config, storage }), Reactivity.Reactivity, Reactivity.make), + (client) => { + // Nested transactions reuse the outer storage transaction, so only the + // outermost one takes the gate. + const withTransaction = client.withTransaction + const gated: SqlClient.SqlClient["withTransaction"] = (effect) => + Effect.withFiber((fiber) => + fiber.getRef(InUserTransaction) + ? withTransaction(effect) + : Semaphore.withPermit(gate, withTransaction(Effect.provideService(effect, InUserTransaction, true))) + ) + return Context.make(DurableObjectSqlClient, Object.assign(client, { withTransaction: gated })) + } + ) return { make, diff --git a/packages/platform/cloudflare/test/EntitySql.test.ts b/packages/platform/cloudflare/test/EntitySql.test.ts index 629d07b763d..e80b7e17181 100644 --- a/packages/platform/cloudflare/test/EntitySql.test.ts +++ b/packages/platform/cloudflare/test/EntitySql.test.ts @@ -70,28 +70,50 @@ const registration: EntityRegistration = { context: Context.make(SqlClient.SqlClient, appSql) } -const addressFor = (entityId: string) => +// Reads its rows through `transformResultNames`, configured by +// `durableObjectSqlClient`. +const Columns = Entity.make("Columns", [Rpc.make("Keys", { success: Schema.Array(Schema.String) })]) + +const columnsRegistration: EntityRegistration = { + entity: Columns, + keepAliveHeartbeat: 30_000, + build: Effect.gen(function*() { + const sql = yield* CloudflareCluster.DurableObjectSqlClient + yield* sql`CREATE TABLE IF NOT EXISTS note (created_at INTEGER NOT NULL)` + yield* sql`INSERT INTO note (created_at) VALUES (1)` + return Columns.of({ + Keys: () => sql`SELECT created_at FROM note`.pipe(Effect.map((rows) => Object.keys(rows[0])), Effect.orDie) + }) + }).pipe(Effect.orDie) as unknown as EntityRegistration["build"], + options: undefined, + context: Context.empty(), + durableObjectSqlClient: { + transformResultNames: (name) => name.replace(/_(\w)/g, (_, letter: string) => letter.toUpperCase()) + } +} + +const addressFor = (entityId: string, entityType: string) => EntityAddress.make({ shardId: ShardId.make("default", 1), - entityType: EntityType.make(Notes.type), + entityType: EntityType.make(entityType), entityId: EntityId.make(entityId) }) let requestCount = 0 const nextRequestId = () => `0198bd72-6a80-72f1-8d87-${String(requestCount++).padStart(12, "0")}` -const makeNotes = Effect.fnUntraced(function*(entityId: string) { +const makeNotes = Effect.fnUntraced(function*(entityId: string, entityType: string = Notes.type) { const database = yield* Effect.acquireRelease( Effect.sync(() => new DatabaseSync(":memory:")), (database) => Effect.sync(() => database.close()) ) const storage = new SqliteStorage(database) ensureEntityStorage(storage.sql) - const address = addressFor(entityId) + const address = addressFor(entityId, entityType) const manager = makeEntityManager({ storage: storage as unknown as DurableObjectStorage, address, - entityName: `${Notes.type.length}:${Notes.type}${entityId}`, + entityName: `${entityType.length}:${entityType}${entityId}`, keepAlive: makeEntityKeepAlive({ startHold: () => Promise.resolve(), wanted: false, @@ -105,7 +127,7 @@ const makeNotes = Effect.fnUntraced(function*(entityId: string) { }) const ask = Effect.fnUntraced(function*( - tag: "Save" | "List" | "Audit", + tag: string, payload: unknown, requestId = nextRequestId() ) { @@ -124,7 +146,8 @@ const makeNotes = Effect.fnUntraced(function*(entityId: string) { save: (ids: ReadonlyArray, options?: { readonly fail?: boolean; readonly requestId?: string }) => ask("Save", { ids, fail: options?.fail ?? false }, options?.requestId), list: Effect.map(ask("List", null), (exit) => exit._tag === "Success" ? exit.value : exit), - audit: (id: string) => ask("Audit", { id }) + audit: (id: string) => ask("Audit", { id }), + ask } }) @@ -145,11 +168,20 @@ describe("Entity DurableObjectSqlClient", () => { assert.isTrue(Exit.isFailure(exit) && Cause.hasDies(exit.cause)) })) + it.effect("configures the client with the registration's durableObjectSqlClient options", () => + Effect.gen(function*() { + const columns = yield* makeNotes("c1", Columns.type) + + assert.deepStrictEqual(yield* columns.ask("Keys", null), { _tag: "Success", value: ["createdAt"] }) + })) + beforeAll(() => { assert.isTrue(registerEntity(Notes.type, registration)) + assert.isTrue(registerEntity(Columns.type, columnsRegistration)) }) afterAll(() => { unregisterEntity(Notes.type, registration) + unregisterEntity(Columns.type, columnsRegistration) Effect.runSync(Scope.close(appScope, Exit.void)) appDatabase.close() })