@crowdedkingdoms/crowdyjs 18.39.1 → 18.40.0-dev.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/MIGRATION.md +62 -0
- package/README.md +420 -17
- package/dist/binary-wire.d.ts +94 -1
- package/dist/binary-wire.d.ts.map +1 -1
- package/dist/binary-wire.js +122 -20
- package/dist/crowdy-client.d.ts +7 -0
- package/dist/crowdy-client.d.ts.map +1 -1
- package/dist/crowdy-client.js +3 -0
- package/dist/default-origin.d.ts +6 -6
- package/dist/default-origin.d.ts.map +1 -1
- package/dist/default-origin.js +6 -6
- package/dist/domains/admin.d.ts +7 -0
- package/dist/domains/admin.d.ts.map +1 -1
- package/dist/domains/admin.js +1 -0
- package/dist/domains/exec.d.ts +91 -3
- package/dist/domains/exec.d.ts.map +1 -1
- package/dist/domains/exec.js +132 -5
- package/dist/domains/fleetSessions.d.ts +87 -0
- package/dist/domains/fleetSessions.d.ts.map +1 -0
- package/dist/domains/fleetSessions.js +87 -0
- package/dist/dropped-read.d.ts +2 -1
- package/dist/dropped-read.d.ts.map +1 -1
- package/dist/dropped-read.js +2 -6
- package/dist/errors.d.ts +59 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +70 -0
- package/dist/fleet/index.d.ts +4 -0
- package/dist/fleet/index.d.ts.map +1 -0
- package/dist/fleet/index.js +21 -0
- package/dist/fleet/session.d.ts +730 -0
- package/dist/fleet/session.d.ts.map +1 -0
- package/dist/fleet/session.js +1376 -0
- package/dist/fleet/socket.d.ts +59 -0
- package/dist/fleet/socket.d.ts.map +1 -0
- package/dist/fleet/socket.js +111 -0
- package/dist/fleet-wire.d.ts +272 -0
- package/dist/fleet-wire.d.ts.map +1 -0
- package/dist/fleet-wire.js +472 -0
- package/dist/generated/graphql-schema.d.ts +176 -13
- package/dist/generated/graphql-schema.d.ts.map +1 -1
- package/dist/generated/graphql-schema.js +15 -3
- package/dist/generated/graphql.d.ts +79 -0
- package/dist/generated/graphql.d.ts.map +1 -1
- package/dist/generated/graphql.js +5 -0
- package/dist/index.d.ts +6 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -3
- package/dist/server-only.d.ts +54 -0
- package/dist/server-only.d.ts.map +1 -0
- package/dist/server-only.js +55 -0
- package/package.json +5 -1
|
@@ -0,0 +1,1376 @@
|
|
|
1
|
+
import { ClientCapability, CONTROL_NONCE_BYTES, MAX_MEDIA_SPEAKERS, serializeActorHeartbeat, serializeActorUpdate, serializeAudioPacket, serializeChannelAudio, serializeChannelMessage, serializeClientCapabilities, serializeClientEvent, serializeClientMediaSpeakers, serializeGenericSpatial, serializeRangedChannelMessage, serializeSingleActorMessage, serializeTextPacket, serializeVideoPacket, serializeVoxelUpdate, SpeakerListMode, WireMessageType, assertVoxelEdit, } from '../binary-wire.js';
|
|
2
|
+
import { CrowdyError, CrowdyRealtimeError } from '../errors.js';
|
|
3
|
+
import { carriedPlayerContext, createFleetSignContext, FLEET_MAX_DATAGRAM_BYTES, FLEET_TOKEN_CHARS, FleetCarryStatus, parseFleetDatagram, serializeFleetCarry, serializeFleetRelease, } from '../fleet-wire.js';
|
|
4
|
+
import { fleetServerAddress, nodeFleetSocket, } from './socket.js';
|
|
5
|
+
/**
|
|
6
|
+
* A send named a player this session does not carry now: never carried, a carry still
|
|
7
|
+
* waiting for its result, or one that ended. Nothing was sent.
|
|
8
|
+
*/
|
|
9
|
+
export class FleetNotCarriedError extends CrowdyError {
|
|
10
|
+
constructor(playerGameTokenId) {
|
|
11
|
+
super({ message: `this fleet session does not carry player ${playerGameTokenId} now` });
|
|
12
|
+
this.code = 'FLEET_NOT_CARRIED';
|
|
13
|
+
this.playerGameTokenId = playerGameTokenId;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* How many rows a session's table may hold past its `maxPlayers`: room for carries that wait
|
|
18
|
+
* for an answer while the table is full, such as a player's carry with a refreshed token
|
|
19
|
+
* before it replaces the row the same user had. The realtime servers allow a session the
|
|
20
|
+
* same 32 carries past `maxPlayers` at once.
|
|
21
|
+
*/
|
|
22
|
+
export const FLEET_TABLE_MARGIN = 32;
|
|
23
|
+
/** The most players any session may carry, used when a grant names no `maxPlayers`. */
|
|
24
|
+
const FLEET_MAX_PLAYERS_CEILING = 1024;
|
|
25
|
+
const OWN_TYPES = new Set([
|
|
26
|
+
WireMessageType.CLIENT_CAPABILITIES,
|
|
27
|
+
WireMessageType.FLEET_CARRY,
|
|
28
|
+
WireMessageType.FLEET_RELEASE,
|
|
29
|
+
WireMessageType.CLIENT_ACTOR_HEARTBEAT,
|
|
30
|
+
]);
|
|
31
|
+
const CARRY_OUTCOMES = {
|
|
32
|
+
[FleetCarryStatus.CARRIED]: 'carried',
|
|
33
|
+
[FleetCarryStatus.NO_LIVE_TOKEN]: 'noLiveToken',
|
|
34
|
+
[FleetCarryStatus.OTHER_ORGANIZATION]: 'otherOrganization',
|
|
35
|
+
[FleetCarryStatus.PROOF_FAILED]: 'proofFailed',
|
|
36
|
+
[FleetCarryStatus.SESSION_FULL]: 'sessionFull',
|
|
37
|
+
};
|
|
38
|
+
function idString(id, what) {
|
|
39
|
+
try {
|
|
40
|
+
if (typeof id === 'number' && !Number.isSafeInteger(id))
|
|
41
|
+
throw new RangeError();
|
|
42
|
+
if (typeof id === 'string' && !/^-?\d+$/.test(id))
|
|
43
|
+
throw new RangeError();
|
|
44
|
+
return BigInt(id).toString();
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
throw new RangeError(`${what} must be a whole 64-bit number: ${String(id)}`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
function speakerChange(list) {
|
|
51
|
+
if (list === undefined)
|
|
52
|
+
return { mode: SpeakerListMode.KEEP, names: [] };
|
|
53
|
+
if (list === null)
|
|
54
|
+
return { mode: SpeakerListMode.EVERYONE, names: [] };
|
|
55
|
+
return { mode: SpeakerListMode.ONLY, names: list };
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* A fleet session: one realtime session an organization's game server opens for itself, in
|
|
59
|
+
* which it carries the players who are on it (realtime servers v0.50.3). It connects to the
|
|
60
|
+
* realtime server over UDP, so it runs on Node, on a server the organization runs.
|
|
61
|
+
*
|
|
62
|
+
* **Security: an org token and a fleet token never go into a browser page or a game
|
|
63
|
+
* client.** The fleet token signs for every player the session carries. Keep it where the
|
|
64
|
+
* org token is kept, on a server your organization runs. A game on a player's device uses
|
|
65
|
+
* that player's own app token (`client.udp`).
|
|
66
|
+
*
|
|
67
|
+
* ```ts
|
|
68
|
+
* import { createCrowdyClient } from '@crowdedkingdoms/crowdyjs';
|
|
69
|
+
* import { FleetSession } from '@crowdedkingdoms/crowdyjs/fleet';
|
|
70
|
+
*
|
|
71
|
+
* const api = createCrowdyClient({ httpUrl });
|
|
72
|
+
* api.setToken(process.env.CK_ORG_TOKEN); // cko_…, scope fleet:session
|
|
73
|
+
*
|
|
74
|
+
* const fleet = new FleetSession({
|
|
75
|
+
* session: await api.fleetSessions.open(appId), // one session for each game server
|
|
76
|
+
* handlers: {
|
|
77
|
+
* actorUpdate: (n) => world.apply(n), // state: once for the session
|
|
78
|
+
* text: (n, players) => players?.forEach((p) => chat.deliver(p, n)), // only these players
|
|
79
|
+
* released: (r) => roster.remove(r.playerGameTokenId),
|
|
80
|
+
* },
|
|
81
|
+
* });
|
|
82
|
+
* await fleet.connect();
|
|
83
|
+
*
|
|
84
|
+
* // A player joined this server. The token and its id are the player's app token's.
|
|
85
|
+
* const carry = await fleet.carry({ token: player.token, gameTokenId: player.gameTokenId });
|
|
86
|
+
* if (carry.carried) await fleet.sendActorUpdate(carry.playerGameTokenId, { chunk, uuid, state });
|
|
87
|
+
*
|
|
88
|
+
* // Now and then: keep the session, and follow it to another realtime server.
|
|
89
|
+
* if (fleet.refreshDue()) await fleet.applyRefresh(await api.fleetSessions.refresh(fleet.refreshInput()));
|
|
90
|
+
* ```
|
|
91
|
+
*
|
|
92
|
+
* What the session sends: for a carried player, the message that player's own session would
|
|
93
|
+
* send, with the player's game token id in its tail and the HMAC keyed with the fleet token.
|
|
94
|
+
* Under its own game token id it sends only its capabilities (29), `FLEET_CARRY` (49),
|
|
95
|
+
* `FLEET_RELEASE` (50) and its keepalive (26). The platform applies each carried player's own
|
|
96
|
+
* permissions, blocks, age rules, speaker lists, rate budget (500 messages a second, bursts
|
|
97
|
+
* to 1,000) and idle timeout.
|
|
98
|
+
*
|
|
99
|
+
* What it receives: state once for the session, and communications inside `FLEET_DELIVERY`
|
|
100
|
+
* with the carried players who may receive them ({@link FleetPlayers}). Every notification
|
|
101
|
+
* is verified with the fleet token before a handler sees it, and no option turns that off.
|
|
102
|
+
* One that names another app than the session's is dropped and counted (`stats().wrongApp`).
|
|
103
|
+
* A refusal of a send has no room for a signature when it arrives alone, so `genericError`
|
|
104
|
+
* is told whether it was verified.
|
|
105
|
+
*
|
|
106
|
+
* The session makes no Application API call. {@link refreshDue} says when to call
|
|
107
|
+
* `refreshFleetSession`, and {@link applyRefresh} takes the answer.
|
|
108
|
+
*/
|
|
109
|
+
export class FleetSession {
|
|
110
|
+
constructor(config) {
|
|
111
|
+
this.ctx = null;
|
|
112
|
+
this.socket = null;
|
|
113
|
+
/** Counts connections: a datagram or a send of an earlier one is dropped. */
|
|
114
|
+
this.generation = 0;
|
|
115
|
+
this.controlNonce = null;
|
|
116
|
+
/** The server acknowledged this connection's nonce: it sends no unbound control frame. */
|
|
117
|
+
this.boundAcked = false;
|
|
118
|
+
/** Something from the server verified on this connection. */
|
|
119
|
+
this.answered = false;
|
|
120
|
+
/** When the server last said something that verified, or when this connection was opened. */
|
|
121
|
+
this.lastHeardAt = 0;
|
|
122
|
+
/** The connection is being opened: nothing goes out before its capabilities. */
|
|
123
|
+
this.binding = false;
|
|
124
|
+
this.currentStatus = 'idle';
|
|
125
|
+
this.moveWasOrdered = false;
|
|
126
|
+
/** The server holds no carry for this session: the next refresh carries every player again. */
|
|
127
|
+
this.carriesLost = false;
|
|
128
|
+
this.table = new Map();
|
|
129
|
+
/** A player's previous game token id, while the carry that replaces it waits: id -> row key. */
|
|
130
|
+
this.aliases = new Map();
|
|
131
|
+
/** Game token ids replaced by the same player's newer one, and when: late frames are ignored. */
|
|
132
|
+
this.replaced = new Map();
|
|
133
|
+
this.attemptOrder = 0;
|
|
134
|
+
/** Each `FLEET_CARRY` of the last second: when it was sent, and whether it was a retry. */
|
|
135
|
+
this.carrySends = [];
|
|
136
|
+
this.nextSequence = 0;
|
|
137
|
+
this.nextCapabilitiesAt = 0;
|
|
138
|
+
this.lastKeepAliveAt = 0;
|
|
139
|
+
this.timer = null;
|
|
140
|
+
this.ticking = false;
|
|
141
|
+
this.inbound = Promise.resolve();
|
|
142
|
+
this.connecting = null;
|
|
143
|
+
this.counters = {
|
|
144
|
+
datagramsSent: 0,
|
|
145
|
+
bytesSent: 0,
|
|
146
|
+
sentByType: {},
|
|
147
|
+
datagramsReceived: 0,
|
|
148
|
+
bytesReceived: 0,
|
|
149
|
+
hmacFailures: 0,
|
|
150
|
+
malformed: 0,
|
|
151
|
+
unsigned: 0,
|
|
152
|
+
wrongApp: 0,
|
|
153
|
+
oversized: 0,
|
|
154
|
+
staleControl: 0,
|
|
155
|
+
boundControlAcks: 0,
|
|
156
|
+
unmatchedCarryResults: 0,
|
|
157
|
+
noLiveTokenRetries: 0,
|
|
158
|
+
replacedIdFrames: 0,
|
|
159
|
+
errorsReceived: 0,
|
|
160
|
+
unauthorizedReceived: 0,
|
|
161
|
+
unverifiedErrorsReceived: 0,
|
|
162
|
+
carriesRefusedTableFull: 0,
|
|
163
|
+
};
|
|
164
|
+
const grant = config.session;
|
|
165
|
+
if (typeof grant?.token !== 'string' || grant.token.length !== FLEET_TOKEN_CHARS) {
|
|
166
|
+
throw new RangeError(`the fleet token must be ${FLEET_TOKEN_CHARS} characters`);
|
|
167
|
+
}
|
|
168
|
+
this.grant = {
|
|
169
|
+
...grant,
|
|
170
|
+
gameTokenId: idString(grant.gameTokenId, 'the fleet gameTokenId'),
|
|
171
|
+
appId: idString(grant.appId, 'appId'),
|
|
172
|
+
server: { ...grant.server },
|
|
173
|
+
};
|
|
174
|
+
fleetServerAddress(this.grant.server);
|
|
175
|
+
this.server = this.grant.server;
|
|
176
|
+
this.handlers = config.handlers ?? {};
|
|
177
|
+
this.logger = config.logger;
|
|
178
|
+
this.socketFactory = config.socket ?? nodeFleetSocket();
|
|
179
|
+
this.now = config.now ?? Date.now;
|
|
180
|
+
this.carryRetryMs = Math.max(1, config.carryRetryMs ?? 250);
|
|
181
|
+
this.carryTimeoutMs = Math.max(1, config.carryTimeoutMs ?? 5000);
|
|
182
|
+
this.maxCarriesPerSecond = Math.max(1, Math.min(63, Math.floor(config.maxCarriesPerSecond ?? 60)));
|
|
183
|
+
this.keepAliveIntervalMs = Math.max(100, config.keepAliveIntervalMs ?? 2000);
|
|
184
|
+
this.actorHeartbeatMs = Math.max(0, config.actorHeartbeatMs ?? 2000);
|
|
185
|
+
const silence = config.silenceTimeoutMs ?? 45000;
|
|
186
|
+
this.silenceTimeoutMs = silence > 0 ? Math.max(3000, silence) : 0;
|
|
187
|
+
// An idle session hears only the acknowledgements of its capabilities, so the silence it
|
|
188
|
+
// tolerates is at least three of their intervals.
|
|
189
|
+
const capabilities = Math.max(1000, config.capabilitiesIntervalMs ?? 15000);
|
|
190
|
+
this.capabilitiesIntervalMs =
|
|
191
|
+
this.silenceTimeoutMs > 0 ? Math.min(capabilities, Math.floor(this.silenceTimeoutMs / 3)) : capabilities;
|
|
192
|
+
this.bindRetryMs = Math.max(50, config.bindRetryMs ?? 500);
|
|
193
|
+
this.tickIntervalMs = Math.max(0, config.tickIntervalMs ?? 20);
|
|
194
|
+
this.capabilityFlags =
|
|
195
|
+
ClientCapability.BUNDLE_SIGNED |
|
|
196
|
+
ClientCapability.BOUND_CONTROL |
|
|
197
|
+
(config.fleetOwnState ? ClientCapability.FLEET_OWN_STATE : 0) |
|
|
198
|
+
(config.ownMediaEcho ? ClientCapability.OWN_MEDIA_ECHO : 0);
|
|
199
|
+
this.grantedAtMs = this.now();
|
|
200
|
+
this.expiresAtMs = expiryOf(grant.expiresAt);
|
|
201
|
+
}
|
|
202
|
+
// ----- What the session is ---------------------------------------------------
|
|
203
|
+
/** The app the session is in. */
|
|
204
|
+
get appId() {
|
|
205
|
+
return this.grant.appId;
|
|
206
|
+
}
|
|
207
|
+
/** The session's own game token id: what `refreshFleetSession` and `closeFleetSession` name it by. */
|
|
208
|
+
get gameTokenId() {
|
|
209
|
+
return this.grant.gameTokenId;
|
|
210
|
+
}
|
|
211
|
+
/** How many players the session may carry at once, when the grant said. */
|
|
212
|
+
get maxPlayers() {
|
|
213
|
+
return this.grant.maxPlayers ?? null;
|
|
214
|
+
}
|
|
215
|
+
/** When the session ends unless it is refreshed first, in epoch milliseconds; null when unknown. */
|
|
216
|
+
get expiresAt() {
|
|
217
|
+
return this.expiresAtMs;
|
|
218
|
+
}
|
|
219
|
+
/** The realtime server the session is on, or will connect to. */
|
|
220
|
+
get currentServer() {
|
|
221
|
+
return { ...this.server };
|
|
222
|
+
}
|
|
223
|
+
get status() {
|
|
224
|
+
return this.currentStatus;
|
|
225
|
+
}
|
|
226
|
+
/** Replace the handlers. */
|
|
227
|
+
setHandlers(handlers) {
|
|
228
|
+
this.handlers = handlers;
|
|
229
|
+
}
|
|
230
|
+
/** A copy of the session's counters. */
|
|
231
|
+
stats() {
|
|
232
|
+
return { ...this.counters, sentByType: { ...this.counters.sentByType } };
|
|
233
|
+
}
|
|
234
|
+
/** Never the tokens: what a log line or `JSON.stringify` shows of a session. */
|
|
235
|
+
toJSON() {
|
|
236
|
+
return {
|
|
237
|
+
appId: this.appId,
|
|
238
|
+
gameTokenId: this.gameTokenId,
|
|
239
|
+
status: this.currentStatus,
|
|
240
|
+
server: this.currentServer,
|
|
241
|
+
players: this.table.size,
|
|
242
|
+
carried: this.carriedCount,
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
/** @internal Node's `console.log` and `util.inspect` show {@link toJSON}, never the tokens. */
|
|
246
|
+
[Symbol.for('nodejs.util.inspect.custom')]() {
|
|
247
|
+
return `FleetSession ${JSON.stringify(this.toJSON())}`;
|
|
248
|
+
}
|
|
249
|
+
// ----- Connecting --------------------------------------------------------------
|
|
250
|
+
/**
|
|
251
|
+
* Open the socket to the realtime server and bind the session: its capabilities are its
|
|
252
|
+
* first datagram, under its own game token id. Resolves once they are sent. The
|
|
253
|
+
* capabilities go again every `bindRetryMs` until the server answers, since the session's
|
|
254
|
+
* token may reach the server a moment after `openFleetSession` returns; the status is then
|
|
255
|
+
* `'connected'`. Carries asked for before that wait and are sent in order.
|
|
256
|
+
*/
|
|
257
|
+
connect() {
|
|
258
|
+
if (this.currentStatus === 'closed') {
|
|
259
|
+
return Promise.reject(new CrowdyRealtimeError('the fleet session is closed', { code: 'FLEET_CLOSED' }));
|
|
260
|
+
}
|
|
261
|
+
if (this.socket)
|
|
262
|
+
return Promise.resolve();
|
|
263
|
+
if (!this.connecting) {
|
|
264
|
+
this.connecting = this.open(this.server).finally(() => {
|
|
265
|
+
this.connecting = null;
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
return this.connecting;
|
|
269
|
+
}
|
|
270
|
+
async open(server) {
|
|
271
|
+
const generation = ++this.generation;
|
|
272
|
+
this.ctx ?? (this.ctx = await createFleetSignContext(this.grant.gameTokenId, this.grant.token));
|
|
273
|
+
const nonce = new Uint8Array(CONTROL_NONCE_BYTES);
|
|
274
|
+
crypto.getRandomValues(nonce);
|
|
275
|
+
const socket = await this.socketFactory(server, {
|
|
276
|
+
onDatagram: (datagram) => this.onDatagram(generation, datagram),
|
|
277
|
+
onError: (error) => this.report(error),
|
|
278
|
+
});
|
|
279
|
+
if (generation !== this.generation || this.currentStatus === 'closed') {
|
|
280
|
+
socket.close();
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
const now = this.now();
|
|
284
|
+
this.binding = true;
|
|
285
|
+
try {
|
|
286
|
+
this.socket = socket;
|
|
287
|
+
this.server = { ...server };
|
|
288
|
+
this.controlNonce = nonce;
|
|
289
|
+
this.boundAcked = false;
|
|
290
|
+
this.answered = false;
|
|
291
|
+
this.carrySends = [];
|
|
292
|
+
this.lastHeardAt = now;
|
|
293
|
+
this.setStatus('connecting');
|
|
294
|
+
// The capabilities are the connection's first datagram: they bind the session.
|
|
295
|
+
await this.sendCapabilities();
|
|
296
|
+
this.nextCapabilitiesAt = now + this.bindRetryMs;
|
|
297
|
+
this.lastKeepAliveAt = now;
|
|
298
|
+
}
|
|
299
|
+
finally {
|
|
300
|
+
this.binding = false;
|
|
301
|
+
}
|
|
302
|
+
if (this.tickIntervalMs > 0 && !this.timer) {
|
|
303
|
+
this.timer = setInterval(() => void this.tick(), this.tickIntervalMs);
|
|
304
|
+
this.timer.unref?.();
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Close the socket and stop the timers. Carries waiting for an answer end `'closed'`, and
|
|
309
|
+
* the table is emptied. This does not end the session on the platform: call
|
|
310
|
+
* `client.fleetSessions.close` for that, or it ends at its `expiresAt`.
|
|
311
|
+
*/
|
|
312
|
+
close() {
|
|
313
|
+
if (this.currentStatus === 'closed')
|
|
314
|
+
return;
|
|
315
|
+
this.generation += 1;
|
|
316
|
+
if (this.timer)
|
|
317
|
+
clearInterval(this.timer);
|
|
318
|
+
this.timer = null;
|
|
319
|
+
this.socket?.close();
|
|
320
|
+
this.socket = null;
|
|
321
|
+
for (const player of this.table.values()) {
|
|
322
|
+
this.settle(player, { status: 'closed', wireStatus: null, userId: null }, false);
|
|
323
|
+
}
|
|
324
|
+
this.table.clear();
|
|
325
|
+
this.aliases.clear();
|
|
326
|
+
this.replaced.clear();
|
|
327
|
+
this.setStatus('closed');
|
|
328
|
+
}
|
|
329
|
+
// ----- Refreshing ----------------------------------------------------------------
|
|
330
|
+
/**
|
|
331
|
+
* True after the realtime server told the session to move, released it (for any reason, the
|
|
332
|
+
* fleet token expiring among them) or went quiet for `silenceTimeoutMs`, until a refresh is
|
|
333
|
+
* applied.
|
|
334
|
+
*/
|
|
335
|
+
get moveOrdered() {
|
|
336
|
+
return this.moveWasOrdered;
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* True when it is time to call `refreshFleetSession`: a move was ordered
|
|
340
|
+
* ({@link moveOrdered}), or less than half of the session's lifetime is left (12 hours into
|
|
341
|
+
* a 24-hour session, counted from when this object was given the grant). The session makes
|
|
342
|
+
* no call itself: ask this from your own loop.
|
|
343
|
+
*/
|
|
344
|
+
refreshDue() {
|
|
345
|
+
if (this.currentStatus === 'closed')
|
|
346
|
+
return false;
|
|
347
|
+
if (this.moveWasOrdered)
|
|
348
|
+
return true;
|
|
349
|
+
if (this.expiresAtMs === null)
|
|
350
|
+
return false;
|
|
351
|
+
return this.now() >= this.grantedAtMs + (this.expiresAtMs - this.grantedAtMs) / 2;
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* The input of `refreshFleetSession` for this session (`client.fleetSessions.refresh`). It
|
|
355
|
+
* names the realtime server the session is on, so the session stays there while that
|
|
356
|
+
* server still serves the app. After a move was ordered it names none, and the answer's
|
|
357
|
+
* server is the next one.
|
|
358
|
+
*
|
|
359
|
+
* `currentServer` is an IPv4 address and a port, which is all the Application API takes.
|
|
360
|
+
* Every realtime server has an IPv4 address. A session that was given none (it connected
|
|
361
|
+
* over `ip6`) sends no `currentServer`, so each refresh may answer another server.
|
|
362
|
+
*/
|
|
363
|
+
refreshInput() {
|
|
364
|
+
const input = { appId: this.appId, gameTokenId: this.gameTokenId };
|
|
365
|
+
if (this.moveWasOrdered || !this.server.ip4)
|
|
366
|
+
return input;
|
|
367
|
+
return { ...input, currentServer: { ip4: this.server.ip4, clientPort: this.server.clientPort } };
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* Take the answer of `refreshFleetSession`: the new expiry and the realtime server.
|
|
371
|
+
*
|
|
372
|
+
* - **The same server:** the carries stand. The session sends its capabilities again and no
|
|
373
|
+
* `FLEET_CARRY`.
|
|
374
|
+
* - **Another server**, or the same one after it released the session or went quiet: the
|
|
375
|
+
* server holds no carry. The session connects there, sends its capabilities, then a new `FLEET_CARRY` (a
|
|
376
|
+
* new time and proof) for every player, paced under 64 a second. Until each is answered,
|
|
377
|
+
* sends for that player are refused locally; each answer reaches `handlers.carryResult`.
|
|
378
|
+
*
|
|
379
|
+
* @throws {CrowdyError} with nothing changed, for an answer that is another session's (a
|
|
380
|
+
* different app or `gameTokenId`) or carries no usable token or server.
|
|
381
|
+
*/
|
|
382
|
+
async applyRefresh(answer) {
|
|
383
|
+
if (this.currentStatus === 'closed') {
|
|
384
|
+
throw new CrowdyRealtimeError('the fleet session is closed', { code: 'FLEET_CLOSED' });
|
|
385
|
+
}
|
|
386
|
+
if (typeof answer?.token !== 'string' || answer.token.length !== FLEET_TOKEN_CHARS) {
|
|
387
|
+
throw new CrowdyError({ message: `the refreshed fleet token must be ${FLEET_TOKEN_CHARS} characters` });
|
|
388
|
+
}
|
|
389
|
+
if (idString(answer.appId, 'appId') !== this.appId || idString(answer.gameTokenId, 'gameTokenId') !== this.gameTokenId) {
|
|
390
|
+
throw new CrowdyError({
|
|
391
|
+
message: 'that answer is another fleet session\u2019s: a refresh keeps the app and the gameTokenId',
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
const next = fleetServerAddress(answer.server);
|
|
395
|
+
const current = fleetServerAddress(this.server);
|
|
396
|
+
const sameServer = next.host === current.host && next.port === current.port;
|
|
397
|
+
const newToken = answer.token !== this.grant.token;
|
|
398
|
+
this.grant = { ...this.grant, token: answer.token, expiresAt: answer.expiresAt, maxPlayers: answer.maxPlayers ?? this.grant.maxPlayers };
|
|
399
|
+
this.grantedAtMs = this.now();
|
|
400
|
+
this.expiresAtMs = expiryOf(answer.expiresAt);
|
|
401
|
+
this.moveWasOrdered = false;
|
|
402
|
+
if (newToken) {
|
|
403
|
+
// A refresh keeps the token. One that does not is taken as a new key for everything.
|
|
404
|
+
this.ctx = await createFleetSignContext(this.grant.gameTokenId, this.grant.token);
|
|
405
|
+
for (const player of this.table.values())
|
|
406
|
+
player.ctx = carriedPlayerContext(this.ctx, player.gameTokenId);
|
|
407
|
+
}
|
|
408
|
+
if (!this.socket && this.currentStatus === 'idle') {
|
|
409
|
+
// Not connected yet: connect() goes to the server the answer names.
|
|
410
|
+
this.server = { ...answer.server };
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
413
|
+
if (sameServer && !this.carriesLost && !newToken && this.socket) {
|
|
414
|
+
await this.sendCapabilities();
|
|
415
|
+
this.nextCapabilitiesAt = this.now() + (this.answered ? this.capabilitiesIntervalMs : this.bindRetryMs);
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
// Another server (or this one again after it let the session go): it holds no carry.
|
|
419
|
+
this.generation += 1;
|
|
420
|
+
this.socket?.close();
|
|
421
|
+
this.socket = null;
|
|
422
|
+
this.carriesLost = false;
|
|
423
|
+
const now = this.now();
|
|
424
|
+
for (const player of this.table.values()) {
|
|
425
|
+
player.carried = false;
|
|
426
|
+
if (player.previous) {
|
|
427
|
+
// The new server holds no carry to stand meanwhile: the newest token is the only one.
|
|
428
|
+
this.aliases.delete(player.previous.gameTokenId);
|
|
429
|
+
this.retire(player.previous.gameTokenId);
|
|
430
|
+
player.previous = null;
|
|
431
|
+
if (this.ctx)
|
|
432
|
+
player.ctx = carriedPlayerContext(this.ctx, player.gameTokenId);
|
|
433
|
+
}
|
|
434
|
+
player.attempt = {
|
|
435
|
+
nextSendAt: now,
|
|
436
|
+
deadline: 0,
|
|
437
|
+
order: this.attemptOrder++,
|
|
438
|
+
resolvers: player.attempt?.resolvers ?? [],
|
|
439
|
+
noLiveToken: 'none',
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
await this.open({ ...answer.server });
|
|
443
|
+
}
|
|
444
|
+
/**
|
|
445
|
+
* Start or stop asking for the state this session's own carried players sent
|
|
446
|
+
* (`ClientCapability.FLEET_OWN_STATE`). Advertised at once when connected and it changed.
|
|
447
|
+
*/
|
|
448
|
+
async setFleetOwnState(on) {
|
|
449
|
+
await this.setCapability(ClientCapability.FLEET_OWN_STATE, on);
|
|
450
|
+
}
|
|
451
|
+
/** Start or stop asking for a carried speaker's own spatial voice and video. */
|
|
452
|
+
async setOwnMediaEcho(on) {
|
|
453
|
+
await this.setCapability(ClientCapability.OWN_MEDIA_ECHO, on);
|
|
454
|
+
}
|
|
455
|
+
async setCapability(bit, on) {
|
|
456
|
+
const flags = on ? this.capabilityFlags | bit : this.capabilityFlags & ~bit;
|
|
457
|
+
if (flags === this.capabilityFlags)
|
|
458
|
+
return;
|
|
459
|
+
this.capabilityFlags = flags;
|
|
460
|
+
if (this.socket)
|
|
461
|
+
await this.sendCapabilities();
|
|
462
|
+
}
|
|
463
|
+
// ----- Carrying ----------------------------------------------------------------------
|
|
464
|
+
/**
|
|
465
|
+
* Start carrying a player. `FLEET_CARRY` is sent when the session is connected and its turn
|
|
466
|
+
* comes (carries are paced under 64 a second), and again every `carryRetryMs` with a new
|
|
467
|
+
* time and proof until `FLEET_CARRY_RESULT` arrives or `carryTimeoutMs` passes. Resolves
|
|
468
|
+
* with how it ended; it does not reject for a refusal. Sends for the player are accepted
|
|
469
|
+
* from the moment the result is `'carried'`.
|
|
470
|
+
*
|
|
471
|
+
* **After you refresh a carried player's token**, call it with the new token and
|
|
472
|
+
* `replaces: <the id the player is carried under>`. The player stays carried throughout,
|
|
473
|
+
* with their actors and speaker lists: the carry made with the old token stands until the
|
|
474
|
+
* new one takes effect, and there is no `released` event. From the moment the new
|
|
475
|
+
* `FLEET_CARRY` goes out, every send for the player names the new id, whichever of the two
|
|
476
|
+
* ids you pass to the send; the realtime server holds those sends behind the carry. Once
|
|
477
|
+
* the result is `'carried'` the old id names nothing in this session. If the new carry is
|
|
478
|
+
* refused, the player stays carried under the old id.
|
|
479
|
+
*
|
|
480
|
+
* A carry answered "no live token" is asked once more, 250 ms later, before it settles. A
|
|
481
|
+
* carry that is refused or times out leaves the player not carried under that game token
|
|
482
|
+
* id; the session sends `FLEET_RELEASE` for one that timed out, since the server may hold a
|
|
483
|
+
* carry whose answers were lost.
|
|
484
|
+
*
|
|
485
|
+
* A carry for a new player when the table is full ends `'tableFull'` with nothing sent
|
|
486
|
+
* ({@link tableLimit}).
|
|
487
|
+
*
|
|
488
|
+
* @throws {RangeError} (as a rejection) for a token that is not 64 characters, or a game
|
|
489
|
+
* token id that is not a number or is the session's own.
|
|
490
|
+
*/
|
|
491
|
+
async carry(player) {
|
|
492
|
+
const id = idString(player?.gameTokenId, 'the player gameTokenId');
|
|
493
|
+
if (typeof player.token !== 'string' || player.token.length !== FLEET_TOKEN_CHARS) {
|
|
494
|
+
throw new RangeError(`the player's token must be ${FLEET_TOKEN_CHARS} characters`);
|
|
495
|
+
}
|
|
496
|
+
if (id === this.gameTokenId) {
|
|
497
|
+
throw new RangeError('a carry names a player\u2019s gameTokenId; that one is the fleet session\u2019s own gameTokenId');
|
|
498
|
+
}
|
|
499
|
+
if (this.currentStatus === 'closed') {
|
|
500
|
+
return { playerGameTokenId: id, userId: null, status: 'closed', wireStatus: null, carried: false };
|
|
501
|
+
}
|
|
502
|
+
const replaces = player.replaces == null ? null : idString(player.replaces, 'replaces');
|
|
503
|
+
this.ctx ?? (this.ctx = await createFleetSignContext(this.grant.gameTokenId, this.grant.token));
|
|
504
|
+
let row = this.table.get(id);
|
|
505
|
+
if (!row && replaces !== null && replaces !== id) {
|
|
506
|
+
// The same player with a refreshed token: the row moves to the new id at once.
|
|
507
|
+
const old = this.rowOf(replaces);
|
|
508
|
+
if (old)
|
|
509
|
+
row = this.supersede(old, id, player.token);
|
|
510
|
+
}
|
|
511
|
+
if (!row && this.table.size >= this.tableLimit) {
|
|
512
|
+
// A game server that never releases anyone must not grow the table without bound.
|
|
513
|
+
this.counters.carriesRefusedTableFull += 1;
|
|
514
|
+
return { playerGameTokenId: id, userId: null, status: 'tableFull', wireStatus: null, carried: false };
|
|
515
|
+
}
|
|
516
|
+
if (!row) {
|
|
517
|
+
row = {
|
|
518
|
+
gameTokenId: id,
|
|
519
|
+
token: player.token,
|
|
520
|
+
ctx: carriedPlayerContext(this.ctx, id),
|
|
521
|
+
previous: null,
|
|
522
|
+
userId: null,
|
|
523
|
+
carried: false,
|
|
524
|
+
attempt: null,
|
|
525
|
+
lastCarryEpoch: 0,
|
|
526
|
+
actors: new Map(),
|
|
527
|
+
voice: undefined,
|
|
528
|
+
video: undefined,
|
|
529
|
+
};
|
|
530
|
+
this.table.set(id, row);
|
|
531
|
+
}
|
|
532
|
+
row.token = player.token;
|
|
533
|
+
return new Promise((resolve) => {
|
|
534
|
+
const target = row;
|
|
535
|
+
if (target.attempt) {
|
|
536
|
+
target.attempt.resolvers.push(resolve);
|
|
537
|
+
}
|
|
538
|
+
else {
|
|
539
|
+
target.attempt = {
|
|
540
|
+
nextSendAt: this.now(),
|
|
541
|
+
deadline: 0,
|
|
542
|
+
order: this.attemptOrder++,
|
|
543
|
+
resolvers: [resolve],
|
|
544
|
+
noLiveToken: 'none',
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
if (this.tickIntervalMs > 0)
|
|
548
|
+
void this.tick();
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
/** The row a game token id names: its own, or the one a waiting replacement moved it to. */
|
|
552
|
+
rowOf(id) {
|
|
553
|
+
return this.table.get(id) ?? this.table.get(this.aliases.get(id) ?? '');
|
|
554
|
+
}
|
|
555
|
+
/** `id` was replaced by the same player's newer token: late frames that name it are ignored. */
|
|
556
|
+
retire(id) {
|
|
557
|
+
this.replaced.set(id, this.now());
|
|
558
|
+
}
|
|
559
|
+
/**
|
|
560
|
+
* Move a player's row to the id of their refreshed token. A carried player stays carried:
|
|
561
|
+
* the carry under the old id stands, and sends keep naming it, until the `FLEET_CARRY` for
|
|
562
|
+
* the new id goes out. A row whose own carry was never confirmed simply takes the new token.
|
|
563
|
+
*/
|
|
564
|
+
supersede(row, id, token) {
|
|
565
|
+
const from = row.gameTokenId;
|
|
566
|
+
this.table.delete(from);
|
|
567
|
+
if (!row.carried) {
|
|
568
|
+
if (row.previous) {
|
|
569
|
+
this.aliases.delete(row.previous.gameTokenId);
|
|
570
|
+
this.retire(row.previous.gameTokenId);
|
|
571
|
+
row.previous = null;
|
|
572
|
+
}
|
|
573
|
+
this.retire(from);
|
|
574
|
+
if (this.ctx)
|
|
575
|
+
row.ctx = carriedPlayerContext(this.ctx, id);
|
|
576
|
+
}
|
|
577
|
+
else if (row.previous) {
|
|
578
|
+
// A newer token while the last replacement still waited: the id that waited is dropped.
|
|
579
|
+
this.retire(from);
|
|
580
|
+
row.ctx = row.previous.ctx;
|
|
581
|
+
}
|
|
582
|
+
else {
|
|
583
|
+
row.previous = { gameTokenId: from, token: row.token, ctx: row.ctx, ended: null };
|
|
584
|
+
}
|
|
585
|
+
if (row.previous)
|
|
586
|
+
this.aliases.set(row.previous.gameTokenId, id);
|
|
587
|
+
row.gameTokenId = id;
|
|
588
|
+
row.token = token;
|
|
589
|
+
this.table.set(id, row);
|
|
590
|
+
// The carry with the new token starts over; whoever waited on the old one hears its answer.
|
|
591
|
+
row.attempt = {
|
|
592
|
+
nextSendAt: this.now(),
|
|
593
|
+
deadline: 0,
|
|
594
|
+
order: this.attemptOrder++,
|
|
595
|
+
resolvers: row.attempt?.resolvers ?? [],
|
|
596
|
+
noLiveToken: 'none',
|
|
597
|
+
};
|
|
598
|
+
return row;
|
|
599
|
+
}
|
|
600
|
+
/**
|
|
601
|
+
* The player left the game: sends `FLEET_RELEASE` and takes them out of the table at once.
|
|
602
|
+
* Their actors leave as when a player's own session ends, about 5 seconds after their last
|
|
603
|
+
* message. A carry still waiting for the player ends `'released'`. The message has no
|
|
604
|
+
* answer; one that is lost leaves the carry on the server until the player is carried
|
|
605
|
+
* elsewhere, their sign-in ends, or they idle out. Stop sending for a player before you hand
|
|
606
|
+
* them to another server: the other session's carry is what moves them, and no release is
|
|
607
|
+
* needed for it.
|
|
608
|
+
*/
|
|
609
|
+
async release(playerGameTokenId) {
|
|
610
|
+
const id = idString(playerGameTokenId, 'the player gameTokenId');
|
|
611
|
+
// An id this session replaced with the player's newer one names nothing here any more,
|
|
612
|
+
// and a release under it could end the carry that replaced it.
|
|
613
|
+
if (this.replaced.has(id) && !this.table.has(id))
|
|
614
|
+
return;
|
|
615
|
+
const row = this.rowOf(id);
|
|
616
|
+
const ids = [id];
|
|
617
|
+
if (row) {
|
|
618
|
+
ids.length = 0;
|
|
619
|
+
ids.push(row.gameTokenId);
|
|
620
|
+
this.table.delete(row.gameTokenId);
|
|
621
|
+
if (row.previous) {
|
|
622
|
+
// A replacement was waiting: the player is let go under both of their ids.
|
|
623
|
+
ids.push(row.previous.gameTokenId);
|
|
624
|
+
this.aliases.delete(row.previous.gameTokenId);
|
|
625
|
+
row.previous = null;
|
|
626
|
+
}
|
|
627
|
+
row.carried = false;
|
|
628
|
+
this.settle(row, { status: 'released', wireStatus: null, userId: null }, false);
|
|
629
|
+
}
|
|
630
|
+
if (!this.socket || this.currentStatus === 'released')
|
|
631
|
+
return;
|
|
632
|
+
for (const each of ids)
|
|
633
|
+
await this.sendRelease(each);
|
|
634
|
+
}
|
|
635
|
+
/**
|
|
636
|
+
* True when the server confirmed a carry of this player and nothing ended it. While a carry
|
|
637
|
+
* with a refreshed token waits, both of the player's ids answer true.
|
|
638
|
+
*/
|
|
639
|
+
carries(playerGameTokenId) {
|
|
640
|
+
return this.rowOf(idString(playerGameTokenId, 'the player gameTokenId'))?.carried === true;
|
|
641
|
+
}
|
|
642
|
+
/** Every row of the table: carried players and carries still waiting. */
|
|
643
|
+
players() {
|
|
644
|
+
return [...this.table.values()].map((p) => ({
|
|
645
|
+
gameTokenId: p.gameTokenId,
|
|
646
|
+
userId: p.userId,
|
|
647
|
+
carried: p.carried,
|
|
648
|
+
pending: p.attempt !== null,
|
|
649
|
+
}));
|
|
650
|
+
}
|
|
651
|
+
/**
|
|
652
|
+
* The most rows the table holds, carried players and carries waiting together: `maxPlayers`
|
|
653
|
+
* (1,024 when the grant named none) and {@link FLEET_TABLE_MARGIN} more. A `carry` for a
|
|
654
|
+
* new player past it ends `'tableFull'`.
|
|
655
|
+
*/
|
|
656
|
+
get tableLimit() {
|
|
657
|
+
const max = this.grant.maxPlayers;
|
|
658
|
+
const players = typeof max === 'number' && max > 0 ? Math.min(max, FLEET_MAX_PLAYERS_CEILING) : FLEET_MAX_PLAYERS_CEILING;
|
|
659
|
+
return players + FLEET_TABLE_MARGIN;
|
|
660
|
+
}
|
|
661
|
+
/** How many players the server confirmed and nothing ended. */
|
|
662
|
+
get carriedCount() {
|
|
663
|
+
let n = 0;
|
|
664
|
+
for (const p of this.table.values())
|
|
665
|
+
if (p.carried)
|
|
666
|
+
n += 1;
|
|
667
|
+
return n;
|
|
668
|
+
}
|
|
669
|
+
// ----- Sends for a carried player ------------------------------------------------------
|
|
670
|
+
//
|
|
671
|
+
// The realtime client's sends with the carried player first. Each resolves with the
|
|
672
|
+
// sequence number it was sent under, and rejects FleetNotCarriedError, with nothing sent,
|
|
673
|
+
// for a game token id this session does not carry now.
|
|
674
|
+
/**
|
|
675
|
+
* An actor update for one of the player's actors. The session then keeps that actor
|
|
676
|
+
* present with heartbeats while it sends nothing (`actorHeartbeatMs`), until
|
|
677
|
+
* {@link forgetActor} or the carry ends.
|
|
678
|
+
*/
|
|
679
|
+
async sendActorUpdate(player, input) {
|
|
680
|
+
const seq = await this.sendFor(player, (ctx, sequenceNumber) => serializeActorUpdate(ctx, { ...input, appId: this.appId, sequenceNumber }));
|
|
681
|
+
this.touchActor(player, input.uuid, input.chunk);
|
|
682
|
+
return seq;
|
|
683
|
+
}
|
|
684
|
+
/** A voxel edit. The player's grid permissions decide it. */
|
|
685
|
+
sendVoxelUpdate(player, input) {
|
|
686
|
+
return this.sendFor(player, (ctx, sequenceNumber) => {
|
|
687
|
+
assertVoxelEdit(input);
|
|
688
|
+
return serializeVoxelUpdate(ctx, { ...input, appId: this.appId, sequenceNumber });
|
|
689
|
+
});
|
|
690
|
+
}
|
|
691
|
+
/** A client event (`eventType` and a base64 `state`). */
|
|
692
|
+
sendClientEvent(player, input) {
|
|
693
|
+
return this.sendFor(player, (ctx, sequenceNumber) => serializeClientEvent(ctx, { ...input, appId: this.appId, sequenceNumber }));
|
|
694
|
+
}
|
|
695
|
+
/** Spatial text. The player's tier needs `use_text_chat`. */
|
|
696
|
+
sendTextPacket(player, input) {
|
|
697
|
+
return this.sendFor(player, (ctx, sequenceNumber) => serializeTextPacket(ctx, { ...input, appId: this.appId, sequenceNumber }));
|
|
698
|
+
}
|
|
699
|
+
/** Spatial voice (base64 `audioData`). It does not keep the player from idling out. */
|
|
700
|
+
sendAudioPacket(player, input) {
|
|
701
|
+
return this.sendFor(player, (ctx, sequenceNumber) => serializeAudioPacket(ctx, { ...input, appId: this.appId, sequenceNumber }));
|
|
702
|
+
}
|
|
703
|
+
/** One webcam video fragment (base64 `videoData`, from `fragmentFrame`). */
|
|
704
|
+
sendVideoPacket(player, input) {
|
|
705
|
+
return this.sendFor(player, (ctx, sequenceNumber) => serializeVideoPacket(ctx, { ...input, appId: this.appId, sequenceNumber }));
|
|
706
|
+
}
|
|
707
|
+
/** An app-defined spatial message (base64 `payload`, at most 1,123 bytes). */
|
|
708
|
+
sendGenericSpatial(player, input) {
|
|
709
|
+
return this.sendFor(player, (ctx, sequenceNumber) => serializeGenericSpatial(ctx, { ...input, appId: this.appId, sequenceNumber }));
|
|
710
|
+
}
|
|
711
|
+
/** A direct message to one actor, named by its chunk and uuid. */
|
|
712
|
+
sendSingleActorMessage(player, input) {
|
|
713
|
+
return this.sendFor(player, (ctx, sequenceNumber) => serializeSingleActorMessage(ctx, { ...input, appId: this.appId, sequenceNumber }));
|
|
714
|
+
}
|
|
715
|
+
/** A channel message. */
|
|
716
|
+
sendChannelMessage(player, input) {
|
|
717
|
+
return this.sendFor(player, (ctx, sequenceNumber) => serializeChannelMessage(ctx, { ...input, sequenceNumber }));
|
|
718
|
+
}
|
|
719
|
+
/** Channel audio. */
|
|
720
|
+
sendChannelAudio(player, input) {
|
|
721
|
+
return this.sendFor(player, (ctx, sequenceNumber) => serializeChannelAudio(ctx, { ...input, sequenceNumber }));
|
|
722
|
+
}
|
|
723
|
+
/** A channel message only members within `maxDistance` chunks of `chunk` receive. */
|
|
724
|
+
sendRangedChannelMessage(player, input) {
|
|
725
|
+
return this.sendFor(player, (ctx, sequenceNumber) => serializeRangedChannelMessage(ctx, { ...input, appId: this.appId, sequenceNumber }));
|
|
726
|
+
}
|
|
727
|
+
/**
|
|
728
|
+
* A heartbeat for one of the player's actors, under the player's id: it keeps the actor
|
|
729
|
+
* present without sending its state. The session sends these itself for actors it knows
|
|
730
|
+
* from {@link sendActorUpdate}; call this for an actor it does not know, or with
|
|
731
|
+
* `actorHeartbeatMs: 0`. A heartbeat is not gameplay input: it does not hold off the app's
|
|
732
|
+
* idle timeout.
|
|
733
|
+
*/
|
|
734
|
+
async sendHeartbeat(player, actor) {
|
|
735
|
+
const seq = await this.sendFor(player, (ctx, sequenceNumber) => serializeActorHeartbeat(ctx, { appId: this.appId, chunk: actor.chunk, uuid: actor.uuid, sequenceNumber }));
|
|
736
|
+
this.touchActor(player, actor.uuid, actor.chunk);
|
|
737
|
+
return seq;
|
|
738
|
+
}
|
|
739
|
+
/** Stop keeping one of the player's actors present. It leaves about 5 seconds later. */
|
|
740
|
+
forgetActor(player, uuid) {
|
|
741
|
+
this.rowOf(idString(player, 'the player gameTokenId'))?.actors.delete(uuid);
|
|
742
|
+
}
|
|
743
|
+
/**
|
|
744
|
+
* The speakers whose spatial voice and video a carried player receives
|
|
745
|
+
* (`CLIENT_MEDIA_SPEAKERS`, under the player's id). Each carried player has their own
|
|
746
|
+
* lists. A changed kind is sent at once, and every list again with each periodic
|
|
747
|
+
* capabilities advertisement and after the player is carried again.
|
|
748
|
+
* @throws {CrowdyRealtimeError} `SPEAKER_LIST_TOO_LONG` over 32 names; {@link FleetNotCarriedError}.
|
|
749
|
+
*/
|
|
750
|
+
async setSpeakers(player, change) {
|
|
751
|
+
const id = idString(player, 'the player gameTokenId');
|
|
752
|
+
for (const [kind, list] of [
|
|
753
|
+
['voice', change.voice],
|
|
754
|
+
['video', change.video],
|
|
755
|
+
]) {
|
|
756
|
+
if (list && list.length > MAX_MEDIA_SPEAKERS) {
|
|
757
|
+
throw new CrowdyRealtimeError(`A ${kind} speaker list names at most ${MAX_MEDIA_SPEAKERS} actors (got ${list.length})`, { code: 'SPEAKER_LIST_TOO_LONG' });
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
const row = this.rowOf(id);
|
|
761
|
+
if (!row?.carried)
|
|
762
|
+
throw new FleetNotCarriedError(id);
|
|
763
|
+
// One kind a message: 32 names of each would not fit one datagram.
|
|
764
|
+
if (change.voice !== undefined) {
|
|
765
|
+
row.voice = change.voice ? [...change.voice] : null;
|
|
766
|
+
await this.sendSpeakers(row, speakerChange(row.voice), speakerChange(undefined));
|
|
767
|
+
}
|
|
768
|
+
if (change.video !== undefined) {
|
|
769
|
+
row.video = change.video ? [...change.video] : null;
|
|
770
|
+
await this.sendSpeakers(row, speakerChange(undefined), speakerChange(row.video));
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
async sendSpeakers(row, voice, video) {
|
|
774
|
+
if (!row.carried || !this.socket)
|
|
775
|
+
return;
|
|
776
|
+
await this.sendFor(row.gameTokenId, (ctx, sequenceNumber) => serializeClientMediaSpeakers(ctx, this.appId, voice, video, sequenceNumber));
|
|
777
|
+
}
|
|
778
|
+
async resendSpeakers(row) {
|
|
779
|
+
if (row.voice !== undefined && row.voice !== null) {
|
|
780
|
+
await this.sendSpeakers(row, speakerChange(row.voice), speakerChange(undefined));
|
|
781
|
+
}
|
|
782
|
+
if (row.video !== undefined && row.video !== null) {
|
|
783
|
+
await this.sendSpeakers(row, speakerChange(undefined), speakerChange(row.video));
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
touchActor(player, uuid, chunk) {
|
|
787
|
+
const row = this.rowOf(idString(player, 'the player gameTokenId'));
|
|
788
|
+
if (!row?.carried || !uuid)
|
|
789
|
+
return;
|
|
790
|
+
row.actors.set(uuid, { chunk: { x: String(chunk.x), y: String(chunk.y), z: String(chunk.z) }, lastSentAt: this.now() });
|
|
791
|
+
}
|
|
792
|
+
// ----- The wire ---------------------------------------------------------------------------
|
|
793
|
+
sequence() {
|
|
794
|
+
const seq = this.nextSequence;
|
|
795
|
+
this.nextSequence = (this.nextSequence + 1) & 0xff;
|
|
796
|
+
return seq;
|
|
797
|
+
}
|
|
798
|
+
transmit(generation, datagram) {
|
|
799
|
+
const socket = this.socket;
|
|
800
|
+
if (!socket || generation !== this.generation)
|
|
801
|
+
return false;
|
|
802
|
+
socket.send(datagram);
|
|
803
|
+
this.counters.datagramsSent += 1;
|
|
804
|
+
this.counters.bytesSent += datagram.length;
|
|
805
|
+
this.counters.sentByType[datagram[0]] = (this.counters.sentByType[datagram[0]] ?? 0) + 1;
|
|
806
|
+
return true;
|
|
807
|
+
}
|
|
808
|
+
/** A message for a carried player: the player's id in the tail, signed with the fleet token. */
|
|
809
|
+
async sendFor(player, build) {
|
|
810
|
+
const id = idString(player, 'the player gameTokenId');
|
|
811
|
+
const row = this.rowOf(id);
|
|
812
|
+
if (!row?.carried)
|
|
813
|
+
throw new FleetNotCarriedError(id);
|
|
814
|
+
if (!this.socket || this.currentStatus === 'released') {
|
|
815
|
+
throw new CrowdyRealtimeError('the fleet session is not connected', { code: 'FLEET_NOT_CONNECTED', retryable: true });
|
|
816
|
+
}
|
|
817
|
+
const generation = this.generation;
|
|
818
|
+
const seq = this.sequence();
|
|
819
|
+
let ctx = row.ctx;
|
|
820
|
+
let datagram = await build(ctx, seq);
|
|
821
|
+
// The id the player's sends name can change while a message is being signed (a carry with
|
|
822
|
+
// a refreshed token went out, or was refused): no message leaves under the id of before.
|
|
823
|
+
while (row.ctx !== ctx) {
|
|
824
|
+
ctx = row.ctx;
|
|
825
|
+
datagram = await build(ctx, seq);
|
|
826
|
+
}
|
|
827
|
+
// The carry may have ended while the message was being signed.
|
|
828
|
+
if (!row.carried || this.table.get(row.gameTokenId) !== row)
|
|
829
|
+
throw new FleetNotCarriedError(id);
|
|
830
|
+
if (!this.transmit(generation, datagram)) {
|
|
831
|
+
throw new CrowdyRealtimeError('the fleet session is not connected', { code: 'FLEET_NOT_CONNECTED', retryable: true });
|
|
832
|
+
}
|
|
833
|
+
return seq;
|
|
834
|
+
}
|
|
835
|
+
/**
|
|
836
|
+
* A message of the session's own, under its own game token id. Only four kinds exist: the
|
|
837
|
+
* realtime servers answer any other `UNAUTHORIZED`.
|
|
838
|
+
*/
|
|
839
|
+
async sendOwn(type, build,
|
|
840
|
+
/** Runs in the same turn as the send, just before it, when the message does go out. */
|
|
841
|
+
beforeTransmit) {
|
|
842
|
+
if (!OWN_TYPES.has(type)) {
|
|
843
|
+
throw new CrowdyError({ message: `a fleet session sends no message of type ${type} under its own id` });
|
|
844
|
+
}
|
|
845
|
+
const ctx = this.ctx;
|
|
846
|
+
if (!ctx || !this.socket)
|
|
847
|
+
return false;
|
|
848
|
+
// A connection's first datagram is its capabilities: nothing else goes out before them.
|
|
849
|
+
if (this.binding && type !== WireMessageType.CLIENT_CAPABILITIES)
|
|
850
|
+
return false;
|
|
851
|
+
const generation = this.generation;
|
|
852
|
+
const datagram = await build(ctx, this.sequence());
|
|
853
|
+
if (datagram[0] !== type) {
|
|
854
|
+
throw new CrowdyError({ message: `built a message of type ${datagram[0]} where ${type} was meant` });
|
|
855
|
+
}
|
|
856
|
+
if (!this.socket || generation !== this.generation)
|
|
857
|
+
return false;
|
|
858
|
+
beforeTransmit?.();
|
|
859
|
+
return this.transmit(generation, datagram);
|
|
860
|
+
}
|
|
861
|
+
sendCapabilities() {
|
|
862
|
+
return this.sendOwn(WireMessageType.CLIENT_CAPABILITIES, (ctx, seq) => serializeClientCapabilities(ctx, this.appId, this.capabilityFlags, seq, this.controlNonce ?? undefined));
|
|
863
|
+
}
|
|
864
|
+
sendRelease(id) {
|
|
865
|
+
return this.sendOwn(WireMessageType.FLEET_RELEASE, (ctx, seq) => serializeFleetRelease(ctx, { appId: this.appId, playerGameTokenId: id, sequenceNumber: seq }));
|
|
866
|
+
}
|
|
867
|
+
// ----- Timed work ---------------------------------------------------------------------------
|
|
868
|
+
/**
|
|
869
|
+
* Do the session's timed work once: the capabilities and keepalive that are due, the
|
|
870
|
+
* `FLEET_CARRY` sends and retries that are due and that the pace allows, the carries that
|
|
871
|
+
* timed out, and the heartbeats of carried players' actors. The session calls this itself
|
|
872
|
+
* every `tickIntervalMs`; call it yourself with `tickIntervalMs: 0`.
|
|
873
|
+
*/
|
|
874
|
+
async tick() {
|
|
875
|
+
if (this.ticking || this.binding || !this.socket)
|
|
876
|
+
return;
|
|
877
|
+
if (this.currentStatus === 'closed' || this.currentStatus === 'released')
|
|
878
|
+
return;
|
|
879
|
+
this.ticking = true;
|
|
880
|
+
try {
|
|
881
|
+
const now = this.now();
|
|
882
|
+
if (this.silenceTimeoutMs > 0 && now - this.lastHeardAt >= this.silenceTimeoutMs) {
|
|
883
|
+
// Nothing verified for three capabilities intervals: the server is gone, or never took
|
|
884
|
+
// the session. It may hold no carry by the time it is heard again.
|
|
885
|
+
this.orderMove(true);
|
|
886
|
+
}
|
|
887
|
+
if (now >= this.nextCapabilitiesAt) {
|
|
888
|
+
await this.sendCapabilities();
|
|
889
|
+
this.nextCapabilitiesAt = now + (this.answered ? this.capabilitiesIntervalMs : this.bindRetryMs);
|
|
890
|
+
// The server keeps a player's speaker lists no longer than it keeps the capabilities.
|
|
891
|
+
if (this.answered)
|
|
892
|
+
for (const row of [...this.table.values()])
|
|
893
|
+
await this.resendSpeakers(row);
|
|
894
|
+
}
|
|
895
|
+
if (now - this.lastKeepAliveAt >= this.keepAliveIntervalMs) {
|
|
896
|
+
this.lastKeepAliveAt = now;
|
|
897
|
+
await this.sendOwn(WireMessageType.CLIENT_ACTOR_HEARTBEAT, (ctx, seq) => serializeActorHeartbeat(ctx, { appId: this.appId, sequenceNumber: seq }));
|
|
898
|
+
}
|
|
899
|
+
await this.driveCarries(now);
|
|
900
|
+
if (this.actorHeartbeatMs > 0)
|
|
901
|
+
await this.heartbeatActors(now);
|
|
902
|
+
// A replaced id's late frames arrive within seconds: a minute on, it can be forgotten.
|
|
903
|
+
for (const [id, at] of this.replaced)
|
|
904
|
+
if (now - at > 60000)
|
|
905
|
+
this.replaced.delete(id);
|
|
906
|
+
}
|
|
907
|
+
catch (error) {
|
|
908
|
+
this.report(error);
|
|
909
|
+
}
|
|
910
|
+
finally {
|
|
911
|
+
this.ticking = false;
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
async driveCarries(now) {
|
|
915
|
+
const firsts = [];
|
|
916
|
+
const retries = [];
|
|
917
|
+
for (const row of [...this.table.values()]) {
|
|
918
|
+
const attempt = row.attempt;
|
|
919
|
+
if (!attempt)
|
|
920
|
+
continue;
|
|
921
|
+
if (attempt.deadline !== 0 && now >= attempt.deadline) {
|
|
922
|
+
this.table.delete(row.gameTokenId);
|
|
923
|
+
const ids = [row.gameTokenId];
|
|
924
|
+
if (row.previous) {
|
|
925
|
+
// Nothing says which of the player's two carries the server holds: neither stands.
|
|
926
|
+
ids.push(row.previous.gameTokenId);
|
|
927
|
+
this.aliases.delete(row.previous.gameTokenId);
|
|
928
|
+
row.previous = null;
|
|
929
|
+
}
|
|
930
|
+
row.carried = false;
|
|
931
|
+
this.settle(row, { status: 'timedOut', wireStatus: null, userId: null }, true);
|
|
932
|
+
// The server may hold a carry whose answers were lost: both sides now agree it ended.
|
|
933
|
+
for (const id of ids)
|
|
934
|
+
await this.sendRelease(id);
|
|
935
|
+
continue;
|
|
936
|
+
}
|
|
937
|
+
if (attempt.nextSendAt <= now)
|
|
938
|
+
(attempt.deadline === 0 ? firsts : retries).push(row);
|
|
939
|
+
}
|
|
940
|
+
if (firsts.length === 0 && retries.length === 0)
|
|
941
|
+
return;
|
|
942
|
+
const byTurn = (a, b) => {
|
|
943
|
+
const x = a.attempt;
|
|
944
|
+
const y = b.attempt;
|
|
945
|
+
return x.nextSendAt - y.nextSendAt || x.order - y.order;
|
|
946
|
+
};
|
|
947
|
+
firsts.sort(byTurn);
|
|
948
|
+
retries.sort(byTurn);
|
|
949
|
+
this.carrySends = this.carrySends.filter((sent) => sent.at >= now - 1000);
|
|
950
|
+
// Retries take at most half of a second's carries while first sends wait, so one lost
|
|
951
|
+
// answer is asked for again before its carry times out, and a server that answers
|
|
952
|
+
// nothing does not keep new players from being asked for at all.
|
|
953
|
+
const retryShare = Math.max(1, Math.floor(this.maxCarriesPerSecond / 2));
|
|
954
|
+
let retriesSent = this.carrySends.filter((sent) => sent.retry).length;
|
|
955
|
+
while (this.carrySends.length < this.maxCarriesPerSecond) {
|
|
956
|
+
const retry = retries.length > 0 && (retriesSent < retryShare || firsts.length === 0);
|
|
957
|
+
const row = retry ? retries.shift() : firsts.shift();
|
|
958
|
+
if (!row)
|
|
959
|
+
break;
|
|
960
|
+
const attempt = row.attempt;
|
|
961
|
+
if (!attempt || this.table.get(row.gameTokenId) !== row)
|
|
962
|
+
continue;
|
|
963
|
+
// A new time for every send, later than the last one this player's carry was made for.
|
|
964
|
+
const epoch = Math.max(now, row.lastCarryEpoch + 1);
|
|
965
|
+
row.lastCarryEpoch = epoch;
|
|
966
|
+
const carriedId = row.gameTokenId;
|
|
967
|
+
const sent = await this.sendOwn(WireMessageType.FLEET_CARRY, (ctx, seq) => serializeFleetCarry(ctx, {
|
|
968
|
+
appId: this.appId,
|
|
969
|
+
playerGameTokenId: carriedId,
|
|
970
|
+
playerToken: row.token,
|
|
971
|
+
epochMillis: epoch,
|
|
972
|
+
sequenceNumber: seq,
|
|
973
|
+
}), () => {
|
|
974
|
+
if (attempt.noLiveToken === 'waiting')
|
|
975
|
+
attempt.noLiveToken = 'retried';
|
|
976
|
+
// A refreshed token's carry: from the moment it goes out, the player's sends name
|
|
977
|
+
// the new id. The realtime server holds them behind the carry.
|
|
978
|
+
if (row.previous && row.gameTokenId === carriedId && row.ctx === row.previous.ctx && this.ctx) {
|
|
979
|
+
row.ctx = carriedPlayerContext(this.ctx, carriedId);
|
|
980
|
+
}
|
|
981
|
+
});
|
|
982
|
+
if (!sent)
|
|
983
|
+
break;
|
|
984
|
+
this.carrySends.push({ at: now, retry });
|
|
985
|
+
if (retry)
|
|
986
|
+
retriesSent += 1;
|
|
987
|
+
attempt.nextSendAt = now + this.carryRetryMs;
|
|
988
|
+
if (attempt.deadline === 0)
|
|
989
|
+
attempt.deadline = now + this.carryTimeoutMs;
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
async heartbeatActors(now) {
|
|
993
|
+
for (const row of [...this.table.values()]) {
|
|
994
|
+
if (!row.carried)
|
|
995
|
+
continue;
|
|
996
|
+
for (const [uuid, actor] of [...row.actors]) {
|
|
997
|
+
if (now - actor.lastSentAt < this.actorHeartbeatMs)
|
|
998
|
+
continue;
|
|
999
|
+
actor.lastSentAt = now;
|
|
1000
|
+
try {
|
|
1001
|
+
await this.sendFor(row.gameTokenId, (ctx, sequenceNumber) => serializeActorHeartbeat(ctx, { appId: this.appId, chunk: actor.chunk, uuid, sequenceNumber }));
|
|
1002
|
+
}
|
|
1003
|
+
catch (error) {
|
|
1004
|
+
if (!(error instanceof FleetNotCarriedError))
|
|
1005
|
+
throw error;
|
|
1006
|
+
break;
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
// ----- Receiving ------------------------------------------------------------------------------
|
|
1012
|
+
onDatagram(generation, datagram) {
|
|
1013
|
+
if (generation !== this.generation)
|
|
1014
|
+
return;
|
|
1015
|
+
this.counters.datagramsReceived += 1;
|
|
1016
|
+
this.counters.bytesReceived += datagram.length;
|
|
1017
|
+
if (datagram.length > FLEET_MAX_DATAGRAM_BYTES) {
|
|
1018
|
+
this.counters.oversized += 1;
|
|
1019
|
+
return;
|
|
1020
|
+
}
|
|
1021
|
+
// A copy: the socket may reuse its buffer before the datagram's turn comes.
|
|
1022
|
+
const bytes = new Uint8Array(datagram);
|
|
1023
|
+
this.inbound = this.inbound
|
|
1024
|
+
.then(() => this.read(generation, bytes))
|
|
1025
|
+
.catch((error) => this.report(error));
|
|
1026
|
+
}
|
|
1027
|
+
/**
|
|
1028
|
+
* Resolves once every datagram received so far has been verified and its handlers have
|
|
1029
|
+
* run: what to wait for before `close()` when nothing received may be lost.
|
|
1030
|
+
*/
|
|
1031
|
+
settled() {
|
|
1032
|
+
return this.inbound;
|
|
1033
|
+
}
|
|
1034
|
+
async read(generation, datagram) {
|
|
1035
|
+
const ctx = this.ctx;
|
|
1036
|
+
if (!ctx || generation !== this.generation)
|
|
1037
|
+
return;
|
|
1038
|
+
const parsed = await parseFleetDatagram(ctx, datagram, { controlNonce: this.controlNonce });
|
|
1039
|
+
if (generation !== this.generation)
|
|
1040
|
+
return;
|
|
1041
|
+
this.counters.hmacFailures += parsed.hmacFailures;
|
|
1042
|
+
this.counters.malformed += parsed.malformed;
|
|
1043
|
+
this.counters.unsigned += parsed.unsigned;
|
|
1044
|
+
this.counters.staleControl += parsed.staleControl;
|
|
1045
|
+
for (const message of parsed.messages) {
|
|
1046
|
+
if (generation !== this.generation)
|
|
1047
|
+
return;
|
|
1048
|
+
if (!(message.kind === 'notification' && !message.verified)) {
|
|
1049
|
+
this.lastHeardAt = this.now();
|
|
1050
|
+
if (!this.answered) {
|
|
1051
|
+
this.answered = true;
|
|
1052
|
+
this.nextCapabilitiesAt = this.lastHeardAt + this.capabilitiesIntervalMs;
|
|
1053
|
+
this.setStatus('connected');
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
await this.handle(message);
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
async handle(message) {
|
|
1060
|
+
switch (message.kind) {
|
|
1061
|
+
case 'controlBoundAck':
|
|
1062
|
+
this.boundAcked = true;
|
|
1063
|
+
this.counters.boundControlAcks += 1;
|
|
1064
|
+
return;
|
|
1065
|
+
case 'reconnect':
|
|
1066
|
+
if (!message.bound && this.boundAcked) {
|
|
1067
|
+
// This server sends only the bound form: one without the nonce was captured earlier.
|
|
1068
|
+
this.counters.staleControl += 1;
|
|
1069
|
+
return;
|
|
1070
|
+
}
|
|
1071
|
+
this.orderMove(false);
|
|
1072
|
+
return;
|
|
1073
|
+
case 'sessionReleased':
|
|
1074
|
+
if (!message.bound && this.boundAcked) {
|
|
1075
|
+
this.counters.staleControl += 1;
|
|
1076
|
+
return;
|
|
1077
|
+
}
|
|
1078
|
+
this.onSessionReleased(message.reason);
|
|
1079
|
+
return;
|
|
1080
|
+
case 'carryResult':
|
|
1081
|
+
await this.onCarryResult(message.playerGameTokenId, message.userId, message.status);
|
|
1082
|
+
return;
|
|
1083
|
+
case 'released':
|
|
1084
|
+
this.onReleased(message.playerGameTokenId, message.reason);
|
|
1085
|
+
return;
|
|
1086
|
+
case 'delivery':
|
|
1087
|
+
this.dispatch(message.notification, message.players);
|
|
1088
|
+
return;
|
|
1089
|
+
case 'notification':
|
|
1090
|
+
if (message.notification.__typename === 'GenericErrorResponse') {
|
|
1091
|
+
// A refusal of one send changes no state here, whatever its code. TOKEN_EXPIRED is
|
|
1092
|
+
// about the token of the player the send named, and FLEET_RELEASED follows it; the
|
|
1093
|
+
// signed word that the session's own token expired is COMMAND_SESSION_RELEASED.
|
|
1094
|
+
this.dispatchError(message.notification, message.verified);
|
|
1095
|
+
return;
|
|
1096
|
+
}
|
|
1097
|
+
if (!message.verified) {
|
|
1098
|
+
// The codec returns state only verified. Should that ever change, a session still
|
|
1099
|
+
// gives no handler a notification the realtime server did not sign.
|
|
1100
|
+
this.counters.unsigned += 1;
|
|
1101
|
+
return;
|
|
1102
|
+
}
|
|
1103
|
+
this.dispatch(message.notification, null);
|
|
1104
|
+
return;
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
/**
|
|
1108
|
+
* The session needs a refresh before anything else: the server asked it to move, or went
|
|
1109
|
+
* quiet. `carriesLost` when the server may hold no carry.
|
|
1110
|
+
*/
|
|
1111
|
+
orderMove(carriesLost) {
|
|
1112
|
+
if (carriesLost)
|
|
1113
|
+
this.carriesLost = true;
|
|
1114
|
+
if (this.moveWasOrdered)
|
|
1115
|
+
return;
|
|
1116
|
+
this.moveWasOrdered = true;
|
|
1117
|
+
this.call(() => this.handlers.moveOrdered?.());
|
|
1118
|
+
}
|
|
1119
|
+
onSessionReleased(reason) {
|
|
1120
|
+
// The server answers this session no more, and its carries ended unannounced.
|
|
1121
|
+
this.carriesLost = true;
|
|
1122
|
+
this.moveWasOrdered = true;
|
|
1123
|
+
for (const row of this.table.values()) {
|
|
1124
|
+
row.carried = false;
|
|
1125
|
+
if (row.attempt) {
|
|
1126
|
+
row.attempt.nextSendAt = Number.POSITIVE_INFINITY;
|
|
1127
|
+
row.attempt.deadline = 0;
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
this.setStatus('released');
|
|
1131
|
+
this.call(() => this.handlers.sessionReleased?.(reason));
|
|
1132
|
+
}
|
|
1133
|
+
async onCarryResult(id, userId, status) {
|
|
1134
|
+
if (this.aliases.has(id) || (this.replaced.has(id) && !this.table.has(id))) {
|
|
1135
|
+
// A late answer about a token the player's newer one replaced, or is replacing.
|
|
1136
|
+
this.counters.replacedIdFrames += 1;
|
|
1137
|
+
return;
|
|
1138
|
+
}
|
|
1139
|
+
const row = this.table.get(id);
|
|
1140
|
+
if (!row) {
|
|
1141
|
+
this.counters.unmatchedCarryResults += 1;
|
|
1142
|
+
// The server carries a player this session let go meanwhile: say so again.
|
|
1143
|
+
if (status === FleetCarryStatus.CARRIED && this.socket)
|
|
1144
|
+
await this.sendRelease(id);
|
|
1145
|
+
return;
|
|
1146
|
+
}
|
|
1147
|
+
const attempt = row.attempt;
|
|
1148
|
+
if (!attempt) {
|
|
1149
|
+
// An answer to a carry sent twice: the first one settled it.
|
|
1150
|
+
if (status !== FleetCarryStatus.CARRIED || !row.carried)
|
|
1151
|
+
this.counters.unmatchedCarryResults += 1;
|
|
1152
|
+
return;
|
|
1153
|
+
}
|
|
1154
|
+
if (status === FleetCarryStatus.NO_LIVE_TOKEN && attempt.noLiveToken !== 'retried') {
|
|
1155
|
+
// A token minted or refreshed a moment ago may not have reached this server yet: ask
|
|
1156
|
+
// once more, with a new time and proof. Answers to carries sent before that one wait.
|
|
1157
|
+
if (attempt.noLiveToken === 'none') {
|
|
1158
|
+
attempt.noLiveToken = 'waiting';
|
|
1159
|
+
attempt.nextSendAt = this.now() + this.carryRetryMs;
|
|
1160
|
+
this.counters.noLiveTokenRetries += 1;
|
|
1161
|
+
}
|
|
1162
|
+
return;
|
|
1163
|
+
}
|
|
1164
|
+
if (status !== FleetCarryStatus.CARRIED) {
|
|
1165
|
+
const refusal = { status: CARRY_OUTCOMES[status] ?? 'refused', wireStatus: status, userId: null };
|
|
1166
|
+
const previous = row.previous;
|
|
1167
|
+
if (previous) {
|
|
1168
|
+
// The refreshed token's carry was refused: the carry under the old id stands.
|
|
1169
|
+
this.table.delete(id);
|
|
1170
|
+
this.aliases.delete(previous.gameTokenId);
|
|
1171
|
+
this.retire(id);
|
|
1172
|
+
this.settle(row, refusal, true);
|
|
1173
|
+
row.gameTokenId = previous.gameTokenId;
|
|
1174
|
+
row.token = previous.token;
|
|
1175
|
+
row.ctx = previous.ctx;
|
|
1176
|
+
row.previous = null;
|
|
1177
|
+
if (previous.ended === null && row.carried) {
|
|
1178
|
+
this.table.set(row.gameTokenId, row);
|
|
1179
|
+
return;
|
|
1180
|
+
}
|
|
1181
|
+
// Unless the server said meanwhile that it ended: then the player is carried no more.
|
|
1182
|
+
if (row.carried) {
|
|
1183
|
+
row.carried = false;
|
|
1184
|
+
const reason = previous.ended ?? 0;
|
|
1185
|
+
this.call(() => this.handlers.released?.({ playerGameTokenId: row.gameTokenId, userId: row.userId, reason }));
|
|
1186
|
+
}
|
|
1187
|
+
return;
|
|
1188
|
+
}
|
|
1189
|
+
const wasCarried = row.carried;
|
|
1190
|
+
row.carried = false;
|
|
1191
|
+
this.table.delete(id);
|
|
1192
|
+
this.settle(row, refusal, true);
|
|
1193
|
+
// The carry that stood before this one was refused is let go, so both sides agree.
|
|
1194
|
+
if (wasCarried && this.socket)
|
|
1195
|
+
await this.sendRelease(id);
|
|
1196
|
+
return;
|
|
1197
|
+
}
|
|
1198
|
+
row.carried = true;
|
|
1199
|
+
const previous = row.previous;
|
|
1200
|
+
if (previous) {
|
|
1201
|
+
// The new carry took effect: the old id names nothing now, and its late frames are ignored.
|
|
1202
|
+
this.aliases.delete(previous.gameTokenId);
|
|
1203
|
+
this.retire(previous.gameTokenId);
|
|
1204
|
+
row.previous = null;
|
|
1205
|
+
if (this.ctx)
|
|
1206
|
+
row.ctx = carriedPlayerContext(this.ctx, row.gameTokenId);
|
|
1207
|
+
if (row.userId !== null && row.userId !== userId) {
|
|
1208
|
+
// `replaces` named another player. That player's carry still stands on the server
|
|
1209
|
+
// under the old id, with nobody here to send for it: let it go.
|
|
1210
|
+
this.report(new CrowdyError({
|
|
1211
|
+
message: `carry: replaces named game token id ${previous.gameTokenId}, which is another player's; that player was released`,
|
|
1212
|
+
}));
|
|
1213
|
+
this.replaced.delete(previous.gameTokenId);
|
|
1214
|
+
row.actors.clear();
|
|
1215
|
+
row.voice = undefined;
|
|
1216
|
+
row.video = undefined;
|
|
1217
|
+
if (this.socket)
|
|
1218
|
+
await this.sendRelease(previous.gameTokenId);
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1221
|
+
row.userId = userId;
|
|
1222
|
+
// The carry belongs to the player: a row the same user had under an older token is replaced.
|
|
1223
|
+
for (const other of [...this.table.values()]) {
|
|
1224
|
+
if (other === row || other.userId !== userId)
|
|
1225
|
+
continue;
|
|
1226
|
+
this.table.delete(other.gameTokenId);
|
|
1227
|
+
this.retire(other.gameTokenId);
|
|
1228
|
+
if (other.previous) {
|
|
1229
|
+
this.aliases.delete(other.previous.gameTokenId);
|
|
1230
|
+
this.retire(other.previous.gameTokenId);
|
|
1231
|
+
}
|
|
1232
|
+
for (const [uuid, actor] of other.actors)
|
|
1233
|
+
if (!row.actors.has(uuid))
|
|
1234
|
+
row.actors.set(uuid, actor);
|
|
1235
|
+
if (row.voice === undefined)
|
|
1236
|
+
row.voice = other.voice;
|
|
1237
|
+
if (row.video === undefined)
|
|
1238
|
+
row.video = other.video;
|
|
1239
|
+
this.settle(other, { status: 'released', wireStatus: null, userId: null }, false);
|
|
1240
|
+
}
|
|
1241
|
+
this.settle(row, { status: 'carried', wireStatus: status, userId }, true);
|
|
1242
|
+
await this.resendSpeakers(row);
|
|
1243
|
+
}
|
|
1244
|
+
onReleased(id, reason) {
|
|
1245
|
+
const moved = this.aliases.get(id);
|
|
1246
|
+
if (moved !== undefined) {
|
|
1247
|
+
// The carry under the old id ended while the refreshed token's carry waits. The player
|
|
1248
|
+
// is not dropped: the new carry's answer decides, and remembers this if it is refused.
|
|
1249
|
+
const waiting = this.table.get(moved);
|
|
1250
|
+
if (waiting?.previous)
|
|
1251
|
+
waiting.previous.ended = reason;
|
|
1252
|
+
this.counters.replacedIdFrames += 1;
|
|
1253
|
+
return;
|
|
1254
|
+
}
|
|
1255
|
+
if (this.replaced.has(id) && !this.table.has(id)) {
|
|
1256
|
+
this.counters.replacedIdFrames += 1;
|
|
1257
|
+
return;
|
|
1258
|
+
}
|
|
1259
|
+
const row = this.table.get(id);
|
|
1260
|
+
if (!row)
|
|
1261
|
+
return;
|
|
1262
|
+
const wasCarried = row.carried;
|
|
1263
|
+
row.carried = false;
|
|
1264
|
+
// A carry sent since then is still waiting for its own answer.
|
|
1265
|
+
if (!row.attempt)
|
|
1266
|
+
this.table.delete(id);
|
|
1267
|
+
if (wasCarried) {
|
|
1268
|
+
this.call(() => this.handlers.released?.({ playerGameTokenId: id, userId: row.userId, reason }));
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
/** End a row's waiting carry, if it has one, and tell whoever waits. */
|
|
1272
|
+
settle(row, outcome, announce) {
|
|
1273
|
+
const attempt = row.attempt;
|
|
1274
|
+
if (!attempt)
|
|
1275
|
+
return;
|
|
1276
|
+
row.attempt = null;
|
|
1277
|
+
const result = {
|
|
1278
|
+
playerGameTokenId: row.gameTokenId,
|
|
1279
|
+
userId: outcome.userId,
|
|
1280
|
+
status: outcome.status,
|
|
1281
|
+
wireStatus: outcome.wireStatus,
|
|
1282
|
+
carried: outcome.status === 'carried',
|
|
1283
|
+
};
|
|
1284
|
+
for (const resolve of attempt.resolvers)
|
|
1285
|
+
resolve(result);
|
|
1286
|
+
if (announce)
|
|
1287
|
+
this.call(() => this.handlers.carryResult?.(result));
|
|
1288
|
+
}
|
|
1289
|
+
/** A refusal of one send. It reaches the handler either way, with whether it was verified. */
|
|
1290
|
+
dispatchError(notification, verified) {
|
|
1291
|
+
this.counters.errorsReceived += 1;
|
|
1292
|
+
if (notification.errorCode === 'UNAUTHORIZED')
|
|
1293
|
+
this.counters.unauthorizedReceived += 1;
|
|
1294
|
+
if (!verified)
|
|
1295
|
+
this.counters.unverifiedErrorsReceived += 1;
|
|
1296
|
+
this.call(() => this.handlers.genericError?.(notification, verified));
|
|
1297
|
+
}
|
|
1298
|
+
/** A verified notification, and the players it is for. */
|
|
1299
|
+
dispatch(notification, players) {
|
|
1300
|
+
const h = this.handlers;
|
|
1301
|
+
// A refusal inside a FLEET_DELIVERY is not a thing the servers send, and the codec
|
|
1302
|
+
// refuses one; it has no handler here.
|
|
1303
|
+
if (notification.__typename === 'GenericErrorResponse')
|
|
1304
|
+
return;
|
|
1305
|
+
// The session is in one app. A notification that names another is not this session's,
|
|
1306
|
+
// even verified: it reaches no handler. (A channel notification names no app.)
|
|
1307
|
+
const app = notification.appId;
|
|
1308
|
+
if (typeof app === 'string' && app !== this.grant.appId) {
|
|
1309
|
+
this.counters.wrongApp += 1;
|
|
1310
|
+
return;
|
|
1311
|
+
}
|
|
1312
|
+
this.call(() => h.any?.(notification, players));
|
|
1313
|
+
this.call(() => {
|
|
1314
|
+
switch (notification.__typename) {
|
|
1315
|
+
case 'ActorUpdateNotification':
|
|
1316
|
+
return h.actorUpdate?.(notification, players);
|
|
1317
|
+
case 'VoxelUpdateNotification':
|
|
1318
|
+
return h.voxelUpdate?.(notification, players);
|
|
1319
|
+
case 'ActorLeftNotification':
|
|
1320
|
+
return h.actorLeft?.(notification, players);
|
|
1321
|
+
case 'ChunkChangedNotification':
|
|
1322
|
+
return h.chunkChanged?.(notification, players);
|
|
1323
|
+
case 'ClientEventNotification':
|
|
1324
|
+
return h.clientEvent?.(notification, players);
|
|
1325
|
+
case 'ServerEventNotification':
|
|
1326
|
+
return h.serverEvent?.(notification, players);
|
|
1327
|
+
case 'GenericSpatialNotification':
|
|
1328
|
+
return h.genericSpatial?.(notification, players);
|
|
1329
|
+
case 'ClientAudioNotification':
|
|
1330
|
+
return h.audio?.(notification, players);
|
|
1331
|
+
case 'ClientVideoNotification':
|
|
1332
|
+
return h.video?.(notification, players);
|
|
1333
|
+
case 'ClientTextNotification':
|
|
1334
|
+
return h.text?.(notification, players);
|
|
1335
|
+
case 'SingleActorMessageNotification':
|
|
1336
|
+
return h.singleActorMessage?.(notification, players);
|
|
1337
|
+
case 'ChannelMessageNotification':
|
|
1338
|
+
return h.channelMessage?.(notification, players);
|
|
1339
|
+
case 'ChannelAudioNotification':
|
|
1340
|
+
return h.channelAudio?.(notification, players);
|
|
1341
|
+
default:
|
|
1342
|
+
return undefined;
|
|
1343
|
+
}
|
|
1344
|
+
});
|
|
1345
|
+
}
|
|
1346
|
+
setStatus(status) {
|
|
1347
|
+
if (this.currentStatus === status)
|
|
1348
|
+
return;
|
|
1349
|
+
this.currentStatus = status;
|
|
1350
|
+
this.call(() => this.handlers.status?.(status));
|
|
1351
|
+
}
|
|
1352
|
+
call(fn) {
|
|
1353
|
+
try {
|
|
1354
|
+
fn();
|
|
1355
|
+
}
|
|
1356
|
+
catch (error) {
|
|
1357
|
+
this.report(error);
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
report(error) {
|
|
1361
|
+
const failure = error instanceof Error ? error : new Error(String(error));
|
|
1362
|
+
this.logger?.warn?.('fleet session', failure);
|
|
1363
|
+
try {
|
|
1364
|
+
this.handlers.error?.(failure);
|
|
1365
|
+
}
|
|
1366
|
+
catch {
|
|
1367
|
+
/* the error handler's own failure has nowhere to go */
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
function expiryOf(expiresAt) {
|
|
1372
|
+
if (!expiresAt)
|
|
1373
|
+
return null;
|
|
1374
|
+
const at = Date.parse(expiresAt);
|
|
1375
|
+
return Number.isFinite(at) ? at : null;
|
|
1376
|
+
}
|