@rbxts/scribe-telemetry 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/Config.luau ADDED
@@ -0,0 +1,446 @@
1
+ --!strict
2
+ -- Validates and resolves the options handed to Start; a refusal names the field.
3
+
4
+ local Config = {}
5
+
6
+ local Transport = require(script.Parent.Transport)
7
+
8
+ export type Category = "Health" | "Issues" | "Warnings" | "Performance" | "Summaries" | "Leaderboards"
9
+ export type MentionKind = "Fatal" | "Error" | "Outage" | "Degraded" | "Recovery" | "Performance"
10
+ -- One name, several, or false for nowhere.
11
+ export type Route = string | { string } | false
12
+
13
+ export type WebhookOptions = {
14
+ Url: string,
15
+ Enabled: boolean?,
16
+ Mention: { RoleId: string, On: { MentionKind }?, Cooldown: number? }?,
17
+ }
18
+
19
+ export type RuleOptions = { Threshold: number?, MinSamples: number?, Enabled: boolean? }
20
+ export type RuleSetOptions = { SlowSaves: RuleOptions?, SaveFailures: RuleOptions?, Traffic: RuleOptions? }
21
+ export type WarningOptions = { Include: { string }?, Categories: { string }? }
22
+ export type IssueOptions = { ExcludeCodes: { string }?, ExcludeCategories: { string }? }
23
+ export type GroupingOptions = { Interval: number?, Expiry: number?, MaxGroups: number? }
24
+ export type SummaryOptions = { Enabled: boolean?, Interval: number? }
25
+ export type LeaderboardOptions = { Enabled: boolean?, Interval: number?, MaxBoards: number? }
26
+ export type PerformanceOptions = { Interval: number?, Checks: number?, Rules: RuleSetOptions? }
27
+ export type LimitOptions = {
28
+ MaxQueued: number?,
29
+ MaxQueuedBytes: number?,
30
+ PerDestination: number?,
31
+ MaxAge: number?,
32
+ MaxAttempts: number?,
33
+ MaxRetryDelay: number?,
34
+ }
35
+
36
+ --- What Start accepts; only Webhooks is required, and the seams are for tests.
37
+ export type Options = {
38
+ Webhooks: { [string]: WebhookOptions },
39
+ Default: string?,
40
+ Routes: {
41
+ Health: Route?,
42
+ Issues: Route?,
43
+ Warnings: Route?,
44
+ Performance: Route?,
45
+ Summaries: Route?,
46
+ Leaderboards: Route?,
47
+ }?,
48
+ Warnings: WarningOptions?,
49
+ Issues: IssueOptions?,
50
+ Grouping: GroupingOptions?,
51
+ Summaries: SummaryOptions?,
52
+ Leaderboards: LeaderboardOptions?,
53
+ Performance: PerformanceOptions?,
54
+ Limits: LimitOptions?,
55
+ IncludePlayerIds: boolean?,
56
+ Environment: string?,
57
+ AllowStudio: boolean?,
58
+ ReportHealthyStartup: boolean?,
59
+ Http: Transport.Http?,
60
+ Clock: Transport.Clock?,
61
+ Scheduler: Transport.Scheduler?,
62
+ Json: Transport.Json?,
63
+ Jitter: (() -> number)?,
64
+ Studio: boolean?,
65
+ }
66
+
67
+ export type Destination = {
68
+ Name: string,
69
+ Url: string,
70
+ Enabled: boolean,
71
+ MentionRoleId: string?,
72
+ -- Which report kinds may mention the role: "Fatal", "Error", "Outage", "Degraded", "Recovery", "Performance".
73
+ MentionOn: { [string]: boolean },
74
+ MentionCooldown: number,
75
+ }
76
+
77
+ export type Rule = {
78
+ Enabled: boolean,
79
+ Threshold: number,
80
+ MinSamples: number,
81
+ }
82
+
83
+ export type Resolved = {
84
+ Destinations: { [string]: Destination },
85
+ Default: string?,
86
+ -- Per category: a list of destination names, false for explicitly off, nil for unset.
87
+ Routes: { [string]: { string } | boolean },
88
+ WarningCodes: { [string]: boolean },
89
+ WarningCategories: { [string]: boolean },
90
+ ExcludeCodes: { [string]: boolean },
91
+ ExcludeCategories: { [string]: boolean },
92
+ GroupInterval: number,
93
+ GroupExpiry: number,
94
+ MaxGroups: number,
95
+ SummaryInterval: number,
96
+ SummariesEnabled: boolean,
97
+ LeaderboardsEnabled: boolean,
98
+ LeaderboardInterval: number,
99
+ MaxBoards: number,
100
+ PerformanceInterval: number,
101
+ PerformanceChecks: number,
102
+ Rules: { SlowSaves: Rule, SaveFailures: Rule, Traffic: Rule },
103
+ MaxQueued: number,
104
+ MaxQueuedBytes: number,
105
+ PerDestinationQueued: number,
106
+ MaxAge: number,
107
+ MaxAttempts: number,
108
+ MaxRetryDelay: number,
109
+ IncludePlayerIds: boolean,
110
+ Environment: string,
111
+ AllowStudio: boolean,
112
+ ReportHealthyStartup: boolean,
113
+ BrandName: string,
114
+ IconUrl: string,
115
+ Urls: { string }, -- every configured URL, longest first, for redaction
116
+ }
117
+
118
+ Config.CATEGORIES = { "Health", "Issues", "Warnings", "Performance", "Summaries", "Leaderboards" }
119
+
120
+ -- Fixed, like the name beside it: every message is visibly Scribe's.
121
+ Config.LOGO_URL = "https://raw.githubusercontent.com/ericplane/Scribe/main/docgen/theme/assets/favicon.png"
122
+ Config.BRAND_NAME = "Scribe Telemetry"
123
+
124
+ -- Forwarded by default: warnings a developer acts on (docgen/guides/log-codes.md).
125
+ Config.DEFAULT_WARNING_CODES = {
126
+ "PROFILE_SIZE",
127
+ "SLOW_LOAD",
128
+ "PLAYER_LEAVING_HOOK_SLOW",
129
+ "WIPE_GUARD_BLOCKED",
130
+ "WIPE_GUARD_FORCED",
131
+ "PURCHASE_ID_EVICTED",
132
+ "PURCHASE_CLAIM_EVICTED",
133
+ "GIFT_CREDIT_UNCONFIRMED",
134
+ "PASS_PURCHASE_UNCONFIRMED",
135
+ "LB_WRITE_DROPPED",
136
+ "LB_READ_FAIL",
137
+ "LB_WRITE_FAIL",
138
+ "LB_QUEUE_OVERFLOW",
139
+ "LB_BUDGET_DEFERRED",
140
+ "RECEIPT_RETRY",
141
+ }
142
+
143
+ local MENTION_KINDS =
144
+ { Fatal = true, Error = true, Outage = true, Degraded = true, Recovery = true, Performance = true }
145
+
146
+ local function fail(message: string)
147
+ error(`ScribeTelemetry: {message}`, 0)
148
+ end
149
+
150
+ local function number(value: any, field: string, default: number, min: number): number
151
+ if value == nil then
152
+ return default
153
+ end
154
+ if type(value) ~= "number" or value ~= value or value < min then
155
+ fail(`{field} must be a number of at least {min}`)
156
+ end
157
+ return value
158
+ end
159
+
160
+ local function boolean(value: any, field: string, default: boolean): boolean
161
+ if value == nil then
162
+ return default
163
+ end
164
+ if type(value) ~= "boolean" then
165
+ fail(`{field} must be true or false`)
166
+ end
167
+ return value
168
+ end
169
+
170
+ local function set(list: any, field: string): { [string]: boolean }
171
+ local out: { [string]: boolean } = {}
172
+ if list == nil then
173
+ return out
174
+ end
175
+ if type(list) ~= "table" then
176
+ fail(`{field} must be a list of strings`)
177
+ end
178
+ for _, item in list :: { any } do
179
+ if type(item) ~= "string" then
180
+ fail(`{field} must contain only strings`)
181
+ end
182
+ out[item] = true
183
+ end
184
+ return out
185
+ end
186
+
187
+ -- Discord, a proxy in front of it, or a service of your own; Discord refuses Roblox's servers.
188
+ local function isEndpointUrl(url: string): boolean
189
+ return string.match(url, "^https?://[%w%.%-%[%]:]+[/?]") ~= nil
190
+ or string.match(url, "^https?://[%w%.%-%[%]:]+$") ~= nil
191
+ end
192
+
193
+ --- The URL to post to. Discord answers a webhook with 204 and no body unless `wait=true`
194
+ --- is asked for, so that is added on Discord's path (a proxy keeps it) and nowhere else.
195
+ function Config.PostUrl(url: string): string
196
+ if string.find(url, "/api/webhooks/", 1, true) == nil then
197
+ return url
198
+ end
199
+ return url .. (if string.find(url, "?", 1, true) then "&wait=true" else "?wait=true")
200
+ end
201
+
202
+ local function destination(name: string, raw: any): Destination
203
+ if type(raw) ~= "table" then
204
+ fail(`Webhooks.{name} must be a table`)
205
+ end
206
+ if type(raw.Url) ~= "string" or not isEndpointUrl(raw.Url) then
207
+ fail(`Webhooks.{name}.Url must be an http or https URL with a host`)
208
+ end
209
+ local mention = raw.Mention
210
+ local roleId: string? = nil
211
+ local on: { [string]: boolean } = {}
212
+ local cooldown = 300
213
+ if mention ~= nil then
214
+ if type(mention) ~= "table" then
215
+ fail(`Webhooks.{name}.Mention must be a table`)
216
+ end
217
+ if type(mention.RoleId) ~= "string" or string.match(mention.RoleId, "^%d+$") == nil then
218
+ fail(`Webhooks.{name}.Mention.RoleId must be a role id as a string of digits`)
219
+ end
220
+ roleId = mention.RoleId
221
+ for kind in set(mention.On or { "Fatal", "Outage" }, `Webhooks.{name}.Mention.On`) do
222
+ if not MENTION_KINDS[kind] then
223
+ fail(`Webhooks.{name}.Mention.On has an unknown kind "{kind}"`)
224
+ end
225
+ on[kind] = true
226
+ end
227
+ cooldown = number(mention.Cooldown, `Webhooks.{name}.Mention.Cooldown`, 300, 0)
228
+ end
229
+ return {
230
+ Name = name,
231
+ Url = raw.Url,
232
+ Enabled = boolean(raw.Enabled, `Webhooks.{name}.Enabled`, true),
233
+ MentionRoleId = roleId,
234
+ MentionOn = on,
235
+ MentionCooldown = cooldown,
236
+ }
237
+ end
238
+
239
+ local function rule(raw: any, field: string, defaultMinSamples: number): Rule
240
+ if raw == nil then
241
+ return { Enabled = false, Threshold = 0, MinSamples = defaultMinSamples }
242
+ end
243
+ if type(raw) ~= "table" then
244
+ fail(`{field} must be a table`)
245
+ end
246
+ if type(raw.Threshold) ~= "number" or raw.Threshold <= 0 then
247
+ fail(`{field}.Threshold must be a positive number; there is no default`)
248
+ end
249
+ return {
250
+ Enabled = boolean(raw.Enabled, `{field}.Enabled`, true),
251
+ Threshold = raw.Threshold,
252
+ MinSamples = number(raw.MinSamples, `{field}.MinSamples`, defaultMinSamples, 1),
253
+ }
254
+ end
255
+
256
+ --- Resolves and validates `options`, raising a message that names the field otherwise.
257
+ function Config.Resolve(options: Options): Resolved
258
+ if type(options) ~= "table" then
259
+ fail("Start needs an options table")
260
+ end
261
+ if type(options.Webhooks) ~= "table" then
262
+ fail("Webhooks must be a table of named destinations")
263
+ end
264
+ local destinations: { [string]: Destination } = {}
265
+ local count = 0
266
+ for name, raw in options.Webhooks do
267
+ if type(name) ~= "string" or name == "" then
268
+ fail("every Webhooks key must be a non-empty name")
269
+ end
270
+ destinations[name] = destination(name, raw)
271
+ count += 1
272
+ end
273
+ if count == 0 then
274
+ fail("Webhooks must name at least one destination")
275
+ end
276
+
277
+ local default: string? = options.Default
278
+ if default ~= nil then
279
+ if type(default) ~= "string" or destinations[default] == nil then
280
+ fail(`Default names a destination that is not in Webhooks: "{tostring(default)}"`)
281
+ end
282
+ end
283
+
284
+ local routes: { [string]: { string } | boolean } = {}
285
+ local rawRoutes = options.Routes or {}
286
+ if type(rawRoutes) ~= "table" then
287
+ fail("Routes must be a table")
288
+ end
289
+ for category, route in rawRoutes do
290
+ if not table.find(Config.CATEGORIES, category) then
291
+ fail(`Routes.{tostring(category)} is not a report category; use {table.concat(Config.CATEGORIES, ", ")}`)
292
+ end
293
+ if route == false then
294
+ routes[category] = false
295
+ elseif type(route) == "string" then
296
+ if destinations[route] == nil then
297
+ fail(`Routes.{category} names a destination that is not in Webhooks: "{route}"`)
298
+ end
299
+ routes[category] = { route }
300
+ elseif type(route) == "table" then
301
+ local names = {}
302
+ for _, item in route :: { any } do
303
+ if type(item) ~= "string" or destinations[item] == nil then
304
+ fail(`Routes.{category} names a destination that is not in Webhooks: "{tostring(item)}"`)
305
+ end
306
+ table.insert(names, item)
307
+ end
308
+ if #names == 0 then
309
+ fail(`Routes.{category} is an empty list; use false to disable the category`)
310
+ end
311
+ routes[category] = names
312
+ else
313
+ fail(`Routes.{category} must be a destination name, a list of names, or false`)
314
+ end
315
+ end
316
+
317
+ local warnings: WarningOptions = options.Warnings or {}
318
+ if type(warnings) ~= "table" then
319
+ fail("Warnings must be a table")
320
+ end
321
+ local issues: IssueOptions = options.Issues or {}
322
+ if type(issues) ~= "table" then
323
+ fail("Issues must be a table")
324
+ end
325
+ local grouping: GroupingOptions = options.Grouping or {}
326
+ local summaries: SummaryOptions = options.Summaries or {}
327
+ if options.Leaderboards ~= nil and type(options.Leaderboards) ~= "table" then
328
+ fail("Leaderboards must be a table")
329
+ end
330
+ local leaderboards: LeaderboardOptions = options.Leaderboards or {}
331
+ local performance: PerformanceOptions = options.Performance or {}
332
+ local rules: RuleSetOptions = performance.Rules or {}
333
+ local limits: LimitOptions = options.Limits or {}
334
+ local tables: { [string]: any } = {
335
+ Grouping = grouping,
336
+ Summaries = summaries,
337
+ Leaderboards = leaderboards,
338
+ Performance = performance,
339
+ Limits = limits,
340
+ Rules = rules,
341
+ }
342
+ for field, value in tables do
343
+ if type(value) ~= "table" then
344
+ fail(`{field} must be a table`)
345
+ end
346
+ end
347
+ local boardInterval = number(leaderboards.Interval, "Leaderboards.Interval", 30, 5)
348
+ if boardInterval == math.huge then
349
+ fail("Leaderboards.Interval must be finite")
350
+ end
351
+ local maxBoards = number(leaderboards.MaxBoards, "Leaderboards.MaxBoards", 64, 1)
352
+ if maxBoards > 1024 or maxBoards % 1 ~= 0 then
353
+ fail("Leaderboards.MaxBoards must be an integer from 1 to 1024")
354
+ end
355
+
356
+ local environment = options.Environment
357
+ if environment ~= nil and type(environment) ~= "string" then
358
+ fail("Environment must be a string")
359
+ end
360
+ if (options :: any).IconUrl ~= nil or (options :: any).BrandName ~= nil then
361
+ fail("IconUrl and BrandName are fixed to Scribe's own and cannot be set")
362
+ end
363
+
364
+ local urls: { string } = {}
365
+ for _, dest in destinations do
366
+ if table.find(urls, dest.Url) == nil then
367
+ table.insert(urls, dest.Url)
368
+ end
369
+ end
370
+ table.sort(urls, function(a: string, b: string)
371
+ return #a > #b
372
+ end)
373
+
374
+ return {
375
+ Destinations = destinations,
376
+ Default = default,
377
+ Routes = routes,
378
+ Urls = urls,
379
+ WarningCodes = set(warnings.Include or Config.DEFAULT_WARNING_CODES, "Warnings.Include"),
380
+ WarningCategories = set(warnings.Categories, "Warnings.Categories"),
381
+ ExcludeCodes = set(issues.ExcludeCodes, "Issues.ExcludeCodes"),
382
+ ExcludeCategories = set(issues.ExcludeCategories, "Issues.ExcludeCategories"),
383
+ GroupInterval = number(grouping.Interval, "Grouping.Interval", 60, 1),
384
+ GroupExpiry = number(grouping.Expiry, "Grouping.Expiry", 600, 1),
385
+ MaxGroups = number(grouping.MaxGroups, "Grouping.MaxGroups", 128, 1),
386
+ SummariesEnabled = boolean(summaries.Enabled, "Summaries.Enabled", false),
387
+ SummaryInterval = number(summaries.Interval, "Summaries.Interval", 1800, 60),
388
+ LeaderboardsEnabled = boolean(leaderboards.Enabled, "Leaderboards.Enabled", true),
389
+ LeaderboardInterval = boardInterval,
390
+ MaxBoards = maxBoards,
391
+ PerformanceInterval = number(performance.Interval, "Performance.Interval", 60, 5),
392
+ PerformanceChecks = number(performance.Checks, "Performance.Checks", 3, 1),
393
+ Rules = {
394
+ SlowSaves = rule(rules.SlowSaves, "Performance.Rules.SlowSaves", 20),
395
+ SaveFailures = rule(rules.SaveFailures, "Performance.Rules.SaveFailures", 1),
396
+ Traffic = rule(rules.Traffic, "Performance.Rules.Traffic", 1),
397
+ },
398
+ MaxQueued = number(limits.MaxQueued, "Limits.MaxQueued", 200, 1),
399
+ MaxQueuedBytes = number(limits.MaxQueuedBytes, "Limits.MaxQueuedBytes", 262144, 1024),
400
+ PerDestinationQueued = number(limits.PerDestination, "Limits.PerDestination", 64, 1),
401
+ MaxAge = number(limits.MaxAge, "Limits.MaxAge", 900, 10),
402
+ MaxAttempts = number(limits.MaxAttempts, "Limits.MaxAttempts", 5, 1),
403
+ MaxRetryDelay = number(limits.MaxRetryDelay, "Limits.MaxRetryDelay", 300, 1),
404
+ IncludePlayerIds = boolean(options.IncludePlayerIds, "IncludePlayerIds", false),
405
+ Environment = environment or "production",
406
+ AllowStudio = boolean(options.AllowStudio, "AllowStudio", false),
407
+ ReportHealthyStartup = boolean(options.ReportHealthyStartup, "ReportHealthyStartup", false),
408
+ BrandName = Config.BRAND_NAME,
409
+ IconUrl = Config.LOGO_URL,
410
+ }
411
+ end
412
+
413
+ export type Resolution = {
414
+ Destinations: { Destination },
415
+ Skipped: string?, -- "disabled", "unrouted" or "none-enabled" when the list is empty
416
+ }
417
+
418
+ --- The enabled destinations a category delivers to, deduplicated by webhook URL so two
419
+ --- names on one channel cannot deliver a report twice. An explicit `false` never falls
420
+ --- back to the default; an omitted route does.
421
+ function Config.Route(config: Resolved, category: string): Resolution
422
+ local route = config.Routes[category]
423
+ local names: { string }
424
+ if route == false then
425
+ return { Destinations = {}, Skipped = "disabled" }
426
+ elseif route == nil then
427
+ if config.Default == nil then
428
+ return { Destinations = {}, Skipped = "unrouted" }
429
+ end
430
+ names = { config.Default :: string }
431
+ else
432
+ names = route :: { string }
433
+ end
434
+ local out: { Destination } = {}
435
+ local seenUrl: { [string]: boolean } = {}
436
+ for _, name in names do
437
+ local dest = config.Destinations[name]
438
+ if dest ~= nil and dest.Enabled and not seenUrl[dest.Url] then
439
+ seenUrl[dest.Url] = true
440
+ table.insert(out, dest)
441
+ end
442
+ end
443
+ return { Destinations = out, Skipped = if #out == 0 then "none-enabled" else nil }
444
+ end
445
+
446
+ return Config
@@ -0,0 +1,104 @@
1
+ --!strict
2
+ -- Optional runtime diagnostics for the periodic summary.
3
+
4
+ local Format = require(script.Parent.Format)
5
+
6
+ local Diagnostics = {}
7
+
8
+ local function number(value: any): number?
9
+ return if type(value) == "number" and value >= 0 and value < math.huge then value else nil
10
+ end
11
+
12
+ local function countText(value: number?): string
13
+ if value == nil then
14
+ return "n/a"
15
+ end
16
+ return if value >= 1e9 then string.format("%.3g", value) else tostring(value)
17
+ end
18
+
19
+ local function duration(value: any): string
20
+ local seconds = number(value)
21
+ if seconds == nil then
22
+ return "n/a"
23
+ elseif seconds < 10 then
24
+ return string.format("%.2fs", seconds)
25
+ elseif seconds < 60 then
26
+ return `{math.floor(seconds)}s`
27
+ elseif seconds < 3600 then
28
+ return `{math.floor(seconds / 60)}m {math.floor(seconds % 60)}s`
29
+ end
30
+ return `{countText(math.floor(seconds / 3600))}h {math.floor((seconds % 3600) / 60)}m`
31
+ end
32
+
33
+ local function distribution(p: any): string
34
+ if type(p) ~= "table" or number(p.Samples) == 0 then
35
+ return "no samples"
36
+ end
37
+ return `p50 {duration(p.P50)} · p90 {duration(p.P90)} · p99 {duration(p.P99)} ({countText(number(p.Samples))} samples over {duration(
38
+ p.Window
39
+ )}, newest {duration(p.Age)} ago)`
40
+ end
41
+
42
+ function Diagnostics.Fields(
43
+ metrics: { [string]: any },
44
+ previous: { [string]: any },
45
+ percentiles: { [string]: any }
46
+ ): { Format.Field }
47
+ local fields: { Format.Field } = {}
48
+ local function present(names: { string }): boolean
49
+ for _, name in names do
50
+ if number(metrics[name]) ~= nil then
51
+ return true
52
+ end
53
+ end
54
+ return false
55
+ end
56
+ local function count(name: string): string
57
+ local current = number(metrics[name])
58
+ return countText(if current == nil then nil else math.max(0, current - (number(previous[name]) or 0)))
59
+ end
60
+ local function add(name: string, value: string, inline: boolean?)
61
+ table.insert(fields, { Name = name, Value = value, Inline = inline })
62
+ end
63
+ if present({ "ReceiptHistoryRefusals" }) then
64
+ add("Receipts", `{count("ReceiptHistoryRefusals")} history-capacity refusals`, true)
65
+ end
66
+ if present({ "LogSinkDropped", "LogSinkErrors" }) then
67
+ add("Log delivery", `{count("LogSinkDropped")} dropped · {count("LogSinkErrors")} sink errors`, true)
68
+ end
69
+ if
70
+ present({
71
+ "LbWrites",
72
+ "LbWritesSkipped",
73
+ "LbReadFailures",
74
+ "LbWriteFailures",
75
+ "LbQueueDepth",
76
+ "LbBudgetDeferred",
77
+ "LbQueueOverflow",
78
+ })
79
+ then
80
+ add(
81
+ "Leaderboard requests",
82
+ `{count("LbWrites")} writes · {count("LbWritesSkipped")} skipped\n{count("LbReadFailures")} read failures · {count(
83
+ "LbWriteFailures"
84
+ )} write failures\n{countText(number(metrics.LbQueueDepth))} last reported queue · {count(
85
+ "LbBudgetDeferred"
86
+ )} budget deferrals · {count("LbQueueOverflow")} queue drops`
87
+ )
88
+ end
89
+ for _, definition in
90
+ {
91
+ { "ProfileLoadDuration", "Profile acquisition (rolling)" },
92
+ { "LoadDuration", "Player load (rolling)" },
93
+ { "PlayerLeavingHookDuration", "Player leaving hook (rolling)" },
94
+ }
95
+ do
96
+ local key, label = definition[1], definition[2]
97
+ if type(metrics[key]) == "table" or type(percentiles[key]) == "table" then
98
+ add(label, distribution(percentiles[key]))
99
+ end
100
+ end
101
+ return fields
102
+ end
103
+
104
+ return Diagnostics
package/Format.luau ADDED
@@ -0,0 +1,152 @@
1
+ --!strict
2
+ -- One report record to one Discord webhook payload, branded and bounded to Discord's limits.
3
+
4
+ local Sanitize = require(script.Parent.Sanitize)
5
+
6
+ local Format = {}
7
+
8
+ export type Field = { Name: string, Value: string, Inline: boolean? }
9
+
10
+ export type Report = {
11
+ Id: string,
12
+ Kind: string, -- Issue, Warning, Repeat, Health, Performance, Summary, Test
13
+ Category: string,
14
+ Severity: string, -- Fatal, Error, Warn, Outage, Degraded, Recovery, Info
15
+ Title: string,
16
+ Code: string?,
17
+ Description: string,
18
+ Fields: { Field },
19
+ At: number, -- wall clock seconds
20
+ MentionKind: string?,
21
+ Priority: number, -- 3 first, 1 last, when the queue has to choose
22
+ }
23
+
24
+ export type Meta = {
25
+ PlaceId: number,
26
+ PlaceVersion: number,
27
+ JobId: string,
28
+ ScribeVersion: string,
29
+ Environment: string,
30
+ }
31
+
32
+ -- Discord's limits, in characters; applied here in bytes, which is never looser.
33
+ local TITLE_MAX = 256
34
+ local DESCRIPTION_MAX = 4096
35
+ local FIELD_NAME_MAX = 256
36
+ local FIELD_VALUE_MAX = 1024
37
+ local FOOTER_MAX = 2048
38
+ local FIELDS_MAX = 25
39
+ local EMBED_TOTAL_MAX = 6000
40
+
41
+ Format.COLORS = {
42
+ Fatal = 0xB91C1C,
43
+ Error = 0xE5484D,
44
+ Warn = 0xF5A524,
45
+ Outage = 0xE5484D,
46
+ Degraded = 0xF5A524,
47
+ Recovery = 0x34D399,
48
+ Performance = 0xF97316,
49
+ Info = 0x3B82F6,
50
+ }
51
+
52
+ local function isoTimestamp(at: number): string
53
+ local ok, text = pcall(function()
54
+ return os.date("!%Y-%m-%dT%H:%M:%SZ", at)
55
+ end)
56
+ return if ok then text else ""
57
+ end
58
+
59
+ local function utcClock(at: number): string
60
+ local ok, text = pcall(function()
61
+ return os.date("!%H:%M:%S UTC", at)
62
+ end)
63
+ return if ok then text else ""
64
+ end
65
+
66
+ --- The browser link into this server.
67
+ function Format.JoinUrl(meta: Meta): string
68
+ return `https://www.roblox.com/games/start?placeId={meta.PlaceId}&gameInstanceId={meta.JobId}`
69
+ end
70
+
71
+ local function utf8Length(s: string): number
72
+ local ok, n = pcall(function()
73
+ return utf8.len(s)
74
+ end)
75
+ return if ok and n then n else #s
76
+ end
77
+
78
+ --- The payload for one destination. `mention` is the role id to ping, already decided
79
+ --- by the caller's severity and cooldown rules; nil sends with every mention parse off.
80
+ function Format.Payload(
81
+ report: Report,
82
+ meta: Meta,
83
+ brand: { Name: string, IconUrl: string },
84
+ mention: string?
85
+ ): { [string]: any }
86
+ local title = Sanitize.Truncate(report.Title, TITLE_MAX)
87
+ local description = Sanitize.Truncate(report.Description, DESCRIPTION_MAX)
88
+ local fields: { { [string]: any } } = {}
89
+ local function add(name: string, value: string, inline: boolean?)
90
+ if #fields >= FIELDS_MAX then
91
+ return
92
+ end
93
+ local cell: { [string]: any } = {
94
+ name = Sanitize.Truncate(name, FIELD_NAME_MAX),
95
+ value = Sanitize.Truncate(if value == "" then "\u{2014}" else value, FIELD_VALUE_MAX),
96
+ inline = inline == true,
97
+ }
98
+ table.insert(fields, cell)
99
+ end
100
+ for _, field in report.Fields do
101
+ add(field.Name, field.Value, field.Inline)
102
+ end
103
+ -- Identity on health and summaries; a join link everywhere.
104
+ if report.Kind == "Health" or report.Kind == "Summary" then
105
+ add("Place", `{meta.PlaceId} v{meta.PlaceVersion}`, true)
106
+ add("Scribe", meta.ScribeVersion, true)
107
+ end
108
+ if meta.PlaceId > 0 and meta.JobId ~= "" then
109
+ add("Server", `[Join {string.sub(meta.JobId, 1, 8)}]({Format.JoinUrl(meta)})`, true)
110
+ end
111
+ local footer = Sanitize.Truncate(
112
+ `{report.Id} \u{00B7} v{meta.PlaceVersion} \u{00B7} {meta.Environment} \u{00B7} {utcClock(report.At)}`,
113
+ FOOTER_MAX
114
+ )
115
+
116
+ -- Fields past the 6000 are dropped from the end; the description takes what is left.
117
+ local used = utf8Length(title) + utf8Length(footer) + utf8Length(brand.Name)
118
+ for _, field in fields do
119
+ used += utf8Length(field.name) + utf8Length(field.value)
120
+ end
121
+ while #fields > 0 and used > EMBED_TOTAL_MAX do
122
+ local last = table.remove(fields) :: { [string]: any }
123
+ used -= utf8Length(last.name) + utf8Length(last.value)
124
+ end
125
+ local room = EMBED_TOTAL_MAX - used
126
+ if utf8Length(description) > room then
127
+ description = Sanitize.Truncate(description, math.max(0, room))
128
+ end
129
+
130
+ local embed: { [string]: any } = {
131
+ author = { name = brand.Name, icon_url = brand.IconUrl },
132
+ title = title,
133
+ description = description,
134
+ color = Format.COLORS[report.Severity] or Format.COLORS.Info,
135
+ fields = fields,
136
+ footer = { text = footer },
137
+ timestamp = isoTimestamp(report.At),
138
+ }
139
+ local payload: { [string]: any } = {
140
+ username = brand.Name,
141
+ avatar_url = brand.IconUrl,
142
+ embeds = { embed },
143
+ allowed_mentions = { parse = {} },
144
+ }
145
+ if mention ~= nil then
146
+ payload.content = `<@&{mention}>`
147
+ payload.allowed_mentions = { parse = {}, roles = { mention } }
148
+ end
149
+ return payload
150
+ end
151
+
152
+ return Format