@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,120 @@
1
+ --!strict
2
+ --!optimize 2
3
+
4
+ --[=[
5
+ @class Pacer
6
+
7
+ A client's `intent` sends, held to the channel's declared rate.
8
+
9
+ An intent is continuous input — aim, movement, a held button — and the class already says stale
10
+ input has no value: the server delivers at most one value per player per tick and coalesces the
11
+ rest. What it could not do was stop the client *sending* the rest. A `send` in every
12
+ `RenderStepped` against `rate = 30` was forty refusals a second at stage `budget`, reported on the
13
+ server, invisible on the client, and every one of them wasted bytes and read as an attack.
14
+
15
+ So the client view holds the newest value per intent channel and pushes it at the declared rate,
16
+ through the same token bucket `Budget` runs on the server, keyed by channel rather than by sender.
17
+ A held value is superseded, never dropped and never reported; `nw.diagnostics()` counts what was
18
+ held per channel so a game that over-sends can see it without a refusal (`PLAN-M5` D-6).
19
+
20
+ Internal. `Driver` builds one for the client and asks it once a frame, before the flush.
21
+ ]=]
22
+
23
+ --[[
24
+ Not for `signal` or `command`, where every packet is a packet and a held one would be a lost
25
+ one. The server's budget stays the enforcement; this is the courtesy that keeps honest traffic
26
+ quiet on it, and a client that bypasses the view still meets the server's.
27
+ ]]
28
+
29
+ local Budget = require("./Budget")
30
+ local Observer = require("../api/Observer")
31
+
32
+ local Pacer = {}
33
+
34
+ --[=[
35
+ @interface Pacer
36
+ @within Pacer
37
+ .send (channel: any, value: any) -> boolean -- pushed now (true), or held for the next tick that has a token (false)
38
+ .tick () -> () -- push every held value whose channel has a token again
39
+ .held (channel: any) -> any? -- what is waiting on a channel, for tests
40
+ ]=]
41
+ export type Pacer = {
42
+ send: (channel: any, value: any) -> boolean,
43
+ tick: () -> (),
44
+ held: (channel: any) -> any?,
45
+ }
46
+
47
+ --[[ `Budget` is keyed by sender, and the client has one peer, so one sentinel is every channel's
48
+ sender here. A table rather than `nil`, because `admit` treats a nil sender as "no budget". ]]
49
+ local SELF = table.freeze({})
50
+
51
+ --[=[
52
+ @within Pacer
53
+ @function new
54
+ @param push (channel: any, value: any) -> () -- what a send that is admitted does
55
+ @param clock (() -> number)? -- injectable for tests; `os.clock` otherwise
56
+ @return Pacer
57
+ ]=]
58
+ function Pacer.new(push: (channel: any, value: any) -> (), clock: (() -> number)?): Pacer
59
+ local budget = Budget.new(clock)
60
+
61
+ --[[ The newest value per channel that is waiting for a token, and the channels waiting, as an
62
+ array so a tick walks only those and a channel that never over-sends costs nothing here. ]]
63
+ local held: { [any]: any } = {}
64
+ local waiting: { any } = {}
65
+
66
+ local function release(channel: any)
67
+ held[channel] = nil
68
+
69
+ local count = #waiting
70
+
71
+ for index = 1, count do
72
+ if waiting[index] == channel then
73
+ waiting[index] = waiting[count]
74
+ waiting[count] = nil
75
+ return
76
+ end
77
+ end
78
+ end
79
+
80
+ return {
81
+ send = function(channel: any, value: any): boolean
82
+ if budget.admit(channel, SELF, 0) == nil then
83
+ --[[ Admitted, so this is the newest and anything held is older than it. ]]
84
+ if held[channel] ~= nil then
85
+ release(channel)
86
+ end
87
+
88
+ push(channel, value)
89
+ return true
90
+ end
91
+
92
+ if held[channel] == nil then
93
+ table.insert(waiting, channel)
94
+ end
95
+
96
+ held[channel] = value
97
+ Observer.pace(channel.qualified)
98
+ return false
99
+ end,
100
+
101
+ tick = function()
102
+ --[[ Backwards, because a channel that goes out is swap-removed from the end. ]]
103
+ for index = #waiting, 1, -1 do
104
+ local channel = waiting[index]
105
+
106
+ if budget.admit(channel, SELF, 0) == nil then
107
+ local value = held[channel]
108
+ release(channel)
109
+ push(channel, value)
110
+ end
111
+ end
112
+ end,
113
+
114
+ held = function(channel: any): any?
115
+ return held[channel]
116
+ end,
117
+ }
118
+ end
119
+
120
+ return Pacer
@@ -0,0 +1,535 @@
1
+ --!strict
2
+ --!optimize 2
3
+
4
+ --[=[
5
+ @class Query
6
+
7
+ Request and response: the call ids, the deadlines, and the accounting that keeps a slow handler
8
+ from becoming a way to hold the server.
9
+
10
+ Internal.
11
+ ]=]
12
+
13
+ --[[
14
+ This module exists because of one measured gap. Blink (`Generator/init.luau:723-745`) and Zap
15
+ (`client.rs:1329`) both key their pending calls by a **u8**, so 256 unanswered calls is a hard
16
+ ceiling and the 257th is dropped with a raise — and neither has a timeout at all
17
+ (`grep -ri timeout blink/src` returns nothing). The pattern in both is `Calls[id] =
18
+ coroutine.running()` then `coroutine.yield()`, so a peer that never answers parks the caller's
19
+ thread for the lifetime of the session. `RESEARCH §3.7-G`.
20
+
21
+ Flamework, from the other side of the ecosystem, has the timeouts and the typed failures and
22
+ pays for them with a Promise per call (`RESEARCH §3.6-A`). §3.7-G calls that "the clearest
23
+ evidence that the structure axis and the byte axis fail in exactly opposite directions".
24
+
25
+ netweave takes the resume-the-thread-directly shape from Blink, the deadlines and the
26
+ per-player cleanup from Flamework, and a **varint** call id from neither, which removes the
27
+ ceiling both of them have.
28
+
29
+ Three bounds live here, and all three are resources an untrusted peer can spend:
30
+
31
+ 1. **In flight, per player.** A query handler is the one handler netweave lets yield, so a
32
+ player whose handler blocks on a datastore holds a thread until it returns. `callsInFlight`
33
+ bounds how many they may hold at once.
34
+ 2. **Outstanding, on the caller.** The same number from the other end: how many answers one
35
+ game may be waiting for.
36
+ 3. **The deadline.** `timeout` is required on the declaration, so there is no unlimited to
37
+ forget to set.
38
+ ]]
39
+
40
+ local Batch = require("./Batch")
41
+ local Config = require("../api/Config")
42
+ local Observer = require("../api/Observer")
43
+
44
+ local Query = {}
45
+
46
+ --[[
47
+ Two varint bytes, and the wrap is what keeps it there.
48
+
49
+ A call id is only ever meaningful while its call is outstanding, and `callsInFlight` caps that
50
+ at 4096 — well under this — so the search for a free id below always terminates and two live
51
+ calls can never collide. Blink and Zap's u8 is the same idea with the ceiling set three orders
52
+ of magnitude lower, and theirs is a hard failure rather than a wrap.
53
+ ]]
54
+ local CALL_MAX = 16383
55
+
56
+ --[[
57
+ What the caller is told, per status code. Deliberately short and deliberately netweave's own
58
+ words: the server's reason for refusing never crosses the wire (`src/transport/Batch.luau`,
59
+ `PLAN-M3` D-12), so there is nothing here to interpolate a policy's message into.
60
+ ]]
61
+ local REASON: { [number]: string } = {
62
+ [Batch.REFUSED] = "the server refused it",
63
+ [Batch.FAILED] = "the handler failed",
64
+ [Batch.UNHANDLED] = "no handler is attached on the server",
65
+ [Batch.BUSY] = "the server is already holding this player's call limit",
66
+ }
67
+ table.freeze(REASON)
68
+
69
+ --[[ One record per outstanding call, on the calling side.
70
+
71
+ This allocates, and it is the same argument `Context.detached` makes: a query has already paid
72
+ for a round trip and a parked thread, so a table to remember what is parked is not the cost
73
+ that matters. The per-packet paths above this one still allocate nothing. ]]
74
+ type Call = {
75
+ thread: thread,
76
+ channel: any,
77
+ deadline: number,
78
+ --[[ Set by `abandon` when the answer arrived and could not be kept. Without it the caller waits
79
+ out the whole timeout and is then told nothing answered, which is a lie about a packet that
80
+ was decoded and discarded. ]]
81
+ reason: string?,
82
+ }
83
+
84
+ --[[ One record per player with a call in flight, on the answering side. The call ids are kept as a
85
+ set rather than a count alone, so that a client repeating an id cannot make the count and the
86
+ reality disagree — see `enter`. ]]
87
+ type Slots = {
88
+ count: number,
89
+ calls: { [number]: true },
90
+ }
91
+
92
+ --[=[
93
+ @interface Config
94
+ @within Query
95
+ .request (channel: any, call: number, value: any) -> () -- put a request on the wire
96
+ .reply (channel: any, who: any, call: number, status: number, value: any?) -> () -- put an answer on the wire
97
+ .spawn (target: any, ...any) -> () -- run a function, or resume a thread
98
+ .clock (() -> number)? -- defaults to `os.clock`
99
+
100
+ `spawn` is injected rather than reached for, because `task` does not exist under lune and this
101
+ module has to be testable there — the same reason `Budget` takes its clock. Roblox passes
102
+ `task.spawn`, which both starts a function on a fresh thread and resumes a parked one; a test
103
+ passes something it can drive by hand.
104
+ ]=]
105
+ export type Config = {
106
+ request: (channel: any, call: number, value: any) -> (),
107
+ reply: (channel: any, who: any, call: number, status: number, value: any?) -> (),
108
+ spawn: (target: any, ...any) -> (),
109
+ clock: (() -> number)?,
110
+ }
111
+
112
+ --[=[
113
+ @interface Queries
114
+ @within Query
115
+
116
+ The half of this module `Inbound` needs. Passed to `Inbound.new` as one record rather than four
117
+ callbacks, so an endpoint either serves queries or does not.
118
+ ]=]
119
+ export type Queries = {
120
+ spawn: (target: any, ...any) -> (),
121
+ enter: (channel: any, who: any, call: number) -> boolean,
122
+ answer: (channel: any, who: any, call: number, status: number, value: any?) -> (),
123
+ refuse: (channel: any, who: any, call: number, status: number) -> (),
124
+ answered: (channel: any, call: number, status: number, value: any?) -> (),
125
+ abandon: (channel: any, call: number, reason: string) -> (),
126
+ }
127
+
128
+ export type Query = {
129
+ spawn: (target: any, ...any) -> (),
130
+ enter: (channel: any, who: any, call: number) -> boolean,
131
+ answer: (channel: any, who: any, call: number, status: number, value: any?) -> (),
132
+ refuse: (channel: any, who: any, call: number, status: number) -> (),
133
+ answered: (channel: any, call: number, status: number, value: any?) -> (),
134
+
135
+ abandon: (channel: any, call: number, reason: string) -> (),
136
+
137
+ invoke: (channel: any, args: any) -> (any?, string?),
138
+ tick: () -> (),
139
+ forget: (who: any) -> (),
140
+
141
+ outstanding: () -> number,
142
+ inflight: (who: any) -> number,
143
+ }
144
+
145
+ --[=[
146
+ @within Query
147
+ @function new
148
+ @param config Config
149
+ @return Query
150
+ ]=]
151
+ function Query.new(config: Config): Query
152
+ local request = config.request
153
+ local reply = config.reply
154
+ local spawn = config.spawn
155
+ local now = config.clock or os.clock
156
+
157
+ --[[ The calling side. ]]
158
+ local pending: { [number]: Call } = {}
159
+ local outstanding = 0
160
+ local nextCall = 0
161
+
162
+ --[[ The answering side. ]]
163
+ local slots: { [any]: Slots } = {}
164
+
165
+ --[[ Reused by `tick`, which cannot resume a thread while it is walking `pending` — see there. ]]
166
+ local expired: { number } = {}
167
+
168
+ local function report(channel: any, who: any?, reason: string)
169
+ --[[ Zero bytes, and that is honest rather than lazy: a timeout is the absence of a packet
170
+ and a refusal code arrived as a packet the reader already counted. Charging either to
171
+ this channel's byte tally would double-count the one and invent the other. ]]
172
+ Observer.emit(channel.qualified, who, "query", reason, 0)
173
+ end
174
+
175
+ --[[
176
+ Put an answer on the wire, whatever happens.
177
+
178
+ `reply` reaches `Batch.writeReply`, which encodes the handler's return value — and a handler
179
+ returning something the `returns` schema forbids raises there, the same as any other encode.
180
+ That raise is on a thread this module spawned, inside the receive path's blast radius, so it
181
+ is caught and converted into the status the caller was going to need anyway.
182
+ ]]
183
+ local function send(channel: any, who: any, call: number, status: number, value: any?)
184
+ if status == Batch.OK then
185
+ local ok, failure = pcall(reply, channel, who, call, Batch.OK, value)
186
+
187
+ if ok then
188
+ return
189
+ end
190
+
191
+ Observer.emit(
192
+ channel.qualified,
193
+ who,
194
+ "handler",
195
+ `the answer did not encode: {tostring(failure)}`,
196
+ 0
197
+ )
198
+
199
+ status = Batch.FAILED
200
+ end
201
+
202
+ --[[ A status-only reply has no payload to encode, so this cannot fail for a reason the game
203
+ caused. It is still guarded: this runs on the receive path's behalf and G4 says nothing
204
+ there raises, so a surprise here has to become a report rather than an error. ]]
205
+ local ok, failure = pcall(reply, channel, who, call, status, nil)
206
+
207
+ if not ok then
208
+ Observer.emit(channel.qualified, who, "send", `the reply did not go out: {tostring(failure)}`, 0)
209
+ end
210
+ end
211
+
212
+ local self: Query
213
+
214
+ self = {
215
+ spawn = spawn,
216
+
217
+ --[=[
218
+ @within Query
219
+ @function enter
220
+
221
+ Take a call slot for this player, or refuse the call and say so.
222
+
223
+ Called on the receive path, synchronously, before anything is spawned — so a player over
224
+ the limit costs a reply and nothing else.
225
+ ]=]
226
+ enter = function(channel: any, who: any, call: number): boolean
227
+ local record = slots[who]
228
+
229
+ if not record then
230
+ record = { count = 0, calls = {} }
231
+ slots[who] = record
232
+ end
233
+
234
+ --[[
235
+ A repeated call id from the same player, refused.
236
+
237
+ Without this the count and the set disagree: two entries increment `count` twice and
238
+ set one key, the first answer clears that key, and the second finds nothing to clear
239
+ and never gives the slot back. Sixteen repeats of one id would retire this player's
240
+ call budget permanently, which is a denial of service a client writes in one line.
241
+ ]]
242
+ if record.calls[call] then
243
+ report(channel, who, `call id {call} is already in flight`)
244
+ send(channel, who, call, Batch.REFUSED, nil)
245
+ return false
246
+ end
247
+
248
+ local ceiling = Config.limitOf("callsInFlight")
249
+
250
+ if record.count >= ceiling then
251
+ --[[ The bound is per player rather than per channel. The resource is a thread parked
252
+ inside a handler, and a thread does not become cheaper because it is parked in a
253
+ different handler — so one player's slow query cannot be paid for out of their
254
+ own budget on another channel, which is the point. ]]
255
+ report(channel, who, `{record.count} calls already in flight, the limit is {ceiling}`)
256
+ send(channel, who, call, Batch.BUSY, nil)
257
+ return false
258
+ end
259
+
260
+ record.count += 1
261
+ record.calls[call] = true
262
+
263
+ return true
264
+ end,
265
+
266
+ --[=[
267
+ @within Query
268
+ @function answer
269
+
270
+ The end of a handler that took a slot. Releases it and replies.
271
+
272
+ A call whose player has left is dropped here rather than written: `Outbound.forget` has
273
+ already discarded their parked batch, and `switchTo` would build a new one for a
274
+ destination that will never be flushed to anyone.
275
+ ]=]
276
+ answer = function(channel: any, who: any, call: number, status: number, value: any?)
277
+ local record = slots[who]
278
+
279
+ if not record or not record.calls[call] then
280
+ return
281
+ end
282
+
283
+ record.calls[call] = nil
284
+ record.count -= 1
285
+
286
+ if record.count == 0 then
287
+ slots[who] = nil
288
+ end
289
+
290
+ send(channel, who, call, status, value)
291
+ end,
292
+
293
+ --[=[
294
+ @within Query
295
+ @function refuse
296
+
297
+ An answer for a call that never took a slot — refused while the batch that carried it was
298
+ still being read, so the player is by definition still here.
299
+ ]=]
300
+ refuse = function(channel: any, who: any, call: number, status: number)
301
+ send(channel, who, call, status, nil)
302
+ end,
303
+
304
+ --[=[
305
+ @within Query
306
+ @function invoke
307
+ @param channel Channel
308
+ @param args any
309
+ @return (any?, string?)
310
+
311
+ Send a request and park this thread until the answer, the refusal, or the deadline.
312
+ ]=]
313
+ invoke = function(channel: any, args: any): (any?, string?)
314
+ --[[ Checked before anything is written. The alternative is a request on the wire that
315
+ nobody is waiting for, answered into a pending table that has no entry for it. ]]
316
+ if not coroutine.isyieldable() then
317
+ error(
318
+ `{channel.qualified}:invoke waits for the answer, so it has to be called from a `
319
+ .. `thread that can yield. Wrap the call: task.spawn(function() ... end).`,
320
+ 3
321
+ )
322
+ end
323
+
324
+ local ceiling = Config.limitOf("callsInFlight")
325
+
326
+ if outstanding >= ceiling then
327
+ --[[ The caller's own bound, and it is the same number as the server's because it
328
+ counts the same thing from the other end: this player's unanswered calls. A game
329
+ that trips it is issuing requests faster than the server answers them, and the
330
+ honest thing is to say so now rather than at the deadline. ]]
331
+ local reason = `{outstanding} calls already waiting, the limit is {ceiling}`
332
+ report(channel, nil, reason)
333
+ return nil, reason
334
+ end
335
+
336
+ local call = nextCall
337
+
338
+ --[[ Wrapping, and skipping anything still outstanding. `callsInFlight` caps at 4096 and
339
+ the id space is 16383, so this terminates on the first or second try and can never
340
+ hand out an id another call is still waiting on. ]]
341
+ repeat
342
+ call = if call >= CALL_MAX then 1 else call + 1
343
+ until pending[call] == nil
344
+
345
+ nextCall = call
346
+
347
+ --[[ The request goes out before the record exists. A value the schema forbids raises
348
+ here, the same as `send` on any other class does — and this order is what makes that
349
+ raise leave nothing behind: no pending entry, no slot, no id to reclaim. ]]
350
+ request(channel, call, args)
351
+
352
+ pending[call] = {
353
+ thread = coroutine.running(),
354
+ channel = channel,
355
+ deadline = now() + channel.timeout,
356
+ reason = nil,
357
+ }
358
+
359
+ outstanding += 1
360
+
361
+ return coroutine.yield()
362
+ end,
363
+
364
+ --[=[
365
+ @within Query
366
+ @function answered
367
+
368
+ A reply arrived. Resumes whoever is waiting for it.
369
+ ]=]
370
+ answered = function(channel: any, call: number, status: number, value: any?)
371
+ local record = pending[call]
372
+
373
+ --[[ A reply nobody is waiting for: the call already timed out, or the server answered
374
+ it twice. Dropped without a report — the timeout was reported when it fired, and
375
+ saying so a second time would make a channel that recovered look like one that
376
+ failed twice. ]]
377
+ if not record then
378
+ return
379
+ end
380
+
381
+ --[[ The id is the caller's own and the channel came off the wire, so this pairs them
382
+ before resuming. It is not a hostile case — only the server sends replies — but a
383
+ resumed thread receiving another channel's answer is the kind of wrong that would
384
+ be diagnosed as a codec bug. ]]
385
+ if record.channel ~= channel then
386
+ return
387
+ end
388
+
389
+ pending[call] = nil
390
+ outstanding -= 1
391
+
392
+ if status == Batch.OK then
393
+ spawn(record.thread, value, nil)
394
+ return
395
+ end
396
+
397
+ local reason = REASON[status] or `refused with status {status}`
398
+ report(channel, nil, reason)
399
+ spawn(record.thread, nil, reason)
400
+ end,
401
+
402
+ --[=[
403
+ @within Query
404
+ @function abandon
405
+ @param channel Channel
406
+ @param call number
407
+ @param reason string
408
+
409
+ Give up on a call whose answer arrived and could not be kept.
410
+
411
+ The only caller is the pending-set ceiling: a batch past `pendingPerBatch` stops, and if
412
+ one of the packets it stopped on was a reply then the answer was decoded and thrown away
413
+ with a caller still parked on it.
414
+ ]=]
415
+ --[[
416
+ The thread is **not** resumed here, and that is the whole reason this function exists
417
+ rather than a call to `answered`.
418
+
419
+ `abandon` runs inside the read phase, where resuming means running game code that is free
420
+ to yield — the corruption `Inbound`'s read-then-dispatch split exists to prevent. Moving
421
+ the deadline into the past hands the resume to `tick`, which runs later in the same frame
422
+ (`src/transport/Driver.luau`), so the caller still gives up in a frame rather than at its
423
+ timeout, and the reason it is given is what actually happened.
424
+ ]]
425
+ abandon = function(channel: any, call: number, reason: string)
426
+ local record = pending[call]
427
+
428
+ if not record or record.channel ~= channel then
429
+ return
430
+ end
431
+
432
+ record.deadline = -math.huge
433
+ record.reason = reason
434
+ end,
435
+
436
+ --[=[
437
+ @within Query
438
+ @function tick
439
+
440
+ Resolve every call whose deadline has passed, and every call that was abandoned. Called
441
+ once a frame.
442
+ ]=]
443
+ tick = function()
444
+ if outstanding == 0 then
445
+ return
446
+ end
447
+
448
+ local at = now()
449
+ local count = 0
450
+
451
+ --[[
452
+ Collected first, resumed second, and the two halves cannot be merged.
453
+
454
+ A resumed thread is game code, and the first thing a game does with a timed-out query
455
+ is often to retry it — which inserts into `pending` from inside the loop that is
456
+ walking `pending`. Adding a key to a table being iterated is undefined in Luau, so
457
+ the resume has to happen after the walk has finished.
458
+ ]]
459
+ for call, record in pending do
460
+ if at >= record.deadline then
461
+ count += 1
462
+ expired[count] = call
463
+ end
464
+ end
465
+
466
+ if count == 0 then
467
+ return
468
+ end
469
+
470
+ for index = 1, count do
471
+ local call = expired[index]
472
+ expired[index] = nil
473
+
474
+ local record = pending[call]
475
+
476
+ if record then
477
+ pending[call] = nil
478
+ outstanding -= 1
479
+
480
+ local reason = record.reason or `no answer within {record.channel.timeout}s`
481
+ report(record.channel, nil, reason)
482
+ spawn(record.thread, nil, reason)
483
+ end
484
+ end
485
+ end,
486
+
487
+ --[=[
488
+ @within Query
489
+ @function forget
490
+
491
+ A player who left. Their call slots are released so the budget does not leak, and any
492
+ answer their handlers eventually produce is dropped by [Query.answer].
493
+
494
+ :::caution
495
+ A handler already parked inside a yield is **not** cancelled, because a yielded Luau
496
+ coroutine cannot be. What is released is the accounting; the thread itself returns when
497
+ whatever it is waiting on returns, finds its slot gone, and writes nothing.
498
+ :::
499
+ ]=]
500
+ forget = function(who: any)
501
+ slots[who] = nil
502
+ end,
503
+
504
+ --[=[
505
+ @within Query
506
+ @function outstanding
507
+ @return number
508
+ @private
509
+
510
+ Calls this peer is waiting on. Exposed so a test can assert the count rather than infer
511
+ it from behaviour.
512
+ ]=]
513
+ outstanding = function(): number
514
+ return outstanding
515
+ end,
516
+
517
+ --[=[
518
+ @within Query
519
+ @function inflight
520
+ @param who Player
521
+ @return number
522
+ @private
523
+
524
+ Calls this player is holding open on this peer.
525
+ ]=]
526
+ inflight = function(who: any): number
527
+ local record = slots[who]
528
+ return if record then record.count else 0
529
+ end,
530
+ }
531
+
532
+ return self
533
+ end
534
+
535
+ return Query