castle-web-sdk 0.4.49 → 0.4.51
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/README.md +53 -0
- package/dist/castle.d.ts +3 -1
- package/dist/castle.js +1 -0
- package/dist/commands.d.ts +25 -1
- package/dist/commands.js +29 -1
- package/dist/hub.d.ts +17 -0
- package/dist/hub.js +52 -11
- package/dist/hubRejoin.d.ts +4 -0
- package/dist/hubRejoin.js +15 -0
- package/dist/localCache.d.ts +27 -0
- package/dist/localCache.js +115 -0
- package/dist/localCacheStore.d.ts +15 -0
- package/dist/localCacheStore.js +358 -0
- package/dist/multiplayer.js +7 -0
- package/dist/transport.d.ts +1 -0
- package/dist/transport.js +4 -5
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -18,6 +18,7 @@ import { setup, initCard, Store, Leaderboard } from "castle-web-sdk";
|
|
|
18
18
|
- [Store](#store)
|
|
19
19
|
- [Storage](#storage)
|
|
20
20
|
- [SharedStorage](#sharedstorage)
|
|
21
|
+
- [LocalCache](#localcache)
|
|
21
22
|
- [Leaderboard](#leaderboard)
|
|
22
23
|
- [Time](#time)
|
|
23
24
|
- [User](#user)
|
|
@@ -853,6 +854,44 @@ const { color } = await Store.user(otherUserId).get(["color"]);
|
|
|
853
854
|
await Store.me.set({ color: "red" });
|
|
854
855
|
```
|
|
855
856
|
|
|
857
|
+
## LocalCache
|
|
858
|
+
|
|
859
|
+
`LocalCache` keeps bytes and text on the player's device, for things the
|
|
860
|
+
deck can rebuild: downloaded or unpacked assets, compiled data. Entries
|
|
861
|
+
belong to the deck whose code is running. A hub town's doors change the
|
|
862
|
+
place but not the code, so the games played through them use the town's
|
|
863
|
+
entries. In the app, decks loaded from the same web address share entries.
|
|
864
|
+
|
|
865
|
+
Any entry can be gone at any time. Each deck has 20 MB; past that, its own
|
|
866
|
+
least recently used entries are evicted. On the web all decks
|
|
867
|
+
together have 300 MB; past that, the least recently used entries of any
|
|
868
|
+
deck are evicted. Both are less when the device is short of space. The
|
|
869
|
+
browser or app may also clear the whole cache. Never keep anything here
|
|
870
|
+
that the deck cannot make again; use [`Store`](#store) for that.
|
|
871
|
+
|
|
872
|
+
- **`LocalCache.getBinary(key): Promise<ArrayBuffer | null>`** — the bytes
|
|
873
|
+
at `key`, or `null` if there are none. A text entry comes back as UTF-8.
|
|
874
|
+
- **`LocalCache.getText(key): Promise<string | null>`** — the text at
|
|
875
|
+
`key`. A bytes entry is decoded as UTF-8.
|
|
876
|
+
- **`LocalCache.set(key, value): Promise<void>`** — stores an
|
|
877
|
+
`ArrayBuffer`, a `Uint8Array` or a string. An `ArrayBuffer` is moved, not
|
|
878
|
+
copied, and is empty (detached) once `set` returns; pass `buffer.slice(0)`
|
|
879
|
+
to keep one. A `Uint8Array` that covers its whole buffer moves that buffer
|
|
880
|
+
the same way; one over part of a buffer is copied.
|
|
881
|
+
- **`LocalCache.remove(key): Promise<void>`** — removes `key`.
|
|
882
|
+
|
|
883
|
+
Keys are 1 to 1024 characters, without NUL; a bad key or value throws.
|
|
884
|
+
Nothing else does: a get that cannot read returns `null`, and a set that
|
|
885
|
+
cannot write stores nothing.
|
|
886
|
+
|
|
887
|
+
```js
|
|
888
|
+
let bytes = await LocalCache.getBinary("town-v3");
|
|
889
|
+
if (!bytes) {
|
|
890
|
+
bytes = await unpackTown();
|
|
891
|
+
LocalCache.set("town-v3", bytes.slice(0));
|
|
892
|
+
}
|
|
893
|
+
```
|
|
894
|
+
|
|
856
895
|
## Leaderboard
|
|
857
896
|
|
|
858
897
|
`Leaderboard` ranks players by a numeric score, per deck and per
|
|
@@ -1361,6 +1400,14 @@ the signed-in account id. A new host without native sign-in support returns
|
|
|
1361
1400
|
- `Hub.onBack(listener)` hears the host's Back control, which a game cannot hide.
|
|
1362
1401
|
Answer it with `Hub.back()` behind the door animation; a host that hears
|
|
1363
1402
|
nothing takes the player home itself. Returns an unsubscribe function.
|
|
1403
|
+
- `Hub.onGo(listener)` hears the host ask to take the player through a door,
|
|
1404
|
+
e.g. a trip begun outside this page. The listener gets
|
|
1405
|
+
`{ doorId, owner, title, party }`: `owner` is whose House a House door leads
|
|
1406
|
+
to (or null), `title` the host's name for the door (or null), `party` how many
|
|
1407
|
+
travel (1 when the host does not say). A hub kit answers it like a fired pad:
|
|
1408
|
+
`Hub.go(doorId)` (with `{ ownerUserId: owner }` when set) behind its door
|
|
1409
|
+
animation. Hosts that never send it are the norm. Returns an unsubscribe
|
|
1410
|
+
function.
|
|
1364
1411
|
|
|
1365
1412
|
A player Castle has barred from the hub is refused at every hub door and at the
|
|
1366
1413
|
town itself with `CastleError` code `CAULDRON_HUB_BANNED` (from `Hub.go`,
|
|
@@ -1372,6 +1419,12 @@ destination session's content pack hash) and `contentUrl` (that pack's immutable
|
|
|
1372
1419
|
URL, or null when the destination has none), or `cancelled`, `full`,
|
|
1373
1420
|
`unavailable`, `not_found`, `forbidden` or `party_required` with those fields null.
|
|
1374
1421
|
|
|
1422
|
+
Castle lists a player at a door only once it has seen them in the place's
|
|
1423
|
+
session, which can take up to 15 seconds after they arrive or after their
|
|
1424
|
+
connection comes back from a break (an app switch, a network drop). In that
|
|
1425
|
+
window `go` and `jump` keep asking and answer once the player is listed, so a
|
|
1426
|
+
`forbidden` they return is final.
|
|
1427
|
+
|
|
1375
1428
|
A door can also lead to a cabinet: a classic Castle deck the host plays itself.
|
|
1376
1429
|
`Hub.go` then answers `status: "ok"` with `kind: "classic"` and null `url`, `nonce`
|
|
1377
1430
|
and `sessionId`: there is no session to join, and the trip is already committed.
|
package/dist/castle.d.ts
CHANGED
|
@@ -13,7 +13,7 @@ export { deckPrefixOf, IMPORTS_DIR, IMPORTS_PREFIX, isImportedFile, resolveDeckF
|
|
|
13
13
|
export { Haptics } from "./haptics";
|
|
14
14
|
export type { CastleHapticsApi, HapticsResult, HapticsStatus, HapticStyle } from "./haptics";
|
|
15
15
|
export { Hub } from "./hub";
|
|
16
|
-
export type { CastleHubApi, HubBackResult, HubCancelResult, HubCancelStatus, HubChatMessage, HubChatResult, HubDoor, HubDoorsResult, HubFriend, HubFriendsResult, HubInviteResult, HubCanInviteResult, HubInviteArrivalResult, HubHeartsResult, HubGoParams, HubSignInParams, HubSignInResult, HubGoResult, HubHandoffResult, HubHandoffStatus, HubJumpResult, HubPlacementKind, HubReportResult, HubSayResult, } from "./hub";
|
|
16
|
+
export type { CastleHubApi, HubBackResult, HubCancelResult, HubCancelStatus, HubChatMessage, HubChatResult, HubDoor, HubDoorsResult, HubFriend, HubFriendsResult, HubInviteResult, HubCanInviteResult, HubInviteArrivalResult, HubHeartsResult, HubGoParams, HubGoRequest, HubSignInParams, HubSignInResult, HubGoResult, HubHandoffResult, HubHandoffStatus, HubJumpResult, HubPlacementKind, HubReportResult, HubSayResult, } from "./hub";
|
|
17
17
|
export { Social } from "./social";
|
|
18
18
|
export type { CastleSocialApi, SocialFriend, SocialPresence } from "./social";
|
|
19
19
|
export { Party } from "./party";
|
|
@@ -42,6 +42,8 @@ export { cardUnit, fitStage, fovForAspect, getDisplay } from "./display";
|
|
|
42
42
|
export type { DeckDisplay, DeckLayout, DeckOrientation } from "./display";
|
|
43
43
|
export { flushSaves, hasPendingSave, onSaveState, writeFile, } from "./saveQueue";
|
|
44
44
|
export type { SaveState } from "./saveQueue";
|
|
45
|
+
export { LocalCache } from "./localCache";
|
|
46
|
+
export type { LocalCacheApi } from "./localCache";
|
|
45
47
|
export { SharedStorage, Storage } from "./storage";
|
|
46
48
|
export { Store } from "./store";
|
|
47
49
|
export type { CastleStoreApi, StoreBoardApi, StoreBoardScore, StoreListEntry, StoreListOptions, StoreListPage, StoreAllowance, StoreScopeApi, StoreUsage, } from "./store";
|
package/dist/castle.js
CHANGED
|
@@ -22,6 +22,7 @@ export { Portal } from "./portal";
|
|
|
22
22
|
export { CARD_RATIO, deleteFile, fileUrl, initCard, onBeforeRestart, onFilesChanged, onSaveReloadState, openFile, renameFile, requestReload, setup, takeReloadState, writeFileOnce, } from "./runtime";
|
|
23
23
|
export { cardUnit, fitStage, fovForAspect, getDisplay } from "./display";
|
|
24
24
|
export { flushSaves, hasPendingSave, onSaveState, writeFile, } from "./saveQueue";
|
|
25
|
+
export { LocalCache } from "./localCache";
|
|
25
26
|
export { SharedStorage, Storage } from "./storage";
|
|
26
27
|
export { Store } from "./store";
|
|
27
28
|
export { Time } from "./time";
|
package/dist/commands.d.ts
CHANGED
|
@@ -348,9 +348,18 @@ export type HubCancelStatus = "cancelled" | "expired" | "none" | "unavailable";
|
|
|
348
348
|
export interface HubCancelResult {
|
|
349
349
|
status: HubCancelStatus;
|
|
350
350
|
}
|
|
351
|
-
export type
|
|
351
|
+
export type HubBackEvent = {
|
|
352
352
|
type: "back";
|
|
353
353
|
};
|
|
354
|
+
export type HubGoEvent = {
|
|
355
|
+
type: "go";
|
|
356
|
+
doorId: string;
|
|
357
|
+
owner?: string;
|
|
358
|
+
title?: string;
|
|
359
|
+
party?: number;
|
|
360
|
+
};
|
|
361
|
+
export type HubEvent = HubBackEvent | HubGoEvent;
|
|
362
|
+
export declare const HUB_GO_DOOR_ID_MAX = 128;
|
|
354
363
|
export interface HubEventEnvelope {
|
|
355
364
|
castleSdk: typeof CASTLE_SDK_PROTOCOL;
|
|
356
365
|
hub: HubEvent;
|
|
@@ -791,6 +800,16 @@ export interface CommandParams {
|
|
|
791
800
|
};
|
|
792
801
|
"cauldronStorage.usage": Record<string, never>;
|
|
793
802
|
"lifecycle.restoreState": Record<string, never>;
|
|
803
|
+
"localCache.get": {
|
|
804
|
+
key: string;
|
|
805
|
+
};
|
|
806
|
+
"localCache.set": {
|
|
807
|
+
key: string;
|
|
808
|
+
value: ArrayBuffer | string;
|
|
809
|
+
};
|
|
810
|
+
"localCache.remove": {
|
|
811
|
+
key: string;
|
|
812
|
+
};
|
|
794
813
|
}
|
|
795
814
|
export interface CommandResult {
|
|
796
815
|
"agent.chat": AgentChatResult;
|
|
@@ -938,6 +957,11 @@ export interface CommandResult {
|
|
|
938
957
|
usage: StoreAllowances;
|
|
939
958
|
};
|
|
940
959
|
"lifecycle.restoreState": LifecycleRestoreStateResult;
|
|
960
|
+
"localCache.get": {
|
|
961
|
+
value: ArrayBuffer | string | null;
|
|
962
|
+
};
|
|
963
|
+
"localCache.set": Record<string, never>;
|
|
964
|
+
"localCache.remove": Record<string, never>;
|
|
941
965
|
}
|
|
942
966
|
export interface UserPayload {
|
|
943
967
|
userId: string;
|
package/dist/commands.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
// Marker + protocol version. Doubles as a discriminator so host messages can't
|
|
7
7
|
// be confused with embed.js `castlexyz:` strings or RN console messages.
|
|
8
8
|
export const CASTLE_SDK_PROTOCOL = 1;
|
|
9
|
+
export const HUB_GO_DOOR_ID_MAX = 128;
|
|
9
10
|
export function hubEventFrom(value) {
|
|
10
11
|
if (typeof value !== "object" || value === null)
|
|
11
12
|
return null;
|
|
@@ -15,7 +16,29 @@ export function hubEventFrom(value) {
|
|
|
15
16
|
const event = record.hub;
|
|
16
17
|
if (typeof event !== "object" || event === null)
|
|
17
18
|
return null;
|
|
18
|
-
|
|
19
|
+
if (event.type === "back")
|
|
20
|
+
return { type: "back" };
|
|
21
|
+
if (event.type === "go")
|
|
22
|
+
return hubGoEventFrom(event);
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
function hubGoEventFrom(event) {
|
|
26
|
+
const { doorId, owner, title, party } = event;
|
|
27
|
+
if (typeof doorId !== "string" || doorId.length === 0 || doorId.length > HUB_GO_DOOR_ID_MAX)
|
|
28
|
+
return null;
|
|
29
|
+
const go = { type: "go", doorId };
|
|
30
|
+
// A bad owner refuses the whole event: a trip to the wrong House is worse
|
|
31
|
+
// than none.
|
|
32
|
+
if (owner !== undefined && owner !== null) {
|
|
33
|
+
if (typeof owner !== "string" || !/^[1-9]\d{0,9}$/.test(owner))
|
|
34
|
+
return null;
|
|
35
|
+
go.owner = owner;
|
|
36
|
+
}
|
|
37
|
+
if (typeof title === "string")
|
|
38
|
+
go.title = title;
|
|
39
|
+
if (typeof party === "number" && Number.isInteger(party) && party > 0)
|
|
40
|
+
go.party = party;
|
|
41
|
+
return go;
|
|
19
42
|
}
|
|
20
43
|
// How long the deck waits for a reply to these commands, in place of the
|
|
21
44
|
// data-command timeout. A deck list fetches every cover on the list. A host
|
|
@@ -32,6 +55,11 @@ export const COMMAND_TIMEOUTS_MS = {
|
|
|
32
55
|
// Native auth may include a provider handoff, but it must not leave a deck
|
|
33
56
|
// waiting forever if the host loses the completion callback.
|
|
34
57
|
"hub.signIn": 120_000,
|
|
58
|
+
// A large entry is an IndexedDB read or write plus a copy into the other
|
|
59
|
+
// frame, and can wait behind other tabs' writes to the same store.
|
|
60
|
+
"localCache.get": 60_000,
|
|
61
|
+
"localCache.set": 60_000,
|
|
62
|
+
"localCache.remove": 60_000,
|
|
35
63
|
};
|
|
36
64
|
// Once a host streams a command, each stream envelope restarts the wait at this
|
|
37
65
|
// length instead. The deck-agent service sends a heartbeat every 15 seconds, and the host
|
package/dist/hub.d.ts
CHANGED
|
@@ -112,5 +112,22 @@ export interface CastleHubApi {
|
|
|
112
112
|
* takes the player home itself. Returns an unsubscribe function.
|
|
113
113
|
*/
|
|
114
114
|
onBack(listener: () => void): () => void;
|
|
115
|
+
/**
|
|
116
|
+
* The host asked to take the player through a door, e.g. a trip begun
|
|
117
|
+
* outside this page. A hub kit answers it like a fired pad: `go(doorId)`
|
|
118
|
+
* behind its door animation, passing `owner` as `ownerUserId` when set.
|
|
119
|
+
* `owner` names whose House a House door leads to, or null; `title` is the
|
|
120
|
+
* host's name for the door, or null; `party` is how many travel (1 when
|
|
121
|
+
* the host does not say). Hosts
|
|
122
|
+
* that never send it are the norm. Returns an unsubscribe function.
|
|
123
|
+
*/
|
|
124
|
+
onGo(listener: (go: HubGoRequest) => void): () => void;
|
|
125
|
+
}
|
|
126
|
+
/** A host's request to go through a door (see `Hub.onGo`). */
|
|
127
|
+
export interface HubGoRequest {
|
|
128
|
+
doorId: string;
|
|
129
|
+
owner: string | null;
|
|
130
|
+
title: string | null;
|
|
131
|
+
party: number;
|
|
115
132
|
}
|
|
116
133
|
export declare const Hub: CastleHubApi;
|
package/dist/hub.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { CastleError } from "./errors";
|
|
2
2
|
import { hostRequest, setHubEventHandler } from "./transport";
|
|
3
|
+
import { HUB_FORBIDDEN_RETRY_MS, rejoinedRecently } from "./hubRejoin";
|
|
3
4
|
export const Hub = {
|
|
4
5
|
go,
|
|
5
6
|
back,
|
|
@@ -19,6 +20,7 @@ export const Hub = {
|
|
|
19
20
|
reportChat,
|
|
20
21
|
cancel,
|
|
21
22
|
onBack,
|
|
23
|
+
onGo,
|
|
22
24
|
};
|
|
23
25
|
async function go(doorId, options = {}) {
|
|
24
26
|
if (typeof doorId !== "string" || doorId.length === 0) {
|
|
@@ -36,7 +38,22 @@ async function go(doorId, options = {}) {
|
|
|
36
38
|
operation: "Hub.go",
|
|
37
39
|
});
|
|
38
40
|
}
|
|
39
|
-
return hostRequest("hub.go", ownerUserId === undefined ? { doorId } : { doorId, ownerUserId });
|
|
41
|
+
return untilListed(() => hostRequest("hub.go", ownerUserId === undefined ? { doorId } : { doorId, ownerUserId }));
|
|
42
|
+
}
|
|
43
|
+
// Right after the socket rejoined its session ghost may not list the player
|
|
44
|
+
// yet, and answers `forbidden` until it does. `Hub.cancel` ends the wait.
|
|
45
|
+
let cancels = 0;
|
|
46
|
+
async function untilListed(ask) {
|
|
47
|
+
const asked = cancels;
|
|
48
|
+
for (;;) {
|
|
49
|
+
const result = await ask();
|
|
50
|
+
if (result.status !== "forbidden" || !rejoinedRecently())
|
|
51
|
+
return result;
|
|
52
|
+
await new Promise((resolve) => setTimeout(resolve, HUB_FORBIDDEN_RETRY_MS));
|
|
53
|
+
if (cancels !== asked) {
|
|
54
|
+
return { status: "cancelled", url: null, nonce: null, sessionId: null, bundleHash: null, contentUrl: null };
|
|
55
|
+
}
|
|
56
|
+
}
|
|
40
57
|
}
|
|
41
58
|
async function back() {
|
|
42
59
|
return hostRequest("hub.back", {});
|
|
@@ -99,7 +116,7 @@ async function jump(userId) {
|
|
|
99
116
|
operation: "Hub.jump",
|
|
100
117
|
});
|
|
101
118
|
}
|
|
102
|
-
return hostRequest("hub.jump", { userId });
|
|
119
|
+
return untilListed(() => hostRequest("hub.jump", { userId }));
|
|
103
120
|
}
|
|
104
121
|
async function report(userId, reason) {
|
|
105
122
|
if (typeof userId !== "string" || userId.length === 0) {
|
|
@@ -135,32 +152,56 @@ async function reportChat(messageId, options) {
|
|
|
135
152
|
return hostRequest("hub.reportChat", { messageId, ...(options?.block === true ? { block: true } : {}) });
|
|
136
153
|
}
|
|
137
154
|
async function cancel() {
|
|
155
|
+
cancels += 1;
|
|
138
156
|
return hostRequest("hub.cancel", {});
|
|
139
157
|
}
|
|
140
158
|
const backListeners = new Set();
|
|
159
|
+
const goListeners = new Set();
|
|
141
160
|
function onBack(listener) {
|
|
161
|
+
return subscribe(backListeners, listener, "Hub.onBack");
|
|
162
|
+
}
|
|
163
|
+
function onGo(listener) {
|
|
164
|
+
return subscribe(goListeners, listener, "Hub.onGo");
|
|
165
|
+
}
|
|
166
|
+
// The host's hub event handler stays installed while any listener of any kind
|
|
167
|
+
// is left, so dropping the last Back listener never silences Go, or vice versa.
|
|
168
|
+
function subscribe(listeners, listener, operation) {
|
|
142
169
|
if (typeof listener !== "function") {
|
|
143
170
|
throw new CastleError({
|
|
144
171
|
code: "INVALID_ARGUMENT",
|
|
145
|
-
message:
|
|
146
|
-
operation
|
|
172
|
+
message: `${operation} requires a function.`,
|
|
173
|
+
operation,
|
|
147
174
|
});
|
|
148
175
|
}
|
|
149
|
-
|
|
176
|
+
listeners.add(listener);
|
|
150
177
|
setHubEventHandler(dispatchHubEvent);
|
|
151
178
|
return () => {
|
|
152
|
-
|
|
153
|
-
if (backListeners.size === 0)
|
|
179
|
+
listeners.delete(listener);
|
|
180
|
+
if (backListeners.size === 0 && goListeners.size === 0)
|
|
154
181
|
setHubEventHandler(null);
|
|
155
182
|
};
|
|
156
183
|
}
|
|
157
|
-
function dispatchHubEvent() {
|
|
158
|
-
|
|
184
|
+
function dispatchHubEvent(event) {
|
|
185
|
+
if (event.type === "back") {
|
|
186
|
+
notify(backListeners, (listener) => listener(), "Hub.onBack");
|
|
187
|
+
}
|
|
188
|
+
else if (event.type === "go") {
|
|
189
|
+
const go = {
|
|
190
|
+
doorId: event.doorId,
|
|
191
|
+
owner: event.owner ?? null,
|
|
192
|
+
title: event.title ?? null,
|
|
193
|
+
party: event.party ?? 1,
|
|
194
|
+
};
|
|
195
|
+
notify(goListeners, (listener) => listener({ ...go }), "Hub.onGo");
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
function notify(listeners, call, operation) {
|
|
199
|
+
for (const listener of [...listeners]) {
|
|
159
200
|
try {
|
|
160
|
-
listener
|
|
201
|
+
call(listener);
|
|
161
202
|
}
|
|
162
203
|
catch (error) {
|
|
163
|
-
console.error(
|
|
204
|
+
console.error(`Castle ${operation} listener threw:`, error);
|
|
164
205
|
}
|
|
165
206
|
}
|
|
166
207
|
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// Ghost's source check for a door reads the session's heartbeat roster, which
|
|
2
|
+
// drops a player who was away and takes up to 15 s to list them again. The host
|
|
3
|
+
// waits that out after an arrival it saw; a socket that reconnected to the same
|
|
4
|
+
// session is one only the deck sees, so the deck waits it out itself.
|
|
5
|
+
export const HUB_ROSTER_LAG_MS = 16_000;
|
|
6
|
+
export const HUB_FORBIDDEN_RETRY_MS = 1_000;
|
|
7
|
+
let rejoinedAt = null;
|
|
8
|
+
// Monotonic where there is one: a wall-clock correction must not stretch or cut the wait.
|
|
9
|
+
const now = () => globalThis.performance?.now() ?? Date.now();
|
|
10
|
+
export function noteSessionRejoined() {
|
|
11
|
+
rejoinedAt = now();
|
|
12
|
+
}
|
|
13
|
+
export function rejoinedRecently() {
|
|
14
|
+
return rejoinedAt !== null && now() - rejoinedAt < HUB_ROSTER_LAG_MS;
|
|
15
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export interface LocalCacheApi {
|
|
2
|
+
getBinary(key: string): Promise<ArrayBuffer | null>;
|
|
3
|
+
getText(key: string): Promise<string | null>;
|
|
4
|
+
set(key: string, value: ArrayBuffer | Uint8Array | string): Promise<void>;
|
|
5
|
+
remove(key: string): Promise<void>;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* A cache on the player's device, for bytes and text the deck can rebuild:
|
|
9
|
+
* downloaded or unpacked assets, compiled data. Entries belong to the deck
|
|
10
|
+
* whose code is running. A hub town's doors change the place but not the
|
|
11
|
+
* code, so the games played through them use the town's entries. In the app,
|
|
12
|
+
* decks loaded from the same web address share entries.
|
|
13
|
+
*
|
|
14
|
+
* Any entry can be gone at any time. Each deck has 20 MB; past that its own
|
|
15
|
+
* least recently used entries are evicted. On the web all decks together
|
|
16
|
+
* have 300 MB; past that the least recently used entries of any deck are
|
|
17
|
+
* evicted. Both are less when the device is short of space. The browser or
|
|
18
|
+
* app may also clear the whole cache.
|
|
19
|
+
*
|
|
20
|
+
* `getBinary` returns bytes (text entries as UTF-8), `getText` returns text
|
|
21
|
+
* (byte entries decoded as UTF-8). `set` takes an ArrayBuffer, a Uint8Array or
|
|
22
|
+
* a string. An ArrayBuffer is moved into the cache and is empty (detached)
|
|
23
|
+
* afterwards, so pass `buffer.slice(0)` to keep a copy; so is the buffer of a
|
|
24
|
+
* Uint8Array that covers all of it. A Uint8Array over part of a buffer is
|
|
25
|
+
* copied.
|
|
26
|
+
*/
|
|
27
|
+
export declare const LocalCache: LocalCacheApi;
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { openLocalCacheStore } from "./localCacheStore";
|
|
2
|
+
import { getCommandChannel, hostRequest } from "./transport";
|
|
3
|
+
// The deck's own origin is its namespace, so every entry there uses this one.
|
|
4
|
+
const OWN_ORIGIN_NAMESPACE = "deck";
|
|
5
|
+
let ownStore = null;
|
|
6
|
+
function usesOwnOrigin() {
|
|
7
|
+
return getCommandChannel() !== "web";
|
|
8
|
+
}
|
|
9
|
+
function store() {
|
|
10
|
+
ownStore ??= openLocalCacheStore();
|
|
11
|
+
return ownStore;
|
|
12
|
+
}
|
|
13
|
+
async function read(key, operation) {
|
|
14
|
+
assertKey(key, operation);
|
|
15
|
+
try {
|
|
16
|
+
if (usesOwnOrigin()) {
|
|
17
|
+
return await store().get(OWN_ORIGIN_NAMESPACE, key);
|
|
18
|
+
}
|
|
19
|
+
const { value } = await hostRequest("localCache.get", { key });
|
|
20
|
+
return value;
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
async function write(key, value) {
|
|
27
|
+
assertKey(key, "LocalCache.set");
|
|
28
|
+
const moved = moveIn(value);
|
|
29
|
+
try {
|
|
30
|
+
if (usesOwnOrigin()) {
|
|
31
|
+
await store().set(OWN_ORIGIN_NAMESPACE, key, moved);
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
const transfer = typeof moved === "string" ? [] : [moved];
|
|
35
|
+
await hostRequest("localCache.set", { key, value: moved }, { transfer });
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
// A write that fails stores nothing.
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
async function remove(key) {
|
|
42
|
+
assertKey(key, "LocalCache.remove");
|
|
43
|
+
try {
|
|
44
|
+
if (usesOwnOrigin()) {
|
|
45
|
+
await store().remove(OWN_ORIGIN_NAMESPACE, key);
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
await hostRequest("localCache.remove", { key });
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
// A host without LocalCache never stored the entry.
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
// An ArrayBuffer is moved, not copied, in every host, so a deck sees the same
|
|
55
|
+
// detached buffer after the call wherever it runs. A Uint8Array that covers
|
|
56
|
+
// its whole buffer moves that buffer the same way; one that covers part of it
|
|
57
|
+
// has its bytes copied, and its buffer is left as it was.
|
|
58
|
+
function moveIn(value) {
|
|
59
|
+
if (typeof value === "string") {
|
|
60
|
+
return value;
|
|
61
|
+
}
|
|
62
|
+
if (value instanceof ArrayBuffer) {
|
|
63
|
+
return structuredClone(value, { transfer: [value] });
|
|
64
|
+
}
|
|
65
|
+
if (value instanceof Uint8Array) {
|
|
66
|
+
const buffer = value.buffer;
|
|
67
|
+
const whole = buffer instanceof ArrayBuffer && value.byteOffset === 0 && value.byteLength === buffer.byteLength;
|
|
68
|
+
return whole ? structuredClone(buffer, { transfer: [buffer] }) : value.slice().buffer;
|
|
69
|
+
}
|
|
70
|
+
throw new TypeError("LocalCache.set takes an ArrayBuffer, a Uint8Array or a string.");
|
|
71
|
+
}
|
|
72
|
+
// The host refuses a key with NUL in it, so the SDK does too, in every host.
|
|
73
|
+
function assertKey(key, operation) {
|
|
74
|
+
if (typeof key !== "string" || key.length === 0 || key.length > 1024 || key.includes("\0")) {
|
|
75
|
+
throw new TypeError(`${operation} takes a key of 1 to 1024 characters, without NUL.`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* A cache on the player's device, for bytes and text the deck can rebuild:
|
|
80
|
+
* downloaded or unpacked assets, compiled data. Entries belong to the deck
|
|
81
|
+
* whose code is running. A hub town's doors change the place but not the
|
|
82
|
+
* code, so the games played through them use the town's entries. In the app,
|
|
83
|
+
* decks loaded from the same web address share entries.
|
|
84
|
+
*
|
|
85
|
+
* Any entry can be gone at any time. Each deck has 20 MB; past that its own
|
|
86
|
+
* least recently used entries are evicted. On the web all decks together
|
|
87
|
+
* have 300 MB; past that the least recently used entries of any deck are
|
|
88
|
+
* evicted. Both are less when the device is short of space. The browser or
|
|
89
|
+
* app may also clear the whole cache.
|
|
90
|
+
*
|
|
91
|
+
* `getBinary` returns bytes (text entries as UTF-8), `getText` returns text
|
|
92
|
+
* (byte entries decoded as UTF-8). `set` takes an ArrayBuffer, a Uint8Array or
|
|
93
|
+
* a string. An ArrayBuffer is moved into the cache and is empty (detached)
|
|
94
|
+
* afterwards, so pass `buffer.slice(0)` to keep a copy; so is the buffer of a
|
|
95
|
+
* Uint8Array that covers all of it. A Uint8Array over part of a buffer is
|
|
96
|
+
* copied.
|
|
97
|
+
*/
|
|
98
|
+
export const LocalCache = {
|
|
99
|
+
async getBinary(key) {
|
|
100
|
+
const value = await read(key, "LocalCache.getBinary");
|
|
101
|
+
if (typeof value === "string") {
|
|
102
|
+
return new TextEncoder().encode(value).buffer;
|
|
103
|
+
}
|
|
104
|
+
return value;
|
|
105
|
+
},
|
|
106
|
+
async getText(key) {
|
|
107
|
+
const value = await read(key, "LocalCache.getText");
|
|
108
|
+
if (value instanceof ArrayBuffer) {
|
|
109
|
+
return new TextDecoder().decode(value);
|
|
110
|
+
}
|
|
111
|
+
return value;
|
|
112
|
+
},
|
|
113
|
+
set: write,
|
|
114
|
+
remove,
|
|
115
|
+
};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export type LocalCacheValue = ArrayBuffer | string;
|
|
2
|
+
export interface LocalCacheStore {
|
|
3
|
+
get(namespace: string, key: string): Promise<LocalCacheValue | null>;
|
|
4
|
+
set(namespace: string, key: string, value: LocalCacheValue): Promise<void>;
|
|
5
|
+
remove(namespace: string, key: string): Promise<void>;
|
|
6
|
+
}
|
|
7
|
+
export interface LocalCacheStoreOptions {
|
|
8
|
+
databaseName?: string;
|
|
9
|
+
deckBudgetBytes?: number;
|
|
10
|
+
totalBudgetBytes?: number;
|
|
11
|
+
}
|
|
12
|
+
export declare const LOCAL_CACHE_DATABASE_NAME = "castle-local-cache";
|
|
13
|
+
export declare const LOCAL_CACHE_DECK_BUDGET_BYTES: number;
|
|
14
|
+
export declare const LOCAL_CACHE_TOTAL_BUDGET_BYTES: number;
|
|
15
|
+
export declare function openLocalCacheStore(options?: LocalCacheStoreOptions): LocalCacheStore;
|
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
// An IndexedDB store for LocalCache entries, with least-recently-used eviction
|
|
2
|
+
// over a budget for each namespace and one for the whole store. The SDK opens
|
|
3
|
+
// it in a deck's own origin (mobile, the dev serve), where there is one
|
|
4
|
+
// namespace; castle-www opens it in castle.xyz's origin for every deck it
|
|
5
|
+
// hosts, so there the namespace is the deck id.
|
|
6
|
+
//
|
|
7
|
+
// No imports: host repos vendor the built file as it is
|
|
8
|
+
// (scripts/copy-host-module.mjs).
|
|
9
|
+
export const LOCAL_CACHE_DATABASE_NAME = "castle-local-cache";
|
|
10
|
+
export const LOCAL_CACHE_DECK_BUDGET_BYTES = 20 * 1024 * 1024;
|
|
11
|
+
export const LOCAL_CACHE_TOTAL_BUDGET_BYTES = 300 * 1024 * 1024;
|
|
12
|
+
const DATABASE_VERSION = 3;
|
|
13
|
+
const VALUES = "values";
|
|
14
|
+
const ENTRIES = "entries";
|
|
15
|
+
const META = "meta";
|
|
16
|
+
const ACCESSED = "accessed";
|
|
17
|
+
const NAMESPACE_ACCESSED = "namespaceAccessed";
|
|
18
|
+
// The `meta` record holding the charged total of every entry, so a write
|
|
19
|
+
// changes the total without reading the other records. Each namespace's total
|
|
20
|
+
// is kept the same way, under namespaceTotalKey.
|
|
21
|
+
const TOTAL = "total";
|
|
22
|
+
// The fixed part of an entry's charge, for its two records. The namespace and
|
|
23
|
+
// key are charged too, at two bytes a character for each of the two places
|
|
24
|
+
// they are stored.
|
|
25
|
+
const RECORD_BYTES = 256;
|
|
26
|
+
// Access times from reads are written in one batch shortly after, so reads run
|
|
27
|
+
// in read-only transactions and do not queue behind each other. Each keeps the
|
|
28
|
+
// time of its read.
|
|
29
|
+
const TOUCH_DELAY_MS = 50;
|
|
30
|
+
export function openLocalCacheStore(options = {}) {
|
|
31
|
+
const databaseName = options.databaseName ?? LOCAL_CACHE_DATABASE_NAME;
|
|
32
|
+
const budgets = {
|
|
33
|
+
deck: options.deckBudgetBytes ?? LOCAL_CACHE_DECK_BUDGET_BYTES,
|
|
34
|
+
total: options.totalBudgetBytes ?? LOCAL_CACHE_TOTAL_BUDGET_BYTES,
|
|
35
|
+
};
|
|
36
|
+
let database = null;
|
|
37
|
+
const touched = new Map();
|
|
38
|
+
let touchTimer = null;
|
|
39
|
+
// A connection that closes or fails to open is dropped, and the next call
|
|
40
|
+
// opens a new one.
|
|
41
|
+
const open = () => {
|
|
42
|
+
if (database) {
|
|
43
|
+
return database;
|
|
44
|
+
}
|
|
45
|
+
const opening = openDatabase(databaseName, () => {
|
|
46
|
+
if (database === opening) {
|
|
47
|
+
database = null;
|
|
48
|
+
}
|
|
49
|
+
}).catch((error) => {
|
|
50
|
+
if (database === opening) {
|
|
51
|
+
database = null;
|
|
52
|
+
}
|
|
53
|
+
throw error;
|
|
54
|
+
});
|
|
55
|
+
database = opening;
|
|
56
|
+
return opening;
|
|
57
|
+
};
|
|
58
|
+
const flushTouches = async () => {
|
|
59
|
+
touchTimer = null;
|
|
60
|
+
const touches = Array.from(touched.values());
|
|
61
|
+
touched.clear();
|
|
62
|
+
await touchEntries(await open(), touches);
|
|
63
|
+
};
|
|
64
|
+
const touch = (id) => {
|
|
65
|
+
touched.set(JSON.stringify(id), { id, accessed: Date.now() });
|
|
66
|
+
touchTimer ??= setTimeout(() => {
|
|
67
|
+
flushTouches().catch(() => undefined);
|
|
68
|
+
}, TOUCH_DELAY_MS);
|
|
69
|
+
};
|
|
70
|
+
return {
|
|
71
|
+
async get(namespace, key) {
|
|
72
|
+
const id = [namespace, key];
|
|
73
|
+
const value = await readValue(await open(), id);
|
|
74
|
+
if (value !== null) {
|
|
75
|
+
touch(id);
|
|
76
|
+
}
|
|
77
|
+
return value;
|
|
78
|
+
},
|
|
79
|
+
async set(namespace, key, value) {
|
|
80
|
+
const id = [namespace, key];
|
|
81
|
+
touched.delete(JSON.stringify(id));
|
|
82
|
+
const write = { id, value, charge: chargeOf(id, value) };
|
|
83
|
+
const freeBytes = await originFreeBytes();
|
|
84
|
+
await writeValue(await open(), write, budgets, freeBytes);
|
|
85
|
+
},
|
|
86
|
+
async remove(namespace, key) {
|
|
87
|
+
const id = [namespace, key];
|
|
88
|
+
touched.delete(JSON.stringify(id));
|
|
89
|
+
await removeValue(await open(), id);
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
function openDatabase(name, onClosed) {
|
|
94
|
+
return new Promise((resolve, reject) => {
|
|
95
|
+
if (typeof indexedDB === "undefined") {
|
|
96
|
+
reject(new Error("IndexedDB is unavailable."));
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
let blocked = false;
|
|
100
|
+
const request = indexedDB.open(name, DATABASE_VERSION);
|
|
101
|
+
request.onupgradeneeded = () => createStores(request.result);
|
|
102
|
+
request.onsuccess = () => {
|
|
103
|
+
const database = request.result;
|
|
104
|
+
// A blocked open has already failed its callers. The connection it gets
|
|
105
|
+
// once the other tab lets go is closed, and the next call opens again.
|
|
106
|
+
if (blocked) {
|
|
107
|
+
database.close();
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
// Another tab opening a later version, or deleting the database, waits
|
|
111
|
+
// until this connection closes.
|
|
112
|
+
database.onversionchange = () => {
|
|
113
|
+
database.close();
|
|
114
|
+
onClosed();
|
|
115
|
+
};
|
|
116
|
+
// The browser closes a connection itself when it clears site data.
|
|
117
|
+
database.onclose = onClosed;
|
|
118
|
+
resolve(database);
|
|
119
|
+
};
|
|
120
|
+
request.onerror = () => reject(request.error ?? new Error("IndexedDB open failed."));
|
|
121
|
+
request.onblocked = () => {
|
|
122
|
+
blocked = true;
|
|
123
|
+
reject(new Error("IndexedDB open was blocked."));
|
|
124
|
+
};
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
// Older versions kept no totals for each namespace, so an older database
|
|
128
|
+
// starts empty, which a cache allows.
|
|
129
|
+
function createStores(database) {
|
|
130
|
+
for (const name of Array.from(database.objectStoreNames)) {
|
|
131
|
+
database.deleteObjectStore(name);
|
|
132
|
+
}
|
|
133
|
+
database.createObjectStore(VALUES);
|
|
134
|
+
const entries = database.createObjectStore(ENTRIES, { keyPath: ["namespace", "key"] });
|
|
135
|
+
entries.createIndex(ACCESSED, "accessed");
|
|
136
|
+
entries.createIndex(NAMESPACE_ACCESSED, ["namespace", "accessed"]);
|
|
137
|
+
database.createObjectStore(META);
|
|
138
|
+
}
|
|
139
|
+
function readValue(database, id) {
|
|
140
|
+
const transaction = database.transaction(VALUES, "readonly");
|
|
141
|
+
const request = transaction.objectStore(VALUES).get(id);
|
|
142
|
+
return finished(transaction).then(() => asValue(request.result));
|
|
143
|
+
}
|
|
144
|
+
function touchEntries(database, touches) {
|
|
145
|
+
if (touches.length === 0) {
|
|
146
|
+
return Promise.resolve();
|
|
147
|
+
}
|
|
148
|
+
const transaction = database.transaction(ENTRIES, "readwrite");
|
|
149
|
+
const entries = transaction.objectStore(ENTRIES);
|
|
150
|
+
for (const { id, accessed } of touches) {
|
|
151
|
+
const request = entries.get(id);
|
|
152
|
+
request.onsuccess = () => {
|
|
153
|
+
const entry = request.result;
|
|
154
|
+
// An entry removed since the read stays removed, and one written since
|
|
155
|
+
// keeps its newer time.
|
|
156
|
+
if (entry && entry.accessed < accessed) {
|
|
157
|
+
entries.put({ ...entry, accessed });
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
return finished(transaction);
|
|
162
|
+
}
|
|
163
|
+
// What the browser says this origin can still store. Neither budget is ever
|
|
164
|
+
// more than the store's own total plus this.
|
|
165
|
+
async function originFreeBytes() {
|
|
166
|
+
try {
|
|
167
|
+
const { quota, usage } = await navigator.storage.estimate();
|
|
168
|
+
if (typeof quota === "number" && typeof usage === "number") {
|
|
169
|
+
return Math.max(0, quota - usage);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
catch {
|
|
173
|
+
// No estimate in this context, or no navigator at all.
|
|
174
|
+
}
|
|
175
|
+
return Infinity;
|
|
176
|
+
}
|
|
177
|
+
// A write the browser refuses for want of space evicts the least recently used
|
|
178
|
+
// entries and is tried once more.
|
|
179
|
+
async function writeValue(database, write, budgets, freeBytes) {
|
|
180
|
+
try {
|
|
181
|
+
await putValue(database, write, budgets, freeBytes);
|
|
182
|
+
}
|
|
183
|
+
catch (error) {
|
|
184
|
+
if (!isQuotaError(error)) {
|
|
185
|
+
throw error;
|
|
186
|
+
}
|
|
187
|
+
await makeRoom(database, write);
|
|
188
|
+
await putValue(database, write, budgets, freeBytes);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
// The write, the totals and the eviction happen in one transaction, so two
|
|
192
|
+
// tabs writing at once still leave the store within its budgets. The writing
|
|
193
|
+
// namespace's own entries are evicted first, until it is within the budget for
|
|
194
|
+
// a namespace; then the entries of every namespace, until the store is within
|
|
195
|
+
// its total budget.
|
|
196
|
+
function putValue(database, write, budgets, freeBytes) {
|
|
197
|
+
const transaction = database.transaction([VALUES, ENTRIES, META], "readwrite");
|
|
198
|
+
const stores = storesOf(transaction);
|
|
199
|
+
const [namespace, key] = write.id;
|
|
200
|
+
readTotals(stores, write.id, (total, namespaceTotal, old) => {
|
|
201
|
+
const totalBudget = Math.min(budgets.total, total + freeBytes);
|
|
202
|
+
const namespaceBudget = Math.min(budgets.deck, totalBudget);
|
|
203
|
+
// An entry over the budget for a namespace is not kept, and the old value
|
|
204
|
+
// under its key goes too, so a later get does not return it.
|
|
205
|
+
if (write.charge > namespaceBudget) {
|
|
206
|
+
deleteEntry(stores, write.id);
|
|
207
|
+
saveTotals(stores, total, new Map(old ? [[namespace, old.size]] : []));
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
stores.values.put(write.value, write.id);
|
|
211
|
+
const entry = { namespace, key, size: write.charge, accessed: Date.now() };
|
|
212
|
+
stores.entries.put(entry);
|
|
213
|
+
const written = write.charge - (old?.size ?? 0);
|
|
214
|
+
stores.meta.put(namespaceTotal + written, namespaceTotalKey(namespace));
|
|
215
|
+
const freed = new Map();
|
|
216
|
+
const namespaceExcess = namespaceTotal + written - namespaceBudget;
|
|
217
|
+
evictOldest(stores, namespace, namespaceExcess, write.id, freed, () => {
|
|
218
|
+
const totalExcess = total + written - sumOf(freed) - totalBudget;
|
|
219
|
+
evictOldest(stores, null, totalExcess, write.id, freed, () => {
|
|
220
|
+
saveTotals(stores, total + written, freed);
|
|
221
|
+
});
|
|
222
|
+
});
|
|
223
|
+
});
|
|
224
|
+
return finished(transaction);
|
|
225
|
+
}
|
|
226
|
+
// After a write is refused for want of space, the old value under its key is
|
|
227
|
+
// removed, and the least recently used entries are evicted until the entries
|
|
228
|
+
// and the new value together take at most half of what the entries took.
|
|
229
|
+
function makeRoom(database, write) {
|
|
230
|
+
const transaction = database.transaction([VALUES, ENTRIES, META], "readwrite");
|
|
231
|
+
const stores = storesOf(transaction);
|
|
232
|
+
readTotals(stores, write.id, (total, _namespaceTotal, old) => {
|
|
233
|
+
deleteEntry(stores, write.id);
|
|
234
|
+
const freed = new Map();
|
|
235
|
+
if (old) {
|
|
236
|
+
freed.set(old.namespace, old.size);
|
|
237
|
+
}
|
|
238
|
+
const target = Math.max(0, total / 2 - write.charge);
|
|
239
|
+
evictOldest(stores, null, total - sumOf(freed) - target, null, freed, () => {
|
|
240
|
+
saveTotals(stores, total, freed);
|
|
241
|
+
});
|
|
242
|
+
});
|
|
243
|
+
return finished(transaction);
|
|
244
|
+
}
|
|
245
|
+
// Walks the entries from least recently accessed, those of one namespace or of
|
|
246
|
+
// all, deleting until `excess` bytes are freed, then calls `then`. The entry
|
|
247
|
+
// just written is skipped. Each deletion is added to `freed` under its
|
|
248
|
+
// namespace.
|
|
249
|
+
function evictOldest(stores, namespace, excess, kept, freed, then) {
|
|
250
|
+
if (excess <= 0) {
|
|
251
|
+
then();
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
const request = namespace === null
|
|
255
|
+
? stores.entries.index(ACCESSED).openCursor()
|
|
256
|
+
: stores.entries
|
|
257
|
+
.index(NAMESPACE_ACCESSED)
|
|
258
|
+
.openCursor(IDBKeyRange.bound([namespace, -Infinity], [namespace, Infinity]));
|
|
259
|
+
request.onsuccess = () => {
|
|
260
|
+
const cursor = request.result;
|
|
261
|
+
if (!cursor || excess <= 0) {
|
|
262
|
+
then();
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
const entry = cursor.value;
|
|
266
|
+
if (!kept || entry.namespace !== kept[0] || entry.key !== kept[1]) {
|
|
267
|
+
stores.values.delete(cursor.primaryKey);
|
|
268
|
+
cursor.delete();
|
|
269
|
+
excess -= entry.size;
|
|
270
|
+
freed.set(entry.namespace, (freed.get(entry.namespace) ?? 0) + entry.size);
|
|
271
|
+
}
|
|
272
|
+
cursor.continue();
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
function removeValue(database, id) {
|
|
276
|
+
const transaction = database.transaction([VALUES, ENTRIES, META], "readwrite");
|
|
277
|
+
const stores = storesOf(transaction);
|
|
278
|
+
readTotals(stores, id, (total, _namespaceTotal, entry) => {
|
|
279
|
+
deleteEntry(stores, id);
|
|
280
|
+
if (entry) {
|
|
281
|
+
saveTotals(stores, total, new Map([[entry.namespace, entry.size]]));
|
|
282
|
+
}
|
|
283
|
+
});
|
|
284
|
+
return finished(transaction);
|
|
285
|
+
}
|
|
286
|
+
function storesOf(transaction) {
|
|
287
|
+
return {
|
|
288
|
+
values: transaction.objectStore(VALUES),
|
|
289
|
+
entries: transaction.objectStore(ENTRIES),
|
|
290
|
+
meta: transaction.objectStore(META),
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
// Requests in a transaction complete in the order they were made, so both
|
|
294
|
+
// totals have been read when the entry's request succeeds.
|
|
295
|
+
function readTotals(stores, id, then) {
|
|
296
|
+
const total = stores.meta.get(TOTAL);
|
|
297
|
+
const namespaceTotal = stores.meta.get(namespaceTotalKey(id[0]));
|
|
298
|
+
const entry = stores.entries.get(id);
|
|
299
|
+
entry.onsuccess = () => {
|
|
300
|
+
then(total.result ?? 0, namespaceTotal.result ?? 0, entry.result);
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
// Stores the total less what was freed, and takes what was freed off each
|
|
304
|
+
// namespace's total. A namespace left with nothing loses its record.
|
|
305
|
+
function saveTotals(stores, total, freed) {
|
|
306
|
+
stores.meta.put(total - sumOf(freed), TOTAL);
|
|
307
|
+
for (const [namespace, bytes] of freed) {
|
|
308
|
+
const request = stores.meta.get(namespaceTotalKey(namespace));
|
|
309
|
+
request.onsuccess = () => {
|
|
310
|
+
const left = (request.result ?? 0) - bytes;
|
|
311
|
+
if (left > 0) {
|
|
312
|
+
stores.meta.put(left, namespaceTotalKey(namespace));
|
|
313
|
+
}
|
|
314
|
+
else {
|
|
315
|
+
stores.meta.delete(namespaceTotalKey(namespace));
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
function namespaceTotalKey(namespace) {
|
|
321
|
+
return ["namespace", namespace];
|
|
322
|
+
}
|
|
323
|
+
function sumOf(freed) {
|
|
324
|
+
let sum = 0;
|
|
325
|
+
for (const bytes of freed.values()) {
|
|
326
|
+
sum += bytes;
|
|
327
|
+
}
|
|
328
|
+
return sum;
|
|
329
|
+
}
|
|
330
|
+
function deleteEntry(stores, id) {
|
|
331
|
+
stores.values.delete(id);
|
|
332
|
+
stores.entries.delete(id);
|
|
333
|
+
}
|
|
334
|
+
// Text is counted at two bytes a character, the size of a JavaScript string,
|
|
335
|
+
// so measuring it costs no encoding.
|
|
336
|
+
function chargeOf(id, value) {
|
|
337
|
+
const valueBytes = typeof value === "string" ? value.length * 2 : value.byteLength;
|
|
338
|
+
return valueBytes + (id[0].length + id[1].length) * 4 + RECORD_BYTES;
|
|
339
|
+
}
|
|
340
|
+
function asValue(stored) {
|
|
341
|
+
if (typeof stored === "string" || stored instanceof ArrayBuffer) {
|
|
342
|
+
return stored;
|
|
343
|
+
}
|
|
344
|
+
return null;
|
|
345
|
+
}
|
|
346
|
+
function isQuotaError(error) {
|
|
347
|
+
return error instanceof DOMException && error.name === "QuotaExceededError";
|
|
348
|
+
}
|
|
349
|
+
// A failed request aborts its transaction with that request's error, so a write
|
|
350
|
+
// the browser refuses for space rejects with QuotaExceededError.
|
|
351
|
+
function finished(transaction) {
|
|
352
|
+
return new Promise((resolve, reject) => {
|
|
353
|
+
transaction.oncomplete = () => resolve();
|
|
354
|
+
transaction.onabort = () => {
|
|
355
|
+
reject(transaction.error ?? new Error("IndexedDB transaction aborted."));
|
|
356
|
+
};
|
|
357
|
+
});
|
|
358
|
+
}
|
package/dist/multiplayer.js
CHANGED
|
@@ -3,6 +3,7 @@ import { BINARY_MESSAGE_TAG, isBinaryPayload, MAX_CLIENT_FRAME_BYTES, toUint8Arr
|
|
|
3
3
|
import { hostRequest } from "./transport";
|
|
4
4
|
import { MultiplayerVoiceImpl } from "./multiplayerVoice";
|
|
5
5
|
import { ReconnectBudget } from "./reconnectBudget";
|
|
6
|
+
import { noteSessionRejoined } from "./hubRejoin";
|
|
6
7
|
const KEEPALIVE_INTERVAL_MS = 25_000;
|
|
7
8
|
const HELLO_TIMEOUT_MS = 10_000;
|
|
8
9
|
const RECONNECT_BUDGET_MS = 30_000;
|
|
@@ -205,6 +206,7 @@ class MultiplayerConnectionImpl {
|
|
|
205
206
|
pongExtensionUsed = false;
|
|
206
207
|
pongDeadline = null;
|
|
207
208
|
reAcquisitionUsed = false;
|
|
209
|
+
greeted = false;
|
|
208
210
|
recovering = false;
|
|
209
211
|
reconnectBudget = null;
|
|
210
212
|
hubSettled = false;
|
|
@@ -580,6 +582,11 @@ class MultiplayerConnectionImpl {
|
|
|
580
582
|
});
|
|
581
583
|
}
|
|
582
584
|
acceptHello(frame) {
|
|
585
|
+
// A later hello is a rejoin the host never hears of; doors wait out the
|
|
586
|
+
// roster lag after it (hubRejoin.ts).
|
|
587
|
+
if (this.greeted)
|
|
588
|
+
noteSessionRejoined();
|
|
589
|
+
this.greeted = true;
|
|
583
590
|
this.currentPlayerId = frame.playerId;
|
|
584
591
|
this.currentSessionId = frame.sessionId;
|
|
585
592
|
// Diagnostics never decide whether a hello is accepted. Missing or malformed
|
package/dist/transport.d.ts
CHANGED
package/dist/transport.js
CHANGED
|
@@ -143,7 +143,7 @@ function sendCommand(channel, command, params, stream) {
|
|
|
143
143
|
return;
|
|
144
144
|
}
|
|
145
145
|
installHostListener();
|
|
146
|
-
sendEnvelope(channel, { castleSdk: CASTLE_SDK_PROTOCOL, requestId, command, params });
|
|
146
|
+
sendEnvelope(channel, { castleSdk: CASTLE_SDK_PROTOCOL, requestId, command, params }, stream.transfer);
|
|
147
147
|
});
|
|
148
148
|
}
|
|
149
149
|
// Interactive commands have no timeout; they resolve only when the host replies.
|
|
@@ -202,13 +202,12 @@ function cancelledError(command) {
|
|
|
202
202
|
operation: command,
|
|
203
203
|
});
|
|
204
204
|
}
|
|
205
|
-
function sendEnvelope(channel, envelope) {
|
|
206
|
-
const json = JSON.stringify(envelope);
|
|
205
|
+
function sendEnvelope(channel, envelope, transfer = []) {
|
|
207
206
|
if (channel === "mobile") {
|
|
208
|
-
window.ReactNativeWebView?.postMessage(
|
|
207
|
+
window.ReactNativeWebView?.postMessage(JSON.stringify(envelope));
|
|
209
208
|
}
|
|
210
209
|
else {
|
|
211
|
-
window.parent.postMessage(envelope, "*");
|
|
210
|
+
window.parent.postMessage(envelope, "*", transfer);
|
|
212
211
|
}
|
|
213
212
|
}
|
|
214
213
|
// The mobile host can't dispatch a DOM 'message' event, so it calls this global
|