-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathProfileStore.luau
2232 lines (1637 loc) · 62.8 KB
/
ProfileStore.luau
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--[[
MAD STUDIO (by loleris)
-[ProfileStore]---------------------------------------
Periodic DataStore saving solution with session locking
WARNINGS FOR "Profile.Data" VALUES:
! Do not create numeric tables with gaps - attempting to store such tables will result in an error.
! Do not create mixed tables (some values indexed by number and others by a string key)
- only numerically indexed data will be stored.
! Do not index tables by anything other than numbers and strings.
! Do not reference Roblox Instances
! Do not reference userdata (Vector3, Color3, CFrame...) - Serialize userdata before referencing
! Do not reference functions
Members:
ProfileStore.IsClosing [bool]
-- Set to true after a game:BindToClose() trigger
ProfileStore.IsCriticalState [bool]
-- Set to true when ProfileStore experiences too many consecutive errors
ProfileStore.OnError [Signal] (message, store_name, profile_key)
-- Most ProfileStore errors will be caught and passed to this signal
ProfileStore.OnOverwrite [Signal] (store_name, profile_key)
-- Triggered when a DataStore key was likely used to store data that wasn't
a ProfileStore profile or the ProfileStore structure was invalidly manually
altered for that DataStore key
ProfileStore.OnCriticalToggle [Signal] (is_critical)
-- Triggered when ProfileStore experiences too many consecutive errors
ProfileStore.DataStoreState [string] ("NotReady", "NoInternet", "NoAccess", "Access")
-- This value resembles ProfileStore's access to the DataStore; The value starts
as "NotReady" and will eventually change to one of the other 3 possible values.
Functions:
ProfileStore.New(store_name, template?) --> [ProfileStore]
store_name [string] -- DataStore name
template [table] or nil -- Profiles will default to given table (hard-copy) when no data was saved previously
ProfileStore.SetConstant(name, value)
name [string]
value [number]
Members [ProfileStore]:
ProfileStore.Mock [ProfileStore]
-- Reflection of ProfileStore methods, but the methods will now query a mock
DataStore with no relation to the real DataStore
ProfileStore.Name [string]
Methods [ProfileStore]:
ProfileStore:StartSessionAsync(profile_key, params?) --> [Profile] or nil
profile_key [string] -- DataStore key
params nil or [table]: -- Custom params; E.g. {Steal = true}
{
Steal = true, -- Pass this to disregard an existing session lock
Cancel = fn() -> (boolean), -- Pass this to create a request cancel condition.
-- If the cancel function returns true, ProfileStore will stop trying to
-- start the session and return nil
}
ProfileStore:MessageAsync(profile_key, message) --> is_success [bool]
profile_key [string] -- DataStore key
message [table] -- Data to be messaged to the profile
ProfileStore:GetAsync(profile_key, version?) --> [Profile] or nil
-- Reads a profile without starting a session - will not autosave
profile_key [string] -- DataStore key
version nil or [string] -- DataStore key version
ProfileStore:VersionQuery(profile_key, sort_direction?, min_date?, max_date?) --> [VersionQuery]
profile_key [string]
sort_direction nil or [Enum.SortDirection]
min_date nil or [DateTime]
max_date nil or [DateTime]
ProfileStore:RemoveAsync(profile_key) --> is_success [bool]
-- Completely removes profile data from the DataStore / mock DataStore with no way to recover it.
Methods [VersionQuery]:
VersionQuery:NextAsync() --> [Profile] or nil -- (Yields)
-- Returned profile is similar to profiles returned by ProfileStore:GetAsync()
Members [Profile]:
Profile.Data [table]
-- When the profile is active changes to this table are guaranteed to be saved
Profile.LastSavedData [table] (Read-only)
-- Last snapshot of "Profile.Data" that has been successfully saved to the DataStore;
Useful for proper developer product purchase receipt handling
Profile.FirstSessionTime [number] (Read-only)
-- os.time() timestamp of the first profile session
Profile.SessionLoadCount [number] (Read-only) -- Amount of times a session was started for this profile
Profile.Session [table] (Read-only) {PlaceId = number, JobId = string} / nil
-- Set to a table if this profile is in use by a server; nil if released
Profile.RobloxMetaData [table] -- Writable table that gets saved automatically and once the profile is released
Profile.UserIds [table] -- (Read-only) -- {user_id [number], ...} -- User ids associated with this profile
Profile.KeyInfo [DataStoreKeyInfo] -- Changes before OnAfterSave signal
Profile.OnSave [Signal] ()
-- Triggered right before changes to Profile.Data are saved to the DataStore
Profile.OnLastSave [Signal] (reason [string]: "Manual", "External", "Shutdown")
-- Triggered right before changes to Profile.Data are saved to the DataStore
for the last time; A reason is provided for the last save:
- "Manual" - Profile:EndSession() was called
- "Shutdown" - The server that has ownership of this profile is shutting down
- "External" - Another server has started a session for this profile
Note that this event will not trigger for when a profile session is ended by
another server trying to take ownership of the session - this is impossible to
do without compromising on ProfileStore's speed.
Profile.OnSessionEnd [Signal] ()
-- Triggered when the profile session is terminated on this server
Profile.OnAfterSave [Signal] (last_saved_data)
-- Triggered after a successful save
last_saved_data [table] -- Profile.LastSavedData
Profile.ProfileStore [ProfileStore] -- ProfileStore object this profile belongs to
Profile.Key [string] -- DataStore key
Methods [Profile]:
Profile:IsActive() --> [bool] -- If "true" is returned, changes to Profile.Data are guaranteed to save;
This guarantee is only valid until code yields (e.g. task.wait() is used).
Profile:Reconcile() -- Fills in missing (nil) [string_key] = [value] pairs to the Profile.Data structure
from the "template" argument that was passed to "ProfileStore.New()"
Profile:EndSession() -- Call after the server has finished working with this profile
e.g., after the player leaves (Profile object will become inactive)
Profile:AddUserId(user_id) -- Associates user_id with profile (GDPR compliance)
user_id [number]
Profile:RemoveUserId(user_id) -- Unassociates user_id with profile (safe function)
user_id [number]
Profile:MessageHandler(fn) -- Sets a message handler for this profile
fn [function] (message [table], processed [function]())
-- The handler function receives a message table and a callback function;
The callback function is to be called when a message has been processed
- this will discard the message from the profile message cache; If the
callback function is not called, other message handlers will also be triggered
with unprocessed message data.
Profile:Save() -- If the profile session is still active makes an UpdateAsync call
to the DataStore to immediately save profile data
Profile:SetAsync() -- Forcefully saves changes to the profile; Only for profiles
loaded with ProfileStore:GetAsync() or ProfileStore:VersionQuery()
--]]
local AUTO_SAVE_PERIOD = 300 -- (Seconds) Time between when changes to a profile are saved to the DataStore
local LOAD_REPEAT_PERIOD = 10 -- (Seconds) Time between successive profile reads when handling a session conflict
local FIRST_LOAD_REPEAT = 5 -- (Seconds) Time between first and second profile read when handling a session conflict
local SESSION_STEAL = 40 -- (Seconds) Time until a session conflict is resolved with the waiting server stealing the session
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
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
local CRITICAL_STATE_ERROR_COUNT = 5 -- Assume critical state if this many issues happen in a short amount of time
local CRITICAL_STATE_ERROR_EXPIRE = 120 -- (Seconds) Individual issue expiration
local CRITICAL_STATE_EXPIRE = 120 -- (Seconds) Critical state expiration
local MAX_MESSAGE_QUEUE = 1000 -- Max messages saved in a profile that were sent using "ProfileStore:MessageAsync()"
----- Dependencies -----
-- local Util = require(game.ReplicatedStorage.Shared.Util)
-- local Signal = Util.Signal
local Signal do
local FreeRunnerThread
--[[
Yield-safe coroutine reusing by stravant;
Sources:
https://devforum.roblox.com/t/lua-signal-class-comparison-optimal-goodsignal-class/1387063
https://gist.github.com/stravant/b75a322e0919d60dde8a0316d1f09d2f
--]]
local function AcquireRunnerThreadAndCallEventHandler(fn, ...)
local acquired_runner_thread = FreeRunnerThread
FreeRunnerThread = nil
fn(...)
-- The handler finished running, this runner thread is free again.
FreeRunnerThread = acquired_runner_thread
end
local function RunEventHandlerInFreeThread(...)
AcquireRunnerThreadAndCallEventHandler(...)
while true do
AcquireRunnerThreadAndCallEventHandler(coroutine.yield())
end
end
local Connection = {}
Connection.__index = Connection
local SignalClass = {}
SignalClass.__index = SignalClass
function Connection:Disconnect()
if self.is_connected == false then
return
end
local signal = self.signal
self.is_connected = false
signal.listener_count -= 1
if signal.head == self then
signal.head = self.next
else
local prev = signal.head
while prev ~= nil and prev.next ~= self do
prev = prev.next
end
if prev ~= nil then
prev.next = self.next
end
end
end
function SignalClass.New()
local self = {
head = nil,
listener_count = 0,
}
setmetatable(self, SignalClass)
return self
end
function SignalClass:Connect(listener: (...any) -> ())
if type(listener) ~= "function" then
error(`[{script.Name}]: \"listener\" must be a function; Received {typeof(listener)}`)
end
local connection = {
listener = listener,
signal = self,
next = self.head,
is_connected = true,
}
setmetatable(connection, Connection)
self.head = connection
self.listener_count += 1
return connection
end
function SignalClass:GetListenerCount(): number
return self.listener_count
end
function SignalClass:Fire(...)
local item = self.head
while item ~= nil do
if item.is_connected == true then
if not FreeRunnerThread then
FreeRunnerThread = coroutine.create(RunEventHandlerInFreeThread)
end
task.spawn(FreeRunnerThread, item.listener, ...)
end
item = item.next
end
end
function SignalClass:Wait()
local co = coroutine.running()
local connection
connection = self:Connect(function(...)
connection:Disconnect()
task.spawn(co, ...)
end)
return coroutine.yield()
end
Signal = table.freeze({
New = SignalClass.New,
})
end
----- Private -----
local ActiveSessionCheck = {} -- {[session_token] = profile, ...}
local AutoSaveList = {} -- {profile, ...} -- Loaded profile table which will be circularly auto-saved
local IssueQueue = {} -- {issue_time, ...}
local DataStoreService = game:GetService("DataStoreService")
local MessagingService = game:GetService("MessagingService")
local HttpService = game:GetService("HttpService")
local RunService = game:GetService("RunService")
local PlaceId = game.PlaceId
local JobId = game.JobId
local AutoSaveIndex = 1 -- Next profile to auto save
local LastAutoSave = os.clock()
local LoadIndex = 0
local ActiveProfileLoadJobs = 0 -- Number of active threads that are loading in profiles
local ActiveProfileSaveJobs = 0 -- Number of active threads that are saving profiles
local CriticalStateStart = 0 -- os.clock()
local IsStudio = RunService:IsStudio()
local DataStoreState: "NotReady" | "NoInternet" | "NoAccess" | "Access" = "NotReady"
local MockStore = {}
local UserMockStore = {}
local MockFlag = false
local OnError = Signal.New() -- (message, store_name, profile_key)
local OnOverwrite = Signal.New() -- (store_name, profile_key)
local UpdateQueue = { -- For stability sake, we won't do UpdateAsync calls for the same key until all previous calls finish
--[[
[session_token] = {
coroutine, ...
},
...
--]]
}
local function WaitInUpdateQueue(session_token) --> next_in_queue()
local is_first = false
if UpdateQueue[session_token] == nil then
is_first = true
UpdateQueue[session_token] = {}
end
local queue = UpdateQueue[session_token]
if is_first == false then
table.insert(queue, coroutine.running())
coroutine.yield()
end
return function()
local next_co = table.remove(queue, 1)
if next_co ~= nil then
coroutine.resume(next_co)
else
UpdateQueue[session_token] = nil
end
end
end
local function SessionToken(store_name, profile_key, is_mock)
local session_token = "L_" -- Live
if is_mock == true then
session_token = "U_" -- User mock
elseif DataStoreState ~= "Access" then
session_token = "M_" -- Mock, cause no DataStore access
end
session_token ..= store_name .. "\0" .. profile_key
return session_token
end
local function DeepCopyTable(t)
local copy = {}
for key, value in pairs(t) do
if type(value) == "table" then
copy[key] = DeepCopyTable(value)
else
copy[key] = value
end
end
return copy
end
local function ReconcileTable(target, template)
for k, v in pairs(template) do
if type(k) == "string" then -- Only string keys will be reconciled
if target[k] == nil then
if type(v) == "table" then
target[k] = DeepCopyTable(v)
else
target[k] = v
end
elseif type(target[k]) == "table" and type(v) == "table" then
ReconcileTable(target[k], v)
end
end
end
end
local function RegisterError(error_message, store_name, profile_key) -- Called when a DataStore API call errors
warn(`[{script.Name}]: DataStore API error (STORE:{store_name}; KEY:{profile_key}) - {tostring(error_message)}`)
table.insert(IssueQueue, os.clock()) -- Adding issue time to queue
OnError:Fire(tostring(error_message), store_name, profile_key)
end
local function RegisterOverwrite(store_name, profile_key) -- Called when a corrupted profile is loaded
warn(`[{script.Name}]: Invalid profile was overwritten (STORE:{store_name}; KEY:{profile_key})`)
OnOverwrite:Fire(store_name, profile_key)
end
local function NewMockDataStoreKeyInfo(params)
local version_id_string = tostring(params.VersionId or 0)
local meta_data = params.MetaData or {}
local user_ids = params.UserIds or {}
return {
CreatedTime = params.CreatedTime,
UpdatedTime = params.UpdatedTime,
Version = string.rep("0", 16) .. "."
.. string.rep("0", 10 - string.len(version_id_string)) .. version_id_string
.. "." .. string.rep("0", 16) .. "." .. "01",
GetMetadata = function()
return DeepCopyTable(meta_data)
end,
GetUserIds = function()
return DeepCopyTable(user_ids)
end,
}
end
local function MockUpdateAsync(mock_data_store, profile_store_name, key, transform_function, is_get_call) --> loaded_data, key_info
local profile_store = mock_data_store[profile_store_name]
if profile_store == nil then
profile_store = {}
mock_data_store[profile_store_name] = profile_store
end
local epoch_time = math.floor(os.time() * 1000)
local mock_entry = profile_store[key]
local mock_entry_was_nil = false
if mock_entry == nil then
mock_entry_was_nil = true
if is_get_call ~= true then
mock_entry = {
Data = nil,
CreatedTime = epoch_time,
UpdatedTime = epoch_time,
VersionId = 0,
UserIds = {},
MetaData = {},
}
profile_store[key] = mock_entry
end
end
local mock_key_info = mock_entry_was_nil == false and NewMockDataStoreKeyInfo(mock_entry) or nil
local transform, user_ids, roblox_meta_data = transform_function(mock_entry and mock_entry.Data, mock_key_info)
if transform == nil then
return nil
else
if mock_entry ~= nil and is_get_call ~= true then
mock_entry.Data = DeepCopyTable(transform)
mock_entry.UserIds = DeepCopyTable(user_ids or {})
mock_entry.MetaData = DeepCopyTable(roblox_meta_data or {})
mock_entry.VersionId += 1
mock_entry.UpdatedTime = epoch_time
end
return DeepCopyTable(transform), mock_entry ~= nil and NewMockDataStoreKeyInfo(mock_entry) or nil
end
end
local function UpdateAsync(profile_store, profile_key, transform_params, is_user_mock, is_get_call, version) --> loaded_data, key_info
--transform_params = {
-- ExistingProfileHandle = function(latest_data),
-- MissingProfileHandle = function(latest_data),
-- EditProfile = function(lastest_data),
--}
local loaded_data, key_info
local next_in_queue = WaitInUpdateQueue(SessionToken(profile_store.Name, profile_key, is_user_mock))
local success = true
local success, error_message = pcall(function()
local transform_function = function(latest_data)
local missing_profile = false
local overwritten = false
local global_updates = {0, {}}
if latest_data == nil then
missing_profile = true
elseif type(latest_data) ~= "table" then
missing_profile = true
overwritten = true
else
if type(latest_data.Data) == "table" and type(latest_data.MetaData) == "table" and type(latest_data.GlobalUpdates) == "table" then
-- Regular profile structure detected:
latest_data.WasOverwritten = false -- Must be set to false if set previously
global_updates = latest_data.GlobalUpdates
if transform_params.ExistingProfileHandle ~= nil then
transform_params.ExistingProfileHandle(latest_data)
end
elseif latest_data.Data == nil and latest_data.MetaData == nil and type(latest_data.GlobalUpdates) == "table" then
-- Regular structure not detected, but GlobalUpdate data exists:
latest_data.WasOverwritten = false -- Must be set to false if set previously
global_updates = latest_data.GlobalUpdates or global_updates
missing_profile = true
else
missing_profile = true
overwritten = true
end
end
-- Profile was not created or corrupted and no GlobalUpdate data exists:
if missing_profile == true then
latest_data = {
-- Data = nil,
-- MetaData = nil,
GlobalUpdates = global_updates,
}
if transform_params.MissingProfileHandle ~= nil then
transform_params.MissingProfileHandle(latest_data)
end
end
-- Editing profile:
if transform_params.EditProfile ~= nil then
transform_params.EditProfile(latest_data)
end
-- Invalid data handling (Silently override with empty profile)
if overwritten == true then
latest_data.WasOverwritten = true -- Temporary tag that will be removed on first save
end
return latest_data, latest_data.UserIds, latest_data.RobloxMetaData
end
if is_user_mock == true then -- Used when the profile is accessed through ProfileStore.Mock
loaded_data, key_info = MockUpdateAsync(UserMockStore, profile_store.Name, profile_key, transform_function, is_get_call)
task.wait() -- Simulate API call yield
elseif DataStoreState ~= "Access" then -- Used when API access is disabled
loaded_data, key_info = MockUpdateAsync(MockStore, profile_store.Name, profile_key, transform_function, is_get_call)
task.wait() -- Simulate API call yield
else
if is_get_call == true then
if version ~= nil then
local success, error_message = pcall(function()
loaded_data, key_info = profile_store.data_store:GetVersionAsync(profile_key, version)
end)
if success == false and type(error_message) == "string" and string.find(error_message, "not valid") ~= nil then
warn(`[{script.Name}]: Passed version argument is not valid; Traceback:\n` .. debug.traceback())
end
else
loaded_data, key_info = profile_store.data_store:GetAsync(profile_key)
end
loaded_data = transform_function(loaded_data)
else
loaded_data, key_info = profile_store.data_store:UpdateAsync(profile_key, transform_function)
end
end
end)
next_in_queue()
if success == true and type(loaded_data) == "table" then
-- Invalid data handling:
if loaded_data.WasOverwritten == true and is_get_call ~= true then
RegisterOverwrite(
profile_store.Name,
profile_key
)
end
-- Return loaded_data:
return loaded_data, key_info
else
-- Error handling:
RegisterError(
error_message or "Undefined error",
profile_store.Name,
profile_key
)
-- Return nothing:
return nil
end
end
local function IsThisSession(session_tag)
return session_tag[1] == PlaceId and session_tag[2] == JobId
end
local function ReadMockFlag(): boolean
local is_mock = MockFlag
MockFlag = false
return is_mock
end
local function WaitForStoreReady(profile_store)
while profile_store.is_ready == false do
task.wait()
end
end
local function AddProfileToAutoSave(profile)
ActiveSessionCheck[profile.session_token] = profile
-- Add at AutoSaveIndex and move AutoSaveIndex right:
table.insert(AutoSaveList, AutoSaveIndex, profile)
if #AutoSaveList > 1 then
AutoSaveIndex = AutoSaveIndex + 1
elseif #AutoSaveList == 1 then
-- First profile created - make sure it doesn't get immediately auto saved:
LastAutoSave = os.clock()
end
end
local function RemoveProfileFromAutoSave(profile)
ActiveSessionCheck[profile.session_token] = nil
local auto_save_index = table.find(AutoSaveList, profile)
if auto_save_index ~= nil then
table.remove(AutoSaveList, auto_save_index)
if auto_save_index < AutoSaveIndex then
AutoSaveIndex = AutoSaveIndex - 1 -- Table contents were moved left before AutoSaveIndex so move AutoSaveIndex left as well
end
if AutoSaveList[AutoSaveIndex] == nil then -- AutoSaveIndex was at the end of the AutoSaveList - reset to 1
AutoSaveIndex = 1
end
end
end
local function SaveProfileAsync(profile, is_ending_session, is_overwriting, last_save_reason)
if type(profile.Data) ~= "table" then
error(`[{script.Name}]: Developer code likely set "Profile.Data" to a non-table value! (STORE:{profile.ProfileStore.Name}; KEY:{profile.Key})`)
end
profile.OnSave:Fire()
if is_ending_session == true then
profile.OnLastSave:Fire(last_save_reason or "Manual")
end
if is_ending_session == true and is_overwriting ~= true then
if profile.roblox_message_subscription ~= nil then
profile.roblox_message_subscription:Disconnect()
end
RemoveProfileFromAutoSave(profile)
profile.OnSessionEnd:Fire()
end
ActiveProfileSaveJobs = ActiveProfileSaveJobs + 1
-- 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
local repeat_save_flag = true -- Released Profile save calls have to repeat until they succeed
local exp_backoff = 1
while repeat_save_flag == true do
if is_ending_session ~= true then
repeat_save_flag = false
end
local loaded_data, key_info = UpdateAsync(
profile.ProfileStore,
profile.Key,
{
ExistingProfileHandle = nil,
MissingProfileHandle = nil,
EditProfile = function(latest_data)
-- Check if this session still owns the profile:
local session_owns_profile = false
if is_overwriting ~= true then
local active_session = latest_data.MetaData.ActiveSession
local session_load_count = latest_data.MetaData.SessionLoadCount
if type(active_session) == "table" then
session_owns_profile = IsThisSession(active_session) and session_load_count == profile.load_index
end
else
session_owns_profile = true
end
-- We may only edit the profile if this server has ownership of the profile:
if session_owns_profile == true then
-- Clear processed updates (messages):
local locked_updates = profile.locked_global_updates -- [index] = true, ...
local active_updates = latest_data.GlobalUpdates[2]
-- ProfileService module format: {{update_id, version_id, update_locked, update_data}, ...}
-- ProfileStore module format: {{update_id, update_data}, ...}
if next(locked_updates) ~= nil then
local i = 1
while i <= #active_updates do
local update = active_updates[i]
if locked_updates[update[1]] == true then
table.remove(active_updates, i)
else
i += 1
end
end
end
-- Save profile data:
latest_data.Data = profile.Data
latest_data.RobloxMetaData = profile.RobloxMetaData
latest_data.UserIds = profile.UserIds
if is_overwriting ~= true then
latest_data.MetaData.LastUpdate = os.time()
if is_ending_session == true then
latest_data.MetaData.ActiveSession = nil
end
else
latest_data.MetaData.ActiveSession = nil
latest_data.MetaData.ForceLoadSession = nil
end
end
end,
},
profile.is_mock
)
if loaded_data ~= nil and key_info ~= nil then
if is_overwriting == true then
break
end
repeat_save_flag = false
local active_session = loaded_data.MetaData.ActiveSession
local session_load_count = loaded_data.MetaData.SessionLoadCount
local session_owns_profile = false
if type(active_session) == "table" then
session_owns_profile = IsThisSession(active_session) and session_load_count == profile.load_index
end
local force_load_session = loaded_data.MetaData.ForceLoadSession
local force_load_pending = false
if type(force_load_session) == "table" then
force_load_pending = not IsThisSession(force_load_session)
end
local is_active = profile:IsActive()
-- If another server is trying to start a session for this profile - end the session:
if force_load_pending == true and session_owns_profile == true then
if is_active == true then
SaveProfileAsync(profile, true, false, "External")
end
break
end
-- Clearing processed update list / Detecting new updates:
local locked_updates = profile.locked_global_updates -- [index] = true, ...
local received_updates = profile.received_global_updates -- [index] = true, ...
local active_updates = loaded_data.GlobalUpdates[2]
local new_updates = {} -- {}, ...
local still_pending = {} -- [index] = true, ...
for _, update in ipairs(active_updates) do
if locked_updates[update[1]] == true then
still_pending[update[1]] = true
elseif received_updates[update[1]] ~= true then
received_updates[update[1]] = true
table.insert(new_updates, update)
end
end
for index in pairs(locked_updates) do
if still_pending[index] ~= true then
locked_updates[index] = nil
end
end
-- Updating profile values:
profile.KeyInfo = key_info
profile.LastSavedData = loaded_data.Data
profile.global_updates = loaded_data.GlobalUpdates and loaded_data.GlobalUpdates[2] or {}
if session_owns_profile == true then
if is_active == true and is_ending_session ~= true then
-- Processing new global updates (messages):
for _, update in ipairs(new_updates) do
local index = update[1]
local update_data = update[#update] -- Backwards compatibility with ProfileService
for _, handler in ipairs(profile.message_handlers) do
local is_processed = false
local processed_callback = function()
is_processed = true
locked_updates[index] = true
end
local send_update_data = DeepCopyTable(update_data)
task.spawn(handler, send_update_data, processed_callback)
if is_processed == true then
break
end
end
end
end
else
if profile.roblox_message_subscription ~= nil then
profile.roblox_message_subscription:Disconnect()
end
if is_active == true then
RemoveProfileFromAutoSave(profile)
profile.OnSessionEnd:Fire()
end
end
profile.OnAfterSave:Fire(profile.LastSavedData)
elseif repeat_save_flag == true then
-- DataStore call likely resulted in an error; Repeat the DataStore call shortly
task.wait(exp_backoff)
exp_backoff = math.min(if last_save_reason == "Shutdown" then 8 else 20, exp_backoff * 2)
end
end
ActiveProfileSaveJobs = ActiveProfileSaveJobs - 1
end
----- Public -----
--[[
Saved profile structure:
{
Data = {},
MetaData = {
ProfileCreateTime = 0,
SessionLoadCount = 0,
ActiveSession = {place_id, game_job_id, unique_session_id} / nil,
ForceLoadSession = {place_id, game_job_id} / nil,
LastUpdate = 0, -- os.time()
MetaTags = {}, -- Backwards compatibility with ProfileService
},
RobloxMetaData = {},
UserIds = {},
GlobalUpdates = {
update_index,
{
{update_index, data}, ...
},
},
}
--]]
export type JSONAcceptable = { JSONAcceptable } | { [string]: JSONAcceptable } | number | string | boolean | buffer
export type Profile<T> = {
Data: T & JSONAcceptable,
LastSavedData: T & JSONAcceptable,
FirstSessionTime: number,
SessionLoadCount: number,
Session: {PlaceId: number, JobId: string}?,
RobloxMetaData: JSONAcceptable,
UserIds: {number},
KeyInfo: DataStoreKeyInfo,
OnSave: {Connect: (self: any, listener: () -> ()) -> ({Disconnect: (self: any) -> ()})},
OnLastSave: {Connect: (self: any, listener: (reason: "Manual" | "External" | "Shutdown") -> ()) -> ({Disconnect: (self: any) -> ()})},
OnSessionEnd: {Connect: (self: any, listener: () -> ()) -> ({Disconnect: (self: any) -> ()})},
OnAfterSave: {Connect: (self: any, listener: (last_saved_data: T & JSONAcceptable) -> ()) -> ({Disconnect: (self: any) -> ()})},
ProfileStore: JSONAcceptable,
Key: string,
IsActive: (self: any) -> (boolean),
Reconcile: (self: any) -> (),
EndSession: (self: any) -> (),
AddUserId: (self: any, user_id: number) -> (),
RemoveUserId: (self: any, user_id: number) -> (),
MessageHandler: (self: any, fn: (message: JSONAcceptable, processed: () -> ()) -> ()) -> (),
Save: (self: any) -> (),
SetAsync: (self: any) -> (),
}
export type VersionQuery<T> = {
NextAsync: (self: any) -> (Profile<T>?),
}