-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRollbar.lua
509 lines (422 loc) · 13.1 KB
/
Rollbar.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
--!strict
--[[
TITLE: ROLLBAR ERROR HANDLING SERVICE MANAGER
DESC: Manages communication between game place and Rollbar web api, allows for easy configuration and
customisation of error logging such as automated output logging for both client and server and
manual logging functions for both client and server.
AUTHOR: RoyallyFlushed
CREATION DATE: 02/27/2022
MODIFIED DATE: 03/09/2022
--]]
--[[SERVICES]]--
local ReplicatedStorage = game.ReplicatedStorage
local HttpService = game:GetService("HttpService")
local LogService = game:GetService("LogService")
local RunService = game:GetService("RunService")
type Array<T> = { [number]: T }
type Dictionary = { [string]: any }
type Enumeration = { [string]: number }
type schema = {
DEBUG_MODE : boolean,
IgnoreStudio : boolean,
ManualMode : boolean,
IgnoreDuplicates : boolean,
GeneraliseClientErrors : boolean,
_initialised : boolean,
DefaultEnvironment : string,
Connection : RemoteEvent,
NextCallMetadata : boolean | Dictionary,
DefaultMetadata : Dictionary,
Auth : Dictionary,
ConnectionRequest : Enumeration,
Level : Enumeration,
RollbarLevel : Array<string>,
Total : Enumeration,
Logs : Array<string>,
Url : string,
SendEvent: (
manualCall : boolean,
level : number,
message : string
) -> ()?,
Configure: (
schema,
metadata : Dictionary
) -> ()?,
GetLogTotal: ((
schema,
level : number
) -> (number?))?,
LogCritical: (
schema,
message : string
) -> ()?,
LogError: (
schema,
message : string
) -> ()?,
LogWarning: (
schema,
message : string
) -> ()?,
LogInfo: (
schema,
message : string
) -> ()?,
LogDebug: (
schema,
message : string
) -> ()?,
init: () -> ()?,
_funcCount : number
}
local module: schema = {
--[[SETTINGS]]--
IgnoreStudio = false,
ManualMode = false,
IgnoreDuplicates = false,
GeneraliseClientErrors = false,
NextCallMetadata = false,
_initialised = false,
Connection = ReplicatedStorage.SendRollbarEvent,
DEBUG_MODE = true,
DefaultEnvironment = tostring(game.PlaceId),
DefaultMetadata = {
["build"] = game.PlaceVersion,
["server-id"] = game.JobId
},
Auth = {
ServerToken = "dfcg345sf234gghdf44222ss",
ClientToken = "dfg843vvxc4434sq934fgjdd"
},
--[[INTERNAL PROPERTIES]]--
ConnectionRequest = {
SETMETADATA = 0,
LOGEVENT = 1,
LOGTOTAL = 2
},
Level = {
DEBUG = 0,
INFO = 1,
WARNING = 2,
ERROR = 3,
CRITICAL = 4
},
RollbarLevel = {
"debug",
"info",
"warning",
"error",
"critical"
},
Total = {
DEBUG = 0,
INFO = 0,
WARNING = 0,
ERROR = 0,
CRITICAL = 0
},
Url = "https://api.rollbar.com/api/1/item/",
Logs = {},
SendEvent = nil,
GetLogTotal = nil,
Configure = nil,
LogCritical = nil,
LogError = nil,
LogWarning = nil,
LogInfo = nil,
LogDebug = nil,
init = nil,
_funcCount = 9
}
-- Initialise module with functions
assert(module._funcCount == 9, "Exhaustive handling of module functions in initialisation stage, initialise any module functions that need to be accessed")
module.SendEvent = _SendEvent
module.GetLogTotal = _GetLogTotal
module.Configure = _Configure
module.LogCritical = _LogCritical
module.LogError = _LogError
module.LogWarning = _LogWarning
module.LogInfo = _LogInfo
module.LogDebug = _LogDebug
module.init = _init
-- Soft assertion function to warn instead of error
local function softAssert(cond: boolean, msg: string?): ()
if not cond then
warn(msg or "Assertion failed!")
end
end
-- Function to find values in tables
local function find(t: any, q: any): any?
for k,v in next, t do
if v == q then
return k
end
end
return nil
end
-- Wrapper function to retry requests
local function try(maxTries: number, func: ()->(boolean, any)): (boolean, any)
local attempts: number = 0
local success: boolean, result: any
repeat
success, result = pcall(func)
attempts += 1
until success or attempts >= maxTries
return success, result
end
-- Handles the actual http request
local function sendRequest(timestamp: number, messageType: string, environment: string, metadata: Dictionary, message: string): ()
-- Send request to rollbar
if module.DEBUG_MODE then
print("SENDING ROLLBAR EVENT!")
return
end
local success, result = try(3, function()
return game:service'HttpService':RequestAsync({
Url = module.Url,
Method = "POST",
Headers = {
['Content-Type'] = "application/json",
['X-Rollbar-Access-Token'] = module.Auth.ServerToken
},
Body = game:service'HttpService':JSONEncode({
['data'] = {
['environment'] = environment,
['body'] = {
['telemetry'] = {
{
['level'] = messageType,
['type'] = "error",
['source'] = "server",
['timestamp_ms'] = timestamp * 1000,
['body'] = {
['subtype'] = "xhr",
['message'] = message,
}
}
},
['message'] = {
['body'] = message
}
},
['level'] = messageType,
['timestamp'] = timestamp,
['Custom'] = metadata
}
})
})
end)
-- Handle success pcall request (no network failure)
if success then
local response = result
-- Handle failure of Rollbar request (Rollbar API failure)
if not response.Success then
warn(("$ Rollbar request contained %d errors!\n-->Response: %s\n-->Status Code: %d"):format(
response.Body.err,
response.Body.message,
response.StatusCode
))
end
else
warn(("$ Network error occured when trying to send request to Rollbar\n %s"):format(result))
end
end
-- Handle logic for sending events to Rollbar
function _SendEvent(manualCall: boolean, level: number, message: string): ()
-- If IgnoreStudio flag is set, drop request entirely
if RunService:IsStudio() and module.IgnoreStudio then
warn("$ Rollbar is disabled in Studio! Request dropped!")
return
end
-- Stringify message argument and define variables
message = tostring(message)
local metadata: Dictionary = module.DefaultMetadata
local environment: string = module.DefaultEnvironment
-- Check for manual metadata and apply
if manualCall and module.NextCallMetadata then
-- Check to see if manual metadata has an Environment datum, if so, separate from metadata
local nextCallMetadata: Dictionary = module.NextCallMetadata :: Dictionary
if nextCallMetadata.Environment then
environment = nextCallMetadata.Environment
metadata = {}
-- Reset the metadata table to remove the Environment datum
for i,v in next, module.NextCallMetadata :: Dictionary do
if i ~= "Environment" then
metadata[i] = v
end
end
else
-- No Environment datum so just set the metadata
metadata = module.NextCallMetadata :: {}
end
end
-- Check for duplicate error
if module.IgnoreDuplicates and table.find(module.Logs, message :: string) then
return
end
-- Check to see if should generalise client errors
if module.GeneraliseClientErrors then
message = (string.gsub(message :: string, "Players.%w+.", "Players.<PLAYER>."))
end
-- Add to log cache
table.insert(module.Logs, message :: string)
-- Increment log type counter
module.Total[find(module.Level, level) :: string] += 1
-- Send request
sendRequest(
os.time(),
module.RollbarLevel[level],
environment,
metadata,
message :: string
)
-- Reset nextCallMetadata for subsequent calls
module.NextCallMetadata = false
end
-- Handles log service event fires and sends server log
local function clientLogServiceHandler(message: string, messageType: number): ()
module.Connection:FireServer(module.ConnectionRequest.LOGEVENT, {
message = message,
messageType = messageType,
manualCall = false
})
end
-- Handles log service event fires on the server side
local function serverLogServiceHandler(message: string, messageType: number): ()
assert(module.SendEvent ~= nil, "This could be a bug with function assigning")
module.SendEvent(false, messageType, message)
end
-- Handles all server responses over connection on client
local function connectionClientHandler(level: number, total: number): ()
if RunService:IsClient() then
if level and total then
module.Total[find(module.Level, level) :: string] = total
end
end
end
-- Handles all client requests over connection on server
local function connectionServerHandler(player: Player, requestType: number, data: Dictionary): ()
assert(requestType ~= nil, "$ requestType is required!")
assert(data ~= nil, "$ data is required!")
assert(data ~= {}, "$ data must contain data!")
if requestType == module.ConnectionRequest.SETMETADATA and data.metadata then
module.NextCallMetadata = data.metadata
elseif requestType == module.ConnectionRequest.LOGEVENT and data.message and data.messageType and data.manualCall then
assert(module.SendEvent ~= nil, "This could be a bug with function assigning")
module.SendEvent(data.manualCall, data.messageType, data.message :: string)
elseif requestType == module.ConnectionRequest.LOGTOTAL and data.level then
module.Connection:FireClient(player, data.level, module.Total[find(module.Level, data.level) :: string])
end
end
-- Sends Client current total for log level
function _GetLogTotal(self: schema, level: number): number?
assert(module.Total[find(module.Level, level) :: string], "$ level must be a listed level!")
if RunService:IsClient() then
module.Connection:FireServer(module.ConnectionRequest.LOGTOTAL, {level = level})
return nil
else
return module.Total[find(module.Level, level) :: string]
end
end
-- Configure the log metadata for the next manual log call
function _Configure(self: schema, metadata: {}): ()
assert(metadata ~= nil, "$ metadata is required!")
assert(metadata ~= {}, "$ metadata must contain data!")
-- If client, then ask server to set
if RunService:IsClient() then
module.Connection:FireServer(module.ConnectionRequest.SETMETADATA, {metadata = metadata})
else
module.NextCallMetadata = metadata
end
end
-- Manually send a critical log to Rollbar
function _LogCritical(self: schema, message: string): ()
-- If client, then ask server to set
if RunService:IsClient() then
module.Connection:FireServer(module.ConnectionRequest.LOGEVENT, {
message = message,
messageType = module.Level.CRITICAL
})
else
assert(module.SendEvent ~= nil, "This could be a bug with function assigning")
module.SendEvent(true, module.Level.CRITICAL, message)
end
end
-- Manually send an error log to Rollbar
function _LogError(self: schema, message: string): ()
-- If client, then ask server to set
if RunService:IsClient() then
module.Connection:FireServer(module.ConnectionRequest.LOGEVENT, {
message = message,
messageType = module.Level.ERROR
})
else
assert(module.SendEvent ~= nil, "This could be a bug with function assigning")
module.SendEvent(true, module.Level.ERROR, message)
end
end
-- Manually send a warning log to Rollbar
function _LogWarning(self: schema, message: string): ()
-- If client, then ask server to set
if RunService:IsClient() then
module.Connection:FireServer(module.ConnectionRequest.LOGEVENT, {
message = message,
messageType = module.Level.WARNING
})
else
assert(module.SendEvent ~= nil, "This could be a bug with function assigning")
module.SendEvent(true, module.Level.WARNING, message)
end
end
-- Manually send an info log to Rollbar
function _LogInfo(self: schema, message: string): ()
-- If client, then ask server to set
if RunService:IsClient() then
module.Connection:FireServer(module.ConnectionRequest.LOGEVENT, {
message = message,
messageType = module.Level.INFO
})
else
assert(module.SendEvent ~= nil, "This could be a bug with function assigning")
module.SendEvent(true, module.Level.INFO, message)
end
end
-- Manually send a debug log to Rollbar
function _LogDebug(self: schema, message: string): ()
-- If client, then ask server to set
if RunService:IsClient() then
module.Connection:FireServer(module.ConnectionRequest.LOGEVENT, {
message = message,
messageType = module.Level.DEBUG
})
else
assert(module.SendEvent ~= nil, "This could be a bug with function assigning")
module.SendEvent(true, module.Level.DEBUG, message)
end
end
-- Initiation for client and server
function _init(): ()
softAssert(not module._initialised, "$ Rollbar has already been initialised in this environment!")
-- Initiate logging services for output on client and server
if RunService:IsStudio() and module.IgnoreStudio then
warn("$ Rollbar is disabled in Studio!")
elseif RunService:IsServer() then
module.Connection.OnServerEvent:Connect(connectionServerHandler)
if not module.ManualMode then
LogService.MessageOut:Connect(serverLogServiceHandler)
end
elseif RunService:IsClient() then
module.Connection.OnClientEvent:Connect(connectionClientHandler)
if not module.ManualMode then
LogService.MessageOut:Connect(clientLogServiceHandler)
end
end
-- Set init flag to stop further initialisation calls
module._initialised = true
end
--[[
TODO:
- Test everything :(
--]]
return module