@rbxts/scribe 2.5.0

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 (56) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +21 -0
  3. package/README.md +100 -0
  4. package/Scribe-source-map.json +1 -0
  5. package/licenses/ProfileStore-Apache-2.0.txt +201 -0
  6. package/package.json +32 -0
  7. package/src/Client/DebugHook.luau +457 -0
  8. package/src/Client/init.luau +1607 -0
  9. package/src/Internal/Addons.luau +68 -0
  10. package/src/Internal/Big.luau +582 -0
  11. package/src/Internal/Budget.luau +377 -0
  12. package/src/Internal/Clock.luau +75 -0
  13. package/src/Internal/Config.luau +17 -0
  14. package/src/Internal/Conform.luau +400 -0
  15. package/src/Internal/Datatypes.luau +653 -0
  16. package/src/Internal/Defaults.luau +12 -0
  17. package/src/Internal/Derived.luau +428 -0
  18. package/src/Internal/Exchange.luau +556 -0
  19. package/src/Internal/ExchangeLeg.luau +1368 -0
  20. package/src/Internal/ExchangeVerdict.luau +179 -0
  21. package/src/Internal/Failure.luau +148 -0
  22. package/src/Internal/Health.luau +320 -0
  23. package/src/Internal/LeaderboardDiagnostics.luau +36 -0
  24. package/src/Internal/Log.luau +378 -0
  25. package/src/Internal/Marker.luau +76 -0
  26. package/src/Internal/Metrics.luau +152 -0
  27. package/src/Internal/Node.luau +3954 -0
  28. package/src/Internal/Profile.luau +69 -0
  29. package/src/Internal/Rng.luau +83 -0
  30. package/src/Internal/Sched.luau +56 -0
  31. package/src/Internal/Signal.luau +199 -0
  32. package/src/Internal/Store/ProfileStore.luau +3019 -0
  33. package/src/Internal/Store/init.luau +18 -0
  34. package/src/Internal/StudioCodec.luau +155 -0
  35. package/src/Internal/Template.luau +1848 -0
  36. package/src/Internal/Transport.luau +169 -0
  37. package/src/Internal/Util.luau +517 -0
  38. package/src/Internal/Version.luau +4 -0
  39. package/src/Internal/Wire.luau +1283 -0
  40. package/src/Server/Analytics.luau +223 -0
  41. package/src/Server/Commands.luau +728 -0
  42. package/src/Server/DebugHook.luau +1490 -0
  43. package/src/Server/Exchanges.luau +737 -0
  44. package/src/Server/Leaderboards.luau +2143 -0
  45. package/src/Server/Monetization.luau +3212 -0
  46. package/src/Server/Persistence.luau +3775 -0
  47. package/src/Server/Replication.luau +1253 -0
  48. package/src/Server/ServerStore.luau +81 -0
  49. package/src/Server/Timed.luau +579 -0
  50. package/src/Server/init.luau +672 -0
  51. package/src/Types.luau +480 -0
  52. package/src/init.luau +2231 -0
  53. package/types/api.d.ts +252 -0
  54. package/types/common.d.ts +355 -0
  55. package/types/index.d.ts +226 -0
  56. package/types/schema.d.ts +276 -0
@@ -0,0 +1,737 @@
1
+ --!strict
2
+ -- The ClaimExchange subsystem: what owns the verdict key, the in-flight set, and the
3
+ -- resolution that runs on every load. The primitives underneath are dependency-injected
4
+ -- so the specs can drive them against a modelled disk; this layer is thin on purpose and
5
+ -- only decides what the real server passes them.
6
+ --
7
+ -- Resolution runs on load because an exchange can be interrupted at any point and its two
8
+ -- profiles may never be on one server again. Every position has to reach a terminal state
9
+ -- on its own, and a load is the one moment a profile is guaranteed to be looked at. The
10
+ -- cadence exists for sessions that never end.
11
+ local DataStoreService = game:GetService("DataStoreService")
12
+ local HttpService = game:GetService("HttpService")
13
+
14
+ local Internal = script.Parent.Parent.Internal
15
+ local Clock = require(Internal.Clock)
16
+ local Profile = require(Internal.Profile)
17
+ local Log = require(Internal.Log)
18
+ local Rng = require(Internal.Rng)
19
+ local Sched = require(Internal.Sched)
20
+ local Exchange = require(Internal.Exchange)
21
+ local ExchangeLeg = require(Internal.ExchangeLeg)
22
+ local ExchangeVerdict = require(Internal.ExchangeVerdict)
23
+
24
+ local Exchanges = {}
25
+
26
+ -- How often the sweep looks, and how old a record must be before it will touch it.
27
+ --
28
+ -- The age floor is not a tuning knob. A live attempt writes its records and then yields
29
+ -- through two forced flushes, and a sweep resolving them mid-attempt would propose Abort
30
+ -- against an exchange about to commit. The in-flight set covers that on THIS server but
31
+ -- not on another, which sees only the record, so the floor has to exceed the attempt's
32
+ -- own deadline.
33
+ local SWEEP_INTERVAL = 30
34
+ local RESOLVE_AGE_FLOOR = 60
35
+
36
+ --- An in-memory stand-in for the verdict key, with the SAME contract.
37
+ ---
38
+ --- First writer wins and the transform never returns nil: a Mock or NoSave bundle that
39
+ --- behaved differently would make exchanges resolve one way in Studio and another in
40
+ --- production.
41
+ local function newMockVerdictStore()
42
+ local keys: { [string]: any } = {}
43
+ return {
44
+ UpdateAsync = function(_self, key: string, transform: (any) -> any)
45
+ local value = transform(keys[key])
46
+ if value == nil then
47
+ return nil, nil
48
+ end
49
+ keys[key] = value
50
+ return value, nil
51
+ end,
52
+ GetAsync = function(_self, key: string)
53
+ return keys[key], nil
54
+ end,
55
+ }
56
+ end
57
+
58
+ function Exchanges.new(ctx: any)
59
+ local self = {} :: any
60
+
61
+ -- Read the RESOLVED mode rather than the option, the same way Leaderboards does:
62
+ -- Persistence turns Mode into its own fields and never writes it back, so a
63
+ -- Mode = "Mock" bundle would otherwise reach a real DataStore.
64
+ local mode: string = ctx.Persistence.Mode
65
+ local useMock: boolean = mode == "Mock" or mode == "NoSave"
66
+ local storeHandle: any = nil
67
+ local stopped = false
68
+ local sweepThread: thread? = nil
69
+
70
+ -- exchangeId per userId, for THIS server only. The cheap local check, never the
71
+ -- authority: the record answers the same question durably.
72
+ local inFlight: { [number]: string } = {}
73
+ local sweepParked = false
74
+ -- Entries with an exchange open; the sweep parks when there are none.
75
+ local candidates: { [any]: boolean } = {}
76
+ local function watch(entry: any)
77
+ candidates[entry] = true
78
+ if sweepParked and sweepThread ~= nil and not stopped then
79
+ sweepParked = false
80
+ Sched.Resume(sweepThread)
81
+ end
82
+ end
83
+
84
+ self.UsesMockStore = useMock
85
+ self.InFlight = inFlight
86
+
87
+ -- Refused at STARTUP, by name, so a misconfigured game fails to boot rather than
88
+ -- discovering the problem when two players are mid-exchange and value is in escrow.
89
+ -- Logged as well as raised: the raise stops the boot, and the log entry makes the
90
+ -- refusal a filterable diagnostic rather than only a stack trace, which matters when
91
+ -- it surfaces from a place-start in someone else's CI.
92
+ local refuseOk, refusal = pcall(ExchangeLeg.Refuse, ctx.Compiled, ctx.Options.Exchangeable)
93
+ if not refuseOk then
94
+ Log.Error("Exchanges", "EXCHANGE_REGISTRATION_REFUSED", tostring(refusal), {})
95
+ error(refusal, 0)
96
+ end
97
+
98
+ -- Indexed once, and READ on every basket. The startup refusal above proves the
99
+ -- declarations are safe to move; on its own it gated a list nothing consulted, so
100
+ -- a caller could hand Attempt any path the template declared.
101
+ local approved = ExchangeLeg.Approve(ctx.Options.Exchangeable)
102
+
103
+ --- The verdict key's store, acquired lazily: a bundle that never exchanges should not
104
+ --- touch DataStoreService at all, and the acquisition can throw on a server with no data
105
+ --- access.
106
+ function self.VerdictStore(): any
107
+ if storeHandle ~= nil then
108
+ return storeHandle
109
+ end
110
+ if useMock then
111
+ storeHandle = newMockVerdictStore()
112
+ return storeHandle
113
+ end
114
+ local ok, store = pcall(function()
115
+ return DataStoreService:GetDataStore(ExchangeVerdict.STORE_NAME)
116
+ end)
117
+ if not ok or store == nil then
118
+ -- No data access. Falling back to a mock would let exchanges "resolve" against a
119
+ -- store nothing else can see, and the verdict is the one thing that must be global.
120
+ Log.Error(
121
+ "Exchanges",
122
+ "EXCHANGE_STORE_UNAVAILABLE",
123
+ `could not reach the verdict store: {tostring(store)}`,
124
+ {}
125
+ )
126
+ return nil
127
+ end
128
+ storeHandle = store
129
+ return storeHandle
130
+ end
131
+
132
+ --- A forced save of one side. Not true means unproved, never failed.
133
+ local function flushSide(side: any): boolean
134
+ return ctx.Persistence.Flush(side.Ctx.Entry.Player, { Force = true, Timeout = 8 })
135
+ end
136
+
137
+ --- The side descriptor the resolver takes, built from a loaded entry.
138
+ local function sideFor(entry: any): Exchange.Side
139
+ return {
140
+ Ctx = {
141
+ Tree = entry.Tree,
142
+ Entry = entry,
143
+ Compiled = ctx.Compiled,
144
+ UserId = entry.UserId,
145
+ -- On the context, not in the escrow record: a parked delivery can
146
+ -- outlive the server that staked it.
147
+ Plans = approved,
148
+ },
149
+ UserId = entry.UserId,
150
+ Legs = {},
151
+ }
152
+ end
153
+
154
+ -- Conditions already announced, keyed by code and exchange id.
155
+ --
156
+ -- The sweep revisits a stranded exchange every thirty seconds and a parked delivery on
157
+ -- every load, and an alarm repeating twice a minute buries the next one. A restart
158
+ -- re-announces, which is correct: the condition lives on the key, not in this process.
159
+ local announced: { [string]: boolean } = {}
160
+
161
+ local function announce(code: any, exchangeId: string, message: string, context: any)
162
+ local key = `{code}|{exchangeId}`
163
+ if announced[key] then
164
+ return
165
+ end
166
+ announced[key] = true
167
+ Log.Warn("Exchanges", code, message, context)
168
+ end
169
+
170
+ --- Forget an exchange that reached a clean end, so a later one on the same id is heard.
171
+ local function forget(exchangeId: string)
172
+ announced[`EXCHANGE_UNRESOLVED|{exchangeId}`] = nil
173
+ announced[`EXCHANGE_PARKED|{exchangeId}`] = nil
174
+ end
175
+
176
+ --- One exchange, carried to a terminal state and REPORTED. Returns whether it reached
177
+ --- one.
178
+ ---
179
+ --- Shared by the load path and the sweep because the sweep's copy drifted: it counted
180
+ --- every call that did not RAISE, and ResolveOne returns nil with a reason rather than
181
+ --- raising when it merely cannot resolve, so an unreachable verdict key was reported as
182
+ --- resolved on every tick and logged nothing.
183
+ local function resolveExchange(side: any, exchangeId: string, entry: any): boolean
184
+ local store = self.VerdictStore()
185
+ if store == nil then
186
+ return false
187
+ end
188
+ local ok, outcome, err = pcall(Exchange.ResolveOne, { VerdictStore = store }, side, exchangeId)
189
+ local context = { Player = entry.Player, ExchangeId = exchangeId }
190
+ if not ok then
191
+ Log.Error(
192
+ "Exchanges",
193
+ "EXCHANGE_RESOLVE_ERROR",
194
+ `resolving "{exchangeId}" raised: {tostring(outcome)}`,
195
+ context
196
+ )
197
+ return false
198
+ end
199
+ if outcome == nil then
200
+ announce(
201
+ "EXCHANGE_UNRESOLVED",
202
+ exchangeId,
203
+ `"{exchangeId}" could not be resolved: {tostring(err)}`,
204
+ context
205
+ )
206
+ return false
207
+ end
208
+
209
+ -- A delivery that could not be applied stays in the inbox and is retried for ever,
210
+ -- so nothing is lost, but it is invisible unless something says so. It is also the
211
+ -- exact condition Redirect exists for.
212
+ if side.Ctx.Tree.Reserved.ExchangeInbox[exchangeId].Get() ~= nil then
213
+ announce("EXCHANGE_PARKED", exchangeId, `"{exchangeId}" settled but could not be delivered yet`, context)
214
+ else
215
+ forget(exchangeId)
216
+ end
217
+ Log.Info("Exchanges", "EXCHANGE_RESOLVED", `"{exchangeId}" resolved as {outcome}`, context)
218
+ return true
219
+ end
220
+
221
+ --- Carry every exchange this profile still has business with to a terminal state.
222
+ ---
223
+ --- Yields, and runs AFTER the profile is Ready: an exchange resolving a second into play
224
+ --- is invisible, where a load waiting on a DataStore round trip would not be.
225
+ function self.Resolve(entry: any): number
226
+ if stopped or entry == nil or entry.Tree == nil or entry.Tree.Dead then
227
+ return 0
228
+ end
229
+ local side = sideFor(entry)
230
+ local open = Exchange.OpenExchangeIds(side)
231
+ if #open == 0 then
232
+ return 0
233
+ end
234
+ watch(entry)
235
+ if self.VerdictStore() == nil then
236
+ return 0
237
+ end
238
+
239
+ local resolved = 0
240
+ for _, exchangeId in open do
241
+ if stopped or entry.Tree.Dead then
242
+ break
243
+ end
244
+ -- One exchange's failure must not strand the rest: a digest mismatch on one record
245
+ -- is an operator problem, not a reason to leave another exchange's value in escrow.
246
+ if resolveExchange(side, exchangeId, entry) then
247
+ resolved += 1
248
+ end
249
+ end
250
+ return resolved
251
+ end
252
+
253
+ --- Exchange ids an operator verb is currently working on. The sweep skips these: a verb
254
+ --- reads state, decides and writes, and a sweep resolving the same exchange in between
255
+ --- would act on state the verb had already ruled on.
256
+ local operatorHold: { [string]: boolean } = {}
257
+ self.OperatorHold = operatorHold
258
+
259
+ --- The two userIds for an exchange, from a record plus whoever is loaded.
260
+ local function participantsFor(record: any, sides: { any }): (number, number)
261
+ local owner = if type(record.Owner) == "number" then record.Owner else sides[1].UserId
262
+ local partner = if type(record.Partner) == "number" then record.Partner else owner
263
+ if record.Role == "B" then
264
+ return partner, owner
265
+ end
266
+ return owner, partner
267
+ end
268
+
269
+ --- Is this record old enough, and quiet enough, for the sweep to touch? Both guards are
270
+ --- needed: the in-flight set knows only about attempts THIS server is running.
271
+ local function sweepMayResolve(record: any, userId: number, exchangeId: string): boolean
272
+ if inFlight[userId] ~= nil or operatorHold[exchangeId] then
273
+ return false
274
+ end
275
+ local stakedAt = if type(record) == "table" then record.StakedAt else nil
276
+ if type(stakedAt) ~= "number" then
277
+ -- No timestamp: an inbox-only entry, or a record from before this field
278
+ -- existed. Nothing is mid-attempt on it, so the floor has nothing to protect.
279
+ return true
280
+ end
281
+ return (Clock.Now() - stakedAt) >= RESOLVE_AGE_FLOOR
282
+ end
283
+
284
+ --- One sweep over the profiles this server is holding, for sessions that never end: a
285
+ --- load resolves what it finds, but a player who stays on for six hours after a
286
+ --- counterparty vanished would otherwise wait six hours. Returns how many it resolved.
287
+ --- What the sweep may resolve on one entry, and whether any exchange stays open.
288
+ local function sweepEntry(entry: any): (number, boolean)
289
+ if entry.Tree == nil or entry.Tree.Dead then
290
+ return 0, false
291
+ end
292
+ if entry.State ~= "Ready" then
293
+ return 0, true
294
+ end
295
+ local side = sideFor(entry)
296
+ local resolved = 0
297
+ for _, exchangeId in Exchange.OpenExchangeIds(side) do
298
+ if stopped then
299
+ break
300
+ end
301
+ local record = entry.Tree.Reserved.Exchange[exchangeId].Get()
302
+ if sweepMayResolve(record, entry.UserId, exchangeId) and resolveExchange(side, exchangeId, entry) then
303
+ resolved += 1
304
+ end
305
+ end
306
+ return resolved, #Exchange.OpenExchangeIds(side) > 0
307
+ end
308
+
309
+ function self.Sweep(): number
310
+ if stopped then
311
+ return 0
312
+ end
313
+ -- Snapshotted before any yield. The body yields on a store round trip, and adding a
314
+ -- key to a table mid-traversal is undefined in Luau, so a player joining during a
315
+ -- sweep could abandon the rest of the cycle in silence. Never reproduced: the copy
316
+ -- removes the undefined behaviour rather than a measured defect.
317
+ local entries = {}
318
+ for _, entry in ctx.Persistence.Entries do
319
+ table.insert(entries, entry)
320
+ end
321
+
322
+ local resolved = 0
323
+ for _, entry in entries do
324
+ if stopped then
325
+ break
326
+ end
327
+ resolved += (sweepEntry(entry))
328
+ end
329
+ return resolved
330
+ end
331
+
332
+ --- The periodic pass over the entries with an exchange open; a failure keeps its entry.
333
+ function self.SweepCandidates(): number
334
+ local batch = candidates
335
+ candidates = {}
336
+ local resolved = 0
337
+ for entry in batch do
338
+ if stopped then
339
+ break
340
+ end
341
+ if entry.TornDown then
342
+ continue
343
+ end
344
+ local ok, count, open = pcall(sweepEntry, entry)
345
+ if ok then
346
+ resolved += count
347
+ end
348
+ if stopped or entry.TornDown then
349
+ continue
350
+ end
351
+ if not ok or open then
352
+ candidates[entry] = true
353
+ end
354
+ end
355
+ return resolved
356
+ end
357
+
358
+ function self.CandidateCount(): number
359
+ local count = 0
360
+ for _ in candidates do
361
+ count += 1
362
+ end
363
+ return count
364
+ end
365
+
366
+ function self.Parked(): boolean
367
+ return sweepParked
368
+ end
369
+
370
+ local function sweepLoop()
371
+ -- Its own long-lived thread, so what it allocates is attributable. Only Scribe's own
372
+ -- background work: an accessor write runs on the game's calling thread and stays
373
+ -- under the game's category.
374
+ Profile.MemoryCategory("Scribe")
375
+ while not stopped do
376
+ if next(candidates) == nil then
377
+ sweepParked = true
378
+ coroutine.yield()
379
+ sweepParked = false
380
+ if stopped then
381
+ break
382
+ end
383
+ end
384
+ -- Jittered so a shard restart does not put every server's sweep on the same
385
+ -- second, which is how a quiet key becomes a throttled one.
386
+ Clock.Wait(Rng.Jitter(SWEEP_INTERVAL))
387
+ self.SweepCandidates()
388
+ end
389
+ end
390
+
391
+ function self.Start()
392
+ if sweepThread == nil then
393
+ sweepThread = Sched.Spawn(sweepLoop)
394
+ end
395
+ end
396
+
397
+ --------------------------------------------------------------------------------
398
+ -- Operator verbs
399
+ --
400
+ -- For the one case the automatic machinery cannot finish: a verdict key that is gone,
401
+ -- or records that disagree, where a person has to decide. Every one is verdict-gated,
402
+ -- because the verb that replaced the last catastrophic verb reintroduced its shape.
403
+ --------------------------------------------------------------------------------
404
+
405
+ --- Every loaded profile that has business with this exchange.
406
+ local function sidesFor(exchangeId: string)
407
+ local found = {}
408
+ for _, entry in ctx.Persistence.Entries do
409
+ if entry.State == "Ready" and entry.Tree ~= nil and not entry.Tree.Dead then
410
+ local reserved = entry.Tree.Reserved
411
+ if reserved.Exchange[exchangeId].Get() ~= nil or reserved.ExchangeInbox[exchangeId].Get() ~= nil then
412
+ table.insert(found, sideFor(entry))
413
+ end
414
+ end
415
+ end
416
+ return found
417
+ end
418
+
419
+ --- Drop an abandoned exchange that never took value.
420
+ ---
421
+ --- REFUSES IF ANY VERDICT EXISTS. The tempting precondition, "both records are present,
422
+ --- so no side has settled", is true at the read and false at the write with a yielding
423
+ --- store call in between; the verdict key is the only durable statement.
424
+ function self.Discard(exchangeId: string): (boolean, string?)
425
+ if type(exchangeId) ~= "string" or #exchangeId == 0 then
426
+ return false, "discard needs an exchange id"
427
+ end
428
+ if operatorHold[exchangeId] then
429
+ return false, "another operator verb is already holding this exchange"
430
+ end
431
+ operatorHold[exchangeId] = true
432
+
433
+ local ok, result, reason = pcall(function(): (boolean, string?)
434
+ local store = self.VerdictStore()
435
+ if store == nil then
436
+ return false, "the verdict store is unreachable, so no discard can be proved safe"
437
+ end
438
+ -- A failed read is not an absent verdict.
439
+ local verdict, readErr = ExchangeVerdict.Read(store, exchangeId)
440
+ if readErr ~= nil then
441
+ return false,
442
+ `the verdict key for "{exchangeId}" could not be read ({readErr}); nothing can be discarded until it can`
443
+ end
444
+ if verdict ~= nil then
445
+ return false, `exchange "{exchangeId}" already has a {verdict.V} verdict; use settle, not discard`
446
+ end
447
+
448
+ local dropped = 0
449
+ for _, side in sidesFor(exchangeId) do
450
+ -- Phase is re-asserted INSIDE the write by Unclaim, not carried from the
451
+ -- read above: the store call between them yields.
452
+ if select(1, ExchangeLeg.Unclaim(side.Ctx, exchangeId)) then
453
+ dropped += 1
454
+ end
455
+ end
456
+ if dropped == 0 then
457
+ return false, `nothing to discard: no loaded profile holds an unstaked claim for "{exchangeId}"`
458
+ end
459
+ return true, nil
460
+ end)
461
+
462
+ operatorHold[exchangeId] = nil
463
+ if not ok then
464
+ return false, tostring(result)
465
+ end
466
+ return result, reason
467
+ end
468
+
469
+ --- Force a verdict on an exchange that cannot resolve itself.
470
+ ---
471
+ --- The verdict is REQUIRED. Inheriting the resolver's "propose Abort when the key is
472
+ --- empty" would, in exactly the state this verb exists for, land a fresh Abort against a
473
+ --- Commit the other side has already settled.
474
+ function self.Settle(exchangeId: string, verdictKind: string?): (boolean, string?)
475
+ if type(exchangeId) ~= "string" or #exchangeId == 0 then
476
+ return false, "settle needs an exchange id"
477
+ end
478
+ if verdictKind ~= "Commit" and verdictKind ~= "Abort" then
479
+ return false, "settle requires an explicit verdict of Commit or Abort; there is no safe default"
480
+ end
481
+ if operatorHold[exchangeId] then
482
+ return false, "another operator verb is already holding this exchange"
483
+ end
484
+ operatorHold[exchangeId] = true
485
+
486
+ local ok, result, reason = pcall(function(): (boolean, string?)
487
+ local store = self.VerdictStore()
488
+ if store == nil then
489
+ return false, "the verdict store is unreachable"
490
+ end
491
+ local sides = sidesFor(exchangeId)
492
+ if #sides == 0 then
493
+ return false, `no loaded profile has business with "{exchangeId}"`
494
+ end
495
+ local record = nil
496
+ for _, side in sides do
497
+ record = record or side.Ctx.Tree.Reserved.Exchange[exchangeId].Get()
498
+ end
499
+ if record == nil then
500
+ return false, `"{exchangeId}" has no record to settle; only an inbox entry, which delivers on its own`
501
+ end
502
+
503
+ -- Commit is not the peer of Abort. A Commit drops each profile's escrow, safe only
504
+ -- because the counterparty took a durable copy first, and the Take is the evidence.
505
+ -- Both checks below run BEFORE the proposal because the verdict key is permanent and
506
+ -- first-writer-wins: proposing Commit and only then finding the settle cannot be
507
+ -- applied marks the exchange Commit for ever. Abort needs neither check, because
508
+ -- returning an escrow to its owner needs no counterparty at all.
509
+ if verdictKind == "Commit" then
510
+ if #sides < 2 then
511
+ return false,
512
+ `"{exchangeId}" needs both sides loaded to Commit: the verdict binds the absent profile too and `
513
+ .. "this server cannot prove its take was ever filled. Abort is safe from one side"
514
+ end
515
+ for _, side in sides do
516
+ local held = side.Ctx.Tree.Reserved.Exchange[exchangeId].Get()
517
+ if
518
+ held ~= nil
519
+ and type(held.Take) ~= "table"
520
+ and type(held.Escrow) == "table"
521
+ and next(held.Escrow) ~= nil
522
+ then
523
+ return false,
524
+ `"{exchangeId}" holds escrow for {side.UserId} with no take recorded; a Commit would destroy `
525
+ .. "it. Abort returns it to its owner"
526
+ end
527
+ end
528
+ -- Attempt's ordering proof: no Commit verdict until both takes are on disk.
529
+ for _, side in sides do
530
+ local flushOk, flushed = pcall(flushSide, side)
531
+ if not flushOk or flushed ~= true then
532
+ return false,
533
+ `"{exchangeId}" cannot Commit until both records are durable, and the save for {side.UserId} `
534
+ .. "did not complete. Retry once the store answers, or Abort"
535
+ end
536
+ end
537
+ end
538
+
539
+ local userIdA, userIdB = participantsFor(record, sides)
540
+ local verdict = ExchangeVerdict.Propose(store, exchangeId, {
541
+ V = verdictKind,
542
+ A = userIdA,
543
+ B = userIdB,
544
+ D = record.Digest,
545
+ })
546
+ if verdict == nil then
547
+ return false, "no verdict could be established"
548
+ end
549
+ local matches, whyNot = ExchangeVerdict.Matches(verdict, record.Digest, userIdA, userIdB)
550
+ if not matches then
551
+ return false, `verdict does not govern this exchange: {tostring(whyNot)}`
552
+ end
553
+ for _, side in sides do
554
+ pcall(ExchangeLeg.Settle, side.Ctx, exchangeId, verdict)
555
+ pcall(ExchangeLeg.Deliver, side.Ctx, exchangeId)
556
+ end
557
+ return true, `settled as {verdict.V}`
558
+ end)
559
+
560
+ operatorHold[exchangeId] = nil
561
+ if not ok then
562
+ return false, tostring(result)
563
+ end
564
+ return result, reason
565
+ end
566
+
567
+ --- Re-point a parked delivery at a different key on the same container.
568
+ ---
569
+ --- The park that needs this is a destination that is occupied and stays occupied. Only
570
+ --- the KEY moves, so a redirect cannot land value on a path registration never vetted.
571
+ function self.Redirect(exchangeId: string, userId: number, newKey: string): (boolean, string?)
572
+ if type(exchangeId) ~= "string" or type(newKey) ~= "string" or #newKey == 0 then
573
+ return false, "redirect needs an exchange id and a new key"
574
+ end
575
+ if operatorHold[exchangeId] then
576
+ return false, "another operator verb is already holding this exchange"
577
+ end
578
+ -- TAKEN, not merely tested for. This verb checked the hold and never set it, so a
579
+ -- sweep could run underneath: it rewrites a key and then delivers, and a resolution
580
+ -- landing between those two acts on state the verb has already ruled on.
581
+ operatorHold[exchangeId] = true
582
+
583
+ local ok, result, reason = pcall(function(): (boolean, string?)
584
+ for _, side in sidesFor(exchangeId) do
585
+ if side.UserId == userId then
586
+ local parked = side.Ctx.Tree.Reserved.ExchangeInbox[exchangeId].Get()
587
+ if type(parked) ~= "table" or type(parked.Legs) ~= "table" then
588
+ return false, `"{exchangeId}" has no parked delivery for {userId}`
589
+ end
590
+
591
+ -- ONE leg, named by nothing but being the only one. The rewrite used
592
+ -- to point EVERY key leg at the new key, so a two item basket came out
593
+ -- with both legs naming one key: never deliverable, and never
594
+ -- recoverable, because no later redirect can tell them apart again.
595
+ local target = nil
596
+ local count = 0
597
+ -- Stack legs count too: a mixed basket would otherwise collapse a Key
598
+ -- and a Stack leg onto one destination.
599
+ for index, leg in parked.Legs do
600
+ if leg.Kind == "Key" or leg.Kind == "Stack" then
601
+ count += 1
602
+ target = target or index
603
+ end
604
+ end
605
+ if count == 0 then
606
+ return false, `"{exchangeId}" has no key leg to redirect`
607
+ end
608
+ if count > 1 then
609
+ return false,
610
+ `"{exchangeId}" holds more than one key leg, and one new key cannot name {count} `
611
+ .. "destinations without collapsing them onto each other"
612
+ end
613
+
614
+ local rekeyable, whyNot = ExchangeLeg.Rekeyable(ctx.Compiled, parked.Legs[target].Path)
615
+ if not rekeyable then
616
+ return false, `"{exchangeId}" cannot be redirected: {tostring(whyNot)}`
617
+ end
618
+
619
+ side.Ctx.Tree.Reserved.ExchangeInbox[exchangeId].Legs[target].Key.Set(newKey)
620
+ local delivered = select(1, ExchangeLeg.Deliver(side.Ctx, exchangeId))
621
+ return true,
622
+ if delivered
623
+ then `redirected to "{newKey}" and delivered`
624
+ else `redirected to "{newKey}", still parked`
625
+ end
626
+ end
627
+ return false, `no loaded profile holds a parked delivery for "{exchangeId}"`
628
+ end)
629
+
630
+ operatorHold[exchangeId] = nil
631
+ if not ok then
632
+ return false, tostring(result)
633
+ end
634
+ return result, reason
635
+ end
636
+
637
+ --- Every leg in this basket is one the game declared exchangeable.
638
+ ---
639
+ --- THE TRUST BOUNDARY. Baskets enter the library here, and an exchange UI naturally
640
+ --- builds them from what a client asked for. It runs before any slot is claimed and
641
+ --- before any value moves, so a refused basket costs the player nothing.
642
+ local function approveBasket(basket: any): (boolean, string?)
643
+ if basket == nil then
644
+ return true, nil
645
+ end
646
+ if type(basket) ~= "table" then
647
+ return false, "each basket must be a list of legs"
648
+ end
649
+ for _, leg in basket do
650
+ local okLeg, whyLeg = ExchangeLeg.ApprovedLeg(approved, leg)
651
+ if not okLeg then
652
+ return false, whyLeg
653
+ end
654
+ end
655
+ return true, nil
656
+ end
657
+
658
+ --- Begin an exchange between two players on this server.
659
+ ---
660
+ --- Yields. Returns "Committed", "Aborted", or nil with a reason.
661
+ function self.Attempt(playerA: Player, basketA: { any }, playerB: Player, basketB: { any }): (string?, string?)
662
+ local entryA = ctx.Persistence.Entries[playerA]
663
+ local entryB = ctx.Persistence.Entries[playerB]
664
+ if entryA == nil or entryB == nil or entryA.State ~= "Ready" or entryB.State ~= "Ready" then
665
+ return nil, "both players must be loaded on this server"
666
+ end
667
+ -- The allowlist, enforced on the basket. Checked one basket at a time rather than
668
+ -- through a `{ basketA, basketB }` literal, because a nil first basket makes that
669
+ -- literal iterate nothing and skips both.
670
+ local okA, whyA = approveBasket(basketA)
671
+ if not okA then
672
+ return nil, whyA
673
+ end
674
+ local okB, whyB = approveBasket(basketB)
675
+ if not okB then
676
+ return nil, whyB
677
+ end
678
+
679
+ local store = self.VerdictStore()
680
+ if store == nil then
681
+ return nil, "the verdict store is unreachable"
682
+ end
683
+
684
+ local sideA = sideFor(entryA)
685
+ local sideB = sideFor(entryB)
686
+ sideA.Legs = basketA or {}
687
+ sideB.Legs = basketB or {}
688
+ watch(entryA)
689
+ watch(entryB)
690
+
691
+ return Exchange.Attempt({
692
+ ExchangeId = HttpService:GenerateGUID(false),
693
+ VerdictStore = store,
694
+ InFlight = inFlight,
695
+ Options = ctx.Options.Exchange,
696
+ Flush = flushSide,
697
+ }, sideA, sideB)
698
+ end
699
+
700
+ --- What this player still has in flight, and what it is holding while it does.
701
+ function self.Open(player: Player): { Exchange.OpenExchange }
702
+ local entry = ctx.Persistence.Entries[player]
703
+ if entry == nil or entry.Tree == nil or entry.Tree.Dead then
704
+ return {}
705
+ end
706
+ return Exchange.OpenExchanges(sideFor(entry))
707
+ end
708
+
709
+ --- The load hook. Named separately from Resolve so the hook contract and the
710
+ --- operator-facing call cannot drift apart.
711
+ function self.OnLoad(entry: any)
712
+ self.Resolve(entry)
713
+ end
714
+
715
+ function self.OnUnload(entry: any)
716
+ candidates[entry] = nil
717
+ end
718
+
719
+ function self.Stop()
720
+ if stopped then
721
+ return
722
+ end
723
+ stopped = true
724
+ -- Cancelled as well as flagged: a parked loop would otherwise hold a thread per
725
+ -- bundle until its next wake.
726
+ if sweepThread ~= nil then
727
+ pcall(task.cancel, sweepThread)
728
+ sweepThread = nil
729
+ end
730
+ table.clear(inFlight)
731
+ table.clear(candidates)
732
+ end
733
+
734
+ return self
735
+ end
736
+
737
+ return Exchanges