@rbxts/netweave 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,490 @@
1
+ --!strict
2
+ --!optimize 2
3
+
4
+ --[=[
5
+ @class netweave
6
+
7
+ A Roblox networking library whose first-order goals are security and structure.
8
+
9
+ ```lua
10
+ local nw = require(Packages.netweave)
11
+ local t = nw.types
12
+
13
+ return nw.namespace("combat", {
14
+ fireWeapon = nw.command({
15
+ data = t.struct({ origin = t.vector3, direction = t.unitVector3, seq = t.u16 }),
16
+ rate = 20,
17
+ authorize = nw.all(policy.alive, policy.originNearCharacter),
18
+ }),
19
+
20
+ playerState = nw.state({
21
+ data = t.struct({ entityId = t.u16, position = t.vector3 }),
22
+ audience = nw.audience.nearby(120),
23
+ }),
24
+ })
25
+ ```
26
+
27
+ What makes this different from the libraries surveyed in `docs/RESEARCH-AND-PLAN.md` is not
28
+ how a packet is sent — every one of them answers that about the same way. It is **what the API
29
+ refuses to let you write**:
30
+
31
+ | | Guarantee | Violating code |
32
+ |---|---|---|
33
+ | G1 | An inbound channel that changes authoritative state has no listener until a policy is attached | type error |
34
+ | G2 | Every inbound channel declares a rate budget. There is no unlimited | type error |
35
+ | G3 | Every server-to-client channel declares its audience. `broadcast` exists only where the audience is everyone | type error |
36
+ | G4 | Wire data never reaches `error()`. Rejections are values, routed to an observer. The sidecar is wire data, and the read and dispatch phases are guarded rather than trusted | not expressible |
37
+ | G5 | Length-prefixed framing: one malformed packet cannot stop the rest of its batch | not expressible |
38
+ | G6 | Direction is a class, not a string field | type error |
39
+
40
+ :::caution
41
+ netweave **requires Luau's new type solver** (`LuauSolverV2`). Half the guarantees above are
42
+ type errors or they are nothing, and on the stock solver you would see analysis errors inside
43
+ code you did not write. See `docs/DESIGN-API.md` §7.
44
+ :::
45
+ ]=]
46
+
47
+ --[[
48
+ The public surface is assembled here and nowhere else. Each module below owns one idea and is
49
+ independently testable; this file exists so a game writes `nw.command` rather than requiring
50
+ six paths, and so there is exactly one place to look for what netweave exposes.
51
+ ]]
52
+
53
+ local Audience = require("./api/Audience")
54
+ local Driver = require("./transport/Driver")
55
+ local Channel = require("./api/Channel")
56
+ local Config = require("./api/Config")
57
+ local Context = require("./api/Context")
58
+ local Namespace = require("./api/Namespace")
59
+ local Protocol = require("./api/Protocol")
60
+ local Observer = require("./api/Observer")
61
+ local Policy = require("./api/Policy")
62
+ local Store = require("./replication/Store")
63
+ local Transport = require("./api/Transport")
64
+ local Trust = require("./api/Trust")
65
+ local Types = require("./types")
66
+ local View = require("./api/View")
67
+
68
+ --[[
69
+ Requiring netweave inside a running game installs the transport. There is nothing to configure
70
+ and no step to remember: a game that declared its channels correctly has already said everything
71
+ the transport needs, and an install call in every game would be a step to forget.
72
+
73
+ Running, and not only inside Roblox (netweave-typescript patch 0002). Studio's Edit DataModel has
74
+ a `game` and no peer: it answers `IsClient`, so the client link waited 30 seconds for remotes no
75
+ server would create and then raised, and a unit test runner requiring a module that imports
76
+ netweave in Edit mode never got it back. There netweave is what it is under lune: channels are
77
+ declared, schemas exercised, handlers attached, and a send raises that no transport is installed.
78
+ Edit mode is never running; a playtest and a live server are, and the require there installs as
79
+ before.
80
+
81
+ The guard is a check rather than a `pcall`, so that a genuine failure inside `install` is loud.
82
+ Under lune there is no `game`, and the whole transport is testable there because Roblox lives
83
+ behind `Link` and `Recipients` (`tests/transport_runtime.luau`).
84
+ ]]
85
+ if typeof(game) == "Instance" and game:GetService("RunService"):IsRunning() then
86
+ Driver.install()
87
+ end
88
+
89
+ local nw = {}
90
+
91
+ --[=[
92
+ @prop milestone string
93
+ @within netweave
94
+
95
+ Which milestone this build is. `"M5"`.
96
+
97
+ It moves when the **plan** for the next milestone appears, not when that milestone's code lands,
98
+ because the question this answers is "what was the tree doing when it produced that number" and
99
+ a tree with `PLAN-M4.md` in it is doing M4. `master` still says M3, because that is where M3 is.
100
+
101
+ netweave has no release versions yet, so this is the coarsest true thing it can say about
102
+ itself, and it exists because something else needed it to be true: the benchmark writes the
103
+ subject of every run into the run document, and it wrote `"M2"` for the whole of M3, because the
104
+ string was typed into the harness rather than read from the library. A results file that
105
+ misattributes its own subject is worse than one with no attribution — it is evidence for the
106
+ wrong thing (`CLAUDE.md` §5). Read this instead of typing it.
107
+
108
+ :::note
109
+ The wire format has its own version, which is not this one and moves for different reasons. See
110
+ `docs/WIRE-FORMAT.md` and `nw.protocol()`.
111
+ :::
112
+ ]=]
113
+ nw.milestone = "M5"
114
+
115
+ --[=[
116
+ @prop types Types
117
+ @within netweave
118
+
119
+ The type vocabulary. One declaration yields the payload type, the validation and the
120
+ serialisation.
121
+ ]=]
122
+ nw.types = Types
123
+
124
+ --[=[
125
+ @prop audience Audience
126
+ @within netweave
127
+
128
+ Who a `state` or `event` reaches. Guarantee G3.
129
+ ]=]
130
+ nw.audience = Audience
131
+
132
+ -- Channel classes -------------------------------------------------------------------------------
133
+
134
+ nw.command = Channel.command
135
+ nw.intent = Channel.intent
136
+ nw.signal = Channel.signal
137
+ nw.query = Channel.query
138
+ nw.state = Channel.state
139
+ nw.event = Channel.event
140
+
141
+ --[=[
142
+ @prop replicate (spec) -> Channel
143
+ @within netweave
144
+
145
+ Server-to-client state, sent as **changes** against what each client already has. The seventh
146
+ class, and the one the server never calls: its `store` is the only way in.
147
+
148
+ :::caution
149
+ The value a handler receives is **frozen**: it is this client's baseline, and the next change is
150
+ applied to it. `table.clone` it if you need one to write to.
151
+ :::
152
+
153
+ See `docs/DESIGN-API.md` §3, "Replication is a seventh class, not `state` growing up".
154
+ ]=]
155
+ nw.replicate = Channel.replicate
156
+
157
+ --[=[
158
+ @prop store Store
159
+ @within netweave
160
+
161
+ Where the game keeps what `nw.replicate` replicates. `nw.store.of` for a plain table,
162
+ `nw.store.charm` for a Charm atom, `nw.store.replica` for ReplicaService.
163
+
164
+ netweave never requires either library, and asks nothing of them either: a store is a shape
165
+ rather than a dependency, and anything with `subjects()` and `read(subject)` is one.
166
+ ]=]
167
+ nw.store = Store
168
+
169
+ -- Policies --------------------------------------------------------------------------------------
170
+
171
+ nw.policy = Policy.policy
172
+ nw.all = Policy.all
173
+ nw.allow = Policy.allow
174
+ nw.deny = Policy.deny
175
+
176
+ -- Trust -----------------------------------------------------------------------------------------
177
+
178
+ nw.validate = Trust.validate
179
+
180
+ -- Rejections ------------------------------------------------------------------------------------
181
+
182
+ nw.observe = Observer.observe
183
+
184
+ --[=[
185
+ @within netweave
186
+ @function diagnostics
187
+ @return Observer.Diagnostics
188
+
189
+ Every refusal since the counters were last reset, by channel and stage.
190
+
191
+ ```lua
192
+ for channel, stages in nw.diagnostics().channels do
193
+ for stage, tally in stages do
194
+ print(channel, stage, tally.count, tally.bytes)
195
+ end
196
+ end
197
+ ```
198
+
199
+ The console goes quiet after a few reports per channel and stage so a flood does not become the
200
+ outage, which makes this the only way to answer "is this channel refusing more than it was" —
201
+ the question that separates a bug from an attack.
202
+ ]=]
203
+ nw.diagnostics = Observer.diagnostics
204
+
205
+ -- Settings --------------------------------------------------------------------------------------
206
+
207
+ --[=[
208
+ @within netweave
209
+ @function configure
210
+ @param settings Config.Settings
211
+
212
+ Global settings, in the shape ESLint made familiar.
213
+
214
+ ```lua
215
+ nw.configure({
216
+ rules = {
217
+ budget = "warn", -- a sender over its declared rate
218
+ authorize = "error", -- with a traceback, and suppressed like any other
219
+ handler = "warn",
220
+ },
221
+ limits = { queueCapacity = 512 },
222
+ })
223
+ ```
224
+
225
+ Call it before declaring channels: limits are read when the transport builds the thing they
226
+ limit, and a queue that already exists keeps the capacity it was created with.
227
+
228
+ :::caution `"off"` is discouraged, and it is not an off switch
229
+ No severity turns enforcement off. A packet refused at `budget` is refused whatever `budget` is
230
+ set to — `"off"` silences netweave's console output for that stage and nothing else, and
231
+ callbacks attached with [netweave.observe] keep receiving it.
232
+
233
+ Reach for `"off"` when a stage is *expected* to fire in normal play and the log is drowning
234
+ something else out — a `signal` channel that refuses under load by design, say. Reaching for it
235
+ because a warning is annoying removes the only notice a game gets that it is dropping traffic,
236
+ which is the failure `RESEARCH §3.7-K` documents in Warp and the reason these defaults are on.
237
+ :::
238
+ ]=]
239
+ --[[ `S` alone, not `S & Config.Settings`. The intersection reads correctly and rejects every call:
240
+ Luau binds `S` to the argument's own type and then wants the intersection to be exactly that,
241
+ so a settings table that omits any optional field — which is all of them — fails. The names and
242
+ the value types are both checked by `CheckedSettings`, which says what is wrong in one line
243
+ rather than eight. ]]
244
+ nw.configure = function<S>(settings: S): Config.CheckedSettings<S, Config.Snapshot>
245
+ Config.configure(settings :: any)
246
+
247
+ --[[
248
+ `contextGuard` is applied here rather than read inside `Context` because the guard is
249
+ checked once per packet and `Config` would be a second table index on that path. Pushing it
250
+ at configure time keeps the read side a single upvalue, which is what `CLAUDE.md` §4 asks
251
+ of anything the receive loop touches.
252
+ ]]
253
+ local guard = Config.contextGuard()
254
+
255
+ if guard ~= nil then
256
+ Context.setGuarded(guard)
257
+ end
258
+
259
+ --[[ The declared return is a type function the analyzer cannot reduce while `S` is free, so the
260
+ cast is the only way to say "this is that". The type function is in the signature for its
261
+ `error()`, which is what rejects a misspelled rule at the call site; the value handed back
262
+ is a plain snapshot either way. ]]
263
+ return Config.snapshot() :: any
264
+ end
265
+
266
+ --[=[
267
+ @within netweave
268
+ @prop config Config
269
+ @within netweave
270
+
271
+ The settings themselves: `nw.config.snapshot()` for what is in force, `nw.config.describe()`
272
+ for every rule with its default and one line on what it reports.
273
+ ]=]
274
+ nw.config = Config
275
+
276
+ --[=[
277
+ @within netweave
278
+ @function namespace
279
+ @param name string
280
+ @param channels D -- a table of channels
281
+ @return Views<D> -- `.server` and `.client`, typed per channel class
282
+
283
+ Declares a namespace and returns its two directional views.
284
+
285
+ ```lua
286
+ local combat = nw.namespace("combat", {
287
+ fireWeapon = nw.command({ ... }),
288
+ })
289
+
290
+ combat.server.fireWeapon:listen(function(ctx, shot) end)
291
+ combat.client.fireWeapon:send(shot)
292
+ ```
293
+
294
+ The views are typed per channel class: a `command` has `listen` on the server and `send` on the
295
+ client, and neither has the other. `combat.server.fireWeapon:send(...)` is an analysis error,
296
+ not a runtime check — guarantee G6.
297
+ ]=]
298
+ function nw.namespace<D>(name: string, channels: D): View.Views<D>
299
+ --[[ Level 2 is the module calling `nw.namespace`: its full name on Roblox, a path under lune.
300
+ `Namespace.declare` refuses the two prefixes a client can never require (`PLAN-M5` D-7). ]]
301
+ local source = debug.info(2, "s")
302
+
303
+ return (Namespace.declare(name, channels :: any, source) :: any) :: View.Views<D>
304
+ end
305
+
306
+ --[=[
307
+ @within netweave
308
+ @function protocol
309
+ @return Protocol
310
+
311
+ The agreed protocol: an FNV-1a hash over every channel's name, class and **lowered schema**, plus
312
+ the names themselves in id order.
313
+
314
+ Both peers compute this independently and the client sends its hash as the first packet it ever
315
+ sends. A peer whose hash differs is refused at stage `"protocol"` from that point on — every
316
+ packet between them would otherwise decode as a different channel, successfully, and be handed
317
+ to a handler as a well-formed payload (`docs/WIRE-FORMAT.md` §4).
318
+
319
+ :::note
320
+ The hash deliberately ignores `rate`, `burst`, `maxBytes`, `authorize`, `audience` and
321
+ `unreliable`. Those are one side's policy, and a hash that moved when a server tuned a rate limit
322
+ would force a client redeploy for a server-side edit.
323
+ :::
324
+ ]=]
325
+ nw.protocol = Namespace.protocol
326
+
327
+ --[=[
328
+ @within netweave
329
+ @function signature
330
+ @return string
331
+
332
+ The text the protocol hash is taken over: every channel, in id order, with its class and the
333
+ shape its schema lowered to.
334
+
335
+ ```lua
336
+ print(nw.signature())
337
+ --> combat.fireWeapon|command
338
+ --> data=static/14/14/0:struct(origin:vector3(...)seq:number(storage=u16;...))
339
+ ```
340
+
341
+ A hash that differs tells you *that* two builds disagree and nothing about where. Print this on
342
+ both sides and diff it: the line that differs is the declaration that differs. That is the whole
343
+ affordance, and without it "the hashes do not match" is a dead end.
344
+ ]=]
345
+ nw.signature = function(): string
346
+ local protocol = Namespace.protocol()
347
+ local byName: { [string]: any } = {}
348
+
349
+ for _, qualified in protocol.names do
350
+ byName[qualified] = Namespace.channelByName(qualified)
351
+ end
352
+
353
+ return Protocol.signature(protocol.names, byName)
354
+ end
355
+
356
+ --[=[
357
+ @type Trusted<T> T
358
+ @within netweave
359
+
360
+ A value that has passed the checks its channel declares.
361
+ ]=]
362
+ export type Trusted<T> = Trust.Trusted<T>
363
+
364
+ --[=[
365
+ @type Untrusted<T> T
366
+ @within netweave
367
+
368
+ A value that arrived from a client and conforms to its schema, and nothing more.
369
+ ]=]
370
+ export type Untrusted<T> = Trust.Untrusted<T>
371
+
372
+ export type Ctx = Context.Ctx
373
+ export type Verdict = Policy.Verdict
374
+ export type Rejection = Observer.Rejection
375
+ export type Stage = Observer.Stage
376
+ export type Diagnostics = Observer.Diagnostics
377
+ export type Tally = Observer.Tally
378
+ export type Protocol = Namespace.Protocol
379
+ export type Views<D> = View.Views<D>
380
+ export type Severity = Config.Severity
381
+ export type Settings = Config.Settings
382
+
383
+ --[[
384
+ A public value gets a public type (`PLAN-M5` D-3). Until this milestone `nw.policy`'s return,
385
+ `nw.audience.nearby`'s return, `nw.configure`'s snapshot and `nw.store.of`'s result had no name a
386
+ game could write through `nw` — M4-1 found the first three, and `tools/exports` now demands one
387
+ per value family so the list cannot regrow. Every alias below is a name for something a game
388
+ already holds, and none of them widens what it can do with it.
389
+ ]]
390
+
391
+ --[=[
392
+ @type Policy<T> Policy<T>
393
+ @within netweave
394
+
395
+ What `nw.policy` and `nw.all` return, and what `authorize` takes: a policy over a payload `T`.
396
+ ]=]
397
+ export type Policy<T> = Policy.Policy<T>
398
+
399
+ --[=[
400
+ @type Check<T> (ctx: Ctx, payload: T) -> Verdict
401
+ @within netweave
402
+
403
+ The per-request half of a policy, for a game that keeps checks as values before wrapping them.
404
+ ]=]
405
+ export type Check<T> = Policy.Check<T>
406
+
407
+ --[=[
408
+ @type Factory<T> (config: any) -> (Check<T>, ...(() -> ())?)
409
+ @within netweave
410
+
411
+ What `nw.policy` takes: the load-time half, returning the check and optionally the server stage.
412
+ ]=]
413
+ export type Factory<T> = Policy.Factory<T>
414
+
415
+ --[=[
416
+ @type Audience<S> Audience<S>
417
+ @within netweave
418
+
419
+ What `nw.audience.*` are and what `audience` takes. `S` is `"everyone"` or `"subset"`, and it is
420
+ what gives a channel `broadcast` or withholds it.
421
+ ]=]
422
+ export type Audience<S> = Audience.Audience<S>
423
+
424
+ --[=[
425
+ @type Store Store
426
+ @within netweave
427
+
428
+ What `nw.store.of`, `nw.store.charm` and `nw.store.replica` return, and what `replicate` takes.
429
+ ]=]
430
+ export type Store = Store.Store
431
+
432
+ --[=[
433
+ @type Observer (rejection: Rejection) -> ()
434
+ @within netweave
435
+
436
+ What `nw.observe` takes.
437
+ ]=]
438
+ export type Observer = Observer.Observer
439
+
440
+ --[=[
441
+ @type Snapshot Snapshot
442
+ @within netweave
443
+
444
+ What `nw.configure` and `nw.config.snapshot()` return: the settings in force, frozen.
445
+ ]=]
446
+ export type Snapshot = Config.Snapshot
447
+
448
+ --[=[
449
+ @type Described Described
450
+ @within netweave
451
+
452
+ One row of `nw.config.describe()`.
453
+ ]=]
454
+ export type Described = Config.Described
455
+
456
+ --[=[
457
+ @type Rules Rules
458
+ @within netweave
459
+
460
+ The `rules` section of a settings table: a severity per rule.
461
+ ]=]
462
+ export type Rules = Config.Rules
463
+
464
+ --[=[
465
+ @type Limits Limits
466
+ @within netweave
467
+
468
+ The `limits` section of a settings table: a number per limit.
469
+ ]=]
470
+ export type Limits = Config.Limits
471
+
472
+ --[=[
473
+ @prop internal table
474
+ @within netweave
475
+ @private
476
+
477
+ The seams M2 attaches to, and the resets the test suite needs. Not part of the public surface:
478
+ everything here either belongs to a milestone that has not landed or exists to undo state that
479
+ a game has no reason to undo.
480
+ ]=]
481
+ nw.internal = table.freeze({
482
+ config = Config,
483
+ transport = Transport,
484
+ context = Context,
485
+ observer = Observer,
486
+ namespaces = Namespace,
487
+ view = View,
488
+ })
489
+
490
+ return table.freeze(nw)