@dcl/sdk 7.30.1 → 7.30.2-37807847179.commit-24c42ea

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.
Files changed (77) hide show
  1. package/atom.d.ts +19 -0
  2. package/atom.js +83 -0
  3. package/future.d.ts +8 -0
  4. package/future.js +26 -0
  5. package/internal/transports/rendererTransport.js +5 -2
  6. package/network/binary-message-bus.d.ts +6 -3
  7. package/network/binary-message-bus.js +9 -5
  8. package/network/chunking.d.ts +5 -0
  9. package/network/chunking.js +38 -0
  10. package/network/events/implementation.d.ts +93 -0
  11. package/network/events/implementation.js +221 -0
  12. package/network/events/index.d.ts +42 -0
  13. package/network/events/index.js +43 -0
  14. package/network/events/protocol.d.ts +27 -0
  15. package/network/events/protocol.js +66 -0
  16. package/network/events/registry.d.ts +8 -0
  17. package/network/events/registry.js +3 -0
  18. package/network/index.d.ts +8 -2
  19. package/network/index.js +16 -3
  20. package/network/message-bus-sync.d.ts +16 -3
  21. package/network/message-bus-sync.js +164 -103
  22. package/network/server/index.d.ts +14 -0
  23. package/network/server/index.js +256 -0
  24. package/network/server/utils.d.ts +18 -0
  25. package/network/server/utils.js +135 -0
  26. package/network/state.js +3 -5
  27. package/package.json +6 -6
  28. package/server/env-var.d.ts +15 -0
  29. package/server/env-var.js +31 -0
  30. package/server/index.d.ts +2 -0
  31. package/server/index.js +3 -0
  32. package/server/storage/constants.d.ts +80 -0
  33. package/server/storage/constants.js +19 -0
  34. package/server/storage/error-message.d.ts +1 -0
  35. package/server/storage/error-message.js +9 -0
  36. package/server/storage/index.d.ts +54 -0
  37. package/server/storage/index.js +60 -0
  38. package/server/storage/player.d.ts +60 -0
  39. package/server/storage/player.js +244 -0
  40. package/server/storage/scene.d.ts +55 -0
  41. package/server/storage/scene.js +232 -0
  42. package/server/storage/serialize.d.ts +1 -0
  43. package/server/storage/serialize.js +135 -0
  44. package/server/storage/value-cache.d.ts +1 -0
  45. package/server/storage/value-cache.js +67 -0
  46. package/server/storage/write-queue.d.ts +1 -0
  47. package/server/storage/write-queue.js +113 -0
  48. package/server/storage-url.d.ts +13 -0
  49. package/server/storage-url.js +42 -0
  50. package/server/utils.d.ts +35 -0
  51. package/server/utils.js +69 -0
  52. package/src/atom.ts +98 -0
  53. package/src/future.ts +38 -0
  54. package/src/internal/transports/rendererTransport.ts +4 -1
  55. package/src/network/binary-message-bus.ts +9 -4
  56. package/src/network/chunking.ts +45 -0
  57. package/src/network/events/implementation.ts +271 -0
  58. package/src/network/events/index.ts +48 -0
  59. package/src/network/events/protocol.ts +94 -0
  60. package/src/network/events/registry.ts +18 -0
  61. package/src/network/index.ts +40 -3
  62. package/src/network/message-bus-sync.ts +180 -112
  63. package/src/network/server/index.ts +341 -0
  64. package/src/network/server/utils.ts +189 -0
  65. package/src/network/state.ts +3 -4
  66. package/src/server/env-var.ts +36 -0
  67. package/src/server/index.ts +12 -0
  68. package/src/server/storage/constants.ts +112 -0
  69. package/src/server/storage/error-message.ts +8 -0
  70. package/src/server/storage/index.ts +83 -0
  71. package/src/server/storage/player.ts +345 -0
  72. package/src/server/storage/scene.ts +324 -0
  73. package/src/server/storage/serialize.ts +132 -0
  74. package/src/server/storage/value-cache.ts +119 -0
  75. package/src/server/storage/write-queue.ts +174 -0
  76. package/src/server/storage-url.ts +49 -0
  77. package/src/server/utils.ts +83 -0
@@ -0,0 +1,324 @@
1
+ import { getStorageServerUrl } from '../storage-url'
2
+ import { assertIsServer, wrapSignedFetch } from '../utils'
3
+ import {
4
+ createStorageConfig,
5
+ GetOptions,
6
+ GetValuesOptions,
7
+ GetValuesResult,
8
+ MODULE_NAME,
9
+ SetOptions,
10
+ StorageConfigState
11
+ } from './constants'
12
+ import { createValueCache } from './value-cache'
13
+ import { errorMessage } from './error-message'
14
+ import { assertStorageKey, serializeStorageValue } from './serialize'
15
+ import { createWriteQueue, SupersedingWriteFailed } from './write-queue'
16
+
17
+ /**
18
+ * Scene-scoped storage interface for key-value pairs from the Server Side Storage service.
19
+ * This is NOT filesystem storage - data is stored in the remote storage service.
20
+ */
21
+ export interface ISceneStorage {
22
+ /**
23
+ * Retrieves a value from scene storage by key from the Server Side Storage service.
24
+ *
25
+ * By default (cacheReads), values read or written during the last cacheMaxAgeMs
26
+ * are served from a local cache without a network request, including confirmed
27
+ * "not found" results. Concurrent gets for the same key share one request.
28
+ * Out-of-band writers (e.g. CLI storage commands) may not be visible for up to
29
+ * cacheMaxAgeMs — pass { fresh: true } to force a network read.
30
+ * A read first waits for writes to the same key that were pending when it was
31
+ * issued, so it reflects every write issued before it.
32
+ * @param key - The key to retrieve
33
+ * @param options - Optional { fresh } to bypass the read cache
34
+ * @returns A promise that resolves to the parsed JSON value, or null if not found
35
+ * @throws Error if the read fails, so a failure is never mistaken for a missing key
36
+ * @throws TypeError if the key is invalid
37
+ */
38
+ get<T = unknown>(key: string, options?: GetOptions): Promise<T | null>
39
+
40
+ /**
41
+ * Stores a value in scene storage in the Server Side Storage service.
42
+ * @param key - The key to store the value under
43
+ * @param value - The value to store (will be JSON serialized)
44
+ * @param options - Optional { skipIfUnchanged } to skip the network write when the value is already stored
45
+ * @returns true once stored, or once a newer write that replaced this one lands
46
+ * (rapid writes coalesce); false if the write, or its replacement, fails
47
+ * @throws TypeError if the key is invalid, or the value cannot be stored unchanged: undefined,
48
+ * circular, a BigInt, or containing a function, a symbol, a non-finite number, an undefined array
49
+ * element or hole, a Map, Set, typed array or other built-in with no JSON form, or text with an
50
+ * unpaired surrogate or a NUL character. An undefined object property is dropped; a Date is
51
+ * stored as its ISO string and a class instance as its own enumerable data.
52
+ */
53
+ set<T = unknown>(key: string, value: T, options?: SetOptions): Promise<boolean>
54
+
55
+ /**
56
+ * Deletes a value from scene storage in the Server Side Storage service.
57
+ * @param key - The key to delete
58
+ * @returns true once applied, or once a newer write that replaced it lands;
59
+ * false only for a confirmed 404
60
+ * @throws Error if the delete, or its replacement, fails; a failure is never reported as absence
61
+ * @throws TypeError if the key is invalid
62
+ */
63
+ delete(key: string): Promise<boolean>
64
+
65
+ /**
66
+ * Returns key-value entries from scene storage, optionally filtered by prefix.
67
+ * Supports pagination via limit and offset.
68
+ * @param options - Optional { prefix, limit, offset } for filtering and pagination.
69
+ * @returns A promise that resolves to { data, pagination: { offset, total } } for pagination UI
70
+ * @throws Error if the read fails, so a failure is never mistaken for an empty page
71
+ */
72
+ getValues(options?: GetValuesOptions): Promise<GetValuesResult>
73
+ }
74
+
75
+ /**
76
+ * Creates scene-scoped storage that provides methods to interact with
77
+ * scene-specific key-value pairs from the Server Side Storage service.
78
+ * This module only works when running on server-side scenes.
79
+ * @internal
80
+ */
81
+ export const createSceneStorage = (config: StorageConfigState = createStorageConfig()): ISceneStorage => {
82
+ const cache = createValueCache(config)
83
+ // Each in-flight GET is tracked by a wrapper object whose identity marks
84
+ // ownership: a landed write detaches the pending GET so its stale response is not cached.
85
+ const inflightGets = new Map<string, { promise: Promise<unknown> }>()
86
+ // Writes to the same key are serialized (and rapid ones coalesced to the
87
+ // latest value) so the service commits them in issue order — overlapping
88
+ // PUTs would otherwise leave both the kept value and the cached value to
89
+ // response-order chance.
90
+ const writes = createWriteQueue()
91
+
92
+ async function executeSet(key: string, body: string): Promise<boolean> {
93
+ let baseUrl: string
94
+ try {
95
+ baseUrl = await getStorageServerUrl()
96
+ } catch (error) {
97
+ cache.delete(key)
98
+ console.error(`Failed to set storage value '${key}': ${errorMessage(error)}`)
99
+ return false
100
+ }
101
+ const url = `${baseUrl}/values/${encodeURIComponent(key)}`
102
+
103
+ const [error] = await wrapSignedFetch({
104
+ url,
105
+ init: {
106
+ method: 'PUT',
107
+ headers: {
108
+ 'content-type': 'application/json'
109
+ },
110
+ body
111
+ }
112
+ })
113
+
114
+ // Either way the entry changed server-side (or may have): detach any
115
+ // overlapping in-flight GET so its stale response is not cached.
116
+ inflightGets.delete(key)
117
+
118
+ if (error) {
119
+ // The PUT may have reached the server, so the cached body is no
120
+ // longer reliable.
121
+ cache.delete(key)
122
+ return false
123
+ }
124
+
125
+ cache.set(key, { body })
126
+ return true
127
+ }
128
+
129
+ async function executeDelete(key: string): Promise<boolean> {
130
+ let baseUrl: string
131
+ try {
132
+ baseUrl = await getStorageServerUrl()
133
+ } catch (error) {
134
+ cache.delete(key)
135
+ throw new Error(`Failed to delete storage value '${key}': ${errorMessage(error)}`)
136
+ }
137
+ const url = `${baseUrl}/values/${encodeURIComponent(key)}`
138
+
139
+ const [error, , status] = await wrapSignedFetch({
140
+ url,
141
+ init: {
142
+ method: 'DELETE',
143
+ headers: {}
144
+ }
145
+ })
146
+
147
+ // Detach again: a GET may have started while the DELETE was in flight.
148
+ inflightGets.delete(key)
149
+
150
+ if (error) {
151
+ // A 404 still confirms the key is absent server-side.
152
+ if (status === 404) {
153
+ cache.setAbsent(key)
154
+ return false
155
+ }
156
+ // The DELETE may have reached the server, so the cached body is unreliable.
157
+ cache.delete(key)
158
+ throw new Error(`Failed to delete storage value '${key}': ${errorMessage(error)}`)
159
+ }
160
+
161
+ cache.setAbsent(key)
162
+ return true
163
+ }
164
+
165
+ return {
166
+ async get<T = unknown>(key: string, options?: GetOptions): Promise<T | null> {
167
+ assertIsServer(MODULE_NAME)
168
+ assertStorageKey(key, 'Storage.get()')
169
+
170
+ if (writes.isPending(key)) await writes.settled(key)
171
+
172
+ if (config.cacheReads && !options?.fresh) {
173
+ const entry = cache.get(key)
174
+ if (entry?.absent) return null
175
+ // Parse per hit so each caller gets a fresh object (no shared mutation).
176
+ if (entry?.body !== undefined) return JSON.parse(entry.body).value as T
177
+ }
178
+
179
+ // Coalesce concurrent gets (even fresh ones: an in-flight response is
180
+ // milliseconds old, not TTL-stale) into a single network request.
181
+ const joined = inflightGets.get(key)
182
+ if (joined) return joined.promise as Promise<T | null>
183
+
184
+ const inflight = {} as { promise: Promise<T | null> }
185
+ inflight.promise = (async () => {
186
+ try {
187
+ let baseUrl: string
188
+ try {
189
+ baseUrl = await getStorageServerUrl()
190
+ } catch (error) {
191
+ throw new Error(`Failed to get storage value '${key}': ${errorMessage(error)}`)
192
+ }
193
+ const url = `${baseUrl}/values/${encodeURIComponent(key)}`
194
+
195
+ const [error, data, status] = await wrapSignedFetch<{ value: T }>({ url })
196
+
197
+ const isOwner = inflightGets.get(key) === inflight
198
+
199
+ if (error) {
200
+ // A confirmed 404 is a first-class "absent" outcome, not a failure.
201
+ if (status === 404) {
202
+ if (isOwner) cache.setAbsent(key)
203
+ return null
204
+ }
205
+ throw new Error(`Failed to get storage value '${key}': ${errorMessage(error)}`)
206
+ }
207
+
208
+ // wrapSignedFetch parses an empty 2xx body as {}: a missing value is a fault, not an absence.
209
+ if (!data || data.value === undefined) {
210
+ throw new Error(`Failed to get storage value '${key}': response carried no value`)
211
+ }
212
+
213
+ // Same serialization shape as set()'s PUT body, so a read followed by
214
+ // an unchanged write can be skipped.
215
+ const body = JSON.stringify({ value: data.value })
216
+ if (isOwner) cache.set(key, { body })
217
+ return data.value
218
+ } finally {
219
+ if (inflightGets.get(key) === inflight) inflightGets.delete(key)
220
+ }
221
+ })()
222
+
223
+ inflightGets.set(key, inflight)
224
+ return inflight.promise
225
+ },
226
+
227
+ async set<T = unknown>(key: string, value: T, options?: SetOptions): Promise<boolean> {
228
+ assertIsServer(MODULE_NAME)
229
+ assertStorageKey(key, 'Storage.set()')
230
+
231
+ const body = serializeStorageValue(value, `Storage.set('${key}')`)
232
+ const skipIfUnchanged = options?.skipIfUnchanged ?? config.skipIfUnchanged
233
+
234
+ // Dedup against confirmed state only while no write is pending — a
235
+ // pending write makes the cache momentarily stale; enqueue() coalesces
236
+ // against pending writes instead.
237
+ if (skipIfUnchanged && writes.pending(key) === undefined && cache.get(key)?.body === body) {
238
+ return true
239
+ }
240
+
241
+ return writes.enqueue(key, body, (b) => executeSet(key, b as string), skipIfUnchanged)
242
+ },
243
+
244
+ async delete(key: string): Promise<boolean> {
245
+ assertIsServer(MODULE_NAME)
246
+ assertStorageKey(key, 'Storage.delete()')
247
+
248
+ return writes
249
+ .enqueue(key, null, () => executeDelete(key), true)
250
+ .catch((error: unknown) => {
251
+ if (error instanceof SupersedingWriteFailed) {
252
+ throw new Error(`Failed to delete storage value '${key}': ${error.message}`)
253
+ }
254
+ throw error
255
+ })
256
+ },
257
+
258
+ async getValues(options?: GetValuesOptions): Promise<GetValuesResult> {
259
+ assertIsServer(MODULE_NAME)
260
+
261
+ const { prefix, limit, offset } = options ?? {}
262
+ let baseUrl: string
263
+ try {
264
+ baseUrl = await getStorageServerUrl()
265
+ } catch (error) {
266
+ throw new Error(`Failed to get storage values: ${errorMessage(error)}`)
267
+ }
268
+ const parts: string[] = []
269
+
270
+ if (!!prefix) {
271
+ parts.push(`prefix=${encodeURIComponent(prefix)}`)
272
+ }
273
+
274
+ if (!!limit) {
275
+ parts.push(`limit=${limit}`)
276
+ }
277
+
278
+ if (!!offset) {
279
+ parts.push(`offset=${offset}`)
280
+ }
281
+
282
+ const query = parts.join('&')
283
+ const url = query ? `${baseUrl}/values?${query}` : `${baseUrl}/values`
284
+
285
+ const watcher = cache.watch()
286
+ const [error, response] = await wrapSignedFetch<GetValuesResult>({ url })
287
+ watcher.stop()
288
+
289
+ if (error) {
290
+ throw new Error(`Failed to get storage values: ${errorMessage(error)}`)
291
+ }
292
+
293
+ const data = response?.data
294
+ if (!Array.isArray(data)) {
295
+ throw new Error('Failed to get storage values: response carried no data array')
296
+ }
297
+ if (data.some((entry) => typeof entry?.key !== 'string' || entry.value === undefined)) {
298
+ throw new Error('Failed to get storage values: response carried a malformed entry')
299
+ }
300
+
301
+ // Seed the per-key cache so subsequent get()/set() on returned keys can
302
+ // skip the network. Only keys with no live entry and no pending write
303
+ // are seeded: existing per-key state comes from a confirmed operation
304
+ // that this page snapshot — whose request started earlier — must not
305
+ // clobber with stale data. Absence is never seeded (prefix/pagination
306
+ // make it non-authoritative). A page larger than cacheMaxEntries churns
307
+ // the cache; entries repopulate lazily.
308
+ for (const entry of data) {
309
+ if (watcher.mutated(entry.key) || writes.isPending(entry.key) || inflightGets.has(entry.key)) continue
310
+ if (cache.get(entry.key) === undefined) {
311
+ cache.set(entry.key, { body: JSON.stringify({ value: entry.value }) })
312
+ }
313
+ }
314
+
315
+ const requestedOffset = offset ?? 0
316
+ const pagination = {
317
+ offset: response!.pagination?.offset ?? requestedOffset,
318
+ total: response!.pagination?.total ?? data.length
319
+ }
320
+
321
+ return { data, pagination }
322
+ }
323
+ }
324
+ }
@@ -0,0 +1,132 @@
1
+ const LONE_SURROGATE = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/
2
+ const UNSTORABLE_TEXT = /\u0000/
3
+ const MAX_KEY_LENGTH = 255
4
+
5
+ /**
6
+ * JSON.stringify always writes NUL as `\u0000` and an unpaired surrogate as a `\udXXX` escape (ES2019),
7
+ * while paired surrogates stay raw; an escaped backslash in front means the text is literal.
8
+ */
9
+ const ESCAPED_UNSTORABLE_TEXT = /(?<!\\)(?:\\\\)*\\u(?:0000|d[89a-f][0-9a-f]{2})/i
10
+
11
+ /** Raised from inside the replacer, so it is not mistaken for an engine error. */
12
+ class UnstorableValueError extends TypeError {}
13
+
14
+ type Reason = (holder: Record<string, unknown>, property: string, item: unknown) => string | undefined
15
+
16
+ /**
17
+ * The `{ value }` PUT body. Rejects, at any depth, what JSON would drop or change: functions,
18
+ * symbols, non-finite numbers, `undefined` array elements and holes, built-ins with no JSON form
19
+ * (Map, Set, typed arrays, RegExp, Error, ...), and text the service cannot store. An `undefined`
20
+ * object property is dropped, as it reads back the same.
21
+ * @internal
22
+ */
23
+ export function serializeStorageValue(value: unknown, callSite: string): string {
24
+ const body = stringify(value, callSite, fastReason)
25
+ // Text is checked once on the output; only a rejection pays for locating the offending item.
26
+ if (ESCAPED_UNSTORABLE_TEXT.test(body)) {
27
+ stringify(value, callSite, unstorable)
28
+ throw new TypeError(`${callSite}: value must not contain an unpaired surrogate or a NUL character.`)
29
+ }
30
+ if (body === '{}') {
31
+ throw new TypeError(`${callSite}: value must be JSON-serializable. Use delete() to remove a key.`)
32
+ }
33
+ return body
34
+ }
35
+
36
+ function stringify(value: unknown, callSite: string, reason: Reason): string {
37
+ const envelope = { value }
38
+ try {
39
+ return JSON.stringify(envelope, function (this: Record<string, unknown>, property, item) {
40
+ const why = reason(this, property, item)
41
+ if (why) {
42
+ const where = this === envelope ? 'the value' : `"${property}"`
43
+ throw new UnstorableValueError(
44
+ `${callSite}: value must be JSON-serializable, but ${where} ${why}. Use delete() to remove a key.`
45
+ )
46
+ }
47
+ return item
48
+ })
49
+ } catch (error) {
50
+ if (error instanceof UnstorableValueError) throw error
51
+ const cause = error instanceof Error ? error.message.split('\n')[0] : String(error)
52
+ throw new TypeError(`${callSite}: value must be JSON-serializable (${cause}). Use delete() to remove a key.`)
53
+ }
54
+ }
55
+
56
+ /** Everything but the text checks, with plain objects and arrays skipping the built-in check. */
57
+ function fastReason(holder: Record<string, unknown>, property: string, item: unknown): string | undefined {
58
+ switch (typeof item) {
59
+ case 'function':
60
+ case 'symbol':
61
+ return `is a ${typeof item}`
62
+ case 'number':
63
+ return Number.isFinite(item) ? undefined : `is the non-finite number ${item}`
64
+ case 'undefined':
65
+ if (Array.isArray(holder)) return 'is undefined or a hole in an array'
66
+ return holder[property] !== undefined ? 'has a toJSON() that returns undefined' : undefined
67
+ case 'object': {
68
+ if (item === null || Array.isArray(item)) return undefined
69
+ const prototype = Object.getPrototypeOf(item)
70
+ return prototype === Object.prototype || prototype === null ? undefined : builtInReason(item)
71
+ }
72
+ default:
73
+ return undefined
74
+ }
75
+ }
76
+
77
+ /** Every check, per item: used to name the item a text rejection comes from. */
78
+ function unstorable(holder: Record<string, unknown>, property: string, item: unknown): string | undefined {
79
+ const fast = fastReason(holder, property, item)
80
+ if (fast) return fast
81
+ if (typeof item === 'string' && (LONE_SURROGATE.test(item) || UNSTORABLE_TEXT.test(item))) {
82
+ return 'contains an unpaired surrogate or a NUL character'
83
+ }
84
+ if (!Array.isArray(holder) && (LONE_SURROGATE.test(property) || UNSTORABLE_TEXT.test(property))) {
85
+ return 'is a key with an unpaired surrogate or a NUL character'
86
+ }
87
+ return undefined
88
+ }
89
+
90
+ function builtInReason(item: unknown): string | undefined {
91
+ const builtIn = builtInName(item)
92
+ return builtIn ? `is ${/^[AEIO]/.test(builtIn) ? 'an' : 'a'} ${builtIn}, which has no JSON form` : undefined
93
+ }
94
+
95
+ function builtInName(item: unknown): string | undefined {
96
+ if (item === null || typeof item !== 'object') return undefined
97
+ if (item instanceof Map) return 'Map'
98
+ if (item instanceof Set) return 'Set'
99
+ if (item instanceof WeakMap) return 'WeakMap'
100
+ if (item instanceof WeakSet) return 'WeakSet'
101
+ if (item instanceof RegExp) return 'RegExp'
102
+ if (item instanceof Error) return 'Error'
103
+ if (item instanceof Promise) return 'Promise'
104
+ if (item instanceof ArrayBuffer) return 'ArrayBuffer'
105
+ if (ArrayBuffer.isView(item)) return item.constructor?.name ?? 'typed array'
106
+ return undefined
107
+ }
108
+
109
+ /**
110
+ * Keys and player addresses go into the request path, where `.`, `..` and an empty segment are
111
+ * resolved away by URL parsing, so they would address a different resource.
112
+ * @internal
113
+ */
114
+ export function assertStorageKey(key: unknown, callSite: string): void {
115
+ if (typeof key !== 'string' || key === '' || key === '.' || key === '..') {
116
+ throw new TypeError(`${callSite}: key must be a non-empty string other than "." and "..".`)
117
+ }
118
+ if (LONE_SURROGATE.test(key) || UNSTORABLE_TEXT.test(key)) {
119
+ throw new TypeError(`${callSite}: key must not contain an unpaired surrogate or a NUL character.`)
120
+ }
121
+ // Counted in characters, as the service counts them.
122
+ if ([...key].length > MAX_KEY_LENGTH) {
123
+ throw new TypeError(`${callSite}: key must be at most ${MAX_KEY_LENGTH} characters.`)
124
+ }
125
+ }
126
+
127
+ /** @internal */
128
+ export function assertPlayerAddress(address: unknown, callSite: string): void {
129
+ if (typeof address !== 'string' || !/^0x[0-9a-fA-F]{40}$/.test(address)) {
130
+ throw new TypeError(`${callSite}: address must be a 0x-prefixed 20-byte hex address.`)
131
+ }
132
+ }
@@ -0,0 +1,119 @@
1
+ import { DEFAULT_STORAGE_CONFIG, StorageConfigState } from './constants'
2
+
3
+ /**
4
+ * A cached fact about a key's server-side state.
5
+ * @internal
6
+ */
7
+ export interface CacheEntry {
8
+ /**
9
+ * Serialized `{ value }` body; absent for negative entries. Parsed per read
10
+ * hit so callers never share object references, and compared verbatim for
11
+ * write dedup (exact equality — no hash-collision risk).
12
+ */
13
+ body?: string
14
+ /** True when the server confirmed the key does not exist (GET 404 or successful DELETE). */
15
+ absent?: boolean
16
+ }
17
+
18
+ /**
19
+ * Bounded, lazily-expiring cache of key states, backing both write dedup
20
+ * (skip storage writes whose value is already known to be stored) and read
21
+ * caching (serve get() without a network request within the TTL).
22
+ * @internal
23
+ */
24
+ export interface ValueCache {
25
+ /** Returns the entry if present and fresh; lazily evicts expired entries. */
26
+ get(key: string): CacheEntry | undefined
27
+ /** Stores or refreshes a known value (serialized body); overwrites negative entries. */
28
+ set(key: string, entry: { body: string }): void
29
+ /** Stores a confirmed-absent (negative) entry, replacing any value entry. */
30
+ setAbsent(key: string): void
31
+ delete(key: string): void
32
+ /** Starts recording mutated keys, so a read issued earlier can tell its snapshot went stale. */
33
+ watch(): CacheWatcher
34
+ }
35
+
36
+ /**
37
+ * Keys mutated since the watch started. Always stop() it, or it keeps collecting.
38
+ * @internal
39
+ */
40
+ export interface CacheWatcher {
41
+ mutated(key: string): boolean
42
+ stop(): void
43
+ }
44
+
45
+ /**
46
+ * Creates the bounded value cache shared by a storage scope.
47
+ * @internal
48
+ */
49
+ export function createValueCache(config: StorageConfigState): ValueCache {
50
+ const entries = new Map<string, CacheEntry & { storedAt: number }>()
51
+ const watchers = new Set<Set<string>>()
52
+
53
+ function noteMutation(key: string): void {
54
+ for (const seen of watchers) seen.add(key)
55
+ }
56
+
57
+ function insert(key: string, entry: CacheEntry): void {
58
+ noteMutation(key)
59
+ // Delete + re-insert moves refreshed keys to the end of the Map's
60
+ // insertion order, so eviction below drops the least-recently-written.
61
+ entries.delete(key)
62
+ entries.set(key, { ...entry, storedAt: Date.now() })
63
+
64
+ // Guard against misconfiguration: a negative bound would loop forever on
65
+ // an empty map, and a NaN bound would silently disable eviction.
66
+ const maxEntries = !Number.isNaN(config.cacheMaxEntries)
67
+ ? Math.max(0, config.cacheMaxEntries)
68
+ : DEFAULT_STORAGE_CONFIG.cacheMaxEntries
69
+
70
+ while (entries.size > maxEntries) {
71
+ entries.delete(entries.keys().next().value!)
72
+ }
73
+ }
74
+
75
+ return {
76
+ get(key: string): CacheEntry | undefined {
77
+ const entry = entries.get(key)
78
+ if (!entry) return undefined
79
+
80
+ // Guard against misconfiguration, mirroring cacheMaxEntries: a NaN
81
+ // bound would silently disable expiry (NaN comparisons are false).
82
+ // Negative values need no guard — they just expire everything.
83
+ const maxAgeMs = !Number.isNaN(config.cacheMaxAgeMs) ? config.cacheMaxAgeMs : DEFAULT_STORAGE_CONFIG.cacheMaxAgeMs
84
+
85
+ // Lazy max-age expiry: storedAt is never refreshed on hits, so the age
86
+ // bounds the time since the last actual network confirmation.
87
+ if (Date.now() - entry.storedAt > maxAgeMs) {
88
+ entries.delete(key)
89
+ return undefined
90
+ }
91
+
92
+ return entry
93
+ },
94
+
95
+ set(key: string, entry: { body: string }): void {
96
+ insert(key, entry)
97
+ },
98
+
99
+ setAbsent(key: string): void {
100
+ insert(key, { absent: true })
101
+ },
102
+
103
+ delete(key: string): void {
104
+ noteMutation(key)
105
+ entries.delete(key)
106
+ },
107
+
108
+ watch(): CacheWatcher {
109
+ const seen = new Set<string>()
110
+ watchers.add(seen)
111
+ return {
112
+ mutated: (key: string) => seen.has(key),
113
+ stop: () => {
114
+ watchers.delete(seen)
115
+ }
116
+ }
117
+ }
118
+ }
119
+ }