castle-web-cli 0.4.230 → 0.4.232
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/castle-host/host.js +81 -0
- package/dist/devSaveStorage.d.ts +36 -0
- package/dist/devSaveStorage.js +469 -0
- package/dist/devSessionChild.js +22 -12
- package/dist/devSessionServer.js +8 -2
- package/dist/devSessionStorage.d.ts +9 -0
- package/dist/devSessionStorage.js +66 -1
- package/dist/init.js +1 -1
- package/dist/serve.js +5 -1
- package/dist/serverBundle.js +5 -3
- package/kits/base/castle.json +1 -1
- package/kits/base/sdk/README.md +148 -1
- package/kits/base/sdk/castle.d.ts +4 -0
- package/kits/base/sdk/castle.js +2 -0
- package/kits/base/sdk/commands.d.ts +15 -0
- package/kits/base/sdk/multiplayer.js +52 -4
- package/kits/base/sdk/save.d.ts +197 -0
- package/kits/base/sdk/save.js +525 -0
- package/kits/base/sdk/saveCoordinator.d.ts +39 -0
- package/kits/base/sdk/saveCoordinator.js +252 -0
- package/kits/base/sdk/server/storage.d.ts +3 -2
- package/kits/base/sdk/server/storage.js +25 -5
- package/kits/base/sdk/server/wrapper.d.ts +4 -0
- package/kits/base/sdk/server/wrapper.js +2 -0
- package/kits/base/sdk/store.d.ts +3 -2
- package/kits/base/sdk/store.js +5 -0
- package/kits/hub-game/CLAUDE.md +29 -4
- package/kits/hub-game/code/client/avatar.js +39 -0
- package/kits/hub-game/code/client/chat.js +12 -0
- package/kits/hub-game/code/client/chrome.js +237 -13
- package/kits/hub-game/code/client/grab.js +166 -7
- package/kits/hub-game/code/client/hats.js +26 -0
- package/kits/hub-game/code/client/hookLayer.js +36 -3
- package/kits/hub-game/code/client/hudClear.js +126 -0
- package/kits/hub-game/code/client/state.js +35 -1
- package/kits/hub-game/code/client/talk.js +10 -36
- package/kits/hub-game/code/client/tiers.js +505 -0
- package/kits/hub-game/code/client/together.js +144 -4
- package/kits/hub-game/code/client/wear.js +96 -14
- package/kits/hub-game/code/server/actors.js +5 -0
- package/kits/hub-game/code/server/grab.js +299 -13
- package/kits/hub-game/code/server/hub.js +162 -7
- package/kits/hub-game/code/server/manifest.js +80 -8
- package/kits/hub-game/code/server/npcs.js +21 -33
- package/kits/hub-game/code/server/party.js +75 -6
- package/kits/hub-game/code/server/say.js +8 -2
- package/kits/hub-game/code/server/wear.js +116 -11
- package/kits/hub-game/code/systems/hub.js +386 -21
- package/kits/hub-game/docs/contract.md +285 -19
- package/kits/hub-game/package.json +1 -1
- package/kits/hub-game/scripts/test-chat.mjs +32 -0
- package/kits/hub-game/scripts/test-grab-client.mjs +511 -0
- package/kits/hub-game/scripts/test-grab.mjs +857 -3
- package/kits/hub-game/scripts/test-hats.mjs +229 -0
- package/kits/hub-game/scripts/test-hub-trip.mjs +721 -0
- package/kits/hub-game/scripts/test-hud-clear.mjs +676 -0
- package/kits/hub-game/scripts/test-manifest.mjs +122 -1
- package/kits/hub-game/scripts/test-npcs.mjs +34 -24
- package/kits/hub-game/scripts/test-party.mjs +108 -4
- package/kits/hub-game/scripts/test-say.mjs +59 -2
- package/kits/hub-game/scripts/test-tiers.mjs +854 -0
- package/kits/hub-game/scripts/test-together.mjs +33 -1
- package/kits/hub-game/scripts/test-try-on.mjs +940 -0
- package/kits/physics-2d/CLAUDE.md +2 -0
- package/kits/physics-2d/castle.json +2 -2
- package/kits/physics-2d/engine/scene.js +127 -0
- package/kits/physics-2d/package.json +1 -1
- package/kits/physics-2d/scripts/test-skip-unchanged.mjs +298 -0
- package/kits/physics-3d/CLAUDE.md +531 -0
- package/kits/physics-3d/behaviors/Player.jsx +437 -3
- package/kits/physics-3d/castle.json +3 -3
- package/kits/physics-3d/docs/pxmodel-format.md +4 -0
- package/kits/physics-3d/engine3d/Scene3DPlayer.jsx +33 -1
- package/kits/physics-3d/engine3d/actornode.js +253 -0
- package/kits/physics-3d/engine3d/nearshadows.js +600 -0
- package/kits/physics-3d/engine3d/optimize.js +49 -0
- package/kits/physics-3d/engine3d/orbitinput.js +277 -0
- package/kits/physics-3d/engine3d/unchanged.js +153 -0
- package/kits/physics-3d/engine3d/world3d.js +525 -11
- package/kits/physics-3d/package.json +1 -1
- package/kits/physics-3d/scripts/Player.before-orbit.mjs +310 -0
- package/kits/physics-3d/scripts/Scene3DPlayer.before-orbit.jsx +337 -0
- package/kits/physics-3d/scripts/test-camera-follow.mjs +543 -0
- package/kits/physics-3d/scripts/test-camera-orbit.mjs +2105 -0
- package/kits/physics-3d/scripts/test-drop-empty-parts.mjs +787 -0
- package/kits/physics-3d/scripts/test-near-shadows.mjs +1073 -0
- package/kits/physics-3d/scripts/test-static-actors.mjs +667 -0
- package/kits/physics-3d/scripts/test-static-passes.mjs +459 -0
- package/kits/physics-3d/scripts/test-static-physics.mjs +128 -0
- package/kits/physics-3d/scripts/test-steady-hover.mjs +633 -0
- package/kits/physics-3d/systems/physics3d.js +273 -9
- package/package.json +1 -1
package/dist/devSessionServer.js
CHANGED
|
@@ -8,7 +8,8 @@ import { fileURLToPath } from 'url';
|
|
|
8
8
|
import { WebSocketServer, WebSocket } from 'ws';
|
|
9
9
|
import { readCastleJson, resolveServerConfig } from './castleJson.js';
|
|
10
10
|
import { OutboundFrameMeter } from './devSessionFrameBudget.js';
|
|
11
|
-
import {
|
|
11
|
+
import { SAVE_VERBS } from './devSaveStorage.js';
|
|
12
|
+
import { runDevSave, runDevStorageOperation } from './devSessionStorage.js';
|
|
12
13
|
import { rawDataToString } from './rawData.js';
|
|
13
14
|
import { bundleServerModule } from './serverBundle.js';
|
|
14
15
|
import { devDeckCastleJsons, devDeckSessionKey } from './contentPack.js';
|
|
@@ -598,13 +599,18 @@ class DevSessionImpl {
|
|
|
598
599
|
this.log('log', warning);
|
|
599
600
|
}
|
|
600
601
|
async handleStorageRequest(reqId, op, args) {
|
|
602
|
+
const socket = this.platformSocket;
|
|
601
603
|
const deckId = readCastleJson(this.projectDir)?.deckId;
|
|
602
604
|
// Local serve has no host credential to stamp a remote player's authority. Its
|
|
603
605
|
// authenticated OPEN roster proves presence here; GraphQL separately restricts
|
|
604
606
|
// funded audience sends to the signed-in CLI user's own subject.
|
|
605
|
-
const result =
|
|
607
|
+
const result = SAVE_VERBS.has(op)
|
|
608
|
+
? runDevSave(this.projectDir, this.sessionId, op, args)
|
|
609
|
+
: await runDevStorageOperation(deckId, op, args, this.connectedPlayers().map((player) => player.userId));
|
|
606
610
|
// The child may have restarted while this was out; its replacement never asked, so
|
|
607
611
|
// there is nobody to tell.
|
|
612
|
+
if (this.platformSocket !== socket)
|
|
613
|
+
return;
|
|
608
614
|
this.sendPlatform({
|
|
609
615
|
protocolVersion: PROTOCOL_VERSION,
|
|
610
616
|
t: 'storageResult',
|
|
@@ -1,9 +1,18 @@
|
|
|
1
|
+
import type { GraphqlResponse } from './castle-host/host.js';
|
|
1
2
|
export interface DevStorageResult {
|
|
2
3
|
ok: boolean;
|
|
3
4
|
value?: unknown;
|
|
4
5
|
error?: {
|
|
5
6
|
code: string;
|
|
6
7
|
message: string;
|
|
8
|
+
[detail: string]: unknown;
|
|
7
9
|
};
|
|
8
10
|
}
|
|
11
|
+
/** A session server's save. Its args are what the platform's storage route takes. */
|
|
12
|
+
export declare function runDevSave(projectDir: string, sessionId: string, op: string, args: Record<string, unknown>): DevStorageResult;
|
|
13
|
+
/**
|
|
14
|
+
* A page's save, answered in place of the GraphQL call the browser host makes
|
|
15
|
+
* for it. Undefined for every other document, which goes to the real API.
|
|
16
|
+
*/
|
|
17
|
+
export declare function devSaveGraphql(projectDir: string, userId: string | null, query: string, variables: Record<string, unknown>): GraphqlResponse | undefined;
|
|
9
18
|
export declare function runDevStorageOperation(deckId: string | undefined, op: string, args: Record<string, unknown>, connectedUserIds?: readonly string[]): Promise<DevStorageResult>;
|
|
@@ -1,4 +1,62 @@
|
|
|
1
1
|
import { graphql } from './api.js';
|
|
2
|
+
import { readCastleJson } from './castleJson.js';
|
|
3
|
+
import { DevSaveStorage } from './devSaveStorage.js';
|
|
4
|
+
// The platform's reply allowance for one storage call: its byte-rate window.
|
|
5
|
+
const SERVER_REPLY_BYTES = 2 * 1024 * 1024;
|
|
6
|
+
const CLIENT_REPLY_BYTES = 512 * 1024;
|
|
7
|
+
const saveStores = new Map();
|
|
8
|
+
function saveStoreFor(projectDir) {
|
|
9
|
+
let store = saveStores.get(projectDir);
|
|
10
|
+
if (!store) {
|
|
11
|
+
store = new DevSaveStorage();
|
|
12
|
+
saveStores.set(projectDir, store);
|
|
13
|
+
}
|
|
14
|
+
return store;
|
|
15
|
+
}
|
|
16
|
+
/** A session server's save. Its args are what the platform's storage route takes. */
|
|
17
|
+
export function runDevSave(projectDir, sessionId, op, args) {
|
|
18
|
+
const input = op === 'operation' ? args : args.input;
|
|
19
|
+
return saveStoreFor(projectDir).execute(op, input, {
|
|
20
|
+
principal: 'server',
|
|
21
|
+
binding: `session:${sessionId}`,
|
|
22
|
+
server: true,
|
|
23
|
+
deckWritable: true,
|
|
24
|
+
replyEnvelope: (value) => ({ value }),
|
|
25
|
+
replyBytes: SERVER_REPLY_BYTES,
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
const SAVE_FIELDS = {
|
|
29
|
+
cauldronStorageSnapshot: 'snapshot',
|
|
30
|
+
cauldronStorageOperation: 'operation',
|
|
31
|
+
cauldronStorageTransaction: 'transaction',
|
|
32
|
+
cauldronStorageClaim: 'claim',
|
|
33
|
+
cauldronStorageInitialize: 'initialize',
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* A page's save, answered in place of the GraphQL call the browser host makes
|
|
37
|
+
* for it. Undefined for every other document, which goes to the real API.
|
|
38
|
+
*/
|
|
39
|
+
export function devSaveGraphql(projectDir, userId, query, variables) {
|
|
40
|
+
const field = /\b(cauldronStorage[A-Z][A-Za-z]*)\s*\(/.exec(query)?.[1];
|
|
41
|
+
const op = field && SAVE_FIELDS[field];
|
|
42
|
+
if (!field || !op)
|
|
43
|
+
return undefined;
|
|
44
|
+
const input = op === 'operation'
|
|
45
|
+
? { operationId: variables.operationId }
|
|
46
|
+
: variables.input;
|
|
47
|
+
const result = saveStoreFor(projectDir).execute(op, input, {
|
|
48
|
+
principal: `user:${userId}`,
|
|
49
|
+
binding: `user:${userId}`,
|
|
50
|
+
server: false,
|
|
51
|
+
...(userId ? { userId } : {}),
|
|
52
|
+
deckWritable: !readCastleJson(projectDir)?.server,
|
|
53
|
+
replyEnvelope: (value) => ({ data: { [field]: value } }),
|
|
54
|
+
replyBytes: CLIENT_REPLY_BYTES,
|
|
55
|
+
});
|
|
56
|
+
return result.ok
|
|
57
|
+
? { data: { [field]: result.value } }
|
|
58
|
+
: { errors: [{ message: result.error.message, extensions: result.error }] };
|
|
59
|
+
}
|
|
2
60
|
const SCOPE_ARGS = `
|
|
3
61
|
$deckId: ID!
|
|
4
62
|
$scope: CauldronStorageScope!
|
|
@@ -402,7 +460,14 @@ export async function runDevStorageOperation(deckId, op, args, connectedUserIds
|
|
|
402
460
|
const error = response.errors?.[0];
|
|
403
461
|
if (error) {
|
|
404
462
|
const code = error.extensions?.code;
|
|
405
|
-
return
|
|
463
|
+
return {
|
|
464
|
+
ok: false,
|
|
465
|
+
error: {
|
|
466
|
+
...error.extensions,
|
|
467
|
+
code: typeof code === 'string' ? code : 'CAULDRON_STORAGE_UNAVAILABLE',
|
|
468
|
+
message: error.message ?? 'storage request failed',
|
|
469
|
+
},
|
|
470
|
+
};
|
|
406
471
|
}
|
|
407
472
|
return { ok: true, value: response.data?.[operation.field] ?? null };
|
|
408
473
|
}
|
package/dist/init.js
CHANGED
|
@@ -64,7 +64,7 @@ const BARE_SCAFFOLDS = [
|
|
|
64
64
|
// Registry version of castle-web-sdk to inject when scaffolding from a
|
|
65
65
|
// globally-installed castle-web (not from inside the workspace). Bumped
|
|
66
66
|
// alongside cli/sdk version bumps.
|
|
67
|
-
const PUBLISHED_SDK_VERSION = '0.4.
|
|
67
|
+
const PUBLISHED_SDK_VERSION = '0.4.46';
|
|
68
68
|
// Range, not a pin: `castle-web-fonts` is its own package precisely so a tenth
|
|
69
69
|
// face can ship without a cli release, and a caret range means an existing
|
|
70
70
|
// deck's next install picks it up. Nothing here has to move when it does.
|
package/dist/serve.js
CHANGED
|
@@ -29,6 +29,7 @@ import { graphql as castleGraphql } from './api.js';
|
|
|
29
29
|
import { executeCommand } from './castle-host/host.js';
|
|
30
30
|
import { DevHubVisit, readDevHubDoors } from './devHub.js';
|
|
31
31
|
import { DevExperiments } from './devExperiments.js';
|
|
32
|
+
import { devSaveGraphql } from './devSessionStorage.js';
|
|
32
33
|
import { serveOracleStream } from './deckAgentRoute.js';
|
|
33
34
|
import { ServeSecurity } from './serveSecurity.js';
|
|
34
35
|
import { atomicWriteFileSync } from './atomicFile.js';
|
|
@@ -886,7 +887,10 @@ async function handleCastleCommand(ws, projectDir, broadcast, multiplayer, multi
|
|
|
886
887
|
// does have: this process can't draw it, so the fetched payload goes to the
|
|
887
888
|
// shell, which mounts the same panel the app and the website use.
|
|
888
889
|
const result = await executeCommand(ctx, command, params, {
|
|
889
|
-
graphqlFetch:
|
|
890
|
+
graphqlFetch: (query, variables) => {
|
|
891
|
+
const save = devSaveGraphql(projectDir, ctx.userId, query, variables);
|
|
892
|
+
return save ? Promise.resolve(save) : castleGraphql(query, variables);
|
|
893
|
+
},
|
|
890
894
|
oracleStream,
|
|
891
895
|
showLeaderboard: (payload) => broadcast({ type: 'castle_leaderboard_show', payload }),
|
|
892
896
|
hub: devHubVisit(ws, playSessionSlot, projectDir, multiplayer, multiplayerUrl),
|
package/dist/serverBundle.js
CHANGED
|
@@ -2,11 +2,13 @@ import { createHash } from 'crypto';
|
|
|
2
2
|
import { createRequire } from 'module';
|
|
3
3
|
import * as path from 'path';
|
|
4
4
|
import { build } from 'vite';
|
|
5
|
-
import { resolveServerConfig
|
|
5
|
+
import { resolveServerConfig } from './castleJson.js';
|
|
6
6
|
import { forksOverlayPlugin, importsAliasPlugin, sdkAliasPlugin } from './vitePlugins.js';
|
|
7
7
|
import { resolveSdkSpecifier, SDK_PACKAGE } from './sdkResolve.js';
|
|
8
8
|
const WARN_BYTES = 1024 * 1024;
|
|
9
|
-
|
|
9
|
+
// Ghost accepts 20MB from an admin or on an admin's deck, and 5MB from
|
|
10
|
+
// everyone else.
|
|
11
|
+
const MAX_BYTES = 20 * 1024 * 1024;
|
|
10
12
|
const VIRTUAL_ENTRY = '\0castle-server-entry';
|
|
11
13
|
// Build the artifact Cauldron executes. A deck without a valid server entry is
|
|
12
14
|
// not an error: multiplayer is opt-in, so callers can handle that as a skip (or
|
|
@@ -18,7 +20,7 @@ export async function buildServerBundle(projectDir) {
|
|
|
18
20
|
const code = await bundleServerModule(projectDir, config, true);
|
|
19
21
|
const sizeBytes = Buffer.byteLength(code, 'utf8');
|
|
20
22
|
if (sizeBytes > MAX_BYTES) {
|
|
21
|
-
throw new Error(`Server bundle is ${(sizeBytes / 1024 / 1024).toFixed(2)}MB; the maximum is
|
|
23
|
+
throw new Error(`Server bundle is ${(sizeBytes / 1024 / 1024).toFixed(2)}MB; the maximum is ${MAX_BYTES / 1024 / 1024}MB.`);
|
|
22
24
|
}
|
|
23
25
|
if (sizeBytes > WARN_BYTES) {
|
|
24
26
|
console.warn(`Warning: Server bundle is ${(sizeBytes / 1024 / 1024).toFixed(2)}MB. ` +
|
package/kits/base/castle.json
CHANGED
package/kits/base/sdk/README.md
CHANGED
|
@@ -53,6 +53,12 @@ connection.onMessage((message) => receiveServerMessage(message));
|
|
|
53
53
|
connection.send({ type: "ready" });
|
|
54
54
|
```
|
|
55
55
|
|
|
56
|
+
Attach `onMessage` in the same step that receives the connection (right after
|
|
57
|
+
`await Multiplayer.join(...)`). On a hub join (`mode: "hub"`), which resolves a
|
|
58
|
+
little after the socket's hello, messages the place sent in between, such as
|
|
59
|
+
the snapshot it greets a player with, are kept for that first listener. A
|
|
60
|
+
listener attached later gets only what arrives after it.
|
|
61
|
+
|
|
56
62
|
Named rooms use `{ mode: "named", key: "room-name" }`; party sessions use
|
|
57
63
|
`{ mode: "party" }`. Only one connection can be live per deck instance. The SDK
|
|
58
64
|
reconnects temporary socket drops automatically. `onStateChange` reports
|
|
@@ -141,7 +147,8 @@ export default {
|
|
|
141
147
|
|
|
142
148
|
`session.storage.deck` is shared by everyone playing.
|
|
143
149
|
`session.storage.user(userId)` is one player's public data.
|
|
144
|
-
`session.storage.board(name)` is a leaderboard.
|
|
150
|
+
`session.storage.board(name)` is a leaderboard. The root and its buckets also
|
|
151
|
+
support the [atomic save API](#atomic-saves). Each scope has the same
|
|
145
152
|
`get`, `set`, `remove`, `increment` and `list` as `Store`.
|
|
146
153
|
|
|
147
154
|
Two differences follow from a session server not being a player:
|
|
@@ -469,6 +476,146 @@ A value is JSON, so binary data such as a picture or a video clip costs
|
|
|
469
476
|
about a third more once encoded, and a clip of more than a few seconds
|
|
470
477
|
does not fit in one. Ship media with the deck instead.
|
|
471
478
|
|
|
479
|
+
### Atomic saves
|
|
480
|
+
|
|
481
|
+
`Store` and `session.storage` expose the same typed save methods:
|
|
482
|
+
|
|
483
|
+
- `snapshot({ targets: [{ target, select? }] })` reads every selected target at
|
|
484
|
+
one consistent point. `select` is `{ prefix }` or `{ keys }` within the
|
|
485
|
+
target; omitted selection reads its whole prefix. The result has `access`
|
|
486
|
+
and `targets: [{ target, revision, rows, complete }]`. `complete` describes
|
|
487
|
+
coverage of the entire target. A successful `null` revision means absent;
|
|
488
|
+
an initialized empty target has a revision. A failed read never means absent.
|
|
489
|
+
- `transaction({ operationId, expectedAccess, checks?, changes })` commits all
|
|
490
|
+
changes together. Each change has `target`, `expectedRevision` (string or
|
|
491
|
+
`null`), optional `writer`, and either `put`/`remove` or `replace`. `replace`
|
|
492
|
+
removes omitted rows within the prefix. Each target appears once. A `null`
|
|
493
|
+
expected revision creates only an absent target; an explicit `replace` also
|
|
494
|
+
supports importing unregistered legacy rows. `checks` are read-only target
|
|
495
|
+
checks with an expected revision and/or writer; they leave revisions intact.
|
|
496
|
+
- `claim({ operationId, expectedAccess?, target, initial?, load? })` explicitly
|
|
497
|
+
takes ownership of a target and returns `{ writer, receipt, snapshot }`.
|
|
498
|
+
`initial: [{ target, rows }]` initializes absent targets only. An absent
|
|
499
|
+
claimed target initializes empty if defaults were omitted. Claiming an
|
|
500
|
+
existing target leaves its data revision unchanged. The latest committed
|
|
501
|
+
claim wins; claimed targets require the current writer on every change.
|
|
502
|
+
- `initialize({ operationId, expectedAccess?, initial, load? })` initializes
|
|
503
|
+
only absent targets and returns `{ receipt, snapshot }`. Concurrent defaults
|
|
504
|
+
are applied once. It never claims ownership or replaces existing data.
|
|
505
|
+
- `operation(operationId)` returns `{ state: "committed", receipt }` or
|
|
506
|
+
`{ state: "unknown" }`. Unknown does not cancel a delayed request. Settle it
|
|
507
|
+
by replaying the original input and ID.
|
|
508
|
+
|
|
509
|
+
A target is `{ scope: "deck" | "user" | "private", subject?, prefix }`.
|
|
510
|
+
The prefix must be nonempty, and registered prefixes in a bucket cannot
|
|
511
|
+
intersect. All row keys stay inside their target. `subject` is only for user
|
|
512
|
+
scope; omitted subject means the current player. Session servers must name a
|
|
513
|
+
user and cannot access private targets. Permissions and quotas are unchanged:
|
|
514
|
+
deck-scoped bags remain publicly readable and share the deck allowance.
|
|
515
|
+
`rows`, `put` and `replace` are maps of keys to JSON values, validated through
|
|
516
|
+
the same JSON handling as ordinary Store writes.
|
|
517
|
+
|
|
518
|
+
A receipt contains `operationId`, `access`, `revisions: [{ target, revision }]`
|
|
519
|
+
and, for claims, `writer`. Access and revisions are opaque. Use snapshot access
|
|
520
|
+
as `expectedAccess`; reset and undo invalidate old access, revisions and writer
|
|
521
|
+
tokens. Claim/initialize may omit expected access for a deliberate first open.
|
|
522
|
+
When `load` is omitted, the SDK requests the claimed/initial targets. Supply
|
|
523
|
+
an explicit `load` to choose other targets or smaller projections.
|
|
524
|
+
|
|
525
|
+
Every bucket also has `target(prefix)` and the same methods with a `prefix`
|
|
526
|
+
wherever the root takes a `target`: `snapshot({ prefix, select? })`,
|
|
527
|
+
`transaction({ changes: [{ prefix, ... }], checks?: [{ prefix, ... }] })`,
|
|
528
|
+
`claim({ prefix, initial?: [{ prefix, rows }], load?: [{ prefix, select? }] })`,
|
|
529
|
+
`initialize({ initial: [{ prefix, rows }], load? })` and `operation(id)`.
|
|
530
|
+
Root methods can combine buckets atomically:
|
|
531
|
+
|
|
532
|
+
```js
|
|
533
|
+
const room = session.storage.deck.target(`room:${roomId}:`);
|
|
534
|
+
const bag = session.storage.deck.target(`bag:${roomId}:${userId}:`);
|
|
535
|
+
const opened = await session.storage.claim({
|
|
536
|
+
operationId: crypto.randomUUID(),
|
|
537
|
+
target: room,
|
|
538
|
+
initial: [{ target: room, rows: roomDefaults }, { target: bag, rows: starterBag }],
|
|
539
|
+
load: [{ target: room }, { target: bag }],
|
|
540
|
+
});
|
|
541
|
+
const receipt = await session.storage.transaction({
|
|
542
|
+
operationId: actionId,
|
|
543
|
+
expectedAccess: opened.snapshot.access,
|
|
544
|
+
changes: [
|
|
545
|
+
{ target: room, expectedRevision: opened.snapshot.targets[0].revision,
|
|
546
|
+
writer: opened.writer, put: changedRoomRows, remove: deletedRoomKeys },
|
|
547
|
+
{ target: bag, expectedRevision: opened.snapshot.targets[1].revision,
|
|
548
|
+
put: changedBagRows },
|
|
549
|
+
],
|
|
550
|
+
});
|
|
551
|
+
// Acknowledge the gameplay action only after this receipt.
|
|
552
|
+
```
|
|
553
|
+
|
|
554
|
+
Atomic saves bypass ordinary coalescing and 32-key splitting. They are never
|
|
555
|
+
split into partial writes or retried as ordinary SETs. A request or snapshot
|
|
556
|
+
that exceeds a transport or single-charge byte allowance fails with
|
|
557
|
+
`CAULDRON_STORAGE_TOO_LARGE`; narrow the selection or reduce the atomic payload.
|
|
558
|
+
Ordinary `set`, `remove` and `increment` reject keys inside registered targets
|
|
559
|
+
with `CAULDRON_STORAGE_MANAGED_TARGET`.
|
|
560
|
+
|
|
561
|
+
Save methods reject with `SaveError`, exported from the client and server SDK.
|
|
562
|
+
It carries `code`, `message`, `operationId`, `retryable`,
|
|
563
|
+
`committed: false | true | "unknown"`, and optional `receipt`, `retryAfterMs`
|
|
564
|
+
and `target`. Extra platform details remain in `extensions`. Conflicts, writer
|
|
565
|
+
loss and stale access require explicit reload/rebuild. A replayed historical
|
|
566
|
+
claim can fail with writer loss while `committed === true` and its original
|
|
567
|
+
receipt; it never takes ownership again. Transport ambiguity keeps the outcome
|
|
568
|
+
unknown until receipt lookup or identical replay settles it.
|
|
569
|
+
|
|
570
|
+
### Save coordinator
|
|
571
|
+
|
|
572
|
+
`createSaveCoordinator`, from `castle-web-sdk` or `castle-web-sdk/server`,
|
|
573
|
+
sends a deck's transactions in order and keeps each one until it settles:
|
|
574
|
+
|
|
575
|
+
```js
|
|
576
|
+
const saves = createSaveCoordinator(session.storage, opened.snapshot, [
|
|
577
|
+
{ target: room, writer: opened.writer },
|
|
578
|
+
]);
|
|
579
|
+
const receipt = await saves.submit({
|
|
580
|
+
operationId: actionId,
|
|
581
|
+
checks: [{ target: room, writer: opened.writer }],
|
|
582
|
+
changes: [{ target: bag, put: changedBagRows }],
|
|
583
|
+
});
|
|
584
|
+
await saves.flush();
|
|
585
|
+
// saves.status is "pending", "saved" or "blocked".
|
|
586
|
+
```
|
|
587
|
+
|
|
588
|
+
`submit` copies the save and resolves with its receipt once it commits. A
|
|
589
|
+
change without `expectedRevision` takes the target's revision from the latest
|
|
590
|
+
receipt, filled in when the save is first sent; a change without `writer`
|
|
591
|
+
takes the one passed in for its target. Saves are sent one at a time, in
|
|
592
|
+
order. A save whose reply was lost is looked up by its id and, when the
|
|
593
|
+
platform has no receipt for it, sent again unchanged.
|
|
594
|
+
|
|
595
|
+
A failure that cannot be settled that way sets `status` to `"blocked"` and
|
|
596
|
+
holds back every save behind it. When the outcome is unknown or the error is
|
|
597
|
+
retryable, the save's promise stays pending and `retry()` sends the same
|
|
598
|
+
request again. When the save definitely did not commit (a conflict, a lost
|
|
599
|
+
writer), its promise rejects and the coordinator stays blocked: reload a
|
|
600
|
+
snapshot and start a new coordinator. It never claims or rebuilds a save on
|
|
601
|
+
its own. `error`, `pendingOperationIds` and `revision(target)` show its state.
|
|
602
|
+
|
|
603
|
+
`flush()` resolves once every save submitted before it has committed, and
|
|
604
|
+
rejects if the queue blocks first. Saves submitted after it do not hold it up,
|
|
605
|
+
and an earlier receipt never marks a later save saved. For start-over, call
|
|
606
|
+
`discardUnsent()` and submit the replacement: saves already sent still settle
|
|
607
|
+
first, and the replacement goes out at the revision they leave.
|
|
608
|
+
|
|
609
|
+
Keep the coordinator in the page when a private worker is replaced. A page or
|
|
610
|
+
process that dies loses the saves it had not sent and the ids of those it had;
|
|
611
|
+
reopening restores the last committed snapshot.
|
|
612
|
+
|
|
613
|
+
During `castle-web serve`, the serve answers the save API itself, from one
|
|
614
|
+
in-memory store per project shared by its pages and named sessions. Its rows,
|
|
615
|
+
receipts and writers survive a runtime restart and are lost when the serve
|
|
616
|
+
exits. Ordinary `get`, `set` and `list` still use the deck's real storage, and
|
|
617
|
+
the two do not see each other's rows.
|
|
618
|
+
|
|
472
619
|
## Storage
|
|
473
620
|
|
|
474
621
|
> Older API, still supported and not going away. New decks should use
|
|
@@ -46,3 +46,7 @@ export type { CastleClockZone, CastleDateParts, CastleTimeApi } from "./time";
|
|
|
46
46
|
export type { Json } from "./types";
|
|
47
47
|
export { User } from "./user";
|
|
48
48
|
export type { CastleUser, CastleUserApi } from "./user";
|
|
49
|
+
export { createSaveCoordinator } from "./saveCoordinator";
|
|
50
|
+
export type { CoordinatedChange, CoordinatedSave, SaveCoordinator, SaveStatus, } from "./saveCoordinator";
|
|
51
|
+
export { SaveError } from "./save";
|
|
52
|
+
export type { SaveApi, SaveBucketApi, SaveBucketRead, SaveChange, SaveCheck, SaveClaimed, SaveClaimInput, SaveErrorEnvelope, SaveInitial, SaveInitializeInput, SaveOpened, SaveOperation, SaveReadTarget, SaveReceipt, SaveRevision, SaveRows, SaveScope, SaveSelection, SaveSnapshot, SaveTarget, SaveTransactionInput, SaveWriter, } from "./save";
|
package/kits/base/sdk/castle.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { SaveClaimed, SaveClaimInput, SaveInitializeInput, SaveOpened, SaveOperation, SaveReadTarget, SaveReceipt, SaveSnapshot, SaveTransactionInput } from "./save";
|
|
1
2
|
import type { Json } from "./types";
|
|
2
3
|
export declare const CASTLE_SDK_PROTOCOL = 1;
|
|
3
4
|
export type StorageBlob = Record<string, string>;
|
|
@@ -584,6 +585,15 @@ export interface CommandParams {
|
|
|
584
585
|
characterId: string;
|
|
585
586
|
operationId: string;
|
|
586
587
|
};
|
|
588
|
+
"cauldronStorage.snapshot": {
|
|
589
|
+
targets: SaveReadTarget[];
|
|
590
|
+
};
|
|
591
|
+
"cauldronStorage.transaction": SaveTransactionInput;
|
|
592
|
+
"cauldronStorage.claim": SaveClaimInput;
|
|
593
|
+
"cauldronStorage.initialize": SaveInitializeInput;
|
|
594
|
+
"cauldronStorage.operation": {
|
|
595
|
+
operationId: string;
|
|
596
|
+
};
|
|
587
597
|
"cauldronStorage.get": {
|
|
588
598
|
scope: StoreScope;
|
|
589
599
|
subject?: string | null;
|
|
@@ -721,6 +731,11 @@ export interface CommandResult {
|
|
|
721
731
|
"characters.status": CharacterOperation;
|
|
722
732
|
"characters.history": CharacterHistory;
|
|
723
733
|
"characters.reset": CharacterAdmission;
|
|
734
|
+
"cauldronStorage.snapshot": SaveSnapshot;
|
|
735
|
+
"cauldronStorage.transaction": SaveReceipt;
|
|
736
|
+
"cauldronStorage.claim": SaveClaimed;
|
|
737
|
+
"cauldronStorage.initialize": SaveOpened;
|
|
738
|
+
"cauldronStorage.operation": SaveOperation;
|
|
724
739
|
"cauldronStorage.get": {
|
|
725
740
|
entries: StoreEntry[];
|
|
726
741
|
};
|
|
@@ -55,6 +55,7 @@ async function join(options) {
|
|
|
55
55
|
connection.leave();
|
|
56
56
|
throw multiplayerError("MULTIPLAYER_UNAVAILABLE", "The hub trip could not be completed; the player is still where they were.", "Multiplayer.join");
|
|
57
57
|
}
|
|
58
|
+
connection.handedOver();
|
|
58
59
|
return connection;
|
|
59
60
|
}
|
|
60
61
|
// A hub handoff is joined as it was acquired; it cannot be acquired again.
|
|
@@ -169,6 +170,8 @@ async function joinDestination(options) {
|
|
|
169
170
|
activeConnection = connection;
|
|
170
171
|
return { status: "joined", connection, audience: acquired.audience };
|
|
171
172
|
}
|
|
173
|
+
// How many messages are kept for a deck that has not attached a listener yet.
|
|
174
|
+
const EARLY_MESSAGES_MAX = 512;
|
|
172
175
|
class MultiplayerConnectionImpl {
|
|
173
176
|
request;
|
|
174
177
|
onClosed;
|
|
@@ -192,6 +195,16 @@ class MultiplayerConnectionImpl {
|
|
|
192
195
|
sharedCharactersSupported = false;
|
|
193
196
|
pendingCharacterRequests = new Map();
|
|
194
197
|
messages = new Set();
|
|
198
|
+
// Messages that arrived before the deck had a listener, on a hub join only.
|
|
199
|
+
// A hub join resolves some tasks after the socket's hello (it first commits
|
|
200
|
+
// with the host), and a place greets a player with a snapshot in that gap:
|
|
201
|
+
// with nobody listening it was dropped, and the deck never saw the state it
|
|
202
|
+
// joined into. They are kept, in order, for a listener attached as soon as
|
|
203
|
+
// the deck is handed the connection (`handedOver`); a deck that attaches one
|
|
204
|
+
// later gets only what arrives from then on. Null on every other join, which
|
|
205
|
+
// resolves in the hello's own task: nothing is kept there and delivery is
|
|
206
|
+
// exactly what it always was.
|
|
207
|
+
early = null;
|
|
195
208
|
rosters = new Set();
|
|
196
209
|
states = new Set();
|
|
197
210
|
voiceImpl = new MultiplayerVoiceImpl({
|
|
@@ -312,8 +325,43 @@ class MultiplayerConnectionImpl {
|
|
|
312
325
|
}
|
|
313
326
|
onMessage(callback) {
|
|
314
327
|
this.messages.add(callback);
|
|
328
|
+
const early = this.early;
|
|
329
|
+
if (early) {
|
|
330
|
+
// The first listener takes what arrived before it; later ones get only
|
|
331
|
+
// what arrives from now on, as before.
|
|
332
|
+
this.early = null;
|
|
333
|
+
for (const data of early) {
|
|
334
|
+
// A listener that leaves part-way hears no more.
|
|
335
|
+
if (this.currentState === "closed")
|
|
336
|
+
break;
|
|
337
|
+
callListener(callback, data);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
315
340
|
return () => this.messages.delete(callback);
|
|
316
341
|
}
|
|
342
|
+
/**
|
|
343
|
+
* The deck is being handed this connection. Whatever arrived before that is
|
|
344
|
+
* kept through the deck's own next step (the code after its `await`), where
|
|
345
|
+
* a kit attaches its listener; after that, nothing more is kept.
|
|
346
|
+
*/
|
|
347
|
+
handedOver() {
|
|
348
|
+
if (!this.early)
|
|
349
|
+
return;
|
|
350
|
+
setTimeout(() => {
|
|
351
|
+
if (this.messages.size === 0)
|
|
352
|
+
this.early = null;
|
|
353
|
+
}, 0);
|
|
354
|
+
}
|
|
355
|
+
deliver(data) {
|
|
356
|
+
if (this.early && this.messages.size === 0) {
|
|
357
|
+
// Bounded: a deck that never listens does not grow this forever.
|
|
358
|
+
if (this.early.length < EARLY_MESSAGES_MAX)
|
|
359
|
+
this.early.push(data);
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
for (const callback of this.messages)
|
|
363
|
+
callListener(callback, data);
|
|
364
|
+
}
|
|
317
365
|
onRoster(callback) {
|
|
318
366
|
this.rosters.add(callback);
|
|
319
367
|
if (this.roster)
|
|
@@ -343,6 +391,7 @@ class MultiplayerConnectionImpl {
|
|
|
343
391
|
hostRequest("hub.cancel", { nonce }).catch(() => { });
|
|
344
392
|
return;
|
|
345
393
|
}
|
|
394
|
+
this.early = [];
|
|
346
395
|
this.hubCommit = commitHubTrip(nonce, this.currentSessionId);
|
|
347
396
|
}
|
|
348
397
|
hubCommitted() {
|
|
@@ -516,8 +565,7 @@ class MultiplayerConnectionImpl {
|
|
|
516
565
|
this.acceptRoster(frame);
|
|
517
566
|
break;
|
|
518
567
|
case "m":
|
|
519
|
-
|
|
520
|
-
callListener(callback, frame.d);
|
|
568
|
+
this.deliver(frame.d);
|
|
521
569
|
break;
|
|
522
570
|
case "worldCharacterResult":
|
|
523
571
|
this.acceptWorldCharacterResult(frame);
|
|
@@ -542,8 +590,7 @@ class MultiplayerConnectionImpl {
|
|
|
542
590
|
if (bytes.byteLength < 1 || bytes[0] !== BINARY_MESSAGE_TAG)
|
|
543
591
|
return;
|
|
544
592
|
const payload = new Uint8Array(buffer, 1);
|
|
545
|
-
|
|
546
|
-
callListener(callback, payload);
|
|
593
|
+
this.deliver(payload);
|
|
547
594
|
}
|
|
548
595
|
acceptRoster(frame) {
|
|
549
596
|
const players = frame.players.slice();
|
|
@@ -653,6 +700,7 @@ class MultiplayerConnectionImpl {
|
|
|
653
700
|
this.socketAttempt += 1;
|
|
654
701
|
closeSocket(socket, 1000, "session closed");
|
|
655
702
|
this.currentState = "closed";
|
|
703
|
+
this.early = null;
|
|
656
704
|
this.voiceImpl.dispose();
|
|
657
705
|
for (const callback of this.states)
|
|
658
706
|
callStateListener(callback, "closed", metadata);
|