Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/cloudflare-durable-object-sql-client.md
Original file line number Diff line number Diff line change
@@ -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`.
7 changes: 7 additions & 0 deletions packages/platform/cloudflare/src/AlchemyCloudflareCluster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -120,6 +121,11 @@ export interface MakeOptions<ROut, E, RIn> {
* `CloudflareCluster.LayerOptions`. Defaults to 30 seconds.
*/
readonly keepAliveHeartbeat?: Duration.Input | undefined
/**
* Options for each entity's `DurableObjectSqlClient`, as in
* `CloudflareCluster.LayerOptions`.
*/
readonly durableObjectSqlClient?: Omit<SqliteClientConfig, "db" | "storage"> | undefined
/**
* Restricts all four cluster Durable Object bindings to a Cloudflare
* jurisdiction (for example `"eu"`). Opting in does not migrate existing
Expand Down Expand Up @@ -172,6 +178,7 @@ const makeUnsafe = Effect.fnUntraced(function*(options: MakeOptions<any, any, an
layer: options.layer,
env,
keepAliveHeartbeat: options.keepAliveHeartbeat,
durableObjectSqlClient: options.durableObjectSqlClient,
jurisdiction: options.jurisdiction
})
})
Expand Down
15 changes: 14 additions & 1 deletion packages/platform/cloudflare/src/CloudflareCluster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
* @stability experimental
* @since 4.1.3
*/
import type { SqliteClientConfig } from "@effect/sql-sqlite-do/SqliteClient"
import * as Cause from "effect/Cause"
import { Clock } from "effect/Clock"
import { MailboxFull, PersistenceError } from "effect/cluster/ClusterError"
Expand Down Expand Up @@ -143,6 +144,10 @@ export const clusterCronSingletonName = (name: string): string => `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
Expand All @@ -154,6 +159,7 @@ export interface LayerOptions {
readonly queueNamespace: DurableObjectNamespace
readonly singletonNamespace: DurableObjectNamespace
readonly keepAliveHeartbeat?: Duration.Input | undefined
readonly durableObjectSqlClient?: Omit<SqliteClientConfig, "db" | "storage"> | undefined
}

const notImplemented = (method: string) =>
Expand Down Expand Up @@ -533,7 +539,14 @@ const make = Effect.fnUntraced(function*(options: LayerOptions) {
return yield* unknownEntity(entity)
}
const context = yield* Effect.context<never>()
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(() =>
Expand Down
5 changes: 4 additions & 1 deletion packages/platform/cloudflare/src/internal/alchemyCluster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -28,6 +29,7 @@ export interface ClusterHandleOptions {
readonly layer: Layer.Layer<never, any, any>
readonly env: Record<string, unknown>
readonly keepAliveHeartbeat?: Duration.Input | undefined
readonly durableObjectSqlClient?: Omit<SqliteClientConfig, "db" | "storage"> | undefined
readonly jurisdiction?: DurableObjectJurisdiction | undefined
}

Expand Down Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions packages/platform/cloudflare/src/internal/entityRegistry.ts
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -16,6 +17,8 @@ export interface EntityRegistration {
readonly context: Context.Context<never>
/** Interval of the keep-alive heartbeat alarm, in milliseconds. */
readonly keepAliveHeartbeat: number
/** Options for the entity's `DurableObjectSqlClient`. */
readonly durableObjectSqlClient?: Omit<SqliteClientConfig, "db" | "storage"> | undefined
}

const registry = makeRegistry<EntityRegistration>()
Expand Down
5 changes: 4 additions & 1 deletion packages/platform/cloudflare/src/internal/entityRuntime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
35 changes: 19 additions & 16 deletions packages/platform/cloudflare/src/internal/entitySql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Context.Context<DurableObjectSqlClient>, never, Scope.Scope>
readonly make: (
config: Omit<SqliteClient.SqliteClientConfig, "db" | "storage"> | undefined
) => Effect.Effect<Context.Context<DurableObjectSqlClient>, never, Scope.Scope>
/** Runs a mailbox write once no user transaction is open. */
readonly guard: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>
}
Expand All @@ -37,21 +39,22 @@ const InUserTransaction = Context.Reference<boolean>(
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,
Expand Down
46 changes: 39 additions & 7 deletions packages/platform/cloudflare/test/EntitySql.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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()
) {
Expand All @@ -124,7 +146,8 @@ const makeNotes = Effect.fnUntraced(function*(entityId: string) {
save: (ids: ReadonlyArray<string>, 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
}
})

Expand All @@ -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()
})
Expand Down
Loading