@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,385 @@
1
+ --!strict
2
+ --!optimize 2
3
+
4
+ --[=[
5
+ @class Context
6
+
7
+ What a policy and a handler are told about the request they are looking at.
8
+
9
+ ```lua
10
+ combat.fireWeapon:listen(function(ctx, shot)
11
+ if (shot.origin - ctx.character.PrimaryPart.Position).Magnitude > 8 then
12
+ return
13
+ end
14
+ end)
15
+ ```
16
+
17
+ :::caution
18
+ **A `ctx` is valid only for the synchronous duration of the handler.** There is one per player
19
+ and its fields are refreshed in place; retaining it across a yield hands you the next packet's
20
+ context, or another channel's. In Studio that is an error rather than a silent wrong answer.
21
+ :::
22
+ ]=]
23
+
24
+ --[[
25
+ `ctx` reaches every policy and every handler, so allocating one per packet would break the
26
+ zero-hot-path-allocation criterion on the first packet (`RESEARCH §3.6-A4`, `§3.6-B4`,
27
+ `PLAN-M1` acceptance 7). One per player, refreshed, is the only shape that costs nothing.
28
+
29
+ The cost of that choice is a real footgun, so it is guarded rather than documented and hoped
30
+ about: in Studio the handler receives a proxy that compares a generation counter before every
31
+ read, and a fresh one per acquisition so it can tell which acquisition the holder has. Production
32
+ hands over the record itself — no proxy, no comparison, nothing allocated.
33
+ ]]
34
+
35
+ local Context = {}
36
+
37
+ --[=[
38
+ @interface Ctx
39
+ @within Context
40
+ .player Player -- the sender, on the server; the local player on the client
41
+ .channel string -- the qualified channel name this request arrived on
42
+ .character Model? -- refreshed per request, nil if the player has none
43
+ .humanoid Humanoid? -- refreshed per request, nil if the character has none
44
+ .now number -- `os.clock()` at the moment the packet was dispatched
45
+ ]=]
46
+ export type Ctx = {
47
+ player: Player,
48
+ channel: string,
49
+ character: Model?,
50
+ humanoid: Humanoid?,
51
+ now: number,
52
+ }
53
+
54
+ type Record = {
55
+ live: Ctx,
56
+ generation: number,
57
+ --[[ Whether this acquisition has already gone and looked the character up. A boolean rather than
58
+ testing the field, because "this player has no character" is a real answer and `nil` cannot
59
+ tell it apart from "nobody has asked yet". ]]
60
+ looked: boolean,
61
+ }
62
+
63
+ --[[
64
+ `RunService` does not exist under lune, where the tests run, and neither does `game`. A pcall
65
+ is the only detection that works in both places; it runs once at load, not per request.
66
+ ]]
67
+ local function detectStudio(): boolean
68
+ local ok, studio = pcall(function()
69
+ return game:GetService("RunService"):IsStudio()
70
+ end)
71
+
72
+ return ok and studio == true
73
+ end
74
+
75
+ local GUARDED = detectStudio()
76
+
77
+ local records: { [any]: Record } = {}
78
+
79
+ --[[
80
+ One proxy per *acquisition*, not per player, and only in Studio.
81
+
82
+ A single proxy per player cannot work, and the first version of this file shipped that bug: the
83
+ closure captures `generation` when the proxy is built, so the first `release` expires it
84
+ permanently and every handler from the second packet onward raises. Caught by running
85
+ `tests/api_runtime.luau` in Studio, which is the only place the guard is even on.
86
+
87
+ Nor is a plain `active` boolean enough. It answers "is some handler running", so it catches a
88
+ `ctx` read after its handler returned — and misses the worse case, a `ctx` retained and read
89
+ during a *later* packet's handler, where it would quietly hand over another request's data.
90
+ Distinguishing those needs the holder's acquisition to be identifiable, which means a distinct
91
+ object per acquisition.
92
+
93
+ Studio pays two allocations per packet for that, and Studio is not where throughput is
94
+ measured. Production never calls this: `acquire` hands back the record itself.
95
+ ]]
96
+ local function guard(record: Record): Ctx
97
+ local generation = record.generation
98
+ local live = record.live
99
+
100
+ --[[
101
+ A metatable, not a copy: copying the fields per request would make the stale value
102
+ *readable*, which is worse than an error because it looks like it worked.
103
+ ]]
104
+ return (
105
+ setmetatable({}, {
106
+ __index = function(_, key: any): any
107
+ if record.generation ~= generation then
108
+ error(
109
+ `this ctx expired. It belonged to a handler that has already returned; a ctx is `
110
+ .. `valid only for the synchronous duration of the handler that received it `
111
+ .. `(netweave DESIGN-API §8). Copy the fields you need instead: `
112
+ .. `local player = ctx.player`,
113
+ 2
114
+ )
115
+ end
116
+
117
+ return (live :: any)[key]
118
+ end,
119
+
120
+ __newindex = function(_, key: any)
121
+ error(
122
+ `a ctx is read-only, so ctx.{tostring(key)} = ... is not a place to keep anything: `
123
+ .. `the record is reused for this player's next packet and the write would leak `
124
+ .. `into it. Keep per-request state in your own table, keyed by ctx.player.`,
125
+ 2
126
+ )
127
+ end,
128
+
129
+ __metatable = "netweave.Ctx",
130
+ }) :: any
131
+ ) :: Ctx
132
+ end
133
+
134
+ --[[
135
+ **The character is looked up when something reads it, and not before.**
136
+
137
+ It used to be refreshed in `acquire`, which runs per packet — two property reads and a
138
+ `FindFirstChildOfClass` for every packet of every batch, whether or not anything on that channel
139
+ was ever going to ask. A `signal` or `intent` with no policy needs it from nobody, and a batch of
140
+ twenty packets from one player paid twenty tree searches (M4 report).
141
+
142
+ Deferring it is not a caching window: each acquisition still gets that packet's answer, computed
143
+ fresh the first time it is read. What goes away is the packet that never reads it at all, which
144
+ is most of them.
145
+
146
+ Both fields are computed together on either one's first read, because `humanoid` is found through
147
+ `character` and a policy that asks for one has already paid for the other. `rawset` for the
148
+ caching so the metatable does not re-enter, and a `nil` character simply leaves the key absent —
149
+ `looked` is what stops it being looked up twice.
150
+ ]]
151
+ local function recordFor(player: any): Record
152
+ local existing = records[player]
153
+
154
+ if existing then
155
+ return existing
156
+ end
157
+
158
+ local record: Record = {
159
+ live = nil :: any,
160
+ generation = 0,
161
+ looked = false,
162
+ }
163
+
164
+ local live: any = setmetatable({
165
+ player = player,
166
+ channel = "",
167
+ now = 0,
168
+ }, {
169
+ __index = function(self: any, key: any): any
170
+ if key ~= "character" and key ~= "humanoid" then
171
+ return nil
172
+ end
173
+
174
+ if not record.looked then
175
+ record.looked = true
176
+
177
+ local character = (player :: any).Character
178
+
179
+ rawset(self, "character", character)
180
+ rawset(
181
+ self,
182
+ "humanoid",
183
+ if character then character:FindFirstChildOfClass("Humanoid") else nil
184
+ )
185
+ end
186
+
187
+ return rawget(self, key)
188
+ end,
189
+
190
+ --[[
191
+ The production record refuses a write, not only the Studio guard. Before M4 phase 8
192
+ every `acquire` overwrote `character` and `humanoid`, so a handler that wrote into
193
+ `ctx` was corrected on the next packet; the lazy lookup above fires only while the key
194
+ is absent, so a write sat in the shared record and was handed to every later policy
195
+ and handler for that player until `forget` — `ctx.character = …` believed by
196
+ `originNearCharacter`, with no message in production (M4-1). A key that exists is
197
+ still assignable, and `acquire` resets each of those every packet.
198
+ ]]
199
+ __newindex = function(_, key: any)
200
+ error(
201
+ `a ctx is read-only, so ctx.{tostring(key)} = ... is not a place to keep anything: `
202
+ .. `the record is reused for this player's next packet and the write would leak `
203
+ .. `into it. Keep per-request state in your own table, keyed by ctx.player.`,
204
+ 2
205
+ )
206
+ end,
207
+ })
208
+
209
+ record.live = live :: Ctx
210
+ records[player] = record
211
+
212
+ return record
213
+ end
214
+
215
+ --[=[
216
+ @within Context
217
+ @function acquire
218
+ @param player Player
219
+ @param channel string -- the qualified channel name
220
+ @return Ctx
221
+ @private
222
+
223
+ Refreshes this player's context and hands it out. Called by the transport per packet.
224
+ ]=]
225
+ function Context.acquire(player: any, channel: string): Ctx
226
+ local record = recordFor(player)
227
+ local live = record.live
228
+
229
+ --[[ `player` too, though it never changes: it is the one key a handler can overwrite without
230
+ `__newindex` noticing, because it exists. Three plain stores per packet. ]]
231
+ live.player = player
232
+ live.channel = channel
233
+ live.now = os.clock()
234
+
235
+ --[[
236
+ ~~Character and humanoid are refreshed here rather than looked up by each policy, because
237
+ `policy.alive` and `policy.originNearCharacter` would otherwise each pay for the same two
238
+ property reads on every packet.~~
239
+
240
+ **That argument is about policies and this function runs per packet.** Sharing one lookup
241
+ between the policies of one request is right and still happens; paying for it on a request
242
+ where no policy and no handler will read it is what the M4 report found, and it is most
243
+ requests. The lookup moved to `recordFor`'s `__index`, and what is left here is dropping the
244
+ previous acquisition's answer — one branch when nothing looked, which is the common case.
245
+ ]]
246
+ if record.looked then
247
+ record.looked = false
248
+
249
+ rawset(live :: any, "character", nil)
250
+ rawset(live :: any, "humanoid", nil)
251
+ end
252
+
253
+ if GUARDED then
254
+ return guard(record)
255
+ end
256
+
257
+ return live
258
+ end
259
+
260
+ --[=[
261
+ @within Context
262
+ @function release
263
+ @param player Player
264
+ @private
265
+
266
+ Ends the context's validity. Every read through a retained `ctx` after this point is an error
267
+ in Studio, and reads a later packet's data in production.
268
+ ]=]
269
+ function Context.release(player: any)
270
+ local record = records[player]
271
+
272
+ if record then
273
+ record.generation += 1
274
+ end
275
+ end
276
+
277
+ --[=[
278
+ @within Context
279
+ @function generation
280
+ @param player Player
281
+ @return number
282
+ @private
283
+
284
+ How many times this player's context has been released. The transport reads it before it runs a
285
+ handler or a policy and compares after: a value that moved means another packet of the same
286
+ player was dispatched while that code was parked on a yield, so the `ctx` it held was refreshed
287
+ under it — the case the Studio guard raises on, made reportable in production for the cost of
288
+ one integer compare (`PLAN-M5` D-5).
289
+ ]=]
290
+ function Context.generation(player: any): number
291
+ local record = records[player]
292
+
293
+ return if record then record.generation else 0
294
+ end
295
+
296
+ --[=[
297
+ @within Context
298
+ @function detached
299
+ @param player Player
300
+ @param channel string -- the qualified channel name
301
+ @return Ctx
302
+ @private
303
+
304
+ A context of its own, for a handler that is allowed to yield.
305
+
306
+ `nw.query` is the only class where that is true, and it is true by design: a query exists to
307
+ fetch something, and fetching means a datastore, a `WaitForChild`, an HTTP call. So a query's
308
+ handler gets a record nobody else will touch, frozen, valid for as long as it holds it.
309
+ ]=]
310
+ --[[
311
+ One allocation per call, and it is the right trade here rather than an exception to the rule.
312
+
313
+ The shared per-player record exists because `ctx` reaches every policy and every handler on
314
+ every packet, and a table per packet would have broken the zero-allocation criterion on the
315
+ first one. A query is not that: it has already cost a coroutine, a round trip and a reply
316
+ packet, and the alternative to allocating is a record whose `channel`, `now` and `character`
317
+ are refreshed out from under a handler that yielded — which in Studio raises through the guard
318
+ above, and in production hands back another packet's context. The optimisation and the class
319
+ are incompatible, so the class pays.
320
+
321
+ Frozen, so the one thing a detached context and a live one still have in common is that neither
322
+ can be written to.
323
+ ]]
324
+ function Context.detached(player: any, channel: string): Ctx
325
+ local character = (player :: any).Character
326
+
327
+ return table.freeze({
328
+ player = player,
329
+ channel = channel,
330
+ character = character,
331
+ humanoid = if character then character:FindFirstChildOfClass("Humanoid") else nil,
332
+ now = os.clock(),
333
+ }) :: any
334
+ end
335
+
336
+ --[=[
337
+ @within Context
338
+ @function forget
339
+ @param player Player
340
+ @private
341
+
342
+ Drops the player's context entirely. Called when they leave, so the record does not outlive them.
343
+ ]=]
344
+ function Context.forget(player: any)
345
+ records[player] = nil
346
+ end
347
+
348
+ --[=[
349
+ @within Context
350
+ @function guarded
351
+ @return boolean
352
+
353
+ Whether expired-context access is being checked. True in Studio, false in a live server.
354
+
355
+ Exposed so a test can assert which mode it is running in rather than infer it — the guard is
356
+ the kind of thing that quietly stops working.
357
+ ]=]
358
+ function Context.guarded(): boolean
359
+ return GUARDED
360
+ end
361
+
362
+ --[=[
363
+ @within Context
364
+ @function setGuarded
365
+ @param enabled boolean
366
+ @private
367
+
368
+ Turns the expired-context check off, or back on.
369
+
370
+ The only reason this exists is measurement. The guard allocates two tables per packet, in
371
+ Studio, and Studio is where the benchmark runs — so a run with it on charges netweave for a
372
+ debug facility no competitor has and no live server pays. `bench/` turns it off for the
373
+ comparison and reports its cost as a line of its own.
374
+
375
+ :::caution
376
+ This is not a performance knob for a game. Studio is not where throughput is decided, and the
377
+ guard is the only thing standing between a retained `ctx` and a handler quietly reading another
378
+ player's request.
379
+ :::
380
+ ]=]
381
+ function Context.setGuarded(enabled: boolean)
382
+ GUARDED = enabled
383
+ end
384
+
385
+ return Context