@dcl/sdk 7.26.0 → 7.26.1-31714079767.commit-96e9a29
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/atom.d.ts +19 -0
- package/atom.js +83 -0
- package/future.d.ts +8 -0
- package/future.js +26 -0
- package/network/binary-message-bus.d.ts +6 -3
- package/network/binary-message-bus.js +9 -5
- package/network/chunking.d.ts +5 -0
- package/network/chunking.js +38 -0
- package/network/events/implementation.d.ts +93 -0
- package/network/events/implementation.js +221 -0
- package/network/events/index.d.ts +42 -0
- package/network/events/index.js +43 -0
- package/network/events/protocol.d.ts +27 -0
- package/network/events/protocol.js +66 -0
- package/network/events/registry.d.ts +8 -0
- package/network/events/registry.js +3 -0
- package/network/index.d.ts +8 -2
- package/network/index.js +16 -3
- package/network/message-bus-sync.d.ts +16 -3
- package/network/message-bus-sync.js +161 -103
- package/network/server/index.d.ts +14 -0
- package/network/server/index.js +219 -0
- package/network/server/utils.d.ts +18 -0
- package/network/server/utils.js +135 -0
- package/network/state.js +3 -5
- package/package.json +6 -6
- package/server/env-var.d.ts +15 -0
- package/server/env-var.js +31 -0
- package/server/index.d.ts +2 -0
- package/server/index.js +3 -0
- package/server/storage/constants.d.ts +79 -0
- package/server/storage/constants.js +19 -0
- package/server/storage/index.d.ts +45 -0
- package/server/storage/index.js +51 -0
- package/server/storage/player.d.ts +45 -0
- package/server/storage/player.js +198 -0
- package/server/storage/scene.d.ts +40 -0
- package/server/storage/scene.js +188 -0
- package/server/storage/value-cache.d.ts +1 -0
- package/server/storage/value-cache.js +52 -0
- package/server/storage/write-queue.d.ts +1 -0
- package/server/storage/write-queue.js +71 -0
- package/server/storage-url.d.ts +13 -0
- package/server/storage-url.js +42 -0
- package/server/utils.d.ts +35 -0
- package/server/utils.js +61 -0
- package/src/atom.ts +98 -0
- package/src/future.ts +38 -0
- package/src/network/binary-message-bus.ts +9 -4
- package/src/network/chunking.ts +45 -0
- package/src/network/events/implementation.ts +271 -0
- package/src/network/events/index.ts +48 -0
- package/src/network/events/protocol.ts +94 -0
- package/src/network/events/registry.ts +18 -0
- package/src/network/index.ts +40 -3
- package/src/network/message-bus-sync.ts +176 -112
- package/src/network/server/index.ts +301 -0
- package/src/network/server/utils.ts +189 -0
- package/src/network/state.ts +3 -4
- package/src/server/env-var.ts +36 -0
- package/src/server/index.ts +12 -0
- package/src/server/storage/constants.ts +111 -0
- package/src/server/storage/index.ts +74 -0
- package/src/server/storage/player.ts +289 -0
- package/src/server/storage/scene.ts +270 -0
- package/src/server/storage/value-cache.ts +92 -0
- package/src/server/storage/write-queue.ts +131 -0
- package/src/server/storage-url.ts +49 -0
- package/src/server/utils.ts +76 -0
|
@@ -0,0 +1,289 @@
|
|
|
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 { createWriteQueue } from './write-queue'
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Player-scoped storage interface for key-value pairs from the Server Side Storage service.
|
|
17
|
+
* This is NOT filesystem storage - data is stored in the remote storage service.
|
|
18
|
+
*/
|
|
19
|
+
export interface IPlayerStorage {
|
|
20
|
+
/**
|
|
21
|
+
* Retrieves a value from a player's storage by key from the Server Side Storage service.
|
|
22
|
+
*
|
|
23
|
+
* By default (cacheReads), values read or written during the last cacheMaxAgeMs
|
|
24
|
+
* are served from a local cache without a network request, including confirmed
|
|
25
|
+
* "not found" results. Concurrent gets for the same player and key share one
|
|
26
|
+
* request. Out-of-band writers (e.g. CLI storage commands) may not be visible
|
|
27
|
+
* for up to cacheMaxAgeMs — pass { fresh: true } to force a network read.
|
|
28
|
+
* @param address - The player's wallet address
|
|
29
|
+
* @param key - The key to retrieve
|
|
30
|
+
* @param options - Optional { fresh } to bypass the read cache
|
|
31
|
+
* @returns A promise that resolves to the parsed JSON value, or null if not found
|
|
32
|
+
*/
|
|
33
|
+
get<T = unknown>(address: string, key: string, options?: GetOptions): Promise<T | null>
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Stores a value in a player's storage in the Server Side Storage service.
|
|
37
|
+
* @param address - The player's wallet address
|
|
38
|
+
* @param key - The key to store the value under
|
|
39
|
+
* @param value - The value to store (will be JSON serialized)
|
|
40
|
+
* @param options - Optional { skipIfUnchanged } to skip the network write when the value is already stored
|
|
41
|
+
* @returns A promise that resolves to true if successful, false otherwise
|
|
42
|
+
*/
|
|
43
|
+
set<T = unknown>(address: string, key: string, value: T, options?: SetOptions): Promise<boolean>
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Deletes a value from a player's storage in the Server Side Storage service.
|
|
47
|
+
* @param address - The player's wallet address
|
|
48
|
+
* @param key - The key to delete
|
|
49
|
+
* @returns A promise that resolves to true if deleted, false if not found
|
|
50
|
+
*/
|
|
51
|
+
delete(address: string, key: string): Promise<boolean>
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Returns key-value entries from a player's storage, optionally filtered by prefix.
|
|
55
|
+
* Supports pagination via limit and offset.
|
|
56
|
+
* @param address - The player's wallet address
|
|
57
|
+
* @param options - Optional { prefix, limit, offset } for filtering and pagination.
|
|
58
|
+
* @returns A promise that resolves to { data, pagination: { offset, total } } for pagination UI
|
|
59
|
+
*/
|
|
60
|
+
getValues(address: string, options?: GetValuesOptions): Promise<GetValuesResult>
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Creates player-scoped storage that provides methods to interact with
|
|
65
|
+
* player-specific key-value pairs from the Server Side Storage service.
|
|
66
|
+
* This module only works when running on server-side scenes.
|
|
67
|
+
* @internal
|
|
68
|
+
*/
|
|
69
|
+
export const createPlayerStorage = (config: StorageConfigState = createStorageConfig()): IPlayerStorage => {
|
|
70
|
+
const cache = createValueCache(config)
|
|
71
|
+
// Each in-flight GET is tracked by a wrapper object whose identity marks
|
|
72
|
+
// ownership: set()/delete() drop the wrapper, detaching the pending GET so
|
|
73
|
+
// its stale response cannot overwrite the newer cache entry.
|
|
74
|
+
const inflightGets = new Map<string, { promise: Promise<unknown> }>()
|
|
75
|
+
|
|
76
|
+
// Ethereum addresses are case-insensitive (checksum casing only), so
|
|
77
|
+
// mixed-case callers must share the same cache entry. The NUL separator
|
|
78
|
+
// cannot appear in an address, making the pair unambiguous.
|
|
79
|
+
const cacheKey = (address: string, key: string) => `${address.toLowerCase()}\u0000${key}`
|
|
80
|
+
|
|
81
|
+
// Writes to the same player key are serialized (and rapid ones coalesced to
|
|
82
|
+
// the latest value) so the service commits them in issue order — overlapping
|
|
83
|
+
// PUTs would otherwise leave both the kept value and the cached value to
|
|
84
|
+
// response-order chance. Keyed by the same case-insensitive cache key.
|
|
85
|
+
const writes = createWriteQueue()
|
|
86
|
+
|
|
87
|
+
async function executeSet(address: string, key: string, ck: string, body: string): Promise<boolean> {
|
|
88
|
+
const baseUrl = await getStorageServerUrl()
|
|
89
|
+
const url = `${baseUrl}/players/${encodeURIComponent(address)}/values/${encodeURIComponent(key)}`
|
|
90
|
+
|
|
91
|
+
const [error] = await wrapSignedFetch({
|
|
92
|
+
url,
|
|
93
|
+
init: {
|
|
94
|
+
method: 'PUT',
|
|
95
|
+
headers: {
|
|
96
|
+
'content-type': 'application/json'
|
|
97
|
+
},
|
|
98
|
+
body
|
|
99
|
+
}
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
// Either way the entry changed server-side (or may have): detach any
|
|
103
|
+
// overlapping in-flight GET so its stale response is not cached.
|
|
104
|
+
inflightGets.delete(ck)
|
|
105
|
+
|
|
106
|
+
if (error) {
|
|
107
|
+
// The PUT may have reached the server, so the cached body is no
|
|
108
|
+
// longer reliable.
|
|
109
|
+
cache.delete(ck)
|
|
110
|
+
console.error(`Failed to set player storage value '${key}' for '${address}': ${error}`)
|
|
111
|
+
return false
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
cache.set(ck, { body })
|
|
115
|
+
return true
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function executeDelete(address: string, key: string, ck: string): Promise<boolean> {
|
|
119
|
+
const baseUrl = await getStorageServerUrl()
|
|
120
|
+
const url = `${baseUrl}/players/${encodeURIComponent(address)}/values/${encodeURIComponent(key)}`
|
|
121
|
+
|
|
122
|
+
const [error, , status] = await wrapSignedFetch({
|
|
123
|
+
url,
|
|
124
|
+
init: {
|
|
125
|
+
method: 'DELETE',
|
|
126
|
+
headers: {}
|
|
127
|
+
}
|
|
128
|
+
})
|
|
129
|
+
|
|
130
|
+
// Detach again: a GET may have started while the DELETE was in flight.
|
|
131
|
+
inflightGets.delete(ck)
|
|
132
|
+
|
|
133
|
+
if (error) {
|
|
134
|
+
// A 404 still confirms the key is absent server-side.
|
|
135
|
+
if (status === 404) cache.setAbsent(ck)
|
|
136
|
+
console.error(`Failed to delete player storage value '${key}' for '${address}': ${error}`)
|
|
137
|
+
return false
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
cache.setAbsent(ck)
|
|
141
|
+
return true
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return {
|
|
145
|
+
async get<T = unknown>(address: string, key: string, options?: GetOptions): Promise<T | null> {
|
|
146
|
+
assertIsServer(MODULE_NAME)
|
|
147
|
+
|
|
148
|
+
const ck = cacheKey(address, key)
|
|
149
|
+
|
|
150
|
+
if (config.cacheReads && !options?.fresh) {
|
|
151
|
+
const entry = cache.get(ck)
|
|
152
|
+
if (entry?.absent) return null
|
|
153
|
+
// Parse per hit so each caller gets a fresh object (no shared mutation).
|
|
154
|
+
if (entry?.body !== undefined) return JSON.parse(entry.body).value as T
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// Coalesce concurrent gets (even fresh ones: an in-flight response is
|
|
158
|
+
// milliseconds old, not TTL-stale) into a single network request.
|
|
159
|
+
const joined = inflightGets.get(ck)
|
|
160
|
+
if (joined) return joined.promise as Promise<T | null>
|
|
161
|
+
|
|
162
|
+
const inflight = {} as { promise: Promise<T | null> }
|
|
163
|
+
inflight.promise = (async () => {
|
|
164
|
+
try {
|
|
165
|
+
const baseUrl = await getStorageServerUrl()
|
|
166
|
+
const url = `${baseUrl}/players/${encodeURIComponent(address)}/values/${encodeURIComponent(key)}`
|
|
167
|
+
|
|
168
|
+
const [error, data, status] = await wrapSignedFetch<{ value: T }>({ url })
|
|
169
|
+
|
|
170
|
+
const isOwner = inflightGets.get(ck) === inflight
|
|
171
|
+
|
|
172
|
+
if (error) {
|
|
173
|
+
// A confirmed 404 is a first-class "absent" outcome, not a failure.
|
|
174
|
+
if (status === 404) {
|
|
175
|
+
if (isOwner) cache.setAbsent(ck)
|
|
176
|
+
return null
|
|
177
|
+
}
|
|
178
|
+
console.error(`Failed to get player storage value '${key}' for '${address}': ${error}`)
|
|
179
|
+
return null
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
if (data && data.value !== undefined) {
|
|
183
|
+
// Same serialization shape as set()'s PUT body, so a read followed by
|
|
184
|
+
// an unchanged write can be skipped.
|
|
185
|
+
const body = JSON.stringify({ value: data.value })
|
|
186
|
+
if (isOwner) cache.set(ck, { body })
|
|
187
|
+
return data.value
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// 200 with a missing value is ambiguous: neither a confirmed value
|
|
191
|
+
// nor a confirmed absence, so cache nothing.
|
|
192
|
+
return null
|
|
193
|
+
} finally {
|
|
194
|
+
if (inflightGets.get(ck) === inflight) inflightGets.delete(ck)
|
|
195
|
+
}
|
|
196
|
+
})()
|
|
197
|
+
|
|
198
|
+
inflightGets.set(ck, inflight)
|
|
199
|
+
return inflight.promise
|
|
200
|
+
},
|
|
201
|
+
|
|
202
|
+
async set<T = unknown>(address: string, key: string, value: T, options?: SetOptions): Promise<boolean> {
|
|
203
|
+
assertIsServer(MODULE_NAME)
|
|
204
|
+
|
|
205
|
+
const ck = cacheKey(address, key)
|
|
206
|
+
const body = JSON.stringify({ value })
|
|
207
|
+
const skipIfUnchanged = options?.skipIfUnchanged ?? config.skipIfUnchanged
|
|
208
|
+
|
|
209
|
+
// Dedup against confirmed state only while no write is pending — a
|
|
210
|
+
// pending write makes the cache momentarily stale; enqueue() coalesces
|
|
211
|
+
// against pending writes instead.
|
|
212
|
+
if (skipIfUnchanged && writes.pending(ck) === undefined && cache.get(ck)?.body === body) {
|
|
213
|
+
return true
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
return writes.enqueue(ck, body, (b) => executeSet(address, key, ck, b as string), skipIfUnchanged)
|
|
217
|
+
},
|
|
218
|
+
|
|
219
|
+
async delete(address: string, key: string): Promise<boolean> {
|
|
220
|
+
assertIsServer(MODULE_NAME)
|
|
221
|
+
|
|
222
|
+
const ck = cacheKey(address, key)
|
|
223
|
+
|
|
224
|
+
// Invalidate immediately — even while the DELETE waits behind other
|
|
225
|
+
// writes, reads must not serve the doomed value, and a stale
|
|
226
|
+
// "unchanged" skip would lose a future write.
|
|
227
|
+
cache.delete(ck)
|
|
228
|
+
inflightGets.delete(ck)
|
|
229
|
+
|
|
230
|
+
return writes.enqueue(ck, null, () => executeDelete(address, key, ck), true)
|
|
231
|
+
},
|
|
232
|
+
|
|
233
|
+
async getValues(address: string, options?: GetValuesOptions): Promise<GetValuesResult> {
|
|
234
|
+
assertIsServer(MODULE_NAME)
|
|
235
|
+
|
|
236
|
+
const { prefix, limit, offset } = options ?? {}
|
|
237
|
+
const baseUrl = await getStorageServerUrl()
|
|
238
|
+
const parts: string[] = []
|
|
239
|
+
|
|
240
|
+
if (!!prefix) {
|
|
241
|
+
parts.push(`prefix=${encodeURIComponent(prefix)}`)
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
if (!!limit) {
|
|
245
|
+
parts.push(`limit=${limit}`)
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
if (!!offset) {
|
|
249
|
+
parts.push(`offset=${offset}`)
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const query = parts.join('&')
|
|
253
|
+
const url = query
|
|
254
|
+
? `${baseUrl}/players/${encodeURIComponent(address)}/values?${query}`
|
|
255
|
+
: `${baseUrl}/players/${encodeURIComponent(address)}/values`
|
|
256
|
+
|
|
257
|
+
const [error, response] = await wrapSignedFetch<GetValuesResult>({ url })
|
|
258
|
+
|
|
259
|
+
if (error) {
|
|
260
|
+
console.error(`Failed to get player storage values for '${address}': ${error}`)
|
|
261
|
+
return { data: [], pagination: { offset: 0, total: 0 } }
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const data = response?.data ?? []
|
|
265
|
+
|
|
266
|
+
// Seed the per-key cache so subsequent get()/set() on returned keys can
|
|
267
|
+
// skip the network. Only keys with no live entry and no pending write
|
|
268
|
+
// are seeded: existing per-key state comes from a confirmed operation
|
|
269
|
+
// that this page snapshot — whose request started earlier — must not
|
|
270
|
+
// clobber with stale data. Absence is never seeded (prefix/pagination
|
|
271
|
+
// make it non-authoritative). A page larger than cacheMaxEntries churns
|
|
272
|
+
// the cache; entries repopulate lazily.
|
|
273
|
+
for (const entry of data) {
|
|
274
|
+
const ck = cacheKey(address, entry.key)
|
|
275
|
+
if (entry.value !== undefined && !writes.isPending(ck) && cache.get(ck) === undefined) {
|
|
276
|
+
cache.set(ck, { body: JSON.stringify({ value: entry.value }) })
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
const requestedOffset = offset ?? 0
|
|
281
|
+
const pagination = {
|
|
282
|
+
offset: response?.pagination?.offset ?? requestedOffset,
|
|
283
|
+
total: response?.pagination?.total ?? data.length
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
return { data, pagination }
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
}
|
|
@@ -0,0 +1,270 @@
|
|
|
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 { createWriteQueue } from './write-queue'
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Scene-scoped storage interface for key-value pairs from the Server Side Storage service.
|
|
17
|
+
* This is NOT filesystem storage - data is stored in the remote storage service.
|
|
18
|
+
*/
|
|
19
|
+
export interface ISceneStorage {
|
|
20
|
+
/**
|
|
21
|
+
* Retrieves a value from scene storage by key from the Server Side Storage service.
|
|
22
|
+
*
|
|
23
|
+
* By default (cacheReads), values read or written during the last cacheMaxAgeMs
|
|
24
|
+
* are served from a local cache without a network request, including confirmed
|
|
25
|
+
* "not found" results. Concurrent gets for the same key share one request.
|
|
26
|
+
* Out-of-band writers (e.g. CLI storage commands) may not be visible for up to
|
|
27
|
+
* cacheMaxAgeMs — pass { fresh: true } to force a network read.
|
|
28
|
+
* @param key - The key to retrieve
|
|
29
|
+
* @param options - Optional { fresh } to bypass the read cache
|
|
30
|
+
* @returns A promise that resolves to the parsed JSON value, or null if not found
|
|
31
|
+
*/
|
|
32
|
+
get<T = unknown>(key: string, options?: GetOptions): Promise<T | null>
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Stores a value in scene storage in the Server Side Storage service.
|
|
36
|
+
* @param key - The key to store the value under
|
|
37
|
+
* @param value - The value to store (will be JSON serialized)
|
|
38
|
+
* @param options - Optional { skipIfUnchanged } to skip the network write when the value is already stored
|
|
39
|
+
*/
|
|
40
|
+
set<T = unknown>(key: string, value: T, options?: SetOptions): Promise<boolean>
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Deletes a value from scene storage in the Server Side Storage service.
|
|
44
|
+
* @param key - The key to delete
|
|
45
|
+
* @returns A promise that resolves to true if deleted, false if not found
|
|
46
|
+
*/
|
|
47
|
+
delete(key: string): Promise<boolean>
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Returns key-value entries from scene storage, optionally filtered by prefix.
|
|
51
|
+
* Supports pagination via limit and offset.
|
|
52
|
+
* @param options - Optional { prefix, limit, offset } for filtering and pagination.
|
|
53
|
+
* @returns A promise that resolves to { data, pagination: { offset, total } } for pagination UI
|
|
54
|
+
*/
|
|
55
|
+
getValues(options?: GetValuesOptions): Promise<GetValuesResult>
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Creates scene-scoped storage that provides methods to interact with
|
|
60
|
+
* scene-specific key-value pairs from the Server Side Storage service.
|
|
61
|
+
* This module only works when running on server-side scenes.
|
|
62
|
+
* @internal
|
|
63
|
+
*/
|
|
64
|
+
export const createSceneStorage = (config: StorageConfigState = createStorageConfig()): ISceneStorage => {
|
|
65
|
+
const cache = createValueCache(config)
|
|
66
|
+
// Each in-flight GET is tracked by a wrapper object whose identity marks
|
|
67
|
+
// ownership: set()/delete() drop the wrapper, detaching the pending GET so
|
|
68
|
+
// its stale response cannot overwrite the newer cache entry.
|
|
69
|
+
const inflightGets = new Map<string, { promise: Promise<unknown> }>()
|
|
70
|
+
// Writes to the same key are serialized (and rapid ones coalesced to the
|
|
71
|
+
// latest value) so the service commits them in issue order — overlapping
|
|
72
|
+
// PUTs would otherwise leave both the kept value and the cached value to
|
|
73
|
+
// response-order chance.
|
|
74
|
+
const writes = createWriteQueue()
|
|
75
|
+
|
|
76
|
+
async function executeSet(key: string, body: string): Promise<boolean> {
|
|
77
|
+
const baseUrl = await getStorageServerUrl()
|
|
78
|
+
const url = `${baseUrl}/values/${encodeURIComponent(key)}`
|
|
79
|
+
|
|
80
|
+
const [error] = await wrapSignedFetch({
|
|
81
|
+
url,
|
|
82
|
+
init: {
|
|
83
|
+
method: 'PUT',
|
|
84
|
+
headers: {
|
|
85
|
+
'content-type': 'application/json'
|
|
86
|
+
},
|
|
87
|
+
body
|
|
88
|
+
}
|
|
89
|
+
})
|
|
90
|
+
|
|
91
|
+
// Either way the entry changed server-side (or may have): detach any
|
|
92
|
+
// overlapping in-flight GET so its stale response is not cached.
|
|
93
|
+
inflightGets.delete(key)
|
|
94
|
+
|
|
95
|
+
if (error) {
|
|
96
|
+
// The PUT may have reached the server, so the cached body is no
|
|
97
|
+
// longer reliable.
|
|
98
|
+
cache.delete(key)
|
|
99
|
+
console.error(`Failed to set storage value '${key}': ${error}`)
|
|
100
|
+
return false
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
cache.set(key, { body })
|
|
104
|
+
return true
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function executeDelete(key: string): Promise<boolean> {
|
|
108
|
+
const baseUrl = await getStorageServerUrl()
|
|
109
|
+
const url = `${baseUrl}/values/${encodeURIComponent(key)}`
|
|
110
|
+
|
|
111
|
+
const [error, , status] = await wrapSignedFetch({
|
|
112
|
+
url,
|
|
113
|
+
init: {
|
|
114
|
+
method: 'DELETE',
|
|
115
|
+
headers: {}
|
|
116
|
+
}
|
|
117
|
+
})
|
|
118
|
+
|
|
119
|
+
// Detach again: a GET may have started while the DELETE was in flight.
|
|
120
|
+
inflightGets.delete(key)
|
|
121
|
+
|
|
122
|
+
if (error) {
|
|
123
|
+
// A 404 still confirms the key is absent server-side.
|
|
124
|
+
if (status === 404) cache.setAbsent(key)
|
|
125
|
+
console.error(`Failed to delete storage value '${key}': ${error}`)
|
|
126
|
+
return false
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
cache.setAbsent(key)
|
|
130
|
+
return true
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
return {
|
|
134
|
+
async get<T = unknown>(key: string, options?: GetOptions): Promise<T | null> {
|
|
135
|
+
assertIsServer(MODULE_NAME)
|
|
136
|
+
|
|
137
|
+
if (config.cacheReads && !options?.fresh) {
|
|
138
|
+
const entry = cache.get(key)
|
|
139
|
+
if (entry?.absent) return null
|
|
140
|
+
// Parse per hit so each caller gets a fresh object (no shared mutation).
|
|
141
|
+
if (entry?.body !== undefined) return JSON.parse(entry.body).value as T
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// Coalesce concurrent gets (even fresh ones: an in-flight response is
|
|
145
|
+
// milliseconds old, not TTL-stale) into a single network request.
|
|
146
|
+
const joined = inflightGets.get(key)
|
|
147
|
+
if (joined) return joined.promise as Promise<T | null>
|
|
148
|
+
|
|
149
|
+
const inflight = {} as { promise: Promise<T | null> }
|
|
150
|
+
inflight.promise = (async () => {
|
|
151
|
+
try {
|
|
152
|
+
const baseUrl = await getStorageServerUrl()
|
|
153
|
+
const url = `${baseUrl}/values/${encodeURIComponent(key)}`
|
|
154
|
+
|
|
155
|
+
const [error, data, status] = await wrapSignedFetch<{ value: T }>({ url })
|
|
156
|
+
|
|
157
|
+
const isOwner = inflightGets.get(key) === inflight
|
|
158
|
+
|
|
159
|
+
if (error) {
|
|
160
|
+
// A confirmed 404 is a first-class "absent" outcome, not a failure.
|
|
161
|
+
if (status === 404) {
|
|
162
|
+
if (isOwner) cache.setAbsent(key)
|
|
163
|
+
return null
|
|
164
|
+
}
|
|
165
|
+
console.error(`Failed to get storage value '${key}': ${error}`)
|
|
166
|
+
return null
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (data && data.value !== undefined) {
|
|
170
|
+
// Same serialization shape as set()'s PUT body, so a read followed by
|
|
171
|
+
// an unchanged write can be skipped.
|
|
172
|
+
const body = JSON.stringify({ value: data.value })
|
|
173
|
+
if (isOwner) cache.set(key, { body })
|
|
174
|
+
return data.value
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// 200 with a missing value is ambiguous: neither a confirmed value
|
|
178
|
+
// nor a confirmed absence, so cache nothing.
|
|
179
|
+
return null
|
|
180
|
+
} finally {
|
|
181
|
+
if (inflightGets.get(key) === inflight) inflightGets.delete(key)
|
|
182
|
+
}
|
|
183
|
+
})()
|
|
184
|
+
|
|
185
|
+
inflightGets.set(key, inflight)
|
|
186
|
+
return inflight.promise
|
|
187
|
+
},
|
|
188
|
+
|
|
189
|
+
async set<T = unknown>(key: string, value: T, options?: SetOptions): Promise<boolean> {
|
|
190
|
+
assertIsServer(MODULE_NAME)
|
|
191
|
+
|
|
192
|
+
const body = JSON.stringify({ value })
|
|
193
|
+
const skipIfUnchanged = options?.skipIfUnchanged ?? config.skipIfUnchanged
|
|
194
|
+
|
|
195
|
+
// Dedup against confirmed state only while no write is pending — a
|
|
196
|
+
// pending write makes the cache momentarily stale; enqueue() coalesces
|
|
197
|
+
// against pending writes instead.
|
|
198
|
+
if (skipIfUnchanged && writes.pending(key) === undefined && cache.get(key)?.body === body) {
|
|
199
|
+
return true
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
return writes.enqueue(key, body, (b) => executeSet(key, b as string), skipIfUnchanged)
|
|
203
|
+
},
|
|
204
|
+
|
|
205
|
+
async delete(key: string): Promise<boolean> {
|
|
206
|
+
assertIsServer(MODULE_NAME)
|
|
207
|
+
|
|
208
|
+
// Invalidate immediately — even while the DELETE waits behind other
|
|
209
|
+
// writes, reads must not serve the doomed value, and a stale
|
|
210
|
+
// "unchanged" skip would lose a future write.
|
|
211
|
+
cache.delete(key)
|
|
212
|
+
inflightGets.delete(key)
|
|
213
|
+
|
|
214
|
+
return writes.enqueue(key, null, () => executeDelete(key), true)
|
|
215
|
+
},
|
|
216
|
+
|
|
217
|
+
async getValues(options?: GetValuesOptions): Promise<GetValuesResult> {
|
|
218
|
+
assertIsServer(MODULE_NAME)
|
|
219
|
+
|
|
220
|
+
const { prefix, limit, offset } = options ?? {}
|
|
221
|
+
const baseUrl = await getStorageServerUrl()
|
|
222
|
+
const parts: string[] = []
|
|
223
|
+
|
|
224
|
+
if (!!prefix) {
|
|
225
|
+
parts.push(`prefix=${encodeURIComponent(prefix)}`)
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
if (!!limit) {
|
|
229
|
+
parts.push(`limit=${limit}`)
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
if (!!offset) {
|
|
233
|
+
parts.push(`offset=${offset}`)
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const query = parts.join('&')
|
|
237
|
+
const url = query ? `${baseUrl}/values?${query}` : `${baseUrl}/values`
|
|
238
|
+
|
|
239
|
+
const [error, response] = await wrapSignedFetch<GetValuesResult>({ url })
|
|
240
|
+
|
|
241
|
+
if (error) {
|
|
242
|
+
console.error(`Failed to get storage values: ${error}`)
|
|
243
|
+
return { data: [], pagination: { offset: 0, total: 0 } }
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const data = response?.data ?? []
|
|
247
|
+
|
|
248
|
+
// Seed the per-key cache so subsequent get()/set() on returned keys can
|
|
249
|
+
// skip the network. Only keys with no live entry and no pending write
|
|
250
|
+
// are seeded: existing per-key state comes from a confirmed operation
|
|
251
|
+
// that this page snapshot — whose request started earlier — must not
|
|
252
|
+
// clobber with stale data. Absence is never seeded (prefix/pagination
|
|
253
|
+
// make it non-authoritative). A page larger than cacheMaxEntries churns
|
|
254
|
+
// the cache; entries repopulate lazily.
|
|
255
|
+
for (const entry of data) {
|
|
256
|
+
if (entry.value !== undefined && !writes.isPending(entry.key) && cache.get(entry.key) === undefined) {
|
|
257
|
+
cache.set(entry.key, { body: JSON.stringify({ value: entry.value }) })
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const requestedOffset = offset ?? 0
|
|
262
|
+
const pagination = {
|
|
263
|
+
offset: response?.pagination?.offset ?? requestedOffset,
|
|
264
|
+
total: response?.pagination?.total ?? data.length
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
return { data, pagination }
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
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
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Creates the bounded value cache shared by a storage scope.
|
|
36
|
+
* @internal
|
|
37
|
+
*/
|
|
38
|
+
export function createValueCache(config: StorageConfigState): ValueCache {
|
|
39
|
+
const entries = new Map<string, CacheEntry & { storedAt: number }>()
|
|
40
|
+
|
|
41
|
+
function insert(key: string, entry: CacheEntry): void {
|
|
42
|
+
// Delete + re-insert moves refreshed keys to the end of the Map's
|
|
43
|
+
// insertion order, so eviction below drops the least-recently-written.
|
|
44
|
+
entries.delete(key)
|
|
45
|
+
entries.set(key, { ...entry, storedAt: Date.now() })
|
|
46
|
+
|
|
47
|
+
// Guard against misconfiguration: a negative bound would loop forever on
|
|
48
|
+
// an empty map, and a NaN bound would silently disable eviction.
|
|
49
|
+
const maxEntries = Number.isFinite(config.cacheMaxEntries)
|
|
50
|
+
? Math.max(0, config.cacheMaxEntries)
|
|
51
|
+
: DEFAULT_STORAGE_CONFIG.cacheMaxEntries
|
|
52
|
+
|
|
53
|
+
while (entries.size > maxEntries) {
|
|
54
|
+
entries.delete(entries.keys().next().value!)
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
return {
|
|
59
|
+
get(key: string): CacheEntry | undefined {
|
|
60
|
+
const entry = entries.get(key)
|
|
61
|
+
if (!entry) return undefined
|
|
62
|
+
|
|
63
|
+
// Guard against misconfiguration, mirroring cacheMaxEntries: a NaN
|
|
64
|
+
// bound would silently disable expiry (NaN comparisons are false).
|
|
65
|
+
// Negative values need no guard — they just expire everything.
|
|
66
|
+
const maxAgeMs = Number.isFinite(config.cacheMaxAgeMs)
|
|
67
|
+
? config.cacheMaxAgeMs
|
|
68
|
+
: DEFAULT_STORAGE_CONFIG.cacheMaxAgeMs
|
|
69
|
+
|
|
70
|
+
// Lazy max-age expiry: storedAt is never refreshed on hits, so the age
|
|
71
|
+
// bounds the time since the last actual network confirmation.
|
|
72
|
+
if (Date.now() - entry.storedAt > maxAgeMs) {
|
|
73
|
+
entries.delete(key)
|
|
74
|
+
return undefined
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return entry
|
|
78
|
+
},
|
|
79
|
+
|
|
80
|
+
set(key: string, entry: { body: string }): void {
|
|
81
|
+
insert(key, entry)
|
|
82
|
+
},
|
|
83
|
+
|
|
84
|
+
setAbsent(key: string): void {
|
|
85
|
+
insert(key, { absent: true })
|
|
86
|
+
},
|
|
87
|
+
|
|
88
|
+
delete(key: string): void {
|
|
89
|
+
entries.delete(key)
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|