@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,1607 @@
|
|
|
1
|
+
--!strict
|
|
2
|
+
-- Client assembly: local mirror tree, Hello/Init handshake, diff application,
|
|
3
|
+
-- command RPC, leaderboard/status/shared mirrors, and the edit-mode fallback.
|
|
4
|
+
|
|
5
|
+
local RunService = game:GetService("RunService")
|
|
6
|
+
|
|
7
|
+
local Internal = script.Parent.Internal
|
|
8
|
+
local Util = require(Internal.Util)
|
|
9
|
+
local Node = require(Internal.Node)
|
|
10
|
+
local Wire = require(Internal.Wire)
|
|
11
|
+
local Template = require(Internal.Template)
|
|
12
|
+
local TransportModule = require(Internal.Transport)
|
|
13
|
+
local DerivedModule = require(Internal.Derived)
|
|
14
|
+
local Version = require(Internal.Version)
|
|
15
|
+
local Log = require(Internal.Log)
|
|
16
|
+
local Metrics = require(Internal.Metrics)
|
|
17
|
+
local Health = require(Internal.Health)
|
|
18
|
+
local Signal = require(Internal.Signal)
|
|
19
|
+
local Clock = require(script.Parent.Internal.Clock)
|
|
20
|
+
local Rng = require(script.Parent.Internal.Rng)
|
|
21
|
+
local Sched = require(Internal.Sched)
|
|
22
|
+
local Defaults = require(Internal.Defaults)
|
|
23
|
+
-- For RequestFailed only: the identity Request appends to its own refusals.
|
|
24
|
+
local Types = require(script.Parent.Types)
|
|
25
|
+
|
|
26
|
+
-- Request names are the client's to choose, so the named series are capped.
|
|
27
|
+
local MAX_TIMEOUT_SERIES = 32
|
|
28
|
+
local timeoutSeries: { [string]: true } = {}
|
|
29
|
+
local timeoutSeriesCount = 0
|
|
30
|
+
|
|
31
|
+
local function timeoutMetric(name: string): string
|
|
32
|
+
local key = `RequestTimeouts:{name}`
|
|
33
|
+
if timeoutSeries[key] then
|
|
34
|
+
return key
|
|
35
|
+
end
|
|
36
|
+
if timeoutSeriesCount >= MAX_TIMEOUT_SERIES then
|
|
37
|
+
return "RequestTimeouts:Other"
|
|
38
|
+
end
|
|
39
|
+
timeoutSeries[key] = true
|
|
40
|
+
timeoutSeriesCount += 1
|
|
41
|
+
return key
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
local Client = {}
|
|
45
|
+
|
|
46
|
+
-- Test seam: Players.LocalPlayer is read-only in Studio.
|
|
47
|
+
local localPlayerProbe: (() -> any)? = nil
|
|
48
|
+
|
|
49
|
+
function Client.SetLocalPlayerProbe(fn: (() -> any)?)
|
|
50
|
+
localPlayerProbe = fn
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
local function readLocalPlayer(): any
|
|
54
|
+
if localPlayerProbe ~= nil then
|
|
55
|
+
return localPlayerProbe()
|
|
56
|
+
end
|
|
57
|
+
return (game:GetService("Players") :: any).LocalPlayer
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
local ID_TO_STATUS: { [number]: string } = { [0] = "Healthy", [1] = "Degraded", [2] = "Outage" }
|
|
61
|
+
|
|
62
|
+
-- The placeholder a request slot carries until it is settled. Frozen and shared
|
|
63
|
+
-- because it is never read or written; one allocation for the whole module.
|
|
64
|
+
local NO_RESULTS: { any } = table.freeze({} :: { any })
|
|
65
|
+
|
|
66
|
+
-- Applies a decoded op to a plain table (other players' Shared mirrors).
|
|
67
|
+
local function applyPlainOp(root: { [any]: any }, op: Wire.Op)
|
|
68
|
+
local container: any = root
|
|
69
|
+
for i = 1, #op.Path - 1 do
|
|
70
|
+
local segment = op.Path[i]
|
|
71
|
+
local nextContainer = container[segment]
|
|
72
|
+
if type(nextContainer) ~= "table" then
|
|
73
|
+
if op.Kind == "Remove" then
|
|
74
|
+
return -- array removals always ship alongside their creating Insert
|
|
75
|
+
end
|
|
76
|
+
-- Materialize intermediates for Set and Clear too: a missing parent means
|
|
77
|
+
-- its creating op was coalesced away in the same flush while the server
|
|
78
|
+
-- still holds the container, so creating it here keeps existence parity.
|
|
79
|
+
nextContainer = {}
|
|
80
|
+
container[segment] = nextContainer
|
|
81
|
+
end
|
|
82
|
+
container = nextContainer
|
|
83
|
+
end
|
|
84
|
+
local key = op.Path[#op.Path]
|
|
85
|
+
if op.Kind == "Set" then
|
|
86
|
+
container[key] = op.Value
|
|
87
|
+
elseif op.Kind == "Insert" then
|
|
88
|
+
local arr = container[key]
|
|
89
|
+
if type(arr) ~= "table" then
|
|
90
|
+
arr = {}
|
|
91
|
+
container[key] = arr
|
|
92
|
+
end
|
|
93
|
+
table.insert(arr, math.clamp(op.Index or #arr + 1, 1, #arr + 1), op.Value)
|
|
94
|
+
elseif op.Kind == "Remove" then
|
|
95
|
+
local arr = container[key]
|
|
96
|
+
if type(arr) == "table" and #arr > 0 then
|
|
97
|
+
table.remove(arr, math.clamp(op.Index or #arr, 1, #arr))
|
|
98
|
+
end
|
|
99
|
+
elseif op.Kind == "Clear" then
|
|
100
|
+
local value = container[key]
|
|
101
|
+
if type(value) == "table" then
|
|
102
|
+
table.clear(value)
|
|
103
|
+
else
|
|
104
|
+
-- A Clear only emits for a container that existed server-side, so if
|
|
105
|
+
-- its creating op was coalesced away, materialize the cleared {}.
|
|
106
|
+
container[key] = {}
|
|
107
|
+
end
|
|
108
|
+
end
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
function Client.new(options: any, compiled: Template.Compiled): any
|
|
112
|
+
-- Test seams: patching RunService itself is illegal on a real service Instance,
|
|
113
|
+
-- so without these nothing needing edit mode or the Studio hook runs in Studio.
|
|
114
|
+
local isRunning = if options.IsRunning ~= nil then options.IsRunning == true else RunService:IsRunning()
|
|
115
|
+
local devMode = if options.DevMode ~= nil then options.DevMode == true else RunService:IsStudio()
|
|
116
|
+
local editMode = not isRunning
|
|
117
|
+
|
|
118
|
+
if options.LogLevel then
|
|
119
|
+
Log.SetLevel(options.LogLevel)
|
|
120
|
+
end
|
|
121
|
+
if options.LogRingLevel then
|
|
122
|
+
Log.SetRingLevel(options.LogRingLevel)
|
|
123
|
+
end
|
|
124
|
+
if options.LogRingSize ~= nil then
|
|
125
|
+
Log.SetRingSize(options.LogRingSize)
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
local mirror: { [string]: any } = Template.BuildDefaults(compiled, "Client")
|
|
129
|
+
local loaded = editMode
|
|
130
|
+
local stopped = false
|
|
131
|
+
local loadedSignal = Signal.new()
|
|
132
|
+
-- Suppress overlapping button requests; the server tracks the open dialog.
|
|
133
|
+
local purchaseRequestPending = false
|
|
134
|
+
|
|
135
|
+
local tree = Node.NewTree({
|
|
136
|
+
Compiled = compiled,
|
|
137
|
+
Stores = { Persist = mirror, Session = mirror },
|
|
138
|
+
IsServer = false,
|
|
139
|
+
Label = "LocalPlayer",
|
|
140
|
+
OnOp = nil, -- client writes are local-only
|
|
141
|
+
OnAnomaly = nil,
|
|
142
|
+
BoundsPolicy = options.BoundsPolicy or "Clamp",
|
|
143
|
+
DevMode = devMode,
|
|
144
|
+
TimedHooks = {
|
|
145
|
+
-- Clients read deadlines; only the server can change them.
|
|
146
|
+
SetTimed = function()
|
|
147
|
+
error("Scribe: SetTimed is server-only", 3)
|
|
148
|
+
end,
|
|
149
|
+
ExtendTimed = function()
|
|
150
|
+
error("Scribe: ExtendTimed is server-only", 3)
|
|
151
|
+
end,
|
|
152
|
+
Active = function(accessor: any): (boolean, number?)
|
|
153
|
+
local schema = Node.SchemaOf(accessor)
|
|
154
|
+
if editMode or not schema or schema.Visibility == "ServerOnly" then
|
|
155
|
+
return false, nil
|
|
156
|
+
end
|
|
157
|
+
local session = mirror[Template.SESSION_ROOT]
|
|
158
|
+
local timers = if session then session.Timed else nil
|
|
159
|
+
local expiry = if timers then timers[tostring(schema.Id)] else nil
|
|
160
|
+
if type(expiry) ~= "number" or expiry ~= expiry or math.abs(expiry) == math.huge then
|
|
161
|
+
return false, nil
|
|
162
|
+
end
|
|
163
|
+
local remaining = expiry - Clock.ServerNow()
|
|
164
|
+
return remaining > 0, if remaining > 0 then remaining else nil
|
|
165
|
+
end,
|
|
166
|
+
},
|
|
167
|
+
OnEconomy = nil,
|
|
168
|
+
LogError = function(message)
|
|
169
|
+
Log.Error("Lifecycle", "LISTENER_ERROR", message, {})
|
|
170
|
+
end,
|
|
171
|
+
OnDerivedIssue = function(code, field, detail)
|
|
172
|
+
-- A mismatch means the server computed a different value than this realm,
|
|
173
|
+
-- so the compute function is impure. The server's value wins.
|
|
174
|
+
local report: typeof(Log.Warn) = if code == "DERIVED_MISMATCH" then Log.Warn else Log.Error
|
|
175
|
+
report("Derived", code :: any, `"{field}": {detail}`, { Field = field })
|
|
176
|
+
end,
|
|
177
|
+
})
|
|
178
|
+
|
|
179
|
+
local sharedMirrors: { [number]: { [string]: any } } = {}
|
|
180
|
+
-- Derived fields another player's mirror has to compute for itself.
|
|
181
|
+
local function isSharedLocalDerived(node: any): boolean
|
|
182
|
+
return node.Visibility == "Shared" and not node.Derived.Transmit
|
|
183
|
+
end
|
|
184
|
+
local leaderboardCache: { [string]: { Entries: { any }, MyRank: number?, MyScore: number? } } = {}
|
|
185
|
+
local mockCommands: { [string]: (...any) -> ...any } = {}
|
|
186
|
+
local mockLeaderboards: { [string]: { any } } = {}
|
|
187
|
+
|
|
188
|
+
local OnServiceStatus = Signal.new()
|
|
189
|
+
local OnSharedChanged = Signal.new()
|
|
190
|
+
local OnOwnershipChanged = Signal.new()
|
|
191
|
+
local OnLeaderboard = Signal.new()
|
|
192
|
+
|
|
193
|
+
local transport: any = nil
|
|
194
|
+
-- One in-flight Client.Request. The slot carries the answer, not the resumption:
|
|
195
|
+
-- Sched.Resume is task.spawn, so a synchronous loopback can settle the slot from
|
|
196
|
+
-- inside the send while the requester is still running, and resuming a running
|
|
197
|
+
-- thread raises.
|
|
198
|
+
-- Parked written only by the requester either side of its yield, so never true
|
|
199
|
+
-- while it runs. coroutine.status is no substitute: a transport that
|
|
200
|
+
-- yields inside SendToServer would misdeliver the reply.
|
|
201
|
+
-- Settled an answer has been claimed. The reply, the timeout and a throwing send
|
|
202
|
+
-- race for it; first wins. Results carries an explicit Count because a
|
|
203
|
+
-- handler may return nils and `#` on a table with a hole is undefined.
|
|
204
|
+
type RequestSlot = {
|
|
205
|
+
Correlation: number,
|
|
206
|
+
Thread: thread,
|
|
207
|
+
Parked: boolean,
|
|
208
|
+
Settled: boolean,
|
|
209
|
+
Results: { any },
|
|
210
|
+
Count: number,
|
|
211
|
+
}
|
|
212
|
+
local requestWaiters: { [number]: RequestSlot } = {}
|
|
213
|
+
local nextCorrelation = 0
|
|
214
|
+
|
|
215
|
+
-- The one place a request is answered and the one place a slot leaves the map, so
|
|
216
|
+
-- the "exactly one winner" rule is a single guard. Nothing after it yields.
|
|
217
|
+
local function settleRequest(slot: RequestSlot, results: { any }, count: number)
|
|
218
|
+
if slot.Settled then
|
|
219
|
+
return
|
|
220
|
+
end
|
|
221
|
+
slot.Settled = true
|
|
222
|
+
slot.Results = results
|
|
223
|
+
slot.Count = count
|
|
224
|
+
-- Cleared by identity, never by presence: correlations wrap at 2^32, so a dead
|
|
225
|
+
-- request's timer must not evict the slot that inherited its number.
|
|
226
|
+
if requestWaiters[slot.Correlation] == slot then
|
|
227
|
+
requestWaiters[slot.Correlation] = nil
|
|
228
|
+
end
|
|
229
|
+
-- No values passed: the requester reads the slot, so a resumed request and one
|
|
230
|
+
-- answered before it yielded cannot disagree about arity.
|
|
231
|
+
if slot.Parked then
|
|
232
|
+
Sched.Resume(slot.Thread)
|
|
233
|
+
end
|
|
234
|
+
end
|
|
235
|
+
|
|
236
|
+
local function waitForLoaded()
|
|
237
|
+
while not loaded do
|
|
238
|
+
loadedSignal:Wait()
|
|
239
|
+
end
|
|
240
|
+
end
|
|
241
|
+
|
|
242
|
+
-- Frame handling ------------------------------------------------------------------
|
|
243
|
+
|
|
244
|
+
local helloSendFailLogged = false
|
|
245
|
+
local function sendHello()
|
|
246
|
+
if not transport then
|
|
247
|
+
return
|
|
248
|
+
end
|
|
249
|
+
local w = Wire.NewWriter(8)
|
|
250
|
+
Wire.U8(w, Wire.Frames.Hello)
|
|
251
|
+
Wire.U32(w, compiled.Hash % 4294967296)
|
|
252
|
+
Wire.U8(w, Wire.PROTOCOL_VERSION)
|
|
253
|
+
local ok, err = pcall(function()
|
|
254
|
+
transport:SendToServer(Wire.Finish(w))
|
|
255
|
+
end)
|
|
256
|
+
-- A dropped Hello leaves the client stuck at defaults, so surface the send error
|
|
257
|
+
-- once instead of retrying silently. A sandboxed calling thread fails here.
|
|
258
|
+
if not ok and not helloSendFailLogged then
|
|
259
|
+
helloSendFailLogged = true
|
|
260
|
+
Log.Warn("Transport", "SEND_FAIL", `client could not send its Hello handshake: {tostring(err)}`, {})
|
|
261
|
+
end
|
|
262
|
+
end
|
|
263
|
+
|
|
264
|
+
local function applyInit(reader: Wire.Reader)
|
|
265
|
+
local ops = Wire.DecodeOps(reader, compiled)
|
|
266
|
+
-- The snapshot supersedes local state: reset to defaults, then apply.
|
|
267
|
+
local defaults = Template.BuildDefaults(compiled, "Client")
|
|
268
|
+
-- Reset and apply inside ReplayFire so a re-Init's Changed listeners see their
|
|
269
|
+
-- true pre-snapshot value as `old`; ReplayFire snapshots olds before the closure,
|
|
270
|
+
-- so resetting outside it makes every `old` the default.
|
|
271
|
+
tree:ReplayFire(function()
|
|
272
|
+
table.clear(mirror)
|
|
273
|
+
for key, value in defaults do
|
|
274
|
+
mirror[key] = value
|
|
275
|
+
end
|
|
276
|
+
for _, op in ops do
|
|
277
|
+
tree:ApplyOp(op)
|
|
278
|
+
end
|
|
279
|
+
end)
|
|
280
|
+
-- Foreign mirrors are superseded too. sendInit re-sends a SharedInit for every
|
|
281
|
+
-- player still on the server right after this frame, so what does not come back
|
|
282
|
+
-- is what left; the only way a client that missed a SharedGone drops that ghost.
|
|
283
|
+
-- Cleared silently: a player who left and one whose SharedInit is a frame away
|
|
284
|
+
-- are indistinguishable here, so firing would report everyone gone and then back.
|
|
285
|
+
table.clear(sharedMirrors)
|
|
286
|
+
if not loaded then
|
|
287
|
+
loaded = true
|
|
288
|
+
loadedSignal:Fire()
|
|
289
|
+
end
|
|
290
|
+
Log.Debug("Replication", "INIT_APPLIED", "initial snapshot applied", {})
|
|
291
|
+
end
|
|
292
|
+
|
|
293
|
+
-- Fragment reassembly ------------------------------------------------------
|
|
294
|
+
--
|
|
295
|
+
-- The server splits any frame larger than its MaxOutboundBytes; everything below
|
|
296
|
+
-- this point sees only whole logical frames, so a snapshot still lands in one
|
|
297
|
+
-- ReplayFire. Not a security boundary: only the server can raise OnClientEvent on
|
|
298
|
+
-- the Down remote, which is also why the decoder below has no object budget. The
|
|
299
|
+
-- ceiling only stops a corrupted length field becoming a huge allocation.
|
|
300
|
+
local MAX_REASSEMBLY_BYTES = 64 * 1024 * 1024
|
|
301
|
+
local fragBuf: buffer? = nil
|
|
302
|
+
local fragSeq, fragTotal, fragWritten, fragExpected = -1, 0, 0, 0
|
|
303
|
+
-- Set whenever a fragment lands, cleared by the handshake retry loop: a Hello sent
|
|
304
|
+
-- mid-snapshot makes the server throw it away and re-encode the whole profile.
|
|
305
|
+
local fragProgress = false
|
|
306
|
+
|
|
307
|
+
local function resetFragments()
|
|
308
|
+
fragBuf, fragSeq, fragTotal, fragWritten, fragExpected = nil, -1, 0, 0, 0
|
|
309
|
+
end
|
|
310
|
+
|
|
311
|
+
-- Refusals are counted, not just dropped: a gap, a replayed piece or a forged
|
|
312
|
+
-- length is otherwise indistinguishable from an unfinished frame.
|
|
313
|
+
local function refuseFragment(reason: string): buffer?
|
|
314
|
+
resetFragments()
|
|
315
|
+
Metrics.Add("FragmentsRefused")
|
|
316
|
+
Log.Debug("Replication", "FRAGMENT_REFUSED", reason, {})
|
|
317
|
+
return nil
|
|
318
|
+
end
|
|
319
|
+
|
|
320
|
+
local function acceptFragment(bytes: buffer): buffer?
|
|
321
|
+
local size = buffer.len(bytes)
|
|
322
|
+
if size < Wire.FRAGMENT_HEADER then
|
|
323
|
+
return refuseFragment("fragment shorter than its header")
|
|
324
|
+
end
|
|
325
|
+
local seq = buffer.readu16(bytes, 1)
|
|
326
|
+
local declared = buffer.readu32(bytes, 3)
|
|
327
|
+
local index = buffer.readu16(bytes, 7)
|
|
328
|
+
local payload = size - Wire.FRAGMENT_HEADER
|
|
329
|
+
if index == 0 then
|
|
330
|
+
resetFragments()
|
|
331
|
+
if declared == 0 or payload == 0 then
|
|
332
|
+
return refuseFragment("empty fragment")
|
|
333
|
+
end
|
|
334
|
+
if declared > MAX_REASSEMBLY_BYTES then
|
|
335
|
+
return refuseFragment("declared length is not a plausible frame")
|
|
336
|
+
end
|
|
337
|
+
fragBuf, fragSeq, fragTotal, fragWritten, fragExpected = buffer.create(declared), seq, declared, 0, 0
|
|
338
|
+
end
|
|
339
|
+
local dest = fragBuf
|
|
340
|
+
if dest == nil then
|
|
341
|
+
-- Not an error and deliberately not counted: a fragment arriving with
|
|
342
|
+
-- nothing in flight is the tail of a frame whose head was lost.
|
|
343
|
+
return nil
|
|
344
|
+
end
|
|
345
|
+
if seq ~= fragSeq or index ~= fragExpected or declared ~= fragTotal or payload == 0 then
|
|
346
|
+
return refuseFragment("fragment does not continue the frame in progress")
|
|
347
|
+
end
|
|
348
|
+
if fragWritten + payload > fragTotal then
|
|
349
|
+
return refuseFragment("fragment overruns the declared length")
|
|
350
|
+
end
|
|
351
|
+
buffer.copy(dest, fragWritten, bytes, Wire.FRAGMENT_HEADER, payload)
|
|
352
|
+
fragWritten += payload
|
|
353
|
+
fragExpected += 1
|
|
354
|
+
fragProgress = true
|
|
355
|
+
if fragWritten < fragTotal then
|
|
356
|
+
return nil
|
|
357
|
+
end
|
|
358
|
+
resetFragments()
|
|
359
|
+
-- A reassembled frame is never itself a fragment; refusing it stops a malformed
|
|
360
|
+
-- stream re-entering the dispatcher without bound.
|
|
361
|
+
if buffer.readu8(dest, 0) == Wire.Frames.Fragment then
|
|
362
|
+
return refuseFragment("reassembled frame is itself a fragment")
|
|
363
|
+
end
|
|
364
|
+
Metrics.Add("FramesReassembled")
|
|
365
|
+
return dest
|
|
366
|
+
end
|
|
367
|
+
|
|
368
|
+
local function handleFrame(bytes: buffer)
|
|
369
|
+
local reader = Wire.NewReader(bytes)
|
|
370
|
+
local frameType = Wire.RU8(reader)
|
|
371
|
+
|
|
372
|
+
if frameType == Wire.Frames.Fragment then
|
|
373
|
+
local whole = acceptFragment(bytes)
|
|
374
|
+
if whole ~= nil then
|
|
375
|
+
handleFrame(whole)
|
|
376
|
+
end
|
|
377
|
+
return
|
|
378
|
+
end
|
|
379
|
+
|
|
380
|
+
-- The apply timers include the listeners a frame fires: what the update costs the device.
|
|
381
|
+
if frameType == Wire.Frames.Init then
|
|
382
|
+
local startedAt = Clock.Monotonic()
|
|
383
|
+
applyInit(reader)
|
|
384
|
+
Metrics.Observe("InitApplyDuration", Clock.Monotonic() - startedAt)
|
|
385
|
+
elseif frameType == Wire.Frames.Diff then
|
|
386
|
+
if not loaded then
|
|
387
|
+
-- Op before Init is a protocol error: request a re-Init.
|
|
388
|
+
Log.Warn("Replication", "OP_BEFORE_INIT", "diff arrived before Init; requesting re-Init", {})
|
|
389
|
+
sendHello()
|
|
390
|
+
return
|
|
391
|
+
end
|
|
392
|
+
local startedAt = Clock.Monotonic()
|
|
393
|
+
local ops = Wire.DecodeOps(reader, compiled)
|
|
394
|
+
-- Apply deadlines before values, keeping the whole frame in one batch.
|
|
395
|
+
local ordered: { Wire.Op }? = nil
|
|
396
|
+
for _, op in ops do
|
|
397
|
+
if op.Path[1] == Template.SESSION_ROOT and op.Path[2] == "Timed" then
|
|
398
|
+
if ordered == nil then
|
|
399
|
+
ordered = table.create(#ops)
|
|
400
|
+
end
|
|
401
|
+
table.insert(ordered, op)
|
|
402
|
+
end
|
|
403
|
+
end
|
|
404
|
+
if ordered ~= nil then
|
|
405
|
+
for _, op in ops do
|
|
406
|
+
if op.Path[1] ~= Template.SESSION_ROOT or op.Path[2] ~= "Timed" then
|
|
407
|
+
table.insert(ordered, op)
|
|
408
|
+
end
|
|
409
|
+
end
|
|
410
|
+
ops = ordered
|
|
411
|
+
end
|
|
412
|
+
tree:ApplyOps(ops)
|
|
413
|
+
Metrics.Add("DiffsApplied")
|
|
414
|
+
Metrics.Observe("DiffApplyDuration", Clock.Monotonic() - startedAt)
|
|
415
|
+
elseif frameType == Wire.Frames.CommandReply then
|
|
416
|
+
local correlation = Wire.RU32(reader)
|
|
417
|
+
local ok = Wire.RU8(reader) == 1
|
|
418
|
+
local count = Wire.RU8(reader)
|
|
419
|
+
local results = table.create(count)
|
|
420
|
+
for i = 1, count do
|
|
421
|
+
results[i] = Wire.DecodeGeneric(reader)
|
|
422
|
+
end
|
|
423
|
+
local slot = requestWaiters[correlation]
|
|
424
|
+
if slot then
|
|
425
|
+
if ok then
|
|
426
|
+
-- Transparent RPC: the handler's return values are the Request results,
|
|
427
|
+
-- handed over by reference with the frame's own count byte.
|
|
428
|
+
settleRequest(slot, results, count)
|
|
429
|
+
else
|
|
430
|
+
-- ok == 0: the framework refused, so results[1] is a sentinel and the
|
|
431
|
+
-- appended marker is what makes that distinguishable. The count is
|
|
432
|
+
-- spelled out because a malformed reply can leave results[1] nil.
|
|
433
|
+
settleRequest(slot, { false, results[1], Types.RequestFailed }, 3)
|
|
434
|
+
end
|
|
435
|
+
end
|
|
436
|
+
elseif frameType == Wire.Frames.Status then
|
|
437
|
+
local status = ID_TO_STATUS[Wire.RU8(reader)] or "Healthy"
|
|
438
|
+
Health.AdoptBroadcast(status :: any)
|
|
439
|
+
OnServiceStatus:Fire(status)
|
|
440
|
+
elseif frameType == Wire.Frames.SharedInit or frameType == Wire.Frames.SharedDiff then
|
|
441
|
+
local startedAt = Clock.Monotonic()
|
|
442
|
+
local userId = Wire.RF64(reader)
|
|
443
|
+
local ops = Wire.DecodeOps(reader, compiled)
|
|
444
|
+
local shared: { [string]: any } = sharedMirrors[userId] or {}
|
|
445
|
+
if frameType == Wire.Frames.SharedInit then
|
|
446
|
+
shared = {}
|
|
447
|
+
end
|
|
448
|
+
sharedMirrors[userId] = shared
|
|
449
|
+
for _, op in ops do
|
|
450
|
+
applyPlainOp(shared, op)
|
|
451
|
+
end
|
|
452
|
+
-- A Shared derived field the server did not send is computed per client, and
|
|
453
|
+
-- a foreign mirror is a plain table with no accessor tree. Recompute before
|
|
454
|
+
-- the change event so a listener never sees it without its derived fields.
|
|
455
|
+
DerivedModule.EvaluateInto(compiled, shared, isSharedLocalDerived)
|
|
456
|
+
-- One event per update carrying a clone of the shared data; nil is reserved
|
|
457
|
+
-- for SharedGone. CloneUnpack also converts packed datatype fields back to
|
|
458
|
+
-- the real datatype, so only pay for it when something is listening.
|
|
459
|
+
if OnSharedChanged:HasListeners() then
|
|
460
|
+
OnSharedChanged:Fire(userId, Node.CloneUnpack(compiled.Root, shared))
|
|
461
|
+
end
|
|
462
|
+
Metrics.Observe("SharedApplyDuration", Clock.Monotonic() - startedAt)
|
|
463
|
+
elseif frameType == Wire.Frames.SharedGone then
|
|
464
|
+
local userId = Wire.RF64(reader)
|
|
465
|
+
sharedMirrors[userId] = nil
|
|
466
|
+
OnSharedChanged:Fire(userId, nil)
|
|
467
|
+
elseif frameType == Wire.Frames.Leaderboard then
|
|
468
|
+
local name = Wire.RStr(reader)
|
|
469
|
+
local count = Wire.RU8(reader)
|
|
470
|
+
local entries = table.create(count)
|
|
471
|
+
for rank = 1, count do
|
|
472
|
+
local userId = Wire.RF64(reader)
|
|
473
|
+
local displayName = Wire.RStr(reader)
|
|
474
|
+
local score = Wire.RF64(reader)
|
|
475
|
+
table.insert(entries, { Rank = rank, UserId = userId, Name = displayName, Score = score })
|
|
476
|
+
end
|
|
477
|
+
local cache: { Entries: { any }, MyRank: number?, MyScore: number? } =
|
|
478
|
+
{ Entries = entries, MyRank = nil, MyScore = nil }
|
|
479
|
+
if Wire.RU8(reader) == 1 then
|
|
480
|
+
cache.MyRank = Wire.RVarint(reader)
|
|
481
|
+
cache.MyScore = Wire.RF64(reader)
|
|
482
|
+
end
|
|
483
|
+
leaderboardCache[name] = cache
|
|
484
|
+
OnLeaderboard:Fire(name, entries)
|
|
485
|
+
end
|
|
486
|
+
end
|
|
487
|
+
|
|
488
|
+
-- Studio-only, opt-in; attached before the transport connects so the Init frame is captured.
|
|
489
|
+
if isRunning and options.StudioHook == true and (options.IsClient == true or RunService:IsClient()) then
|
|
490
|
+
local hookOk, hookErr = pcall(function()
|
|
491
|
+
(require(script.DebugHook) :: any).Attach({
|
|
492
|
+
Compiled = compiled,
|
|
493
|
+
Mirror = mirror,
|
|
494
|
+
Tree = tree,
|
|
495
|
+
IsLoaded = function()
|
|
496
|
+
return loaded
|
|
497
|
+
end,
|
|
498
|
+
})
|
|
499
|
+
end)
|
|
500
|
+
if not hookOk then
|
|
501
|
+
Log.Warn("Lifecycle", "DEBUG_HOOK_FAIL", tostring(hookErr), {})
|
|
502
|
+
end
|
|
503
|
+
end
|
|
504
|
+
|
|
505
|
+
if isRunning then
|
|
506
|
+
Sched.Spawn(function()
|
|
507
|
+
local resolved = TransportModule.Resolve(options.Transport, options.TransportChannel)
|
|
508
|
+
transport = resolved
|
|
509
|
+
resolved:ListenClient(function(bytes: buffer)
|
|
510
|
+
local ok, err = pcall(handleFrame :: any, bytes)
|
|
511
|
+
if not ok then
|
|
512
|
+
Log.Warn("Transport", "MALFORMED_FRAME", tostring(err), {})
|
|
513
|
+
end
|
|
514
|
+
end)
|
|
515
|
+
-- Hello retries cover server-side races and adapters that connect late.
|
|
516
|
+
sendHello()
|
|
517
|
+
local delaySeconds = 2
|
|
518
|
+
while not loaded do
|
|
519
|
+
-- The retry delay only. The first sendHello stays immediate: delaying it
|
|
520
|
+
-- would slow every ordinary join to fix a problem only a mass rejoin has.
|
|
521
|
+
Clock.Wait(Rng.Jitter(delaySeconds))
|
|
522
|
+
if loaded or stopped then
|
|
523
|
+
break
|
|
524
|
+
end
|
|
525
|
+
if fragProgress then
|
|
526
|
+
-- A snapshot is arriving, one fragment at a time. Asking again is harmful:
|
|
527
|
+
-- the server answers a Hello by re-encoding the whole profile, so a large
|
|
528
|
+
-- Init would keep restarting. Clearing the flag keeps a stalled sequence
|
|
529
|
+
-- from blocking retries forever.
|
|
530
|
+
fragProgress = false
|
|
531
|
+
delaySeconds = 2
|
|
532
|
+
continue
|
|
533
|
+
end
|
|
534
|
+
sendHello()
|
|
535
|
+
delaySeconds = math.min(delaySeconds * 1.5, 10)
|
|
536
|
+
end
|
|
537
|
+
end)
|
|
538
|
+
end
|
|
539
|
+
|
|
540
|
+
-- Public API -----------------------------------------------------------------------
|
|
541
|
+
|
|
542
|
+
local Data = {} :: any
|
|
543
|
+
|
|
544
|
+
-- Reads snapshot readiness without yielding.
|
|
545
|
+
function Data.IsReady(): boolean
|
|
546
|
+
return loaded
|
|
547
|
+
end
|
|
548
|
+
|
|
549
|
+
-- Waits for the first snapshot, returning false on timeout.
|
|
550
|
+
function Data.WaitForData(timeout: number?): boolean
|
|
551
|
+
if loaded then
|
|
552
|
+
return true
|
|
553
|
+
end
|
|
554
|
+
local thread = coroutine.running()
|
|
555
|
+
local settled = false
|
|
556
|
+
local function resume(result: boolean)
|
|
557
|
+
if not settled then
|
|
558
|
+
settled = true
|
|
559
|
+
Sched.Resume(thread, result)
|
|
560
|
+
end
|
|
561
|
+
end
|
|
562
|
+
local conn = loadedSignal:Connect(function()
|
|
563
|
+
resume(true)
|
|
564
|
+
end)
|
|
565
|
+
Clock.Delay(timeout or Defaults.ClientWaitForData, function()
|
|
566
|
+
resume(false)
|
|
567
|
+
end)
|
|
568
|
+
local result = coroutine.yield()
|
|
569
|
+
conn:Disconnect()
|
|
570
|
+
return result
|
|
571
|
+
end
|
|
572
|
+
|
|
573
|
+
-- The body behind Request and RequestOnce. `idemKey` is nil for a plain request
|
|
574
|
+
-- and ships as an empty string, which the server reads as "no key", so a command
|
|
575
|
+
-- frame has one layout. `level` keeps the arity error pointing at the caller.
|
|
576
|
+
local function dispatchRequest(name: string, idemKey: string?, args: { n: number, [number]: any }, level: number)
|
|
577
|
+
if editMode then
|
|
578
|
+
local mock = mockCommands[name]
|
|
579
|
+
if mock then
|
|
580
|
+
local results
|
|
581
|
+
local ok = pcall(function()
|
|
582
|
+
results = table.pack(mock(table.unpack(args, 1, args.n)))
|
|
583
|
+
end)
|
|
584
|
+
if ok and results then
|
|
585
|
+
return table.unpack(results, 1, results.n)
|
|
586
|
+
end
|
|
587
|
+
return false, "mock-error", Types.RequestFailed
|
|
588
|
+
end
|
|
589
|
+
return false, "edit-mode", Types.RequestFailed
|
|
590
|
+
end
|
|
591
|
+
-- Fail loud rather than clamping: dropping the extras here would run the
|
|
592
|
+
-- handler with missing trailing arguments instead of the server's refusal.
|
|
593
|
+
if args.n > Wire.MAX_COMMAND_ARGS then
|
|
594
|
+
error(`Scribe: a command takes at most {Wire.MAX_COMMAND_ARGS} arguments (got {args.n})`, level)
|
|
595
|
+
end
|
|
596
|
+
-- No transport check here: waitForLoaded only returns once an Init frame arrived,
|
|
597
|
+
-- which requires the transport. A nil one still surfaces as "send-failed" below.
|
|
598
|
+
waitForLoaded()
|
|
599
|
+
nextCorrelation = (nextCorrelation + 1) % 4294967296
|
|
600
|
+
local correlation = nextCorrelation
|
|
601
|
+
local w = Wire.NewWriter(64)
|
|
602
|
+
Wire.U8(w, Wire.Frames.Command)
|
|
603
|
+
Wire.U32(w, correlation)
|
|
604
|
+
Wire.Str(w, name)
|
|
605
|
+
Wire.U8(w, args.n)
|
|
606
|
+
-- Ahead of the arguments, so the server can refuse an unusable key before it
|
|
607
|
+
-- decodes anything attacker-sized.
|
|
608
|
+
Wire.Str(w, idemKey or "")
|
|
609
|
+
for i = 1, args.n do
|
|
610
|
+
Wire.EncodeGeneric(w, args[i])
|
|
611
|
+
end
|
|
612
|
+
|
|
613
|
+
local slot: RequestSlot = {
|
|
614
|
+
Correlation = correlation,
|
|
615
|
+
Thread = coroutine.running(),
|
|
616
|
+
Parked = false,
|
|
617
|
+
Settled = false,
|
|
618
|
+
Results = NO_RESULTS,
|
|
619
|
+
Count = 0,
|
|
620
|
+
}
|
|
621
|
+
requestWaiters[correlation] = slot
|
|
622
|
+
-- Armed before the send so the deadline covers the send itself, which matters if
|
|
623
|
+
-- the spawn below ever goes. Clock.Delay cannot be cancelled, so the callback
|
|
624
|
+
-- always fires and settleRequest is what makes a late one a no-op.
|
|
625
|
+
Clock.Delay(options.RequestTimeout or Defaults.Request, function()
|
|
626
|
+
if not slot.Settled then
|
|
627
|
+
Metrics.Add("RequestTimeouts")
|
|
628
|
+
Metrics.Add(timeoutMetric(name))
|
|
629
|
+
end
|
|
630
|
+
settleRequest(slot, { false, "timeout", Types.RequestFailed }, 3)
|
|
631
|
+
end)
|
|
632
|
+
-- Spawned, not deferred. Sched.Spawn runs the send immediately on this stack, so
|
|
633
|
+
-- a synchronous loopback closes the round trip before this line returns and the
|
|
634
|
+
-- requester never parks. A Sched.Defer would put the reply's resume inside a
|
|
635
|
+
-- deferred callback, promoting the requester one re-entrancy generation per round
|
|
636
|
+
-- trip until it hangs. The spawn also means a SendToServer that never returns
|
|
637
|
+
-- hangs its own coroutine, so the timeout can still answer.
|
|
638
|
+
local bytes = Wire.Finish(w)
|
|
639
|
+
Sched.Spawn(function()
|
|
640
|
+
local ok = pcall(function()
|
|
641
|
+
transport:SendToServer(bytes)
|
|
642
|
+
end)
|
|
643
|
+
if not ok then
|
|
644
|
+
-- Reached synchronously for a throwing send, so the requester is still
|
|
645
|
+
-- running and this records rather than resumes.
|
|
646
|
+
settleRequest(slot, { false, "send-failed", Types.RequestFailed }, 3)
|
|
647
|
+
end
|
|
648
|
+
end)
|
|
649
|
+
-- A loop rather than an `if`, so a stray resume from outside Scribe re-parks
|
|
650
|
+
-- instead of returning an unsettled slot; the timeout above always arrives.
|
|
651
|
+
while not slot.Settled do
|
|
652
|
+
slot.Parked = true
|
|
653
|
+
coroutine.yield()
|
|
654
|
+
slot.Parked = false
|
|
655
|
+
end
|
|
656
|
+
return table.unpack(slot.Results, 1, slot.Count)
|
|
657
|
+
end
|
|
658
|
+
|
|
659
|
+
-- Sends a command to the server and waits for its reply.
|
|
660
|
+
function Data.Request(name: string, ...: any): ...any
|
|
661
|
+
return dispatchRequest(name, nil, table.pack(...), 3)
|
|
662
|
+
end
|
|
663
|
+
|
|
664
|
+
-- Sends a keyed command so retries reuse the server's original result.
|
|
665
|
+
function Data.RequestOnce(name: string, key: string, ...: any): ...any
|
|
666
|
+
-- Rejected here rather than at the server: an unusable key is a caller mistake,
|
|
667
|
+
-- and a round trip would return it looking like a genuine handler refusal.
|
|
668
|
+
if type(key) ~= "string" or key == "" or #key > Wire.MAX_IDEMPOTENCY_KEY_BYTES or not utf8.len(key) then
|
|
669
|
+
error(
|
|
670
|
+
`Scribe: RequestOnce needs a non-empty idempotency key of at most `
|
|
671
|
+
.. `{Wire.MAX_IDEMPOTENCY_KEY_BYTES} valid UTF-8 bytes`,
|
|
672
|
+
2
|
|
673
|
+
)
|
|
674
|
+
end
|
|
675
|
+
return dispatchRequest(name, key, table.pack(...), 3)
|
|
676
|
+
end
|
|
677
|
+
|
|
678
|
+
-- Reads the replicated leaderboard cache without requesting a refresh.
|
|
679
|
+
function Data.GetLeaderboard(name: string, limit: number?): { any }
|
|
680
|
+
if editMode then
|
|
681
|
+
local mocked = mockLeaderboards[name]
|
|
682
|
+
return if mocked then Util.deepClone(mocked) else {}
|
|
683
|
+
end
|
|
684
|
+
local cache = leaderboardCache[name]
|
|
685
|
+
if not cache then
|
|
686
|
+
return {}
|
|
687
|
+
end
|
|
688
|
+
local out = {}
|
|
689
|
+
for i = 1, math.min(limit or #cache.Entries, #cache.Entries) do
|
|
690
|
+
table.insert(out, table.clone(cache.Entries[i]))
|
|
691
|
+
end
|
|
692
|
+
return out
|
|
693
|
+
end
|
|
694
|
+
|
|
695
|
+
-- Finds the local player's rank in the replicated board.
|
|
696
|
+
function Data.GetMyRank(name: string): number?
|
|
697
|
+
local cache = leaderboardCache[name]
|
|
698
|
+
return if cache then cache.MyRank else nil
|
|
699
|
+
end
|
|
700
|
+
|
|
701
|
+
-- Fires when a replicated leaderboard changes.
|
|
702
|
+
Data.OnLeaderboard = OnLeaderboard
|
|
703
|
+
|
|
704
|
+
-- Reads the replicated data-service health.
|
|
705
|
+
function Data.GetServiceStatus(): string
|
|
706
|
+
return Health.GetStatus()
|
|
707
|
+
end
|
|
708
|
+
|
|
709
|
+
-- Fires when the replicated service health changes.
|
|
710
|
+
Data.OnServiceStatus = OnServiceStatus
|
|
711
|
+
|
|
712
|
+
-- Reads another player's replicated Shared roots.
|
|
713
|
+
function Data.GetShared(playerOrUserId: Player | number): { [string]: any }?
|
|
714
|
+
local userId = if typeof(playerOrUserId) == "Instance"
|
|
715
|
+
then (playerOrUserId :: Player).UserId
|
|
716
|
+
else playerOrUserId :: number
|
|
717
|
+
local shared = sharedMirrors[userId]
|
|
718
|
+
-- CloneUnpack converts packed datatype buffers (wire form) back to the real
|
|
719
|
+
-- datatype; the Shared mirror has no accessor tree to do it on read.
|
|
720
|
+
return if shared then Node.CloneUnpack(compiled.Root, shared) else nil
|
|
721
|
+
end
|
|
722
|
+
|
|
723
|
+
-- Fires when another player's Shared data changes.
|
|
724
|
+
Data.OnSharedChanged = OnSharedChanged
|
|
725
|
+
-- Fires for ownership changes after the initial baseline.
|
|
726
|
+
Data.OnOwnershipChanged = OnOwnershipChanged
|
|
727
|
+
|
|
728
|
+
-- Ownership: reads the replicated mirror.
|
|
729
|
+
-- Client twin of the server's check. Without it a non-string key reads as "not owned"
|
|
730
|
+
-- off a nil table index, so a typo is indistinguishable from a player who owns nothing.
|
|
731
|
+
local function assertOwnsKey(key: any, what: string)
|
|
732
|
+
if type(key) ~= "string" then
|
|
733
|
+
-- 3: assertOwnsKey -> Data.<Api> -> the game code that got it wrong.
|
|
734
|
+
error(`Scribe: {what}: key must be a string, got {typeof(key)}`, 3)
|
|
735
|
+
end
|
|
736
|
+
end
|
|
737
|
+
|
|
738
|
+
local function ownsFromMirror(key: string): boolean
|
|
739
|
+
local reserved = mirror[Template.RESERVED_ROOT]
|
|
740
|
+
if type(reserved) == "table" and type(reserved.Perks) == "table" and reserved.Perks[key] == true then
|
|
741
|
+
return true
|
|
742
|
+
end
|
|
743
|
+
local session = mirror[Template.SESSION_ROOT]
|
|
744
|
+
if type(session) == "table" and type(session.OwnsCache) == "table" and session.OwnsCache[key] == true then
|
|
745
|
+
return true
|
|
746
|
+
end
|
|
747
|
+
return false
|
|
748
|
+
end
|
|
749
|
+
|
|
750
|
+
-- Reads mirrored ownership after the profile loads.
|
|
751
|
+
function Data.Owns(key: string): boolean
|
|
752
|
+
assertOwnsKey(key, "Owns")
|
|
753
|
+
if not editMode then
|
|
754
|
+
waitForLoaded()
|
|
755
|
+
end
|
|
756
|
+
return ownsFromMirror(key)
|
|
757
|
+
end
|
|
758
|
+
|
|
759
|
+
local function ownsSyncedFromMirror(): boolean
|
|
760
|
+
local session = mirror[Template.SESSION_ROOT]
|
|
761
|
+
return type(session) == "table" and session.OwnsSynced == true
|
|
762
|
+
end
|
|
763
|
+
|
|
764
|
+
-- Waits for the server's initial ownership sync before reading the mirror.
|
|
765
|
+
function Data.OwnsAsync(key: string, timeout: number?): boolean
|
|
766
|
+
assertOwnsKey(key, "OwnsAsync")
|
|
767
|
+
if editMode then
|
|
768
|
+
return ownsFromMirror(key)
|
|
769
|
+
end
|
|
770
|
+
waitForLoaded()
|
|
771
|
+
if not ownsSyncedFromMirror() then
|
|
772
|
+
local thread = coroutine.running()
|
|
773
|
+
local settled = false
|
|
774
|
+
local disconnect: (() -> ())? = nil
|
|
775
|
+
local function wake()
|
|
776
|
+
if not settled then
|
|
777
|
+
settled = true
|
|
778
|
+
if disconnect then
|
|
779
|
+
disconnect()
|
|
780
|
+
end
|
|
781
|
+
Sched.Resume(thread)
|
|
782
|
+
end
|
|
783
|
+
end
|
|
784
|
+
disconnect = tree.Accessor[Template.SESSION_ROOT].OwnsSynced.Changed(function(v)
|
|
785
|
+
if v == true then
|
|
786
|
+
wake()
|
|
787
|
+
end
|
|
788
|
+
end) :: () -> ()
|
|
789
|
+
Clock.Delay(timeout or Defaults.OwnsAsync, wake)
|
|
790
|
+
-- If the flag arrived between the check and the connect, clean up and skip
|
|
791
|
+
-- the yield: never task.spawn a thread that has not yielded.
|
|
792
|
+
if ownsSyncedFromMirror() then
|
|
793
|
+
settled = true
|
|
794
|
+
if disconnect then
|
|
795
|
+
disconnect()
|
|
796
|
+
end
|
|
797
|
+
else
|
|
798
|
+
coroutine.yield()
|
|
799
|
+
end
|
|
800
|
+
end
|
|
801
|
+
return ownsFromMirror(key)
|
|
802
|
+
end
|
|
803
|
+
|
|
804
|
+
-- Drives OnOwnershipChanged. Dedupes like ObserveOwned, but across every key the
|
|
805
|
+
-- mirror holds, so a listener does not have to know keys up front.
|
|
806
|
+
local ownsLast: { [string]: boolean } = {}
|
|
807
|
+
local ownsWatched = false
|
|
808
|
+
local function scanOwnership(silent: boolean?)
|
|
809
|
+
local candidates: { [string]: boolean } = {}
|
|
810
|
+
local reserved = mirror[Template.RESERVED_ROOT]
|
|
811
|
+
if type(reserved) == "table" and type(reserved.Perks) == "table" then
|
|
812
|
+
for key in reserved.Perks do
|
|
813
|
+
candidates[key] = true
|
|
814
|
+
end
|
|
815
|
+
end
|
|
816
|
+
local session = mirror[Template.SESSION_ROOT]
|
|
817
|
+
if type(session) == "table" and type(session.OwnsCache) == "table" then
|
|
818
|
+
for key in session.OwnsCache do
|
|
819
|
+
candidates[key] = true
|
|
820
|
+
end
|
|
821
|
+
end
|
|
822
|
+
-- Keys that went away still need a false transition.
|
|
823
|
+
for key in ownsLast do
|
|
824
|
+
candidates[key] = true
|
|
825
|
+
end
|
|
826
|
+
for key in candidates do
|
|
827
|
+
local owned = ownsFromMirror(key)
|
|
828
|
+
if owned ~= (ownsLast[key] == true) then
|
|
829
|
+
ownsLast[key] = owned
|
|
830
|
+
if not silent then
|
|
831
|
+
OnOwnershipChanged:Fire(key, owned)
|
|
832
|
+
end
|
|
833
|
+
end
|
|
834
|
+
end
|
|
835
|
+
end
|
|
836
|
+
-- Attached lazily on first subscribe: a game that never listens pays nothing.
|
|
837
|
+
local function ensureOwnershipWatched()
|
|
838
|
+
if ownsWatched or editMode then
|
|
839
|
+
return
|
|
840
|
+
end
|
|
841
|
+
ownsWatched = true
|
|
842
|
+
waitForLoaded()
|
|
843
|
+
scanOwnership(true) -- baseline: current ownership is not a "change"
|
|
844
|
+
local accessor = tree.Accessor
|
|
845
|
+
-- Through the privileged handle, not the public child: a public read of the
|
|
846
|
+
-- reserved root hands back a detached deep copy (readOut in Node.luau).
|
|
847
|
+
tree.Reserved.Perks.Changed(function()
|
|
848
|
+
scanOwnership()
|
|
849
|
+
end)
|
|
850
|
+
accessor[Template.SESSION_ROOT].OwnsCache.Changed(function()
|
|
851
|
+
scanOwnership()
|
|
852
|
+
end)
|
|
853
|
+
end
|
|
854
|
+
|
|
855
|
+
-- Reports current ownership and later changes; returns a disconnect.
|
|
856
|
+
function Data.ObserveOwned(key: string, callback: (owned: boolean) -> ()): () -> ()
|
|
857
|
+
assertOwnsKey(key, "ObserveOwned")
|
|
858
|
+
if not editMode then
|
|
859
|
+
waitForLoaded()
|
|
860
|
+
end
|
|
861
|
+
local last: boolean? = nil
|
|
862
|
+
local function push()
|
|
863
|
+
local owned = ownsFromMirror(key)
|
|
864
|
+
if owned ~= last then
|
|
865
|
+
last = owned
|
|
866
|
+
Sched.Spawn(callback, owned)
|
|
867
|
+
end
|
|
868
|
+
end
|
|
869
|
+
local accessor = tree.Accessor
|
|
870
|
+
-- Privileged handle: see the note in ensureOwnershipWatched.
|
|
871
|
+
local disconnectPerk = tree.Reserved.Perks.Changed(push)
|
|
872
|
+
local disconnectCache = accessor[Template.SESSION_ROOT].OwnsCache.Changed(push)
|
|
873
|
+
push()
|
|
874
|
+
return function()
|
|
875
|
+
disconnectPerk()
|
|
876
|
+
disconnectCache()
|
|
877
|
+
end
|
|
878
|
+
end
|
|
879
|
+
|
|
880
|
+
-- Product info --------------------------------------------------------------
|
|
881
|
+
--
|
|
882
|
+
-- Client-side by necessity: a live server has no player in context, so its
|
|
883
|
+
-- GetProductInfoAsync answers the base catalog price, which is the one number a
|
|
884
|
+
-- discounted player never pays. Studio servers DO answer personalized, so the
|
|
885
|
+
-- server version tests clean and ships broken.
|
|
886
|
+
--
|
|
887
|
+
-- Lazy throughout: a bundle that never asks for a price pays nothing.
|
|
888
|
+
|
|
889
|
+
-- Overridable because patching a real service Instance is illegal, the same seam
|
|
890
|
+
-- as the server's UserOwnsGamePassAsync.
|
|
891
|
+
local getProductInfoAsync: (assetId: number, infoType: any) -> any = options.GetProductInfoAsync
|
|
892
|
+
or function(assetId: number, infoType: any): any
|
|
893
|
+
local marketplace: any = game:GetService("MarketplaceService")
|
|
894
|
+
return marketplace:GetProductInfoAsync(assetId, infoType)
|
|
895
|
+
end
|
|
896
|
+
local getPolicyInfoAsync: (player: any) -> any = options.GetPolicyInfoAsync
|
|
897
|
+
or function(player: any): any
|
|
898
|
+
return (game:GetService("PolicyService") :: any):GetPolicyInfoForPlayerAsync(player)
|
|
899
|
+
end
|
|
900
|
+
|
|
901
|
+
-- Distinct from nil, so an observer's first push fires while nothing is resolved.
|
|
902
|
+
local UNRESOLVED: any = table.freeze({})
|
|
903
|
+
local PRODUCT_ATTEMPTS = 4
|
|
904
|
+
local PRODUCT_RETRY_BASE = 2
|
|
905
|
+
|
|
906
|
+
local productAssets: { [string]: { Id: number, InfoType: any } }? = nil
|
|
907
|
+
local productInfo: { [string]: any } = {}
|
|
908
|
+
local productWaiters: { [string]: { { Thread: thread, Settled: boolean } } } = {}
|
|
909
|
+
local productObservers: { [string]: { () -> () } } = {}
|
|
910
|
+
local productQueue: { string } = {}
|
|
911
|
+
local productQueued: { [string]: boolean } = {}
|
|
912
|
+
local productFlushScheduled = false
|
|
913
|
+
local membershipWatched = false
|
|
914
|
+
local membershipConnection: any = nil
|
|
915
|
+
|
|
916
|
+
-- Every declared pass and product, built on first use.
|
|
917
|
+
local function ensureProductAssets(): { [string]: { Id: number, InfoType: any } }
|
|
918
|
+
if productAssets == nil then
|
|
919
|
+
local built: { [string]: { Id: number, InfoType: any } } = {}
|
|
920
|
+
for passName, config in (options.Passes or {}) :: { [string]: any } do
|
|
921
|
+
built[passName] = { Id = config.Id, InfoType = Enum.InfoType.GamePass }
|
|
922
|
+
end
|
|
923
|
+
-- The server refuses a product named like a pass, so one namespace is enough.
|
|
924
|
+
for productName, config in (options.Products or {}) :: { [string]: any } do
|
|
925
|
+
built[productName] = { Id = config.Id, InfoType = Enum.InfoType.Product }
|
|
926
|
+
end
|
|
927
|
+
productAssets = built
|
|
928
|
+
end
|
|
929
|
+
return productAssets :: any
|
|
930
|
+
end
|
|
931
|
+
|
|
932
|
+
-- The declared pass or product, or a raise naming the key.
|
|
933
|
+
local function productAsset(name: string, api: string): { Id: number, InfoType: any }
|
|
934
|
+
local asset = ensureProductAssets()[name]
|
|
935
|
+
if asset == nil then
|
|
936
|
+
-- 3: productAsset -> Data.<Api> -> the game code that got it wrong.
|
|
937
|
+
error(`Scribe.{api}: "{tostring(name)}" is not a declared pass or product`, 3)
|
|
938
|
+
end
|
|
939
|
+
return asset
|
|
940
|
+
end
|
|
941
|
+
|
|
942
|
+
local function notifyProduct(name: string)
|
|
943
|
+
if stopped then
|
|
944
|
+
return
|
|
945
|
+
end
|
|
946
|
+
local observers = productObservers[name]
|
|
947
|
+
if observers == nil then
|
|
948
|
+
return
|
|
949
|
+
end
|
|
950
|
+
-- Cloned: a callback may disconnect itself, which mutates the list.
|
|
951
|
+
for _, push in table.clone(observers) do
|
|
952
|
+
push()
|
|
953
|
+
end
|
|
954
|
+
end
|
|
955
|
+
|
|
956
|
+
local function settleProduct(name: string, info: any)
|
|
957
|
+
if stopped then
|
|
958
|
+
return
|
|
959
|
+
end
|
|
960
|
+
productQueued[name] = nil
|
|
961
|
+
if info ~= nil then
|
|
962
|
+
productInfo[name] = info
|
|
963
|
+
end
|
|
964
|
+
local waiters = productWaiters[name]
|
|
965
|
+
productWaiters[name] = nil
|
|
966
|
+
if waiters ~= nil then
|
|
967
|
+
for _, waiter in waiters do
|
|
968
|
+
-- Settled is the discriminator, not coroutine status: a caller that timed
|
|
969
|
+
-- out and then parked on something else is also "suspended", and resuming
|
|
970
|
+
-- it here wakes it out of an unrelated wait.
|
|
971
|
+
if not waiter.Settled then
|
|
972
|
+
waiter.Settled = true
|
|
973
|
+
-- Directly: a wake must never travel the defer queue.
|
|
974
|
+
Sched.Resume(waiter.Thread, if stopped then nil else info)
|
|
975
|
+
end
|
|
976
|
+
end
|
|
977
|
+
end
|
|
978
|
+
notifyProduct(name)
|
|
979
|
+
end
|
|
980
|
+
|
|
981
|
+
local function fetchProduct(name: string)
|
|
982
|
+
local asset = if productAssets ~= nil then (productAssets :: any)[name] else nil
|
|
983
|
+
if asset == nil then
|
|
984
|
+
return
|
|
985
|
+
end
|
|
986
|
+
for attempt = 1, PRODUCT_ATTEMPTS do
|
|
987
|
+
if stopped then
|
|
988
|
+
return
|
|
989
|
+
end
|
|
990
|
+
local ok, result = pcall(getProductInfoAsync, asset.Id, asset.InfoType)
|
|
991
|
+
if stopped then
|
|
992
|
+
return
|
|
993
|
+
end
|
|
994
|
+
if ok and type(result) == "table" then
|
|
995
|
+
settleProduct(name, result)
|
|
996
|
+
return
|
|
997
|
+
end
|
|
998
|
+
if attempt == PRODUCT_ATTEMPTS then
|
|
999
|
+
Log.Warn(
|
|
1000
|
+
"Monetization",
|
|
1001
|
+
"PRODUCT_INFO_FAIL",
|
|
1002
|
+
`could not read product info for "{name}": {tostring(result)}`,
|
|
1003
|
+
{ Product = name }
|
|
1004
|
+
)
|
|
1005
|
+
-- Never the base price: nil means "show a placeholder".
|
|
1006
|
+
settleProduct(name, nil)
|
|
1007
|
+
return
|
|
1008
|
+
end
|
|
1009
|
+
Log.Warn(
|
|
1010
|
+
"Monetization",
|
|
1011
|
+
"PRODUCT_INFO_THROTTLED",
|
|
1012
|
+
`product info for "{name}" failed, retrying ({attempt}/{PRODUCT_ATTEMPTS})`,
|
|
1013
|
+
{ Product = name }
|
|
1014
|
+
)
|
|
1015
|
+
Clock.Wait(Rng.Jitter(PRODUCT_RETRY_BASE * 2 ^ (attempt - 1)))
|
|
1016
|
+
end
|
|
1017
|
+
end
|
|
1018
|
+
|
|
1019
|
+
local function flushProductQueue()
|
|
1020
|
+
productFlushScheduled = false
|
|
1021
|
+
if stopped then
|
|
1022
|
+
return
|
|
1023
|
+
end
|
|
1024
|
+
local batch = productQueue
|
|
1025
|
+
productQueue = {}
|
|
1026
|
+
-- Together on purpose: the engine only coalesces calls in flight at the same
|
|
1027
|
+
-- time, so one burst costs one request where N singles cost N.
|
|
1028
|
+
for _, name in batch do
|
|
1029
|
+
if stopped then
|
|
1030
|
+
break
|
|
1031
|
+
end
|
|
1032
|
+
Sched.Spawn(fetchProduct, name)
|
|
1033
|
+
end
|
|
1034
|
+
end
|
|
1035
|
+
|
|
1036
|
+
local function enqueueProduct(name: string)
|
|
1037
|
+
if stopped or productInfo[name] ~= nil or productQueued[name] then
|
|
1038
|
+
return
|
|
1039
|
+
end
|
|
1040
|
+
productQueued[name] = true
|
|
1041
|
+
table.insert(productQueue, name)
|
|
1042
|
+
if not productFlushScheduled then
|
|
1043
|
+
productFlushScheduled = true
|
|
1044
|
+
Sched.Defer(flushProductQueue)
|
|
1045
|
+
end
|
|
1046
|
+
end
|
|
1047
|
+
|
|
1048
|
+
-- Observers hear about the new value landing, not the old one being dropped, so a
|
|
1049
|
+
-- successful refresh does not blink the price to nil.
|
|
1050
|
+
local function refreshProduct(name: string?)
|
|
1051
|
+
if stopped then
|
|
1052
|
+
return
|
|
1053
|
+
end
|
|
1054
|
+
local names: { string } = {}
|
|
1055
|
+
if name ~= nil then
|
|
1056
|
+
names[1] = name
|
|
1057
|
+
else
|
|
1058
|
+
for cached in productInfo do
|
|
1059
|
+
table.insert(names, cached)
|
|
1060
|
+
end
|
|
1061
|
+
end
|
|
1062
|
+
for _, each in names do
|
|
1063
|
+
productInfo[each] = nil
|
|
1064
|
+
enqueueProduct(each)
|
|
1065
|
+
end
|
|
1066
|
+
end
|
|
1067
|
+
|
|
1068
|
+
-- A Roblox Plus discount moves the price, leaving the cached one wrong for the rest
|
|
1069
|
+
-- of the session. Armed on first use, and one-shot: the flag flips at most once in a
|
|
1070
|
+
-- session. The 10% to 20% step at month three does not move it at all, which is what
|
|
1071
|
+
-- RefreshProductInfo is for.
|
|
1072
|
+
--
|
|
1073
|
+
-- The signal is on the PLAYER. Asking the Players service for it raises, and the
|
|
1074
|
+
-- pcall would swallow that into a watch that silently never fires.
|
|
1075
|
+
local function watchMembership()
|
|
1076
|
+
if stopped or membershipWatched then
|
|
1077
|
+
return
|
|
1078
|
+
end
|
|
1079
|
+
-- Left unarmed while there is no LocalPlayer, so the next read retries.
|
|
1080
|
+
membershipWatched = pcall(function()
|
|
1081
|
+
local localPlayer: any = readLocalPlayer()
|
|
1082
|
+
membershipConnection = localPlayer:GetPropertyChangedSignal("HasRobloxSubscription"):Once(function()
|
|
1083
|
+
refreshProduct(nil)
|
|
1084
|
+
end)
|
|
1085
|
+
end)
|
|
1086
|
+
end
|
|
1087
|
+
|
|
1088
|
+
-- Paid random items. The server enforces; this greys the button, so unknown
|
|
1089
|
+
-- reads as pending.
|
|
1090
|
+
local POLICY_ATTEMPTS = 3
|
|
1091
|
+
local POLICY_RETRY_BASE = 2
|
|
1092
|
+
local POLICY_REARM_AFTER = 30
|
|
1093
|
+
local policy: any = nil
|
|
1094
|
+
local policyObservers: { () -> () } = {}
|
|
1095
|
+
|
|
1096
|
+
local function anyPaidRandom(): boolean
|
|
1097
|
+
for _, config in (options.Products or {}) :: { [string]: any } do
|
|
1098
|
+
if config.PaidRandom == true then
|
|
1099
|
+
return true
|
|
1100
|
+
end
|
|
1101
|
+
end
|
|
1102
|
+
return false
|
|
1103
|
+
end
|
|
1104
|
+
|
|
1105
|
+
local function notifyPolicy()
|
|
1106
|
+
for _, push in table.clone(policyObservers) do
|
|
1107
|
+
push()
|
|
1108
|
+
end
|
|
1109
|
+
end
|
|
1110
|
+
|
|
1111
|
+
local function readPolicy(attempts: number)
|
|
1112
|
+
local mine = policy
|
|
1113
|
+
for attempt = 1, attempts do
|
|
1114
|
+
if policy ~= mine or stopped then
|
|
1115
|
+
return
|
|
1116
|
+
end
|
|
1117
|
+
mine.LastAttempt = Clock.Monotonic()
|
|
1118
|
+
local ok, info = pcall(function()
|
|
1119
|
+
return getPolicyInfoAsync(readLocalPlayer())
|
|
1120
|
+
end)
|
|
1121
|
+
if policy ~= mine or stopped then
|
|
1122
|
+
return
|
|
1123
|
+
end
|
|
1124
|
+
if ok and type(info) == "table" then
|
|
1125
|
+
mine.Restricted = info.ArePaidRandomItemsRestricted == true
|
|
1126
|
+
mine.Phase = "known"
|
|
1127
|
+
notifyPolicy()
|
|
1128
|
+
return
|
|
1129
|
+
end
|
|
1130
|
+
if attempt == attempts then
|
|
1131
|
+
mine.Phase = "failed"
|
|
1132
|
+
if not mine.Logged then
|
|
1133
|
+
mine.Logged = true
|
|
1134
|
+
Log.Warn(
|
|
1135
|
+
"Monetization",
|
|
1136
|
+
"POLICY_READ_FAIL",
|
|
1137
|
+
`could not read the local player's policy: {tostring(info)}; paid random items stay pending`,
|
|
1138
|
+
{}
|
|
1139
|
+
)
|
|
1140
|
+
end
|
|
1141
|
+
return
|
|
1142
|
+
end
|
|
1143
|
+
Clock.Wait(Rng.Jitter(POLICY_RETRY_BASE * 2 ^ (attempt - 1)))
|
|
1144
|
+
end
|
|
1145
|
+
end
|
|
1146
|
+
|
|
1147
|
+
local function ensurePolicy(): any
|
|
1148
|
+
if policy == nil then
|
|
1149
|
+
policy = { Phase = "pending", Restricted = false, LastAttempt = 0, Logged = false }
|
|
1150
|
+
Sched.Spawn(readPolicy, POLICY_ATTEMPTS)
|
|
1151
|
+
elseif policy.Phase == "failed" and Clock.Monotonic() - policy.LastAttempt >= POLICY_REARM_AFTER then
|
|
1152
|
+
policy.Phase = "pending"
|
|
1153
|
+
Sched.Spawn(readPolicy, 1)
|
|
1154
|
+
end
|
|
1155
|
+
return policy
|
|
1156
|
+
end
|
|
1157
|
+
|
|
1158
|
+
-- nil when the local player may buy paid random items.
|
|
1159
|
+
local function paidRandomState(): string?
|
|
1160
|
+
local current = ensurePolicy()
|
|
1161
|
+
if current.Phase == "known" then
|
|
1162
|
+
return if current.Restricted then "paid-random-restricted" else nil
|
|
1163
|
+
end
|
|
1164
|
+
return "policy-pending"
|
|
1165
|
+
end
|
|
1166
|
+
|
|
1167
|
+
-- The same answer the server gives, from the mirror and the local policy.
|
|
1168
|
+
local function productStateFor(name: string): string
|
|
1169
|
+
if not loaded then
|
|
1170
|
+
return "not-loaded"
|
|
1171
|
+
end
|
|
1172
|
+
local products: any = options.Products or {}
|
|
1173
|
+
local passes: any = options.Passes or {}
|
|
1174
|
+
local config: any = products[name] or passes[name]
|
|
1175
|
+
if products[name] ~= nil and config.PaidRandom == true then
|
|
1176
|
+
local refused = paidRandomState()
|
|
1177
|
+
if refused ~= nil then
|
|
1178
|
+
return refused
|
|
1179
|
+
end
|
|
1180
|
+
end
|
|
1181
|
+
local ownedKey = if products[name] ~= nil then config.Grants else name
|
|
1182
|
+
if ownedKey ~= nil and ownsFromMirror(ownedKey) then
|
|
1183
|
+
return "owned"
|
|
1184
|
+
end
|
|
1185
|
+
return "purchasable"
|
|
1186
|
+
end
|
|
1187
|
+
|
|
1188
|
+
-- Reads cached player-specific marketplace info, fetching on demand.
|
|
1189
|
+
function Data.GetProductInfo(name: string): { [string]: any }?
|
|
1190
|
+
productAsset(name, "GetProductInfo")
|
|
1191
|
+
if stopped then
|
|
1192
|
+
return nil
|
|
1193
|
+
end
|
|
1194
|
+
watchMembership()
|
|
1195
|
+
enqueueProduct(name)
|
|
1196
|
+
return productInfo[name]
|
|
1197
|
+
end
|
|
1198
|
+
|
|
1199
|
+
-- Reads the local player's cached Robux price, or nil while loading.
|
|
1200
|
+
function Data.GetPrice(name: string): number?
|
|
1201
|
+
local info = Data.GetProductInfo(name)
|
|
1202
|
+
local price = if info ~= nil then info.PriceInRobux else nil
|
|
1203
|
+
return if type(price) == "number" then price else nil
|
|
1204
|
+
end
|
|
1205
|
+
|
|
1206
|
+
-- Waits for marketplace info, returning nil on timeout or failure.
|
|
1207
|
+
function Data.GetProductInfoAsync(name: string, timeout: number?): { [string]: any }?
|
|
1208
|
+
productAsset(name, "GetProductInfoAsync")
|
|
1209
|
+
if stopped then
|
|
1210
|
+
return nil
|
|
1211
|
+
end
|
|
1212
|
+
watchMembership()
|
|
1213
|
+
local cached = productInfo[name]
|
|
1214
|
+
if cached ~= nil then
|
|
1215
|
+
return cached
|
|
1216
|
+
end
|
|
1217
|
+
enqueueProduct(name)
|
|
1218
|
+
-- Re-checked before parking: a queue that ever resolved synchronously would
|
|
1219
|
+
-- leave this thread in the waiter list with nobody left to wake it.
|
|
1220
|
+
local resolved = productInfo[name]
|
|
1221
|
+
if resolved ~= nil then
|
|
1222
|
+
return resolved
|
|
1223
|
+
end
|
|
1224
|
+
local waiters = productWaiters[name]
|
|
1225
|
+
if waiters == nil then
|
|
1226
|
+
waiters = {}
|
|
1227
|
+
productWaiters[name] = waiters
|
|
1228
|
+
end
|
|
1229
|
+
local waiter = { Thread = coroutine.running(), Settled = false }
|
|
1230
|
+
table.insert(waiters :: { any }, waiter)
|
|
1231
|
+
Clock.Delay(timeout or Defaults.ProductInfo, function()
|
|
1232
|
+
if not waiter.Settled then
|
|
1233
|
+
waiter.Settled = true
|
|
1234
|
+
Sched.Resume(waiter.Thread, nil)
|
|
1235
|
+
end
|
|
1236
|
+
end)
|
|
1237
|
+
return coroutine.yield()
|
|
1238
|
+
end
|
|
1239
|
+
|
|
1240
|
+
-- Waits for the local player's Robux price.
|
|
1241
|
+
function Data.GetPriceAsync(name: string, timeout: number?): number?
|
|
1242
|
+
local info = Data.GetProductInfoAsync(name, timeout)
|
|
1243
|
+
local price = if info ~= nil then info.PriceInRobux else nil
|
|
1244
|
+
return if type(price) == "number" then price else nil
|
|
1245
|
+
end
|
|
1246
|
+
|
|
1247
|
+
-- Reports cached product info and updates; returns a disconnect.
|
|
1248
|
+
function Data.ObserveProductInfo(name: string, callback: ({ [string]: any }?) -> ()): () -> ()
|
|
1249
|
+
productAsset(name, "ObserveProductInfo")
|
|
1250
|
+
if stopped then
|
|
1251
|
+
return function() end
|
|
1252
|
+
end
|
|
1253
|
+
watchMembership()
|
|
1254
|
+
local last: any = UNRESOLVED
|
|
1255
|
+
local alive = true
|
|
1256
|
+
local function push()
|
|
1257
|
+
if not alive or stopped then
|
|
1258
|
+
return
|
|
1259
|
+
end
|
|
1260
|
+
local info = productInfo[name]
|
|
1261
|
+
if info ~= last then
|
|
1262
|
+
last = info
|
|
1263
|
+
Sched.Spawn(callback, info)
|
|
1264
|
+
end
|
|
1265
|
+
end
|
|
1266
|
+
local list = productObservers[name]
|
|
1267
|
+
if list == nil then
|
|
1268
|
+
list = {}
|
|
1269
|
+
productObservers[name] = list
|
|
1270
|
+
end
|
|
1271
|
+
table.insert(list :: { () -> () }, push)
|
|
1272
|
+
enqueueProduct(name)
|
|
1273
|
+
push()
|
|
1274
|
+
return function()
|
|
1275
|
+
alive = false
|
|
1276
|
+
local current = productObservers[name]
|
|
1277
|
+
if current ~= nil then
|
|
1278
|
+
local index = table.find(current, push)
|
|
1279
|
+
if index ~= nil then
|
|
1280
|
+
table.remove(current, index)
|
|
1281
|
+
end
|
|
1282
|
+
end
|
|
1283
|
+
end
|
|
1284
|
+
end
|
|
1285
|
+
|
|
1286
|
+
-- Warms selected product info in one batch.
|
|
1287
|
+
function Data.PrefetchProductInfo(names: { string }?)
|
|
1288
|
+
if stopped then
|
|
1289
|
+
return
|
|
1290
|
+
end
|
|
1291
|
+
watchMembership()
|
|
1292
|
+
if anyPaidRandom() then
|
|
1293
|
+
ensurePolicy()
|
|
1294
|
+
end
|
|
1295
|
+
if names == nil then
|
|
1296
|
+
for name in ensureProductAssets() do
|
|
1297
|
+
enqueueProduct(name)
|
|
1298
|
+
end
|
|
1299
|
+
return
|
|
1300
|
+
end
|
|
1301
|
+
-- Validated in full first, so a typo raises instead of half-warming.
|
|
1302
|
+
for _, name in names do
|
|
1303
|
+
productAsset(name, "PrefetchProductInfo")
|
|
1304
|
+
end
|
|
1305
|
+
for _, name in names do
|
|
1306
|
+
enqueueProduct(name)
|
|
1307
|
+
end
|
|
1308
|
+
end
|
|
1309
|
+
|
|
1310
|
+
-- Invalidates cached marketplace info and starts fresh reads.
|
|
1311
|
+
function Data.RefreshProductInfo(name: string?)
|
|
1312
|
+
if name ~= nil then
|
|
1313
|
+
productAsset(name, "RefreshProductInfo")
|
|
1314
|
+
end
|
|
1315
|
+
refreshProduct(name)
|
|
1316
|
+
end
|
|
1317
|
+
|
|
1318
|
+
-- Reads the mirrored ownership and policy state for shop UI.
|
|
1319
|
+
function Data.GetProductState(name: string): string
|
|
1320
|
+
productAsset(name, "GetProductState")
|
|
1321
|
+
return productStateFor(name)
|
|
1322
|
+
end
|
|
1323
|
+
|
|
1324
|
+
-- Asks the server to validate and open the purchase prompt.
|
|
1325
|
+
function Data.PromptPurchase(name: string): (boolean, string?, {}?)
|
|
1326
|
+
if type(name) ~= "string" then
|
|
1327
|
+
error("Scribe.PromptPurchase: name must be a string", 2)
|
|
1328
|
+
end
|
|
1329
|
+
if stopped then
|
|
1330
|
+
return false, "not-loaded"
|
|
1331
|
+
end
|
|
1332
|
+
if editMode then
|
|
1333
|
+
return false, "edit-mode", Types.RequestFailed
|
|
1334
|
+
end
|
|
1335
|
+
if not loaded then
|
|
1336
|
+
return false, "not-loaded"
|
|
1337
|
+
end
|
|
1338
|
+
if purchaseRequestPending then
|
|
1339
|
+
return false, "purchase prompt already open"
|
|
1340
|
+
end
|
|
1341
|
+
purchaseRequestPending = true
|
|
1342
|
+
local requested, prompted, reason, failed =
|
|
1343
|
+
pcall(dispatchRequest, Wire.PURCHASE_PROMPT_COMMAND, nil, table.pack(name), 3)
|
|
1344
|
+
purchaseRequestPending = false
|
|
1345
|
+
if not requested then
|
|
1346
|
+
return false, `purchase prompt failed: {prompted}`
|
|
1347
|
+
end
|
|
1348
|
+
return prompted, reason, failed
|
|
1349
|
+
end
|
|
1350
|
+
|
|
1351
|
+
-- Reports the current shop state and later changes.
|
|
1352
|
+
function Data.ObserveProductState(name: string, callback: (state: string) -> ()): () -> ()
|
|
1353
|
+
productAsset(name, "ObserveProductState")
|
|
1354
|
+
local last: string? = nil
|
|
1355
|
+
local function push()
|
|
1356
|
+
local state = productStateFor(name)
|
|
1357
|
+
if state ~= last then
|
|
1358
|
+
last = state
|
|
1359
|
+
Sched.Spawn(callback, state)
|
|
1360
|
+
end
|
|
1361
|
+
end
|
|
1362
|
+
local loadedConn = if loaded then nil else loadedSignal:Connect(push)
|
|
1363
|
+
table.insert(policyObservers, push)
|
|
1364
|
+
local disconnectPerk = tree.Reserved.Perks.Changed(push)
|
|
1365
|
+
local disconnectCache = tree.Accessor[Template.SESSION_ROOT].OwnsCache.Changed(push)
|
|
1366
|
+
push()
|
|
1367
|
+
return function()
|
|
1368
|
+
if loadedConn ~= nil then
|
|
1369
|
+
loadedConn:Disconnect()
|
|
1370
|
+
end
|
|
1371
|
+
local index = table.find(policyObservers, push)
|
|
1372
|
+
if index ~= nil then
|
|
1373
|
+
table.remove(policyObservers, index)
|
|
1374
|
+
end
|
|
1375
|
+
disconnectPerk()
|
|
1376
|
+
disconnectCache()
|
|
1377
|
+
end
|
|
1378
|
+
end
|
|
1379
|
+
|
|
1380
|
+
-- Reads the owner's replicated save status.
|
|
1381
|
+
function Data.GetSaveInfo(): { [string]: any }
|
|
1382
|
+
if not editMode then
|
|
1383
|
+
waitForLoaded()
|
|
1384
|
+
end
|
|
1385
|
+
local session = mirror[Template.SESSION_ROOT]
|
|
1386
|
+
local info = if type(session) == "table" then session.SaveInfo else nil
|
|
1387
|
+
return if type(info) == "table" then Util.deepClone(info) else { Dirty = false }
|
|
1388
|
+
end
|
|
1389
|
+
|
|
1390
|
+
-- Reads unassigned gift credits from the local mirror.
|
|
1391
|
+
function Data.GetGiftCredits(): { [string]: number }
|
|
1392
|
+
if not editMode then
|
|
1393
|
+
waitForLoaded()
|
|
1394
|
+
end
|
|
1395
|
+
local reserved = mirror[Template.RESERVED_ROOT]
|
|
1396
|
+
local credits = if type(reserved) == "table" then reserved.GiftCredits else nil
|
|
1397
|
+
return if type(credits) == "table" then Util.deepClone(credits) else {}
|
|
1398
|
+
end
|
|
1399
|
+
|
|
1400
|
+
-- Reads purchase history only when its replication is enabled.
|
|
1401
|
+
function Data.GetPurchases(filter: { [string]: any }?): { { [string]: any } }
|
|
1402
|
+
if not editMode then
|
|
1403
|
+
waitForLoaded()
|
|
1404
|
+
end
|
|
1405
|
+
local reserved = mirror[Template.RESERVED_ROOT]
|
|
1406
|
+
local logs = if type(reserved) == "table" then reserved.PurchaseLogs else nil
|
|
1407
|
+
if type(logs) ~= "table" then
|
|
1408
|
+
return {}
|
|
1409
|
+
end
|
|
1410
|
+
local out = {}
|
|
1411
|
+
local function collect(kind: string, ring: any)
|
|
1412
|
+
if filter and filter.Kind and filter.Kind ~= kind then
|
|
1413
|
+
return
|
|
1414
|
+
end
|
|
1415
|
+
if type(ring) ~= "table" then
|
|
1416
|
+
return
|
|
1417
|
+
end
|
|
1418
|
+
for _, item in ring do
|
|
1419
|
+
if filter then
|
|
1420
|
+
if filter.Category and item.Category ~= filter.Category then
|
|
1421
|
+
continue
|
|
1422
|
+
end
|
|
1423
|
+
if filter.ItemId and item.ItemId ~= filter.ItemId then
|
|
1424
|
+
continue
|
|
1425
|
+
end
|
|
1426
|
+
if filter.Since and (tonumber(item.Ts) or 0) < filter.Since then
|
|
1427
|
+
continue
|
|
1428
|
+
end
|
|
1429
|
+
end
|
|
1430
|
+
local record = Util.deepClone(item)
|
|
1431
|
+
record.Kind = kind
|
|
1432
|
+
table.insert(out, record)
|
|
1433
|
+
end
|
|
1434
|
+
end
|
|
1435
|
+
collect("Robux", logs.Robux)
|
|
1436
|
+
collect("InGame", logs.InGame)
|
|
1437
|
+
table.sort(out, function(a, b)
|
|
1438
|
+
return (tonumber(a.Ts) or 0) > (tonumber(b.Ts) or 0)
|
|
1439
|
+
end)
|
|
1440
|
+
if filter and filter.Limit then
|
|
1441
|
+
for i = #out, (filter.Limit :: number) + 1, -1 do
|
|
1442
|
+
out[i] = nil
|
|
1443
|
+
end
|
|
1444
|
+
end
|
|
1445
|
+
return out
|
|
1446
|
+
end
|
|
1447
|
+
|
|
1448
|
+
-- Edit-mode mocks -------------------------------------------------------------
|
|
1449
|
+
|
|
1450
|
+
local function assertEditMode(what: string)
|
|
1451
|
+
if not editMode then
|
|
1452
|
+
error(`Scribe: {what} is only available in edit mode (storybooks, command bar)`, 3)
|
|
1453
|
+
end
|
|
1454
|
+
end
|
|
1455
|
+
|
|
1456
|
+
local function deepMerge(base: any, over: any): any
|
|
1457
|
+
if type(base) ~= "table" or type(over) ~= "table" then
|
|
1458
|
+
return Util.deepClone(over)
|
|
1459
|
+
end
|
|
1460
|
+
local out = Util.deepClone(base)
|
|
1461
|
+
for key, value in over do
|
|
1462
|
+
out[key] = deepMerge(out[key], value)
|
|
1463
|
+
end
|
|
1464
|
+
return out
|
|
1465
|
+
end
|
|
1466
|
+
|
|
1467
|
+
-- Seeds local mirror data in edit mode only.
|
|
1468
|
+
function Data.Mock(values: { [string]: any }?, scribeState: { [string]: any }?)
|
|
1469
|
+
assertEditMode("Data.Mock")
|
|
1470
|
+
-- Batch the whole-root Sets through ReplayFire so a nested observer registered
|
|
1471
|
+
-- before Mock still fires; a whole-root Set fires only the container's Changed.
|
|
1472
|
+
tree:ReplayFire(function()
|
|
1473
|
+
if values then
|
|
1474
|
+
for key, value in values do
|
|
1475
|
+
local current = mirror[key]
|
|
1476
|
+
tree.Accessor[key].Set(deepMerge(current, value))
|
|
1477
|
+
end
|
|
1478
|
+
end
|
|
1479
|
+
if scribeState then
|
|
1480
|
+
-- The privileged handle: Data.Mock seeds Scribe's own ledgers, which the
|
|
1481
|
+
-- public accessor refuses to write.
|
|
1482
|
+
local reservedAccessor = tree.Reserved
|
|
1483
|
+
if scribeState.Perks then
|
|
1484
|
+
for _, perk in scribeState.Perks :: { string } do
|
|
1485
|
+
reservedAccessor.Perks[perk].Set(true)
|
|
1486
|
+
end
|
|
1487
|
+
end
|
|
1488
|
+
if scribeState.GiftCredits then
|
|
1489
|
+
reservedAccessor.GiftCredits.Set(scribeState.GiftCredits)
|
|
1490
|
+
end
|
|
1491
|
+
if scribeState.PurchaseLogs then
|
|
1492
|
+
local logs = scribeState.PurchaseLogs :: { [string]: any }
|
|
1493
|
+
if logs.Robux then
|
|
1494
|
+
reservedAccessor.PurchaseLogs.Robux.Set(logs.Robux)
|
|
1495
|
+
end
|
|
1496
|
+
if logs.InGame then
|
|
1497
|
+
reservedAccessor.PurchaseLogs.InGame.Set(logs.InGame)
|
|
1498
|
+
end
|
|
1499
|
+
end
|
|
1500
|
+
if scribeState.Leaderboards then
|
|
1501
|
+
for name, entries in scribeState.Leaderboards :: { [string]: { any } } do
|
|
1502
|
+
mockLeaderboards[name] = entries
|
|
1503
|
+
end
|
|
1504
|
+
end
|
|
1505
|
+
end
|
|
1506
|
+
end)
|
|
1507
|
+
end
|
|
1508
|
+
|
|
1509
|
+
-- Registers an edit-mode command handler without a server.
|
|
1510
|
+
function Data.MockCommand(name: string, handler: (...any) -> ...any)
|
|
1511
|
+
assertEditMode("Data.MockCommand")
|
|
1512
|
+
mockCommands[name] = handler
|
|
1513
|
+
end
|
|
1514
|
+
|
|
1515
|
+
-- Data.<rootField> resolves through the mirror tree, returning the accessor
|
|
1516
|
+
-- immediately: reads give template defaults until Init lands. A metamethod must
|
|
1517
|
+
-- never yield, so waiting here errors with "yield across metamethod/C-call".
|
|
1518
|
+
setmetatable(Data :: any, {
|
|
1519
|
+
__index = function(_, key: any)
|
|
1520
|
+
if type(key) ~= "string" then
|
|
1521
|
+
return nil
|
|
1522
|
+
end
|
|
1523
|
+
return tree.Accessor[key]
|
|
1524
|
+
end,
|
|
1525
|
+
})
|
|
1526
|
+
|
|
1527
|
+
-- Server store roots are in this mirror like any other root; they simply are never
|
|
1528
|
+
-- written from here. Same per-root shape as the server exposes.
|
|
1529
|
+
if compiled.Views.Store ~= nil then
|
|
1530
|
+
local proxy = {}
|
|
1531
|
+
for _, key in compiled.Views.Store.RootOrder do
|
|
1532
|
+
proxy[key] = tree.Accessor.Child(key)
|
|
1533
|
+
end
|
|
1534
|
+
Data.ServerStore = table.freeze(proxy)
|
|
1535
|
+
end
|
|
1536
|
+
|
|
1537
|
+
-- Coalesces local container notifications; writes stay on this client.
|
|
1538
|
+
function Data.Batch(fn: () -> ())
|
|
1539
|
+
tree:RunBatch(fn)
|
|
1540
|
+
end
|
|
1541
|
+
|
|
1542
|
+
-- Releases this bundle's listeners, retry loop, and mirror.
|
|
1543
|
+
function Data.Stop()
|
|
1544
|
+
if stopped then
|
|
1545
|
+
return
|
|
1546
|
+
end
|
|
1547
|
+
stopped = true
|
|
1548
|
+
table.clear(productQueue)
|
|
1549
|
+
table.clear(productQueued)
|
|
1550
|
+
table.clear(productInfo)
|
|
1551
|
+
table.clear(productObservers)
|
|
1552
|
+
local waiters = productWaiters
|
|
1553
|
+
productWaiters = {}
|
|
1554
|
+
if transport ~= nil and type((transport :: any).Release) == "function" then
|
|
1555
|
+
pcall((transport :: any).Release, transport)
|
|
1556
|
+
end
|
|
1557
|
+
if membershipConnection ~= nil then
|
|
1558
|
+
pcall(function()
|
|
1559
|
+
membershipConnection:Disconnect()
|
|
1560
|
+
end)
|
|
1561
|
+
membershipConnection = nil
|
|
1562
|
+
end
|
|
1563
|
+
tree:Destroy()
|
|
1564
|
+
for _, waiting in waiters do
|
|
1565
|
+
for _, waiter in waiting do
|
|
1566
|
+
if not waiter.Settled then
|
|
1567
|
+
waiter.Settled = true
|
|
1568
|
+
Sched.Resume(waiter.Thread, nil)
|
|
1569
|
+
end
|
|
1570
|
+
end
|
|
1571
|
+
end
|
|
1572
|
+
end
|
|
1573
|
+
|
|
1574
|
+
-- Exposes the same API without template-aware types.
|
|
1575
|
+
Data.Raw = Data
|
|
1576
|
+
|
|
1577
|
+
-- One line confirming the bundle initialized (Banner = false to silence).
|
|
1578
|
+
if options.Banner ~= false then
|
|
1579
|
+
print(`Running Scribe v{Version} by ericplane. Client is now initialized`)
|
|
1580
|
+
end
|
|
1581
|
+
|
|
1582
|
+
-- Drive OnOwnershipChanged once the first snapshot lands.
|
|
1583
|
+
Sched.Spawn(ensureOwnershipWatched)
|
|
1584
|
+
|
|
1585
|
+
-- A root field named like a client Data API is silently shadowed by that real key
|
|
1586
|
+
-- (a real key always wins over __index), so it is unreachable as `Data.<name>`.
|
|
1587
|
+
-- Reported always rather than only in Studio, and at Error level so it reaches
|
|
1588
|
+
-- Scribe.OnIssue: the case worth catching is a shipped game upgrading into a
|
|
1589
|
+
-- collision. Keep this last: `for key in Data` sees only the keys that exist when
|
|
1590
|
+
-- it runs, and raw iteration means only real keys are judged.
|
|
1591
|
+
local rootChildren = compiled.Root.Children :: { [string]: any }
|
|
1592
|
+
for key in Data do
|
|
1593
|
+
if type(key) == "string" and rootChildren[key] then
|
|
1594
|
+
Log.Error(
|
|
1595
|
+
"Lifecycle",
|
|
1596
|
+
"API_NAME_COLLISION",
|
|
1597
|
+
`template root field "{key}" collides with a client Data API name, so it is unreachable as `
|
|
1598
|
+
.. `Data.{key} on the client. Rename the field, or read it through the accessor tree.`,
|
|
1599
|
+
{ Field = key }
|
|
1600
|
+
)
|
|
1601
|
+
end
|
|
1602
|
+
end
|
|
1603
|
+
|
|
1604
|
+
return Data
|
|
1605
|
+
end
|
|
1606
|
+
|
|
1607
|
+
return Client
|