diff --git a/packages/client/src/effect/api/api.ts b/packages/client/src/effect/api/api.ts index c6548ef7d41..e6d7cd236a0 100644 --- a/packages/client/src/effect/api/api.ts +++ b/packages/client/src/effect/api/api.ts @@ -2678,17 +2678,14 @@ 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 ExperimentalSpaceWriteInput = { + readonly space: string + readonly changes: ReadonlyArray<{ readonly key: string; readonly value: string | null }> +} +export type ExperimentalSpaceWriteOutput = { readonly revision: number; readonly cursor: string } +export type ExperimentalSpaceWriteOperation = ( + input: ExperimentalSpaceWriteInput, +) => Effect.Effect export type ExperimentalSpaceSyncInput = { readonly space: string; readonly cursor?: string | undefined } export type ExperimentalSpaceSyncOutput = @@ -2787,8 +2784,7 @@ export interface ExperimentalApi { readonly settings: { readonly set: ExperimentalPushSettingsSetOperation } } readonly space: { - readonly set: ExperimentalSpaceSetOperation - readonly delete: ExperimentalSpaceDeleteOperation + readonly write: ExperimentalSpaceWriteOperation readonly sync: ExperimentalSpaceSyncOperation readonly subscribe: ExperimentalSpaceSubscribeOperation readonly unsubscribe: ExperimentalSpaceUnsubscribeOperation diff --git a/packages/client/src/effect/generated/client.ts b/packages/client/src/effect/generated/client.ts index 06e25f7ce33..9bcb095e09a 100644 --- a/packages/client/src/effect/generated/client.ts +++ b/packages/client/src/effect/generated/client.ts @@ -298,10 +298,8 @@ import type { ExperimentalPushSessionRemoveOutput, ExperimentalPushSettingsSetInput, ExperimentalPushSettingsSetOutput, - ExperimentalSpaceSetInput, - ExperimentalSpaceSetOutput, - ExperimentalSpaceDeleteInput, - ExperimentalSpaceDeleteOutput, + ExperimentalSpaceWriteInput, + ExperimentalSpaceWriteOutput, ExperimentalSpaceSyncInput, ExperimentalSpaceSyncOutput, ExperimentalSpaceSubscribeInput, @@ -1912,17 +1910,10 @@ 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( +const EndpointExperimentalSpaceWrite = + (raw: RawClient["server.experimental"]) => (input: ExperimentalSpaceWriteInput) => + preserveEffect()( + raw["space.write"]({ params: { space: input["space"] }, payload: { changes: input["changes"] } }).pipe( Effect.mapError(mapClientError), ), ) @@ -2004,8 +1995,7 @@ const adaptGroupExperimental = (raw: RawClient["server.experimental"]) => ({ settings: { set: EndpointExperimentalPushSettingsSet(raw) }, }, space: { - set: EndpointExperimentalSpaceSet(raw), - delete: EndpointExperimentalSpaceDelete(raw), + write: EndpointExperimentalSpaceWrite(raw), sync: EndpointExperimentalSpaceSync(raw), subscribe: EndpointExperimentalSpaceSubscribe(raw), unsubscribe: EndpointExperimentalSpaceUnsubscribe(raw), diff --git a/packages/client/src/promise/generated/client.ts b/packages/client/src/promise/generated/client.ts index 1992a513297..5982d5d6f66 100644 --- a/packages/client/src/promise/generated/client.ts +++ b/packages/client/src/promise/generated/client.ts @@ -304,10 +304,8 @@ import type { ExperimentalPushSessionRemoveOutput, ExperimentalPushSettingsSetInput, ExperimentalPushSettingsSetOutput, - ExperimentalSpaceSetInput, - ExperimentalSpaceSetOutput, - ExperimentalSpaceDeleteInput, - ExperimentalSpaceDeleteOutput, + ExperimentalSpaceWriteInput, + ExperimentalSpaceWriteOutput, ExperimentalSpaceSyncInput, ExperimentalSpaceSyncOutput, ExperimentalSpaceSubscribeInput, @@ -1993,26 +1991,15 @@ export function make(options: ClientOptions) { }, }, space: { - set: (input: ExperimentalSpaceSetInput, requestOptions?: RequestOptions) => - request( + write: (input: ExperimentalSpaceWriteInput, requestOptions?: RequestOptions) => + request( { - method: "PUT", - path: `/api/experimental/space/${encodeURIComponent(input.space)}/${encodeURIComponent(input.key)}`, - body: { value: input["value"] }, - successStatus: 204, + method: "POST", + path: `/api/experimental/space/${encodeURIComponent(input.space)}/write`, + body: { changes: input["changes"] }, + successStatus: 200, 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, + empty: false, }, requestOptions, ), diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index a4de0f60720..a3a5fafd92a 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -394,10 +394,10 @@ export type PushLevel = "all" | "attention" | "none" export type PushRegistered = { publicKey: string } -export type SpaceEpoch = string - export type SpaceCursor = string +export type SpaceEpoch = string + export type ReferenceGitSource = { type: "git"; repository: string; branch?: string } export type VcsBranch = { current?: string; default?: string } @@ -5075,13 +5075,12 @@ 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 ExperimentalSpaceWriteInput = { + readonly space: string + readonly changes: ReadonlyArray<{ readonly key: string; readonly value: string | null }> +} -export type ExperimentalSpaceSetOutput = void - -export type ExperimentalSpaceDeleteInput = { readonly space: string; readonly key: string } - -export type ExperimentalSpaceDeleteOutput = void +export type ExperimentalSpaceWriteOutput = { revision: SpaceRevision; cursor: SpaceCursor } export type ExperimentalSpaceSyncInput = { readonly space: string; readonly cursor?: string | undefined } diff --git a/packages/core/src/space.ts b/packages/core/src/space.ts index d16508710cd..0834921305c 100644 --- a/packages/core/src/space.ts +++ b/packages/core/src/space.ts @@ -7,6 +7,7 @@ import type { Database } from "./database/database.js" import { SpaceTable } from "./space/sql.js" type Db = Database.Interface["db"] +type Transaction = Parameters[0]>[0] // 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. @@ -19,7 +20,7 @@ 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) => +export const set = (db: Db | Transaction, space: Space.Name, key: Space.Key, value: Space.Value) => db .insert(SpaceTable) .values({ space, key, value, revision: next(space) }) @@ -35,7 +36,7 @@ export const set = (db: Db, space: Space.Name, key: Space.Key, value: Space.Valu ) /** 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) => +export const remove = (db: Db | Transaction, space: Space.Name, key: Space.Key) => db .update(SpaceTable) .set({ value: null, revision: next(space) }) @@ -47,6 +48,28 @@ export const remove = (db: Db, space: Space.Name, key: Space.Key) => Effect.map((row) => row?.revision), ) +/** + * Applies the changes in order in one transaction, as if written one after another: each that changes a row takes the + * next revision, so a key changed twice gets both and keeps the last. Returns those changes, and the head after them. + */ +export const write = (db: Db, space: Space.Name, changes: ReadonlyArray) => + db + .transaction((tx) => + Effect.gen(function* () { + const written = yield* Effect.forEach(changes, (change) => + change.value === null + ? remove(tx, space, change.key).pipe( + Effect.map((revision) => (revision === undefined ? [] : [{ key: change.key, value: null, revision }])), + ) + : set(tx, space, change.key, change.value).pipe( + Effect.map((revision) => [{ key: change.key, value: change.value, revision }]), + ), + ).pipe(Effect.map((rows) => rows.flat())) + return { written, head: written.at(-1)?.revision ?? (yield* head(tx, space)) } + }), + ) + .pipe(Effect.orDie) + /** Tombstones a space keeps once `purge` runs. */ export const TombstoneLimit = 10_000 @@ -94,7 +117,7 @@ export const floor = (db: Db, space: Space.Name) => ) /** The space's highest revision, 0 before its first write. */ -export const head = (db: Db, space: Space.Name) => +export const head = (db: Db | Transaction, space: Space.Name) => db .select({ revision: max(SpaceTable.revision) }) .from(SpaceTable) diff --git a/packages/core/test/space.test.ts b/packages/core/test/space.test.ts index b6c45fbabe0..c8f6af82254 100644 --- a/packages/core/test/space.test.ts +++ b/packages/core/test/space.test.ts @@ -79,6 +79,30 @@ describe.each([ }), ) + it.effect("writes changes in order in one transaction, returning those that changed a row and the head", () => + Effect.gen(function* () { + const db = (yield* Database.Service).db + expect( + yield* SpaceRows.write(db, "batch", [ + { key: "a", value: "1" }, + { key: "b", value: null }, + { key: "a", value: null }, + { key: "a", value: null }, + { key: "b", value: "2" }, + ]), + ).toEqual({ + written: [ + { key: "a", value: "1", revision: 1 }, + { key: "a", value: null, revision: 2 }, + { key: "b", value: "2", revision: 3 }, + ], + head: 3, + }) + expect(yield* SpaceRows.write(db, "batch", [{ key: "c", value: null }])).toEqual({ written: [], head: 3 }) + expect(yield* SpaceRows.write(db, "unwritten", [])).toEqual({ written: [], head: 0 }) + }), + ) + 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 diff --git a/packages/protocol/openapi.json b/packages/protocol/openapi.json index 0f7f177a345..fa52f78f2f6 100644 --- a/packages/protocol/openapi.json +++ b/packages/protocol/openapi.json @@ -14913,10 +14913,10 @@ } } }, - "/api/experimental/space/{space}/{key}": { - "put": { + "/api/experimental/space/{space}/write": { + "post": { "tags": ["experimental"], - "operationId": "experimental.space.set", + "operationId": "experimental.space.write", "parameters": [ { "name": "space", @@ -14925,20 +14925,29 @@ "$ref": "#/components/schemas/Space.Name" }, "required": true - }, - { - "name": "key", - "in": "path", - "schema": { - "$ref": "#/components/schemas/Space.Key" - }, - "required": true } ], "security": [], "responses": { - "204": { - "description": "" + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "revision": { + "$ref": "#/components/schemas/Space.Revision" + }, + "cursor": { + "$ref": "#/components/schemas/Space.Cursor" + } + }, + "required": ["revision", "cursor"], + "additionalProperties": false + } + } + } }, "400": { "description": "InvalidRequestError", @@ -14961,75 +14970,30 @@ } } }, - "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", + "description": "Commit 1 to 1024 changes in one transaction, their values at most 1 MiB of UTF-8 in total. A string value sets the key, replacing any previous value; null deletes it, and deleting an unset key changes nothing. In request order, each change that changes a key takes the space's next revision and goes to its subscribers as its own experimental.space.updated or experimental.space.deleted event, so a key that appears twice keeps its last value. Values are client-defined, such as JSON text, and sent back unchanged. Returns the space's revision after the write. To follow a space, a client opens /api/event and reads its stream ID from server.connected, syncs with experimental.space.sync until no `next` remains, then subscribes the stream with the saved cursor through experimental.space.subscribe and applies the stream's events in order. On experimental.space.resync it syncs and subscribes that space again; after a reconnect it subscribes again with its latest cursor. Experimental: may change without compatibility guarantees.", + "summary": "Write values", "requestBody": { "content": { "application/json": { "schema": { "type": "object", "properties": { - "value": { - "$ref": "#/components/schemas/Space.Value" + "changes": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Space.Change" + }, + "minItems": 1, + "maxItems": 1024 } }, - "required": ["value"], + "required": ["changes"], "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}": { @@ -15051,7 +15015,7 @@ "schema": { "anyOf": [ { - "$ref": "#/components/schemas/Space.Cursor" + "$ref": "#/components/schemas/Space.Cursor_1" } ] }, @@ -15148,7 +15112,7 @@ "$ref": "#/components/schemas/Space.Name" }, "cursor": { - "$ref": "#/components/schemas/Space.Cursor" + "$ref": "#/components/schemas/Space.Cursor_1" } }, "required": ["space", "cursor"], @@ -27668,10 +27632,34 @@ "Snapshot.ID": { "type": "string" }, + "Space.Change": { + "type": "object", + "properties": { + "key": { + "$ref": "#/components/schemas/Space.Key" + }, + "value": { + "anyOf": [ + { + "$ref": "#/components/schemas/Space.Value" + }, + { + "type": "null" + } + ] + } + }, + "required": ["key", "value"], + "additionalProperties": false + }, "Space.Cursor": { - "type": "string" + "type": "string", + "description": "Covers this write and every change before it." }, "Space.Cursor_1": { + "type": "string" + }, + "Space.Cursor_2": { "type": "string", "description": "Covers every change up to this page; save it to subscribe or sync from." }, @@ -27698,10 +27686,10 @@ } }, "cursor": { - "$ref": "#/components/schemas/Space.Cursor_1" + "$ref": "#/components/schemas/Space.Cursor_2" }, "next": { - "$ref": "#/components/schemas/Space.Cursor" + "$ref": "#/components/schemas/Space.Cursor_1" }, "deleted": { "type": "array", @@ -27777,10 +27765,10 @@ } }, "cursor": { - "$ref": "#/components/schemas/Space.Cursor_1" + "$ref": "#/components/schemas/Space.Cursor_2" }, "next": { - "$ref": "#/components/schemas/Space.Cursor" + "$ref": "#/components/schemas/Space.Cursor_1" } }, "required": ["type", "space", "epoch", "revision", "entries", "cursor"], diff --git a/packages/protocol/src/groups/space.ts b/packages/protocol/src/groups/space.ts index 03a2d7033a2..b2a7ceb130c 100644 --- a/packages/protocol/src/groups/space.ts +++ b/packages/protocol/src/groups/space.ts @@ -3,7 +3,6 @@ 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}`, @@ -15,26 +14,21 @@ const annotations = (identifier: string, summary: string, description: string) = /** 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 }), + HttpApiEndpoint.post("space.write", "/api/experimental/space/:space/write", { + params: { space: Space.Name }, + payload: Schema.Struct({ + changes: Schema.Array(Space.Change).check(Schema.isMinLength(1), Schema.isMaxLength(Space.MaxChanges)), + }), error: InvalidRequestError, - success: HttpApiSchema.NoContent, + success: Schema.Struct({ + revision: Space.Revision, + cursor: Space.Cursor.annotate({ description: "Covers this write and every change before it." }), + }), }).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.", + "write", + "Write values", + "Commit 1 to 1024 changes in one transaction, their values at most 1 MiB of UTF-8 in total. A string value sets the key, replacing any previous value; null deletes it, and deleting an unset key changes nothing. In request order, each change that changes a key takes the space's next revision and goes to its subscribers as its own experimental.space.updated or experimental.space.deleted event, so a key that appears twice keeps its last value. Values are client-defined, such as JSON text, and sent back unchanged. Returns the space's revision after the write.", ), ), HttpApiEndpoint.get("space.sync", "/api/experimental/space/:space", { diff --git a/packages/schema/src/space.ts b/packages/schema/src/space.ts index 39d7eedf5f3..f8d1fd27749 100644 --- a/packages/schema/src/space.ts +++ b/packages/schema/src/space.ts @@ -19,12 +19,21 @@ export type Key = typeof Key.Type 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. */ +/** A value always goes out as one event, so a write's values are capped at 1 MiB of UTF-8 in total. */ export const MaxValueBytes = 1024 * 1024 export interface Entry extends Schema.Schema.Type {} export const Entry = Schema.Struct({ key: Key, value: Value }).annotate({ identifier: "Space.Entry" }) +/** One change of a write: a value sets the key, `null` deletes it. */ +export interface Change extends Schema.Schema.Type {} +export const Change = Schema.Struct({ key: Key, value: Schema.NullOr(Value) }).annotate({ + identifier: "Space.Change", +}) + +/** Changes one write commits at most. */ +export const MaxChanges = 1024 + /** 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 diff --git a/packages/server/src/handlers/persistent-pty.ts b/packages/server/src/handlers/persistent-pty.ts index f65b41d1bd2..96a96d71975 100644 --- a/packages/server/src/handlers/persistent-pty.ts +++ b/packages/server/src/handlers/persistent-pty.ts @@ -63,8 +63,7 @@ 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.write", (ctx) => space.write(ctx.params.space, ctx.payload.changes)) .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)) diff --git a/packages/server/src/handlers/space.ts b/packages/server/src/handlers/space.ts index dbde55c2dbd..98cbe122936 100644 --- a/packages/server/src/handlers/space.ts +++ b/packages/server/src/handlers/space.ts @@ -12,11 +12,15 @@ 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() + write: Effect.fn("SpaceHandler.write")(function* (space: Space.Name, changes: ReadonlyArray) { + const encoder = new TextEncoder() + const bytes = changes.reduce( + (total, change) => total + (change.value === null ? 0 : encoder.encode(change.value).length), + 0, + ) + if (bytes > Space.MaxValueBytes) + return yield* new InvalidRequestError({ message: "Values exceed 1 MiB of UTF-8 in total", field: "changes" }) + return yield* store.write(space, changes) }), sync: Effect.fn("SpaceHandler.sync")(function* (space: Space.Name, cursor: string | undefined) { return yield* store.sync(space, cursor) @@ -39,9 +43,5 @@ export const makeSpace = Effect.gen(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/space-store.ts b/packages/server/src/space-store.ts index 8956dbc16e0..ccdfec84908 100644 --- a/packages/server/src/space-store.ts +++ b/packages/server/src/space-store.ts @@ -20,8 +20,14 @@ 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 + /** + * Commits the changes in one transaction, as `SpaceRows.write` applies them, then sends each one that changed a row + * in revision order. Returns the space's head after them, with its cursor. + */ + readonly write: ( + space: Space.Name, + changes: ReadonlyArray, + ) => Effect.Effect<{ readonly revision: Space.Revision; readonly cursor: string }> /** This database's epoch, created once and kept, so revisions from another server or database are never used. */ readonly epoch: string /** Replaces the epoch: every client's next sync starts from a snapshot, e.g. after a database restore. */ @@ -64,37 +70,24 @@ const layer = Layer.effect( ), ) const listeners = new Array() - // Held per space from the commit until listeners have the change, so they get each space in revision order. + // Held per space from the commit until listeners have its changes, 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) => + const tombstoned = (space: Space.Name, count: number) => Effect.suspend(() => { - const since = (deletes.get(space) ?? PurgeInterval - 1) + 1 + if (count === 0) return Effect.void + const since = (deletes.get(space) ?? PurgeInterval - 1) + count 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. + // The deletes are committed already, so a failed purge must not keep listeners from hearing of them. 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() @@ -165,31 +158,26 @@ const layer = Layer.effect( 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, - ), - ), + events: rows.map((row) => change(space, row, 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 })), - ), + write: Effect.fn("SpaceStore.write")(function* (space, changes) { + return yield* locks.withLock(space)( + // A dropped request must not commit changes that listeners never hear about. + Effect.uninterruptible( + Effect.gen(function* () { + const result = yield* SpaceRows.write(db, space, changes) + yield* tombstoned(space, result.written.filter((row) => row.value === null).length) + const created = yield* Clock.currentTimeMillis + for (const row of result.written) { + const committed = change(space, row, created) + yield* Effect.forEach(listeners, (listener) => listener(committed), { discard: true }) + yield* Effect.forEach(streams.values(), (stream) => deliver(stream, committed), { discard: true }) + } + return { revision: result.head, cursor: `${epoch}.${result.head}` } + }), ), ) }), @@ -290,10 +278,24 @@ interface Attached { 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 change( + space: Space.Name, + row: { readonly key: Space.Key; readonly value: Space.Value | null; readonly revision: Space.Revision }, + created: number, +): Change { + return row.value === null + ? { + id: Event.ID.create(), + created, + type: Space.Event.Deleted.type, + data: { space, key: row.key, revision: row.revision }, + } + : { + id: Event.ID.create(), + created, + type: Space.Event.Updated.type, + data: { space, key: row.key, value: row.value, revision: row.revision }, + } } function entries(rows: ReadonlyArray<{ readonly key: Space.Key; readonly value: Space.Value | null }>) { diff --git a/packages/server/test/space-store.test.ts b/packages/server/test/space-store.test.ts index 5a33d3b9ad0..5d4edd72fb7 100644 --- a/packages/server/test/space-store.test.ts +++ b/packages/server/test/space-store.test.ts @@ -5,7 +5,7 @@ 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 { 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" @@ -93,7 +93,10 @@ it.live("syncs a space in pages: live rows up to the starting head, then a delta const { boot } = yield* setup const { store } = yield* boot() const count = SpaceStore.BatchSize + 10 - yield* Effect.forEach(range(count), (index) => store.set("big", `k${index}`, String(index)), { discard: true }) + yield* store.write( + "big", + range(count).map((index) => ({ key: `k${index}`, value: String(index) })), + ) const epoch = store.epoch const first = yield* store.sync("big") @@ -105,10 +108,10 @@ it.live("syncs a space in pages: live rows up to the starting head, then a delta `${epoch}.${SpaceStore.BatchSize}.${count}`, ]) // Between pages: a delete and a rewrite of keys the first page held, and of keys the second would hold. - yield* store.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}`) + yield* store.write("big", [{ key: "k0", value: null }]) + yield* store.write("big", [{ key: "k1", value: "new" }]) + yield* store.write("big", [{ key: `k${SpaceStore.BatchSize + 5}`, value: "new" }]) + yield* store.write("big", [{ key: `k${SpaceStore.BatchSize + 6}`, value: null }]) 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. @@ -155,10 +158,11 @@ it.live("a snapshot reads no tombstones, and its last page reports the head it s Effect.gen(function* () { const { boot } = yield* setup const { store } = yield* boot() - yield* Effect.forEach(range(SpaceStore.BatchSize + 1), (index) => store.set("big", `k${index}`, String(index)), { - discard: true, - }) - yield* store.remove("big", "k0") + yield* store.write( + "big", + range(SpaceStore.BatchSize + 1).map((index) => ({ key: `k${index}`, value: String(index) })), + ) + yield* store.write("big", [{ key: "k0", value: null }]) const page = yield* store.sync("big") expect([page.type, page.revision, page.entries.length, page.next]).toEqual([ "snapshot", @@ -174,20 +178,20 @@ it.live("syncs each space from its cursor: final values and deletions, else a sn Effect.gen(function* () { const { boot } = yield* setup const { store } = yield* boot() - yield* store.set("app", "kept", "v1") - yield* store.set("app", "churn", "1") - yield* store.set("app", "doomed", "true") - yield* store.set("other", "x", "y") + yield* store.write("app", [{ key: "kept", value: "v1" }]) + yield* store.write("app", [{ key: "churn", value: "1" }]) + yield* store.write("app", [{ key: "doomed", value: "true" }]) + yield* store.write("other", [{ key: "x", value: "y" }]) // 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") + yield* store.write("app", [{ key: "churn", value: "2" }]) + yield* store.write("app", [{ key: "churn", value: "3" }]) + yield* store.write("app", [{ key: "doomed", value: null }]) + yield* store.write("app", [{ key: "doomed", value: null }]) + yield* store.write("app", [{ key: "never-set", value: null }]) + yield* store.write("app", [{ key: "back", value: "a" }]) + yield* store.write("app", [{ key: "back", value: null }]) + yield* store.write("app", [{ key: "back", value: "b" }]) const epoch = store.epoch const page = (space: string, cursor?: string) => store.sync(space, cursor) @@ -239,7 +243,10 @@ it.live("a cursor below the space's floor gets a snapshot and one at or above it Effect.gen(function* () { const { boot, db } = yield* setup const before = yield* boot() - yield* Effect.forEach(["a", "b", "c", "d"], (key) => before.store.set("app", key, key), { discard: true }) + yield* before.store.write( + "app", + ["a", "b", "c", "d"].map((key) => ({ key, value: key })), + ) // 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) @@ -274,12 +281,16 @@ it.live("a delta page whose deletions were purged meanwhile comes back as a snap const { boot, db } = yield* setup const { store } = yield* boot() // The client holds k0 to k9, at revision 10. - yield* Effect.forEach(range(10), (index) => store.set("app", `k${index}`, String(index)), { discard: true }) + yield* store.write( + "app", + range(10).map((index) => ({ key: `k${index}`, value: String(index) })), + ) const held = new Map(range(10).map((index) => [`k${index}`, String(index)])) // Then come a full page of new keys and two tombstones. - yield* Effect.forEach(range(SpaceStore.BatchSize), (index) => store.set("app", `u${index}`, String(index)), { - discard: true, - }) + yield* store.write( + "app", + range(SpaceStore.BatchSize).map((index) => ({ key: `u${index}`, value: String(index) })), + ) yield* SpaceRows.remove(db, "app", "k0") yield* SpaceRows.remove(db, "app", "k1") @@ -305,14 +316,14 @@ 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") + yield* before.store.write("app", [{ key: "k", value: "a" }]) + yield* before.store.write("app", [{ key: "k", value: "b" }]) + yield* before.store.write("app", [{ key: "k", value: null }]) // 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") + yield* after.store.write("app", [{ key: "j", value: "c" }]) expect(yield* after.store.sync("app", `${after.store.epoch}.1`)).toEqual({ type: "delta", space: "app", @@ -329,21 +340,21 @@ it.live("a subscription sends the changes since its cursor once, then live chang Effect.gen(function* () { const { boot } = yield* setup const { store, feed, bus } = yield* boot() - yield* store.set("app", "k", "1") - yield* store.set("app", "gone", "x") - yield* store.set("other", "x", "1") + yield* store.write("app", [{ key: "k", value: "1" }]) + yield* store.write("app", [{ key: "gone", value: "x" }]) + yield* store.write("other", [{ key: "x", value: "1" }]) const synced = yield* store.sync("app") // After the sync and before the subscription. - yield* store.set("app", "k", "2") - yield* store.remove("app", "gone") + yield* store.write("app", [{ key: "k", value: "2" }]) + yield* store.write("app", [{ key: "gone", value: null }]) const stream = yield* feed.subscribe([Agent.Event.Updated.type]) const plain = yield* feed.subscribe() const seen: Array = [] yield* bus.listen((event) => Effect.sync(() => seen.push(event.type))) expect(yield* store.subscribe(stream.id, [{ space: "app", cursor: synced.cursor }])).toBe(true) - yield* store.set("app", "k", "3") - yield* store.set("other", "x", "2") + yield* store.write("app", [{ key: "k", value: "3" }]) + yield* store.write("other", [{ key: "x", value: "2" }]) yield* bus.publish(Agent.Event.Updated, {}) // The changes since the cursor, one event per row in revision order, then the live ones. @@ -359,23 +370,86 @@ it.live("a subscription sends the changes since its cursor once, then live chang }), ) +it.live("a write commits all its changes, each at the next revision in order, then sends one event per change", () => + Effect.gen(function* () { + const { boot, hold } = yield* setup + const { store, feed } = yield* boot() + const epoch = store.epoch + const stream = yield* feed.subscribe() + yield* store.subscribe(stream.id, [{ space: "app", cursor: `${epoch}.0` }]) + const updated = (key: string, value: string, revision: number) => ({ + type: "experimental.space.updated", + data: { space: "app", key, value, revision }, + }) + const deleted = (key: string, revision: number) => ({ + type: "experimental.space.deleted", + data: { space: "app", key, revision }, + }) + + // The most changes a write takes: sets, then deletes of the same keys. + const half = Space.MaxChanges / 2 + expect( + yield* store.write( + "app", + range(Space.MaxChanges).map((index) => ({ key: `k${index % half}`, value: index < half ? `${index}` : null })), + ), + ).toEqual({ revision: Space.MaxChanges, cursor: `${epoch}.${Space.MaxChanges}` }) + expect(yield* take(stream.events, Space.MaxChanges)).toEqual([ + ...range(half).map((index) => updated(`k${index}`, `${index}`, index + 1)), + ...range(half).map((index) => deleted(`k${index}`, half + index + 1)), + ]) + + // Held after its first change reaches listeners: by then every change is committed. A delete of an unset key, or + // of one already deleted, takes no revision and sends nothing; a key changed twice gets both. + const head = Space.MaxChanges + const pending = yield* hold(head + 1) + const write = yield* store + .write("app", [ + { key: "a", value: "1" }, + { key: "never", value: null }, + { key: "a", value: "2" }, + { key: "b", value: "1" }, + { key: "b", value: null }, + { key: "b", value: null }, + ]) + .pipe(Effect.forkChild(now)) + yield* Deferred.await(pending.reached) + expect(yield* current(store, "app")).toEqual(new Map([["a", "2"]])) + yield* Deferred.succeed(pending.release, undefined) + // The head after the write, also when its last changes change nothing. + expect(yield* Fiber.join(write)).toEqual({ revision: head + 4, cursor: `${epoch}.${head + 4}` }) + expect(yield* store.write("app", [{ key: "never", value: null }])).toEqual({ + revision: head + 4, + cursor: `${epoch}.${head + 4}`, + }) + yield* store.write("app", [{ key: "c", value: "1" }]) + expect(yield* take(stream.events, 5)).toEqual([ + updated("a", "1", head + 1), + updated("a", "2", head + 2), + updated("b", "1", head + 3), + deleted("b", head + 4), + updated("c", "1", head + 5), + ]) + }), +) + 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") + yield* store.write("app", [{ key: "k", value: "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)) + const write = yield* store.write("app", [{ key: "k", value: "2" }]).pipe(Effect.forkChild(now)) yield* Deferred.await(pending.reached) // "2" is committed but not yet delivered, and the space's lock is held; neither sync, subscribe nor other spaces // wait for it. expect((yield* store.sync("app", synced.cursor)).revision).toBe(2) - yield* store.set("other", "x", "1") + yield* store.write("other", [{ key: "x", value: "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)) + const next = yield* store.write("app", [{ key: "k", value: "3" }]).pipe(Effect.forkChild(now)) yield* Deferred.succeed(pending.release, undefined) yield* Fiber.join(write) yield* Fiber.join(next) @@ -398,7 +472,10 @@ it.live("concurrent writes reach a subscribed stream in revision order", () => writes, (index) => Effect.all( - [store.set("app", `k${index % 4}`, String(index)), store.set(`space-${index % 3}`, "k", String(index))], + [ + store.write("app", [{ key: `k${index % 4}`, value: String(index) }]), + store.write(`space-${index % 3}`, [{ key: "k", value: String(index) }]), + ], { concurrency: "unbounded" }, ), { concurrency: "unbounded", discard: true }, @@ -419,15 +496,20 @@ it.live("a subscription sends resync instead of changes that do not fit one batc 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* store.write( + "big", + range(SpaceStore.BatchSize + 1).map((index) => ({ key: `k${index}`, value: String(index) })), + ) + yield* store.write( + "purged", + ["a", "b", "c"].map((key) => ({ key, value: key })), + ) yield* Effect.forEach(["a", "b", "c"], (key) => SpaceRows.remove(db, "purged", key), { discard: true }) yield* SpaceRows.purge(db, "purged", 2) - yield* Effect.forEach(range(SpaceStore.BatchSize), (index) => store.set("full", `k${index}`, String(index)), { - discard: true, - }) + yield* store.write( + "full", + range(SpaceStore.BatchSize).map((index) => ({ key: `k${index}`, value: String(index) })), + ) const stream = yield* feed.subscribe() yield* store.subscribe(stream.id, [ @@ -440,7 +522,7 @@ it.live("a subscription sends resync instead of changes that do not fit one batc // Exactly one batch still fits. { space: "full", cursor: `${epoch}.0` }, ]) - yield* store.set("big", "after", "true") + yield* store.write("big", [{ key: "after", value: "true" }]) const events = yield* take(stream.events, 5 + SpaceStore.BatchSize + 1) expect(events.slice(0, 5)).toEqual( ["big", "purged", "elsewhere", "ahead", "partial"].map((space) => ({ @@ -477,7 +559,7 @@ it.live("subscribe needs an open stream, and a stream leaves the store when it c ) expect(yield* store.subscribe(id, [{ space: "app", cursor }])).toBe(false) // Writes to a space a closed stream subscribed to go nowhere. - yield* store.set("app", "k", "1") + yield* store.write("app", [{ key: "k", value: "1" }]) }), ) @@ -488,9 +570,9 @@ it.live("subscribing a space again on the same stream replaces its subscription" 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.write("app", [{ key: "k", value: "1" }]) yield* store.subscribe(stream.id, [{ space: "app", cursor }]) - yield* store.set("app", "k", "2") + yield* store.write("app", [{ key: "k", value: "2" }]) const updated = (value: string, revision: number) => ({ type: "experimental.space.updated", @@ -534,8 +616,8 @@ it.live("of two overlapping subscribes of one space on a stream, only the newer type: "experimental.space.updated", data: { space, key, value, revision }, }) - yield* store.set("other", "x", "1") - yield* store.set("app", "a", "1") + yield* store.write("other", [{ key: "x", value: "1" }]) + yield* store.write("app", [{ key: "a", value: "1" }]) // The older subscribe pauses on its first space, before it reads app's changes; the newer one replaces its app. const first = yield* pausedStream(store, "first") @@ -546,11 +628,11 @@ it.live("of two overlapping subscribes of one space on a stream, only the newer ]) .pipe(Effect.forkChild(now)) yield* Deferred.await(first.reached) - yield* store.set("app", "b", "2") + yield* store.write("app", [{ key: "b", value: "2" }]) expect(yield* store.subscribe("first", [{ space: "app", cursor }])).toBe(true) yield* Deferred.succeed(first.release, undefined) yield* Fiber.join(older) - yield* store.set("app", "c", "3") + yield* store.write("app", [{ key: "c", value: "3" }]) expect(first.sent.filter((event) => (event.data as { space: string }).space === "app")).toEqual([ updated("app", "a", "1", 1), updated("app", "b", "2", 2), @@ -564,7 +646,7 @@ it.live("of two overlapping subscribes of one space on a stream, only the newer expect(yield* store.subscribe("second", [{ space: "app", cursor }])).toBe(true) yield* Deferred.succeed(second.release, undefined) yield* Fiber.join(paused) - yield* store.set("app", "d", "4") + yield* store.write("app", [{ key: "d", value: "4" }]) expect(second.sent).toEqual([ // The newer catch-up, then the one event the older was already sending, then the next change once. updated("app", "a", "1", 1), @@ -590,10 +672,10 @@ it.live("unsubscribing stops a space's events, also mid catch-up, while other sp { space: "app", cursor }, { space: "other", cursor }, ]) - yield* store.set("app", "a", "1") + yield* store.write("app", [{ key: "a", value: "1" }]) expect(yield* store.unsubscribe(stream.id, ["app"])).toBe(true) - yield* store.set("app", "b", "2") - yield* store.set("other", "x", "1") + yield* store.write("app", [{ key: "b", value: "2" }]) + yield* store.write("other", [{ key: "x", value: "1" }]) expect(yield* take(stream.events, 2)).toEqual([updated("app", "a", "1", 1), updated("other", "x", "1", 1)]) // A space the stream does not follow is fine; a stream that is not open is not. expect(yield* store.unsubscribe(stream.id, ["never"])).toBe(true) @@ -606,7 +688,7 @@ it.live("unsubscribing stops a space's events, also mid catch-up, while other sp expect(yield* store.unsubscribe("paused", ["app"])).toBe(true) yield* Deferred.succeed(paused.release, undefined) yield* Fiber.join(subscribing) - yield* store.set("app", "c", "3") + yield* store.write("app", [{ key: "c", value: "3" }]) // Only the event it was already sending. expect(paused.sent).toEqual([updated("app", "a", "1", 1)]) }), @@ -616,9 +698,10 @@ it.live("a client that syncs while writes go on, then subscribes, ends with exac Effect.gen(function* () { const { boot } = yield* setup const { store, feed } = yield* boot() - yield* Effect.forEach(range(SpaceStore.BatchSize + 5), (index) => store.set("app", `k${index}`, String(index)), { - discard: true, - }) + yield* store.write( + "app", + range(SpaceStore.BatchSize + 5).map((index) => ({ key: `k${index}`, value: String(index) })), + ) const stream = yield* feed.subscribe() // Writes between every page, and between the last page and the subscription. @@ -626,16 +709,16 @@ it.live("a client that syncs while writes go on, then subscribes, ends with exac 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}`) + yield* store.write("app", [{ key: `k${round}`, value: `during ${round}` }]) + yield* store.write("app", [{ key: `k${SpaceStore.BatchSize + round}`, value: null }]) page = yield* store.sync("app", page.next) applyPage(state, page) } - yield* store.set("app", "k1", "before subscribe") - yield* store.remove("app", "k2") + yield* store.write("app", [{ key: "k1", value: "before subscribe" }]) + yield* store.write("app", [{ key: "k2", value: null }]) yield* store.subscribe(stream.id, [{ space: "app", cursor: page.cursor }]) - yield* store.set("app", "k3", "live") - yield* store.remove("app", "k4") + yield* store.write("app", [{ key: "k3", value: "live" }]) + yield* store.write("app", [{ key: "k4", value: null }]) const events = yield* take(stream.events, 4) expect(events.map((event) => event.type)).toEqual([ @@ -666,34 +749,42 @@ it.live("checks a space's tombstones on its first delete after a start, then on 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") + yield* store.write( + "app", + range(interval + 2).map((index) => ({ key: `k${index}`, value: String(index) })), + ) + yield* store.write("app", [{ key: "missing", value: null }]) // Neither writes nor deletes that make no tombstone check. expect([yield* tombstones, yield* floor]).toEqual([limit + 5, 0]) - yield* store.remove("app", "k0") + yield* store.write("app", [{ key: "k0", value: null }]) 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)), + store.write("app", [ + { key: `k${index + 1}`, value: null }, + { key: `k${index + 1}`, value: null }, + { key: "missing", value: null }, + { key: "written", value: 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}`) + yield* store.write("app", [{ key: `k${interval}`, value: null }]) expect([yield* tombstones, yield* floor]).toEqual([limit, 6 + interval]) // A restarted store checks on the first delete again. const restarted = yield* boot() - yield* restarted.store.remove("app", `k${interval + 1}`) + yield* restarted.store.write("app", [{ key: `k${interval + 1}`, value: null }]) expect([yield* tombstones, yield* floor]).toEqual([limit, 7 + interval]) + + // A write that makes `interval` tombstones counts each of them, and checks once after it. + yield* restarted.store.write("app", [ + ...range(interval).map((index) => ({ key: `n${index}`, value: "1" })), + ...range(interval).map((index) => ({ key: `n${index}`, value: null })), + ]) + expect(yield* tombstones).toBe(limit) }), ) diff --git a/packages/server/test/space.test.ts b/packages/server/test/space.test.ts index 2bc714c87e7..f0456a12873 100644 --- a/packages/server/test/space.test.ts +++ b/packages/server/test/space.test.ts @@ -78,8 +78,11 @@ it.live("syncs a space through the API and follows it on the event stream, acros await writer.session.create({ location: { directory: dir } }) expect((await plain.next()).type).toBe("session.created") - await writer.experimental.space.set({ space: "app", key: "draft/1", value: '{"text":"hi","n":[1,null]}' }) - await writer.experimental.space.set({ space: "other", key: "draft/1", value: "elsewhere" }) + await writer.experimental.space.write({ + space: "app", + changes: [{ key: "draft/1", value: '{"text":"hi","n":[1,null]}' }], + }) + await writer.experimental.space.write({ space: "other", changes: [{ key: "draft/1", value: "elsewhere" }] }) const reader = await subscribe(handler, "types=session.created") const readerStream = ((await reader.next()).data as { stream: string }).stream expect(readerStream).not.toBe(stream) @@ -94,7 +97,7 @@ it.live("syncs a space through the API and follows it on the event stream, acros 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.write({ space: "app", changes: [{ key: "draft/2", value: "2" }] }) await writer.experimental.space.subscribe({ stream: readerStream, spaces: [{ space: "app", cursor: page.cursor }], @@ -103,8 +106,8 @@ it.live("syncs a space through the API and follows it on the event stream, acros 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.experimental.space.write({ space: "other", changes: [{ key: "draft/1", value: "unseen" }] }) + await writer.experimental.space.write({ space: "app", changes: [{ key: "draft/1", value: null }] }) await writer.session.create({ location: { directory: dir } }) expect(await reader.next()).toEqual({ type: "experimental.space.deleted", @@ -130,13 +133,21 @@ it.live("syncs a space through the API and follows it on the event stream, acros 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" }) + // Offline, in one write: repeated updates, a key created and deleted, and deletes of already deleted keys. + // It reports the head after its last change that changed a key. + expect( + await writer.experimental.space.write({ + space: "app", + changes: [ + { key: "draft/2", value: "3" }, + { key: "draft/2", value: "4" }, + { key: "draft/3", value: "x" }, + { key: "draft/3", value: null }, + { key: "draft/3", value: null }, + { key: "draft/1", value: null }, + ], + }), + ).toEqual({ revision: 7, cursor: `${epoch}.7` }) expect(await writer.experimental.space.sync({ space: "app", cursor })).toEqual({ type: "delta", space: "app", @@ -150,33 +161,61 @@ it.live("syncs a space through the API and follows it on the event stream, acros const anonymous = client(handler) for (const call of [ - () => anonymous.experimental.space.set({ space: "app", key: "x", value: "1" }), + () => anonymous.experimental.space.write({ space: "app", changes: [{ key: "x", value: "1" }] }), () => anonymous.experimental.space.sync({ space: "app" }), () => anonymous.experimental.space.subscribe({ stream, spaces: [] }), () => anonymous.experimental.space.unsubscribe({ stream, spaces: [] }), ]) 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) => + // In its own space, so the revisions above are unchanged. + const write = (changes: unknown) => handler( - new Request(`http://opencode.local/api/experimental/space/${space}/c`, { - method: "PUT", + new Request("http://opencode.local/api/experimental/space/limit/write", { + method: "POST", headers: { authorization, "content-type": "application/json" }, - body: JSON.stringify({ value }), + body: JSON.stringify({ changes }), }), ) - expect((await put("limit", "x".repeat(1024 * 1024))).status).toBe(204) - expect((await put("limit", "x".repeat(1024 * 1024 + 1))).status).toBe(400) + const values = (count: number) => + Array.from({ length: count }, (_, index) => ({ key: "c", value: `${index}` })) + // A write has 1 to 1024 changes, each value a string or null. + for (const changes of [[], values(1025), [{ key: "c", value: 1 }], [{ key: "c" }]]) + expect((await write(changes)).status).toBe(400) + expect(await (await write(values(1024))).json()).toEqual({ revision: 1024, cursor: `${epoch}.1024` }) + // The cap is the UTF-8 length of a write's values together, keys aren't counted: exactly 1 MiB is stored, one + // byte more is not. + expect((await write([{ key: "c", value: "x".repeat(1024 * 1024) }])).status).toBe(200) + expect( + ( + await write([ + { key: "c", value: "x".repeat(1024 * 1024 - 2) }, + { key: "d", value: "é" }, + ]) + ).status, + ).toBe(200) + expect( + ( + await write([ + { key: "c", value: "x".repeat(1024 * 1024 - 1) }, + { key: "d", value: "é" }, + ]) + ).status, + ).toBe(400) + // A rejected write commits none of its changes, though each value would fit, and one that changes nothing + // reports the head. + expect( + ( + await write([ + { key: "e", value: "x".repeat(512 * 1024) }, + { key: "c", value: "x".repeat(512 * 1024 + 1) }, + ]) + ).status, + ).toBe(400) + expect(await (await write([{ key: "e", value: null }])).json()).toEqual({ + revision: 1027, + cursor: `${epoch}.1027`, + }) }) }), ) @@ -186,14 +225,14 @@ it.live("syncs a space through the API and follows it on the event stream, acros const writer = client(handler, { authorization }) const reader = await subscribe(handler, "types=session.created") const stream = ((await reader.next()).data as { stream: string }).stream - await writer.experimental.space.set({ space: "app", key: "draft/4", value: "true" }) + await writer.experimental.space.write({ space: "app", changes: [{ 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" }) + await writer.experimental.space.write({ space: "app", changes: [{ key: "draft/4", value: null }] }) expect(await reader.next()).toEqual({ type: "experimental.space.deleted", data: { space: "app", key: "draft/4", revision: 9 }, @@ -250,16 +289,16 @@ it.live("two clients follow one space on their own streams, through unsubscribe for (const page of [a.page, b.page]) expect(page).toEqual({ type: "snapshot", space: "pins", epoch, revision: 0, entries: [], cursor: `${epoch}.0` }) - await api.experimental.space.set({ space: "pins", key: "x", value: "1" }) + await api.experimental.space.write({ space: "pins", changes: [{ 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" }) + await api.experimental.space.write({ space: "pins", changes: [{ key: "x", value: null }] }) 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" }) + await api.experimental.space.write({ space: "pins", changes: [{ 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.experimental.space.write({ space: "pins", changes: [{ 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") @@ -267,12 +306,17 @@ it.live("two clients follow one space on their own streams, through unsubscribe // B goes away; A changes more; B comes back on a new stream with the cursor of the last change it applied. await b.events.close() - await api.experimental.space.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" }) + await api.experimental.space.write({ + space: "pins", + changes: [ + { key: "a", value: "4" }, + { key: "b", value: "5" }, + { key: "a", value: null }, + ], + }) const back = await follow(`${epoch}.3`) expect(back.stream).not.toBe(b.stream) - await api.experimental.space.set({ space: "pins", key: "c", value: "6" }) + await api.experimental.space.write({ space: "pins", changes: [{ key: "c", value: "6" }] }) // What it missed, one event per key in revision order, then the live change. expect([ await back.events.next(),