forked from grilme99/ProfileService
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProfileService.lua
2621 lines (2288 loc) · 89.1 KB
/
ProfileService.lua
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
-- local Madwork = _G.Madwork
--[[
{Madwork}
-[ProfileService]---------------------------------------
(STANDALONE VERSION)
DataStore profiles - universal session-locked savable table API
Official documentation:
https://madstudioroblox.github.io/ProfileService/
DevForum discussion:
https://devforum.roblox.com/t/ProfileService/667805
WARNINGS FOR "Profile.Data" VALUES:
! Do not create numeric tables with gaps - attempting to replicate such tables will result in an error;
! Do not create mixed tables (some values indexed by number and others by string key), as only
the data indexed by number will be replicated.
! 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
WARNING: Calling ProfileStore:LoadProfileAsync() with a "profile_key" which wasn't released in the SAME SESSION will result
in an error! If you want to "ProfileStore:LoadProfileAsync()" instead of using the already loaded profile, :Release()
the old Profile object.
Members:
ProfileService.ServiceLocked [bool]
ProfileService.IssueSignal [ScriptSignal] (error_message, profile_store_name, profile_key)
ProfileService.CorruptionSignal [ScriptSignal] (profile_store_name, profile_key)
ProfileService.CriticalStateSignal [ScriptSignal] (is_critical_state)
Functions:
ProfileService.GetProfileStore(profile_store_index, profile_template) --> [ProfileStore]
profile_store_index [string] -- DataStore name
OR
profile_store_index [table]: -- Allows the developer to define more GlobalDataStore variables
{
Name = "StoreName", -- [string] -- DataStore name
-- Optional arguments:
Scope = "StoreScope", -- [string] -- DataStore scope
}
profile_template [table] -- Profiles will default to given table (hard-copy) when no data was saved previously
ProfileService.IsLive() --> [bool] -- (CAN YIELD!!!)
-- Returns true if ProfileService is connected to live Roblox DataStores
Members [ProfileStore]:
ProfileStore.Mock [ProfileStore] -- Reflection of ProfileStore methods, but the methods will use a mock DataStore
Methods [ProfileStore]:
ProfileStore:LoadProfileAsync(profile_key, not_released_handler) --> [Profile] or nil -- not_released_handler(place_id, game_job_id)
profile_key [string] -- DataStore key
not_released_handler nil or []: -- Defaults to "ForceLoad"
[string] "ForceLoad" -- Force loads profile on first call
OR
[string] "Steal" -- Steals the profile ignoring it's session lock
OR
[function] (place_id, game_job_id) --> [string] "Repeat", "Cancel", "ForceLoad" or "Steal"
place_id [number] or nil
game_job_id [string] or nil
-- not_released_handler [function] will be triggered in cases where the profile is not released by a session. This
-- function may yield for as long as desirable and must return one of three string values:
["Repeat"] - ProfileService will repeat the profile loading proccess and may trigger the release handler again
["Cancel"] - ProfileStore:LoadProfileAsync() will immediately return nil
["ForceLoad"] - ProfileService will repeat the profile loading call, but will return Profile object afterwards
and release the profile for another session that has loaded the profile
["Steal"] - The profile will usually be loaded immediately, ignoring an existing remote session lock and applying
a session lock for this session.
ProfileStore:GlobalUpdateProfileAsync(profile_key, update_handler) --> [GlobalUpdates] or nil
-- Returns GlobalUpdates object if update was successful, otherwise returns nil
profile_key [string] -- DataStore key
update_handler [function] (global_updates [GlobalUpdates])
ProfileStore:ViewProfileAsync(profile_key, version) --> [Profile] or nil
-- Reads profile without requesting a session lock; Data will not be saved and profile doesn't need to be released
profile_key [string] -- DataStore key
version nil or [string] -- DataStore key version
ProfileStore:ProfileVersionQuery(profile_key, sort_direction, min_date, max_date) --> [ProfileVersionQuery]
profile_key [string]
sort_direction nil or [Enum.SortDirection]
min_date nil or [DateTime]
max_date nil or [DateTime]
ProfileStore:WipeProfileAsync(profile_key) --> is_wipe_successful [bool]
-- Completely wipes out profile data from the DataStore / mock DataStore with no way to recover it.
* Parameter description for "ProfileStore:GlobalUpdateProfileAsync()":
profile_key [string] -- DataStore key
update_handler [function] (GlobalUpdates) -- This function gains access to GlobalUpdates object methods
(update_handler can't yield)
Methods [ProfileVersionQuery]:
ProfileVersionQuery:NextAsync() --> [Profile] or nil -- (Yields)
-- Returned profile has the same rules as profile returned by :ViewProfileAsync()
Members [Profile]:
Profile.Data [table] -- Writable table that gets saved automatically and once the profile is released
Profile.MetaData [table] (Read-only) -- Information about this profile
Profile.MetaData.ProfileCreateTime [number] (Read-only) -- os.time() timestamp of profile creation
Profile.MetaData.SessionLoadCount [number] (Read-only) -- Amount of times the profile was loaded
Profile.MetaData.ActiveSession [table] (Read-only) {place_id, game_job_id} / nil -- Set to a session link if a
game session is currently having this profile loaded; nil if released
Profile.MetaData.MetaTags [table] {["tag_name"] = tag_value, ...} -- Saved and auto-saved just like Profile.Data
Profile.MetaData.MetaTagsLatest [table] (Read-only) -- Latest version of MetaData.MetaTags that was definetly saved to DataStore
(You can use Profile.MetaData.MetaTagsLatest for product purchase save confirmation, but create a system to clear old tags after
they pile up)
Profile.MetaTagsUpdated [ScriptSignal] (meta_tags_latest) -- Fires after every auto-save, after
-- Profile.MetaData.MetaTagsLatest has been updated with the version that's guaranteed to be saved;
-- .MetaTagsUpdated will fire regardless of whether .MetaTagsLatest changed after update;
-- .MetaTagsUpdated may fire after the Profile is released - changes to Profile.Data are not saved
-- after release.
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]
Profile.KeyInfoUpdated [ScriptSignal] (key_info [DataStoreKeyInfo])
Profile.GlobalUpdates [GlobalUpdates]
Methods [Profile]:
-- SAFE METHODS - Will not error after profile expires:
Profile:IsActive() --> [bool] -- Returns true while the profile is active and can be written to
Profile:GetMetaTag(tag_name) --> value [any]
tag_name [string]
Profile:Reconcile() -- Fills in missing (nil) [string_key] = [value] pairs to the Profile.Data structure
Profile:ListenToRelease(listener) --> [ScriptConnection] (place_id / nil, game_job_id / nil)
-- WARNING: Profiles can be released externally if another session force-loads
-- this profile - use :ListenToRelease() to handle player leaving cleanup.
Profile:Release() -- Call after the session has finished working with this profile
e.g., after the player leaves (Profile object will become expired) (Does not yield)
Profile:ListenToHopReady(listener) --> [ScriptConnection] () -- Passed listener will be executed after the releasing UpdateAsync call finishes;
-- Wrap universe teleport requests with this method AFTER releasing the profile to improve session lock sharing between universe places;
-- :ListenToHopReady() will usually call the listener in around a second, but may occasionally take up to 7 seconds when a release happens
-- next to an auto-update in regular usage scenarios.
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:Identify() --> [string] -- Returns a string containing DataStore name, scope and key; Used for debug;
-- Example return: "[Store:"GameData";Scope:"Live";Key:"Player_2312310"]"
Profile:SetMetaTag(tag_name, value) -- Equivalent of Profile.MetaData.MetaTags[tag_name] = value
tag_name [string]
value [any]
Profile:Save() -- Call to quickly progress global update state or to speed up save validation processes (Does not yield)
-- VIEW-MODE ONLY:
Profile:ClearGlobalUpdates() -- Clears all global updates data from a profile payload
Profile:OverwriteAsync() -- (Yields) Saves the profile payload to the DataStore and removes the session lock
Methods [GlobalUpdates]:
-- ALWAYS PUBLIC:
GlobalUpdates:GetActiveUpdates() --> [table] {{update_id, update_data [table]}, ...}
GlobalUpdates:GetLockedUpdates() --> [table] {{update_id, update_data [table]}, ...}
-- ONLY WHEN FROM "Profile.GlobalUpdates":
GlobalUpdates:ListenToNewActiveUpdate(listener) --> [ScriptConnection] (update_id, update_data)
update_data [table]
GlobalUpdates:ListenToNewLockedUpdate(listener) --> [ScriptConnection] (update_id, update_data)
update_data [table]
GlobalUpdates:LockActiveUpdate(update_id) -- WARNING: will error after profile expires
GlobalUpdates:ClearLockedUpdate(update_id) -- WARNING: will error after profile expires
-- EXPOSED TO "update_handler" DURING ProfileStore:GlobalUpdateProfileAsync() CALL
GlobalUpdates:AddActiveUpdate(update_data)
update_data [table]
GlobalUpdates:ChangeActiveUpdate(update_id, update_data)
update_data [table]
GlobalUpdates:ClearActiveUpdate(update_id)
--]]
type Settings = {
AutoSaveProfiles: number,
RobloxWriteCooldown: number,
ForceLoadMaxSteps: number,
AssumeDeadSessionLock: number,
IssueCountForCriticalState: number,
IssueLast: number,
CriticalStateLast: number,
MetaTagsUpdatedValues: {
ProfileCreateTime: true,
SessionLoadCount: true,
ActiveSession: true,
ForceLoadSession: true,
LastUpdate: true,
},
}
export type PartialSettings = {
AutoSaveProfiles: number?,
RobloxWriteCooldown: number?,
ForceLoadMaxSteps: number?,
AssumeDeadSessionLock: number?,
IssueCountForCriticalState: number?,
IssueLast: number?,
CriticalStateLast: number?,
}
local Settings: Settings = {
AutoSaveProfiles = 30, -- Seconds (This value may vary - ProfileService will split the auto save load evenly in the given time)
RobloxWriteCooldown = 7, -- Seconds between successive DataStore calls for the same key
ForceLoadMaxSteps = 8, -- Steps taken before ForceLoad request steals the active session for a profile
AssumeDeadSessionLock = 30 * 60, -- (seconds) If a profile hasn't been updated for 30 minutes, assume the session lock is dead
-- As of writing, os.time() is not completely reliable, so we can only assume session locks are dead after a significant amount of time.
IssueCountForCriticalState = 5, -- Issues to collect to announce critical state
IssueLast = 120, -- Seconds
CriticalStateLast = 120, -- Seconds
MetaTagsUpdatedValues = { -- Technical stuff - do not alter
ProfileCreateTime = true,
SessionLoadCount = true,
ActiveSession = true,
ForceLoadSession = true,
LastUpdate = true,
},
}
--- {place_id, game_job_id}
export type ActiveSession = { number | string }
export type Listener = (place_id: number | nil, job_id: string | nil) -> any
type NotReleasedHandler =
"ForceLoad"
| "Steal"
| (placeId: number, jobId: string) -> "Repeat" | "Cancel" | "ForceLoad" | "Steal"
export type ProfileService = {
--- Set to false when the Roblox server is shutting down. ProfileStore methods should not be called after this
--- value is set to false.
ServiceLocked: boolean,
--- Analytics endpoint for DataStore error logging.
--- {error_message, profile_store_name, profile_key}.
IssueSignal: RBXScriptSignal<string, string, string>,
--- Analytics endpoint for cases when a DataStore key returns a value that has all or some of it's profile
--- components set to invalid data types. E.g., accidentally setting Profile.Data to a non table value.
--- {profile_store_name, profile_key}
CorruptionSignal: RBXScriptSignal<string, string>,
--- Analytics endpoint for cases when DataStore is throwing too many errors and it's most likely affecting your
--- game really really bad - this could be due to developer errors or due to Roblox server problems. Could be used
--- to alert players about data store outages.
--- {is_critical_state}
CriticalStateSignal: RBXScriptSignal<boolean>,
--- ProfileStore objects expose methods for loading / viewing profiles and sending global updates.
--- Equivalent of `:GetDataStore()` in Roblox `DataStoreService` API.
GetProfileStore: <Data, MetaTags, RobloxMetaData>(
storeIndex: string,
dataTemplate: Data
) -> ProfileStore<Data, MetaTags, RobloxMetaData>,
}
export type ProfileStore<Data, MetaTags, RobloxMetaData> = {
LoadProfileAsync: (
self: ProfileStore<Data, MetaTags, RobloxMetaData>,
profileKey: string,
notReleasedHandler: NotReleasedHandler | nil
) -> Profile<Data, MetaTags, RobloxMetaData> | nil,
GlobalUpdateProfileAsync: (
self: ProfileStore<Data, MetaTags, RobloxMetaData>,
profileKey: string,
updateHandler: (globalUpdates: GlobalUpdates) -> any
) -> GlobalUpdates | nil,
ViewProfileAsync: (
self: ProfileStore<Data, MetaTags, RobloxMetaData>,
profileKey: string,
version: string | nil
) -> Profile<Data, MetaTags, RobloxMetaData> | nil,
}
export type GlobalUpdates = {
-- TODO
}
export type Profile<Data, MetaTags, RobloxMetaData> = {
--- Non-strict reference - developer can set this value to a new table reference.
Data: Data,
--- Data about the profile itself.
MetaData: {
--- os.time() timestamp of profile creation.
ProfileCreationTime: number,
--- Amount of times the profile was loaded.
SessionLoadCount: number,
--- Set to a session link if a Roblox server is currently the owner of this profile; nil if released.
--- {place_id, game_job_id}
ActiveSession: ActiveSession | nil,
--- Saved and auto-saved just like `Profile.Data`.
MetaTags: MetaTags,
--- The most recent version of MetaData.MetaTags which has been saved to the DataStore during the last auto-save
--- or `Profile:Save()` call.
MetaTagsLatest: MetaTags,
},
--- This signal fires after every auto-save, after `Profile.MetaData.MetaTagsLatest` has been updated with the
--- version that's guaranteed to be saved. `MetaTagsUpdated` will fire regardless of whether MetaTagsLatest changed
--- after update.
MetaTagsUpdated: RBXScriptSignal<MetaTags>,
--- Non-strict reference - developer can set this value to a new table reference.
RobloxMetaData: RobloxMetaData,
--- User ids associated with this profile. Entries must be added with `Profile:AddUserId()` and removed with
--- `Profile:RemoveUserId()`.
UserIds: { number },
--- The `DataStoreKeyInfo` instance related to this profile.
KeyInfo: DataStoreKeyInfo,
--- A signal that gets triggered every time `Profile.KeyInfo` is updated with a new `DataStoreKeyInfo` instance
--- reference after every auto-save or profile release.
KeyInfoUpdated: RBXScriptSignal<DataStoreKeyInfo>,
--- This is the GlobalUpdates object tied to this specific Profile. It exposes GlobalUpdates methods for update
--- processing.
GlobalUpdates: GlobalUpdates,
--- Returns true while the profile is session-locked and saving of changes to Profile.Data is guaranteed.
IsActive: (self: Profile<Data, MetaTags, RobloxMetaData>) -> boolean,
--- Equivalent of `Profile.MetaData.MetaTags[tag_name]`. See `Profile:SetMetaTag()` for more info.
--- TODO: Properly type this with Luau.
GetMetaTag: (self: Profile<Data, MetaTags, RobloxMetaData>, tagName: string) -> any,
--- Fills in missing variables inside `Profile.Data` from `profile_template` table that was provided when calling
--- `ProfileService.GetProfileStore()`.
Reconcile: (self: Profile<Data, MetaTags, RobloxMetaData>) -> nil,
--- Listener functions subscribed to `Profile:ListenToRelease()` will be called when the profile is released
--- remotely or locally.
ListenToRelease: (self: Profile<Data, MetaTags, RobloxMetaData>, listener: Listener) -> RBXScriptConnection,
--- Removes the session lock for this profile for this Roblox server. Call this method after you're done working
--- with the Profile object. Profile data will be immediately saved for the last time.
Release: (self: Profile<Data, MetaTags, RobloxMetaData>) -> nil,
ListenToHopReady: (self: Profile<Data, MetaTags, RobloxMetaData>, listener: () -> any) -> RBXScriptConnection,
AddUserId: (self: Profile<Data, MetaTags, RobloxMetaData>, userId: number) -> nil,
RemoveUserId: (self: Profile<Data, MetaTags, RobloxMetaData>, userId: number) -> nil,
--- Returns a string containing DataStore name, scope and key; Used for debugging.
Identify: (self: Profile<Data, MetaTags, RobloxMetaData>) -> string,
--- Call `Profile:Save()` to quickly progress GlobalUpdates state or to speed up the propagation of
--- `Profile.MetaData.MetaTags` changes to `Profile.MetaData.MetaTagsLatest`.
Save: (self: Profile<Data, MetaTags, RobloxMetaData>) -> nil,
}
local Madwork -- Standalone Madwork reference for portable version of ProfileService
do
local MadworkScriptSignal = {}
local FreeRunnerThread = nil
local function AcquireRunnerThreadAndCallEventHandler(fn, ...)
local acquired_runner_thread = FreeRunnerThread
FreeRunnerThread = nil
fn(...)
FreeRunnerThread = acquired_runner_thread
end
local function RunEventHandlerInFreeThread(...)
AcquireRunnerThreadAndCallEventHandler(...)
while true do
AcquireRunnerThreadAndCallEventHandler(coroutine.yield())
end
end
-- ScriptConnection object:
local ScriptConnection = {
--[[
_listener = listener,
_script_signal = script_signal,
_disconnect_listener = disconnect_listener,
_disconnect_param = disconnect_param,
_next = next_script_connection,
_is_connected = is_connected,
--]]
}
ScriptConnection.__index = ScriptConnection
function ScriptConnection:Disconnect()
if self._is_connected == false then
return
end
self._is_connected = false
self._script_signal._listener_count -= 1
if self._script_signal._head == self then
self._script_signal._head = self._next
else
local prev = self._script_signal._head
while prev ~= nil and prev._next ~= self do
prev = prev._next
end
if prev ~= nil then
prev._next = self._next
end
end
if self._disconnect_listener ~= nil then
if not FreeRunnerThread then
FreeRunnerThread = coroutine.create(RunEventHandlerInFreeThread)
end
task.spawn(FreeRunnerThread, self._disconnect_listener, self._disconnect_param)
self._disconnect_listener = nil
end
end
-- ScriptSignal object:
local ScriptSignal = {
--[[
_head = nil,
_listener_count = 0,
--]]
}
ScriptSignal.__index = ScriptSignal
function ScriptSignal:Connect(listener, disconnect_listener, disconnect_param) --> [ScriptConnection]
local script_connection = {
_listener = listener,
_script_signal = self,
_disconnect_listener = disconnect_listener,
_disconnect_param = disconnect_param,
_next = self._head,
_is_connected = true,
}
setmetatable(script_connection, ScriptConnection)
self._head = script_connection
self._listener_count += 1
return script_connection
end
function ScriptSignal:GetListenerCount() --> [number]
return self._listener_count
end
function ScriptSignal: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 ScriptSignal:FireUntil(continue_callback, ...)
local item = self._head
while item ~= nil do
if item._is_connected == true then
item._listener(...)
if continue_callback() ~= true then
return
end
end
item = item._next
end
end
function MadworkScriptSignal.NewScriptSignal() --> [ScriptSignal]
return {
_head = nil,
_listener_count = 0,
Connect = ScriptSignal.Connect,
GetListenerCount = ScriptSignal.GetListenerCount,
Fire = ScriptSignal.Fire,
FireUntil = ScriptSignal.FireUntil,
}
end
-- Madwork framework namespace:
Madwork = {
NewScriptSignal = MadworkScriptSignal.NewScriptSignal,
ConnectToOnClose = function(task, run_in_studio_mode)
if game:GetService("RunService"):IsStudio() == false or run_in_studio_mode == true then
game:BindToClose(task)
end
end,
}
end
----- Service Table -----
local ProfileService = {
ServiceLocked = false, -- Set to true once the server is shutting down
IssueSignal = Madwork.NewScriptSignal(), -- (error_message, profile_store_name, profile_key) -- Fired when a DataStore API call throws an error
CorruptionSignal = Madwork.NewScriptSignal(), -- (profile_store_name, profile_key) -- Fired when DataStore key returns a value that has
-- all or some of it's profile components set to invalid data types. E.g., accidentally setting Profile.Data to a noon table value
CriticalState = false, -- Set to true while DataStore service is throwing too many errors
CriticalStateSignal = Madwork.NewScriptSignal(), -- (is_critical_state) -- Fired when CriticalState is set to true
-- (You may alert players with this, or set up analytics)
ServiceIssueCount = 0,
_active_profile_stores = {}, -- {profile_store, ...}
_auto_save_list = {}, -- {profile, ...} -- loaded profile table which will be circularly auto-saved
_issue_queue = {}, -- [table] {issue_time, ...}
_critical_state_start = 0, -- [number] 0 = no critical state / os.clock() = critical state start
-- Debug:
_mock_data_store = {},
_user_mock_data_store = {},
_use_mock_data_store = false,
}
--[[
Saved profile structure:
DataStoreProfile = {
Data = {},
MetaData = {
ProfileCreateTime = 0,
SessionLoadCount = 0,
ActiveSession = {place_id, game_job_id} / nil,
ForceLoadSession = {place_id, game_job_id} / nil,
MetaTags = {},
LastUpdate = 0, -- os.time()
},
RobloxMetaData = {},
UserIds = {},
GlobalUpdates = {
update_index,
{
{update_id, version_id, update_locked, update_data},
...
}
},
}
OR
DataStoreProfile = {
GlobalUpdates = {
update_index,
{
{update_id, version_id, update_locked, update_data},
...
}
},
}
--]]
----- Private Variables -----
local ActiveProfileStores = ProfileService._active_profile_stores
local AutoSaveList = ProfileService._auto_save_list
local IssueQueue = ProfileService._issue_queue
local DataStoreService = game:GetService("DataStoreService")
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 IsLiveCheckActive = false
local UseMockDataStore = false
local MockDataStore = ProfileService._mock_data_store -- Mock data store used when API access is disabled
local UserMockDataStore = ProfileService._user_mock_data_store -- Separate mock data store accessed via ProfileStore.Mock
local UseMockTag = {}
local CustomWriteQueue = {
--[[
[store] = {
[key] = {
LastWrite = os.clock(),
Queue = {callback, ...},
CleanupJob = nil,
},
...
},
...
--]]
}
----- Utils -----
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
----- Private functions -----
local function IdentifyProfile(store_name, store_scope, key)
return string.format(
'[Store:"%s";%sKey:"%s"]',
store_name,
store_scope ~= nil and string.format('Scope:"%s";', store_scope) or "",
key
)
end
local function CustomWriteQueueCleanup(store, key)
if CustomWriteQueue[store] ~= nil then
CustomWriteQueue[store][key] = nil
if next(CustomWriteQueue[store]) == nil then
CustomWriteQueue[store] = nil
end
end
end
local function CustomWriteQueueMarkForCleanup(store, key)
if CustomWriteQueue[store] ~= nil then
if CustomWriteQueue[store][key] ~= nil then
local queue_data = CustomWriteQueue[store][key]
local queue = queue_data.Queue
if queue_data.CleanupJob == nil then
queue_data.CleanupJob = RunService.Heartbeat:Connect(function()
if os.clock() - queue_data.LastWrite > Settings.RobloxWriteCooldown and #queue == 0 then
queue_data.CleanupJob:Disconnect()
CustomWriteQueueCleanup(store, key)
end
end)
end
elseif next(CustomWriteQueue[store]) == nil then
CustomWriteQueue[store] = nil
end
end
end
local function CustomWriteQueueAsync(callback, store, key) --> ... -- Passed return from callback
if CustomWriteQueue[store] == nil then
CustomWriteQueue[store] = {}
end
if CustomWriteQueue[store][key] == nil then
CustomWriteQueue[store][key] = { LastWrite = 0, Queue = {}, CleanupJob = nil }
end
local queue_data = CustomWriteQueue[store][key]
local queue = queue_data.Queue
-- Cleanup job:
if queue_data.CleanupJob ~= nil then
queue_data.CleanupJob:Disconnect()
queue_data.CleanupJob = nil
end
-- Queue logic:
if os.clock() - queue_data.LastWrite > Settings.RobloxWriteCooldown and #queue == 0 then
queue_data.LastWrite = os.clock()
return callback()
else
table.insert(queue, callback)
while true do
if os.clock() - queue_data.LastWrite > Settings.RobloxWriteCooldown and queue[1] == callback then
table.remove(queue, 1)
queue_data.LastWrite = os.clock()
return callback()
end
task.wait()
end
end
end
local function IsCustomWriteQueueEmptyFor(store, key) --> is_empty [bool]
local lookup = CustomWriteQueue[store]
if lookup ~= nil then
lookup = lookup[key]
return lookup == nil or #lookup.Queue == 0
end
return true
end
local function WaitForLiveAccessCheck() -- This function was created to prevent the ProfileService module yielding execution when required
while IsLiveCheckActive == true do
task.wait()
end
end
local function WaitForPendingProfileStore(profile_store)
while profile_store._is_pending == true do
task.wait()
end
end
local function RegisterIssue(error_message, store_name, store_scope, profile_key) -- Called when a DataStore API call errors
warn(
"[ProfileService]: DataStore API error "
.. IdentifyProfile(store_name, store_scope, profile_key)
.. ' - "'
.. tostring(error_message)
.. '"'
)
table.insert(IssueQueue, os.clock()) -- Adding issue time to queue
ProfileService.IssueSignal:Fire(tostring(error_message), store_name, profile_key)
end
local function RegisterCorruption(store_name, store_scope, profile_key) -- Called when a corrupted profile is loaded
warn("[ProfileService]: Resolved profile corruption " .. IdentifyProfile(store_name, store_scope, profile_key))
ProfileService.CorruptionSignal: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 = 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 IsThisSession(session_tag)
return session_tag[1] == PlaceId and session_tag[2] == JobId
end
--[[
update_settings = {
ExistingProfileHandle = function(latest_data),
MissingProfileHandle = function(latest_data),
EditProfile = function(lastest_data),
}
--]]
local function StandardProfileUpdateAsyncDataStore(
profile_store,
profile_key,
update_settings,
is_user_mock,
is_get_call,
version
) --> loaded_data, key_info
local loaded_data, key_info
local success, error_message = pcall(function()
local transform_function = function(latest_data)
local missing_profile = false
local data_corrupted = false
local global_updates_data = { 0, {} }
if latest_data == nil then
missing_profile = true
elseif type(latest_data) ~= "table" then
missing_profile = true
data_corrupted = true
end
if type(latest_data) == "table" then
-- Case #1: Profile was loaded
if
type(latest_data.Data) == "table"
and type(latest_data.MetaData) == "table"
and type(latest_data.GlobalUpdates) == "table"
then
latest_data.WasCorrupted = false -- Must be set to false if set previously
global_updates_data = latest_data.GlobalUpdates
if update_settings.ExistingProfileHandle ~= nil then
update_settings.ExistingProfileHandle(latest_data)
end
-- Case #2: Profile was not loaded but GlobalUpdate data exists
elseif
latest_data.Data == nil
and latest_data.MetaData == nil
and type(latest_data.GlobalUpdates) == "table"
then
latest_data.WasCorrupted = false -- Must be set to false if set previously
global_updates_data = latest_data.GlobalUpdates or global_updates_data
missing_profile = true
else
missing_profile = true
data_corrupted = true
end
end
-- Case #3: 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_data,
}
if update_settings.MissingProfileHandle ~= nil then
update_settings.MissingProfileHandle(latest_data)
end
end
-- Editing profile:
if update_settings.EditProfile ~= nil then
update_settings.EditProfile(latest_data)
end
-- Data corruption handling (Silently override with empty profile) (Also run Case #1)
if data_corrupted == true then
latest_data.WasCorrupted = 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(
UserMockDataStore,
profile_store._profile_store_lookup,
profile_key,
transform_function,
is_get_call
)
task.wait() -- Simulate API call yield
elseif UseMockDataStore == true then -- Used when API access is disabled
loaded_data, key_info = MockUpdateAsync(
MockDataStore,
profile_store._profile_store_lookup,
profile_key,
transform_function,
is_get_call
)
task.wait() -- Simulate API call yield
else
loaded_data, key_info = CustomWriteQueueAsync(
function() -- Callback
if is_get_call == true then
local get_data, get_key_info
if version ~= nil then
local success, error_message = pcall(function()
get_data, get_key_info = profile_store._global_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("[ProfileService]: Passed version argument is not valid; Traceback:\n" .. debug.traceback())
end
else
get_data, get_key_info = profile_store._global_data_store:GetAsync(profile_key)
end
get_data = transform_function(get_data)
return get_data, get_key_info
else
return profile_store._global_data_store:UpdateAsync(profile_key, transform_function)
end
end,
profile_store._profile_store_lookup, -- Store
profile_key -- Key
)
end
end)
if success == true and type(loaded_data) == "table" then
-- Corruption handling:
if loaded_data.WasCorrupted == true and is_get_call ~= true then
RegisterCorruption(profile_store._profile_store_name, profile_store._profile_store_scope, profile_key)
end
-- Return loaded_data:
return loaded_data, key_info