@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,81 @@
1
+ --!strict
2
+ -- The server-owned tree: one store per bundle, shared by everyone on the server.
3
+ -- Nothing here persists (store roots compile with Persist = false), so there is no key,
4
+ -- no session lock and no migration. Built with the bundle, destroyed with it.
5
+
6
+ local Internal = script.Parent.Parent.Internal
7
+ local Node = require(Internal.Node)
8
+ local Template = require(Internal.Template)
9
+ local Log = require(Internal.Log)
10
+ local Metrics = require(Internal.Metrics)
11
+ local Util = require(Internal.Util)
12
+
13
+ local ServerStore = {}
14
+
15
+ --- Builds the store tree, or returns nil when the bundle declared no ServerStore.
16
+ function ServerStore.new(ctx: any): any?
17
+ local storeView = ctx.Compiled.Views.Store
18
+ if storeView == nil then
19
+ return nil
20
+ end
21
+
22
+ local self = {}
23
+ -- One table under both stores: nothing here persists, so the split separates nothing.
24
+ local data = Template.BuildDefaults(storeView, "Session")
25
+
26
+ local tree = Node.NewTree({
27
+ Compiled = storeView,
28
+ Stores = { Persist = data, Session = data },
29
+ IsServer = true,
30
+ IsServerStore = true,
31
+ Label = "ServerStore",
32
+ OnOp = function(op: Node.Op, schema: Template.SchemaNode?)
33
+ ctx.Replication.PushStoreOp(op, schema)
34
+ end,
35
+ OnAnomaly = function(path, _value, reason)
36
+ Metrics.Add("Anomalies")
37
+ Log.Warn("Integrity", "ANOMALY", `implausible store write at "{Util.pathString(path)}": {reason}`, {
38
+ Path = Util.pathString(path),
39
+ Reason = reason,
40
+ })
41
+ end,
42
+ BoundsPolicy = ctx.Options.BoundsPolicy,
43
+ DevMode = ctx.DevMode,
44
+ -- A deadline is swept per profile and economy is reported per player; the store has
45
+ -- neither. Timed is refused at compile time, economy tags are accepted and dropped.
46
+ TimedHooks = nil,
47
+ OnEconomy = nil,
48
+ -- Same codes a player tree uses; no Player to name, so the label goes in the context.
49
+ LogError = function(message: string)
50
+ Log.Error("Lifecycle", "LISTENER_ERROR", message, { Field = "ServerStore" })
51
+ end,
52
+ LogWarn = function(message: string)
53
+ Log.Warn("Lifecycle", "DEV_WARNING", message, { Field = "ServerStore" })
54
+ end,
55
+ OnDerivedIssue = function(code: any, field: string, detail: string)
56
+ local report: typeof(Log.Warn) = if code == "DERIVED_MISMATCH" then Log.Warn else Log.Error
57
+ report("Derived", code, `"{field}": {detail}`, { Field = field })
58
+ end,
59
+ OnBatchEnd = function()
60
+ ctx.Replication.FlushStoreQueue()
61
+ end,
62
+ })
63
+ -- Not done by the constructor: without it a derived store field serves a value computed
64
+ -- from template defaults, which is a plausible wrong number.
65
+ tree:SeedDerived()
66
+
67
+ self.Tree = tree
68
+ self.Data = data
69
+ self.Accessor = tree.Accessor
70
+
71
+ -- A closure, not a method: the failed-build unwind calls pcall(subsystem.Stop) with no
72
+ -- receiver. Destroy does not release Params.Stores, so clear the data table here.
73
+ function self.Stop()
74
+ tree:Destroy()
75
+ table.clear(data)
76
+ end
77
+
78
+ return self
79
+ end
80
+
81
+ return ServerStore
@@ -0,0 +1,579 @@
1
+ --!strict
2
+ -- TTL and cooldowns. Absolute expiry timestamps live under _Scribe.Timed
3
+ -- (server-only), evaluated lazily on read so they survive rejoins; a 1 Hz sweep
4
+ -- clears lapsed fields back to their template default, firing Changed.
5
+
6
+ local Internal = script.Parent.Parent.Internal
7
+ local Util = require(Internal.Util)
8
+ local Node = require(Internal.Node)
9
+ local Template = require(Internal.Template)
10
+ local Log = require(Internal.Log)
11
+ local Clock = require(Internal.Clock)
12
+ local Profile = require(Internal.Profile)
13
+ local Sched = require(Internal.Sched)
14
+ local Rng = require(Internal.Rng)
15
+
16
+ local Timed = {}
17
+
18
+ -- Shared with Template, which rejects a root field using this prefix so a template
19
+ -- field can never alias a cooldown slot in the flat _Scribe.Timed dict.
20
+ local COOLDOWN_PREFIX = Template.COOLDOWN_PREFIX
21
+ local ONLINE_PREFIX = Template.ONLINE_COOLDOWN_PREFIX
22
+ local SWEEP_INTERVAL = 1
23
+
24
+ -- Keys under this prefix are Scribe's, not the game's. Scribe's own once-guards share
25
+ -- the flat cooldown dict a game's cooldowns live in, so the namespace is reserved in both
26
+ -- directions: the sweep does not announce a lapsed claim through OnCooldownEnded, and the
27
+ -- public entry points refuse the prefix loudly, because Data.ClearCooldown on a purchase
28
+ -- idempotency claim is exactly what lets a retry apply the same purchase twice.
29
+ local RESERVED_KEY_PREFIX = "@"
30
+
31
+ --- Is `key` in Scribe's reserved claim namespace?
32
+ local function isReserved(key: string): boolean
33
+ return string.sub(key, 1, #RESERVED_KEY_PREFIX) == RESERVED_KEY_PREFIX
34
+ end
35
+
36
+ --- Guard for the public cooldown API. Internal callers (Claim/IsClaimed) skip it:
37
+ --- they are the ones that own the reserved namespace.
38
+ local function checkPublicKey(key: string, what: string)
39
+ if not Util.isUtf8(key) then
40
+ error(`Scribe: {what} key contains invalid UTF-8 bytes (would corrupt the profile save)`, 3)
41
+ end
42
+ if isReserved(key) then
43
+ error(
44
+ `Scribe: {what} key "{key}" starts with "{RESERVED_KEY_PREFIX}", which is reserved for Scribe's own `
45
+ .. "idempotency claims; pick another prefix",
46
+ 3
47
+ )
48
+ end
49
+ end
50
+
51
+ -- Finite ceiling (~126 years) so SetTimed(value, math.huge) means "effectively
52
+ -- permanent": expiries are written raw into the persisted _Scribe.Timed store, and an
53
+ -- infinite one would break the DataStore JSON round trip.
54
+ local MAX_TIMED_SECONDS = 4e9
55
+
56
+ -- Whole seconds, floored to at least 1 and capped finite.
57
+ local function clampSeconds(seconds: number): number
58
+ return math.max(1, math.floor(math.min(seconds, MAX_TIMED_SECONDS)))
59
+ end
60
+
61
+ function Timed.new(ctx: any)
62
+ local self = {} :: any
63
+ local compiled: Template.Compiled = ctx.Compiled
64
+ local visibleFields: { [string]: string } = {}
65
+ for id, node in compiled.ById do
66
+ if node.Timed and node.Visibility ~= "ServerOnly" then
67
+ visibleFields[Util.pathKey(node.Path)] = tostring(id)
68
+ end
69
+ end
70
+
71
+ local stopped = false
72
+ local sweepThread: thread? = nil
73
+ local sweepParked = false
74
+ -- Entries holding a timer; the sweep parks when there are none.
75
+ local active: { [any]: boolean } = {}
76
+ local function watch(entry: any)
77
+ active[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
+ local function timedStore(entry: any): { [string]: number }?
85
+ -- While a save is in flight the profile carries a converted copy (see BeforeSave)
86
+ -- and the live deadlines move here, so no reader ever sees the persisted form.
87
+ if entry.TimedLive then
88
+ return entry.TimedLive
89
+ end
90
+ local live = entry.LiveData
91
+ local reserved = if live then live[Template.RESERVED_ROOT] else nil
92
+ if type(reserved) ~= "table" then
93
+ return nil
94
+ end
95
+ if type(reserved.Timed) ~= "table" then
96
+ reserved.Timed = {}
97
+ end
98
+ return reserved.Timed
99
+ end
100
+
101
+ -- Write an internal expiry, or clear it with value == nil, straight into the ServerOnly
102
+ -- _Scribe.Timed dict. It bypasses the accessor tree on purpose: a nested Scribe.Timed
103
+ -- field's pathKey embeds the \31 separator, which Node's dictionary-key guard rejects.
104
+ -- The store lives in profile.Data, so a raw write persists on the next save; Dirty only
105
+ -- makes that save prompt rather than the next autosave tick.
106
+ local function setTimed(entry: any, pathKey: string, value: number?, replicate: boolean?)
107
+ local store = timedStore(entry)
108
+ if not store then
109
+ return
110
+ end
111
+ local tree = entry.Tree
112
+ -- Cross-tree check first: refuse while a transaction is open on another player.
113
+ -- RecordRawWrite below can only roll back for the tree that owns the transaction,
114
+ -- so on any other tree it is a no-op and the write would outlive the rollback.
115
+ -- Level 4: AssertSameTreeWrite (1) -> setTimed (2) -> the Timed entry point (3) ->
116
+ -- its public caller (4).
117
+ Node.AssertSameTreeWrite(tree, `{Template.RESERVED_ROOT}.Timed.{pathKey}`, 4)
118
+ -- Record the pre-write expiry so a rollback reverts it in lockstep with the
119
+ -- field's value; without it the value reverts but the timer does not, and a
120
+ -- cooldown armed inside an aborted transaction persists. No-op outside a txn.
121
+ if tree then
122
+ tree:RecordRawWrite(store, pathKey)
123
+ end
124
+ store[pathKey] = value
125
+ if entry.SaveInfo then
126
+ entry.SaveInfo.Dirty = true
127
+ end
128
+ if value ~= nil then
129
+ watch(entry)
130
+ end
131
+ local fieldId = visibleFields[pathKey]
132
+ if fieldId and tree then
133
+ -- Session metadata shares normal replication and transaction rollback.
134
+ tree.Accessor.Child(Template.SESSION_ROOT).Child("Timed").Child(fieldId).Set(value, replicate)
135
+ end
136
+ end
137
+
138
+ local function fieldAccessorFromKey(entry: any, pathKey: string): (any, Template.SchemaNode?)
139
+ local segments = string.split(pathKey, "\31")
140
+ local accessor = entry.Tree.Accessor
141
+ for _, segment in segments do
142
+ accessor = accessor.Child(segment)
143
+ end
144
+ -- node.Default is only the field's default when Resolve fully consumed the path.
145
+ -- For a field a newer template removed, Resolve stops at a surviving ancestor whose
146
+ -- Default is that whole container, which would fabricate a phantom sub-table.
147
+ local node, dynStart = Template.Resolve(compiled, segments :: { string | number })
148
+ if dynStart <= #segments then
149
+ return accessor, nil
150
+ end
151
+ return accessor, node
152
+ end
153
+
154
+ -- Node.luau hooks for accessors of Scribe.Timed fields.
155
+ function self.HooksFor(entry: any)
156
+ return {
157
+ SetTimed = function(accessor: any, value: any, seconds: number, replicate: boolean?)
158
+ if type(seconds) ~= "number" or seconds ~= seconds or seconds <= 0 then
159
+ error("Scribe: SetTimed seconds must be a positive number", 3)
160
+ end
161
+ accessor.Set(value, replicate)
162
+ local pathKey = Node.PathKeyOf(accessor)
163
+ setTimed(entry, pathKey, Clock.Now() + clampSeconds(seconds), replicate)
164
+ end,
165
+ ExtendTimed = function(accessor: any, seconds: number, replicate: boolean?)
166
+ if type(seconds) ~= "number" or seconds ~= seconds or seconds <= 0 then
167
+ error("Scribe: ExtendTimed seconds must be a positive number", 3)
168
+ end
169
+ local pathKey = Node.PathKeyOf(accessor)
170
+ local store = timedStore(entry)
171
+ local now = Clock.Now()
172
+ local current = if store then store[pathKey] else nil
173
+ -- Stack onto a running timer; if expired, behave like SetTimed from
174
+ -- now, leaving the value itself untouched.
175
+ local base = if current and current > now then current else now
176
+ setTimed(entry, pathKey, base + clampSeconds(seconds), replicate)
177
+ end,
178
+ Active = function(accessor: any): (boolean, number?)
179
+ local pathKey = Node.PathKeyOf(accessor)
180
+ local store = timedStore(entry)
181
+ local expiry = if store then store[pathKey] else nil
182
+ local now = Clock.Now()
183
+ if expiry and now < expiry then
184
+ return true, expiry - now
185
+ end
186
+ return false, nil
187
+ end,
188
+ }
189
+ end
190
+
191
+ -- A once-guard: has this key been claimed, and is the claim still live? Separate from
192
+ -- OnCooldown, which re-arms on every use, because checking a claim must not re-arm it.
193
+ function self.IsClaimed(entry: any, key: string): boolean
194
+ local store = timedStore(entry)
195
+ if not store then
196
+ return false
197
+ end
198
+ local deadline = store[COOLDOWN_PREFIX .. key]
199
+ return type(deadline) == "number" and deadline > Clock.Now()
200
+ end
201
+
202
+ --- Drop the nearest-to-expiring claims under `prefix` until at most `cap - 1` remain,
203
+ --- so the caller's own claim lands inside the cap. Returns how many were dropped and
204
+ --- how many are live afterwards. Nothing else bounds the count: with a seven-day TTL
205
+ --- every keyed purchase a player makes in a week rides in every save and is walked by
206
+ --- the 1 Hz sweep. Nearest-to-expiring goes first, its retry window being closest to
207
+ --- over. Still an eviction, so the caller logs it: a retry under a dropped claim applies.
208
+ function self.PruneClaims(entry: any, prefix: string, cap: number): (number, number)
209
+ local store = timedStore(entry)
210
+ if not store then
211
+ return 0, 0
212
+ end
213
+ local full = COOLDOWN_PREFIX .. prefix
214
+ local live: { { Key: string, At: number } } = {}
215
+ for pathKey, expiry in store do
216
+ if type(expiry) == "number" and string.sub(pathKey, 1, #full) == full then
217
+ table.insert(live, { Key = pathKey, At = expiry })
218
+ end
219
+ end
220
+ -- Shrink to the current cap rather than only trimming by one, so a profile
221
+ -- carrying more than a cap lowered between deploys comes back under it.
222
+ local target = math.max(0, math.floor(cap) - 1)
223
+ if #live <= target then
224
+ return 0, #live
225
+ end
226
+ table.sort(live, function(a: { Key: string, At: number }, b: { Key: string, At: number })
227
+ -- Ties broken on the key so eviction is deterministic: two claims taken in
228
+ -- the same second are otherwise ordered by table layout.
229
+ if a.At == b.At then
230
+ return a.Key < b.Key
231
+ end
232
+ return a.At < b.At
233
+ end)
234
+ local dropped = #live - target
235
+ for i = 1, dropped do
236
+ -- Through setTimed, so an open transaction rolls the eviction back with the
237
+ -- claim it made room for; a rolled-back purchase must not still cost another
238
+ -- claim its protection.
239
+ setTimed(entry, live[i].Key, nil)
240
+ end
241
+ return dropped, target
242
+ end
243
+
244
+ -- Record that `key` happened, for `seconds`. Re-claiming a live claim does not push
245
+ -- its deadline out, so a retrying caller cannot keep one alive indefinitely.
246
+ function self.Claim(entry: any, key: string, seconds: number)
247
+ if not Util.isUtf8(key) then
248
+ error("Scribe: claim key contains invalid UTF-8 bytes (would corrupt the profile save)", 2)
249
+ end
250
+ local store = timedStore(entry)
251
+ if not store then
252
+ return
253
+ end
254
+ local pathKey = COOLDOWN_PREFIX .. key
255
+ local existing = store[pathKey]
256
+ local now = Clock.Now()
257
+ if type(existing) == "number" and existing > now then
258
+ return
259
+ end
260
+ -- clampSeconds for the finite ceiling: math.floor(inf) is inf, so a PurchaseClaimTTL
261
+ -- of math.huge writes an unserializable expiry that the profile's guards read as
262
+ -- unpersistable, refusing offline receipts forever.
263
+ setTimed(entry, pathKey, now + clampSeconds(seconds))
264
+ end
265
+ -- Keyed cooldowns: checks and, when off cooldown, arms it. Call it at the grant
266
+ -- moment only; PeekCooldown is the read-only check.
267
+ function self.OnCooldown(entry: any, key: string, seconds: number, options: any?): (boolean, number)
268
+ -- Zero or negative seconds means "no cooldown": clampSeconds floors to 1 and would
269
+ -- turn a computed 0 into a real one-second gate.
270
+ if type(seconds) ~= "number" or seconds <= 0 then
271
+ return false, 0
272
+ end
273
+ -- The key becomes a persisted table key in the raw _Scribe.Timed dict, bypassing
274
+ -- Node.validateWrite, so invalid UTF-8 would fail the whole profile save (error
275
+ -- 104). Rejected loudly here, along with Scribe's reserved claim namespace.
276
+ checkPublicKey(key, "cooldown")
277
+ local includeOffline = if options and options.IncludeOfflineTime ~= nil
278
+ then options.IncludeOfflineTime == true
279
+ else true
280
+ local pathKey = (if includeOffline then COOLDOWN_PREFIX else ONLINE_PREFIX) .. key
281
+ local otherKey = (if includeOffline then ONLINE_PREFIX else COOLDOWN_PREFIX) .. key
282
+ local store = timedStore(entry)
283
+ if not store then
284
+ return false, 0
285
+ end
286
+ local now = Clock.Now()
287
+ -- Both slots hold an absolute deadline in memory; only the copy the DataStore gets
288
+ -- carries the online one as remaining seconds. Check both, not just this call's
289
+ -- mode: a key holds one cooldown, so flipping the flag mid-cooldown still reports it.
290
+ for _, prefix in { COOLDOWN_PREFIX, ONLINE_PREFIX } do
291
+ local running = store[prefix .. key]
292
+ if running and now < running then
293
+ return true, running - now
294
+ end
295
+ end
296
+ -- Flipping the flag must not strand the old slot, which would hand the player a
297
+ -- second, independent cooldown of the other kind.
298
+ if store[otherKey] ~= nil then
299
+ setTimed(entry, otherKey, nil)
300
+ end
301
+ setTimed(entry, pathKey, now + clampSeconds(seconds))
302
+ return false, 0
303
+ end
304
+
305
+ -- Read-only cooldown check: never arms. Returns (onCooldown, remaining).
306
+ function self.PeekCooldown(entry: any, key: string): (boolean, number)
307
+ checkPublicKey(key, "cooldown")
308
+ local store = timedStore(entry)
309
+ if not store then
310
+ return false, 0
311
+ end
312
+ local now = Clock.Now()
313
+ for _, prefix in { COOLDOWN_PREFIX, ONLINE_PREFIX } do
314
+ local expiry = store[prefix .. key]
315
+ if expiry and now < expiry then
316
+ return true, expiry - now
317
+ end
318
+ end
319
+ return false, 0
320
+ end
321
+
322
+ -- Clear a cooldown (support/testing resets).
323
+ function self.ClearCooldown(entry: any, key: string)
324
+ -- The reserved check matters most here; see RESERVED_KEY_PREFIX.
325
+ checkPublicKey(key, "cooldown")
326
+ if timedStore(entry) then
327
+ setTimed(entry, COOLDOWN_PREFIX .. key, nil)
328
+ setTimed(entry, ONLINE_PREFIX .. key, nil)
329
+ end
330
+ end
331
+
332
+ -- Clear lapsed entries. Timed fields reset to their template default, which fires
333
+ -- Changed and replicates, so a client Observe covers expiry with no separate event.
334
+ -- `notify` gates OnCooldownEnded; the load sweep passes false, since those lapsed while
335
+ -- the player was away and no listener is attached yet.
336
+ local function sweepEntry(entry: any, notify: boolean?)
337
+ local store = timedStore(entry)
338
+ if not store or not entry.Tree or entry.Tree.Dead then
339
+ return
340
+ end
341
+ local now = Clock.Now()
342
+ local lapsed: { { Key: string, Expiry: number } }? = nil
343
+ for pathKey, expiry in store do
344
+ if type(expiry) == "number" and now >= expiry then
345
+ lapsed = lapsed or {}
346
+ table.insert(lapsed :: { { Key: string, Expiry: number } }, { Key = pathKey, Expiry = expiry })
347
+ end
348
+ end
349
+ if not lapsed then
350
+ return
351
+ end
352
+ for _, item in lapsed :: { { Key: string, Expiry: number } } do
353
+ local pathKey = item.Key
354
+ -- Re-check before processing: a Changed listener fired while resetting an
355
+ -- earlier lapsed field may have re-armed or cleared this one, and the stale
356
+ -- precollected entry would wipe that fresh expiry.
357
+ if store[pathKey] ~= item.Expiry then
358
+ continue
359
+ end
360
+ setTimed(entry, pathKey, nil)
361
+ local isOnline = string.sub(pathKey, 1, #ONLINE_PREFIX) == ONLINE_PREFIX
362
+ if not isOnline and string.sub(pathKey, 1, #COOLDOWN_PREFIX) ~= COOLDOWN_PREFIX then
363
+ local ok, err = pcall(function()
364
+ local accessor, node = fieldAccessorFromKey(entry, pathKey)
365
+ accessor.Set(if node then Util.deepClone(node.Default) else nil)
366
+ end)
367
+ if not ok then
368
+ Log.Warn("Integrity", "TIMED_SWEEP_FAIL", tostring(err), { Player = entry.Player })
369
+ end
370
+ elseif notify then
371
+ -- A cooldown holds no value, so clearing it fires no Changed. This
372
+ -- signal is the only expiry notification cooldowns get.
373
+ local prefixLength = if isOnline then #ONLINE_PREFIX else #COOLDOWN_PREFIX
374
+ local bareKey = string.sub(pathKey, prefixLength + 1)
375
+ -- Game cooldowns only: Scribe's idempotency claims share this dict, and
376
+ -- announcing one puts a key the game never set through its handler.
377
+ if not isReserved(bareKey) then
378
+ ctx.Signals.OnCooldownEnded:Fire(entry.Player, bareKey)
379
+ end
380
+ end
381
+ end
382
+ end
383
+
384
+ local function toDeadline(entry: any, remainingByKey: { [string]: number })
385
+ local store = timedStore(entry)
386
+ if not store then
387
+ return
388
+ end
389
+ local now = Clock.Now()
390
+ for pathKey, remaining in remainingByKey do
391
+ store[pathKey] = now + remaining
392
+ end
393
+ end
394
+
395
+ -- Online-only cooldowns are deadlines in memory and remaining seconds on disk, so every
396
+ -- read works as it does for a wall-clock one. Converting on every save rather than only
397
+ -- on leave makes a crash safe: whatever the DataStore caught is already a remaining, so
398
+ -- the worst case is a cooldown that resumes slightly long. The conversion goes into a
399
+ -- copy the profile carries for the save, while the live deadlines move to
400
+ -- entry.TimedLive; converting the shared table in place would make a live cooldown read
401
+ -- as a 1970 deadline for the whole round trip, and the sweep would delete it.
402
+ function self.BeforeSave(entry: any): { [string]: number }?
403
+ local store = timedStore(entry)
404
+ if not store then
405
+ return nil
406
+ end
407
+ local now = Clock.Now()
408
+ local persisted: { [string]: number } = {}
409
+ for pathKey, value in store do
410
+ if string.sub(pathKey, 1, #ONLINE_PREFIX) == ONLINE_PREFIX and type(value) == "number" then
411
+ -- Whole seconds only: a fractional value roughly quadruples the JSON for
412
+ -- this entry, which feeds the profile-size and wipe-guard checks.
413
+ persisted[pathKey] = math.max(0, math.floor(value - now))
414
+ else
415
+ persisted[pathKey] = value
416
+ end
417
+ end
418
+ entry.TimedLive = store
419
+ -- ProfileStore task.spawns every save and holds no per-profile lock, so an autosave
420
+ -- tick can start while a Data.Flush is in flight; count the open windows.
421
+ entry.TimedSaves = (entry.TimedSaves or 0) + 1
422
+ local reserved = entry.LiveData and entry.LiveData[Template.RESERVED_ROOT]
423
+ if type(reserved) == "table" then
424
+ reserved.Timed = persisted
425
+ end
426
+ return store
427
+ end
428
+
429
+ function self.AfterSave(entry: any, held: { [string]: number }?)
430
+ if held == nil then
431
+ return
432
+ end
433
+ -- Only the last save out closes the window. Restoring while another is still in
434
+ -- flight would point the profile back at the live deadlines, and that save would
435
+ -- serialize them as remaining seconds: a rejoin then turns 1.78e9 "remaining" into
436
+ -- a deadline decades away, re-minted by every later save.
437
+ --
438
+ -- A failed save never fires OnAfterSave, so the window stays open for the session.
439
+ -- That is inert, and ProfileStore cannot say which call failed anyway.
440
+ local remaining = (entry.TimedSaves or 1) - 1
441
+ entry.TimedSaves = math.max(0, remaining)
442
+ if remaining > 0 then
443
+ return
444
+ end
445
+ entry.TimedLive = nil
446
+ local reserved = entry.LiveData and entry.LiveData[Template.RESERVED_ROOT]
447
+ if type(reserved) == "table" then
448
+ reserved.Timed = held
449
+ end
450
+ end
451
+
452
+ -- Clear one field's expiry in the live store. DebugHook's ClearTimed needs the flat
453
+ -- dict directly, since a nested field's pathKey embeds \31 and the accessor tree
454
+ -- rejects it; routing it here keeps it off the throwaway copy a save is holding.
455
+ function self.ClearField(entry: any, pathKey: string)
456
+ setTimed(entry, pathKey, nil)
457
+ end
458
+
459
+ -- On load the stored value is a remaining, so turn it back into a deadline before
460
+ -- anything reads it.
461
+ local function restoreDeadlines(entry: any)
462
+ local store = timedStore(entry)
463
+ if not store then
464
+ return
465
+ end
466
+ local remaining: { [string]: number } = {}
467
+ for pathKey, value in store do
468
+ if string.sub(pathKey, 1, #ONLINE_PREFIX) == ONLINE_PREFIX and type(value) == "number" then
469
+ remaining[pathKey] = value
470
+ end
471
+ end
472
+ toDeadline(entry, remaining)
473
+ end
474
+
475
+ function self.OnLoad(entry: any)
476
+ restoreDeadlines(entry)
477
+ sweepEntry(entry)
478
+ local store = timedStore(entry)
479
+ if next(visibleFields) ~= nil then
480
+ local visible: { [string]: number } = {}
481
+ for pathKey, expiry in store or {} do
482
+ local fieldId = visibleFields[pathKey]
483
+ if fieldId and type(expiry) == "number" and expiry > -math.huge and expiry < math.huge then
484
+ visible[fieldId] = expiry
485
+ end
486
+ end
487
+ entry.Tree.Accessor.Child(Template.SESSION_ROOT).Child("Timed").Set(visible)
488
+ end
489
+ if store ~= nil and next(store) ~= nil then
490
+ watch(entry)
491
+ end
492
+ end
493
+
494
+ -- One pass of the periodic sweep, including the OnCooldownEnded signal. Named so
495
+ -- the 1 Hz loop below and the tests drive the same code path.
496
+ function self.Sweep(entry: any)
497
+ sweepEntry(entry, true)
498
+ end
499
+
500
+ function self.OnUnload(entry: any)
501
+ active[entry] = nil
502
+ end
503
+
504
+ --- One pass over the entries holding a timer; an entry with none left is forgotten.
505
+ function self.SweepActive()
506
+ local batch = active
507
+ active = {}
508
+ for entry in batch do
509
+ if entry.TornDown then
510
+ continue
511
+ end
512
+ if entry.State == "Ready" then
513
+ self.Sweep(entry)
514
+ end
515
+ if stopped or entry.TornDown then
516
+ continue
517
+ end
518
+ local store = timedStore(entry)
519
+ if store ~= nil and next(store) ~= nil then
520
+ active[entry] = true
521
+ end
522
+ end
523
+ end
524
+
525
+ function self.ActiveCount(): number
526
+ local count = 0
527
+ for _ in active do
528
+ count += 1
529
+ end
530
+ return count
531
+ end
532
+
533
+ function self.Parked(): boolean
534
+ return sweepParked
535
+ end
536
+
537
+ -- Called by Server.build once the full ctx is assembled, so the sweep never runs
538
+ -- against a half-constructed context.
539
+ function self.Start()
540
+ sweepThread = Sched.Spawn(function()
541
+ -- Its own long-lived thread, so what it allocates is attributable. Scribe's own
542
+ -- background work only: an accessor write runs on the game's calling thread and
543
+ -- stays under the game's category.
544
+ Profile.MemoryCategory("Scribe")
545
+ while not stopped do
546
+ if next(active) == nil then
547
+ sweepParked = true
548
+ coroutine.yield()
549
+ sweepParked = false
550
+ if stopped then
551
+ break
552
+ end
553
+ end
554
+ -- Jittered so every server in the place does not sweep on one tick.
555
+ Clock.Wait(Rng.Jitter(SWEEP_INTERVAL))
556
+ self.SweepActive()
557
+ end
558
+ end)
559
+ end
560
+
561
+ -- Release the sweep so the bundle can be discarded. The flag alone leaves the thread
562
+ -- parked in task.wait for up to SWEEP_INTERVAL, so many bundles in one process (a
563
+ -- multi-server simulation, or the test harnesses) would pile up.
564
+ function self.Stop()
565
+ if stopped then
566
+ return
567
+ end
568
+ stopped = true
569
+ if sweepThread ~= nil then
570
+ pcall(task.cancel, sweepThread)
571
+ sweepThread = nil
572
+ end
573
+ table.clear(active)
574
+ end
575
+
576
+ return self
577
+ end
578
+
579
+ return Timed