@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,135 @@
1
+ --!strict
2
+ --!optimize 2
3
+
4
+ --[=[
5
+ @class Transport
6
+
7
+ The seam between the declaration surface and the thing that actually moves bytes.
8
+
9
+ M1 defined what a channel *is*: its schema, its budget, its audience, its policy, its wire id.
10
+ M2 defined what happens when you send on one — batching, flush scheduling, budget enforcement,
11
+ audience evaluation, intent coalescing — and M4 added replication. This module is where that
12
+ second half attaches.
13
+ ]=]
14
+
15
+ --[[
16
+ Written as a hole rather than as a stub that pretends to work.
17
+
18
+ A `send` that silently did nothing would make the M1 test suite pass and every M1 integration
19
+ fail in a way that looks like packet loss. Raising names the milestone instead, so the failure
20
+ says what is missing rather than leaving it to be inferred from a game that does not respond.
21
+
22
+ This is a programmer error — the game called `send` in a build with no transport — so raising
23
+ is correct. It is not wire data, and G4 is not in play.
24
+ ]]
25
+
26
+ local Transport = {}
27
+
28
+ --[=[
29
+ @interface Driver
30
+ @within Transport
31
+ .send (channel: any, value: any) -> ()
32
+ .publish (channel: any, subject: any, value: any) -> ()
33
+ .broadcast (channel: any, value: any) -> ()
34
+ .invoke (channel: any, args: any) -> (any?, string?)
35
+ .dispatch (channel: any, handler: any) -> () -- called when a handler is attached
36
+
37
+ What M2 installs. Every method receives the channel record, so the driver reads the rate,
38
+ audience, policy and codec off the declaration rather than being told them again.
39
+ ]=]
40
+ export type Driver = {
41
+ send: (channel: any, value: any) -> (),
42
+ publish: (channel: any, subject: any, value: any) -> (),
43
+ broadcast: (channel: any, value: any) -> (),
44
+ invoke: (channel: any, args: any) -> (any?, string?),
45
+ dispatch: (channel: any, handler: any) -> (),
46
+ }
47
+
48
+ local driver: Driver? = nil
49
+
50
+ --[=[
51
+ @within Transport
52
+ @function install
53
+ @param installed Driver
54
+ @private
55
+
56
+ Attaches the transport. Called once, by M2.
57
+ ]=]
58
+ function Transport.install(installed: Driver)
59
+ if driver ~= nil then
60
+ error(
61
+ "a transport is already installed. Requiring netweave installs it once, from "
62
+ .. "src/netweave.luau, and a second install would leave half the channels writing "
63
+ .. "into a buffer the other half never flushes. If this is a test swapping the "
64
+ .. "transport out, call Transport.uninstall() first.",
65
+ 2
66
+ )
67
+ end
68
+
69
+ driver = installed
70
+ end
71
+
72
+ --[=[
73
+ @within Transport
74
+ @function installed
75
+ @return boolean
76
+
77
+ Whether anything can actually be sent yet.
78
+ ]=]
79
+ function Transport.installed(): boolean
80
+ return driver ~= nil
81
+ end
82
+
83
+ --[=[
84
+ @within Transport
85
+ @function driver
86
+ @param operation string -- what was attempted, for the message
87
+ @return Driver
88
+ @private
89
+ ]=]
90
+ function Transport.driver(operation: string): Driver
91
+ local installed = driver
92
+
93
+ if not installed then
94
+ error(
95
+ --[[ The message named unfinished milestones until M3 phase 7, which was true when it was
96
+ written and became a lie the moment the transport landed. What is left is the one
97
+ case that can still reach here: netweave required somewhere `game` does not exist. ]]
98
+ `{operation} needs a transport, and none is installed. Requiring netweave inside Roblox `
99
+ .. `installs it; outside Roblox — under lune, or in a plain Luau host — there are no `
100
+ .. `remotes to install, so a channel can be declared, its schema exercised and its `
101
+ .. `handlers attached, and nothing crosses the wire. In a test, install a loopback `
102
+ .. `with Transport.install(...).`,
103
+ 3
104
+ )
105
+ end
106
+
107
+ return installed
108
+ end
109
+
110
+ --[=[
111
+ @within Transport
112
+ @function peek
113
+ @return Driver?
114
+ @private
115
+
116
+ The installed driver, or nil. [Transport.driver] raises when there is none, which is right for
117
+ the send path and wrong for a caller that wants to put back what it found — a test that installs
118
+ a fake has to leave the real one where it was, or everything after it sends into a hole.
119
+ ]=]
120
+ function Transport.peek(): Driver?
121
+ return driver
122
+ end
123
+
124
+ --[=[
125
+ @within Transport
126
+ @function uninstall
127
+ @private
128
+
129
+ Detaches the transport. Exists so a test can install a fake one and put things back.
130
+ ]=]
131
+ function Transport.uninstall()
132
+ driver = nil
133
+ end
134
+
135
+ return Transport
@@ -0,0 +1,393 @@
1
+ --!strict
2
+ --!optimize 2
3
+
4
+ --[=[
5
+ @class Trust
6
+
7
+ Provenance in the type. `Untrusted<T>` says: this value came off the wire.
8
+
9
+ ```lua
10
+ local function giveItem(player: Player, amount: nw.Trusted<{ id: number, count: number }>) end
11
+
12
+ combat.openedMenu:listen(function(ctx, request) -- request: Untrusted<...>
13
+ log("menu " .. request.id) -- fine
14
+ giveItem(ctx.player, request) -- type error
15
+ end)
16
+ ```
17
+
18
+ Only three things produce `Trusted<T>`: a `command` handler, a `query` handler, and
19
+ [Trust.validate] — plus an explicit cast, `(value :: any) :: nw.Trusted<T>`, for server-authored
20
+ data that never came off a wire. **There is no `nw.untrust`.** An unwrap function would be reached for
21
+ reflexively and the brand would become decoration — the same reason `unsafe` in Rust is ugly
22
+ on purpose (`DESIGN-API.md` §10.6).
23
+ ]=]
24
+
25
+ --[[
26
+ Enforcement is opt-in on the game's side, and that is not a shortcut. Luau is structurally
27
+ typed, so a value usable as `T` is accepted anywhere `T` is; `Untrusted<T>` is deliberately a
28
+ subtype of `T`, which is what lets arithmetic, logging and UI work without ceremony. The price
29
+ is that it also satisfies an un-annotated `f(x: T)`.
30
+
31
+ Deciding which of your functions carry authority is the discipline this library sells, so
32
+ requiring that to be written down is the intended cost, not an oversight (`DESIGN-API.md` §6).
33
+ ]]
34
+
35
+ --[[
36
+ **The tag is required, and that is a correction.**
37
+
38
+ It was `{ __nwTrusted: true? }` — optional — until M3 phase 3, and an optional property is one
39
+ a table literal is inferred to satisfy by not having it. So `giveItem({ screen = 1 })` compiled,
40
+ and the claim above that only three things produce `Trusted<T>` was **false**: a literal of the
41
+ right shape produced one too, and the one-line laundering
42
+
43
+ giveItem({ screen = untrusted.screen })
44
+
45
+ rebuilt an untrusted payload into a trusted one with nothing to see. Measured, then fixed by
46
+ making the property required; `tests/api_reject.luau` cases 16 and 17 are those two lines.
47
+
48
+ The cost is that the type asserts a field the runtime does not have. Reading `__nwTrusted` off
49
+ a payload gives `nil` where the type promises `true`. That is a phantom on a `__nw`-prefixed
50
+ name nobody reads, and it is a much smaller lie than the alternative §6 rejected — a wrapper,
51
+ which would misdescribe the whole value and allocate one per packet.
52
+
53
+ **What it still does not stop.** Writing the tag out — `giveItem({ screen = 1, __nwTrusted = true })`
54
+ — type-checks. That is deliberate: the escape hatch has to exist for server-authored data, and
55
+ a forgery you have to spell is one a reviewer sees and `grep` finds. The supported spelling is a
56
+ cast, `(value :: any) :: nw.Trusted<T>`, which is pinned in `tests/api_ok.luau`.
57
+
58
+ **The four places that build a tag must agree**, and they cannot share code: a `type function`
59
+ body sees only the `types` library, so `src/api/View.luau` builds its own. `tests/api_ok.luau`
60
+ asserts the agreement by assigning one to the other, and a divergence fails it — verified by
61
+ changing one side alone.
62
+ ]]
63
+
64
+ local Buffer = require("../codec/Buffer")
65
+ local Serdes = require("../codec/Serdes")
66
+ local Types = require("../types")
67
+
68
+ local Trust = {}
69
+
70
+ --[[
71
+ Measured in `spike/declare/brand.luau`, and the reason both brands are type functions rather
72
+ than the plain intersections `DESIGN-API.md` §6 originally specified:
73
+
74
+ `number & { __nwTrusted: true? }` normalises to `never`. A branded scalar therefore rejects
75
+ every legitimate use of the value — `wire + 1` does not type-check — while satisfying *every*
76
+ parameter, including `Trusted<number>`, because `never` is a subtype of everything. That is
77
+ strictly worse than no brand at all: it breaks the honest caller and admits the dishonest one.
78
+
79
+ So the brand binds to table payloads and passes scalars through unchanged. A scalar payload is
80
+ unbranded and the type says so, rather than pretending to a guarantee Luau cannot express.
81
+ ]]
82
+
83
+ --[=[
84
+ @type Trusted<T> T
85
+ @within Trust
86
+
87
+ A value that has passed the checks its channel declares. Produced by a `command` handler, a
88
+ `query` handler, and [Trust.validate], and by nothing else.
89
+
90
+ :::caution
91
+ The brand binds to **table** payloads only. `Trusted<number>` is `number`, because Luau
92
+ normalises the intersection of a primitive and a table to `never`, which would satisfy every
93
+ parameter rather than none. Wrap a scalar in a one-field struct if you want the brand on it.
94
+ :::
95
+ ]=]
96
+ --[[
97
+ **A union is branded component by component, and until M4 it was not branded at all.**
98
+
99
+ `T?` is a union, and the test that guarded these functions was `value:is("table")` — false for a
100
+ union, so an optional payload came back untouched. A `signal` whose `data` is
101
+ `t.optional(t.struct({ ... }))` handed its handler a plain `{ screen: number }?`, and
102
+ `nw.Trusted<Req?>` reduced to `Req?` as well, so the two coincided: untrusted client data reached
103
+ a parameter annotated for trusted data **with no cast to grep for** (M4 report).
104
+
105
+ The documented limit was "scalar payloads are unbranded", which is still true and is a different
106
+ sentence: `Trusted<number>` is `number` because Luau normalises the intersection of a primitive
107
+ and a table to `never`, which would satisfy every parameter rather than none. An optional table
108
+ is not a scalar, and there was never a reason for it to be exempt.
109
+
110
+ Branding each table component and rebuilding the union keeps the narrowed case working too:
111
+ `if r then authoritative(r) end` narrows to the branded table, so the brand survives the `if`
112
+ the payload's optionality forces a game to write.
113
+ ]]
114
+ -- selene: allow(undefined_variable)
115
+ type function branded(payload: type, name: string): type
116
+ local value = types.copy(payload)
117
+
118
+ local function tagged(inner)
119
+ local tag = types.newtable()
120
+ tag:setproperty(types.singleton(name), types.singleton(true))
121
+ return types.intersectionof(inner, tag)
122
+ end
123
+
124
+ if value:is("table") then
125
+ return tagged(value)
126
+ end
127
+
128
+ if value:is("union") then
129
+ local rebuilt = nil
130
+ local marked = false
131
+
132
+ for _, component in value:components() do
133
+ local part = component
134
+
135
+ if component:is("table") then
136
+ part = tagged(component)
137
+ marked = true
138
+ end
139
+
140
+ rebuilt = if rebuilt then types.unionof(rebuilt, part) else part
141
+ end
142
+
143
+ --[[ A union with no table in it is a scalar union — `number | string` — and the caution
144
+ above applies to it whole. Returning the copy rather than the rebuilt one keeps that
145
+ case byte-identical to what it was. ]]
146
+ if marked and rebuilt then
147
+ return rebuilt
148
+ end
149
+ end
150
+
151
+ return value
152
+ end
153
+
154
+ -- selene: allow(undefined_variable)
155
+ export type function Trusted(payload)
156
+ return branded(payload, "__nwTrusted")
157
+ end
158
+
159
+ --[=[
160
+ @type Untrusted<T> T
161
+ @within Trust
162
+
163
+ A value that arrived from a client and has been checked for *shape* only. It conforms to the
164
+ schema; nothing has said the sender was entitled to send it.
165
+
166
+ This is what a `signal` handler receives, because `signal` is the class that carries no
167
+ authority (`DESIGN-API.md` §3).
168
+
169
+ :::caution
170
+ Table payloads only, for the reason given on [Trust.Trusted].
171
+ :::
172
+ ]=]
173
+ -- selene: allow(undefined_variable)
174
+ export type function Untrusted(payload)
175
+ return branded(payload, "__nwUntrusted")
176
+ end
177
+
178
+ --[[
179
+ These two aliases are load-bearing, and deleting them breaks the library silently.
180
+
181
+ Measured in `spike/declare/mod/`: an `export type function` that its own module never references
182
+ does **not** reduce for a module that requires it. It becomes `any`, with no diagnostic — so
183
+ every `nw.Trusted<T>` annotation in a game would keep compiling and stop meaning anything, and
184
+ `tests/api_reject.luau` would stop reporting the untrusted-reaches-authoritative-function case.
185
+ Any reference inside this file is enough; a local alias is the smallest one.
186
+ ]]
187
+ type _instantiateTrusted = Trusted<{ probe: boolean }>
188
+ type _instantiateUntrusted = Untrusted<{ probe: boolean }>
189
+
190
+ --[[
191
+ `Trusted<PayloadOf<S>>` would say this more directly, and does not work: nesting one type
192
+ function inside another over an un-resolved generic fails to reduce, and the analyser reports
193
+ `type functions do not currently support types of the form '*error-type*'` — inside netweave's
194
+ source, where a user cannot act on it.
195
+
196
+ Taking the schema whole and reading `__payload` here is also what makes the inference work at
197
+ all. `validate<T>(schema: Types.Type<T>, ...)` does not bind `T`: the solver resolves it to
198
+ `unknown`, so the brand sees a non-table and passes it through, and every validated value comes
199
+ back as `unknown?`. Inferring the schema type and projecting the payload out of it is the shape
200
+ `src/types/init.luau` already had to use for `t.struct`, for the same reason.
201
+ ]]
202
+ --[[
203
+ A callable constructor's table half.
204
+
205
+ `t.u8`, `t.string`, `t.vector3` and `t.instance` are `Type<T> & ((…) -> Type<T>)` since
206
+ `PLAN-M5` phase 1 — an intersection, because that is the only spelling that checks the argument
207
+ *types* rather than only their count. To a `type function` an intersection is not a table, so
208
+ anything reading `__payload` off a schema has to take the table half out first.
209
+
210
+ `src/types/init.luau` carries the same walk. A `type function` cannot reference an outer local
211
+ and calling one across a `require` needs it exported, so the copy is the cheaper of the two
212
+ costs — and the two are tested by the same `_ok` files, which annotate a payload projected
213
+ through both.
214
+ ]]
215
+ -- selene: allow(undefined_variable)
216
+ type function carrierOf(ty: type): type
217
+ if not ty:is("intersection") then
218
+ return ty
219
+ end
220
+
221
+ for _, part in ty:components() do
222
+ if part:is("table") and part:readproperty(types.singleton("__payload")) then
223
+ return part
224
+ end
225
+ end
226
+
227
+ return ty
228
+ end
229
+
230
+ -- selene: allow(undefined_variable)
231
+ export type function TrustedPayload(schema)
232
+ local descriptor = carrierOf(types.copy(schema))
233
+
234
+ --[[ One sentence, two failures: something that is not a table, and a table that is not a
235
+ netweave type. Both are the same mistake at the call site. ]]
236
+ local advice = "nw.validate takes a netweave type as its first argument and the value as its "
237
+ .. "second: nw.validate(t.struct({ screen = t.u8 }), value). A plain Luau table is not a "
238
+ .. "schema, so there is nothing to check the value against."
239
+
240
+ if not descriptor:is("table") then
241
+ error(advice)
242
+ end
243
+
244
+ local payload = descriptor:readproperty(types.singleton("__payload"))
245
+
246
+ if not payload then
247
+ error(advice)
248
+ end
249
+
250
+ --[[ `nw.validate(t.optional(S), v)` returned an unbranded value for the same reason `Trusted`
251
+ did, so it goes through the same helper. ]]
252
+ return branded(payload, "__nwTrusted")
253
+ end
254
+
255
+ --[[
256
+ **The other half of finding 5 is open, and was measured rather than dropped.**
257
+
258
+ `nw.validate(Schema, untrusted)` is the `nw.untrust` that `DESIGN-API` §6 refused to ship, spelled
259
+ as a call: the value arrived on a signal, its type says `Untrusted<T>`, and this hands back
260
+ `Trusted<T>`. The type-level fix is available and was written — an `Unbranded<V>` type function on
261
+ the value parameter, walking an intersection for `__nwUntrusted` and `__nwTrusted` and erroring
262
+ with the advice — and it costs more than it buys: with it, `tests/api_ok.luau` reports **"Code is
263
+ too complex to typecheck"** and 709 diagnostics behind it, because every call site then has to
264
+ solve a free generic and feed it to a second type function beside `TrustedPayload`. Reverted, the
265
+ tree is clean.
266
+
267
+ So the laundering route stays open, and the copy below closes the half that leaked keys.
268
+ `DESIGN-API` §6 says so where a reader would look for it.
269
+ ]]
270
+
271
+ --[[
272
+ One codec per descriptor, built on first use and kept. Building one walks the schema and
273
+ synthesises closures; doing that per `validate` call would make the honest path the expensive
274
+ one, which is how a safety feature gets switched off.
275
+
276
+ Weak keys so a descriptor built inside a function does not pin its codec forever.
277
+ ]]
278
+ local codecs: { [Types.Descriptor]: Serdes.Codec } = setmetatable({}, { __mode = "k" }) :: any
279
+
280
+ local function codecFor(schema: Types.Descriptor): Serdes.Codec
281
+ local existing = codecs[schema]
282
+
283
+ if existing then
284
+ return existing
285
+ end
286
+
287
+ local codec = Serdes.fromSchema(schema)
288
+ codecs[schema] = codec
289
+
290
+ return codec
291
+ end
292
+
293
+ --[=[
294
+ @within Trust
295
+ @function validate
296
+ @param schema S -- any type from `nw.types`
297
+ @param value any -- typically from outside netweave entirely
298
+ @return T? -- a schema-shaped **copy**, branded `Trusted<T>`, or nil
299
+ @return string? -- why it was refused
300
+
301
+ The third and last producer of `Trusted<T>`: check an arbitrary value against a schema.
302
+
303
+ ```lua
304
+ local settings, failure = nw.validate(SettingsSchema, HttpService:JSONDecode(body))
305
+
306
+ if not settings then
307
+ warn(`stored settings for {userId} are unusable: {failure}`)
308
+ settings = DEFAULTS
309
+ end
310
+ ```
311
+
312
+ Use it for data that did not arrive on a netweave channel — a DataStore read, an HTTP
313
+ response, a legacy `RemoteEvent` you have not migrated. Data that *did* arrive on a channel is
314
+ already validated by its codec, and validating it twice buys nothing.
315
+
316
+ :::caution
317
+ This round-trips `value` through the codec, so it costs a real serialisation **and** a decode. It
318
+ is an escape hatch, not a hot path.
319
+ :::
320
+
321
+ :::note
322
+ **What comes back is a copy, and it holds exactly the keys the schema names.** The encoder ignores
323
+ the rest, so returning the caller's own table handed back a `Trusted<T>` with
324
+ `{ isAdmin = true }` still inside it, typed as though it were not there (M4 report finding 5). The
325
+ copy is the decode of what the encoder wrote, so it cannot carry anything the schema did not — and
326
+ mutating the original afterwards cannot reach into what was validated.
327
+ :::
328
+
329
+ :::caution
330
+ **It is exactly as strict as the encoder**, and until M3 phase 9 the encoder was not strict
331
+ enough for this to mean what it says. The boolean writer tested truthiness, so
332
+ `{ admin = "false" }` validated against `t.boolean` and came back branded and truthy; the
333
+ instance writer tested only non-nil; the integer writers checked the range and let the fraction
334
+ truncate. All three are refused now, and the reason to say so here is that the two ways this
335
+ function is reached — a DataStore row and an HTTP body — are exactly the values nobody wrote.
336
+ :::
337
+ ]=]
338
+ function Trust.validate<S>(schema: S, value: any): (TrustedPayload<S>?, string?)
339
+ if not Types.isType(schema) then
340
+ error(
341
+ `nw.validate takes a netweave type as its first argument and the value as its second, `
342
+ .. `got {typeof(schema)}. Write it as nw.validate(t.struct(...), value); a policy is `
343
+ .. `not a schema and neither is a plain table.`,
344
+ 2
345
+ )
346
+ end
347
+
348
+ local codec = codecFor(schema :: any)
349
+
350
+ --[[
351
+ Written and read back, rather than checked in place.
352
+
353
+ `check` alone answers whether the value conforms and hands the caller's own table back, so a
354
+ key the schema does not name rode inside a `Trusted<T>` whose type said it was not there
355
+ (M4 report finding 5). The decode of what the encoder wrote cannot contain one.
356
+
357
+ Both sides of the buffer are parked first. The write side because a `validate` from inside a
358
+ `:publish` would otherwise land in the middle of somebody's batch; the read side because a
359
+ `validate` from inside a `:listen` would move the cursor of the batch being read, and every
360
+ packet behind it would decode from the wrong offset — measured, `a = 0, b = 0` for the packet
361
+ behind it with the read parking removed.
362
+ ]]
363
+ local parkedWrite = Buffer.save()
364
+ local parkedRead = Buffer.saveRead()
365
+
366
+ Buffer.load(nil)
367
+ local wrote, failure = pcall(codec.write, value)
368
+ local bytes, instances = Buffer.take()
369
+ Buffer.load(parkedWrite)
370
+
371
+ if not wrote then
372
+ Buffer.loadRead(parkedRead)
373
+
374
+ --[[ `error()` prefixes a script position; the caller wants the reason, not the line. ]]
375
+ local reason = tostring(failure)
376
+ return nil, (string.gsub(reason, "^.-:%d+: ", "", 1))
377
+ end
378
+
379
+ --[[ The sidecar this write just produced, read straight back. `{ Instance }` on the way out and
380
+ `{ unknown }` on the way in, and Luau arrays are invariant, so the cast is the boundary
381
+ rather than a claim (M4 report finding 50). ]]
382
+ Buffer.beginRead(bytes, instances :: { unknown })
383
+ local copy, refused = codec.read()
384
+ Buffer.loadRead(parkedRead)
385
+
386
+ if refused then
387
+ return nil, refused
388
+ end
389
+
390
+ return (copy :: any) :: TrustedPayload<S>, nil
391
+ end
392
+
393
+ return Trust