@rbxts/scribe 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +21 -0
  3. package/README.md +100 -0
  4. package/Scribe-source-map.json +1 -0
  5. package/licenses/ProfileStore-Apache-2.0.txt +201 -0
  6. package/package.json +32 -0
  7. package/src/Client/DebugHook.luau +457 -0
  8. package/src/Client/init.luau +1607 -0
  9. package/src/Internal/Addons.luau +68 -0
  10. package/src/Internal/Big.luau +582 -0
  11. package/src/Internal/Budget.luau +377 -0
  12. package/src/Internal/Clock.luau +75 -0
  13. package/src/Internal/Config.luau +17 -0
  14. package/src/Internal/Conform.luau +400 -0
  15. package/src/Internal/Datatypes.luau +653 -0
  16. package/src/Internal/Defaults.luau +12 -0
  17. package/src/Internal/Derived.luau +428 -0
  18. package/src/Internal/Exchange.luau +556 -0
  19. package/src/Internal/ExchangeLeg.luau +1368 -0
  20. package/src/Internal/ExchangeVerdict.luau +179 -0
  21. package/src/Internal/Failure.luau +148 -0
  22. package/src/Internal/Health.luau +320 -0
  23. package/src/Internal/LeaderboardDiagnostics.luau +36 -0
  24. package/src/Internal/Log.luau +378 -0
  25. package/src/Internal/Marker.luau +76 -0
  26. package/src/Internal/Metrics.luau +152 -0
  27. package/src/Internal/Node.luau +3954 -0
  28. package/src/Internal/Profile.luau +69 -0
  29. package/src/Internal/Rng.luau +83 -0
  30. package/src/Internal/Sched.luau +56 -0
  31. package/src/Internal/Signal.luau +199 -0
  32. package/src/Internal/Store/ProfileStore.luau +3019 -0
  33. package/src/Internal/Store/init.luau +18 -0
  34. package/src/Internal/StudioCodec.luau +155 -0
  35. package/src/Internal/Template.luau +1848 -0
  36. package/src/Internal/Transport.luau +169 -0
  37. package/src/Internal/Util.luau +517 -0
  38. package/src/Internal/Version.luau +4 -0
  39. package/src/Internal/Wire.luau +1283 -0
  40. package/src/Server/Analytics.luau +223 -0
  41. package/src/Server/Commands.luau +728 -0
  42. package/src/Server/DebugHook.luau +1490 -0
  43. package/src/Server/Exchanges.luau +737 -0
  44. package/src/Server/Leaderboards.luau +2143 -0
  45. package/src/Server/Monetization.luau +3212 -0
  46. package/src/Server/Persistence.luau +3775 -0
  47. package/src/Server/Replication.luau +1253 -0
  48. package/src/Server/ServerStore.luau +81 -0
  49. package/src/Server/Timed.luau +579 -0
  50. package/src/Server/init.luau +672 -0
  51. package/src/Types.luau +480 -0
  52. package/src/init.luau +2231 -0
  53. package/types/api.d.ts +252 -0
  54. package/types/common.d.ts +355 -0
  55. package/types/index.d.ts +226 -0
  56. package/types/schema.d.ts +276 -0
@@ -0,0 +1,3019 @@
1
+ --!nocheck
2
+ -- selene: allow(unused_variable)
3
+ --
4
+ -- VENDORED FORK of ProfileStore v1.0.3.
5
+ -- Copyright (c) loleris / MAD STUDIO.
6
+ -- Licensed under the Apache License, Version 2.0. The full licence text ships
7
+ -- with the source package at licenses/ProfileStore-Apache-2.0.txt.
8
+ -- Upstream project: ProfileStore by MAD STUDIO, on GitHub under MadStudioRoblox.
9
+ --
10
+ -- No off-platform URLs anywhere, deliberately: Roblox flags links that send
11
+ -- players off-platform and the whole of src/ is packed into the released .rbxm.
12
+ -- Attribution is given by name, which is what the licence requires.
13
+ --
14
+ -- THIS FILE HAS BEEN MODIFIED BY SCRIBE, as Apache-2.0 section 4(b) requires it
15
+ -- to say. Every change is marked `SCRIBE PATCH` and nothing else is touched --
16
+ -- no reformatting, no renaming, no style fixes -- so a future upstream release
17
+ -- can still be diffed against this one. That is also why this file is excluded
18
+ -- from stylua and selene (see .styluaignore and selene.toml).
19
+ --
20
+ -- Most of the patches remove one defect class: a save that SUCCEEDS while
21
+ -- writing nothing, because the session was superseded. A boolean cannot report
22
+ -- that, so SaveProfileAsync answers "Saved" | "NotOwned" | "Failed".
23
+
24
+ --[[
25
+ MAD STUDIO (by loleris)
26
+
27
+ -[ProfileStore]---------------------------------------
28
+
29
+ Periodic DataStore saving solution with session locking
30
+
31
+ WARNINGS FOR "Profile.Data" VALUES:
32
+ ! Do not create numeric tables with gaps - attempting to store such tables will result in an error.
33
+ ! Do not create mixed tables (some values indexed by number and others by a string key)
34
+ - only numerically indexed data will be stored.
35
+ ! Do not index tables by anything other than numbers and strings.
36
+ ! Do not reference Roblox Instances
37
+ ! Do not reference userdata (Vector3, Color3, CFrame...) - Serialize userdata before referencing
38
+ ! Do not reference functions
39
+
40
+ Members:
41
+
42
+ ProfileStore.IsClosing [bool]
43
+ -- Set to true after a game:BindToClose() trigger
44
+
45
+ ProfileStore.IsCriticalState [bool]
46
+ -- Set to true when ProfileStore experiences too many consecutive errors
47
+
48
+ ProfileStore.OnError [Signal] (message, store_name, profile_key)
49
+ -- Most ProfileStore errors will be caught and passed to this signal
50
+
51
+ ProfileStore.OnOverwrite [Signal] (store_name, profile_key)
52
+ -- Triggered when a DataStore key was likely used to store data that wasn't
53
+ a ProfileStore profile or the ProfileStore structure was invalidly manually
54
+ altered for that DataStore key
55
+
56
+ ProfileStore.OnCriticalToggle [Signal] (is_critical)
57
+ -- Triggered when ProfileStore experiences too many consecutive errors
58
+
59
+ ProfileStore.DataStoreState [string] ("NotReady", "NoInternet", "NoAccess", "Access")
60
+ -- This value resembles ProfileStore's access to the DataStore; The value starts
61
+ as "NotReady" and will eventually change to one of the other 3 possible values.
62
+
63
+ Functions:
64
+
65
+ ProfileStore.New(store_name, template?) --> [ProfileStore]
66
+ store_name [string] -- DataStore name
67
+ template [table] or nil -- Profiles will default to given table (hard-copy) when no data was saved previously
68
+
69
+ ProfileStore.SetConstant(name, value)
70
+ name [string]
71
+ value [number]
72
+
73
+ Members [ProfileStore]:
74
+
75
+ ProfileStore.Mock [ProfileStore]
76
+ -- Reflection of ProfileStore methods, but the methods will now query a mock
77
+ DataStore with no relation to the real DataStore
78
+
79
+ ProfileStore.Name [string]
80
+
81
+ Methods [ProfileStore]:
82
+
83
+ ProfileStore:StartSessionAsync(profile_key, params?) --> [Profile] or nil
84
+ profile_key [string] -- DataStore key
85
+ params nil or [table]: -- Custom params; E.g. {Steal = true}
86
+ {
87
+ Steal = true, -- Pass this to disregard an existing session lock
88
+ Cancel = fn() -> (boolean), -- Pass this to create a request cancel condition.
89
+ -- If the cancel function returns true, ProfileStore will stop trying to
90
+ -- start the session and return nil
91
+ }
92
+
93
+ ProfileStore:MessageAsync(profile_key, message) --> is_success [bool]
94
+ profile_key [string] -- DataStore key
95
+ message [table] -- Data to be messaged to the profile
96
+ -- SCRIBE PATCH: two further returns, reason [string?] and
97
+ -- provably_clean [bool?]; see the method body.
98
+
99
+ ProfileStore:GetAsync(profile_key, version?) --> [Profile] or nil
100
+ -- Reads a profile without starting a session - will not autosave
101
+ profile_key [string] -- DataStore key
102
+ version nil or [string] -- DataStore key version
103
+
104
+ ProfileStore:VersionQuery(profile_key, sort_direction?, min_date?, max_date?) --> [VersionQuery]
105
+ profile_key [string]
106
+ sort_direction nil or [Enum.SortDirection]
107
+ min_date nil or [DateTime]
108
+ max_date nil or [DateTime]
109
+
110
+ ProfileStore:RemoveAsync(profile_key) --> is_success [bool]
111
+ -- Completely removes profile data from the DataStore / mock DataStore with no way to recover it.
112
+
113
+ Methods [VersionQuery]:
114
+
115
+ VersionQuery:NextAsync() --> [Profile] or nil -- (Yields)
116
+ -- Returned profile is similar to profiles returned by ProfileStore:GetAsync()
117
+
118
+ Members [Profile]:
119
+
120
+ Profile.Data [table]
121
+ -- When the profile is active changes to this table are guaranteed to be saved
122
+ Profile.LastSavedData [table] (Read-only)
123
+ -- Last snapshot of "Profile.Data" that has been successfully saved to the DataStore;
124
+ Useful for proper developer product purchase receipt handling
125
+
126
+ Profile.FirstSessionTime [number] (Read-only)
127
+ -- os.time() timestamp of the first profile session
128
+
129
+ Profile.SessionLoadCount [number] (Read-only) -- Amount of times a session was started for this profile
130
+
131
+ Profile.Session [table] (Read-only) {PlaceId = number, JobId = string} / nil
132
+ -- Set to a table if this profile is in use by a server; nil if released
133
+
134
+ Profile.RobloxMetaData [table] -- Writable table that gets saved automatically and once the profile is released
135
+ Profile.UserIds [table] -- (Read-only) -- {user_id [number], ...} -- User ids associated with this profile
136
+
137
+ Profile.KeyInfo [DataStoreKeyInfo] -- Changes before OnAfterSave signal
138
+
139
+ Profile.OnSave [Signal] ()
140
+ -- Triggered right before changes to Profile.Data are saved to the DataStore
141
+
142
+ Profile.OnLastSave [Signal] (reason [string]: "Manual", "External", "Shutdown")
143
+ -- Triggered right before changes to Profile.Data are saved to the DataStore
144
+ for the last time; A reason is provided for the last save:
145
+ - "Manual" - Profile:EndSession() was called
146
+ - "Shutdown" - The server that has ownership of this profile is shutting down
147
+ - "External" - Another server has started a session for this profile
148
+ Note that this event will not trigger for when a profile session is ended by
149
+ another server trying to take ownership of the session - this is impossible to
150
+ do without compromising on ProfileStore's speed.
151
+
152
+ Profile.OnSessionEnd [Signal] ()
153
+ -- Triggered when the profile session is terminated on this server
154
+
155
+ Profile.OnAfterSave [Signal] (last_saved_data)
156
+ -- Triggered after a successful save
157
+ last_saved_data [table] -- Profile.LastSavedData
158
+
159
+ Profile.ProfileStore [ProfileStore] -- ProfileStore object this profile belongs to
160
+ Profile.Key [string] -- DataStore key
161
+
162
+ Methods [Profile]:
163
+
164
+ Profile:IsActive() --> [bool] -- If "true" is returned, changes to Profile.Data are guaranteed to save;
165
+ This guarantee is only valid until code yields (e.g. task.wait() is used).
166
+
167
+ Profile:Reconcile() -- Fills in missing (nil) [string_key] = [value] pairs to the Profile.Data structure
168
+ from the "template" argument that was passed to "ProfileStore.New()"
169
+
170
+ Profile:HasCompletedSave() --> [bool] -- (SCRIBE PATCH) Whether a save for this profile
171
+ has ever committed. Never true for a profile keyed on a negative user id
172
+ outside mock, since AddUserId refuses those.
173
+
174
+ Profile:SessionsStarted() --> [number] -- (SCRIBE PATCH) Profile.SessionLoadCount,
175
+ normalized for view mode, which skips the session-start increment
176
+
177
+ Profile:SetSaveSource(data) --> () -- (SCRIBE PATCH) Choose the table this profile
178
+ serializes from. Per-profile, not per-save; see the note at the method.
179
+
180
+ Profile:EndSession() -- Call after the server has finished working with this profile
181
+ e.g., after the player leaves (Profile object will become inactive)
182
+
183
+ Profile:AddUserId(user_id) -- Associates user_id with profile (GDPR compliance)
184
+ user_id [number]
185
+
186
+ Profile:RemoveUserId(user_id) -- Removes user_id association with profile (safe function)
187
+ user_id [number]
188
+
189
+ Profile:MessageHandler(fn) -- Sets a message handler for this profile
190
+ fn [function] (message [table], processed [function]())
191
+ -- The handler function receives a message table and a callback function;
192
+ The callback function is to be called when a message has been processed
193
+ - this will discard the message from the profile message cache; If the
194
+ callback function is not called, other message handlers will also be triggered
195
+ with unprocessed message data.
196
+
197
+ Profile:Save() -- If the profile session is still active makes an UpdateAsync call
198
+ to the DataStore to immediately save profile data
199
+
200
+ Profile:SetAsync() -- Forcefully saves changes to the profile; Only for profiles
201
+ loaded with ProfileStore:GetAsync() or ProfileStore:VersionQuery()
202
+
203
+ --]]
204
+
205
+ local AUTO_SAVE_PERIOD = 300 -- (Seconds) Time between when changes to a profile are saved to the DataStore
206
+ local LOAD_REPEAT_PERIOD = 10 -- (Seconds) Time between successive profile reads when handling a session conflict
207
+ local FIRST_LOAD_REPEAT = 5 -- (Seconds) Time between first and second profile read when handling a session conflict
208
+ local SESSION_STEAL = 40 -- (Seconds) Time until a session conflict is resolved with the waiting server stealing the session
209
+ local ASSUME_DEAD = 630 -- (Seconds) If a profile hasn't had updates for this long, quickly assume an active session belongs to a crashed server
210
+ local START_SESSION_TIMEOUT = 120 -- (Seconds) If a session can't be started for a profile for this long, stop repeating calls to the DataStore
211
+
212
+ local CRITICAL_STATE_ERROR_COUNT = 5 -- Assume critical state if this many issues happen in a short amount of time
213
+ local CRITICAL_STATE_ERROR_EXPIRE = 120 -- (Seconds) Individual issue expiration
214
+ local CRITICAL_STATE_EXPIRE = 120 -- (Seconds) Critical state expiration
215
+
216
+ local MAX_MESSAGE_QUEUE = 1000 -- Max messages saved in a profile that were sent using "ProfileStore:MessageAsync()"
217
+
218
+ ----- Dependencies -----
219
+
220
+ -- local Util = require(game.ReplicatedStorage.Shared.Util)
221
+ -- local Signal = Util.Signal
222
+
223
+ -- SCRIBE PATCH: the error classifier, INJECTED rather than required, and the
224
+ -- file's only dependency of any kind.
225
+ --
226
+ -- MessageAsync's third return has to answer "could ANY attempt in this call have
227
+ -- written?", and the evidence is the error each failed attempt raised. Scribe
228
+ -- already owns that classifier in Internal/Failure.luau, so it is handed in rather
229
+ -- than restated here. Persistence installs it as it adopts the store module
230
+ -- (findProfileStoreModule), the single seam every route to this file goes through.
231
+ --
232
+ -- A require was tried first and is wrong. This file has no `require` and no
233
+ -- `script`, and that is load-bearing: the simulation loads it as raw source into a
234
+ -- synthetic global table so each simulated server gets a private copy of the module
235
+ -- state (test/Sim/Server.luau, test/Sim/Loader.luau). A require fails outright
236
+ -- there, and making it work would hand every simulated server the harness's one
237
+ -- shared Health/Log/Metrics graph.
238
+ --
239
+ -- Unset is exactly the old behaviour: absent a classifier every failed attempt
240
+ -- reads as "could have written", which is bit-for-bit what the attempt COUNT it
241
+ -- replaced computed. The field is declared with the module table below.
242
+
243
+ local Signal do
244
+
245
+ local FreeRunnerThread
246
+
247
+ --[[
248
+ Yield-safe coroutine reusing by stravant;
249
+ Source: the GoodSignal comparison thread on the Roblox DevForum.
250
+ (SCRIBE PATCH: the two source URLs are removed rather than redacted at
251
+ build time to comply with roblox development guidelines.)
252
+ --]]
253
+
254
+ local function AcquireRunnerThreadAndCallEventHandler(fn, ...)
255
+ local acquired_runner_thread = FreeRunnerThread
256
+ FreeRunnerThread = nil
257
+ fn(...)
258
+ -- The handler finished running, this runner thread is free again.
259
+ FreeRunnerThread = acquired_runner_thread
260
+ end
261
+
262
+ local function RunEventHandlerInFreeThread(...)
263
+ AcquireRunnerThreadAndCallEventHandler(...)
264
+ while true do
265
+ AcquireRunnerThreadAndCallEventHandler(coroutine.yield())
266
+ end
267
+ end
268
+
269
+ local Connection = {}
270
+ Connection.__index = Connection
271
+
272
+ local SignalClass = {}
273
+ SignalClass.__index = SignalClass
274
+
275
+ function Connection:Disconnect()
276
+
277
+ if self.is_connected == false then
278
+ return
279
+ end
280
+
281
+ local signal = self.signal
282
+ self.is_connected = false
283
+ signal.listener_count -= 1
284
+
285
+ if signal.head == self then
286
+ signal.head = self.next
287
+ else
288
+ local prev = signal.head
289
+ while prev ~= nil and prev.next ~= self do
290
+ prev = prev.next
291
+ end
292
+ if prev ~= nil then
293
+ prev.next = self.next
294
+ end
295
+ end
296
+
297
+ end
298
+
299
+ function SignalClass.New()
300
+
301
+ local self = {
302
+ head = nil,
303
+ listener_count = 0,
304
+ }
305
+ setmetatable(self, SignalClass)
306
+
307
+ return self
308
+
309
+ end
310
+
311
+ function SignalClass:Connect(listener: (...any) -> ())
312
+
313
+ if type(listener) ~= "function" then
314
+ error(`[{script.Name}]: \"listener\" must be a function; Received {typeof(listener)}`)
315
+ end
316
+
317
+ local connection = {
318
+ listener = listener,
319
+ signal = self,
320
+ next = self.head,
321
+ is_connected = true,
322
+ }
323
+ setmetatable(connection, Connection)
324
+
325
+ self.head = connection
326
+ self.listener_count += 1
327
+
328
+ return connection
329
+
330
+ end
331
+
332
+ function SignalClass:GetListenerCount(): number
333
+ return self.listener_count
334
+ end
335
+
336
+ function SignalClass:Fire(...)
337
+ local item = self.head
338
+ while item ~= nil do
339
+ if item.is_connected == true then
340
+ if not FreeRunnerThread then
341
+ FreeRunnerThread = coroutine.create(RunEventHandlerInFreeThread)
342
+ end
343
+ task.spawn(FreeRunnerThread, item.listener, ...)
344
+ end
345
+ item = item.next
346
+ end
347
+ end
348
+
349
+ function SignalClass:Wait()
350
+ local co = coroutine.running()
351
+ local connection
352
+ connection = self:Connect(function(...)
353
+ connection:Disconnect()
354
+ task.spawn(co, ...)
355
+ end)
356
+ return coroutine.yield()
357
+ end
358
+
359
+ Signal = table.freeze({
360
+ New = SignalClass.New,
361
+ })
362
+
363
+ end
364
+
365
+ ----- Private -----
366
+
367
+ local ActiveSessionCheck = {} -- {[session_token] = profile, ...}
368
+ -- SCRIBE PATCH: what LastSavedData becomes for an owner that has opted out of
369
+ -- retaining it. Frozen and shared, so releasing costs one field write and no
370
+ -- allocation -- and empty, which every existing consumer already reads as "there is
371
+ -- no baseline to compare against" (Scribe's own wipe guard tests exactly that).
372
+ local RELEASED_LAST_SAVED = table.freeze({})
373
+
374
+ local AutoSaveList = {} -- {profile, ...} -- Loaded profile table which will be circularly auto-saved
375
+ local IssueQueue = {} -- {issue_time, ...}
376
+
377
+ local DataStoreService = game:GetService("DataStoreService")
378
+ local MessagingService = game:GetService("MessagingService")
379
+ local HttpService = game:GetService("HttpService")
380
+ local RunService = game:GetService("RunService")
381
+
382
+ local PlaceId = game.PlaceId
383
+ local JobId = game.JobId
384
+
385
+ local AutoSaveIndex = 1 -- Next profile to auto save
386
+ local LastAutoSave = os.clock()
387
+
388
+ local LoadIndex = 0
389
+
390
+ local ActiveProfileLoadJobs = 0 -- Number of active threads that are loading in profiles
391
+ local ActiveProfileSaveJobs = 0 -- Number of active threads that are saving profiles
392
+
393
+ local CriticalStateStart = 0 -- os.clock()
394
+
395
+ local IsStudio = RunService:IsStudio()
396
+ local DataStoreState: "NotReady" | "NoInternet" | "NoAccess" | "Access" = "NotReady"
397
+
398
+ local MockStore = {}
399
+ local UserMockStore = {}
400
+ local MockFlag = false
401
+
402
+ local OnError = Signal.New() -- (message, store_name, profile_key)
403
+ local OnOverwrite = Signal.New() -- (store_name, profile_key)
404
+
405
+ local UpdateQueue = { -- For stability sake, we won't do UpdateAsync calls for the same key until all previous calls finish
406
+ --[[
407
+ [session_token] = {
408
+ coroutine, ...
409
+ },
410
+ ...
411
+ --]]
412
+ }
413
+
414
+ local function WaitInUpdateQueue(session_token) --> next_in_queue()
415
+
416
+ local is_first = false
417
+
418
+ if UpdateQueue[session_token] == nil then
419
+ is_first = true
420
+ UpdateQueue[session_token] = {}
421
+ end
422
+
423
+ local queue = UpdateQueue[session_token]
424
+
425
+ if is_first == false then
426
+ table.insert(queue, coroutine.running())
427
+ coroutine.yield()
428
+ end
429
+
430
+ return function()
431
+ local next_co = table.remove(queue, 1)
432
+ if next_co ~= nil then
433
+ coroutine.resume(next_co)
434
+ else
435
+ UpdateQueue[session_token] = nil
436
+ end
437
+ end
438
+
439
+ end
440
+
441
+ local function SessionToken(store_name, profile_key, is_mock)
442
+
443
+ local session_token = "L_" -- Live
444
+
445
+ if is_mock == true then
446
+ session_token = "U_" -- User mock
447
+ elseif DataStoreState ~= "Access" then
448
+ session_token = "M_" -- Mock, cause no DataStore access
449
+ end
450
+
451
+ session_token ..= store_name .. "\0" .. profile_key
452
+
453
+ return session_token
454
+
455
+ end
456
+
457
+ -- SCRIBE PATCH: buffers are COPIED, not shared. Upstream's DeepCopyTable and
458
+ -- ReconcileTable recurse on tables and pass everything else through by value,
459
+ -- which is wrong for a buffer, because a buffer IS a mutable reference.
460
+ -- (Upstream PR #22, unmerged.)
461
+ --
462
+ -- Scribe's persistent template contains buffers, so two copies were aliases:
463
+ -- template -> Data on every key mint, so every profile on the server shared one
464
+ -- buffer with the template and a write through any of them seeded every future
465
+ -- profile with the last player's bytes; and Data -> LastSavedData in Profile.New,
466
+ -- which the wipe guard diffs against live data -- aliased, it diffs live against
467
+ -- live and can never trip. Latent today only because Scribe's own datatype writes
468
+ -- always allocate a fresh buffer instead of writing through the existing one.
469
+ local function CopyBuffer(source)
470
+ local size = buffer.len(source)
471
+ local copy = buffer.create(size)
472
+ buffer.copy(copy, 0, source, 0, size)
473
+ return copy
474
+ end
475
+
476
+ local function DeepCopyTable(t)
477
+ local copy = {}
478
+ for key, value in pairs(t) do
479
+ if type(value) == "table" then
480
+ copy[key] = DeepCopyTable(value)
481
+ elseif type(value) == "buffer" then -- SCRIBE PATCH
482
+ copy[key] = CopyBuffer(value)
483
+ else
484
+ copy[key] = value
485
+ end
486
+ end
487
+ return copy
488
+ end
489
+
490
+ local function ReconcileTable(target, template)
491
+ for k, v in pairs(template) do
492
+ if type(k) == "string" then -- Only string keys will be reconciled
493
+ if target[k] == nil then
494
+ if type(v) == "table" then
495
+ target[k] = DeepCopyTable(v)
496
+ elseif type(v) == "buffer" then -- SCRIBE PATCH: see CopyBuffer
497
+ target[k] = CopyBuffer(v)
498
+ else
499
+ target[k] = v
500
+ end
501
+ elseif type(target[k]) == "table" and type(v) == "table" then
502
+ ReconcileTable(target[k], v)
503
+ end
504
+ end
505
+ end
506
+ end
507
+
508
+ local function RegisterError(error_message, store_name, profile_key) -- Called when a DataStore API call errors
509
+ warn(`[{script.Name}]: DataStore API error (STORE:{store_name}; KEY:{profile_key}) - {tostring(error_message)}`)
510
+ table.insert(IssueQueue, os.clock()) -- Adding issue time to queue
511
+ OnError:Fire(tostring(error_message), store_name, profile_key)
512
+ end
513
+
514
+ local function RegisterOverwrite(store_name, profile_key) -- Called when a corrupted profile is loaded
515
+ warn(`[{script.Name}]: Invalid profile was overwritten (STORE:{store_name}; KEY:{profile_key})`)
516
+ OnOverwrite:Fire(store_name, profile_key)
517
+ end
518
+
519
+ local function NewMockDataStoreKeyInfo(params)
520
+
521
+ local version_id_string = tostring(params.VersionId or 0)
522
+ local meta_data = params.MetaData or {}
523
+ local user_ids = params.UserIds or {}
524
+
525
+ return {
526
+ CreatedTime = params.CreatedTime,
527
+ UpdatedTime = params.UpdatedTime,
528
+ Version = string.rep("0", 16) .. "."
529
+ .. string.rep("0", 10 - string.len(version_id_string)) .. version_id_string
530
+ .. "." .. string.rep("0", 16) .. "." .. "01",
531
+
532
+ GetMetadata = function()
533
+ return DeepCopyTable(meta_data)
534
+ end,
535
+
536
+ GetUserIds = function()
537
+ return DeepCopyTable(user_ids)
538
+ end,
539
+ }
540
+
541
+ end
542
+
543
+ local function MockUpdateAsync(mock_data_store, profile_store_name, key, transform_function, is_get_call) --> loaded_data, key_info
544
+
545
+ local profile_store = mock_data_store[profile_store_name]
546
+
547
+ if profile_store == nil then
548
+ profile_store = {}
549
+ mock_data_store[profile_store_name] = profile_store
550
+ end
551
+
552
+ local epoch_time = math.floor(os.time() * 1000)
553
+ local mock_entry = profile_store[key]
554
+ local mock_entry_was_nil = false
555
+
556
+ if mock_entry == nil then
557
+ mock_entry_was_nil = true
558
+ if is_get_call ~= true then
559
+ mock_entry = {
560
+ Data = nil,
561
+ CreatedTime = epoch_time,
562
+ UpdatedTime = epoch_time,
563
+ VersionId = 0,
564
+ UserIds = {},
565
+ MetaData = {},
566
+ }
567
+ profile_store[key] = mock_entry
568
+ end
569
+ end
570
+
571
+ local mock_key_info = mock_entry_was_nil == false and NewMockDataStoreKeyInfo(mock_entry) or nil
572
+
573
+ local transform, user_ids, roblox_meta_data = transform_function(mock_entry and mock_entry.Data, mock_key_info)
574
+
575
+ if transform == nil then
576
+ return nil
577
+ else
578
+ if mock_entry ~= nil and is_get_call ~= true then
579
+ mock_entry.Data = DeepCopyTable(transform)
580
+ mock_entry.UserIds = DeepCopyTable(user_ids or {})
581
+ mock_entry.MetaData = DeepCopyTable(roblox_meta_data or {})
582
+ mock_entry.VersionId += 1
583
+ mock_entry.UpdatedTime = epoch_time
584
+ end
585
+
586
+ return DeepCopyTable(transform), mock_entry ~= nil and NewMockDataStoreKeyInfo(mock_entry) or nil
587
+ end
588
+
589
+ end
590
+
591
+ local function UpdateAsync(profile_store, profile_key, transform_params, is_user_mock, is_get_call, version) --> loaded_data, key_info
592
+ --transform_params = {
593
+ -- ExistingProfileHandle = function(latest_data),
594
+ -- MissingProfileHandle = function(latest_data),
595
+ -- EditProfile = function(latest_data),
596
+ --}
597
+
598
+ local loaded_data, key_info
599
+
600
+ local next_in_queue = WaitInUpdateQueue(SessionToken(profile_store.Name, profile_key, is_user_mock))
601
+
602
+ local success = true
603
+
604
+ local success, error_message = pcall(function()
605
+ local transform_function = function(latest_data)
606
+
607
+ local missing_profile = false
608
+ local overwritten = false
609
+ local global_updates = {0, {}}
610
+
611
+ if latest_data == nil then
612
+
613
+ missing_profile = true
614
+
615
+ elseif type(latest_data) ~= "table" then
616
+
617
+ missing_profile = true
618
+ overwritten = true
619
+
620
+ else
621
+
622
+ if type(latest_data.Data) == "table" and type(latest_data.MetaData) == "table" and type(latest_data.GlobalUpdates) == "table" then
623
+
624
+ -- Regular profile structure detected:
625
+
626
+ latest_data.WasOverwritten = false -- Must be set to false if set previously
627
+ global_updates = latest_data.GlobalUpdates
628
+
629
+ if transform_params.ExistingProfileHandle ~= nil then
630
+ transform_params.ExistingProfileHandle(latest_data)
631
+ end
632
+
633
+ elseif latest_data.Data == nil and latest_data.MetaData == nil and type(latest_data.GlobalUpdates) == "table" then
634
+
635
+ -- Regular structure not detected, but GlobalUpdate data exists:
636
+
637
+ latest_data.WasOverwritten = false -- Must be set to false if set previously
638
+ global_updates = latest_data.GlobalUpdates or global_updates
639
+ missing_profile = true
640
+
641
+ else
642
+
643
+ missing_profile = true
644
+ overwritten = true
645
+
646
+ end
647
+
648
+ end
649
+
650
+ -- Profile was not created or corrupted and no GlobalUpdate data exists:
651
+ if missing_profile == true then
652
+ latest_data = {
653
+ -- Data = nil,
654
+ -- MetaData = nil,
655
+ GlobalUpdates = global_updates,
656
+ }
657
+ if transform_params.MissingProfileHandle ~= nil then
658
+ transform_params.MissingProfileHandle(latest_data)
659
+ end
660
+ end
661
+
662
+ -- Editing profile:
663
+ if transform_params.EditProfile ~= nil then
664
+ transform_params.EditProfile(latest_data)
665
+ end
666
+
667
+ -- SCRIBE PATCH: let a transform genuinely DECLINE. Every path below used
668
+ -- to return latest_data, and UpdateAsync commits unless the transform
669
+ -- returns nil -- so a refused compare-and-set still minted a key version,
670
+ -- spent a write budget, and (on the missing-profile path above) created a
671
+ -- stub key that had never existed.
672
+ if transform_params.AbortWrite == true then
673
+ return nil
674
+ end
675
+
676
+ -- Invalid data handling (Silently override with empty profile)
677
+ if overwritten == true then
678
+ latest_data.WasOverwritten = true -- Temporary tag that will be removed on first save
679
+ end
680
+
681
+ return latest_data, latest_data.UserIds, latest_data.RobloxMetaData
682
+ end
683
+
684
+ if is_user_mock == true then -- Used when the profile is accessed through ProfileStore.Mock
685
+
686
+ loaded_data, key_info = MockUpdateAsync(UserMockStore, profile_store.Name, profile_key, transform_function, is_get_call)
687
+ task.wait() -- Simulate API call yield
688
+
689
+ elseif DataStoreState ~= "Access" then -- Used when API access is disabled
690
+
691
+ loaded_data, key_info = MockUpdateAsync(MockStore, profile_store.Name, profile_key, transform_function, is_get_call)
692
+ task.wait() -- Simulate API call yield
693
+
694
+ else
695
+
696
+ if is_get_call == true then
697
+
698
+ if version ~= nil then
699
+
700
+ local success, error_message = pcall(function()
701
+ loaded_data, key_info = profile_store.data_store:GetVersionAsync(profile_key, version)
702
+ end)
703
+
704
+ if success == false and type(error_message) == "string" and string.find(error_message, "not valid") ~= nil then
705
+ warn(`[{script.Name}]: Passed version argument is not valid; Traceback:\n` .. debug.traceback())
706
+ end
707
+
708
+ else
709
+
710
+ loaded_data, key_info = profile_store.data_store:GetAsync(profile_key)
711
+
712
+ end
713
+
714
+ loaded_data = transform_function(loaded_data)
715
+
716
+ else
717
+
718
+ loaded_data, key_info = profile_store.data_store:UpdateAsync(profile_key, transform_function)
719
+
720
+ end
721
+
722
+ end
723
+
724
+ end)
725
+
726
+ next_in_queue()
727
+
728
+ if success == true and type(loaded_data) == "table" then
729
+ -- Invalid data handling:
730
+ if loaded_data.WasOverwritten == true and is_get_call ~= true then
731
+ RegisterOverwrite(
732
+ profile_store.Name,
733
+ profile_key
734
+ )
735
+ end
736
+ -- Return loaded_data:
737
+ return loaded_data, key_info
738
+ elseif success == true and transform_params.AbortWrite == true then
739
+ -- SCRIBE PATCH: a transform that DECLINED is not a DataStore error.
740
+ --
741
+ -- A refusal returns nil, and so does a FAILED call; this branch could not
742
+ -- tell them apart, so every refusal warned, added an entry to IssueQueue
743
+ -- (five inside the window flip IsCriticalState) and fired OnError -- which
744
+ -- Scribe reports as PROFILE_STORE_ERROR and feeds into Health, where an
745
+ -- Outage refuses Robux grants for every player on the server.
746
+ -- UpdateOfflineAsync guards the same condition at its call site, but on the
747
+ -- RETURN VALUE, by which time OnError has fired; both stay, because they
748
+ -- answer different questions.
749
+ --
750
+ -- `success == true` is load-bearing: a transform that set AbortWrite and
751
+ -- THEN hit a failing DataStore call must still be registered, so a genuine
752
+ -- outage cannot hide behind a refusal.
753
+ return nil
754
+ else
755
+ -- Error handling:
756
+ -- SCRIBE PATCH: KEEP the error, do not only report it. RegisterError warns,
757
+ -- queues an issue and fires OnError, and then the string is gone -- every
758
+ -- failure class reached the caller as the same bare nil, which is what forced
759
+ -- MessageAsync's `provably_clean` to be guessed from an attempt COUNT. See the
760
+ -- note on `provably_clean` in MessageAsync for what is done with the class.
761
+ --
762
+ -- Written onto transform_params, which the caller already owns and already
763
+ -- reads for AbortWrite and QueueFull, so the return signature is unchanged and
764
+ -- the `table.pack(UpdateAsync(...))` in StartSessionAsync keeps its arity.
765
+ transform_params.ErrorMessage = error_message
766
+ RegisterError(
767
+ error_message or "Undefined error",
768
+ profile_store.Name,
769
+ profile_key
770
+ )
771
+ -- Return nothing:
772
+ return nil
773
+ end
774
+
775
+ end
776
+
777
+ local function IsThisSession(session_tag)
778
+ return session_tag[1] == PlaceId and session_tag[2] == JobId
779
+ end
780
+
781
+ local function ReadMockFlag(): boolean
782
+ local is_mock = MockFlag
783
+ MockFlag = false
784
+ return is_mock
785
+ end
786
+
787
+ local function WaitForStoreReady(profile_store)
788
+ while profile_store.is_ready == false do
789
+ task.wait()
790
+ end
791
+ end
792
+
793
+ local function AddProfileToAutoSave(profile)
794
+
795
+ ActiveSessionCheck[profile.session_token] = profile
796
+
797
+ -- Add at AutoSaveIndex and move AutoSaveIndex right:
798
+
799
+ table.insert(AutoSaveList, AutoSaveIndex, profile)
800
+
801
+ if #AutoSaveList > 1 then
802
+ AutoSaveIndex = AutoSaveIndex + 1
803
+ elseif #AutoSaveList == 1 then
804
+ -- First profile created - make sure it doesn't get immediately auto saved:
805
+ LastAutoSave = os.clock()
806
+ end
807
+
808
+ end
809
+
810
+ local function RemoveProfileFromAutoSave(profile)
811
+
812
+ ActiveSessionCheck[profile.session_token] = nil
813
+
814
+ local auto_save_index = table.find(AutoSaveList, profile)
815
+
816
+ if auto_save_index ~= nil then
817
+ table.remove(AutoSaveList, auto_save_index)
818
+ if auto_save_index < AutoSaveIndex then
819
+ AutoSaveIndex = AutoSaveIndex - 1 -- Table contents were moved left before AutoSaveIndex so move AutoSaveIndex left as well
820
+ end
821
+ if AutoSaveList[AutoSaveIndex] == nil then -- AutoSaveIndex was at the end of the AutoSaveList - reset to 1
822
+ AutoSaveIndex = 1
823
+ end
824
+ end
825
+
826
+ end
827
+
828
+ local function SaveProfileAsync(profile, is_ending_session, is_overwriting, last_save_reason)
829
+
830
+ if type(profile.Data) ~= "table" then
831
+ error(`[{script.Name}]: Developer code likely set "Profile.Data" to a non-table value! (STORE:{profile.ProfileStore.Name}; KEY:{profile.Key})`)
832
+ end
833
+
834
+ -- SCRIBE PATCH: a context owned by THIS call, handed to OnSave and returned to
835
+ -- the caller, so a handler can record something about the save it is running
836
+ -- inside. Anything stored on `entry` instead would be a single slot shared by
837
+ -- every in-flight save. Existing handlers take no arguments and are unaffected.
838
+ local save_context = {}
839
+ profile.OnSave:Fire(save_context)
840
+ if is_ending_session == true then
841
+ profile.OnLastSave:Fire(last_save_reason or "Manual")
842
+ end
843
+
844
+ if is_ending_session == true and is_overwriting ~= true then
845
+ if profile.roblox_message_subscription ~= nil then
846
+ profile.roblox_message_subscription:Disconnect()
847
+ end
848
+ RemoveProfileFromAutoSave(profile)
849
+ profile.OnSessionEnd:Fire()
850
+ end
851
+
852
+ ActiveProfileSaveJobs = ActiveProfileSaveJobs + 1
853
+
854
+ -- Compare "SessionLoadCount" when writing to profile to prevent a rare case of repeat last save when the profile is loaded on the same server again
855
+
856
+ local repeat_save_flag = true -- Released Profile save calls have to repeat until they succeed
857
+ local exp_backoff = 1
858
+ -- SCRIBE PATCH: what THIS call achieved. nil until a round trip settles it.
859
+ local outcome: string? = nil
860
+
861
+ while repeat_save_flag == true do
862
+
863
+ if is_ending_session ~= true then
864
+ repeat_save_flag = false
865
+ end
866
+
867
+ -- SCRIBE PATCH: the release a save performs when it turns out not to own the
868
+ -- profile. Extracted so the removed-key path below can take the SAME one
869
+ -- rather than growing a second copy that drifts.
870
+ local function release_not_owned()
871
+ if profile.roblox_message_subscription ~= nil then
872
+ profile.roblox_message_subscription:Disconnect()
873
+ end
874
+ if profile:IsActive() == true then
875
+ RemoveProfileFromAutoSave(profile)
876
+ profile.OnSessionEnd:Fire()
877
+ end
878
+ end
879
+
880
+ -- SCRIBE PATCH: set by the transform when the key has been REMOVED under this
881
+ -- live session. See the note at its assignment.
882
+ local key_removed = false
883
+ local transform_params
884
+ transform_params = {
885
+ ExistingProfileHandle = nil,
886
+ MissingProfileHandle = nil,
887
+ AbortWrite = false,
888
+ EditProfile = function(latest_data)
889
+
890
+ -- Check if this session still owns the profile:
891
+
892
+ local session_owns_profile = false
893
+
894
+ if is_overwriting ~= true then
895
+
896
+ -- SCRIBE PATCH: `type(latest_data.MetaData) == "table"`.
897
+ --
898
+ -- A key REMOVED under a live session (a GDPR erase that raced the
899
+ -- session start) reaches this transform as UpdateAsync's
900
+ -- missing-profile stub -- GlobalUpdates and nothing else. Indexing
901
+ -- MetaData on it threw inside UpdateAsync's own pcall, so the save
902
+ -- neither wrote nor released; and because that repeated on every
903
+ -- autosave the session stayed ACTIVE FOREVER, accepting writes it
904
+ -- silently discarded. Measured: 200 s at a 30 s autosave period,
905
+ -- still Ready, every write gone. No MetaData means no ActiveSession,
906
+ -- so leaving session_owns_profile false routes it to the same clean
907
+ -- release a stolen session takes.
908
+ if type(latest_data.MetaData) == "table" then
909
+ local active_session = latest_data.MetaData.ActiveSession
910
+ local session_load_count = latest_data.MetaData.SessionLoadCount
911
+
912
+ if type(active_session) == "table" then
913
+ session_owns_profile = IsThisSession(active_session)
914
+ and session_load_count == profile.load_index
915
+ end
916
+ else
917
+ -- The key is gone. Write NOTHING: committing here would
918
+ -- recreate it as a GlobalUpdates-only stub, and an erased user
919
+ -- whose key exists again answers Data.GetOffline as though the
920
+ -- erase had not happened. Measured before this abort was added:
921
+ -- keyShape=GlobalUpdates, getOffline=true.
922
+ key_removed = true
923
+ transform_params.AbortWrite = true
924
+ end
925
+
926
+ else
927
+ session_owns_profile = true
928
+ end
929
+
930
+ -- We may only edit the profile if this server has ownership of the profile:
931
+
932
+ if session_owns_profile == true then
933
+
934
+ -- Clear processed updates (messages):
935
+
936
+ local locked_updates = profile.locked_global_updates -- [index] = true, ...
937
+ local active_updates = latest_data.GlobalUpdates[2]
938
+ -- ProfileService module format: {{update_id, version_id, update_locked, update_data}, ...}
939
+ -- ProfileStore module format: {{update_id, update_data}, ...}
940
+
941
+ -- SCRIBE PATCH: `and profile.scribe_release_only ~= true`.
942
+ --
943
+ -- Retiring a message and persisting the data that message
944
+ -- produced have to land in the SAME UpdateAsync, or delivery
945
+ -- degrades from at-least-once to at-most-once. This sweep sat
946
+ -- OUTSIDE the release-only gate below, so a release that
947
+ -- deliberately writes no Data still deleted every update
948
+ -- processed() had acknowledged: the gift was consumed into
949
+ -- profile.Data, profile.Data was then not written, and the
950
+ -- message that would have redelivered it was gone from the key.
951
+ --
952
+ -- Skipping the sweep leaves the update in storage, so the next
953
+ -- session is handed it again. A duplicate delivery is recoverable
954
+ -- (Scribe dedupes on ProcessedPurchaseIds) and a dropped one is
955
+ -- not. Leaving the ids in locked_global_updates is safe: the
956
+ -- prune after the round trip drops an id once storage stops
957
+ -- listing it, and a release-only save is ending this session.
958
+ if next(locked_updates) ~= nil and profile.scribe_release_only ~= true then
959
+ local i = 1
960
+ while i <= #active_updates do
961
+ local update = active_updates[i]
962
+ if locked_updates[update[1]] == true then
963
+ table.remove(active_updates, i)
964
+ else
965
+ i += 1
966
+ end
967
+ end
968
+ end
969
+
970
+ -- Save profile data:
971
+
972
+ -- SCRIBE PATCH: a release that deliberately writes no Data.
973
+ --
974
+ -- Scribe's three fail-closed load paths (a failed migration, a
975
+ -- rejected schema check, a refused load) promise the stored bytes
976
+ -- are left alone so the profile can be inspected and recovered.
977
+ -- Ending the session breaks that: EndSession is
978
+ -- SaveProfileAsync(..., is_ending_session), and by the time those
979
+ -- paths run, profile.Data has already been through CoerceMapKeys,
980
+ -- Reconcile, the version stamp and the whole migration chain.
981
+ -- Measured: a rejected profile came back with template defaults
982
+ -- backfilled into storage and the key version advanced twice.
983
+ --
984
+ -- The lock still has to be released or the player cannot rejoin
985
+ -- anywhere, so this writes MetaData and nothing else. Data,
986
+ -- RobloxMetaData and UserIds keep whatever is on the key.
987
+ if profile.scribe_release_only ~= true then
988
+ latest_data.Data = profile.Data
989
+ -- SCRIBE PATCH: WHICH table this write serialized, recorded at WRITE
990
+ -- time. A caller that decided what its payload was when ITS OnSave fired
991
+ -- is describing the pointer as it stood at SNAPSHOT time, and the line
992
+ -- above reads it now; see the hazard note on SetSaveSource.
993
+ --
994
+ -- The identity, not a verdict: the store has no idea what a wipe guard
995
+ -- is. It reports which table went to the key and lets the caller compare
996
+ -- that against whatever it considers live.
997
+ save_context.SavedSource = profile.Data
998
+ latest_data.RobloxMetaData = profile.RobloxMetaData
999
+ latest_data.UserIds = profile.UserIds
1000
+ else
1001
+ -- SCRIBE PATCH: tell the caller this write carried no Data.
1002
+ --
1003
+ -- The outcome of a release-only save is still "Saved", and correctly
1004
+ -- so -- it IS a successful write, of MetaData. But an AwaitSave that
1005
+ -- reads only the outcome therefore answers TRUE for a save that put
1006
+ -- none of the caller's bytes on disk. Scribe's monetization path
1007
+ -- returns PurchaseGranted on that boolean and Roblox never retries a
1008
+ -- granted receipt, so the lie is paid Robux for data that was never
1009
+ -- stored. Measured on a prototype that set the flag on a Ready profile:
1010
+ -- one run minted 40 coins, another destroyed 40.
1011
+ --
1012
+ -- Recorded here in the transform rather than when OnSave fired:
1013
+ -- release-only is decided at WRITE time, and a save already on the wire
1014
+ -- when the flag was set writes no Data while an OnSave-time capture
1015
+ -- would still report that it did.
1016
+ save_context.ReleaseOnly = true
1017
+ end
1018
+
1019
+ -- SCRIBE PATCH: bumped ABOVE the branch, so the OVERWRITE arm
1020
+ -- gets it too. That arm is the view-mode SetAsync that
1021
+ -- RestoreVersion commits through, and it stamps neither
1022
+ -- LastUpdate nor SessionLoadCount -- so before this counter a
1023
+ -- view write left the compare-and-set fingerprint byte-identical
1024
+ -- and a stale CAS silently reverted an operator's restore.
1025
+ latest_data.MetaData.WriteIndex = (latest_data.MetaData.WriteIndex or 0) + 1
1026
+
1027
+ if is_overwriting ~= true then
1028
+
1029
+ latest_data.MetaData.LastUpdate = os.time()
1030
+
1031
+ if is_ending_session == true then
1032
+ latest_data.MetaData.ActiveSession = nil
1033
+ end
1034
+
1035
+ else
1036
+
1037
+ latest_data.MetaData.ActiveSession = nil
1038
+ latest_data.MetaData.ForceLoadSession = nil
1039
+
1040
+ end
1041
+
1042
+ end
1043
+
1044
+ end,
1045
+ }
1046
+
1047
+ local loaded_data, key_info = UpdateAsync(profile.ProfileStore, profile.Key, transform_params, profile.is_mock)
1048
+
1049
+ if key_removed == true then
1050
+ -- Nothing was written and nothing can be: this session no longer owns a
1051
+ -- key that no longer exists. Release it the same way a stolen session is
1052
+ -- released, so the holder stops accepting writes it would silently drop.
1053
+ repeat_save_flag = false
1054
+ release_not_owned()
1055
+ outcome = "NotOwned"
1056
+ profile.OnAfterSave:Fire(profile.LastSavedData)
1057
+ break
1058
+ end
1059
+
1060
+ if loaded_data ~= nil and key_info ~= nil then
1061
+
1062
+ if is_overwriting == true then
1063
+ -- SCRIBE PATCH: the round trip returned, so an overwrite ends here having
1064
+ -- written. Unreachable today (no caller passes is_overwriting), assigned so
1065
+ -- it stays correct if one ever does.
1066
+ outcome = "Saved"
1067
+ break
1068
+ end
1069
+
1070
+ repeat_save_flag = false
1071
+
1072
+ -- SCRIBE PATCH: same missing-MetaData tolerance as the transform above --
1073
+ -- these three reads threw on a removed key too, one statement later.
1074
+ local latest_meta = if type(loaded_data.MetaData) == "table" then loaded_data.MetaData else nil
1075
+ local active_session = if latest_meta then latest_meta.ActiveSession else nil
1076
+ local session_load_count = if latest_meta then latest_meta.SessionLoadCount else nil
1077
+ local session_owns_profile = false
1078
+
1079
+ if type(active_session) == "table" then
1080
+ session_owns_profile = IsThisSession(active_session) and session_load_count == profile.load_index
1081
+ end
1082
+
1083
+ local force_load_session = if latest_meta then latest_meta.ForceLoadSession else nil
1084
+ local force_load_pending = false
1085
+ if type(force_load_session) == "table" then
1086
+ force_load_pending = not IsThisSession(force_load_session)
1087
+ end
1088
+
1089
+ local is_active = profile:IsActive()
1090
+
1091
+ -- If another server is trying to start a session for this profile - end the session:
1092
+
1093
+ if force_load_pending == true and session_owns_profile == true then
1094
+ -- SCRIBE PATCH: report what THIS call achieved before handing over. The
1095
+ -- transform wrote and the bytes are on the key; breaking with `outcome`
1096
+ -- unassigned made `outcome or "Failed"` below report a failure for a save
1097
+ -- that persisted, which AwaitSave, Data.Flush and the receipt path all read.
1098
+ outcome = "Saved"
1099
+ if is_active == true then
1100
+ SaveProfileAsync(profile, true, false, "External")
1101
+ end
1102
+ break
1103
+ end
1104
+
1105
+ -- Clearing processed update list / Detecting new updates:
1106
+
1107
+ local locked_updates = profile.locked_global_updates -- [index] = true, ...
1108
+ local received_updates = profile.received_global_updates -- [index] = true, ...
1109
+ local active_updates = loaded_data.GlobalUpdates[2]
1110
+
1111
+ local new_updates = {} -- {}, ...
1112
+ local still_pending = {} -- [index] = true, ...
1113
+
1114
+ for _, update in ipairs(active_updates) do
1115
+ if locked_updates[update[1]] == true then
1116
+ still_pending[update[1]] = true
1117
+ elseif received_updates[update[1]] ~= true then
1118
+ received_updates[update[1]] = true
1119
+ table.insert(new_updates, update)
1120
+ end
1121
+ end
1122
+
1123
+ for index in pairs(locked_updates) do
1124
+ if still_pending[index] ~= true then
1125
+ locked_updates[index] = nil
1126
+ end
1127
+ end
1128
+
1129
+ -- Updating profile values:
1130
+
1131
+ profile.KeyInfo = key_info
1132
+ -- SCRIBE PATCH: a removed key's stub carries no Data, and overwriting the
1133
+ -- last known good copy with nil would hand every OnAfterSave handler a nil.
1134
+ if loaded_data.Data ~= nil then
1135
+ profile.LastSavedData = loaded_data.Data
1136
+ end
1137
+ profile.global_updates = loaded_data.GlobalUpdates and loaded_data.GlobalUpdates[2] or {}
1138
+
1139
+ if session_owns_profile == true then
1140
+ if is_active == true and is_ending_session ~= true then
1141
+
1142
+ -- Processing new global updates (messages):
1143
+
1144
+ for _, update in ipairs(new_updates) do
1145
+
1146
+ local index = update[1]
1147
+ local update_data = update[#update] -- Backwards compatibility with ProfileService
1148
+
1149
+ for _, handler in ipairs(profile.message_handlers) do
1150
+
1151
+ local is_processed = false
1152
+ local processed_callback = function()
1153
+ is_processed = true
1154
+ locked_updates[index] = true
1155
+ end
1156
+
1157
+ local send_update_data = DeepCopyTable(update_data)
1158
+
1159
+ task.spawn(handler, send_update_data, processed_callback)
1160
+
1161
+ if is_processed == true then
1162
+ break
1163
+ end
1164
+
1165
+ end
1166
+
1167
+ end
1168
+
1169
+ end
1170
+ else
1171
+ release_not_owned()
1172
+ end
1173
+
1174
+ -- SCRIBE PATCH: set BEFORE OnAfterSave fires, so a handler can never observe
1175
+ -- a settled save whose outcome has not been recorded yet.
1176
+ outcome = if session_owns_profile == true then "Saved" else "NotOwned"
1177
+
1178
+ profile.OnAfterSave:Fire(profile.LastSavedData)
1179
+
1180
+ -- SCRIBE PATCH: drop the decoded response once the handlers have seen it.
1181
+ --
1182
+ -- LastSavedData is a SECOND FULL COPY of the profile, held for the life of
1183
+ -- the session. Measured: 200 deep copies of ~22 KB profiles raised the heap
1184
+ -- counter by 18.2 MiB against the live set's 22.1 MiB -- 83%, and not 100%
1185
+ -- because deep copies share interned strings while the table structure and
1186
+ -- boxed values are duplicated in full.
1187
+ --
1188
+ -- Whether releasing hands that back is NOT measurable here: Luau exposes only
1189
+ -- collectgarbage("count") with no forced collect, so an end-to-end comparison
1190
+ -- measures the collector's schedule instead, and it returned a NEGATIVE delta.
1191
+ -- The claim that does not need the collector is that this table stops being
1192
+ -- retained for the whole session and becomes collectable as soon as the save
1193
+ -- that produced it is done with.
1194
+ --
1195
+ -- Released AFTER OnAfterSave so a handler computing a summary still receives
1196
+ -- the real thing; opt-in, so an owner that says nothing is unaffected.
1197
+ if profile.scribe_retain_last_saved == false then
1198
+ profile.LastSavedData = RELEASED_LAST_SAVED
1199
+ end
1200
+
1201
+ elseif repeat_save_flag == true then
1202
+
1203
+ -- DataStore call likely resulted in an error; Repeat the DataStore call shortly
1204
+ task.wait(exp_backoff)
1205
+ exp_backoff = math.min(if last_save_reason == "Shutdown" then 8 else 20, exp_backoff * 2)
1206
+
1207
+ end
1208
+
1209
+ end
1210
+
1211
+ ActiveProfileSaveJobs = ActiveProfileSaveJobs - 1
1212
+
1213
+ -- SCRIBE PATCH: nil means every attempt errored -- for a live (non-ending) save
1214
+ -- that is exactly one attempt, because repeat_save_flag is cleared on entry.
1215
+ local settled = outcome or "Failed"
1216
+
1217
+ -- SCRIBE PATCH: the one place every call leaves, so the pairing with OnSave is
1218
+ -- exact. pcall'd because a handler that throws must not strand the save job
1219
+ -- count that was just decremented above.
1220
+ pcall(function()
1221
+ profile.OnSettled:Fire(save_context, settled)
1222
+ end)
1223
+
1224
+ return settled, save_context
1225
+
1226
+ end
1227
+
1228
+ ----- Public -----
1229
+
1230
+ --[[
1231
+ Saved profile structure:
1232
+
1233
+ {
1234
+ Data = {},
1235
+
1236
+ MetaData = {
1237
+ ProfileCreateTime = 0,
1238
+ SessionLoadCount = 0,
1239
+ ActiveSession = {place_id, game_job_id, unique_session_id} / nil,
1240
+ ForceLoadSession = {place_id, game_job_id} / nil,
1241
+ LastUpdate = 0, -- os.time()
1242
+ MetaTags = {}, -- Backwards compatibility with ProfileService
1243
+ },
1244
+
1245
+ RobloxMetaData = {},
1246
+ UserIds = {},
1247
+
1248
+ GlobalUpdates = {
1249
+ update_index,
1250
+ {
1251
+ {update_index, data}, ...
1252
+ },
1253
+ },
1254
+ }
1255
+
1256
+ --]]
1257
+
1258
+ export type JSONAcceptable = { JSONAcceptable } | { [string]: JSONAcceptable } | number | string | boolean | buffer
1259
+
1260
+ export type Profile<T> = {
1261
+ Data: T & JSONAcceptable,
1262
+ LastSavedData: T & JSONAcceptable,
1263
+ FirstSessionTime: number,
1264
+ SessionLoadCount: number,
1265
+ Session: {PlaceId: number, JobId: string}?,
1266
+ RobloxMetaData: JSONAcceptable,
1267
+ UserIds: {number},
1268
+ KeyInfo: DataStoreKeyInfo,
1269
+ OnSave: {Connect: (self: any, listener: () -> ()) -> ({Disconnect: (self: any) -> ()})},
1270
+ OnLastSave: {Connect: (self: any, listener: (reason: "Manual" | "External" | "Shutdown") -> ()) -> ({Disconnect: (self: any) -> ()})},
1271
+ OnSessionEnd: {Connect: (self: any, listener: () -> ()) -> ({Disconnect: (self: any) -> ()})},
1272
+ OnAfterSave: {Connect: (self: any, listener: (last_saved_data: T & JSONAcceptable) -> ()) -> ({Disconnect: (self: any) -> ()})},
1273
+ ProfileStore: JSONAcceptable,
1274
+ Key: string,
1275
+
1276
+ IsActive: (self: any) -> (boolean),
1277
+ Reconcile: (self: any) -> (),
1278
+ EndSession: (self: any) -> (),
1279
+ AddUserId: (self: any, user_id: number) -> (),
1280
+ RemoveUserId: (self: any, user_id: number) -> (),
1281
+ MessageHandler: (self: any, fn: (message: JSONAcceptable, processed: () -> ()) -> ()) -> (),
1282
+ Save: (self: any) -> (),
1283
+ SetAsync: (self: any) -> (),
1284
+ }
1285
+
1286
+ export type VersionQuery<T> = {
1287
+ NextAsync: (self: any) -> (Profile<T>?),
1288
+ }
1289
+
1290
+ type ProfileStoreStandard<T> = {
1291
+ Name: string,
1292
+ StartSessionAsync: (self: any, profile_key: string, params: {Steal: boolean?}) -> (Profile<T>?),
1293
+ -- SCRIBE PATCH: (is_success, reason, provably_clean); see MessageAsync's body.
1294
+ MessageAsync: (self: any, profile_key: string, message: JSONAcceptable) -> (boolean, string?, boolean?),
1295
+ GetAsync: (self: any, profile_key: string, version: string?) -> (Profile<T>?),
1296
+ VersionQuery: (self: any, profile_key: string, sort_direction: Enum.SortDirection?, min_date: DateTime | number | nil, max_date: DateTime | number | nil) -> (VersionQuery<T>),
1297
+ RemoveAsync: (self: any, profile_key: string) -> (boolean),
1298
+ }
1299
+
1300
+ export type ProfileStore<T> = {
1301
+ Mock: ProfileStoreStandard<T>,
1302
+ } & ProfileStoreStandard<T>
1303
+
1304
+ type ConstantName = "AUTO_SAVE_PERIOD" | "LOAD_REPEAT_PERIOD" | "FIRST_LOAD_REPEAT" | "SESSION_STEAL"
1305
+ | "ASSUME_DEAD" | "START_SESSION_TIMEOUT" | "CRITICAL_STATE_ERROR_COUNT" | "CRITICAL_STATE_ERROR_EXPIRE"
1306
+ | "CRITICAL_STATE_EXPIRE" | "MAX_MESSAGE_QUEUE"
1307
+
1308
+ export type ProfileStoreModule = {
1309
+ IsClosing: boolean,
1310
+ IsCriticalState: boolean,
1311
+ OnError: {Connect: (self: any, listener: (message: string, store_name: string, profile_key: string) -> ()) -> ({Disconnect: (self: any) -> ()})},
1312
+ OnOverwrite: {Connect: (self: any, listener: (store_name: string, profile_key: string) -> ()) -> ({Disconnect: (self: any) -> ()})},
1313
+ OnCriticalToggle: {Connect: (self: any, listener: (is_critical: boolean) -> ()) -> ({Disconnect: (self: any) -> ()})},
1314
+ DataStoreState: "NotReady" | "NoInternet" | "NoAccess" | "Access",
1315
+ -- SCRIBE PATCH: see the Dependencies note. Optional, and nil is the pre-hook
1316
+ -- behaviour rather than a broken state.
1317
+ ClassifyError: ((message: any) -> string)?,
1318
+ New: <T>(store_name: string, template: (T & JSONAcceptable)?) -> (ProfileStore<T>),
1319
+ SetConstant: (name: ConstantName, value: number) -> ()
1320
+ }
1321
+
1322
+ local Profile = {}
1323
+ Profile.__index = Profile
1324
+
1325
+ function Profile.New(raw_data, key_info, profile_store, key, is_mock, session_token)
1326
+
1327
+ local data = raw_data.Data or {}
1328
+ local session = raw_data.MetaData and raw_data.MetaData.ActiveSession or nil
1329
+
1330
+ local global_updates = raw_data.GlobalUpdates and raw_data.GlobalUpdates[2] or {}
1331
+ local received_global_updates = {}
1332
+
1333
+ for _, update in ipairs(global_updates) do
1334
+ received_global_updates[update[1]] = true
1335
+ end
1336
+
1337
+ local self = {
1338
+
1339
+ Data = data,
1340
+ LastSavedData = DeepCopyTable(data),
1341
+
1342
+ FirstSessionTime = raw_data.MetaData and raw_data.MetaData.ProfileCreateTime or 0,
1343
+ -- SCRIBE PATCH: the key's lineage; false for a key minted before it.
1344
+ Generation = raw_data.MetaData and raw_data.MetaData.Generation or false,
1345
+ SessionLoadCount = raw_data.MetaData and raw_data.MetaData.SessionLoadCount or 0,
1346
+ -- SCRIBE PATCH: exposed so a caller can fingerprint what it read and hand
1347
+ -- that to UpdateOfflineAsync. Every owning save stamps it, so a key that
1348
+ -- moved between the read and the write fails the comparison.
1349
+ LastUpdate = raw_data.MetaData and raw_data.MetaData.LastUpdate or 0,
1350
+ -- SCRIBE PATCH: the fingerprint LastUpdate cannot be on its own -- it has
1351
+ -- one-second granularity, and a view-mode SetAsync moves neither it nor
1352
+ -- SessionLoadCount. This counter moves on EVERY committing write; the full
1353
+ -- reasoning is at UpdateOfflineAsync.
1354
+ --
1355
+ -- `or 0` on read, and `or 0` on BOTH sides of the comparison in
1356
+ -- UpdateOfflineAsync: a profile saved by an older build carries no WriteIndex,
1357
+ -- and it must be exactly as permissive as it was before -- neither failing
1358
+ -- every CAS nor passing every one. The first post-upgrade write installs 1.
1359
+ WriteIndex = raw_data.MetaData and raw_data.MetaData.WriteIndex or 0,
1360
+ Session = session and {PlaceId = session[1], JobId = session[2]},
1361
+
1362
+ RobloxMetaData = raw_data.RobloxMetaData or {},
1363
+ UserIds = raw_data.UserIds or {},
1364
+ KeyInfo = key_info,
1365
+
1366
+ OnAfterSave = Signal.New(),
1367
+ OnSave = Signal.New(),
1368
+ -- SCRIBE PATCH: fires exactly ONCE per SaveProfileAsync call, whatever the
1369
+ -- outcome -- (save_context, "Saved" | "NotOwned" | "Failed").
1370
+ --
1371
+ -- OnSave and OnAfterSave cannot be paired up by an observer: OnSave fires per
1372
+ -- call, OnAfterSave only on success, so a save that fails leaves the pair
1373
+ -- unbalanced and anything counting in-flight saves leaks. Scribe tracked that
1374
+ -- in a single timestamp slot, and a failure arriving after a concurrent success
1375
+ -- had cleared it was dropped: LastResult stayed "Ok", Dirty stayed false, and
1376
+ -- SavesFailed never moved.
1377
+ OnSettled = Signal.New(),
1378
+ OnLastSave = Signal.New(),
1379
+ OnSessionEnd = Signal.New(),
1380
+
1381
+ ProfileStore = profile_store,
1382
+ Key = key,
1383
+
1384
+ load_timestamp = os.clock(),
1385
+ is_mock = is_mock,
1386
+ session_token = session_token or "",
1387
+ load_index = raw_data.MetaData and raw_data.MetaData.SessionLoadCount or 0,
1388
+ locked_global_updates = {},
1389
+ received_global_updates = received_global_updates,
1390
+ message_handlers = {},
1391
+ global_updates = global_updates,
1392
+
1393
+ }
1394
+ setmetatable(self, Profile)
1395
+
1396
+ return self
1397
+
1398
+ end
1399
+
1400
+ function Profile:IsActive()
1401
+ return ActiveSessionCheck[self.session_token] == self
1402
+ end
1403
+
1404
+ function Profile:Reconcile()
1405
+ ReconcileTable(self.Data, self.ProfileStore.template)
1406
+ end
1407
+
1408
+ -- SCRIBE PATCH: has a save for this profile ever committed?
1409
+ --
1410
+ -- This tells a returning player who has simply never earned anything from one
1411
+ -- whose FIRST session crashed before its save landed. Those look identical by
1412
+ -- every other measure -- SessionLoadCount advances when a session STARTS -- and
1413
+ -- treating the second as "returning" skips their legacy import and their
1414
+ -- migrations, then saves an empty profile over the top as canonical.
1415
+ --
1416
+ -- UserIds answers it, and the answer is a property of THIS module rather than
1417
+ -- of the DataStore: the list is written to the key only as part of a completed
1418
+ -- save (SaveProfileAsync's EditProfile, above), and neither key-minting path --
1419
+ -- the MissingProfileHandle in StartSessionAsync nor the one in GetAsync --
1420
+ -- seeds it.
1421
+ --
1422
+ -- ONE LIMIT: AddUserId no-ops for a NEGATIVE user id outside mock (it refuses
1423
+ -- to hand Roblox's APIs one), so the signal never accumulates for a profile
1424
+ -- keyed on one. A caller that mints negative ids must exclude them itself.
1425
+ function Profile:HasCompletedSave()
1426
+ return #self.UserIds > 0
1427
+ end
1428
+
1429
+ -- SCRIBE PATCH: how many sessions have been STARTED for this profile.
1430
+ --
1431
+ -- SessionLoadCount is incremented by the session-start transform, which a view
1432
+ -- does not run (GetAsync passes EditProfile = nil), so a view of a profile that
1433
+ -- has been loaded once reports 0 where a live load reports 1. A caller comparing
1434
+ -- the raw field against 1 to mean "brand new" therefore judges every view brand
1435
+ -- new -- which for Scribe's dry-run mode meant stamping the current version and
1436
+ -- skipping every migration. Normalising it here means the caller no longer has
1437
+ -- to know which mode it is in to read the number correctly.
1438
+ function Profile:SessionsStarted()
1439
+ return self.SessionLoadCount + (if self.view_mode == true then 1 else 0)
1440
+ end
1441
+
1442
+ -- SCRIBE PATCH: keep, or stop keeping, the decoded response of each save.
1443
+ --
1444
+ -- `LastSavedData` is a full second copy of the profile, retained for the whole
1445
+ -- session. Pass `false` and it is released once OnAfterSave has fired, becoming
1446
+ -- a shared frozen empty table, which reads as "no baseline" to anything that
1447
+ -- checks rather than as stale data that could be mistaken for the real thing.
1448
+ -- The handler still receives the real table, so a summary can be taken there.
1449
+ --
1450
+ -- Retention is ON unless this is called. Anything that needs the BYTES of the
1451
+ -- last save -- Scribe's wipe guard under `WipeGuardPolicy = "Block"` writes them
1452
+ -- back as the save payload -- must keep retention on.
1453
+ function Profile:SetRetainLastSaved(retain)
1454
+ self.scribe_retain_last_saved = retain ~= false
1455
+ end
1456
+
1457
+ -- SCRIBE PATCH: choose the table this profile serializes from.
1458
+ --
1459
+ -- Assigning profile.Data works and always has, but WHEN it works was stated
1460
+ -- nowhere: SaveProfileAsync fires OnSave, and only afterwards does its
1461
+ -- UpdateAsync transform read profile.Data, so a handler that swaps the pointer
1462
+ -- inside OnSave changes what that save writes. Scribe's wipe guard depends on
1463
+ -- exactly that.
1464
+ --
1465
+ -- THE HAZARD: this is per-PROFILE, not per-save. Saves overlap -- an autosave
1466
+ -- tick can start while a Flush is in flight -- and the transform reads whatever
1467
+ -- the pointer holds when IT runs, so a swap affects every transform that has not
1468
+ -- run yet, including ones whose OnSave fired before the swap. Anything that must
1469
+ -- be per-call belongs in the OnSave context table instead.
1470
+ --
1471
+ -- Validated the same way SaveProfileAsync validates it, so a bad value fails at
1472
+ -- the assignment rather than at the next save with no clue who wrote it.
1473
+ function Profile:SetSaveSource(data)
1474
+ if type(data) ~= "table" then
1475
+ error(`[{script.Name}]: SetSaveSource expects a table (got {typeof(data)})`)
1476
+ end
1477
+ self.Data = data
1478
+ end
1479
+
1480
+ -- SCRIBE PATCH: end the session WITHOUT writing Data back.
1481
+ --
1482
+ -- For the fail-closed load paths: release the lock so the player can rejoin
1483
+ -- elsewhere, but leave the stored bytes exactly as they were found. Everything
1484
+ -- else about the release is unchanged, including the retry until the write lands.
1485
+ function Profile:EndSessionWithoutSaving()
1486
+ if self:IsActive() == true then
1487
+ self.scribe_release_only = true
1488
+ task.spawn(SaveProfileAsync, self, true, nil, "Manual")
1489
+ end
1490
+ end
1491
+
1492
+ function Profile:EndSession()
1493
+ if self:IsActive() == true then
1494
+ task.spawn(SaveProfileAsync, self, true, nil, "Manual") -- Call save function in a new thread with release_from_session = true
1495
+ end
1496
+ end
1497
+
1498
+ function Profile:AddUserId(user_id) -- Associates user_id with profile (GDPR compliance)
1499
+
1500
+ if type(user_id) ~= "number" or user_id % 1 ~= 0 then
1501
+ warn(`[{script.Name}]: Invalid UserId argument for :AddUserId() ({tostring(user_id)}); Traceback:\n` .. debug.traceback())
1502
+ return
1503
+ end
1504
+
1505
+ if user_id < 0 and self.is_mock ~= true and DataStoreState == "Access" then
1506
+ return -- Avoid giving real Roblox APIs negative UserId's
1507
+ end
1508
+
1509
+ if table.find(self.UserIds, user_id) == nil then
1510
+ table.insert(self.UserIds, user_id)
1511
+ end
1512
+
1513
+ end
1514
+
1515
+ function Profile:RemoveUserId(user_id) -- Removes user_id association with profile (safe function)
1516
+
1517
+ if type(user_id) ~= "number" or user_id % 1 ~= 0 then
1518
+ warn(`[{script.Name}]: Invalid UserId argument for :RemoveUserId() ({tostring(user_id)}); Traceback:\n` .. debug.traceback())
1519
+ return
1520
+ end
1521
+
1522
+ local index = table.find(self.UserIds, user_id)
1523
+
1524
+ if index ~= nil then
1525
+ table.remove(self.UserIds, index)
1526
+ end
1527
+
1528
+ end
1529
+
1530
+ function Profile:SetAsync() -- Saves the profile to the DataStore and removes the session lock
1531
+
1532
+ if self.view_mode ~= true then
1533
+ error(`[{script.Name}]: :SetAsync() can only be used in view mode`)
1534
+ end
1535
+
1536
+ SaveProfileAsync(self, nil, true)
1537
+
1538
+ end
1539
+
1540
+ function Profile:MessageHandler(fn)
1541
+
1542
+ if type(fn) ~= "function" then
1543
+ error(`[{script.Name}]: fn argument is not a function`)
1544
+ end
1545
+
1546
+ if self.view_mode ~= true and self:IsActive() ~= true then
1547
+ return -- Don't process messages if the profile session was ended
1548
+ end
1549
+
1550
+ local locked_updates = self.locked_global_updates
1551
+ table.insert(self.message_handlers, fn)
1552
+
1553
+ for _, update in ipairs(self.global_updates) do
1554
+
1555
+ local index = update[1]
1556
+ local update_data = update[#update] -- Backwards compatibility with ProfileService
1557
+
1558
+ if locked_updates[index] ~= true then
1559
+
1560
+ local processed_callback = function()
1561
+ locked_updates[index] = true
1562
+ end
1563
+
1564
+ local send_update_data = DeepCopyTable(update_data)
1565
+
1566
+ task.spawn(fn, send_update_data, processed_callback)
1567
+
1568
+ end
1569
+
1570
+ end
1571
+
1572
+ end
1573
+
1574
+ function Profile:Save()
1575
+
1576
+ if self.view_mode == true then
1577
+ error(`[{script.Name}]: Can't save profile in view mode; Should you be calling :SetAsync() instead?`)
1578
+ end
1579
+
1580
+ if self:IsActive() == false then
1581
+ warn(`[{script.Name}]: Attempted saving an inactive profile (STORE:{self.ProfileStore.Name}; KEY:{self.Key});`
1582
+ .. ` Traceback:\n` .. debug.traceback())
1583
+ return
1584
+ end
1585
+
1586
+ -- Move the profile right behind the auto save index to delay the next auto save for it:
1587
+ RemoveProfileFromAutoSave(self)
1588
+ AddProfileToAutoSave(self)
1589
+
1590
+ -- Perform save in new thread:
1591
+ task.spawn(SaveProfileAsync, self)
1592
+
1593
+ end
1594
+
1595
+ -- SCRIBE PATCH: Save(), but yields and reports what happened to THIS call.
1596
+ --
1597
+ -- Save() task.spawns the work and returns immediately, so a caller can only
1598
+ -- watch OnAfterSave and guess which save it belonged to. Guessing is what Scribe
1599
+ -- used to do, and it granted Robux receipts on saves that were still in flight.
1600
+ function Profile:SaveAwait(): (string, { [string]: any })
1601
+
1602
+ if self.view_mode == true then
1603
+ error(`[{script.Name}]: Can't save profile in view mode; Should you be calling :SetAsync() instead?`)
1604
+ end
1605
+
1606
+ if self:IsActive() == false then
1607
+ -- No save was started, so there is no context to report from one.
1608
+ return "NotOwned", {}
1609
+ end
1610
+
1611
+ -- Same auto-save reordering Save() does, so a confirmed save also delays the
1612
+ -- next tick rather than being immediately followed by one.
1613
+ RemoveProfileFromAutoSave(self)
1614
+ AddProfileToAutoSave(self)
1615
+
1616
+ return SaveProfileAsync(self)
1617
+
1618
+ end
1619
+
1620
+ local ProfileStore: ProfileStoreModule = {
1621
+
1622
+ IsClosing = false,
1623
+ IsCriticalState = false,
1624
+ -- SCRIBE PATCH: set by an owner that drives shutdown itself (see BindToClose).
1625
+ ExternalShutdown = false,
1626
+ -- SCRIBE PATCH: injected by whoever adopts this module -- Scribe does it in
1627
+ -- Persistence's findProfileStoreModule. Takes a DataStore error message and
1628
+ -- answers its class; MessageAsync reads it to decide whether a failed attempt
1629
+ -- could have written. nil means "assume every failure might have", which is the
1630
+ -- behaviour this file had before the hook existed.
1631
+ ClassifyError = nil,
1632
+ OnError = OnError, -- (message, store_name, profile_key)
1633
+ OnOverwrite = OnOverwrite, -- (store_name, profile_key)
1634
+ OnCriticalToggle = Signal.New(), -- (is_critical)
1635
+ DataStoreState = "NotReady", -- ("NotReady", "NoInternet", "NoAccess", "Access")
1636
+
1637
+ }
1638
+ ProfileStore.__index = ProfileStore
1639
+
1640
+ -- SCRIBE PATCH: shutdown, split so an owner can interleave its own work.
1641
+ --
1642
+ -- BeginClose stops new work starting; AwaitClose releases whatever is still held
1643
+ -- and waits for every outstanding job. Between the two, Scribe runs its leaving
1644
+ -- hooks and ends its own sessions -- an ordering this file cannot provide on its
1645
+ -- own, because BindToClose callbacks run concurrently. With everything already
1646
+ -- released AwaitClose degrades to the job-drain wait, which is the part that
1647
+ -- keeps the process alive until saves land.
1648
+ function ProfileStore.BeginClose()
1649
+ ProfileStore.IsClosing = true
1650
+ end
1651
+
1652
+ function ProfileStore.AwaitClose()
1653
+ -- Cloned because AutoSaveList changes as profiles are released.
1654
+ local on_close_save_job_count = 0
1655
+ local active_profiles = {}
1656
+ for index, profile in ipairs(AutoSaveList) do
1657
+ active_profiles[index] = profile
1658
+ end
1659
+
1660
+ -- Releasing a profile can trigger listeners that release others, so re-check.
1661
+ for _, profile in ipairs(active_profiles) do
1662
+ if profile:IsActive() == true then
1663
+ on_close_save_job_count = on_close_save_job_count + 1
1664
+ task.spawn(function()
1665
+ SaveProfileAsync(profile, true, nil, "Shutdown")
1666
+ on_close_save_job_count = on_close_save_job_count - 1
1667
+ end)
1668
+ end
1669
+ end
1670
+
1671
+ while on_close_save_job_count > 0 or ActiveProfileLoadJobs > 0 or ActiveProfileSaveJobs > 0 do
1672
+ task.wait()
1673
+ end
1674
+ end
1675
+
1676
+ -- SCRIBE PATCH: compare-and-set for an OFFLINE profile.
1677
+ --
1678
+ -- Writing to an absent player's key means reading it, letting developer code
1679
+ -- decide what to change, then writing back, and developer code can yield for as
1680
+ -- long as it likes, so the player can join a server inside that window. A view
1681
+ -- SetAsync does not merely race for the value: its overwrite path sets
1682
+ -- session_owns_profile = true unconditionally and clears ActiveSession, so
1683
+ -- committing over a live session DISOWNS it -- its next save writes nothing, its
1684
+ -- player is kicked, and everything since its last save is gone.
1685
+ --
1686
+ -- So the check and the write are made one UpdateAsync. The mutation still cannot
1687
+ -- happen in here, because a transform must not yield and developer code does; the
1688
+ -- caller prepares `new_data` outside and this commits it only if the key still
1689
+ -- looks the way they read it:
1690
+ --
1691
+ -- * still offline, and
1692
+ -- * unchanged since the read, compared on SessionLoadCount, LastUpdate AND
1693
+ -- WriteIndex. The first two alone were not enough: LastUpdate has one-second
1694
+ -- granularity, so two writers off one snapshot whose first commit lands inside
1695
+ -- that second both passed; and a view-mode SetAsync moves neither of them, so
1696
+ -- an operator's RestoreVersion was invisible at any timing. WriteIndex moves
1697
+ -- on every committing write and closes both.
1698
+ --
1699
+ -- "Still offline" means ActiveSession == nil, or -- when the caller passes
1700
+ -- `options.StaleSessionAfter` -- a session whose LastUpdate is older than that,
1701
+ -- the same rule StartSessionAsync uses to steal a dead session. Opt-in, so the
1702
+ -- store's default stays conservative for any other consumer.
1703
+ --
1704
+ -- Returns "Written" | "SessionActive" | "Changed" | "Missing" | "Failed".
1705
+ -- Unlike the view path, a decline writes NOTHING: the transform returns nil.
1706
+ function ProfileStore:UpdateOfflineAsync(profile_key, expected, new_data, options)
1707
+
1708
+ if type(profile_key) ~= "string" or #profile_key == 0 then
1709
+ error(`[{script.Name}]: Invalid profile_key`)
1710
+ end
1711
+ if type(expected) ~= "table" or type(new_data) ~= "table" then
1712
+ error(`[{script.Name}]: UpdateOfflineAsync needs an expected snapshot and a data table`)
1713
+ end
1714
+
1715
+ local outcome = "Failed"
1716
+ local minted = nil
1717
+ local transform_params
1718
+ transform_params = {
1719
+ ExistingProfileHandle = nil,
1720
+ -- SCRIBE PATCH: with options.CreateIfMissing the key is minted inside the
1721
+ -- transform, so a key that appeared meanwhile reads as a change below.
1722
+ MissingProfileHandle = if options and options.CreateIfMissing == true
1723
+ then function(latest_data)
1724
+ minted = HttpService:GenerateGUID(false)
1725
+ latest_data.Data = new_data
1726
+ latest_data.MetaData = {
1727
+ ProfileCreateTime = os.time(),
1728
+ Generation = minted,
1729
+ SessionLoadCount = 0,
1730
+ WriteIndex = 0,
1731
+ ActiveSession = nil,
1732
+ ForceLoadSession = nil,
1733
+ MetaTags = {},
1734
+ }
1735
+ end
1736
+ else nil,
1737
+ -- Set by EditProfile on every declining path; UpdateAsync's transform
1738
+ -- returns nil when it is true, so a refusal commits nothing at all.
1739
+ AbortWrite = false,
1740
+ EditProfile = function(latest_data)
1741
+
1742
+ if type(latest_data.Data) ~= "table" or type(latest_data.MetaData) ~= "table" then
1743
+ outcome = "Missing"
1744
+ transform_params.AbortWrite = true
1745
+ return
1746
+ end
1747
+
1748
+ -- Minted by THIS run; a rerun over a key another server created sees its generation.
1749
+ if minted ~= nil and latest_data.MetaData.Generation == minted then
1750
+ latest_data.MetaData.LastUpdate = os.time()
1751
+ latest_data.MetaData.WriteIndex = 1
1752
+ outcome = "Written"
1753
+ return
1754
+ end
1755
+
1756
+ local active_session = latest_data.MetaData.ActiveSession
1757
+ if active_session ~= nil then
1758
+ local stale_after = options and options.StaleSessionAfter
1759
+ local last_update = latest_data.MetaData.LastUpdate
1760
+ -- The same three clauses StartSessionAsync uses at its own steal
1761
+ -- (ExistingProfileHandle, further down): no usable LastUpdate means
1762
+ -- LIVE, because refusing is the safe direction. Evaluated HERE rather
1763
+ -- than on the caller's pre-CAS snapshot, because deciding staleness out
1764
+ -- there is exactly the read-then-write race this closes.
1765
+ if
1766
+ type(stale_after) ~= "number"
1767
+ or type(last_update) ~= "number"
1768
+ or last_update <= 0
1769
+ or os.time() - last_update <= stale_after
1770
+ then
1771
+ outcome = "SessionActive"
1772
+ transform_params.AbortWrite = true
1773
+ return
1774
+ end
1775
+ -- Past the dead-session threshold, so take the lock off the key, the
1776
+ -- same disowning StartSessionAsync performs when it steals. Leaving it
1777
+ -- set would let the incumbent's next save overwrite this write wholesale,
1778
+ -- and Monetization has already answered PurchaseGranted on it.
1779
+ latest_data.MetaData.ActiveSession = nil
1780
+ latest_data.MetaData.ForceLoadSession = nil
1781
+ end
1782
+
1783
+ -- SCRIBE PATCH: Generation is the key's lineage; a recreated key can repeat the
1784
+ -- three counters and, inside one second, its creation time.
1785
+ if
1786
+ latest_data.MetaData.SessionLoadCount ~= expected.SessionLoadCount
1787
+ or latest_data.MetaData.LastUpdate ~= expected.LastUpdate
1788
+ or (latest_data.MetaData.WriteIndex or 0) ~= (expected.WriteIndex or 0)
1789
+ or (expected.Generation ~= nil and (latest_data.MetaData.Generation or false) ~= expected.Generation)
1790
+ then
1791
+ outcome = "Changed"
1792
+ transform_params.AbortWrite = true
1793
+ return
1794
+ end
1795
+
1796
+ latest_data.Data = new_data
1797
+ -- Stamped for the same reason an owning save stamps it: the next
1798
+ -- caller's "unchanged since I read it" check needs this write to be
1799
+ -- visible to it.
1800
+ latest_data.MetaData.LastUpdate = os.time()
1801
+ latest_data.MetaData.WriteIndex = (latest_data.MetaData.WriteIndex or 0) + 1
1802
+ outcome = "Written"
1803
+
1804
+ end,
1805
+ }
1806
+
1807
+ local loaded_data = UpdateAsync(self, profile_key, transform_params, self._is_user_mock)
1808
+
1809
+ if loaded_data == nil and transform_params.AbortWrite ~= true then
1810
+ -- The call itself failed; whatever the transform decided is not authoritative
1811
+ -- because it may never have run. Guarded on AbortWrite because a DECLINE also
1812
+ -- returns nil, and reporting an ordinary refusal as "Failed" would send routine
1813
+ -- contention to Health and degrade the server to Outage.
1814
+ return "Failed"
1815
+ end
1816
+
1817
+ return outcome
1818
+
1819
+ end
1820
+
1821
+ function ProfileStore.SetConstant(name, value)
1822
+
1823
+ if type(value) ~= "number" then
1824
+ error(`[{script.Name}]: Invalid value type`)
1825
+ end
1826
+
1827
+ if name == "AUTO_SAVE_PERIOD" then
1828
+ AUTO_SAVE_PERIOD = value
1829
+ elseif name == "LOAD_REPEAT_PERIOD" then
1830
+ LOAD_REPEAT_PERIOD = value
1831
+ elseif name == "FIRST_LOAD_REPEAT" then
1832
+ FIRST_LOAD_REPEAT = value
1833
+ elseif name == "SESSION_STEAL" then
1834
+ SESSION_STEAL = value
1835
+ elseif name == "ASSUME_DEAD" then
1836
+ ASSUME_DEAD = value
1837
+ elseif name == "START_SESSION_TIMEOUT" then
1838
+ START_SESSION_TIMEOUT = value
1839
+ elseif name == "CRITICAL_STATE_ERROR_COUNT" then
1840
+ CRITICAL_STATE_ERROR_COUNT = value
1841
+ elseif name == "CRITICAL_STATE_ERROR_EXPIRE" then
1842
+ CRITICAL_STATE_ERROR_EXPIRE = value
1843
+ elseif name == "CRITICAL_STATE_EXPIRE" then
1844
+ CRITICAL_STATE_EXPIRE = value
1845
+ elseif name == "MAX_MESSAGE_QUEUE" then
1846
+ MAX_MESSAGE_QUEUE = value
1847
+ else
1848
+ error(`[{script.Name}]: Invalid constant name was provided`)
1849
+ end
1850
+
1851
+ end
1852
+
1853
+ function ProfileStore.Test()
1854
+ return {
1855
+ ActiveSessionCheck = ActiveSessionCheck,
1856
+ AutoSaveList = AutoSaveList,
1857
+ ActiveProfileLoadJobs = ActiveProfileLoadJobs,
1858
+ ActiveProfileSaveJobs = ActiveProfileSaveJobs,
1859
+ MockStore = MockStore,
1860
+ UserMockStore = UserMockStore,
1861
+ UpdateQueue = UpdateQueue,
1862
+ }
1863
+ end
1864
+
1865
+ function ProfileStore.New(store_name, template)
1866
+
1867
+ template = template or {}
1868
+
1869
+ if type(store_name) ~= "string" then
1870
+ error(`[{script.Name}]: Invalid or missing "store_name"`)
1871
+ elseif string.len(store_name) == 0 then
1872
+ error(`[{script.Name}]: store_name cannot be an empty string`)
1873
+ elseif string.len(store_name) > 50 then
1874
+ error(`[{script.Name}]: store_name is too long`)
1875
+ end
1876
+
1877
+ if type(template) ~= "table" then
1878
+ error(`[{script.Name}]: Invalid template argument`)
1879
+ end
1880
+
1881
+ local self
1882
+ self = {
1883
+
1884
+ Mock = {
1885
+
1886
+ Name = store_name,
1887
+
1888
+ StartSessionAsync = function(_, profile_key)
1889
+ MockFlag = true
1890
+ return self:StartSessionAsync(profile_key)
1891
+ end,
1892
+ MessageAsync = function(_, profile_key, message)
1893
+ MockFlag = true
1894
+ return self:MessageAsync(profile_key, message)
1895
+ end,
1896
+ GetAsync = function(_, profile_key, version)
1897
+ MockFlag = true
1898
+ return self:GetAsync(profile_key, version)
1899
+ end,
1900
+ VersionQuery = function(_, profile_key, sort_direction, min_date, max_date)
1901
+ MockFlag = true
1902
+ return self:VersionQuery(profile_key, sort_direction, min_date, max_date)
1903
+ end,
1904
+ RemoveAsync = function(_, profile_key)
1905
+ MockFlag = true
1906
+ return self:RemoveAsync(profile_key)
1907
+ end
1908
+ },
1909
+
1910
+ Name = store_name,
1911
+
1912
+ template = template,
1913
+ data_store = nil,
1914
+ load_jobs = {},
1915
+ mock_load_jobs = {},
1916
+ is_ready = true,
1917
+
1918
+ }
1919
+ setmetatable(self, ProfileStore)
1920
+
1921
+ local options = Instance.new("DataStoreOptions")
1922
+ options:SetExperimentalFeatures({v2 = true})
1923
+
1924
+ if DataStoreState == "NotReady" then
1925
+
1926
+ -- The module is not sure whether DataStores are accessible yet:
1927
+
1928
+ self.is_ready = false
1929
+
1930
+ task.spawn(function()
1931
+
1932
+ repeat task.wait() until DataStoreState ~= "NotReady"
1933
+
1934
+ if DataStoreState == "Access" then
1935
+ self.data_store = DataStoreService:GetDataStore(store_name, nil, options)
1936
+ end
1937
+
1938
+ self.is_ready = true
1939
+
1940
+ end)
1941
+
1942
+ elseif DataStoreState == "Access" then
1943
+
1944
+ self.data_store = DataStoreService:GetDataStore(store_name, nil, options)
1945
+
1946
+ end
1947
+
1948
+ return self
1949
+
1950
+ end
1951
+
1952
+ -- SCRIBE PATCH: how far PAST the six-second boundary a DEFERRED nudge fires. One
1953
+ -- frame, and the number is not arbitrary: the immediate path's test is `> 6`, so
1954
+ -- a deferred fire landing exactly ON the boundary would sit on the equality case,
1955
+ -- where float error rather than the code decides whether the spacing held. A fire
1956
+ -- landing one ulp early would be a rate increase, and bounding the rate is the
1957
+ -- only thing this throttle is for.
1958
+ local NUDGE_FIRE_MARGIN = 1 / 60
1959
+
1960
+ -- SCRIBE PATCH: a nudge that arrives inside the throttle window is DEFERRED, not
1961
+ -- dropped.
1962
+ --
1963
+ -- Upstream's `if os.clock() - last_roblox_message > 6 then` had no else branch, so
1964
+ -- a second message inside six seconds was discarded outright. That looks like a 6x
1965
+ -- delay and is not one. This nudge is the ONLY thing that gets a cross-server
1966
+ -- request acted on quickly -- MessageAsync asking the holding server to auto-save
1967
+ -- sooner, a session steal asking it to release -- so losing one drops the request
1968
+ -- off the ~1s path onto the next autosave: AUTO_SAVE_PERIOD, 300 seconds by
1969
+ -- default. Two servers touching the same player within six seconds is ordinary
1970
+ -- traffic, not an edge case.
1971
+ --
1972
+ -- WHAT IS DEFERRED IS THE REQUEST, NEVER THE SPACING. The six seconds protect the
1973
+ -- DataStore write budget (the numPlayers x 10 figure named below), so the deferred
1974
+ -- save fires when the window expires and not a moment sooner, and every nudge that
1975
+ -- arrived during it collapses into that ONE save. The maximum save rate is
1976
+ -- unchanged; only the losses are gone.
1977
+ --
1978
+ -- ENDSESSION WINS THE MERGE. Merging an EndSession down into an ordinary save
1979
+ -- would leave the lock held and put the stealing server back on the SESSION_STEAL
1980
+ -- deadline, so the flag is sticky and the coalesced save is a release. The merge
1981
+ -- the other way loses nothing: a release save writes Data too. Urgency wins the
1982
+ -- MERGE and not the WINDOW: a release is a DataStore write like any other.
1983
+ local function RobloxMessageSubscription(profile, unique_session_id)
1984
+
1985
+ local last_roblox_message = 0
1986
+
1987
+ -- SCRIBE PATCH: what a nudge inside the window leaves behind. `nudge_timer_armed`
1988
+ -- is what makes ten nudges one save rather than ten -- the timer is armed once
1989
+ -- per window and every later nudge only folds itself into the flags.
1990
+ local pending_end_session = false
1991
+ local nudge_timer_armed = false
1992
+
1993
+ -- SCRIBE PATCH: the body of the window, extracted so the deferred fire runs the
1994
+ -- SAME code the immediate one does instead of a second copy that can drift apart
1995
+ -- from it. last_roblox_message is stamped BEFORE the IsActive test, exactly where
1996
+ -- upstream stamped it, so an inactive profile still consumes its window.
1997
+ local function ServeNudge(end_session)
1998
+ last_roblox_message = os.clock()
1999
+ if profile:IsActive() == true then
2000
+ if end_session == true then
2001
+ SaveProfileAsync(profile, true, false, "External")
2002
+ else
2003
+ profile:Save()
2004
+ end
2005
+ end
2006
+ end
2007
+
2008
+ local roblox_message_subscription = MessagingService:SubscribeAsync("PS_" .. unique_session_id, function(message)
2009
+ if type(message.Data) == "table" and message.Data.LoadCount == profile.SessionLoadCount then
2010
+ -- High reaction rate, based on numPlayers × 10 DataStore budget as of writing
2011
+ if os.clock() - last_roblox_message > 6 then
2012
+ ServeNudge(message.Data.EndSession == true)
2013
+ else
2014
+ -- SCRIBE PATCH: remember it rather than discarding it.
2015
+ pending_end_session = pending_end_session or message.Data.EndSession == true
2016
+ if nudge_timer_armed == false then
2017
+ nudge_timer_armed = true
2018
+ task.delay((last_roblox_message + 6 + NUDGE_FIRE_MARGIN) - os.clock(), function()
2019
+ nudge_timer_armed = false
2020
+ local end_session = pending_end_session
2021
+ pending_end_session = false
2022
+ -- ServeNudge's profile:IsActive() test is evaluated HERE, at FIRE time,
2023
+ -- and routing through it is the point. A session can end between a nudge
2024
+ -- arriving and its window expiring, and a save fired on a dead profile is
2025
+ -- a write from a session that no longer owns the key. Nothing cancels this
2026
+ -- timer -- Disconnect on the subscription cannot reach it -- so that test
2027
+ -- is what retires it, and it is why the timer is one-shot: the longest it
2028
+ -- can outlive a session is the one window it was already waiting out.
2029
+ ServeNudge(end_session)
2030
+ end)
2031
+ end
2032
+ end
2033
+ end
2034
+ end)
2035
+
2036
+ if profile:IsActive() == true then
2037
+ profile.roblox_message_subscription = roblox_message_subscription
2038
+ else
2039
+ roblox_message_subscription:Disconnect()
2040
+ end
2041
+
2042
+ end
2043
+
2044
+ function ProfileStore:StartSessionAsync(profile_key, params)
2045
+
2046
+ local is_mock = ReadMockFlag()
2047
+
2048
+ if type(profile_key) ~= "string" then
2049
+ error(`[{script.Name}]: profile_key must be a string`)
2050
+ elseif string.len(profile_key) == 0 then
2051
+ error(`[{script.Name}]: Invalid profile_key`)
2052
+ elseif string.len(profile_key) > 50 then
2053
+ error(`[{script.Name}]: profile_key is too long`)
2054
+ end
2055
+
2056
+ if params ~= nil and type(params) ~= "table" then
2057
+ error(`[{script.Name}]: Invalid params`)
2058
+ end
2059
+
2060
+ params = params or {}
2061
+
2062
+ if ProfileStore.IsClosing == true then
2063
+ return nil
2064
+ end
2065
+
2066
+ WaitForStoreReady(self)
2067
+
2068
+ local session_token = SessionToken(self.Name, profile_key, is_mock)
2069
+
2070
+ if ActiveSessionCheck[session_token] ~= nil then
2071
+ error(`[{script.Name}]: Profile (STORE:{self.Name}; KEY:{profile_key}) is already loaded in this session`)
2072
+ end
2073
+
2074
+ ActiveProfileLoadJobs = ActiveProfileLoadJobs + 1
2075
+
2076
+ local is_user_cancel = false
2077
+
2078
+ local function cancel_condition()
2079
+ if is_user_cancel == false then
2080
+ if params.Cancel ~= nil then
2081
+ is_user_cancel = params.Cancel() == true
2082
+ end
2083
+ return is_user_cancel
2084
+ end
2085
+ return true
2086
+ end
2087
+
2088
+ local user_steal = params.Steal == true
2089
+
2090
+ local force_load_steps = 0 -- Session conflict handling values
2091
+ local request_force_load = true
2092
+ local steal_session = false
2093
+
2094
+ local start = os.clock()
2095
+ local exp_backoff = 1
2096
+
2097
+ while ProfileStore.IsClosing == false and cancel_condition() == false do
2098
+
2099
+ -- Load profile:
2100
+
2101
+ -- SPECIAL CASE - If StartSessionAsync is called for the same key again before another StartSessionAsync finishes,
2102
+ -- grab the DataStore return for the new call. The early call will return nil. This is supposed to retain
2103
+ -- expected and efficient behavior in cases where a player would quickly rejoin the same server.
2104
+
2105
+ LoadIndex += 1
2106
+ local load_id = LoadIndex
2107
+ local profile_load_jobs = is_mock == true and self.mock_load_jobs or self.load_jobs
2108
+ local profile_load_job = profile_load_jobs[profile_key] -- {load_id, {loaded_data, key_info} or nil}
2109
+
2110
+ local loaded_data, key_info
2111
+ local unique_session_id = HttpService:GenerateGUID(false)
2112
+
2113
+ if profile_load_job ~= nil then
2114
+
2115
+ profile_load_job[1] = load_id -- Steal load job
2116
+ while profile_load_job[2] == nil do -- Wait for job to finish
2117
+ task.wait()
2118
+ end
2119
+ if profile_load_job[1] == load_id then -- Load job hasn't been double-stolen
2120
+ loaded_data, key_info = table.unpack(profile_load_job[2])
2121
+ profile_load_jobs[profile_key] = nil
2122
+ else
2123
+ ActiveProfileLoadJobs = ActiveProfileLoadJobs - 1
2124
+ return nil
2125
+ end
2126
+
2127
+ else
2128
+
2129
+ profile_load_job = {load_id, nil}
2130
+ profile_load_jobs[profile_key] = profile_load_job
2131
+
2132
+ profile_load_job[2] = table.pack(UpdateAsync(
2133
+ self,
2134
+ profile_key,
2135
+ {
2136
+ ExistingProfileHandle = function(latest_data)
2137
+
2138
+ if ProfileStore.IsClosing == true or cancel_condition() == true then
2139
+ return
2140
+ end
2141
+
2142
+ local active_session = latest_data.MetaData.ActiveSession
2143
+ local force_load_session = latest_data.MetaData.ForceLoadSession
2144
+
2145
+ if active_session == nil then
2146
+ latest_data.MetaData.ActiveSession = {PlaceId, JobId, unique_session_id}
2147
+ latest_data.MetaData.ForceLoadSession = nil
2148
+ elseif type(active_session) == "table" then
2149
+ if IsThisSession(active_session) == false then
2150
+ local last_update = latest_data.MetaData.LastUpdate
2151
+ if last_update ~= nil then
2152
+ if os.time() - last_update > ASSUME_DEAD then
2153
+ latest_data.MetaData.ActiveSession = {PlaceId, JobId, unique_session_id}
2154
+ latest_data.MetaData.ForceLoadSession = nil
2155
+ return
2156
+ end
2157
+ end
2158
+ if steal_session == true or user_steal == true then
2159
+ local force_load_interrupted = if force_load_session ~= nil then not IsThisSession(force_load_session) else true
2160
+ if force_load_interrupted == false or user_steal == true then
2161
+ latest_data.MetaData.ActiveSession = {PlaceId, JobId, unique_session_id}
2162
+ latest_data.MetaData.ForceLoadSession = nil
2163
+ end
2164
+ elseif request_force_load == true then
2165
+ latest_data.MetaData.ForceLoadSession = {PlaceId, JobId}
2166
+ end
2167
+ else
2168
+ latest_data.MetaData.ForceLoadSession = nil
2169
+ end
2170
+ end
2171
+
2172
+ end,
2173
+ MissingProfileHandle = function(latest_data)
2174
+
2175
+ local is_cancel = ProfileStore.IsClosing == true or cancel_condition() == true
2176
+
2177
+ latest_data.Data = DeepCopyTable(self.template)
2178
+ latest_data.MetaData = {
2179
+ ProfileCreateTime = os.time(),
2180
+ Generation = HttpService:GenerateGUID(false), -- SCRIBE PATCH: the key's lineage
2181
+ SessionLoadCount = 0,
2182
+ WriteIndex = 0, -- SCRIBE PATCH: the compare-and-set fingerprint
2183
+ ActiveSession = if is_cancel == false then {PlaceId, JobId, unique_session_id} else nil,
2184
+ ForceLoadSession = nil,
2185
+ MetaTags = {}, -- Backwards compatibility with ProfileService
2186
+ }
2187
+
2188
+ end,
2189
+ EditProfile = function(latest_data)
2190
+
2191
+ if ProfileStore.IsClosing == true or cancel_condition() == true then
2192
+ return
2193
+ end
2194
+
2195
+ local active_session = latest_data.MetaData.ActiveSession
2196
+ if active_session ~= nil and IsThisSession(active_session) == true then
2197
+ latest_data.MetaData.SessionLoadCount = latest_data.MetaData.SessionLoadCount + 1
2198
+ latest_data.MetaData.LastUpdate = os.time()
2199
+ -- SCRIBE PATCH: see the WriteIndex note in SaveProfileAsync.
2200
+ latest_data.MetaData.WriteIndex = (latest_data.MetaData.WriteIndex or 0) + 1
2201
+ end
2202
+
2203
+ end,
2204
+ },
2205
+ is_mock
2206
+ ))
2207
+ if profile_load_job[1] == load_id then -- Load job hasn't been stolen
2208
+ loaded_data, key_info = table.unpack(profile_load_job[2])
2209
+ profile_load_jobs[profile_key] = nil
2210
+ else
2211
+ ActiveProfileLoadJobs = ActiveProfileLoadJobs - 1
2212
+ return nil -- Load job stolen
2213
+ end
2214
+ end
2215
+
2216
+ -- Handle load_data:
2217
+
2218
+ if loaded_data ~= nil and key_info ~= nil then
2219
+ local active_session = loaded_data.MetaData.ActiveSession
2220
+ if type(active_session) == "table" then
2221
+
2222
+ if IsThisSession(active_session) == true then
2223
+
2224
+ -- Profile is now taken by this session:
2225
+
2226
+ local profile = Profile.New(loaded_data, key_info, self, profile_key, is_mock, session_token)
2227
+ AddProfileToAutoSave(profile)
2228
+
2229
+ if is_mock ~= true and DataStoreState == "Access" then
2230
+
2231
+ -- Use MessagingService to quickly detect session conflicts and resolve them quickly:
2232
+ task.spawn(RobloxMessageSubscription, profile, unique_session_id) -- Blocking prevention
2233
+
2234
+ end
2235
+
2236
+ if ProfileStore.IsClosing == true or cancel_condition() == true then
2237
+ -- The server has initiated a shutdown by the time this profile was loaded
2238
+ SaveProfileAsync(profile, true) -- Release profile and yield until the DataStore call is finished
2239
+ profile = nil -- Don't return the profile object
2240
+ end
2241
+
2242
+ ActiveProfileLoadJobs = ActiveProfileLoadJobs - 1
2243
+ return profile
2244
+
2245
+ else
2246
+
2247
+ if ProfileStore.IsClosing == true or cancel_condition() == true then
2248
+ ActiveProfileLoadJobs = ActiveProfileLoadJobs - 1
2249
+ return nil
2250
+ end
2251
+
2252
+ -- Profile is taken by some other session:
2253
+
2254
+ local force_load_session = loaded_data.MetaData.ForceLoadSession
2255
+ local force_load_interrupted = if force_load_session ~= nil then not IsThisSession(force_load_session) else true
2256
+
2257
+ if force_load_interrupted == false then
2258
+
2259
+ if request_force_load == false then
2260
+ force_load_steps = force_load_steps + 1
2261
+ if force_load_steps >= math.ceil(SESSION_STEAL / LOAD_REPEAT_PERIOD) then
2262
+ steal_session = true
2263
+ end
2264
+ end
2265
+
2266
+ -- Request the remote server to end its session:
2267
+ if type(active_session[3]) == "string" then
2268
+ local session_load_count = loaded_data.MetaData.SessionLoadCount or 0
2269
+ task.spawn(MessagingService.PublishAsync, MessagingService, "PS_" .. active_session[3], {LoadCount = session_load_count, EndSession = true})
2270
+ end
2271
+
2272
+ -- Attempt to load the profile again after a delay
2273
+ local wait_until = os.clock() + if request_force_load == true then FIRST_LOAD_REPEAT else LOAD_REPEAT_PERIOD
2274
+ repeat task.wait() until os.clock() >= wait_until or ProfileStore.IsClosing == true
2275
+
2276
+ else
2277
+ -- Another session tried to load this profile:
2278
+ ActiveProfileLoadJobs = ActiveProfileLoadJobs - 1
2279
+ return nil
2280
+ end
2281
+
2282
+ request_force_load = false -- Only request a force load once
2283
+
2284
+ end
2285
+
2286
+ else
2287
+ ActiveProfileLoadJobs = ActiveProfileLoadJobs - 1
2288
+ return nil -- In this scenario it is likely that this server started shutting down
2289
+ end
2290
+ else
2291
+
2292
+ -- A DataStore call has likely ended in an error:
2293
+
2294
+ local default_timeout = false
2295
+
2296
+ if params.Cancel == nil then
2297
+ default_timeout = os.clock() - start >= START_SESSION_TIMEOUT
2298
+ end
2299
+
2300
+ if default_timeout == true or ProfileStore.IsClosing == true or cancel_condition() == true then
2301
+ ActiveProfileLoadJobs = ActiveProfileLoadJobs - 1
2302
+ return nil
2303
+ end
2304
+
2305
+ task.wait(exp_backoff) -- Repeat the call shortly
2306
+ exp_backoff = math.min(20, exp_backoff * 2)
2307
+
2308
+ end
2309
+
2310
+ end
2311
+
2312
+ ActiveProfileLoadJobs = ActiveProfileLoadJobs - 1
2313
+ return nil -- Game started shutting down or the request was cancelled - don't return the profile
2314
+
2315
+ end
2316
+
2317
+ function ProfileStore:MessageAsync(profile_key, message)
2318
+
2319
+ local is_mock = ReadMockFlag()
2320
+
2321
+ if type(profile_key) ~= "string" then
2322
+ error(`[{script.Name}]: profile_key must be a string`)
2323
+ elseif string.len(profile_key) == 0 then
2324
+ error(`[{script.Name}]: Invalid profile_key`)
2325
+ elseif string.len(profile_key) > 50 then
2326
+ error(`[{script.Name}]: profile_key is too long`)
2327
+ end
2328
+
2329
+ if type(message) ~= "table" then
2330
+ error(`[{script.Name}]: message must be a table`)
2331
+ end
2332
+
2333
+ if ProfileStore.IsClosing == true then
2334
+ -- SCRIBE PATCH: PROVABLY CLEAN. This guard sits above WaitForStoreReady and
2335
+ -- above the retry loop: zero attempts, nothing written and no way to have
2336
+ -- written anything. It used to answer the same bare `false` as the loop's
2337
+ -- give-up below, which is the opposite case, and Scribe's gift-credit spend ate
2338
+ -- a paid credit here for a delivery it never made.
2339
+ return false, nil, true
2340
+ end
2341
+
2342
+ WaitForStoreReady(self)
2343
+
2344
+ local exp_backoff = 1
2345
+
2346
+ -- SCRIBE PATCH: `provably_clean`, the third return.
2347
+ --
2348
+ -- A caller with money on the line needs the one thing this method used to
2349
+ -- collapse: COULD ANYTHING HAVE BEEN WRITTEN? Neither of the two old values
2350
+ -- answers it. A bare `false` came from the IsClosing guard above, which attempts
2351
+ -- nothing, and from the end of the loop below, whose attempts may each have
2352
+ -- committed before erroring. `(false, "QueueFull")` describes the attempt that
2353
+ -- ANSWERED and says nothing about the attempts before it in the same call. Both
2354
+ -- directions were measured wrong in Scribe: a gift credit refunded on a QueueFull
2355
+ -- that followed a commit bought a SECOND grant off one payment, and a credit spent
2356
+ -- inside a shutdown window was eaten for a send never attempted.
2357
+ --
2358
+ -- So the third value is a POSITIVE claim: true only where nothing can have been
2359
+ -- written. Absent reads as false, and false means "cannot be sure" -- the cheap
2360
+ -- direction for an old caller, an old test double, or an exit added later that
2361
+ -- forgets the value.
2362
+ --
2363
+ -- IT IS NOT AN ATTEMPT COUNT, and a count is what made it cost the wrong way: it
2364
+ -- asks "was there a previous attempt?" instead of "could a previous attempt have
2365
+ -- written?". The loop repeats while UpdateAsync answers nil, and it answers nil for
2366
+ -- EVERY failure class, including the two that never reach storage, so one 3xx
2367
+ -- throttle in front of an ordinary full inbox ate a buyer's paid gift credit.
2368
+ --
2369
+ -- What replaces it is the error itself, classified once per failed attempt. Only
2370
+ -- "Rejected" (1xx: refused before storage, and refused identically forever) and
2371
+ -- "Throttled" (3xx: dropped at the queue, never dispatched) prove an attempt wrote
2372
+ -- nothing. "Unresolved" (504) cannot be proven either way, and "Failed" is the safe
2373
+ -- default, so an error family Roblox adds tomorrow lands on "cannot be sure".
2374
+ local provably_clean = true
2375
+
2376
+ while ProfileStore.IsClosing == false do
2377
+
2378
+ -- Updating profile:
2379
+
2380
+ local transform_params
2381
+ transform_params = {
2382
+ ExistingProfileHandle = nil,
2383
+ MissingProfileHandle = nil,
2384
+ AbortWrite = false,
2385
+ -- SCRIBE PATCH: set when the queue is already full. See below.
2386
+ QueueFull = false,
2387
+ EditProfile = function(latest_data)
2388
+
2389
+ local global_updates = latest_data.GlobalUpdates
2390
+ local update_list = global_updates[2]
2391
+ --{
2392
+ -- update_index,
2393
+ -- {
2394
+ -- {update_index, data}, ...
2395
+ -- },
2396
+ --},
2397
+
2398
+ -- SCRIBE PATCH: REFUSE at the cap instead of evicting.
2399
+ --
2400
+ -- This was a `table.insert` followed by a loop dropping the OLDEST entry,
2401
+ -- which still returned true. Measured with the cap at 8 and 12 sends: every
2402
+ -- call reported success and the recipient received only sequences 5..12.
2403
+ -- Scribe's gift delivery treats that true as durable and clears the buyer's
2404
+ -- escrow, so a PURCHASED gift was destroyed with nothing recording it
2405
+ -- anywhere. Gifts and Data.SendMessage share this channel.
2406
+ --
2407
+ -- The reason to refuse is that the eviction is SILENT, not that the key is
2408
+ -- nearly full: a thousand gift-shaped messages is about 136 KB, 3.4% of the
2409
+ -- 4 MB key. No trim loop for a key inherited OVER the cap from an older
2410
+ -- build either, for the same reason -- it stays over cap, refusing sends,
2411
+ -- until its acks sweep it, which is visible and recoverable.
2412
+ if #update_list >= MAX_MESSAGE_QUEUE then
2413
+ transform_params.QueueFull = true
2414
+ transform_params.AbortWrite = true
2415
+ return
2416
+ end
2417
+
2418
+ global_updates[1] += 1
2419
+ table.insert(update_list, {global_updates[1], message})
2420
+
2421
+ end,
2422
+ }
2423
+
2424
+ -- SCRIBE PATCH: transform_params is rebuilt on every pass, so `QueueFull` and
2425
+ -- `ErrorMessage` below are always THIS attempt's answer and never a stale one.
2426
+ --
2427
+ -- A RAISE OUT OF UpdateAsync IS NOT AN EXIT OF THIS FUNCTION, it is an exit of
2428
+ -- the CALL, and it carries no third value at all. UpdateAsync pcalls the
2429
+ -- DataStore itself, so what can still raise through here is the per-key update
2430
+ -- queue and any OnError handler inside RegisterError, either of which can fire
2431
+ -- after an attempt that may have committed. The caller's pcall reads absent as
2432
+ -- false and treats the call as ambiguous, which is both correct and cheap.
2433
+ local loaded_data = UpdateAsync(self, profile_key, transform_params, is_mock)
2434
+
2435
+ if transform_params.QueueFull == true then
2436
+ -- Nothing was written BY THE ATTEMPT THAT ANSWERED: the transform ran, saw
2437
+ -- the cap, set AbortWrite and returned nil, so the UpdateAsync it sat inside
2438
+ -- committed nothing at all. The reason keeps existing callers source-compatible
2439
+ -- while letting one that cares tell a full inbox from a DataStore fault.
2440
+ --
2441
+ -- `provably_clean` turns that into a statement about the CALL, and it is carried
2442
+ -- in from the attempts BEFORE this one: a QueueFull on a later pass can be a
2443
+ -- refusal reported for a message an earlier pass of this same call already
2444
+ -- queued, and the caller must not read that as clean; but a QueueFull behind
2445
+ -- nothing but rejections and throttles still IS clean.
2446
+ return false, "QueueFull", provably_clean
2447
+ end
2448
+
2449
+ if loaded_data ~= nil then
2450
+
2451
+ local session_token = SessionToken(self.Name, profile_key, is_mock)
2452
+
2453
+ local profile = ActiveSessionCheck[session_token]
2454
+
2455
+ if profile ~= nil then
2456
+
2457
+ -- The message was sent to a profile that is active in this server:
2458
+ profile:Save()
2459
+
2460
+ else
2461
+
2462
+ local meta_data = loaded_data.MetaData or {}
2463
+ local active_session = meta_data.ActiveSession
2464
+ local session_load_count = meta_data.SessionLoadCount or 0
2465
+
2466
+ if type(active_session) == "table" and type(active_session[3]) == "string" then
2467
+ -- Request the remote server to auto-save sooner and receive the message:
2468
+ task.spawn(MessagingService.PublishAsync, MessagingService, "PS_" .. active_session[3], {LoadCount = session_load_count})
2469
+ end
2470
+
2471
+ end
2472
+
2473
+ return true
2474
+
2475
+ else
2476
+
2477
+ -- SCRIBE PATCH: classify the attempt that just failed, before backing off.
2478
+ -- `Rejected` and `Throttled` provably never reached storage, so an attempt in
2479
+ -- either leaves the call as clean as it found it. Everything else settles the
2480
+ -- claim to false for the rest of the call, with no way back: once one attempt
2481
+ -- might have written, no later attempt can unprove it. No classifier installed
2482
+ -- means no class, and no class means no proof.
2483
+ local classify = ProfileStore.ClassifyError
2484
+ local class = if classify ~= nil then classify(transform_params.ErrorMessage) else nil
2485
+ if class ~= "Rejected" and class ~= "Throttled" then
2486
+ provably_clean = false
2487
+ end
2488
+
2489
+ task.wait(exp_backoff) -- A DataStore call has likely ended in an error - repeat the call shortly
2490
+ exp_backoff = math.min(20, exp_backoff * 2)
2491
+
2492
+ end
2493
+
2494
+ end
2495
+
2496
+ -- SCRIBE PATCH: the give-up exit. Ambiguous whenever any attempt could have
2497
+ -- written, and clean otherwise -- which covers two cases and not one: IsClosing
2498
+ -- can flip while WaitForStoreReady yields, so the loop body never ran at all; and
2499
+ -- a loop that ran only into rejections and throttles never reached storage either,
2500
+ -- on a key that may not even exist.
2501
+ return false, nil, provably_clean
2502
+
2503
+ end
2504
+
2505
+ function ProfileStore:GetAsync(profile_key, version)
2506
+
2507
+ local is_mock = ReadMockFlag()
2508
+
2509
+ if type(profile_key) ~= "string" then
2510
+ error(`[{script.Name}]: profile_key must be a string`)
2511
+ elseif string.len(profile_key) == 0 then
2512
+ error(`[{script.Name}]: Invalid profile_key`)
2513
+ elseif string.len(profile_key) > 50 then
2514
+ error(`[{script.Name}]: profile_key is too long`)
2515
+ end
2516
+
2517
+ if ProfileStore.IsClosing == true then
2518
+ return nil
2519
+ end
2520
+
2521
+ WaitForStoreReady(self)
2522
+
2523
+ if version ~= nil and (is_mock or DataStoreState ~= "Access") then
2524
+ return nil -- No version support in mock mode
2525
+ end
2526
+
2527
+ local exp_backoff = 1
2528
+
2529
+ while ProfileStore.IsClosing == false do
2530
+
2531
+ -- Load profile:
2532
+
2533
+ local loaded_data, key_info = UpdateAsync(
2534
+ self,
2535
+ profile_key,
2536
+ {
2537
+ ExistingProfileHandle = nil,
2538
+ MissingProfileHandle = function(latest_data)
2539
+
2540
+ latest_data.Data = DeepCopyTable(self.template)
2541
+ latest_data.MetaData = {
2542
+ ProfileCreateTime = os.time(),
2543
+ Generation = HttpService:GenerateGUID(false), -- SCRIBE PATCH: the key's lineage
2544
+ SessionLoadCount = 0,
2545
+ WriteIndex = 0, -- SCRIBE PATCH: the compare-and-set fingerprint
2546
+ ActiveSession = nil,
2547
+ ForceLoadSession = nil,
2548
+ MetaTags = {}, -- Backwards compatibility with ProfileService
2549
+ }
2550
+
2551
+ end,
2552
+ EditProfile = nil,
2553
+ },
2554
+ is_mock,
2555
+ true, -- Use :GetAsync()
2556
+ version -- DataStore key version
2557
+ )
2558
+
2559
+ -- Handle load_data:
2560
+
2561
+ if loaded_data ~= nil then
2562
+
2563
+ if key_info == nil then
2564
+ return nil -- Load was successful, but the key was empty - return no profile object
2565
+ end
2566
+
2567
+ local profile = Profile.New(loaded_data, key_info, self, profile_key, is_mock)
2568
+ profile.view_mode = true
2569
+
2570
+ return profile
2571
+
2572
+ else
2573
+
2574
+ task.wait(exp_backoff) -- A DataStore call has likely ended in an error - repeat the call shortly
2575
+ exp_backoff = math.min(20, exp_backoff * 2)
2576
+
2577
+ end
2578
+
2579
+ end
2580
+
2581
+ return nil -- Game started shutting down - don't return the profile
2582
+
2583
+ end
2584
+
2585
+ function ProfileStore:RemoveAsync(profile_key)
2586
+
2587
+ local is_mock = ReadMockFlag()
2588
+
2589
+ if type(profile_key) ~= "string" or string.len(profile_key) == 0 then
2590
+ error(`[{script.Name}]: Invalid profile_key`)
2591
+ end
2592
+
2593
+ if ProfileStore.IsClosing == true then
2594
+ return false
2595
+ end
2596
+
2597
+ WaitForStoreReady(self)
2598
+
2599
+ local wipe_status = false
2600
+
2601
+ local next_in_queue = WaitInUpdateQueue(SessionToken(self.Name, profile_key, is_mock))
2602
+
2603
+ if is_mock == true then -- Used when the profile is accessed through ProfileStore.Mock
2604
+
2605
+ local mock_data_store = UserMockStore[self.Name]
2606
+
2607
+ if mock_data_store ~= nil then
2608
+ mock_data_store[profile_key] = nil
2609
+ if next(mock_data_store) == nil then
2610
+ UserMockStore[self.Name] = nil
2611
+ end
2612
+ end
2613
+
2614
+ wipe_status = true
2615
+ task.wait() -- Simulate API call yield
2616
+
2617
+ elseif DataStoreState ~= "Access" then -- Used when API access is disabled
2618
+
2619
+ local mock_data_store = MockStore[self.Name]
2620
+
2621
+ if mock_data_store ~= nil then
2622
+ mock_data_store[profile_key] = nil
2623
+ if next(mock_data_store) == nil then
2624
+ MockStore[self.Name] = nil
2625
+ end
2626
+ end
2627
+
2628
+ wipe_status = true
2629
+ task.wait() -- Simulate API call yield
2630
+
2631
+ else -- Live DataStore
2632
+
2633
+ wipe_status = pcall(function()
2634
+ self.data_store:RemoveAsync(profile_key)
2635
+ end)
2636
+
2637
+ end
2638
+
2639
+ next_in_queue()
2640
+
2641
+ return wipe_status
2642
+
2643
+ end
2644
+
2645
+ local ProfileVersionQuery = {}
2646
+ ProfileVersionQuery.__index = ProfileVersionQuery
2647
+
2648
+ function ProfileVersionQuery.New(profile_store, profile_key, sort_direction, min_date, max_date, is_mock)
2649
+
2650
+ local self = {
2651
+ profile_store = profile_store,
2652
+ profile_key = profile_key,
2653
+ sort_direction = sort_direction,
2654
+ min_date = min_date,
2655
+ max_date = max_date,
2656
+
2657
+ query_pages = nil,
2658
+ query_index = 0,
2659
+ query_failure = false,
2660
+
2661
+ is_query_yielded = false,
2662
+ query_queue = {},
2663
+
2664
+ is_mock = is_mock,
2665
+ }
2666
+ setmetatable(self, ProfileVersionQuery)
2667
+
2668
+ return self
2669
+
2670
+ end
2671
+
2672
+ function MoveVersionQueryQueue(self) -- Hidden ProfileVersionQuery method
2673
+ while #self.query_queue > 0 do
2674
+
2675
+ local queue_entry = table.remove(self.query_queue, 1)
2676
+
2677
+ task.spawn(queue_entry)
2678
+
2679
+ if self.is_query_yielded == true then
2680
+ break
2681
+ end
2682
+
2683
+ end
2684
+ end
2685
+
2686
+ local VersionQueryNextAsyncStackingFlag = false
2687
+ local WarnAboutVersionQueryOnce = false
2688
+
2689
+ function ProfileVersionQuery:NextAsync()
2690
+
2691
+ local is_stacking = VersionQueryNextAsyncStackingFlag == true
2692
+ VersionQueryNextAsyncStackingFlag = false
2693
+
2694
+ WaitForStoreReady(self.profile_store)
2695
+
2696
+ if ProfileStore.IsClosing == true then
2697
+ return nil -- Silently fail :NextAsync() requests
2698
+ end
2699
+
2700
+ if self.is_mock == true or DataStoreState ~= "Access" then
2701
+ if IsStudio == true and WarnAboutVersionQueryOnce == false then
2702
+ WarnAboutVersionQueryOnce = true
2703
+ warn(`[{script.Name}]: :VersionQuery() is not supported in mock mode!`)
2704
+ end
2705
+ return nil -- Silently fail :NextAsync() requests
2706
+ end
2707
+
2708
+ local profile
2709
+ local is_finished = false
2710
+
2711
+ local function query_job()
2712
+
2713
+ if self.query_failure == true then
2714
+ is_finished = true
2715
+ return
2716
+ end
2717
+
2718
+ -- First "next" call loads version pages:
2719
+
2720
+ if self.query_pages == nil then
2721
+
2722
+ self.is_query_yielded = true
2723
+
2724
+ task.spawn(function()
2725
+ VersionQueryNextAsyncStackingFlag = true
2726
+ profile = self:NextAsync()
2727
+ is_finished = true
2728
+ end)
2729
+
2730
+ local list_success, error_message = pcall(function()
2731
+ self.query_pages = self.profile_store.data_store:ListVersionsAsync(
2732
+ self.profile_key,
2733
+ self.sort_direction,
2734
+ self.min_date,
2735
+ self.max_date
2736
+ )
2737
+ self.query_index = 0
2738
+ end)
2739
+
2740
+ if list_success == false or self.query_pages == nil then
2741
+ warn(`[{script.Name}]: Version query fail - {tostring(error_message)}`)
2742
+ self.query_failure = true
2743
+ end
2744
+
2745
+ self.is_query_yielded = false
2746
+
2747
+ MoveVersionQueryQueue(self)
2748
+
2749
+ return
2750
+
2751
+ end
2752
+
2753
+ local current_page = self.query_pages:GetCurrentPage()
2754
+ local next_item = current_page[self.query_index + 1]
2755
+
2756
+ -- No more entries:
2757
+
2758
+ if self.query_pages.IsFinished == true and next_item == nil then
2759
+ is_finished = true
2760
+ return
2761
+ end
2762
+
2763
+ -- Load next page when this page is over:
2764
+
2765
+ if next_item == nil then
2766
+
2767
+ self.is_query_yielded = true
2768
+ task.spawn(function()
2769
+ VersionQueryNextAsyncStackingFlag = true
2770
+ profile = self:NextAsync()
2771
+ is_finished = true
2772
+ end)
2773
+
2774
+ local success, error_message = pcall(function()
2775
+ self.query_pages:AdvanceToNextPageAsync()
2776
+ self.query_index = 0
2777
+ end)
2778
+
2779
+ if success == false or #self.query_pages:GetCurrentPage() == 0 then
2780
+ self.query_failure = true
2781
+ end
2782
+
2783
+ self.is_query_yielded = false
2784
+ MoveVersionQueryQueue(self)
2785
+
2786
+ return
2787
+
2788
+ end
2789
+
2790
+ -- Next page item:
2791
+
2792
+ self.query_index += 1
2793
+ profile = self.profile_store:GetAsync(self.profile_key, next_item.Version)
2794
+ is_finished = true
2795
+
2796
+ end
2797
+
2798
+ if self.is_query_yielded == false then
2799
+ query_job()
2800
+ else
2801
+ if is_stacking == true then
2802
+ table.insert(self.query_queue, 1, query_job)
2803
+ else
2804
+ table.insert(self.query_queue, query_job)
2805
+ end
2806
+ end
2807
+
2808
+ while is_finished == false do
2809
+ task.wait()
2810
+ end
2811
+
2812
+ return profile
2813
+
2814
+ end
2815
+
2816
+ function ProfileStore:VersionQuery(profile_key, sort_direction, min_date, max_date)
2817
+
2818
+ local is_mock = ReadMockFlag()
2819
+
2820
+ if type(profile_key) ~= "string" or string.len(profile_key) == 0 then
2821
+ error(`[{script.Name}]: Invalid profile_key`)
2822
+ end
2823
+
2824
+ -- Type check:
2825
+
2826
+ if sort_direction ~= nil and (typeof(sort_direction) ~= "EnumItem"
2827
+ or sort_direction.EnumType ~= Enum.SortDirection) then
2828
+ error(`[{script.Name}]: Invalid sort_direction ({tostring(sort_direction)})`)
2829
+ end
2830
+
2831
+ if min_date ~= nil and typeof(min_date) ~= "DateTime" and typeof(min_date) ~= "number" then
2832
+ error(`[{script.Name}]: Invalid min_date ({tostring(min_date)})`)
2833
+ end
2834
+
2835
+ if max_date ~= nil and typeof(max_date) ~= "DateTime" and typeof(max_date) ~= "number" then
2836
+ error(`[{script.Name}]: Invalid max_date ({tostring(max_date)})`)
2837
+ end
2838
+
2839
+ min_date = typeof(min_date) == "DateTime" and min_date.UnixTimestampMillis or min_date
2840
+ max_date = typeof(max_date) == "DateTime" and max_date.UnixTimestampMillis or max_date
2841
+
2842
+ return ProfileVersionQuery.New(self, profile_key, sort_direction, min_date, max_date, is_mock)
2843
+
2844
+ end
2845
+
2846
+ -- DataStore API access check:
2847
+
2848
+ if IsStudio == true then
2849
+
2850
+ task.spawn(function()
2851
+
2852
+ local new_state = "NoAccess"
2853
+
2854
+ local status, message = pcall(function()
2855
+ -- This will error if current instance has no Studio API access:
2856
+ DataStoreService:GetDataStore("____PS"):SetAsync("____PS", os.time())
2857
+ end)
2858
+
2859
+ local no_internet_access = status == false and string.find(message, "ConnectFail", 1, true) ~= nil
2860
+
2861
+ if no_internet_access == true then
2862
+ warn(`[{script.Name}]: No internet access - check your network connection`)
2863
+ end
2864
+
2865
+ if status == false and
2866
+ (string.find(message, "403", 1, true) ~= nil or -- Cannot write to DataStore from studio if API access is not enabled
2867
+ string.find(message, "must publish", 1, true) ~= nil or -- Game must be published to access live keys
2868
+ no_internet_access == true) then -- No internet access
2869
+
2870
+ new_state = if no_internet_access == true then "NoInternet" else "NoAccess"
2871
+ print(`[{script.Name}]: Roblox API services unavailable - data will not be saved`)
2872
+ else
2873
+ new_state = "Access"
2874
+ print(`[{script.Name}]: Roblox API services available - data will be saved`)
2875
+ end
2876
+
2877
+ DataStoreState = new_state
2878
+ ProfileStore.DataStoreState = new_state
2879
+
2880
+ end)
2881
+
2882
+ else
2883
+
2884
+ DataStoreState = "Access"
2885
+ ProfileStore.DataStoreState = "Access"
2886
+
2887
+ end
2888
+
2889
+ -- Update loop:
2890
+
2891
+ RunService.Heartbeat:Connect(function()
2892
+
2893
+ -- Auto saving:
2894
+
2895
+ local auto_save_list_length = #AutoSaveList
2896
+ if auto_save_list_length > 0 then
2897
+ local auto_save_index_speed = AUTO_SAVE_PERIOD / auto_save_list_length
2898
+ local os_clock = os.clock()
2899
+ while os_clock - LastAutoSave > auto_save_index_speed do
2900
+ LastAutoSave = LastAutoSave + auto_save_index_speed
2901
+ local profile = AutoSaveList[AutoSaveIndex]
2902
+ if os_clock - profile.load_timestamp < AUTO_SAVE_PERIOD / 2 then
2903
+ -- This profile is freshly loaded - auto saving immediately is not necessary:
2904
+ profile = nil
2905
+ for _ = 1, auto_save_list_length - 1 do
2906
+ -- Move auto save index to the right:
2907
+ AutoSaveIndex = AutoSaveIndex + 1
2908
+ if AutoSaveIndex > auto_save_list_length then
2909
+ AutoSaveIndex = 1
2910
+ end
2911
+ profile = AutoSaveList[AutoSaveIndex]
2912
+ if os_clock - profile.load_timestamp >= AUTO_SAVE_PERIOD / 2 then
2913
+ break
2914
+ else
2915
+ profile = nil
2916
+ end
2917
+ end
2918
+ end
2919
+ -- Move auto save index to the right:
2920
+ AutoSaveIndex = AutoSaveIndex + 1
2921
+ if AutoSaveIndex > auto_save_list_length then
2922
+ AutoSaveIndex = 1
2923
+ end
2924
+ -- Perform save call:
2925
+ if profile ~= nil then
2926
+ task.spawn(SaveProfileAsync, profile) -- Auto save profile in new thread
2927
+ end
2928
+ end
2929
+ end
2930
+
2931
+ -- Critical state handling:
2932
+
2933
+ if ProfileStore.IsCriticalState == false then
2934
+ if #IssueQueue >= CRITICAL_STATE_ERROR_COUNT then
2935
+ ProfileStore.IsCriticalState = true
2936
+ ProfileStore.OnCriticalToggle:Fire(true)
2937
+ CriticalStateStart = os.clock()
2938
+ warn(`[{script.Name}]: Entered critical state`)
2939
+ end
2940
+ else
2941
+ if #IssueQueue >= CRITICAL_STATE_ERROR_COUNT then
2942
+ CriticalStateStart = os.clock()
2943
+ elseif os.clock() - CriticalStateStart > CRITICAL_STATE_EXPIRE then
2944
+ ProfileStore.IsCriticalState = false
2945
+ ProfileStore.OnCriticalToggle:Fire(false)
2946
+ warn(`[{script.Name}]: Critical state ended`)
2947
+ end
2948
+ end
2949
+
2950
+ -- Issue queue:
2951
+
2952
+ while true do
2953
+ local issue_time = IssueQueue[1]
2954
+ if issue_time == nil then
2955
+ break
2956
+ elseif os.clock() - issue_time > CRITICAL_STATE_ERROR_EXPIRE then
2957
+ table.remove(IssueQueue, 1)
2958
+ else
2959
+ break
2960
+ end
2961
+ end
2962
+
2963
+ end)
2964
+
2965
+ -- Release all loaded profiles when the server is shutting down:
2966
+
2967
+ task.spawn(function()
2968
+
2969
+ while DataStoreState == "NotReady" do
2970
+ task.wait()
2971
+ end
2972
+
2973
+ if DataStoreState ~= "Access" then
2974
+
2975
+ game:BindToClose(function()
2976
+ -- SCRIBE PATCH: same opt-out as the live handler below.
2977
+ if ProfileStore.ExternalShutdown == true then
2978
+ return
2979
+ end
2980
+ ProfileStore.IsClosing = true
2981
+ task.wait() -- Mock shutdown delay
2982
+ end)
2983
+
2984
+ return -- Don't wait for profiles to properly save in mock mode so studio could end the simulation faster
2985
+
2986
+ end
2987
+
2988
+ game:BindToClose(function()
2989
+
2990
+ -- SCRIBE PATCH: stand down when the owner drives shutdown itself.
2991
+ --
2992
+ -- Roblox runs every bound callback CONCURRENTLY and documents no order, and
2993
+ -- both this and Scribe's drain want the same instant. This one releases every
2994
+ -- profile immediately -- RemoveProfileFromAutoSave runs synchronously inside
2995
+ -- SaveProfileAsync, before any DataStore call -- while Scribe's drain first
2996
+ -- collects the sessions whose profile is still IsActive() so it can run each
2997
+ -- player's leaving hook. Whoever is invoked first wins outright, because
2998
+ -- neither yields before it has taken what it needs.
2999
+ --
3000
+ -- Measured: with this handler first, ZERO leaving hooks run -- the drain's list
3001
+ -- comes back empty, so it skips nothing and reports nothing. It only works today
3002
+ -- because this registration waits behind `while DataStoreState == "NotReady"` (a
3003
+ -- DataStore round trip) while Scribe's happens during construction; a game that
3004
+ -- builds Scribe lazily gets the other order.
3005
+ --
3006
+ -- So the owner takes it over instead of racing it: BeginClose(), then AwaitClose()
3007
+ -- once its hooks have run and its sessions are ended.
3008
+ if ProfileStore.ExternalShutdown == true then
3009
+ return
3010
+ end
3011
+
3012
+ ProfileStore.BeginClose()
3013
+ ProfileStore.AwaitClose()
3014
+
3015
+ end)
3016
+
3017
+ end)
3018
+
3019
+ return ProfileStore