diff --git a/packages/client/src/effect/api/api.ts b/packages/client/src/effect/api/api.ts index e6d7cd236a0..150b2f9178f 100644 --- a/packages/client/src/effect/api/api.ts +++ b/packages/client/src/effect/api/api.ts @@ -2679,35 +2679,41 @@ export type ExperimentalPushSettingsSetOperation = ( ) => Effect.Effect export type ExperimentalSpaceWriteInput = { - readonly space: string - readonly changes: ReadonlyArray<{ readonly key: string; readonly value: string | null }> + readonly changes: ReadonlyArray<{ readonly space: string; readonly key: string; readonly value: string | null }> +} +export type ExperimentalSpaceWriteOutput = { + readonly spaces: ReadonlyArray<{ readonly space: string; readonly revision: number; readonly cursor: string }> } -export type ExperimentalSpaceWriteOutput = { readonly revision: number; readonly cursor: string } export type ExperimentalSpaceWriteOperation = ( input: ExperimentalSpaceWriteInput, ) => Effect.Effect -export type ExperimentalSpaceSyncInput = { readonly space: string; readonly cursor?: string | undefined } -export type ExperimentalSpaceSyncOutput = - | { - readonly type: "snapshot" - readonly space: string - readonly epoch: string - readonly revision: number - readonly entries: ReadonlyArray<{ readonly key: string; readonly value: string }> - readonly cursor: string - readonly next?: string | undefined - } - | { - readonly type: "delta" - readonly space: string - readonly epoch: string - readonly revision: number - readonly entries: ReadonlyArray<{ readonly key: string; readonly value: string }> - readonly cursor: string - readonly next?: string | undefined - readonly deleted: ReadonlyArray - } +export type ExperimentalSpaceSyncInput = { + readonly spaces: ReadonlyArray<{ readonly space: string; readonly cursor?: string | undefined }> +} +export type ExperimentalSpaceSyncOutput = { + readonly pages: ReadonlyArray< + | { + readonly type: "snapshot" + readonly space: string + readonly epoch: string + readonly revision: number + readonly entries: ReadonlyArray<{ readonly key: string; readonly value: string }> + readonly cursor: string + readonly next?: string | undefined + } + | { + readonly type: "delta" + readonly space: string + readonly epoch: string + readonly revision: number + readonly entries: ReadonlyArray<{ readonly key: string; readonly value: string }> + readonly cursor: string + readonly next?: string | undefined + readonly deleted: ReadonlyArray + } + > +} export type ExperimentalSpaceSyncOperation = ( input: ExperimentalSpaceSyncInput, ) => Effect.Effect diff --git a/packages/client/src/effect/generated/client.ts b/packages/client/src/effect/generated/client.ts index 9bcb095e09a..c58f0818246 100644 --- a/packages/client/src/effect/generated/client.ts +++ b/packages/client/src/effect/generated/client.ts @@ -1913,16 +1913,12 @@ const EndpointExperimentalPushSettingsSet = const EndpointExperimentalSpaceWrite = (raw: RawClient["server.experimental"]) => (input: ExperimentalSpaceWriteInput) => preserveEffect()( - raw["space.write"]({ params: { space: input["space"] }, payload: { changes: input["changes"] } }).pipe( - Effect.mapError(mapClientError), - ), + raw["space.write"]({ payload: { changes: input["changes"] } }).pipe(Effect.mapError(mapClientError)), ) const EndpointExperimentalSpaceSync = (raw: RawClient["server.experimental"]) => (input: ExperimentalSpaceSyncInput) => preserveEffect()( - raw["space.sync"]({ params: { space: input["space"] }, query: { cursor: input["cursor"] } }).pipe( - Effect.mapError(mapClientError), - ), + raw["space.sync"]({ payload: { spaces: input["spaces"] } }).pipe(Effect.mapError(mapClientError)), ) const EndpointExperimentalSpaceSubscribe = diff --git a/packages/client/src/promise/generated/client.ts b/packages/client/src/promise/generated/client.ts index 5982d5d6f66..af7ae8e660f 100644 --- a/packages/client/src/promise/generated/client.ts +++ b/packages/client/src/promise/generated/client.ts @@ -1995,7 +1995,7 @@ export function make(options: ClientOptions) { request( { method: "POST", - path: `/api/experimental/space/${encodeURIComponent(input.space)}/write`, + path: `/api/experimental/space/write`, body: { changes: input["changes"] }, successStatus: 200, declaredStatuses: [400, 401], @@ -2006,9 +2006,9 @@ export function make(options: ClientOptions) { sync: (input: ExperimentalSpaceSyncInput, requestOptions?: RequestOptions) => request( { - method: "GET", - path: `/api/experimental/space/${encodeURIComponent(input.space)}`, - query: { cursor: input["cursor"] }, + method: "POST", + path: `/api/experimental/space/sync`, + body: { spaces: input["spaces"] }, successStatus: 200, declaredStatuses: [400, 401], empty: false, diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index a3a5fafd92a..9dffd7bc5a7 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -5076,15 +5076,18 @@ export type ExperimentalPushSettingsSetInput = { readonly paused: boolean; reado export type ExperimentalPushSettingsSetOutput = { data: PushSettings }["data"] export type ExperimentalSpaceWriteInput = { - readonly space: string - readonly changes: ReadonlyArray<{ readonly key: string; readonly value: string | null }> + readonly changes: ReadonlyArray<{ readonly space: string; readonly key: string; readonly value: string | null }> } -export type ExperimentalSpaceWriteOutput = { revision: SpaceRevision; cursor: SpaceCursor } +export type ExperimentalSpaceWriteOutput = { + spaces: Array<{ space: SpaceName; revision: SpaceRevision; cursor: SpaceCursor }> +} -export type ExperimentalSpaceSyncInput = { readonly space: string; readonly cursor?: string | undefined } +export type ExperimentalSpaceSyncInput = { + readonly spaces: ReadonlyArray<{ readonly space: string; readonly cursor?: string }> +} -export type ExperimentalSpaceSyncOutput = SpacePage +export type ExperimentalSpaceSyncOutput = { pages: Array } export type ExperimentalSpaceSubscribeInput = { readonly stream: string diff --git a/packages/core/src/space.ts b/packages/core/src/space.ts index 0834921305c..6c6dcf85723 100644 --- a/packages/core/src/space.ts +++ b/packages/core/src/space.ts @@ -1,6 +1,6 @@ export * as SpaceRows from "./space.js" -import { and, asc, count, eq, gt, isNotNull, isNull, lte, max, sql } from "drizzle-orm" +import { and, asc, count, eq, isNotNull, isNull, lte, max, sql, type SQL } from "drizzle-orm" import { Effect } from "effect" import type { Space } from "@opencode/schema/space" import type { Database } from "./database/database.js" @@ -49,23 +49,32 @@ export const remove = (db: Db | Transaction, space: Space.Name, key: Space.Key) ) /** - * Applies the changes in order in one transaction, as if written one after another: each that changes a row takes the - * next revision, so a key changed twice gets both and keeps the last. Returns those changes, and the head after them. + * Applies the changes in order in one transaction, as if written one after another: each that changes a row takes its + * space's next revision, so a key changed twice gets both and keeps the last. Returns those changes, and each space's + * head after them, in the order the spaces first appear. */ -export const write = (db: Db, space: Space.Name, changes: ReadonlyArray) => +export const write = (db: Db, changes: ReadonlyArray) => db .transaction((tx) => Effect.gen(function* () { const written = yield* Effect.forEach(changes, (change) => change.value === null - ? remove(tx, space, change.key).pipe( - Effect.map((revision) => (revision === undefined ? [] : [{ key: change.key, value: null, revision }])), + ? remove(tx, change.space, change.key).pipe( + Effect.map((revision) => + revision === undefined ? [] : [{ space: change.space, key: change.key, value: null, revision }], + ), ) - : set(tx, space, change.key, change.value).pipe( - Effect.map((revision) => [{ key: change.key, value: change.value, revision }]), + : set(tx, change.space, change.key, change.value).pipe( + Effect.map((revision) => [{ space: change.space, key: change.key, value: change.value, revision }]), ), ).pipe(Effect.map((rows) => rows.flat())) - return { written, head: written.at(-1)?.revision ?? (yield* head(tx, space)) } + const last = new Map(written.map((row) => [row.space, row.revision])) + const heads = yield* Effect.forEach(new Set(changes.map((change) => change.space)), (space) => { + const revision = last.get(space) + if (revision !== undefined) return Effect.succeed({ space, revision }) + return head(tx, space).pipe(Effect.map((revision) => ({ space, revision }))) + }) + return { written, heads } }), ) .pipe(Effect.orDie) @@ -128,34 +137,75 @@ export const head = (db: Db | Transaction, space: Space.Name) => Effect.map((row) => row?.revision ?? 0), ) -/** Rows, tombstones included, written after `since`, in revision order: one range of the revision index. */ -export const changes = (db: Db, space: Space.Name, since: Space.Revision, limit?: number) => - db - .select({ key: SpaceTable.key, value: SpaceTable.value, revision: SpaceTable.revision }) - .from(SpaceTable) - .where(and(eq(SpaceTable.space, space), gt(SpaceTable.revision, since))) - .orderBy(asc(SpaceTable.revision)) - .limit(limit ?? -1) - .all() - .pipe(Effect.orDie) +/** + * Where a read starts. A delta is every row after `since`, tombstones included; with `snapshot`, a space that never + * reached `since` or no longer holds every deletion after it gives a snapshot instead. A snapshot is the live rows after + * `since` up to `until`, or from 0 up to the head without `until` or when the head is below it. + */ +export type From = + | { readonly type: "delta"; readonly since: Space.Revision; readonly snapshot: boolean } + | { readonly type: "snapshot"; readonly since: Space.Revision; readonly until?: Space.Revision } -/** Rows holding a value, written after `since` and up to `until`, in revision order: one range of the live index. */ -export const live = (db: Db, space: Space.Name, since: Space.Revision, until: Space.Revision, limit: number) => - db - .select({ key: SpaceTable.key, value: SpaceTable.value, revision: SpaceTable.revision }) - .from(SpaceTable) - .where( - and( - eq(SpaceTable.space, space), - isNotNull(SpaceTable.value), - gt(SpaceTable.revision, since), - lte(SpaceTable.revision, until), - ), +/** + * The space's head and up to `limit` rows from `from` in revision order, read by one statement and so from one snapshot + * of the database. `continued` is false when the rows are a snapshot from 0 to the head instead, or none for a delta + * without `snapshot`. Deltas read one range of the revision index, snapshots one of the live index. + */ +export const read = (db: Db, space: Space.Name, from: From, limit: number) => { + const continued = + from.type === "delta" + ? sql`head >= ${from.since} AND coalesce(( + SELECT CAST("value" AS INTEGER) FROM "space" WHERE "space" = ${Meta} AND "key" = ${floorKey(space)} + ), 0) <= ${from.since}` + : from.until === undefined + ? sql`0` + : sql`head >= ${from.until}` + // A branch that does not apply gets an empty range rather than a condition, which SQLite would check on every row. + const live = (since: SQL, until: SQL) => sql` + SELECT "key", "value", "revision" FROM "space" + WHERE "space" = ${space} AND "value" IS NOT NULL AND "revision" > ${since} AND "revision" <= ${until} + ORDER BY "revision" LIMIT ${limit}` + const delta = sql` + SELECT "key", "value", "revision" FROM "space" + WHERE "space" = ${space} AND "revision" > (SELECT CASE WHEN continued THEN ${from.since} ELSE head END FROM meta) + ORDER BY "revision" LIMIT ${limit}` + const rows = + from.type === "snapshot" + ? live( + sql`(SELECT CASE WHEN continued THEN ${from.since} ELSE 0 END FROM meta)`, + sql`(SELECT CASE WHEN continued THEN ${from.until ?? 0} ELSE head END FROM meta)`, + ) + : from.snapshot + ? sql`SELECT * FROM (${delta}) UNION ALL SELECT * FROM (${live(sql`0`, sql`(SELECT CASE WHEN continued THEN 0 ELSE head END FROM meta)`)})` + : delta + return db + .all<{ + head: Space.Revision + continued: number + key: Space.Key | null + value: Space.Value | null + revision: Space.Revision | null + }>( + sql` + WITH meta AS MATERIALIZED ( + SELECT head, ${continued} AS continued + FROM (SELECT coalesce((SELECT max("revision") FROM "space" WHERE "space" = ${space}), 0) AS head) + ) + SELECT meta.head, meta.continued, page."key", page."value", page."revision" + FROM meta LEFT JOIN (${rows}) AS page + ORDER BY page."revision"`, ) - .orderBy(asc(SpaceTable.revision)) - .limit(limit) - .all() - .pipe(Effect.orDie) + .pipe( + Effect.orDie, + Effect.map((result) => ({ + head: result[0]?.head ?? 0, + continued: result[0]?.continued === 1, + rows: result.flatMap((row) => + row.key === null || row.revision === null ? [] : [{ key: row.key, value: row.value, revision: row.revision }], + ), + })), + ) +} /** This database's epoch: created once in the empty space, which no client can name, then kept. */ export const epoch = (db: Db) => diff --git a/packages/core/test/fixture/recorded-sql.ts b/packages/core/test/fixture/recorded-sql.ts new file mode 100644 index 00000000000..8b4fd78dc12 --- /dev/null +++ b/packages/core/test/fixture/recorded-sql.ts @@ -0,0 +1,38 @@ +import { SqliteClient } from "@effect/sql-sqlite-bun" +import { Effect, Layer } from "effect" +import { Reactivity } from "effect/reactivity" +import { SqlClient, Statement } from "effect/sql" + +/** An in-memory SQLite client that records every statement it runs, so a test can count them or ask SQLite how it plans them. */ +export const recordedSql = () => { + const statements: Array<{ readonly query: string; readonly params: ReadonlyArray }> = [] + const layer = Layer.effect( + SqlClient.SqlClient, + Effect.gen(function* () { + const client = yield* SqlClient.SqlClient + const connection = yield* client.reserve + const record = (query: string, params: ReadonlyArray) => statements.push({ query, params }) + return yield* SqlClient.make({ + acquirer: Effect.succeed({ + ...connection, + execute: (query, params, transform) => { + record(query, params) + return connection.execute(query, params, transform) + }, + executeValues: (query, params) => { + record(query, params) + return connection.executeValues(query, params) + }, + }), + compiler: Statement.makeCompilerSqlite(), + driver: client.driver, + spanAttributes: [], + }) + }), + ).pipe( + Layer.provide(SqliteClient.layer({ filename: ":memory:", disableWAL: true })), + Layer.provide(Reactivity.layer), + Layer.orDie, + ) + return { statements, layer } +} diff --git a/packages/core/test/space.test.ts b/packages/core/test/space.test.ts index c8f6af82254..0a598196c9d 100644 --- a/packages/core/test/space.test.ts +++ b/packages/core/test/space.test.ts @@ -1,46 +1,23 @@ import { describe, expect } from "bun:test" -import { SqliteClient } from "@effect/sql-sqlite-bun" import { and, asc, eq, isNull } from "drizzle-orm" import { Effect, Layer } from "effect" -import { Reactivity } from "effect/reactivity" -import { SqlClient, Statement } from "effect/sql" +import { SqlClient } from "effect/sql" import { SpaceRows } from "@opencode/core/space" import { SpaceTable } from "@opencode/core/space/sql" import { Database } from "@opencode/core/database/database" import { sqliteLayer } from "@opencode/core/database/sqlite.workerd" import { makeDurableObjectStorage } from "./fixture/durable-object-storage" import { tempGlobalLayer } from "./fixture/global" +import { recordedSql } from "./fixture/recorded-sql" import { testEffect } from "./lib/effect" // Every statement the database runs, so a test can ask SQLite how it plans the ones Space issues. -const statements: Array<{ readonly query: string; readonly params: ReadonlyArray }> = [] +const recorded = recordedSql() +const statements = recorded.statements -const recording = Layer.effect( - SqlClient.SqlClient, - Effect.gen(function* () { - const client = yield* SqlClient.SqlClient - const connection = yield* client.reserve - const record = (query: string, params: ReadonlyArray) => statements.push({ query, params }) - return yield* SqlClient.make({ - acquirer: Effect.succeed({ - ...connection, - execute: (query, params, transform) => { - record(query, params) - return connection.execute(query, params, transform) - }, - executeValues: (query, params) => { - record(query, params) - return connection.executeValues(query, params) - }, - }), - compiler: Statement.makeCompilerSqlite(), - driver: client.driver, - spanAttributes: [], - }) - }), -).pipe(Layer.provide(SqliteClient.layer({ filename: ":memory:", disableWAL: true })), Layer.provide(Reactivity.layer)) - -const local = testEffect(Database.layerFromClient.pipe(Layer.provideMerge(recording), Layer.provide(tempGlobalLayer))) +const local = testEffect( + Database.layerFromClient.pipe(Layer.provideMerge(recorded.layer), Layer.provide(tempGlobalLayer)), +) const durableObject = testEffect( Database.layerFromClient.pipe( Layer.provide(sqliteLayer({ storage: makeDurableObjectStorage() })), @@ -71,35 +48,114 @@ describe.each([ { space: "other", key: "a", value: "x", revision: 1 }, ]) expect(yield* SpaceRows.head(db, "app")).toBe(4) - expect(yield* SpaceRows.changes(db, "app", 2)).toEqual([ - { key: "a", value: "2", revision: 3 }, - { key: "b", value: null, revision: 4 }, - ]) + expect(yield* SpaceRows.read(db, "app", { type: "delta", since: 2, snapshot: false }, 10)).toEqual({ + head: 4, + continued: true, + rows: [ + { key: "a", value: "2", revision: 3 }, + { key: "b", value: null, revision: 4 }, + ], + }) expect(yield* SpaceRows.set(db, "app", "b", "true")).toBe(5) }), ) - it.effect("writes changes in order in one transaction, returning those that changed a row and the head", () => + it.effect( + "writes changes in order in one transaction, returning those that changed a row and each space's head", + () => + Effect.gen(function* () { + const db = (yield* Database.Service).db + expect( + yield* SpaceRows.write(db, [ + { space: "batch", key: "a", value: "1" }, + { space: "second", key: "a", value: "x" }, + { space: "batch", key: "b", value: null }, + { space: "batch", key: "a", value: null }, + { space: "second", key: "a", value: "y" }, + { space: "batch", key: "a", value: null }, + { space: "batch", key: "b", value: "2" }, + ]), + ).toEqual({ + written: [ + { space: "batch", key: "a", value: "1", revision: 1 }, + { space: "second", key: "a", value: "x", revision: 1 }, + { space: "batch", key: "a", value: null, revision: 2 }, + { space: "second", key: "a", value: "y", revision: 2 }, + { space: "batch", key: "b", value: "2", revision: 3 }, + ], + heads: [ + { space: "batch", revision: 3 }, + { space: "second", revision: 2 }, + ], + }) + // A space whose changes change nothing reports its head. + expect( + yield* SpaceRows.write(db, [ + { space: "unwritten", key: "c", value: null }, + { space: "batch", key: "c", value: null }, + { space: "second", key: "b", value: "1" }, + ]), + ).toEqual({ + written: [{ space: "second", key: "b", value: "1", revision: 3 }], + heads: [ + { space: "unwritten", revision: 0 }, + { space: "batch", revision: 3 }, + { space: "second", revision: 3 }, + ], + }) + }), + ) + + it.effect("reads a page with the head in one statement: a delta, a snapshot, or a snapshot instead of a delta", () => Effect.gen(function* () { const db = (yield* Database.Service).db - expect( - yield* SpaceRows.write(db, "batch", [ - { key: "a", value: "1" }, - { key: "b", value: null }, - { key: "a", value: null }, - { key: "a", value: null }, - { key: "b", value: "2" }, - ]), - ).toEqual({ - written: [ - { key: "a", value: "1", revision: 1 }, - { key: "a", value: null, revision: 2 }, - { key: "b", value: "2", revision: 3 }, - ], - head: 3, + const read = (from: SpaceRows.From, limit = 10) => SpaceRows.read(db, "read", from, limit) + const row = (key: string, value: string | null, revision: number) => ({ key, value, revision }) + // An empty space: a snapshot of nothing at head 0, and a delta from 0. + expect(yield* read({ type: "snapshot", since: 0 })).toEqual({ head: 0, continued: false, rows: [] }) + expect(yield* read({ type: "delta", since: 0, snapshot: true })).toEqual({ head: 0, continued: true, rows: [] }) + + yield* Effect.forEach(["a", "b", "c", "d"], (key) => SpaceRows.set(db, "read", key, key), { discard: true }) + yield* SpaceRows.remove(db, "read", "a") + yield* SpaceRows.remove(db, "read", "b") + // With a limit of 1, the purge takes a's tombstone at revision 5: the floor is 5, the head 6. + yield* SpaceRows.purge(db, "read", 1) + yield* SpaceRows.set(db, "other", "x", "1") + + // A snapshot reads live rows only, up to the head without `until`, and `limit` of them. + expect(yield* read({ type: "snapshot", since: 0 })).toEqual({ + head: 6, + continued: false, + rows: [row("c", "c", 3), row("d", "d", 4)], }) - expect(yield* SpaceRows.write(db, "batch", [{ key: "c", value: null }])).toEqual({ written: [], head: 3 }) - expect(yield* SpaceRows.write(db, "unwritten", [])).toEqual({ written: [], head: 0 }) + expect(yield* read({ type: "snapshot", since: 0 }, 1)).toEqual({ + head: 6, + continued: false, + rows: [row("c", "c", 3)], + }) + // A continuation up to its own head; one past the head starts over. + expect(yield* read({ type: "snapshot", since: 3, until: 4 })).toEqual({ + head: 6, + continued: true, + rows: [row("d", "d", 4)], + }) + expect((yield* read({ type: "snapshot", since: 3, until: 7 })).continued).toBe(false) + // A delta at or above the floor, tombstones included; at the head, nothing. + expect(yield* read({ type: "delta", since: 5, snapshot: true })).toEqual({ + head: 6, + continued: true, + rows: [row("b", null, 6)], + }) + expect(yield* read({ type: "delta", since: 6, snapshot: true })).toEqual({ head: 6, continued: true, rows: [] }) + // Below the floor or past the head, a snapshot instead, or no rows without `snapshot`. + for (const since of [4, 7]) { + expect(yield* read({ type: "delta", since, snapshot: true })).toEqual({ + head: 6, + continued: false, + rows: [row("c", "c", 3), row("d", "d", 4)], + }) + expect(yield* read({ type: "delta", since, snapshot: false })).toEqual({ head: 6, continued: false, rows: [] }) + } }), ) @@ -138,11 +194,18 @@ describe.each([ expect(yield* SpaceRows.floor(db, "pruned")).toBe(10) // Live rows and other spaces stay, and the newest tombstone keeps the head, so no revision is reissued. - expect(yield* SpaceRows.changes(db, "pruned", 0)).toEqual([ + const stored = (space: string) => + db + .select({ key: SpaceTable.key, value: SpaceTable.value, revision: SpaceTable.revision }) + .from(SpaceTable) + .where(eq(SpaceTable.space, space)) + .orderBy(asc(SpaceTable.revision)) + .all() + expect(yield* stored("pruned")).toEqual([ { key: "f", value: "f", revision: 6 }, { key: "e", value: null, revision: 11 }, ]) - expect(yield* SpaceRows.changes(db, "kept", 0)).toEqual([{ key: "a", value: null, revision: 2 }]) + expect(yield* stored("kept")).toEqual([{ key: "a", value: null, revision: 2 }]) expect(yield* SpaceRows.floor(db, "kept")).toBe(0) expect(yield* SpaceRows.head(db, "pruned")).toBe(11) expect(yield* SpaceRows.set(db, "pruned", "a", "1")).toBe(12) @@ -166,16 +229,14 @@ local.effect("reads and writes a space through its indexes: deltas on the revisi // Then a purge past a limit of 1 takes c's tombstone. yield* SpaceRows.remove(db, "app", "b") yield* SpaceRows.purge(db, "app", 1) - yield* SpaceRows.floor(db, "app") yield* SpaceRows.head(db, "app") - yield* SpaceRows.changes(db, "app", 2) - yield* SpaceRows.live(db, "app", 0, 6, 500) + const planned = (statement: { readonly query: string; readonly params: ReadonlyArray }) => + client + .unsafe<{ detail: string }>(`EXPLAIN QUERY PLAN ${statement.query}`, statement.params) + .pipe(Effect.map((rows) => rows.map((row) => row.detail))) const plans = yield* Effect.forEach( statements.filter((statement) => /^\s*(select|insert|update|delete)\b/iu.test(statement.query)), - (statement) => - client - .unsafe<{ detail: string }>(`EXPLAIN QUERY PLAN ${statement.query}`, statement.params) - .pipe(Effect.map((rows) => rows.map((row) => row.detail))), + planned, ) const revisionIndex = "SEARCH space USING COVERING INDEX space_revision_idx (space=?)" const tombstoneIndex = "SEARCH space USING COVERING INDEX space_tombstone_idx (space=?)" @@ -191,14 +252,34 @@ local.effect("reads and writes a space through its indexes: deltas on the revisi ["SEARCH space USING INDEX space_tombstone_idx (space=? AND revision?)"], - // live - ["SEARCH space USING INDEX space_live_idx (space=? AND revision>? AND revision, + (from) => + Effect.gen(function* () { + statements.length = 0 + yield* SpaceRows.read(db, "app", from, 501) + expect(statements).toHaveLength(1) + return (yield* planned(statements[0])).filter((detail) => /^(SEARCH|SCAN) space\b/u.test(detail)) + }), + ) + const live = "SEARCH space USING INDEX space_live_idx (space=? AND revision>? AND revision?)" + expect(reads).toEqual([ + [revisionIndex, live], + [revisionIndex, live], + [revisionIndex, primaryKey, delta], + [revisionIndex, primaryKey, delta, live], ]) }), ) diff --git a/packages/protocol/openapi.json b/packages/protocol/openapi.json index fa52f78f2f6..f56c0f6fa1c 100644 --- a/packages/protocol/openapi.json +++ b/packages/protocol/openapi.json @@ -14913,20 +14913,11 @@ } } }, - "/api/experimental/space/{space}/write": { + "/api/experimental/space/write": { "post": { "tags": ["experimental"], "operationId": "experimental.space.write", - "parameters": [ - { - "name": "space", - "in": "path", - "schema": { - "$ref": "#/components/schemas/Space.Name" - }, - "required": true - } - ], + "parameters": [], "security": [], "responses": { "200": { @@ -14936,14 +14927,27 @@ "schema": { "type": "object", "properties": { - "revision": { - "$ref": "#/components/schemas/Space.Revision" - }, - "cursor": { - "$ref": "#/components/schemas/Space.Cursor" + "spaces": { + "type": "array", + "items": { + "type": "object", + "properties": { + "space": { + "$ref": "#/components/schemas/Space.Name" + }, + "revision": { + "$ref": "#/components/schemas/Space.Revision" + }, + "cursor": { + "$ref": "#/components/schemas/Space.Cursor" + } + }, + "required": ["space", "revision", "cursor"], + "additionalProperties": false + } } }, - "required": ["revision", "cursor"], + "required": ["spaces"], "additionalProperties": false } } @@ -14970,7 +14974,7 @@ } } }, - "description": "Commit 1 to 1024 changes in one transaction, their values at most 1 MiB of UTF-8 in total. A string value sets the key, replacing any previous value; null deletes it, and deleting an unset key changes nothing. In request order, each change that changes a key takes the space's next revision and goes to its subscribers as its own experimental.space.updated or experimental.space.deleted event, so a key that appears twice keeps its last value. Values are client-defined, such as JSON text, and sent back unchanged. Returns the space's revision after the write. To follow a space, a client opens /api/event and reads its stream ID from server.connected, syncs with experimental.space.sync until no `next` remains, then subscribes the stream with the saved cursor through experimental.space.subscribe and applies the stream's events in order. On experimental.space.resync it syncs and subscribes that space again; after a reconnect it subscribes again with its latest cursor. Experimental: may change without compatibility guarantees.", + "description": "Commit 1 to 1024 changes, across any spaces, in one transaction, their values at most 1 MiB of UTF-8 in total. A string value sets the space's key, replacing any previous value; null deletes it, and deleting an unset key changes nothing. In request order, each change that changes a key takes its space's next revision and goes to that space's subscribers as its own experimental.space.updated or experimental.space.deleted event, so a key that appears twice keeps its last value. Values are client-defined, such as JSON text, and sent back unchanged. Returns each space's revision after the write, in the order the spaces first appear. To follow a space, a client opens /api/event and reads its stream ID from server.connected, syncs with experimental.space.sync until no space has a `next` or is left without a page, then subscribes the stream with the saved cursor through experimental.space.subscribe and applies the stream's events in order. On experimental.space.resync it syncs and subscribes that space again; after a reconnect it subscribes again with its latest cursor. Experimental: may change without compatibility guarantees.", "summary": "Write values", "requestBody": { "content": { @@ -14996,41 +15000,29 @@ } } }, - "/api/experimental/space/{space}": { - "get": { + "/api/experimental/space/sync": { + "post": { "tags": ["experimental"], "operationId": "experimental.space.sync", - "parameters": [ - { - "name": "space", - "in": "path", - "schema": { - "$ref": "#/components/schemas/Space.Name" - }, - "required": true - }, - { - "name": "cursor", - "in": "query", - "schema": { - "anyOf": [ - { - "$ref": "#/components/schemas/Space.Cursor_1" - } - ] - }, - "required": false, - "description": "A page's `next`, or a saved `cursor`. Without one, or with one this database cannot use, sync starts from a snapshot." - } - ], + "parameters": [], "security": [], "responses": { "200": { - "description": "Space.Page", + "description": "Success", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Space.Page" + "type": "object", + "properties": { + "pages": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Space.Page" + } + } + }, + "required": ["pages"], + "additionalProperties": false } } } @@ -15056,8 +15048,40 @@ } } }, - "description": "Read one page of at most 500 keys: a snapshot that replaces what the client holds, or a delta of the keys changed and deleted since the cursor. A delta whose deletions were purged comes back as a snapshot. To follow a space, a client opens /api/event and reads its stream ID from server.connected, syncs with experimental.space.sync until no `next` remains, then subscribes the stream with the saved cursor through experimental.space.subscribe and applies the stream's events in order. On experimental.space.resync it syncs and subscribes that space again; after a reconnect it subscribes again with its latest cursor. Experimental: may change without compatibility guarantees.", - "summary": "Sync space" + "description": "Read one page for each of 1 to 100 distinct spaces, in request order, with at most 500 keys across all pages: a snapshot page, or a delta of the keys changed and deleted since the cursor. A delta whose deletions were purged comes back as a snapshot. Apply a delta page at once; apply a snapshot page's entries at once, and remove the keys none of the snapshot's pages held after its last one, the page without `next` or the one before a delta. Once the 500 keys are used up, the remaining spaces get no page: sync them again with the same cursor, together with the `next` of the pages that have one. To follow a space, a client opens /api/event and reads its stream ID from server.connected, syncs with experimental.space.sync until no space has a `next` or is left without a page, then subscribes the stream with the saved cursor through experimental.space.subscribe and applies the stream's events in order. On experimental.space.resync it syncs and subscribes that space again; after a reconnect it subscribes again with its latest cursor. Experimental: may change without compatibility guarantees.", + "summary": "Sync spaces", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "spaces": { + "type": "array", + "items": { + "type": "object", + "properties": { + "space": { + "$ref": "#/components/schemas/Space.Name" + }, + "cursor": { + "$ref": "#/components/schemas/Space.Cursor_1" + } + }, + "required": ["space"], + "additionalProperties": false + }, + "minItems": 1, + "maxItems": 100 + } + }, + "required": ["spaces"], + "additionalProperties": false + } + } + }, + "required": true + } } }, "/api/experimental/space/subscribe": { @@ -15091,7 +15115,7 @@ } } }, - "description": "Send a space's changes to an open event stream, replacing any earlier subscription of that space on it: first the changes since the cursor as experimental.space.updated and experimental.space.deleted events in revision order, or experimental.space.resync when they do not fit one page or the cursor is unusable, then every later change the same way, none missed or repeated. To follow a space, a client opens /api/event and reads its stream ID from server.connected, syncs with experimental.space.sync until no `next` remains, then subscribes the stream with the saved cursor through experimental.space.subscribe and applies the stream's events in order. On experimental.space.resync it syncs and subscribes that space again; after a reconnect it subscribes again with its latest cursor. Experimental: may change without compatibility guarantees.", + "description": "Send 1 to 100 distinct spaces' changes to an open event stream, replacing any earlier subscription of those spaces on it: first the changes since each cursor as experimental.space.updated and experimental.space.deleted events in revision order, then every later change the same way, none missed or repeated. The catch-ups read at most 500 changes together, in request order: a space whose changes do not fit what is left, every space after they are used up, and one whose cursor is unusable get experimental.space.resync instead. To follow a space, a client opens /api/event and reads its stream ID from server.connected, syncs with experimental.space.sync until no space has a `next` or is left without a page, then subscribes the stream with the saved cursor through experimental.space.subscribe and applies the stream's events in order. On experimental.space.resync it syncs and subscribes that space again; after a reconnect it subscribes again with its latest cursor. Experimental: may change without compatibility guarantees.", "summary": "Subscribe stream", "requestBody": { "content": { @@ -15117,7 +15141,9 @@ }, "required": ["space", "cursor"], "additionalProperties": false - } + }, + "minItems": 1, + "maxItems": 100 } }, "required": ["stream", "spaces"], @@ -15160,7 +15186,7 @@ } } }, - "description": "Stop sending these spaces' changes to an open event stream, including a catch-up still going out. Spaces it does not follow are ignored. To follow a space, a client opens /api/event and reads its stream ID from server.connected, syncs with experimental.space.sync until no `next` remains, then subscribes the stream with the saved cursor through experimental.space.subscribe and applies the stream's events in order. On experimental.space.resync it syncs and subscribes that space again; after a reconnect it subscribes again with its latest cursor. Experimental: may change without compatibility guarantees.", + "description": "Stop sending these 1 to 100 distinct spaces' changes to an open event stream, including a catch-up still going out. Spaces it does not follow are ignored. To follow a space, a client opens /api/event and reads its stream ID from server.connected, syncs with experimental.space.sync until no space has a `next` or is left without a page, then subscribes the stream with the saved cursor through experimental.space.subscribe and applies the stream's events in order. On experimental.space.resync it syncs and subscribes that space again; after a reconnect it subscribes again with its latest cursor. Experimental: may change without compatibility guarantees.", "summary": "Unsubscribe stream", "requestBody": { "content": { @@ -15176,7 +15202,9 @@ "type": "array", "items": { "$ref": "#/components/schemas/Space.Name" - } + }, + "minItems": 1, + "maxItems": 100 } }, "required": ["stream", "spaces"], @@ -15219,7 +15247,7 @@ } } }, - "description": "Replace the epoch, so every client's saved cursor becomes unusable and its next sync starts from a snapshot. A restored backup brings back its old epoch, and cursors issued after the backup would then get wrong deltas: after restoring one, call this before clients reconnect, and do not serve writes or subscribers until it has run. To follow a space, a client opens /api/event and reads its stream ID from server.connected, syncs with experimental.space.sync until no `next` remains, then subscribes the stream with the saved cursor through experimental.space.subscribe and applies the stream's events in order. On experimental.space.resync it syncs and subscribes that space again; after a reconnect it subscribes again with its latest cursor. Experimental: may change without compatibility guarantees.", + "description": "Replace the epoch, so every client's saved cursor becomes unusable and its next sync starts from a snapshot. A restored backup brings back its old epoch, and cursors issued after the backup would then get wrong deltas: after restoring one, call this before clients reconnect, and do not serve writes or subscribers until it has run. To follow a space, a client opens /api/event and reads its stream ID from server.connected, syncs with experimental.space.sync until no space has a `next` or is left without a page, then subscribes the stream with the saved cursor through experimental.space.subscribe and applies the stream's events in order. On experimental.space.resync it syncs and subscribes that space again; after a reconnect it subscribes again with its latest cursor. Experimental: may change without compatibility guarantees.", "summary": "Reset revisions" } }, @@ -27635,6 +27663,9 @@ "Space.Change": { "type": "object", "properties": { + "space": { + "$ref": "#/components/schemas/Space.Name" + }, "key": { "$ref": "#/components/schemas/Space.Key" }, @@ -27649,12 +27680,12 @@ ] } }, - "required": ["key", "value"], + "required": ["space", "key", "value"], "additionalProperties": false }, "Space.Cursor": { "type": "string", - "description": "Covers this write and every change before it." + "description": "Covers this write and every change of the space before it." }, "Space.Cursor_1": { "type": "string" diff --git a/packages/protocol/src/groups/space.ts b/packages/protocol/src/groups/space.ts index b2a7ceb130c..317634c44ac 100644 --- a/packages/protocol/src/groups/space.ts +++ b/packages/protocol/src/groups/space.ts @@ -1,4 +1,5 @@ import { Space } from "@opencode/schema/space" +import { optional } from "@opencode/schema/schema" import { InvalidRequestError } from "../errors.js" import { Schema } from "effect" import { HttpApiEndpoint, HttpApiSchema, OpenApi } from "effect/http-api" @@ -7,50 +8,62 @@ const annotations = (identifier: string, summary: string, description: string) = OpenApi.annotations({ identifier: `experimental.space.${identifier}`, summary, - description: `${description} To follow a space, a client opens /api/event and reads its stream ID from server.connected, syncs with experimental.space.sync until no \`next\` remains, then subscribes the stream with the saved cursor through experimental.space.subscribe and applies the stream's events in order. On experimental.space.resync it syncs and subscribes that space again; after a reconnect it subscribes again with its latest cursor. Experimental: may change without compatibility guarantees.`, + description: `${description} To follow a space, a client opens /api/event and reads its stream ID from server.connected, syncs with experimental.space.sync until no space has a \`next\` or is left without a page, then subscribes the stream with the saved cursor through experimental.space.subscribe and applies the stream's events in order. On experimental.space.resync it syncs and subscribes that space again; after a reconnect it subscribes again with its latest cursor. Experimental: may change without compatibility guarantees.`, // The routes share the `server.experimental` group with the persistent PTY prototype; tag them on their own. transform: (operation) => ({ ...operation, tags: ["experimental"] }), }) /** Lives in the `server.experimental` group (see `groups/experimental.ts`). */ export const SpaceEndpoints = [ - HttpApiEndpoint.post("space.write", "/api/experimental/space/:space/write", { - params: { space: Space.Name }, + HttpApiEndpoint.post("space.write", "/api/experimental/space/write", { payload: Schema.Struct({ changes: Schema.Array(Space.Change).check(Schema.isMinLength(1), Schema.isMaxLength(Space.MaxChanges)), }), error: InvalidRequestError, success: Schema.Struct({ - revision: Space.Revision, - cursor: Space.Cursor.annotate({ description: "Covers this write and every change before it." }), + spaces: Schema.Array( + Schema.Struct({ + space: Space.Name, + revision: Space.Revision, + cursor: Space.Cursor.annotate({ description: "Covers this write and every change of the space before it." }), + }), + ), }), }).annotateMerge( annotations( "write", "Write values", - "Commit 1 to 1024 changes in one transaction, their values at most 1 MiB of UTF-8 in total. A string value sets the key, replacing any previous value; null deletes it, and deleting an unset key changes nothing. In request order, each change that changes a key takes the space's next revision and goes to its subscribers as its own experimental.space.updated or experimental.space.deleted event, so a key that appears twice keeps its last value. Values are client-defined, such as JSON text, and sent back unchanged. Returns the space's revision after the write.", + "Commit 1 to 1024 changes, across any spaces, in one transaction, their values at most 1 MiB of UTF-8 in total. A string value sets the space's key, replacing any previous value; null deletes it, and deleting an unset key changes nothing. In request order, each change that changes a key takes its space's next revision and goes to that space's subscribers as its own experimental.space.updated or experimental.space.deleted event, so a key that appears twice keeps its last value. Values are client-defined, such as JSON text, and sent back unchanged. Returns each space's revision after the write, in the order the spaces first appear.", ), ), - HttpApiEndpoint.get("space.sync", "/api/experimental/space/:space", { - params: { space: Space.Name }, - query: Schema.Struct({ - cursor: Schema.optional(Space.Cursor).annotate({ - description: - "A page's `next`, or a saved `cursor`. Without one, or with one this database cannot use, sync starts from a snapshot.", - }), + HttpApiEndpoint.post("space.sync", "/api/experimental/space/sync", { + payload: Schema.Struct({ + spaces: Schema.Array( + Schema.Struct({ + space: Space.Name, + cursor: optional(Space.Cursor).annotate({ + description: + "A page's `next`, or a saved `cursor`. Without one, or with one this database cannot use, sync starts from a snapshot.", + }), + }), + ).check(Schema.isMinLength(1), Schema.isMaxLength(Space.MaxSpaces)), }), - success: Space.Page, + error: InvalidRequestError, + success: Schema.Struct({ pages: Schema.Array(Space.Page) }), }).annotateMerge( annotations( "sync", - "Sync space", - "Read one page of at most 500 keys: a snapshot that replaces what the client holds, or a delta of the keys changed and deleted since the cursor. A delta whose deletions were purged comes back as a snapshot.", + "Sync spaces", + "Read one page for each of 1 to 100 distinct spaces, in request order, with at most 500 keys across all pages: a snapshot page, or a delta of the keys changed and deleted since the cursor. A delta whose deletions were purged comes back as a snapshot. Apply a delta page at once; apply a snapshot page's entries at once, and remove the keys none of the snapshot's pages held after its last one, the page without `next` or the one before a delta. Once the 500 keys are used up, the remaining spaces get no page: sync them again with the same cursor, together with the `next` of the pages that have one.", ), ), HttpApiEndpoint.post("space.subscribe", "/api/experimental/space/subscribe", { payload: Schema.Struct({ stream: Schema.String.annotate({ description: "The stream ID from the stream's server.connected event." }), - spaces: Schema.Array(Schema.Struct({ space: Space.Name, cursor: Space.Cursor })), + spaces: Schema.Array(Schema.Struct({ space: Space.Name, cursor: Space.Cursor })).check( + Schema.isMinLength(1), + Schema.isMaxLength(Space.MaxSpaces), + ), }), error: InvalidRequestError, success: HttpApiSchema.NoContent, @@ -58,13 +71,13 @@ export const SpaceEndpoints = [ annotations( "subscribe", "Subscribe stream", - "Send a space's changes to an open event stream, replacing any earlier subscription of that space on it: first the changes since the cursor as experimental.space.updated and experimental.space.deleted events in revision order, or experimental.space.resync when they do not fit one page or the cursor is unusable, then every later change the same way, none missed or repeated.", + "Send 1 to 100 distinct spaces' changes to an open event stream, replacing any earlier subscription of those spaces on it: first the changes since each cursor as experimental.space.updated and experimental.space.deleted events in revision order, then every later change the same way, none missed or repeated. The catch-ups read at most 500 changes together, in request order: a space whose changes do not fit what is left, every space after they are used up, and one whose cursor is unusable get experimental.space.resync instead.", ), ), HttpApiEndpoint.post("space.unsubscribe", "/api/experimental/space/unsubscribe", { payload: Schema.Struct({ stream: Schema.String.annotate({ description: "The stream ID from the stream's server.connected event." }), - spaces: Schema.Array(Space.Name), + spaces: Schema.Array(Space.Name).check(Schema.isMinLength(1), Schema.isMaxLength(Space.MaxSpaces)), }), error: InvalidRequestError, success: HttpApiSchema.NoContent, @@ -72,7 +85,7 @@ export const SpaceEndpoints = [ annotations( "unsubscribe", "Unsubscribe stream", - "Stop sending these spaces' changes to an open event stream, including a catch-up still going out. Spaces it does not follow are ignored.", + "Stop sending these 1 to 100 distinct spaces' changes to an open event stream, including a catch-up still going out. Spaces it does not follow are ignored.", ), ), HttpApiEndpoint.post("space.reset", "/api/experimental/space/reset", { diff --git a/packages/schema/src/space.ts b/packages/schema/src/space.ts index f8d1fd27749..45504fb5b56 100644 --- a/packages/schema/src/space.ts +++ b/packages/schema/src/space.ts @@ -25,15 +25,18 @@ export const MaxValueBytes = 1024 * 1024 export interface Entry extends Schema.Schema.Type {} export const Entry = Schema.Struct({ key: Key, value: Value }).annotate({ identifier: "Space.Entry" }) -/** One change of a write: a value sets the key, `null` deletes it. */ +/** One change of a write: a value sets the space's key, `null` deletes it. */ export interface Change extends Schema.Schema.Type {} -export const Change = Schema.Struct({ key: Key, value: Schema.NullOr(Value) }).annotate({ +export const Change = Schema.Struct({ space: Name, key: Key, value: Schema.NullOr(Value) }).annotate({ identifier: "Space.Change", }) -/** Changes one write commits at most. */ +/** Changes one write commits at most, across all its spaces. */ export const MaxChanges = 1024 +/** Spaces one sync, subscribe or unsubscribe names at most. */ +export const MaxSpaces = 100 + /** Server-issued, per space: every write in a space gets the next revision, and revisions are never reused. */ export const Revision = NonNegativeInt.annotate({ identifier: "Space.Revision" }) export type Revision = typeof Revision.Type @@ -53,7 +56,10 @@ const page = { next: optional(Cursor).annotate({ description: "Present while more pages remain: sync again with it as `cursor`." }), } -/** A sync page that replaces everything the client held for the space. */ +/** + * A page of a snapshot, which replaces everything the client held for the space: its entries apply at once, and keys + * none of the snapshot's pages held are removed after its last one. + */ export interface Snapshot extends Schema.Schema.Type {} export const Snapshot = Schema.Struct({ type: Schema.tag("snapshot"), ...page }).annotate({ identifier: "Space.Snapshot", diff --git a/packages/server/src/handlers/persistent-pty.ts b/packages/server/src/handlers/persistent-pty.ts index 96a96d71975..185af99d6bd 100644 --- a/packages/server/src/handlers/persistent-pty.ts +++ b/packages/server/src/handlers/persistent-pty.ts @@ -63,8 +63,8 @@ export const PersistentPtyHandler = HttpApiBuilder.group(Api, "server.experiment .handle("push.session.set", (ctx) => push.setSessionBell(ctx.params.sessionID, ctx.payload)) .handle("push.session.remove", (ctx) => push.removeSessionBell(ctx.params.sessionID)) .handle("push.settings.set", (ctx) => push.setSettings(ctx.payload)) - .handle("space.write", (ctx) => space.write(ctx.params.space, ctx.payload.changes)) - .handle("space.sync", (ctx) => space.sync(ctx.params.space, ctx.query.cursor)) + .handle("space.write", (ctx) => space.write(ctx.payload.changes)) + .handle("space.sync", (ctx) => space.sync(ctx.payload.spaces)) .handle("space.subscribe", (ctx) => space.subscribe(ctx.payload)) .handle("space.unsubscribe", (ctx) => space.unsubscribe(ctx.payload)) .handle("space.reset", () => space.reset()) diff --git a/packages/server/src/handlers/space.ts b/packages/server/src/handlers/space.ts index 98cbe122936..988c15e63b4 100644 --- a/packages/server/src/handlers/space.ts +++ b/packages/server/src/handlers/space.ts @@ -7,12 +7,14 @@ import { SpaceStore } from "../space-store" /** `space.*` in the `server.experimental` group. */ const streamNotFound = () => new InvalidRequestError({ message: "No open event stream has this ID", kind: "stream_not_found", field: "stream" }) +const repeated = (spaces: ReadonlyArray) => new Set(spaces).size !== spaces.length +const repeatedSpace = () => new InvalidRequestError({ message: "Each space may appear only once", field: "spaces" }) export const makeSpace = Effect.gen(function* () { const store = yield* SpaceStore.Service return { - write: Effect.fn("SpaceHandler.write")(function* (space: Space.Name, changes: ReadonlyArray) { + write: Effect.fn("SpaceHandler.write")(function* (changes: ReadonlyArray) { const encoder = new TextEncoder() const bytes = changes.reduce( (total, change) => total + (change.value === null ? 0 : encoder.encode(change.value).length), @@ -20,15 +22,19 @@ export const makeSpace = Effect.gen(function* () { ) if (bytes > Space.MaxValueBytes) return yield* new InvalidRequestError({ message: "Values exceed 1 MiB of UTF-8 in total", field: "changes" }) - return yield* store.write(space, changes) + return { spaces: yield* store.write(changes) } }), - sync: Effect.fn("SpaceHandler.sync")(function* (space: Space.Name, cursor: string | undefined) { - return yield* store.sync(space, cursor) + sync: Effect.fn("SpaceHandler.sync")(function* ( + spaces: ReadonlyArray<{ readonly space: Space.Name; readonly cursor?: string }>, + ) { + if (repeated(spaces.map((item) => item.space))) return yield* repeatedSpace() + return { pages: yield* store.sync(spaces) } }), subscribe: Effect.fn("SpaceHandler.subscribe")(function* (payload: { readonly stream: string readonly spaces: ReadonlyArray<{ readonly space: Space.Name; readonly cursor: string }> }) { + if (repeated(payload.spaces.map((item) => item.space))) return yield* repeatedSpace() if (!(yield* store.subscribe(payload.stream, payload.spaces))) return yield* streamNotFound() return HttpApiSchema.NoContent.make() }), @@ -36,6 +42,7 @@ export const makeSpace = Effect.gen(function* () { readonly stream: string readonly spaces: ReadonlyArray }) { + if (repeated(payload.spaces)) return yield* repeatedSpace() if (!(yield* store.unsubscribe(payload.stream, payload.spaces))) return yield* streamNotFound() return HttpApiSchema.NoContent.make() }), diff --git a/packages/server/src/space-store.ts b/packages/server/src/space-store.ts index ccdfec84908..3dd0a1110e1 100644 --- a/packages/server/src/space-store.ts +++ b/packages/server/src/space-store.ts @@ -9,7 +9,7 @@ import { makeGlobalNode } from "@opencode/util/effect/app-node" import { Clock, Context, Effect, Layer, Scope } from "effect" import { EventFeed } from "./event-feed" -/** Rows per snapshot or delta batch, so a large space never goes out as one event. */ +/** Rows one sync, or one subscribe's catch-up, reads at most across all its spaces. */ export const BatchSize = 500 /** Tombstone-creating deletes in a space between two checks of its tombstones against `SpaceRows.TombstoneLimit`. */ @@ -22,27 +22,33 @@ type Send = (event: typeof Space.Event.Resync.Type | Change) => Effect.Effect, - ) => Effect.Effect<{ readonly revision: Space.Revision; readonly cursor: string }> + ) => Effect.Effect< + ReadonlyArray<{ readonly space: Space.Name; readonly revision: Space.Revision; readonly cursor: string }> + > /** This database's epoch, created once and kept, so revisions from another server or database are never used. */ readonly epoch: string /** Replaces the epoch: every client's next sync starts from a snapshot, e.g. after a database restore. */ readonly resetEpoch: Effect.Effect /** - * One page of at most `BatchSize` keys after `cursor`: a delta when this database issued the cursor and still holds - * every deletion after it, else a snapshot. `next` continues it. + * One page per space after its cursor, in order, of `BatchSize` rows in total: a delta when this database issued the + * cursor and still holds every deletion after it, else a snapshot; `next` continues it. Once the rows are used up, + * the remaining spaces are not read and get no page. */ - readonly sync: (space: Space.Name, cursor?: string) => Effect.Effect + readonly sync: ( + spaces: ReadonlyArray<{ readonly space: Space.Name; readonly cursor?: string }>, + ) => Effect.Effect> /** Lets `subscribe` address an event stream by its ID while `send` reaches it, until the scope closes. */ readonly attach: (stream: string, send: Send) => Effect.Effect /** - * Sends each space's changes since its cursor to the stream as single updated and deleted events, or `resync` when - * they do not fit one batch or the cursor is unusable, then its live changes, none missed or repeated. Replaces earlier subscriptions of those spaces - * on the stream; false when no such stream is attached. + * Sends each space's changes since its cursor to the stream as single updated and deleted events, then its live + * changes, none missed or repeated. The spaces' catch-ups read `BatchSize` rows in total, in order: a space whose + * changes do not fit what is left, every space after the rows are used up, and one with an unusable cursor get + * `resync` instead. Replaces earlier subscriptions of those spaces on the stream; false when no such stream is + * attached. */ readonly subscribe: ( stream: string, @@ -102,81 +108,99 @@ const layer = Layer.effect( return change.data.revision > subscription.covered ? stream.send(change) : Effect.void }) - // Live rows only, after `since` and up to the head the snapshot started from, so it reads no tombstones; its last - // page reports that head. A key written meanwhile moves above it, and `next` continues with a delta from there. - const snapshot = (space: Space.Name, since: Space.Revision, head: Space.Revision) => + // One page of at most `limit` rows. A snapshot reads live rows only, up to the head it started from, and its last + // page reports that head; a key written meanwhile moves above it, and `next` continues with a delta from there. + // A delta reads every row after its cursor, so a key rewritten meanwhile moves to a later page. + const page = (space: Space.Name, cursor: string | undefined, limit: number) => Effect.gen(function* () { - const rows = yield* SpaceRows.live(db, space, since, head, BatchSize + 1) - const more = rows.length > BatchSize - const kept = rows.slice(0, BatchSize) - const revision = more ? (kept.at(-1)?.revision ?? head) : head - const next = more - ? `${epoch}.${revision}.${head}` - : (yield* SpaceRows.changes(db, space, head, 1)).length - ? `${epoch}.${head}` - : undefined - const data = { space, epoch, revision, entries: entries(kept), cursor: `${epoch}.${revision}`, next } - const page: Space.Page = since === 0 ? { type: "snapshot", ...data } : { type: "delta", ...data, deleted: [] } - return page - }) - - // Rows after `since` through the revision index, so a key rewritten meanwhile moves to a later page and every - // page's revision covers all changes up to it. - const delta = (space: Space.Name, since: Space.Revision, head: Space.Revision) => - Effect.gen(function* () { - const rows = yield* SpaceRows.changes(db, space, since, BatchSize + 1) - // Read after the rows: a purge above `since` the rows may have missed has raised the floor by now. - if ((yield* SpaceRows.floor(db, space)) > since) return yield* snapshot(space, 0, head) - const kept = rows.slice(0, BatchSize) - const revision = kept.at(-1)?.revision ?? since - const page: Space.Page = { - type: "delta", + const position = cursor === undefined ? undefined : parse(epoch, cursor) + const from: SpaceRows.From = + position?.head === undefined + ? position + ? { type: "delta", since: position.since, snapshot: true } + : { type: "snapshot", since: 0 } + : position.since > position.head + ? { type: "snapshot", since: 0 } + : { type: "snapshot", since: position.since, until: position.head } + const read = yield* SpaceRows.read(db, space, from, limit + 1) + const more = read.rows.length > limit + const kept = read.rows.slice(0, limit) + if (read.continued && from.type === "delta") { + const revision = kept.at(-1)?.revision ?? from.since + const delta: Space.Page = { + type: "delta", + space, + epoch, + revision, + entries: entries(kept), + deleted: deleted(kept), + cursor: `${epoch}.${revision}`, + next: more ? `${epoch}.${revision}` : undefined, + } + return delta + } + const since = read.continued ? from.since : 0 + const until = read.continued && from.type === "snapshot" ? (from.until ?? read.head) : read.head + const revision = more ? (kept.at(-1)?.revision ?? since) : until + const snapshot: Space.Page = { + type: "snapshot", space, epoch, revision, entries: entries(kept), - deleted: deleted(kept), cursor: `${epoch}.${revision}`, - next: rows.length > BatchSize ? `${epoch}.${revision}` : undefined, + next: more ? `${epoch}.${revision}.${until}` : read.head > until ? `${epoch}.${until}` : undefined, } - return page + return snapshot }) - // The changes since the subscription's cursor, one event per row in revision order, with the revision they cover; - // `resync` instead when they do not fit one batch or the cursor is unusable. - const catchUp = (space: Space.Name, cursor: string) => + // The changes since the subscription's cursor, one event per row in revision order, with the revision they cover + // and the rows read; `resync` instead when they do not fit `budget` or the cursor is unusable. + const catchUp = (space: Space.Name, cursor: string, budget: number) => Effect.gen(function* () { const position = parse(epoch, cursor) const created = yield* Clock.currentTimeMillis - const resync = { + const resync = (read: number) => ({ covered: 0, + read, events: [{ id: Event.ID.create(), created, type: Space.Event.Resync.type, data: { space } }], - } as const - if (!position || position.head !== undefined || position.since > (yield* SpaceRows.head(db, space))) - return resync - const rows = yield* SpaceRows.changes(db, space, position.since, BatchSize + 1) - if (rows.length > BatchSize || (yield* SpaceRows.floor(db, space)) > position.since) return resync + }) + if (budget === 0 || !position || position.head !== undefined) return resync(0) + const read = yield* SpaceRows.read( + db, + space, + { type: "delta", since: position.since, snapshot: false }, + budget + 1, + ) + if (!read.continued || read.rows.length > budget) return resync(read.rows.length) return { - covered: rows.at(-1)?.revision ?? position.since, - events: rows.map((row) => change(space, row, created)), + covered: read.rows.at(-1)?.revision ?? position.since, + read: read.rows.length, + events: read.rows.map((row) => change(space, row, created)), } }) return Service.of({ - write: Effect.fn("SpaceStore.write")(function* (space, changes) { - return yield* locks.withLock(space)( + write: Effect.fn("SpaceStore.write")(function* (changes) { + // Every write takes its spaces' locks in the same order, so two writes never wait on each other. + return yield* [...new Set(changes.map((change) => change.space))].toSorted().reduceRight( + (effect, space) => locks.withLock(space)(effect), // A dropped request must not commit changes that listeners never hear about. Effect.uninterruptible( Effect.gen(function* () { - const result = yield* SpaceRows.write(db, space, changes) - yield* tombstoned(space, result.written.filter((row) => row.value === null).length) + const result = yield* SpaceRows.write(db, changes) + const tombstones = Map.groupBy( + result.written.filter((row) => row.value === null), + (row) => row.space, + ) + yield* Effect.forEach(tombstones, ([space, rows]) => tombstoned(space, rows.length), { discard: true }) const created = yield* Clock.currentTimeMillis for (const row of result.written) { - const committed = change(space, row, created) + const committed = change(row.space, row, created) yield* Effect.forEach(listeners, (listener) => listener(committed), { discard: true }) yield* Effect.forEach(streams.values(), (stream) => deliver(stream, committed), { discard: true }) } - return { revision: result.head, cursor: `${epoch}.${result.head}` } + return result.heads.map((head) => ({ ...head, cursor: `${epoch}.${head.revision}` })) }), ), ) @@ -187,14 +211,16 @@ const layer = Layer.effect( resetEpoch: Effect.fn("SpaceStore.resetEpoch")(function* () { epoch = yield* SpaceRows.resetEpoch(db) })(), - sync: Effect.fn("SpaceStore.sync")(function* (space, cursor) { - const head = yield* SpaceRows.head(db, space) - const position = cursor === undefined ? undefined : parse(epoch, cursor) - if (!position || position.since > head) return yield* snapshot(space, 0, head) - if (position.head === undefined) return yield* delta(space, position.since, head) - // A snapshot's continuation: its head is still this database's, or the epoch would differ. - if (position.head > head || position.since > position.head) return yield* snapshot(space, 0, head) - return yield* snapshot(space, position.since, position.head) + sync: Effect.fn("SpaceStore.sync")(function* (requests) { + const pages = new Array() + let budget = BatchSize + for (const request of requests) { + if (budget === 0) break + const next = yield* page(request.space, request.cursor, budget) + budget -= next.entries.length + (next.type === "delta" ? next.deleted.length : 0) + pages.push(next) + } + return pages }), attach: (id, send) => Effect.acquireRelease( @@ -209,6 +235,7 @@ const layer = Layer.effect( stream.spaces.set(request.space, subscription) return { request, subscription } }) + let budget = BatchSize yield* Effect.forEach( subscriptions, ({ request, subscription }) => @@ -216,7 +243,8 @@ const layer = Layer.effect( // A later subscribe of this space on the stream replaces this one and sends its own catch-up, so this // one stops sending as soon as it is replaced. const current = () => stream.spaces.get(request.space) === subscription - const first = yield* catchUp(request.space, request.cursor) + const first = yield* catchUp(request.space, request.cursor, budget) + budget = Math.max(0, budget - first.read) if (!subscription.pending) return subscription.covered = first.covered for (const event of first.events) if (current()) yield* stream.send(event) diff --git a/packages/server/test/space-store.test.ts b/packages/server/test/space-store.test.ts index 5d4edd72fb7..fa33e18f27e 100644 --- a/packages/server/test/space-store.test.ts +++ b/packages/server/test/space-store.test.ts @@ -7,15 +7,20 @@ import { SpaceTable } from "@opencode/core/space/sql" import { LayerNode } from "@opencode/util/effect/layer-node" import { Space } from "@opencode/schema/space" import { Context, Deferred, Effect, Fiber, Layer, Stream } from "effect" +import { recordedSql } from "../../core/test/fixture/recorded-sql" import { it } from "../../core/test/lib/effect" import { SpaceStore } from "../src/space-store" import { EventFeed } from "../src/event-feed" -// One in-memory database shared by every `boot()`, each a fresh store, bus and feed as after a process restart. -// `hold(revision)` pauses the change with that revision after it commits and before streams hear of it, so a test -// can line up competing writes and subscriptions behind it. +// One in-memory database shared by every `boot()`, each a fresh store, bus and feed as after a process restart, with +// the statements it runs. `hold(revision)` pauses the change with that revision after it commits and before streams +// hear of it, so a test can line up competing writes and subscriptions behind it. const setup = Effect.gen(function* () { - const database = Context.get(yield* Layer.build(LayerNode.compile(Database.node)), Database.Service) + const recorded = recordedSql() + const database = Context.get( + yield* Layer.build(LayerNode.compile(Database.configuredClient(recorded.layer))), + Database.Service, + ) const shared = Database.node.replace(Layer.succeed(Database.Service, database)) const gates = new Map; release: Deferred.Deferred }>() const boot = Effect.fnUntraced(function* () { @@ -40,7 +45,7 @@ const setup = Effect.gen(function* () { gates.set(revision, gate) return gate }) - return { boot, hold, db: database.db } + return { boot, hold, db: database.db, statements: recorded.statements } }) const take = (live: Stream.Stream, count: number) => @@ -57,23 +62,56 @@ const take = (live: Stream.Stream, count: number) => const now = { startImmediately: true } as const +// Writes the changes to one space, and returns its head. +const write = (store: SpaceStore.Interface, space: string, changes: ReadonlyArray>) => + store.write(changes.map((change) => ({ space, ...change }))).pipe(Effect.map((heads) => heads[0])) + +// The page of a sync of one space alone, which always gets one. +const syncOne = (store: SpaceStore.Interface, space: string, cursor?: string) => + store + .sync([cursor === undefined ? { space } : { space, cursor }]) + .pipe(Effect.flatMap(([page]) => (page ? Effect.succeed(page) : Effect.die(new Error("No page"))))) + // Every page of a sync from `cursor`, following `next`. const syncAll = Effect.fnUntraced(function* (store: SpaceStore.Interface, space: string, cursor?: string) { const pages: Array = [] for (let next = cursor, first = true; first || next !== undefined; first = false) { - const page = yield* store.sync(space, next) + const page = yield* syncOne(store, space, next) pages.push(page) next = page.next } return pages }) -// What a client holds after applying a sync page: a snapshot replaces everything, a delta changes and deletes keys. -const applyPage = (state: Map, page: Space.Page) => { - if (page.type === "snapshot") state.clear() - for (const entry of page.entries) state.set(entry.key, entry.value) - if (page.type === "delta") for (const key of page.deleted) state.delete(key) - return state +// A client applying sync pages as the API describes: a delta's entries and deletions at once, a snapshot's entries at +// once, and the keys none of a snapshot's pages held removed after its last one, the page without `next` or the one +// before a delta. +const follower = (state = new Map()) => { + let snapshot: Set | undefined + const finish = () => { + if (snapshot) for (const key of state.keys()) if (!snapshot.has(key)) state.delete(key) + snapshot = undefined + } + return { + state, + apply: (page: Space.Page) => { + if (page.type === "delta") finish() + for (const entry of page.entries) state.set(entry.key, entry.value) + if (page.type === "delta") for (const key of page.deleted) state.delete(key) + if (page.type === "snapshot") { + snapshot ??= new Set() + for (const entry of page.entries) snapshot.add(entry.key) + } + if (page.next === undefined) finish() + return state + }, + } +} + +const applyPages = (pages: ReadonlyArray, state?: Map) => { + const client = follower(state) + for (const page of pages) client.apply(page) + return client.state } // And after applying a stream event. @@ -84,7 +122,7 @@ const applyEvent = (state: Map, event: { readonly type: string; } const current = (store: SpaceStore.Interface, space: string) => - syncAll(store, space).pipe(Effect.map((pages) => pages.reduce(applyPage, new Map()))) + syncAll(store, space).pipe(Effect.map((pages) => applyPages(pages))) const range = (count: number) => Array.from({ length: count }, (_, index) => index) @@ -93,13 +131,14 @@ it.live("syncs a space in pages: live rows up to the starting head, then a delta const { boot } = yield* setup const { store } = yield* boot() const count = SpaceStore.BatchSize + 10 - yield* store.write( + yield* write( + store, "big", range(count).map((index) => ({ key: `k${index}`, value: String(index) })), ) const epoch = store.epoch - const first = yield* store.sync("big") + const first = yield* syncOne(store, "big") expect([first.type, first.revision, first.entries.length, first.cursor, first.next]).toEqual([ "snapshot", SpaceStore.BatchSize, @@ -108,26 +147,25 @@ it.live("syncs a space in pages: live rows up to the starting head, then a delta `${epoch}.${SpaceStore.BatchSize}.${count}`, ]) // Between pages: a delete and a rewrite of keys the first page held, and of keys the second would hold. - yield* store.write("big", [{ key: "k0", value: null }]) - yield* store.write("big", [{ key: "k1", value: "new" }]) - yield* store.write("big", [{ key: `k${SpaceStore.BatchSize + 5}`, value: "new" }]) - yield* store.write("big", [{ key: `k${SpaceStore.BatchSize + 6}`, value: null }]) + yield* write(store, "big", [{ key: "k0", value: null }]) + yield* write(store, "big", [{ key: "k1", value: "new" }]) + yield* write(store, "big", [{ key: `k${SpaceStore.BatchSize + 5}`, value: "new" }]) + yield* write(store, "big", [{ key: `k${SpaceStore.BatchSize + 6}`, value: null }]) - const second = yield* store.sync("big", first.next) - // The rest of the keys up to the starting head, without the two changed meanwhile, and no deletions. + const second = yield* syncOne(store, "big", first.next) + // The rest of the keys up to the starting head, without the two changed meanwhile. expect(second).toEqual({ - type: "delta", + type: "snapshot", space: "big", epoch, revision: count, entries: range(10) .filter((index) => index !== 5 && index !== 6) .map((index) => ({ key: `k${SpaceStore.BatchSize + index}`, value: String(SpaceStore.BatchSize + index) })), - deleted: [], cursor: `${epoch}.${count}`, next: `${epoch}.${count}`, }) - const third = yield* store.sync("big", second.next) + const third = yield* syncOne(store, "big", second.next) expect(third).toEqual({ type: "delta", space: "big", @@ -144,12 +182,12 @@ it.live("syncs a space in pages: live rows up to the starting head, then a delta // Every page's cursor resumes: what the pages up to it hold, then a sync from it, is the current state. const now = yield* current(store, "big") expect(now.has("k0")).toBe(false) - const held = new Map() + const held = follower() for (const page of [first, second, third]) { - applyPage(held, page) + held.apply(page) const resumed = yield* syncAll(store, "big", page.cursor) expect(resumed.map((item) => item.type)).not.toContain("snapshot") - expect(resumed.reduce(applyPage, new Map(held))).toEqual(now) + expect(applyPages(resumed, new Map(held.state))).toEqual(now) } }), ) @@ -158,12 +196,13 @@ it.live("a snapshot reads no tombstones, and its last page reports the head it s Effect.gen(function* () { const { boot } = yield* setup const { store } = yield* boot() - yield* store.write( + yield* write( + store, "big", range(SpaceStore.BatchSize + 1).map((index) => ({ key: `k${index}`, value: String(index) })), ) - yield* store.write("big", [{ key: "k0", value: null }]) - const page = yield* store.sync("big") + yield* write(store, "big", [{ key: "k0", value: null }]) + const page = yield* syncOne(store, "big") expect([page.type, page.revision, page.entries.length, page.next]).toEqual([ "snapshot", SpaceStore.BatchSize + 2, @@ -178,23 +217,23 @@ it.live("syncs each space from its cursor: final values and deletions, else a sn Effect.gen(function* () { const { boot } = yield* setup const { store } = yield* boot() - yield* store.write("app", [{ key: "kept", value: "v1" }]) - yield* store.write("app", [{ key: "churn", value: "1" }]) - yield* store.write("app", [{ key: "doomed", value: "true" }]) - yield* store.write("other", [{ key: "x", value: "y" }]) + yield* write(store, "app", [{ key: "kept", value: "v1" }]) + yield* write(store, "app", [{ key: "churn", value: "1" }]) + yield* write(store, "app", [{ key: "doomed", value: "true" }]) + yield* write(store, "other", [{ key: "x", value: "y" }]) // While the client is away: repeated updates, a delete, a delete repeated, and a delete then re-set. - yield* store.write("app", [{ key: "churn", value: "2" }]) - yield* store.write("app", [{ key: "churn", value: "3" }]) - yield* store.write("app", [{ key: "doomed", value: null }]) - yield* store.write("app", [{ key: "doomed", value: null }]) - yield* store.write("app", [{ key: "never-set", value: null }]) - yield* store.write("app", [{ key: "back", value: "a" }]) - yield* store.write("app", [{ key: "back", value: null }]) - yield* store.write("app", [{ key: "back", value: "b" }]) + yield* write(store, "app", [{ key: "churn", value: "2" }]) + yield* write(store, "app", [{ key: "churn", value: "3" }]) + yield* write(store, "app", [{ key: "doomed", value: null }]) + yield* write(store, "app", [{ key: "doomed", value: null }]) + yield* write(store, "app", [{ key: "never-set", value: null }]) + yield* write(store, "app", [{ key: "back", value: "a" }]) + yield* write(store, "app", [{ key: "back", value: null }]) + yield* write(store, "app", [{ key: "back", value: "b" }]) const epoch = store.epoch - const page = (space: string, cursor?: string) => store.sync(space, cursor) + const page = (space: string, cursor?: string) => syncOne(store, space, cursor) expect(yield* page("app", `${epoch}.3`)).toEqual({ type: "delta", space: "app", @@ -243,7 +282,8 @@ it.live("a cursor below the space's floor gets a snapshot and one at or above it Effect.gen(function* () { const { boot, db } = yield* setup const before = yield* boot() - yield* before.store.write( + yield* write( + before.store, "app", ["a", "b", "c", "d"].map((key) => ({ key, value: key })), ) @@ -254,7 +294,7 @@ it.live("a cursor below the space's floor gets a snapshot and one at or above it const { store } = yield* boot() const epoch = store.epoch // A delta from 4 could no longer report that a was deleted. - expect(yield* store.sync("app", `${epoch}.4`)).toEqual({ + expect(yield* syncOne(store, "app", `${epoch}.4`)).toEqual({ type: "snapshot", space: "app", epoch, @@ -271,8 +311,8 @@ it.live("a cursor below the space's floor gets a snapshot and one at or above it deleted, cursor: `${epoch}.7`, }) - expect(yield* store.sync("app", `${epoch}.5`)).toEqual(delta(["b", "c"])) - expect(yield* store.sync("app", `${epoch}.6`)).toEqual(delta(["c"])) + expect(yield* syncOne(store, "app", `${epoch}.5`)).toEqual(delta(["b", "c"])) + expect(yield* syncOne(store, "app", `${epoch}.6`)).toEqual(delta(["c"])) }), ) @@ -281,20 +321,22 @@ it.live("a delta page whose deletions were purged meanwhile comes back as a snap const { boot, db } = yield* setup const { store } = yield* boot() // The client holds k0 to k9, at revision 10. - yield* store.write( + yield* write( + store, "app", range(10).map((index) => ({ key: `k${index}`, value: String(index) })), ) const held = new Map(range(10).map((index) => [`k${index}`, String(index)])) // Then come a full page of new keys and two tombstones. - yield* store.write( + yield* write( + store, "app", range(SpaceStore.BatchSize).map((index) => ({ key: `u${index}`, value: String(index) })), ) yield* SpaceRows.remove(db, "app", "k0") yield* SpaceRows.remove(db, "app", "k1") - const first = yield* store.sync("app", `${store.epoch}.10`) + const first = yield* syncOne(store, "app", `${store.epoch}.10`) // Before the next page, a third delete purges k0's tombstone with a limit of 2. yield* SpaceRows.remove(db, "app", "k2") yield* SpaceRows.purge(db, "app", 2) @@ -305,9 +347,9 @@ it.live("a delta page whose deletions were purged meanwhile comes back as a snap ["delta", SpaceStore.BatchSize + 10, SpaceStore.BatchSize], // k3 to k9, then the new keys, up to the head when the snapshot started. ["snapshot", SpaceStore.BatchSize + 3, SpaceStore.BatchSize], - ["delta", head, 7], + ["snapshot", head, 7], ]) - expect(pages.reduce(applyPage, held)).toEqual(yield* current(store, "app")) + expect(applyPages(pages, held)).toEqual(yield* current(store, "app")) expect(held.has("k0")).toBe(false) }), ) @@ -316,15 +358,15 @@ it.live("a restarted store resumes revisions and sync from storage alone", () => Effect.gen(function* () { const { boot } = yield* setup const before = yield* boot() - yield* before.store.write("app", [{ key: "k", value: "a" }]) - yield* before.store.write("app", [{ key: "k", value: "b" }]) - yield* before.store.write("app", [{ key: "k", value: null }]) + yield* write(before.store, "app", [{ key: "k", value: "a" }]) + yield* write(before.store, "app", [{ key: "k", value: "b" }]) + yield* write(before.store, "app", [{ key: "k", value: null }]) // A new process over the same database. Its first write must not reuse a revision, even the tombstone's. const after = yield* boot() expect(after.store.epoch).toBe(before.store.epoch) - yield* after.store.write("app", [{ key: "j", value: "c" }]) - expect(yield* after.store.sync("app", `${after.store.epoch}.1`)).toEqual({ + yield* write(after.store, "app", [{ key: "j", value: "c" }]) + expect(yield* syncOne(after.store, "app", `${after.store.epoch}.1`)).toEqual({ type: "delta", space: "app", epoch: after.store.epoch, @@ -340,21 +382,21 @@ it.live("a subscription sends the changes since its cursor once, then live chang Effect.gen(function* () { const { boot } = yield* setup const { store, feed, bus } = yield* boot() - yield* store.write("app", [{ key: "k", value: "1" }]) - yield* store.write("app", [{ key: "gone", value: "x" }]) - yield* store.write("other", [{ key: "x", value: "1" }]) - const synced = yield* store.sync("app") + yield* write(store, "app", [{ key: "k", value: "1" }]) + yield* write(store, "app", [{ key: "gone", value: "x" }]) + yield* write(store, "other", [{ key: "x", value: "1" }]) + const synced = yield* syncOne(store, "app") // After the sync and before the subscription. - yield* store.write("app", [{ key: "k", value: "2" }]) - yield* store.write("app", [{ key: "gone", value: null }]) + yield* write(store, "app", [{ key: "k", value: "2" }]) + yield* write(store, "app", [{ key: "gone", value: null }]) const stream = yield* feed.subscribe([Agent.Event.Updated.type]) const plain = yield* feed.subscribe() const seen: Array = [] yield* bus.listen((event) => Effect.sync(() => seen.push(event.type))) expect(yield* store.subscribe(stream.id, [{ space: "app", cursor: synced.cursor }])).toBe(true) - yield* store.write("app", [{ key: "k", value: "3" }]) - yield* store.write("other", [{ key: "x", value: "2" }]) + yield* write(store, "app", [{ key: "k", value: "3" }]) + yield* write(store, "other", [{ key: "x", value: "2" }]) yield* bus.publish(Agent.Event.Updated, {}) // The changes since the cursor, one event per row in revision order, then the live ones. @@ -370,65 +412,126 @@ it.live("a subscription sends the changes since its cursor once, then live chang }), ) -it.live("a write commits all its changes, each at the next revision in order, then sends one event per change", () => +it.live( + "a write commits all its changes across spaces at once, each at its space's next revision, then sends each", + () => + Effect.gen(function* () { + const { boot, hold } = yield* setup + const { store, feed } = yield* boot() + const epoch = store.epoch + const stream = yield* feed.subscribe() + yield* store.subscribe(stream.id, [ + { space: "app", cursor: `${epoch}.0` }, + { space: "other", cursor: `${epoch}.0` }, + ]) + const updated = (key: string, value: string, revision: number, space = "app") => ({ + type: "experimental.space.updated", + data: { space, key, value, revision }, + }) + const deleted = (key: string, revision: number, space = "app") => ({ + type: "experimental.space.deleted", + data: { space, key, revision }, + }) + + // The most changes a write takes: sets, then deletes of the same keys. + const half = Space.MaxChanges / 2 + expect( + yield* write( + store, + "app", + range(Space.MaxChanges).map((index) => ({ + key: `k${index % half}`, + value: index < half ? `${index}` : null, + })), + ), + ).toEqual({ space: "app", revision: Space.MaxChanges, cursor: `${epoch}.${Space.MaxChanges}` }) + expect(yield* take(stream.events, Space.MaxChanges)).toEqual([ + ...range(half).map((index) => updated(`k${index}`, `${index}`, index + 1)), + ...range(half).map((index) => deleted(`k${index}`, half + index + 1)), + ]) + + // Held after its first change reaches listeners: by then every change in every space is committed. A delete of an + // unset key, or of one already deleted, takes no revision and sends nothing; a key changed twice gets both. + const head = Space.MaxChanges + const pending = yield* hold(head + 1) + const held = yield* store + .write([ + { space: "app", key: "a", value: "1" }, + { space: "other", key: "x", value: "1" }, + { space: "app", key: "never", value: null }, + { space: "app", key: "a", value: "2" }, + { space: "other", key: "x", value: null }, + { space: "app", key: "b", value: "1" }, + { space: "idle", key: "never", value: null }, + { space: "app", key: "b", value: null }, + { space: "app", key: "b", value: null }, + ]) + .pipe(Effect.forkChild(now)) + yield* Deferred.await(pending.reached) + expect(yield* current(store, "app")).toEqual(new Map([["a", "2"]])) + expect((yield* syncOne(store, "other")).revision).toBe(2) + yield* Deferred.succeed(pending.release, undefined) + // Each space's head after the write, in the order the spaces first appear, also when its changes change nothing. + expect(yield* Fiber.join(held)).toEqual([ + { space: "app", revision: head + 4, cursor: `${epoch}.${head + 4}` }, + { space: "other", revision: 2, cursor: `${epoch}.2` }, + { space: "idle", revision: 0, cursor: `${epoch}.0` }, + ]) + expect(yield* write(store, "app", [{ key: "never", value: null }])).toEqual({ + space: "app", + revision: head + 4, + cursor: `${epoch}.${head + 4}`, + }) + yield* write(store, "app", [{ key: "c", value: "1" }]) + // In request order, so each space's in revision order. + expect(yield* take(stream.events, 7)).toEqual([ + updated("a", "1", head + 1), + updated("x", "1", 1, "other"), + updated("a", "2", head + 2), + deleted("x", 2, "other"), + updated("b", "1", head + 3), + deleted("b", head + 4), + updated("c", "1", head + 5), + ]) + }), +) + +it.live("writes sharing spaces take their locks in one order, so crossing writes never wait on each other", () => Effect.gen(function* () { const { boot, hold } = yield* setup - const { store, feed } = yield* boot() - const epoch = store.epoch - const stream = yield* feed.subscribe() - yield* store.subscribe(stream.id, [{ space: "app", cursor: `${epoch}.0` }]) - const updated = (key: string, value: string, revision: number) => ({ - type: "experimental.space.updated", - data: { space: "app", key, value, revision }, - }) - const deleted = (key: string, revision: number) => ({ - type: "experimental.space.deleted", - data: { space: "app", key, revision }, - }) - - // The most changes a write takes: sets, then deletes of the same keys. - const half = Space.MaxChanges / 2 - expect( - yield* store.write( - "app", - range(Space.MaxChanges).map((index) => ({ key: `k${index % half}`, value: index < half ? `${index}` : null })), - ), - ).toEqual({ revision: Space.MaxChanges, cursor: `${epoch}.${Space.MaxChanges}` }) - expect(yield* take(stream.events, Space.MaxChanges)).toEqual([ - ...range(half).map((index) => updated(`k${index}`, `${index}`, index + 1)), - ...range(half).map((index) => deleted(`k${index}`, half + index + 1)), - ]) - - // Held after its first change reaches listeners: by then every change is committed. A delete of an unset key, or - // of one already deleted, takes no revision and sends nothing; a key changed twice gets both. - const head = Space.MaxChanges - const pending = yield* hold(head + 1) - const write = yield* store - .write("app", [ - { key: "a", value: "1" }, - { key: "never", value: null }, - { key: "a", value: "2" }, - { key: "b", value: "1" }, - { key: "b", value: null }, - { key: "b", value: null }, + const { store } = yield* boot() + yield* write(store, "b", [{ key: "k", value: "0" }]) + // The first write holds b's lock. The second wants b and then a, the third a and then b: taking them in request + // order, the second would hold b waiting for a while the third held a waiting for b. + const pending = yield* hold(2) + const first = yield* write(store, "b", [{ key: "k", value: "1" }]).pipe(Effect.forkChild(now)) + yield* Deferred.await(pending.reached) + const second = yield* store + .write([ + { space: "b", key: "k", value: "2" }, + { space: "a", key: "k", value: "2" }, + ]) + .pipe(Effect.forkChild(now)) + const third = yield* store + .write([ + { space: "a", key: "k", value: "3" }, + { space: "b", key: "k", value: "3" }, ]) .pipe(Effect.forkChild(now)) - yield* Deferred.await(pending.reached) - expect(yield* current(store, "app")).toEqual(new Map([["a", "2"]])) yield* Deferred.succeed(pending.release, undefined) - // The head after the write, also when its last changes change nothing. - expect(yield* Fiber.join(write)).toEqual({ revision: head + 4, cursor: `${epoch}.${head + 4}` }) - expect(yield* store.write("app", [{ key: "never", value: null }])).toEqual({ - revision: head + 4, - cursor: `${epoch}.${head + 4}`, - }) - yield* store.write("app", [{ key: "c", value: "1" }]) - expect(yield* take(stream.events, 5)).toEqual([ - updated("a", "1", head + 1), - updated("a", "2", head + 2), - updated("b", "1", head + 3), - deleted("b", head + 4), - updated("c", "1", head + 5), + const epoch = store.epoch + expect( + yield* Effect.all([Fiber.join(first), Fiber.join(second), Fiber.join(third)]).pipe(Effect.timeout("2 seconds")), + ).toEqual([ + { space: "b", revision: 2, cursor: `${epoch}.2` }, + [ + { space: "b", revision: 3, cursor: `${epoch}.3` }, + { space: "a", revision: 1, cursor: `${epoch}.1` }, + ], + [ + { space: "a", revision: 2, cursor: `${epoch}.2` }, + { space: "b", revision: 4, cursor: `${epoch}.4` }, + ], ]) }), ) @@ -437,21 +540,21 @@ it.live("a write committed before the subscribe read and delivered after it reac Effect.gen(function* () { const { boot, hold } = yield* setup const { store, feed } = yield* boot() - yield* store.write("app", [{ key: "k", value: "1" }]) - const synced = yield* store.sync("app") + yield* write(store, "app", [{ key: "k", value: "1" }]) + const synced = yield* syncOne(store, "app") const stream = yield* feed.subscribe() const pending = yield* hold(2) - const write = yield* store.write("app", [{ key: "k", value: "2" }]).pipe(Effect.forkChild(now)) + const written = yield* write(store, "app", [{ key: "k", value: "2" }]).pipe(Effect.forkChild(now)) yield* Deferred.await(pending.reached) // "2" is committed but not yet delivered, and the space's lock is held; neither sync, subscribe nor other spaces // wait for it. - expect((yield* store.sync("app", synced.cursor)).revision).toBe(2) - yield* store.write("other", [{ key: "x", value: "1" }]) + expect((yield* syncOne(store, "app", synced.cursor)).revision).toBe(2) + yield* write(store, "other", [{ key: "x", value: "1" }]) expect(yield* store.subscribe(stream.id, [{ space: "app", cursor: synced.cursor }])).toBe(true) - const next = yield* store.write("app", [{ key: "k", value: "3" }]).pipe(Effect.forkChild(now)) + const next = yield* write(store, "app", [{ key: "k", value: "3" }]).pipe(Effect.forkChild(now)) yield* Deferred.succeed(pending.release, undefined) - yield* Fiber.join(write) + yield* Fiber.join(written) yield* Fiber.join(next) expect(yield* take(stream.events, 2)).toEqual([ @@ -466,15 +569,15 @@ it.live("concurrent writes reach a subscribed stream in revision order", () => const { boot } = yield* setup const { store, feed } = yield* boot() const stream = yield* feed.subscribe() - yield* store.subscribe(stream.id, [{ space: "app", cursor: (yield* store.sync("app")).cursor }]) + yield* store.subscribe(stream.id, [{ space: "app", cursor: (yield* syncOne(store, "app")).cursor }]) const writes = range(20) yield* Effect.forEach( writes, (index) => Effect.all( [ - store.write("app", [{ key: `k${index % 4}`, value: String(index) }]), - store.write(`space-${index % 3}`, [{ key: "k", value: String(index) }]), + write(store, "app", [{ key: `k${index % 4}`, value: String(index) }]), + write(store, `space-${index % 3}`, [{ key: "k", value: String(index) }]), ], { concurrency: "unbounded" }, ), @@ -491,56 +594,129 @@ it.live("concurrent writes reach a subscribed stream in revision order", () => }), ) -it.live("a subscription sends resync instead of changes that do not fit one batch or a cursor it cannot use", () => - Effect.gen(function* () { - const { boot, db } = yield* setup - const { store, feed } = yield* boot() - const epoch = store.epoch - yield* store.write( - "big", - range(SpaceStore.BatchSize + 1).map((index) => ({ key: `k${index}`, value: String(index) })), - ) - yield* store.write( - "purged", - ["a", "b", "c"].map((key) => ({ key, value: key })), - ) - yield* Effect.forEach(["a", "b", "c"], (key) => SpaceRows.remove(db, "purged", key), { discard: true }) - yield* SpaceRows.purge(db, "purged", 2) - yield* store.write( - "full", - range(SpaceStore.BatchSize).map((index) => ({ key: `k${index}`, value: String(index) })), - ) +it.live( + "a subscribe's catch-ups share one batch: what does not fit, all after it and unusable cursors get resync", + () => + Effect.gen(function* () { + const { boot, db, statements } = yield* setup + const { store, feed } = yield* boot() + const epoch = store.epoch + const fill = (space: string, count: number) => + write( + store, + space, + range(count).map((index) => ({ key: `k${index}`, value: String(index) })), + ) + yield* fill("big", SpaceStore.BatchSize + 1) + yield* fill("purged", 3) + yield* Effect.forEach(["k0", "k1", "k2"], (key) => SpaceRows.remove(db, "purged", key), { discard: true }) + yield* SpaceRows.purge(db, "purged", 2) + yield* fill("small", 10) + yield* fill("rest", SpaceStore.BatchSize - 10) + yield* fill("later", 1) + const resync = (space: string) => ({ type: "experimental.space.resync", data: { space } }) + const updated = (space: string, count: number) => + range(count).map((index) => ({ + type: "experimental.space.updated", + data: { space, key: `k${index}`, value: String(index), revision: index + 1 }, + })) - const stream = yield* feed.subscribe() - yield* store.subscribe(stream.id, [ - { space: "big", cursor: `${epoch}.0` }, - // Below the floor, from another database, a revision never issued, a snapshot's continuation. - { space: "purged", cursor: `${epoch}.3` }, - { space: "elsewhere", cursor: "another-database.0" }, - { space: "ahead", cursor: `${epoch}.9` }, - { space: "partial", cursor: `${epoch}.0.5` }, - // Exactly one batch still fits. - { space: "full", cursor: `${epoch}.0` }, - ]) - yield* store.write("big", [{ key: "after", value: "true" }]) - const events = yield* take(stream.events, 5 + SpaceStore.BatchSize + 1) - expect(events.slice(0, 5)).toEqual( - ["big", "purged", "elsewhere", "ahead", "partial"].map((space) => ({ - type: "experimental.space.resync", - data: { space }, - })), - ) - expect(events.slice(5, -1)).toEqual( - range(SpaceStore.BatchSize).map((index) => ({ - type: "experimental.space.updated", - data: { space: "full", key: `k${index}`, value: String(index), revision: index + 1 }, - })), - ) - // Live changes still follow a resync. - expect(events.at(-1)).toEqual({ - type: "experimental.space.updated", - data: { space: "big", key: "after", value: "true", revision: SpaceStore.BatchSize + 2 }, + // Below the floor, from another database, a revision never issued and a snapshot's continuation cost nothing; + // small and rest fill the batch exactly, so later is not read at all. + const first = yield* feed.subscribe() + statements.length = 0 + yield* store.subscribe( + first.id, + ["purged", "elsewhere", "ahead", "partial", "small", "rest", "later"].map((space) => ({ + space, + cursor: + { purged: `${epoch}.3`, elsewhere: "another-database.0", ahead: `${epoch}.9`, partial: `${epoch}.0.5` }[ + space + ] ?? `${epoch}.0`, + })), + ) + // One statement for each cursor that parses as a delta: purged, ahead, small and rest. + expect(statements).toHaveLength(4) + yield* write(store, "later", [{ key: "after", value: "true" }]) + expect(yield* take(first.events, 4 + SpaceStore.BatchSize + 2)).toEqual([ + ...["purged", "elsewhere", "ahead", "partial"].map(resync), + ...updated("small", 10), + ...updated("rest", SpaceStore.BatchSize - 10), + resync("later"), + // Live changes still follow a resync. + { type: "experimental.space.updated", data: { space: "later", key: "after", value: "true", revision: 2 } }, + ]) + + // Big does not fit and uses up the batch, so small, which would, is not read either. + const second = yield* feed.subscribe() + statements.length = 0 + yield* store.subscribe(second.id, [ + { space: "big", cursor: `${epoch}.0` }, + { space: "small", cursor: `${epoch}.0` }, + ]) + expect(statements).toHaveLength(1) + expect(yield* take(second.events, 2)).toEqual([resync("big"), resync("small")]) + }), +) + +it.live("syncs several spaces in one request: in order, from one batch of rows, and unread once it is used up", () => + Effect.gen(function* () { + const { boot, statements } = yield* setup + const { store } = yield* boot() + const epoch = store.epoch + const fill = (space: string, count: number) => + write( + store, + space, + range(count).map((index) => ({ key: `k${index}`, value: String(index) })), + ) + yield* fill("a", 300) + yield* fill("b", 300) + yield* fill("c", 5) + const snapshot = (space: string, from: number, to: number, revision: number, next?: string) => ({ + type: "snapshot" as const, + space, + epoch, + revision, + entries: range(to - from).map((index) => ({ key: `k${from + index}`, value: String(from + index) })), + cursor: `${epoch}.${revision}`, + ...(next === undefined ? {} : { next }), }) + + // An empty space is a snapshot of nothing and costs no rows; b gets what a leaves, and c gets no page. + statements.length = 0 + const pages = yield* store.sync([{ space: "empty" }, { space: "a" }, { space: "b" }, { space: "c" }]) + expect(statements).toHaveLength(3) + expect(pages).toEqual([ + snapshot("empty", 0, 0, 0), + snapshot("a", 0, 300, 300), + snapshot("b", 0, 200, 200, `${epoch}.200.300`), + ]) + + // The client sends b's `next` and c without a cursor again, and both fit. + yield* write(store, "b", [{ key: "k0", value: "new" }]) + yield* write(store, "c", [{ key: "k9", value: "9" }]) + const rest = yield* store.sync([{ space: "b", cursor: `${epoch}.200.300` }, { space: "c" }]) + expect(rest).toEqual([ + // The rest of b up to its starting head, then a delta of what changed meanwhile. + snapshot("b", 200, 300, 300, `${epoch}.300`), + { ...snapshot("c", 0, 5, 6), entries: [...snapshot("c", 0, 5, 6).entries, { key: "k9", value: "9" }] }, + ]) + const delta = yield* store.sync([{ space: "b", cursor: `${epoch}.300` }]) + expect(delta).toEqual([ + { + type: "delta", + space: "b", + epoch, + revision: 301, + entries: [{ key: "k0", value: "new" }], + deleted: [], + cursor: `${epoch}.301`, + }, + ]) + expect(applyPages([pages[2], rest[0], delta[0]].filter((page) => page !== undefined))).toEqual( + yield* current(store, "b"), + ) }), ) @@ -559,7 +735,7 @@ it.live("subscribe needs an open stream, and a stream leaves the store when it c ) expect(yield* store.subscribe(id, [{ space: "app", cursor }])).toBe(false) // Writes to a space a closed stream subscribed to go nowhere. - yield* store.write("app", [{ key: "k", value: "1" }]) + yield* write(store, "app", [{ key: "k", value: "1" }]) }), ) @@ -567,12 +743,12 @@ it.live("subscribing a space again on the same stream replaces its subscription" Effect.gen(function* () { const { boot } = yield* setup const { store, feed } = yield* boot() - const cursor = (yield* store.sync("app")).cursor + const cursor = (yield* syncOne(store, "app")).cursor const stream = yield* feed.subscribe() yield* store.subscribe(stream.id, [{ space: "app", cursor }]) - yield* store.write("app", [{ key: "k", value: "1" }]) + yield* write(store, "app", [{ key: "k", value: "1" }]) yield* store.subscribe(stream.id, [{ space: "app", cursor }]) - yield* store.write("app", [{ key: "k", value: "2" }]) + yield* write(store, "app", [{ key: "k", value: "2" }]) const updated = (value: string, revision: number) => ({ type: "experimental.space.updated", @@ -616,8 +792,8 @@ it.live("of two overlapping subscribes of one space on a stream, only the newer type: "experimental.space.updated", data: { space, key, value, revision }, }) - yield* store.write("other", [{ key: "x", value: "1" }]) - yield* store.write("app", [{ key: "a", value: "1" }]) + yield* write(store, "other", [{ key: "x", value: "1" }]) + yield* write(store, "app", [{ key: "a", value: "1" }]) // The older subscribe pauses on its first space, before it reads app's changes; the newer one replaces its app. const first = yield* pausedStream(store, "first") @@ -628,11 +804,11 @@ it.live("of two overlapping subscribes of one space on a stream, only the newer ]) .pipe(Effect.forkChild(now)) yield* Deferred.await(first.reached) - yield* store.write("app", [{ key: "b", value: "2" }]) + yield* write(store, "app", [{ key: "b", value: "2" }]) expect(yield* store.subscribe("first", [{ space: "app", cursor }])).toBe(true) yield* Deferred.succeed(first.release, undefined) yield* Fiber.join(older) - yield* store.write("app", [{ key: "c", value: "3" }]) + yield* write(store, "app", [{ key: "c", value: "3" }]) expect(first.sent.filter((event) => (event.data as { space: string }).space === "app")).toEqual([ updated("app", "a", "1", 1), updated("app", "b", "2", 2), @@ -646,7 +822,7 @@ it.live("of two overlapping subscribes of one space on a stream, only the newer expect(yield* store.subscribe("second", [{ space: "app", cursor }])).toBe(true) yield* Deferred.succeed(second.release, undefined) yield* Fiber.join(paused) - yield* store.write("app", [{ key: "d", value: "4" }]) + yield* write(store, "app", [{ key: "d", value: "4" }]) expect(second.sent).toEqual([ // The newer catch-up, then the one event the older was already sending, then the next change once. updated("app", "a", "1", 1), @@ -672,10 +848,10 @@ it.live("unsubscribing stops a space's events, also mid catch-up, while other sp { space: "app", cursor }, { space: "other", cursor }, ]) - yield* store.write("app", [{ key: "a", value: "1" }]) + yield* write(store, "app", [{ key: "a", value: "1" }]) expect(yield* store.unsubscribe(stream.id, ["app"])).toBe(true) - yield* store.write("app", [{ key: "b", value: "2" }]) - yield* store.write("other", [{ key: "x", value: "1" }]) + yield* write(store, "app", [{ key: "b", value: "2" }]) + yield* write(store, "other", [{ key: "x", value: "1" }]) expect(yield* take(stream.events, 2)).toEqual([updated("app", "a", "1", 1), updated("other", "x", "1", 1)]) // A space the stream does not follow is fine; a stream that is not open is not. expect(yield* store.unsubscribe(stream.id, ["never"])).toBe(true) @@ -688,7 +864,7 @@ it.live("unsubscribing stops a space's events, also mid catch-up, while other sp expect(yield* store.unsubscribe("paused", ["app"])).toBe(true) yield* Deferred.succeed(paused.release, undefined) yield* Fiber.join(subscribing) - yield* store.write("app", [{ key: "c", value: "3" }]) + yield* write(store, "app", [{ key: "c", value: "3" }]) // Only the event it was already sending. expect(paused.sent).toEqual([updated("app", "a", "1", 1)]) }), @@ -698,27 +874,31 @@ it.live("a client that syncs while writes go on, then subscribes, ends with exac Effect.gen(function* () { const { boot } = yield* setup const { store, feed } = yield* boot() - yield* store.write( + yield* write( + store, "app", range(SpaceStore.BatchSize + 5).map((index) => ({ key: `k${index}`, value: String(index) })), ) const stream = yield* feed.subscribe() - // Writes between every page, and between the last page and the subscription. - const state = new Map() - let page = yield* store.sync("app") - applyPage(state, page) + // Writes between every page, and between the last page and the subscription. The client still holds a key from + // before, which the snapshot drops after its last page. + const client = follower(new Map([["stale", "x"]])) + let page = yield* syncOne(store, "app") + client.apply(page) + expect(client.state.get("stale")).toBe("x") for (let round = 0; page.next !== undefined; round++) { - yield* store.write("app", [{ key: `k${round}`, value: `during ${round}` }]) - yield* store.write("app", [{ key: `k${SpaceStore.BatchSize + round}`, value: null }]) - page = yield* store.sync("app", page.next) - applyPage(state, page) + yield* write(store, "app", [{ key: `k${round}`, value: `during ${round}` }]) + yield* write(store, "app", [{ key: `k${SpaceStore.BatchSize + round}`, value: null }]) + page = yield* syncOne(store, "app", page.next) + client.apply(page) } - yield* store.write("app", [{ key: "k1", value: "before subscribe" }]) - yield* store.write("app", [{ key: "k2", value: null }]) + expect(client.state.has("stale")).toBe(false) + yield* write(store, "app", [{ key: "k1", value: "before subscribe" }]) + yield* write(store, "app", [{ key: "k2", value: null }]) yield* store.subscribe(stream.id, [{ space: "app", cursor: page.cursor }]) - yield* store.write("app", [{ key: "k3", value: "live" }]) - yield* store.write("app", [{ key: "k4", value: null }]) + yield* write(store, "app", [{ key: "k3", value: "live" }]) + yield* write(store, "app", [{ key: "k4", value: null }]) const events = yield* take(stream.events, 4) expect(events.map((event) => event.type)).toEqual([ @@ -727,7 +907,7 @@ it.live("a client that syncs while writes go on, then subscribes, ends with exac "experimental.space.updated", "experimental.space.deleted", ]) - expect(events.reduce(applyEvent, state)).toEqual(yield* current(store, "app")) + expect(events.reduce(applyEvent, client.state)).toEqual(yield* current(store, "app")) }), ) @@ -743,26 +923,29 @@ it.live("checks a space's tombstones on its first delete after a start, then on .insert(SpaceTable) .values(rows.slice(start, start + 1000)) .run() - const tombstones = SpaceRows.changes(db, "app", 0).pipe( - Effect.map((rows) => rows.filter((row) => row.value === null).length), - ) + const tombstones = db + .select({ value: SpaceTable.value }) + .from(SpaceTable) + .all() + .pipe(Effect.map((rows) => rows.filter((row) => row.value === null).length)) const floor = SpaceRows.floor(db, "app") const { store } = yield* boot() - yield* store.write( + yield* write( + store, "app", range(interval + 2).map((index) => ({ key: `k${index}`, value: String(index) })), ) - yield* store.write("app", [{ key: "missing", value: null }]) + yield* write(store, "app", [{ key: "missing", value: null }]) // Neither writes nor deletes that make no tombstone check. expect([yield* tombstones, yield* floor]).toEqual([limit + 5, 0]) - yield* store.write("app", [{ key: "k0", value: null }]) + yield* write(store, "app", [{ key: "k0", value: null }]) expect([yield* tombstones, yield* floor]).toEqual([limit, 6]) yield* Effect.forEach( range(interval - 1), (index) => - store.write("app", [ + write(store, "app", [ { key: `k${index + 1}`, value: null }, { key: `k${index + 1}`, value: null }, { key: "missing", value: null }, @@ -772,16 +955,16 @@ it.live("checks a space's tombstones on its first delete after a start, then on ) // At most `interval - 1` past the limit between checks. expect([yield* tombstones, yield* floor]).toEqual([limit + interval - 1, 6]) - yield* store.write("app", [{ key: `k${interval}`, value: null }]) + yield* write(store, "app", [{ key: `k${interval}`, value: null }]) expect([yield* tombstones, yield* floor]).toEqual([limit, 6 + interval]) // A restarted store checks on the first delete again. const restarted = yield* boot() - yield* restarted.store.write("app", [{ key: `k${interval + 1}`, value: null }]) + yield* write(restarted.store, "app", [{ key: `k${interval + 1}`, value: null }]) expect([yield* tombstones, yield* floor]).toEqual([limit, 7 + interval]) // A write that makes `interval` tombstones counts each of them, and checks once after it. - yield* restarted.store.write("app", [ + yield* write(restarted.store, "app", [ ...range(interval).map((index) => ({ key: `n${index}`, value: "1" })), ...range(interval).map((index) => ({ key: `n${index}`, value: null })), ]) diff --git a/packages/server/test/space.test.ts b/packages/server/test/space.test.ts index f0456a12873..2b344d83409 100644 --- a/packages/server/test/space.test.ts +++ b/packages/server/test/space.test.ts @@ -78,36 +78,55 @@ it.live("syncs a space through the API and follows it on the event stream, acros await writer.session.create({ location: { directory: dir } }) expect((await plain.next()).type).toBe("session.created") - await writer.experimental.space.write({ - space: "app", - changes: [{ key: "draft/1", value: '{"text":"hi","n":[1,null]}' }], + // One write and one sync cover several spaces. + const written = await writer.experimental.space.write({ + changes: [ + { space: "app", key: "draft/1", value: '{"text":"hi","n":[1,null]}' }, + { space: "other", key: "draft/1", value: "elsewhere" }, + ], }) - await writer.experimental.space.write({ space: "other", changes: [{ key: "draft/1", value: "elsewhere" }] }) const reader = await subscribe(handler, "types=session.created") const readerStream = ((await reader.next()).data as { stream: string }).stream expect(readerStream).not.toBe(stream) - const page = await writer.experimental.space.sync({ space: "app" }) - epoch = page.epoch - expect(page).toEqual({ - type: "snapshot", - space: "app", - epoch, - revision: 1, - entries: [{ key: "draft/1", value: '{"text":"hi","n":[1,null]}' }], - cursor: `${epoch}.1`, + const synced = await writer.experimental.space.sync({ spaces: [{ space: "app" }, { space: "other" }] }) + const page = synced.pages[0] + epoch = page?.epoch ?? "" + expect(written).toEqual({ + spaces: [ + { space: "app", revision: 1, cursor: `${epoch}.1` }, + { space: "other", revision: 1, cursor: `${epoch}.1` }, + ], }) + expect(synced.pages).toEqual([ + { + type: "snapshot", + space: "app", + epoch, + revision: 1, + entries: [{ key: "draft/1", value: '{"text":"hi","n":[1,null]}' }], + cursor: `${epoch}.1`, + }, + { + type: "snapshot", + space: "other", + epoch, + revision: 1, + entries: [{ key: "draft/1", value: "elsewhere" }], + cursor: `${epoch}.1`, + }, + ]) // Between the sync and the subscription. - await writer.experimental.space.write({ space: "app", changes: [{ key: "draft/2", value: "2" }] }) + await writer.experimental.space.write({ changes: [{ space: "app", key: "draft/2", value: "2" }] }) await writer.experimental.space.subscribe({ stream: readerStream, - spaces: [{ space: "app", cursor: page.cursor }], + spaces: [{ space: "app", cursor: page?.cursor ?? "" }], }) expect(await reader.next()).toEqual({ type: "experimental.space.updated", data: { space: "app", key: "draft/2", value: "2", revision: 2 }, }) - await writer.experimental.space.write({ space: "other", changes: [{ key: "draft/1", value: "unseen" }] }) - await writer.experimental.space.write({ space: "app", changes: [{ key: "draft/1", value: null }] }) + await writer.experimental.space.write({ changes: [{ space: "other", key: "draft/1", value: "unseen" }] }) + await writer.experimental.space.write({ changes: [{ space: "app", key: "draft/1", value: null }] }) await writer.session.create({ location: { directory: dir } }) expect(await reader.next()).toEqual({ type: "experimental.space.deleted", @@ -127,7 +146,7 @@ it.live("syncs a space through the API and follows it on the event stream, acros writer.experimental.space.subscribe({ stream: readerStream, spaces: [{ space: "app", cursor }] }), ).rejects.toMatchObject({ _tag: "InvalidRequestError", kind: "stream_not_found", field: "stream" }) await expect( - writer.experimental.space.subscribe({ stream: "not-a-stream", spaces: [] }), + writer.experimental.space.subscribe({ stream: "not-a-stream", spaces: [{ space: "app", cursor }] }), ).rejects.toMatchObject({ _tag: "InvalidRequestError", kind: "stream_not_found", field: "stream" }) await expect( writer.experimental.space.unsubscribe({ stream: "not-a-stream", spaces: ["app"] }), @@ -137,84 +156,143 @@ it.live("syncs a space through the API and follows it on the event stream, acros // It reports the head after its last change that changed a key. expect( await writer.experimental.space.write({ - space: "app", changes: [ - { key: "draft/2", value: "3" }, - { key: "draft/2", value: "4" }, - { key: "draft/3", value: "x" }, - { key: "draft/3", value: null }, - { key: "draft/3", value: null }, - { key: "draft/1", value: null }, + { space: "app", key: "draft/2", value: "3" }, + { space: "app", key: "draft/2", value: "4" }, + { space: "app", key: "draft/3", value: "x" }, + { space: "app", key: "draft/3", value: null }, + { space: "app", key: "draft/3", value: null }, + { space: "app", key: "draft/1", value: null }, ], }), - ).toEqual({ revision: 7, cursor: `${epoch}.7` }) - expect(await writer.experimental.space.sync({ space: "app", cursor })).toEqual({ - type: "delta", - space: "app", - epoch, - revision: 7, - entries: [{ key: "draft/2", value: "4" }], - deleted: ["draft/3"], - cursor: `${epoch}.7`, + ).toEqual({ spaces: [{ space: "app", revision: 7, cursor: `${epoch}.7` }] }) + expect(await writer.experimental.space.sync({ spaces: [{ space: "app", cursor }] })).toEqual({ + pages: [ + { + type: "delta", + space: "app", + epoch, + revision: 7, + entries: [{ key: "draft/2", value: "4" }], + deleted: ["draft/3"], + cursor: `${epoch}.7`, + }, + ], }) cursor = `${epoch}.7` const anonymous = client(handler) for (const call of [ - () => anonymous.experimental.space.write({ space: "app", changes: [{ key: "x", value: "1" }] }), - () => anonymous.experimental.space.sync({ space: "app" }), - () => anonymous.experimental.space.subscribe({ stream, spaces: [] }), - () => anonymous.experimental.space.unsubscribe({ stream, spaces: [] }), + () => anonymous.experimental.space.write({ changes: [{ space: "app", key: "x", value: "1" }] }), + () => anonymous.experimental.space.sync({ spaces: [{ space: "app" }] }), + () => anonymous.experimental.space.subscribe({ stream, spaces: [{ space: "app", cursor }] }), + () => anonymous.experimental.space.unsubscribe({ stream, spaces: ["app"] }), ]) await expect(call()).rejects.toMatchObject({ _tag: "UnauthorizedError" }) expect((await subscribe(handler, "", {})).status).toBe(401) - // In its own space, so the revisions above are unchanged. - const write = (changes: unknown) => + const post = (path: string, body: unknown) => handler( - new Request("http://opencode.local/api/experimental/space/limit/write", { + new Request(`http://opencode.local/api/experimental/space/${path}`, { method: "POST", headers: { authorization, "content-type": "application/json" }, - body: JSON.stringify({ changes }), + body: JSON.stringify(body), }), ) + // Sync, subscribe and unsubscribe name 1 to 100 spaces, each once, on an open stream. + const open = await subscribe(handler, "types=session.created") + const openStream = ((await open.next()).data as { stream: string }).stream + const names = (count: number) => Array.from({ length: count }, (_, index) => `s${index}`) + for (const spaces of [[], names(101), ["app", "app"]]) { + expect((await post("sync", { spaces: spaces.map((space) => ({ space })) })).status).toBe(400) + expect( + (await post("subscribe", { stream: openStream, spaces: spaces.map((space) => ({ space, cursor })) })) + .status, + ).toBe(400) + expect((await post("unsubscribe", { stream: openStream, spaces })).status).toBe(400) + } + const repeated = { _tag: "InvalidRequestError", field: "spaces" } + await expect( + writer.experimental.space.sync({ spaces: [{ space: "app" }, { space: "app", cursor }] }), + ).rejects.toMatchObject(repeated) + await expect( + writer.experimental.space.subscribe({ + stream: openStream, + spaces: [ + { space: "app", cursor }, + { space: "app", cursor }, + ], + }), + ).rejects.toMatchObject(repeated) + await expect( + writer.experimental.space.unsubscribe({ stream: openStream, spaces: ["app", "app"] }), + ).rejects.toMatchObject(repeated) + expect( + (await writer.experimental.space.sync({ spaces: names(100).map((space) => ({ space })) })).pages, + ).toHaveLength(100) + await writer.experimental.space.subscribe({ + stream: openStream, + spaces: names(100).map((space) => ({ space, cursor })), + }) + await writer.experimental.space.unsubscribe({ stream: openStream, spaces: names(100) }) + await open.close() + + // In their own spaces, so the revisions above are unchanged. + const write = (changes: unknown) => post("write", { changes }) const values = (count: number) => - Array.from({ length: count }, (_, index) => ({ key: "c", value: `${index}` })) - // A write has 1 to 1024 changes, each value a string or null. - for (const changes of [[], values(1025), [{ key: "c", value: 1 }], [{ key: "c" }]]) + Array.from({ length: count }, (_, index) => ({ space: "limit", key: "c", value: `${index}` })) + // A write has 1 to 1024 changes, each value a string or null, in a named space. + for (const changes of [ + [], + values(1025), + [{ space: "limit", key: "c", value: 1 }], + [{ space: "limit", key: "c" }], + [{ key: "c", value: "1" }], + ]) expect((await write(changes)).status).toBe(400) - expect(await (await write(values(1024))).json()).toEqual({ revision: 1024, cursor: `${epoch}.1024` }) + expect(await (await write(values(1024))).json()).toEqual({ + spaces: [{ space: "limit", revision: 1024, cursor: `${epoch}.1024` }], + }) // The cap is the UTF-8 length of a write's values together, keys aren't counted: exactly 1 MiB is stored, one // byte more is not. - expect((await write([{ key: "c", value: "x".repeat(1024 * 1024) }])).status).toBe(200) + expect((await write([{ space: "limit", key: "c", value: "x".repeat(1024 * 1024) }])).status).toBe(200) expect( ( await write([ - { key: "c", value: "x".repeat(1024 * 1024 - 2) }, - { key: "d", value: "é" }, + { space: "limit", key: "c", value: "x".repeat(1024 * 1024 - 2) }, + { space: "limit", key: "d", value: "é" }, ]) ).status, ).toBe(200) expect( ( await write([ - { key: "c", value: "x".repeat(1024 * 1024 - 1) }, - { key: "d", value: "é" }, + { space: "limit", key: "c", value: "x".repeat(1024 * 1024 - 1) }, + { space: "other-limit", key: "d", value: "é" }, ]) ).status, ).toBe(400) - // A rejected write commits none of its changes, though each value would fit, and one that changes nothing - // reports the head. + // A rejected write commits none of its changes in any space, though each value would fit, and one that + // changes nothing reports the head. expect( ( await write([ - { key: "e", value: "x".repeat(512 * 1024) }, - { key: "c", value: "x".repeat(512 * 1024 + 1) }, + { space: "limit", key: "e", value: "x".repeat(512 * 1024) }, + { space: "other-limit", key: "e", value: "x".repeat(512 * 1024 + 1) }, ]) ).status, ).toBe(400) - expect(await (await write([{ key: "e", value: null }])).json()).toEqual({ - revision: 1027, - cursor: `${epoch}.1027`, + expect( + await ( + await write([ + { space: "limit", key: "e", value: null }, + { space: "other-limit", key: "e", value: null }, + ]) + ).json(), + ).toEqual({ + spaces: [ + { space: "limit", revision: 1027, cursor: `${epoch}.1027` }, + { space: "other-limit", revision: 0, cursor: `${epoch}.0` }, + ], }) }) }), @@ -225,14 +303,14 @@ it.live("syncs a space through the API and follows it on the event stream, acros const writer = client(handler, { authorization }) const reader = await subscribe(handler, "types=session.created") const stream = ((await reader.next()).data as { stream: string }).stream - await writer.experimental.space.write({ space: "app", changes: [{ key: "draft/4", value: "true" }] }) + await writer.experimental.space.write({ changes: [{ space: "app", key: "draft/4", value: "true" }] }) // A new stream after the restart subscribes with the cursor saved before it. await writer.experimental.space.subscribe({ stream, spaces: [{ space: "app", cursor }] }) expect(await reader.next()).toEqual({ type: "experimental.space.updated", data: { space: "app", key: "draft/4", value: "true", revision: 8 }, }) - await writer.experimental.space.write({ space: "app", changes: [{ key: "draft/4", value: null }] }) + await writer.experimental.space.write({ changes: [{ space: "app", key: "draft/4", value: null }] }) expect(await reader.next()).toEqual({ type: "experimental.space.deleted", data: { space: "app", key: "draft/4", revision: 9 }, @@ -242,9 +320,9 @@ it.live("syncs a space through the API and follows it on the event stream, acros // A reset, as after a restore, makes every saved cursor unusable; only an authenticated client may do it. await expect(client(handler).experimental.space.reset()).rejects.toMatchObject({ _tag: "UnauthorizedError" }) await writer.experimental.space.reset() - const reset = await writer.experimental.space.sync({ space: "app", cursor }) - expect(reset.type).toBe("snapshot") - expect(reset.epoch).not.toBe(epoch) + const reset = (await writer.experimental.space.sync({ spaces: [{ space: "app", cursor }] })).pages[0] + expect(reset?.type).toBe("snapshot") + expect(reset?.epoch).not.toBe(epoch) }) }).pipe(Effect.scoped), ) @@ -274,7 +352,10 @@ it.live("two clients follow one space on their own streams, through unsubscribe const follow = async (saved?: string) => { const events = await subscribe(handler, "types=session.created") const stream = ((await events.next()).data as { stream: string }).stream - const page = saved === undefined ? await api.experimental.space.sync({ space: "pins" }) : undefined + const page = + saved === undefined + ? (await api.experimental.space.sync({ spaces: [{ space: "pins" }] })).pages[0] + : undefined await api.experimental.space.subscribe({ stream, spaces: [{ space: "pins", cursor: saved ?? page?.cursor ?? "" }], @@ -289,16 +370,16 @@ it.live("two clients follow one space on their own streams, through unsubscribe for (const page of [a.page, b.page]) expect(page).toEqual({ type: "snapshot", space: "pins", epoch, revision: 0, entries: [], cursor: `${epoch}.0` }) - await api.experimental.space.write({ space: "pins", changes: [{ key: "x", value: "1" }] }) + await api.experimental.space.write({ changes: [{ space: "pins", key: "x", value: "1" }] }) expect([await a.events.next(), await b.events.next()]).toEqual([updated("x", "1", 1), updated("x", "1", 1)]) - await api.experimental.space.write({ space: "pins", changes: [{ key: "x", value: null }] }) + await api.experimental.space.write({ changes: [{ space: "pins", key: "x", value: null }] }) expect([await a.events.next(), await b.events.next()]).toEqual([deleted("x", 2), deleted("x", 2)]) - await api.experimental.space.write({ space: "pins", changes: [{ key: "y", value: "2" }] }) + await api.experimental.space.write({ changes: [{ space: "pins", key: "y", value: "2" }] }) expect([await a.events.next(), await b.events.next()]).toEqual([updated("y", "2", 3), updated("y", "2", 3)]) // B stops following pins: A still gets z, and B's next event is the session created after it. await api.experimental.space.unsubscribe({ stream: b.stream, spaces: ["pins"] }) - await api.experimental.space.write({ space: "pins", changes: [{ key: "z", value: "3" }] }) + await api.experimental.space.write({ changes: [{ space: "pins", key: "z", value: "3" }] }) await api.session.create({ location: { directory: dir } }) expect(await a.events.next()).toEqual(updated("z", "3", 4)) expect((await a.events.next()).type).toBe("session.created") @@ -307,16 +388,15 @@ it.live("two clients follow one space on their own streams, through unsubscribe // B goes away; A changes more; B comes back on a new stream with the cursor of the last change it applied. await b.events.close() await api.experimental.space.write({ - space: "pins", changes: [ - { key: "a", value: "4" }, - { key: "b", value: "5" }, - { key: "a", value: null }, + { space: "pins", key: "a", value: "4" }, + { space: "pins", key: "b", value: "5" }, + { space: "pins", key: "a", value: null }, ], }) const back = await follow(`${epoch}.3`) expect(back.stream).not.toBe(b.stream) - await api.experimental.space.write({ space: "pins", changes: [{ key: "c", value: "6" }] }) + await api.experimental.space.write({ changes: [{ space: "pins", key: "c", value: "6" }] }) // What it missed, one event per key in revision order, then the live change. expect([ await back.events.next(), @@ -326,19 +406,21 @@ it.live("two clients follow one space on their own streams, through unsubscribe ]).toEqual([updated("z", "3", 4), updated("b", "5", 6), deleted("a", 7), updated("c", "6", 8)]) // A fresh client with no cursor gets the final state as a snapshot. - expect(await api.experimental.space.sync({ space: "pins" })).toEqual({ - type: "snapshot", - space: "pins", - epoch, - revision: 8, - entries: [ - { key: "y", value: "2" }, - { key: "z", value: "3" }, - { key: "b", value: "5" }, - { key: "c", value: "6" }, - ], - cursor: `${epoch}.8`, - }) + expect((await api.experimental.space.sync({ spaces: [{ space: "pins" }] })).pages).toEqual([ + { + type: "snapshot", + space: "pins", + epoch, + revision: 8, + entries: [ + { key: "y", value: "2" }, + { key: "z", value: "3" }, + { key: "b", value: "5" }, + { key: "c", value: "6" }, + ], + cursor: `${epoch}.8`, + }, + ]) await a.events.close() await back.events.close() })