@usions/sdk 2.21.0 → 2.24.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.
- package/package.json +1 -1
- package/src/browser.js +961 -166
- package/src/modules/backend-channel.js +41 -8
- package/src/modules/core.js +59 -8
- package/src/modules/errors.js +49 -4
- package/src/modules/game-core.js +26 -17
- package/src/modules/game-direct.js +14 -7
- package/src/modules/game-methods.js +114 -29
- package/src/modules/game-netcode.js +3 -0
- package/src/modules/game-resilience.js +245 -0
- package/src/modules/matchmaking.js +92 -13
- package/src/modules/misc.js +7 -2
- package/src/modules/netcode/index.js +4 -2
- package/src/modules/netcode/interest-grid.js +227 -0
- package/src/modules/wallet.js +12 -5
- package/types/index.d.ts +164 -6
package/src/browser.js
CHANGED
|
@@ -1,10 +1,132 @@
|
|
|
1
1
|
var Usion = (function () {
|
|
2
2
|
'use strict';
|
|
3
3
|
|
|
4
|
+
/**
|
|
5
|
+
* Usion SDK Errors — stable, machine-readable error codes.
|
|
6
|
+
*
|
|
7
|
+
* Developers should branch on `err.code`, never on message text. Messages
|
|
8
|
+
* are human-readable and may change; codes are part of the public API and
|
|
9
|
+
* follow the deprecation policy (never removed within a major version).
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** @type {Record<string, string>} */
|
|
13
|
+
const ERROR_CODES = {
|
|
14
|
+
NOT_CONNECTED: 'NOT_CONNECTED', // No live connection for this call
|
|
15
|
+
NO_ROOM: 'NO_ROOM', // No room id provided/known
|
|
16
|
+
ROOM_NOT_FOUND: 'ROOM_NOT_FOUND', // Room does not exist server-side
|
|
17
|
+
NOT_PARTICIPANT: 'NOT_PARTICIPANT', // Caller is not a player in the room
|
|
18
|
+
NOT_IN_ROOM: 'NOT_IN_ROOM', // Socket not in the room — rejoin required
|
|
19
|
+
NOT_AUTHORITY: 'NOT_AUTHORITY', // Authority-only call (e.g. lobby start)
|
|
20
|
+
NOT_AUTHENTICATED: 'NOT_AUTHENTICATED', // Missing/invalid auth server-side
|
|
21
|
+
JOIN_TIMEOUT: 'JOIN_TIMEOUT', // Join did not complete in time
|
|
22
|
+
CONNECT_TIMEOUT: 'CONNECT_TIMEOUT', // Connect did not complete in time
|
|
23
|
+
INIT_TIMEOUT: 'INIT_TIMEOUT', // init() got no INIT from the host in time
|
|
24
|
+
MATCH_TIMEOUT: 'MATCH_TIMEOUT', // matchmaking.find() opts.timeout elapsed
|
|
25
|
+
STATE_TOO_LARGE: 'STATE_TOO_LARGE', // setState payload over the quota
|
|
26
|
+
INVALID_STATE: 'INVALID_STATE', // setState payload not a JSON object
|
|
27
|
+
STALE_STATE: 'STALE_STATE', // setState older than the stored checkpoint
|
|
28
|
+
INVALID_NEXT_TURN: 'INVALID_NEXT_TURN', // nextTurn is not a player in the room
|
|
29
|
+
INVALID_INPUT: 'INVALID_INPUT', // Missing/malformed argument server-side
|
|
30
|
+
NOT_FOUND: 'NOT_FOUND', // Referenced entity (service, lobby, …) missing
|
|
31
|
+
QUOTA_EXCEEDED: 'QUOTA_EXCEEDED', // Bucket key/size quota reached (cloud KV)
|
|
32
|
+
VALUE_TOO_LARGE: 'VALUE_TOO_LARGE', // Single value over the per-value quota
|
|
33
|
+
LOBBY_FULL: 'LOBBY_FULL', // Lobby at max_players
|
|
34
|
+
LOBBY_CLOSED: 'LOBBY_CLOSED', // Lobby exists but is not open
|
|
35
|
+
WORLD_FULL: 'WORLD_FULL', // World room at max_players
|
|
36
|
+
CONFLICT: 'CONFLICT', // Concurrent-write conflict; retry
|
|
37
|
+
RATE_LIMITED: 'RATE_LIMITED', // Too many calls; back off (see retryAfter)
|
|
38
|
+
REQUEST_TIMEOUT: 'REQUEST_TIMEOUT', // Host/parent did not reply in time
|
|
39
|
+
QUEUE_FULL: 'QUEUE_FULL', // Offline action queue at capacity
|
|
40
|
+
CANCELLED: 'CANCELLED', // Cancelled by a local cancel() call
|
|
41
|
+
SUPERSEDED: 'SUPERSEDED', // Replaced by a newer identical request
|
|
42
|
+
UNSUPPORTED: 'UNSUPPORTED', // Not available in this transport
|
|
43
|
+
UNKNOWN: 'UNKNOWN', // Unmapped error (see message)
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
class UsionError extends Error {
|
|
47
|
+
/**
|
|
48
|
+
* @param {string} code - One of ERROR_CODES
|
|
49
|
+
* @param {string} [message] - Human-readable detail (may change between versions)
|
|
50
|
+
*/
|
|
51
|
+
constructor(code, message) {
|
|
52
|
+
super(message || code);
|
|
53
|
+
this.name = 'UsionError';
|
|
54
|
+
this.code = ERROR_CODES[code] ? code : ERROR_CODES.UNKNOWN;
|
|
55
|
+
/** @type {number|undefined} Seconds until a RATE_LIMITED call may retry. */
|
|
56
|
+
this.retryAfter = undefined;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Backend error strings → stable codes. Order matters: first match wins.
|
|
61
|
+
// Fallback path only: the backend now sends a structured `code` on every
|
|
62
|
+
// error ack, which toUsionError prefers. These patterns cover old backends
|
|
63
|
+
// and hosts that strip the code.
|
|
64
|
+
/** @type {Array<[RegExp, string]>} */
|
|
65
|
+
const BACKEND_PATTERNS = [
|
|
66
|
+
[/not authenticated/i, ERROR_CODES.NOT_AUTHENTICATED],
|
|
67
|
+
[/room_id required|no room id/i, ERROR_CODES.NO_ROOM],
|
|
68
|
+
[/room not found/i, ERROR_CODES.ROOM_NOT_FOUND],
|
|
69
|
+
[/not in room/i, ERROR_CODES.NOT_IN_ROOM],
|
|
70
|
+
[/not a participant/i, ERROR_CODES.NOT_PARTICIPANT],
|
|
71
|
+
[/room authority/i, ERROR_CODES.NOT_AUTHORITY],
|
|
72
|
+
[/exceeds .*limit/i, ERROR_CODES.STATE_TOO_LARGE],
|
|
73
|
+
[/stale checkpoint|stale state/i, ERROR_CODES.STALE_STATE],
|
|
74
|
+
[/state must be/i, ERROR_CODES.INVALID_STATE],
|
|
75
|
+
[/next_turn must be/i, ERROR_CODES.INVALID_NEXT_TURN],
|
|
76
|
+
[/rate limit|too many/i, ERROR_CODES.RATE_LIMITED],
|
|
77
|
+
[/join timeout/i, ERROR_CODES.JOIN_TIMEOUT],
|
|
78
|
+
[/connection timeout|connect timeout/i, ERROR_CODES.CONNECT_TIMEOUT],
|
|
79
|
+
[/request timeout/i, ERROR_CODES.REQUEST_TIMEOUT],
|
|
80
|
+
[/not connected/i, ERROR_CODES.NOT_CONNECTED],
|
|
81
|
+
[/quota exceeded/i, ERROR_CODES.QUOTA_EXCEEDED],
|
|
82
|
+
[/value too large/i, ERROR_CODES.VALUE_TOO_LARGE],
|
|
83
|
+
[/lobby is full/i, ERROR_CODES.LOBBY_FULL],
|
|
84
|
+
[/lobby is not open/i, ERROR_CODES.LOBBY_CLOSED],
|
|
85
|
+
[/world room is full/i, ERROR_CODES.WORLD_FULL],
|
|
86
|
+
[/not found|unknown service/i, ERROR_CODES.NOT_FOUND],
|
|
87
|
+
[/conflict/i, ERROR_CODES.CONFLICT],
|
|
88
|
+
[/cancelled/i, ERROR_CODES.CANCELLED],
|
|
89
|
+
[/superseded/i, ERROR_CODES.SUPERSEDED],
|
|
90
|
+
];
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Normalize anything — a structured backend ack ({ error, code?, retry_after? }),
|
|
94
|
+
* an Error, or a raw string — into a UsionError with the best stable code.
|
|
95
|
+
* A machine-readable `code` on the input always wins over message matching.
|
|
96
|
+
* @param {*} err
|
|
97
|
+
* @param {string} [fallbackCode] - Code to use when nothing matches
|
|
98
|
+
* @returns {UsionError}
|
|
99
|
+
*/
|
|
100
|
+
function toUsionError(err, fallbackCode) {
|
|
101
|
+
if (err instanceof UsionError) return err;
|
|
102
|
+
|
|
103
|
+
// Structured input (backend ack object or an Error carrying a code).
|
|
104
|
+
if (err && typeof err === 'object') {
|
|
105
|
+
const code = typeof err.code === 'string' && ERROR_CODES[err.code] ? err.code : null;
|
|
106
|
+
const message = err.message || err.error;
|
|
107
|
+
if (code) {
|
|
108
|
+
const ue = new UsionError(code, typeof message === 'string' ? message : code);
|
|
109
|
+
const retryAfter = err.retry_after != null ? err.retry_after : err.retryAfter;
|
|
110
|
+
if (typeof retryAfter === 'number' && isFinite(retryAfter)) ue.retryAfter = retryAfter;
|
|
111
|
+
return ue;
|
|
112
|
+
}
|
|
113
|
+
if (!(err instanceof Error) && typeof message === 'string') err = message;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const message = err && err.message ? err.message : String(err || 'Unknown error');
|
|
117
|
+
for (let i = 0; i < BACKEND_PATTERNS.length; i++) {
|
|
118
|
+
if (BACKEND_PATTERNS[i][0].test(message)) {
|
|
119
|
+
return new UsionError(BACKEND_PATTERNS[i][1], message);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return new UsionError(fallbackCode || ERROR_CODES.UNKNOWN, message);
|
|
123
|
+
}
|
|
124
|
+
|
|
4
125
|
/**
|
|
5
126
|
* Usion SDK Core — init, _post, _request, message handling
|
|
6
127
|
*/
|
|
7
128
|
|
|
129
|
+
|
|
8
130
|
// Request ID counter for tracking async responses
|
|
9
131
|
let _requestId = 0;
|
|
10
132
|
const _pendingRequests = {};
|
|
@@ -69,7 +191,7 @@ var Usion = (function () {
|
|
|
69
191
|
* Core Usion object with init, _post, _request
|
|
70
192
|
*/
|
|
71
193
|
const core = {
|
|
72
|
-
version: '2.
|
|
194
|
+
version: '2.24.0', // injected from package.json at build
|
|
73
195
|
config: {},
|
|
74
196
|
_initialized: false,
|
|
75
197
|
_initCallback: null,
|
|
@@ -78,24 +200,60 @@ var Usion = (function () {
|
|
|
78
200
|
_backButtonCallback: null,
|
|
79
201
|
|
|
80
202
|
/**
|
|
81
|
-
* Initialize the SDK with config from parent app
|
|
82
|
-
*
|
|
203
|
+
* Initialize the SDK with config from parent app.
|
|
204
|
+
*
|
|
205
|
+
* Callback form (unchanged): `Usion.init(cb)` — cb(config) fires when the
|
|
206
|
+
* host's INIT arrives. Promise form: every call ALSO returns a
|
|
207
|
+
* Promise<config>, so `const config = await Usion.init()` works.
|
|
208
|
+
*
|
|
209
|
+
* `opts.timeout` (ms, optional) rejects the promise with
|
|
210
|
+
* UsionError(INIT_TIMEOUT) if no INIT arrives in time — the "embedded but
|
|
211
|
+
* host silent" case that otherwise hangs forever. The callback still fires
|
|
212
|
+
* if INIT arrives late. Both `init(cb, opts)` and `init(opts)` are accepted.
|
|
213
|
+
*
|
|
214
|
+
* @param {function|{timeout?: number}} [callback] - Called with config when ready
|
|
215
|
+
* @param {{timeout?: number}} [opts]
|
|
216
|
+
* @returns {Promise<object>} Resolves with config
|
|
83
217
|
*/
|
|
84
|
-
init: function(callback) {
|
|
218
|
+
init: function(callback, opts) {
|
|
85
219
|
const self = this;
|
|
220
|
+
if (callback && typeof callback === 'object') {
|
|
221
|
+
opts = callback;
|
|
222
|
+
callback = null;
|
|
223
|
+
}
|
|
224
|
+
opts = opts || {};
|
|
86
225
|
|
|
87
226
|
// Prevent double initialization - just update callback
|
|
88
227
|
if (self._initialized) {
|
|
89
228
|
if (callback) callback(self.config);
|
|
90
|
-
return;
|
|
229
|
+
return Promise.resolve(self.config);
|
|
91
230
|
}
|
|
92
231
|
|
|
93
232
|
// Store callback for when config arrives
|
|
94
|
-
self._initCallback = callback;
|
|
233
|
+
if (callback) self._initCallback = callback;
|
|
234
|
+
|
|
235
|
+
// One shared promise for every init() call before INIT arrives.
|
|
236
|
+
if (!self._initPromise) {
|
|
237
|
+
self._initPromise = new Promise(function(resolve, reject) {
|
|
238
|
+
self._initResolve = resolve;
|
|
239
|
+
self._initReject = reject;
|
|
240
|
+
});
|
|
241
|
+
// Callback-style users never touch the promise — don't let an
|
|
242
|
+
// INIT_TIMEOUT rejection surface as an unhandled-rejection error.
|
|
243
|
+
self._initPromise.catch(function() {});
|
|
244
|
+
}
|
|
245
|
+
if (opts.timeout > 0 && !self._initTimer) {
|
|
246
|
+
self._initTimer = setTimeout(function() {
|
|
247
|
+
self._initTimer = null;
|
|
248
|
+
if (self._initialized || !self._initReject) return;
|
|
249
|
+
self._initReject(new UsionError(ERROR_CODES.INIT_TIMEOUT,
|
|
250
|
+
'No INIT from host within ' + opts.timeout + 'ms — host silent or running standalone'));
|
|
251
|
+
}, opts.timeout);
|
|
252
|
+
}
|
|
95
253
|
|
|
96
254
|
// Only register message handler once
|
|
97
255
|
if (self._messageHandlerRegistered) {
|
|
98
|
-
return;
|
|
256
|
+
return self._initPromise;
|
|
99
257
|
}
|
|
100
258
|
self._messageHandlerRegistered = true;
|
|
101
259
|
|
|
@@ -151,6 +309,15 @@ var Usion = (function () {
|
|
|
151
309
|
if (self._initCallback) {
|
|
152
310
|
self._initCallback(data.config);
|
|
153
311
|
}
|
|
312
|
+
|
|
313
|
+
// Settle the promise form
|
|
314
|
+
if (self._initTimer) {
|
|
315
|
+
clearTimeout(self._initTimer);
|
|
316
|
+
self._initTimer = null;
|
|
317
|
+
}
|
|
318
|
+
if (self._initResolve) {
|
|
319
|
+
self._initResolve(data.config);
|
|
320
|
+
}
|
|
154
321
|
}
|
|
155
322
|
|
|
156
323
|
// Handle response messages for async requests
|
|
@@ -159,7 +326,9 @@ var Usion = (function () {
|
|
|
159
326
|
delete _pendingRequests[data._requestId];
|
|
160
327
|
|
|
161
328
|
if (data.error) {
|
|
162
|
-
|
|
329
|
+
// Preserve the backend's stable code/retry_after when the host
|
|
330
|
+
// relayed them (see errors.js).
|
|
331
|
+
reject(toUsionError(data));
|
|
163
332
|
} else {
|
|
164
333
|
resolve(data);
|
|
165
334
|
}
|
|
@@ -218,6 +387,8 @@ var Usion = (function () {
|
|
|
218
387
|
|
|
219
388
|
// Signal ready to parent
|
|
220
389
|
this._post({ type: 'READY' });
|
|
390
|
+
|
|
391
|
+
return self._initPromise;
|
|
221
392
|
},
|
|
222
393
|
|
|
223
394
|
/**
|
|
@@ -339,7 +510,7 @@ var Usion = (function () {
|
|
|
339
510
|
// Setup timeout
|
|
340
511
|
const timer = setTimeout(function() {
|
|
341
512
|
delete _pendingRequests[requestId];
|
|
342
|
-
reject(new
|
|
513
|
+
reject(new UsionError(ERROR_CODES.REQUEST_TIMEOUT, 'Request timeout'));
|
|
343
514
|
}, timeout);
|
|
344
515
|
|
|
345
516
|
// Store pending request
|
|
@@ -513,13 +684,17 @@ var Usion = (function () {
|
|
|
513
684
|
|
|
514
685
|
/**
|
|
515
686
|
* Get current wallet balance
|
|
687
|
+
* @param {object} [opts]
|
|
688
|
+
* @param {boolean} [opts.fresh] - Bypass the cache and re-query the host.
|
|
689
|
+
* Use after out-of-band balance changes (e.g. a server-side settle).
|
|
516
690
|
* @returns {Promise<number>} Balance in credits
|
|
517
691
|
*/
|
|
518
|
-
getBalance: function() {
|
|
692
|
+
getBalance: function(opts) {
|
|
519
693
|
const self = this;
|
|
694
|
+
const fresh = !!(opts && opts.fresh);
|
|
520
695
|
|
|
521
696
|
// If we have cached balance, return it
|
|
522
|
-
if (self._balance !== null) {
|
|
697
|
+
if (!fresh && self._balance !== null) {
|
|
523
698
|
return Promise.resolve(self._balance);
|
|
524
699
|
}
|
|
525
700
|
|
|
@@ -586,11 +761,14 @@ var Usion = (function () {
|
|
|
586
761
|
settled = true;
|
|
587
762
|
cleanup();
|
|
588
763
|
// Update cached balance from the authoritative new balance, else
|
|
589
|
-
// best-effort subtract
|
|
764
|
+
// best-effort subtract now and re-query the host so the cache
|
|
765
|
+
// converges on the real value (an estimate would otherwise stick
|
|
766
|
+
// until reload).
|
|
590
767
|
if (response && response.newBalance !== undefined) {
|
|
591
768
|
self._balance = response.newBalance;
|
|
592
|
-
} else
|
|
593
|
-
self._balance -= amount;
|
|
769
|
+
} else {
|
|
770
|
+
if (self._balance !== null) self._balance -= amount;
|
|
771
|
+
self.getBalance({ fresh: true }).catch(function() { /* keep estimate */ });
|
|
594
772
|
}
|
|
595
773
|
resolve(response);
|
|
596
774
|
}
|
|
@@ -1191,9 +1369,10 @@ var Usion = (function () {
|
|
|
1191
1369
|
* Listen for messages from parent app
|
|
1192
1370
|
* @param {string} type - Message type to listen for
|
|
1193
1371
|
* @param {function} callback - Handler function
|
|
1372
|
+
* @returns {function} Unsubscribe function
|
|
1194
1373
|
*/
|
|
1195
1374
|
on: function(type, callback) {
|
|
1196
|
-
|
|
1375
|
+
function listener(event) {
|
|
1197
1376
|
if (!isTrustedMessageSource(event)) return;
|
|
1198
1377
|
|
|
1199
1378
|
let data;
|
|
@@ -1206,7 +1385,11 @@ var Usion = (function () {
|
|
|
1206
1385
|
if (data.type === type) {
|
|
1207
1386
|
callback(data);
|
|
1208
1387
|
}
|
|
1209
|
-
}
|
|
1388
|
+
}
|
|
1389
|
+
window.addEventListener('message', listener);
|
|
1390
|
+
return function() {
|
|
1391
|
+
window.removeEventListener('message', listener);
|
|
1392
|
+
};
|
|
1210
1393
|
}
|
|
1211
1394
|
};
|
|
1212
1395
|
|
|
@@ -1283,6 +1466,7 @@ var Usion = (function () {
|
|
|
1283
1466
|
return self._connectPromise;
|
|
1284
1467
|
}
|
|
1285
1468
|
|
|
1469
|
+
if (self._resConfigure) self._resConfigure(config); // liveness/backpressure opts → game._res
|
|
1286
1470
|
self._connecting = true;
|
|
1287
1471
|
self.directMode = true;
|
|
1288
1472
|
self._autoReconnect = config.autoReconnect !== undefined
|
|
@@ -1393,6 +1577,7 @@ var Usion = (function () {
|
|
|
1393
1577
|
self._sendDirect('heartbeat', {});
|
|
1394
1578
|
}
|
|
1395
1579
|
}, 25000);
|
|
1580
|
+
if (self._resOnOpen) self._resOnOpen(); // start liveness watchdog + foreground resync
|
|
1396
1581
|
resolve();
|
|
1397
1582
|
};
|
|
1398
1583
|
|
|
@@ -1404,6 +1589,7 @@ var Usion = (function () {
|
|
|
1404
1589
|
};
|
|
1405
1590
|
|
|
1406
1591
|
ws.onclose = function(evt) {
|
|
1592
|
+
if (self._resOnClose) self._resOnClose(evt); // capture close code, stop timers
|
|
1407
1593
|
self.connected = false;
|
|
1408
1594
|
self._joined = false;
|
|
1409
1595
|
self._joinPromise = null;
|
|
@@ -1419,6 +1605,7 @@ var Usion = (function () {
|
|
|
1419
1605
|
};
|
|
1420
1606
|
|
|
1421
1607
|
ws.onmessage = function(evt) {
|
|
1608
|
+
if (self._res) self._res.lastInboundAt = Date.now(); // any bytes = alive
|
|
1422
1609
|
self._handleDirectMessage(evt && evt.data);
|
|
1423
1610
|
};
|
|
1424
1611
|
});
|
|
@@ -1439,7 +1626,9 @@ var Usion = (function () {
|
|
|
1439
1626
|
if (!self.directMode) { self._reconnecting = false; return; } // disconnected meanwhile
|
|
1440
1627
|
attempt += 1;
|
|
1441
1628
|
self._reconnectAttempt = attempt;
|
|
1442
|
-
|
|
1629
|
+
// Reuse the cached room token while valid (skips the access round trip).
|
|
1630
|
+
var reuse = self._resCanReuseToken && self._resCanReuseToken();
|
|
1631
|
+
(reuse ? Promise.resolve(self.directConfig) : self._fetchDirectAccess({}))
|
|
1443
1632
|
.then(function(access) { self.directConfig = access; return self._initDirectSocket(access); })
|
|
1444
1633
|
.then(function() {
|
|
1445
1634
|
self.connected = true;
|
|
@@ -1454,11 +1643,13 @@ var Usion = (function () {
|
|
|
1454
1643
|
setTimeout(go, delay);
|
|
1455
1644
|
});
|
|
1456
1645
|
};
|
|
1457
|
-
setTimeout(go,
|
|
1646
|
+
setTimeout(go, 100); // fast first attempt; exponential backoff after
|
|
1458
1647
|
};
|
|
1459
1648
|
|
|
1460
1649
|
game._sendDirect = function(type, payload) {
|
|
1461
1650
|
if (!this.directSocket || this.directSocket.readyState !== WebSocket.OPEN) return;
|
|
1651
|
+
// Backpressure (input frames only): hold latest while the buffer is full.
|
|
1652
|
+
if (type === 'input' && this._resHoldInput && this._resHoldInput(payload)) return;
|
|
1462
1653
|
this._directSeq = this._directSeq + 1;
|
|
1463
1654
|
this.directSocket.send(JSON.stringify({
|
|
1464
1655
|
type: type,
|
|
@@ -1500,11 +1691,10 @@ var Usion = (function () {
|
|
|
1500
1691
|
return;
|
|
1501
1692
|
}
|
|
1502
1693
|
if (data.type === 'pong') {
|
|
1503
|
-
// Resolve a pending game.ping() RTT probe, if any.
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
}
|
|
1694
|
+
// Resolve a pending game.ping() RTT probe, if any; feed the stats EWMA.
|
|
1695
|
+
var waiter = (this._pongWaiters && this._pongWaiters.length) ? this._pongWaiters.shift() : null;
|
|
1696
|
+
if (this._resOnPong) this._resOnPong(waiter);
|
|
1697
|
+
if (waiter) waiter();
|
|
1508
1698
|
this._dispatch('sync', payload);
|
|
1509
1699
|
return;
|
|
1510
1700
|
}
|
|
@@ -1518,6 +1708,252 @@ var Usion = (function () {
|
|
|
1518
1708
|
};
|
|
1519
1709
|
}
|
|
1520
1710
|
|
|
1711
|
+
/**
|
|
1712
|
+
* Usion SDK Game Resilience (SDK >= 2.24) - direct-mode liveness watchdog,
|
|
1713
|
+
* token-reuse fast reconnect, input backpressure, and network stats/quality.
|
|
1714
|
+
* State lives on game._res; game-direct.js calls the small _res* hooks here.
|
|
1715
|
+
* Relay mode gets getNetworkStats()/onNetworkQuality() too (quality from the
|
|
1716
|
+
* connection-state machine; no relay RTT measurement in this module).
|
|
1717
|
+
*/
|
|
1718
|
+
|
|
1719
|
+
/** @typedef {{probeAfterMs: number, deadAfterMs: number}} LivenessCfg */
|
|
1720
|
+
|
|
1721
|
+
/** @param {any} game @param {any} Usion */
|
|
1722
|
+
function applyGameResilience(game, Usion) {
|
|
1723
|
+
var res = {
|
|
1724
|
+
liveness: /** @type {LivenessCfg|null} */ ({ probeAfterMs: 4000, deadAfterMs: 12000 }),
|
|
1725
|
+
backpressureBytes: 8192,
|
|
1726
|
+
lastInboundAt: 0,
|
|
1727
|
+
lastProbeAt: 0,
|
|
1728
|
+
lastCloseCode: /** @type {number|null} */ (null),
|
|
1729
|
+
declaredDead: false,
|
|
1730
|
+
watchdogTimer: /** @type {*} */ (null),
|
|
1731
|
+
drainTimer: /** @type {*} */ (null),
|
|
1732
|
+
pendingInput: /** @type {*} */ (null),
|
|
1733
|
+
visHandler: /** @type {*} */ (null),
|
|
1734
|
+
lastVisResyncAt: 0,
|
|
1735
|
+
wrappedDisconnect: false,
|
|
1736
|
+
rtt: /** @type {number|null} */ (null),
|
|
1737
|
+
jitter: 0,
|
|
1738
|
+
quality: 'dead',
|
|
1739
|
+
};
|
|
1740
|
+
game._res = res;
|
|
1741
|
+
|
|
1742
|
+
/** EWMA (a=0.3) over ping->pong RTT samples. @param {number} sample */
|
|
1743
|
+
function feedRtt(sample) {
|
|
1744
|
+
if (!(sample >= 0)) return;
|
|
1745
|
+
if (res.rtt == null) { res.rtt = sample; res.jitter = 0; return; }
|
|
1746
|
+
res.jitter += 0.3 * (Math.abs(sample - res.rtt) - res.jitter);
|
|
1747
|
+
res.rtt += 0.3 * (sample - res.rtt);
|
|
1748
|
+
}
|
|
1749
|
+
|
|
1750
|
+
function measuredRtt() { // game.ping() samples count too (any transport)
|
|
1751
|
+
if (res.rtt != null) return { rtt: res.rtt, jitter: res.jitter };
|
|
1752
|
+
var m = game._pingMeter;
|
|
1753
|
+
return m && m.rtt != null ? { rtt: m.rtt, jitter: m.jitter } : { rtt: null, jitter: null };
|
|
1754
|
+
}
|
|
1755
|
+
|
|
1756
|
+
function computeQuality() {
|
|
1757
|
+
var state = game.getConnectionState ? game.getConnectionState()
|
|
1758
|
+
: (game.connected ? 'connected' : 'disconnected');
|
|
1759
|
+
if (res.declaredDead || state === 'disconnected') return 'dead';
|
|
1760
|
+
if (game.directMode && (!game.directSocket || game.directSocket.readyState !== 1)) return 'dead';
|
|
1761
|
+
var rtt = measuredRtt().rtt || 0;
|
|
1762
|
+
var age = (game.directMode && res.lastInboundAt) ? Date.now() - res.lastInboundAt : 0;
|
|
1763
|
+
return (rtt < 150 && age < 2000) ? 'good' : (rtt < 400 && age < 5000) ? 'fair' : 'poor';
|
|
1764
|
+
}
|
|
1765
|
+
|
|
1766
|
+
/** Dispatches networkQuality on TRANSITIONS only. */
|
|
1767
|
+
function evaluate() {
|
|
1768
|
+
var q = computeQuality();
|
|
1769
|
+
if (q === res.quality) return;
|
|
1770
|
+
var prev = res.quality;
|
|
1771
|
+
res.quality = q;
|
|
1772
|
+
game._dispatch('networkQuality', { quality: q, prev: prev, stats: game.getNetworkStats() });
|
|
1773
|
+
}
|
|
1774
|
+
|
|
1775
|
+
/** Cheap snapshot of tracked connection-health numbers. */
|
|
1776
|
+
game.getNetworkStats = function () {
|
|
1777
|
+
var direct = !!game.directMode;
|
|
1778
|
+
var s = direct ? game.directSocket : null;
|
|
1779
|
+
var m = measuredRtt();
|
|
1780
|
+
return {
|
|
1781
|
+
transport: direct ? 'direct' : 'relay',
|
|
1782
|
+
connectionState: game.getConnectionState ? game.getConnectionState() : 'disconnected',
|
|
1783
|
+
quality: res.quality,
|
|
1784
|
+
rtt: m.rtt,
|
|
1785
|
+
jitter: m.jitter,
|
|
1786
|
+
lastInboundAgeMs: (direct && res.lastInboundAt) ? Math.max(0, Date.now() - res.lastInboundAt) : null,
|
|
1787
|
+
bufferedAmount: s ? (s.bufferedAmount || 0) : null,
|
|
1788
|
+
};
|
|
1789
|
+
};
|
|
1790
|
+
|
|
1791
|
+
/** Quality transitions ({quality, prev, stats}); returns unsubscribe. @param {Function} callback */
|
|
1792
|
+
game.onNetworkQuality = function (callback) { return game._setHandler('networkQuality', callback); };
|
|
1793
|
+
|
|
1794
|
+
function stopWatchdog() {
|
|
1795
|
+
if (res.watchdogTimer) { clearInterval(res.watchdogTimer); res.watchdogTimer = null; }
|
|
1796
|
+
}
|
|
1797
|
+
|
|
1798
|
+
/** One plain RTT ping ({t}) - never {last_sequence} (that is a resync). */
|
|
1799
|
+
function sendProbe() {
|
|
1800
|
+
var s = game.directSocket;
|
|
1801
|
+
if (!s || s.readyState !== 1) return;
|
|
1802
|
+
var now = Date.now();
|
|
1803
|
+
var w = /** @type {any} */ (function () {}); // stats-only pong waiter
|
|
1804
|
+
w.sentAt = now;
|
|
1805
|
+
w.statsOnly = true;
|
|
1806
|
+
game._pongWaiters.push(w);
|
|
1807
|
+
res.lastProbeAt = now;
|
|
1808
|
+
game._sendDirect('ping', { t: now });
|
|
1809
|
+
}
|
|
1810
|
+
|
|
1811
|
+
function watchdogTick() {
|
|
1812
|
+
var s = game.directSocket;
|
|
1813
|
+
if (!game.directMode || !s || s.readyState !== 1) { stopWatchdog(); return; }
|
|
1814
|
+
if (res.liveness) {
|
|
1815
|
+
var age = Date.now() - res.lastInboundAt;
|
|
1816
|
+
if (age >= res.liveness.deadAfterMs) {
|
|
1817
|
+
// Silent-dead: declare + close; the onclose path then reconnects.
|
|
1818
|
+
res.declaredDead = true;
|
|
1819
|
+
stopWatchdog();
|
|
1820
|
+
Usion.log('Direct socket liveness timeout - declaring dead');
|
|
1821
|
+
evaluate();
|
|
1822
|
+
game._dispatch('disconnect', 'liveness_timeout');
|
|
1823
|
+
try { s.close(); } catch (e) { /* noop */ }
|
|
1824
|
+
return;
|
|
1825
|
+
}
|
|
1826
|
+
if (age >= res.liveness.probeAfterMs
|
|
1827
|
+
&& Date.now() - res.lastProbeAt >= res.liveness.probeAfterMs) sendProbe();
|
|
1828
|
+
}
|
|
1829
|
+
evaluate();
|
|
1830
|
+
}
|
|
1831
|
+
|
|
1832
|
+
/** connectDirect(config) options -> clamped _res settings. @param {any} config */
|
|
1833
|
+
game._resConfigure = function (config) {
|
|
1834
|
+
if (config.liveness === false) {
|
|
1835
|
+
res.liveness = null;
|
|
1836
|
+
} else {
|
|
1837
|
+
var lv = (config.liveness && typeof config.liveness === 'object') ? config.liveness : {};
|
|
1838
|
+
var probe = isFinite(lv.probeAfterMs) ? Math.max(1000, lv.probeAfterMs) : 4000;
|
|
1839
|
+
var dead = isFinite(lv.deadAfterMs) ? lv.deadAfterMs : 12000;
|
|
1840
|
+
res.liveness = { probeAfterMs: probe, deadAfterMs: Math.max(dead, probe + 2000) };
|
|
1841
|
+
}
|
|
1842
|
+
if (config.backpressureBytes === false || config.backpressureBytes === 0) res.backpressureBytes = 0;
|
|
1843
|
+
else if (typeof config.backpressureBytes === 'number' && config.backpressureBytes > 0) res.backpressureBytes = config.backpressureBytes;
|
|
1844
|
+
};
|
|
1845
|
+
|
|
1846
|
+
/** Direct socket opened: reset state, start watchdog + foreground resync. */
|
|
1847
|
+
game._resOnOpen = function () {
|
|
1848
|
+
res.declaredDead = false;
|
|
1849
|
+
res.lastCloseCode = null;
|
|
1850
|
+
res.lastInboundAt = Date.now();
|
|
1851
|
+
res.lastProbeAt = 0;
|
|
1852
|
+
stopWatchdog();
|
|
1853
|
+
res.watchdogTimer = setInterval(watchdogTick, 1000);
|
|
1854
|
+
addVisibility();
|
|
1855
|
+
if (!res.wrappedDisconnect) { // clear timers even if onclose never fires
|
|
1856
|
+
res.wrappedDisconnect = true;
|
|
1857
|
+
var orig = game.disconnect;
|
|
1858
|
+
game.disconnect = function () { teardown(); return orig.apply(game, arguments); };
|
|
1859
|
+
}
|
|
1860
|
+
evaluate();
|
|
1861
|
+
};
|
|
1862
|
+
|
|
1863
|
+
/** @param {any} evt CloseEvent - code kept for the token-reuse decision. */
|
|
1864
|
+
game._resOnClose = function (evt) {
|
|
1865
|
+
res.lastCloseCode = (evt && typeof evt.code === 'number') ? evt.code : null;
|
|
1866
|
+
teardown();
|
|
1867
|
+
evaluate();
|
|
1868
|
+
};
|
|
1869
|
+
|
|
1870
|
+
/** Pong: feed the stats EWMA from the matched waiter. @param {any} waiter */
|
|
1871
|
+
game._resOnPong = function (waiter) {
|
|
1872
|
+
if (waiter && typeof waiter.sentAt === 'number') feedRtt(Date.now() - waiter.sentAt);
|
|
1873
|
+
evaluate();
|
|
1874
|
+
};
|
|
1875
|
+
|
|
1876
|
+
/** Reuse the cached room token on reconnect while safely un-expired. */
|
|
1877
|
+
game._resCanReuseToken = function () {
|
|
1878
|
+
if (res.lastCloseCode === 4401) return false; // auth reject -> refetch
|
|
1879
|
+
var cfg = game.directConfig;
|
|
1880
|
+
if (!cfg || !cfg.ws_url || !cfg.access_token) return false;
|
|
1881
|
+
var exp = parseExpiry(cfg.expires_at);
|
|
1882
|
+
return exp != null && exp - Date.now() > 30000;
|
|
1883
|
+
};
|
|
1884
|
+
|
|
1885
|
+
/**
|
|
1886
|
+
* Backpressure for realtime 'input' frames: while the send buffer is above
|
|
1887
|
+
* the threshold hold the LATEST frame only; drain when it clears.
|
|
1888
|
+
* @param {any} payload @returns {boolean} true = held, don't send now
|
|
1889
|
+
*/
|
|
1890
|
+
game._resHoldInput = function (payload) {
|
|
1891
|
+
if (!res.backpressureBytes) return false;
|
|
1892
|
+
var s = game.directSocket;
|
|
1893
|
+
if (!s || (res.pendingInput == null && !(s.bufferedAmount > res.backpressureBytes))) return false;
|
|
1894
|
+
res.pendingInput = payload; // latest-only: newer input replaces stale
|
|
1895
|
+
if (!res.drainTimer) res.drainTimer = setTimeout(drainInput, 50);
|
|
1896
|
+
return true;
|
|
1897
|
+
};
|
|
1898
|
+
|
|
1899
|
+
function drainInput() {
|
|
1900
|
+
res.drainTimer = null;
|
|
1901
|
+
var s = game.directSocket;
|
|
1902
|
+
if (!s || s.readyState !== 1) { res.pendingInput = null; return; }
|
|
1903
|
+
if (res.pendingInput == null) return;
|
|
1904
|
+
if (s.bufferedAmount > res.backpressureBytes) { res.drainTimer = setTimeout(drainInput, 50); return; }
|
|
1905
|
+
var p = res.pendingInput;
|
|
1906
|
+
res.pendingInput = null;
|
|
1907
|
+
game._sendDirect('input', p);
|
|
1908
|
+
}
|
|
1909
|
+
|
|
1910
|
+
/** Defensive expires_at parse (ISO or epoch); null = doubt -> refetch. @param {*} v */
|
|
1911
|
+
function parseExpiry(v) {
|
|
1912
|
+
if (typeof v === 'number' && isFinite(v)) return v > 1e12 ? v : v * 1000;
|
|
1913
|
+
if (typeof v === 'string' && v) {
|
|
1914
|
+
var t = Date.parse(/[zZ]|[+-]\d\d:?\d\d$/.test(v) ? v : v + 'Z'); // bare ISO = UTC
|
|
1915
|
+
return isNaN(t) ? null : t;
|
|
1916
|
+
}
|
|
1917
|
+
return null;
|
|
1918
|
+
}
|
|
1919
|
+
|
|
1920
|
+
function teardown() {
|
|
1921
|
+
stopWatchdog();
|
|
1922
|
+
if (res.drainTimer) { clearTimeout(res.drainTimer); res.drainTimer = null; }
|
|
1923
|
+
res.pendingInput = null;
|
|
1924
|
+
removeVisibility();
|
|
1925
|
+
if (game._pongWaiters && game._pongWaiters.length) {
|
|
1926
|
+
game._pongWaiters = game._pongWaiters.filter(function (/** @type {any} */ w) { return !w.statsOnly; });
|
|
1927
|
+
}
|
|
1928
|
+
}
|
|
1929
|
+
|
|
1930
|
+
/** Foreground: probe immediately + throttled requestSync. */
|
|
1931
|
+
function addVisibility() {
|
|
1932
|
+
if (typeof document === 'undefined' || !document.addEventListener || res.visHandler) return;
|
|
1933
|
+
res.visHandler = function () {
|
|
1934
|
+
if (document.visibilityState !== 'visible' || !game.directMode || !game._joined) return;
|
|
1935
|
+
sendProbe();
|
|
1936
|
+
var now = Date.now();
|
|
1937
|
+
if (now - res.lastVisResyncAt >= 2000) {
|
|
1938
|
+
res.lastVisResyncAt = now;
|
|
1939
|
+
try { game.requestSync(game._lastSequence || 0); } catch (e) { /* non-fatal */ }
|
|
1940
|
+
}
|
|
1941
|
+
};
|
|
1942
|
+
document.addEventListener('visibilitychange', res.visHandler);
|
|
1943
|
+
}
|
|
1944
|
+
|
|
1945
|
+
function removeVisibility() {
|
|
1946
|
+
if (res.visHandler && typeof document !== 'undefined' && document.removeEventListener) {
|
|
1947
|
+
document.removeEventListener('visibilitychange', res.visHandler);
|
|
1948
|
+
}
|
|
1949
|
+
res.visHandler = null;
|
|
1950
|
+
}
|
|
1951
|
+
|
|
1952
|
+
// Re-evaluate quality on connection events (covers relay mode too).
|
|
1953
|
+
game.on('disconnect', evaluate);
|
|
1954
|
+
game.on('connectionState', evaluate);
|
|
1955
|
+
}
|
|
1956
|
+
|
|
1521
1957
|
/**
|
|
1522
1958
|
* Usion SDK Game Socket — Socket.IO connection management
|
|
1523
1959
|
*/
|
|
@@ -1731,82 +2167,6 @@ var Usion = (function () {
|
|
|
1731
2167
|
};
|
|
1732
2168
|
}
|
|
1733
2169
|
|
|
1734
|
-
/**
|
|
1735
|
-
* Usion SDK Errors — stable, machine-readable error codes.
|
|
1736
|
-
*
|
|
1737
|
-
* Developers should branch on `err.code`, never on message text. Messages
|
|
1738
|
-
* are human-readable and may change; codes are part of the public API and
|
|
1739
|
-
* follow the deprecation policy (never removed within a major version).
|
|
1740
|
-
*/
|
|
1741
|
-
|
|
1742
|
-
/** @type {Record<string, string>} */
|
|
1743
|
-
const ERROR_CODES = {
|
|
1744
|
-
NOT_CONNECTED: 'NOT_CONNECTED', // No live connection for this call
|
|
1745
|
-
NO_ROOM: 'NO_ROOM', // No room id provided/known
|
|
1746
|
-
ROOM_NOT_FOUND: 'ROOM_NOT_FOUND', // Room does not exist server-side
|
|
1747
|
-
NOT_PARTICIPANT: 'NOT_PARTICIPANT', // Caller is not a player in the room
|
|
1748
|
-
NOT_AUTHORITY: 'NOT_AUTHORITY', // Authority-only call (e.g. setState)
|
|
1749
|
-
NOT_AUTHENTICATED: 'NOT_AUTHENTICATED', // Missing/invalid auth server-side
|
|
1750
|
-
JOIN_TIMEOUT: 'JOIN_TIMEOUT', // Join did not complete in time
|
|
1751
|
-
CONNECT_TIMEOUT: 'CONNECT_TIMEOUT', // Connect did not complete in time
|
|
1752
|
-
STATE_TOO_LARGE: 'STATE_TOO_LARGE', // setState payload over the quota
|
|
1753
|
-
INVALID_STATE: 'INVALID_STATE', // setState payload not a JSON object
|
|
1754
|
-
INVALID_NEXT_TURN: 'INVALID_NEXT_TURN', // nextTurn is not a player in the room
|
|
1755
|
-
RATE_LIMITED: 'RATE_LIMITED', // Too many calls; back off
|
|
1756
|
-
REQUEST_TIMEOUT: 'REQUEST_TIMEOUT', // Host/parent did not reply in time
|
|
1757
|
-
QUEUE_FULL: 'QUEUE_FULL', // Offline action queue at capacity
|
|
1758
|
-
UNSUPPORTED: 'UNSUPPORTED', // Not available in this transport
|
|
1759
|
-
UNKNOWN: 'UNKNOWN', // Unmapped error (see message)
|
|
1760
|
-
};
|
|
1761
|
-
|
|
1762
|
-
class UsionError extends Error {
|
|
1763
|
-
/**
|
|
1764
|
-
* @param {string} code - One of ERROR_CODES
|
|
1765
|
-
* @param {string} [message] - Human-readable detail (may change between versions)
|
|
1766
|
-
*/
|
|
1767
|
-
constructor(code, message) {
|
|
1768
|
-
super(message || code);
|
|
1769
|
-
this.name = 'UsionError';
|
|
1770
|
-
this.code = ERROR_CODES[code] ? code : ERROR_CODES.UNKNOWN;
|
|
1771
|
-
}
|
|
1772
|
-
}
|
|
1773
|
-
|
|
1774
|
-
// Backend error strings → stable codes. Order matters: first match wins.
|
|
1775
|
-
/** @type {Array<[RegExp, string]>} */
|
|
1776
|
-
const BACKEND_PATTERNS = [
|
|
1777
|
-
[/not authenticated/i, ERROR_CODES.NOT_AUTHENTICATED],
|
|
1778
|
-
[/room_id required|no room id/i, ERROR_CODES.NO_ROOM],
|
|
1779
|
-
[/room not found/i, ERROR_CODES.ROOM_NOT_FOUND],
|
|
1780
|
-
[/not a participant/i, ERROR_CODES.NOT_PARTICIPANT],
|
|
1781
|
-
[/room authority/i, ERROR_CODES.NOT_AUTHORITY],
|
|
1782
|
-
[/exceeds .*limit/i, ERROR_CODES.STATE_TOO_LARGE],
|
|
1783
|
-
[/state must be/i, ERROR_CODES.INVALID_STATE],
|
|
1784
|
-
[/next_turn must be/i, ERROR_CODES.INVALID_NEXT_TURN],
|
|
1785
|
-
[/rate limit|too many/i, ERROR_CODES.RATE_LIMITED],
|
|
1786
|
-
[/join timeout/i, ERROR_CODES.JOIN_TIMEOUT],
|
|
1787
|
-
[/connection timeout|connect timeout/i, ERROR_CODES.CONNECT_TIMEOUT],
|
|
1788
|
-
[/request timeout/i, ERROR_CODES.REQUEST_TIMEOUT],
|
|
1789
|
-
[/not connected/i, ERROR_CODES.NOT_CONNECTED],
|
|
1790
|
-
];
|
|
1791
|
-
|
|
1792
|
-
/**
|
|
1793
|
-
* Normalize anything (backend `{error}` string, Error, raw string) into a
|
|
1794
|
-
* UsionError with the best-matching stable code.
|
|
1795
|
-
* @param {*} err
|
|
1796
|
-
* @param {string} [fallbackCode] - Code to use when nothing matches
|
|
1797
|
-
* @returns {UsionError}
|
|
1798
|
-
*/
|
|
1799
|
-
function toUsionError(err, fallbackCode) {
|
|
1800
|
-
if (err instanceof UsionError) return err;
|
|
1801
|
-
const message = err && err.message ? err.message : String(err || 'Unknown error');
|
|
1802
|
-
for (let i = 0; i < BACKEND_PATTERNS.length; i++) {
|
|
1803
|
-
if (BACKEND_PATTERNS[i][0].test(message)) {
|
|
1804
|
-
return new UsionError(BACKEND_PATTERNS[i][1], message);
|
|
1805
|
-
}
|
|
1806
|
-
}
|
|
1807
|
-
return new UsionError(fallbackCode || ERROR_CODES.UNKNOWN, message);
|
|
1808
|
-
}
|
|
1809
|
-
|
|
1810
2170
|
/**
|
|
1811
2171
|
* Usion SDK Game Proxy — postMessage relay through parent app
|
|
1812
2172
|
*/
|
|
@@ -2055,7 +2415,7 @@ var Usion = (function () {
|
|
|
2055
2415
|
self.socket.emit('game:join', { room_id: roomId }, function(response) {
|
|
2056
2416
|
if (response.error) {
|
|
2057
2417
|
self._joined = false;
|
|
2058
|
-
reject(toUsionError(response
|
|
2418
|
+
reject(toUsionError(response));
|
|
2059
2419
|
} else {
|
|
2060
2420
|
self._joined = true;
|
|
2061
2421
|
if (response.sequence !== undefined) {
|
|
@@ -2077,6 +2437,30 @@ var Usion = (function () {
|
|
|
2077
2437
|
return self._joinPromise;
|
|
2078
2438
|
};
|
|
2079
2439
|
|
|
2440
|
+
/**
|
|
2441
|
+
* Place this player into a drop-in/drop-out WORLD room (SDK ≥ 2.23).
|
|
2442
|
+
*
|
|
2443
|
+
* World rooms (services tagged `world`) run continuously: players enter and
|
|
2444
|
+
* leave at any time instead of playing fixed matches. Placement rides the
|
|
2445
|
+
* matchmaking channel (works embedded AND standalone): the platform returns
|
|
2446
|
+
* the world you're already in, else backfills a world with space, else
|
|
2447
|
+
* creates a new one. On success `game.roomId` is set, so the usual
|
|
2448
|
+
* `connect()`+`join()` (platform relay) or `connectDirect()` (direct/hosted)
|
|
2449
|
+
* flow works unchanged afterwards. Rejects with MATCH_TIMEOUT after 15s.
|
|
2450
|
+
*
|
|
2451
|
+
* @param {object} [opts]
|
|
2452
|
+
* @param {string} [opts.serviceId] - Defaults to the current service.
|
|
2453
|
+
* @returns {Promise<{roomId: string, playerIds: string[]}>}
|
|
2454
|
+
*/
|
|
2455
|
+
game.joinWorld = function(opts) {
|
|
2456
|
+
const self = this;
|
|
2457
|
+
opts = opts || {};
|
|
2458
|
+
return Usion.matchmaking._joinWorld(opts.serviceId).then(function(m) {
|
|
2459
|
+
self.roomId = m.roomId;
|
|
2460
|
+
return { roomId: m.roomId, playerIds: m.players || [] };
|
|
2461
|
+
});
|
|
2462
|
+
};
|
|
2463
|
+
|
|
2080
2464
|
/**
|
|
2081
2465
|
* Leave the current game room
|
|
2082
2466
|
*/
|
|
@@ -2158,36 +2542,81 @@ var Usion = (function () {
|
|
|
2158
2542
|
// move can't go out before the client has resynced.
|
|
2159
2543
|
const gate = self._rejoinPromise || Promise.resolve();
|
|
2160
2544
|
return gate.then(function() {
|
|
2161
|
-
|
|
2162
|
-
if (
|
|
2163
|
-
|
|
2164
|
-
self._queueOfflineAction(actionType, actionData, opts).then(resolve, reject);
|
|
2165
|
-
return;
|
|
2166
|
-
}
|
|
2167
|
-
reject(new UsionError(ERROR_CODES.NOT_CONNECTED, 'Not connected'));
|
|
2168
|
-
return;
|
|
2545
|
+
if (!self.socket || !self.connected) {
|
|
2546
|
+
if (queueOffline) {
|
|
2547
|
+
return self._queueOfflineAction(actionType, actionData, opts);
|
|
2169
2548
|
}
|
|
2549
|
+
throw new UsionError(ERROR_CODES.NOT_CONNECTED, 'Not connected');
|
|
2550
|
+
}
|
|
2551
|
+
const payload = {
|
|
2552
|
+
room_id: self.roomId,
|
|
2553
|
+
action_type: actionType,
|
|
2554
|
+
action_data: actionData
|
|
2555
|
+
};
|
|
2556
|
+
if (nextTurn) payload.next_turn = nextTurn;
|
|
2557
|
+
return self._emitAction(payload, true);
|
|
2558
|
+
});
|
|
2559
|
+
};
|
|
2170
2560
|
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
|
|
2561
|
+
/**
|
|
2562
|
+
* @private Emit game:action and handle the ack. On NOT_IN_ROOM (the server
|
|
2563
|
+
* detected a detached socket — connected but no room membership), auto-
|
|
2564
|
+
* rejoin + resync once and retry the same action, so a move made in the
|
|
2565
|
+
* detached window is delivered instead of silently lost.
|
|
2566
|
+
*/
|
|
2567
|
+
game._emitAction = function(payload, retryOnNotInRoom) {
|
|
2568
|
+
const self = this;
|
|
2569
|
+
return new Promise(function(resolve, reject) {
|
|
2570
|
+
if (!self.socket || !self.connected) {
|
|
2571
|
+
reject(new UsionError(ERROR_CODES.NOT_CONNECTED, 'Not connected'));
|
|
2572
|
+
return;
|
|
2573
|
+
}
|
|
2574
|
+
self.socket.emit('game:action', payload, function(response) {
|
|
2575
|
+
if (response && response.error) {
|
|
2576
|
+
const ue = toUsionError(response);
|
|
2577
|
+
if (retryOnNotInRoom && ue.code === ERROR_CODES.NOT_IN_ROOM) {
|
|
2578
|
+
self._autoRejoin()
|
|
2579
|
+
.then(function() { return self._emitAction(payload, false); })
|
|
2580
|
+
.then(resolve, reject);
|
|
2581
|
+
return;
|
|
2185
2582
|
}
|
|
2186
|
-
|
|
2583
|
+
reject(ue);
|
|
2584
|
+
} else {
|
|
2585
|
+
if (response && response.sequence !== undefined) {
|
|
2586
|
+
self._lastSequence = response.sequence;
|
|
2587
|
+
}
|
|
2588
|
+
resolve(response);
|
|
2589
|
+
}
|
|
2187
2590
|
});
|
|
2188
2591
|
});
|
|
2189
2592
|
};
|
|
2190
2593
|
|
|
2594
|
+
/**
|
|
2595
|
+
* @private Recover a detached socket: the server said we're not in the
|
|
2596
|
+
* Socket.IO room (NOT_IN_ROOM), so rejoin + resync exactly like the
|
|
2597
|
+
* post-reconnect path, gating action() sends on _rejoinPromise meanwhile.
|
|
2598
|
+
*/
|
|
2599
|
+
game._autoRejoin = function() {
|
|
2600
|
+
const self = this;
|
|
2601
|
+
if (self._rejoinPromise) return self._rejoinPromise;
|
|
2602
|
+
if (!self.roomId || !self.socket || !self.connected) return Promise.resolve();
|
|
2603
|
+
Usion.log('Server reports socket not in room - auto-rejoining ' + self.roomId);
|
|
2604
|
+
self._joined = false;
|
|
2605
|
+
self._joinPromise = null;
|
|
2606
|
+
self._rejoinPromise = self.join(self.roomId)
|
|
2607
|
+
.then(function() {
|
|
2608
|
+
self.requestSync(self._lastSequence || 0);
|
|
2609
|
+
})
|
|
2610
|
+
.catch(function(err) {
|
|
2611
|
+
Usion.log('Auto-rejoin failed: ' + (err && err.message ? err.message : String(err)));
|
|
2612
|
+
})
|
|
2613
|
+
.then(function() {
|
|
2614
|
+
self._rejoinPromise = null;
|
|
2615
|
+
if (self._flushOfflineQueue) self._flushOfflineQueue();
|
|
2616
|
+
});
|
|
2617
|
+
return self._rejoinPromise;
|
|
2618
|
+
};
|
|
2619
|
+
|
|
2191
2620
|
// ── Offline action queue (opt-in via action(..., { queueOffline: true })) ──
|
|
2192
2621
|
|
|
2193
2622
|
const OFFLINE_QUEUE_MAX = 20;
|
|
@@ -2262,11 +2691,17 @@ var Usion = (function () {
|
|
|
2262
2691
|
return Promise.resolve({ success: false, error: 'not_supported_in_direct_mode', code: ERROR_CODES.UNSUPPORTED });
|
|
2263
2692
|
}
|
|
2264
2693
|
|
|
2694
|
+
// The checkpoint carries the action sequence this state reflects. The
|
|
2695
|
+
// server persists it and rejects OLDER checkpoints (STALE_STATE), so two
|
|
2696
|
+
// concurrent writers can't clobber newer state with older.
|
|
2697
|
+
const checkpointSeq = self._lastSequence || 0;
|
|
2698
|
+
|
|
2265
2699
|
if (self._useProxy) {
|
|
2266
|
-
return Usion._request('GAME_SET_STATE', { room_id: self.roomId, state: state || {} })
|
|
2700
|
+
return Usion._request('GAME_SET_STATE', { room_id: self.roomId, state: state || {}, sequence: checkpointSeq })
|
|
2267
2701
|
.then(function(res) {
|
|
2268
2702
|
if (res && res.error) {
|
|
2269
|
-
|
|
2703
|
+
const rue = toUsionError(res);
|
|
2704
|
+
return { success: false, error: rue.message, code: rue.code };
|
|
2270
2705
|
}
|
|
2271
2706
|
return res || { success: true };
|
|
2272
2707
|
})
|
|
@@ -2283,10 +2718,12 @@ var Usion = (function () {
|
|
|
2283
2718
|
}
|
|
2284
2719
|
self.socket.emit('game:set_state', {
|
|
2285
2720
|
room_id: self.roomId,
|
|
2286
|
-
state: state || {}
|
|
2721
|
+
state: state || {},
|
|
2722
|
+
sequence: checkpointSeq
|
|
2287
2723
|
}, function(response) {
|
|
2288
2724
|
if (response && response.error) {
|
|
2289
|
-
|
|
2725
|
+
const ue = toUsionError(response);
|
|
2726
|
+
resolve({ success: false, error: ue.message, code: ue.code });
|
|
2290
2727
|
} else {
|
|
2291
2728
|
resolve(response || { success: true });
|
|
2292
2729
|
}
|
|
@@ -2319,10 +2756,18 @@ var Usion = (function () {
|
|
|
2319
2756
|
return;
|
|
2320
2757
|
}
|
|
2321
2758
|
|
|
2759
|
+
// Still fire-and-forget for the game, but the server now acks failures
|
|
2760
|
+
// (previously dropped silently): surface them via onError, and on
|
|
2761
|
+
// NOT_IN_ROOM (detached socket) auto-rejoin so the stream recovers.
|
|
2322
2762
|
self.socket.emit('game:realtime', {
|
|
2323
2763
|
room_id: self.roomId,
|
|
2324
2764
|
action_type: actionType,
|
|
2325
2765
|
action_data: actionData
|
|
2766
|
+
}, function(response) {
|
|
2767
|
+
if (!response || !response.error) return;
|
|
2768
|
+
const ue = toUsionError(response);
|
|
2769
|
+
self._dispatch('error', { code: ue.code, message: ue.message, source: 'realtime' });
|
|
2770
|
+
if (ue.code === ERROR_CODES.NOT_IN_ROOM) self._autoRejoin();
|
|
2326
2771
|
});
|
|
2327
2772
|
};
|
|
2328
2773
|
|
|
@@ -2398,7 +2843,7 @@ var Usion = (function () {
|
|
|
2398
2843
|
|
|
2399
2844
|
self.socket.emit('game:forfeit', { room_id: self.roomId }, function(response) {
|
|
2400
2845
|
if (response.error) {
|
|
2401
|
-
reject(toUsionError(response
|
|
2846
|
+
reject(toUsionError(response));
|
|
2402
2847
|
} else {
|
|
2403
2848
|
resolve(response);
|
|
2404
2849
|
}
|
|
@@ -4305,6 +4750,234 @@ var Usion = (function () {
|
|
|
4305
4750
|
return reader(bytes)();
|
|
4306
4751
|
}
|
|
4307
4752
|
|
|
4753
|
+
/**
|
|
4754
|
+
* Usion SDK Netcode — Interest grid (area-of-interest spatial hash).
|
|
4755
|
+
*
|
|
4756
|
+
* Buckets entities into fixed-size cells so "who is near (x, y)?" costs a few
|
|
4757
|
+
* cell lookups instead of an O(N) scan — the building block for world rooms
|
|
4758
|
+
* where each client should only receive nearby state (AOI filtering). Pure
|
|
4759
|
+
* JS, no DOM/window references: the same helper runs in the browser and in a
|
|
4760
|
+
* Node game server producing per-player snapshots.
|
|
4761
|
+
*
|
|
4762
|
+
* const grid = Usion.netcode.createInterestGrid({ cellSize: 256 });
|
|
4763
|
+
* grid.upsert('p1', 120, 40); // insert or move
|
|
4764
|
+
* grid.query(0, 0, 300); // → ids within 300 units (circle)
|
|
4765
|
+
* const { entered, left, visible } = grid.observe('p1', 120, 40, 500);
|
|
4766
|
+
* // entered → spawn for this observer; left → despawn (diffed per observer)
|
|
4767
|
+
*/
|
|
4768
|
+
|
|
4769
|
+
/** @typedef {string|number} InterestGridId */
|
|
4770
|
+
|
|
4771
|
+
/**
|
|
4772
|
+
* @param {*} id
|
|
4773
|
+
* @param {string} method
|
|
4774
|
+
* @returns {InterestGridId}
|
|
4775
|
+
*/
|
|
4776
|
+
function checkId(id, method) {
|
|
4777
|
+
const ok = (typeof id === 'string' && id.length > 0)
|
|
4778
|
+
|| (typeof id === 'number' && isFinite(id));
|
|
4779
|
+
if (!ok) {
|
|
4780
|
+
throw new Error('interestGrid.' + method + ': id must be a non-empty string or a finite number');
|
|
4781
|
+
}
|
|
4782
|
+
return id;
|
|
4783
|
+
}
|
|
4784
|
+
|
|
4785
|
+
/**
|
|
4786
|
+
* @param {*} value
|
|
4787
|
+
* @param {string} name
|
|
4788
|
+
* @param {string} method
|
|
4789
|
+
* @returns {number}
|
|
4790
|
+
*/
|
|
4791
|
+
function checkFinite(value, name, method) {
|
|
4792
|
+
if (typeof value !== 'number' || !isFinite(value)) {
|
|
4793
|
+
throw new Error('interestGrid.' + method + ': ' + name + ' must be a finite number');
|
|
4794
|
+
}
|
|
4795
|
+
return value;
|
|
4796
|
+
}
|
|
4797
|
+
|
|
4798
|
+
/**
|
|
4799
|
+
* @param {*} value
|
|
4800
|
+
* @param {string} method
|
|
4801
|
+
* @returns {number}
|
|
4802
|
+
*/
|
|
4803
|
+
function checkRadius(value, method) {
|
|
4804
|
+
checkFinite(value, 'radius', method);
|
|
4805
|
+
if (value < 0) throw new Error('interestGrid.' + method + ': radius must be >= 0');
|
|
4806
|
+
return value;
|
|
4807
|
+
}
|
|
4808
|
+
|
|
4809
|
+
/**
|
|
4810
|
+
* Create an interest grid.
|
|
4811
|
+
* @param {{cellSize?: number}} [opts] - cellSize (world units) defaults to 256;
|
|
4812
|
+
* pick roughly the typical query radius so lookups touch ~4–9 cells.
|
|
4813
|
+
*/
|
|
4814
|
+
function createInterestGrid(opts) {
|
|
4815
|
+
opts = opts || {};
|
|
4816
|
+
const cellSize = opts.cellSize != null ? opts.cellSize : 256;
|
|
4817
|
+
if (typeof cellSize !== 'number' || !isFinite(cellSize) || cellSize <= 0) {
|
|
4818
|
+
throw new Error('createInterestGrid: cellSize must be a finite number > 0');
|
|
4819
|
+
}
|
|
4820
|
+
|
|
4821
|
+
/** @type {Map<InterestGridId, {x: number, y: number, key: string}>} */
|
|
4822
|
+
const entities = new Map();
|
|
4823
|
+
/** @type {Map<string, Set<InterestGridId>>} */
|
|
4824
|
+
const cells = new Map();
|
|
4825
|
+
// Per-observer visible sets. `prev`/`next` are swapped (never reallocated)
|
|
4826
|
+
// each observe() call — this runs per tick per observer.
|
|
4827
|
+
/** @type {Map<InterestGridId, {prev: Set<InterestGridId>, next: Set<InterestGridId>}>} */
|
|
4828
|
+
const observers = new Map();
|
|
4829
|
+
|
|
4830
|
+
/** @param {string} key @param {InterestGridId} id */
|
|
4831
|
+
function addToCell(key, id) {
|
|
4832
|
+
let set = cells.get(key);
|
|
4833
|
+
if (!set) { set = new Set(); cells.set(key, set); }
|
|
4834
|
+
set.add(id);
|
|
4835
|
+
}
|
|
4836
|
+
|
|
4837
|
+
/** @param {string} key @param {InterestGridId} id */
|
|
4838
|
+
function removeFromCell(key, id) {
|
|
4839
|
+
const set = cells.get(key);
|
|
4840
|
+
if (!set) return;
|
|
4841
|
+
set.delete(id);
|
|
4842
|
+
if (set.size === 0) cells.delete(key);
|
|
4843
|
+
}
|
|
4844
|
+
|
|
4845
|
+
/**
|
|
4846
|
+
* Visit every entity within `radius` of (x, y): scan the cells the circle's
|
|
4847
|
+
* bounding box overlaps, then apply a true circle test per entity.
|
|
4848
|
+
* @param {number} x @param {number} y @param {number} radius
|
|
4849
|
+
* @param {(id: InterestGridId) => void} visit
|
|
4850
|
+
*/
|
|
4851
|
+
function forEachInRadius(x, y, radius, visit) {
|
|
4852
|
+
const r2 = radius * radius;
|
|
4853
|
+
const minCx = Math.floor((x - radius) / cellSize);
|
|
4854
|
+
const maxCx = Math.floor((x + radius) / cellSize);
|
|
4855
|
+
const minCy = Math.floor((y - radius) / cellSize);
|
|
4856
|
+
const maxCy = Math.floor((y + radius) / cellSize);
|
|
4857
|
+
for (let cx = minCx; cx <= maxCx; cx++) {
|
|
4858
|
+
for (let cy = minCy; cy <= maxCy; cy++) {
|
|
4859
|
+
const set = cells.get(cx + ',' + cy);
|
|
4860
|
+
if (!set) continue;
|
|
4861
|
+
for (const id of set) {
|
|
4862
|
+
const ent = entities.get(id);
|
|
4863
|
+
if (!ent) continue;
|
|
4864
|
+
const dx = ent.x - x;
|
|
4865
|
+
const dy = ent.y - y;
|
|
4866
|
+
if (dx * dx + dy * dy <= r2) visit(id);
|
|
4867
|
+
}
|
|
4868
|
+
}
|
|
4869
|
+
}
|
|
4870
|
+
}
|
|
4871
|
+
|
|
4872
|
+
return {
|
|
4873
|
+
/**
|
|
4874
|
+
* Insert an entity or move an existing one.
|
|
4875
|
+
* @param {InterestGridId} id @param {number} x @param {number} y
|
|
4876
|
+
*/
|
|
4877
|
+
upsert: function (id, x, y) {
|
|
4878
|
+
checkId(id, 'upsert');
|
|
4879
|
+
checkFinite(x, 'x', 'upsert');
|
|
4880
|
+
checkFinite(y, 'y', 'upsert');
|
|
4881
|
+
const key = Math.floor(x / cellSize) + ',' + Math.floor(y / cellSize);
|
|
4882
|
+
const ent = entities.get(id);
|
|
4883
|
+
if (ent) {
|
|
4884
|
+
ent.x = x;
|
|
4885
|
+
ent.y = y;
|
|
4886
|
+
if (ent.key !== key) {
|
|
4887
|
+
removeFromCell(ent.key, id);
|
|
4888
|
+
addToCell(key, id);
|
|
4889
|
+
ent.key = key;
|
|
4890
|
+
}
|
|
4891
|
+
return;
|
|
4892
|
+
}
|
|
4893
|
+
entities.set(id, { x: x, y: y, key: key });
|
|
4894
|
+
addToCell(key, id);
|
|
4895
|
+
},
|
|
4896
|
+
|
|
4897
|
+
/**
|
|
4898
|
+
* Remove an entity. Unknown ids are a no-op.
|
|
4899
|
+
* @param {InterestGridId} id
|
|
4900
|
+
*/
|
|
4901
|
+
remove: function (id) {
|
|
4902
|
+
checkId(id, 'remove');
|
|
4903
|
+
const ent = entities.get(id);
|
|
4904
|
+
if (!ent) return;
|
|
4905
|
+
entities.delete(id);
|
|
4906
|
+
removeFromCell(ent.key, id);
|
|
4907
|
+
},
|
|
4908
|
+
|
|
4909
|
+
/**
|
|
4910
|
+
* All entity ids within `radius` of (x, y) — a circle test, not just
|
|
4911
|
+
* cell membership.
|
|
4912
|
+
* @param {number} x @param {number} y @param {number} radius
|
|
4913
|
+
* @returns {InterestGridId[]}
|
|
4914
|
+
*/
|
|
4915
|
+
query: function (x, y, radius) {
|
|
4916
|
+
checkFinite(x, 'x', 'query');
|
|
4917
|
+
checkFinite(y, 'y', 'query');
|
|
4918
|
+
checkRadius(radius, 'query');
|
|
4919
|
+
/** @type {InterestGridId[]} */
|
|
4920
|
+
const out = [];
|
|
4921
|
+
forEachInRadius(x, y, radius, function (id) { out.push(id); });
|
|
4922
|
+
return out;
|
|
4923
|
+
},
|
|
4924
|
+
|
|
4925
|
+
/**
|
|
4926
|
+
* Like query(), but diffed against this observer's previous observe():
|
|
4927
|
+
* `entered` are ids newly visible, `left` are ids no longer visible,
|
|
4928
|
+
* `visible` is the full current set. Drive spawn/despawn messages from
|
|
4929
|
+
* entered/left and per-tick snapshots from visible.
|
|
4930
|
+
* @param {InterestGridId} observerId @param {number} x @param {number} y @param {number} radius
|
|
4931
|
+
* @returns {{entered: InterestGridId[], left: InterestGridId[], visible: InterestGridId[]}}
|
|
4932
|
+
*/
|
|
4933
|
+
observe: function (observerId, x, y, radius) {
|
|
4934
|
+
checkId(observerId, 'observe');
|
|
4935
|
+
checkFinite(x, 'x', 'observe');
|
|
4936
|
+
checkFinite(y, 'y', 'observe');
|
|
4937
|
+
checkRadius(radius, 'observe');
|
|
4938
|
+
let tracker = observers.get(observerId);
|
|
4939
|
+
if (!tracker) {
|
|
4940
|
+
tracker = { prev: new Set(), next: new Set() };
|
|
4941
|
+
observers.set(observerId, tracker);
|
|
4942
|
+
}
|
|
4943
|
+
const prev = tracker.prev;
|
|
4944
|
+
const next = tracker.next;
|
|
4945
|
+
next.clear();
|
|
4946
|
+
/** @type {InterestGridId[]} */
|
|
4947
|
+
const entered = [];
|
|
4948
|
+
/** @type {InterestGridId[]} */
|
|
4949
|
+
const left = [];
|
|
4950
|
+
/** @type {InterestGridId[]} */
|
|
4951
|
+
const visible = [];
|
|
4952
|
+
forEachInRadius(x, y, radius, function (id) {
|
|
4953
|
+
next.add(id);
|
|
4954
|
+
visible.push(id);
|
|
4955
|
+
if (!prev.has(id)) entered.push(id);
|
|
4956
|
+
});
|
|
4957
|
+
for (const id of prev) {
|
|
4958
|
+
if (!next.has(id)) left.push(id);
|
|
4959
|
+
}
|
|
4960
|
+
tracker.prev = next;
|
|
4961
|
+
tracker.next = prev; // reused as scratch on the next call
|
|
4962
|
+
return { entered: entered, left: left, visible: visible };
|
|
4963
|
+
},
|
|
4964
|
+
|
|
4965
|
+
/**
|
|
4966
|
+
* Free an observer's tracking state (call when a player leaves).
|
|
4967
|
+
* @param {InterestGridId} observerId
|
|
4968
|
+
*/
|
|
4969
|
+
dropObserver: function (observerId) {
|
|
4970
|
+
checkId(observerId, 'dropObserver');
|
|
4971
|
+
observers.delete(observerId);
|
|
4972
|
+
},
|
|
4973
|
+
|
|
4974
|
+
/** @returns {number} Number of entities in the grid. */
|
|
4975
|
+
size: function () {
|
|
4976
|
+
return entities.size;
|
|
4977
|
+
},
|
|
4978
|
+
};
|
|
4979
|
+
}
|
|
4980
|
+
|
|
4308
4981
|
/**
|
|
4309
4982
|
* Usion SDK Game Netcode — convenience wiring of the netcode toolkit onto the
|
|
4310
4983
|
* game module. These helpers ride on the existing realtime/action channels, so
|
|
@@ -4323,6 +4996,7 @@ var Usion = (function () {
|
|
|
4323
4996
|
game.createPredictor = function (opts) { return new Predictor(opts || {}); };
|
|
4324
4997
|
game.createLagCompensator = function (opts) { return new LagCompensator(opts || {}); };
|
|
4325
4998
|
game.createLockstep = function (opts) { return new Lockstep(opts || {}); };
|
|
4999
|
+
game.createInterestGrid = function (opts) { return createInterestGrid(opts || {}); };
|
|
4326
5000
|
|
|
4327
5001
|
// ── Realtime channel router ──────────────────────────────────────────────
|
|
4328
5002
|
// Multiplexes realtime by action_type so replicate / mesh / mesh-network and
|
|
@@ -4608,6 +5282,7 @@ var Usion = (function () {
|
|
|
4608
5282
|
const id = self._pingMeter.begin();
|
|
4609
5283
|
let done = false;
|
|
4610
5284
|
const finish = function () { if (done) return; done = true; resolve(self._pingMeter.end(id)); };
|
|
5285
|
+
finish.sentAt = Date.now(); // lets the pong pair feed getNetworkStats' EWMA too
|
|
4611
5286
|
self._pongWaiters.push(finish);
|
|
4612
5287
|
self._sendDirect('ping', { t: Date.now() });
|
|
4613
5288
|
setTimeout(function () {
|
|
@@ -4946,6 +5621,7 @@ var Usion = (function () {
|
|
|
4946
5621
|
room_assigned: 'roomAssigned',
|
|
4947
5622
|
connection_state: 'connectionState',
|
|
4948
5623
|
reconnected: 'reconnected',
|
|
5624
|
+
network_quality: 'networkQuality',
|
|
4949
5625
|
};
|
|
4950
5626
|
|
|
4951
5627
|
function _normalizeEventName(event) {
|
|
@@ -5041,26 +5717,31 @@ var Usion = (function () {
|
|
|
5041
5717
|
self._connectPromise = new Promise(function(resolve, reject) {
|
|
5042
5718
|
// Check if socket.io-client is available
|
|
5043
5719
|
if (typeof io === 'undefined') {
|
|
5044
|
-
// Load
|
|
5045
|
-
|
|
5046
|
-
|
|
5047
|
-
|
|
5048
|
-
|
|
5049
|
-
|
|
5050
|
-
|
|
5051
|
-
|
|
5052
|
-
|
|
5053
|
-
|
|
5054
|
-
|
|
5055
|
-
self._initSocket(socketUrl, token, resolve, reject);
|
|
5056
|
-
};
|
|
5057
|
-
cdnScript.onerror = function() {
|
|
5720
|
+
// Load the Socket.IO client: same-origin copy first, then the
|
|
5721
|
+
// platform-hosted copy (same origin as the SDK itself — reachable
|
|
5722
|
+
// wherever the app is), and only then the public CDN, which
|
|
5723
|
+
// restricted networks often block.
|
|
5724
|
+
var sources = [
|
|
5725
|
+
'/socket.io.min.js',
|
|
5726
|
+
'https://usions.com/socket.io.min.js',
|
|
5727
|
+
'https://cdn.socket.io/4.7.2/socket.io.min.js'
|
|
5728
|
+
];
|
|
5729
|
+
(function tryLoad(i) {
|
|
5730
|
+
if (i >= sources.length) {
|
|
5058
5731
|
self._connecting = false;
|
|
5059
5732
|
reject(new Error('Failed to load Socket.IO client'));
|
|
5733
|
+
return;
|
|
5734
|
+
}
|
|
5735
|
+
var script = document.createElement('script');
|
|
5736
|
+
script.src = sources[i];
|
|
5737
|
+
script.onload = function() {
|
|
5738
|
+
self._initSocket(socketUrl, token, resolve, reject);
|
|
5739
|
+
};
|
|
5740
|
+
script.onerror = function() {
|
|
5741
|
+
tryLoad(i + 1);
|
|
5060
5742
|
};
|
|
5061
|
-
document.head.appendChild(
|
|
5062
|
-
};
|
|
5063
|
-
document.head.appendChild(script);
|
|
5743
|
+
document.head.appendChild(script);
|
|
5744
|
+
})(0);
|
|
5064
5745
|
} else {
|
|
5065
5746
|
self._initSocket(socketUrl, token, resolve, reject);
|
|
5066
5747
|
}
|
|
@@ -5155,6 +5836,8 @@ var Usion = (function () {
|
|
|
5155
5836
|
|
|
5156
5837
|
// Apply sub-modules
|
|
5157
5838
|
applyGameDirect(game, Usion);
|
|
5839
|
+
// Direct-mode liveness/backpressure + network stats (hooks into game-direct).
|
|
5840
|
+
applyGameResilience(game, Usion);
|
|
5158
5841
|
applyGameSocket(game, Usion);
|
|
5159
5842
|
applyGameProxy(game, Usion);
|
|
5160
5843
|
applyGameMethods(game, Usion);
|
|
@@ -5411,12 +6094,18 @@ var Usion = (function () {
|
|
|
5411
6094
|
*
|
|
5412
6095
|
* const m = await Usion.matchmaking.find(); // resolves when matched
|
|
5413
6096
|
* await Usion.game.connect(); await Usion.game.join(m.roomId);
|
|
5414
|
-
* // ...or cancel while waiting:
|
|
6097
|
+
* // ...or bound the wait / cancel while waiting:
|
|
6098
|
+
* const m2 = await Usion.matchmaking.find(null, { timeout: 30000 });
|
|
5415
6099
|
* Usion.matchmaking.cancel();
|
|
5416
6100
|
* Usion.matchmaking.onMatch(({ roomId, players }) => { ... });
|
|
5417
6101
|
*/
|
|
6102
|
+
|
|
6103
|
+
// World placement is a single backend round-trip (no queue wait), so the
|
|
6104
|
+
// bound is fixed rather than caller-supplied like find()'s opts.timeout.
|
|
6105
|
+
const WORLD_JOIN_TIMEOUT_MS = 15000;
|
|
6106
|
+
|
|
5418
6107
|
function createMatchmakingModule(Usion) {
|
|
5419
|
-
let pending = null; // { resolve, reject }
|
|
6108
|
+
let pending = null; // active placement entry: { resolve, reject }
|
|
5420
6109
|
let onMatchCb = null;
|
|
5421
6110
|
let bound = false;
|
|
5422
6111
|
|
|
@@ -5434,30 +6123,103 @@ var Usion = (function () {
|
|
|
5434
6123
|
});
|
|
5435
6124
|
}
|
|
5436
6125
|
|
|
6126
|
+
/**
|
|
6127
|
+
* Shared mm-channel placement used by find() (queue matches) and
|
|
6128
|
+
* game.joinWorld() (world backfill): register the resolver, bound the wait,
|
|
6129
|
+
* emit mm:join, and resolve from the immediate-placement ack
|
|
6130
|
+
* ({queued:false, matched:true, room_id, player_ids}) or the mm:matched
|
|
6131
|
+
* push — whichever arrives first.
|
|
6132
|
+
* @param {object} payload - mm:join payload
|
|
6133
|
+
* @param {number} [timeout] - ms until MATCH_TIMEOUT (falsy = wait forever)
|
|
6134
|
+
* @param {string} timeoutMessage
|
|
6135
|
+
*/
|
|
6136
|
+
function place(payload, timeout, timeoutMessage) {
|
|
6137
|
+
bind();
|
|
6138
|
+
|
|
6139
|
+
if (pending) {
|
|
6140
|
+
const old = pending; pending = null;
|
|
6141
|
+
old.reject(new UsionError(ERROR_CODES.SUPERSEDED, 'Superseded by a newer find()'));
|
|
6142
|
+
}
|
|
6143
|
+
|
|
6144
|
+
let timer = null;
|
|
6145
|
+
const entry = {};
|
|
6146
|
+
const promise = new Promise(function (resolve, reject) {
|
|
6147
|
+
entry.resolve = function (r) {
|
|
6148
|
+
if (timer) clearTimeout(timer);
|
|
6149
|
+
resolve(r);
|
|
6150
|
+
};
|
|
6151
|
+
entry.reject = function (e) {
|
|
6152
|
+
if (timer) clearTimeout(timer);
|
|
6153
|
+
if (pending === entry) pending = null;
|
|
6154
|
+
reject(e);
|
|
6155
|
+
};
|
|
6156
|
+
});
|
|
6157
|
+
|
|
6158
|
+
// Register BEFORE emitting mm:join: when someone is already waiting in
|
|
6159
|
+
// the queue, mm:matched can arrive ahead of the join ack — registering
|
|
6160
|
+
// afterwards dropped that instant match and left find() hanging forever.
|
|
6161
|
+
pending = entry;
|
|
6162
|
+
|
|
6163
|
+
if (timeout > 0) {
|
|
6164
|
+
timer = setTimeout(function () {
|
|
6165
|
+
timer = null;
|
|
6166
|
+
Usion._backendEmit('mm:cancel', {}).catch(function () { /* best-effort dequeue */ });
|
|
6167
|
+
entry.reject(new UsionError(ERROR_CODES.MATCH_TIMEOUT,
|
|
6168
|
+
timeoutMessage + timeout + 'ms'));
|
|
6169
|
+
}, timeout);
|
|
6170
|
+
}
|
|
6171
|
+
|
|
6172
|
+
Usion._backendEmit('mm:join', payload)
|
|
6173
|
+
.then(function (ack) {
|
|
6174
|
+
// Immediate placement (world rooms): the ack itself carries the room.
|
|
6175
|
+
// The mm:matched push may still follow; pending is already cleared,
|
|
6176
|
+
// so it can't double-resolve.
|
|
6177
|
+
if (ack && ack.matched && ack.room_id && pending === entry) {
|
|
6178
|
+
pending = null;
|
|
6179
|
+
entry.resolve(normalize(ack));
|
|
6180
|
+
}
|
|
6181
|
+
})
|
|
6182
|
+
.catch(function (err) {
|
|
6183
|
+
if (pending === entry) entry.reject(toUsionError(err));
|
|
6184
|
+
});
|
|
6185
|
+
|
|
6186
|
+
return promise;
|
|
6187
|
+
}
|
|
6188
|
+
|
|
5437
6189
|
return {
|
|
5438
6190
|
/** Register a handler called whenever a match is found. */
|
|
5439
6191
|
onMatch: function (cb) { onMatchCb = cb; bind(); },
|
|
5440
6192
|
|
|
5441
6193
|
/**
|
|
5442
6194
|
* Join the queue for `serviceId` (defaults to the current game) and resolve
|
|
5443
|
-
* when matched with { roomId, players, serviceId }.
|
|
5444
|
-
* match (use cancel() to stop waiting)
|
|
6195
|
+
* when matched with { roomId, players, serviceId }. Without `opts.timeout`
|
|
6196
|
+
* it stays pending until a match (use cancel() to stop waiting); with it,
|
|
6197
|
+
* rejects MATCH_TIMEOUT (and leaves the queue) once the wait elapses.
|
|
6198
|
+
* @param {string} [serviceId]
|
|
6199
|
+
* @param {{size?: number, timeout?: number}} [opts]
|
|
5445
6200
|
*/
|
|
5446
6201
|
find: function (serviceId, opts) {
|
|
5447
6202
|
opts = opts || {};
|
|
5448
6203
|
const sid = serviceId || (Usion.config && Usion.config.serviceId);
|
|
5449
|
-
|
|
5450
|
-
|
|
5451
|
-
|
|
5452
|
-
|
|
5453
|
-
|
|
5454
|
-
|
|
5455
|
-
|
|
6204
|
+
return place({ service_id: sid, size: opts.size || 2 }, opts.timeout, 'No match within ');
|
|
6205
|
+
},
|
|
6206
|
+
|
|
6207
|
+
/**
|
|
6208
|
+
* @private SDK-internal — use Usion.game.joinWorld(). Immediate placement
|
|
6209
|
+
* into a drop-in/drop-out world room over the same mm channel.
|
|
6210
|
+
* @param {string} [serviceId]
|
|
6211
|
+
*/
|
|
6212
|
+
_joinWorld: function (serviceId) {
|
|
6213
|
+
const sid = serviceId || (Usion.config && Usion.config.serviceId);
|
|
6214
|
+
return place({ service_id: sid, mode: 'world' }, WORLD_JOIN_TIMEOUT_MS, 'No world placement within ');
|
|
5456
6215
|
},
|
|
5457
6216
|
|
|
5458
6217
|
/** Leave the queue / stop waiting. */
|
|
5459
6218
|
cancel: function () {
|
|
5460
|
-
if (pending) {
|
|
6219
|
+
if (pending) {
|
|
6220
|
+
const old = pending; pending = null;
|
|
6221
|
+
old.reject(new UsionError(ERROR_CODES.CANCELLED, 'cancelled'));
|
|
6222
|
+
}
|
|
5461
6223
|
return Usion._backendEmit('mm:cancel', {});
|
|
5462
6224
|
},
|
|
5463
6225
|
};
|
|
@@ -5707,6 +6469,7 @@ var Usion = (function () {
|
|
|
5707
6469
|
* safe, namespaced allow-list (e.g. lobby:* / mm:*) so a mini-app can't abuse
|
|
5708
6470
|
* the user's authenticated connection. The backend re-validates every call.
|
|
5709
6471
|
*/
|
|
6472
|
+
|
|
5710
6473
|
function applyBackendChannel(Usion) {
|
|
5711
6474
|
Usion._backendHandlers = {};
|
|
5712
6475
|
Usion._boundSockets = typeof WeakSet !== 'undefined' ? new WeakSet() : null;
|
|
@@ -5741,30 +6504,61 @@ var Usion = (function () {
|
|
|
5741
6504
|
/**
|
|
5742
6505
|
* Emit a backend request and await its ack. Routes to the SDK socket when
|
|
5743
6506
|
* standalone, or through the parent host when embedded.
|
|
6507
|
+
* Standalone apps that never call Usion.game.connect() (e.g. a non-game
|
|
6508
|
+
* app using cloud/leaderboard/notify) get an automatic one-time connect —
|
|
6509
|
+
* the backend channel is not coupled to starting a game.
|
|
6510
|
+
* Rejections are always UsionError (stable `code`, plus `retryAfter` on
|
|
6511
|
+
* RATE_LIMITED), regardless of transport.
|
|
5744
6512
|
* @returns {Promise<any>}
|
|
5745
6513
|
*/
|
|
5746
6514
|
Usion._backendEmit = function (event, data, timeout) {
|
|
5747
6515
|
const self = this;
|
|
5748
6516
|
timeout = timeout || 8000;
|
|
5749
|
-
|
|
5750
|
-
|
|
6517
|
+
|
|
6518
|
+
function emitOn(sock) {
|
|
5751
6519
|
return new Promise(function (resolve, reject) {
|
|
5752
6520
|
let done = false;
|
|
5753
|
-
const timer = setTimeout(function () {
|
|
6521
|
+
const timer = setTimeout(function () {
|
|
6522
|
+
if (done) return; done = true;
|
|
6523
|
+
reject(new UsionError(ERROR_CODES.REQUEST_TIMEOUT, 'Backend request timeout'));
|
|
6524
|
+
}, timeout);
|
|
5754
6525
|
try {
|
|
5755
|
-
|
|
6526
|
+
sock.emit(event, data || {}, function (resp) {
|
|
5756
6527
|
if (done) return; done = true; clearTimeout(timer);
|
|
5757
|
-
if (resp && resp.error) reject(
|
|
6528
|
+
if (resp && resp.error) reject(toUsionError(resp));
|
|
5758
6529
|
else resolve(resp);
|
|
5759
6530
|
});
|
|
5760
|
-
} catch (e) { clearTimeout(timer); reject(e); }
|
|
6531
|
+
} catch (e) { clearTimeout(timer); reject(toUsionError(e)); }
|
|
5761
6532
|
});
|
|
5762
6533
|
}
|
|
6534
|
+
|
|
6535
|
+
const s = self.game && self.game.socket;
|
|
6536
|
+
if (s && s.connected) return emitOn(s);
|
|
5763
6537
|
if (self._isEmbedded) {
|
|
5764
6538
|
// Host relays this onto its authenticated socket and replies with the ack.
|
|
5765
|
-
return self._request('BACKEND_EMIT', { event: event, data: data || {} }, timeout)
|
|
6539
|
+
return self._request('BACKEND_EMIT', { event: event, data: data || {} }, timeout)
|
|
6540
|
+
.catch(function (e) { throw toUsionError(e); });
|
|
6541
|
+
}
|
|
6542
|
+
|
|
6543
|
+
// Standalone without a live socket. If no socket exists yet, auto-connect
|
|
6544
|
+
// once (connect() dedupes concurrent callers via _connectPromise). A
|
|
6545
|
+
// socket that exists but is mid-reconnect is left to Socket.IO's own
|
|
6546
|
+
// reconnection — the caller gets a coded error and can retry.
|
|
6547
|
+
const connectionMode = (self.config && self.config.connectionMode) || 'platform';
|
|
6548
|
+
if (!s && connectionMode !== 'direct'
|
|
6549
|
+
&& self.game && typeof self.game.connect === 'function') {
|
|
6550
|
+
return self.game.connect().then(function () {
|
|
6551
|
+
const sock = self.game.socket;
|
|
6552
|
+
if (sock && sock.connected) return emitOn(sock);
|
|
6553
|
+
throw new UsionError(ERROR_CODES.NOT_CONNECTED, 'No backend connection');
|
|
6554
|
+
}).catch(function (e) {
|
|
6555
|
+
if (e instanceof UsionError) throw e;
|
|
6556
|
+
throw new UsionError(ERROR_CODES.NOT_CONNECTED,
|
|
6557
|
+
'Backend connect failed: ' + (e && e.message ? e.message : String(e)));
|
|
6558
|
+
});
|
|
5766
6559
|
}
|
|
5767
|
-
return Promise.reject(new
|
|
6560
|
+
return Promise.reject(new UsionError(ERROR_CODES.NOT_CONNECTED,
|
|
6561
|
+
'No backend connection — socket is offline or reconnecting'));
|
|
5768
6562
|
};
|
|
5769
6563
|
}
|
|
5770
6564
|
|
|
@@ -5784,12 +6578,13 @@ var Usion = (function () {
|
|
|
5784
6578
|
* MeshNetwork — N-peer full mesh
|
|
5785
6579
|
* diff / patch / quantize — JSON delta compression (id-keyed arrays)
|
|
5786
6580
|
* encode / decode — compact binary codec
|
|
6581
|
+
* createInterestGrid — spatial hash for area-of-interest (AOI) filtering
|
|
5787
6582
|
*/
|
|
5788
6583
|
|
|
5789
6584
|
const netcode = {
|
|
5790
6585
|
SnapshotInterpolation, Vault, Predictor, Coalescer, PingMeter,
|
|
5791
6586
|
MeshConnection, MeshNetwork, WebTransportConnection, NetworkSim, Lockstep, LagCompensator,
|
|
5792
|
-
diff, patch, quantize, encode, decode,
|
|
6587
|
+
diff, patch, quantize, encode, decode, createInterestGrid,
|
|
5793
6588
|
};
|
|
5794
6589
|
|
|
5795
6590
|
/**
|