@colyseus/core 0.18.0 → 0.18.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.
- package/build/MatchMaker.cjs +3 -7
- package/build/MatchMaker.cjs.map +2 -2
- package/build/MatchMaker.mjs +4 -8
- package/build/MatchMaker.mjs.map +2 -2
- package/build/Protocol.cjs +3 -3
- package/build/Protocol.cjs.map +1 -1
- package/build/Protocol.d.ts +3 -3
- package/build/Protocol.mjs +3 -3
- package/build/Protocol.mjs.map +1 -1
- package/build/Rewind.cjs +385 -0
- package/build/Rewind.cjs.map +7 -0
- package/build/Rewind.d.ts +291 -0
- package/build/Rewind.mjs +359 -0
- package/build/Rewind.mjs.map +7 -0
- package/build/Room.cjs +280 -281
- package/build/Room.cjs.map +3 -3
- package/build/Room.d.ts +185 -81
- package/build/Room.mjs +286 -286
- package/build/Room.mjs.map +2 -2
- package/build/RoomMessages.cjs +265 -0
- package/build/RoomMessages.cjs.map +7 -0
- package/build/RoomMessages.d.ts +49 -0
- package/build/RoomMessages.mjs +240 -0
- package/build/RoomMessages.mjs.map +7 -0
- package/build/Server.cjs +88 -31
- package/build/Server.cjs.map +2 -2
- package/build/Server.d.ts +36 -0
- package/build/Server.mjs +88 -31
- package/build/Server.mjs.map +2 -2
- package/build/Transport.cjs +26 -0
- package/build/Transport.cjs.map +2 -2
- package/build/Transport.d.ts +69 -2
- package/build/Transport.mjs +25 -0
- package/build/Transport.mjs.map +2 -2
- package/build/errors/RoomExceptions.cjs +7 -4
- package/build/errors/RoomExceptions.cjs.map +2 -2
- package/build/errors/RoomExceptions.d.ts +15 -3
- package/build/errors/RoomExceptions.mjs +5 -3
- package/build/errors/RoomExceptions.mjs.map +2 -2
- package/build/index.cjs +19 -2
- package/build/index.cjs.map +2 -2
- package/build/index.d.ts +7 -4
- package/build/index.mjs +17 -4
- package/build/index.mjs.map +2 -2
- package/build/input/InputBuffer.cjs +439 -16
- package/build/input/InputBuffer.cjs.map +2 -2
- package/build/input/InputBuffer.d.ts +186 -96
- package/build/input/InputBuffer.mjs +436 -15
- package/build/input/InputBuffer.mjs.map +2 -2
- package/build/input/RoomInput.cjs +306 -0
- package/build/input/RoomInput.cjs.map +7 -0
- package/build/input/RoomInput.d.ts +91 -0
- package/build/input/RoomInput.mjs +287 -0
- package/build/input/RoomInput.mjs.map +7 -0
- package/build/input/types.cjs +18 -0
- package/build/input/types.cjs.map +7 -0
- package/build/input/types.d.ts +476 -0
- package/build/input/types.mjs +0 -0
- package/build/input/types.mjs.map +7 -0
- package/build/rooms/QueueRoom.cjs +1 -1
- package/build/rooms/QueueRoom.cjs.map +2 -2
- package/build/rooms/QueueRoom.mjs +1 -1
- package/build/rooms/QueueRoom.mjs.map +2 -2
- package/build/router/default_routes.cjs +4 -1
- package/build/router/default_routes.cjs.map +2 -2
- package/build/router/default_routes.mjs +4 -1
- package/build/router/default_routes.mjs.map +2 -2
- package/build/router/index.cjs +6 -1
- package/build/router/index.cjs.map +2 -2
- package/build/router/index.mjs +6 -1
- package/build/router/index.mjs.map +2 -2
- package/build/router/node.cjs +37 -2
- package/build/router/node.cjs.map +2 -2
- package/build/router/node.d.ts +10 -0
- package/build/router/node.mjs +35 -1
- package/build/router/node.mjs.map +2 -2
- package/build/serializer/NoneSerializer.cjs +2 -2
- package/build/serializer/NoneSerializer.cjs.map +2 -2
- package/build/serializer/NoneSerializer.d.ts +3 -3
- package/build/serializer/NoneSerializer.mjs +2 -2
- package/build/serializer/NoneSerializer.mjs.map +2 -2
- package/build/serializer/SchemaSerializer.cjs +44 -14
- package/build/serializer/SchemaSerializer.cjs.map +2 -2
- package/build/serializer/SchemaSerializer.d.ts +3 -3
- package/build/serializer/SchemaSerializer.mjs +46 -16
- package/build/serializer/SchemaSerializer.mjs.map +2 -2
- package/build/serializer/Serializer.cjs.map +1 -1
- package/build/serializer/Serializer.d.ts +12 -2
- package/build/utils/DevMode.cjs +14 -14
- package/build/utils/DevMode.cjs.map +2 -2
- package/build/utils/DevMode.d.ts +0 -2
- package/build/utils/DevMode.mjs +14 -12
- package/build/utils/DevMode.mjs.map +2 -2
- package/build/utils/Env.cjs +8 -4
- package/build/utils/Env.cjs.map +3 -3
- package/build/utils/Env.mjs +8 -4
- package/build/utils/Env.mjs.map +2 -2
- package/build/utils/Utils.cjs +3 -0
- package/build/utils/Utils.cjs.map +2 -2
- package/build/utils/Utils.d.ts +8 -0
- package/build/utils/Utils.mjs +2 -0
- package/build/utils/Utils.mjs.map +2 -2
- package/package.json +11 -11
- package/src/MatchMaker.ts +7 -9
- package/src/Protocol.ts +3 -3
- package/src/Rewind.ts +572 -0
- package/src/Room.ts +409 -448
- package/src/RoomMessages.ts +342 -0
- package/src/Server.ts +112 -38
- package/src/Transport.ts +97 -2
- package/src/errors/RoomExceptions.ts +18 -4
- package/src/index.ts +13 -2
- package/src/input/InputBuffer.ts +464 -107
- package/src/input/RoomInput.ts +337 -0
- package/src/input/types.ts +503 -0
- package/src/rooms/QueueRoom.ts +1 -1
- package/src/router/default_routes.ts +6 -1
- package/src/router/index.ts +6 -1
- package/src/router/node.ts +44 -0
- package/src/serializer/NoneSerializer.ts +3 -3
- package/src/serializer/SchemaSerializer.ts +110 -19
- package/src/serializer/Serializer.ts +13 -2
- package/src/utils/DevMode.ts +18 -13
- package/src/utils/Env.ts +12 -4
- package/src/utils/Utils.ts +9 -0
package/src/input/InputBuffer.ts
CHANGED
|
@@ -1,125 +1,273 @@
|
|
|
1
1
|
import type { ClientPrivate } from '../Transport.ts';
|
|
2
|
+
import { $METADATA } from '../utils/Utils.ts';
|
|
2
3
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
* on the input schema. Filters out booleans, strings, methods, etc.
|
|
7
|
-
*/
|
|
8
|
-
export type NumericFieldsOf<I> = {
|
|
9
|
-
[K in keyof I]: I[K] extends number ? (K extends string ? K : never) : never;
|
|
10
|
-
}[keyof I];
|
|
4
|
+
import type {
|
|
5
|
+
ConsumeOptions, IdleContext, IdleInput, InputAccessor, SanitizeInput,
|
|
6
|
+
} from './types.ts';
|
|
11
7
|
|
|
12
8
|
/**
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
* @internal
|
|
9
|
+
* @internal Validate a `subSteps` count. Throws on a fractional/non-positive
|
|
10
|
+
* value: both sides loop `subSteps` times at `dt/subSteps`, so anything but a
|
|
11
|
+
* whole number is a determinism bug, not a tunable. Shared by `defineInput`
|
|
12
|
+
* and `setFixedTimestep`.
|
|
18
13
|
*/
|
|
19
|
-
export
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
* duplicate `@colyseus/schema` installs; the runtime calls
|
|
26
|
-
* `instance.clone()` and friends, which match by shape.
|
|
27
|
-
*/
|
|
28
|
-
ctor: new () => any;
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* Name of a monotonically-increasing numeric field on the input schema used
|
|
32
|
-
* to order and dedupe incoming frames. When set, the framework:
|
|
33
|
-
* - Drops redundant frames (`input[seqField]` ≤ the last-seen value are
|
|
34
|
-
* discarded before they enter the buffer). Matches the unreliable-mode
|
|
35
|
-
* ring-redundancy pattern out of the box.
|
|
36
|
-
* - Powers `room.input(sessionId).at(value)` lookups.
|
|
37
|
-
*
|
|
38
|
-
* Despite the name, "seq" here is broader than an integer counter — any
|
|
39
|
-
* monotonic numeric field works:
|
|
40
|
-
* - **Sequence counter** (`"seq"`, `"tick"`, `"frame"`) — typical for
|
|
41
|
-
* lockstep / rollback netcode (Photon Quantum, GGPO).
|
|
42
|
-
* - **Timestamp** (`"timestamp"`, milliseconds or seconds) — useful for
|
|
43
|
-
* variable-rate clients, lag compensation, hit registration (Unreal CMC
|
|
44
|
-
* uses float-seconds timestamps via `FSavedMove_Character.TimeStamp`).
|
|
45
|
-
*
|
|
46
|
-
* Whichever you use, the field must increase monotonically across frames
|
|
47
|
-
* for dedupe to work.
|
|
48
|
-
*/
|
|
49
|
-
seqField?: string;
|
|
50
|
-
|
|
51
|
-
/**
|
|
52
|
-
* > 0 enables per-client buffering of cloned snapshots — required for
|
|
53
|
-
* `room.input(sessionId).drain() / .peek() / .at()` to return populated
|
|
54
|
-
* data. Oldest drops on overflow. Set to `0` to disable (`.latest` still
|
|
55
|
-
* works).
|
|
56
|
-
*/
|
|
57
|
-
bufferMaxSize: number;
|
|
14
|
+
export function validateSubSteps(subSteps: number | undefined, source: string): number | undefined {
|
|
15
|
+
if (subSteps === undefined) { return undefined; }
|
|
16
|
+
if (!Number.isInteger(subSteps) || subSteps < 1) {
|
|
17
|
+
throw new Error(`[${source}] subSteps must be an integer >= 1 (got ${subSteps}).`);
|
|
18
|
+
}
|
|
19
|
+
return subSteps;
|
|
58
20
|
}
|
|
59
21
|
|
|
60
22
|
/**
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
* - {@link latest} — the bound Schema instance, mutated in place by the
|
|
65
|
-
* decoder. Cheapest read; use when only the most recent state matters.
|
|
66
|
-
* - {@link drain} / {@link peek} / {@link at} — populated when
|
|
67
|
-
* `defineInput()` was called with `bufferMaxSize > 0` (default 32).
|
|
68
|
-
* Use for rollback netcode / lockstep where every frame matters.
|
|
69
|
-
*
|
|
70
|
-
* Returned for unknown sessionIds and rooms without `defineInput()` is a
|
|
71
|
-
* frozen no-op accessor (latest=undefined, drain/peek=[], at=undefined,
|
|
72
|
-
* size=0, clear=no-op).
|
|
23
|
+
* @internal Compile a {@link SanitizeInput} spec into the per-frame function the
|
|
24
|
+
* decode path applies. The map form precompiles to dense min/max arrays walked
|
|
25
|
+
* with the NaN-safe branch clamp; the callback form passes through.
|
|
73
26
|
*/
|
|
74
|
-
export
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
/** Number of snapshots currently buffered. */
|
|
95
|
-
readonly size: number;
|
|
27
|
+
export function compileSanitizer<I>(spec: SanitizeInput<I>): (input: I) => void {
|
|
28
|
+
if (typeof spec === 'function') { return spec; }
|
|
29
|
+
const names = Object.keys(spec);
|
|
30
|
+
const mins = new Float64Array(names.length);
|
|
31
|
+
const maxs = new Float64Array(names.length);
|
|
32
|
+
for (let i = 0; i < names.length; i++) {
|
|
33
|
+
const range = (spec as Record<string, readonly [number, number]>)[names[i]]!;
|
|
34
|
+
mins[i] = range[0];
|
|
35
|
+
maxs[i] = range[1];
|
|
36
|
+
}
|
|
37
|
+
return (input: I) => {
|
|
38
|
+
const inst = input as Record<string, number>;
|
|
39
|
+
for (let i = 0; i < names.length; i++) {
|
|
40
|
+
const v = inst[names[i]];
|
|
41
|
+
// NaN-safe: NaN fails both comparisons → clamp floor.
|
|
42
|
+
inst[names[i]] = v >= mins[i] ? (v <= maxs[i] ? v : maxs[i]) : mins[i];
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
}
|
|
96
46
|
|
|
97
|
-
|
|
98
|
-
|
|
47
|
+
/** Field names of an input schema ctor, in declaration order (indices are dense
|
|
48
|
+
* from 0 in the metadata). Resolved ONCE per buffer (cold path). */
|
|
49
|
+
function fieldNamesOf(ctor: new () => any): string[] {
|
|
50
|
+
const md = (ctor as any)[$METADATA] as Record<number, { name?: string }> | undefined;
|
|
51
|
+
const names: string[] = [];
|
|
52
|
+
if (md) {
|
|
53
|
+
for (let i = 0; ; i++) {
|
|
54
|
+
const f = md[i];
|
|
55
|
+
if (!f || typeof f.name !== "string") break;
|
|
56
|
+
names.push(f.name);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return names;
|
|
99
60
|
}
|
|
100
61
|
|
|
101
|
-
/**
|
|
102
|
-
*
|
|
103
|
-
*
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
62
|
+
/** Reclaim the consumed prefix once the read cursor passes this many items —
|
|
63
|
+
* bounds the parallel arrays' slack to O(THRESHOLD) between compactions while
|
|
64
|
+
* keeping per-consume work O(1) (no `shift()` re-index on every input). */
|
|
65
|
+
const COMPACT_THRESHOLD = 32;
|
|
66
|
+
|
|
67
|
+
/** Shared zero-state "already done" iterator — returned by `consume()` on an
|
|
68
|
+
* empty buffer with no idle policy, and by the no-op accessor. Frozen + a frozen
|
|
69
|
+
* result, so it's allocation-free and safe to share across all callers. */
|
|
70
|
+
const DONE_RESULT: IteratorResult<any> = Object.freeze({ value: undefined, done: true });
|
|
71
|
+
const DONE_ITERATOR: IterableIterator<any> = Object.freeze({
|
|
72
|
+
[Symbol.iterator]() { return this; },
|
|
73
|
+
next() { return DONE_RESULT; },
|
|
74
|
+
});
|
|
107
75
|
|
|
108
76
|
/** @internal */
|
|
109
77
|
export class InputBufferImpl<I = any> {
|
|
78
|
+
/** Pending snapshots, indexed `[_head, _items.length)`. Consumed inputs are
|
|
79
|
+
* NOT spliced off per-read — `_head` advances and the prefix is reclaimed in
|
|
80
|
+
* bulk by {@link compact} (a `shift()` per read is O(n), so a burst would be
|
|
81
|
+
* O(n²)). `_renderTimes`/`_reckonTimes` stay parallel to `_items`. */
|
|
110
82
|
private _items: I[] = [];
|
|
83
|
+
/** Read cursor: index of the oldest UNCONSUMED input (== `_items.length` when empty). */
|
|
84
|
+
private _head = 0;
|
|
111
85
|
private _lastSeq: number = -Infinity;
|
|
112
86
|
private readonly _maxSize: number;
|
|
113
87
|
private readonly _seqField: string | undefined;
|
|
114
88
|
|
|
115
|
-
|
|
89
|
+
/**
|
|
90
|
+
* Cumulative count of inputs CONSUMED from this buffer (via any consume
|
|
91
|
+
* primitive — {@link next}/{@link take}/{@link drain}/{@link consume} — plus
|
|
92
|
+
* {@link clear} and overflow). Consumed = "removed from the pending set",
|
|
93
|
+
* whether applied to state or discarded. The server echoes this in the TIMED
|
|
94
|
+
* prefix as the reconciliation ack: how many of the client's inputs are
|
|
95
|
+
* reflected in (or finished influencing) the authoritative state, which lags
|
|
96
|
+
* the receive counter by inputs still buffered. Distinct from
|
|
97
|
+
* `_receivedInputCount` (receive-time, for RTT), which leads the state.
|
|
98
|
+
*/
|
|
99
|
+
consumedCount = 0;
|
|
100
|
+
|
|
101
|
+
/** Render times parallel to `_items` (server-clock ms; `0` when unset). */
|
|
102
|
+
private _renderTimes: number[] = [];
|
|
103
|
+
/** Render time of the most recently drained input (see {@link renderTime}). */
|
|
104
|
+
private _lastRenderTime = 0;
|
|
105
|
+
/** Reckon-display stamps parallel to `_items` — the client's serverNow
|
|
106
|
+
* estimate at input-sample time, i.e. the instant its forward-reckoned
|
|
107
|
+
* entities were displayed at (server-clock ms; `0` when unset). */
|
|
108
|
+
private _reckonTimes: number[] = [];
|
|
109
|
+
/** Reckon stamp of the most recently consumed input (see {@link reckonTime}). */
|
|
110
|
+
private _lastReckonTime = 0;
|
|
111
|
+
/** Framework wire seq per buffered input (parallel to `_items`) — UNRELIABLE
|
|
112
|
+
* ONLY, lazily created on the first seq-carrying push. Reliable inputs are
|
|
113
|
+
* contiguous, so their consumed-seq-value is always exactly {@link consumedCount}
|
|
114
|
+
* and needs no parallel array; `undefined` here marks that (the common, default
|
|
115
|
+
* path pays nothing). A buffer is single-mode, so this is either never created
|
|
116
|
+
* (reliable) or created once and kept parallel (unreliable). */
|
|
117
|
+
private _seqs?: number[];
|
|
118
|
+
/** Seq VALUE of the last consumed input — the reconciliation ack echoed to the
|
|
119
|
+
* client (see {@link ackSeq}). Only meaningful when {@link _seqs} is tracked
|
|
120
|
+
* (unreliable); reliable's ack falls back to {@link consumedCount}. */
|
|
121
|
+
private _lastConsumedSeq = 0;
|
|
122
|
+
/** Whether the most recently produced frame was a synthesized idle (see {@link wasIdle}). */
|
|
123
|
+
private _lastWasIdle = false;
|
|
124
|
+
|
|
125
|
+
/** Reused {@link consume} iterator (lazily minted) + its per-call state, so a
|
|
126
|
+
* per-tick loop allocates no generator frame. `_iterRemaining` snapshots the
|
|
127
|
+
* COUNT to walk — a count, not an index: mid-pass mutations (`next()`/`take()`/
|
|
128
|
+
* `clear()`/compaction) shift indices but can only shorten a count-based pass,
|
|
129
|
+
* never point it past the tail. `_iterIdle` is an optional trailing synthesized
|
|
130
|
+
* frame; `_iterActive` guards against a nested consume() clobbering the shared
|
|
131
|
+
* `_iterRes`. */
|
|
132
|
+
private _iter?: IterableIterator<I>;
|
|
133
|
+
private _iterRemaining = 0;
|
|
134
|
+
private _iterActive = false;
|
|
135
|
+
private _iterIdle?: I;
|
|
136
|
+
private readonly _iterRes: { value: I | undefined; done: boolean } = { value: undefined, done: false };
|
|
137
|
+
|
|
138
|
+
/** Input schema ctor — mints the reused idle frame; idle is off without it. */
|
|
139
|
+
private readonly _ctor?: new () => I;
|
|
140
|
+
/** Client slice this buffer belongs to (the live object is `Client & ClientPrivate`)
|
|
141
|
+
* — feeds the idle callback's ctx (latest + sessionId). */
|
|
142
|
+
private readonly _client?: Pick<ClientPrivate, '_input'> & { sessionId: string };
|
|
143
|
+
/** Room-level idle policy (`defineInput({ idle })`) — the bare-call default. */
|
|
144
|
+
private readonly _roomIdle?: IdleInput<I>;
|
|
145
|
+
/** Reused synthesized idle frame + the schema's field names/defaults (lazy). */
|
|
146
|
+
private _idle?: I;
|
|
147
|
+
private _fieldNames?: string[];
|
|
148
|
+
private _defaults?: unknown[];
|
|
149
|
+
/** Reused ctx for the idle callback form (see {@link IdleContext}). */
|
|
150
|
+
private readonly _idleCtx: IdleContext<I> = { latest: undefined, sessionId: "" };
|
|
151
|
+
|
|
152
|
+
constructor(maxSize: number, seqField: string | undefined, ctor?: new () => I, client?: Pick<ClientPrivate, '_input'> & { sessionId: string }, idle?: IdleInput<I>) {
|
|
116
153
|
this._maxSize = maxSize;
|
|
117
154
|
this._seqField = seqField;
|
|
155
|
+
this._ctor = ctor;
|
|
156
|
+
this._client = client;
|
|
157
|
+
this._roomIdle = idle;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** The effective idle policy for one consume call: per-call `false` suppresses,
|
|
161
|
+
* per-call value overrides, else the room-level default (or none). */
|
|
162
|
+
private effectiveIdle(opts?: ConsumeOptions<I>): IdleInput<I> | undefined {
|
|
163
|
+
return opts?.idle === false ? undefined : (opts?.idle ?? this._roomIdle);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Resolve an {@link IdleInput} to overrides — invokes the callback form
|
|
167
|
+
* LAZILY, here at synthesis time (the buffer is known to be empty). */
|
|
168
|
+
private resolveIdle(idle: IdleInput<I>): true | Partial<I> {
|
|
169
|
+
if (typeof idle !== "function") return idle;
|
|
170
|
+
this._idleCtx.latest = this._client?._input as I | undefined;
|
|
171
|
+
this._idleCtx.sessionId = this._client?.sessionId ?? "";
|
|
172
|
+
return idle(this._idleCtx) ?? true;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* The synthesized "no input this tick" frame: schema defaults overlaid with
|
|
177
|
+
* `overrides` (`true` = none). Copies BY FIELD NAME from the schema metadata —
|
|
178
|
+
* schema fields are prototype accessors (no own props), so `Object.assign`
|
|
179
|
+
* can't source from a schema instance; the name walk reads getters, letting
|
|
180
|
+
* `overrides` be a plain partial OR a schema instance (e.g. `latest`).
|
|
181
|
+
* ONE reused instance — refilled per call, never advances the ack.
|
|
182
|
+
*/
|
|
183
|
+
private idleFrame(overrides: true | Partial<I>): I {
|
|
184
|
+
if (this._idle === undefined) {
|
|
185
|
+
// Lazy mint (cold): the fresh instance doubles as the defaults source.
|
|
186
|
+
this._idle = new this._ctor!();
|
|
187
|
+
this._fieldNames = fieldNamesOf(this._ctor!);
|
|
188
|
+
const fresh = this._idle as Record<string, unknown>;
|
|
189
|
+
this._defaults = this._fieldNames.map((n) => fresh[n]);
|
|
190
|
+
}
|
|
191
|
+
const idle = this._idle as Record<string, unknown>;
|
|
192
|
+
const names = this._fieldNames!;
|
|
193
|
+
const defaults = this._defaults!;
|
|
194
|
+
const ov = overrides === true ? undefined : (overrides as Record<string, unknown>);
|
|
195
|
+
for (let i = 0; i < names.length; i++) {
|
|
196
|
+
const v = ov?.[names[i]];
|
|
197
|
+
idle[names[i]] = v !== undefined ? v : defaults[i];
|
|
198
|
+
}
|
|
199
|
+
return this._idle;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** The idle frame to synthesize on an empty tick (room policy or per-call
|
|
203
|
+
* `opts.idle`), or `undefined` when no policy is in effect. Reuses the single
|
|
204
|
+
* idle instance; never advances the ack. Callers set {@link wasIdle}. */
|
|
205
|
+
private idleFrameOnEmpty(opts?: ConsumeOptions<I>): I | undefined {
|
|
206
|
+
const idle = this._ctor !== undefined ? this.effectiveIdle(opts) : undefined;
|
|
207
|
+
return idle === undefined ? undefined : this.idleFrame(this.resolveIdle(idle));
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Consume the input at the cursor: advance cursor + ack, stamp THIS input's
|
|
211
|
+
* render/reckon times, clear {@link wasIdle}. The shared per-input step behind
|
|
212
|
+
* {@link next}, {@link consume}'s iterator, and the re-entrant fallback. */
|
|
213
|
+
private stepHead(): I {
|
|
214
|
+
const i = this._head;
|
|
215
|
+
this._lastWasIdle = false;
|
|
216
|
+
this._lastRenderTime = this._renderTimes[i];
|
|
217
|
+
this._lastReckonTime = this._reckonTimes[i];
|
|
218
|
+
if (this._seqs !== undefined) { this._lastConsumedSeq = this._seqs[i]; }
|
|
219
|
+
this._head = i + 1;
|
|
220
|
+
this.consumedCount++;
|
|
221
|
+
return this._items[i];
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Drop ALL slots, reusing the backing arrays' capacity — the zero-GC reset for
|
|
225
|
+
* the consume/next path ({@link compact}/{@link clear}). `drain()` deliberately
|
|
226
|
+
* does NOT use this (it returns an array, so fresh `[]` is faster there). */
|
|
227
|
+
private truncate(): void {
|
|
228
|
+
this._items.length = 0;
|
|
229
|
+
this._renderTimes.length = 0;
|
|
230
|
+
this._reckonTimes.length = 0;
|
|
231
|
+
if (this._seqs !== undefined) { this._seqs.length = 0; }
|
|
232
|
+
this._head = 0;
|
|
118
233
|
}
|
|
119
234
|
|
|
120
|
-
|
|
235
|
+
/**
|
|
236
|
+
* Append a decoded input snapshot. `seq` is the framework wire seq (unreliable);
|
|
237
|
+
* omit it for reliable inputs, which get an implicit monotonic receive count so
|
|
238
|
+
* {@link ackSeq} stays well-defined in both modes.
|
|
239
|
+
*/
|
|
240
|
+
push(snapshot: I, renderTime: number = 0, reckonTime: number = 0, seq?: number): void {
|
|
121
241
|
this._items.push(snapshot);
|
|
122
|
-
|
|
242
|
+
this._renderTimes.push(renderTime);
|
|
243
|
+
this._reckonTimes.push(reckonTime);
|
|
244
|
+
// Track the wire seq only for unreliable (seq provided); reliable derives its
|
|
245
|
+
// ack from consumedCount, so it never allocates/maintains this array.
|
|
246
|
+
if (seq !== undefined) { (this._seqs ??= []).push(seq); }
|
|
247
|
+
// Overflow drops the oldest unconsumed input; count it consumed so the ack
|
|
248
|
+
// still advances past it. Advance the cursor (don't shift) — keeps it O(1).
|
|
249
|
+
if (this.size > this._maxSize) {
|
|
250
|
+
if (this._seqs !== undefined) { this._lastConsumedSeq = this._seqs[this._head]; } // dropped oldest counts as acked
|
|
251
|
+
this._head++;
|
|
252
|
+
this.consumedCount++;
|
|
253
|
+
this.compact();
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Reclaim the consumed prefix `[0, _head)`. Free when fully drained (reuse the
|
|
258
|
+
* arrays); otherwise splice only once the cursor passes {@link COMPACT_THRESHOLD},
|
|
259
|
+
* so the amortized per-input cost stays O(1). */
|
|
260
|
+
private compact(): void {
|
|
261
|
+
if (this._head === 0) { return; }
|
|
262
|
+
if (this._head >= this._items.length) {
|
|
263
|
+
this.truncate();
|
|
264
|
+
} else if (this._head >= COMPACT_THRESHOLD) {
|
|
265
|
+
this._items.splice(0, this._head);
|
|
266
|
+
this._renderTimes.splice(0, this._head);
|
|
267
|
+
this._reckonTimes.splice(0, this._head);
|
|
268
|
+
if (this._seqs !== undefined) { this._seqs.splice(0, this._head); }
|
|
269
|
+
this._head = 0;
|
|
270
|
+
}
|
|
123
271
|
}
|
|
124
272
|
|
|
125
273
|
/** Returns true if `value` hasn't been seen, and updates the last-seen marker. */
|
|
@@ -129,31 +277,205 @@ export class InputBufferImpl<I = any> {
|
|
|
129
277
|
return true;
|
|
130
278
|
}
|
|
131
279
|
|
|
132
|
-
drain(): I[] {
|
|
133
|
-
|
|
280
|
+
drain(opts?: ConsumeOptions<I>): I[] {
|
|
281
|
+
// Empty: synthesize one idle frame (NOT consumed — no ack bump, stamps
|
|
282
|
+
// untouched) when a policy is in effect, else [].
|
|
283
|
+
if (this.size === 0) {
|
|
284
|
+
const idle = this.idleFrameOnEmpty(opts);
|
|
285
|
+
this._lastWasIdle = idle !== undefined;
|
|
286
|
+
return idle !== undefined ? [idle] : [];
|
|
287
|
+
}
|
|
288
|
+
this._lastWasIdle = false;
|
|
289
|
+
const last = this._items.length - 1;
|
|
290
|
+
this._lastRenderTime = this._renderTimes[last]; // drain reports the NEWEST stamps
|
|
291
|
+
this._lastReckonTime = this._reckonTimes[last];
|
|
292
|
+
if (this._seqs !== undefined) { this._lastConsumedSeq = this._seqs[last]; }
|
|
293
|
+
// Hand off the backing array untouched when nothing was partially consumed
|
|
294
|
+
// (O(1) — the caller may retain it); else copy out the unconsumed tail. Fresh
|
|
295
|
+
// arrays here, NOT truncate(): drain already allocates the returned array, and
|
|
296
|
+
// V8 makes `= []` + refill cheaper than `length = 0` reuse (~1.8× at small N),
|
|
297
|
+
// so the speed wins and the 3 tiny empties are negligible next to the return.
|
|
298
|
+
const out = this._head === 0 ? this._items : this._items.slice(this._head);
|
|
299
|
+
this.consumedCount += out.length;
|
|
134
300
|
this._items = [];
|
|
301
|
+
this._renderTimes = [];
|
|
302
|
+
this._reckonTimes = [];
|
|
303
|
+
if (this._seqs !== undefined) { this._seqs = []; }
|
|
304
|
+
this._head = 0;
|
|
305
|
+
return out;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** Consume the single oldest input (ack advances by one); `undefined` if
|
|
309
|
+
* empty — or the synthesized idle frame when an idle policy is in effect. */
|
|
310
|
+
next(opts?: ConsumeOptions<I>): I | undefined {
|
|
311
|
+
if (this.size === 0) {
|
|
312
|
+
const idle = this.idleFrameOnEmpty(opts);
|
|
313
|
+
this._lastWasIdle = idle !== undefined;
|
|
314
|
+
return idle;
|
|
315
|
+
}
|
|
316
|
+
const item = this.stepHead();
|
|
317
|
+
this.compact();
|
|
318
|
+
return item;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** Consume up to `n` oldest inputs (ack advances by the count actually taken). */
|
|
322
|
+
take(n: number): I[] {
|
|
323
|
+
this._lastWasIdle = false; // take never synthesizes idle
|
|
324
|
+
const avail = this.size;
|
|
325
|
+
if (n <= 0 || avail === 0) { return []; }
|
|
326
|
+
const count = Math.min(n, avail);
|
|
327
|
+
const start = this._head;
|
|
328
|
+
const out = this._items.slice(start, start + count);
|
|
329
|
+
this._lastRenderTime = this._renderTimes[start + count - 1]; // newest taken input's stamps
|
|
330
|
+
this._lastReckonTime = this._reckonTimes[start + count - 1];
|
|
331
|
+
if (this._seqs !== undefined) { this._lastConsumedSeq = this._seqs[start + count - 1]; }
|
|
332
|
+
this._head += count;
|
|
333
|
+
this.consumedCount += count;
|
|
334
|
+
this.compact();
|
|
135
335
|
return out;
|
|
136
336
|
}
|
|
137
337
|
|
|
338
|
+
/**
|
|
339
|
+
* Iterate pending inputs one at a time (per-yield ack + stamp updates), or
|
|
340
|
+
* exactly one synthesized idle frame on an empty buffer with a policy in
|
|
341
|
+
* effect. See {@link InputAccessor.consume}.
|
|
342
|
+
*
|
|
343
|
+
* Returns a POOLED iterator (reused across calls — no generator frame, no
|
|
344
|
+
* per-call allocation) that consumes at most the pending count snapshotted at
|
|
345
|
+
* the call — never past the live tail — plus one optional trailing idle frame.
|
|
346
|
+
* The cursor advances per `next()`, so `break` (which calls `return()`)
|
|
347
|
+
* leaves the rest buffered and compacts. A nested
|
|
348
|
+
* `consume()` of the SAME buffer while one is live falls back to a fresh
|
|
349
|
+
* generator so the pooled `_iterRes` isn't clobbered (nesting is meaningless —
|
|
350
|
+
* both share the cursor — but it must not corrupt).
|
|
351
|
+
*/
|
|
352
|
+
consume(opts?: ConsumeOptions<I>): IterableIterator<I> {
|
|
353
|
+
const empty = this.size === 0;
|
|
354
|
+
const idle = empty ? this.idleFrameOnEmpty(opts) : undefined;
|
|
355
|
+
if (empty && idle === undefined) { this._lastWasIdle = false; return DONE_ITERATOR as IterableIterator<I>; }
|
|
356
|
+
// A nested consume() of this same buffer would clobber the pooled iterator's
|
|
357
|
+
// shared state → hand the rare case a fresh generator instead.
|
|
358
|
+
if (this._iterActive) { return this.consumeGen(idle); }
|
|
359
|
+
this._iterActive = true;
|
|
360
|
+
this._iterIdle = idle; // one trailing idle frame, or undefined
|
|
361
|
+
this._iterRemaining = this.size; // count snapshot — a (hypothetical) mid-loop push isn't consumed this pass
|
|
362
|
+
return this.ensureIter();
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
[Symbol.iterator](): IterableIterator<I> {
|
|
366
|
+
return this.consume();
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** Lazily mint the reused iterator. Closures over `this` so it reads the
|
|
370
|
+
* private cursor directly; one `_iterRes` is reused — read each result before
|
|
371
|
+
* the next `next()`, as `for..of` / spread / `Array.from` all do. */
|
|
372
|
+
private ensureIter(): IterableIterator<I> {
|
|
373
|
+
if (this._iter !== undefined) { return this._iter; }
|
|
374
|
+
const self = this;
|
|
375
|
+
const res = this._iterRes;
|
|
376
|
+
const finish = (): IteratorResult<I> => {
|
|
377
|
+
self.compact();
|
|
378
|
+
self._iterActive = false;
|
|
379
|
+
self._iterRemaining = 0;
|
|
380
|
+
self._iterIdle = undefined;
|
|
381
|
+
res.value = undefined;
|
|
382
|
+
res.done = true;
|
|
383
|
+
return res as IteratorResult<I>;
|
|
384
|
+
};
|
|
385
|
+
this._iter = {
|
|
386
|
+
[Symbol.iterator]() { return this; },
|
|
387
|
+
next(): IteratorResult<I> {
|
|
388
|
+
// `size > 0` re-checks the live tail: a mid-loop next()/take()/clear()
|
|
389
|
+
// can only shorten the pass, never make it read past the end.
|
|
390
|
+
if (self._iterRemaining > 0 && self.size > 0) { // a buffered input
|
|
391
|
+
self._iterRemaining--;
|
|
392
|
+
res.value = self.stepHead();
|
|
393
|
+
res.done = false;
|
|
394
|
+
return res as IteratorResult<I>;
|
|
395
|
+
}
|
|
396
|
+
if (self._iterIdle !== undefined) { // one trailing idle frame
|
|
397
|
+
self._lastWasIdle = true;
|
|
398
|
+
res.value = self._iterIdle;
|
|
399
|
+
self._iterIdle = undefined;
|
|
400
|
+
res.done = false;
|
|
401
|
+
return res as IteratorResult<I>;
|
|
402
|
+
}
|
|
403
|
+
return finish();
|
|
404
|
+
},
|
|
405
|
+
return(): IteratorResult<I> { return finish(); }, // `break` → compact + release
|
|
406
|
+
};
|
|
407
|
+
return this._iter;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** Re-entrant fallback: a fresh generator for a nested `consume()` of this same
|
|
411
|
+
* buffer (the pooled iterator is single-active). Same accounting + compaction. */
|
|
412
|
+
private *consumeGen(idleFrame: I | undefined): IterableIterator<I> {
|
|
413
|
+
let remaining = this.size; // count-based walk, same reason as the pooled pass
|
|
414
|
+
try {
|
|
415
|
+
while (remaining-- > 0 && this.size > 0) { yield this.stepHead(); }
|
|
416
|
+
if (idleFrame !== undefined) { this._lastWasIdle = true; yield idleFrame; }
|
|
417
|
+
} finally {
|
|
418
|
+
this.compact();
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
138
422
|
peek(): I[] {
|
|
139
|
-
return this._items.slice();
|
|
423
|
+
return this._items.slice(this._head);
|
|
140
424
|
}
|
|
141
425
|
|
|
142
426
|
at(value: number): I | undefined {
|
|
143
427
|
if (this._seqField === undefined) { return undefined; }
|
|
144
|
-
for (let i =
|
|
428
|
+
for (let i = this._head; i < this._items.length; i++) {
|
|
145
429
|
if ((this._items[i] as any)[this._seqField] === value) { return this._items[i]; }
|
|
146
430
|
}
|
|
147
431
|
return undefined;
|
|
148
432
|
}
|
|
149
433
|
|
|
150
434
|
get size(): number {
|
|
151
|
-
return this._items.length;
|
|
435
|
+
return this._items.length - this._head;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/** Render time (server-clock ms) of the most recently drained input; `0`
|
|
439
|
+
* until the first render-time-stamped input is drained. */
|
|
440
|
+
get renderTime(): number {
|
|
441
|
+
return this._lastRenderTime;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/** Reckon-display stamp of the most recently consumed input — the client's
|
|
445
|
+
* serverNow estimate when it sampled that input, i.e. the EXACT instant its
|
|
446
|
+
* forward-reckoned entities were displayed at. Same consume semantics as
|
|
447
|
+
* {@link renderTime}. RAW: stays `0` until stamped — the resolved,
|
|
448
|
+
* always-usable value is the accessor's `reckonTime`
|
|
449
|
+
* (`room.inputs.get(sid)`); `rewind.lastSeenBy()`'s midpoint-reconstruction
|
|
450
|
+
* fallback depends on this raw `0`. */
|
|
451
|
+
get reckonTime(): number {
|
|
452
|
+
return this._lastReckonTime;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/** Seq VALUE of the last consumed input — the reconciliation ack sent to the
|
|
456
|
+
* client. Reliable (no wire seq tracked): falls back to {@link consumedCount}
|
|
457
|
+
* for free. Unreliable: the framework wire seq, so a fully-dropped input doesn't
|
|
458
|
+
* make the ack lag the client's sent seq by the lost count. `0` before the first
|
|
459
|
+
* consume. */
|
|
460
|
+
get ackSeq(): number {
|
|
461
|
+
return this._seqs !== undefined ? this._lastConsumedSeq : this.consumedCount;
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/** Whether the most recently produced frame was a synthesized idle (see {@link wasIdle}). */
|
|
465
|
+
get wasIdle(): boolean {
|
|
466
|
+
return this._lastWasIdle;
|
|
152
467
|
}
|
|
153
468
|
|
|
154
469
|
clear(): void {
|
|
155
|
-
|
|
470
|
+
// Cleared inputs count as consumed: advance both the count and the seq-value ack
|
|
471
|
+
// past them so the client's pending set drains (capture the newest seq before truncate).
|
|
472
|
+
if (this._seqs !== undefined && this._items.length > 0) { this._lastConsumedSeq = this._seqs[this._items.length - 1]; }
|
|
473
|
+
this.consumedCount += this.size;
|
|
474
|
+
this.truncate();
|
|
156
475
|
this._lastSeq = -Infinity;
|
|
476
|
+
this._iterActive = false; // recovery hatch if a consume() iterator was abandoned unclosed
|
|
477
|
+
this._iterRemaining = 0; // an abandoned iterator must not consume post-clear pushes
|
|
478
|
+
this._iterIdle = undefined;
|
|
157
479
|
}
|
|
158
480
|
}
|
|
159
481
|
|
|
@@ -161,23 +483,50 @@ export class InputBufferImpl<I = any> {
|
|
|
161
483
|
* Default per-client accessor. Reads `_input` and `_inputBuffer` off the
|
|
162
484
|
* client at access time — both are nullable until the room declares input
|
|
163
485
|
* via `defineInput()`. Cached as `client._inputAccessor` at join, so
|
|
164
|
-
* `room.
|
|
486
|
+
* `room.inputs.get(sessionId)` is a Map lookup + property read.
|
|
165
487
|
*
|
|
166
488
|
* @internal
|
|
167
489
|
*/
|
|
168
490
|
export class InputAccessorImpl<I = any> implements InputAccessor<I> {
|
|
169
491
|
private _client: ClientPrivate;
|
|
170
|
-
|
|
492
|
+
/** Current room time (`clock.elapsedTime`) — resolves the {@link reckonTime}
|
|
493
|
+
* fallback. Threaded by `RoomInput.allocate()`; optional so bare
|
|
494
|
+
* constructions (tests) keep the raw 0. */
|
|
495
|
+
private _nowOf?: () => number;
|
|
496
|
+
constructor(client: ClientPrivate, nowOf?: () => number) {
|
|
497
|
+
this._client = client;
|
|
498
|
+
this._nowOf = nowOf;
|
|
499
|
+
}
|
|
171
500
|
get latest(): I | undefined { return this._client._input as I | undefined; }
|
|
172
501
|
at(value: number): I | undefined { return this._client._inputBuffer?.at(value) as I | undefined; }
|
|
173
|
-
|
|
502
|
+
consume(opts?: ConsumeOptions<I>): IterableIterator<I> {
|
|
503
|
+
return (this._client._inputBuffer?.consume(opts) ?? DONE_ITERATOR) as IterableIterator<I>;
|
|
504
|
+
}
|
|
505
|
+
[Symbol.iterator](): IterableIterator<I> { return this.consume(); }
|
|
506
|
+
drain(opts?: ConsumeOptions<I>): I[] { return (this._client._inputBuffer?.drain(opts) ?? []) as I[]; }
|
|
507
|
+
next(): I | undefined;
|
|
508
|
+
next(opts: { idle: IdleInput<I> }): I;
|
|
509
|
+
next(opts?: ConsumeOptions<I>): I | undefined { return this._client._inputBuffer?.next(opts) as I | undefined; }
|
|
510
|
+
take(n: number): I[] { return (this._client._inputBuffer?.take(n) ?? []) as I[]; }
|
|
174
511
|
peek(): I[] { return (this._client._inputBuffer?.peek() ?? []) as I[]; }
|
|
175
512
|
get size(): number { return this._client._inputBuffer?.size ?? 0; }
|
|
513
|
+
get consumedCount(): number { return this._client._inputBuffer?.consumedCount ?? 0; }
|
|
514
|
+
get wasIdle(): boolean { return this._client._inputBuffer?.wasIdle ?? false; }
|
|
176
515
|
clear(): void { this._client._inputBuffer?.clear(); }
|
|
516
|
+
get renderTime(): number { return this._client._inputBuffer?.renderTime ?? 0; }
|
|
517
|
+
/** @internal RAW reckon stamp (0 until stamped). The rewind binding reads
|
|
518
|
+
* THIS, not the resolved getter below: `Rewind._aim`'s midpoint fallback
|
|
519
|
+
* must still see 0 for unstamped clients (a resolved value would silently
|
|
520
|
+
* take the direct-stamp clamp path). */
|
|
521
|
+
get rawReckonTime(): number { return this._client._inputBuffer?.reckonTime ?? 0; }
|
|
522
|
+
get reckonTime(): number {
|
|
523
|
+
const raw = this._client._inputBuffer?.reckonTime ?? 0;
|
|
524
|
+
return raw > 0 ? raw : this._nowOf !== undefined ? this._nowOf() : 0;
|
|
525
|
+
}
|
|
177
526
|
}
|
|
178
527
|
|
|
179
528
|
/**
|
|
180
|
-
* Returned by `room.
|
|
529
|
+
* Returned by `room.inputs.get(sessionId)` for unknown sessions and for rooms
|
|
181
530
|
* that didn't call `defineInput()`.
|
|
182
531
|
*
|
|
183
532
|
* @internal
|
|
@@ -185,8 +534,16 @@ export class InputAccessorImpl<I = any> implements InputAccessor<I> {
|
|
|
185
534
|
export const NO_OP_INPUT_ACCESSOR: InputAccessor<any> = Object.freeze({
|
|
186
535
|
latest: undefined,
|
|
187
536
|
at: () => undefined,
|
|
537
|
+
consume: () => DONE_ITERATOR,
|
|
538
|
+
[Symbol.iterator]: () => DONE_ITERATOR,
|
|
188
539
|
drain: () => [],
|
|
540
|
+
next: () => undefined,
|
|
541
|
+
take: () => [],
|
|
189
542
|
peek: () => [],
|
|
190
543
|
size: 0,
|
|
544
|
+
consumedCount: 0,
|
|
545
|
+
wasIdle: false,
|
|
191
546
|
clear: () => {},
|
|
547
|
+
renderTime: 0,
|
|
548
|
+
reckonTime: 0, // stays 0 — an unknown session / input-less room has no clock to resolve against
|
|
192
549
|
});
|