@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.
- package/LICENSE +21 -0
- package/NOTICE +21 -0
- package/README.md +100 -0
- package/Scribe-source-map.json +1 -0
- package/licenses/ProfileStore-Apache-2.0.txt +201 -0
- package/package.json +32 -0
- package/src/Client/DebugHook.luau +457 -0
- package/src/Client/init.luau +1607 -0
- package/src/Internal/Addons.luau +68 -0
- package/src/Internal/Big.luau +582 -0
- package/src/Internal/Budget.luau +377 -0
- package/src/Internal/Clock.luau +75 -0
- package/src/Internal/Config.luau +17 -0
- package/src/Internal/Conform.luau +400 -0
- package/src/Internal/Datatypes.luau +653 -0
- package/src/Internal/Defaults.luau +12 -0
- package/src/Internal/Derived.luau +428 -0
- package/src/Internal/Exchange.luau +556 -0
- package/src/Internal/ExchangeLeg.luau +1368 -0
- package/src/Internal/ExchangeVerdict.luau +179 -0
- package/src/Internal/Failure.luau +148 -0
- package/src/Internal/Health.luau +320 -0
- package/src/Internal/LeaderboardDiagnostics.luau +36 -0
- package/src/Internal/Log.luau +378 -0
- package/src/Internal/Marker.luau +76 -0
- package/src/Internal/Metrics.luau +152 -0
- package/src/Internal/Node.luau +3954 -0
- package/src/Internal/Profile.luau +69 -0
- package/src/Internal/Rng.luau +83 -0
- package/src/Internal/Sched.luau +56 -0
- package/src/Internal/Signal.luau +199 -0
- package/src/Internal/Store/ProfileStore.luau +3019 -0
- package/src/Internal/Store/init.luau +18 -0
- package/src/Internal/StudioCodec.luau +155 -0
- package/src/Internal/Template.luau +1848 -0
- package/src/Internal/Transport.luau +169 -0
- package/src/Internal/Util.luau +517 -0
- package/src/Internal/Version.luau +4 -0
- package/src/Internal/Wire.luau +1283 -0
- package/src/Server/Analytics.luau +223 -0
- package/src/Server/Commands.luau +728 -0
- package/src/Server/DebugHook.luau +1490 -0
- package/src/Server/Exchanges.luau +737 -0
- package/src/Server/Leaderboards.luau +2143 -0
- package/src/Server/Monetization.luau +3212 -0
- package/src/Server/Persistence.luau +3775 -0
- package/src/Server/Replication.luau +1253 -0
- package/src/Server/ServerStore.luau +81 -0
- package/src/Server/Timed.luau +579 -0
- package/src/Server/init.luau +672 -0
- package/src/Types.luau +480 -0
- package/src/init.luau +2231 -0
- package/types/api.d.ts +252 -0
- package/types/common.d.ts +355 -0
- package/types/index.d.ts +226 -0
- package/types/schema.d.ts +276 -0
|
@@ -0,0 +1,1490 @@
|
|
|
1
|
+
--!strict
|
|
2
|
+
-- Studio debug hook: the game-side half of the Scribe Studio plugin. Server.new gates
|
|
3
|
+
-- the require on RunService:IsStudio(), so outside Studio nothing here exists.
|
|
4
|
+
-- Transport is one BindableFunction and one BindableEvent under
|
|
5
|
+
-- ServerStorage._ScribeDebugHook; payloads cross VMs as Codec-encoded strings, since
|
|
6
|
+
-- plain-table reflection rejects mixed keys and mangles sparse arrays. Writes need a
|
|
7
|
+
-- per-session opt-in and go through the public Value API, so the hook can never do
|
|
8
|
+
-- what game code could not; receipt injection also needs Mode = "Mock".
|
|
9
|
+
|
|
10
|
+
local RunService = game:GetService("RunService")
|
|
11
|
+
local ServerStorage = game:GetService("ServerStorage")
|
|
12
|
+
local Players = game:GetService("Players")
|
|
13
|
+
|
|
14
|
+
local Internal = script.Parent.Parent.Internal
|
|
15
|
+
local Util = require(Internal.Util)
|
|
16
|
+
local Template = require(Internal.Template)
|
|
17
|
+
local Datatypes = require(Internal.Datatypes)
|
|
18
|
+
local Log = require(Internal.Log)
|
|
19
|
+
local Metrics = require(Internal.Metrics)
|
|
20
|
+
local Health = require(Internal.Health)
|
|
21
|
+
local Addons = require(Internal.Addons)
|
|
22
|
+
|
|
23
|
+
local DebugHook = {}
|
|
24
|
+
|
|
25
|
+
-- Bumped whenever the request/response shapes change. The plugin declares the range
|
|
26
|
+
-- [MinProtocolVersion, Version] it can speak and the hook accepts when its own version
|
|
27
|
+
-- falls inside, so a newer plugin emulates older hooks and games never have to update
|
|
28
|
+
-- Scribe just for the plugin. A plugin older than the hook is refused: the hook cannot
|
|
29
|
+
-- know future semantics. v9 adds Derived info to schema nodes and refuses a write to a
|
|
30
|
+
-- derived field. The full history lives in the plugin's src/Protocol.luau, the one copy
|
|
31
|
+
-- kept complete; bump both together.
|
|
32
|
+
DebugHook.PROTOCOL_VERSION = 9
|
|
33
|
+
DebugHook.CONTAINER_NAME = "_ScribeDebugHook"
|
|
34
|
+
|
|
35
|
+
local OPS_FLUSH_HZ = 8
|
|
36
|
+
local ROSTER_HZ = 1
|
|
37
|
+
local METRICS_HZ = 1
|
|
38
|
+
-- Always-on stream rings, each kept below the pending-queue cap of MAX_BATCH * 4 so a
|
|
39
|
+
-- replay never drops live records.
|
|
40
|
+
local RECENT_OPS_CAP = 2000
|
|
41
|
+
local RECENT_LOGS_CAP = 2000
|
|
42
|
+
local RECENT_SENDS_CAP = 2000
|
|
43
|
+
local RECENT_METRICS_CAP = 1200 -- 1 Hz ticks = 20 minutes of graphs
|
|
44
|
+
local MAX_BATCH = 512 -- ops/log entries per digest fire
|
|
45
|
+
local MAX_TREE_NODES = 2000 -- ReadTree response budget
|
|
46
|
+
local SIZE_RECOMPUTE_SECONDS = 5
|
|
47
|
+
|
|
48
|
+
--------------------------------------------------------------------------------
|
|
49
|
+
-- Codec: shared with the client hook via Internal/StudioCodec, byte-compatible with the
|
|
50
|
+
-- plugin's Codec.luau and versioned by PROTOCOL_VERSION.
|
|
51
|
+
--------------------------------------------------------------------------------
|
|
52
|
+
|
|
53
|
+
local StudioCodec = require(Internal.StudioCodec)
|
|
54
|
+
local encode = StudioCodec.Encode
|
|
55
|
+
local decode = StudioCodec.Decode
|
|
56
|
+
|
|
57
|
+
DebugHook.Encode = encode
|
|
58
|
+
DebugHook.Decode = decode
|
|
59
|
+
|
|
60
|
+
--------------------------------------------------------------------------------
|
|
61
|
+
-- Mirror: a plain-table replica of each session's data, built from the same op stream the
|
|
62
|
+
-- plugin sees, so a digest can report the old value. Writes with Replicate=false bypass
|
|
63
|
+
-- ops and drift it, which is acceptable for a diagnostics view.
|
|
64
|
+
--------------------------------------------------------------------------------
|
|
65
|
+
|
|
66
|
+
local function readPath(root: any, path: { string | number }): any
|
|
67
|
+
local value = root
|
|
68
|
+
for _, seg in path do
|
|
69
|
+
if type(value) ~= "table" then
|
|
70
|
+
return nil
|
|
71
|
+
end
|
|
72
|
+
value = value[seg]
|
|
73
|
+
end
|
|
74
|
+
return value
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
local function applyPlainOp(root: { [any]: any }, op: any)
|
|
78
|
+
local container: any = root
|
|
79
|
+
for i = 1, #op.Path - 1 do
|
|
80
|
+
local seg = op.Path[i]
|
|
81
|
+
local nextContainer = container[seg]
|
|
82
|
+
if type(nextContainer) ~= "table" then
|
|
83
|
+
if op.Kind == "Remove" then
|
|
84
|
+
return -- array removals always ship alongside their creating Insert
|
|
85
|
+
end
|
|
86
|
+
-- A removal op only emits when the parent chain existed server-side, so a
|
|
87
|
+
-- missing parent means its creating op was coalesced away in the same flush
|
|
88
|
+
-- while the container still exists live. Materialize it.
|
|
89
|
+
nextContainer = {}
|
|
90
|
+
container[seg] = nextContainer
|
|
91
|
+
end
|
|
92
|
+
container = nextContainer
|
|
93
|
+
end
|
|
94
|
+
local key = op.Path[#op.Path]
|
|
95
|
+
if key == nil then
|
|
96
|
+
return
|
|
97
|
+
end
|
|
98
|
+
if op.Kind == "Set" then
|
|
99
|
+
-- deepClone copies tables and buffers, both mutable.
|
|
100
|
+
container[key] = Util.deepClone(op.Value)
|
|
101
|
+
elseif op.Kind == "Insert" then
|
|
102
|
+
local arr = container[key]
|
|
103
|
+
if type(arr) ~= "table" then
|
|
104
|
+
arr = {}
|
|
105
|
+
container[key] = arr
|
|
106
|
+
end
|
|
107
|
+
-- An Insert op's Value is the live-stored element reference, so inserting it raw
|
|
108
|
+
-- aliases live data into this mirror and a later op would corrupt the real save.
|
|
109
|
+
table.insert(arr, math.clamp(op.Index or #arr + 1, 1, #arr + 1), Util.deepClone(op.Value))
|
|
110
|
+
elseif op.Kind == "Remove" then
|
|
111
|
+
local arr = container[key]
|
|
112
|
+
if type(arr) == "table" and #arr > 0 then
|
|
113
|
+
table.remove(arr, math.clamp(op.Index or #arr, 1, #arr))
|
|
114
|
+
end
|
|
115
|
+
elseif op.Kind == "Clear" then
|
|
116
|
+
local value = container[key]
|
|
117
|
+
if type(value) == "table" then
|
|
118
|
+
table.clear(value)
|
|
119
|
+
else
|
|
120
|
+
-- A Clear only emits for a container that existed server-side, so materialize
|
|
121
|
+
-- the cleared {} if its creating op was coalesced away.
|
|
122
|
+
container[key] = {}
|
|
123
|
+
end
|
|
124
|
+
end
|
|
125
|
+
end
|
|
126
|
+
|
|
127
|
+
--------------------------------------------------------------------------------
|
|
128
|
+
-- Attach
|
|
129
|
+
--------------------------------------------------------------------------------
|
|
130
|
+
|
|
131
|
+
local attached = false
|
|
132
|
+
|
|
133
|
+
function DebugHook.Attach(Data: any, ctx: any): (() -> ())?
|
|
134
|
+
if not RunService:IsStudio() then
|
|
135
|
+
return nil
|
|
136
|
+
end
|
|
137
|
+
if attached or ServerStorage:FindFirstChild(DebugHook.CONTAINER_NAME) then
|
|
138
|
+
Log.Warn(
|
|
139
|
+
"Lifecycle",
|
|
140
|
+
"DEBUG_HOOK_DUPLICATE",
|
|
141
|
+
"a Scribe debug hook already exists; only the first bundle is inspectable",
|
|
142
|
+
{}
|
|
143
|
+
)
|
|
144
|
+
return nil
|
|
145
|
+
end
|
|
146
|
+
attached = true
|
|
147
|
+
|
|
148
|
+
local compiled: Template.Compiled = ctx.Compiled
|
|
149
|
+
local options = ctx.Options
|
|
150
|
+
local packagePrefix = script.Parent.Parent:GetFullName()
|
|
151
|
+
|
|
152
|
+
-- Session state ------------------------------------------------------------
|
|
153
|
+
|
|
154
|
+
local writesEnabled = false
|
|
155
|
+
local attributionEnabled = false
|
|
156
|
+
local subscriptions: { [string]: boolean } = {}
|
|
157
|
+
|
|
158
|
+
local pending: { [string]: { any } } = { Ops = {}, Logs = {}, Players = {}, Status = {}, Bandwidth = {} }
|
|
159
|
+
local mirrors: { [any]: { [string]: any } } = {} -- entry -> merged root mirror
|
|
160
|
+
local entryConnections: { [any]: RBXScriptConnection } = {}
|
|
161
|
+
local sizeCache: { [any]: { Bytes: number?, At: number } } = {}
|
|
162
|
+
local statusHistory: { { T: number, WallAt: number, From: string, To: string } } = {}
|
|
163
|
+
local armedLoadFailures: { [string]: number } = {}
|
|
164
|
+
-- Removers for registrations on library-level singletons: the Log sink list and
|
|
165
|
+
-- Health.OnStatusChanged. Everything else here is ctx-scoped and dies with the bundle.
|
|
166
|
+
local teardown: { () -> () } = {}
|
|
167
|
+
local detached = false
|
|
168
|
+
local wrapsInstalled = false
|
|
169
|
+
local storeWrapped = false
|
|
170
|
+
local everHandshaken = false
|
|
171
|
+
|
|
172
|
+
-- Everything since Attach, whether or not a plugin is listening; each ring replays on
|
|
173
|
+
-- its stream's subscribe edge, so a panel shows the whole session however late its tab
|
|
174
|
+
-- was opened. Circular, because a shifting array would pay an O(cap) move per record.
|
|
175
|
+
type Ring = { Items: { any }, Cap: number, Count: number, Next: number }
|
|
176
|
+
|
|
177
|
+
local function newRing(cap: number): Ring
|
|
178
|
+
return { Items = table.create(cap), Cap = cap, Count = 0, Next = 1 }
|
|
179
|
+
end
|
|
180
|
+
|
|
181
|
+
local function ringPush(ring: Ring, record: any)
|
|
182
|
+
ring.Items[ring.Next] = record
|
|
183
|
+
ring.Next = ring.Next % ring.Cap + 1
|
|
184
|
+
if ring.Count < ring.Cap then
|
|
185
|
+
ring.Count += 1
|
|
186
|
+
end
|
|
187
|
+
end
|
|
188
|
+
|
|
189
|
+
-- Chronological snapshot. With `flagReplay` each record is a shallow copy marked
|
|
190
|
+
-- Replay = true; the plugin must not apply those to its live tree mirror, since they
|
|
191
|
+
-- are older than any ReadTree page it holds.
|
|
192
|
+
local function ringSnapshot(ring: Ring, flagReplay: boolean?): { any }
|
|
193
|
+
local out = table.create(ring.Count)
|
|
194
|
+
local start = if ring.Count < ring.Cap then 1 else ring.Next
|
|
195
|
+
for i = 0, ring.Count - 1 do
|
|
196
|
+
local record = ring.Items[(start + i - 1) % ring.Cap + 1]
|
|
197
|
+
if flagReplay then
|
|
198
|
+
record = table.clone(record)
|
|
199
|
+
record.Replay = true
|
|
200
|
+
end
|
|
201
|
+
table.insert(out, record)
|
|
202
|
+
end
|
|
203
|
+
return out
|
|
204
|
+
end
|
|
205
|
+
|
|
206
|
+
local opsRing = newRing(RECENT_OPS_CAP)
|
|
207
|
+
local logsRing = newRing(RECENT_LOGS_CAP)
|
|
208
|
+
local sendsRing = newRing(RECENT_SENDS_CAP)
|
|
209
|
+
local metricsRing = newRing(RECENT_METRICS_CAP)
|
|
210
|
+
local opSeq = 0
|
|
211
|
+
local logSeq = 0
|
|
212
|
+
local sendSeq = 0
|
|
213
|
+
local metricSeq = 0
|
|
214
|
+
|
|
215
|
+
-- Writes initiated by the plugin are attributed Source=ScribeStudio. Per-coroutine
|
|
216
|
+
-- rather than a depth counter, so game writes during a hook yield are not mislabeled.
|
|
217
|
+
local hookWriteThreads: { [thread]: boolean } = {}
|
|
218
|
+
|
|
219
|
+
local function studioCall(fn: any, ...: any): (boolean, ...any)
|
|
220
|
+
local thread = coroutine.running()
|
|
221
|
+
hookWriteThreads[thread] = true
|
|
222
|
+
local results = table.pack(pcall(fn, ...))
|
|
223
|
+
hookWriteThreads[thread] = nil
|
|
224
|
+
return table.unpack(results, 1, results.n)
|
|
225
|
+
end
|
|
226
|
+
|
|
227
|
+
-- Attach runs inside Server.new, before the bundle is returned, so wrapping Register
|
|
228
|
+
-- here observes every registration game code makes.
|
|
229
|
+
local commandRegistry: { [string]: { Name: string, Args: { string }?, Handler: any } } = {}
|
|
230
|
+
do
|
|
231
|
+
local origRegister = ctx.Commands.Register
|
|
232
|
+
ctx.Commands.Register = function(name: string, specOrHandler: any, handler: any?)
|
|
233
|
+
origRegister(name, specOrHandler, handler) -- validation errors propagate
|
|
234
|
+
local record: any = { Name = name }
|
|
235
|
+
if handler ~= nil then
|
|
236
|
+
record.Args = if type(specOrHandler) == "table" then specOrHandler.Args else nil
|
|
237
|
+
record.Handler = handler
|
|
238
|
+
else
|
|
239
|
+
record.Handler = specOrHandler
|
|
240
|
+
end
|
|
241
|
+
commandRegistry[name] = record
|
|
242
|
+
end
|
|
243
|
+
end
|
|
244
|
+
|
|
245
|
+
local container = Instance.new("Folder")
|
|
246
|
+
container.Name = DebugHook.CONTAINER_NAME
|
|
247
|
+
local requestFn = Instance.new("BindableFunction")
|
|
248
|
+
requestFn.Name = "Request"
|
|
249
|
+
requestFn.Parent = container
|
|
250
|
+
local streamEv = Instance.new("BindableEvent")
|
|
251
|
+
streamEv.Name = "Stream"
|
|
252
|
+
streamEv.Parent = container
|
|
253
|
+
|
|
254
|
+
--- Release the process-singleton registrations (the Log sink, the Health listener) and
|
|
255
|
+
--- stop the pump. Idempotent, and deliberately does not clear `attached`, so a second
|
|
256
|
+
--- Attach still refuses with DEBUG_HOOK_DUPLICATE.
|
|
257
|
+
local function detach()
|
|
258
|
+
if detached then
|
|
259
|
+
return
|
|
260
|
+
end
|
|
261
|
+
detached = true
|
|
262
|
+
-- Ends the pump on its next tick, which is what it already watches for.
|
|
263
|
+
container.Parent = nil
|
|
264
|
+
for _, release in teardown do
|
|
265
|
+
-- A throwing release must not strand the ones after it.
|
|
266
|
+
pcall(release)
|
|
267
|
+
end
|
|
268
|
+
table.clear(teardown)
|
|
269
|
+
end
|
|
270
|
+
|
|
271
|
+
local function queue(stream: string, item: any)
|
|
272
|
+
if not subscriptions[stream] then
|
|
273
|
+
return
|
|
274
|
+
end
|
|
275
|
+
local bucket = pending[stream]
|
|
276
|
+
if #bucket < MAX_BATCH * 4 then
|
|
277
|
+
table.insert(bucket, item)
|
|
278
|
+
end
|
|
279
|
+
end
|
|
280
|
+
|
|
281
|
+
local function flushStream(stream: string)
|
|
282
|
+
local bucket = pending[stream]
|
|
283
|
+
if #bucket == 0 or not subscriptions[stream] then
|
|
284
|
+
if #bucket > 0 then
|
|
285
|
+
pending[stream] = {}
|
|
286
|
+
end
|
|
287
|
+
return
|
|
288
|
+
end
|
|
289
|
+
while #bucket > 0 do
|
|
290
|
+
local chunk = table.move(bucket, 1, math.min(MAX_BATCH, #bucket), 1, {})
|
|
291
|
+
local remaining = #bucket - #chunk
|
|
292
|
+
if remaining > 0 then
|
|
293
|
+
bucket = table.move(bucket, #chunk + 1, #chunk + remaining, 1, {})
|
|
294
|
+
else
|
|
295
|
+
bucket = {}
|
|
296
|
+
end
|
|
297
|
+
-- Commit the drain progress before encoding, so a chunk that throws is dropped
|
|
298
|
+
-- instead of the whole bucket re-firing on every pump tick.
|
|
299
|
+
pending[stream] = bucket
|
|
300
|
+
local ok, err = pcall(function()
|
|
301
|
+
streamEv:Fire(stream, encode(chunk))
|
|
302
|
+
end)
|
|
303
|
+
if not ok then
|
|
304
|
+
Log.Warn("Lifecycle", "DEBUG_HOOK_ERROR", `dropped a {stream} digest chunk: {tostring(err)}`, {})
|
|
305
|
+
end
|
|
306
|
+
end
|
|
307
|
+
pending[stream] = bucket
|
|
308
|
+
end
|
|
309
|
+
|
|
310
|
+
-- Attribution ---------------------------------------------------------------
|
|
311
|
+
|
|
312
|
+
local function captureSource(): { [string]: any }?
|
|
313
|
+
if hookWriteThreads[coroutine.running()] then
|
|
314
|
+
return { Script = "ScribeStudio", Line = 0 }
|
|
315
|
+
end
|
|
316
|
+
if not attributionEnabled then
|
|
317
|
+
return nil
|
|
318
|
+
end
|
|
319
|
+
-- Walk out of the Scribe package to the first game-code frame. Batches and
|
|
320
|
+
-- transactions add frames, so the walk goes deep.
|
|
321
|
+
for level = 3, 24 do
|
|
322
|
+
local source, line = debug.info(level, "sl")
|
|
323
|
+
if source == nil then
|
|
324
|
+
return nil
|
|
325
|
+
end
|
|
326
|
+
if string.sub(source, 1, #packagePrefix) ~= packagePrefix and source ~= "[C]" then
|
|
327
|
+
return { Script = source, Line = line }
|
|
328
|
+
end
|
|
329
|
+
end
|
|
330
|
+
return nil
|
|
331
|
+
end
|
|
332
|
+
|
|
333
|
+
-- Entry helpers --------------------------------------------------------------
|
|
334
|
+
|
|
335
|
+
local function entryForUserId(userId: number): any
|
|
336
|
+
return ctx.Persistence.EntryForUserId(userId)
|
|
337
|
+
end
|
|
338
|
+
|
|
339
|
+
local function profileIsActive(profile: any): boolean
|
|
340
|
+
if profile == nil then
|
|
341
|
+
return false
|
|
342
|
+
end
|
|
343
|
+
local ok, active = pcall(function()
|
|
344
|
+
return profile:IsActive()
|
|
345
|
+
end)
|
|
346
|
+
return ok and active == true
|
|
347
|
+
end
|
|
348
|
+
|
|
349
|
+
local function mirrorFor(entry: any): { [string]: any }
|
|
350
|
+
local mirror = mirrors[entry]
|
|
351
|
+
if mirror == nil then
|
|
352
|
+
mirror = {}
|
|
353
|
+
if entry.LiveData then
|
|
354
|
+
for k, v in Util.deepClone(entry.LiveData) :: { [string]: any } do
|
|
355
|
+
mirror[k] = v
|
|
356
|
+
end
|
|
357
|
+
end
|
|
358
|
+
if entry.SessionStore then
|
|
359
|
+
for k, v in Util.deepClone(entry.SessionStore) :: { [string]: any } do
|
|
360
|
+
mirror[k] = v
|
|
361
|
+
end
|
|
362
|
+
end
|
|
363
|
+
mirrors[entry] = mirror
|
|
364
|
+
end
|
|
365
|
+
return mirror
|
|
366
|
+
end
|
|
367
|
+
|
|
368
|
+
local function watchEntry(entry: any)
|
|
369
|
+
if entryConnections[entry] then
|
|
370
|
+
return
|
|
371
|
+
end
|
|
372
|
+
local connection
|
|
373
|
+
connection = entry.StateChanged:Connect(function(state: string, reason: string?)
|
|
374
|
+
queue("Players", {
|
|
375
|
+
Kind = "StateChanged",
|
|
376
|
+
T = os.clock(),
|
|
377
|
+
UserId = entry.UserId,
|
|
378
|
+
Name = entry.Player.Name,
|
|
379
|
+
State = state,
|
|
380
|
+
Reason = reason,
|
|
381
|
+
})
|
|
382
|
+
if state == "Ready" then
|
|
383
|
+
-- Seed the old-value mirror before the entry's first op: the node tree
|
|
384
|
+
-- mutates LiveData before emitting, so lazy seeding reads Old == new.
|
|
385
|
+
mirrorFor(entry)
|
|
386
|
+
elseif state == "SessionEnded" then
|
|
387
|
+
mirrors[entry] = nil
|
|
388
|
+
sizeCache[entry] = nil
|
|
389
|
+
-- Drop the strong reference or the profile stays pinned all session.
|
|
390
|
+
entryConnections[entry] = nil
|
|
391
|
+
connection:Disconnect()
|
|
392
|
+
end
|
|
393
|
+
end)
|
|
394
|
+
entryConnections[entry] = connection
|
|
395
|
+
end
|
|
396
|
+
|
|
397
|
+
local function profileSize(entry: any): number?
|
|
398
|
+
local cached = sizeCache[entry]
|
|
399
|
+
local now = os.clock()
|
|
400
|
+
if cached and now - cached.At < SIZE_RECOMPUTE_SECONDS then
|
|
401
|
+
return cached.Bytes
|
|
402
|
+
end
|
|
403
|
+
local bytes = entry.LastSavedSize
|
|
404
|
+
if entry.LiveData then
|
|
405
|
+
bytes = Util.approxSize(entry.LiveData)
|
|
406
|
+
end
|
|
407
|
+
sizeCache[entry] = { Bytes = bytes, At = now }
|
|
408
|
+
return bytes
|
|
409
|
+
end
|
|
410
|
+
|
|
411
|
+
local function rosterSnapshot(): { any }
|
|
412
|
+
local roster = {}
|
|
413
|
+
for _, entry in ctx.Persistence.Entries do
|
|
414
|
+
watchEntry(entry)
|
|
415
|
+
table.insert(roster, {
|
|
416
|
+
UserId = entry.UserId,
|
|
417
|
+
Name = entry.Player.Name,
|
|
418
|
+
DisplayName = entry.Player.DisplayName,
|
|
419
|
+
State = entry.State,
|
|
420
|
+
FailReason = entry.FailReason,
|
|
421
|
+
Dirty = entry.SaveInfo.Dirty,
|
|
422
|
+
LastSaveAt = entry.SaveInfo.LastSaveAt,
|
|
423
|
+
LastResult = entry.SaveInfo.LastResult,
|
|
424
|
+
SizeBytes = profileSize(entry),
|
|
425
|
+
Blocked = entry.Blocked,
|
|
426
|
+
HandshakeReady = entry.HandshakeReady,
|
|
427
|
+
QueueOpen = entry.QueueOpen,
|
|
428
|
+
QueueDepth = #entry.Queue,
|
|
429
|
+
Mock = ctx.Persistence.Mode == "Mock",
|
|
430
|
+
})
|
|
431
|
+
end
|
|
432
|
+
table.sort(roster, function(a: any, b: any)
|
|
433
|
+
return a.UserId < b.UserId
|
|
434
|
+
end)
|
|
435
|
+
return roster
|
|
436
|
+
end
|
|
437
|
+
|
|
438
|
+
-- Interception (installed at Attach, so game boot is captured) ---------------
|
|
439
|
+
|
|
440
|
+
local function installWraps()
|
|
441
|
+
if wrapsInstalled then
|
|
442
|
+
return
|
|
443
|
+
end
|
|
444
|
+
wrapsInstalled = true
|
|
445
|
+
|
|
446
|
+
-- Every replication-worthy op, including the ServerOnly paths the original PushOp
|
|
447
|
+
-- filters out after us. Recorded whether or not anything is subscribed, so early
|
|
448
|
+
-- ops can replay into the Changes feed later.
|
|
449
|
+
local origPushOp = ctx.Replication.PushOp
|
|
450
|
+
ctx.Replication.PushOp = function(entry: any, op: any, schema: any?)
|
|
451
|
+
local ok, err = pcall(function()
|
|
452
|
+
watchEntry(entry) -- StateChanged cleanup for mirrors, pre-roster
|
|
453
|
+
local mirror = mirrorFor(entry)
|
|
454
|
+
local old: any = nil
|
|
455
|
+
if op.Kind == "Set" or op.Kind == "Clear" then
|
|
456
|
+
-- For Clear this is the full contents, not a count, so the plugin's
|
|
457
|
+
-- replay can undo it; the clone below snapshots it before applyPlainOp.
|
|
458
|
+
old = readPath(mirror, op.Path)
|
|
459
|
+
elseif op.Kind == "Remove" then
|
|
460
|
+
local arr = readPath(mirror, op.Path)
|
|
461
|
+
if type(arr) == "table" then
|
|
462
|
+
old = arr[math.clamp(op.Index or #arr, 1, math.max(#arr, 1))]
|
|
463
|
+
end
|
|
464
|
+
end
|
|
465
|
+
local visibility = if schema then schema.Visibility else Template.VisibilityOf(compiled, op.Path)
|
|
466
|
+
opSeq += 1
|
|
467
|
+
-- Value/Old are cloned because the ring outlives the flush window and both
|
|
468
|
+
-- game code and the mirror keep mutating what they reference.
|
|
469
|
+
local record = {
|
|
470
|
+
HookSeq = opSeq,
|
|
471
|
+
T = os.clock(),
|
|
472
|
+
UserId = entry.UserId,
|
|
473
|
+
Kind = op.Kind,
|
|
474
|
+
Path = table.clone(op.Path),
|
|
475
|
+
Index = op.Index,
|
|
476
|
+
Value = if type(op.Value) == "table" or type(op.Value) == "buffer"
|
|
477
|
+
then Util.deepClone(op.Value)
|
|
478
|
+
else op.Value,
|
|
479
|
+
Old = if type(old) == "table" or type(old) == "buffer" then Util.deepClone(old) else old,
|
|
480
|
+
Visibility = visibility,
|
|
481
|
+
FieldId = if schema then schema.Id else nil,
|
|
482
|
+
Source = captureSource(),
|
|
483
|
+
}
|
|
484
|
+
ringPush(opsRing, record)
|
|
485
|
+
queue("Ops", record)
|
|
486
|
+
applyPlainOp(mirror, op)
|
|
487
|
+
end)
|
|
488
|
+
if not ok then
|
|
489
|
+
Log.Warn("Lifecycle", "DEBUG_HOOK_ERROR", tostring(err), {})
|
|
490
|
+
end
|
|
491
|
+
return origPushOp(entry, op, schema)
|
|
492
|
+
end
|
|
493
|
+
|
|
494
|
+
-- Real wire bytes per send, per player.
|
|
495
|
+
local function recordSend(userId: number, bytes: buffer)
|
|
496
|
+
sendSeq += 1
|
|
497
|
+
local record = {
|
|
498
|
+
SendSeq = sendSeq,
|
|
499
|
+
T = os.clock(),
|
|
500
|
+
UserId = userId,
|
|
501
|
+
Bytes = buffer.len(bytes),
|
|
502
|
+
Frame = if buffer.len(bytes) > 0 then buffer.readu8(bytes, 0) else 0,
|
|
503
|
+
}
|
|
504
|
+
ringPush(sendsRing, record)
|
|
505
|
+
queue("Bandwidth", record)
|
|
506
|
+
end
|
|
507
|
+
|
|
508
|
+
local transport = ctx.Transport
|
|
509
|
+
local origSend = transport.SendToClient
|
|
510
|
+
transport.SendToClient = function(self: any, player: Player, bytes: buffer)
|
|
511
|
+
pcall(recordSend, player.UserId, bytes)
|
|
512
|
+
return origSend(self, player, bytes)
|
|
513
|
+
end
|
|
514
|
+
if transport.SendToAllClients then
|
|
515
|
+
local origBroadcast: any = transport.SendToAllClients
|
|
516
|
+
transport.SendToAllClients = function(self: any, bytes: buffer)
|
|
517
|
+
pcall(recordSend, 0, bytes) -- 0 = broadcast
|
|
518
|
+
return origBroadcast(self, bytes)
|
|
519
|
+
end
|
|
520
|
+
end
|
|
521
|
+
|
|
522
|
+
-- Log ring: seeded from the core log history, which covers everything logged
|
|
523
|
+
-- before Attach, then fed by the sink.
|
|
524
|
+
local function recordLog(logEntry: any)
|
|
525
|
+
logSeq += 1
|
|
526
|
+
local record = {
|
|
527
|
+
LogSeq = logSeq,
|
|
528
|
+
At = logEntry.At,
|
|
529
|
+
Level = logEntry.Level,
|
|
530
|
+
Category = logEntry.Category,
|
|
531
|
+
Code = logEntry.Code,
|
|
532
|
+
Message = logEntry.Message,
|
|
533
|
+
Context = Util.sanitizeContext(logEntry.Context),
|
|
534
|
+
}
|
|
535
|
+
ringPush(logsRing, record)
|
|
536
|
+
queue("Logs", record)
|
|
537
|
+
end
|
|
538
|
+
|
|
539
|
+
pcall(function()
|
|
540
|
+
for _, logEntry in Log.GetRecent({ Limit = RECENT_LOGS_CAP }) do
|
|
541
|
+
recordLog(logEntry)
|
|
542
|
+
end
|
|
543
|
+
end)
|
|
544
|
+
table.insert(teardown, Log.AddSink(recordLog, { Level = "Debug" }))
|
|
545
|
+
|
|
546
|
+
local statusConn = Health.OnStatusChanged:Connect(function(newStatus: string, oldStatus: string)
|
|
547
|
+
local record = { T = os.clock(), WallAt = os.time(), From = oldStatus, To = newStatus }
|
|
548
|
+
table.insert(statusHistory, record)
|
|
549
|
+
if #statusHistory > 100 then
|
|
550
|
+
table.remove(statusHistory, 1)
|
|
551
|
+
end
|
|
552
|
+
queue("Status", record)
|
|
553
|
+
end)
|
|
554
|
+
table.insert(teardown, function()
|
|
555
|
+
statusConn:Disconnect()
|
|
556
|
+
end)
|
|
557
|
+
|
|
558
|
+
ctx.Signals.OnSave:Connect(function(info: any)
|
|
559
|
+
local savePlayer: any = info.Player
|
|
560
|
+
queue("Players", {
|
|
561
|
+
Kind = "Save",
|
|
562
|
+
T = os.clock(),
|
|
563
|
+
UserId = if savePlayer ~= nil then savePlayer.UserId else 0,
|
|
564
|
+
Ok = info.Ok,
|
|
565
|
+
Duration = info.Duration,
|
|
566
|
+
At = info.At,
|
|
567
|
+
})
|
|
568
|
+
end)
|
|
569
|
+
|
|
570
|
+
-- Digest pump. Single loop; per-stream cadence via accumulators.
|
|
571
|
+
task.spawn(function()
|
|
572
|
+
local lastRoster = 0
|
|
573
|
+
local lastMetrics = 0
|
|
574
|
+
local lastResync = 0
|
|
575
|
+
while container.Parent ~= nil do
|
|
576
|
+
task.wait(1 / OPS_FLUSH_HZ)
|
|
577
|
+
local ok, err = pcall(function()
|
|
578
|
+
local now = os.clock()
|
|
579
|
+
-- Seed every Ready entry each tick, or Old reads back as the new value.
|
|
580
|
+
for _, entry in ctx.Persistence.Entries do
|
|
581
|
+
if entry.State == "Ready" and mirrors[entry] == nil then
|
|
582
|
+
watchEntry(entry)
|
|
583
|
+
mirrorFor(entry)
|
|
584
|
+
end
|
|
585
|
+
end
|
|
586
|
+
-- Writes with Replicate=false bypass the op stream and drift the mirrors.
|
|
587
|
+
-- Gated on a plugin having attached, so an unwatched game never pays a
|
|
588
|
+
-- recurring deep clone of every profile.
|
|
589
|
+
if everHandshaken and now - lastResync >= 10 then
|
|
590
|
+
lastResync = now
|
|
591
|
+
local mirrored = {}
|
|
592
|
+
for entry in mirrors do
|
|
593
|
+
table.insert(mirrored, entry)
|
|
594
|
+
end
|
|
595
|
+
for _, entry in mirrored do
|
|
596
|
+
mirrors[entry] = nil
|
|
597
|
+
if entry.State == "Ready" and not entry.TornDown then
|
|
598
|
+
mirrorFor(entry)
|
|
599
|
+
end
|
|
600
|
+
end
|
|
601
|
+
end
|
|
602
|
+
flushStream("Ops")
|
|
603
|
+
flushStream("Logs")
|
|
604
|
+
flushStream("Status")
|
|
605
|
+
flushStream("Bandwidth")
|
|
606
|
+
if subscriptions.Players and now - lastRoster >= 1 / ROSTER_HZ then
|
|
607
|
+
lastRoster = now
|
|
608
|
+
queue("Players", { Kind = "Roster", T = now, Roster = rosterSnapshot() })
|
|
609
|
+
end
|
|
610
|
+
flushStream("Players")
|
|
611
|
+
if now - lastMetrics >= 1 / METRICS_HZ then
|
|
612
|
+
lastMetrics = now
|
|
613
|
+
metricSeq += 1
|
|
614
|
+
local tick = {
|
|
615
|
+
MetricSeq = metricSeq,
|
|
616
|
+
T = now,
|
|
617
|
+
WallAt = os.time(),
|
|
618
|
+
Status = Health.GetStatus(),
|
|
619
|
+
Metrics = Metrics.Get(),
|
|
620
|
+
Percentiles = Metrics.GetPercentiles(),
|
|
621
|
+
}
|
|
622
|
+
ringPush(metricsRing, tick)
|
|
623
|
+
if subscriptions.Metrics then
|
|
624
|
+
streamEv:Fire("Metrics", encode({ tick }))
|
|
625
|
+
end
|
|
626
|
+
end
|
|
627
|
+
end)
|
|
628
|
+
if not ok then
|
|
629
|
+
Log.Warn("Lifecycle", "DEBUG_HOOK_ERROR", tostring(err), {})
|
|
630
|
+
end
|
|
631
|
+
end
|
|
632
|
+
-- The container may be destroyed by somebody other than detach(). Release
|
|
633
|
+
-- either way, or the sink and the listener outlive the pump that fed them.
|
|
634
|
+
detach()
|
|
635
|
+
end)
|
|
636
|
+
end
|
|
637
|
+
|
|
638
|
+
-- Store wrap for simulated load failures --------------------------------------
|
|
639
|
+
|
|
640
|
+
local function ensureStoreWrap()
|
|
641
|
+
if storeWrapped then
|
|
642
|
+
return
|
|
643
|
+
end
|
|
644
|
+
storeWrapped = true
|
|
645
|
+
local store = ctx.Persistence.Store
|
|
646
|
+
local origStart = store.StartSessionAsync
|
|
647
|
+
store.StartSessionAsync = function(self: any, key: string, params: any?)
|
|
648
|
+
local remaining = armedLoadFailures[key]
|
|
649
|
+
if remaining and remaining > 0 then
|
|
650
|
+
armedLoadFailures[key] = remaining - 1
|
|
651
|
+
if armedLoadFailures[key] == 0 then
|
|
652
|
+
armedLoadFailures[key] = nil
|
|
653
|
+
end
|
|
654
|
+
Log.Warn(
|
|
655
|
+
"Persistence",
|
|
656
|
+
"SIM_LOAD_FAILURE",
|
|
657
|
+
"simulated profile load failure (Scribe Studio)",
|
|
658
|
+
{ Key = key }
|
|
659
|
+
)
|
|
660
|
+
error("Scribe Studio: simulated load failure")
|
|
661
|
+
end
|
|
662
|
+
return origStart(self, key, params)
|
|
663
|
+
end
|
|
664
|
+
end
|
|
665
|
+
|
|
666
|
+
-- Value API access -----------------------------------------------------------
|
|
667
|
+
|
|
668
|
+
local function accessorAt(entry: any, path: { string | number }): any
|
|
669
|
+
local accessor = entry.Tree.Accessor
|
|
670
|
+
for _, seg in path do
|
|
671
|
+
accessor = accessor[seg]
|
|
672
|
+
end
|
|
673
|
+
return accessor
|
|
674
|
+
end
|
|
675
|
+
|
|
676
|
+
-- Live view straight off the stores (Persist + Session roots merged by
|
|
677
|
+
-- reference); the op mirror is only for old values.
|
|
678
|
+
local function liveRootsFor(entry: any): { [string]: any }
|
|
679
|
+
local merged = {}
|
|
680
|
+
if entry.LiveData then
|
|
681
|
+
for k, v in entry.LiveData :: { [string]: any } do
|
|
682
|
+
merged[k] = v
|
|
683
|
+
end
|
|
684
|
+
end
|
|
685
|
+
if entry.SessionStore then
|
|
686
|
+
for k, v in entry.SessionStore :: { [string]: any } do
|
|
687
|
+
merged[k] = v
|
|
688
|
+
end
|
|
689
|
+
end
|
|
690
|
+
return merged
|
|
691
|
+
end
|
|
692
|
+
|
|
693
|
+
local function describeValue(value: any, depth: number, budget: { n: number }, schema: any): any
|
|
694
|
+
budget.n -= 1
|
|
695
|
+
if type(value) ~= "table" then
|
|
696
|
+
-- A packed datatype leaf is a bare buffer in the store; show the real
|
|
697
|
+
-- value as a display string (StudioCodec cannot carry Roblox datatypes).
|
|
698
|
+
if type(value) == "buffer" and schema and schema.ValueType == "datatype" then
|
|
699
|
+
local name = schema.Datatype :: string
|
|
700
|
+
local ok, unpacked = pcall(Datatypes.Unpack, name, value)
|
|
701
|
+
if ok then
|
|
702
|
+
return { Leaf = true, Value = `{name}({tostring(unpacked)})`, Datatype = name }
|
|
703
|
+
end
|
|
704
|
+
end
|
|
705
|
+
return { Leaf = true, Value = value }
|
|
706
|
+
end
|
|
707
|
+
local count = Util.count(value)
|
|
708
|
+
if depth <= 0 or budget.n <= 0 then
|
|
709
|
+
return { Table = true, Count = count, Truncated = true }
|
|
710
|
+
end
|
|
711
|
+
local children: { [any]: any } = {}
|
|
712
|
+
for k, v in value do
|
|
713
|
+
if budget.n <= 0 then
|
|
714
|
+
return { Table = true, Count = count, Truncated = true, Children = children }
|
|
715
|
+
end
|
|
716
|
+
local childSchema = if schema then Template.ChildSchema(schema, k) else nil
|
|
717
|
+
children[k] = describeValue(v, depth - 1, budget, childSchema)
|
|
718
|
+
end
|
|
719
|
+
return { Table = true, Count = count, Children = children }
|
|
720
|
+
end
|
|
721
|
+
|
|
722
|
+
-- A page of the tree at `path`: leaves inline, deep tables as stubs the plugin
|
|
723
|
+
-- re-requests on expand. Bounded by a node budget so no response can explode.
|
|
724
|
+
local function readTreePage(entry: any, path: { string | number }, depth: number, budget: { n: number }): any
|
|
725
|
+
local value = readPath(liveRootsFor(entry), path)
|
|
726
|
+
local schema: any, dynStart = Template.Resolve(compiled, path)
|
|
727
|
+
for i = dynStart, #path do
|
|
728
|
+
schema = if schema then Template.ChildSchema(schema, path[i]) else nil
|
|
729
|
+
end
|
|
730
|
+
return describeValue(value, depth, budget, schema)
|
|
731
|
+
end
|
|
732
|
+
|
|
733
|
+
-- Dotted input paths of a derived node, for the schema export and the write
|
|
734
|
+
-- refusal. The spec's Compute is a function and never crosses the wire.
|
|
735
|
+
local function derivedInputPaths(spec: any): { string }
|
|
736
|
+
local out = table.create(#spec.InputPaths) :: { string }
|
|
737
|
+
for i, inputPath in spec.InputPaths do
|
|
738
|
+
out[i] = table.concat(inputPath, ".")
|
|
739
|
+
end
|
|
740
|
+
return out
|
|
741
|
+
end
|
|
742
|
+
|
|
743
|
+
-- Command handlers -------------------------------------------------------------
|
|
744
|
+
|
|
745
|
+
local handlers: { [string]: (args: any) -> any } = {}
|
|
746
|
+
|
|
747
|
+
function handlers.Handshake(args: any): any
|
|
748
|
+
local major = tonumber(args.ProtocolVersion) or 0
|
|
749
|
+
-- A plugin without MinProtocolVersion effectively declares [major, major].
|
|
750
|
+
local minSupported = tonumber(args.MinProtocolVersion) or major
|
|
751
|
+
-- NaN compares false both ways and would slip through the range check.
|
|
752
|
+
if major ~= major or minSupported ~= minSupported then
|
|
753
|
+
major, minSupported = 0, 0
|
|
754
|
+
end
|
|
755
|
+
if DebugHook.PROTOCOL_VERSION < minSupported or DebugHook.PROTOCOL_VERSION > major then
|
|
756
|
+
return {
|
|
757
|
+
Ok = false,
|
|
758
|
+
Error = `protocol mismatch: game hook speaks v{DebugHook.PROTOCOL_VERSION}, plugin speaks v{minSupported}-v{major}`
|
|
759
|
+
.. if major < DebugHook.PROTOCOL_VERSION
|
|
760
|
+
then "; update the Scribe Studio plugin"
|
|
761
|
+
else "; update the Scribe package in this game",
|
|
762
|
+
ProtocolVersion = DebugHook.PROTOCOL_VERSION,
|
|
763
|
+
}
|
|
764
|
+
end
|
|
765
|
+
installWraps()
|
|
766
|
+
everHandshaken = true
|
|
767
|
+
-- A handshake means a new plugin instance, so forget the previous one's
|
|
768
|
+
-- subscriptions: the next SetSubscriptions then sees a false->true Ops edge and
|
|
769
|
+
-- replays the boot ring.
|
|
770
|
+
for stream in subscriptions do
|
|
771
|
+
subscriptions[stream] = false
|
|
772
|
+
end
|
|
773
|
+
for _, bucket in pending do
|
|
774
|
+
table.clear(bucket)
|
|
775
|
+
end
|
|
776
|
+
local scribeVersion = "unknown"
|
|
777
|
+
pcall(function()
|
|
778
|
+
scribeVersion = (require :: any)(script.Parent.Parent).Version
|
|
779
|
+
end)
|
|
780
|
+
Log.Info("Lifecycle", "DEBUG_HOOK_ATTACHED", "Scribe Studio attached", {})
|
|
781
|
+
return {
|
|
782
|
+
Ok = true,
|
|
783
|
+
ProtocolVersion = DebugHook.PROTOCOL_VERSION,
|
|
784
|
+
ScribeVersion = scribeVersion,
|
|
785
|
+
TemplateHash = compiled.Hash,
|
|
786
|
+
NodeCount = compiled.NodeCount,
|
|
787
|
+
-- Derived from the resolved mode, so a Mode = "Mock" bundle reports as mocked.
|
|
788
|
+
Mode = ctx.Persistence.Mode,
|
|
789
|
+
UseMock = ctx.Persistence.Mode == "Mock",
|
|
790
|
+
DontSave = ctx.Persistence.Mode == "Mock",
|
|
791
|
+
Clock = os.clock(),
|
|
792
|
+
WallClock = os.time(),
|
|
793
|
+
WritesEnabled = writesEnabled,
|
|
794
|
+
AttributionEnabled = attributionEnabled,
|
|
795
|
+
Status = Health.GetStatus(),
|
|
796
|
+
PlaceName = game.Name,
|
|
797
|
+
}
|
|
798
|
+
end
|
|
799
|
+
|
|
800
|
+
function handlers.SetSubscriptions(args: any): any
|
|
801
|
+
local had: { [string]: boolean } = {}
|
|
802
|
+
for _, stream in { "Ops", "Logs", "Metrics", "Players", "Status", "Bandwidth" } do
|
|
803
|
+
had[stream] = subscriptions[stream] == true
|
|
804
|
+
subscriptions[stream] = args[stream] == true
|
|
805
|
+
if not subscriptions[stream] and pending[stream] then
|
|
806
|
+
table.clear(pending[stream])
|
|
807
|
+
end
|
|
808
|
+
end
|
|
809
|
+
-- Mirrors stay resident while unsubscribed because the op ring needs Old values;
|
|
810
|
+
-- seed any Ready entries that have no ops yet.
|
|
811
|
+
if subscriptions.Ops then
|
|
812
|
+
for _, entry in ctx.Persistence.Entries do
|
|
813
|
+
if entry.State == "Ready" then
|
|
814
|
+
watchEntry(entry)
|
|
815
|
+
mirrorFor(entry)
|
|
816
|
+
end
|
|
817
|
+
end
|
|
818
|
+
end
|
|
819
|
+
-- On each stream's false->true edge, replay its ring and flush immediately so the
|
|
820
|
+
-- pending queue is free again for live records. Every record carries a per-stream
|
|
821
|
+
-- sequence number the plugin dedupes on, so a re-subscribe cannot double-deliver.
|
|
822
|
+
local function replay(stream: string, ring: Ring, flagReplay: boolean?)
|
|
823
|
+
if subscriptions[stream] and not had[stream] and ring.Count > 0 then
|
|
824
|
+
pending[stream] = ringSnapshot(ring, flagReplay)
|
|
825
|
+
flushStream(stream)
|
|
826
|
+
end
|
|
827
|
+
end
|
|
828
|
+
replay("Ops", opsRing, true)
|
|
829
|
+
replay("Logs", logsRing)
|
|
830
|
+
replay("Bandwidth", sendsRing)
|
|
831
|
+
-- Metrics has no pending bucket, being fired directly at 1 Hz; replay the tick
|
|
832
|
+
-- history the same chunked way.
|
|
833
|
+
if subscriptions.Metrics and not had.Metrics and metricsRing.Count > 0 then
|
|
834
|
+
local snapshot = ringSnapshot(metricsRing)
|
|
835
|
+
local offset = 1
|
|
836
|
+
while offset <= #snapshot do
|
|
837
|
+
local chunk = table.move(snapshot, offset, math.min(offset + MAX_BATCH - 1, #snapshot), 1, {})
|
|
838
|
+
local ok, err = pcall(function()
|
|
839
|
+
streamEv:Fire("Metrics", encode(chunk))
|
|
840
|
+
end)
|
|
841
|
+
if not ok then
|
|
842
|
+
Log.Warn("Lifecycle", "DEBUG_HOOK_ERROR", `dropped a Metrics replay chunk: {tostring(err)}`, {})
|
|
843
|
+
end
|
|
844
|
+
offset += MAX_BATCH
|
|
845
|
+
end
|
|
846
|
+
end
|
|
847
|
+
return { Ok = true }
|
|
848
|
+
end
|
|
849
|
+
|
|
850
|
+
function handlers.SetAttribution(args: any): any
|
|
851
|
+
attributionEnabled = args.Enabled == true
|
|
852
|
+
Log.Info(
|
|
853
|
+
"Lifecycle",
|
|
854
|
+
"DEBUG_HOOK_ATTRIBUTION",
|
|
855
|
+
`attribution capture {if attributionEnabled then "enabled" else "disabled"}`,
|
|
856
|
+
{}
|
|
857
|
+
)
|
|
858
|
+
return { Ok = true, Enabled = attributionEnabled }
|
|
859
|
+
end
|
|
860
|
+
|
|
861
|
+
function handlers.SetWritesEnabled(args: any): any
|
|
862
|
+
writesEnabled = args.Enabled == true
|
|
863
|
+
Log.Warn(
|
|
864
|
+
"Lifecycle",
|
|
865
|
+
"DEBUG_HOOK_WRITES",
|
|
866
|
+
`Scribe Studio writes {if writesEnabled then "ENABLED" else "disabled"}`,
|
|
867
|
+
{}
|
|
868
|
+
)
|
|
869
|
+
return { Ok = true, Enabled = writesEnabled }
|
|
870
|
+
end
|
|
871
|
+
|
|
872
|
+
function handlers.ListPlayers(_args: any): any
|
|
873
|
+
return { Ok = true, Roster = rosterSnapshot() }
|
|
874
|
+
end
|
|
875
|
+
|
|
876
|
+
function handlers.ReadTree(args: any): any
|
|
877
|
+
local entry = entryForUserId(tonumber(args.UserId) or 0)
|
|
878
|
+
if not entry then
|
|
879
|
+
return { Ok = false, Error = "no session for that UserId" }
|
|
880
|
+
end
|
|
881
|
+
if entry.State ~= "Ready" then
|
|
882
|
+
return { Ok = false, Error = `session is {entry.State}` }
|
|
883
|
+
end
|
|
884
|
+
local path: { string | number } = args.Path or {}
|
|
885
|
+
local depth = math.clamp(tonumber(args.Depth) or 2, 1, 6)
|
|
886
|
+
local budget = { n = math.clamp(tonumber(args.MaxNodes) or MAX_TREE_NODES, 50, MAX_TREE_NODES) }
|
|
887
|
+
local page = readTreePage(entry, path, depth, budget)
|
|
888
|
+
return { Ok = true, Path = path, Node = page }
|
|
889
|
+
end
|
|
890
|
+
|
|
891
|
+
local function requireWrites(): string?
|
|
892
|
+
if not writesEnabled then
|
|
893
|
+
return "writes are disabled: enable the write toggle in Scribe Studio settings"
|
|
894
|
+
end
|
|
895
|
+
return nil
|
|
896
|
+
end
|
|
897
|
+
|
|
898
|
+
function handlers.WriteValue(args: any): any
|
|
899
|
+
local gate = requireWrites()
|
|
900
|
+
if gate then
|
|
901
|
+
return { Ok = false, Error = gate }
|
|
902
|
+
end
|
|
903
|
+
local entry = entryForUserId(tonumber(args.UserId) or 0)
|
|
904
|
+
if not entry or entry.State ~= "Ready" then
|
|
905
|
+
return { Ok = false, Error = "no Ready session for that UserId" }
|
|
906
|
+
end
|
|
907
|
+
local path: { string | number } = args.Path or {}
|
|
908
|
+
if #path == 0 then
|
|
909
|
+
return { Ok = false, Error = "cannot write the root" }
|
|
910
|
+
end
|
|
911
|
+
-- Refuse here rather than let the accessor's own error surface, so the plugin
|
|
912
|
+
-- can show what the field is computed from. Derived paths are always static.
|
|
913
|
+
local targetNode, dynStart = Template.Resolve(compiled, path)
|
|
914
|
+
if dynStart > #path and targetNode.Derived then
|
|
915
|
+
local inputs = table.concat(derivedInputPaths(targetNode.Derived), ", ")
|
|
916
|
+
return {
|
|
917
|
+
Ok = false,
|
|
918
|
+
Error = `{table.concat(path, ".")} is a derived field: it is computed from {inputs} and cannot be written`,
|
|
919
|
+
}
|
|
920
|
+
end
|
|
921
|
+
local mode: string = args.Mode or "Set"
|
|
922
|
+
local ok, err = studioCall(function()
|
|
923
|
+
if mode == "Set" then
|
|
924
|
+
accessorAt(entry, path).Set(args.Value)
|
|
925
|
+
elseif mode == "Insert" then
|
|
926
|
+
accessorAt(entry, path).Insert(args.Value, args.Index)
|
|
927
|
+
elseif mode == "RemoveIndex" then
|
|
928
|
+
accessorAt(entry, path).Remove(tonumber(args.Index))
|
|
929
|
+
elseif mode == "RemoveKey" then
|
|
930
|
+
accessorAt(entry, path).Remove(tostring(args.Key))
|
|
931
|
+
elseif mode == "Clear" then
|
|
932
|
+
accessorAt(entry, path).Clear()
|
|
933
|
+
elseif mode == "Increment" then
|
|
934
|
+
accessorAt(entry, path).Increment(tonumber(args.Value) or 0)
|
|
935
|
+
elseif mode == "SetTimed" then
|
|
936
|
+
-- Value + wall-clock timer; errors on non-Timed fields.
|
|
937
|
+
local seconds = tonumber(args.Seconds)
|
|
938
|
+
if seconds == nil or seconds <= 0 then
|
|
939
|
+
error("SetTimed needs positive Seconds")
|
|
940
|
+
end
|
|
941
|
+
accessorAt(entry, path).SetTimed(args.Value, seconds)
|
|
942
|
+
elseif mode == "ExtendTimed" then
|
|
943
|
+
local seconds = tonumber(args.Seconds)
|
|
944
|
+
if seconds == nil or seconds <= 0 then
|
|
945
|
+
error("ExtendTimed needs positive Seconds")
|
|
946
|
+
end
|
|
947
|
+
accessorAt(entry, path).ExtendTimed(seconds)
|
|
948
|
+
elseif mode == "ClearTimed" then
|
|
949
|
+
-- Cancel the timer, leave the value. Through Timed's own raw-store write
|
|
950
|
+
-- rather than _Scribe.Timed here: a nested Timed field's pathKey embeds
|
|
951
|
+
-- \31, which the accessor tree rejects, and a save in flight has the
|
|
952
|
+
-- profile pointed at a converted copy.
|
|
953
|
+
accessorAt(entry, path).Active() -- errors early on non-Timed fields
|
|
954
|
+
ctx.Timed.ClearField(entry, Util.pathKey(path))
|
|
955
|
+
else
|
|
956
|
+
error(`unknown write mode "{mode}"`)
|
|
957
|
+
end
|
|
958
|
+
end)
|
|
959
|
+
if not ok then
|
|
960
|
+
return { Ok = false, Error = tostring(err) }
|
|
961
|
+
end
|
|
962
|
+
local newValue = nil
|
|
963
|
+
pcall(function()
|
|
964
|
+
newValue = accessorAt(entry, path).Get()
|
|
965
|
+
end)
|
|
966
|
+
return { Ok = true, NewValue = newValue }
|
|
967
|
+
end
|
|
968
|
+
|
|
969
|
+
function handlers.GetSchema(_args: any): any
|
|
970
|
+
local nodes = {}
|
|
971
|
+
for id = 0, compiled.NodeCount - 1 do
|
|
972
|
+
local node = compiled.ById[id]
|
|
973
|
+
if node then
|
|
974
|
+
local record: any = {
|
|
975
|
+
Id = node.Id,
|
|
976
|
+
Path = table.clone(node.Path),
|
|
977
|
+
Kind = node.Kind,
|
|
978
|
+
ValueType = node.ValueType,
|
|
979
|
+
Datatype = node.Datatype,
|
|
980
|
+
Visibility = node.Visibility,
|
|
981
|
+
Timed = node.Timed,
|
|
982
|
+
Min = node.Min,
|
|
983
|
+
Max = node.Max,
|
|
984
|
+
MaxLength = node.MaxLength,
|
|
985
|
+
Members = if node.Members then table.clone(node.Members) else nil,
|
|
986
|
+
HasChildren = node.Children ~= nil,
|
|
987
|
+
}
|
|
988
|
+
-- Additive since v9; the field is absent on a non-derived node.
|
|
989
|
+
local derived = node.Derived
|
|
990
|
+
if derived then
|
|
991
|
+
record.Derived = {
|
|
992
|
+
Inputs = derivedInputPaths(derived),
|
|
993
|
+
Transmit = derived.Transmit,
|
|
994
|
+
OfflineComputable = derived.OfflineComputable,
|
|
995
|
+
Label = derived.Label,
|
|
996
|
+
}
|
|
997
|
+
end
|
|
998
|
+
table.insert(nodes, record)
|
|
999
|
+
end
|
|
1000
|
+
end
|
|
1001
|
+
-- Element subtrees are id-less, reached only through AnyChild, so the ById walk
|
|
1002
|
+
-- above cannot see them. Exported additively, keyed by the container node's id;
|
|
1003
|
+
-- older plugins ignore the extra field.
|
|
1004
|
+
local elements: { [any]: any } = {}
|
|
1005
|
+
local function describeSchemaNode(node: any): any
|
|
1006
|
+
local children: { [string]: any }? = nil
|
|
1007
|
+
if node.Children then
|
|
1008
|
+
children = {}
|
|
1009
|
+
for name, child in node.Children do
|
|
1010
|
+
(children :: any)[name] = describeSchemaNode(child)
|
|
1011
|
+
end
|
|
1012
|
+
end
|
|
1013
|
+
return {
|
|
1014
|
+
Name = node.Name,
|
|
1015
|
+
Kind = node.Kind,
|
|
1016
|
+
ValueType = node.ValueType,
|
|
1017
|
+
Datatype = node.Datatype,
|
|
1018
|
+
Visibility = node.Visibility,
|
|
1019
|
+
Min = node.Min,
|
|
1020
|
+
Max = node.Max,
|
|
1021
|
+
MaxLength = node.MaxLength,
|
|
1022
|
+
Members = if node.Members then table.clone(node.Members) else nil,
|
|
1023
|
+
Nullable = node.Nullable,
|
|
1024
|
+
Container = node.Container,
|
|
1025
|
+
MaxItems = node.MaxItems,
|
|
1026
|
+
MaxKeys = node.MaxKeys,
|
|
1027
|
+
MaxKeyLength = node.MaxKeyLength,
|
|
1028
|
+
Children = children,
|
|
1029
|
+
Element = if node.AnyChild and node.AnyChild.IsElement then describeSchemaNode(node.AnyChild) else nil,
|
|
1030
|
+
}
|
|
1031
|
+
end
|
|
1032
|
+
for id = 0, compiled.NodeCount - 1 do
|
|
1033
|
+
local node = compiled.ById[id]
|
|
1034
|
+
if node and node.Container ~= nil and node.AnyChild then
|
|
1035
|
+
elements[id] = describeSchemaNode(node.AnyChild)
|
|
1036
|
+
end
|
|
1037
|
+
end
|
|
1038
|
+
return { Ok = true, Hash = compiled.Hash, NodeCount = compiled.NodeCount, Nodes = nodes, Elements = elements }
|
|
1039
|
+
end
|
|
1040
|
+
|
|
1041
|
+
function handlers.GetRecentLogs(args: any): any
|
|
1042
|
+
local entries = Log.GetRecent({
|
|
1043
|
+
Level = args.Level,
|
|
1044
|
+
Category = args.Category,
|
|
1045
|
+
Code = args.Code,
|
|
1046
|
+
Limit = tonumber(args.Limit) or 500,
|
|
1047
|
+
})
|
|
1048
|
+
local out = {}
|
|
1049
|
+
for _, logEntry in entries do
|
|
1050
|
+
table.insert(out, {
|
|
1051
|
+
At = logEntry.At,
|
|
1052
|
+
Level = logEntry.Level,
|
|
1053
|
+
Category = logEntry.Category,
|
|
1054
|
+
Code = logEntry.Code,
|
|
1055
|
+
Message = logEntry.Message,
|
|
1056
|
+
Context = Util.sanitizeContext(logEntry.Context),
|
|
1057
|
+
})
|
|
1058
|
+
end
|
|
1059
|
+
return { Ok = true, Entries = out }
|
|
1060
|
+
end
|
|
1061
|
+
|
|
1062
|
+
function handlers.GetMetrics(_args: any): any
|
|
1063
|
+
return {
|
|
1064
|
+
Ok = true,
|
|
1065
|
+
T = os.clock(),
|
|
1066
|
+
Metrics = Metrics.Get(),
|
|
1067
|
+
Percentiles = Metrics.GetPercentiles(),
|
|
1068
|
+
Status = Health.GetStatus(),
|
|
1069
|
+
}
|
|
1070
|
+
end
|
|
1071
|
+
|
|
1072
|
+
function handlers.GetStatusInfo(_args: any): any
|
|
1073
|
+
return { Ok = true, Status = Health.GetStatus(), History = statusHistory }
|
|
1074
|
+
end
|
|
1075
|
+
|
|
1076
|
+
function handlers.SimulateStatus(args: any): any
|
|
1077
|
+
local gate = requireWrites()
|
|
1078
|
+
if gate then
|
|
1079
|
+
return { Ok = false, Error = gate }
|
|
1080
|
+
end
|
|
1081
|
+
local status = tostring(args.Status)
|
|
1082
|
+
if status ~= "Healthy" and status ~= "Degraded" and status ~= "Outage" then
|
|
1083
|
+
return { Ok = false, Error = `invalid status "{status}"` }
|
|
1084
|
+
end
|
|
1085
|
+
Log.Warn("Lifecycle", "SIM_STATUS", `Scribe Studio forcing service status {status}`, { To = status })
|
|
1086
|
+
Health.AdoptBroadcast(status :: any)
|
|
1087
|
+
if status == "Healthy" then
|
|
1088
|
+
table.clear(armedLoadFailures)
|
|
1089
|
+
end
|
|
1090
|
+
return { Ok = true, Status = Health.GetStatus() }
|
|
1091
|
+
end
|
|
1092
|
+
|
|
1093
|
+
function handlers.SimulateLoadFailure(args: any): any
|
|
1094
|
+
local gate = requireWrites()
|
|
1095
|
+
if gate then
|
|
1096
|
+
return { Ok = false, Error = gate }
|
|
1097
|
+
end
|
|
1098
|
+
local userId = tonumber(args.UserId) or 0
|
|
1099
|
+
local key = ctx.Persistence.KeyFor(userId)
|
|
1100
|
+
ensureStoreWrap()
|
|
1101
|
+
armedLoadFailures[key] = tonumber(args.Failures) or 3
|
|
1102
|
+
Log.Warn("Persistence", "SIM_LOAD_FAILURE", "Scribe Studio armed simulated load failures", {
|
|
1103
|
+
UserId = userId,
|
|
1104
|
+
Failures = armedLoadFailures[key],
|
|
1105
|
+
})
|
|
1106
|
+
|
|
1107
|
+
local entry = entryForUserId(userId)
|
|
1108
|
+
if not entry then
|
|
1109
|
+
return { Ok = true, Note = "armed for the next session load (no active session)" }
|
|
1110
|
+
end
|
|
1111
|
+
local player = entry.Player
|
|
1112
|
+
local profile: any = entry.Profile
|
|
1113
|
+
if profileIsActive(profile) then
|
|
1114
|
+
-- Without this flag Persistence classifies the OnSessionEnd as an external
|
|
1115
|
+
-- steal and skips the final save's bookkeeping. SimulateSessionSteal omits it
|
|
1116
|
+
-- deliberately, since a steal is what that simulation exercises.
|
|
1117
|
+
entry.LocalSessionEnd = true
|
|
1118
|
+
profile:EndSession()
|
|
1119
|
+
end
|
|
1120
|
+
-- Re-run the load path against the armed store so LoadFailurePolicy is
|
|
1121
|
+
-- actually exercised (only possible if the player wasn't kicked).
|
|
1122
|
+
task.delay(0.4, function()
|
|
1123
|
+
if player.Parent == Players and not ctx.Persistence.Entries[player] then
|
|
1124
|
+
ctx.Persistence.OnPlayerAdded(player)
|
|
1125
|
+
end
|
|
1126
|
+
end)
|
|
1127
|
+
return {
|
|
1128
|
+
Ok = true,
|
|
1129
|
+
Note = if options.KickOnSessionEnd ~= false
|
|
1130
|
+
then "session ended; with default KickOnSessionEnd the player is kicked; set KickOnSessionEnd=false to watch the reload loop"
|
|
1131
|
+
else "session ended; reload will hit the armed failures",
|
|
1132
|
+
}
|
|
1133
|
+
end
|
|
1134
|
+
|
|
1135
|
+
function handlers.SimulateSessionSteal(args: any): any
|
|
1136
|
+
local gate = requireWrites()
|
|
1137
|
+
if gate then
|
|
1138
|
+
return { Ok = false, Error = gate }
|
|
1139
|
+
end
|
|
1140
|
+
local entry = entryForUserId(tonumber(args.UserId) or 0)
|
|
1141
|
+
if not entry then
|
|
1142
|
+
return { Ok = false, Error = "no session for that UserId" }
|
|
1143
|
+
end
|
|
1144
|
+
Log.Warn(
|
|
1145
|
+
"Persistence",
|
|
1146
|
+
"SIM_SESSION_STEAL",
|
|
1147
|
+
"Scribe Studio simulating a session steal",
|
|
1148
|
+
{ UserId = entry.UserId }
|
|
1149
|
+
)
|
|
1150
|
+
local profile: any = entry.Profile
|
|
1151
|
+
if profileIsActive(profile) then
|
|
1152
|
+
profile:EndSession()
|
|
1153
|
+
return { Ok = true }
|
|
1154
|
+
end
|
|
1155
|
+
return { Ok = false, Error = "profile is not active" }
|
|
1156
|
+
end
|
|
1157
|
+
|
|
1158
|
+
function handlers.GetConfig(_args: any): any
|
|
1159
|
+
local products = {}
|
|
1160
|
+
for name, config in (options.Products or {}) :: { [string]: any } do
|
|
1161
|
+
products[name] = {
|
|
1162
|
+
Id = config.Id,
|
|
1163
|
+
Category = config.Category,
|
|
1164
|
+
Grants = config.Grants,
|
|
1165
|
+
HasGrantCallback = type(config.Grant) == "function",
|
|
1166
|
+
}
|
|
1167
|
+
end
|
|
1168
|
+
local passes = {}
|
|
1169
|
+
for name, config in (options.Passes or {}) :: { [string]: any } do
|
|
1170
|
+
passes[name] = { Id = config.Id, Category = config.Category }
|
|
1171
|
+
end
|
|
1172
|
+
return {
|
|
1173
|
+
Ok = true,
|
|
1174
|
+
Mode = ctx.Persistence.Mode,
|
|
1175
|
+
UseMock = ctx.Persistence.Mode == "Mock",
|
|
1176
|
+
DontSave = ctx.Persistence.Mode == "Mock",
|
|
1177
|
+
-- Where profiles live, so the plugin's Production panel locks onto the real store.
|
|
1178
|
+
ProfileStoreIndex = options.ProfileStoreIndex or "Default",
|
|
1179
|
+
ProfileKeyPrefix = options.ProfileKeyPrefix or "PLAYER_",
|
|
1180
|
+
LoadFailurePolicy = options.LoadFailurePolicy or "Kick",
|
|
1181
|
+
KickOnSessionEnd = options.KickOnSessionEnd ~= false,
|
|
1182
|
+
BoundsPolicy = options.BoundsPolicy or "Clamp",
|
|
1183
|
+
WipeGuardPolicy = options.WipeGuardPolicy or "Warn",
|
|
1184
|
+
NoGiftIntentPolicy = options.NoGiftIntentPolicy or "GrantOrCredit",
|
|
1185
|
+
GiftIntentTTL = options.GiftIntentTTL or 3600,
|
|
1186
|
+
Products = products,
|
|
1187
|
+
Passes = passes,
|
|
1188
|
+
Perks = options.Perks or {},
|
|
1189
|
+
}
|
|
1190
|
+
end
|
|
1191
|
+
|
|
1192
|
+
function handlers.GetMonetization(args: any): any
|
|
1193
|
+
local entry = entryForUserId(tonumber(args.UserId) or 0)
|
|
1194
|
+
local liveData: any = if entry then entry.LiveData else nil
|
|
1195
|
+
if not entry or entry.State ~= "Ready" or liveData == nil then
|
|
1196
|
+
return { Ok = false, Error = "no Ready session for that UserId" }
|
|
1197
|
+
end
|
|
1198
|
+
local reserved: { [string]: any } = (liveData :: any)[Template.RESERVED_ROOT]
|
|
1199
|
+
if type(reserved) ~= "table" then
|
|
1200
|
+
reserved = {}
|
|
1201
|
+
end
|
|
1202
|
+
local logs: { [string]: any } = if type(reserved.PurchaseLogs) == "table" then reserved.PurchaseLogs else {}
|
|
1203
|
+
local function tableOrEmpty(value: any): { [any]: any }
|
|
1204
|
+
return if type(value) == "table" then Util.deepClone(value) else {}
|
|
1205
|
+
end
|
|
1206
|
+
return {
|
|
1207
|
+
Ok = true,
|
|
1208
|
+
WallClock = os.time(),
|
|
1209
|
+
Perks = tableOrEmpty(reserved.Perks),
|
|
1210
|
+
PendingGifts = tableOrEmpty(reserved.PendingGifts),
|
|
1211
|
+
GiftCredits = tableOrEmpty(reserved.GiftCredits),
|
|
1212
|
+
Robux = tableOrEmpty(logs.Robux),
|
|
1213
|
+
InGame = tableOrEmpty(logs.InGame),
|
|
1214
|
+
ProcessedCount = if type(reserved.ProcessedPurchaseIds) == "table"
|
|
1215
|
+
then #reserved.ProcessedPurchaseIds
|
|
1216
|
+
else 0,
|
|
1217
|
+
}
|
|
1218
|
+
end
|
|
1219
|
+
|
|
1220
|
+
function handlers.GrantPerk(args: any): any
|
|
1221
|
+
local gate = requireWrites()
|
|
1222
|
+
if gate then
|
|
1223
|
+
return { Ok = false, Error = gate }
|
|
1224
|
+
end
|
|
1225
|
+
local entry = entryForUserId(tonumber(args.UserId) or 0)
|
|
1226
|
+
if not entry then
|
|
1227
|
+
return { Ok = false, Error = "no session for that UserId" }
|
|
1228
|
+
end
|
|
1229
|
+
local ok, err = studioCall(Data.GrantPerk, entry.Player, tostring(args.Key))
|
|
1230
|
+
return if ok then { Ok = true } else { Ok = false, Error = tostring(err) }
|
|
1231
|
+
end
|
|
1232
|
+
|
|
1233
|
+
function handlers.RevokePerk(args: any): any
|
|
1234
|
+
local gate = requireWrites()
|
|
1235
|
+
if gate then
|
|
1236
|
+
return { Ok = false, Error = gate }
|
|
1237
|
+
end
|
|
1238
|
+
local entry = entryForUserId(tonumber(args.UserId) or 0)
|
|
1239
|
+
if not entry then
|
|
1240
|
+
return { Ok = false, Error = "no session for that UserId" }
|
|
1241
|
+
end
|
|
1242
|
+
local ok, err = studioCall(Data.RevokePerk, entry.Player, tostring(args.Key))
|
|
1243
|
+
return if ok then { Ok = true } else { Ok = false, Error = tostring(err) }
|
|
1244
|
+
end
|
|
1245
|
+
|
|
1246
|
+
function handlers.PromptGift(args: any): any
|
|
1247
|
+
local gate = requireWrites()
|
|
1248
|
+
if gate then
|
|
1249
|
+
return { Ok = false, Error = gate }
|
|
1250
|
+
end
|
|
1251
|
+
local entry = entryForUserId(tonumber(args.BuyerUserId) or 0)
|
|
1252
|
+
if not entry then
|
|
1253
|
+
return { Ok = false, Error = "no session for the buyer UserId" }
|
|
1254
|
+
end
|
|
1255
|
+
local ok, granted, reason =
|
|
1256
|
+
studioCall(Data.PromptGift, entry.Player, tostring(args.ProductName), tonumber(args.RecipientUserId) or 0)
|
|
1257
|
+
if not ok then
|
|
1258
|
+
return { Ok = false, Error = tostring(granted) }
|
|
1259
|
+
end
|
|
1260
|
+
return { Ok = granted == true, Error = reason }
|
|
1261
|
+
end
|
|
1262
|
+
|
|
1263
|
+
function handlers.InjectReceipt(args: any): any
|
|
1264
|
+
local gate = requireWrites()
|
|
1265
|
+
if gate then
|
|
1266
|
+
return { Ok = false, Error = gate }
|
|
1267
|
+
end
|
|
1268
|
+
-- The resolved mode, not the legacy UseMock flag: Mode never reaches options, so
|
|
1269
|
+
-- gating on UseMock refuses injection on a Mode = "Mock" bundle.
|
|
1270
|
+
if ctx.Persistence.Mode ~= "Mock" then
|
|
1271
|
+
return {
|
|
1272
|
+
Ok = false,
|
|
1273
|
+
Error = 'receipt injection requires Mode = "Mock" (or the legacy UseMock), matching the core\'s testing posture: no real store is ever touched',
|
|
1274
|
+
}
|
|
1275
|
+
end
|
|
1276
|
+
local receipt = args.ReceiptInfo
|
|
1277
|
+
if type(receipt) ~= "table" then
|
|
1278
|
+
return { Ok = false, Error = "ReceiptInfo table required" }
|
|
1279
|
+
end
|
|
1280
|
+
Log.Warn("Monetization", "SIM_RECEIPT", "Scribe Studio injecting a mock receipt", {
|
|
1281
|
+
PurchaseId = tostring(receipt.PurchaseId),
|
|
1282
|
+
ProductId = tonumber(receipt.ProductId),
|
|
1283
|
+
})
|
|
1284
|
+
local ok, decision = studioCall(Data.HandleReceipt, receipt)
|
|
1285
|
+
if not ok then
|
|
1286
|
+
return { Ok = false, Error = tostring(decision) }
|
|
1287
|
+
end
|
|
1288
|
+
local name = if typeof(decision) == "EnumItem" then (decision :: EnumItem).Name else tostring(decision)
|
|
1289
|
+
return { Ok = true, Decision = name }
|
|
1290
|
+
end
|
|
1291
|
+
|
|
1292
|
+
-- Command console -----------------------------------------------------------
|
|
1293
|
+
|
|
1294
|
+
function handlers.ListCommands(_args: any): any
|
|
1295
|
+
local commands = {}
|
|
1296
|
+
for _, record in commandRegistry do
|
|
1297
|
+
table.insert(commands, {
|
|
1298
|
+
Name = record.Name,
|
|
1299
|
+
Args = if record.Args then table.clone(record.Args) else nil,
|
|
1300
|
+
})
|
|
1301
|
+
end
|
|
1302
|
+
table.sort(commands, function(a: any, b: any)
|
|
1303
|
+
return a.Name < b.Name
|
|
1304
|
+
end)
|
|
1305
|
+
return { Ok = true, Commands = commands }
|
|
1306
|
+
end
|
|
1307
|
+
|
|
1308
|
+
function handlers.InvokeCommand(args: any): any
|
|
1309
|
+
local gate = requireWrites()
|
|
1310
|
+
if gate then
|
|
1311
|
+
return { Ok = false, Error = gate }
|
|
1312
|
+
end
|
|
1313
|
+
local record = commandRegistry[tostring(args.Name)]
|
|
1314
|
+
if record == nil then
|
|
1315
|
+
return { Ok = false, Error = `unknown command "{tostring(args.Name)}"` }
|
|
1316
|
+
end
|
|
1317
|
+
local entry = entryForUserId(tonumber(args.UserId) or 0)
|
|
1318
|
+
if not entry or entry.State ~= "Ready" then
|
|
1319
|
+
return { Ok = false, Error = "no Ready session for that UserId" }
|
|
1320
|
+
end
|
|
1321
|
+
local commandArgs: { any } = if type(args.Args) == "table" then args.Args :: any else {}
|
|
1322
|
+
local argCount = tonumber(args.ArgCount) or #commandArgs
|
|
1323
|
+
Log.Info("Commands", "SIM_COMMAND", `Scribe Studio invoking command "{record.Name}"`, {
|
|
1324
|
+
Player = entry.Player,
|
|
1325
|
+
Command = record.Name,
|
|
1326
|
+
})
|
|
1327
|
+
local results = table.pack(studioCall(record.Handler, entry.Player, table.unpack(commandArgs, 1, argCount)))
|
|
1328
|
+
local ok = results[1]
|
|
1329
|
+
if not ok then
|
|
1330
|
+
return { Ok = false, Error = tostring(results[2]) }
|
|
1331
|
+
end
|
|
1332
|
+
local returns = table.create(results.n - 1)
|
|
1333
|
+
for i = 2, results.n do
|
|
1334
|
+
returns[i - 1] = results[i]
|
|
1335
|
+
end
|
|
1336
|
+
return { Ok = true, Results = returns, ResultCount = results.n - 1 }
|
|
1337
|
+
end
|
|
1338
|
+
|
|
1339
|
+
-- Leaderboards ---------------------------------------------------------------
|
|
1340
|
+
|
|
1341
|
+
function handlers.GetLeaderboards(_args: any): any
|
|
1342
|
+
local boards = {}
|
|
1343
|
+
for name, config in (options.Leaderboards or {}) :: { [string]: any } do
|
|
1344
|
+
local entries = {}
|
|
1345
|
+
pcall(function()
|
|
1346
|
+
entries = ctx.Leaderboards.GetLeaderboard(name, config.Limit)
|
|
1347
|
+
end)
|
|
1348
|
+
local myRanks = {}
|
|
1349
|
+
for _, entry in ctx.Persistence.Entries do
|
|
1350
|
+
local rank = nil
|
|
1351
|
+
pcall(function()
|
|
1352
|
+
rank = ctx.Leaderboards.GetMyRank(entry.Player, name)
|
|
1353
|
+
end)
|
|
1354
|
+
if rank ~= nil then
|
|
1355
|
+
myRanks[tostring(entry.UserId)] = rank
|
|
1356
|
+
end
|
|
1357
|
+
end
|
|
1358
|
+
table.insert(boards, {
|
|
1359
|
+
Name = name,
|
|
1360
|
+
Stat = config.Stat,
|
|
1361
|
+
Limit = config.Limit or 100,
|
|
1362
|
+
Scale = config.Scale or 1,
|
|
1363
|
+
Replicate = config.Replicate == true,
|
|
1364
|
+
Entries = entries,
|
|
1365
|
+
MyRanks = myRanks,
|
|
1366
|
+
})
|
|
1367
|
+
end
|
|
1368
|
+
table.sort(boards, function(a: any, b: any)
|
|
1369
|
+
return a.Name < b.Name
|
|
1370
|
+
end)
|
|
1371
|
+
return {
|
|
1372
|
+
Ok = true,
|
|
1373
|
+
Boards = boards,
|
|
1374
|
+
QueueDepth = tonumber(Metrics.Get().LbQueueDepth) or 0,
|
|
1375
|
+
Workers = ctx.Leaderboards.Workers(),
|
|
1376
|
+
}
|
|
1377
|
+
end
|
|
1378
|
+
|
|
1379
|
+
function handlers.RefreshLeaderboards(args: any): any
|
|
1380
|
+
local ok, err = pcall(function()
|
|
1381
|
+
ctx.Leaderboards.RefreshNow(if args.Name then tostring(args.Name) else nil)
|
|
1382
|
+
end)
|
|
1383
|
+
return if ok then { Ok = true } else { Ok = false, Error = tostring(err) }
|
|
1384
|
+
end
|
|
1385
|
+
|
|
1386
|
+
function handlers.FlushLeaderboards(_args: any): any
|
|
1387
|
+
local gate = requireWrites()
|
|
1388
|
+
if gate then
|
|
1389
|
+
return { Ok = false, Error = gate }
|
|
1390
|
+
end
|
|
1391
|
+
Log.Info("Leaderboards", "SIM_LB_FLUSH", "Scribe Studio draining the leaderboard write queue", {})
|
|
1392
|
+
local ok, err = pcall(function()
|
|
1393
|
+
ctx.Leaderboards.FlushAllBlocking(5)
|
|
1394
|
+
end)
|
|
1395
|
+
return if ok then { Ok = true } else { Ok = false, Error = tostring(err) }
|
|
1396
|
+
end
|
|
1397
|
+
|
|
1398
|
+
function handlers.ListAddons(_args: any): any
|
|
1399
|
+
return { Ok = true, Addons = Addons.List() }
|
|
1400
|
+
end
|
|
1401
|
+
|
|
1402
|
+
function handlers.AddonAction(args: any): any
|
|
1403
|
+
local name, action = tostring(args.Addon), tostring(args.Action)
|
|
1404
|
+
if Addons.Writes(name, action) then
|
|
1405
|
+
local gate = requireWrites()
|
|
1406
|
+
if gate then
|
|
1407
|
+
return { Ok = false, Error = gate }
|
|
1408
|
+
end
|
|
1409
|
+
end
|
|
1410
|
+
local called, ok, result = studioCall(Addons.Invoke, name, action, args.Args)
|
|
1411
|
+
if not called then
|
|
1412
|
+
return { Ok = false, Error = tostring(ok) }
|
|
1413
|
+
end
|
|
1414
|
+
return if ok then { Ok = true, Result = result } else { Ok = false, Error = tostring(result) }
|
|
1415
|
+
end
|
|
1416
|
+
|
|
1417
|
+
-- Template defaults (player comparison baseline) ------------------------------
|
|
1418
|
+
|
|
1419
|
+
function handlers.GetDefaults(_args: any): any
|
|
1420
|
+
return {
|
|
1421
|
+
Ok = true,
|
|
1422
|
+
Persistent = Template.BuildDefaults(compiled, "Persistent"),
|
|
1423
|
+
Session = Template.BuildDefaults(compiled, "Session"),
|
|
1424
|
+
}
|
|
1425
|
+
end
|
|
1426
|
+
|
|
1427
|
+
function handlers.Snapshot(args: any): any
|
|
1428
|
+
local entry = entryForUserId(tonumber(args.UserId) or 0)
|
|
1429
|
+
if not entry or entry.State ~= "Ready" or not entry.LiveData then
|
|
1430
|
+
return { Ok = false, Error = "no Ready session for that UserId" }
|
|
1431
|
+
end
|
|
1432
|
+
return {
|
|
1433
|
+
Ok = true,
|
|
1434
|
+
UserId = entry.UserId,
|
|
1435
|
+
Name = entry.Player.Name,
|
|
1436
|
+
Data = Util.deepClone(entry.LiveData),
|
|
1437
|
+
Session = Util.deepClone(entry.SessionStore or {}),
|
|
1438
|
+
}
|
|
1439
|
+
end
|
|
1440
|
+
|
|
1441
|
+
function handlers.Flush(args: any): any
|
|
1442
|
+
local gate = requireWrites()
|
|
1443
|
+
if gate then
|
|
1444
|
+
return { Ok = false, Error = gate }
|
|
1445
|
+
end
|
|
1446
|
+
local entry = entryForUserId(tonumber(args.UserId) or 0)
|
|
1447
|
+
if not entry then
|
|
1448
|
+
return { Ok = false, Error = "no session for that UserId" }
|
|
1449
|
+
end
|
|
1450
|
+
local ok = Data.Flush(entry.Player, if args.Force then { Force = true } else nil)
|
|
1451
|
+
return { Ok = ok == true, Error = if ok then nil else "flush did not confirm" }
|
|
1452
|
+
end
|
|
1453
|
+
|
|
1454
|
+
-- Dispatch -------------------------------------------------------------------
|
|
1455
|
+
|
|
1456
|
+
requestFn.OnInvoke = function(name: any, encodedArgs: any): string
|
|
1457
|
+
local response: any
|
|
1458
|
+
Util.safeCall(function(err)
|
|
1459
|
+
response = { Ok = false, Error = tostring(err) }
|
|
1460
|
+
end, function()
|
|
1461
|
+
local handler = handlers[tostring(name)]
|
|
1462
|
+
if not handler then
|
|
1463
|
+
response = { Ok = false, Error = `unknown command "{tostring(name)}"` }
|
|
1464
|
+
return
|
|
1465
|
+
end
|
|
1466
|
+
local args: any = {}
|
|
1467
|
+
if type(encodedArgs) == "string" and #encodedArgs > 0 then
|
|
1468
|
+
args = decode(encodedArgs)
|
|
1469
|
+
end
|
|
1470
|
+
response = handler(if type(args) == "table" then args else {})
|
|
1471
|
+
end)
|
|
1472
|
+
return encode(response)
|
|
1473
|
+
end
|
|
1474
|
+
|
|
1475
|
+
container.Parent = ServerStorage
|
|
1476
|
+
|
|
1477
|
+
-- Record from game boot, not from the first plugin handshake: the op ring, old-value
|
|
1478
|
+
-- mirrors and status history must exist before any plugin attaches. Parent the
|
|
1479
|
+
-- container first, because the pump loop exits when container.Parent is nil.
|
|
1480
|
+
installWraps()
|
|
1481
|
+
|
|
1482
|
+
-- Restore simulated state on teardown; Studio destroys the DataModel anyway.
|
|
1483
|
+
game:BindToClose(function()
|
|
1484
|
+
table.clear(armedLoadFailures)
|
|
1485
|
+
end)
|
|
1486
|
+
|
|
1487
|
+
return detach
|
|
1488
|
+
end
|
|
1489
|
+
|
|
1490
|
+
return DebugHook
|