@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
|
@@ -14,6 +14,8 @@
|
|
|
14
14
|
* safe, namespaced allow-list (e.g. lobby:* / mm:*) so a mini-app can't abuse
|
|
15
15
|
* the user's authenticated connection. The backend re-validates every call.
|
|
16
16
|
*/
|
|
17
|
+
import { UsionError, toUsionError, ERROR_CODES } from './errors.js';
|
|
18
|
+
|
|
17
19
|
export function applyBackendChannel(Usion) {
|
|
18
20
|
Usion._backendHandlers = {};
|
|
19
21
|
Usion._boundSockets = typeof WeakSet !== 'undefined' ? new WeakSet() : null;
|
|
@@ -48,29 +50,60 @@ export function applyBackendChannel(Usion) {
|
|
|
48
50
|
/**
|
|
49
51
|
* Emit a backend request and await its ack. Routes to the SDK socket when
|
|
50
52
|
* standalone, or through the parent host when embedded.
|
|
53
|
+
* Standalone apps that never call Usion.game.connect() (e.g. a non-game
|
|
54
|
+
* app using cloud/leaderboard/notify) get an automatic one-time connect —
|
|
55
|
+
* the backend channel is not coupled to starting a game.
|
|
56
|
+
* Rejections are always UsionError (stable `code`, plus `retryAfter` on
|
|
57
|
+
* RATE_LIMITED), regardless of transport.
|
|
51
58
|
* @returns {Promise<any>}
|
|
52
59
|
*/
|
|
53
60
|
Usion._backendEmit = function (event, data, timeout) {
|
|
54
61
|
const self = this;
|
|
55
62
|
timeout = timeout || 8000;
|
|
56
|
-
|
|
57
|
-
|
|
63
|
+
|
|
64
|
+
function emitOn(sock) {
|
|
58
65
|
return new Promise(function (resolve, reject) {
|
|
59
66
|
let done = false;
|
|
60
|
-
const timer = setTimeout(function () {
|
|
67
|
+
const timer = setTimeout(function () {
|
|
68
|
+
if (done) return; done = true;
|
|
69
|
+
reject(new UsionError(ERROR_CODES.REQUEST_TIMEOUT, 'Backend request timeout'));
|
|
70
|
+
}, timeout);
|
|
61
71
|
try {
|
|
62
|
-
|
|
72
|
+
sock.emit(event, data || {}, function (resp) {
|
|
63
73
|
if (done) return; done = true; clearTimeout(timer);
|
|
64
|
-
if (resp && resp.error) reject(
|
|
74
|
+
if (resp && resp.error) reject(toUsionError(resp));
|
|
65
75
|
else resolve(resp);
|
|
66
76
|
});
|
|
67
|
-
} catch (e) { clearTimeout(timer); reject(e); }
|
|
77
|
+
} catch (e) { clearTimeout(timer); reject(toUsionError(e)); }
|
|
68
78
|
});
|
|
69
79
|
}
|
|
80
|
+
|
|
81
|
+
const s = self.game && self.game.socket;
|
|
82
|
+
if (s && s.connected) return emitOn(s);
|
|
70
83
|
if (self._isEmbedded) {
|
|
71
84
|
// Host relays this onto its authenticated socket and replies with the ack.
|
|
72
|
-
return self._request('BACKEND_EMIT', { event: event, data: data || {} }, timeout)
|
|
85
|
+
return self._request('BACKEND_EMIT', { event: event, data: data || {} }, timeout)
|
|
86
|
+
.catch(function (e) { throw toUsionError(e); });
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// Standalone without a live socket. If no socket exists yet, auto-connect
|
|
90
|
+
// once (connect() dedupes concurrent callers via _connectPromise). A
|
|
91
|
+
// socket that exists but is mid-reconnect is left to Socket.IO's own
|
|
92
|
+
// reconnection — the caller gets a coded error and can retry.
|
|
93
|
+
const connectionMode = (self.config && self.config.connectionMode) || 'platform';
|
|
94
|
+
if (!s && connectionMode !== 'direct'
|
|
95
|
+
&& self.game && typeof self.game.connect === 'function') {
|
|
96
|
+
return self.game.connect().then(function () {
|
|
97
|
+
const sock = self.game.socket;
|
|
98
|
+
if (sock && sock.connected) return emitOn(sock);
|
|
99
|
+
throw new UsionError(ERROR_CODES.NOT_CONNECTED, 'No backend connection');
|
|
100
|
+
}).catch(function (e) {
|
|
101
|
+
if (e instanceof UsionError) throw e;
|
|
102
|
+
throw new UsionError(ERROR_CODES.NOT_CONNECTED,
|
|
103
|
+
'Backend connect failed: ' + (e && e.message ? e.message : String(e)));
|
|
104
|
+
});
|
|
73
105
|
}
|
|
74
|
-
return Promise.reject(new
|
|
106
|
+
return Promise.reject(new UsionError(ERROR_CODES.NOT_CONNECTED,
|
|
107
|
+
'No backend connection — socket is offline or reconnecting'));
|
|
75
108
|
};
|
|
76
109
|
}
|
package/src/modules/core.js
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
* Usion SDK Core — init, _post, _request, message handling
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
+
import { UsionError, toUsionError, ERROR_CODES } from './errors.js';
|
|
6
|
+
|
|
5
7
|
// Request ID counter for tracking async responses
|
|
6
8
|
let _requestId = 0;
|
|
7
9
|
export const _pendingRequests = {};
|
|
@@ -75,24 +77,60 @@ export const core = {
|
|
|
75
77
|
_backButtonCallback: null,
|
|
76
78
|
|
|
77
79
|
/**
|
|
78
|
-
* Initialize the SDK with config from parent app
|
|
79
|
-
*
|
|
80
|
+
* Initialize the SDK with config from parent app.
|
|
81
|
+
*
|
|
82
|
+
* Callback form (unchanged): `Usion.init(cb)` — cb(config) fires when the
|
|
83
|
+
* host's INIT arrives. Promise form: every call ALSO returns a
|
|
84
|
+
* Promise<config>, so `const config = await Usion.init()` works.
|
|
85
|
+
*
|
|
86
|
+
* `opts.timeout` (ms, optional) rejects the promise with
|
|
87
|
+
* UsionError(INIT_TIMEOUT) if no INIT arrives in time — the "embedded but
|
|
88
|
+
* host silent" case that otherwise hangs forever. The callback still fires
|
|
89
|
+
* if INIT arrives late. Both `init(cb, opts)` and `init(opts)` are accepted.
|
|
90
|
+
*
|
|
91
|
+
* @param {function|{timeout?: number}} [callback] - Called with config when ready
|
|
92
|
+
* @param {{timeout?: number}} [opts]
|
|
93
|
+
* @returns {Promise<object>} Resolves with config
|
|
80
94
|
*/
|
|
81
|
-
init: function(callback) {
|
|
95
|
+
init: function(callback, opts) {
|
|
82
96
|
const self = this;
|
|
97
|
+
if (callback && typeof callback === 'object') {
|
|
98
|
+
opts = callback;
|
|
99
|
+
callback = null;
|
|
100
|
+
}
|
|
101
|
+
opts = opts || {};
|
|
83
102
|
|
|
84
103
|
// Prevent double initialization - just update callback
|
|
85
104
|
if (self._initialized) {
|
|
86
105
|
if (callback) callback(self.config);
|
|
87
|
-
return;
|
|
106
|
+
return Promise.resolve(self.config);
|
|
88
107
|
}
|
|
89
108
|
|
|
90
109
|
// Store callback for when config arrives
|
|
91
|
-
self._initCallback = callback;
|
|
110
|
+
if (callback) self._initCallback = callback;
|
|
111
|
+
|
|
112
|
+
// One shared promise for every init() call before INIT arrives.
|
|
113
|
+
if (!self._initPromise) {
|
|
114
|
+
self._initPromise = new Promise(function(resolve, reject) {
|
|
115
|
+
self._initResolve = resolve;
|
|
116
|
+
self._initReject = reject;
|
|
117
|
+
});
|
|
118
|
+
// Callback-style users never touch the promise — don't let an
|
|
119
|
+
// INIT_TIMEOUT rejection surface as an unhandled-rejection error.
|
|
120
|
+
self._initPromise.catch(function() {});
|
|
121
|
+
}
|
|
122
|
+
if (opts.timeout > 0 && !self._initTimer) {
|
|
123
|
+
self._initTimer = setTimeout(function() {
|
|
124
|
+
self._initTimer = null;
|
|
125
|
+
if (self._initialized || !self._initReject) return;
|
|
126
|
+
self._initReject(new UsionError(ERROR_CODES.INIT_TIMEOUT,
|
|
127
|
+
'No INIT from host within ' + opts.timeout + 'ms — host silent or running standalone'));
|
|
128
|
+
}, opts.timeout);
|
|
129
|
+
}
|
|
92
130
|
|
|
93
131
|
// Only register message handler once
|
|
94
132
|
if (self._messageHandlerRegistered) {
|
|
95
|
-
return;
|
|
133
|
+
return self._initPromise;
|
|
96
134
|
}
|
|
97
135
|
self._messageHandlerRegistered = true;
|
|
98
136
|
|
|
@@ -148,6 +186,15 @@ export const core = {
|
|
|
148
186
|
if (self._initCallback) {
|
|
149
187
|
self._initCallback(data.config);
|
|
150
188
|
}
|
|
189
|
+
|
|
190
|
+
// Settle the promise form
|
|
191
|
+
if (self._initTimer) {
|
|
192
|
+
clearTimeout(self._initTimer);
|
|
193
|
+
self._initTimer = null;
|
|
194
|
+
}
|
|
195
|
+
if (self._initResolve) {
|
|
196
|
+
self._initResolve(data.config);
|
|
197
|
+
}
|
|
151
198
|
}
|
|
152
199
|
|
|
153
200
|
// Handle response messages for async requests
|
|
@@ -156,7 +203,9 @@ export const core = {
|
|
|
156
203
|
delete _pendingRequests[data._requestId];
|
|
157
204
|
|
|
158
205
|
if (data.error) {
|
|
159
|
-
|
|
206
|
+
// Preserve the backend's stable code/retry_after when the host
|
|
207
|
+
// relayed them (see errors.js).
|
|
208
|
+
reject(toUsionError(data));
|
|
160
209
|
} else {
|
|
161
210
|
resolve(data);
|
|
162
211
|
}
|
|
@@ -215,6 +264,8 @@ export const core = {
|
|
|
215
264
|
|
|
216
265
|
// Signal ready to parent
|
|
217
266
|
this._post({ type: 'READY' });
|
|
267
|
+
|
|
268
|
+
return self._initPromise;
|
|
218
269
|
},
|
|
219
270
|
|
|
220
271
|
/**
|
|
@@ -336,7 +387,7 @@ export const core = {
|
|
|
336
387
|
// Setup timeout
|
|
337
388
|
const timer = setTimeout(function() {
|
|
338
389
|
delete _pendingRequests[requestId];
|
|
339
|
-
reject(new
|
|
390
|
+
reject(new UsionError(ERROR_CODES.REQUEST_TIMEOUT, 'Request timeout'));
|
|
340
391
|
}, timeout);
|
|
341
392
|
|
|
342
393
|
// Store pending request
|
package/src/modules/errors.js
CHANGED
|
@@ -12,16 +12,30 @@ export const ERROR_CODES = {
|
|
|
12
12
|
NO_ROOM: 'NO_ROOM', // No room id provided/known
|
|
13
13
|
ROOM_NOT_FOUND: 'ROOM_NOT_FOUND', // Room does not exist server-side
|
|
14
14
|
NOT_PARTICIPANT: 'NOT_PARTICIPANT', // Caller is not a player in the room
|
|
15
|
-
|
|
15
|
+
NOT_IN_ROOM: 'NOT_IN_ROOM', // Socket not in the room — rejoin required
|
|
16
|
+
NOT_AUTHORITY: 'NOT_AUTHORITY', // Authority-only call (e.g. lobby start)
|
|
16
17
|
NOT_AUTHENTICATED: 'NOT_AUTHENTICATED', // Missing/invalid auth server-side
|
|
17
18
|
JOIN_TIMEOUT: 'JOIN_TIMEOUT', // Join did not complete in time
|
|
18
19
|
CONNECT_TIMEOUT: 'CONNECT_TIMEOUT', // Connect did not complete in time
|
|
20
|
+
INIT_TIMEOUT: 'INIT_TIMEOUT', // init() got no INIT from the host in time
|
|
21
|
+
MATCH_TIMEOUT: 'MATCH_TIMEOUT', // matchmaking.find() opts.timeout elapsed
|
|
19
22
|
STATE_TOO_LARGE: 'STATE_TOO_LARGE', // setState payload over the quota
|
|
20
23
|
INVALID_STATE: 'INVALID_STATE', // setState payload not a JSON object
|
|
24
|
+
STALE_STATE: 'STALE_STATE', // setState older than the stored checkpoint
|
|
21
25
|
INVALID_NEXT_TURN: 'INVALID_NEXT_TURN', // nextTurn is not a player in the room
|
|
22
|
-
|
|
26
|
+
INVALID_INPUT: 'INVALID_INPUT', // Missing/malformed argument server-side
|
|
27
|
+
NOT_FOUND: 'NOT_FOUND', // Referenced entity (service, lobby, …) missing
|
|
28
|
+
QUOTA_EXCEEDED: 'QUOTA_EXCEEDED', // Bucket key/size quota reached (cloud KV)
|
|
29
|
+
VALUE_TOO_LARGE: 'VALUE_TOO_LARGE', // Single value over the per-value quota
|
|
30
|
+
LOBBY_FULL: 'LOBBY_FULL', // Lobby at max_players
|
|
31
|
+
LOBBY_CLOSED: 'LOBBY_CLOSED', // Lobby exists but is not open
|
|
32
|
+
WORLD_FULL: 'WORLD_FULL', // World room at max_players
|
|
33
|
+
CONFLICT: 'CONFLICT', // Concurrent-write conflict; retry
|
|
34
|
+
RATE_LIMITED: 'RATE_LIMITED', // Too many calls; back off (see retryAfter)
|
|
23
35
|
REQUEST_TIMEOUT: 'REQUEST_TIMEOUT', // Host/parent did not reply in time
|
|
24
36
|
QUEUE_FULL: 'QUEUE_FULL', // Offline action queue at capacity
|
|
37
|
+
CANCELLED: 'CANCELLED', // Cancelled by a local cancel() call
|
|
38
|
+
SUPERSEDED: 'SUPERSEDED', // Replaced by a newer identical request
|
|
25
39
|
UNSUPPORTED: 'UNSUPPORTED', // Not available in this transport
|
|
26
40
|
UNKNOWN: 'UNKNOWN', // Unmapped error (see message)
|
|
27
41
|
};
|
|
@@ -35,18 +49,25 @@ export class UsionError extends Error {
|
|
|
35
49
|
super(message || code);
|
|
36
50
|
this.name = 'UsionError';
|
|
37
51
|
this.code = ERROR_CODES[code] ? code : ERROR_CODES.UNKNOWN;
|
|
52
|
+
/** @type {number|undefined} Seconds until a RATE_LIMITED call may retry. */
|
|
53
|
+
this.retryAfter = undefined;
|
|
38
54
|
}
|
|
39
55
|
}
|
|
40
56
|
|
|
41
57
|
// Backend error strings → stable codes. Order matters: first match wins.
|
|
58
|
+
// Fallback path only: the backend now sends a structured `code` on every
|
|
59
|
+
// error ack, which toUsionError prefers. These patterns cover old backends
|
|
60
|
+
// and hosts that strip the code.
|
|
42
61
|
/** @type {Array<[RegExp, string]>} */
|
|
43
62
|
const BACKEND_PATTERNS = [
|
|
44
63
|
[/not authenticated/i, ERROR_CODES.NOT_AUTHENTICATED],
|
|
45
64
|
[/room_id required|no room id/i, ERROR_CODES.NO_ROOM],
|
|
46
65
|
[/room not found/i, ERROR_CODES.ROOM_NOT_FOUND],
|
|
66
|
+
[/not in room/i, ERROR_CODES.NOT_IN_ROOM],
|
|
47
67
|
[/not a participant/i, ERROR_CODES.NOT_PARTICIPANT],
|
|
48
68
|
[/room authority/i, ERROR_CODES.NOT_AUTHORITY],
|
|
49
69
|
[/exceeds .*limit/i, ERROR_CODES.STATE_TOO_LARGE],
|
|
70
|
+
[/stale checkpoint|stale state/i, ERROR_CODES.STALE_STATE],
|
|
50
71
|
[/state must be/i, ERROR_CODES.INVALID_STATE],
|
|
51
72
|
[/next_turn must be/i, ERROR_CODES.INVALID_NEXT_TURN],
|
|
52
73
|
[/rate limit|too many/i, ERROR_CODES.RATE_LIMITED],
|
|
@@ -54,17 +75,41 @@ const BACKEND_PATTERNS = [
|
|
|
54
75
|
[/connection timeout|connect timeout/i, ERROR_CODES.CONNECT_TIMEOUT],
|
|
55
76
|
[/request timeout/i, ERROR_CODES.REQUEST_TIMEOUT],
|
|
56
77
|
[/not connected/i, ERROR_CODES.NOT_CONNECTED],
|
|
78
|
+
[/quota exceeded/i, ERROR_CODES.QUOTA_EXCEEDED],
|
|
79
|
+
[/value too large/i, ERROR_CODES.VALUE_TOO_LARGE],
|
|
80
|
+
[/lobby is full/i, ERROR_CODES.LOBBY_FULL],
|
|
81
|
+
[/lobby is not open/i, ERROR_CODES.LOBBY_CLOSED],
|
|
82
|
+
[/world room is full/i, ERROR_CODES.WORLD_FULL],
|
|
83
|
+
[/not found|unknown service/i, ERROR_CODES.NOT_FOUND],
|
|
84
|
+
[/conflict/i, ERROR_CODES.CONFLICT],
|
|
85
|
+
[/cancelled/i, ERROR_CODES.CANCELLED],
|
|
86
|
+
[/superseded/i, ERROR_CODES.SUPERSEDED],
|
|
57
87
|
];
|
|
58
88
|
|
|
59
89
|
/**
|
|
60
|
-
* Normalize anything
|
|
61
|
-
* UsionError with the best
|
|
90
|
+
* Normalize anything — a structured backend ack ({ error, code?, retry_after? }),
|
|
91
|
+
* an Error, or a raw string — into a UsionError with the best stable code.
|
|
92
|
+
* A machine-readable `code` on the input always wins over message matching.
|
|
62
93
|
* @param {*} err
|
|
63
94
|
* @param {string} [fallbackCode] - Code to use when nothing matches
|
|
64
95
|
* @returns {UsionError}
|
|
65
96
|
*/
|
|
66
97
|
export function toUsionError(err, fallbackCode) {
|
|
67
98
|
if (err instanceof UsionError) return err;
|
|
99
|
+
|
|
100
|
+
// Structured input (backend ack object or an Error carrying a code).
|
|
101
|
+
if (err && typeof err === 'object') {
|
|
102
|
+
const code = typeof err.code === 'string' && ERROR_CODES[err.code] ? err.code : null;
|
|
103
|
+
const message = err.message || err.error;
|
|
104
|
+
if (code) {
|
|
105
|
+
const ue = new UsionError(code, typeof message === 'string' ? message : code);
|
|
106
|
+
const retryAfter = err.retry_after != null ? err.retry_after : err.retryAfter;
|
|
107
|
+
if (typeof retryAfter === 'number' && isFinite(retryAfter)) ue.retryAfter = retryAfter;
|
|
108
|
+
return ue;
|
|
109
|
+
}
|
|
110
|
+
if (!(err instanceof Error) && typeof message === 'string') err = message;
|
|
111
|
+
}
|
|
112
|
+
|
|
68
113
|
const message = err && err.message ? err.message : String(err || 'Unknown error');
|
|
69
114
|
for (let i = 0; i < BACKEND_PATTERNS.length; i++) {
|
|
70
115
|
if (BACKEND_PATTERNS[i][0].test(message)) {
|
package/src/modules/game-core.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
5
|
import { applyGameDirect } from './game-direct.js';
|
|
6
|
+
import { applyGameResilience } from './game-resilience.js';
|
|
6
7
|
import { applyGameSocket } from './game-socket.js';
|
|
7
8
|
import { applyGameProxy } from './game-proxy.js';
|
|
8
9
|
import { applyGameMethods } from './game-methods.js';
|
|
@@ -31,6 +32,7 @@ const _EVENT_ALIASES = {
|
|
|
31
32
|
room_assigned: 'roomAssigned',
|
|
32
33
|
connection_state: 'connectionState',
|
|
33
34
|
reconnected: 'reconnected',
|
|
35
|
+
network_quality: 'networkQuality',
|
|
34
36
|
};
|
|
35
37
|
|
|
36
38
|
function _normalizeEventName(event) {
|
|
@@ -126,26 +128,31 @@ export function createGameModule(Usion) {
|
|
|
126
128
|
self._connectPromise = new Promise(function(resolve, reject) {
|
|
127
129
|
// Check if socket.io-client is available
|
|
128
130
|
if (typeof io === 'undefined') {
|
|
129
|
-
// Load
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
self._initSocket(socketUrl, token, resolve, reject);
|
|
141
|
-
};
|
|
142
|
-
cdnScript.onerror = function() {
|
|
131
|
+
// Load the Socket.IO client: same-origin copy first, then the
|
|
132
|
+
// platform-hosted copy (same origin as the SDK itself — reachable
|
|
133
|
+
// wherever the app is), and only then the public CDN, which
|
|
134
|
+
// restricted networks often block.
|
|
135
|
+
var sources = [
|
|
136
|
+
'/socket.io.min.js',
|
|
137
|
+
'https://usions.com/socket.io.min.js',
|
|
138
|
+
'https://cdn.socket.io/4.7.2/socket.io.min.js'
|
|
139
|
+
];
|
|
140
|
+
(function tryLoad(i) {
|
|
141
|
+
if (i >= sources.length) {
|
|
143
142
|
self._connecting = false;
|
|
144
143
|
reject(new Error('Failed to load Socket.IO client'));
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
var script = document.createElement('script');
|
|
147
|
+
script.src = sources[i];
|
|
148
|
+
script.onload = function() {
|
|
149
|
+
self._initSocket(socketUrl, token, resolve, reject);
|
|
150
|
+
};
|
|
151
|
+
script.onerror = function() {
|
|
152
|
+
tryLoad(i + 1);
|
|
145
153
|
};
|
|
146
|
-
document.head.appendChild(
|
|
147
|
-
};
|
|
148
|
-
document.head.appendChild(script);
|
|
154
|
+
document.head.appendChild(script);
|
|
155
|
+
})(0);
|
|
149
156
|
} else {
|
|
150
157
|
self._initSocket(socketUrl, token, resolve, reject);
|
|
151
158
|
}
|
|
@@ -240,6 +247,8 @@ export function createGameModule(Usion) {
|
|
|
240
247
|
|
|
241
248
|
// Apply sub-modules
|
|
242
249
|
applyGameDirect(game, Usion);
|
|
250
|
+
// Direct-mode liveness/backpressure + network stats (hooks into game-direct).
|
|
251
|
+
applyGameResilience(game, Usion);
|
|
243
252
|
applyGameSocket(game, Usion);
|
|
244
253
|
applyGameProxy(game, Usion);
|
|
245
254
|
applyGameMethods(game, Usion);
|
|
@@ -24,6 +24,7 @@ export function applyGameDirect(game, Usion) {
|
|
|
24
24
|
return self._connectPromise;
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
+
if (self._resConfigure) self._resConfigure(config); // liveness/backpressure opts → game._res
|
|
27
28
|
self._connecting = true;
|
|
28
29
|
self.directMode = true;
|
|
29
30
|
self._autoReconnect = config.autoReconnect !== undefined
|
|
@@ -134,6 +135,7 @@ export function applyGameDirect(game, Usion) {
|
|
|
134
135
|
self._sendDirect('heartbeat', {});
|
|
135
136
|
}
|
|
136
137
|
}, 25000);
|
|
138
|
+
if (self._resOnOpen) self._resOnOpen(); // start liveness watchdog + foreground resync
|
|
137
139
|
resolve();
|
|
138
140
|
};
|
|
139
141
|
|
|
@@ -145,6 +147,7 @@ export function applyGameDirect(game, Usion) {
|
|
|
145
147
|
};
|
|
146
148
|
|
|
147
149
|
ws.onclose = function(evt) {
|
|
150
|
+
if (self._resOnClose) self._resOnClose(evt); // capture close code, stop timers
|
|
148
151
|
self.connected = false;
|
|
149
152
|
self._joined = false;
|
|
150
153
|
self._joinPromise = null;
|
|
@@ -160,6 +163,7 @@ export function applyGameDirect(game, Usion) {
|
|
|
160
163
|
};
|
|
161
164
|
|
|
162
165
|
ws.onmessage = function(evt) {
|
|
166
|
+
if (self._res) self._res.lastInboundAt = Date.now(); // any bytes = alive
|
|
163
167
|
self._handleDirectMessage(evt && evt.data);
|
|
164
168
|
};
|
|
165
169
|
});
|
|
@@ -180,7 +184,9 @@ export function applyGameDirect(game, Usion) {
|
|
|
180
184
|
if (!self.directMode) { self._reconnecting = false; return; } // disconnected meanwhile
|
|
181
185
|
attempt += 1;
|
|
182
186
|
self._reconnectAttempt = attempt;
|
|
183
|
-
|
|
187
|
+
// Reuse the cached room token while valid (skips the access round trip).
|
|
188
|
+
var reuse = self._resCanReuseToken && self._resCanReuseToken();
|
|
189
|
+
(reuse ? Promise.resolve(self.directConfig) : self._fetchDirectAccess({}))
|
|
184
190
|
.then(function(access) { self.directConfig = access; return self._initDirectSocket(access); })
|
|
185
191
|
.then(function() {
|
|
186
192
|
self.connected = true;
|
|
@@ -195,11 +201,13 @@ export function applyGameDirect(game, Usion) {
|
|
|
195
201
|
setTimeout(go, delay);
|
|
196
202
|
});
|
|
197
203
|
};
|
|
198
|
-
setTimeout(go,
|
|
204
|
+
setTimeout(go, 100); // fast first attempt; exponential backoff after
|
|
199
205
|
};
|
|
200
206
|
|
|
201
207
|
game._sendDirect = function(type, payload) {
|
|
202
208
|
if (!this.directSocket || this.directSocket.readyState !== WebSocket.OPEN) return;
|
|
209
|
+
// Backpressure (input frames only): hold latest while the buffer is full.
|
|
210
|
+
if (type === 'input' && this._resHoldInput && this._resHoldInput(payload)) return;
|
|
203
211
|
this._directSeq = this._directSeq + 1;
|
|
204
212
|
this.directSocket.send(JSON.stringify({
|
|
205
213
|
type: type,
|
|
@@ -241,11 +249,10 @@ export function applyGameDirect(game, Usion) {
|
|
|
241
249
|
return;
|
|
242
250
|
}
|
|
243
251
|
if (data.type === 'pong') {
|
|
244
|
-
// Resolve a pending game.ping() RTT probe, if any.
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
}
|
|
252
|
+
// Resolve a pending game.ping() RTT probe, if any; feed the stats EWMA.
|
|
253
|
+
var waiter = (this._pongWaiters && this._pongWaiters.length) ? this._pongWaiters.shift() : null;
|
|
254
|
+
if (this._resOnPong) this._resOnPong(waiter);
|
|
255
|
+
if (waiter) waiter();
|
|
249
256
|
this._dispatch('sync', payload);
|
|
250
257
|
return;
|
|
251
258
|
}
|
|
@@ -66,7 +66,7 @@ export function applyGameMethods(game, Usion) {
|
|
|
66
66
|
self.socket.emit('game:join', { room_id: roomId }, function(response) {
|
|
67
67
|
if (response.error) {
|
|
68
68
|
self._joined = false;
|
|
69
|
-
reject(toUsionError(response
|
|
69
|
+
reject(toUsionError(response));
|
|
70
70
|
} else {
|
|
71
71
|
self._joined = true;
|
|
72
72
|
if (response.sequence !== undefined) {
|
|
@@ -88,6 +88,30 @@ export function applyGameMethods(game, Usion) {
|
|
|
88
88
|
return self._joinPromise;
|
|
89
89
|
};
|
|
90
90
|
|
|
91
|
+
/**
|
|
92
|
+
* Place this player into a drop-in/drop-out WORLD room (SDK ≥ 2.23).
|
|
93
|
+
*
|
|
94
|
+
* World rooms (services tagged `world`) run continuously: players enter and
|
|
95
|
+
* leave at any time instead of playing fixed matches. Placement rides the
|
|
96
|
+
* matchmaking channel (works embedded AND standalone): the platform returns
|
|
97
|
+
* the world you're already in, else backfills a world with space, else
|
|
98
|
+
* creates a new one. On success `game.roomId` is set, so the usual
|
|
99
|
+
* `connect()`+`join()` (platform relay) or `connectDirect()` (direct/hosted)
|
|
100
|
+
* flow works unchanged afterwards. Rejects with MATCH_TIMEOUT after 15s.
|
|
101
|
+
*
|
|
102
|
+
* @param {object} [opts]
|
|
103
|
+
* @param {string} [opts.serviceId] - Defaults to the current service.
|
|
104
|
+
* @returns {Promise<{roomId: string, playerIds: string[]}>}
|
|
105
|
+
*/
|
|
106
|
+
game.joinWorld = function(opts) {
|
|
107
|
+
const self = this;
|
|
108
|
+
opts = opts || {};
|
|
109
|
+
return Usion.matchmaking._joinWorld(opts.serviceId).then(function(m) {
|
|
110
|
+
self.roomId = m.roomId;
|
|
111
|
+
return { roomId: m.roomId, playerIds: m.players || [] };
|
|
112
|
+
});
|
|
113
|
+
};
|
|
114
|
+
|
|
91
115
|
/**
|
|
92
116
|
* Leave the current game room
|
|
93
117
|
*/
|
|
@@ -169,36 +193,81 @@ export function applyGameMethods(game, Usion) {
|
|
|
169
193
|
// move can't go out before the client has resynced.
|
|
170
194
|
const gate = self._rejoinPromise || Promise.resolve();
|
|
171
195
|
return gate.then(function() {
|
|
172
|
-
|
|
173
|
-
if (
|
|
174
|
-
|
|
175
|
-
self._queueOfflineAction(actionType, actionData, opts).then(resolve, reject);
|
|
176
|
-
return;
|
|
177
|
-
}
|
|
178
|
-
reject(new UsionError(ERROR_CODES.NOT_CONNECTED, 'Not connected'));
|
|
179
|
-
return;
|
|
196
|
+
if (!self.socket || !self.connected) {
|
|
197
|
+
if (queueOffline) {
|
|
198
|
+
return self._queueOfflineAction(actionType, actionData, opts);
|
|
180
199
|
}
|
|
200
|
+
throw new UsionError(ERROR_CODES.NOT_CONNECTED, 'Not connected');
|
|
201
|
+
}
|
|
202
|
+
const payload = {
|
|
203
|
+
room_id: self.roomId,
|
|
204
|
+
action_type: actionType,
|
|
205
|
+
action_data: actionData
|
|
206
|
+
};
|
|
207
|
+
if (nextTurn) payload.next_turn = nextTurn;
|
|
208
|
+
return self._emitAction(payload, true);
|
|
209
|
+
});
|
|
210
|
+
};
|
|
181
211
|
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
212
|
+
/**
|
|
213
|
+
* @private Emit game:action and handle the ack. On NOT_IN_ROOM (the server
|
|
214
|
+
* detected a detached socket — connected but no room membership), auto-
|
|
215
|
+
* rejoin + resync once and retry the same action, so a move made in the
|
|
216
|
+
* detached window is delivered instead of silently lost.
|
|
217
|
+
*/
|
|
218
|
+
game._emitAction = function(payload, retryOnNotInRoom) {
|
|
219
|
+
const self = this;
|
|
220
|
+
return new Promise(function(resolve, reject) {
|
|
221
|
+
if (!self.socket || !self.connected) {
|
|
222
|
+
reject(new UsionError(ERROR_CODES.NOT_CONNECTED, 'Not connected'));
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
self.socket.emit('game:action', payload, function(response) {
|
|
226
|
+
if (response && response.error) {
|
|
227
|
+
const ue = toUsionError(response);
|
|
228
|
+
if (retryOnNotInRoom && ue.code === ERROR_CODES.NOT_IN_ROOM) {
|
|
229
|
+
self._autoRejoin()
|
|
230
|
+
.then(function() { return self._emitAction(payload, false); })
|
|
231
|
+
.then(resolve, reject);
|
|
232
|
+
return;
|
|
196
233
|
}
|
|
197
|
-
|
|
234
|
+
reject(ue);
|
|
235
|
+
} else {
|
|
236
|
+
if (response && response.sequence !== undefined) {
|
|
237
|
+
self._lastSequence = response.sequence;
|
|
238
|
+
}
|
|
239
|
+
resolve(response);
|
|
240
|
+
}
|
|
198
241
|
});
|
|
199
242
|
});
|
|
200
243
|
};
|
|
201
244
|
|
|
245
|
+
/**
|
|
246
|
+
* @private Recover a detached socket: the server said we're not in the
|
|
247
|
+
* Socket.IO room (NOT_IN_ROOM), so rejoin + resync exactly like the
|
|
248
|
+
* post-reconnect path, gating action() sends on _rejoinPromise meanwhile.
|
|
249
|
+
*/
|
|
250
|
+
game._autoRejoin = function() {
|
|
251
|
+
const self = this;
|
|
252
|
+
if (self._rejoinPromise) return self._rejoinPromise;
|
|
253
|
+
if (!self.roomId || !self.socket || !self.connected) return Promise.resolve();
|
|
254
|
+
Usion.log('Server reports socket not in room - auto-rejoining ' + self.roomId);
|
|
255
|
+
self._joined = false;
|
|
256
|
+
self._joinPromise = null;
|
|
257
|
+
self._rejoinPromise = self.join(self.roomId)
|
|
258
|
+
.then(function() {
|
|
259
|
+
self.requestSync(self._lastSequence || 0);
|
|
260
|
+
})
|
|
261
|
+
.catch(function(err) {
|
|
262
|
+
Usion.log('Auto-rejoin failed: ' + (err && err.message ? err.message : String(err)));
|
|
263
|
+
})
|
|
264
|
+
.then(function() {
|
|
265
|
+
self._rejoinPromise = null;
|
|
266
|
+
if (self._flushOfflineQueue) self._flushOfflineQueue();
|
|
267
|
+
});
|
|
268
|
+
return self._rejoinPromise;
|
|
269
|
+
};
|
|
270
|
+
|
|
202
271
|
// ── Offline action queue (opt-in via action(..., { queueOffline: true })) ──
|
|
203
272
|
|
|
204
273
|
const OFFLINE_QUEUE_MAX = 20;
|
|
@@ -273,11 +342,17 @@ export function applyGameMethods(game, Usion) {
|
|
|
273
342
|
return Promise.resolve({ success: false, error: 'not_supported_in_direct_mode', code: ERROR_CODES.UNSUPPORTED });
|
|
274
343
|
}
|
|
275
344
|
|
|
345
|
+
// The checkpoint carries the action sequence this state reflects. The
|
|
346
|
+
// server persists it and rejects OLDER checkpoints (STALE_STATE), so two
|
|
347
|
+
// concurrent writers can't clobber newer state with older.
|
|
348
|
+
const checkpointSeq = self._lastSequence || 0;
|
|
349
|
+
|
|
276
350
|
if (self._useProxy) {
|
|
277
|
-
return Usion._request('GAME_SET_STATE', { room_id: self.roomId, state: state || {} })
|
|
351
|
+
return Usion._request('GAME_SET_STATE', { room_id: self.roomId, state: state || {}, sequence: checkpointSeq })
|
|
278
352
|
.then(function(res) {
|
|
279
353
|
if (res && res.error) {
|
|
280
|
-
|
|
354
|
+
const rue = toUsionError(res);
|
|
355
|
+
return { success: false, error: rue.message, code: rue.code };
|
|
281
356
|
}
|
|
282
357
|
return res || { success: true };
|
|
283
358
|
})
|
|
@@ -294,10 +369,12 @@ export function applyGameMethods(game, Usion) {
|
|
|
294
369
|
}
|
|
295
370
|
self.socket.emit('game:set_state', {
|
|
296
371
|
room_id: self.roomId,
|
|
297
|
-
state: state || {}
|
|
372
|
+
state: state || {},
|
|
373
|
+
sequence: checkpointSeq
|
|
298
374
|
}, function(response) {
|
|
299
375
|
if (response && response.error) {
|
|
300
|
-
|
|
376
|
+
const ue = toUsionError(response);
|
|
377
|
+
resolve({ success: false, error: ue.message, code: ue.code });
|
|
301
378
|
} else {
|
|
302
379
|
resolve(response || { success: true });
|
|
303
380
|
}
|
|
@@ -330,10 +407,18 @@ export function applyGameMethods(game, Usion) {
|
|
|
330
407
|
return;
|
|
331
408
|
}
|
|
332
409
|
|
|
410
|
+
// Still fire-and-forget for the game, but the server now acks failures
|
|
411
|
+
// (previously dropped silently): surface them via onError, and on
|
|
412
|
+
// NOT_IN_ROOM (detached socket) auto-rejoin so the stream recovers.
|
|
333
413
|
self.socket.emit('game:realtime', {
|
|
334
414
|
room_id: self.roomId,
|
|
335
415
|
action_type: actionType,
|
|
336
416
|
action_data: actionData
|
|
417
|
+
}, function(response) {
|
|
418
|
+
if (!response || !response.error) return;
|
|
419
|
+
const ue = toUsionError(response);
|
|
420
|
+
self._dispatch('error', { code: ue.code, message: ue.message, source: 'realtime' });
|
|
421
|
+
if (ue.code === ERROR_CODES.NOT_IN_ROOM) self._autoRejoin();
|
|
337
422
|
});
|
|
338
423
|
};
|
|
339
424
|
|
|
@@ -409,7 +494,7 @@ export function applyGameMethods(game, Usion) {
|
|
|
409
494
|
|
|
410
495
|
self.socket.emit('game:forfeit', { room_id: self.roomId }, function(response) {
|
|
411
496
|
if (response.error) {
|
|
412
|
-
reject(toUsionError(response
|
|
497
|
+
reject(toUsionError(response));
|
|
413
498
|
} else {
|
|
414
499
|
resolve(response);
|
|
415
500
|
}
|