@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,507 @@
1
+ --!strict
2
+ --!optimize 2
3
+
4
+ --[=[
5
+ @class Recipients
6
+
7
+ Turns a declared audience into the players it reaches.
8
+
9
+ Guarantee G3 is half type and half this file. The type makes the audience impossible to omit
10
+ and makes `broadcast` exist only where the audience is everyone; this decides, per publish, who
11
+ `nearby(120)` actually means.
12
+
13
+ Internal.
14
+ ]=]
15
+
16
+ --[[
17
+ Geometry is behind a `Roster` for the same reason the remotes are behind a `Link`: it is the
18
+ only Roblox-shaped part, and putting it behind an interface is what lets the audience rules be
19
+ tested in-process rather than by watching who received what in Studio.
20
+
21
+ `DESIGN-API.md` §11 (Open) left open whether `nearby` is evaluated per subject or cached per tick.
22
+ It is per subject here, and that is a decision this milestone is allowed to revisit once phase
23
+ 5 measures it — at 100 players and a 60 Hz state channel the difference is four orders of
24
+ magnitude, and guessing which way is the risk `PLAN-M2` R-3 names.
25
+ ]]
26
+
27
+ local Observer = require("../api/Observer")
28
+
29
+ local Recipients = {}
30
+
31
+ --[[
32
+ Whether a value could be a recipient at all, asked the way `Serdes.isInstance` asks its own
33
+ question and for the same reason: inside Roblox it is exact, and under lune there are no
34
+ Instances and the suite stands players in with tables.
35
+
36
+ It is deliberately a *shape* test rather than an identity one. Whether a particular player is
37
+ still connected is the roster's question — `has` above — and a roster that does not answer it
38
+ still gets the values that could never have been a recipient at all refused here.
39
+ ]]
40
+ --[[
41
+ ~~Asked the way `Serdes.isInstance` asks its own question: exact inside Roblox, and a table under
42
+ lune where the suite stands players in.~~ **That split was wrong here, and the way it was wrong is
43
+ the finding.**
44
+
45
+ `Serdes.isInstance` can branch on the runtime because the Studio suite hands it a **real
46
+ Instance** — the double matches the real thing in the dimension the code checks, which is
47
+ `CLAUDE.md` §9's rule for doubles. A `Player` cannot be constructed, so no suite can do the same
48
+ here: `replication_runtime` needs two of them and Play mode has one. The branch therefore made
49
+ every table stand-in a recipient under lune and none in Studio, and two suites that pass on every
50
+ lune run went red the moment the place was opened — which is §9's "the half that cannot run under
51
+ lune is the half that goes red quietly", reproduced by the commit that quoted it.
52
+
53
+ So the two questions are separated instead of merged:
54
+
55
+ * **kind**, here — could this ever be addressed at all. A number, a string or a boolean cannot
56
+ be a table key the send buffers are parked under, let alone reach `FireClient`. That is true
57
+ in both runtimes and needs no branch.
58
+ * **identity**, `has` below — is this someone this endpoint can send to *right now*.
59
+ `Recipients.roblox` answers it with `typeof(who) == "Instance"`, `IsA("Player")` and
60
+ `Parent == Players`, which is strictly more than the kind test and is what production runs.
61
+
62
+ A roster that answers `has` is therefore the whole test, and this is the floor for one that does
63
+ not. What that floor gives up is a plain table: `{ 5, "text", {} }` was three parked send buffers
64
+ before M4 phase 8 and is one now rather than zero — and zero everywhere `has` exists, which is
65
+ every path netweave builds itself.
66
+ ]]
67
+ local function isRecipient(who: any): boolean
68
+ return type(who) == "table" or typeof(who) == "Instance"
69
+ end
70
+
71
+ --[[
72
+ Said once per audience, not once per publish.
73
+
74
+ A selector that returns rubbish returns it every tick, and a `state` channel publishes per
75
+ subject per tick — so reporting each one would be thousands of copies of one unchanging fact a
76
+ second, which is the mistake `Baseline` made with `baselinesPerClient` and the same lesson
77
+ (`CLAUDE.md` §9). Weak keys so a namespace that is reset does not pin its audiences here.
78
+ ]]
79
+ local announced: { [any]: { dropped: boolean, duplicated: boolean } } = setmetatable({}, { __mode = "k" }) :: any
80
+
81
+ --[[ Which players a `select` has already admitted this call, so a duplicate is one lookup rather
82
+ than a scan of everything admitted so far. Module-owned and cleared after each call: one table
83
+ for the life of the process, nothing per publish. ]]
84
+ local chosenSet: { [any]: boolean } = {}
85
+
86
+ --[[
87
+ Who is here this frame, as a set, built from the frame's player list the first time a call
88
+ brings that list and kept while calls keep bringing the same one. The tick takes `roster.all()`
89
+ once and hands it to every subject (finding 77), so the set is built once a tick and every
90
+ membership question after — one per recipient per subject, S × P of them — is a lookup rather
91
+ than `has`, which on Roblox is three engine calls (`typeof`, `IsA`, `Parent`). A fresh list, as
92
+ a lone `publish` brings, rebuilds it: P writes, against the P `has` calls it replaces.
93
+
94
+ The list is the roster's own answer to who is here, so it is at least the answer `has` gives,
95
+ and a member of it cannot have left inside the tick that holds it — nothing yields there.
96
+ ]]
97
+ local presentFor: { any }? = nil
98
+ local present: { [any]: true } = {}
99
+
100
+ local function presence(players: { any }): { [any]: true }
101
+ if presentFor ~= players then
102
+ table.clear(present)
103
+
104
+ for _, who in players do
105
+ present[who] = true
106
+ end
107
+
108
+ presentFor = players
109
+ end
110
+
111
+ return present
112
+ end
113
+
114
+ local NOT_A_RECIPIENT = "an audience.select returned something that is not a player who is here — a "
115
+ .. "nil, a value of another type, or somebody who has left. It was not sent to. Return only "
116
+ .. "players from Players:GetPlayers(), and rebuild the list rather than keeping one across "
117
+ .. "frames: a stale entry is a send buffer this server holds until it shuts down"
118
+
119
+ local DUPLICATED = "an audience.select returned the same player more than once, and the extra copies "
120
+ .. "were dropped. A recipient receives a packet or does not; listing one twice put the packet in "
121
+ .. "that player's batch twice, which is bandwidth nothing asked for"
122
+
123
+ local function announce(audience: any, channel: any, dropped: boolean, duplicated: boolean)
124
+ local said = announced[audience]
125
+
126
+ if not said then
127
+ said = { dropped = false, duplicated = false }
128
+ announced[audience] = said
129
+ end
130
+
131
+ --[[ `Observer` keys its counters by name, so an unnamed channel is `"?"` — the same stand-in
132
+ `Inbound.report` uses for a packet whose id resolved to nothing. ]]
133
+ local named = if channel then channel.qualified else "?"
134
+
135
+ if dropped and not said.dropped then
136
+ said.dropped = true
137
+ Observer.emit(named, nil, "send", NOT_A_RECIPIENT, 0)
138
+ end
139
+
140
+ if duplicated and not said.duplicated then
141
+ said.duplicated = true
142
+ Observer.emit(named, nil, "send", DUPLICATED, 0)
143
+ end
144
+ end
145
+
146
+ --[=[
147
+ @interface Roster
148
+ @within Recipients
149
+ .all () -> { any } -- every connected player
150
+ .owner (subject: any) -> any? -- the player the subject belongs to, or nil
151
+ .within (subject: any, studs: number, out: { any }, players: { any }) -> number -- fills `out` from `players`, returns how many
152
+ .has ((who: any) -> boolean)? -- whether this is someone the endpoint can send to right now
153
+
154
+ Everything the audience rules need to know about the world.
155
+
156
+ `within` fills a caller-owned array rather than returning a fresh one, because it runs per
157
+ publish and a `state` channel publishes per subject per tick. Returning a table there would
158
+ allocate once per subject per frame for the life of the server. It is handed the players to
159
+ measure for the same reason: the Roblox roster used to ask the engine for `GetPlayers()`
160
+ itself, a fresh table per call, once per subject per publish — 60,000 a second for a `nearby`
161
+ channel of a thousand subjects — when the tick had already taken `all()` once for the frame
162
+ (SECURITY-REPORT-M4 77; `bench/residue` rung 77).
163
+
164
+ `has` is optional, and every rule but `everyone` consults it. ~~The other three rules build their
165
+ answers out of the roster itself, so what they return is a recipient by construction.~~ `owner`
166
+ and `nearby` return what the roster answers, and the roster answers for a player who left the
167
+ tick before — a `Player` subject owns itself, connected or not (M4-1). Absent, they trust the
168
+ answer, and a rig that leaves it out runs that degraded path.
169
+ ]=]
170
+ export type Roster = {
171
+ all: () -> { any },
172
+ owner: (subject: any) -> any?,
173
+ within: (subject: any, studs: number, out: { any }, players: { any }) -> number,
174
+
175
+ --[[ Optional so a rig that stands players in with tables need not answer it — under lune the
176
+ shape test cannot tell a stand-in from a stray table. ]]
177
+ has: ((who: any) -> boolean)?,
178
+ }
179
+
180
+ --[=[
181
+ @within Recipients
182
+ @function roblox
183
+ @return Roster
184
+
185
+ The Roblox roster. `nearby` measures from the subject to each player's character, and a player
186
+ with no character is not near anything — which is the honest answer rather than an error.
187
+ ]=]
188
+ function Recipients.roblox(): Roster
189
+ local Players = game:GetService("Players")
190
+
191
+ --[[ A subject is whatever the publisher passed: a player, a model, or something with a
192
+ position. Resolving it here keeps `publish(subject, value)` from dictating a shape. ]]
193
+ local function positionOf(thing: any): Vector3?
194
+ if typeof(thing) ~= "Instance" then
195
+ return nil
196
+ end
197
+
198
+ --[[ Narrowing `any` by `typeof` leaves the solver with a union it cannot call `IsA` on, so
199
+ the cast says what the check already established. ]]
200
+ local instance = thing :: Instance
201
+
202
+ if instance:IsA("Player") then
203
+ local character = (instance :: Player).Character
204
+ local root = character and character.PrimaryPart
205
+ return if root then root.Position else nil
206
+ end
207
+
208
+ if instance:IsA("Model") then
209
+ local root = (instance :: Model).PrimaryPart
210
+ return if root then root.Position else nil
211
+ end
212
+
213
+ if instance:IsA("BasePart") then
214
+ return (instance :: BasePart).Position
215
+ end
216
+
217
+ return nil
218
+ end
219
+
220
+ --[[
221
+ Every player's position, read once per list rather than once per subject. `within` runs per
222
+ subject per publish and used to read `Character`, `PrimaryPart` and `Position` — three
223
+ engine calls — for every player each time, S × P × 3 a tick. The tick hands every subject the
224
+ same list, so the reads happen once a tick and the S × P distance checks are arithmetic over
225
+ this array (`PLAN-M5` phase 5). `false` marks a player with no character, which is not near
226
+ anything. A lone `publish` brings a fresh list and pays the P reads it always paid.
227
+ ]]
228
+ local positionsFor: { any }? = nil
229
+ local positions: { Vector3 | false } = {}
230
+
231
+ local function positionsOf(players: { any }): { Vector3 | false }
232
+ if positionsFor ~= players then
233
+ local count = #players
234
+
235
+ for index = 1, count do
236
+ positions[index] = positionOf(players[index]) or false
237
+ end
238
+
239
+ for index = count + 1, #positions do
240
+ positions[index] = nil
241
+ end
242
+
243
+ positionsFor = players
244
+ end
245
+
246
+ return positions
247
+ end
248
+
249
+ return {
250
+ all = function(): { any }
251
+ return Players:GetPlayers() :: any
252
+ end,
253
+
254
+ --[[
255
+ Whether this is somebody the server can send to *now*.
256
+
257
+ `Parent == Players` rather than a scan of `GetPlayers()`: it is O(1), it is what the
258
+ engine itself uses to mean "connected", and it is the half `select` could not answer for
259
+ itself. A player who left is still a `Player` — the shape test cannot tell — and a stale
260
+ list naming them rebuilt the send buffer `forget` had just removed, one per departed
261
+ player, for as long as the game kept naming them (M4 report).
262
+ ]]
263
+ has = function(who: any): boolean
264
+ return typeof(who) == "Instance"
265
+ and (who :: Instance):IsA("Player")
266
+ and (who :: Player).Parent == Players
267
+ end,
268
+
269
+ owner = function(subject: any): any?
270
+ if typeof(subject) ~= "Instance" then
271
+ return nil
272
+ end
273
+
274
+ local instance = subject :: Instance
275
+
276
+ if instance:IsA("Player") then
277
+ return instance
278
+ end
279
+
280
+ --[[
281
+ A real narrowing rather than the `:: Model` cast this used to carry.
282
+
283
+ `GetPlayerFromCharacter` takes a `Model`, and anything reaching this line is whatever
284
+ the game passed to `publish` — a `BasePart`, a `Folder`, a `Tool`. An external review
285
+ flagged that as an unverified raise (M3 phase 9): it would have raised from inside
286
+ `publish`, in game code, on a path whose whole contract is "or nil".
287
+
288
+ Not verified in Studio and it does not need to be, because the check makes the answer
289
+ the same either way. `within` above takes a `BasePart` and this deliberately does
290
+ not: a position can be read off any part, and a part is not a character. Pass the
291
+ character, or the `Player`.
292
+ ]]
293
+ if not instance:IsA("Model") then
294
+ return nil
295
+ end
296
+
297
+ return Players:GetPlayerFromCharacter(instance)
298
+ end,
299
+
300
+ within = function(subject: any, studs: number, out: { any }, players: { any }): number
301
+ local origin = positionOf(subject)
302
+
303
+ if not origin then
304
+ return 0
305
+ end
306
+
307
+ local limit = studs * studs
308
+ local count = 0
309
+ local known = positionsOf(players)
310
+
311
+ for index, player in players do
312
+ local position = known[index]
313
+
314
+ if position then
315
+ --[[ Squared distance, compared against a squared radius. `Magnitude` is a
316
+ square root, and this runs once per player per subject per publish — a
317
+ `state` channel at 60 Hz with 100 players is 600,000 of them a second. ]]
318
+ local dx = position.X - origin.X
319
+ local dy = position.Y - origin.Y
320
+ local dz = position.Z - origin.Z
321
+
322
+ if dx * dx + dy * dy + dz * dz <= limit then
323
+ count += 1
324
+ out[count] = player
325
+ end
326
+ end
327
+ end
328
+
329
+ return count
330
+ end,
331
+ }
332
+ end
333
+
334
+ --[[ Drops what an earlier, wider audience left in the scratch past `count`. The array is dense
335
+ from 1, so this stops at the first hole and costs one write per stale entry, once — not a
336
+ `table.clear` per subject per tick. ]]
337
+ local function trim(out: { any }, count: number)
338
+ local index = count + 1
339
+
340
+ while out[index] ~= nil do
341
+ out[index] = nil
342
+ index += 1
343
+ end
344
+ end
345
+
346
+ --[=[
347
+ @within Recipients
348
+ @function of
349
+ @param audience Audience
350
+ @param subject any
351
+ @param roster Roster
352
+ @param out { any } -- caller-owned scratch array, filled in place
353
+ @param channel any? -- named in the report when a `select` returns something that is not a recipient
354
+ @param players { any }? -- the roster's players, when the caller already holds them for the frame
355
+ @return number -- how many recipients, or -1 for "everyone"
356
+
357
+ Resolves an audience to recipients.
358
+
359
+ **-1 means everyone**, and it is not the same as filling `out` with every player. A channel
360
+ whose audience is everyone sends one `FireAllClients` instead of N `FireClient`s, which is the
361
+ one place ByteNet beats both code generators (`RESEARCH §3.7-E`). Collapsing the two would
362
+ throw that away silently.
363
+
364
+ `out` holds exactly the recipients past the call, and nothing past `count`: the scratch is
365
+ reused per subject, and what a wider audience left behind kept a departed player referenced
366
+ until a wider one overwrote the slot (SECURITY-REPORT-M4 77).
367
+
368
+ With `players`, membership is answered from that list rather than by asking the roster per
369
+ recipient (`PLAN-M5` phase 5): the tick brings the same list for every subject of the frame,
370
+ so the set behind it is built once a tick.
371
+ ]=]
372
+ function Recipients.of(
373
+ audience: any,
374
+ subject: any,
375
+ roster: Roster,
376
+ out: { any },
377
+ channel: any?,
378
+ players: { any }?
379
+ ): number
380
+ local kind = audience.kind
381
+
382
+ if kind == "everyone" then
383
+ trim(out, 0)
384
+ return -1
385
+ end
386
+
387
+ --[[
388
+ `owner` and `nearby` ask the roster the same question `select` asks of the game's list:
389
+ is this player still here. 2ea8c90 closed it for `select` only, and the owner of a
390
+ `Player`-keyed subject is the instance itself, connected or not — a store that lists the
391
+ departed player's subject for one more tick (a profile save that yields) rebuilt the
392
+ baselines and the parked send record `forget` had just removed, for the life of the server
393
+ (M4 report, finding 19; M4-1).
394
+ ]]
395
+ local here = roster.has
396
+ local listed: { [any]: true }? = if players then presence(players) else nil
397
+
398
+ if kind == "owner" then
399
+ local player = roster.owner(subject)
400
+
401
+ if not player or (if listed then not listed[player] elseif here then not here(player) else false) then
402
+ trim(out, 0)
403
+ return 0
404
+ end
405
+
406
+ out[1] = player
407
+ trim(out, 1)
408
+ return 1
409
+ end
410
+
411
+ if kind == "nearby" then
412
+ local count = roster.within(subject, audience.radius, out, players or roster.all())
413
+
414
+ if not listed and not here then
415
+ trim(out, count)
416
+ return count
417
+ end
418
+
419
+ --[[ Compacted in place: `within` fills the caller's array, and a hole in it would be the
420
+ `select` defect over again. ]]
421
+ local kept = 0
422
+
423
+ for index = 1, count do
424
+ local who = out[index]
425
+
426
+ if if listed then listed[who] == true else (here :: (any) -> boolean)(who) then
427
+ kept += 1
428
+ out[kept] = who
429
+ end
430
+ end
431
+
432
+ trim(out, kept)
433
+ return kept
434
+ end
435
+
436
+ --[[
437
+ `select` hands the decision to the game, so the result is whatever it returned. It is copied
438
+ into the caller's array rather than used directly: the selector may hand back a table it
439
+ keeps, and writing into it later would be a bug in netweave that looks like one in the game.
440
+
441
+ **What it returned is not trusted to be a list of recipients**, and every part of that
442
+ sentence was a defect before M4 phase 8 (M4 report):
443
+
444
+ * `{ alice, nil, bob }` — `#` over a table with a hole is unspecified in Luau, so what
445
+ happened depended on how the game built the list. Measured: it raised
446
+ `Outbound:173: table index is nil`, which is `switchTo` writing `parked[nil]`, the exact
447
+ hazard the comment above that table names and does not guard.
448
+ * `{ 5, "text", {} }` — three parked send buffers, one per value, none of which will ever be
449
+ forgotten because `forget` runs from `PlayerRemoving` and none of these will ever leave.
450
+ Measured at 5,000 publishes to fresh values: **3.8 MB retained**.
451
+ * a player who has left, still named by a stale list, rebuilds the record `forget` just
452
+ removed — and `FireClient` on them is silent, so nothing says the packet went nowhere.
453
+
454
+ So the walk is `pairs`, which cannot be fooled by a hole, and every value is checked before it
455
+ becomes a destination. Duplicates are dropped for the same reason: a recipient receives a
456
+ packet or does not, and `{ alice, alice }` put the packet in alice's batch **twice** — three
457
+ bytes became five, measured.
458
+ ]]
459
+ local chosen = audience.select(subject)
460
+
461
+ if type(chosen) ~= "table" then
462
+ trim(out, 0)
463
+ return 0
464
+ end
465
+
466
+ local count = 0
467
+ local dropped = false
468
+ local duplicated = false
469
+
470
+ for _, who in chosen do
471
+ --[[ The frame's list where there is one, the roster's answer where there is one, and the
472
+ kind test where there is neither. `has` is strictly the stronger question —
473
+ `Recipients.roblox` checks the kind inside it — so asking both would be asking the
474
+ weaker one twice. See `isRecipient`. ]]
475
+ local admitted = if listed then listed[who] == true elseif here then here(who) else isRecipient(who)
476
+
477
+ if not admitted then
478
+ dropped = true
479
+ continue
480
+ end
481
+
482
+ --[[ ~~Linear, because an audience is a handful of players.~~ A `select` that returns the roster
483
+ is the common `select` — everyone but spectators, a team — and the scan was O(n²) per
484
+ subject: 500 subjects × 50 players was 1.25 million comparisons a tick, 7 ms of the
485
+ 14 the M4-1 report measured (`bench/tick`, `select-all`). One set, module-owned and
486
+ cleared per call, so it still allocates nothing per publish. ]]
487
+ if chosenSet[who] then
488
+ duplicated = true
489
+ continue
490
+ end
491
+
492
+ chosenSet[who] = true
493
+ count += 1
494
+ out[count] = who
495
+ end
496
+
497
+ table.clear(chosenSet)
498
+ trim(out, count)
499
+
500
+ if dropped or duplicated then
501
+ announce(audience, channel, dropped, duplicated)
502
+ end
503
+
504
+ return count
505
+ end
506
+
507
+ return Recipients