@rbxts/netweave 0.0.0-stage → 0.1.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.
@@ -0,0 +1,493 @@
1
+ --!strict
2
+ --!optimize 2
3
+
4
+ --[=[
5
+ @class Observer
6
+
7
+ Where rejections go. Nothing in netweave is thrown at the game: a packet that fails to parse,
8
+ exceeds its budget or fails authorization is delivered here as a value.
9
+
10
+ ```lua
11
+ nw.observe(function(rejection)
12
+ Analytics:report(rejection.channel, rejection.stage, rejection.reason)
13
+ end)
14
+ ```
15
+
16
+ This is also what makes rejection rates *measurable*. `RESEARCH §3-G6` records that no surveyed
17
+ library reports them, and `§3.7-K` records what that costs: Warp blackholes a player whose
18
+ packet fails and nothing anywhere says so.
19
+ ]=]
20
+
21
+ --[[
22
+ Guarantee G4 lives here. Wire data must never reach `error()`, so every receive-path failure
23
+ has to have somewhere to go that is not the call stack — otherwise one hostile packet aborts
24
+ the batch, which is the failure Blink and Zap both have (`RESEARCH §3.8-R`).
25
+ ]]
26
+
27
+ local Config = require("./Config")
28
+
29
+ local Observer = {}
30
+
31
+ --[=[
32
+ @type Stage "parse" | "budget" | "authorize" | "handler" | "queue" | "send" | "protocol" | "query" | "direction" | "replicate"
33
+ @within Observer
34
+
35
+ How far a packet got before it was refused.
36
+
37
+ | Stage | Meaning |
38
+ |---|---|
39
+ | `parse` | the bytes did not decode against the channel's schema |
40
+ | `budget` | the sender is over the channel's declared `rate` |
41
+ | `authorize` | the payload decoded and was in budget, and a policy said no |
42
+ | `handler` | the packet was delivered and the game's own handler threw |
43
+ | `queue` | nothing is listening on that channel yet, and the backlog is full |
44
+ | `send` | netweave refused to put a packet on the wire |
45
+ | `protocol` | the peer is on a different set of channel definitions |
46
+ | `query` | a `nw.query` call came back without an answer |
47
+
48
+ The first three are worth separating because they mean different things about the sender.
49
+ `parse` is a stale client or an attacker; `budget` is a flood; `authorize` is a player asking
50
+ for something they are not entitled to.
51
+
52
+ `handler` and `queue` are about this game rather than the sender: one says a handler threw, the
53
+ other that no handler is attached and the backlog has started dropping. Both are the kind of
54
+ thing that is otherwise noticed as "some packets do not seem to arrive".
55
+
56
+ `send` points the other way entirely — netweave refusing *this* game's own outgoing packet. The
57
+ only case in M2 is an unreliable payload over Roblox's size limit, which Roblox enforces by
58
+ dropping silently, so without a signal here it is invisible from both ends (`RESEARCH §3.7-F`).
59
+
60
+ `protocol` is the odd one: it fires once when a peer joins on a hash that does not match, not per
61
+ packet. No surveyed library checks this at all, so the failure it replaces is a stale client that
62
+ connects successfully and is then refused on every packet forever, with nothing saying why.
63
+
64
+ `query` is the caller's side of a request that produced no answer — a timeout, or a refusal the
65
+ server sent back as a code. The refusal itself was already reported on the server at whichever
66
+ stage made it, so this is not a duplicate: it is the same event seen from the end that was
67
+ waiting, which is the end that has to decide what to do about it.
68
+ `direction` is guarantee G6 arriving on the wire. The declaration makes a direction violation an
69
+ analysis error in the game's own code, which is where it belongs and where it stops nothing a
70
+ *peer* does — a client can put any id in a packet it writes. Until M3 phase 9 the server decoded
71
+ and queued those, and could not budget them either, because the classes they name declare no
72
+ rate.
73
+ ]=]
74
+ --[[ Defined in `Config` and re-exported here, where a game reads it: the modules that produce a
75
+ stage sit below the observer, and `Config` is the leaf both halves can reach (finding 48). ]]
76
+ export type Stage = Config.Stage
77
+
78
+ --[=[
79
+ @interface Rejection
80
+ @within Observer
81
+ .channel string -- the qualified name, `"combat.fireWeapon"`
82
+ .player Player? -- nil for a rejection on the client, or before the sender is known
83
+ .stage Stage
84
+ .reason string
85
+ .bytes number -- payload size, for attributing bandwidth to traffic that was thrown away
86
+
87
+ :::caution
88
+ The record is **reused**. Read what you need inside the observer; do not retain it. Under a
89
+ flood the rejection path is the hot path, and allocating one table per refused packet would
90
+ hand an attacker a way to make refusing cost more than accepting.
91
+ :::
92
+ ]=]
93
+ export type Rejection = {
94
+ channel: string,
95
+ player: Player?,
96
+ stage: Stage,
97
+ reason: string,
98
+ bytes: number,
99
+ }
100
+
101
+ export type Observer = (rejection: Rejection) -> ()
102
+
103
+ local observers: { Observer } = {}
104
+ local count = 0
105
+
106
+ --[[
107
+ Removal is a tombstone, because `emit` may be walking the list when it happens.
108
+
109
+ An observer that stops observing from inside its own call is ordinary code — "warn once, then
110
+ detach" — and `table.remove` used to shift the observer behind it into the index the loop had
111
+ already passed, so that one was skipped and the last index read `nil`. `xpcall(nil, ...)` does
112
+ not raise, so the miss was silent (M3 phase 9).
113
+
114
+ The slot is overwritten with `NOOP` instead and the list is compacted the next time nothing is
115
+ iterating it, which is a bounded amount of work with no allocation and no ordering to get wrong.
116
+ ]]
117
+ local function NOOP() end
118
+
119
+ local emitting = 0
120
+ local tombstones = false
121
+
122
+ local function compact()
123
+ if not tombstones or emitting > 0 then
124
+ return
125
+ end
126
+
127
+ local kept = 0
128
+
129
+ for index = 1, count do
130
+ local observer = observers[index]
131
+
132
+ if observer ~= NOOP then
133
+ kept += 1
134
+ observers[kept] = observer
135
+ end
136
+ end
137
+
138
+ for index = kept + 1, count do
139
+ observers[index] = nil
140
+ end
141
+
142
+ count = kept
143
+ tombstones = false
144
+ end
145
+
146
+ --[[ One record, refilled per rejection. See the caution on `Rejection`. ]]
147
+ local record: Rejection = {
148
+ channel = "",
149
+ player = nil,
150
+ stage = "parse",
151
+ reason = "",
152
+ bytes = 0,
153
+ }
154
+
155
+ --[[
156
+ An observer is game code and can therefore throw. If it did so straight into the receive loop
157
+ it would abort the batch — the exact failure G4 exists to prevent, reintroduced by the
158
+ mechanism meant to report it. `xpcall` with a shared handler allocates no closure per call.
159
+ ]]
160
+ local function report(message: string): string
161
+ return message
162
+ end
163
+
164
+ --[[
165
+ The default sink, and the reason `nw.observe` is no longer the only way to find out.
166
+
167
+ M2 shipped every one of these stages and then returned early when nothing was observing, so a
168
+ game that attached no observer got silent drops at all six. That is precisely what
169
+ `RESEARCH §3.7-K` faults Warp for — a player blackholed with nothing anywhere saying so — and
170
+ building the signal and not raising it reproduces the fault with extra steps.
171
+
172
+ It goes quiet on its own. One channel and stage prints `repeatsPerDiagnostic` times and then
173
+ says it is done, because the failure mode of a default-on log is that a refusal storm becomes
174
+ the outage. `"error"` is the opt-in to every occurrence, and even there nothing raises: these
175
+ are rejections carrying wire data, and G4 has no exceptions.
176
+ ]]
177
+ local seen: { [string]: number } = {}
178
+
179
+ --[[ Injected for the same reason `Budget` injects its clock: `warn` writes somewhere a test cannot
180
+ read, so a sink that is only ever eyeballed is a sink nobody has asserted. Defaults to `warn`
181
+ and is private. ]]
182
+ local sink: (string) -> () = warn
183
+
184
+ --[[
185
+ Counters, kept because the sink deliberately goes quiet.
186
+
187
+ A default sink that reported every refusal would become the outage under a flood, so it prints
188
+ three times per channel and stage and then stops. That is right for a console and useless for a
189
+ question like "is this channel refusing more than it did an hour ago" — which is the question
190
+ that distinguishes a bug from an attack, and the one `RESEARCH §3-G6` says nobody can answer.
191
+
192
+ Two integers per channel and stage. The table for a channel is allocated on its first refusal
193
+ and refilled after that, so a sustained flood allocates nothing: under load the rejection path
194
+ is the hot path, and making refusal cost more than acceptance is how a limiter becomes an
195
+ amplifier.
196
+ ]]
197
+ type Counter = { count: number, bytes: number }
198
+
199
+ local tallies: { [string]: { [string]: Counter } } = {}
200
+ local total = 0
201
+ local since = os.clock()
202
+
203
+ --[[ One integer per channel that has ever been paced, incremented in place: a client that sends an
204
+ intent every frame against its rate pays a table read here, not an allocation. ]]
205
+ local paced: { [string]: number } = {}
206
+
207
+ --[=[
208
+ @within Observer
209
+ @function pace
210
+ @param channel string -- the qualified name of the intent channel
211
+ @private
212
+
213
+ Counts an intent send the client held to its declared rate. Called by the transport's pacer;
214
+ read back through [Observer.diagnostics] as `paced`.
215
+ ]=]
216
+ function Observer.pace(channel: string)
217
+ paced[channel] = (paced[channel] or 0) + 1
218
+ end
219
+
220
+ local function tally(channel: string, stage: Stage, bytes: number)
221
+ local byStage = tallies[channel]
222
+
223
+ if not byStage then
224
+ byStage = {}
225
+ tallies[channel] = byStage
226
+ end
227
+
228
+ local entry = byStage[stage]
229
+
230
+ if not entry then
231
+ byStage[stage] = { count = 1, bytes = bytes }
232
+ total += 1
233
+ return
234
+ end
235
+
236
+ entry.count += 1
237
+ entry.bytes += bytes
238
+ total += 1
239
+ end
240
+
241
+ local function announce(channel: string, stage: Stage, reason: string, player: Player?)
242
+ local level = Config.severityOf(stage)
243
+
244
+ if level == "off" then
245
+ return
246
+ end
247
+
248
+ --[[
249
+ Counted **before** the severity is looked at, and that ordering is the whole point.
250
+
251
+ `error` used to print and return above this, because two stages declare that default and
252
+ both argued the same way: nobody sends on a channel they receive on by accident, and a
253
+ protocol mismatch means that client cannot play at all, so the fiftieth is worth as much as
254
+ the first. The argument holds for the diagnostic and not for the cost. Both are **wire**
255
+ stages, which is to say stages whose rate a peer chooses — and an `error` carries a
256
+ `debug.traceback`, so a client sending anything at all on a `state` id bought a stack walk
257
+ and a console line per packet. Found by running the Studio suite, where 2,000 refusals from
258
+ one test filled the output window (M3 phase 9).
259
+
260
+ Every level counts and every level suppresses now. What `error` keeps is the traceback and
261
+ the louder sink; what it loses is the ability to be asked for fifty thousand of them. The
262
+ "fourth player is as stuck as the first" case the `protocol` comment worried about is
263
+ answered by `nw.observe`, which receives every one, and by `nw.diagnostics()`, which counts
264
+ them — both of which the suppression line says out loud.
265
+ ]]
266
+ local key = `{channel}\0{stage}`
267
+ local times = (seen[key] or 0) + 1
268
+ local ceiling = Config.limitOf("repeatsPerDiagnostic")
269
+
270
+ if times > ceiling then
271
+ return
272
+ end
273
+
274
+ seen[key] = times
275
+
276
+ local who = if player then ` from {player.Name}` else ""
277
+ local suffix = if times == ceiling
278
+ then ` (further "{stage}" reports for {channel} are suppressed; nw.observe still receives them)`
279
+ else ""
280
+
281
+ if level == "error" then
282
+ sink(`[netweave] {channel} refused at {stage}{who}: {reason}{suffix}\n{debug.traceback("", 2)}`)
283
+ return
284
+ end
285
+
286
+ sink(`[netweave] {channel} refused at {stage}{who}: {reason}{suffix}`)
287
+ end
288
+
289
+ --[=[
290
+ @within Observer
291
+ @function observe
292
+ @param observer (rejection: Rejection) -> ()
293
+ @return () -> () -- call to stop observing
294
+
295
+ Registers a rejection observer. Several may be registered; each is called in registration
296
+ order, and one that throws does not stop the others or the batch.
297
+
298
+ ```lua
299
+ local stop = nw.observe(function(rejection)
300
+ if rejection.stage == "authorize" then
301
+ warn(`{rejection.player} was refused {rejection.channel}: {rejection.reason}`)
302
+ end
303
+ end)
304
+ ```
305
+ ]=]
306
+ function Observer.observe(observer: Observer): () -> ()
307
+ count += 1
308
+ observers[count] = observer
309
+
310
+ local removed = false
311
+
312
+ return function()
313
+ if removed then
314
+ return
315
+ end
316
+
317
+ removed = true
318
+
319
+ for index = 1, count do
320
+ if observers[index] == observer then
321
+ observers[index] = NOOP
322
+ tombstones = true
323
+ break
324
+ end
325
+ end
326
+
327
+ compact()
328
+ end
329
+ end
330
+
331
+ --[=[
332
+ @within Observer
333
+ @function emit
334
+ @param channel string
335
+ @param player Player?
336
+ @param stage Stage
337
+ @param reason string
338
+ @param bytes number
339
+ @private
340
+
341
+ Fills the shared record and hands it to every observer. Called by the transport, not by games.
342
+ ]=]
343
+ function Observer.emit(channel: string, player: Player?, stage: Stage, reason: string, bytes: number)
344
+ record.channel = channel
345
+ record.player = player
346
+ record.stage = stage
347
+ record.reason = reason
348
+ record.bytes = bytes
349
+
350
+ tally(channel, stage, bytes)
351
+
352
+ compact()
353
+
354
+ emitting += 1
355
+
356
+ for index = 1, count do
357
+ local observer = observers[index]
358
+
359
+ if observer ~= NOOP then
360
+ xpcall(observer, report, record)
361
+ end
362
+ end
363
+
364
+ emitting -= 1
365
+
366
+ announce(channel, stage, reason, player)
367
+ end
368
+
369
+ --[=[
370
+ @interface Tally
371
+ @within Observer
372
+ .count number -- refusals at this channel and stage
373
+ .bytes number -- their payloads, added up
374
+
375
+ Bytes are counted whether or not the packet was ever decoded, because a refused packet still
376
+ crossed the wire and a figure that only counted what was accepted would understate exactly the
377
+ traffic worth looking at.
378
+ ]=]
379
+ export type Tally = { read count: number, read bytes: number }
380
+
381
+ --[=[
382
+ @interface Diagnostics
383
+ @within Observer
384
+ .since number -- `os.clock` when counting last started
385
+ .total number -- refusals at every channel and stage
386
+ .channels { [string]: { [string]: Tally } } -- qualified name, then stage
387
+
388
+ What [Observer.diagnostics] returns. Frozen at every level.
389
+ ]=]
390
+ export type Diagnostics = {
391
+ read since: number,
392
+ read total: number,
393
+ read channels: { read [string]: { read [string]: Tally } },
394
+ --[[ Intent sends the client held back to the declared rate, per channel. Not refusals — a held
395
+ value is superseded, never lost — so they are beside the counters rather than in them
396
+ (`PLAN-M5` D-6). ]]
397
+ read paced: { read [string]: number },
398
+ }
399
+
400
+ --[=[
401
+ @within Observer
402
+ @function diagnostics
403
+ @return Diagnostics
404
+
405
+ Every refusal since the counters were last reset, by channel and stage.
406
+
407
+ ```lua
408
+ local seen = nw.diagnostics()
409
+
410
+ for channel, stages in seen.channels do
411
+ for stage, tally in stages do
412
+ print(channel, stage, tally.count, tally.bytes)
413
+ end
414
+ end
415
+ ```
416
+
417
+ The console sink goes quiet after a few reports so a flood does not become the outage, which
418
+ makes this the only way to answer "is this channel refusing more than it was" — the question
419
+ that separates a bug from an attack. `RESEARCH §3-G6` records that no surveyed library can
420
+ answer it.
421
+
422
+ :::note Built on read, not on the rejection path
423
+ The snapshot is assembled here rather than kept assembled, so counting a refusal stays two
424
+ increments. Call it on a timer or when a diagnostic screen opens, not per packet.
425
+ :::
426
+
427
+ :::caution
428
+ Frozen at every level, so it cannot be mutated back into the live counters — a diagnostic
429
+ screen must not become a way to reset them by accident. [Observer.reset] is how they are
430
+ cleared, and it drops observers too.
431
+ :::
432
+ ]=]
433
+ function Observer.diagnostics(): Diagnostics
434
+ local channels: { [string]: { [string]: Tally } } = {}
435
+
436
+ for channel, byStage in tallies do
437
+ local copied: { [string]: Tally } = {}
438
+
439
+ for stage, entry in byStage do
440
+ copied[stage] = table.freeze({ count = entry.count, bytes = entry.bytes })
441
+ end
442
+
443
+ channels[channel] = table.freeze(copied)
444
+ end
445
+
446
+ local taken = {
447
+ since = since,
448
+ total = total,
449
+ channels = table.freeze(channels),
450
+ paced = table.freeze(table.clone(paced)),
451
+ }
452
+
453
+ table.freeze(taken)
454
+
455
+ --[[ Frozen, so the value is read-only where the constructor is not; the cast says that and
456
+ nothing more. ]]
457
+ return taken :: any
458
+ end
459
+
460
+ --[=[
461
+ @within Observer
462
+ @function setSink
463
+ @param replacement ((line: string) -> ())?
464
+ @private
465
+
466
+ Replaces where the default sink writes. `nil` puts `warn` back, and so does [Observer.reset].
467
+ Exists so the severities and the repeat suppression can be asserted rather than eyeballed.
468
+ ]=]
469
+ function Observer.setSink(replacement: ((string) -> ())?)
470
+ sink = replacement or warn
471
+ end
472
+
473
+ --[=[
474
+ @within Observer
475
+ @function reset
476
+ @private
477
+
478
+ Drops every observer. Exists for tests; a game has no reason to call it.
479
+ ]=]
480
+ function Observer.reset()
481
+ table.clear(observers)
482
+ table.clear(seen)
483
+ table.clear(tallies)
484
+ table.clear(paced)
485
+ count = 0
486
+ emitting = 0
487
+ tombstones = false
488
+ total = 0
489
+ since = os.clock()
490
+ sink = warn
491
+ end
492
+
493
+ return Observer