@usions/sdk 2.32.0 → 2.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,609 @@
1
+ /** Shared small-room networking. Platform-authenticated signaling, WebRTC first,
2
+ * platform relay always available. Gameplay delivery is best effort, not RPC. */
3
+ const CHANNEL = '__usion_players_v1';
4
+ /** @param {string} mode */
5
+ const isRTC = mode => ['direct', 'turn', 'webrtc'].includes(mode);
6
+ const id = () => globalThis.crypto.randomUUID();
7
+ /** @param {any} value */
8
+ const validId = value => typeof value === 'string' && value.length > 0 && value.length <= 128;
9
+ export class PlayersConnection {
10
+ /**
11
+ * @param {any} game
12
+ * @param {any} Usion
13
+ * @param {any} [options]
14
+ */
15
+ constructor(game, Usion, options = {}) {
16
+ this.game = game;
17
+ this.usion = Usion;
18
+ this.options = options;
19
+ this.selfId = Usion.user.getId();
20
+ /** @type {string | null} */
21
+ this.roomId = null;
22
+ this.closed = false;
23
+ this.online = false;
24
+ this.session = id();
25
+ /** @type {Map<string, any>} */
26
+ this.peers = new Map();
27
+ this.roster = new Set();
28
+ /** @type {Record<string, Set<(value:any)=>void>>} */
29
+ this.listeners = { message: new Set(), status: new Set(), log: new Set() };
30
+ /** @type {Array<{time:number,event:string,peerId?:string,reason?:string}>} */
31
+ this.logs = [];
32
+ this.sequence = 0;
33
+ this.generation = 0;
34
+ this.lastHello = 0;
35
+ this.RTC = options.RTCPeerConnection === undefined ? globalThis.RTCPeerConnection : options.RTCPeerConnection;
36
+ this.iceServers = options.iceServers || [{ urls: 'stun:stun.l.google.com:19302' }];
37
+ this.timeout = options.directTimeoutMs ?? 6000;
38
+ this.unsubscribers = [
39
+ game._onChannel(CHANNEL, /** @param {any} packet @param {any} envelope */ (packet, envelope) => this._incoming(packet, envelope)),
40
+ game.on('joined', /** @param {any} data */ data => this._joined(data)),
41
+ game.on('playerJoined', /** @param {any} data */ data => this._roster(data)),
42
+ game.on('playerLeft', /** @param {any} data */ data => this._roster(data, true)),
43
+ game.on('sync', /** @param {any} data */ data => this._roster(data)),
44
+ game.on('roomAssigned', /** @param {{roomId:string}} data */ ({ roomId }) => { void this._join(roomId).catch(() => this._log('join_failed')); }),
45
+ game.on('disconnect', () => this._offline()),
46
+ game.on('reconnect', () => this._recover()),
47
+ game.on('reconnected', () => this._recover()),
48
+ ];
49
+ this.tick = setInterval(() => this._tick(), 1000);
50
+ }
51
+ async start() {
52
+ const room = this.options.roomId || this.game.roomId || this.usion.config.roomId;
53
+ if (room)
54
+ await this._join(room);
55
+ return this;
56
+ }
57
+ /**
58
+ * @param {any} type
59
+ * @param {any} data
60
+ */
61
+ _emit(type, data) {
62
+ for (const fn of this.listeners[type]) {
63
+ try {
64
+ fn(data);
65
+ }
66
+ catch { /* A game callback must not break the transport. */ }
67
+ }
68
+ }
69
+ /**
70
+ * @param {any} type
71
+ * @param {any} fn
72
+ */
73
+ _listen(type, fn) { this.listeners[type].add(fn); return () => this.listeners[type].delete(fn); }
74
+ /**
75
+ * @param {any} fn
76
+ */
77
+ onMessage(fn) { return this._listen('message', fn); }
78
+ /**
79
+ * @param {any} fn
80
+ */
81
+ onStatusChange(fn) { return this._listen('status', fn); }
82
+ /**
83
+ * @param {any} fn
84
+ */
85
+ onLog(fn) { return this._listen('log', fn); }
86
+ getLogs() { return this.logs.map(e => ({ ...e })); }
87
+ /**
88
+ * @param {any} event
89
+ * @param {any} peerId
90
+ * @param {any} reason
91
+ */
92
+ _log(event, peerId = undefined, reason = undefined) {
93
+ const entry = { time: Date.now(), event, peerId, reason };
94
+ this.logs.push(entry);
95
+ if (this.logs.length > 100)
96
+ this.logs.shift();
97
+ this._emit('log', { ...entry });
98
+ }
99
+ getStatus() {
100
+ return { roomId: this.roomId, state: this.closed ? 'closed' : !this.roomId ? 'waiting' : this.online ? 'connected' : 'offline',
101
+ peers: [...this.peers.values()].map(p => ({ playerId: p.id, transport: this.online ? p.mode : 'offline',
102
+ rttMs: p.rtt, sent: p.sent, received: p.received })) };
103
+ }
104
+ _status() { this._emit('status', this.getStatus()); }
105
+ /**
106
+ * @param {any} p
107
+ * @param {any} mode
108
+ * @param {any} reason
109
+ */
110
+ _mode(p, mode, reason) { p.mode = mode; p.rtt = null; this._log('transport', p.id, reason); this._status(); }
111
+ /**
112
+ * @param {any} roomId
113
+ */
114
+ async _join(roomId) {
115
+ if (this.closed)
116
+ return;
117
+ const generation = ++this.generation;
118
+ if (this.roomId !== roomId) {
119
+ this._clearPeers();
120
+ this.roster.clear();
121
+ this.session = id();
122
+ this.roomId = roomId;
123
+ }
124
+ this.online = false;
125
+ await this.game.connect();
126
+ if (this.closed || generation !== this.generation)
127
+ return;
128
+ const data = await this.game.join(roomId);
129
+ if (this.closed || generation !== this.generation)
130
+ return;
131
+ this._joined(data || {});
132
+ }
133
+ /**
134
+ * @param {any} data
135
+ */
136
+ _joined(data) {
137
+ if (this.closed)
138
+ return;
139
+ const room = data.room_id || this.game.roomId;
140
+ if (room !== this.roomId)
141
+ return;
142
+ this.online = true;
143
+ this._roster(data);
144
+ this._hello();
145
+ this._status();
146
+ }
147
+ _recover() { if (!this.closed && !this.online && this.roomId)
148
+ void this._join(this.roomId).catch(() => this._log('rejoin_failed')); }
149
+ _offline() {
150
+ if (this.closed)
151
+ return;
152
+ this.generation++;
153
+ this.online = false;
154
+ this.session = id();
155
+ this._clearPeers();
156
+ this._log('offline');
157
+ this._status();
158
+ }
159
+ /**
160
+ * @param {any} data
161
+ * @param {any} [left]
162
+ */
163
+ _roster(data, left = false) {
164
+ if (this.closed || !data || (data.room_id && data.room_id !== this.roomId))
165
+ return;
166
+ if (Array.isArray(data.player_ids))
167
+ this.roster = new Set(data.player_ids.filter(validId));
168
+ else if (validId(data.player_id)) {
169
+ if (left)
170
+ this.roster.delete(data.player_id);
171
+ else
172
+ this.roster.add(data.player_id);
173
+ }
174
+ for (const [key, p] of this.peers)
175
+ if (!this.roster.has(key) || (left && key === data.player_id)) {
176
+ this._closeRTC(p);
177
+ this.peers.delete(key);
178
+ this._log('peer_left', key);
179
+ }
180
+ this._hello();
181
+ this._status();
182
+ }
183
+ /**
184
+ * @param {any} packet
185
+ * @param {any} to
186
+ */
187
+ _relay(packet, to) {
188
+ if (!this.online || this.closed)
189
+ return false;
190
+ try {
191
+ this.game.realtime(CHANNEL, { ...packet, v: 1, room: this.roomId, session: this.session, to });
192
+ return true;
193
+ }
194
+ catch {
195
+ this._log('relay_send_failed', to);
196
+ return false;
197
+ }
198
+ }
199
+ /**
200
+ * @param {any} to
201
+ */
202
+ _hello(to = undefined) { this._relay({ kind: 'hello' }, to); }
203
+ /**
204
+ * @param {any} peerId
205
+ * @param {any} session
206
+ */
207
+ _peer(peerId, session) {
208
+ let p = this.peers.get(peerId);
209
+ if (p && p.session !== session) {
210
+ this._closeRTC(p);
211
+ this.peers.delete(peerId);
212
+ p = null;
213
+ }
214
+ if (!p) {
215
+ if (this.peers.size >= 7) {
216
+ this._log('peer_limit', peerId);
217
+ return null;
218
+ }
219
+ p = { id: peerId, session, mode: 'relay', pc: null, dc: null, attempt: null, candidates: [],
220
+ queue: Promise.resolve(), lastDirect: 0, lastSequence: -1, rtt: null, sent: 0, received: 0,
221
+ started: false, pendingPing: null };
222
+ this.peers.set(peerId, p);
223
+ this._log('peer_joined', peerId);
224
+ this._status();
225
+ }
226
+ return p;
227
+ }
228
+ /**
229
+ * @param {any} m
230
+ * @param {any} envelope
231
+ */
232
+ _incoming(m, envelope) {
233
+ // Use the backend's sender identity, never a client-supplied `from` field.
234
+ const from = envelope?.player_id;
235
+ if (this.closed || !this.online || !m || m.v !== 1 || m.room !== this.roomId ||
236
+ envelope.room_id !== this.roomId || !validId(from) || from === this.selfId ||
237
+ !this.roster.has(from) || !validId(m.session) || (m.to && m.to !== this.selfId))
238
+ return;
239
+ if (m.kind === 'hello') {
240
+ const known = this.peers.get(from)?.session === m.session;
241
+ const p = this._peer(from, m.session);
242
+ if (!p)
243
+ return;
244
+ if (!known)
245
+ this._hello(from);
246
+ if (this.selfId < from && !p.started)
247
+ this._attempt(p);
248
+ return;
249
+ }
250
+ const p = this.peers.get(from);
251
+ if (!p || p.session !== m.session || m.target !== this.session)
252
+ return;
253
+ if (m.kind === 'offer' && this.selfId > from && validId(m.attempt)) {
254
+ if (p.attempt === m.attempt)
255
+ return;
256
+ this._setup(p, m.attempt);
257
+ if (p.pc)
258
+ this._signal(p, m);
259
+ }
260
+ else if (['answer', 'ice'].includes(m.kind) && m.attempt === p.attempt)
261
+ this._signal(p, m);
262
+ else if (m.kind === 'fallback' && m.attempt === p.attempt)
263
+ this._fallback(p, 'peer_requested', false);
264
+ else if (m.kind === 'retry' && this.selfId < from)
265
+ this._attempt(p);
266
+ else if (m.kind === 'data')
267
+ this._receive(p, m, 'relay');
268
+ }
269
+ /**
270
+ * @param {any} p
271
+ * @param {any} packet
272
+ */
273
+ _control(p, packet) { return this._relay({ ...packet, target: p.session, attempt: p.attempt }, p.id); }
274
+ /**
275
+ * @param {any} p
276
+ * @param {any} attempt
277
+ */
278
+ _setup(p, attempt) {
279
+ this._closeRTC(p);
280
+ p.attempt = attempt;
281
+ p.started = true;
282
+ if (!this.RTC || this.options.direct === false) {
283
+ this._fallback(p, 'direct_unavailable');
284
+ return;
285
+ }
286
+ this._mode(p, 'connecting', 'direct_attempt');
287
+ try {
288
+ const pc = p.pc = new this.RTC({ iceServers: this.iceServers });
289
+ p.localCandidates = [];
290
+ p.descriptionSent = false;
291
+ pc.onicecandidate = /** @param {any} e */ /** @param {any} e */ e => {
292
+ if (p.pc !== pc || !e.candidate)
293
+ return;
294
+ const candidate = e.candidate.toJSON();
295
+ if (p.descriptionSent)
296
+ this._control(p, { kind: 'ice', candidate });
297
+ else if (p.localCandidates.length < 64)
298
+ p.localCandidates.push(candidate);
299
+ };
300
+ pc.ondatachannel = /** @param {any} e */ /** @param {any} e */ e => { if (p.pc === pc)
301
+ this._channel(p, pc, e.channel); };
302
+ pc.onconnectionstatechange = () => {
303
+ if (p.pc === pc && ['failed', 'disconnected', 'closed'].includes(pc.connectionState))
304
+ this._fallback(p, pc.connectionState);
305
+ };
306
+ p.timer = setTimeout(() => { if (p.pc === pc)
307
+ this._fallback(p, 'direct_timeout'); }, this.timeout);
308
+ }
309
+ catch {
310
+ this._fallback(p, 'rtc_setup_failed');
311
+ }
312
+ }
313
+ /**
314
+ * @param {any} p
315
+ */
316
+ _attempt(p) {
317
+ this._setup(p, id());
318
+ const pc = p.pc;
319
+ if (!pc)
320
+ return;
321
+ try {
322
+ this._channel(p, pc, pc.createDataChannel('usion-game', { ordered: false, maxRetransmits: 0 }));
323
+ }
324
+ catch {
325
+ this._fallback(p, 'channel_failed');
326
+ return;
327
+ }
328
+ p.queue = (async () => {
329
+ const offer = await pc.createOffer();
330
+ if (p.pc !== pc)
331
+ return;
332
+ await pc.setLocalDescription(offer);
333
+ if (p.pc === pc)
334
+ this._description(p, 'offer');
335
+ })().catch(() => { if (p.pc === pc)
336
+ this._fallback(p, 'offer_failed'); });
337
+ }
338
+ /**
339
+ * @param {any} p
340
+ * @param {any} m
341
+ */
342
+ _signal(p, m) {
343
+ const pc = p.pc;
344
+ if (!pc)
345
+ return;
346
+ p.queue = p.queue.then(async () => {
347
+ if (p.pc !== pc)
348
+ return;
349
+ if (m.kind === 'ice') {
350
+ if (pc.remoteDescription)
351
+ await pc.addIceCandidate(m.candidate);
352
+ else if (p.candidates.length < 64)
353
+ p.candidates.push(m.candidate);
354
+ }
355
+ else {
356
+ await pc.setRemoteDescription(m.description);
357
+ if (p.pc !== pc)
358
+ return;
359
+ const pending = p.candidates;
360
+ p.candidates = [];
361
+ for (const candidate of pending)
362
+ await pc.addIceCandidate(candidate);
363
+ if (m.kind === 'offer') {
364
+ await pc.setLocalDescription(await pc.createAnswer());
365
+ if (p.pc === pc)
366
+ this._description(p, 'answer');
367
+ }
368
+ }
369
+ }).catch(() => { if (p.pc === pc)
370
+ this._fallback(p, 'negotiation_failed'); });
371
+ }
372
+ /**
373
+ * @param {any} p
374
+ * @param {any} kind
375
+ */
376
+ _description(p, kind) {
377
+ this._control(p, { kind, description: p.pc.localDescription.toJSON() });
378
+ p.descriptionSent = true;
379
+ for (const candidate of p.localCandidates)
380
+ this._control(p, { kind: 'ice', candidate });
381
+ p.localCandidates = [];
382
+ }
383
+ /**
384
+ * @param {any} p
385
+ * @param {any} pc
386
+ * @param {any} dc
387
+ */
388
+ _channel(p, pc, dc) {
389
+ p.dc = dc;
390
+ dc.onopen = () => {
391
+ if (p.pc !== pc)
392
+ return;
393
+ clearTimeout(p.timer);
394
+ p.lastDirect = Date.now();
395
+ this._mode(p, 'webrtc', 'channel_open');
396
+ void this._inspectRoute(p, pc);
397
+ };
398
+ dc.onmessage = /** @param {any} e */ /** @param {any} e */ e => {
399
+ if (p.pc !== pc || typeof e.data !== 'string' || e.data.length > 16384)
400
+ return;
401
+ try {
402
+ this._receive(p, JSON.parse(e.data), 'direct');
403
+ }
404
+ catch { /* malformed peer data */ }
405
+ };
406
+ dc.onerror = dc.onclose = () => { if (p.pc === pc)
407
+ this._fallback(p, 'channel_closed'); };
408
+ }
409
+ /** @param {any} p @param {any} pc */
410
+ async _inspectRoute(p, pc) {
411
+ if (!pc?.getStats)
412
+ return;
413
+ try {
414
+ const stats = await pc.getStats();
415
+ if (p.pc !== pc || !isRTC(p.mode))
416
+ return;
417
+ /** @type {any} */
418
+ let pair;
419
+ stats.forEach(/** @param {any} report */ /** @param {any} report */ report => {
420
+ if (report.type === 'transport' && report.selectedCandidatePairId)
421
+ pair = stats.get(report.selectedCandidatePairId);
422
+ });
423
+ if (!pair)
424
+ stats.forEach(/** @param {any} report */ /** @param {any} report */ report => {
425
+ if (report.type === 'candidate-pair' && report.nominated && report.state === 'succeeded')
426
+ pair = report;
427
+ });
428
+ if (!pair)
429
+ return;
430
+ const local = stats.get(pair.localCandidateId), remote = stats.get(pair.remoteCandidateId);
431
+ if (!local?.candidateType || !remote?.candidateType)
432
+ return;
433
+ const mode = local.candidateType === 'relay' || remote.candidateType === 'relay' ? 'turn' : 'direct';
434
+ if (mode !== p.mode)
435
+ this._mode(p, mode, 'ice_route_selected');
436
+ }
437
+ catch { /* Keep generic WebRTC label if stats are unavailable. */ }
438
+ }
439
+ /**
440
+ * @param {any} p
441
+ */
442
+ _closeRTC(p) {
443
+ clearTimeout(p.timer);
444
+ const pc = p.pc, dc = p.dc;
445
+ p.pc = p.dc = null;
446
+ p.candidates = [];
447
+ p.queue = Promise.resolve();
448
+ if (dc) {
449
+ dc.onopen = dc.onmessage = dc.onerror = dc.onclose = null;
450
+ dc.close();
451
+ }
452
+ if (pc) {
453
+ pc.onicecandidate = pc.ondatachannel = pc.onconnectionstatechange = null;
454
+ pc.close();
455
+ }
456
+ }
457
+ /**
458
+ * @param {any} p
459
+ * @param {any} reason
460
+ * @param {any} [notify]
461
+ */
462
+ _fallback(p, reason, notify = true) {
463
+ if (notify)
464
+ this._control(p, { kind: 'fallback' });
465
+ this._closeRTC(p);
466
+ this._mode(p, 'relay', reason);
467
+ }
468
+ /**
469
+ * @param {any} p
470
+ * @param {any} packet
471
+ */
472
+ _packet(p, packet) {
473
+ const m = { ...packet, kind: 'data', room: this.roomId, session: this.session, target: p.session };
474
+ if (isRTC(p.mode) && p.dc?.readyState === 'open') {
475
+ try {
476
+ if (p.dc.bufferedAmount > 65536)
477
+ throw Error('backpressure');
478
+ p.dc.send(JSON.stringify(m));
479
+ return true;
480
+ }
481
+ catch {
482
+ this._fallback(p, 'send_failed');
483
+ }
484
+ }
485
+ return this._control(p, m);
486
+ }
487
+ /**
488
+ * @param {any} p
489
+ * @param {any} m
490
+ * @param {any} transport
491
+ */
492
+ _receive(p, m, transport) {
493
+ if (m.room !== this.roomId || m.session !== p.session || m.target !== this.session)
494
+ return;
495
+ if (transport === 'direct')
496
+ p.lastDirect = Date.now();
497
+ if (Number.isSafeInteger(m.ping) && m.ping > 0) {
498
+ this._packet(p, { pong: m.ping });
499
+ return;
500
+ }
501
+ if (Number.isSafeInteger(m.pong) && m.pong > 0) {
502
+ if (m.pong === p.pendingPing) {
503
+ p.rtt = Date.now() - m.pong;
504
+ p.pendingPing = null;
505
+ this._status();
506
+ }
507
+ return;
508
+ }
509
+ if (!Number.isSafeInteger(m.seq) || m.seq <= p.lastSequence)
510
+ return;
511
+ p.lastSequence = m.seq;
512
+ p.received++;
513
+ this._emit('message', { data: m.data, playerId: p.id, transport: transport === 'direct' ? (isRTC(p.mode) ? p.mode : 'webrtc') : transport });
514
+ }
515
+ /**
516
+ * @param {any} data
517
+ * @param {any} playerId
518
+ */
519
+ send(data, playerId) {
520
+ if (this.closed || !this.online)
521
+ return false;
522
+ const json = JSON.stringify(data);
523
+ if (json === undefined || new TextEncoder().encode(json).length > 4096)
524
+ throw new Error('connectPlayers messages must be JSON, at most 4096 bytes');
525
+ const copy = JSON.parse(json), seq = ++this.sequence;
526
+ const peers = playerId ? [this.peers.get(playerId)].filter(Boolean) : [...this.peers.values()];
527
+ let accepted = peers.length > 0;
528
+ for (const p of peers) {
529
+ const ok = this._packet(p, { data: copy, seq });
530
+ if (ok)
531
+ p.sent++;
532
+ accepted = accepted && ok;
533
+ }
534
+ return accepted;
535
+ }
536
+ /**
537
+ * @param {any} playerId
538
+ */
539
+ forceRelay(playerId) { for (const p of this.peers.values())
540
+ if (!playerId || p.id === playerId)
541
+ this._fallback(p, 'forced'); }
542
+ /**
543
+ * @param {any} playerId
544
+ */
545
+ retryDirect(playerId) {
546
+ if (!this.online || this.closed)
547
+ return;
548
+ for (const p of this.peers.values())
549
+ if (!playerId || p.id === playerId) {
550
+ if (this.selfId < p.id)
551
+ this._attempt(p);
552
+ else
553
+ this._control(p, { kind: 'retry' });
554
+ }
555
+ }
556
+ async invite() { return this.game.invite(); }
557
+ _tick() {
558
+ if (!this.online || this.closed)
559
+ return;
560
+ const now = Date.now();
561
+ if (now - this.lastHello >= 3000) {
562
+ this.lastHello = now;
563
+ this._hello();
564
+ }
565
+ for (const p of this.peers.values()) {
566
+ if (isRTC(p.mode) && now - (p.lastStats || 0) > 10000) {
567
+ p.lastStats = now;
568
+ void this._inspectRoute(p, p.pc);
569
+ }
570
+ if (isRTC(p.mode) && now - p.lastDirect > 3000)
571
+ this._fallback(p, 'direct_unresponsive');
572
+ p.pendingPing = now;
573
+ this._packet(p, { ping: now });
574
+ }
575
+ }
576
+ _clearPeers() { for (const p of this.peers.values())
577
+ this._closeRTC(p); this.peers.clear(); }
578
+ close() {
579
+ if (this.closed)
580
+ return;
581
+ this.closed = true;
582
+ this.generation++;
583
+ clearInterval(this.tick);
584
+ this._clearPeers();
585
+ this.unsubscribers.forEach(off => off());
586
+ this._status();
587
+ for (const list of Object.values(this.listeners))
588
+ list.clear();
589
+ }
590
+ }
591
+ /**
592
+ * @param {any} game
593
+ * @param {any} Usion
594
+ */
595
+ export function applyGamePlayers(game, Usion) {
596
+ game.connectPlayers = /** @param {any} [options] */ function (options = {}) {
597
+ if (game._playersConnection && !game._playersConnection.closed)
598
+ return game._playersPromise;
599
+ if (game.directMode || Usion.config.connectionMode === 'direct')
600
+ return Promise.reject(new Error('connectPlayers requires platform room signaling'));
601
+ if (!validId(Usion.user.getId()))
602
+ return Promise.reject(new Error('Initialize Usion before connectPlayers'));
603
+ if (options.directTimeoutMs !== undefined && (!Number.isFinite(options.directTimeoutMs) || options.directTimeoutMs < 1000 || options.directTimeoutMs > 30000))
604
+ return Promise.reject(new Error('directTimeoutMs must be 1000–30000'));
605
+ const connection = game._playersConnection = new PlayersConnection(game, Usion, options);
606
+ game._playersPromise = connection.start().catch(error => { connection.close(); throw error; });
607
+ return game._playersPromise;
608
+ };
609
+ }