@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,540 @@
1
+ --!strict
2
+ --!optimize 2
3
+
4
+ --[=[
5
+ @class Namespace
6
+
7
+ A group of channels declared together, and the two directional views over it.
8
+
9
+ ```lua
10
+ -- shared/Combat.luau
11
+ return nw.namespace("combat", {
12
+ fireWeapon = nw.command({ data = ShotSchema, rate = 20, authorize = policy.canFire }),
13
+ playerState = nw.state({ data = StateSchema, audience = nw.audience.nearby(120) }),
14
+ })
15
+ ```
16
+
17
+ ```lua
18
+ local combat = require(Shared.Combat)
19
+
20
+ combat.server.fireWeapon:listen(function(ctx, shot) end) -- server.luau
21
+ combat.client.fireWeapon:send(shot) -- client.luau
22
+ ```
23
+
24
+ One file per namespace, required by both sides. That is what makes the security model
25
+ reviewable: the declaration is the only place a channel's budget, audience and policy are
26
+ written, and it is a file a reviewer can open.
27
+ ]=]
28
+
29
+ --[[
30
+ Ids are not assigned here, and cannot be.
31
+
32
+ `WIRE-FORMAT.md` §3 assigns them by sorting *every* qualified name in the program and numbering
33
+ from 1, so an id depends on namespaces this one has never heard of. Declaring one more channel
34
+ anywhere renumbers everything, which is fine — both peers recompute the same list — but it
35
+ means a namespace can only register its channels and wait.
36
+
37
+ The alternative, per-namespace numbering with a namespace prefix on the wire, costs a byte per
38
+ packet forever to save one sort at startup.
39
+ ]]
40
+
41
+ local Channel = require("./Channel")
42
+ local Protocol = require("./Protocol")
43
+ local View = require("./View")
44
+
45
+ local Namespace = {}
46
+
47
+ --[=[
48
+ @interface Namespace
49
+ @within Namespace
50
+ .name string
51
+ .server { [string]: any } -- `ServerView<D>` once the declaration's type is known
52
+ .client { [string]: any } -- `ClientView<D>`
53
+ .channels { [string]: Channel }
54
+ ]=]
55
+ export type Namespace = {
56
+ name: string,
57
+ server: { [string]: any },
58
+ client: { [string]: any },
59
+ channels: { [string]: any },
60
+ }
61
+
62
+ local namespaces: { [string]: Namespace } = {}
63
+ local order: { string } = {}
64
+ local sealed = false
65
+
66
+ local function checkName(name: string)
67
+ if type(name) ~= "string" or name == "" then
68
+ error(
69
+ `nw.namespace takes the name first and the channels second, got {typeof(name)}. Write it `
70
+ .. `as nw.namespace("combat", \{ fireWeapon = nw.command(\{ ... }) }) — the name is half `
71
+ .. `of every channel id on the wire, so it cannot be left out.`,
72
+ 3
73
+ )
74
+ end
75
+
76
+ --[[ The name is half of every qualified id, and a dot in it would make `combat.fire.weapon`
77
+ ambiguous about where the namespace ends. ]]
78
+ if string.find(name, ".", 1, true) then
79
+ error(
80
+ `the namespace name "{name}" contains a dot, and a channel id is namespace .. "." .. key. `
81
+ .. `Rename it without one — nw.namespace("combatRanged", ...) rather than `
82
+ .. `"combat.ranged" — or "combat.ranged.fire" would be ambiguous about where the `
83
+ .. `namespace ends.`,
84
+ 3
85
+ )
86
+ end
87
+
88
+ if namespaces[name] then
89
+ error(
90
+ `the namespace {name} is already declared. Two namespaces with one name would collide `
91
+ .. `on the wire, because a channel id is derived from namespace .. "." .. key. Give `
92
+ .. `this one a different name, or require the existing module instead of declaring a `
93
+ .. `second copy — nw.namespace is called once per namespace, at load.`,
94
+ 3
95
+ )
96
+ end
97
+ end
98
+
99
+ --[=[
100
+ @within Namespace
101
+ @function declare
102
+ @param name string -- qualifies every channel id: `"combat.fireWeapon"`
103
+ @param channels { [string]: Channel }
104
+ @return Namespace
105
+
106
+ Declares a namespace. Channel ids come from the string keys, never from table iteration order.
107
+
108
+ :::caution
109
+ Declare every namespace before the first packet moves. Adding one afterwards renumbers the
110
+ channel ids, and the two peers would disagree — which is silent, and decodes every packet as
111
+ the wrong type. `nw.protocol()` is what both sides compare to catch that.
112
+ :::
113
+
114
+ :::caution
115
+ **On a client, "the first packet" is one that *arrives*.** Requiring netweave connects the
116
+ receive side, and the first batch the server sends seals the numbering — so a client that yields
117
+ between `require(netweave)` and its namespace modules (a `WaitForChild`, a deferred require) can
118
+ be sealed by traffic it did not ask for, and the next declaration raises. Require every namespace
119
+ in one unbroken run, before anything yields.
120
+
121
+ This cannot be fixed by deferring the seal: decoding an inbound packet needs the id numbering,
122
+ and the numbering needs every declaration. See `docs/WIRE-FORMAT.md` §3.
123
+ :::
124
+ ]=]
125
+ function Namespace.declare(name: string, channels: { [string]: any }, source: string?): Namespace
126
+ checkName(name)
127
+
128
+ if type(channels) ~= "table" then
129
+ error(`nw.namespace needs a table of channels, got {typeof(channels)}`, 2)
130
+ end
131
+
132
+ --[[
133
+ The declaration that cannot work, refused where it is written (`PLAN-M5` D-7).
134
+
135
+ A namespace the client cannot require can never agree: the protocol hash covers every
136
+ declaration on each side, so one declared under `ServerScriptService` or `ServerStorage` puts
137
+ a channel in the server's hash that no client's can contain, and every client is refused at
138
+ `protocol` from its first batch — "nothing works", with the cause one word in a console line.
139
+ The first mistake on `docs/tutorial/mistakes.md`, and not a matter of degree.
140
+
141
+ `source` is what `nw.namespace` read off `debug.info(2, "s")`: on Roblox the declaring
142
+ module's full name, under lune a path, so the two prefixes match only where they mean
143
+ something and a source of any other shape does nothing. Two prefixes and no more: a bundler or
144
+ a `loadstring` wrapper gives a source that matches neither, and the worst case is today's
145
+ behaviour.
146
+ ]]
147
+ if
148
+ source ~= nil
149
+ and (
150
+ string.find(source, "ServerScriptService.", 1, true) == 1
151
+ or string.find(source, "ServerStorage.", 1, true) == 1
152
+ )
153
+ then
154
+ error(
155
+ `the namespace {name} is declared in {source}, which the client cannot require, so no client `
156
+ .. `could ever agree on the protocol and every one would be refused at "protocol" from its `
157
+ .. `first batch. Declare it in a module under ReplicatedStorage, required by both sides; `
158
+ .. `what is server-only is a policy's dependency, reached from inside the check, not the `
159
+ .. `declaration (docs/tutorial/step3-policies.md).`,
160
+ 3
161
+ )
162
+ end
163
+
164
+ if sealed then
165
+ --[[ The cause this names last is the one that is hardest to find: on a client, a *received*
166
+ packet seals, so a `WaitForChild` between requiring netweave and requiring this module
167
+ is enough. Found by an external review (M3 phase 9); it cannot be fixed by sealing
168
+ later, because decoding the packet that sealed it needs the numbering. ]]
169
+ error(
170
+ `the namespace {name} was declared after the protocol was sealed. Every channel id `
171
+ .. `depends on every other, so a late declaration renumbers ids the other peer has `
172
+ .. `already agreed to. Require all namespaces at startup, in one run — on a client `
173
+ .. `the first packet to arrive seals the protocol, so a yield before this line is `
174
+ .. `enough to lose the race.`,
175
+ 2
176
+ )
177
+ end
178
+
179
+ local count = 0
180
+
181
+ for key, channel in channels do
182
+ if type(key) ~= "string" then
183
+ error(
184
+ `{name} has a non-string channel key, and ids come from the keys. Write the channels `
185
+ .. `as named fields — \{ fireWeapon = nw.command(\{ ... }) } — rather than as an `
186
+ .. `array, because a positional list would renumber the wire every time one is `
187
+ .. `inserted.`,
188
+ 2
189
+ )
190
+ end
191
+
192
+ if not Channel.isChannel(channel) then
193
+ error(
194
+ `{name}.{key} is not a channel. Declare it with nw.command, nw.intent, nw.signal, `
195
+ .. `nw.query, nw.state or nw.event.`,
196
+ 2
197
+ )
198
+ end
199
+
200
+ if channel.qualified ~= "" then
201
+ error(
202
+ `{name}.{key} is already declared as {channel.qualified}. A channel belongs to one `
203
+ .. `namespace; sharing the record would give it two ids and two budgets. Declare a `
204
+ .. `second one with its own nw.command(\{...}), or move the shared *schema* into `
205
+ .. `a local and build both from it — a schema is reusable, a channel is not.`,
206
+ 2
207
+ )
208
+ end
209
+
210
+ channel.key = key
211
+ channel.qualified = `{name}.{key}`
212
+ count += 1
213
+ end
214
+
215
+ if count == 0 then
216
+ error(
217
+ `the namespace {name} declares no channels, so nothing about it can reach the wire. Add `
218
+ .. `the ones it is for — nw.namespace("{name}", \{ fireWeapon = nw.command(\{ ... }) }) `
219
+ .. `— or delete the declaration.`,
220
+ 2
221
+ )
222
+ end
223
+
224
+ --[[
225
+ A copy, frozen. The caller's table was kept by reference, so a key declared *after*
226
+ `nw.namespace` and before the seal was numbered too — a channel whose `qualified` is `""`,
227
+ refused later with a message about something else (M4 report finding 6). Frozen rather than
228
+ only copied, because the views are built from this table and a key added to it afterwards
229
+ would have a view and no id.
230
+
231
+ The records inside are not frozen, and `Channel.Channel` says at length why: `handler` is
232
+ written after declaration by `:listen`, sealing is triggered by the first packet, and the
233
+ typed route is closed by every field of that type being `read`.
234
+ ]]
235
+ local declared = table.freeze(table.clone(channels))
236
+
237
+ local namespace: Namespace = {
238
+ name = name,
239
+ channels = declared,
240
+ server = View.build(declared, "server"),
241
+ client = View.build(declared, "client"),
242
+ }
243
+
244
+ namespaces[name] = namespace
245
+ table.insert(order, name)
246
+
247
+ return namespace
248
+ end
249
+
250
+ --[[
251
+ ~~FNV-1a over the sorted qualified names.~~ **Moved to `src/api/Protocol.luau` in M3 phase 5, and
252
+ widened to cover the lowered IR.**
253
+
254
+ The old note here said a field whose type changed under an unchanged name was left to the
255
+ per-field validation, "which is the right place because it is per packet rather than per
256
+ session". That was wrong twice over: the per-field validation refuses *every* packet for the rest
257
+ of the session, and it never says why. `PLAN-M3` D-7.
258
+ ]]
259
+
260
+ --[=[
261
+ @interface Protocol
262
+ @within Namespace
263
+ .hash number -- FNV-1a over the lowered IR of every channel
264
+ .count number -- how many channels were numbered
265
+ .names { string } -- sorted, so `names[id]` is the channel with that id
266
+
267
+ Re-exported from [Protocol], which is where it is computed.
268
+ ]=]
269
+ export type Protocol = Protocol.Protocol
270
+
271
+ local protocol: Protocol? = nil
272
+
273
+ --[[ Wire id to channel, built when the protocol is sealed. The receive path resolves through this
274
+ once per packet, so it is a flat array-like table rather than a search. ]]
275
+ local byId: { [number]: any } = {}
276
+
277
+ --[[ The `replicate` channels in id order, frozen at seal; before it, and after a reset, an empty
278
+ frozen list rather than nil, so the tick never has to ask. ]]
279
+ local NONE: { any } = table.freeze({} :: { any })
280
+ local replicated: { any } = NONE
281
+
282
+ --[=[
283
+ @within Namespace
284
+ @function seal
285
+ @return Protocol
286
+
287
+ Assigns every channel its wire id and freezes the set. Called automatically on the first
288
+ `nw.protocol()`; call it yourself once every namespace has been required, if you want the
289
+ failure for a late declaration to point at the late one.
290
+
291
+ Ids are `1..n` over all qualified names in the program, sorted. **Id 0 is reserved** for
292
+ control traffic — the schema handshake, and whatever v2 needs.
293
+ ]=]
294
+ function Namespace.seal(): Protocol
295
+ local existing = protocol
296
+
297
+ if existing then
298
+ return existing
299
+ end
300
+
301
+ local names: { string } = {}
302
+ local byName: { [string]: any } = {}
303
+
304
+ for _, name in order do
305
+ for _, channel in namespaces[name].channels do
306
+ table.insert(names, channel.qualified)
307
+ byName[channel.qualified] = channel
308
+ end
309
+ end
310
+
311
+ --[[ Sorted, never iterated. ByteNet assigns ids by walking its declaration table and this
312
+ project hit the resulting silent mis-decode during M0 phase 3: every packet decodes as the
313
+ wrong type, and nothing reports it. ]]
314
+ table.sort(names)
315
+
316
+ table.clear(byId)
317
+
318
+ --[[ Built here and kept, rather than on each ask: the tick asked once a frame and got a fresh
319
+ array each time, for a list that cannot change once the ids are assigned
320
+ (SECURITY-REPORT-M4 77; `bench/residue` rung 77). ]]
321
+ local mirrored: { any } = {}
322
+
323
+ for id, qualified in names do
324
+ local channel = byName[qualified]
325
+ channel.id = id
326
+ byId[id] = channel
327
+
328
+ if channel.class == "replicate" then
329
+ table.insert(mirrored, channel)
330
+ end
331
+ end
332
+
333
+ replicated = table.freeze(mirrored)
334
+
335
+ --[[ After the ids are assigned, not before: the signature is taken in id order, and a channel
336
+ without an id has nothing to be in order by. ]]
337
+ local computed = Protocol.digest(names, byName)
338
+
339
+ protocol = computed
340
+ sealed = true
341
+
342
+ return computed
343
+ end
344
+
345
+ --[=[
346
+ @within Namespace
347
+ @function protocol
348
+ @return Protocol
349
+
350
+ The agreed channel numbering, sealing it if that has not happened yet.
351
+
352
+ Both peers compute this from their own copy of the declarations. If the two hashes differ — a
353
+ stale client, a partial deploy — every packet would decode as the wrong channel, so the
354
+ mismatch is refused at startup rather than producing corrupt payloads for the session.
355
+ ]=]
356
+ function Namespace.protocol(): Protocol
357
+ return Namespace.seal()
358
+ end
359
+
360
+ --[=[
361
+ @within Namespace
362
+ @function channelById
363
+ @param id number
364
+ @return Channel?
365
+ @private
366
+
367
+ The channel a wire id names, sealing the protocol if that has not happened yet.
368
+
369
+ Sealing here rather than at load is what lets a game declare its namespaces in any order and in
370
+ any file: an id depends on every other channel in the program (`docs/WIRE-FORMAT.md` §3), so the
371
+ numbering cannot be fixed until the last declaration has run. The first packet in either
372
+ direction is the latest that can be.
373
+ ]=]
374
+ --[=[
375
+ @within Namespace
376
+ @function replicated
377
+ @return { Channel }
378
+ @private
379
+
380
+ Every declared `replicate` channel, in id order, sealing the protocol if that has not happened
381
+ yet. The same frozen list every time: nothing can be declared after the seal, so it is built
382
+ there once.
383
+ ]=]
384
+ function Namespace.replicated(): { any }
385
+ if not protocol then
386
+ Namespace.seal()
387
+ end
388
+
389
+ return replicated
390
+ end
391
+
392
+ function Namespace.channelById(id: number): any?
393
+ if not protocol then
394
+ Namespace.seal()
395
+ end
396
+
397
+ return byId[id]
398
+ end
399
+
400
+ --[=[
401
+ @within Namespace
402
+ @function channelByName
403
+ @param qualified string -- `"combat.fireWeapon"`
404
+ @return Channel?
405
+ @private
406
+
407
+ The channel behind a qualified name, sealing the protocol if that has not happened yet.
408
+
409
+ Exists for `nw.signature()`, which walks the protocol's own name list and needs the declaration
410
+ behind each one. A search rather than a table, because it runs once when a human asks why two
411
+ builds disagree.
412
+ ]=]
413
+ function Namespace.channelByName(qualified: string): any?
414
+ if not protocol then
415
+ Namespace.seal()
416
+ end
417
+
418
+ for _, channel in byId do
419
+ if channel.qualified == qualified then
420
+ return channel
421
+ end
422
+ end
423
+
424
+ return nil
425
+ end
426
+
427
+ --[=[
428
+ @within Namespace
429
+ @function get
430
+ @param name string
431
+ @return Namespace?
432
+ @private
433
+ ]=]
434
+ function Namespace.get(name: string): Namespace?
435
+ return namespaces[name]
436
+ end
437
+
438
+ local stagesRan = false
439
+
440
+ --[=[
441
+ @within Namespace
442
+ @function runStages
443
+ @private
444
+
445
+ Runs every policy's server stage once — once per distinct function, so a policy attached to two
446
+ channels, or a member of two compositions, runs its stage a single time. Called by the transport
447
+ on the server after the seal and before the first packet decodes, never on a client, and a
448
+ second call is one boolean.
449
+
450
+ A stage that raises or yields is a startup error and is raised as one, with the channel named:
451
+ a check that ran before its stage did would be a policy deciding on nothing, and a seal parked
452
+ on a yield would be a server that never opens (`PLAN-M5` D-5).
453
+ ]=]
454
+ function Namespace.runStages()
455
+ if stagesRan then
456
+ return
457
+ end
458
+
459
+ --[[ Marked before running, so a stage that raises is raised once — loud at startup — rather
460
+ than on every batch that follows. ]]
461
+ stagesRan = true
462
+
463
+ local seen: { [() -> ()]: boolean } = {}
464
+
465
+ for _, name in order do
466
+ for _, channel in namespaces[name].channels do
467
+ local stages: { () -> () }? = channel.stages
468
+
469
+ if not stages then
470
+ continue
471
+ end
472
+
473
+ for _, stage in stages do
474
+ if seen[stage] then
475
+ continue
476
+ end
477
+
478
+ seen[stage] = true
479
+
480
+ --[[ On a thread of its own so a yield is seen rather than parked on: a stage that
481
+ does not finish synchronously has not filled what the check will read. ]]
482
+ local thread = coroutine.create(stage)
483
+ local ok, failure = coroutine.resume(thread)
484
+
485
+ if not ok then
486
+ error(
487
+ `the server stage of a policy on {channel.qualified} raised: {tostring(failure)}. `
488
+ .. `It runs once at seal, before any packet decodes, so this is a startup error; `
489
+ .. `fix it there instead of letting the check run over nothing.`,
490
+ 0
491
+ )
492
+ end
493
+
494
+ if coroutine.status(thread) ~= "dead" then
495
+ error(
496
+ `the server stage of a policy on {channel.qualified} yielded, and a stage has to `
497
+ .. `finish before the first packet decodes. Remove the yield — read what is `
498
+ .. `already loaded, or require the module rather than waiting for it — so the `
499
+ .. `check never runs over a value the stage has not filled.`,
500
+ 0
501
+ )
502
+ end
503
+ end
504
+ end
505
+ end
506
+ end
507
+
508
+ --[=[
509
+ @within Namespace
510
+ @function sealed
511
+ @return boolean
512
+ @private
513
+
514
+ Whether the numbering is fixed. The transport asks this rather than keeping its own flag,
515
+ because [Namespace.reset] would otherwise leave the driver believing a protocol that no longer
516
+ exists is still agreed.
517
+ ]=]
518
+ function Namespace.sealed(): boolean
519
+ return sealed
520
+ end
521
+
522
+ --[=[
523
+ @within Namespace
524
+ @function reset
525
+ @private
526
+
527
+ Forgets every namespace. Exists so one test file can declare a namespace and the next can too;
528
+ a game that calls this has renumbered every channel out from under its peer.
529
+ ]=]
530
+ function Namespace.reset()
531
+ table.clear(namespaces)
532
+ table.clear(order)
533
+ table.clear(byId)
534
+ replicated = NONE
535
+ protocol = nil
536
+ sealed = false
537
+ stagesRan = false
538
+ end
539
+
540
+ return Namespace