forked from PlanetaryOrbit/orbit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOrbit-activity.rbxmx
More file actions
4150 lines (3407 loc) · 115 KB
/
Copy pathOrbit-activity.rbxmx
File metadata and controls
4150 lines (3407 loc) · 115 KB
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
<roblox xmlns:xmime="http://www.w3.org/2005/05/xmlmime" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.roblox.com/roblox.xsd" version="4">
<Meta name="ExplicitAutoJoints">true</Meta>
<External>null</External>
<External>nil</External>
<Item class="Script" referent="RBX97E7E2AD80E04B9E8A93A147C4CA28E2">
<Properties>
<ProtectedString name="Source"><![CDATA[-- Orbit Activity Tracker
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local DataStoreService = game:GetService("DataStoreService")
local HttpService = game:GetService("HttpService")
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local GroupService = game:GetService("GroupService")
local HttpQueue = require(script.Components.HttpQueue)
local FastWait = require(script.Components.FastWait)
local TovyFolder = Instance.new("Folder", ReplicatedStorage)
TovyFolder.Name = "Orbit Assets"
local TovyEvent = Instance.new("RemoteEvent", TovyFolder)
TovyEvent.Name = "Activity"
local TovyClient = script:WaitForChild("Components"):WaitForChild("OrbitClient")
TovyClient.Event.Value = TovyEvent
local Configuration = {
-- !! Do not touch !!
url = "<url>",
auth = "<apikey>",
privateEnabled = <privateenabled>, -- Track private servers?
studioEnabled = <studioenabled>, -- Track Studio sessions?
-- Feature flags
bansEnabled = false, -- Let Orbit handle bans?
rankChecking = true, -- Only track members of the group?
groupId = <groupid>, -- Group ID for rank checks
minTrackedRank = <mintrackedrank>, -- Minimum rank to be tracked (overridable via remote config)
-- Timing
cooldownPeriod = 30, -- Seconds between HTTP retries
minutesTillAFK = 2, -- Idle minutes before AFK flag
scanInterval = 300, -- Seconds between full player scans (5 min)
heartbeatInterval = 60, -- Seconds between lightweight heartbeats
rankRefreshInterval = 600, -- Seconds between per-player rank re-checks (throttles GroupService)
serverHeartbeatEvery = 120, -- Seconds between backend "server alive" pings
remoteEventCooldown = 3, -- Min seconds between accepted client Activity events per player
-- Chat capture
maxStoredChatLines = 200,
maxChatCharsPerLine = 512,
-- Reliability
deadLetterStoreName = "OrbitFailedRequests",
deadLetterFlushEvery = 60, -- Seconds between dead-letter retry sweeps
deadLetterMaxAttempts = 10, -- Give up (but keep for manual review) after this many failed retries
}
if not Configuration.studioEnabled and RunService:IsStudio() then
return warn("Orbit: Tracking disabled in Studio. (studioEnabled = false)")
end
if not Configuration.privateEnabled then
if game.PrivateServerId ~= "" and game.PrivateServerOwnerId ~= 0 then
return warn("Orbit: Tracking disabled in private servers. (privateEnabled = false)")
end
end
warn("Orbit: Module loaded — activity tracking active.")
local function log(level: string, msg: string)
local prefix = string.format("[Orbit][%s] %s", level, msg)
if level == "WARN" or level == "ERROR" then
warn(prefix)
else
print(prefix)
end
end
local function safeEncode(data: unknown): string?
local ok, result = pcall(HttpService.JSONEncode, HttpService, data)
return ok and result or nil
end
local function safeDecode(raw: string): unknown?
local ok, result = pcall(HttpService.JSONDecode, HttpService, raw)
return ok and result or nil
end
type PlayerState = {
rank: number,
chatLog: { string },
sessionActive: boolean,
lastActivity: number,
afkStart: number?,
isAFK: boolean,
afkTimerInstance: NumberValue?,
pendingAFKCheck: boolean,
lastRankCheck: number,
lastRemoteEventAccepted: number,
}
local PlayerData: { [number]: PlayerState } = {}
local function getState(Player: Player): PlayerState?
return PlayerData[Player.UserId]
end
local function isPlayerOnline(Player: Player): boolean
return Players:GetPlayerByUserId(Player.UserId) ~= nil
end
local function stripChat(text: string): string
return (text:gsub("^%s+", ""):gsub("%s+$", ""))
end
local function setAFK(Player: Player, state: boolean)
local st = getState(Player)
if not st then return end
if state and not st.isAFK then
st.isAFK = true
st.afkStart = os.clock()
elseif not state and st.isAFK then
st.isAFK = false
st.afkStart = nil
if st.afkTimerInstance then
st.afkTimerInstance.Value = 0
end
end
end
local function bumpActivity(Player: Player)
local st = getState(Player)
if not st then return end
st.lastActivity = os.clock()
setAFK(Player, false)
end
local function appendChatLine(userId: number, raw: unknown)
local st = PlayerData[userId]
if not st then return end
local text = type(raw) == "string" and raw or ""
text = stripChat(text)
if text == "" then return end
local maxChars = Configuration.maxChatCharsPerLine
if maxChars > 0 and #text > maxChars then
text = text:sub(1, maxChars)
end
table.insert(st.chatLog, text)
local cap = Configuration.maxStoredChatLines
while cap > 0 and #st.chatLog > cap do
table.remove(st.chatLog, 1)
end
end
local function collectSessionEndRow(Player: Player): { [string]: unknown }
local st = getState(Player)
local log_t = st and st.chatLog or {}
local idleMinutes = st and st.afkTimerInstance and st.afkTimerInstance.Value or 0
local row: { [string]: unknown } = {
userid = Player.UserId,
username = Player.Name,
placeid = game.GameId,
idleTime = idleMinutes,
messages = #log_t,
}
if #log_t > 0 then
row.chatBodies = log_t
end
return row
end
local function fetchRank(Player: Player): number
if not Configuration.rankChecking then return math.huge end
local success, rankInfo = pcall(function()
return GroupService:GetRolesInGroupAsync(Player.UserId, Configuration.groupId)
end)
if not success then return math.huge end
if not rankInfo.IsMember then return math.huge end
return rankInfo.Roles[1] and rankInfo.Roles[1].Rank or 0
end
local function isUserTracked(Player: Player): boolean
if not Configuration.rankChecking then return true end
local st = getState(Player)
if not st then return false end
return st.rank >= Configuration.minTrackedRank
end
local DeadLetterStore = DataStoreService:GetDataStore(Configuration.deadLetterStoreName)
local deadLetterCounter = 0
local function deadLetterKey(): string
deadLetterCounter += 1
return string.format("%d-%d-%d", game.JobId and #game.JobId or 0, os.time(), deadLetterCounter)
end
local function enqueueDeadLetter(endpoint: string, body: unknown)
local key = deadLetterKey()
local ok, err = pcall(function()
DeadLetterStore:SetAsync(key, {
endpoint = endpoint,
body = body,
attempts = 0,
queuedAt = os.time(),
})
end)
if ok then
log("WARN", "Queued failed request to dead-letter store: " .. endpoint)
else
log("ERROR", "Failed to enqueue dead-letter entry (" .. endpoint .. "): " .. tostring(err))
end
end
local function rawPost(endpoint: string, encodedBody: string): (boolean, unknown?)
local ok, result = pcall(HttpService.RequestAsync, HttpService, {
Url = Configuration.url .. endpoint,
Method = "POST",
Headers = {
["Content-Type"] = "application/json",
["authorization"] = Configuration.auth,
},
Body = encodedBody,
})
if not ok or not result.Success then return false, nil end
return true, safeDecode(result.Body)
end
local function httpGet(endpoint: string, maxAttempts: number?): (boolean, unknown?)
maxAttempts = maxAttempts or 2
for attempt = 1, maxAttempts do
local ok, result = pcall(HttpService.RequestAsync, HttpService, {
Url = Configuration.url .. endpoint,
Method = "GET",
Headers = { ["authorization"] = Configuration.auth },
})
if ok and result.Success then
local decoded = safeDecode(result.Body)
if decoded ~= nil then
return true, decoded
end
end
if attempt < maxAttempts then
task.wait(1)
end
end
return false, nil
end
local function httpPost(endpoint: string, body: unknown, allowDeadLetter: boolean?): boolean
local encoded = safeEncode(body)
if not encoded then
log("ERROR", "Failed to encode body for " .. endpoint)
return false
end
local ok = rawPost(endpoint, encoded)
if ok then
return true
end
local queuedOk = pcall(function()
HttpQueue.HttpRequest.new(Configuration.url .. endpoint, "POST", encoded, nil, {
["Content-Type"] = "application/json",
["authorization"] = Configuration.auth,
}):Send()
end)
if not queuedOk and allowDeadLetter ~= false then
enqueueDeadLetter(endpoint, body)
end
return queuedOk
end
local function handlePossibleBan(Player: Player, response: unknown)
if not Configuration.bansEnabled then return end
if type(response) ~= "table" then return end
if response.banned then
local reason = type(response.reason) == "string" and response.reason or "Banned"
log("WARN", string.format("%s is banned via Orbit (%s) — kicking.", Player.Name, reason))
Player:Kick("You have been banned: " .. reason)
end
end
local function checkRemoteSessionActive(Player: Player): boolean
local ok, response = httpGet("/api/activity/session?id=" .. Player.UserId)
if ok and type(response) == "table" and response.success then
return true
end
return false
end
local function CreateSession(Player: Player)
local st = getState(Player)
if not st then return end
if st.sessionActive then
log("INFO", "Session already cached as active for " .. Player.Name .. ", skipping.")
return
end
if checkRemoteSessionActive(Player) then
log("WARN", "Remote session already exists for " .. Player.Name .. ", syncing local cache.")
st.sessionActive = true
return
end
local encoded = safeEncode({
userid = Player.UserId,
username = Player.Name,
placeid = game.GameId,
})
local ok, response = false, nil
if encoded then
ok, response = rawPost("/api/activity/session?type=create", encoded)
end
if ok then
st.sessionActive = true
log("INFO", "Session created for " .. Player.Name)
handlePossibleBan(Player, response)
else
local fallbackOk = httpPost("/api/activity/session?type=create", {
userid = Player.UserId,
username = Player.Name,
placeid = game.GameId,
})
if fallbackOk then
st.sessionActive = true
log("INFO", "Session created for " .. Player.Name .. " (via retry path)")
else
log("ERROR", "Failed to create session for " .. Player.Name)
end
end
end
local function BulkCreateSessions(playersList: { Player })
if #playersList == 0 then return end
local rows = {}
for _, Player in ipairs(playersList) do
table.insert(rows, {
userid = Player.UserId,
username = Player.Name,
placeid = game.GameId,
})
end
local encoded = safeEncode({ sessions = rows })
local bulkSucceeded: { [number]: boolean } = {}
if encoded then
local ok, response = rawPost("/api/activity/bulk-start", encoded)
if ok and type(response) == "table" and type(response.started) == "table" then
for _, userId in ipairs(response.started) do
bulkSucceeded[userId] = true
end
log("INFO", string.format("Bulk-started %d/%d session(s).", #response.started, #playersList))
end
end
for _, Player in ipairs(playersList) do
local st = getState(Player)
if st then
if bulkSucceeded[Player.UserId] then
st.sessionActive = true
else
CreateSession(Player)
end
end
end
end
local function EndSession(Player: Player, reason: string?)
local st = getState(Player)
if not st then return end
if not st.sessionActive then
if not checkRemoteSessionActive(Player) then
log("INFO", "No session to end for " .. Player.Name)
return
end
end
local row = collectSessionEndRow(Player)
row.endReason = reason or "natural"
local success = httpPost("/api/activity/session?type=end", row)
if success then
st.sessionActive = false
log("INFO", string.format("Session ended for %s (reason: %s)", Player.Name, row.endReason))
else
log("ERROR", "Failed to end session for " .. Player.Name)
end
end
local function MovementDetection(Player: Player)
local Character = Player.Character or Player.CharacterAdded:Wait()
local Humanoid = Character:WaitForChild("Humanoid")
local st = getState(Player)
if not st then return end
if not st.lastActivity then
st.lastActivity = os.clock()
end
local connections: { RBXScriptConnection } = {}
local function onActivity(speed: number)
if speed > 0 then
bumpActivity(Player)
return
end
local myState = getState(Player)
if not myState or myState.pendingAFKCheck then
return
end
local snapshot = os.clock()
myState.lastActivity = snapshot
myState.pendingAFKCheck = true
task.spawn(function()
FastWait(60 * Configuration.minutesTillAFK)
local currentState = getState(Player)
if currentState then
currentState.pendingAFKCheck = false
end
if isPlayerOnline(Player) and currentState and currentState.lastActivity == snapshot then
setAFK(Player, true)
log("INFO", Player.Name .. " marked AFK (no movement for "
.. Configuration.minutesTillAFK .. " min).")
end
end)
end
table.insert(connections, Humanoid.Running:Connect(onActivity))
table.insert(connections, Humanoid.Swimming:Connect(onActivity))
table.insert(connections, Humanoid.Climbing:Connect(onActivity))
table.insert(connections, Humanoid.Jumping:Connect(function(isJumping)
if isJumping then
bumpActivity(Player)
end
end))
local charRemovedConn
charRemovedConn = Character.AncestryChanged:Connect(function()
if not Character:IsDescendantOf(game) then
for _, c in ipairs(connections) do
c:Disconnect()
end
charRemovedConn:Disconnect()
end
end)
end
local function InputChange(Player: Player, isIdle: unknown)
if typeof(isIdle) ~= "boolean" then
log("WARN", "Rejected malformed Activity event from " .. Player.Name)
return
end
local st = getState(Player)
if not st then return end
local now = os.clock()
if now - (st.lastRemoteEventAccepted or 0) < Configuration.remoteEventCooldown then
return
end
st.lastRemoteEventAccepted = now
if not isIdle then
bumpActivity(Player)
else
local idleSeconds = st.lastActivity and (now - st.lastActivity) or math.huge
local threshold = 60 * Configuration.minutesTillAFK -- matches MovementDetection's threshold
if idleSeconds >= threshold then
setAFK(Player, true)
end
end
end
TovyEvent.OnServerEvent:Connect(InputChange)
local function InitiatePlayer(Player: Player): boolean
local rank = fetchRank(Player)
PlayerData[Player.UserId] = {
rank = rank,
chatLog = {},
sessionActive = false,
lastActivity = os.clock(),
afkStart = nil,
isAFK = false,
afkTimerInstance = nil,
pendingAFKCheck = false,
lastRankCheck = os.clock(),
lastRemoteEventAccepted = 0,
}
if not isUserTracked(Player) then
log("INFO", Player.Name .. " is not at a tracked rank — skipping session.")
return false
end
local afkTimer = Instance.new("NumberValue")
afkTimer.Name = "Orbit AFK Timer"
afkTimer.Parent = Player
PlayerData[Player.UserId].afkTimerInstance = afkTimer
local clientClone = TovyClient:Clone()
clientClone.Parent = Player:WaitForChild("PlayerGui")
task.spawn(MovementDetection, Player)
return true
end
local function CleanupPlayer(Player: Player, reason: string?)
EndSession(Player, reason)
PlayerData[Player.UserId] = nil
end
Players.PlayerAdded:Connect(function(Player)
local tracked = InitiatePlayer(Player)
if tracked then
CreateSession(Player)
end
Player.CharacterAdded:Connect(function()
local st = getState(Player)
if st then
st.lastActivity = os.clock()
end
MovementDetection(Player)
end)
Player.Chatted:Connect(function(Message)
if isUserTracked(Player) then
appendChatLine(Player.UserId, Message)
bumpActivity(Player)
end
end)
end)
Players.PlayerRemoving:Connect(function(Player)
CleanupPlayer(Player, "player_left")
end)
game:BindToClose(function()
local sessions = {}
for _, Player in ipairs(Players:GetPlayers()) do
local st = getState(Player)
if st and isUserTracked(Player) and (st.sessionActive or checkRemoteSessionActive(Player)) then
local row = collectSessionEndRow(Player)
row.endReason = "server_shutdown"
table.insert(sessions, row)
end
end
if #sessions > 0 then
local encoded = safeEncode({ sessions = sessions })
if encoded then
local ok = rawPost("/api/activity/bulk-end", encoded)
if ok then
log("INFO", string.format("Shutdown: bulk-ended %d session(s).", #sessions))
else
log("ERROR", "Shutdown: bulk-end request failed — queueing for dead-letter retry.")
enqueueDeadLetter("/api/activity/bulk-end", { sessions = sessions })
end
end
else
log("INFO", "Shutdown: no active sessions to end.")
end
task.wait(5)
end)
local function fetchRemoteConfig()
local ok, response = httpGet(`/api/activity/config?id={Configuration.groupId}`)
if not ok or type(response.data) ~= "table" then
log("WARN", "Could not fetch remote config — using local defaults.")
return
end
local overridable = {"minTrackedRank", "privateEnabled", "studioEnabled"}
local changed = {}
for _, key in ipairs(overridable) do
if response[key] ~= nil and response[key] ~= Configuration[key] then
Configuration[key] = response[key]
table.insert(changed, key)
end
end
if #changed > 0 then
log("INFO", "Applied remote config overrides: " .. table.concat(changed, ", "))
end
end
task.spawn(function()
while true do
task.wait(Configuration.heartbeatInterval)
for userId, st in pairs(PlayerData) do
if st.isAFK and st.afkStart and st.afkTimerInstance then
local Player = Players:GetPlayerByUserId(userId)
if Player and isPlayerOnline(Player) then
st.afkTimerInstance.Value = math.floor((os.clock() - st.afkStart) / 60)
end
end
end
end
end)
task.spawn(function()
while true do
task.wait(Configuration.deadLetterFlushEvery)
local ok, keysPage = pcall(function()
return DeadLetterStore:ListKeysAsync()
end)
if not ok then continue end
local currentPage = keysPage:GetCurrentPage()
for _, keyInfo in ipairs(currentPage) do
local key = keyInfo.KeyName
local getOk, entry = pcall(function()
local value = DeadLetterStore:GetAsync(key)
return value
end)
if getOk and type(entry) == "table" then
local encoded = safeEncode(entry.body)
if encoded then
local postOk = rawPost(entry.endpoint, encoded)
if postOk then
pcall(function() DeadLetterStore:RemoveAsync(key) end)
log("INFO", "Dead-letter retry succeeded for " .. entry.endpoint)
else
entry.attempts = (entry.attempts or 0) + 1
if entry.attempts >= Configuration.deadLetterMaxAttempts then
log("ERROR", string.format(
"Dead-letter entry %s exceeded max attempts (%d) — leaving in store for manual review.",
key, entry.attempts))
else
pcall(function() DeadLetterStore:SetAsync(key, entry) end)
end
end
end
end
end
end
end)
task.spawn(function()
while true do
task.wait(Configuration.scanInterval)
log("INFO", "Running full player scan...")
local onlinePlayers = Players:GetPlayers()
local onlineSet: { [number]: boolean } = {}
for _, p in ipairs(onlinePlayers) do
onlineSet[p.UserId] = true
end
for userId, st in pairs(PlayerData) do
if st.sessionActive and not onlineSet[userId] then
log("WARN", string.format(
"Ghost session detected for userId %d — ending immediately.", userId))
local ghostRow = {
userid = userId,
idleTime = 0,
messages = #st.chatLog,
endReason = "ghost_cleanup",
}
if #st.chatLog > 0 then
ghostRow.chatBodies = st.chatLog
end
httpPost("/api/activity/session?type=end", ghostRow)
PlayerData[userId] = nil
end
end
for _, Player in ipairs(onlinePlayers) do
if isUserTracked(Player) then
local st = getState(Player)
if st and not st.sessionActive then
local remoteActive = checkRemoteSessionActive(Player)
if remoteActive then
log("WARN", Player.Name .. " has remote session but no local cache — syncing.")
st.sessionActive = true
else
log("WARN", Player.Name .. " has no active session — recreating.")
if st.afkTimerInstance then st.afkTimerInstance.Value = 0 end
CreateSession(Player)
end
end
end
end
if Configuration.rankChecking then
for i, Player in ipairs(onlinePlayers) do
local st = getState(Player)
if st then
local dueForRecheck = (os.clock() - (st.lastRankCheck or 0)) >= Configuration.rankRefreshInterval
if dueForRecheck then
if i > 1 then task.wait(0.25) end
local oldRank = st.rank
local newRank = fetchRank(Player)
st.rank = newRank
st.lastRankCheck = os.clock()
if newRank ~= oldRank then
log("INFO", string.format("%s rank changed: %d → %d", Player.Name, oldRank, newRank))
if oldRank >= Configuration.minTrackedRank
and newRank < Configuration.minTrackedRank then
log("WARN", Player.Name .. " fell below min rank, ending session.")
EndSession(Player, "rank_below_minimum")
elseif oldRank < Configuration.minTrackedRank
and newRank >= Configuration.minTrackedRank then
log("INFO", Player.Name .. " now meets min rank, starting session.")
st.chatLog = {}
st.lastActivity = os.clock()
if not st.afkTimerInstance then
local afkTimer = Instance.new("NumberValue")
afkTimer.Name = "Orbit AFK Timer"
afkTimer.Parent = Player
st.afkTimerInstance = afkTimer
end
CreateSession(Player)
end
end
end
end
end
end
for userId, st in pairs(PlayerData) do
if st.isAFK and not onlineSet[userId] then
st.isAFK = false
st.afkStart = nil
end
end
end
end)
fetchRemoteConfig()
do
local startupPlayers = Players:GetPlayers()
local trackedForBulkStart = {}
for _, Player in ipairs(startupPlayers) do
local tracked = InitiatePlayer(Player)
if tracked then
table.insert(trackedForBulkStart, Player)
end
end
BulkCreateSessions(trackedForBulkStart)
end]]></ProtectedString>
<bool name="Disabled">false</bool>
<Content name="LinkedSource"><null></null></Content>
<token name="RunContext">0</token>
<string name="ScriptGuid">{81740BB3-280D-4363-BA2A-0CE80C16A785}</string>
<BinaryString name="AttributesSerialize"></BinaryString>
<SecurityCapabilities name="Capabilities">0</SecurityCapabilities>
<bool name="DefinesCapabilities">false</bool>
<string name="Name">OrbitActivity</string>
<int64 name="SourceAssetId">-1</int64>
<SharedString name="Tags">yuZpQdnvvUBOTYh1jqZ2cA==</SharedString>
</Properties>
<Item class="Folder" referent="RBX03E86216049E4E9189C6FE50204AFC10">
<Properties>
<BinaryString name="AttributesSerialize"></BinaryString>
<SecurityCapabilities name="Capabilities">0</SecurityCapabilities>
<bool name="DefinesCapabilities">false</bool>
<string name="Name">Components</string>
<int64 name="SourceAssetId">-1</int64>
<SharedString name="Tags">yuZpQdnvvUBOTYh1jqZ2cA==</SharedString>
</Properties>
<Item class="ModuleScript" referent="RBX5E7D8CB756C1427096B95E0140358B8A">
<Properties>
<Content name="LinkedSource"><null></null></Content>
<ProtectedString name="Source"><![CDATA[--[[
File: http-queue/init.lua
Description: Front-end for the http-queue library
SPDX-License-Identifier: MIT
]]
local exports = {
HttpRequestPriority = require(script.HttpRequestPriority),
HttpRequest = require(script.HttpRequest),
HttpQueue = require(script.HttpQueue)
}
for name, guard in pairs(require(script.TypeGuards)) do
exports[name] = guard
end
return exports
]]></ProtectedString>
<string name="ScriptGuid">{FE2A771C-DD2C-45EB-B0B2-BA2830DA58B6}</string>
<BinaryString name="AttributesSerialize"></BinaryString>
<SecurityCapabilities name="Capabilities">0</SecurityCapabilities>
<bool name="DefinesCapabilities">false</bool>
<string name="Name">HttpQueue</string>
<int64 name="SourceAssetId">-1</int64>
<SharedString name="Tags">yuZpQdnvvUBOTYh1jqZ2cA==</SharedString>
</Properties>
<Item class="ModuleScript" referent="RBX75F29D21BFBF4FB3BDF42B2133BFFCF2">
<Properties>
<Content name="LinkedSource"><null></null></Content>
<ProtectedString name="Source"><![CDATA[--[[
File: http-queue/DataUtils.lua
Description: Data structures and basic synchronization utilities
SPDX-License-Identifier: MIT
]]
local dataUtils = {}
-- Small linked list implementation
function dataUtils.newLLNode(item)
return {Data = item, Prev = nil, Next = nil}
end
function dataUtils.addNodeToFirst(node, root)
if not root.First then
root.First = node
root.Last = node
else
root.First.Prev = node
node.Next = root.First
node.Prev = nil
root.First = node
end
end
function dataUtils.addNodeToLast(node, root)
if not root.Last then
root.First = node
root.Last = node
else
root.Last.Next = node
node.Prev = root.Last
node.Next = nil
root.Last = node
end
end
return dataUtils
]]></ProtectedString>
<string name="ScriptGuid">{023794A1-6658-4BCB-92A9-5B9086A5DD23}</string>
<BinaryString name="AttributesSerialize"></BinaryString>
<SecurityCapabilities name="Capabilities">0</SecurityCapabilities>
<bool name="DefinesCapabilities">false</bool>
<string name="Name">DataUtils</string>
<int64 name="SourceAssetId">-1</int64>
<SharedString name="Tags">yuZpQdnvvUBOTYh1jqZ2cA==</SharedString>
</Properties>
</Item>
<Item class="ModuleScript" referent="RBX04FB9AC7D33842D4B89616FD10E0066B">
<Properties>
<Content name="LinkedSource"><null></null></Content>
<ProtectedString name="Source"><![CDATA[--[[
File: http-queue/HttpQueue.lua
Description: Creates a self-regulating queue for rate-limited services
SPDX-License-Identifier: MIT
]]
local Priority = require(script.Parent.HttpRequestPriority)
local newHttpResponse = require(script.Parent.HttpResponse)
local datautil = require(script.Parent.DataUtils)
local guards = require(script.Parent.TypeGuards)
local deps = require(script.Parent.DependencyLoader)
local Promise, t = deps.Promise, deps.t
local HttpQueue = {}
local validInt = t.intersection(t.integer, t.numberPositive)
local newHttpQueueCheck = t.strict(t.strictInterface({
retryAfter = t.union(
t.strictInterface({
header = t.string
}),
t.strictInterface({
cooldown = validInt
}),
t.strictInterface({
callback = t.callback
})
),
maxSimultaneousSendOperations = t.optional(validInt)
}))
local pushCheck = t.strict(t.tuple(guards.isHttpRequest, t.optional(guards.isHttpRequestPriority)))
--[[**
Creates an HttpQueue. It is a self-regulating queue for REST APIs that impose rate limits. When you push a request to the queue,
the queue will send the ones added first to the remote server (unless you specify a priority). The queue automatically handles
the rate limits in order to, as humanly as possible, respect the service's rate limits and Terms of Service.
A queue is NOT A SILVER BULLET NEITHER A GUARANTEE of not spamming invalid requests, though. Depending on your game's
playerbase/number of servers compared to the rate limit of the services, it might not scale well.
@param options The options for the queue.
@param [t:string|nil] options.retryAfter.header If the reqeuest is rate limited, look for this header to determine how long to wait (in seconds). If defined, don't provide options.retryAfter.cooldown
@param [t:number|nil] options.retryAfter.cooldown Define a cooldown period directly. If defined, do not define options.retryAfter.header
@param [t:number(HttpResponse)|nil] options.retryAfter.callback Pass a function that takes a rate-limited response and returns the cooldown period (in seconds). If defined, do not define options.retryAfter.header
@param [t:number|nil] options.maxSimultaneousSendOperations How many requests should be sent at the same time (maximum). Defaults to 10.
**--]]
function HttpQueue.new(options)
newHttpQueueCheck(options)
local prioritaryQueue = {}
local regularQueue = {}
local queueSize = 0
local queueExecutor = coroutine.create(function()
local interrupted = false
local restart = false
local main = coroutine.running()
local availableWorkers = options.maxSimultaneousSendOperations or 10
local cooldown
if options.retryAfter.header then
local header = options.retryAfter.header
cooldown = function(response)
wait(response.Headers[header])
end
elseif options.retryAfter.cooldown then
local cooldownPeriod = options.retryAfter.cooldown
cooldown = function()
wait(cooldownPeriod)
end
else
local callback = options.retryAfter.callback
cooldown = function(response)
wait(callback(response))
end
end
local function resolveNode(node)
-- Resolve the request
if node.Next then
node.Next.Prev = nil
end
node.Next = nil
-- Release resources
queueSize = queueSize - 1
availableWorkers = availableWorkers + 1
if coroutine.status(main) == "suspended" then
coroutine.resume(main)
end
end
local function httpStall()
-- HttpService stalled (number of requests exceeded)
wait(30)
end
local function stall(stallMethod, response)
interrupted = true
restart = true
stallMethod(response)
interrupted = false
end
local function sendNode(node)
return Promise.async(function(resolve)
node.Data.Request:Send():andThen(function(response)
if response.StatusCode == 429 then
stall(cooldown, response)
sendNode(node) -- try again!
else
coroutine.resume(node.Data.Callback, response)
end