-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathOrbit-activity.rbxmx
More file actions
3890 lines (3188 loc) · 107 KB
/
Copy pathOrbit-activity.rbxmx
File metadata and controls
3890 lines (3188 loc) · 107 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="RBX136FA6CC08AA4438A6013208DCCB74BB">
<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 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 = false, -- Track private servers?
studioEnabled = false, -- Track Studio sessions?
-- Feature flags
bansEnabled = false, -- Let Orbit handle bans?
rankChecking = false, -- Only track members of the group?
groupId = 0, -- Group ID for rank checks
minTrackedRank = 0, -- Minimum rank to be tracked (fetched from Orbit on launch)
-- 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
-- Chat capture
maxStoredChatLines = 200,
maxChatCharsPerLine = 512,
}
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 chatLogTable = {}
local rankTable = {}
local afkTable = {}
local sessionActive = {}
local lastActivityTime: { [number]: number } = {}
local afkStartTime: { [number]: number } = {}
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
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 isAFK(Player: Player): boolean
return table.find(afkTable, Player) ~= nil
end
local function setAFK(Player: Player, state: boolean)
local idx = table.find(afkTable, Player)
if state and not idx then
table.insert(afkTable, Player)
afkStartTime[Player.UserId] = os.clock()
elseif not state and idx then
table.remove(afkTable, idx)
afkStartTime[Player.UserId] = nil
end
end
local function bumpActivity(Player: Player)
lastActivityTime[Player.UserId] = os.clock()
setAFK(Player, false)
end
local function appendChatLine(userId: number, raw: unknown)
local log_t = chatLogTable[userId]
if not log_t 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(log_t, text)
local cap = Configuration.maxStoredChatLines
while cap > 0 and #log_t > cap do
table.remove(log_t, 1)
end
end
local function collectSessionEndRow(Player: Player): { [string]: unknown }
local afkTimer = Player:FindFirstChild("Orbit AFK Timer")
local log_t = chatLogTable[Player.UserId] or {}
local row: { [string]: unknown } = {
userid = Player.UserId,
username = Player.Name,
placeid = game.GameId,
idleTime = afkTimer and afkTimer.Value or 0,
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 ok, rank = pcall(Player.GetRankInGroupAsync, Player, Configuration.groupId)
return ok and rank or 0
end
local function isUserTracked(Player: Player): boolean
if not Configuration.rankChecking then return true end
local entry = rankTable[Player.UserId]
if not entry then return false end
return entry.Rank >= Configuration.minTrackedRank
end
local function httpGet(endpoint: string): (boolean, unknown?)
local ok, result = pcall(HttpService.RequestAsync, HttpService, {
Url = Configuration.url .. endpoint,
Method = "GET",
Headers = { ["authorization"] = Configuration.auth },
})
if not ok then return false, nil end
local decoded = safeDecode(result.Body)
return decoded ~= nil, decoded
end
local function httpPost(endpoint: string, body: unknown): boolean
local encoded = safeEncode(body)
if not encoded then
log("ERROR", "Failed to encode body for " .. endpoint)
return false
end
local request = HttpQueue.HttpRequest.new(Configuration.url .. endpoint, "POST", encoded, nil,
{
["Content-Type"] = "application/json",
["authorization"] = Configuration.auth,
}
)
request:Send()
return true
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)
if sessionActive[Player.UserId] 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.")
sessionActive[Player.UserId] = true
return
end
local success = httpPost("/api/activity/session?type=create", {
userid = Player.UserId,
username = Player.Name,
placeid = game.GameId,
})
if success then
sessionActive[Player.UserId] = true
log("INFO", "Session created for " .. Player.Name)
else
log("ERROR", "Failed to create session for " .. Player.Name)
end
end
local function EndSession(Player: Player, reason: string?)
if not sessionActive[Player.UserId] 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
sessionActive[Player.UserId] = 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 userId = Player.UserId
if not lastActivityTime[userId] then
lastActivityTime[userId] = os.clock()
end
local connections: { RBXScriptConnection } = {}
local function onActivity(speed: number)
if speed > 0 then
bumpActivity(Player)
else
local snapshot = os.clock()
lastActivityTime[userId] = snapshot
FastWait(60 * Configuration.minutesTillAFK)
if isPlayerOnline(Player) and lastActivityTime[userId] == 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: boolean)
if not isIdle then
bumpActivity(Player)
else
local lastActive = lastActivityTime[Player.UserId]
local idleSeconds = lastActive and (os.clock() - lastActive) or math.huge
local threshold = 60 * Configuration.minutesTillAFK -- now matches MovementDetection's threshold
if idleSeconds >= threshold then
setAFK(Player, true)
end
end
end
TovyEvent.OnServerEvent:Connect(InputChange)
local function InitiatePlayer(Player: Player)
local rank = fetchRank(Player)
rankTable[Player.UserId] = { Rank = rank }
chatLogTable[Player.UserId] = {}
lastActivityTime[Player.UserId] = os.clock()
if not isUserTracked(Player) then
log("INFO", Player.Name .. " is not at a tracked rank — skipping session.")
return
end
local afkTimer = Instance.new("NumberValue")
afkTimer.Name = "Orbit AFK Timer"
afkTimer.Parent = Player
local clientClone = TovyClient:Clone()
clientClone.Parent = Player:WaitForChild("PlayerGui")
CreateSession(Player)
MovementDetection(Player)
end
local function CleanupPlayer(Player: Player, reason: string?)
EndSession(Player, reason)
setAFK(Player, false)
rankTable[Player.UserId] = nil
chatLogTable[Player.UserId] = nil
sessionActive[Player.UserId] = nil
lastActivityTime[Player.UserId] = nil
afkStartTime[Player.UserId] = nil
end
Players.PlayerAdded:Connect(function(Player)
InitiatePlayer(Player)
Player.CharacterAdded:Connect(function()
lastActivityTime[Player.UserId] = os.clock()
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
if isUserTracked(Player) and (sessionActive[Player.UserId] 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, response = pcall(HttpService.RequestAsync, HttpService, {
Url = Configuration.url .. "/api/activity/bulk-end",
Method = "POST",
Headers = {
["Content-Type"] = "application/json",
["authorization"] = Configuration.auth,
},
Body = encoded,
})
if ok then
log("INFO", string.format("Shutdown: bulk-ended %d session(s).", #sessions))
else
log("ERROR", "Shutdown: bulk-end request failed — " .. tostring(response))
end
end
else
log("INFO", "Shutdown: no active sessions to end.")
end
task.wait(5)
end)
task.spawn(function()
while true do
task.wait(Configuration.heartbeatInterval)
for idx, Player in ipairs(afkTable) do
local online = isPlayerOnline(Player)
if online then
local afkTimer = Player:FindFirstChild("Orbit AFK Timer")
local start = afkStartTime[Player.UserId]
if afkTimer and start then
afkTimer.Value = math.floor((os.clock() - start) / 60)
end
else
log("WARN", "AFK table contained offline player — removing ghost entry.")
table.remove(afkTable, idx)
afkStartTime[Player.UserId] = nil
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 = {}
for _, p in ipairs(onlinePlayers) do
onlineSet[p.UserId] = true
end
for userId, active in pairs(sessionActive) do
if active 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 = #(chatLogTable[userId] or {}),
endReason = "ghost_cleanup",
}
if chatLogTable[userId] and #chatLogTable[userId] > 0 then
ghostRow.chatBodies = chatLogTable[userId]
end
httpPost("/api/activity/session?type=end", ghostRow)
sessionActive[userId] = false
chatLogTable[userId] = nil
rankTable[userId] = nil
lastActivityTime[userId] = nil
afkStartTime[userId] = nil
end
end
for _, Player in ipairs(onlinePlayers) do
if not isUserTracked(Player) then continue end
local hasSession = sessionActive[Player.UserId]
if not hasSession then
local remoteActive = checkRemoteSessionActive(Player)
if remoteActive then
log("WARN", Player.Name .. " has remote session but no local cache — syncing.")
sessionActive[Player.UserId] = true
else
log("WARN", Player.Name .. " has no active session — recreating.")
chatLogTable[Player.UserId] = chatLogTable[Player.UserId] or {}
local afkTimer = Player:FindFirstChild("Orbit AFK Timer")
if afkTimer then afkTimer.Value = 0 end
CreateSession(Player)
end
end
end
if Configuration.rankChecking then
for _, Player in ipairs(onlinePlayers) do
local oldRank = rankTable[Player.UserId] and rankTable[Player.UserId].Rank or 0
local newRank = fetchRank(Player)
rankTable[Player.UserId] = { Rank = newRank }
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.")
chatLogTable[Player.UserId] = {}
lastActivityTime[Player.UserId] = os.clock()
local afkTimer = Instance.new("NumberValue")
afkTimer.Name = "Orbit AFK Timer"
afkTimer.Parent = Player
CreateSession(Player)
end
end
end
end
for idx = #afkTable, 1, -1 do
local Player = afkTable[idx]
if not isPlayerOnline(Player) then
log("WARN", "Scan: purging offline player from AFK table: " .. tostring(Player))
table.remove(afkTable, idx)
afkStartTime[Player.UserId] = nil
end
end
for userId in pairs(chatLogTable) do
if not onlineSet[userId] then
log("WARN", string.format(
"Orphan chat log found for offline userId %d — purging.", userId
))
chatLogTable[userId] = nil
end
end
end
end)
for _, Player in ipairs(Players:GetPlayers()) do
task.spawn(InitiatePlayer, Player)
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>
<BinaryString name="Tags"></BinaryString>
</Properties>
<Item class="Folder" referent="RBX693341DE809A4CD49D9F5CB3B3393E79">
<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>
<BinaryString name="Tags"></BinaryString>
</Properties>
<Item class="ModuleScript" referent="RBX07FA90DC23FB4320BAA3E8AE3B2FB71E">
<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>
<BinaryString name="Tags"></BinaryString>
</Properties>
<Item class="ModuleScript" referent="RBX420582FA45444CE5B7E8BF3848CEC181">
<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>
<BinaryString name="Tags"></BinaryString>
</Properties>
</Item>
<Item class="ModuleScript" referent="RBXE605E8EF534F4B1196851113F9AA2A8F">
<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
resolve(node)
end):catch(function(err)
-- Did we exceed the HttpService limits?
if err:match("Number of requests exceeded limit") then
stall(httpStall)
sendNode(node) -- try again!
else
coroutine.resume(node.Data.Callback, err)
end
resolve(node)
end)
end)
end
local function doQueue(queue)
while queue.First do
while interrupted or availableWorkers == 0 do
coroutine.yield()
end
if restart then
break
end
local node = queue.First
availableWorkers = availableWorkers - 1
sendNode(node):andThen(resolveNode)
queue.First = node.Next
if not queue.First then
queue.Last = nil
end
end
end
while true do
restart = false
doQueue(prioritaryQueue)
doQueue(regularQueue)
if not restart then
coroutine.yield()
end
end
end)
local httpQueue = {}
--[[**
Pushes a request to the queue to be sent whenever possible.
@param [t:HttpRequest] request The request to be sent.
@param [t:HttpRequestPriority] priority The priority of the request in relation to other requests in the same queue.
@returns [t:Promise<HttpResponse>] A promise to a HttpResponse that is resolved when it is available.
**--]]
function httpQueue:Push(request, priority)
pushCheck(request, priority)
local requestBody = {Request = request}
local promise = Promise.async(function(resolve, reject)
requestBody.Callback = coroutine.running()
local response = coroutine.yield()
if guards.isHttpResponse(response) then
resolve(response)
else
reject(response)
end
end)
if not priority or priority == Priority.Normal then
datautil.addNodeToLast(datautil.newLLNode(requestBody), regularQueue)
elseif priority == Priority.Prioritary then
datautil.addNodeToLast(datautil.newLLNode(requestBody), prioritaryQueue)
elseif priority == Priority.First then
datautil.addNodeToFirst(datautil.newLLNode(requestBody), prioritaryQueue)
end
queueSize = queueSize + 1
coroutine.resume(queueExecutor)
return promise
end
--[[**
Pushes a request to the queue to be sent whenever possible.
@param [t:HttpRequest] request The request to be sent.
@param [t:HttpRequestPriority] priority The priority of the request in relation to other requests in the same queue.
@returns [t:HttpResponse] The server's response to the request.
**--]]
function httpQueue:AwaitPush(request, priority)
local resolved, response = self:Push(request, priority):await()
return resolved and response or newHttpResponse(false, response)
end
--[[**
@returns [t:number] The number of unsent requests in the queue.
**--]]
function httpQueue:QueueSize()
return queueSize
end
return setmetatable(httpQueue, {
__metatable = "HttpQueue",
__index = function(_, index)
error("Attempt to index non-existant value HttpQueue." .. tostring(index))
end
})
end
return setmetatable(HttpQueue, {
__metatable = "HttpQueue",
__index = function(_, index)
error("Attempt to index non-existant value HttpQueue." .. tostring(index))
end
})
]]></ProtectedString>
<string name="ScriptGuid">{9C00AA1B-2A14-48E5-998E-9BE6EC807541}</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>
<BinaryString name="Tags"></BinaryString>
</Properties>
</Item>
<Item class="ModuleScript" referent="RBXE4B37F048F3A4B308624637FF63546BE">
<Properties>
<Content name="LinkedSource"><null></null></Content>
<ProtectedString name="Source"><![CDATA[--[[
File: http-queue/HttpRequest.lua
Description: Wrapper for an HttpService request
SPDX-License-Identifier: MIT
]]
local deps = require(script.Parent.DependencyLoader)
local newHttpResponse = require(script.Parent.HttpResponse)
local HttpService, Promise, t = deps.HttpService, deps.Promise, deps.t
local HttpRequest = {}
local requestCheck = t.strict(
t.tuple(t.string, t.string, t.optional(t.string),
t.optional(t.map(t.string, t.union(t.string, t.number, t.boolean))),
t.optional(t.map(t.string, t.string))
)
)
--[[**
Creates an HttpRequest.
@param [t:String] Url The url endpoint the request is being sent to.
@param [t:String] Method A string containing the method/verb being used in the request.
@param [t:String|nil] Body The body of the request. Only applicable if you're going to send data (POST, PUT, etc.)
@param [t:Dictionary<string,string|bool|number>|nil] Query Url query options (which are then appended to the url)
@param [t:Dictionary<string,string>|nil] Headers Additional headers to be included in the request
**--]]
function HttpRequest.new(Url, Method, Body, Query, Headers)
requestCheck(Url, Method, Body, Query, Headers)
-- Now we can assume type-safety!
local endpoint = Url
local url = Url:split("://")
if url[1] == Url then
error("\"" .. Url .. "\" doesn't look like a valid Url!")
end
-- Never hurts to check for this and correct
-- https://example.org?query1=a is invalid
-- https://example.org/?query1=a is not!
-- We also need to check if there's already a path in the URL
-- e.g https://example.com/file is different from https://example.com/file/
if not url[2]:find("/") then
endpoint = endpoint .. "/"
end
if t.table(Query) then
local queryString = "?"
for i, v in pairs (Query) do
queryString = queryString .. HttpService:UrlEncode(i) .. "=" .. HttpService:UrlEncode(tostring(v)) .. "&"
end
endpoint = endpoint .. queryString:sub(1, -2)
end
local httpRequest = {}
httpRequest.Url = endpoint
--[[**
Sends the request to the specified Url.
@returns [t:HttpResponse] The server's response to the request.
**--]]
function httpRequest:AwaitSend()
-- Placeholder
local success, result = pcall(function()
return HttpService:RequestAsync({
Url = endpoint,
Method = Method,
Headers = Headers,
Body = if (Method == "GET" or Method == "HEAD") then nil else Body
})
end)
return newHttpResponse(success, result)
end
--[[**
Sends the request to the specified Url.
@returns [t:Promise<HttpResponse>] A promise to a HttpResponse that is resolved when it is available.
**--]]
function httpRequest:Send()
return Promise.async(function(resolve, reject)
local response = self:AwaitSend()
if response.ConnectionSuccessful then
resolve(response)
else
reject(response.StatusMessage)
end
end)
end
return setmetatable(httpRequest, {
__metatable = "HttpRequest",
__index = function(_, index)
error("Attempt to index non-existant value HttpRequest." .. tostring(index))
end
})
end
return setmetatable(HttpRequest, {
__metatable = "HttpRequest",
__index = function(_, index)
error("Attempt to index non-existant value HttpRequest." .. tostring(index))
end
})
]]></ProtectedString>
<string name="ScriptGuid">{FB8696F6-C420-4A0B-A3F1-67434876F8E3}</string>
<BinaryString name="AttributesSerialize"></BinaryString>
<SecurityCapabilities name="Capabilities">0</SecurityCapabilities>
<bool name="DefinesCapabilities">false</bool>
<string name="Name">HttpRequest</string>
<int64 name="SourceAssetId">-1</int64>
<BinaryString name="Tags"></BinaryString>
</Properties>
</Item>
<Item class="ModuleScript" referent="RBXF423B4D74F8B485A924F53194D118783">
<Properties>
<Content name="LinkedSource"><null></null></Content>
<ProtectedString name="Source"><![CDATA[--[[
File: http-queue/HttpRequestPriority.lua