@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,672 @@
1
+ --!strict
2
+ -- Server assembly: builds the shared context, wires the layers together, and
3
+ -- exposes the public server `Data` API.
4
+
5
+ local Players = game:GetService("Players")
6
+ local RunService = game:GetService("RunService")
7
+
8
+ local Internal = script.Parent.Internal
9
+ local Types = require(script.Parent.Types)
10
+ local Template = require(Internal.Template)
11
+ local TransportModule = require(Internal.Transport)
12
+ local Version = require(Internal.Version)
13
+ local Node = require(Internal.Node)
14
+ local Log = require(Internal.Log)
15
+ local Metrics = require(Internal.Metrics)
16
+ local Health = require(Internal.Health)
17
+ local Signal = require(Internal.Signal)
18
+ local Failure = require(Internal.Failure)
19
+ local Addons = require(Internal.Addons)
20
+
21
+ local Persistence = require(script.Persistence)
22
+ local Replication = require(script.Replication)
23
+ local Commands = require(script.Commands)
24
+ local Timed = require(script.Timed)
25
+ local Analytics = require(script.Analytics)
26
+ local Leaderboards = require(script.Leaderboards)
27
+ local Exchanges = require(script.Exchanges)
28
+ local ServerStore = require(script.ServerStore)
29
+ local Monetization = require(script.Monetization)
30
+
31
+ local Server = {}
32
+
33
+ -- Builds the server context and public Data API without the engine-level wiring
34
+ -- (PlayerAdded/Removing, BindToClose). The test harness calls this directly to drive
35
+ -- the player lifecycle by hand against stub transports. Returns (Data, ctx).
36
+ function Server.build(options: any, compiled: Template.Compiled): (any, any)
37
+ local ctx = {} :: any
38
+ ctx.Options = options
39
+ Addons.SetProfileKeyPrefix(
40
+ if type(options.ProfileKeyPrefix) == "string" then options.ProfileKeyPrefix else "PLAYER_"
41
+ )
42
+ ctx.Compiled = compiled
43
+ -- Studio by default. Overridable because patching RunService is illegal on a real
44
+ -- service Instance, so a spec needing DevMode could not otherwise run in Studio.
45
+ ctx.DevMode = if options.DevMode ~= nil then options.DevMode == true else RunService:IsStudio()
46
+ -- Coarse per-player ceiling on raw inbound frames, spent before a frame is read at
47
+ -- all. Resolved here because Persistence seeds each entry's bucket and Replication
48
+ -- enforces it, and a default derived in two places drifts.
49
+ --
50
+ -- Well above CommandRateLimit on purpose: this tier drops silently, and a silently
51
+ -- dropped Command strands the client until its RequestTimeout, so a merely chatty
52
+ -- client should hit the command token bucket instead. The floor keeps a tiny
53
+ -- CommandRateLimit from throttling handshake and status traffic.
54
+ ctx.InboundFrameRate = options.MaxInboundFrameRate or math.max(60, (options.CommandRateLimit or 20) * 4)
55
+ ctx.Signals = {
56
+ OnSave = Signal.new(), -- { Player, Ok, Duration, At }
57
+ SessionEnded = Signal.new(), -- (player, reason)
58
+ OnAnomaly = Signal.new(), -- { Player, Path, Value, Reason }
59
+ OnGiftReceived = Signal.new(), -- (player, { FromUserId, Product, GiftId })
60
+ OnGiftCredit = Signal.new(), -- (player, productName)
61
+ OnMessage = Signal.new(), -- (player, message)
62
+ OnOwnershipChanged = Signal.new(), -- (player, key, owned)
63
+ OnCooldownEnded = Signal.new(), -- (player, key)
64
+ OnLeaderboard = Signal.new(), -- (boardName, entries)
65
+ }
66
+
67
+ if options.LogLevel then
68
+ Log.SetLevel(options.LogLevel)
69
+ end
70
+ if options.LogRingLevel then
71
+ Log.SetRingLevel(options.LogRingLevel)
72
+ end
73
+ if options.LogRingSize ~= nil then
74
+ Log.SetRingSize(options.LogRingSize)
75
+ end
76
+ Health.Configure(options.StatusThresholds)
77
+
78
+ ctx.Transport = TransportModule.Resolve(options.Transport, options.TransportChannel)
79
+ -- Did we claim the built-in channel? Only the claiming scope may release it, or a
80
+ -- bundle on a custom transport would take Default away from whoever holds it. Read
81
+ -- the option, not ctx.Transport.Name: a custom adapter may call itself "Default".
82
+ local ownsDefaultChannel = options.Transport == nil or options.Transport == "Default"
83
+
84
+ -- Build order matters only for construction-time dependencies; runtime calls flow
85
+ -- through ctx. Pcalled, and the unwind releases what was already built: Replication.new
86
+ -- installs process-global listeners and the constructors after it throw on bad config,
87
+ -- and a failed build leaves no Data object for anyone to call Stop() on. Same list and
88
+ -- reverse order as Data.Stop, each Stop pcalled so one failing teardown cannot replace
89
+ -- the config error the developer is here to read.
90
+ local constructed, constructErr = pcall(function()
91
+ ctx.Analytics = Analytics.new(ctx)
92
+ ctx.Timed = Timed.new(ctx)
93
+ ctx.Persistence = Persistence.new(ctx)
94
+ ctx.Replication = Replication.new(ctx)
95
+ -- After Replication: its OnOp pushes onto Replication's store queue.
96
+ ctx.ServerStore = ServerStore.new(ctx)
97
+ ctx.Commands = Commands.new(ctx)
98
+ ctx.Leaderboards = Leaderboards.new(ctx)
99
+ ctx.Monetization = Monetization.new(ctx)
100
+ -- After Persistence: it reads the resolved mode to decide whether the verdict
101
+ -- key is real or mocked.
102
+ ctx.Exchanges = Exchanges.new(ctx)
103
+ end)
104
+ if not constructed then
105
+ for _, subsystem in
106
+ {
107
+ ctx.Exchanges,
108
+ ctx.Leaderboards,
109
+ ctx.Timed,
110
+ ctx.Monetization,
111
+ ctx.ServerStore,
112
+ ctx.Replication,
113
+ ctx.Persistence,
114
+ }
115
+ do
116
+ if subsystem ~= nil and type(subsystem.Stop) == "function" then
117
+ pcall(subsystem.Stop)
118
+ end
119
+ end
120
+ -- The same release Stop performs: the channel claim and the inbound listener are
121
+ -- both taken above this pcall, so leaving them held turns a config error into
122
+ -- "channel already in use" on the corrected retry. After the subsystems, so
123
+ -- nothing is still sending when the listener goes.
124
+ if ownsDefaultChannel then
125
+ pcall(TransportModule.ReleaseChannel, options.TransportChannel)
126
+ end
127
+ -- Level 0: the message carries its own origin, and re-pointing it at this
128
+ -- line would blame the library for the caller's config.
129
+ error(constructErr, 0)
130
+ end
131
+
132
+ -- Background loops start only after every subsystem exists: a constructor throwing
133
+ -- partway must never leave an orphaned loop running against a half-built ctx.
134
+ ctx.Monetization.Start()
135
+ ctx.Timed.Start()
136
+ ctx.Leaderboards.Start()
137
+ ctx.Exchanges.Start()
138
+
139
+ -- Public API --------------------------------------------------------------------
140
+
141
+ local Data = {} :: any
142
+
143
+ -- Luau does not flag an unknown key in an inline table literal passed to an optional
144
+ -- table parameter, only in one bound to a local first, so a typo like
145
+ -- `{ Forcce = true }` type-checks clean and silently does nothing. This is the only
146
+ -- layer that catches it.
147
+ local function checkOptions(given: any, what: string, allowed: { [string]: true })
148
+ if given == nil then
149
+ return
150
+ end
151
+ if type(given) ~= "table" then
152
+ error(`Scribe: {what} options must be a table`, 3)
153
+ end
154
+ local names = {}
155
+ for name in allowed do
156
+ table.insert(names, name)
157
+ end
158
+ table.sort(names)
159
+ for name in given do
160
+ if not allowed[name] then
161
+ error(`Scribe: {what}: unknown option "{tostring(name)}" (expected {table.concat(names, ", ")})`, 3)
162
+ end
163
+ end
164
+ end
165
+
166
+ local function entryOrError(player: Player, what: string): any
167
+ local entry = ctx.Persistence.EntryFor(player)
168
+ if not entry then
169
+ error(`Scribe: {what}: no data session for {player.Name}`, 3)
170
+ end
171
+ if entry.State ~= "Ready" then
172
+ error(`Scribe: {what}: data for {player.Name} is {entry.State}: use Data.WaitForData(player)`, 3)
173
+ end
174
+ return entry
175
+ end
176
+
177
+ -- Waits for a Ready profile, returning nil and a reason on failure.
178
+ function Data.WaitForData(player: Player, timeout: number?)
179
+ return ctx.Persistence.WaitForData(player, timeout)
180
+ end
181
+ -- Reads session state and loading phase without yielding.
182
+ function Data.GetState(player: Player)
183
+ return ctx.Persistence.GetState(player)
184
+ end
185
+ -- Returns the player's accessor tree; errors unless the profile is Ready.
186
+ function Data.Get(player: Player)
187
+ return entryOrError(player, "Data.Get").Tree.Accessor
188
+ end
189
+
190
+ -- Groups writes into one replication flush and container notification pass.
191
+ function Data.Batch(player: Player, fn: () -> ())
192
+ local entry = entryOrError(player, "Data.Batch")
193
+ entry.Tree:RunBatch(fn)
194
+ end
195
+ -- Rolls back all writes if the callback throws or yields.
196
+ function Data.Transaction(player: Player, fn: () -> ()): (boolean, string?)
197
+ local entry = entryOrError(player, "Data.Transaction")
198
+ return entry.Tree:RunTransaction(fn)
199
+ end
200
+
201
+ -- Waits for pending changes to save; requires a Ready profile.
202
+ function Data.Flush(player: Player, opts: { Force: boolean?, Timeout: number? }?)
203
+ checkOptions(opts, "Data.Flush", { Force = true, Timeout = true })
204
+ return ctx.Persistence.Flush(player, opts)
205
+ end
206
+ -- Reads the player's last save result and pending-change state.
207
+ function Data.GetSaveInfo(player: Player)
208
+ return ctx.Persistence.GetSaveInfo(player)
209
+ end
210
+ -- Clones local Ready data or reads the last persisted snapshot.
211
+ function Data.GetOffline(userId: number)
212
+ return ctx.Persistence.GetOffline(userId)
213
+ end
214
+ -- Updates an offline profile, with optional template validation.
215
+ function Data.UpdateOffline(userId: number, fn: (data: any) -> (), opts: { Validate: boolean? }?)
216
+ checkOptions(opts, "Data.UpdateOffline", { Validate = true })
217
+ return ctx.Persistence.UpdateOffline(userId, fn, opts)
218
+ end
219
+ -- Lists saved profile versions for support tools.
220
+ function Data.ListVersions(userId: number, limit: number?)
221
+ return ctx.Persistence.ListVersions(userId, limit)
222
+ end
223
+ -- Reads a specific historical profile snapshot.
224
+ function Data.GetVersion(userId: number, versionId: string)
225
+ return ctx.Persistence.GetVersion(userId, versionId)
226
+ end
227
+ -- Restores an existing offline profile while preserving reserved data by default.
228
+ function Data.RestoreVersion(userId: number, versionId: string, opts: { RollBackReserved: boolean? }?)
229
+ checkOptions(opts, "Data.RestoreVersion", { RollBackReserved = true })
230
+ return ctx.Persistence.RestoreVersion(userId, versionId, opts)
231
+ end
232
+ -- Deletes the profile and leaderboard records while blocking this user's joins.
233
+ function Data.Erase(userId: number)
234
+ return ctx.Persistence.Erase(userId)
235
+ end
236
+ -- Serializes a profile to JSON, or returns nil when absent.
237
+ function Data.Export(userId: number)
238
+ return ctx.Persistence.Export(userId)
239
+ end
240
+
241
+ -- Registers a validated, rate-limited command for Ready players.
242
+ function Data.Command(name: string, specOrHandler: any, handler: any?)
243
+ ctx.Commands.Register(name, specOrHandler, handler)
244
+ end
245
+
246
+ Data.Exchange = {
247
+ -- Trades both baskets between players loaded on this server.
248
+ Attempt = function(playerA: Player, basketA: { any }, playerB: Player, basketB: { any })
249
+ return ctx.Exchanges.Attempt(playerA, basketA, playerB, basketB)
250
+ end,
251
+ -- Lists the player's unfinished exchanges and held value.
252
+ Open = function(player: Player)
253
+ return ctx.Exchanges.Open(player)
254
+ end,
255
+ -- Drops an unstaked claim only when no verdict exists.
256
+ Discard = function(exchangeId: string)
257
+ return ctx.Exchanges.Discard(exchangeId)
258
+ end,
259
+ -- Applies an explicit recovery verdict to a stalled exchange.
260
+ Settle = function(exchangeId: string, verdict: string)
261
+ return ctx.Exchanges.Settle(exchangeId, verdict)
262
+ end,
263
+ -- Moves a parked delivery to another key in the same container.
264
+ Redirect = function(exchangeId: string, userId: number, newKey: string)
265
+ return ctx.Exchanges.Redirect(exchangeId, userId, newKey)
266
+ end,
267
+ }
268
+
269
+ -- Reads cached board results without a live DataStore request.
270
+ function Data.GetLeaderboard(name: string, limit: number?, offset: number?)
271
+ return ctx.Leaderboards.GetLeaderboard(name, limit, offset)
272
+ end
273
+ -- Reads the player's rank from the leaderboard cache.
274
+ function Data.GetMyRank(player: Player, name: string)
275
+ return ctx.Leaderboards.GetMyRank(player, name)
276
+ end
277
+ -- Reads the next scheduled refresh delay; nil until scheduled.
278
+ function Data.GetLeaderboardRefreshIn(name: string): number?
279
+ return ctx.Leaderboards.GetRefreshIn(name)
280
+ end
281
+ -- Reads board health without a DataStore request.
282
+ function Data.GetLeaderboardStatus(name: string): Types.LeaderboardStatusInfo?
283
+ return ctx.Leaderboards.GetStatus(name)
284
+ end
285
+ -- Reads the time remaining in a periodic board's current period.
286
+ function Data.GetLeaderboardResetIn(name: string): number?
287
+ return ctx.Leaderboards.GetResetIn(name)
288
+ end
289
+
290
+ -- Validates a named product or pass before opening its purchase prompt.
291
+ function Data.PromptPurchase(player: Player, name: string)
292
+ return ctx.Monetization.PromptPurchase(player, name)
293
+ end
294
+ -- Reads the ownership and policy state used by purchase prompts.
295
+ function Data.GetProductState(player: Player, name: string): string
296
+ return ctx.Monetization.GetProductState(player, name)
297
+ end
298
+ -- Uses a gift credit or saves the recipient before opening a paid prompt.
299
+ function Data.PromptGift(buyer: Player, productName: string, recipientUserId: number)
300
+ return ctx.Monetization.PromptGift(buyer, productName, recipientUserId)
301
+ end
302
+ -- Reads the player's unassigned gift credits.
303
+ function Data.GetGiftCredits(player: Player)
304
+ return ctx.Monetization.GetGiftCredits(player)
305
+ end
306
+ -- Processes a Scribe receipt with persisted deduplication.
307
+ function Data.HandleReceipt(receiptInfo: any)
308
+ return ctx.Monetization.HandleReceipt(receiptInfo)
309
+ end
310
+
311
+ -- Processes known products and returns nil for another receipt handler.
312
+ function Data.TryHandleReceipt(receiptInfo: any)
313
+ return ctx.Monetization.TryHandleReceipt(receiptInfo)
314
+ end
315
+ -- Reads cached pass, perk, or Roblox Plus ownership without yielding.
316
+ function Data.Owns(player: Player, key: string)
317
+ return ctx.Monetization.Owns(player, key)
318
+ end
319
+ -- Verifies uncached pass ownership with Roblox before returning.
320
+ function Data.OwnsAsync(player: Player, key: string, timeout: number?)
321
+ return ctx.Monetization.OwnsAsync(player, key, timeout)
322
+ end
323
+ -- Reports current ownership and later changes; returns a disconnect.
324
+ function Data.ObserveOwned(player: Player, key: string, callback: (owned: boolean) -> ())
325
+ return ctx.Monetization.ObserveOwned(player, key, callback)
326
+ end
327
+ -- Grants a perk through Scribe's ownership state.
328
+ function Data.GrantPerk(player: Player, key: string)
329
+ return ctx.Monetization.GrantPerk(player, key)
330
+ end
331
+ -- Removes a granted perk from Scribe's ownership state.
332
+ function Data.RevokePerk(player: Player, key: string)
333
+ return ctx.Monetization.RevokePerk(player, key)
334
+ end
335
+ -- Debits, grants, and logs atomically; failures roll back the purchase.
336
+ function Data.Purchase(player: Player, spec: any)
337
+ return ctx.Monetization.Purchase(player, spec)
338
+ end
339
+ -- Adds a game-defined entry to the in-game purchase log.
340
+ function Data.RecordPurchase(player: Player, entry: any)
341
+ return ctx.Monetization.RecordPurchase(player, entry)
342
+ end
343
+ -- Reads filtered purchase history, newest first.
344
+ function Data.GetPurchases(player: Player, filter: any?)
345
+ checkOptions(filter, "Data.GetPurchases", {
346
+ Kind = true,
347
+ Category = true,
348
+ ItemId = true,
349
+ Since = true,
350
+ Limit = true,
351
+ })
352
+ return ctx.Monetization.GetPurchases(player, filter)
353
+ end
354
+
355
+ -- Checks the cooldown and arms it only when inactive.
356
+ function Data.OnCooldown(
357
+ player: Player,
358
+ key: string,
359
+ seconds: number,
360
+ opts: { IncludeOfflineTime: boolean? }?
361
+ ): (boolean, number)
362
+ local entry = entryOrError(player, "Data.OnCooldown")
363
+ checkOptions(opts, "Data.OnCooldown", { IncludeOfflineTime = true })
364
+ return ctx.Timed.OnCooldown(entry, key, seconds, opts)
365
+ end
366
+
367
+ -- Reads cooldown state without starting or extending it.
368
+ function Data.PeekCooldown(player: Player, key: string): (boolean, number)
369
+ local entry = entryOrError(player, "Data.PeekCooldown")
370
+ return ctx.Timed.PeekCooldown(entry, key)
371
+ end
372
+
373
+ -- Clears a stored cooldown.
374
+ function Data.ClearCooldown(player: Player, key: string)
375
+ local entry = entryOrError(player, "Data.ClearCooldown")
376
+ ctx.Timed.ClearCooldown(entry, key)
377
+ end
378
+
379
+ -- Fires after each save attempt, including failures.
380
+ Data.OnSave = ctx.Signals.OnSave
381
+ -- Fires when a player's session ends.
382
+ Data.SessionEnded = ctx.Signals.SessionEnded
383
+ -- Fires when data validation or integrity checks detect an anomaly.
384
+ Data.OnAnomaly = ctx.Signals.OnAnomaly
385
+ -- Fires when effective ownership changes after load.
386
+ Data.OnOwnershipChanged = ctx.Signals.OnOwnershipChanged
387
+ -- Fires when cached board contents change.
388
+ Data.OnLeaderboard = ctx.Signals.OnLeaderboard
389
+ -- Fires when a cooldown expires during an active session.
390
+ Data.OnCooldownEnded = ctx.Signals.OnCooldownEnded
391
+ -- Fires when a player receives a gift.
392
+ Data.OnGiftReceived = ctx.Signals.OnGiftReceived
393
+ -- Fires when a player receives an unassigned gift credit.
394
+ Data.OnGiftCredit = ctx.Signals.OnGiftCredit
395
+ -- Delivers durable messages; handlers must be idempotent.
396
+ Data.OnMessage = ctx.Signals.OnMessage
397
+
398
+ -- Queues a durable message; receiving handlers must tolerate repeats.
399
+ function Data.SendMessage(userId: number, message: any): boolean
400
+ if ctx.Persistence.Mode == "NoSave" then
401
+ ctx.Persistence.RefuseNoSave("SendMessage")
402
+ return false
403
+ end
404
+ -- `provablyClean` is MessageAsync's third return: true only where no attempt in
405
+ -- its own retry loop could have written. Read for the log line alone; the boolean
406
+ -- this function returns is unchanged.
407
+ local ok, delivered, reason, provablyClean = pcall(function()
408
+ return ctx.Persistence.Store:MessageAsync(ctx.Persistence.KeyFor(userId), {
409
+ ScribeMessage = true,
410
+ Data = message,
411
+ })
412
+ end)
413
+ if ok and delivered == true then
414
+ Health.ReportSuccess("SendMessage")
415
+ return true
416
+ end
417
+ if ok and reason == "QueueFull" then
418
+ -- Deliberately not Failure.Report: that calls Health.ReportFailure, and a full
419
+ -- inbox is one player's profile rather than a DataStore fault, so a single
420
+ -- jammed queue would degrade the whole server to Outage and refuse every Robux
421
+ -- grant. An earlier attempt of the same call may also have committed and lost
422
+ -- only its answer, so this can be reported for a message already in the inbox.
423
+ Metrics.Add("MessageQueueFull")
424
+ if provablyClean ~= true then
425
+ Metrics.Add("MessageQueueFullAmbiguous")
426
+ end
427
+ Log.Warn(
428
+ "Persistence",
429
+ "MESSAGE_QUEUE_FULL",
430
+ if provablyClean == true
431
+ then "the recipient's message queue is at its cap and no attempt in this call reached "
432
+ .. "storage; nothing was written"
433
+ else "the recipient's message queue is at its cap, but an earlier attempt in the same "
434
+ .. "call may already have queued this message; it may yet be delivered",
435
+ { UserId = userId, ProvablyClean = provablyClean == true }
436
+ )
437
+ return false
438
+ end
439
+ -- Keyed by recipient, so a shutdown that fails to deliver for one player counts as
440
+ -- one problem instead of one per attempt. Past this point the send threw,
441
+ -- MessageAsync gave up retrying, or it refused at its IsClosing door without
442
+ -- attempting anything; `provablyClean` separates them. The return is `false` either
443
+ -- way, because at-least-once is this channel's contract.
444
+ Failure.Report({
445
+ Subsystem = "SendMessage",
446
+ Key = tostring(userId),
447
+ Error = if ok then nil else delivered,
448
+ Category = "Persistence",
449
+ Code = "MESSAGE_SEND_FAIL",
450
+ Message = if ok and provablyClean == true
451
+ then "MessageAsync failed; nothing reached storage, so the message was not delivered"
452
+ else "MessageAsync failed; the message may or may not have been delivered, so treat it as retryable",
453
+ Context = {
454
+ UserId = userId,
455
+ Threw = not ok,
456
+ ProvablyClean = ok and provablyClean == true,
457
+ Error = if ok then nil else tostring(delivered),
458
+ },
459
+ })
460
+ return false
461
+ end
462
+
463
+ -- Exposes the underlying store, bypassing Scribe's data guarantees.
464
+ Data.ProfileStore = ctx.Persistence.Store
465
+
466
+ -- Dev-mode misuse guard: a template key shadowed by an accessor method, at any depth,
467
+ -- needs explicit Child(name) lookup. The root-level half runs at the very
468
+ -- end of build; see the comment on it for why.
469
+ if ctx.DevMode then
470
+ local function warnCollision(node: any)
471
+ local name = node.Name
472
+ if
473
+ name
474
+ and Node.METHOD_NAMES[name]
475
+ and node.Path[1] ~= Template.RESERVED_ROOT
476
+ and node.Path[1] ~= Template.SESSION_ROOT
477
+ then
478
+ Log.Warn(
479
+ "Lifecycle",
480
+ "API_NAME_COLLISION",
481
+ `template field "{name}" collides with an accessor method; use Child("{name}") to reach it`,
482
+ { Path = table.concat(node.Path :: { any }, ".") }
483
+ )
484
+ end
485
+ end
486
+ -- ById covers static fields; element subtrees are id-less and hang off
487
+ -- AnyChild, so they have to be walked explicitly.
488
+ local function walkElements(node: any)
489
+ local anyChild = node.AnyChild
490
+ if anyChild and anyChild.IsElement then
491
+ local function walkSubtree(n: any)
492
+ warnCollision(n)
493
+ if n.Children then
494
+ for _, child in n.Children do
495
+ walkSubtree(child)
496
+ end
497
+ end
498
+ if n.AnyChild and n.AnyChild.IsElement then
499
+ walkSubtree(n.AnyChild)
500
+ end
501
+ end
502
+ walkSubtree(anyChild)
503
+ end
504
+ if node.Children then
505
+ for _, child in node.Children do
506
+ walkElements(child)
507
+ end
508
+ end
509
+ end
510
+ for _, node in compiled.ById do
511
+ warnCollision(node)
512
+ end
513
+ walkElements(compiled.Root)
514
+ end
515
+
516
+ -- Data[player] -> typed accessor tree.
517
+ setmetatable(Data :: any, {
518
+ __index = function(_, key: unknown)
519
+ if typeof(key) == "Instance" and key:IsA("Player") then
520
+ return entryOrError(key, "Data[player]").Tree.Accessor
521
+ end
522
+ return nil
523
+ end,
524
+ })
525
+
526
+ -- Exposes the same API without template-aware types.
527
+ Data.Raw = Data
528
+
529
+ Metrics.Set("SchemaNodes", compiled.NodeCount)
530
+ Log.Info("Lifecycle", "SERVER_STARTED", "Scribe server initialized", {
531
+ Fields = compiled.NodeCount,
532
+ Transport = ctx.Transport.Name,
533
+ })
534
+
535
+ -- Hoisted above the doc block below: docgen resolves a @within block from the
536
+ -- next line of code, so a declaration between the two orphans the member.
537
+ local stopped = false
538
+
539
+ -- Stops this bundle's workers and releases its listeners.
540
+ function Data.Stop()
541
+ if stopped then
542
+ return
543
+ end
544
+ stopped = true
545
+ -- Reverse of the Start order: stop producing work before releasing what consumes it.
546
+ for _, subsystem in
547
+ {
548
+ ctx.Exchanges,
549
+ ctx.Leaderboards,
550
+ ctx.Timed,
551
+ ctx.Monetization,
552
+ ctx.ServerStore,
553
+ ctx.Replication,
554
+ ctx.Persistence,
555
+ }
556
+ do
557
+ if subsystem ~= nil and type(subsystem.Stop) == "function" then
558
+ local ok, err = pcall(subsystem.Stop)
559
+ if not ok then
560
+ Log.Warn("Lifecycle", "SUBSYSTEM_HOOK_ERROR", `Stop failed: {tostring(err)}`, {})
561
+ end
562
+ end
563
+ end
564
+ -- After the subsystems, so nothing is still sending when the channel's listener
565
+ -- goes. The claim is a module global that outlives this bundle, so leaving it set
566
+ -- means the channel can never be rebound.
567
+ if ownsDefaultChannel then
568
+ pcall(TransportModule.ReleaseChannel, options.TransportChannel)
569
+ end
570
+ end
571
+
572
+ -- Per store root, not the store's root accessor: the client holds one tree over both
573
+ -- halves, so this keeps the surface identical on both realms.
574
+ -- Exposes server-owned roots without a player argument.
575
+ if ctx.ServerStore ~= nil then
576
+ local proxy = {}
577
+ for _, key in compiled.Views.Store.RootOrder do
578
+ proxy[key] = ctx.ServerStore.Accessor.Child(key)
579
+ end
580
+ Data.ServerStore = table.freeze(proxy)
581
+ end
582
+
583
+ -- A root field named like a Data API name is silently shadowed by that real key (a
584
+ -- real key always wins over __index), so it is unreachable as `Data.<name>`.
585
+ --
586
+ -- Keep this last, after every Data key is assigned: `for key in Data` sees only the
587
+ -- keys that exist when it runs, so a guard placed higher exempts everything below it.
588
+ -- Server.new redefines Data.Stop after this but adds no new key, so this still sees
589
+ -- the whole public surface.
590
+ -- Raw iteration, so the metatable installed above is not consulted.
591
+ if ctx.DevMode then
592
+ local rootChildren = compiled.Root.Children :: { [string]: any }
593
+ for key in Data do
594
+ if type(key) == "string" and rootChildren[key] then
595
+ -- In the context as well as the message, so a sink need not parse prose.
596
+ Log.Warn(
597
+ "Lifecycle",
598
+ "API_NAME_COLLISION",
599
+ `template root field "{key}" collides with a Data API name`,
600
+ { Field = key }
601
+ )
602
+ end
603
+ end
604
+ end
605
+
606
+ return Data, ctx
607
+ end
608
+
609
+ function Server.new(options: any, compiled: Template.Compiled): any
610
+ local Data, ctx = Server.build(options, compiled)
611
+
612
+ -- Studio-only debug hook for the Scribe Studio plugin, opt-in because it records from
613
+ -- the moment it attaches, plugin or not. The remover Attach hands back is kept: it
614
+ -- releases a Log sink and a Health.OnStatusChanged listener, both library-level
615
+ -- singletons that outlive the bundle, and ends the digest pump. Nil on the refusal
616
+ -- and pcall failure paths, and Stop below tolerates both.
617
+ local detachDebugHook: (() -> ())? = nil
618
+ if options.StudioHook == true and RunService:IsStudio() then
619
+ local ok, err = pcall(function()
620
+ detachDebugHook = (require(script.DebugHook) :: any).Attach(Data, ctx)
621
+ end)
622
+ if not ok then
623
+ Log.Warn("Lifecycle", "DEBUG_HOOK_FAIL", tostring(err), {})
624
+ end
625
+ end
626
+
627
+ ctx.Persistence.BindShutdown()
628
+
629
+ local playerConnections = {
630
+ Players.PlayerAdded:Connect(function(player)
631
+ ctx.Persistence.OnPlayerAdded(player)
632
+ end),
633
+ Players.PlayerRemoving:Connect(function(player)
634
+ ctx.Persistence.OnPlayerRemoving(player)
635
+ end),
636
+ }
637
+ for _, player in Players:GetPlayers() do
638
+ ctx.Persistence.OnPlayerAdded(player)
639
+ end
640
+
641
+ -- Extend build's Stop with the engine wiring only Server.new installs, so each
642
+ -- scope releases exactly what it created.
643
+ local stopSubsystems = Data.Stop
644
+ function Data.Stop()
645
+ for _, connection in playerConnections do
646
+ pcall(function()
647
+ connection:Disconnect()
648
+ end)
649
+ end
650
+ table.clear(playerConnections)
651
+ -- Before the subsystems, and cleared so a second Stop cannot call it twice: the
652
+ -- digest pump reads Persistence.Entries once a tick, so the hook lets go before
653
+ -- what it watches is dismantled. pcalled: a debug facility must not fail teardown.
654
+ local detach = detachDebugHook
655
+ detachDebugHook = nil
656
+ if detach ~= nil then
657
+ local ok, err = pcall(detach)
658
+ if not ok then
659
+ Log.Warn("Lifecycle", "DEBUG_HOOK_FAIL", tostring(err), {})
660
+ end
661
+ end
662
+ stopSubsystems()
663
+ end
664
+
665
+ if options.Banner ~= false then
666
+ print(`Running Scribe v{Version} by ericplane. Server is now initialized`)
667
+ end
668
+
669
+ return Data
670
+ end
671
+
672
+ return Server