@rbxts/netweave 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,884 @@
1
+ --!strict
2
+ --!optimize 2
3
+
4
+ --[=[
5
+ @class Config
6
+
7
+ Global settings for netweave, in the shape ESLint made familiar: a rule name, and one of
8
+ `"off"`, `"warn"` or `"error"`.
9
+
10
+ ```lua
11
+ nw.configure({
12
+ rules = {
13
+ budget = "warn",
14
+ authorize = "error",
15
+ rateUnbounded = "off",
16
+ },
17
+ limits = { queueCapacity = 512 },
18
+ })
19
+ ```
20
+
21
+ :::caution What a severity does **not** do
22
+ It never turns enforcement off. A packet refused at `budget` is refused whatever `budget` is
23
+ set to; `"off"` silences the console, and nothing else. There is no setting anywhere in
24
+ netweave that makes a refused packet arrive, a missing policy optional, or an unauthorised
25
+ sender authorised — see [Config.rules] for why that asymmetry is deliberate.
26
+ :::
27
+
28
+ :::note Observers are never silenced
29
+ Severity governs netweave's own console output. A callback attached with `nw.observe` receives
30
+ every rejection regardless, because a metrics pipeline and a log level are different things and
31
+ a game that turns down its logs has not asked to stop counting.
32
+ :::
33
+ ]=]
34
+
35
+ --[[
36
+ The ESLint analogy is load-bearing for the *shape* and misleading about the *meaning*, and
37
+ getting that wrong would have been the whole defect.
38
+
39
+ A linter's `off` is safe: the rule stops reporting, and because a linter only ever reports,
40
+ nothing else changes. Most of what netweave checks is not a report — it is a refusal that
41
+ already happened, on data a hostile client sent. If `off` had meant "stop refusing", then the
42
+ single most copy-pasted artifact in any ecosystem, a config block off a forum post, would be a
43
+ way to remove G1 through G6 from a game whose author never read what they pasted.
44
+
45
+ So severity is bound to output and never to enforcement, and the two are kept in different
46
+ fields (`rules` versus `limits`) so that no future rule can quietly acquire the other meaning.
47
+
48
+ The one place a severity does raise is a rule marked `wire = false`: those fire on the game's
49
+ own declarations, where a raise is correct because `CLAUDE.md` §4 says `assert` is for
50
+ programmer error. A rule marked `wire = true` can never raise at any severity — that is G4, and
51
+ `RESEARCH §3.8-R` is what it costs to get wrong.
52
+ ]]
53
+
54
+ local Config = {}
55
+
56
+ --[=[
57
+ @type Severity "off" | "warn" | "error"
58
+ @within Config
59
+
60
+ | Severity | On a wire rule | On a declaration rule |
61
+ |---|---|---|
62
+ | `"off"` | silent | the check does not run |
63
+ | `"warn"` | reported up to `repeatsPerDiagnostic` times per channel and stage | reported once, and execution continues |
64
+ | `"error"` | the same, **with a traceback** | raised |
65
+
66
+ `"error"` on a wire rule does not raise and cannot be made to. Wire data reaching `error()` is
67
+ the failure G4 exists to prevent, so the strongest thing a severity can buy on the receive path
68
+ is more output.
69
+
70
+ :::caution
71
+ ~~`"error"` reports **every** time.~~ **It is suppressed after `repeatsPerDiagnostic` like
72
+ `"warn"`, as of M3 phase 9.** A wire rule fires at a rate the *peer* chooses, and an `"error"`
73
+ costs a stack walk, so "every time" was a knob a hostile client could turn. What `"error"` buys
74
+ is the traceback and the louder sink; `nw.observe` still receives every rejection and
75
+ `nw.diagnostics()` still counts every one, which is where a flood is meant to be read.
76
+ :::
77
+ ]=]
78
+ export type Severity = "off" | "warn" | "error"
79
+
80
+ --[=[
81
+ @interface Rules
82
+ @within Config
83
+ .parse Severity? -- bytes that did not decode against the channel's schema
84
+ .budget Severity? -- a sender over the channel's declared `rate`
85
+ .authorize Severity? -- a policy said no
86
+ .handler Severity? -- the game's own handler threw
87
+ .queue Severity? -- a channel with no listener overflowed its queue
88
+ .send Severity? -- an outgoing payload was refused before it left
89
+ .protocol Severity? -- a peer joined on a different set of channel definitions
90
+ .query Severity? -- a call came back without an answer
91
+ .direction Severity? -- a peer sent on a channel it is the receiver of
92
+ .replicate Severity? -- a replicated channel is holding more baselines than its limit allows
93
+ .rateUnbounded Severity? -- a `rate` so large it cannot bind, declared as if it were a limit
94
+
95
+ Ten of the eleven are the stages of [Observer.Stage], because a rejection already carries the
96
+ stage it happened at and inventing a second vocabulary for the same things would only make them
97
+ drift apart. `rateUnbounded` is the odd one out: it fires at declaration time, on the game's own
98
+ code, and is the only rule here that raises at `"error"`.
99
+ ]=]
100
+ --[=[
101
+ @type Stage "parse" | "budget" | "authorize" | "handler" | "queue" | "send" | "protocol" | "query" | "direction" | "replicate"
102
+ @within Config
103
+
104
+ Where on the receive path a packet was refused.
105
+
106
+ Here rather than in `Observer`, which is where a game reads it, because the modules that *produce*
107
+ a stage are lower than the observer: `Batch.Sink` carried it as `string` and `Inbound` cast it
108
+ back, so a misspelt stage type-checked all the way to the report (M4 report finding 48). This
109
+ module is the one both can reach — it is a leaf, and it already names every stage as a rule, which
110
+ `tests/config_runtime.luau` asserts member by member.
111
+ ]=]
112
+ export type Stage =
113
+ "parse"
114
+ | "budget"
115
+ | "authorize"
116
+ | "handler"
117
+ | "queue"
118
+ | "send"
119
+ | "protocol"
120
+ | "query"
121
+ | "direction"
122
+ | "replicate"
123
+
124
+ export type Rules = {
125
+ parse: Severity?,
126
+ budget: Severity?,
127
+ authorize: Severity?,
128
+ handler: Severity?,
129
+ queue: Severity?,
130
+ send: Severity?,
131
+ protocol: Severity?,
132
+ query: Severity?,
133
+ direction: Severity?,
134
+ replicate: Severity?,
135
+ rateUnbounded: Severity?,
136
+ }
137
+
138
+ --[=[
139
+ @interface Limits
140
+ @within Config
141
+ .queueCapacity number? -- packets held for a channel whose listener has not attached yet
142
+ .pendingPerBatch number? -- decoded packets held live while a batch is read, before any is dispatched. **Server only**
143
+ .unreliableBytes number? -- the largest unreliable payload that will be sent
144
+ .repeatsPerDiagnostic number? -- how many times one channel and stage prints before it goes quiet
145
+ .callsInFlight number? -- unanswered `nw.query` calls one player may hold at once
146
+ .baselinesPerClient number? -- `(channel, subject)` pairs one client's replication may hold
147
+ .resyncTicks number? -- ticks a peer waits between resyncs that are acted on; a second ask inside the window is honoured when it closes
148
+
149
+ Numbers, not severities, and kept in their own field so that a limit can never be mistaken for a
150
+ switch.
151
+
152
+ They are not read at the same moment, and the difference matters:
153
+
154
+ | Limit | Read |
155
+ |---|---|
156
+ | `queueCapacity` | when a channel's queue is first created, which is its first refusal to a missing listener. A queue that already exists keeps the depth it was made with |
157
+ | `pendingPerBatch` | at the start of every batch, **on a server**. A client does not apply it: the batch's size is chosen by an untrusted peer only when the peer is a client, and enforcing it against the server drops traffic the game asked for — on a replicated channel, permanently (`src/transport/Inbound.luau`, `refreshCeiling`) |
158
+ | `unreliableBytes` | on every unreliable send, so it takes effect immediately and can only *lower* the ceiling — 908 is Roblox's limit, not netweave's |
159
+ | `repeatsPerDiagnostic` | on every report |
160
+ | `callsInFlight` | on every `invoke` and on every request the server accepts, so it takes effect immediately |
161
+ | `baselinesPerClient` | on every baseline a replicated channel is about to keep, so lowering it stops new ones rather than releasing held ones |
162
+ | `resyncTicks` | on every resync request and every tick, so it takes effect immediately. It was a constant until PLAN-M4-BUG phase 5: with a 30 KB replicated state each hostile client could extract 60 KB/s of encode for 10 B/s up, and a game could not tune it (M4-1) |
163
+
164
+ Configuring before the first channel is declared makes all of them behave the same way, which is
165
+ why that is the advice rather than the rule.
166
+ ]=]
167
+ export type Limits = {
168
+ queueCapacity: number?,
169
+ pendingPerBatch: number?,
170
+ unreliableBytes: number?,
171
+ repeatsPerDiagnostic: number?,
172
+ callsInFlight: number?,
173
+ baselinesPerClient: number?,
174
+ resyncTicks: number?,
175
+ }
176
+
177
+ --[=[
178
+ @interface Settings
179
+ @within Config
180
+ .rules Rules?
181
+ .limits Limits?
182
+ .contextGuard boolean? -- the Studio-only check that a `ctx` has not outlived its packet
183
+
184
+ Every field is optional and anything omitted keeps its current value, so a call that sets one
185
+ rule does not silently reset the rest.
186
+ ]=]
187
+ export type Settings = {
188
+ rules: Rules?,
189
+ limits: Limits?,
190
+ contextGuard: boolean?,
191
+ }
192
+
193
+ --[=[
194
+ @interface Snapshot
195
+ @within Config
196
+ .rules { [string]: Severity }
197
+ .limits { [string]: number }
198
+ .contextGuard boolean?
199
+
200
+ What [Config.snapshot] returns. Frozen at every level.
201
+ ]=]
202
+ export type Snapshot = {
203
+ read rules: { read [string]: Severity },
204
+ read limits: { read [string]: number },
205
+ read contextGuard: boolean?,
206
+ }
207
+
208
+ --[=[
209
+ @interface Described
210
+ @within Config
211
+ .rule string
212
+ .severity Severity
213
+ .default Severity
214
+ .wire boolean -- false means "error" raises; true means it never can
215
+ .summary string
216
+
217
+ One row of [Config.describe].
218
+ ]=]
219
+ export type Described = {
220
+ rule: string,
221
+ severity: Severity,
222
+ default: Severity,
223
+ wire: boolean,
224
+ summary: string,
225
+ }
226
+
227
+ --[[
228
+ `wire` decides whether `"error"` may raise, and `floor` decides how far down a rule may be
229
+ turned. Every rule here floors at `"off"` on purpose: none of them gates enforcement, so
230
+ silencing one costs visibility and nothing else. A future rule that *does* gate something
231
+
232
+ --[[
233
+ Width subtyping accepts extra properties, so `Settings` listing only the fields that exist
234
+ forbids nothing: `{ rules = { handlers = "warn" } }` type-checks against a type with no
235
+ `handlers`, and the author reads that as "configured" while the default quietly stays in force.
236
+ It is the same hole `Channel` documents for channel specs, and it wants the same answer — a
237
+ type function reading `properties` sees the extra key and can refuse it.
238
+
239
+ The snapshot type is threaded through as a second argument rather than rebuilt here, because a
240
+ type function body cannot see this module's own type aliases and a hand-built copy would drift
241
+ from `Snapshot` the first time either changed.
242
+ ]]
243
+ -- selene: allow(undefined_variable)
244
+ export type function CheckedSettings(spec, snapshot)
245
+ local settings = types.copy(spec)
246
+
247
+ if not settings:is("table") then
248
+ error(
249
+ "nw.configure takes a table of settings, written inline: "
250
+ .. 'nw.configure({ rules = { budget = "warn" }, limits = { queueCapacity = 512 } }). '
251
+ .. "The three fields are rules, limits and contextGuard, and every one is optional."
252
+ )
253
+ end
254
+
255
+ local sections = { rules = true, limits = true, contextGuard = true }
256
+ local ruleNames = {
257
+ parse = true,
258
+ budget = true,
259
+ authorize = true,
260
+ handler = true,
261
+ queue = true,
262
+ send = true,
263
+ protocol = true,
264
+ query = true,
265
+ direction = true,
266
+ replicate = true,
267
+ rateUnbounded = true,
268
+ }
269
+ --[[ Every key of `Limits`, and it has to be spelled out because a type function body cannot read
270
+ a type alias's properties back out as strings. `pendingPerBatch` was missing here until M3
271
+ phase 4: the field existed, the runtime honoured it, and the analyzer refused the one
272
+ spelling that worked. A list that has to be kept in step by hand is exactly the kind of thing
273
+ that drifts, which is why `tests/config_runtime.luau` now sets every limit by name. ]]
274
+ local limitNames = {
275
+ queueCapacity = true,
276
+ pendingPerBatch = true,
277
+ unreliableBytes = true,
278
+ repeatsPerDiagnostic = true,
279
+ callsInFlight = true,
280
+ baselinesPerClient = true,
281
+ resyncTicks = true,
282
+ }
283
+
284
+ --[[ Annotated `any` throughout: inside a type function the values are the analyzer's own type
285
+ objects, and letting it infer them produces a cyclic type it then cannot print. ]]
286
+ local function refuse(field: any, name: any, allowed: any)
287
+ local names = {}
288
+
289
+ for allowedName in allowed do
290
+ table.insert(names, allowedName)
291
+ end
292
+
293
+ table.sort(names)
294
+
295
+ error(`nw.configure: no such {field} \`{name}\`. Known {field}s: {table.concat(names, ", ")}`)
296
+ end
297
+
298
+ local function reject(container: any, field: any, allowed: any)
299
+ for key in container:properties() do
300
+ local name: any = (key :: any):value()
301
+
302
+ if not allowed[name] then
303
+ refuse(field, name, allowed)
304
+ end
305
+ end
306
+ end
307
+
308
+ --[[
309
+ The value layer, and it lives here rather than in the parameter's type.
310
+
311
+ `nw.configure` was typed `<S>(settings: S & Settings)` until M3 phase 4. That reads correctly
312
+ and does not work: Luau binds `S` to the argument's own type and then requires the
313
+ intersection to be exactly that type, so `{ limits = { queueCapacity = 512 } }` was refused
314
+ for not also carrying the four limits it had not set. **Every** call in the documented shape
315
+ was a type error, including the one in this module's own docstring, and nothing said so
316
+ because no `*_ok` file had ever configured anything — the mirror image of the failure
317
+ `tests/*_reject.luau` exists to catch. It surfaced when a phase 4 test needed to raise
318
+ `callsInFlight` and could not.
319
+
320
+ Checking here costs the eight-line wall of union explanations Luau prints for a failed
321
+ intersection and buys one message per mistake that names what to write instead.
322
+ `tests/config_ok.luau` is what keeps it honest.
323
+ ]]
324
+ local severities = { off = true, warn = true, error = true }
325
+
326
+ local function named(value: any): string
327
+ if value:is("singleton") then
328
+ return `\`{tostring(value:value())}\``
329
+ end
330
+
331
+ if value:is("string") then
332
+ return "a string"
333
+ end
334
+
335
+ if value:is("number") then
336
+ return "a number"
337
+ end
338
+
339
+ if value:is("boolean") then
340
+ return "a boolean"
341
+ end
342
+
343
+ if value:is("table") then
344
+ return "a table"
345
+ end
346
+
347
+ return "that"
348
+ end
349
+
350
+ --[[
351
+ A severity is checked for being *a string* here, and for being one of the three at runtime.
352
+
353
+ The narrower check is not available: with the parameter typed as a bare `S` there is no
354
+ expected type to hold `"warn"` at its singleton, so a config block's severities reach this
355
+ function widened to `string` and there is no literal left to compare. Restoring the expected
356
+ type is what the intersection above did, and what it cost was every call.
357
+
358
+ Nothing is lost that matters. `Config.configure` refuses `"loud"` with the same message, and
359
+ it refuses it at startup where the configure call is, not at the first packet — a misspelled
360
+ severity is loud either way. The case D-11 is actually about is a misspelled rule *name*,
361
+ which reads as "I configured this" while the default stays in force, and that is still caught
362
+ here by `reject`.
363
+ ]]
364
+ local function isSeverity(value: any): boolean
365
+ if value:is("singleton") then
366
+ return severities[value:value()] == true
367
+ end
368
+
369
+ return value:is("string") or value:is("union")
370
+ end
371
+
372
+ local function isNumber(value: any): boolean
373
+ return value:is("number")
374
+ end
375
+
376
+ --[[
377
+ **Every field this function reads is declared optional, so every field it reads is a union.**
378
+
379
+ `Settings.rules` is `Rules?`, `Limits.queueCapacity` is `number?`, `contextGuard` is
380
+ `boolean?`. Against a table *literal* that never showed: `{ limits = { queueCapacity = 32 } }`
381
+ gives properties typed `table` and `number`. Against a value typed with the library's own
382
+ exported types it shows immediately — `local s: nw.Settings = { ... }; nw.configure(s)` was a
383
+ type error saying "`rules` takes a table of rules, got that", because `:is("table")` is false
384
+ for a union and `named()` has no word for one either.
385
+
386
+ The exported type could not build the argument it names, and the only file that called
387
+ `nw.configure` at all was the rejection file, where a diagnostic is what success looks like.
388
+ That is the `nw.configure` incident of M3 phase 0 in a second form, and M4's report is what
389
+ found it (`tools/exports.luau` now requires an `_ok` for every exported type, which is what
390
+ closes it for good).
391
+
392
+ Stripping `nil` is the whole fix: what is left is the type the field would have had if it
393
+ were required, and every test below already handles that.
394
+ ]]
395
+ local function present(value: any): any
396
+ if not value or not value:is("union") then
397
+ return value
398
+ end
399
+
400
+ local rest = nil
401
+
402
+ for _, component in value:components() do
403
+ if not component:is("nil") then
404
+ rest = if rest then types.unionof(rest, component) else component
405
+ end
406
+ end
407
+
408
+ return rest
409
+ end
410
+
411
+ local function values(container: any, field: any, ok: any, expected: any)
412
+ for key, property in container:properties() do
413
+ local value: any = present(property.read)
414
+
415
+ if value and not ok(value) then
416
+ local name: any = (key :: any):value()
417
+ error(`nw.configure: {field} \`{name}\` takes {expected}, got {named(value)}`)
418
+ end
419
+ end
420
+ end
421
+
422
+ reject(settings, "setting", sections)
423
+
424
+ local function section(name: any, field: any, allowed: any, ok: any, expected: any)
425
+ local declared: any = present(settings:readproperty(types.singleton(name)))
426
+
427
+ if not declared then
428
+ return
429
+ end
430
+
431
+ if not declared:is("table") then
432
+ error(`nw.configure: \`{name}\` takes a table of {field}s, got {named(declared)}`)
433
+ end
434
+
435
+ reject(declared, field, allowed)
436
+ values(declared, field, ok, expected)
437
+ end
438
+
439
+ section("rules", "rule", ruleNames, isSeverity, `a severity: "off", "warn" or "error"`)
440
+ section("limits", "limit", limitNames, isNumber, "a number")
441
+
442
+ local guard: any = present(settings:readproperty(types.singleton("contextGuard")))
443
+
444
+ if guard and not guard:is("boolean") then
445
+ error(`nw.configure: \`contextGuard\` takes a boolean, got {named(guard)}`)
446
+ end
447
+
448
+ return types.copy(snapshot)
449
+ end
450
+
451
+ --[[
452
+ Load-bearing. An `export type function` that its own module never references does not reduce
453
+ across a `require` — it silently becomes `any`, and nothing reports it. M1 phase 5 lost the
454
+ directional views and the trust brand to exactly this, and only the exact diagnostic count in
455
+ `tests/api_reject.luau` noticed (`spike/declare/README.md` Q5).
456
+ ]]
457
+ type _instantiateChecked = CheckedSettings<{ rules: { parse: "warn" } }, Snapshot>
458
+
459
+ --[[
460
+ `wire` decides whether `"error"` may raise, and `floor` decides how far down a rule may be
461
+ turned. Every rule here floors at `"off"` on purpose: none of them gates enforcement, so
462
+ silencing one costs visibility and nothing else. A future rule that *does* gate something
463
+ belongs in `limits`, not here — but if one ever lands here by mistake, `floor` is the field
464
+ that stops it being switched off.
465
+ ]]
466
+ type Rule = {
467
+ default: Severity,
468
+ floor: Severity,
469
+ wire: boolean,
470
+ summary: string,
471
+ }
472
+
473
+ local RANK: { [string]: number } = { off = 0, warn = 1, error = 2 }
474
+ table.freeze(RANK)
475
+
476
+ local RULES: { [string]: Rule } = {
477
+ parse = {
478
+ default = "warn",
479
+ floor = "off",
480
+ wire = true,
481
+ summary = "bytes that did not decode against the channel's schema",
482
+ },
483
+ budget = {
484
+ default = "warn",
485
+ floor = "off",
486
+ wire = true,
487
+ summary = "a sender over the channel's declared rate",
488
+ },
489
+ authorize = {
490
+ default = "off",
491
+ floor = "off",
492
+ wire = true,
493
+ summary = "a policy refused the payload",
494
+ },
495
+ handler = {
496
+ default = "error",
497
+ floor = "off",
498
+ wire = true,
499
+ summary = "the game's own handler threw",
500
+ },
501
+ queue = {
502
+ default = "warn",
503
+ floor = "off",
504
+ wire = true,
505
+ summary = "a channel with no listener overflowed its queue",
506
+ },
507
+ protocol = {
508
+ --[[ Loud, because a mismatch means that client cannot play at all — a redeploy, not a
509
+ dropped packet.
510
+
511
+ ~~The repeat suppression would otherwise hide it after three, and the fourth player is
512
+ as stuck as the first.~~ **That was an argument for `error` bypassing the suppression,
513
+ and it does not any more** (M3 phase 9): this is a wire stage, so a peer chooses how
514
+ often it fires, and `error` carries a traceback. The fourth player is answered by
515
+ `nw.observe` and `nw.diagnostics()` instead, which is what the suppression line points
516
+ at. ]]
517
+ default = "error",
518
+ floor = "off",
519
+ wire = true,
520
+ summary = "a peer joined on a different set of channel definitions",
521
+ },
522
+ send = {
523
+ default = "warn",
524
+ floor = "off",
525
+ wire = true,
526
+ summary = "an outgoing payload was refused before it left",
527
+ },
528
+ query = {
529
+ default = "warn",
530
+ floor = "off",
531
+ wire = true,
532
+ summary = "a call came back without an answer",
533
+ },
534
+ direction = {
535
+ --[[ Loud, like `protocol`: nobody sends on a channel they receive on by accident, so the
536
+ first one is worth a stack trace.
537
+
538
+ ~~The first is worth as much as the fiftieth and there is no legitimate traffic for the
539
+ suppression to protect.~~ **Backwards** — the suppression is not protecting the
540
+ traffic, it is protecting the console and the thread that writes to it, and this is the
541
+ cheapest refusal a hostile peer can provoke. See `Observer.announce`. ]]
542
+ default = "error",
543
+ floor = "off",
544
+ wire = true,
545
+ summary = "a peer sent on a channel it is the receiver of",
546
+ },
547
+ replicate = {
548
+ --[[ A game's own volume rather than a peer's: how many subjects it replicates and to how
549
+ many people. Past the limit netweave stops holding a baseline for that subject, which
550
+ means it sends that client a whole snapshot every tick instead of a patch — **correct
551
+ and expensive**, which is the right way for a bound to fail and is exactly what
552
+ `nw.state` does for a living. Warn rather than error for the same reason `queue` does:
553
+ it is a number the game can raise once it has seen it. ]]
554
+ default = "warn",
555
+ floor = "off",
556
+ wire = true,
557
+ summary = "a replicated channel is holding more baselines than its limit allows",
558
+ },
559
+ rateUnbounded = {
560
+ default = "warn",
561
+ floor = "off",
562
+ wire = false,
563
+ summary = "a rate large enough that it cannot bind",
564
+ },
565
+ }
566
+ table.freeze(RULES)
567
+
568
+ local LIMITS: { [string]: { default: number, min: number, max: number } } = {
569
+ queueCapacity = { default = 256, min = 1, max = 65536 },
570
+ pendingPerBatch = { default = 256, min = 1, max = 65536 },
571
+ unreliableBytes = { default = 908, min = 1, max = 908 },
572
+ repeatsPerDiagnostic = { default = 3, min = 1, max = 1000 },
573
+ --[[ Both sides of a query read this one. On the server it bounds the threads a single player
574
+ can have parked inside slow handlers; on the client it bounds the calls one game can leave
575
+ outstanding. They are the same number because they are the same player counted from either
576
+ end (`PLAN-M3` D-13). ]]
577
+ callsInFlight = { default = 16, min = 1, max = 4096 },
578
+
579
+ --[[ How many `(channel, subject)` baselines one client's replication may hold. Not a defence
580
+ against a peer — the audience decides who sees what, so a client cannot ask for more — but
581
+ against a game that replicates thousands of subjects without noticing that the cost is
582
+ multiplied by everyone who can see them (`PLAN-M3` D-6, applied to L3). ]]
583
+ baselinesPerClient = { default = 256, min = 1, max = 65536 },
584
+
585
+ --[[ How many ticks a peer waits between resyncs that are acted on. Half a second at 60 Hz by
586
+ default: an honest client's first ask is always honoured at once, so this is only the gap
587
+ before a second one. The bound on what a hostile peer can extract is one full resend per
588
+ window per channel, and a game with a large replicated state raises this to shrink it. ]]
589
+ resyncTicks = { default = 30, min = 1, max = 3600 },
590
+ }
591
+ table.freeze(LIMITS)
592
+
593
+ --[[
594
+ Two flat tables rather than one nested settings object, because the read side is
595
+ `severity[stage]` on a rejection and `limit.queueCapacity` at construction — one index each,
596
+ with no walk through an options tree and nothing to allocate.
597
+ ]]
598
+ local severity: { [string]: Severity } = {}
599
+ local limit: { [string]: number } = {}
600
+ local contextGuard: boolean? = nil
601
+
602
+ local function restoreDefaults()
603
+ for name, rule in RULES do
604
+ severity[name] = rule.default
605
+ end
606
+
607
+ for name, bounds in LIMITS do
608
+ limit[name] = bounds.default
609
+ end
610
+
611
+ contextGuard = nil
612
+ end
613
+
614
+ restoreDefaults()
615
+
616
+ local function known(set: { [string]: any }): string
617
+ local names = {}
618
+
619
+ for name in set do
620
+ table.insert(names, name)
621
+ end
622
+
623
+ table.sort(names)
624
+
625
+ return table.concat(names, ", ")
626
+ end
627
+
628
+ --[[
629
+ An unknown key is an error rather than a shrug, and that is the one place this module is
630
+ stricter than ESLint. A misspelled rule in a linter costs a rule; a misspelled rule here reads
631
+ as "I configured this" while the default silently stays in force, and the author finds out from
632
+ a support thread. `handler` versus `handlers` should not be a debugging session.
633
+ ]]
634
+ local function reject(field: string, name: string, set: { [string]: any }): never
635
+ error(`nw.configure: no such {field} \`{name}\`. Known {field}s: {known(set)}`, 3)
636
+ end
637
+
638
+ local function readSeverity(name: string, value: any): Severity
639
+ local rule = RULES[name]
640
+
641
+ if not rule then
642
+ reject("rule", name, RULES)
643
+ end
644
+
645
+ if RANK[value] == nil then
646
+ error(
647
+ `nw.configure: rule \`{name}\` takes "off", "warn" or "error", got {typeof(value) == "string" and `"{value}"` or typeof(
648
+ value
649
+ )}`,
650
+ 3
651
+ )
652
+ end
653
+
654
+ if RANK[value] < RANK[rule.floor] then
655
+ error(`nw.configure: rule \`{name}\` cannot go below "{rule.floor}" — {rule.summary}`, 3)
656
+ end
657
+
658
+ return value
659
+ end
660
+
661
+ local function readLimit(name: string, value: any): number
662
+ local bounds = LIMITS[name]
663
+
664
+ if not bounds then
665
+ reject("limit", name, LIMITS)
666
+ end
667
+
668
+ if type(value) ~= "number" or value ~= value or value % 1 ~= 0 then
669
+ error(`nw.configure: limit \`{name}\` takes a whole number, got {tostring(value)}`, 3)
670
+ end
671
+
672
+ if value < bounds.min or value > bounds.max then
673
+ error(`nw.configure: limit \`{name}\` is {value}, outside {bounds.min}..{bounds.max}`, 3)
674
+ end
675
+
676
+ return value
677
+ end
678
+
679
+ --[=[
680
+ @within Config
681
+ @function configure
682
+ @param settings Settings
683
+
684
+ Applies settings. Anything omitted keeps its current value.
685
+
686
+ ```lua
687
+ nw.configure({ rules = { authorize = "warn" } })
688
+ ```
689
+
690
+ Raises on an unknown rule, an unknown limit, a severity that is not one of the three, or a
691
+ limit outside its range — all four are mistakes in the game's own source, where raising is the
692
+ behaviour that gets them fixed.
693
+
694
+ :::caution Configure before you declare
695
+ Limits are read when the thing they limit needs them, and that is not the same moment for each —
696
+ see [Config.Limits]. Raising `queueCapacity` after a channel has already built its queue moves
697
+ the number this function reports and not that queue. Configuring first makes all of them behave
698
+ alike.
699
+ :::
700
+ ]=]
701
+ function Config.configure(settings: Settings)
702
+ if type(settings) ~= "table" then
703
+ error(`nw.configure takes a table of settings, got {typeof(settings)}`, 2)
704
+ end
705
+
706
+ local given = settings :: { [string]: any }
707
+
708
+ for name in given do
709
+ if name ~= "rules" and name ~= "limits" and name ~= "contextGuard" then
710
+ reject("setting", name, { rules = true, limits = true, contextGuard = true })
711
+ end
712
+ end
713
+
714
+ --[[
715
+ Read everything before writing anything. A configure call that raised halfway would leave
716
+ half a config applied and no way to tell which half, which is worse than either outcome the
717
+ author expected.
718
+ ]]
719
+ local rules: { [string]: Severity } = {}
720
+ local limits: { [string]: number } = {}
721
+
722
+ if given.rules ~= nil then
723
+ if type(given.rules) ~= "table" then
724
+ error(`nw.configure: \`rules\` is a table of rule names, got {typeof(given.rules)}`, 2)
725
+ end
726
+
727
+ for name, value in given.rules :: { [string]: any } do
728
+ rules[name] = readSeverity(name, value)
729
+ end
730
+ end
731
+
732
+ if given.limits ~= nil then
733
+ if type(given.limits) ~= "table" then
734
+ error(`nw.configure: \`limits\` is a table of limit names, got {typeof(given.limits)}`, 2)
735
+ end
736
+
737
+ for name, value in given.limits :: { [string]: any } do
738
+ limits[name] = readLimit(name, value)
739
+ end
740
+ end
741
+
742
+ if given.contextGuard ~= nil and type(given.contextGuard) ~= "boolean" then
743
+ error(`nw.configure: \`contextGuard\` is a boolean, got {typeof(given.contextGuard)}`, 2)
744
+ end
745
+
746
+ for name, value in rules do
747
+ severity[name] = value
748
+ end
749
+
750
+ for name, value in limits do
751
+ limit[name] = value
752
+ end
753
+
754
+ if given.contextGuard ~= nil then
755
+ contextGuard = given.contextGuard
756
+ end
757
+ end
758
+
759
+ --[=[
760
+ @within Config
761
+ @function severityOf
762
+ @param rule string
763
+ @return Severity
764
+ @private
765
+
766
+ One table index. Called on the rejection path, which is cold by construction — the hot path is
767
+ the packet that was not refused.
768
+ ]=]
769
+ function Config.severityOf(rule: string): Severity
770
+ return severity[rule] or "off"
771
+ end
772
+
773
+ --[=[
774
+ @within Config
775
+ @function raises
776
+ @param rule string
777
+ @return boolean
778
+ @private
779
+
780
+ Whether this rule at its current severity should raise. True only for a declaration rule set to
781
+ `"error"`; a wire rule answers false at every severity, which is G4 expressed as a function
782
+ rather than as a convention someone has to remember.
783
+ ]=]
784
+ function Config.raises(rule: string): boolean
785
+ local entry = RULES[rule]
786
+
787
+ return entry ~= nil and not entry.wire and severity[rule] == "error"
788
+ end
789
+
790
+ --[=[
791
+ @within Config
792
+ @function limitOf
793
+ @param name string
794
+ @return number
795
+ @private
796
+ ]=]
797
+ function Config.limitOf(name: string): number
798
+ return limit[name]
799
+ end
800
+
801
+ --[=[
802
+ @within Config
803
+ @function contextGuard
804
+ @return boolean?
805
+ @private
806
+
807
+ `nil` means "decide as usual", which is Studio-only. A game that sets it explicitly gets what
808
+ it asked for in both places.
809
+ ]=]
810
+ function Config.contextGuard(): boolean?
811
+ return contextGuard
812
+ end
813
+
814
+ --[=[
815
+ @within Config
816
+ @function snapshot
817
+ @return Snapshot
818
+
819
+ The current settings, frozen. Useful in a bug report, and safe to hand anywhere: mutating what
820
+ comes back cannot reach the live tables, so a diagnostic screen cannot become a way to
821
+ reconfigure the library by accident.
822
+ ]=]
823
+ function Config.snapshot(): Snapshot
824
+ local taken = {
825
+ rules = table.clone(severity),
826
+ limits = table.clone(limit),
827
+ contextGuard = contextGuard,
828
+ }
829
+
830
+ table.freeze(taken.rules)
831
+ table.freeze(taken.limits)
832
+ table.freeze(taken)
833
+
834
+ --[[ Frozen, so the value is read-only where the annotation is not; the cast says that and
835
+ nothing more. The tables inside are clones, so nothing here aliases the live config. ]]
836
+ return taken :: Snapshot
837
+ end
838
+
839
+ --[=[
840
+ @within Config
841
+ @function describe
842
+ @return { Described }
843
+
844
+ Every rule, what it is set to, what it defaults to, and one line on what it reports. This is the
845
+ list to print when someone asks what they can configure.
846
+ ]=]
847
+ function Config.describe(): { Described }
848
+ local names = {}
849
+
850
+ for name in RULES do
851
+ table.insert(names, name)
852
+ end
853
+
854
+ table.sort(names)
855
+
856
+ local described = table.create(#names) :: { Described }
857
+
858
+ for index, name in names do
859
+ local rule = RULES[name]
860
+
861
+ described[index] = {
862
+ rule = name,
863
+ severity = severity[name],
864
+ default = rule.default,
865
+ wire = rule.wire,
866
+ summary = rule.summary,
867
+ }
868
+ end
869
+
870
+ return described
871
+ end
872
+
873
+ --[=[
874
+ @within Config
875
+ @function reset
876
+ @private
877
+
878
+ Back to defaults. Exists for tests; a game has no reason to call it.
879
+ ]=]
880
+ function Config.reset()
881
+ restoreDefaults()
882
+ end
883
+
884
+ return Config