From d580636cd47cdc196c6b99e09bcb2ad7976ae6a1 Mon Sep 17 00:00:00 2001 From: Sebastian Date: Thu, 26 Nov 2026 16:45:28 +0100 Subject: [PATCH] feat(server): experimental spaces (#63998) Co-authored-by: kommander <335157+kommander@users.noreply.github.com> --- packages/client/src/effect/api/api.ts | 63 ++ .../client/src/effect/generated/client.ts | 60 ++ .../client/src/promise/generated/client.ts | 83 +++ .../client/src/promise/generated/types.ts | 94 ++- packages/client/test/promise.test.ts | 1 + packages/core/schema.json | 113 ++- packages/core/src/database/migration.gen.ts | 2 + .../migration/20261123115523_space.ts | 28 + packages/core/src/database/schema.gen.ts | 16 + packages/core/src/space.ts | 167 +++++ packages/core/src/space/sql.ts | 29 + packages/core/test/space.test.ts | 180 +++++ packages/plugin/src/promise/adapter.ts | 4 +- packages/plugin/src/promise/event.ts | 3 +- packages/protocol/openapi.json | 608 ++++++++++++++- packages/protocol/src/groups/event.ts | 10 +- packages/protocol/src/groups/experimental.ts | 2 + packages/protocol/src/groups/space.ts | 93 +++ packages/schema/src/space.ts | 80 ++ packages/server/src/event-feed.ts | 98 ++- packages/server/src/handlers.ts | 3 +- packages/server/src/handlers/event.ts | 17 +- .../server/src/handlers/persistent-pty.ts | 8 + packages/server/src/handlers/space.ts | 47 ++ packages/server/src/routes.ts | 2 + packages/server/src/space-store.ts | 315 ++++++++ packages/server/test/event-feed.test.ts | 49 +- packages/server/test/space-store.test.ts | 699 ++++++++++++++++++ packages/server/test/space.test.ts | 302 ++++++++ 29 files changed, 3130 insertions(+), 46 deletions(-) create mode 100644 packages/core/src/database/migration/20261123115523_space.ts create mode 100644 packages/core/src/space.ts create mode 100644 packages/core/src/space/sql.ts create mode 100644 packages/core/test/space.test.ts create mode 100644 packages/protocol/src/groups/space.ts create mode 100644 packages/schema/src/space.ts create mode 100644 packages/server/src/handlers/space.ts create mode 100644 packages/server/src/space-store.ts create mode 100644 packages/server/test/space-store.test.ts create mode 100644 packages/server/test/space.test.ts diff --git a/packages/client/src/effect/api/api.ts b/packages/client/src/effect/api/api.ts index b5442a39f9e..c6548ef7d41 100644 --- a/packages/client/src/effect/api/api.ts +++ b/packages/client/src/effect/api/api.ts @@ -2678,6 +2678,61 @@ export type ExperimentalPushSettingsSetOperation = ( input: ExperimentalPushSettingsSetInput, ) => Effect.Effect +export type ExperimentalSpaceSetInput = { readonly space: string; readonly key: string; readonly value: string } +export type ExperimentalSpaceSetOutput = void +export type ExperimentalSpaceSetOperation = ( + input: ExperimentalSpaceSetInput, +) => Effect.Effect + +export type ExperimentalSpaceDeleteInput = { readonly space: string; readonly key: string } +export type ExperimentalSpaceDeleteOutput = void +export type ExperimentalSpaceDeleteOperation = ( + input: ExperimentalSpaceDeleteInput, +) => 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 ExperimentalSpaceSyncOperation = ( + input: ExperimentalSpaceSyncInput, +) => Effect.Effect + +export type ExperimentalSpaceSubscribeInput = { + readonly stream: string + readonly spaces: ReadonlyArray<{ readonly space: string; readonly cursor: string }> +} +export type ExperimentalSpaceSubscribeOutput = void +export type ExperimentalSpaceSubscribeOperation = ( + input: ExperimentalSpaceSubscribeInput, +) => Effect.Effect + +export type ExperimentalSpaceUnsubscribeInput = { readonly stream: string; readonly spaces: ReadonlyArray } +export type ExperimentalSpaceUnsubscribeOutput = void +export type ExperimentalSpaceUnsubscribeOperation = ( + input: ExperimentalSpaceUnsubscribeInput, +) => Effect.Effect + +export type ExperimentalSpaceResetOutput = void +export type ExperimentalSpaceResetOperation = () => Effect.Effect + export interface ExperimentalApi { readonly persistentPty: { readonly read: ExperimentalPersistentPtyReadOperation @@ -2731,6 +2786,14 @@ export interface ExperimentalApi { } readonly settings: { readonly set: ExperimentalPushSettingsSetOperation } } + readonly space: { + readonly set: ExperimentalSpaceSetOperation + readonly delete: ExperimentalSpaceDeleteOperation + readonly sync: ExperimentalSpaceSyncOperation + readonly subscribe: ExperimentalSpaceSubscribeOperation + readonly unsubscribe: ExperimentalSpaceUnsubscribeOperation + readonly reset: ExperimentalSpaceResetOperation + } } export type ShellListInput = { readonly location?: { readonly directory?: string | undefined } | undefined } diff --git a/packages/client/src/effect/generated/client.ts b/packages/client/src/effect/generated/client.ts index 85d510a0ed1..06e25f7ce33 100644 --- a/packages/client/src/effect/generated/client.ts +++ b/packages/client/src/effect/generated/client.ts @@ -298,6 +298,17 @@ import type { ExperimentalPushSessionRemoveOutput, ExperimentalPushSettingsSetInput, ExperimentalPushSettingsSetOutput, + ExperimentalSpaceSetInput, + ExperimentalSpaceSetOutput, + ExperimentalSpaceDeleteInput, + ExperimentalSpaceDeleteOutput, + ExperimentalSpaceSyncInput, + ExperimentalSpaceSyncOutput, + ExperimentalSpaceSubscribeInput, + ExperimentalSpaceSubscribeOutput, + ExperimentalSpaceUnsubscribeInput, + ExperimentalSpaceUnsubscribeOutput, + ExperimentalSpaceResetOutput, ShellListInput, ShellListOutput, ShellCreateInput, @@ -1901,6 +1912,47 @@ const EndpointExperimentalPushSettingsSet = ), ) +const EndpointExperimentalSpaceSet = (raw: RawClient["server.experimental"]) => (input: ExperimentalSpaceSetInput) => + preserveEffect()( + raw["space.set"]({ params: { space: input["space"], key: input["key"] }, payload: { value: input["value"] } }).pipe( + Effect.mapError(mapClientError), + ), + ) + +const EndpointExperimentalSpaceDelete = + (raw: RawClient["server.experimental"]) => (input: ExperimentalSpaceDeleteInput) => + preserveEffect()( + raw["space.delete"]({ params: { space: input["space"], key: input["key"] } }).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), + ), + ) + +const EndpointExperimentalSpaceSubscribe = + (raw: RawClient["server.experimental"]) => (input: ExperimentalSpaceSubscribeInput) => + preserveEffect()( + raw["space.subscribe"]({ payload: { stream: input["stream"], spaces: input["spaces"] } }).pipe( + Effect.mapError(mapClientError), + ), + ) + +const EndpointExperimentalSpaceUnsubscribe = + (raw: RawClient["server.experimental"]) => (input: ExperimentalSpaceUnsubscribeInput) => + preserveEffect()( + raw["space.unsubscribe"]({ payload: { stream: input["stream"], spaces: input["spaces"] } }).pipe( + Effect.mapError(mapClientError), + ), + ) + +const EndpointExperimentalSpaceReset = (raw: RawClient["server.experimental"]) => () => + preserveEffect()(raw["space.reset"]({}).pipe(Effect.mapError(mapClientError))) + const adaptGroupExperimental = (raw: RawClient["server.experimental"]) => ({ persistentPty: { read: EndpointExperimentalPersistentPtyRead(raw), @@ -1951,6 +2003,14 @@ const adaptGroupExperimental = (raw: RawClient["server.experimental"]) => ({ session: { set: EndpointExperimentalPushSessionSet(raw), remove: EndpointExperimentalPushSessionRemove(raw) }, settings: { set: EndpointExperimentalPushSettingsSet(raw) }, }, + space: { + set: EndpointExperimentalSpaceSet(raw), + delete: EndpointExperimentalSpaceDelete(raw), + sync: EndpointExperimentalSpaceSync(raw), + subscribe: EndpointExperimentalSpaceSubscribe(raw), + unsubscribe: EndpointExperimentalSpaceUnsubscribe(raw), + reset: EndpointExperimentalSpaceReset(raw), + }, }) const EndpointShellList = (raw: RawClient["server.shell"]) => (input?: ShellListInput) => diff --git a/packages/client/src/promise/generated/client.ts b/packages/client/src/promise/generated/client.ts index d15b84aeae8..1992a513297 100644 --- a/packages/client/src/promise/generated/client.ts +++ b/packages/client/src/promise/generated/client.ts @@ -304,6 +304,17 @@ import type { ExperimentalPushSessionRemoveOutput, ExperimentalPushSettingsSetInput, ExperimentalPushSettingsSetOutput, + ExperimentalSpaceSetInput, + ExperimentalSpaceSetOutput, + ExperimentalSpaceDeleteInput, + ExperimentalSpaceDeleteOutput, + ExperimentalSpaceSyncInput, + ExperimentalSpaceSyncOutput, + ExperimentalSpaceSubscribeInput, + ExperimentalSpaceSubscribeOutput, + ExperimentalSpaceUnsubscribeInput, + ExperimentalSpaceUnsubscribeOutput, + ExperimentalSpaceResetOutput, ShellListInput, ShellListOutput, ShellCreateInput, @@ -1981,6 +1992,78 @@ export function make(options: ClientOptions) { ).then((value) => value.data), }, }, + space: { + set: (input: ExperimentalSpaceSetInput, requestOptions?: RequestOptions) => + request( + { + method: "PUT", + path: `/api/experimental/space/${encodeURIComponent(input.space)}/${encodeURIComponent(input.key)}`, + body: { value: input["value"] }, + successStatus: 204, + declaredStatuses: [400, 401], + empty: true, + }, + requestOptions, + ), + delete: (input: ExperimentalSpaceDeleteInput, requestOptions?: RequestOptions) => + request( + { + method: "DELETE", + path: `/api/experimental/space/${encodeURIComponent(input.space)}/${encodeURIComponent(input.key)}`, + successStatus: 204, + declaredStatuses: [400, 401], + empty: true, + }, + requestOptions, + ), + sync: (input: ExperimentalSpaceSyncInput, requestOptions?: RequestOptions) => + request( + { + method: "GET", + path: `/api/experimental/space/${encodeURIComponent(input.space)}`, + query: { cursor: input["cursor"] }, + successStatus: 200, + declaredStatuses: [400, 401], + empty: false, + }, + requestOptions, + ), + subscribe: (input: ExperimentalSpaceSubscribeInput, requestOptions?: RequestOptions) => + request( + { + method: "POST", + path: `/api/experimental/space/subscribe`, + body: { stream: input["stream"], spaces: input["spaces"] }, + successStatus: 204, + declaredStatuses: [400, 401], + empty: true, + }, + requestOptions, + ), + unsubscribe: (input: ExperimentalSpaceUnsubscribeInput, requestOptions?: RequestOptions) => + request( + { + method: "POST", + path: `/api/experimental/space/unsubscribe`, + body: { stream: input["stream"], spaces: input["spaces"] }, + successStatus: 204, + declaredStatuses: [400, 401], + empty: true, + }, + requestOptions, + ), + reset: (requestOptions?: RequestOptions) => + request( + { + method: "POST", + path: `/api/experimental/space/reset`, + successStatus: 204, + declaredStatuses: [400, 401], + empty: true, + }, + requestOptions, + ), + }, migration: { v1: { status: (requestOptions?: RequestOptions) => diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index 1935b81ace4..e89ce76b92a 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -331,6 +331,14 @@ export type SessionStatus = } | { type: "busy" } +export type SpaceName = string + +export type SpaceKey = string + +export type SpaceValue = string + +export type SpaceRevision = number + export type PersistentPtyHandoff = { directory: string; instanceID: string; ticket: string; expiresAt: number } export type AutomationID = string @@ -378,6 +386,10 @@ export type PushLevel = "all" | "attention" | "none" export type PushRegistered = { publicKey: string } +export type SpaceEpoch = string + +export type SpaceCursor = string + export type ReferenceGitSource = { type: "git"; repository: string; branch?: string } export type VcsBranch = { current?: string; default?: string } @@ -1033,6 +1045,8 @@ export type FormMultiselectField1 = { export type FormAnswer1 = { [x: string]: FormValue1 } +export type SpaceEntry = { key: SpaceKey; value: SpaceValue } + export type AutomationTriggerEvery = { type: "every"; every: AutomationDuration; tz?: string } export type ArtifactProvider = { id: string; name: string; capabilities: Array; default: boolean } @@ -1100,7 +1114,7 @@ export type V2EventServerConnected = { metadata?: { [x: string]: any } | undefined location?: LocationPublicRef | undefined type: "server.connected" - data: {} + data: { stream?: string | undefined } } export type ReferenceSource = ReferenceLocalSource | ReferenceGitSource @@ -2227,6 +2241,33 @@ export type ExperimentalMcpEvent = { } } +export type ExperimentalSpaceResync = { + id: EventID + created: number + metadata?: { [x: string]: any } + type: "experimental.space.resync" + location?: LocationRef + data: { space: SpaceName } +} + +export type ExperimentalSpaceUpdated = { + id: EventID + created: number + metadata?: { [x: string]: any } + type: "experimental.space.updated" + location?: LocationRef + data: { space: SpaceName; key: SpaceKey; value: SpaceValue; revision: SpaceRevision } +} + +export type ExperimentalSpaceDeleted = { + id: EventID + created: number + metadata?: { [x: string]: any } + type: "experimental.space.deleted" + location?: LocationRef + data: { space: SpaceName; key: SpaceKey; revision: SpaceRevision } +} + export type SessionToolSuccess = { id: EventID created: number @@ -2359,6 +2400,27 @@ export type FormReplied = { data: { id: FormID; sessionID: string; answer: FormAnswer1 } } +export type SpaceSnapshot = { + type: "snapshot" + space: SpaceName + epoch: SpaceEpoch + revision: SpaceRevision + entries: Array + cursor: SpaceCursor + next?: SpaceCursor +} + +export type SpaceDelta = { + type: "delta" + space: SpaceName + epoch: SpaceEpoch + revision: SpaceRevision + entries: Array + cursor: SpaceCursor + next?: SpaceCursor + deleted: Array +} + export type AutomationTrigger = | AutomationTriggerAt | AutomationTriggerEvery @@ -2819,6 +2881,8 @@ export type ExperimentalJobUpdated = { export type FormFields1 = [FormField1, ...Array] +export type SpacePage = SpaceSnapshot | SpaceDelta + export type PushInfo = { settings: PushSettings; devices: Array; sessions: { [x: string]: PushBell } } export type AgentInfo = { @@ -3124,6 +3188,9 @@ export type V2Event = | McpStatusChanged | McpResourcesChanged | ExperimentalMcpEvent + | ExperimentalSpaceResync + | ExperimentalSpaceUpdated + | ExperimentalSpaceDeleted | V2EventRpc | V2EventServerConnected @@ -4996,6 +5063,31 @@ export type ExperimentalPushSettingsSetInput = { readonly paused: boolean; reado export type ExperimentalPushSettingsSetOutput = { data: PushSettings }["data"] +export type ExperimentalSpaceSetInput = { readonly space: string; readonly key: string; readonly value: string } + +export type ExperimentalSpaceSetOutput = void + +export type ExperimentalSpaceDeleteInput = { readonly space: string; readonly key: string } + +export type ExperimentalSpaceDeleteOutput = void + +export type ExperimentalSpaceSyncInput = { readonly space: string; readonly cursor?: string | undefined } + +export type ExperimentalSpaceSyncOutput = SpacePage + +export type ExperimentalSpaceSubscribeInput = { + readonly stream: string + readonly spaces: ReadonlyArray<{ readonly space: string; readonly cursor: string }> +} + +export type ExperimentalSpaceSubscribeOutput = void + +export type ExperimentalSpaceUnsubscribeInput = { readonly stream: string; readonly spaces: ReadonlyArray } + +export type ExperimentalSpaceUnsubscribeOutput = void + +export type ExperimentalSpaceResetOutput = void + export type ShellListInput = { readonly location?: { readonly directory?: string | undefined } | undefined } export type ShellListOutput = { location: LocationPublicRef; data: Array } diff --git a/packages/client/test/promise.test.ts b/packages/client/test/promise.test.ts index ce894395b23..4d4ac71ad5f 100644 --- a/packages/client/test/promise.test.ts +++ b/packages/client/test/promise.test.ts @@ -69,6 +69,7 @@ test("exposes every standard HTTP API group", () => { "job", "machine", "push", + "space", "migration", "usage", "flag", diff --git a/packages/core/schema.json b/packages/core/schema.json index 1c883fe1544..6916e30db9b 100644 --- a/packages/core/schema.json +++ b/packages/core/schema.json @@ -1,8 +1,8 @@ { "version": "7", "dialect": "sqlite", - "id": "6fdb1fc8-74cd-4f15-8faa-e109d3030da9", - "prevIds": ["74cace2e-430e-4672-bf3b-eba14ae0c399"], + "id": "ea7fb45e-fef3-40b6-8e09-42b781c5bf23", + "prevIds": ["6fdb1fc8-74cd-4f15-8faa-e109d3030da9"], "ddl": [ { "name": "account_state", @@ -92,6 +92,10 @@ "name": "session_v2", "entityType": "tables" }, + { + "name": "space", + "entityType": "tables" + }, { "name": "workspace", "entityType": "tables" @@ -1960,6 +1964,46 @@ "entityType": "columns", "table": "session_v2" }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "space", + "entityType": "columns", + "table": "space" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "key", + "entityType": "columns", + "table": "space" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "value", + "entityType": "columns", + "table": "space" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "revision", + "entityType": "columns", + "table": "space" + }, { "type": "text", "notNull": false, @@ -2239,6 +2283,13 @@ "entityType": "pks", "table": "session_part" }, + { + "columns": ["space", "key"], + "nameExplicit": false, + "name": "space_pk", + "entityType": "pks", + "table": "space" + }, { "columns": ["project_id", "directory"], "nameExplicit": false, @@ -2757,6 +2808,64 @@ "name": "session_v2_time_suspended_idx", "entityType": "indexes", "table": "session_v2" + }, + { + "columns": [ + { + "value": "space", + "isExpression": false + }, + { + "value": "revision", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "name": "space_revision_idx", + "entityType": "indexes", + "table": "space" + }, + { + "columns": [ + { + "value": "space", + "isExpression": false + }, + { + "value": "revision", + "isExpression": false + } + ], + "isUnique": false, + "where": "\"space\".\"value\" is not null", + "origin": "manual", + "name": "space_live_idx", + "entityType": "indexes", + "table": "space" + }, + { + "columns": [ + { + "value": "space", + "isExpression": false + }, + { + "value": "revision", + "isExpression": false + }, + { + "value": "value", + "isExpression": false + } + ], + "isUnique": false, + "where": "\"space\".\"value\" is null", + "origin": "manual", + "name": "space_tombstone_idx", + "entityType": "indexes", + "table": "space" } ], "renames": [] diff --git a/packages/core/src/database/migration.gen.ts b/packages/core/src/database/migration.gen.ts index 51ba41aa2b3..69952394f20 100644 --- a/packages/core/src/database/migration.gen.ts +++ b/packages/core/src/database/migration.gen.ts @@ -63,6 +63,7 @@ import m60 from "./migration/20261116181958_automation_event_position.js" import m61 from "./migration/20261116213417_automation_active_index.js" import m62 from "./migration/20261119211416_machine.js" import m63 from "./migration/20261120004954_machine-key.js" +import m64 from "./migration/20261123115523_space.js" export const migrations = [ m00, @@ -129,4 +130,5 @@ export const migrations = [ m61, m62, m63, + m64, ] satisfies DatabaseMigration.Migration[] diff --git a/packages/core/src/database/migration/20261123115523_space.ts b/packages/core/src/database/migration/20261123115523_space.ts new file mode 100644 index 00000000000..5df2fa13691 --- /dev/null +++ b/packages/core/src/database/migration/20261123115523_space.ts @@ -0,0 +1,28 @@ +import { Effect } from "effect" +import type { DatabaseMigration } from "../migration.js" + +const migration: DatabaseMigration.Migration = { + id: "20261123115523_space", + up(tx) { + return Effect.gen(function* () { + yield* tx.run(` + CREATE TABLE \`space\` ( + \`space\` text NOT NULL, + \`key\` text NOT NULL, + \`value\` text, + \`revision\` integer NOT NULL, + CONSTRAINT \`space_pk\` PRIMARY KEY(\`space\`, \`key\`) + ); + `) + yield* tx.run(`CREATE INDEX \`space_revision_idx\` ON \`space\` (\`space\`,\`revision\`);`) + yield* tx.run( + `CREATE INDEX \`space_live_idx\` ON \`space\` (\`space\`,\`revision\`) WHERE "space"."value" is not null;`, + ) + yield* tx.run( + `CREATE INDEX \`space_tombstone_idx\` ON \`space\` (\`space\`,\`revision\`,\`value\`) WHERE "space"."value" is null;`, + ) + }) + }, +} + +export default migration diff --git a/packages/core/src/database/schema.gen.ts b/packages/core/src/database/schema.gen.ts index cf46e80f0a5..bffa271a095 100644 --- a/packages/core/src/database/schema.gen.ts +++ b/packages/core/src/database/schema.gen.ts @@ -296,6 +296,15 @@ const schema: Omit = { CONSTRAINT \`fk_session_v2_project_id_project_id_fk\` FOREIGN KEY (\`project_id\`) REFERENCES \`project\`(\`id\`) ON DELETE CASCADE ); `) + yield* tx.run(` + CREATE TABLE \`space\` ( + \`space\` text NOT NULL, + \`key\` text NOT NULL, + \`value\` text, + \`revision\` integer NOT NULL, + CONSTRAINT \`space_pk\` PRIMARY KEY(\`space\`, \`key\`) + ); + `) yield* tx.run(` CREATE TABLE \`workspace\` ( \`id\` text PRIMARY KEY, @@ -356,6 +365,13 @@ const schema: Omit = { yield* tx.run( `CREATE INDEX \`session_v2_time_suspended_idx\` ON \`session_v2\` (\`time_suspended\`) WHERE "session_v2"."time_suspended" is not null;`, ) + yield* tx.run(`CREATE INDEX \`space_revision_idx\` ON \`space\` (\`space\`,\`revision\`);`) + yield* tx.run( + `CREATE INDEX \`space_live_idx\` ON \`space\` (\`space\`,\`revision\`) WHERE "space"."value" is not null;`, + ) + yield* tx.run( + `CREATE INDEX \`space_tombstone_idx\` ON \`space\` (\`space\`,\`revision\`,\`value\`) WHERE "space"."value" is null;`, + ) }) }, } diff --git a/packages/core/src/space.ts b/packages/core/src/space.ts new file mode 100644 index 00000000000..d16508710cd --- /dev/null +++ b/packages/core/src/space.ts @@ -0,0 +1,167 @@ +export * as SpaceRows from "./space.js" + +import { and, asc, count, eq, gt, isNotNull, isNull, lte, max, sql } from "drizzle-orm" +import { Effect } from "effect" +import type { Space } from "@opencode/schema/space" +import type { Database } from "./database/database.js" +import { SpaceTable } from "./space/sql.js" + +type Db = Database.Interface["db"] + +// Client space names need at least one character, so the empty space can hold the server's own rows: the epoch and +// each space's floor, a revision as decimal text. +const Meta = "" +const floorKey = (space: Space.Name) => `floor:${space}` + +// One past the space's highest revision, read by the statement that writes the row. SQLite runs one write at a time, +// so revisions follow commit order, and purges keep the newest tombstone, so none is reissued after a restart. +const next = (space: Space.Name) => + sql`(SELECT coalesce(max(${SpaceTable.revision}), 0) + 1 FROM ${SpaceTable} WHERE ${SpaceTable.space} = ${space})` + +/** Stores the value and returns the revision it was given. */ +export const set = (db: Db, space: Space.Name, key: Space.Key, value: Space.Value) => + db + .insert(SpaceTable) + .values({ space, key, value, revision: next(space) }) + .onConflictDoUpdate({ + target: [SpaceTable.space, SpaceTable.key], + set: { value, revision: sql`excluded.${sql.identifier("revision")}` }, + }) + .returning({ revision: SpaceTable.revision }) + .get() + .pipe( + Effect.orDie, + Effect.flatMap((row) => (row ? Effect.succeed(row.revision) : Effect.die(new Error("Upsert returned no row")))), + ) + +/** Turns a stored value into a tombstone; returns its revision, or undefined when no value was stored. */ +export const remove = (db: Db, space: Space.Name, key: Space.Key) => + db + .update(SpaceTable) + .set({ value: null, revision: next(space) }) + .where(and(eq(SpaceTable.space, space), eq(SpaceTable.key, key), isNotNull(SpaceTable.value))) + .returning({ revision: SpaceTable.revision }) + .get() + .pipe( + Effect.orDie, + Effect.map((row) => row?.revision), + ) + +/** Tombstones a space keeps once `purge` runs. */ +export const TombstoneLimit = 10_000 + +/** Purges the space's oldest tombstones past `limit` and raises its floor to the highest one purged. */ +export const purge = (db: Db, space: Space.Name, limit = TombstoneLimit) => + db + .transaction((tx) => + Effect.gen(function* () { + const tombstones = and(eq(SpaceTable.space, space), isNull(SpaceTable.value)) + const stored = (yield* tx.select({ count: count() }).from(SpaceTable).where(tombstones).get())?.count ?? 0 + if (stored <= limit) return + // The newest tombstones stay, so the space's highest revision does not move. + const purged = yield* tx + .select({ revision: SpaceTable.revision }) + .from(SpaceTable) + .where(tombstones) + .orderBy(asc(SpaceTable.revision)) + .limit(1) + .offset(stored - limit - 1) + .get() + if (!purged) return yield* Effect.die(new Error("Space tombstones changed inside their transaction")) + yield* tx + .delete(SpaceTable) + .where(and(tombstones, lte(SpaceTable.revision, purged.revision))) + .run() + yield* tx + .insert(SpaceTable) + .values({ space: Meta, key: floorKey(space), value: String(purged.revision), revision: 0 }) + .onConflictDoUpdate({ target: [SpaceTable.space, SpaceTable.key], set: { value: String(purged.revision) } }) + .run() + }), + ) + .pipe(Effect.orDie) + +/** The highest purged revision of the space, 0 before any: a delta needs a cursor at or above it. */ +export const floor = (db: Db, space: Space.Name) => + db + .select({ value: SpaceTable.value }) + .from(SpaceTable) + .where(and(eq(SpaceTable.space, Meta), eq(SpaceTable.key, floorKey(space)))) + .get() + .pipe( + Effect.orDie, + Effect.map((row) => Number(row?.value ?? 0)), + ) + +/** The space's highest revision, 0 before its first write. */ +export const head = (db: Db, space: Space.Name) => + db + .select({ revision: max(SpaceTable.revision) }) + .from(SpaceTable) + .where(eq(SpaceTable.space, space)) + .get() + .pipe( + Effect.orDie, + 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) + +/** 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), + ), + ) + .orderBy(asc(SpaceTable.revision)) + .limit(limit) + .all() + .pipe(Effect.orDie) + +/** This database's epoch: created once in the empty space, which no client can name, then kept. */ +export const epoch = (db: Db) => + db + .insert(SpaceTable) + .values({ space: Meta, key: "epoch", value: crypto.randomUUID(), revision: 0 }) + .onConflictDoNothing() + .run() + .pipe( + Effect.andThen( + db + .select({ value: SpaceTable.value }) + .from(SpaceTable) + .where(and(eq(SpaceTable.space, Meta), eq(SpaceTable.key, "epoch"))) + .get(), + ), + Effect.orDie, + Effect.flatMap((row) => + typeof row?.value === "string" ? Effect.succeed(row.value) : Effect.die(new Error("Space epoch is missing")), + ), + ) + +/** Replaces the epoch, so every client's cursor becomes unusable and it reads a fresh snapshot, as after a restore. */ +export const resetEpoch = (db: Db) => { + const value = crypto.randomUUID() + return db + .insert(SpaceTable) + .values({ space: Meta, key: "epoch", value, revision: 0 }) + .onConflictDoUpdate({ target: [SpaceTable.space, SpaceTable.key], set: { value } }) + .run() + .pipe(Effect.orDie, Effect.as(value)) +} diff --git a/packages/core/src/space/sql.ts b/packages/core/src/space/sql.ts new file mode 100644 index 00000000000..e22ec602168 --- /dev/null +++ b/packages/core/src/space/sql.ts @@ -0,0 +1,29 @@ +import { sql } from "drizzle-orm" +import { index, integer, primaryKey, sqliteTable, text } from "drizzle-orm/sqlite-core" +import type { Space } from "@opencode/schema/space" + +/** + * Client-defined state, separate from the server's own `kv` table: one row per key with the revision of its last + * write. A deleted key keeps its row with a NULL value, so catch-up can report the deletion; each space keeps only its + * newest tombstones, so its highest revision is never reissued. + */ +export const SpaceTable = sqliteTable( + "space", + { + space: text().$type().notNull(), + key: text().$type().notNull(), + value: text().$type(), + revision: integer().$type().notNull(), + }, + (table) => [ + primaryKey({ columns: [table.space, table.key] }), + index("space_revision_idx").on(table.space, table.revision), + index("space_live_idx") + .on(table.space, table.revision) + .where(sql`${table.value} is not null`), + // `value` makes counting and purging a space's tombstones read the index alone. + index("space_tombstone_idx") + .on(table.space, table.revision, table.value) + .where(sql`${table.value} is null`), + ], +) diff --git a/packages/core/test/space.test.ts b/packages/core/test/space.test.ts new file mode 100644 index 00000000000..b6c45fbabe0 --- /dev/null +++ b/packages/core/test/space.test.ts @@ -0,0 +1,180 @@ +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 { 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 { 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 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 durableObject = testEffect( + Database.layerFromClient.pipe( + Layer.provide(sqliteLayer({ storage: makeDurableObjectStorage() })), + Layer.provide(tempGlobalLayer), + ), +) + +describe.each([ + ["local SQLite", local], + ["Durable Object storage", durableObject], +] as const)("Space over %s", (_, it) => { + it.effect("numbers each space's writes on its own and keeps deletes as tombstones", () => + Effect.gen(function* () { + const db = (yield* Database.Service).db + const rows = db.select().from(SpaceTable).orderBy(asc(SpaceTable.space), asc(SpaceTable.key)).all() + expect(yield* SpaceRows.head(db, "app")).toBe(0) + expect(yield* SpaceRows.set(db, "app", "a", "1")).toBe(1) + expect(yield* SpaceRows.set(db, "app", "b", '{"n":1}')).toBe(2) + expect(yield* SpaceRows.set(db, "other", "a", "x")).toBe(1) + expect(yield* SpaceRows.set(db, "app", "a", "2")).toBe(3) + expect(yield* SpaceRows.remove(db, "app", "b")).toBe(4) + // Removing a missing or already removed key writes nothing and takes no revision. + expect(yield* SpaceRows.remove(db, "app", "b")).toBeUndefined() + expect(yield* SpaceRows.remove(db, "app", "never")).toBeUndefined() + expect(yield* rows).toEqual([ + { space: "app", key: "a", value: "2", revision: 3 }, + { space: "app", key: "b", value: null, revision: 4 }, + { 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.set(db, "app", "b", "true")).toBe(5) + }), + ) + + it.effect("keeps a space's newest tombstones and raises its floor to the highest purged one", () => + Effect.gen(function* () { + const db = (yield* Database.Service).db + const remove = (space: string, key: string, limit: number) => + SpaceRows.remove(db, space, key).pipe(Effect.tap(SpaceRows.purge(db, space, limit))) + const tombstones = db + .select({ key: SpaceTable.key, revision: SpaceTable.revision }) + .from(SpaceTable) + .where(and(eq(SpaceTable.space, "pruned"), isNull(SpaceTable.value))) + .orderBy(asc(SpaceTable.revision)) + .all() + yield* Effect.forEach(["a", "b", "c", "d", "e", "f"], (key) => SpaceRows.set(db, "pruned", key, key), { + discard: true, + }) + yield* SpaceRows.set(db, "kept", "a", "1") + yield* remove("kept", "a", 2) + expect(yield* remove("pruned", "a", 2)).toBe(7) + expect(yield* remove("pruned", "b", 2)).toBe(8) + expect(yield* SpaceRows.floor(db, "pruned")).toBe(0) + + // The third tombstone passes the limit of 2: the oldest goes. + expect(yield* remove("pruned", "c", 2)).toBe(9) + expect(yield* tombstones).toEqual([ + { key: "b", revision: 8 }, + { key: "c", revision: 9 }, + ]) + expect(yield* SpaceRows.floor(db, "pruned")).toBe(7) + expect(yield* remove("pruned", "d", 2)).toBe(10) + expect(yield* SpaceRows.floor(db, "pruned")).toBe(8) + // Further past the limit, the purge goes straight back down to it, and the floor only rises. + expect(yield* remove("pruned", "e", 1)).toBe(11) + expect(yield* tombstones).toEqual([{ key: "e", revision: 11 }]) + 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([ + { 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* SpaceRows.floor(db, "kept")).toBe(0) + expect(yield* SpaceRows.head(db, "pruned")).toBe(11) + expect(yield* SpaceRows.set(db, "pruned", "a", "1")).toBe(12) + // A new epoch leaves floors as they are. + yield* SpaceRows.resetEpoch(db) + expect(yield* SpaceRows.floor(db, "pruned")).toBe(10) + }), + ) +}) + +local.effect("reads and writes a space through its indexes: deltas on the revision index, snapshots on live rows", () => + Effect.gen(function* () { + const db = (yield* Database.Service).db + const client = yield* SqlClient.SqlClient + yield* Effect.forEach(["a", "b", "c"], (key) => SpaceRows.set(db, "app", key, key), { discard: true }) + yield* SpaceRows.set(db, "other", "a", "1") + yield* SpaceRows.remove(db, "app", "c") + statements.length = 0 + + yield* SpaceRows.set(db, "app", "a", "again") + // 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 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))), + ) + const revisionIndex = "SEARCH space USING COVERING INDEX space_revision_idx (space=?)" + const tombstoneIndex = "SEARCH space USING COVERING INDEX space_tombstone_idx (space=?)" + const primaryKey = "SEARCH space USING INDEX sqlite_autoindex_space_1 (space=? AND key=?)" + expect(plans).toEqual([ + // set: the next revision from the end of the space's index range. + ["SCALAR SUBQUERY 1", revisionIndex], + // remove: the row by primary key, and the next revision. + [primaryKey, "SCALAR SUBQUERY 1", revisionIndex], + // purge: the tombstones counted, the highest one to purge found and the purge, all on their own index. + [tombstoneIndex], + [tombstoneIndex], + ["SEARCH space USING INDEX space_tombstone_idx (space=? AND revision?)"], + // live + ["SEARCH space USING INDEX space_live_idx (space=? AND revision>? AND revision>( + subscribe: < + Type extends Exclude, + >( options?: SubscribeOptions, ) => streams( diff --git a/packages/plugin/src/promise/event.ts b/packages/plugin/src/promise/event.ts index 1bf00a8b5c6..143b27d8641 100644 --- a/packages/plugin/src/promise/event.ts +++ b/packages/plugin/src/promise/event.ts @@ -1,7 +1,8 @@ import type { OpenCodeEvent } from "@opencode/client" import type { SelectedEvent, SubscribeOptions } from "@opencode/client/promise/api" -type EventType = Exclude +// Space events go only to event stream subscribers of their space, never to plugins. +type EventType = Exclude export interface EventDomain { readonly subscribe: ( diff --git a/packages/protocol/openapi.json b/packages/protocol/openapi.json index 8b3baaadc2d..c33b4137d72 100644 --- a/packages/protocol/openapi.json +++ b/packages/protocol/openapi.json @@ -14913,6 +14913,352 @@ } } }, + "/api/experimental/space/{space}/{key}": { + "put": { + "tags": ["experimental"], + "operationId": "experimental.space.set", + "parameters": [ + { + "name": "space", + "in": "path", + "schema": { + "$ref": "#/components/schemas/Space.Name" + }, + "required": true + }, + { + "name": "key", + "in": "path", + "schema": { + "$ref": "#/components/schemas/Space.Key" + }, + "required": true + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestErrorEncoded" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedErrorEncoded" + } + } + } + } + }, + "description": "Store a client-defined string of at most 1 MiB of UTF-8, replacing any previous value, and send it to the space's subscribers unchanged. The server does not interpret it; its format, such as JSON text, is up to the client. 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": "Set value", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "value": { + "$ref": "#/components/schemas/Space.Value" + } + }, + "required": ["value"], + "additionalProperties": false + } + } + }, + "required": true + } + }, + "delete": { + "tags": ["experimental"], + "operationId": "experimental.space.delete", + "parameters": [ + { + "name": "space", + "in": "path", + "schema": { + "$ref": "#/components/schemas/Space.Name" + }, + "required": true + }, + { + "name": "key", + "in": "path", + "schema": { + "$ref": "#/components/schemas/Space.Key" + }, + "required": true + } + ], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestErrorEncoded" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedErrorEncoded" + } + } + } + } + }, + "description": "Remove a stored value and tell the space's subscribers. Removing an unset key succeeds. 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": "Delete value" + } + }, + "/api/experimental/space/{space}": { + "get": { + "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" + } + ] + }, + "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." + } + ], + "security": [], + "responses": { + "200": { + "description": "Space.Page", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Space.Page" + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestErrorEncoded" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedErrorEncoded" + } + } + } + } + }, + "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" + } + }, + "/api/experimental/space/subscribe": { + "post": { + "tags": ["experimental"], + "operationId": "experimental.space.subscribe", + "parameters": [], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestErrorEncoded" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedErrorEncoded" + } + } + } + } + }, + "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.", + "summary": "Subscribe stream", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "stream": { + "type": "string", + "description": "The stream ID from the stream's server.connected event." + }, + "spaces": { + "type": "array", + "items": { + "type": "object", + "properties": { + "space": { + "$ref": "#/components/schemas/Space.Name" + }, + "cursor": { + "$ref": "#/components/schemas/Space.Cursor" + } + }, + "required": ["space", "cursor"], + "additionalProperties": false + } + } + }, + "required": ["stream", "spaces"], + "additionalProperties": false + } + } + }, + "required": true + } + } + }, + "/api/experimental/space/unsubscribe": { + "post": { + "tags": ["experimental"], + "operationId": "experimental.space.unsubscribe", + "parameters": [], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestErrorEncoded" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedErrorEncoded" + } + } + } + } + }, + "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.", + "summary": "Unsubscribe stream", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "stream": { + "type": "string", + "description": "The stream ID from the stream's server.connected event." + }, + "spaces": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Space.Name" + } + } + }, + "required": ["stream", "spaces"], + "additionalProperties": false + } + } + }, + "required": true + } + } + }, + "/api/experimental/space/reset": { + "post": { + "tags": ["experimental"], + "operationId": "experimental.space.reset", + "parameters": [], + "security": [], + "responses": { + "204": { + "description": "" + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestErrorEncoded" + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedErrorEncoded" + } + } + } + } + }, + "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.", + "summary": "Reset revisions" + } + }, "/api/shell": { "get": { "tags": ["shell"], @@ -27322,6 +27668,127 @@ "Snapshot.ID": { "type": "string" }, + "Space.Cursor": { + "type": "string" + }, + "Space.Cursor_1": { + "type": "string", + "description": "Covers every change up to this page; save it to subscribe or sync from." + }, + "Space.Delta": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["delta"] + }, + "space": { + "$ref": "#/components/schemas/Space.Name" + }, + "epoch": { + "$ref": "#/components/schemas/Space.Epoch" + }, + "revision": { + "$ref": "#/components/schemas/Space.Revision" + }, + "entries": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Space.Entry" + } + }, + "cursor": { + "$ref": "#/components/schemas/Space.Cursor_1" + }, + "next": { + "$ref": "#/components/schemas/Space.Cursor" + }, + "deleted": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Space.Key" + } + } + }, + "required": ["type", "space", "epoch", "revision", "entries", "cursor", "deleted"], + "additionalProperties": false + }, + "Space.Entry": { + "type": "object", + "properties": { + "key": { + "$ref": "#/components/schemas/Space.Key" + }, + "value": { + "$ref": "#/components/schemas/Space.Value" + } + }, + "required": ["key", "value"], + "additionalProperties": false + }, + "Space.Epoch": { + "type": "string" + }, + "Space.Key": { + "type": "string", + "minLength": 1, + "maxLength": 1024 + }, + "Space.Name": { + "type": "string", + "pattern": "^[A-Za-z0-9._-]{1,128}$", + "description": "Client-chosen namespace: 1-128 letters, digits, '.', '_' or '-'." + }, + "Space.Page": { + "anyOf": [ + { + "$ref": "#/components/schemas/Space.Snapshot" + }, + { + "$ref": "#/components/schemas/Space.Delta" + } + ] + }, + "Space.Revision": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "Space.Snapshot": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["snapshot"] + }, + "space": { + "$ref": "#/components/schemas/Space.Name" + }, + "epoch": { + "$ref": "#/components/schemas/Space.Epoch" + }, + "revision": { + "$ref": "#/components/schemas/Space.Revision" + }, + "entries": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Space.Entry" + } + }, + "cursor": { + "$ref": "#/components/schemas/Space.Cursor_1" + }, + "next": { + "$ref": "#/components/schemas/Space.Cursor" + } + }, + "required": ["type", "space", "epoch", "revision", "entries", "cursor"], + "additionalProperties": false + }, + "Space.Value": { + "type": "string" + }, "TokenUsage.Info": { "type": "object", "properties": { @@ -27920,6 +28387,15 @@ { "$ref": "#/components/schemas/experimental.mcp.event" }, + { + "$ref": "#/components/schemas/experimental.space.resync" + }, + { + "$ref": "#/components/schemas/experimental.space.updated" + }, + { + "$ref": "#/components/schemas/experimental.space.deleted" + }, { "$ref": "#/components/schemas/V2Event.rpc" }, @@ -27992,9 +28468,21 @@ "enum": ["server.connected"] }, "data": { - "not": { - "type": "null" - } + "type": "object", + "properties": { + "stream": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "This stream's random ID, which addresses it, e.g. in experimental.space.subscribe." + } + }, + "additionalProperties": false } }, "required": ["id", "type", "data"], @@ -28782,6 +29270,120 @@ "required": ["id", "created", "type", "data"], "additionalProperties": false }, + "experimental.space.deleted": { + "type": "object", + "properties": { + "id": { + "$ref": "#/components/schemas/Event.ID" + }, + "created": { + "type": "number" + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": ["experimental.space.deleted"] + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "space": { + "$ref": "#/components/schemas/Space.Name" + }, + "key": { + "$ref": "#/components/schemas/Space.Key" + }, + "revision": { + "$ref": "#/components/schemas/Space.Revision" + } + }, + "required": ["space", "key", "revision"], + "additionalProperties": false + } + }, + "required": ["id", "created", "type", "data"], + "additionalProperties": false + }, + "experimental.space.resync": { + "type": "object", + "properties": { + "id": { + "$ref": "#/components/schemas/Event.ID" + }, + "created": { + "type": "number" + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": ["experimental.space.resync"] + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "space": { + "$ref": "#/components/schemas/Space.Name" + } + }, + "required": ["space"], + "additionalProperties": false + } + }, + "required": ["id", "created", "type", "data"], + "additionalProperties": false + }, + "experimental.space.updated": { + "type": "object", + "properties": { + "id": { + "$ref": "#/components/schemas/Event.ID" + }, + "created": { + "type": "number" + }, + "metadata": { + "type": "object" + }, + "type": { + "type": "string", + "enum": ["experimental.space.updated"] + }, + "location": { + "$ref": "#/components/schemas/Location.Ref" + }, + "data": { + "type": "object", + "properties": { + "space": { + "$ref": "#/components/schemas/Space.Name" + }, + "key": { + "$ref": "#/components/schemas/Space.Key" + }, + "value": { + "$ref": "#/components/schemas/Space.Value" + }, + "revision": { + "$ref": "#/components/schemas/Space.Revision" + } + }, + "required": ["space", "key", "value", "revision"], + "additionalProperties": false + } + }, + "required": ["id", "created", "type", "data"], + "additionalProperties": false + }, "filesystem.changed": { "type": "object", "properties": { diff --git a/packages/protocol/src/groups/event.ts b/packages/protocol/src/groups/event.ts index 3d8423dd90f..741ee779a0c 100644 --- a/packages/protocol/src/groups/event.ts +++ b/packages/protocol/src/groups/event.ts @@ -1,3 +1,4 @@ +import { Space } from "@opencode/schema/space" import { Event } from "@opencode/schema/event" import { EventManifest } from "@opencode/schema/event-manifest" import { Location } from "@opencode/schema/location" @@ -23,6 +24,8 @@ const rpcEvent = Schema.Struct({ const schema = >(definitions: Definitions) => Schema.Union([ ...definitions, + // Sent only by the event feed to streams subscribed to their space, never on the bus, so plugins do not see them. + ...Space.Event.Definitions, rpcEvent, ...(definitions.some((definition) => definition.type === "server.connected") ? [] @@ -30,7 +33,12 @@ const schema = >(definitions Schema.Struct({ ...fields, type: Schema.Literal("server.connected"), - data: Schema.Struct({}), + data: Schema.Struct({ + // Optional for clients and fixtures that predate it; the server always sends it. + stream: Schema.optional(Schema.String).annotate({ + description: "This stream's random ID, which addresses it, e.g. in experimental.space.subscribe.", + }), + }), }).annotate({ identifier: "V2Event.server.connected" }), ]), ]).annotate({ identifier: "V2Event" }) diff --git a/packages/protocol/src/groups/experimental.ts b/packages/protocol/src/groups/experimental.ts index 8e9bcf43d19..17f385fffd7 100644 --- a/packages/protocol/src/groups/experimental.ts +++ b/packages/protocol/src/groups/experimental.ts @@ -4,6 +4,7 @@ import { BrowserTunnelEndpoint } from "./experimental/browser-tunnel.js" import { AutomationEndpoints } from "./automation.js" import { JobEndpoints } from "./job.js" import { MachineEndpoints } from "./machine.js" +import { SpaceEndpoints } from "./space.js" import { MediaGetEndpoint } from "./media.js" import { PersistentPtyGroup } from "./persistent-pty.js" import { PushEndpoints } from "./push.js" @@ -18,4 +19,5 @@ export const ExperimentalGroup = PersistentPtyGroup.add( ...JobEndpoints, ...MachineEndpoints, ...PushEndpoints, + ...SpaceEndpoints, ) diff --git a/packages/protocol/src/groups/space.ts b/packages/protocol/src/groups/space.ts new file mode 100644 index 00000000000..03a2d7033a2 --- /dev/null +++ b/packages/protocol/src/groups/space.ts @@ -0,0 +1,93 @@ +import { Space } from "@opencode/schema/space" +import { InvalidRequestError } from "../errors.js" +import { Schema } from "effect" +import { HttpApiEndpoint, HttpApiSchema, OpenApi } from "effect/http-api" + +const params = { space: Space.Name, key: Space.Key } +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.`, + // 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.put("space.set", "/api/experimental/space/:space/:key", { + params, + payload: Schema.Struct({ value: Space.Value }), + error: InvalidRequestError, + success: HttpApiSchema.NoContent, + }).annotateMerge( + annotations( + "set", + "Set value", + "Store a client-defined string of at most 1 MiB of UTF-8, replacing any previous value, and send it to the space's subscribers unchanged. The server does not interpret it; its format, such as JSON text, is up to the client.", + ), + ), + HttpApiEndpoint.delete("space.delete", "/api/experimental/space/:space/:key", { + params, + success: HttpApiSchema.NoContent, + }).annotateMerge( + annotations( + "delete", + "Delete value", + "Remove a stored value and tell the space's subscribers. Removing an unset key succeeds.", + ), + ), + 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.", + }), + }), + success: 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.", + ), + ), + 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 })), + }), + error: InvalidRequestError, + success: HttpApiSchema.NoContent, + }).annotateMerge( + 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.", + ), + ), + 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), + }), + error: InvalidRequestError, + success: HttpApiSchema.NoContent, + }).annotateMerge( + 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.", + ), + ), + HttpApiEndpoint.post("space.reset", "/api/experimental/space/reset", { + success: HttpApiSchema.NoContent, + }).annotateMerge( + annotations( + "reset", + "Reset revisions", + "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.", + ), + ), +] as const diff --git a/packages/schema/src/space.ts b/packages/schema/src/space.ts new file mode 100644 index 00000000000..39d7eedf5f3 --- /dev/null +++ b/packages/schema/src/space.ts @@ -0,0 +1,80 @@ +export * as Space from "./space.js" + +import { Schema } from "effect" +import { ephemeral, inventory } from "./event.js" +import { NonNegativeInt, optional } from "./schema.js" + +export const Name = Schema.String.check(Schema.isPattern(/^[A-Za-z0-9._-]{1,128}$/u)).annotate({ + identifier: "Space.Name", + description: "Client-chosen namespace: 1-128 letters, digits, '.', '_' or '-'.", +}) +export type Name = typeof Name.Type + +export const Key = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(1024)).annotate({ + identifier: "Space.Key", +}) +export type Key = typeof Key.Type + +/** An opaque string the server stores and sends back unchanged; its format, such as JSON text, is up to the client. */ +export const Value = Schema.String.annotate({ identifier: "Space.Value" }) +export type Value = typeof Value.Type + +/** A value always goes out as one event, so a write is capped at 1 MiB of UTF-8. */ +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" }) + +/** 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 + +/** Identifies the database that issued a space's revisions; a revision is only usable with the same epoch. */ +export const Epoch = Schema.String.annotate({ identifier: "Space.Epoch" }) + +/** An opaque position in a space, issued by the server. Clients save a page's `cursor` and pass back `next` as is. */ +export const Cursor = Schema.String.annotate({ identifier: "Space.Cursor" }) + +const page = { + space: Name, + epoch: Epoch, + revision: Revision, + entries: Schema.Array(Entry), + cursor: Cursor.annotate({ description: "Covers every change up to this page; save it to subscribe or sync from." }), + 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. */ +export interface Snapshot extends Schema.Schema.Type {} +export const Snapshot = Schema.Struct({ type: Schema.tag("snapshot"), ...page }).annotate({ + identifier: "Space.Snapshot", +}) + +/** A sync page with the final values of the keys changed after the previous page, and the keys deleted since. */ +export interface Delta extends Schema.Schema.Type {} +export const Delta = Schema.Struct({ type: Schema.tag("delta"), ...page, deleted: Schema.Array(Key) }).annotate({ + identifier: "Space.Delta", +}) + +export const Page = Schema.Union([Snapshot, Delta]).pipe( + Schema.toTaggedUnion("type"), + Schema.annotate({ identifier: "Space.Page" }), +) +export type Page = typeof Page.Type + +/** Sent instead of the changes when they no longer fit one batch or the cursor is unusable: sync and subscribe again. */ +const Resync = ephemeral({ type: "experimental.space.resync", schema: { space: Name } }) +const Updated = ephemeral({ + type: "experimental.space.updated", + schema: { space: Name, key: Key, value: Value, revision: Revision }, +}) +const Deleted = ephemeral({ + type: "experimental.space.deleted", + schema: { space: Name, key: Key, revision: Revision }, +}) +export const Event = { + Resync, + Updated, + Deleted, + Definitions: inventory(Resync, Updated, Deleted), +} diff --git a/packages/server/src/event-feed.ts b/packages/server/src/event-feed.ts index 19cf5f014c1..3e5ae3a5080 100644 --- a/packages/server/src/event-feed.ts +++ b/packages/server/src/event-feed.ts @@ -3,7 +3,7 @@ export * as EventFeed from "./event-feed" import { Bus } from "@opencode/core/bus" import { Event } from "@opencode/schema/event" import { isOpenCodeEvent, type OpenCodeEvent } from "@opencode/protocol/groups/event" -import { Cause, Context, Effect, Layer, Queue, Schema, Scope, Stream } from "effect" +import { Cause, Context, Effect, Exit, Layer, Queue, Schema, Scope, Stream } from "effect" export const SubscriberCapacity = 4_096 @@ -21,7 +21,21 @@ export class EncodingError extends Schema.TaggedError()("EventFee export type Error = SubscriberOverflowError | EncodingError export interface Interface { - readonly subscribe: (types?: ReadonlyArray) => Effect.Effect, never, Scope.Scope> + /** Opens a stream of encoded events, with the random ID that addresses it, e.g. to subscribe it to more events. */ + readonly subscribe: ( + types?: ReadonlyArray, + ) => Effect.Effect<{ readonly id: string; readonly events: Stream.Stream }, never, Scope.Scope> +} + +/** + * Adds events from outside the bus. `open` runs once for each stream, with its ID and a `send` that reaches that + * stream, whatever its `types`, until the stream closes along with the scope `open` gets. + */ +export interface Extension { + readonly open: ( + stream: string, + send: (event: OpenCodeEvent) => Effect.Effect, + ) => Effect.Effect } export class Service extends Context.Service()("@opencode/server/EventFeed") {} @@ -32,7 +46,11 @@ export function frame(event: OpenCodeEvent) { export const make = Effect.fn("EventFeed.make")(function* ( observe: (subscriber: Bus.Subscriber) => Effect.Effect, - options?: { readonly capacity?: number; readonly encode?: (event: OpenCodeEvent) => string }, + options?: { + readonly capacity?: number + readonly encode?: (event: OpenCodeEvent) => string + readonly extensions?: ReadonlyArray + }, ) { const capacity = options?.capacity ?? SubscriberCapacity const render = options?.encode ?? frame @@ -45,6 +63,12 @@ export const make = Effect.fn("EventFeed.make")(function* ( for (const subscriber of current) Queue.failCauseUnsafe(subscriber, Cause.fail(error)) }) + const offer = (subscriber: Queue.Queue, encoded: string) => { + if (Queue.offerUnsafe(subscriber, encoded)) return + subscribers.delete(subscriber) + Queue.failCauseUnsafe(subscriber, Cause.fail(new SubscriberOverflowError({ capacity }))) + } + const publish = Effect.fnUntraced(function* (event: Event.Payload) { if (!isOpenCodeEvent(event)) return let encoded: string | undefined @@ -63,9 +87,7 @@ export const make = Effect.fn("EventFeed.make")(function* ( ), ) if (encoded === undefined) return - if (Queue.offerUnsafe(subscriber, encoded)) continue - subscribers.delete(subscriber) - Queue.failCauseUnsafe(subscriber, Cause.fail(new SubscriberOverflowError({ capacity }))) + offer(subscriber, encoded) } }) @@ -74,20 +96,56 @@ export const make = Effect.fn("EventFeed.make")(function* ( return Service.of({ subscribe: (types) => - Effect.acquireRelease( - Queue.dropping(capacity).pipe( - Effect.tap((queue) => Effect.sync(() => subscribers.set(queue, types?.length ? new Set(types) : undefined))), - ), - (queue) => - Effect.sync(() => subscribers.delete(queue)).pipe(Effect.andThen(Queue.shutdown(queue)), Effect.asVoid), - ).pipe(Effect.map(Stream.fromQueue)), + Effect.gen(function* () { + const queue = yield* Effect.acquireRelease( + Queue.dropping(capacity).pipe( + Effect.tap((queue) => + Effect.sync(() => subscribers.set(queue, types?.length ? new Set(types) : undefined)), + ), + ), + (queue) => + Effect.sync(() => subscribers.delete(queue)).pipe(Effect.andThen(Queue.shutdown(queue)), Effect.asVoid), + ) + const id = crypto.randomUUID() + // An extension never fails the stream: an event it cannot encode is dropped, and a failed `open` only loses + // that extension's events for this stream. + const send = (event: OpenCodeEvent) => + Effect.suspend(() => { + if (!subscribers.has(queue)) return Effect.void + return Effect.try(() => render(event)).pipe( + Effect.flatMap((encoded) => Effect.sync(() => offer(queue, encoded))), + Effect.catchCause((cause) => + Effect.logError("Failed to encode extension event", { type: event.type, cause }), + ), + ) + }) + const scope = yield* Scope.Scope + yield* Effect.forEach( + options?.extensions ?? [], + (extension) => + Effect.gen(function* () { + const child = yield* Scope.fork(scope) + yield* extension.open(id, send).pipe( + Scope.provide(child), + Effect.catchCause((cause) => + Effect.logError("Event stream extension failed", { cause }).pipe( + Effect.andThen(Scope.close(child, Exit.void)), + ), + ), + ) + }), + { discard: true }, + ) + return { id, events: Stream.fromQueue(queue) } + }), }) }) -export const layer = Layer.effect( - Service, - Effect.gen(function* () { - const bus = yield* Bus.Service - return yield* make(bus.listen) - }), -) +export const layer = (...extensions: ReadonlyArray>) => + Layer.effect( + Service, + Effect.gen(function* () { + const bus = yield* Bus.Service + return yield* make(bus.listen, { extensions: yield* Effect.all(extensions) }) + }), + ) diff --git a/packages/server/src/handlers.ts b/packages/server/src/handlers.ts index 010c93a34be..b31218d448e 100644 --- a/packages/server/src/handlers.ts +++ b/packages/server/src/handlers.ts @@ -31,6 +31,7 @@ import { ProjectHandler } from "./handlers/project" import { WorktreeHandler } from "./handlers/worktree" import { VcsHandler } from "./handlers/vcs" import { EventFeed } from "./event-feed" +import { SpaceStore } from "./space-store" import { MigrationHandler } from "./handlers/migration" import { ConfigHandler } from "./handlers/config" @@ -60,7 +61,7 @@ export const handlers = Layer.mergeAll( CommandHandler, SkillHandler, RpcHandler, - EventHandler.pipe(Layer.provide(EventFeed.layer)), + EventHandler.pipe(Layer.provide(EventFeed.layer(SpaceStore.extension))), PtyHandler, PersistentPtyHandler, ShellHandler, diff --git a/packages/server/src/handlers/event.ts b/packages/server/src/handlers/event.ts index 491cb53cf58..428fe97dafb 100644 --- a/packages/server/src/handlers/event.ts +++ b/packages/server/src/handlers/event.ts @@ -10,15 +10,20 @@ export const EventHandler = HttpApiBuilder.group(Api, "server.event", (handlers) const feed = yield* EventFeed.Service return handlers.handleRaw("event.subscribe", (ctx) => Effect.gen(function* () { - const connected = { - id: Event.ID.create(), - type: "server.connected", - data: {}, - } as const const output = Stream.unwrap( feed .subscribe(ctx.query.types) - .pipe(Effect.map((live) => Stream.make(EventFeed.frame(connected)).pipe(Stream.concat(live)))), + .pipe( + Effect.map((subscription) => + Stream.make( + EventFeed.frame({ + id: Event.ID.create(), + type: "server.connected", + data: { stream: subscription.id }, + }), + ).pipe(Stream.concat(subscription.events)), + ), + ), ) const heartbeat = Stream.tick("15 seconds").pipe(Stream.map(() => ": heartbeat\n\n")) return HttpServerResponse.stream( diff --git a/packages/server/src/handlers/persistent-pty.ts b/packages/server/src/handlers/persistent-pty.ts index d5966ddf7a5..f65b41d1bd2 100644 --- a/packages/server/src/handlers/persistent-pty.ts +++ b/packages/server/src/handlers/persistent-pty.ts @@ -25,6 +25,7 @@ import { makeJob } from "./job" import { makeMachine, makeMachineLink } from "./machine" import { makeMediaGet } from "./media" import { makePush } from "./push" +import { makeSpace } from "./space" import { type Outbound, runPtySocket } from "./pty-socket" export const PersistentPtyHandler = HttpApiBuilder.group(Api, "server.experimental", (handlers) => @@ -34,6 +35,7 @@ export const PersistentPtyHandler = HttpApiBuilder.group(Api, "server.experiment const pty = yield* PersistentPty.Service const artifact = yield* makeArtifact const job = yield* makeJob + const space = yield* makeSpace const mediaGet = yield* makeMediaGet const blobGet = yield* makeBlobGet const automation = yield* makeAutomation @@ -61,6 +63,12 @@ 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.set", (ctx) => space.set(ctx.params.space, ctx.params.key, ctx.payload.value)) + .handle("space.delete", (ctx) => space.remove(ctx.params.space, ctx.params.key)) + .handle("space.sync", (ctx) => space.sync(ctx.params.space, ctx.query.cursor)) + .handle("space.subscribe", (ctx) => space.subscribe(ctx.payload)) + .handle("space.unsubscribe", (ctx) => space.unsubscribe(ctx.payload)) + .handle("space.reset", () => space.reset()) .handle("artifacts.providers", (ctx) => artifact.providers(ctx.query, ctx.request)) .handle("artifacts.list", (ctx) => artifact.list(ctx.query, ctx.request)) .handle("artifacts.create", (ctx) => artifact.create(ctx.query, ctx.payload, ctx.request)) diff --git a/packages/server/src/handlers/space.ts b/packages/server/src/handlers/space.ts new file mode 100644 index 00000000000..dbde55c2dbd --- /dev/null +++ b/packages/server/src/handlers/space.ts @@ -0,0 +1,47 @@ +import { InvalidRequestError } from "@opencode/protocol/errors" +import { Space } from "@opencode/schema/space" +import { Effect } from "effect" +import { HttpApiSchema } from "effect/http-api" +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" }) + +export const makeSpace = Effect.gen(function* () { + const store = yield* SpaceStore.Service + + return { + set: Effect.fn("SpaceHandler.set")(function* (space: Space.Name, key: Space.Key, value: Space.Value) { + if (new TextEncoder().encode(value).length > Space.MaxValueBytes) + return yield* new InvalidRequestError({ message: "Value exceeds 1 MiB of UTF-8", field: "value" }) + yield* store.set(space, key, value) + return HttpApiSchema.NoContent.make() + }), + sync: Effect.fn("SpaceHandler.sync")(function* (space: Space.Name, cursor: string | undefined) { + return yield* store.sync(space, cursor) + }), + subscribe: Effect.fn("SpaceHandler.subscribe")(function* (payload: { + readonly stream: string + readonly spaces: ReadonlyArray<{ readonly space: Space.Name; readonly cursor: string }> + }) { + if (!(yield* store.subscribe(payload.stream, payload.spaces))) return yield* streamNotFound() + return HttpApiSchema.NoContent.make() + }), + unsubscribe: Effect.fn("SpaceHandler.unsubscribe")(function* (payload: { + readonly stream: string + readonly spaces: ReadonlyArray + }) { + if (!(yield* store.unsubscribe(payload.stream, payload.spaces))) return yield* streamNotFound() + return HttpApiSchema.NoContent.make() + }), + reset: Effect.fn("SpaceHandler.reset")(function* () { + yield* store.resetEpoch + return HttpApiSchema.NoContent.make() + }), + remove: Effect.fn("SpaceHandler.remove")(function* (space: Space.Name, key: Space.Key) { + yield* store.remove(space, key) + return HttpApiSchema.NoContent.make() + }), + } +}) diff --git a/packages/server/src/routes.ts b/packages/server/src/routes.ts index 06705abde3a..2d6c4a56007 100644 --- a/packages/server/src/routes.ts +++ b/packages/server/src/routes.ts @@ -55,6 +55,7 @@ import { Context, Effect, Layer, Option } from "effect" import { Base64 } from "effect/encoding" import { Api } from "./api" import { ServerAuth } from "./auth" +import { SpaceStore } from "./space-store" import { CorsConfig } from "./cors" import { handlers } from "./handlers" import { authorizationLayer } from "./middleware/authorization" @@ -98,6 +99,7 @@ const applicationServiceNodes = [ Credential.node, WellKnown.node, ServerPairing.node, + SpaceStore.node, LocationServiceMap.node, LocationActivity.node, SessionRestart.node, diff --git a/packages/server/src/space-store.ts b/packages/server/src/space-store.ts new file mode 100644 index 00000000000..8956dbc16e0 --- /dev/null +++ b/packages/server/src/space-store.ts @@ -0,0 +1,315 @@ +export * as SpaceStore from "./space-store" + +import { SpaceRows } from "@opencode/core/space" +import { Database } from "@opencode/core/database/database" +import { KeyedMutex } from "@opencode/core/effect/keyed-mutex" +import { Space } from "@opencode/schema/space" +import { Event } from "@opencode/schema/event" +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. */ +export const BatchSize = 500 + +/** Tombstone-creating deletes in a space between two checks of its tombstones against `SpaceRows.TombstoneLimit`. */ +export const PurgeInterval = 64 + +export type Change = typeof Space.Event.Updated.Type | typeof Space.Event.Deleted.Type +export type Listener = (change: Change) => Effect.Effect +type Send = (event: typeof Space.Event.Resync.Type | Change) => Effect.Effect + +export interface Interface { + readonly set: (space: Space.Name, key: Space.Key, value: Space.Value) => Effect.Effect + readonly remove: (space: Space.Name, key: Space.Key) => Effect.Effect + /** 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. + */ + readonly sync: (space: Space.Name, 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. + */ + readonly subscribe: ( + stream: string, + spaces: ReadonlyArray<{ readonly space: Space.Name; readonly cursor: string }>, + ) => Effect.Effect + /** Stops sending those spaces to the stream, also mid catch-up; false when no such stream is attached. */ + readonly unsubscribe: (stream: string, spaces: ReadonlyArray) => Effect.Effect + /** + * Runs `listener` with every change before its write returns and before subscribed streams get it, in revision + * order within a space. Changes never go through the bus, so plugins do not see them. + */ + readonly listen: (listener: Listener) => Effect.Effect> +} + +export class Service extends Context.Service()("@opencode/server/SpaceStore") {} + +const layer = Layer.effect( + Service, + Effect.gen(function* () { + const db = (yield* Database.Service).db + // Without a stored epoch, this process's own one still keeps cursors safe: they only fall back to snapshots. + let epoch = yield* SpaceRows.epoch(db).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Could not read the space epoch", { cause }).pipe(Effect.as(crypto.randomUUID())), + ), + ) + const listeners = new Array() + // Held per space from the commit until listeners have the change, so they get each space in revision order. + // Reads and other spaces never wait on it. + const locks = KeyedMutex.makeUnsafe() + // Tombstone-creating deletes per space since its last purge check. A space missing here, as after a restart, is + // checked on its next one, so between commits a space holds at most `PurgeInterval - 1` tombstones past the limit. + const deletes = new Map() + const tombstoned = (space: Space.Name) => + Effect.suspend(() => { + const since = (deletes.get(space) ?? PurgeInterval - 1) + 1 + if (since < PurgeInterval) return Effect.sync(() => deletes.set(space, since)) + // The delete is committed already, so a failed purge must not keep listeners from hearing of it. + return SpaceRows.purge(db, space).pipe( + Effect.andThen(Effect.sync(() => deletes.set(space, 0))), + Effect.catchCause((cause) => Effect.logWarning("Could not purge space tombstones", { space, cause })), + ) + }) + + const commit = (space: Space.Name, write: Effect.Effect) => + locks.withLock(space)( + // A dropped request must not commit a change that listeners never hear about. + Effect.uninterruptible( + Effect.gen(function* () { + const data = yield* write + if (!data) return + const committed = change(data, yield* Clock.currentTimeMillis) + yield* Effect.forEach(listeners, (listener) => listener(committed), { discard: true }) + yield* Effect.forEach(streams.values(), (stream) => deliver(stream, committed), { discard: true }) + }), + ), + ) + + // Each attached stream with its subscribed spaces. A subscription holds the changes that arrive while its catch-up + // is read, then forwards only those after the revision the catch-up covers. + const streams = new Map() + const deliver = (stream: Attached, change: Change) => + Effect.suspend(() => { + const subscription = stream.spaces.get(change.data.space) + if (!subscription) return Effect.void + if (subscription.pending) { + subscription.pending.push(change) + return Effect.void + } + 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) => + 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", + space, + epoch, + revision, + entries: entries(kept), + deleted: deleted(kept), + cursor: `${epoch}.${revision}`, + next: rows.length > BatchSize ? `${epoch}.${revision}` : undefined, + } + return page + }) + + // 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) => + Effect.gen(function* () { + const position = parse(epoch, cursor) + const created = yield* Clock.currentTimeMillis + const resync = { + covered: 0, + 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 + return { + covered: rows.at(-1)?.revision ?? position.since, + events: rows.map((row) => + change( + row.value === null + ? { space, key: row.key, revision: row.revision } + : { space, key: row.key, value: row.value, revision: row.revision }, + created, + ), + ), + } + }) + + return Service.of({ + set: Effect.fn("SpaceStore.set")(function* (space, key, value) { + yield* commit( + space, + SpaceRows.set(db, space, key, value).pipe(Effect.map((revision) => ({ space, key, value, revision }))), + ) + }), + remove: Effect.fn("SpaceStore.remove")(function* (space, key) { + yield* commit( + space, + SpaceRows.remove(db, space, key).pipe( + Effect.flatMap((revision) => + revision === undefined ? Effect.undefined : tombstoned(space).pipe(Effect.as({ space, key, revision })), + ), + ), + ) + }), + get epoch() { + return epoch + }, + 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) + }), + attach: (id, send) => + Effect.acquireRelease( + Effect.sync(() => streams.set(id, { send, spaces: new Map() })), + () => Effect.sync(() => streams.delete(id)), + ).pipe(Effect.asVoid), + subscribe: Effect.fn("SpaceStore.subscribe")(function* (id, requests) { + const stream = streams.get(id) + if (!stream) return false + const subscriptions = requests.map((request) => { + const subscription: Subscription = { covered: 0, pending: [] } + stream.spaces.set(request.space, subscription) + return { request, subscription } + }) + yield* Effect.forEach( + subscriptions, + ({ request, subscription }) => + Effect.gen(function* () { + // 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) + if (!subscription.pending) return + subscription.covered = first.covered + for (const event of first.events) if (current()) yield* stream.send(event) + // Changes arriving while these go out join the end, so the space stays in revision order. + for ( + let change = subscription.pending.shift(); + change && current(); + change = subscription.pending.shift() + ) + if (change.data.revision > subscription.covered) yield* stream.send(change) + subscription.pending = undefined + }), + { discard: true }, + ).pipe( + // A subscribe that fails or is dropped before its catch-up goes out leaves nothing holding changes. + Effect.ensuring( + Effect.sync(() => { + for (const { request, subscription } of subscriptions) + if (subscription.pending && stream.spaces.get(request.space) === subscription) + stream.spaces.delete(request.space) + }), + ), + ) + return true + }), + unsubscribe: (id, spaces) => + Effect.sync(() => { + const stream = streams.get(id) + for (const space of spaces) stream?.spaces.delete(space) + return stream !== undefined + }), + listen: (listener) => + Effect.sync(() => { + listeners.push(listener) + return Effect.sync(() => { + const index = listeners.indexOf(listener) + if (index >= 0) listeners.splice(index, 1) + }) + }), + }) + }), +) + +export const node = makeGlobalNode({ service: Service, layer, deps: [Database.node] }) + +/** Attaches every event stream to the store, so `subscribe` can send space changes to it. */ +export const extension = Effect.gen(function* () { + const store = yield* Service + return { open: (stream, send) => store.attach(stream, send) } satisfies EventFeed.Extension +}) + +interface Subscription { + covered: Space.Revision + pending: Array | undefined +} + +interface Attached { + readonly send: Send + readonly spaces: Map +} + +function change(data: Change["data"], created: number): Change { + return "value" in data + ? { id: Event.ID.create(), created, type: Space.Event.Updated.type, data } + : { id: Event.ID.create(), created, type: Space.Event.Deleted.type, data } +} + +function entries(rows: ReadonlyArray<{ readonly key: Space.Key; readonly value: Space.Value | null }>) { + return rows.flatMap((row) => (row.value === null ? [] : [{ key: row.key, value: row.value }])) +} + +function deleted(rows: ReadonlyArray<{ readonly key: Space.Key; readonly value: Space.Value | null }>) { + return rows.flatMap((row) => (row.value === null ? [row.key] : [])) +} + +// `epoch.revision`, or `epoch.revision.head` while a snapshot goes out. A cursor from another epoch, or one that does +// not parse, is unusable. +function parse(epoch: string, cursor: string) { + if (!cursor.startsWith(`${epoch}.`)) return undefined + const parts = cursor.slice(epoch.length + 1).split(".") + if (parts.length > 2 || !parts.every((part) => /^\d+$/u.test(part) && Number.isSafeInteger(Number(part)))) + return undefined + return { since: Number(parts[0]), head: parts[1] === undefined ? undefined : Number(parts[1]) } +} diff --git a/packages/server/test/event-feed.test.ts b/packages/server/test/event-feed.test.ts index 9a367256e2f..264e08979ed 100644 --- a/packages/server/test/event-feed.test.ts +++ b/packages/server/test/event-feed.test.ts @@ -54,8 +54,8 @@ describe("EventFeed", () => { return event.type }, }) - const first = yield* feed.subscribe() - const second = yield* feed.subscribe() + const first = (yield* feed.subscribe()).events + const second = (yield* feed.subscribe()).events const left = yield* first.pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped) const right = yield* second.pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped) @@ -73,8 +73,8 @@ describe("EventFeed", () => { Effect.gen(function* () { const source = makeSource() const feed = yield* EventFeed.make(source.observe, { encode: (event) => event.type }) - const filtered = yield* feed.subscribe([Credential.Event.Switched.type]) - const all = yield* feed.subscribe() + const filtered = (yield* feed.subscribe([Credential.Event.Switched.type])).events + const all = (yield* feed.subscribe()).events const left = yield* filtered.pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped) const right = yield* all.pipe(Stream.take(2), Stream.runCollect, Effect.forkScoped) @@ -101,8 +101,8 @@ describe("EventFeed", () => { capacity: 1, encode: (event) => event.id, }) - const slow = yield* feed.subscribe() - const fast = yield* feed.subscribe() + const slow = (yield* feed.subscribe()).events + const fast = (yield* feed.subscribe()).events const first = yield* Deferred.make() const second = yield* Deferred.make() const received = new Array() @@ -142,7 +142,7 @@ describe("EventFeed", () => { Effect.gen(function* () { const source = makeSource() const feed = yield* EventFeed.make(source.observe, { encode: (event) => event.type }) - const stream = yield* feed.subscribe() + const stream = (yield* feed.subscribe()).events const received = yield* stream.pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped) yield* source.publish({ @@ -163,7 +163,7 @@ describe("EventFeed", () => { Effect.gen(function* () { const source = makeSource() const feed = yield* EventFeed.make(source.observe, { capacity: 1, encode: (event) => event.type }) - const stream = yield* feed.subscribe() + const stream = (yield* feed.subscribe()).events yield* source.publish(internal("one")) yield* source.publish(internal("two")) @@ -182,13 +182,13 @@ describe("EventFeed", () => { return event.id }, }) - const current = yield* feed.subscribe() + const current = (yield* feed.subscribe()).events const failed = yield* current.pipe(Stream.runCollect, Effect.exit, Effect.forkScoped) yield* source.publish(event("bad")) const exit = yield* Fiber.join(failed) - const next = yield* feed.subscribe() + const next = (yield* feed.subscribe()).events const received = yield* next.pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped) yield* source.publish(event("good")) @@ -199,3 +199,32 @@ describe("EventFeed", () => { }), ) }) + +it.live("each stream gets its own ID, and a failing extension never fails it", () => + Effect.gen(function* () { + const source = makeSource() + const opened: Array<{ stream: string; send: Parameters[1] }> = [] + const feed = yield* EventFeed.make(source.observe, { + extensions: [ + { open: () => Effect.die(new Error("broken")) }, + { open: (stream, send) => Effect.sync(() => void opened.push({ stream, send })) }, + ], + }) + const first = yield* feed.subscribe() + const second = yield* feed.subscribe() + expect(opened.map((item) => item.stream)).toEqual([first.id, second.id]) + expect(first.id).not.toBe(second.id) + // A cyclic payload cannot be encoded; it is dropped instead of failing the stream. + const cyclic: Record = {} + cyclic.self = cyclic + const send = opened[0]?.send + if (send) yield* send({ ...event("bad"), data: cyclic }) + yield* source.publish(event("ok")) + const [frame] = yield* first.events.pipe( + Stream.take(1), + Stream.runCollect, + Effect.map((frames) => Array.from(frames)), + ) + expect(frame && JSON.parse(frame.slice("data: ".length)).id).toBe("evt_ok") + }), +) diff --git a/packages/server/test/space-store.test.ts b/packages/server/test/space-store.test.ts new file mode 100644 index 00000000000..5a33d3b9ad0 --- /dev/null +++ b/packages/server/test/space-store.test.ts @@ -0,0 +1,699 @@ +import { expect } from "bun:test" +import { Agent } from "@opencode/core/agent" +import { Bus } from "@opencode/core/bus" +import { Database } from "@opencode/core/database/database" +import { SpaceRows } from "@opencode/core/space" +import { SpaceTable } from "@opencode/core/space/sql" +import { LayerNode } from "@opencode/util/effect/layer-node" +import type { Space } from "@opencode/schema/space" +import { Context, Deferred, Effect, Fiber, Layer, Stream } from "effect" +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. +const setup = Effect.gen(function* () { + const database = Context.get(yield* Layer.build(LayerNode.compile(Database.node)), Database.Service) + const shared = Database.node.replace(Layer.succeed(Database.Service, database)) + const gates = new Map; release: Deferred.Deferred }>() + const boot = Effect.fnUntraced(function* () { + const bus = Context.get(yield* Layer.build(LayerNode.compile(Bus.node, { replacements: [shared] })), Bus.Service) + const store = Context.get( + yield* Layer.build(LayerNode.compile(SpaceStore.node, { replacements: [shared] })), + SpaceStore.Service, + ) + yield* store.listen((change) => + Effect.suspend(() => { + const gate = gates.get(change.data.revision) + if (!gate) return Effect.void + gates.delete(change.data.revision) + return Deferred.succeed(gate.reached, undefined).pipe(Effect.andThen(Deferred.await(gate.release))) + }), + ) + const extension = yield* SpaceStore.extension.pipe(Effect.provideService(SpaceStore.Service, store)) + return { store, bus, feed: yield* EventFeed.make(bus.listen, { extensions: [extension] }) } + }) + const hold = Effect.fnUntraced(function* (revision: number) { + const gate = { reached: yield* Deferred.make(), release: yield* Deferred.make() } + gates.set(revision, gate) + return gate + }) + return { boot, hold, db: database.db } +}) + +const take = (live: Stream.Stream, count: number) => + live.pipe( + Stream.take(count), + Stream.runCollect, + Effect.map((frames) => + Array.from(frames, (frame) => { + const event = JSON.parse(frame.slice("data: ".length)) + return { type: event.type, data: event.data } + }), + ), + ) + +const now = { startImmediately: true } as const + +// 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) + 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 +} + +// And after applying a stream event. +const applyEvent = (state: Map, event: { readonly type: string; readonly data: any }) => { + if (event.type === "experimental.space.updated") state.set(event.data.key, event.data.value) + if (event.type === "experimental.space.deleted") state.delete(event.data.key) + return state +} + +const current = (store: SpaceStore.Interface, space: string) => + syncAll(store, space).pipe(Effect.map((pages) => pages.reduce(applyPage, new Map()))) + +const range = (count: number) => Array.from({ length: count }, (_, index) => index) + +it.live("syncs a space in pages: live rows up to the starting head, then a delta of what changed meanwhile", () => + Effect.gen(function* () { + const { boot } = yield* setup + const { store } = yield* boot() + const count = SpaceStore.BatchSize + 10 + yield* Effect.forEach(range(count), (index) => store.set("big", `k${index}`, String(index)), { discard: true }) + const epoch = store.epoch + + const first = yield* store.sync("big") + expect([first.type, first.revision, first.entries.length, first.cursor, first.next]).toEqual([ + "snapshot", + SpaceStore.BatchSize, + SpaceStore.BatchSize, + `${epoch}.${SpaceStore.BatchSize}`, + `${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.remove("big", "k0") + yield* store.set("big", "k1", "new") + yield* store.set("big", `k${SpaceStore.BatchSize + 5}`, "new") + yield* store.remove("big", `k${SpaceStore.BatchSize + 6}`) + + 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. + expect(second).toEqual({ + type: "delta", + 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) + expect(third).toEqual({ + type: "delta", + space: "big", + epoch, + revision: count + 4, + entries: [ + { key: "k1", value: "new" }, + { key: `k${SpaceStore.BatchSize + 5}`, value: "new" }, + ], + deleted: ["k0", `k${SpaceStore.BatchSize + 6}`], + cursor: `${epoch}.${count + 4}`, + }) + + // 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() + for (const page of [first, second, third]) { + applyPage(held, 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) + } + }), +) + +it.live("a snapshot reads no tombstones, and its last page reports the head it started from", () => + Effect.gen(function* () { + const { boot } = yield* setup + const { store } = yield* boot() + yield* Effect.forEach(range(SpaceStore.BatchSize + 1), (index) => store.set("big", `k${index}`, String(index)), { + discard: true, + }) + yield* store.remove("big", "k0") + const page = yield* store.sync("big") + expect([page.type, page.revision, page.entries.length, page.next]).toEqual([ + "snapshot", + SpaceStore.BatchSize + 2, + SpaceStore.BatchSize, + undefined, + ]) + expect(page.entries.some((entry) => entry.key === "k0")).toBe(false) + }), +) + +it.live("syncs each space from its cursor: final values and deletions, else a snapshot", () => + Effect.gen(function* () { + const { boot } = yield* setup + const { store } = yield* boot() + yield* store.set("app", "kept", "v1") + yield* store.set("app", "churn", "1") + yield* store.set("app", "doomed", "true") + yield* store.set("other", "x", "y") + + // While the client is away: repeated updates, a delete, a delete repeated, and a delete then re-set. + yield* store.set("app", "churn", "2") + yield* store.set("app", "churn", "3") + yield* store.remove("app", "doomed") + yield* store.remove("app", "doomed") + yield* store.remove("app", "never-set") + yield* store.set("app", "back", "a") + yield* store.remove("app", "back") + yield* store.set("app", "back", "b") + + const epoch = store.epoch + const page = (space: string, cursor?: string) => store.sync(space, cursor) + expect(yield* page("app", `${epoch}.3`)).toEqual({ + type: "delta", + space: "app", + epoch, + revision: 9, + entries: [ + { key: "churn", value: "3" }, + { key: "back", value: "b" }, + ], + deleted: ["doomed"], + cursor: `${epoch}.9`, + }) + const empty = (space: string, revision: number) => ({ + type: "delta" as const, + space, + epoch, + revision, + entries: [], + deleted: [], + cursor: `${epoch}.${revision}`, + }) + expect(yield* page("other", `${epoch}.1`)).toEqual(empty("other", 1)) + expect(yield* page("zero", `${epoch}.0`)).toEqual(empty("zero", 0)) + expect(yield* page("app", `${epoch}.9`)).toEqual(empty("app", 9)) + const snapshot = { type: "snapshot" as const, epoch, revision: 0, entries: [], cursor: `${epoch}.0` } + // No cursor, a revision this database never issued, another database's epoch, and one that does not parse. + expect(yield* page("fresh")).toEqual({ ...snapshot, space: "fresh" }) + expect(yield* page("ahead", `${epoch}.9`)).toEqual({ ...snapshot, space: "ahead" }) + expect(yield* page("app", "another-database.9")).toEqual({ + ...snapshot, + space: "app", + revision: 9, + cursor: `${epoch}.9`, + entries: [ + { key: "kept", value: "v1" }, + { key: "churn", value: "3" }, + { key: "back", value: "b" }, + ], + }) + expect((yield* page("app", `${epoch}.x`)).type).toBe("snapshot") + expect((yield* page("app", `${epoch}.1.9.9`)).type).toBe("snapshot") + }), +) + +it.live("a cursor below the space's floor gets a snapshot and one at or above it a delta, after a restart too", () => + Effect.gen(function* () { + const { boot, db } = yield* setup + const before = yield* boot() + yield* Effect.forEach(["a", "b", "c", "d"], (key) => before.store.set("app", key, key), { discard: true }) + // With a limit of 2, the third delete purges the first tombstone, at revision 5. + yield* Effect.forEach(["a", "b", "c"], (key) => SpaceRows.remove(db, "app", key), { discard: true }) + yield* SpaceRows.purge(db, "app", 2) + + 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({ + type: "snapshot", + space: "app", + epoch, + revision: 7, + entries: [{ key: "d", value: "d" }], + cursor: `${epoch}.7`, + }) + const delta = (deleted: Array) => ({ + type: "delta" as const, + space: "app", + epoch, + revision: 7, + entries: [], + 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"])) + }), +) + +it.live("a delta page whose deletions were purged meanwhile comes back as a snapshot", () => + Effect.gen(function* () { + const { boot, db } = yield* setup + const { store } = yield* boot() + // The client holds k0 to k9, at revision 10. + yield* Effect.forEach(range(10), (index) => store.set("app", `k${index}`, String(index)), { discard: true }) + const held = new Map(range(10).map((index) => [`k${index}`, String(index)])) + // Then come a full page of new keys and two tombstones. + yield* Effect.forEach(range(SpaceStore.BatchSize), (index) => store.set("app", `u${index}`, String(index)), { + discard: true, + }) + yield* SpaceRows.remove(db, "app", "k0") + yield* SpaceRows.remove(db, "app", "k1") + + const first = yield* store.sync("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) + const rest = yield* syncAll(store, "app", first.next) + const pages = [first, ...rest] + const head = SpaceStore.BatchSize + 13 + expect(pages.map((page) => [page.type, page.revision, page.entries.length])).toEqual([ + ["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], + ]) + expect(pages.reduce(applyPage, held)).toEqual(yield* current(store, "app")) + expect(held.has("k0")).toBe(false) + }), +) + +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.set("app", "k", "a") + yield* before.store.set("app", "k", "b") + yield* before.store.remove("app", "k") + + // 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.set("app", "j", "c") + expect(yield* after.store.sync("app", `${after.store.epoch}.1`)).toEqual({ + type: "delta", + space: "app", + epoch: after.store.epoch, + revision: 4, + entries: [{ key: "j", value: "c" }], + deleted: ["k"], + cursor: `${after.store.epoch}.4`, + }) + }), +) + +it.live("a subscription sends the changes since its cursor once, then live changes of its spaces only", () => + Effect.gen(function* () { + const { boot } = yield* setup + const { store, feed, bus } = yield* boot() + yield* store.set("app", "k", "1") + yield* store.set("app", "gone", "x") + yield* store.set("other", "x", "1") + const synced = yield* store.sync("app") + // After the sync and before the subscription. + yield* store.set("app", "k", "2") + yield* store.remove("app", "gone") + + 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.set("app", "k", "3") + yield* store.set("other", "x", "2") + yield* bus.publish(Agent.Event.Updated, {}) + + // The changes since the cursor, one event per row in revision order, then the live ones. + expect(yield* take(stream.events, 4)).toEqual([ + { type: "experimental.space.updated", data: { space: "app", key: "k", value: "2", revision: 3 } }, + { type: "experimental.space.deleted", data: { space: "app", key: "gone", revision: 4 } }, + { type: "experimental.space.updated", data: { space: "app", key: "k", value: "3", revision: 5 } }, + { type: "agent.updated", data: {} }, + ]) + expect(yield* take(plain.events, 1)).toEqual([{ type: "agent.updated", data: {} }]) + // Changes never pass through the bus, which is where plugins listen. + expect(seen).toEqual([Agent.Event.Updated.type]) + }), +) + +it.live("a write committed before the subscribe read and delivered after it reaches the stream once, in order", () => + Effect.gen(function* () { + const { boot, hold } = yield* setup + const { store, feed } = yield* boot() + yield* store.set("app", "k", "1") + const synced = yield* store.sync("app") + const stream = yield* feed.subscribe() + + const pending = yield* hold(2) + const write = yield* store.set("app", "k", "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.set("other", "x", "1") + expect(yield* store.subscribe(stream.id, [{ space: "app", cursor: synced.cursor }])).toBe(true) + const next = yield* store.set("app", "k", "3").pipe(Effect.forkChild(now)) + yield* Deferred.succeed(pending.release, undefined) + yield* Fiber.join(write) + yield* Fiber.join(next) + + expect(yield* take(stream.events, 2)).toEqual([ + { type: "experimental.space.updated", data: { space: "app", key: "k", value: "2", revision: 2 } }, + { type: "experimental.space.updated", data: { space: "app", key: "k", value: "3", revision: 3 } }, + ]) + }), +) + +it.live("concurrent writes reach a subscribed stream in revision order", () => + Effect.gen(function* () { + 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 }]) + const writes = range(20) + yield* Effect.forEach( + writes, + (index) => + Effect.all( + [store.set("app", `k${index % 4}`, String(index)), store.set(`space-${index % 3}`, "k", String(index))], + { concurrency: "unbounded" }, + ), + { concurrency: "unbounded", discard: true }, + ) + + // Nothing changed since the cursor, so only the live changes arrive. + const changes = yield* take(stream.events, writes.length) + expect(changes.map((change) => change.data)).toEqual( + writes.map((_, index) => expect.objectContaining({ space: "app", revision: index + 1 })), + ) + // The last change of each key is the value synced. + expect(changes.reduce(applyEvent, new Map())).toEqual(yield* current(store, "app")) + }), +) + +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* Effect.forEach(range(SpaceStore.BatchSize + 1), (index) => store.set("big", `k${index}`, String(index)), { + discard: true, + }) + yield* Effect.forEach(["a", "b", "c"], (key) => store.set("purged", key, key), { discard: true }) + yield* Effect.forEach(["a", "b", "c"], (key) => SpaceRows.remove(db, "purged", key), { discard: true }) + yield* SpaceRows.purge(db, "purged", 2) + yield* Effect.forEach(range(SpaceStore.BatchSize), (index) => store.set("full", `k${index}`, String(index)), { + discard: true, + }) + + 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.set("big", "after", "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 }, + }) + }), +) + +it.live("subscribe needs an open stream, and a stream leaves the store when it closes", () => + Effect.gen(function* () { + const { boot } = yield* setup + const { store, feed } = yield* boot() + const cursor = `${store.epoch}.0` + expect(yield* store.subscribe("not-a-stream", [{ space: "app", cursor }])).toBe(false) + const id = yield* Effect.scoped( + Effect.gen(function* () { + const stream = yield* feed.subscribe() + expect(yield* store.subscribe(stream.id, [{ space: "app", cursor }])).toBe(true) + return stream.id + }), + ) + expect(yield* store.subscribe(id, [{ space: "app", cursor }])).toBe(false) + // Writes to a space a closed stream subscribed to go nowhere. + yield* store.set("app", "k", "1") + }), +) + +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 stream = yield* feed.subscribe() + yield* store.subscribe(stream.id, [{ space: "app", cursor }]) + yield* store.set("app", "k", "1") + yield* store.subscribe(stream.id, [{ space: "app", cursor }]) + yield* store.set("app", "k", "2") + + const updated = (value: string, revision: number) => ({ + type: "experimental.space.updated", + data: { space: "app", key: "k", value, revision }, + }) + expect(yield* take(stream.events, 3)).toEqual([ + updated("1", 1), + // The second subscription's catch-up from the same cursor, then the next change once, not once per subscription. + updated("1", 1), + updated("2", 2), + ]) + }), +) + +// A stream the test attaches itself, whose first event pauses until released, so a subscribe can be stopped in the +// middle of its catch-up. +const pausedStream = Effect.fnUntraced(function* (store: SpaceStore.Interface, id: string) { + const reached = yield* Deferred.make() + const release = yield* Deferred.make() + const sent: Array<{ readonly type: string; readonly data: unknown }> = [] + let paused = false + yield* store.attach(id, (event) => + Effect.gen(function* () { + if (!paused) { + paused = true + yield* Deferred.succeed(reached, undefined) + yield* Deferred.await(release) + } + sent.push({ type: event.type, data: event.data }) + }), + ) + return { reached, release, sent } +}) + +it.live("of two overlapping subscribes of one space on a stream, only the newer one sends", () => + Effect.gen(function* () { + const { boot } = yield* setup + const { store } = yield* boot() + const cursor = `${store.epoch}.0` + const updated = (space: string, key: string, value: string, revision: number) => ({ + type: "experimental.space.updated", + data: { space, key, value, revision }, + }) + yield* store.set("other", "x", "1") + yield* store.set("app", "a", "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") + const older = yield* store + .subscribe("first", [ + { space: "other", cursor }, + { space: "app", cursor }, + ]) + .pipe(Effect.forkChild(now)) + yield* Deferred.await(first.reached) + yield* store.set("app", "b", "2") + expect(yield* store.subscribe("first", [{ space: "app", cursor }])).toBe(true) + yield* Deferred.succeed(first.release, undefined) + yield* Fiber.join(older) + yield* store.set("app", "c", "3") + expect(first.sent.filter((event) => (event.data as { space: string }).space === "app")).toEqual([ + updated("app", "a", "1", 1), + updated("app", "b", "2", 2), + updated("app", "c", "3", 3), + ]) + + // The older subscribe pauses on its first event in app; once replaced, it sends nothing more. + const second = yield* pausedStream(store, "second") + const paused = yield* store.subscribe("second", [{ space: "app", cursor }]).pipe(Effect.forkChild(now)) + yield* Deferred.await(second.reached) + expect(yield* store.subscribe("second", [{ space: "app", cursor }])).toBe(true) + yield* Deferred.succeed(second.release, undefined) + yield* Fiber.join(paused) + yield* store.set("app", "d", "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), + updated("app", "b", "2", 2), + updated("app", "c", "3", 3), + updated("app", "a", "1", 1), + updated("app", "d", "4", 4), + ]) + }), +) + +it.live("unsubscribing stops a space's events, also mid catch-up, while other spaces keep flowing", () => + Effect.gen(function* () { + const { boot } = yield* setup + const { store, feed } = yield* boot() + const cursor = `${store.epoch}.0` + const updated = (space: string, key: string, value: string, revision: number) => ({ + type: "experimental.space.updated", + data: { space, key, value, revision }, + }) + const stream = yield* feed.subscribe() + yield* store.subscribe(stream.id, [ + { space: "app", cursor }, + { space: "other", cursor }, + ]) + yield* store.set("app", "a", "1") + expect(yield* store.unsubscribe(stream.id, ["app"])).toBe(true) + yield* store.set("app", "b", "2") + yield* store.set("other", "x", "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) + expect(yield* store.unsubscribe("not-a-stream", ["app"])).toBe(false) + + // A catch-up paused on its first event sends nothing more once unsubscribed. + const paused = yield* pausedStream(store, "paused") + const subscribing = yield* store.subscribe("paused", [{ space: "app", cursor }]).pipe(Effect.forkChild(now)) + yield* Deferred.await(paused.reached) + expect(yield* store.unsubscribe("paused", ["app"])).toBe(true) + yield* Deferred.succeed(paused.release, undefined) + yield* Fiber.join(subscribing) + yield* store.set("app", "c", "3") + // Only the event it was already sending. + expect(paused.sent).toEqual([updated("app", "a", "1", 1)]) + }), +) + +it.live("a client that syncs while writes go on, then subscribes, ends with exactly the current state", () => + Effect.gen(function* () { + const { boot } = yield* setup + const { store, feed } = yield* boot() + yield* Effect.forEach(range(SpaceStore.BatchSize + 5), (index) => store.set("app", `k${index}`, String(index)), { + discard: true, + }) + 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) + for (let round = 0; page.next !== undefined; round++) { + yield* store.set("app", `k${round}`, `during ${round}`) + yield* store.remove("app", `k${SpaceStore.BatchSize + round}`) + page = yield* store.sync("app", page.next) + applyPage(state, page) + } + yield* store.set("app", "k1", "before subscribe") + yield* store.remove("app", "k2") + yield* store.subscribe(stream.id, [{ space: "app", cursor: page.cursor }]) + yield* store.set("app", "k3", "live") + yield* store.remove("app", "k4") + + const events = yield* take(stream.events, 4) + expect(events.map((event) => event.type)).toEqual([ + "experimental.space.updated", + "experimental.space.deleted", + "experimental.space.updated", + "experimental.space.deleted", + ]) + expect(events.reduce(applyEvent, state)).toEqual(yield* current(store, "app")) + }), +) + +it.live("checks a space's tombstones on its first delete after a start, then on every 64th that makes one", () => + Effect.gen(function* () { + const { boot, db } = yield* setup + const limit = SpaceRows.TombstoneLimit + const interval = SpaceStore.PurgeInterval + // As a previous process left them: 5 tombstones past the limit. + const rows = range(limit + 5).map((index) => ({ space: "app", key: `t${index}`, value: null, revision: index + 1 })) + for (let start = 0; start < rows.length; start += 1000) + yield* db + .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 floor = SpaceRows.floor(db, "app") + + const { store } = yield* boot() + yield* Effect.forEach(range(interval + 2), (index) => store.set("app", `k${index}`, String(index)), { + discard: true, + }) + yield* store.remove("app", "missing") + // Neither writes nor deletes that make no tombstone check. + expect([yield* tombstones, yield* floor]).toEqual([limit + 5, 0]) + yield* store.remove("app", "k0") + expect([yield* tombstones, yield* floor]).toEqual([limit, 6]) + + yield* Effect.forEach( + range(interval - 1), + (index) => + Effect.all([ + store.remove("app", `k${index + 1}`), + store.remove("app", `k${index + 1}`), + store.remove("app", "missing"), + store.set("app", "written", String(index)), + ]), + { discard: true }, + ) + // At most `interval - 1` past the limit between checks. + expect([yield* tombstones, yield* floor]).toEqual([limit + interval - 1, 6]) + yield* store.remove("app", `k${interval}`) + 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.remove("app", `k${interval + 1}`) + expect([yield* tombstones, yield* floor]).toEqual([limit, 7 + interval]) + }), +) diff --git a/packages/server/test/space.test.ts b/packages/server/test/space.test.ts new file mode 100644 index 00000000000..2bc714c87e7 --- /dev/null +++ b/packages/server/test/space.test.ts @@ -0,0 +1,302 @@ +import path from "node:path" +import { expect } from "bun:test" +import { OpenCode } from "@opencode/client" +import { Effect } from "effect" +import { tmpdirScoped } from "../../core/test/fixture/tmpdir" +import { it } from "../../core/test/lib/effect" +import { ServerFetch } from "../src/fetch" + +const authorization = `Basic ${btoa("opencode:secret")}` + +const client = (handler: (request: Request) => Promise, headers?: Record) => + OpenCode.make({ + baseUrl: "http://opencode.local", + headers, + fetch: Object.assign((input: string | URL | Request, init?: RequestInit) => handler(new Request(input, init)), { + preconnect: fetch.preconnect, + }), + }) + +// Reads the wire stream directly: each call is its own connection, with its own stream ID and HTTP status. +const subscribe = async ( + handler: (request: Request) => Promise, + query: string, + headers: Record = { authorization }, +) => { + const response = await handler(new Request(`http://opencode.local/api/event?${query}`, { headers })) + const reader = response.body?.pipeThrough(new TextDecoderStream()).getReader() + const frames: string[] = [] + let buffer = "" + return { + status: response.status, + next: async (): Promise<{ readonly type: string; readonly data: unknown }> => { + while (frames.length === 0) { + const chunk = await reader?.read() + if (!chunk || chunk.done) throw new Error("event stream closed") + const parts = (buffer + chunk.value).split("\n\n") + buffer = parts.pop() ?? "" + frames.push(...parts.filter((part) => part.startsWith("data: "))) + } + const event = JSON.parse(frames.shift()?.slice("data: ".length) ?? "") + return { type: event.type, data: event.data } + }, + close: () => reader?.cancel(), + } +} + +it.live("syncs a space through the API and follows it on the event stream, across a restart", () => + Effect.gen(function* () { + const dir = (yield* tmpdirScoped("opencode-space-api-")).path + const boot = ServerFetch.make({ + app: { version: "test" }, + password: "secret", + database: { path: path.join(dir, "opencode.db") }, + config: { + directory: dir, + project: false, + claude: false, + content: "{}", + }, + models: { fetch: false }, + fs: { filewatcher: false }, + }) + + // Issued by the database, so it survives the restart below. + let epoch = "" + let cursor = "" + yield* Effect.scoped( + Effect.gen(function* () { + const handler = yield* boot + const writer = client(handler, { authorization }) + yield* Effect.promise(async () => { + // A stream that subscribes to no space still connects at once and gets its other events. + const plain = await subscribe(handler, "types=session.created") + const connected = await plain.next() + expect(connected.type).toBe("server.connected") + const stream = (connected.data as { stream: string }).stream + expect(stream).toMatch(/^[0-9a-f-]{36}$/u) + await writer.session.create({ location: { directory: dir } }) + expect((await plain.next()).type).toBe("session.created") + + await writer.experimental.space.set({ space: "app", key: "draft/1", value: '{"text":"hi","n":[1,null]}' }) + await writer.experimental.space.set({ space: "other", 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`, + }) + // Between the sync and the subscription. + await writer.experimental.space.set({ space: "app", key: "draft/2", value: "2" }) + await writer.experimental.space.subscribe({ + stream: readerStream, + 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.set({ space: "other", key: "draft/1", value: "unseen" }) + await writer.experimental.space.delete({ space: "app", key: "draft/1" }) + await writer.session.create({ location: { directory: dir } }) + expect(await reader.next()).toEqual({ + type: "experimental.space.deleted", + data: { space: "app", key: "draft/1", revision: 3 }, + }) + expect((await reader.next()).type).toBe("session.created") + // The stream that subscribed to nothing sees no space events at all. + expect((await plain.next()).type).toBe("session.created") + // Unsubscribing a space the stream does not follow succeeds. + await writer.experimental.space.unsubscribe({ stream, spaces: ["never"] }) + await reader.close() + await plain.close() + cursor = `${epoch}.3` + + // A closed stream, or one that never existed, cannot be subscribed. + await expect( + 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: [] }), + ).rejects.toMatchObject({ _tag: "InvalidRequestError", kind: "stream_not_found", field: "stream" }) + await expect( + writer.experimental.space.unsubscribe({ stream: "not-a-stream", spaces: ["app"] }), + ).rejects.toMatchObject({ _tag: "InvalidRequestError", kind: "stream_not_found", field: "stream" }) + + // Offline: repeated updates, a key created and deleted, and deletes of already deleted keys. + await writer.experimental.space.set({ space: "app", key: "draft/2", value: "3" }) + await writer.experimental.space.set({ space: "app", key: "draft/2", value: "4" }) + await writer.experimental.space.set({ space: "app", key: "draft/3", value: "x" }) + await writer.experimental.space.delete({ space: "app", key: "draft/3" }) + await writer.experimental.space.delete({ space: "app", key: "draft/3" }) + await writer.experimental.space.delete({ space: "app", key: "draft/1" }) + 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`, + }) + cursor = `${epoch}.7` + + const anonymous = client(handler) + for (const call of [ + () => anonymous.experimental.space.set({ space: "app", key: "x", value: "1" }), + () => anonymous.experimental.space.sync({ space: "app" }), + () => anonymous.experimental.space.subscribe({ stream, spaces: [] }), + () => anonymous.experimental.space.unsubscribe({ stream, spaces: [] }), + ]) + await expect(call()).rejects.toMatchObject({ _tag: "UnauthorizedError" }) + expect((await subscribe(handler, "", {})).status).toBe(401) + const empty = await handler( + new Request("http://opencode.local/api/experimental/space/app/c", { + method: "PUT", + headers: { authorization, "content-type": "application/json" }, + body: JSON.stringify({ value: null }), + }), + ) + expect(empty.status).toBe(400) + // The cap is the value's UTF-8 length: exactly 1 MiB is stored, one byte more is not. In its own space, so + // the revisions above are unchanged. + const put = (space: string, value: string) => + handler( + new Request(`http://opencode.local/api/experimental/space/${space}/c`, { + method: "PUT", + headers: { authorization, "content-type": "application/json" }, + body: JSON.stringify({ value }), + }), + ) + expect((await put("limit", "x".repeat(1024 * 1024))).status).toBe(204) + expect((await put("limit", "x".repeat(1024 * 1024 + 1))).status).toBe(400) + }) + }), + ) + + const handler = yield* boot + yield* Effect.promise(async () => { + 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.set({ 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.delete({ space: "app", key: "draft/4" }) + expect(await reader.next()).toEqual({ + type: "experimental.space.deleted", + data: { space: "app", key: "draft/4", revision: 9 }, + }) + await reader.close() + + // 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) + }) + }).pipe(Effect.scoped), +) + +it.live("two clients follow one space on their own streams, through unsubscribe and a reconnect", () => + Effect.gen(function* () { + const dir = (yield* tmpdirScoped("opencode-space-clients-")).path + const handler = yield* ServerFetch.make({ + app: { version: "test" }, + password: "secret", + database: { path: path.join(dir, "opencode.db") }, + config: { directory: dir, project: false, claude: false, content: "{}" }, + models: { fetch: false }, + fs: { filewatcher: false }, + }) + yield* Effect.promise(async () => { + const api = client(handler, { authorization }) + const updated = (key: string, value: string, revision: number) => ({ + type: "experimental.space.updated", + data: { space: "pins", key, value, revision }, + }) + const deleted = (key: string, revision: number) => ({ + type: "experimental.space.deleted", + data: { space: "pins", key, revision }, + }) + // Each client opens its own stream and reads its ID, then syncs unless it has a saved cursor, and subscribes. + 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 + await api.experimental.space.subscribe({ + stream, + spaces: [{ space: "pins", cursor: saved ?? page?.cursor ?? "" }], + }) + return { events, stream, page } + } + + const a = await follow() + const b = await follow() + expect(a.stream).not.toBe(b.stream) + const epoch = a.page?.epoch ?? "" + 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.set({ 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.delete({ space: "pins", key: "x" }) + expect([await a.events.next(), await b.events.next()]).toEqual([deleted("x", 2), deleted("x", 2)]) + await api.experimental.space.set({ 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.set({ 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") + expect((await b.events.next()).type).toBe("session.created") + + // 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.set({ space: "pins", key: "a", value: "4" }) + await api.experimental.space.set({ space: "pins", key: "b", value: "5" }) + await api.experimental.space.delete({ space: "pins", key: "a" }) + const back = await follow(`${epoch}.3`) + expect(back.stream).not.toBe(b.stream) + await api.experimental.space.set({ 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(), + await back.events.next(), + await back.events.next(), + await back.events.next(), + ]).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`, + }) + await a.events.close() + await back.events.close() + }) + }).pipe(Effect.scoped), +)