@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,1288 @@
1
+ --!strict
2
+ --!optimize 2
3
+
4
+ --[=[
5
+ @class Channel
6
+
7
+ The seven channel classes. A class is a **security obligation**, not a transport mode: a reader
8
+ who sees `nw.intent` knows the server does not approve each packet, and a reader who sees
9
+ `nw.command` knows it does.
10
+
11
+ | Class | Direction | Required | Forbidden | The handler receives |
12
+ |---|---|---|---|---|
13
+ | `command` | C→S | `data`, `rate`, `authorize` | `audience`, `args`, `returns`, `timeout` | `Trusted<T>` |
14
+ | `intent` | C→S | `data`, `rate` | `authorize`, `audience`, `returns`, `timeout` | `T` |
15
+ | `signal` | C→S | `data`, `rate` | `authorize`, `audience`, `returns`, `timeout` | `Untrusted<T>` |
16
+ | `query` | C→S→C | `args`, `returns`, `rate`, `authorize`, `timeout` | `data`, `audience` | `Trusted<T>` |
17
+ | `state` | S→C | `data`, `audience` | `rate`, `authorize`, `args`, `returns`, `timeout` | `T` |
18
+ | `event` | S→C | `data`, `audience` | `rate`, `authorize`, `args`, `returns`, `timeout` | `T` |
19
+
20
+ Omitting a required field is a type error. So is supplying a forbidden one — which is the part
21
+ that keeps the taxonomy honest, because `signal` exists precisely as the class that may not
22
+ authorize, and a `signal` carrying an `authorize` would have been a `command` all along.
23
+ ]=]
24
+
25
+ --[[
26
+ Two layers check a declaration, and they are not redundant.
27
+
28
+ The type functions below are the guarantee: they run at analysis time, and a declaration that
29
+ does not satisfy them never ships. The plain Lua checks further down run at load, and exist for
30
+ the declaration that reached here anyway — through an `any`, through a table built at runtime,
31
+ or in a build where `LuauSolverV2` is off and none of the type layer applies (`PLAN-M1` D-7).
32
+
33
+ Neither is decoration. The type layer catches what a reviewer would miss; the runtime layer
34
+ catches what the type layer was bypassed for.
35
+ ]]
36
+
37
+ local Audience = require("./Audience")
38
+ local Config = require("./Config")
39
+ local Delta = require("../replication/Delta")
40
+ local Ir = require("../codec/Ir")
41
+ local Policy = require("./Policy")
42
+ local Serdes = require("../codec/Serdes")
43
+ local Types = require("../types")
44
+
45
+ local Channel = {}
46
+
47
+ --[=[
48
+ @type Class "command" | "intent" | "signal" | "query" | "state" | "event" | "replicate"
49
+ @within Channel
50
+ ]=]
51
+ export type Class = "command" | "intent" | "signal" | "query" | "state" | "event" | "replicate"
52
+
53
+ --[=[
54
+ @type Primitive "AuthorizedInbound" | "UntrustedInbound" | "Outbound"
55
+ @within Channel
56
+
57
+ Six public classes, three inbound-or-outbound implementations — `query` is an
58
+ `AuthorizedInbound` that also owns a paired `Outbound` for its response.
59
+
60
+ The public surface is where meaning lives; the implementation stays small
61
+ (`DESIGN-API.md` §3).
62
+ ]=]
63
+ export type Primitive = "AuthorizedInbound" | "UntrustedInbound" | "Outbound"
64
+
65
+ --[=[
66
+ @interface Channel
67
+ @within Channel
68
+ .__class Class -- a singleton, so the directional views can branch on it
69
+ .__audience "everyone" | "subset" -- a singleton, so `broadcast` exists only where G3 allows it
70
+ .__payload T -- phantom
71
+ .__response R -- phantom
72
+ .class Class
73
+ .primitive Primitive
74
+ .rate number? -- packets per second the sender may send. nil on outbound classes
75
+ .burst number? -- bucket depth; nil means one second at `rate`
76
+ .maxBytes number -- the most bytes a payload may claim; derived from the schema, tightened by declaration
77
+ .timeout number? -- `query` only, seconds
78
+ .authorize Check<T>? -- resolved from the declared policy at load
79
+ .audience Audience? -- outbound classes only
80
+ .data Descriptor
81
+ .returns Descriptor? -- `query` only
82
+ .key string -- assigned by `nw.namespace`
83
+ .qualified string -- `"namespace.key"`, assigned by `nw.namespace`
84
+ .id number -- wire id, assigned when the protocol is sealed
85
+
86
+ A declared channel. Everything except the last three is fixed the moment it is declared; the
87
+ last three are filled in by the namespace and the registry, because an id depends on every
88
+ other channel in the program (`WIRE-FORMAT.md` §3).
89
+ ]=]
90
+ --[[
91
+ **Every field is `read`**, because the transport reads each of them per packet and a game that
92
+ writes one has switched a guarantee off.
93
+
94
+ `ns.channels.equip.authorize = nil`, `.rate = 1e9` and `.maxBytes = 1e9` all type-checked with no
95
+ cast, and `Inbound` treats a nil `authorize` as allow — so G1 and G2 came off in one typed line
96
+ that a reviewer grepping for `:: any` would not find (M4 report finding 6). They need the cast
97
+ now, which is the whole point: *a forgery you have to write is one a reviewer sees*.
98
+
99
+ ~~And the record is frozen at seal.~~ **Deliberately not, and here is the cost that decided it.**
100
+ `handler` is written *after* declaration by `:listen`, and sealing is triggered by the first
101
+ packet or by `nw.protocol()` — so a game that prints its signature early and attaches a handler
102
+ afterwards would be raising on a legal sequence. Moving the handler to a side table removes that,
103
+ and costs a lookup on the per-packet dispatch path plus 94 assignments across six test rigs that
104
+ own their own channel tables. The typed route is the one the finding is about, and it is closed;
105
+ `Namespace.declare` freezes the `channels` *table* so a late key cannot be added either.
106
+ ]]
107
+ export type Channel<C, A, T, R, U> = {
108
+ read __class: C,
109
+ read __audience: A,
110
+ read __payload: T,
111
+ read __response: R,
112
+ --[[ What a `replicate` channel names its subjects with, and `nil` for every other class — the
113
+ only one that puts a subject on the wire is the only one whose listener is handed one. ]]
114
+ read __subject: U,
115
+
116
+ read class: Class,
117
+ read primitive: Primitive,
118
+ read rate: number?,
119
+ read burst: number?,
120
+ read maxBytes: number?,
121
+ read timeout: number?,
122
+ read authorize: Policy.Check<T>?,
123
+ read audience: Audience.Audience<A>?,
124
+ read data: Types.Descriptor,
125
+ read returns: Types.Descriptor?,
126
+ read codec: Serdes.Codec,
127
+ read responseCodec: Serdes.Codec?,
128
+
129
+ read key: string,
130
+ read qualified: string,
131
+ read id: number,
132
+ read handler: any,
133
+ }
134
+
135
+ --[[
136
+ Every constructor takes its spec as a free generic and lets a type function do the checking.
137
+ That is not the obvious shape, and three measurements forced it (`spike/declare/`):
138
+
139
+ 1. `command<T>(spec: { data: Types.Type<T>, ... })` **does not bind `T`.** The solver resolves
140
+ it to `unknown`, so every channel's payload is lost and the directional views map nothing.
141
+ A minimal `{ __payload: T }` in `data`'s place does not help either. Reading `__payload`
142
+ out of an inferred spec is the only form that yields `{ origin: Vector3, seq: number }`.
143
+ 2. Where `T` appeared in two positions — `data` and `authorize` — an unannotated policy
144
+ widened it to `any`, which silently disabled inference for the *whole channel*. Projecting
145
+ from `data` alone cannot be clobbered.
146
+ 3. **Width subtyping accepts extra properties**, so a spec type listing only the allowed
147
+ fields forbids nothing: `intent({ data = ..., rate = 60, authorize = f })` type-checks
148
+ against a type with no `authorize`. A type function reading `readproperty` sees the field
149
+ and can refuse it.
150
+
151
+ The third is why the messages here are worth writing carefully. A type function's `error()` is
152
+ reported at the call site verbatim, so a bad declaration can say what to write instead of
153
+ printing two structural table types and leaving the reader to diff them.
154
+
155
+ A type function body sees only the `types` library — not this module's locals — so the reasons
156
+ live inside `permit` rather than in a constant table beside it.
157
+ ]]
158
+ --[[
159
+ A callable constructor's table half.
160
+
161
+ `t.u8`, `t.string`, `t.vector3` and `t.instance` are `Type<T> & ((…) -> Type<T>)` since
162
+ `PLAN-M5` phase 1 — an intersection, because that is the only spelling that checks the argument
163
+ *types* rather than only their count. To a `type function` an intersection is not a table, so
164
+ anything reading `__payload` off a schema has to take the table half out first.
165
+
166
+ `src/types/init.luau` carries the same walk. A `type function` cannot reference an outer local
167
+ and calling one across a `require` needs it exported, so the copy is the cheaper of the two
168
+ costs — and the two are tested by the same `_ok` files, which annotate a payload projected
169
+ through both.
170
+ ]]
171
+ -- selene: allow(undefined_variable)
172
+ type function carrierOf(ty: type): type
173
+ if not ty:is("intersection") then
174
+ return ty
175
+ end
176
+
177
+ for _, part in ty:components() do
178
+ if part:is("table") and part:readproperty(types.singleton("__payload")) then
179
+ return part
180
+ end
181
+ end
182
+
183
+ return ty
184
+ end
185
+
186
+ -- selene: allow(undefined_variable)
187
+ type function payloadOf(descriptor: type, field: type): type
188
+ local schema = carrierOf(types.copy(descriptor))
189
+ local name = field:value()
190
+
191
+ --[[ The same sentence twice, because the two failures are the same mistake seen from either
192
+ side: something that is not a netweave type, and something that is a table but not one. A
193
+ reader who hits either has written the same wrong thing. ]]
194
+ --[[ Concatenated rather than interpolated: the advice has to show `t.struct({ ... })`, and a
195
+ brace inside an interpolated string is an interpolation. ]]
196
+ --[[ `:value()` on a type object is `unknown` to the analyser, and concatenating an unknown is an
197
+ error inside netweave's own source — the one place a user cannot act on it. ]]
198
+ local advice = "`"
199
+ .. tostring(name)
200
+ .. "` must be a netweave type. Build one with the type library: local t = nw.types, then "
201
+ .. "t.struct({ ... }), t.u8, t.string(0, 32) or t.array(t.u16). A plain Luau table is not a "
202
+ .. "schema — there is nothing in it to serialise from."
203
+
204
+ if not schema:is("table") then
205
+ error(advice)
206
+ end
207
+
208
+ local payload = schema:readproperty(types.singleton("__payload"))
209
+
210
+ if not payload then
211
+ error(advice)
212
+ end
213
+
214
+ return payload
215
+ end
216
+
217
+ -- selene: allow(undefined_variable)
218
+ type function propertyOf(spec: type, field: type): type?
219
+ local declaration = types.copy(spec)
220
+
221
+ if not declaration:is("table") then
222
+ error(
223
+ "a channel is declared with a table of fields, written inline. Use "
224
+ .. "nw.signal({ data = ..., rate = 20 }) rather than a value built elsewhere and "
225
+ .. "passed in: the fields have to be visible here for the analyzer to read them."
226
+ )
227
+ end
228
+
229
+ return declaration:readproperty(types.singleton(field:value()))
230
+ end
231
+
232
+ -- selene: allow(undefined_variable)
233
+ type function requireRate(spec: type, class: type): type
234
+ local rate = propertyOf(spec, types.singleton("rate"))
235
+
236
+ if not rate then
237
+ error(
238
+ `nw.{class:value()} needs \`rate\`, in packets per second per player. There is no `
239
+ .. `unlimited: netweave guarantee G2.`
240
+ )
241
+ end
242
+
243
+ if not rate:is("number") then
244
+ error(
245
+ "`rate` is a number of packets per second per player, written as a literal: "
246
+ .. "nw.signal({ data = ..., rate = 20 }). There is no unlimited and no default — "
247
+ .. "netweave guarantee G2."
248
+ )
249
+ end
250
+
251
+ return rate
252
+ end
253
+
254
+ --[[
255
+ **Every key a class takes, and nothing else.**
256
+
257
+ ~~`forbid` names the keys that belong to *another* class~~ — one call per forbidden key per class,
258
+ a hand-picked list, and it could not see a misspelling: `maxbytes = 4`, `bursts = 50`, `authorise`, `Rate`,
259
+ `timeOut`, `rate_` all compiled, the runtime ignored the key, and the author believed a ceiling or
260
+ a depth was set — one diagnostic in a probe file of twenty-two declarations (M4 report
261
+ finding 45). This is what `CheckedSettings` already did for `nw.configure`, on the surface the
262
+ design calls the security documentation.
263
+
264
+ So each class passes the keys it takes and this walks the declaration. A key that belongs to
265
+ another class gets that class's reason; anything else is a misspelling, and the message lists what
266
+ the class does take, because the fix is a spelling and the list is the shortest way to find it.
267
+
268
+ The value types come with it: `rate = "20"` was the one diagnostic the probe did produce, but
269
+ `burst`, `maxBytes`, `timeout` and `unreliable` took a string with no complaint, and `timeout` and
270
+ `store` were presence-only — `store = {}` compiled.
271
+
272
+ The list arrives as one comma-separated singleton because a type function takes types, and a
273
+ string is the cheapest type that carries a list.
274
+ ]]
275
+ -- selene: allow(undefined_variable)
276
+ type function permit(spec: type, class: type, allowed: type): type
277
+ local declaration = types.copy(spec)
278
+
279
+ if not declaration:is("table") then
280
+ error(
281
+ "a channel is declared with a table of fields, written inline. Use "
282
+ .. "nw.signal({ data = ..., rate = 20 }) rather than a value built elsewhere and "
283
+ .. "passed in: the fields have to be visible here for the analyzer to read them."
284
+ )
285
+ end
286
+
287
+ local names = {}
288
+ local list = {}
289
+
290
+ for name in string.gmatch(tostring(allowed:value()), "[^,]+") do
291
+ names[name] = true
292
+ table.insert(list, name)
293
+ end
294
+
295
+ --[[ A key that belongs to another class keeps its own sentence, because that mistake and a
296
+ misspelling are not the same mistake: one is a class chosen wrongly and the other is a letter.
297
+ `forbid` is gone — this is where its reasons live now. ]]
298
+ local elsewhere = {
299
+ authorize = "A channel that authorizes is a command or a query; an intent and a signal "
300
+ .. "carry no authority by definition, and letting them approve requests would make "
301
+ .. "the class name a lie. If you need to approve it, it is a command.",
302
+ rate = "The server is the sender on this class, so there is nobody to budget.",
303
+ burst = "Burst is the depth of the rate budget, and this class has no rate to be the depth of.",
304
+ maxBytes = "This class is sent by the server, which is not a peer whose payload size needs "
305
+ .. "policing. The schema still gives it a ceiling.",
306
+ audience = "Only state and event have an audience; an inbound channel has exactly one "
307
+ .. "recipient, which is the server.",
308
+ timeout = "Only a query waits for a reply.",
309
+ returns = "Only a query replies.",
310
+ args = "This class carries `data`, not `args`.",
311
+ data = "A query carries `args` and `returns`, not `data`.",
312
+ unreliable = "This class must arrive. A command changes authoritative state and a query is "
313
+ .. "waiting for an answer; delivering either at best effort would make the class name a "
314
+ .. "promise it does not keep. A replicated channel sends *changes*, and a change that "
315
+ .. "does not arrive leaves that client permanently and silently wrong — which is why "
316
+ .. "nw.state exists beside it for the cases where losing one is fine.",
317
+ store = "Only a replicated channel reads from a store; every other class is handed its "
318
+ .. "payload at the call site.",
319
+ subject = "Only a replicated channel names its subjects on the wire. Everywhere else the "
320
+ .. "audience decides who gets a value and nothing has to say which value it is.",
321
+ }
322
+
323
+ --[[ What a number key is for, so `maxBytes = "4"` is caught where `maxbytes = 4` is. `rate` is
324
+ checked by `requireRate`, which has its own sentence about G2. ]]
325
+ local numbers = { burst = true, maxBytes = true, timeout = true }
326
+
327
+ for key, property in declaration:properties() do
328
+ local name = key:value()
329
+
330
+ if not names[name] then
331
+ local because = elsewhere[name]
332
+
333
+ if because then
334
+ error(`nw.{class:value()} forbids \`{name}\`. {because}`)
335
+ end
336
+
337
+ error(
338
+ `nw.{class:value()} has no \`{name}\`. It takes {table.concat(list, ", ")} — check the `
339
+ .. `spelling, because a key that is ignored looks exactly like one that worked.`
340
+ )
341
+ end
342
+
343
+ local value = property.read
344
+
345
+ if value then
346
+ if numbers[name] and not value:is("number") then
347
+ error(`nw.{class:value()} takes \`{name}\` as a number.`)
348
+ end
349
+
350
+ if name == "unreliable" and not value:is("boolean") then
351
+ error(`nw.{class:value()} takes \`unreliable\` as a boolean: unreliable = true.`)
352
+ end
353
+ end
354
+ end
355
+
356
+ return types.singleton(true)
357
+ end
358
+
359
+ -- selene: allow(undefined_variable)
360
+ type function requireData(spec: type, class: type, field: type, purpose: type): type
361
+ local declared = propertyOf(spec, field)
362
+
363
+ if not declared then
364
+ error(`nw.{class:value()} needs \`{field:value()}\`, a netweave type describing {purpose:value()}`)
365
+ end
366
+
367
+ return payloadOf(declared, field)
368
+ end
369
+
370
+ --[=[
371
+ @type CommandPayload<S> S
372
+ @within Channel
373
+
374
+ Checks a `command` declaration and projects the payload out of its `data`.
375
+ ]=]
376
+ -- selene: allow(undefined_variable)
377
+ export type function CommandPayload(spec)
378
+ local command = types.singleton("command")
379
+
380
+ requireRate(spec, command)
381
+
382
+ if not propertyOf(spec, types.singleton("authorize")) then
383
+ error(
384
+ "nw.command needs `authorize`. Build one with nw.policy, or compose several with "
385
+ .. "nw.all. A command without authorization is the shape of every Roblox exploit "
386
+ .. "writeup; if this channel genuinely carries no authority, declare it a signal."
387
+ )
388
+ end
389
+
390
+ permit(spec, command, types.singleton("data,rate,burst,maxBytes,authorize"))
391
+
392
+ return requireData(spec, command, types.singleton("data"), types.singleton("what the client sends"))
393
+ end
394
+
395
+ --[=[
396
+ @type IntentPayload<S> S
397
+ @within Channel
398
+ ]=]
399
+ -- selene: allow(undefined_variable)
400
+ export type function IntentPayload(spec)
401
+ local intent = types.singleton("intent")
402
+
403
+ requireRate(spec, intent)
404
+
405
+ permit(spec, intent, types.singleton("data,rate,burst,maxBytes,unreliable"))
406
+
407
+ return requireData(spec, intent, types.singleton("data"), types.singleton("the input being observed"))
408
+ end
409
+
410
+ --[=[
411
+ @type SignalPayload<S> S
412
+ @within Channel
413
+ ]=]
414
+ -- selene: allow(undefined_variable)
415
+ export type function SignalPayload(spec)
416
+ local signal = types.singleton("signal")
417
+
418
+ requireRate(spec, signal)
419
+
420
+ permit(spec, signal, types.singleton("data,rate,burst,maxBytes,unreliable"))
421
+
422
+ return requireData(spec, signal, types.singleton("data"), types.singleton("what the client sends"))
423
+ end
424
+
425
+ --[=[
426
+ @type QueryArgs<S> S
427
+ @within Channel
428
+ ]=]
429
+ -- selene: allow(undefined_variable)
430
+ export type function QueryArgs(spec)
431
+ local query = types.singleton("query")
432
+
433
+ requireRate(spec, query)
434
+
435
+ if not propertyOf(spec, types.singleton("authorize")) then
436
+ error(
437
+ "nw.query needs `authorize`. A query reads authoritative state, and a read is how an "
438
+ .. "exploit finds what to write."
439
+ )
440
+ end
441
+
442
+ if not propertyOf(spec, types.singleton("timeout")) then
443
+ error("nw.query needs `timeout`, in seconds. A request that never resolves is a leak.")
444
+ end
445
+
446
+ permit(spec, query, types.singleton("args,returns,rate,burst,maxBytes,timeout,authorize"))
447
+
448
+ return requireData(spec, query, types.singleton("args"), types.singleton("the request"))
449
+ end
450
+
451
+ --[=[
452
+ @type QueryReturns<S> S
453
+ @within Channel
454
+ ]=]
455
+ -- selene: allow(undefined_variable)
456
+ export type function QueryReturns(spec)
457
+ return requireData(
458
+ spec,
459
+ types.singleton("query"),
460
+ types.singleton("returns"),
461
+ types.singleton("the reply")
462
+ )
463
+ end
464
+
465
+ --[=[
466
+ @type OutboundPayload<S> S
467
+ @within Channel
468
+
469
+ Shared by `state` and `event`: both are server-to-client, so both forbid a budget and a policy.
470
+ ]=]
471
+ -- selene: allow(undefined_variable)
472
+ export type function OutboundPayload(spec, class)
473
+ permit(spec, class, types.singleton("data,audience,unreliable"))
474
+
475
+ return requireData(spec, class, types.singleton("data"), types.singleton("what the server sends"))
476
+ end
477
+
478
+ --[=[
479
+ @type ReplicatePayload<S> S
480
+ @within Channel
481
+
482
+ Checks a `replicate` declaration and projects the payload out of its `data`.
483
+
484
+ Everything [OutboundPayload] forbids, plus `unreliable` — which is the difference between this
485
+ class and `state` made mechanical rather than documented. A delta is only meaningful against the
486
+ baseline the receiver has, so one that does not arrive leaves that client wrong for the rest of
487
+ the session (`PLAN-M4` D-2). And two things it requires that no other class has: a `store` to
488
+ read from, and a `subject` type, because replication is the only class where the wire has to say
489
+ *which* value this is.
490
+ ]=]
491
+ -- selene: allow(undefined_variable)
492
+ export type function ReplicatePayload(spec)
493
+ local class = types.singleton("replicate")
494
+
495
+ permit(spec, class, types.singleton("subject,data,audience,store"))
496
+
497
+ if not propertyOf(spec, types.singleton("subject")) then
498
+ error(
499
+ "nw.replicate needs `subject`, a netweave type naming what each value belongs to — "
500
+ .. "t.u16 for entity ids, t.string(0, 32) for names. It is the one class that puts "
501
+ .. "the subject on the wire, because the client keeps a value per subject and has to "
502
+ .. "know which one arrived."
503
+ )
504
+ end
505
+
506
+ if not propertyOf(spec, types.singleton("store")) then
507
+ error(
508
+ "nw.replicate needs `store`, from nw.store: nw.store.of(table), "
509
+ .. "nw.store.charm(atom) or nw.store.replica(replicas). netweave does "
510
+ .. "not own the state it replicates — the game already has somewhere to keep it, and a "
511
+ .. "library that demands that be torn out to get delta compression will not be used."
512
+ )
513
+ end
514
+
515
+ return requireData(spec, class, types.singleton("data"), types.singleton("what is replicated"))
516
+ end
517
+
518
+ --[=[
519
+ @type ReplicateSubject<S> S
520
+ @within Channel
521
+
522
+ Projects the payload out of a `replicate` declaration's `subject`.
523
+
524
+ It reaches the client's listener as the first argument, so a handler that keeps a value per
525
+ subject is typed on both — `function(id: number, value)` rather than `function(id, value)` with
526
+ the id an `any` nobody can check. That is the only reason the type exists: without it the
527
+ listener would take one argument at analysis and two at runtime, which is worse than either.
528
+ ]=]
529
+ -- selene: allow(undefined_variable)
530
+ export type function ReplicateSubject(spec)
531
+ local declared = propertyOf(spec, types.singleton("subject"))
532
+
533
+ --[[ Silent when it is missing, because [ReplicatePayload] refuses that with the message worth
534
+ reading and both type functions run on the same declaration. Two diagnostics for one
535
+ mistake is one diagnostic too many, and `tests/api_reject.luau` counts them. ]]
536
+ if not declared then
537
+ return types.unknown
538
+ end
539
+
540
+ return payloadOf(declared, types.singleton("subject"))
541
+ end
542
+
543
+ --[=[
544
+ @type OutboundScope<S> "everyone" | "subset"
545
+ @within Channel
546
+
547
+ Projects the declared audience's scope, which is what decides whether `broadcast` exists on the
548
+ server view. Guarantee G3 is this type function and the branch it feeds in `src/api/View.luau`.
549
+ ]=]
550
+ -- selene: allow(undefined_variable)
551
+ export type function OutboundScope(spec)
552
+ local audience = propertyOf(spec, types.singleton("audience"))
553
+
554
+ if not audience then
555
+ error(
556
+ "this channel needs `audience`. Use nw.audience.everyone, nw.audience.owner, "
557
+ .. "nw.audience.nearby(studs) or nw.audience.select(fn). There is no default: "
558
+ .. "broadcasting everything to everyone is how positional data reaches a wallhack, "
559
+ .. "so the recipient set is a declaration rather than a call site. Guarantee G3."
560
+ )
561
+ end
562
+
563
+ local scope = types.copy(audience):readproperty(types.singleton("scope"))
564
+
565
+ if not scope then
566
+ error(
567
+ "`audience` must come from nw.audience: use nw.audience.everyone, nw.audience.owner, "
568
+ .. "nw.audience.nearby(studs) or nw.audience.select(fn). A plain table will not do, "
569
+ .. "because the scope has to be a singleton in the type for `broadcast` to exist only "
570
+ .. "where it is safe (guarantee G3)."
571
+ )
572
+ end
573
+
574
+ return scope
575
+ end
576
+
577
+ --[[ Asked of the type library rather than repeated here: a table with a string `kind` used to pass
578
+ both copies, so every invariant the constructors enforce was advisory (M4 report finding 7). ]]
579
+ local function isType(value: any): boolean
580
+ return Types.isType(value)
581
+ end
582
+
583
+ local function requireType(spec: any, field: string, class: string): Types.Descriptor
584
+ local value = spec[field]
585
+
586
+ if not isType(value) then
587
+ error(`nw.{class} needs {field} to be a netweave type, got {typeof(value)}`, 3)
588
+ end
589
+
590
+ return value
591
+ end
592
+
593
+ --[[
594
+ `rate` is checked at declaration rather than trusted, because G2 says there is no unlimited and
595
+ a `rate` of `math.huge` would be exactly that with the type system none the wiser.
596
+ ]]
597
+
598
+ --[[
599
+ A rate above this is documentation, not a limit. One client at 60 fps sending 166 packets a
600
+ frame is already an order of magnitude past any shipped game, so a declaration above it admits
601
+ everything the platform can physically deliver — which is what G2 exists to stop being written
602
+ by accident.
603
+
604
+ It is a lint rather than a rejection because the number is legitimate in a benchmark, where the
605
+ point is to measure the library and not the budget. `bench/src/shared/Modes/netweave.luau`
606
+ declares 1e6 and turns this rule off, in that order, which is the intended shape: a considered
607
+ exception, written down.
608
+ ]]
609
+ local BINDING_RATE = 10000
610
+
611
+ local function lintRate(rate: number, class: string)
612
+ if rate <= BINDING_RATE then
613
+ return
614
+ end
615
+
616
+ local level = Config.severityOf("rateUnbounded")
617
+
618
+ if level == "off" then
619
+ return
620
+ end
621
+
622
+ local message = `nw.{class} declares rate = {rate}, which no client can reach — the channel is `
623
+ .. `effectively unlimited (netweave guarantee G2). Declare the rate the game actually needs, `
624
+ .. `or set rules.rateUnbounded = "off" if this is deliberate.`
625
+
626
+ --[[ This one fires on the game's own declaration rather than on wire data, which is why it is
627
+ allowed to raise at all. G4 covers the receive path; a declaration is programmer error and
628
+ `CLAUDE.md` §4 says that is what raising is for. ]]
629
+ if Config.raises("rateUnbounded") then
630
+ error(message, 4)
631
+ end
632
+
633
+ warn(`[netweave] {message}`)
634
+ end
635
+ local function checkedRate(spec: any, class: string): number
636
+ local rate = spec.rate
637
+
638
+ if type(rate) ~= "number" or rate ~= rate or rate <= 0 or rate == math.huge then
639
+ error(
640
+ `nw.{class} needs a positive finite rate in packets per second, got {tostring(rate)}. `
641
+ .. `There is no unlimited: netweave guarantee G2.`,
642
+ 3
643
+ )
644
+ end
645
+
646
+ lintRate(rate, class)
647
+
648
+ return rate
649
+ end
650
+
651
+ --[[
652
+ The depth of the bucket, and optional: omitting it means one second.s worth, which is the safe
653
+ reading of silence. Declaring it is how a game says "this channel is bursty" — an input the codec
654
+ sends in a flurry on a key press and then not at all — without also raising the sustained rate,
655
+ which is what a game would otherwise have to do and is the thing `rate` exists to bound.
656
+
657
+ Below `rate` is refused rather than clamped. A depth under the rate cannot be honoured: tokens
658
+ accrue at `rate` per second and the cap would throw the difference away every second, so the
659
+ channel would run at the depth and the declared rate would be fiction.
660
+ ]]
661
+ local function checkedBurst(spec: any, class: string, rate: number): number?
662
+ local burst = spec.burst
663
+
664
+ if burst == nil then
665
+ return nil
666
+ end
667
+
668
+ if type(burst) ~= "number" or burst ~= burst or burst == math.huge or burst % 1 ~= 0 then
669
+ error(`nw.{class} takes burst as a whole number of packets, got {tostring(burst)}`, 3)
670
+ end
671
+
672
+ if burst < rate then
673
+ error(
674
+ `nw.{class} declares burst = {burst} below rate = {rate}. The bucket refills at the rate, `
675
+ .. `so a depth under it would be discarded every second and the rate would never be `
676
+ .. `reached. Raise the burst, or lower the rate.`,
677
+ 3
678
+ )
679
+ end
680
+
681
+ return burst
682
+ end
683
+
684
+ --[[
685
+ Optional, and only ever a tightening. The schema already gives every channel a ceiling, so this
686
+ exists for the case the schema cannot express: a channel whose type allows a megabyte because an
687
+ array is unbounded, but whose game never sends more than a few hundred bytes. Declaring the
688
+ smaller number turns a theoretical bound into a real one.
689
+ ]]
690
+ local function checkedMaxBytes(spec: any, class: string): number?
691
+ local maxBytes = spec.maxBytes
692
+
693
+ if maxBytes == nil then
694
+ return nil
695
+ end
696
+
697
+ if type(maxBytes) ~= "number" or maxBytes ~= maxBytes or maxBytes < 1 or maxBytes % 1 ~= 0 then
698
+ error(`nw.{class} takes maxBytes as a whole number of bytes, at least 1, got {tostring(maxBytes)}`, 3)
699
+ end
700
+
701
+ return maxBytes
702
+ end
703
+
704
+ local function requirePolicy(spec: any, class: string): any
705
+ local authorize = spec.authorize
706
+
707
+ if not Policy.isPolicy(authorize) then
708
+ error(
709
+ `nw.{class} needs authorize. Build one with nw.policy, or compose several with `
710
+ .. `nw.all. A {class} without authorization is the shape of every Roblox exploit `
711
+ .. `writeup; if this channel genuinely carries no authority, declare it a signal.`,
712
+ 3
713
+ )
714
+ end
715
+
716
+ return Policy.checkOf(authorize)
717
+ end
718
+
719
+ --[[
720
+ The type system already refuses these, so reaching one of these messages means the declaration
721
+ was written without the new solver (`PLAN-M1` D-7) or came through an `any`. The message has to
722
+ say what to write instead, because at that point nothing else will.
723
+ ]]
724
+ local FORBIDDEN_REASON: { [string]: string } = {
725
+ authorize = "A channel that authorizes is a command or a query; a signal and an intent carry "
726
+ .. "no authority by definition, and letting them approve requests would make the class "
727
+ .. "name a lie.",
728
+ rate = "The server is the sender on this class, so there is nobody to budget.",
729
+ burst = "Burst is the depth of the rate budget, and this class has no rate to be the depth of.",
730
+ maxBytes = "This class is sent by the server, which is not a peer whose payload size needs "
731
+ .. "policing. The schema still gives it a ceiling.",
732
+ audience = "Only state and event have an audience; an inbound channel has one recipient, "
733
+ .. "which is the server.",
734
+ timeout = "Only a query waits for a reply.",
735
+ returns = "Only a query replies.",
736
+ args = "This class carries `data`, not `args`.",
737
+ data = "A query carries `args` and `returns`, not `data`.",
738
+ unreliable = "A replicated channel sends *changes*, and every change is relative to what that "
739
+ .. "client already has — so one delivered at best effort leaves them permanently and "
740
+ .. "silently wrong rather than one tick stale. If losing a packet is acceptable for this "
741
+ .. "data, declare it with nw.state instead, which sends the whole value and can be "
742
+ .. "unreliable for exactly that reason.",
743
+ }
744
+
745
+ --[[
746
+ Optional, and false unless it is exactly `true`. An unreliable channel is delivered at best
747
+ effort and is not batched — one lost datagram would otherwise cost N events instead of one
748
+ (`RESEARCH §3.7-E`) — so it is a per-channel decision the author makes on purpose.
749
+ ]]
750
+ local function checkedUnreliable(spec: any, class: string): boolean
751
+ local value = spec.unreliable
752
+
753
+ if value ~= nil and type(value) ~= "boolean" then
754
+ error(`nw.{class} takes unreliable as a boolean, got {typeof(value)}`, 3)
755
+ end
756
+
757
+ return value == true
758
+ end
759
+
760
+ local function requireAudience(spec: any, class: string): any
761
+ local audience = spec.audience
762
+
763
+ if type(audience) ~= "table" or type(audience.scope) ~= "string" then
764
+ error(
765
+ `nw.{class} needs an audience. Use nw.audience.everyone, nw.audience.owner, `
766
+ .. `nw.audience.nearby(studs) or nw.audience.select(fn). There is no default: `
767
+ .. `netweave guarantee G3.`,
768
+ 3
769
+ )
770
+ end
771
+
772
+ return audience
773
+ end
774
+
775
+ local function rejectForbidden(spec: any, class: string, fields: { string })
776
+ for _, field in fields do
777
+ if spec[field] ~= nil then
778
+ error(
779
+ `nw.{class} forbids {field}. {FORBIDDEN_REASON[field] or "It has no meaning on this class."}`,
780
+ 3
781
+ )
782
+ end
783
+ end
784
+ end
785
+
786
+ --[=[
787
+ @within Channel
788
+ @function directionOf
789
+ @param class string
790
+ @return (boolean, boolean) -- may the client send on it, may the server
791
+ @private
792
+
793
+ Which side may send on a class, as the receive path asks it.
794
+
795
+ Exported rather than inlined into [make] because `tests/transport_runtime.luau` builds channel
796
+ records by hand to keep its cases about the envelope, and a second copy of this table in a test
797
+ is a table that drifts from the one that matters — which `CLAUDE.md` §9 has already been bitten
798
+ by twice.
799
+ ]=]
800
+ function Channel.directionOf(class: string): (boolean, boolean)
801
+ local inbound = class == "command" or class == "intent" or class == "signal" or class == "query"
802
+ local outbound = class == "state" or class == "event" or class == "query" or class == "replicate"
803
+
804
+ return inbound, outbound
805
+ end
806
+
807
+ local function make(
808
+ class: Class,
809
+ primitive: Primitive,
810
+ data: Types.Descriptor,
811
+ fields: { [string]: any }
812
+ ): any
813
+ local channel: any = {
814
+ class = class,
815
+ primitive = primitive,
816
+ data = data,
817
+ codec = Serdes.fromSchema(data),
818
+
819
+ --[[ Filled in by `nw.namespace`, and by the registry when the protocol is sealed. An id of
820
+ 0 is reserved for control traffic, so it doubles as "not yet assigned"
821
+ (`WIRE-FORMAT.md` §3). ]]
822
+ key = "",
823
+ qualified = "",
824
+ id = 0,
825
+ handler = nil,
826
+ }
827
+
828
+ for field, value in fields do
829
+ channel[field] = value
830
+ end
831
+
832
+ --[[
833
+ Which side may **send** on this channel, as two booleans the receive path can read without a
834
+ string compare.
835
+
836
+ G6 says direction is a class rather than a field, and until M3 phase 9 it was enforced only
837
+ on the views — at analysis time, on the game's own code. The wire had no opinion:
838
+ `Namespace.channelById` resolved every id, `Budget.admit` returned nil for a class with no
839
+ `rate` because there was nothing to charge, and a client's packet on a `nw.state` id was
840
+ decoded and queued on the server. Six hundred of them measured `budget=0, queue=344`.
841
+
842
+ Which also means the reason those classes may not declare a `rate` — "the server is the
843
+ sender on this class, so there is nobody to budget" — rested on a check that did not exist.
844
+ Now it does.
845
+
846
+ `query` is on both lists and is the only class that is: a request goes one way and its reply
847
+ comes back on the same id (`docs/WIRE-FORMAT.md` §2).
848
+ ]]
849
+ channel.fromClient, channel.fromServer = Channel.directionOf(class)
850
+
851
+ --[[
852
+ The byte ceiling, derived from the schema and tightened by a declaration if there is one.
853
+
854
+ Deriving it is what makes it universal: a game that declares nothing still gets a bound,
855
+ because every netweave type is bounded and the layout can add them up. A declared `maxBytes`
856
+ can only lower it — asking for more than the schema can produce is a number that could never
857
+ be reached, and accepting it would let an author believe they had set a limit.
858
+
859
+ The same disease has a second form, and it was live until an audit found it: a declaration on a
860
+ **statically framed** channel is inert. A static payload carries no length prefix — the reader
861
+ already knows where it ends — so there is no claim to check and the ceiling is never consulted.
862
+ `maxBytes = 4` on a schema fixed at fourteen bytes was accepted, stored, and did nothing.
863
+ ]]
864
+ local derived = channel.codec.maxSize
865
+ local declared = channel.maxBytes
866
+
867
+ if declared and channel.codec.framing == "static" then
868
+ error(
869
+ `nw.{class} declares maxBytes = {declared}, and this schema is a fixed {derived} bytes every `
870
+ .. `time. A static payload carries no length to police — the size is guaranteed by the `
871
+ .. `framing rather than by a check, so the declaration would do nothing. Remove it.`,
872
+ 3
873
+ )
874
+ end
875
+
876
+ if declared and declared > derived then
877
+ error(
878
+ `nw.{class} declares maxBytes = {declared}, but this schema can never produce more than `
879
+ .. `{derived} bytes. A ceiling above what the schema can reach is not a limit — remove it, `
880
+ .. `or lower it to the size this channel should actually accept.`,
881
+ 3
882
+ )
883
+ end
884
+
885
+ channel.maxBytes = declared or derived
886
+
887
+ return channel
888
+ end
889
+
890
+ --[=[
891
+ @within Channel
892
+ @function command
893
+ @param spec S -- the declaration: `data`, `rate`, `authorize`
894
+ @return Channel<"command", "none", T, nil, nil>
895
+
896
+ A client-to-server channel that **changes authoritative state**. `authorize` is required.
897
+
898
+ ```lua
899
+ fireWeapon = nw.command({
900
+ data = ShotSchema,
901
+ rate = 20,
902
+ authorize = nw.all(policy.alive, policy.originNearCharacter),
903
+ }),
904
+ ```
905
+
906
+ The handler receives `Trusted<T>` — the payload decoded, in budget, and approved.
907
+ ]=]
908
+ function Channel.command<S>(spec: S): Channel<"command", "none", CommandPayload<S>, nil, nil>
909
+ local raw: any = spec
910
+ rejectForbidden(raw, "command", { "audience", "args", "returns", "timeout", "unreliable" })
911
+
912
+ --[[ Once: `checkedRate` also runs the `rateUnbounded` lint, and a channel that warns twice for
913
+ one declaration is a channel whose warning gets ignored. ]]
914
+ local rate = checkedRate(raw, "command")
915
+
916
+ return make("command", "AuthorizedInbound", requireType(raw, "data", "command"), {
917
+ rate = rate,
918
+ burst = checkedBurst(raw, "command", rate),
919
+ maxBytes = checkedMaxBytes(raw, "command"),
920
+ authorize = requirePolicy(raw, "command"),
921
+ stages = Policy.stagesOf(raw.authorize),
922
+ })
923
+ end
924
+
925
+ --[=[
926
+ @within Channel
927
+ @function intent
928
+ @param spec S -- data, rate
929
+ @return Channel<"intent", "none", T, nil, nil>
930
+
931
+ A continuous observed input: movement, aim, a held button.
932
+
933
+ ```lua
934
+ aim = nw.intent({
935
+ data = t.struct({ pitch = t.f32(-90, 90), yaw = t.f32(-180, 180) }),
936
+ rate = 60,
937
+ }),
938
+ ```
939
+
940
+ :::note
941
+ An intent **coalesces**: at most one value per player per tick is delivered. Stale input has no
942
+ value, so an attacker who fills the rate budget cannot convert that into per-packet server
943
+ work. This is the one place merging is semantically safe — `RESEARCH §3.7-E` argues batching
944
+ unreliable traffic is a semantic error in general, and losing a superseded input is the
945
+ exception that proves it. Coalescing itself lands with the transport in M2.
946
+ :::
947
+ ]=]
948
+ function Channel.intent<S>(spec: S): Channel<"intent", "none", IntentPayload<S>, nil, nil>
949
+ local raw: any = spec
950
+ rejectForbidden(raw, "intent", { "authorize", "audience", "args", "returns", "timeout" })
951
+
952
+ --[[ Once: `checkedRate` also runs the `rateUnbounded` lint, and a channel that warns twice for
953
+ one declaration is a channel whose warning gets ignored. ]]
954
+ local rate = checkedRate(raw, "intent")
955
+
956
+ return make("intent", "AuthorizedInbound", requireType(raw, "data", "intent"), {
957
+ rate = rate,
958
+ burst = checkedBurst(raw, "intent", rate),
959
+ maxBytes = checkedMaxBytes(raw, "intent"),
960
+ unreliable = checkedUnreliable(raw, "intent"),
961
+ })
962
+ end
963
+
964
+ --[=[
965
+ @within Channel
966
+ @function signal
967
+ @param spec S -- data, rate
968
+ @return Channel<"signal", "none", T, nil, nil>
969
+
970
+ A client-to-server channel that carries **no authority**: a menu opened, an emote played, a
971
+ tutorial step acknowledged.
972
+
973
+ ```lua
974
+ openedMenu = nw.signal({
975
+ data = t.struct({ screen = t.u8(0, 8) }),
976
+ rate = 2,
977
+ }),
978
+ ```
979
+
980
+ The handler receives `Untrusted<T>`.
981
+
982
+ :::caution
983
+ This is the class an author reaches for to avoid writing a policy, because it is the shortest
984
+ thing that compiles. `Untrusted<T>` closes that route for code annotated `Trusted<T>`, and only
985
+ for that code — the limit is stated in `DESIGN-API.md` §0 and §10.5 rather than papered over.
986
+ :::
987
+ ]=]
988
+ function Channel.signal<S>(spec: S): Channel<"signal", "none", SignalPayload<S>, nil, nil>
989
+ local raw: any = spec
990
+ rejectForbidden(raw, "signal", { "authorize", "audience", "args", "returns", "timeout" })
991
+
992
+ --[[ Once: `checkedRate` also runs the `rateUnbounded` lint, and a channel that warns twice for
993
+ one declaration is a channel whose warning gets ignored. ]]
994
+ local rate = checkedRate(raw, "signal")
995
+
996
+ return make("signal", "UntrustedInbound", requireType(raw, "data", "signal"), {
997
+ rate = rate,
998
+ burst = checkedBurst(raw, "signal", rate),
999
+ maxBytes = checkedMaxBytes(raw, "signal"),
1000
+ unreliable = checkedUnreliable(raw, "signal"),
1001
+ })
1002
+ end
1003
+
1004
+ --[=[
1005
+ @within Channel
1006
+ @function query
1007
+ @param spec S -- args, returns, rate, timeout, authorize
1008
+ @return Channel<"query", "none", T, R, nil>
1009
+
1010
+ A request that expects an answer. Authorized like a command, because it reads authoritative
1011
+ state and a read is how an exploit finds what to write.
1012
+
1013
+ ```lua
1014
+ getLoadout = nw.query({
1015
+ args = t.u8(0, 2),
1016
+ returns = t.struct({ primary = t.u16, secondary = t.u16 }),
1017
+ rate = 2,
1018
+ timeout = 5,
1019
+ authorize = policy.ownsSlot,
1020
+ }),
1021
+ ```
1022
+ ]=]
1023
+ function Channel.query<S>(spec: S): Channel<"query", "none", QueryArgs<S>, QueryReturns<S>, nil>
1024
+ local raw: any = spec
1025
+ rejectForbidden(raw, "query", { "data", "audience", "unreliable" })
1026
+
1027
+ --[[ Once: `checkedRate` also runs the `rateUnbounded` lint, and a channel that warns twice for
1028
+ one declaration is a channel whose warning gets ignored. ]]
1029
+ local rate = checkedRate(raw, "query")
1030
+
1031
+ local timeout = raw.timeout
1032
+
1033
+ if type(timeout) ~= "number" or timeout ~= timeout or timeout <= 0 or timeout == math.huge then
1034
+ error(
1035
+ `nw.query needs a positive finite timeout in seconds, got {tostring(timeout)}. `
1036
+ .. `A request that never resolves is a leak.`,
1037
+ 2
1038
+ )
1039
+ end
1040
+
1041
+ local returns = requireType(raw, "returns", "query")
1042
+
1043
+ --[[
1044
+ `invoke` reports failure as `nil`, so an answer that can legitimately *be* nil would make the
1045
+ two indistinguishable: a handler returning nothing and a server that never replied would
1046
+ reach the caller as the same value, and the caller's `if answer then` would be right about
1047
+ one of them by accident.
1048
+
1049
+ Refused at the declaration rather than papered over at the call site, because the fix is a
1050
+ line the author writes once — wrap it in a struct, and "no loadout" becomes a field that says
1051
+ so (`DESIGN-API.md` §7).
1052
+ ]]
1053
+ if returns.kind == "optional" then
1054
+ error(
1055
+ "nw.query cannot return an optional at the top level. invoke() reports failure by "
1056
+ .. "returning nil, so an answer that may itself be nil cannot be told apart from a "
1057
+ .. "call that never came back. Wrap it, and the absence becomes a field that says "
1058
+ .. "so: returns = t.struct({ found = t.boolean, value = t.optional(...) }).",
1059
+ 2
1060
+ )
1061
+ end
1062
+
1063
+ local channel = make("query", "AuthorizedInbound", requireType(raw, "args", "query"), {
1064
+ rate = rate,
1065
+ burst = checkedBurst(raw, "query", rate),
1066
+ maxBytes = checkedMaxBytes(raw, "query"),
1067
+ authorize = requirePolicy(raw, "query"),
1068
+ stages = Policy.stagesOf(raw.authorize),
1069
+ timeout = timeout,
1070
+ returns = returns,
1071
+ responseCodec = Serdes.fromSchema(returns),
1072
+ })
1073
+
1074
+ --[[
1075
+ The reply gets a ceiling of its own, derived the same way `make` derives the request's.
1076
+
1077
+ Not declarable, and that asymmetry is the point: `maxBytes` exists to police a *peer*, and
1078
+ the peer on a query is the client asking the question. The answer is this server's own bytes,
1079
+ so the number here is a check on netweave and on the game's handler rather than on anyone
1080
+ else — which is exactly what a derived bound is good at and what a declared one would only
1081
+ make configurable.
1082
+ ]]
1083
+ channel.replyMaxBytes = channel.responseCodec.maxSize
1084
+
1085
+ return channel
1086
+ end
1087
+
1088
+ --[=[
1089
+ @within Channel
1090
+ @function state
1091
+ @param spec S -- data, audience
1092
+ @return Channel<"state", Scope, T, nil, nil>
1093
+
1094
+ Server-to-client replicated state.
1095
+
1096
+ ```lua
1097
+ playerState = nw.state({
1098
+ data = t.struct({ entityId = t.u16, position = t.vector3 }),
1099
+ audience = nw.audience.nearby(120),
1100
+ }),
1101
+ ```
1102
+
1103
+ `broadcast` exists on this channel only if the audience is [Audience.everyone]. That is
1104
+ guarantee G3, and it is a type error rather than a runtime check — broadcasting positional
1105
+ data to everyone is how wallhacks are fed, and a call site that does it is invisible in review.
1106
+ ]=]
1107
+ function Channel.state<S>(spec: S): Channel<"state", OutboundScope<S>, OutboundPayload<S, "state">, nil, nil>
1108
+ local raw: any = spec
1109
+ rejectForbidden(raw, "state", { "rate", "burst", "maxBytes", "authorize", "args", "returns", "timeout" })
1110
+
1111
+ return make("state", "Outbound", requireType(raw, "data", "state"), {
1112
+ audience = requireAudience(raw, "state"),
1113
+ unreliable = checkedUnreliable(raw, "state"),
1114
+ })
1115
+ end
1116
+
1117
+ --[[ A store is a shape rather than a class, so this checks the shape. netweave never requires Charm
1118
+ or Replica — there is no package path for either (`CLAUDE.md` §8) — so anything answering
1119
+ `subjects` and `read` is one, which is also what makes a test's own table a legitimate store
1120
+ rather than a mock. ]]
1121
+ local function requireStore(spec: any): any
1122
+ local store = spec.store
1123
+
1124
+ if type(store) ~= "table" or type(store.subjects) ~= "function" or type(store.read) ~= "function" then
1125
+ error(
1126
+ `nw.replicate needs \`store\`, and got {typeof(store)}. Build one with nw.store.of(table), `
1127
+ .. `nw.store.charm(atom) or nw.store.replica(replicas) — or pass anything `
1128
+ .. `with \`subjects()\` and \`read(subject)\`, because a store is a shape and not a `
1129
+ .. `dependency.`,
1130
+ 3
1131
+ )
1132
+ end
1133
+
1134
+ --[[ ~~And a `changed` that is present has to be callable.~~ **Removed with the field it
1135
+ checked** (M4 phase 8). It was the whole of what netweave ever did with a change signal —
1136
+ validate it at declaration and never call it — and its own message said a broken one "would
1137
+ be silently never called", which was true of a working one too. `src/replication/Store.luau`
1138
+ has the measurement that settled it. ]]
1139
+ return store
1140
+ end
1141
+
1142
+ --[=[
1143
+ @within Channel
1144
+ @function replicate
1145
+ @param spec S -- data, subject, audience, store
1146
+ @return Channel<"replicate", Scope, T, nil, Subject>
1147
+
1148
+ Server-to-client replicated state, sent as **changes** against what each client already has.
1149
+
1150
+ ```lua
1151
+ inventory = nw.replicate({
1152
+ subject = t.u16,
1153
+ data = t.struct({ slot = t.u8, count = t.u16, item = t.string(0, 24) }),
1154
+ audience = nw.audience.owner,
1155
+ store = nw.store.of(byPlayer),
1156
+ }),
1157
+ ```
1158
+
1159
+ The server never calls this channel. `store` is the only way in — netweave reads it once a tick,
1160
+ works out what each client is missing, and sends that. A twelve-field subject where one field
1161
+ moved is three bytes.
1162
+
1163
+ :::caution
1164
+ `unreliable` is **forbidden**, and that is the whole difference between this and [Channel.state].
1165
+ A dropped `state` packet costs one tick of staleness and the next corrects it. A dropped *change*
1166
+ leaves that client permanently and silently wrong, because every later change is relative to a
1167
+ baseline it does not have. If losing one is acceptable, the class you want is `state`.
1168
+ :::
1169
+
1170
+ :::caution
1171
+ **The value a handler receives is frozen, and it is this client's baseline.** A change is folded
1172
+ into what the client already had, and every subtree the patch did not touch is shared with it —
1173
+ that sharing is why one field of twelve costs three bytes. Writing into the value would therefore
1174
+ rewrite the base the *next* patch is applied to, so `value.hp -= 1` for a prediction would leave
1175
+ that field wrong for ever with nothing to say so. Keep your own copy instead:
1176
+ `local mine = table.clone(value)`.
1177
+ :::
1178
+
1179
+ :::note
1180
+ There is only one packet shape. A client with no baseline is sent a change against **nothing**,
1181
+ which writes every field — the same bytes a snapshot would have cost, because the flags fit in
1182
+ the byte the schema's own flags were already using. So there is no snapshot/patch bit on the
1183
+ wire, and a join, a resync and an audience entry are the same code.
1184
+ :::
1185
+ ]=]
1186
+ function Channel.replicate<S>(spec: S): Channel<
1187
+ "replicate",
1188
+ OutboundScope<S>,
1189
+ ReplicatePayload<S>,
1190
+ nil,
1191
+ ReplicateSubject<S>
1192
+ >
1193
+ local raw: any = spec
1194
+ rejectForbidden(
1195
+ raw,
1196
+ "replicate",
1197
+ { "rate", "burst", "maxBytes", "authorize", "args", "returns", "timeout", "unreliable" }
1198
+ )
1199
+
1200
+ local data = requireType(raw, "data", "replicate")
1201
+ local channel = make("replicate", "Outbound", data, {
1202
+ audience = requireAudience(raw, "replicate"),
1203
+ subject = requireType(raw, "subject", "replicate"),
1204
+ store = requireStore(raw),
1205
+
1206
+ --[[ Not `checkedUnreliable`, because the field is forbidden above and this is the answer
1207
+ rather than a default that could be overridden. ]]
1208
+ unreliable = false,
1209
+ })
1210
+
1211
+ --[[ Two derived codecs beside the state one `make` built. `subjectCodec` names which value this
1212
+ is — the only class that needs to, because the client keeps one per subject — and `delta`
1213
+ is the change itself. ]]
1214
+ channel.subjectCodec = Serdes.fromSchema(channel.subject)
1215
+ channel.delta = Delta.build(Ir.lower(data))
1216
+
1217
+ --[[
1218
+ The wire ceiling is the *patch's*, not the state's, and it is larger: a change carries one
1219
+ bit per field on top of the values. A client refuses against this before decoding, so
1220
+ leaving it at the state's ceiling would have a replicated channel refuse its own honest
1221
+ traffic — which is precisely the defect an external review found in `Ir.ceiling` and
1222
+ `PLAN-M3` phase 9 fixed. The subject's own bytes are on top of both.
1223
+ ]]
1224
+ channel.maxBytes = channel.subjectCodec.maxSize + channel.delta.layout.maxSize
1225
+
1226
+ --[[
1227
+ How a change is framed, which is neither codec's answer alone.
1228
+
1229
+ **Always `counted`.** The same channel emits a removal — the flag bytes and nothing behind
1230
+ them — and a change carrying values, so a reader cannot know from the schema where a refused
1231
+ one ends, and stepping over a refused packet is guarantee G5. That is the length prefix
1232
+ earning its byte rather than spending one.
1233
+
1234
+ The instance count is written only when something on this channel can carry an Instance,
1235
+ which for most replicated state is nothing at all.
1236
+ ]]
1237
+ local carriesInstances = not (channel.subjectCodec.instances == 0 and channel.delta.layout.instances == 0)
1238
+
1239
+ channel.changeInstances = carriesInstances
1240
+ channel.changeFraming = table.freeze({
1241
+ framing = "counted",
1242
+ instances = if carriesInstances then nil else 0,
1243
+ fixedSize = nil,
1244
+ })
1245
+
1246
+ return channel
1247
+ end
1248
+
1249
+ --[=[
1250
+ @within Channel
1251
+ @function event
1252
+ @param spec S -- data, audience
1253
+ @return Channel<"event", Scope, T, nil, nil>
1254
+
1255
+ A server-to-client occurrence — something happened, once.
1256
+
1257
+ ```lua
1258
+ hitConfirmed = nw.event({
1259
+ data = t.struct({ victim = t.u16, damage = t.u8 }),
1260
+ audience = nw.audience.owner,
1261
+ }),
1262
+ ```
1263
+
1264
+ The difference from [Channel.state] is what M4 does with it: state is a value that can be
1265
+ delta-replicated and re-sent to a late joiner, an event is a moment that cannot.
1266
+ ]=]
1267
+ function Channel.event<S>(spec: S): Channel<"event", OutboundScope<S>, OutboundPayload<S, "event">, nil, nil>
1268
+ local raw: any = spec
1269
+ rejectForbidden(raw, "event", { "rate", "burst", "maxBytes", "authorize", "args", "returns", "timeout" })
1270
+
1271
+ return make("event", "Outbound", requireType(raw, "data", "event"), {
1272
+ audience = requireAudience(raw, "event"),
1273
+ unreliable = checkedUnreliable(raw, "event"),
1274
+ })
1275
+ end
1276
+
1277
+ --[=[
1278
+ @within Channel
1279
+ @function isChannel
1280
+ @param value any
1281
+ @return boolean
1282
+ @private
1283
+ ]=]
1284
+ function Channel.isChannel(value: any): boolean
1285
+ return type(value) == "table" and type((value :: any).primitive) == "string"
1286
+ end
1287
+
1288
+ return Channel