@air-jam/server 0.9.2 → 0.9.3
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/bin/air-jam-server.mjs +43 -20
- package/dist/.tsbuildinfo +1 -0
- package/dist/chunk-AYTGY3H3.js +67 -0
- package/dist/chunk-AYTGY3H3.js.map +1 -0
- package/dist/{chunk-5ZVGSYXC.js → chunk-LWVOQ5PH.js} +50 -44
- package/dist/chunk-LWVOQ5PH.js.map +1 -0
- package/dist/chunk-PSWSCMDN.js +48 -0
- package/dist/chunk-PSWSCMDN.js.map +1 -0
- package/dist/cli.js +29 -112
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +465 -0
- package/dist/index.js +1086 -1879
- package/dist/index.js.map +1 -1
- package/dist/process-lifecycle-M4XOAN4Q.js +8 -0
- package/package.json +38 -23
- package/dist/chunk-5ZVGSYXC.js.map +0 -1
- package/dist/chunk-RM7AMBDY.js +0 -831
- package/dist/chunk-RM7AMBDY.js.map +0 -1
- package/dist/game-dev-D3TEAHOD.js +0 -422
- package/dist/game-dev-D3TEAHOD.js.map +0 -1
- package/dist/local-dev-state-QT7H5GUA.js +0 -270
- package/dist/local-dev-state-QT7H5GUA.js.map +0 -1
- package/dist/secure-dev-HMOGLYVC.js +0 -39
- package/dist/topology-PM3PI753.js +0 -140
- package/dist/topology-PM3PI753.js.map +0 -1
- package/src/project-cli/vite-config.d.mts +0 -17
- package/src/project-cli/vite-config.mjs +0 -121
- package/src/project-cli/vite-https.d.mts +0 -14
- package/src/project-cli/vite-https.mjs +0 -39
- /package/dist/{secure-dev-HMOGLYVC.js.map → process-lifecycle-M4XOAN4Q.js.map} +0 -0
package/dist/index.js
CHANGED
|
@@ -1,842 +1,83 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
redactIdentifier,
|
|
2
|
+
loadWorkspaceEnv,
|
|
4
3
|
resolveDefaultDevLogDir,
|
|
5
4
|
validateEnv
|
|
6
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-LWVOQ5PH.js";
|
|
6
|
+
import {
|
|
7
|
+
installServerProcessSignalHandlers
|
|
8
|
+
} from "./chunk-AYTGY3H3.js";
|
|
9
|
+
import {
|
|
10
|
+
createServerLogger,
|
|
11
|
+
redactIdentifier
|
|
12
|
+
} from "./chunk-PSWSCMDN.js";
|
|
7
13
|
|
|
8
14
|
// src/index.ts
|
|
9
15
|
import {
|
|
10
|
-
AIRJAM_DEV_LOG_EVENTS as
|
|
16
|
+
AIRJAM_DEV_LOG_EVENTS as AIRJAM_DEV_LOG_EVENTS7
|
|
11
17
|
} from "@air-jam/sdk/protocol";
|
|
12
18
|
import cors from "cors";
|
|
13
19
|
import express from "express";
|
|
14
20
|
import { createServer } from "http";
|
|
15
21
|
import { Server } from "socket.io";
|
|
16
22
|
|
|
17
|
-
// src/
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
boolean,
|
|
21
|
-
date,
|
|
22
|
-
integer,
|
|
23
|
-
jsonb,
|
|
24
|
-
pgTable,
|
|
25
|
-
text,
|
|
26
|
-
timestamp
|
|
27
|
-
} from "drizzle-orm/pg-core";
|
|
28
|
-
import { drizzle } from "drizzle-orm/postgres-js";
|
|
29
|
-
import postgres from "postgres";
|
|
30
|
-
var appIds = pgTable("app_ids", {
|
|
31
|
-
id: text("id").primaryKey(),
|
|
32
|
-
gameId: text("game_id").notNull().unique(),
|
|
33
|
-
// One app identity record per game
|
|
34
|
-
key: text("key").notNull().unique(),
|
|
35
|
-
allowedOrigins: jsonb("allowed_origins").$type(),
|
|
36
|
-
isActive: boolean("is_active").default(true).notNull(),
|
|
37
|
-
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
38
|
-
lastUsedAt: timestamp("last_used_at")
|
|
39
|
-
});
|
|
40
|
-
var runtimeUsageSessions = pgTable("runtime_usage_sessions", {
|
|
41
|
-
id: text("id").primaryKey(),
|
|
42
|
-
roomId: text("room_id").notNull(),
|
|
43
|
-
appId: text("app_id"),
|
|
44
|
-
hostVerifiedVia: text("host_verified_via"),
|
|
45
|
-
hostVerifiedOrigin: text("host_verified_origin"),
|
|
46
|
-
startedAt: timestamp("started_at").notNull(),
|
|
47
|
-
createdAt: timestamp("created_at").defaultNow().notNull()
|
|
48
|
-
});
|
|
49
|
-
var runtimeUsageEvents = pgTable("runtime_usage_events", {
|
|
50
|
-
id: text("id").primaryKey(),
|
|
51
|
-
kind: text("kind").notNull(),
|
|
52
|
-
occurredAt: timestamp("occurred_at").notNull(),
|
|
53
|
-
runtimeSessionId: text("runtime_session_id").references(
|
|
54
|
-
() => runtimeUsageSessions.id,
|
|
55
|
-
{ onDelete: "set null" }
|
|
56
|
-
),
|
|
57
|
-
roomId: text("room_id"),
|
|
58
|
-
appId: text("app_id"),
|
|
59
|
-
gameId: text("game_id"),
|
|
60
|
-
hostVerifiedVia: text("host_verified_via"),
|
|
61
|
-
hostVerifiedOrigin: text("host_verified_origin"),
|
|
62
|
-
payload: jsonb("payload").$type().default(sql`'{}'::jsonb`).notNull(),
|
|
63
|
-
createdAt: timestamp("created_at").defaultNow().notNull()
|
|
64
|
-
});
|
|
65
|
-
var runtimeUsageControllerSegments = pgTable(
|
|
66
|
-
"runtime_usage_controller_segments",
|
|
67
|
-
{
|
|
68
|
-
id: text("id").primaryKey(),
|
|
69
|
-
runtimeSessionId: text("runtime_session_id").references(() => runtimeUsageSessions.id, { onDelete: "cascade" }).notNull(),
|
|
70
|
-
roomId: text("room_id").notNull(),
|
|
71
|
-
appId: text("app_id"),
|
|
72
|
-
controllerId: text("controller_id").notNull(),
|
|
73
|
-
startedAt: timestamp("started_at").notNull(),
|
|
74
|
-
endedAt: timestamp("ended_at"),
|
|
75
|
-
startEventId: text("start_event_id").notNull(),
|
|
76
|
-
endEventId: text("end_event_id"),
|
|
77
|
-
endReason: text("end_reason"),
|
|
78
|
-
createdAt: timestamp("created_at").defaultNow().notNull()
|
|
23
|
+
// src/analytics/runtime-usage.ts
|
|
24
|
+
var createNoopRuntimeUsagePublisher = () => ({
|
|
25
|
+
publish: () => {
|
|
79
26
|
}
|
|
80
|
-
);
|
|
81
|
-
var runtimeUsageGameSegments = pgTable("runtime_usage_game_segments", {
|
|
82
|
-
id: text("id").primaryKey(),
|
|
83
|
-
runtimeSessionId: text("runtime_session_id").references(() => runtimeUsageSessions.id, { onDelete: "cascade" }).notNull(),
|
|
84
|
-
roomId: text("room_id").notNull(),
|
|
85
|
-
appId: text("app_id"),
|
|
86
|
-
gameId: text("game_id").notNull(),
|
|
87
|
-
startedAt: timestamp("started_at").notNull(),
|
|
88
|
-
endedAt: timestamp("ended_at"),
|
|
89
|
-
startEventId: text("start_event_id").notNull(),
|
|
90
|
-
endEventId: text("end_event_id"),
|
|
91
|
-
startReason: text("start_reason"),
|
|
92
|
-
endReason: text("end_reason"),
|
|
93
|
-
createdAt: timestamp("created_at").defaultNow().notNull()
|
|
94
27
|
});
|
|
95
|
-
var
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
startedAt: timestamp("started_at").notNull(),
|
|
104
|
-
endedAt: timestamp("ended_at"),
|
|
105
|
-
startEventId: text("start_event_id").notNull(),
|
|
106
|
-
endEventId: text("end_event_id"),
|
|
107
|
-
startReason: text("start_reason"),
|
|
108
|
-
endReason: text("end_reason"),
|
|
109
|
-
createdAt: timestamp("created_at").defaultNow().notNull()
|
|
110
|
-
}
|
|
111
|
-
);
|
|
112
|
-
var runtimeUsageGameSessionMetrics = pgTable(
|
|
113
|
-
"runtime_usage_game_session_metrics",
|
|
114
|
-
{
|
|
115
|
-
id: text("id").primaryKey(),
|
|
116
|
-
runtimeSessionId: text("runtime_session_id").references(() => runtimeUsageSessions.id, { onDelete: "cascade" }).notNull(),
|
|
117
|
-
roomId: text("room_id").notNull(),
|
|
118
|
-
appId: text("app_id"),
|
|
119
|
-
gameId: text("game_id").notNull(),
|
|
120
|
-
startedAt: timestamp("started_at").notNull(),
|
|
121
|
-
endedAt: timestamp("ended_at"),
|
|
122
|
-
controllerSeconds: integer("controller_seconds").default(0).notNull(),
|
|
123
|
-
rawEligiblePlaytimeSeconds: integer("raw_eligible_playtime_seconds").default(0).notNull(),
|
|
124
|
-
eligiblePlaytimeSeconds: integer("eligible_playtime_seconds").default(0).notNull(),
|
|
125
|
-
trustFlags: jsonb("trust_flags").$type().default(sql`'[]'::jsonb`).notNull(),
|
|
126
|
-
peakConcurrentControllers: integer("peak_concurrent_controllers").default(0).notNull(),
|
|
127
|
-
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
128
|
-
updatedAt: timestamp("updated_at").defaultNow().notNull()
|
|
129
|
-
}
|
|
130
|
-
);
|
|
131
|
-
var runtimeUsageDailyGameMetrics = pgTable(
|
|
132
|
-
"runtime_usage_daily_game_metrics",
|
|
133
|
-
{
|
|
134
|
-
id: text("id").primaryKey(),
|
|
135
|
-
bucketDate: date("bucket_date").notNull(),
|
|
136
|
-
appId: text("app_id"),
|
|
137
|
-
gameId: text("game_id").notNull(),
|
|
138
|
-
sessionCount: integer("session_count").default(0).notNull(),
|
|
139
|
-
totalGameActiveSeconds: integer("total_game_active_seconds").default(0).notNull(),
|
|
140
|
-
totalControllerSeconds: integer("total_controller_seconds").default(0).notNull(),
|
|
141
|
-
totalRawEligiblePlaytimeSeconds: integer(
|
|
142
|
-
"total_raw_eligible_playtime_seconds"
|
|
143
|
-
).default(0).notNull(),
|
|
144
|
-
totalEligiblePlaytimeSeconds: integer("total_eligible_playtime_seconds").default(0).notNull(),
|
|
145
|
-
guardedSessionCount: integer("guarded_session_count").default(0).notNull(),
|
|
146
|
-
peakConcurrentControllers: integer("peak_concurrent_controllers").default(0).notNull(),
|
|
147
|
-
lastActivityAt: timestamp("last_activity_at"),
|
|
148
|
-
createdAt: timestamp("created_at").defaultNow().notNull(),
|
|
149
|
-
updatedAt: timestamp("updated_at").defaultNow().notNull()
|
|
150
|
-
}
|
|
151
|
-
);
|
|
152
|
-
var createServerDatabase = (databaseUrl) => {
|
|
153
|
-
if (!databaseUrl) {
|
|
154
|
-
return null;
|
|
155
|
-
}
|
|
156
|
-
return drizzle(postgres(databaseUrl));
|
|
157
|
-
};
|
|
158
|
-
|
|
159
|
-
// src/analytics/runtime-usage-aggregator.ts
|
|
160
|
-
import { and, eq, inArray } from "drizzle-orm";
|
|
161
|
-
|
|
162
|
-
// src/analytics/runtime-usage-trust-domain.ts
|
|
163
|
-
var MIN_TRUSTED_GAME_ACTIVE_SECONDS = 15;
|
|
164
|
-
var MIN_TRUSTED_ELIGIBLE_PLAYTIME_SECONDS = 15;
|
|
165
|
-
var SHORT_SESSION_RECONNECT_CHURN_MAX_ELIGIBLE_SECONDS = 120;
|
|
166
|
-
var SHORT_SESSION_RECONNECT_OVERFLOW_THRESHOLD = 3;
|
|
167
|
-
var clampEnd = (endedAt, referenceTime) => endedAt && endedAt <= referenceTime ? endedAt : referenceTime;
|
|
168
|
-
var overlapsGameSegment = (gameSegment, controllerSegment, referenceTime) => {
|
|
169
|
-
const start = Math.max(
|
|
170
|
-
gameSegment.startedAt.getTime(),
|
|
171
|
-
controllerSegment.startedAt.getTime()
|
|
172
|
-
);
|
|
173
|
-
const end = Math.min(
|
|
174
|
-
clampEnd(gameSegment.endedAt, referenceTime).getTime(),
|
|
175
|
-
clampEnd(controllerSegment.endedAt, referenceTime).getTime()
|
|
176
|
-
);
|
|
177
|
-
return end > start;
|
|
178
|
-
};
|
|
179
|
-
var evaluateRuntimeUsageSessionTrust = (gameSegment, controllerSegments, gameActiveSeconds, rawEligiblePlaytimeSeconds, referenceTime) => {
|
|
180
|
-
const trustFlags = [];
|
|
181
|
-
if (gameActiveSeconds < MIN_TRUSTED_GAME_ACTIVE_SECONDS) {
|
|
182
|
-
trustFlags.push("below_minimum_game_active_seconds");
|
|
183
|
-
}
|
|
184
|
-
if (rawEligiblePlaytimeSeconds < MIN_TRUSTED_ELIGIBLE_PLAYTIME_SECONDS) {
|
|
185
|
-
trustFlags.push("below_minimum_eligible_seconds");
|
|
186
|
-
}
|
|
187
|
-
const overlappingControllerSegments = controllerSegments.filter(
|
|
188
|
-
(controllerSegment) => overlapsGameSegment(gameSegment, controllerSegment, referenceTime)
|
|
189
|
-
);
|
|
190
|
-
const uniqueControllerCount = new Set(
|
|
191
|
-
overlappingControllerSegments.map(
|
|
192
|
-
(controllerSegment) => controllerSegment.controllerId
|
|
193
|
-
)
|
|
194
|
-
).size;
|
|
195
|
-
const reconnectOverflow = Math.max(
|
|
196
|
-
0,
|
|
197
|
-
overlappingControllerSegments.length - uniqueControllerCount
|
|
198
|
-
);
|
|
199
|
-
if (reconnectOverflow >= SHORT_SESSION_RECONNECT_OVERFLOW_THRESHOLD && rawEligiblePlaytimeSeconds <= SHORT_SESSION_RECONNECT_CHURN_MAX_ELIGIBLE_SECONDS) {
|
|
200
|
-
trustFlags.push("reconnect_churn_detected");
|
|
201
|
-
}
|
|
202
|
-
return {
|
|
203
|
-
trustFlags,
|
|
204
|
-
trustedEligiblePlaytimeSeconds: trustFlags.length > 0 ? 0 : rawEligiblePlaytimeSeconds
|
|
205
|
-
};
|
|
206
|
-
};
|
|
207
|
-
|
|
208
|
-
// src/analytics/runtime-usage-aggregates-domain.ts
|
|
209
|
-
var clampEnd2 = (endedAt, referenceTime) => endedAt && endedAt <= referenceTime ? endedAt : referenceTime;
|
|
210
|
-
var durationSeconds = (startedAt, endedAt, referenceTime) => {
|
|
211
|
-
const end = clampEnd2(endedAt, referenceTime);
|
|
212
|
-
return Math.max(0, Math.floor((end.getTime() - startedAt.getTime()) / 1e3));
|
|
213
|
-
};
|
|
214
|
-
var overlapSeconds = (left, right, referenceTime) => {
|
|
215
|
-
const start = Math.max(left.startedAt.getTime(), right.startedAt.getTime());
|
|
216
|
-
const end = Math.min(
|
|
217
|
-
clampEnd2(left.endedAt, referenceTime).getTime(),
|
|
218
|
-
clampEnd2(right.endedAt, referenceTime).getTime()
|
|
219
|
-
);
|
|
220
|
-
return Math.max(0, Math.floor((end - start) / 1e3));
|
|
221
|
-
};
|
|
222
|
-
var peakConcurrentControllers = (gameSegment, controllerSegments, referenceTime) => {
|
|
223
|
-
const points = [];
|
|
224
|
-
for (const controllerSegment of controllerSegments) {
|
|
225
|
-
const overlapStart = Math.max(
|
|
226
|
-
gameSegment.startedAt.getTime(),
|
|
227
|
-
controllerSegment.startedAt.getTime()
|
|
228
|
-
);
|
|
229
|
-
const overlapEnd = Math.min(
|
|
230
|
-
clampEnd2(gameSegment.endedAt, referenceTime).getTime(),
|
|
231
|
-
clampEnd2(controllerSegment.endedAt, referenceTime).getTime()
|
|
232
|
-
);
|
|
233
|
-
if (overlapEnd <= overlapStart) {
|
|
234
|
-
continue;
|
|
235
|
-
}
|
|
236
|
-
points.push({ time: overlapStart, delta: 1 });
|
|
237
|
-
points.push({ time: overlapEnd, delta: -1 });
|
|
238
|
-
}
|
|
239
|
-
points.sort((a, b) => {
|
|
240
|
-
if (a.time !== b.time) {
|
|
241
|
-
return a.time - b.time;
|
|
242
|
-
}
|
|
243
|
-
return a.delta - b.delta;
|
|
244
|
-
});
|
|
245
|
-
let active = 0;
|
|
246
|
-
let peak = 0;
|
|
247
|
-
for (const point of points) {
|
|
248
|
-
active += point.delta;
|
|
249
|
-
peak = Math.max(peak, active);
|
|
250
|
-
}
|
|
251
|
-
return peak;
|
|
252
|
-
};
|
|
253
|
-
var toUtcDateBucket = (value) => value.toISOString().slice(0, 10);
|
|
254
|
-
var buildRuntimeUsageGameSessionMetrics = (gameSegments, controllerSegments, eligibleSegments, referenceTime) => gameSegments.map((gameSegment) => {
|
|
255
|
-
const gameActiveSeconds = durationSeconds(
|
|
256
|
-
gameSegment.startedAt,
|
|
257
|
-
gameSegment.endedAt,
|
|
258
|
-
referenceTime
|
|
259
|
-
);
|
|
260
|
-
const controllerSeconds = controllerSegments.reduce(
|
|
261
|
-
(sum, controllerSegment) => sum + overlapSeconds(gameSegment, controllerSegment, referenceTime),
|
|
262
|
-
0
|
|
263
|
-
);
|
|
264
|
-
const rawEligiblePlaytimeSeconds = eligibleSegments.reduce(
|
|
265
|
-
(sum, eligibleSegment) => sum + overlapSeconds(gameSegment, eligibleSegment, referenceTime),
|
|
266
|
-
0
|
|
267
|
-
);
|
|
268
|
-
const trust = evaluateRuntimeUsageSessionTrust(
|
|
269
|
-
gameSegment,
|
|
270
|
-
controllerSegments,
|
|
271
|
-
gameActiveSeconds,
|
|
272
|
-
rawEligiblePlaytimeSeconds,
|
|
273
|
-
referenceTime
|
|
274
|
-
);
|
|
275
|
-
return {
|
|
276
|
-
id: gameSegment.id,
|
|
277
|
-
runtimeSessionId: gameSegment.runtimeSessionId,
|
|
278
|
-
roomId: gameSegment.roomId,
|
|
279
|
-
appId: gameSegment.appId,
|
|
280
|
-
gameId: gameSegment.gameId,
|
|
281
|
-
startedAt: gameSegment.startedAt,
|
|
282
|
-
endedAt: gameSegment.endedAt,
|
|
283
|
-
controllerSeconds,
|
|
284
|
-
rawEligiblePlaytimeSeconds,
|
|
285
|
-
eligiblePlaytimeSeconds: trust.trustedEligiblePlaytimeSeconds,
|
|
286
|
-
trustFlags: trust.trustFlags,
|
|
287
|
-
peakConcurrentControllers: peakConcurrentControllers(
|
|
288
|
-
gameSegment,
|
|
289
|
-
controllerSegments,
|
|
290
|
-
referenceTime
|
|
291
|
-
)
|
|
292
|
-
};
|
|
28
|
+
var createRoomAnalyticsState = (authority, now = Date.now()) => ({
|
|
29
|
+
runtimeSessionId: crypto.randomUUID(),
|
|
30
|
+
startedAt: now,
|
|
31
|
+
appId: authority?.appId,
|
|
32
|
+
gameId: authority?.gameId,
|
|
33
|
+
hostVerifiedVia: authority?.verifiedVia,
|
|
34
|
+
hostVerifiedOrigin: authority?.verifiedOrigin,
|
|
35
|
+
hostSessionKind: authority?.hostSessionKind ?? "system"
|
|
293
36
|
});
|
|
294
|
-
var
|
|
295
|
-
|
|
296
|
-
for (const sessionMetric of sessionMetrics) {
|
|
297
|
-
const bucketDate = toUtcDateBucket(sessionMetric.startedAt);
|
|
298
|
-
const id = `${sessionMetric.gameId}:${sessionMetric.appId ?? "no-app"}:${bucketDate}`;
|
|
299
|
-
const current = aggregateMap.get(id);
|
|
300
|
-
const totalGameActiveSeconds = durationSeconds(
|
|
301
|
-
sessionMetric.startedAt,
|
|
302
|
-
sessionMetric.endedAt,
|
|
303
|
-
referenceTime
|
|
304
|
-
);
|
|
305
|
-
const lastActivityAt = clampEnd2(sessionMetric.endedAt, referenceTime);
|
|
306
|
-
if (!current) {
|
|
307
|
-
aggregateMap.set(id, {
|
|
308
|
-
id,
|
|
309
|
-
bucketDate,
|
|
310
|
-
appId: sessionMetric.appId,
|
|
311
|
-
gameId: sessionMetric.gameId,
|
|
312
|
-
sessionCount: 1,
|
|
313
|
-
totalGameActiveSeconds,
|
|
314
|
-
totalControllerSeconds: sessionMetric.controllerSeconds,
|
|
315
|
-
totalRawEligiblePlaytimeSeconds: sessionMetric.rawEligiblePlaytimeSeconds,
|
|
316
|
-
totalEligiblePlaytimeSeconds: sessionMetric.eligiblePlaytimeSeconds,
|
|
317
|
-
guardedSessionCount: sessionMetric.trustFlags.length > 0 ? 1 : 0,
|
|
318
|
-
peakConcurrentControllers: sessionMetric.peakConcurrentControllers,
|
|
319
|
-
lastActivityAt
|
|
320
|
-
});
|
|
321
|
-
continue;
|
|
322
|
-
}
|
|
323
|
-
current.sessionCount += 1;
|
|
324
|
-
current.totalGameActiveSeconds += totalGameActiveSeconds;
|
|
325
|
-
current.totalControllerSeconds += sessionMetric.controllerSeconds;
|
|
326
|
-
current.totalRawEligiblePlaytimeSeconds += sessionMetric.rawEligiblePlaytimeSeconds;
|
|
327
|
-
current.totalEligiblePlaytimeSeconds += sessionMetric.eligiblePlaytimeSeconds;
|
|
328
|
-
current.guardedSessionCount += sessionMetric.trustFlags.length > 0 ? 1 : 0;
|
|
329
|
-
current.peakConcurrentControllers = Math.max(
|
|
330
|
-
current.peakConcurrentControllers,
|
|
331
|
-
sessionMetric.peakConcurrentControllers
|
|
332
|
-
);
|
|
333
|
-
current.lastActivityAt = current.lastActivityAt && current.lastActivityAt > lastActivityAt ? current.lastActivityAt : lastActivityAt;
|
|
334
|
-
}
|
|
335
|
-
return Array.from(aggregateMap.values());
|
|
336
|
-
};
|
|
337
|
-
|
|
338
|
-
// src/analytics/runtime-usage-aggregator.ts
|
|
339
|
-
var refreshRuntimeUsageAggregatesForSession = async (db, runtimeSessionId, referenceTime) => {
|
|
340
|
-
const previousSessionMetrics = await db.select().from(runtimeUsageGameSessionMetrics).where(
|
|
341
|
-
eq(runtimeUsageGameSessionMetrics.runtimeSessionId, runtimeSessionId)
|
|
342
|
-
);
|
|
343
|
-
const [gameSegments, controllerSegments, eligibleSegments] = await Promise.all([
|
|
344
|
-
db.select().from(runtimeUsageGameSegments).where(eq(runtimeUsageGameSegments.runtimeSessionId, runtimeSessionId)),
|
|
345
|
-
db.select().from(runtimeUsageControllerSegments).where(
|
|
346
|
-
eq(runtimeUsageControllerSegments.runtimeSessionId, runtimeSessionId)
|
|
347
|
-
),
|
|
348
|
-
db.select().from(runtimeUsageEligibleSegments).where(
|
|
349
|
-
eq(runtimeUsageEligibleSegments.runtimeSessionId, runtimeSessionId)
|
|
350
|
-
)
|
|
351
|
-
]);
|
|
352
|
-
const sessionMetrics = buildRuntimeUsageGameSessionMetrics(
|
|
353
|
-
gameSegments,
|
|
354
|
-
controllerSegments,
|
|
355
|
-
eligibleSegments,
|
|
356
|
-
referenceTime
|
|
357
|
-
);
|
|
358
|
-
await db.delete(runtimeUsageGameSessionMetrics).where(
|
|
359
|
-
eq(runtimeUsageGameSessionMetrics.runtimeSessionId, runtimeSessionId)
|
|
360
|
-
);
|
|
361
|
-
if (sessionMetrics.length > 0) {
|
|
362
|
-
await db.insert(runtimeUsageGameSessionMetrics).values(
|
|
363
|
-
sessionMetrics.map((sessionMetric) => ({
|
|
364
|
-
id: sessionMetric.id,
|
|
365
|
-
runtimeSessionId: sessionMetric.runtimeSessionId,
|
|
366
|
-
roomId: sessionMetric.roomId,
|
|
367
|
-
appId: sessionMetric.appId ?? null,
|
|
368
|
-
gameId: sessionMetric.gameId,
|
|
369
|
-
startedAt: sessionMetric.startedAt,
|
|
370
|
-
endedAt: sessionMetric.endedAt,
|
|
371
|
-
controllerSeconds: sessionMetric.controllerSeconds,
|
|
372
|
-
rawEligiblePlaytimeSeconds: sessionMetric.rawEligiblePlaytimeSeconds,
|
|
373
|
-
eligiblePlaytimeSeconds: sessionMetric.eligiblePlaytimeSeconds,
|
|
374
|
-
trustFlags: sessionMetric.trustFlags,
|
|
375
|
-
peakConcurrentControllers: sessionMetric.peakConcurrentControllers,
|
|
376
|
-
updatedAt: referenceTime
|
|
377
|
-
}))
|
|
378
|
-
);
|
|
379
|
-
}
|
|
380
|
-
const affectedGameIds = Array.from(
|
|
381
|
-
new Set(
|
|
382
|
-
[...previousSessionMetrics, ...sessionMetrics].map(
|
|
383
|
-
(metric) => metric.gameId
|
|
384
|
-
)
|
|
385
|
-
)
|
|
386
|
-
);
|
|
387
|
-
const affectedBucketDates = Array.from(
|
|
388
|
-
new Set(
|
|
389
|
-
[...previousSessionMetrics, ...sessionMetrics].map(
|
|
390
|
-
(metric) => metric.startedAt.toISOString().slice(0, 10)
|
|
391
|
-
)
|
|
392
|
-
)
|
|
393
|
-
);
|
|
394
|
-
if (affectedGameIds.length === 0 || affectedBucketDates.length === 0) {
|
|
395
|
-
return;
|
|
396
|
-
}
|
|
397
|
-
const relevantSessionMetrics = await db.select().from(runtimeUsageGameSessionMetrics).where(inArray(runtimeUsageGameSessionMetrics.gameId, affectedGameIds));
|
|
398
|
-
const recomputedDailyMetrics = buildRuntimeUsageDailyGameMetrics(
|
|
399
|
-
relevantSessionMetrics.map((metric) => ({
|
|
400
|
-
...metric,
|
|
401
|
-
appId: metric.appId ?? void 0
|
|
402
|
-
})),
|
|
403
|
-
referenceTime
|
|
404
|
-
).filter((metric) => affectedBucketDates.includes(metric.bucketDate));
|
|
405
|
-
await db.delete(runtimeUsageDailyGameMetrics).where(
|
|
406
|
-
and(
|
|
407
|
-
inArray(runtimeUsageDailyGameMetrics.gameId, affectedGameIds),
|
|
408
|
-
inArray(runtimeUsageDailyGameMetrics.bucketDate, affectedBucketDates)
|
|
409
|
-
)
|
|
410
|
-
);
|
|
411
|
-
if (recomputedDailyMetrics.length > 0) {
|
|
412
|
-
await db.insert(runtimeUsageDailyGameMetrics).values(
|
|
413
|
-
recomputedDailyMetrics.map((metric) => ({
|
|
414
|
-
id: metric.id,
|
|
415
|
-
bucketDate: metric.bucketDate,
|
|
416
|
-
appId: metric.appId ?? null,
|
|
417
|
-
gameId: metric.gameId,
|
|
418
|
-
sessionCount: metric.sessionCount,
|
|
419
|
-
totalGameActiveSeconds: metric.totalGameActiveSeconds,
|
|
420
|
-
totalControllerSeconds: metric.totalControllerSeconds,
|
|
421
|
-
totalRawEligiblePlaytimeSeconds: metric.totalRawEligiblePlaytimeSeconds,
|
|
422
|
-
totalEligiblePlaytimeSeconds: metric.totalEligiblePlaytimeSeconds,
|
|
423
|
-
guardedSessionCount: metric.guardedSessionCount,
|
|
424
|
-
peakConcurrentControllers: metric.peakConcurrentControllers,
|
|
425
|
-
lastActivityAt: metric.lastActivityAt,
|
|
426
|
-
updatedAt: referenceTime
|
|
427
|
-
}))
|
|
428
|
-
);
|
|
429
|
-
}
|
|
430
|
-
};
|
|
431
|
-
|
|
432
|
-
// src/analytics/runtime-usage-projector.ts
|
|
433
|
-
import { and as and2, desc, eq as eq2, isNull } from "drizzle-orm";
|
|
434
|
-
|
|
435
|
-
// src/analytics/runtime-usage-projection-domain.ts
|
|
436
|
-
var getPayloadString = (event, key) => {
|
|
437
|
-
const value = event.payload?.[key];
|
|
438
|
-
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
439
|
-
};
|
|
440
|
-
var resolveControllerId = (event) => getPayloadString(event, "controllerId");
|
|
441
|
-
var resolveOpenEligibleGameId = (event, openGameId) => event.gameId ?? openGameId;
|
|
442
|
-
var projectRuntimeUsageEvent = (event, openState) => {
|
|
443
|
-
const actions = [];
|
|
444
|
-
switch (event.kind) {
|
|
445
|
-
case "controller_joined": {
|
|
446
|
-
const controllerId = resolveControllerId(event);
|
|
447
|
-
if (!controllerId) {
|
|
448
|
-
return actions;
|
|
449
|
-
}
|
|
450
|
-
if (!openState.hasOpenControllerSegmentForController) {
|
|
451
|
-
actions.push({
|
|
452
|
-
type: "open_controller_segment",
|
|
453
|
-
controllerId
|
|
454
|
-
});
|
|
455
|
-
}
|
|
456
|
-
if (openState.hasOpenGameSegment && openState.openControllerCount === 0 && !openState.hasOpenEligibleSegment) {
|
|
457
|
-
actions.push({
|
|
458
|
-
type: "open_eligible_segment",
|
|
459
|
-
gameId: resolveOpenEligibleGameId(event, openState.openGameId),
|
|
460
|
-
reason: "controller_joined"
|
|
461
|
-
});
|
|
462
|
-
}
|
|
463
|
-
return actions;
|
|
464
|
-
}
|
|
465
|
-
case "controller_disconnected":
|
|
466
|
-
case "controller_left": {
|
|
467
|
-
const controllerId = resolveControllerId(event);
|
|
468
|
-
if (!controllerId) {
|
|
469
|
-
return actions;
|
|
470
|
-
}
|
|
471
|
-
if (openState.hasOpenControllerSegmentForController) {
|
|
472
|
-
actions.push({
|
|
473
|
-
type: "close_controller_segment",
|
|
474
|
-
controllerId,
|
|
475
|
-
reason: event.kind
|
|
476
|
-
});
|
|
477
|
-
}
|
|
478
|
-
if (openState.hasOpenGameSegment && openState.openControllerCount === 1 && openState.hasOpenEligibleSegment) {
|
|
479
|
-
actions.push({
|
|
480
|
-
type: "close_eligible_segment",
|
|
481
|
-
reason: event.kind
|
|
482
|
-
});
|
|
483
|
-
}
|
|
484
|
-
return actions;
|
|
485
|
-
}
|
|
486
|
-
case "game_became_active": {
|
|
487
|
-
const gameId = event.gameId;
|
|
488
|
-
if (!gameId) {
|
|
489
|
-
return actions;
|
|
490
|
-
}
|
|
491
|
-
if (!openState.hasOpenGameSegment) {
|
|
492
|
-
actions.push({
|
|
493
|
-
type: "open_game_segment",
|
|
494
|
-
gameId,
|
|
495
|
-
reason: getPayloadString(event, "activation")
|
|
496
|
-
});
|
|
497
|
-
}
|
|
498
|
-
if (openState.openControllerCount > 0 && !openState.hasOpenEligibleSegment) {
|
|
499
|
-
actions.push({
|
|
500
|
-
type: "open_eligible_segment",
|
|
501
|
-
gameId,
|
|
502
|
-
reason: "game_became_active"
|
|
503
|
-
});
|
|
504
|
-
}
|
|
505
|
-
return actions;
|
|
506
|
-
}
|
|
507
|
-
case "game_returned_to_system": {
|
|
508
|
-
if (openState.hasOpenEligibleSegment) {
|
|
509
|
-
actions.push({
|
|
510
|
-
type: "close_eligible_segment",
|
|
511
|
-
reason: getPayloadString(event, "reason") ?? "game_returned_to_system"
|
|
512
|
-
});
|
|
513
|
-
}
|
|
514
|
-
if (openState.hasOpenGameSegment) {
|
|
515
|
-
actions.push({
|
|
516
|
-
type: "close_all_game_segments",
|
|
517
|
-
reason: getPayloadString(event, "reason") ?? "game_returned_to_system"
|
|
518
|
-
});
|
|
519
|
-
}
|
|
520
|
-
return actions;
|
|
521
|
-
}
|
|
522
|
-
case "room_closed": {
|
|
523
|
-
if (openState.hasOpenEligibleSegment) {
|
|
524
|
-
actions.push({
|
|
525
|
-
type: "close_eligible_segment",
|
|
526
|
-
reason: getPayloadString(event, "reason") ?? "room_closed"
|
|
527
|
-
});
|
|
528
|
-
}
|
|
529
|
-
if (openState.hasOpenGameSegment) {
|
|
530
|
-
actions.push({
|
|
531
|
-
type: "close_all_game_segments",
|
|
532
|
-
reason: getPayloadString(event, "reason") ?? "room_closed"
|
|
533
|
-
});
|
|
534
|
-
}
|
|
535
|
-
if (openState.openControllerCount > 0) {
|
|
536
|
-
actions.push({
|
|
537
|
-
type: "close_all_controller_segments",
|
|
538
|
-
reason: getPayloadString(event, "reason") ?? "room_closed"
|
|
539
|
-
});
|
|
540
|
-
}
|
|
541
|
-
return actions;
|
|
542
|
-
}
|
|
543
|
-
default:
|
|
544
|
-
return actions;
|
|
545
|
-
}
|
|
546
|
-
};
|
|
547
|
-
|
|
548
|
-
// src/analytics/runtime-usage-rebuild-domain.ts
|
|
549
|
-
var buildControllerSegmentId = (runtimeSessionId, controllerId, startEventId) => `ctrl:${runtimeSessionId}:${controllerId}:${startEventId}`;
|
|
550
|
-
var buildGameSegmentId = (runtimeSessionId, gameId, startEventId) => `game:${runtimeSessionId}:${gameId}:${startEventId}`;
|
|
551
|
-
var buildEligibleSegmentId = (runtimeSessionId, gameId, startEventId) => `eligible:${runtimeSessionId}:${gameId ?? "unknown"}:${startEventId}`;
|
|
552
|
-
|
|
553
|
-
// src/analytics/runtime-usage-projector.ts
|
|
554
|
-
var projectRuntimeUsageEventToSegments = async (db, event) => {
|
|
555
|
-
if (!event.runtimeSessionId || !event.roomId) {
|
|
37
|
+
var syncRoomAnalyticsState = (analytics, authority) => {
|
|
38
|
+
if (!authority) {
|
|
556
39
|
return;
|
|
557
40
|
}
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
controllerId: runtimeUsageControllerSegments.controllerId
|
|
561
|
-
}).from(runtimeUsageControllerSegments).where(
|
|
562
|
-
and2(
|
|
563
|
-
eq2(
|
|
564
|
-
runtimeUsageControllerSegments.runtimeSessionId,
|
|
565
|
-
event.runtimeSessionId
|
|
566
|
-
),
|
|
567
|
-
isNull(runtimeUsageControllerSegments.endedAt)
|
|
568
|
-
)
|
|
569
|
-
);
|
|
570
|
-
const [openGameSegment] = await db.select({
|
|
571
|
-
id: runtimeUsageGameSegments.id,
|
|
572
|
-
gameId: runtimeUsageGameSegments.gameId
|
|
573
|
-
}).from(runtimeUsageGameSegments).where(
|
|
574
|
-
and2(
|
|
575
|
-
eq2(runtimeUsageGameSegments.runtimeSessionId, event.runtimeSessionId),
|
|
576
|
-
isNull(runtimeUsageGameSegments.endedAt)
|
|
577
|
-
)
|
|
578
|
-
).orderBy(desc(runtimeUsageGameSegments.startedAt)).limit(1);
|
|
579
|
-
const [openEligibleSegment] = await db.select({
|
|
580
|
-
id: runtimeUsageEligibleSegments.id
|
|
581
|
-
}).from(runtimeUsageEligibleSegments).where(
|
|
582
|
-
and2(
|
|
583
|
-
eq2(
|
|
584
|
-
runtimeUsageEligibleSegments.runtimeSessionId,
|
|
585
|
-
event.runtimeSessionId
|
|
586
|
-
),
|
|
587
|
-
isNull(runtimeUsageEligibleSegments.endedAt)
|
|
588
|
-
)
|
|
589
|
-
).orderBy(desc(runtimeUsageEligibleSegments.startedAt)).limit(1);
|
|
590
|
-
const controllerId = typeof event.payload?.controllerId === "string" ? event.payload.controllerId : void 0;
|
|
591
|
-
const actions = projectRuntimeUsageEvent(event, {
|
|
592
|
-
openControllerCount: openControllerSegments.length,
|
|
593
|
-
hasOpenControllerSegmentForController: controllerId ? openControllerSegments.some(
|
|
594
|
-
(segment) => segment.controllerId === controllerId
|
|
595
|
-
) : false,
|
|
596
|
-
openGameId: openGameSegment?.gameId,
|
|
597
|
-
hasOpenGameSegment: Boolean(openGameSegment),
|
|
598
|
-
hasOpenEligibleSegment: Boolean(openEligibleSegment)
|
|
599
|
-
});
|
|
600
|
-
for (const action of actions) {
|
|
601
|
-
await applyProjectionAction(db, event, action);
|
|
602
|
-
}
|
|
603
|
-
};
|
|
604
|
-
var applyProjectionAction = async (db, event, action) => {
|
|
605
|
-
const occurredAt = new Date(event.occurredAt);
|
|
606
|
-
switch (action.type) {
|
|
607
|
-
case "open_controller_segment":
|
|
608
|
-
await db.insert(runtimeUsageControllerSegments).values({
|
|
609
|
-
id: buildControllerSegmentId(
|
|
610
|
-
event.runtimeSessionId,
|
|
611
|
-
action.controllerId,
|
|
612
|
-
event.id
|
|
613
|
-
),
|
|
614
|
-
runtimeSessionId: event.runtimeSessionId,
|
|
615
|
-
roomId: event.roomId,
|
|
616
|
-
appId: event.appId,
|
|
617
|
-
controllerId: action.controllerId,
|
|
618
|
-
startedAt: occurredAt,
|
|
619
|
-
startEventId: event.id
|
|
620
|
-
});
|
|
621
|
-
return;
|
|
622
|
-
case "close_controller_segment":
|
|
623
|
-
await db.update(runtimeUsageControllerSegments).set({
|
|
624
|
-
endedAt: occurredAt,
|
|
625
|
-
endEventId: event.id,
|
|
626
|
-
endReason: action.reason
|
|
627
|
-
}).where(
|
|
628
|
-
and2(
|
|
629
|
-
eq2(
|
|
630
|
-
runtimeUsageControllerSegments.runtimeSessionId,
|
|
631
|
-
event.runtimeSessionId
|
|
632
|
-
),
|
|
633
|
-
eq2(
|
|
634
|
-
runtimeUsageControllerSegments.controllerId,
|
|
635
|
-
action.controllerId
|
|
636
|
-
),
|
|
637
|
-
isNull(runtimeUsageControllerSegments.endedAt)
|
|
638
|
-
)
|
|
639
|
-
);
|
|
640
|
-
return;
|
|
641
|
-
case "close_all_controller_segments":
|
|
642
|
-
await db.update(runtimeUsageControllerSegments).set({
|
|
643
|
-
endedAt: occurredAt,
|
|
644
|
-
endEventId: event.id,
|
|
645
|
-
endReason: action.reason
|
|
646
|
-
}).where(
|
|
647
|
-
and2(
|
|
648
|
-
eq2(
|
|
649
|
-
runtimeUsageControllerSegments.runtimeSessionId,
|
|
650
|
-
event.runtimeSessionId
|
|
651
|
-
),
|
|
652
|
-
isNull(runtimeUsageControllerSegments.endedAt)
|
|
653
|
-
)
|
|
654
|
-
);
|
|
655
|
-
return;
|
|
656
|
-
case "open_game_segment":
|
|
657
|
-
await db.insert(runtimeUsageGameSegments).values({
|
|
658
|
-
id: buildGameSegmentId(
|
|
659
|
-
event.runtimeSessionId,
|
|
660
|
-
action.gameId,
|
|
661
|
-
event.id
|
|
662
|
-
),
|
|
663
|
-
runtimeSessionId: event.runtimeSessionId,
|
|
664
|
-
roomId: event.roomId,
|
|
665
|
-
appId: event.appId,
|
|
666
|
-
gameId: action.gameId,
|
|
667
|
-
startedAt: occurredAt,
|
|
668
|
-
startEventId: event.id,
|
|
669
|
-
startReason: action.reason
|
|
670
|
-
});
|
|
671
|
-
return;
|
|
672
|
-
case "close_all_game_segments":
|
|
673
|
-
await db.update(runtimeUsageGameSegments).set({
|
|
674
|
-
endedAt: occurredAt,
|
|
675
|
-
endEventId: event.id,
|
|
676
|
-
endReason: action.reason
|
|
677
|
-
}).where(
|
|
678
|
-
and2(
|
|
679
|
-
eq2(
|
|
680
|
-
runtimeUsageGameSegments.runtimeSessionId,
|
|
681
|
-
event.runtimeSessionId
|
|
682
|
-
),
|
|
683
|
-
isNull(runtimeUsageGameSegments.endedAt)
|
|
684
|
-
)
|
|
685
|
-
);
|
|
686
|
-
return;
|
|
687
|
-
case "open_eligible_segment":
|
|
688
|
-
await db.insert(runtimeUsageEligibleSegments).values({
|
|
689
|
-
id: buildEligibleSegmentId(
|
|
690
|
-
event.runtimeSessionId,
|
|
691
|
-
action.gameId,
|
|
692
|
-
event.id
|
|
693
|
-
),
|
|
694
|
-
runtimeSessionId: event.runtimeSessionId,
|
|
695
|
-
roomId: event.roomId,
|
|
696
|
-
appId: event.appId,
|
|
697
|
-
gameId: action.gameId,
|
|
698
|
-
startedAt: occurredAt,
|
|
699
|
-
startEventId: event.id,
|
|
700
|
-
startReason: action.reason
|
|
701
|
-
});
|
|
702
|
-
return;
|
|
703
|
-
case "close_eligible_segment":
|
|
704
|
-
await db.update(runtimeUsageEligibleSegments).set({
|
|
705
|
-
endedAt: occurredAt,
|
|
706
|
-
endEventId: event.id,
|
|
707
|
-
endReason: action.reason
|
|
708
|
-
}).where(
|
|
709
|
-
and2(
|
|
710
|
-
eq2(
|
|
711
|
-
runtimeUsageEligibleSegments.runtimeSessionId,
|
|
712
|
-
event.runtimeSessionId
|
|
713
|
-
),
|
|
714
|
-
isNull(runtimeUsageEligibleSegments.endedAt)
|
|
715
|
-
)
|
|
716
|
-
);
|
|
717
|
-
return;
|
|
718
|
-
}
|
|
719
|
-
};
|
|
720
|
-
|
|
721
|
-
// src/analytics/runtime-usage-ledger.ts
|
|
722
|
-
var createDatabaseRuntimeUsageLedgerPublisher = (logger, db) => {
|
|
723
|
-
const ledgerLogger = logger.child({ component: "runtime-usage-ledger" });
|
|
724
|
-
return {
|
|
725
|
-
publish: (event) => {
|
|
726
|
-
if (!db) {
|
|
727
|
-
return;
|
|
728
|
-
}
|
|
729
|
-
void persistRuntimeUsageEvent(db, event).catch((err) => {
|
|
730
|
-
ledgerLogger.warn(
|
|
731
|
-
{
|
|
732
|
-
err,
|
|
733
|
-
eventId: event.id,
|
|
734
|
-
kind: event.kind,
|
|
735
|
-
runtimeSessionId: event.runtimeSessionId,
|
|
736
|
-
roomId: event.roomId
|
|
737
|
-
},
|
|
738
|
-
"Failed to persist runtime usage event"
|
|
739
|
-
);
|
|
740
|
-
});
|
|
741
|
-
}
|
|
742
|
-
};
|
|
743
|
-
};
|
|
744
|
-
var persistRuntimeUsageEvent = async (db, event) => {
|
|
745
|
-
await db.transaction(async (tx) => {
|
|
746
|
-
if (event.runtimeSessionId && event.roomId && event.runtimeSessionStartedAt !== void 0) {
|
|
747
|
-
await tx.insert(runtimeUsageSessions).values({
|
|
748
|
-
id: event.runtimeSessionId,
|
|
749
|
-
roomId: event.roomId,
|
|
750
|
-
appId: event.appId,
|
|
751
|
-
hostVerifiedVia: event.hostVerifiedVia,
|
|
752
|
-
hostVerifiedOrigin: event.hostVerifiedOrigin,
|
|
753
|
-
startedAt: new Date(event.runtimeSessionStartedAt)
|
|
754
|
-
}).onConflictDoNothing();
|
|
755
|
-
}
|
|
756
|
-
const insertedEvents = await tx.insert(runtimeUsageEvents).values({
|
|
757
|
-
id: event.id,
|
|
758
|
-
kind: event.kind,
|
|
759
|
-
occurredAt: new Date(event.occurredAt),
|
|
760
|
-
runtimeSessionId: event.runtimeSessionId,
|
|
761
|
-
roomId: event.roomId,
|
|
762
|
-
appId: event.appId,
|
|
763
|
-
gameId: event.gameId,
|
|
764
|
-
hostVerifiedVia: event.hostVerifiedVia,
|
|
765
|
-
hostVerifiedOrigin: event.hostVerifiedOrigin,
|
|
766
|
-
payload: event.payload ?? {}
|
|
767
|
-
}).onConflictDoNothing().returning({ id: runtimeUsageEvents.id });
|
|
768
|
-
if (insertedEvents.length === 0) {
|
|
769
|
-
return;
|
|
770
|
-
}
|
|
771
|
-
await projectRuntimeUsageEventToSegments(tx, event);
|
|
772
|
-
if (event.runtimeSessionId) {
|
|
773
|
-
await refreshRuntimeUsageAggregatesForSession(
|
|
774
|
-
tx,
|
|
775
|
-
event.runtimeSessionId,
|
|
776
|
-
new Date(event.occurredAt)
|
|
777
|
-
);
|
|
778
|
-
}
|
|
779
|
-
});
|
|
780
|
-
};
|
|
781
|
-
|
|
782
|
-
// src/env/database-url-policy.ts
|
|
783
|
-
var LOCAL_DATABASE_HOSTS = /* @__PURE__ */ new Set([
|
|
784
|
-
"127.0.0.1",
|
|
785
|
-
"::1",
|
|
786
|
-
"host.docker.internal",
|
|
787
|
-
"localhost",
|
|
788
|
-
"postgres"
|
|
789
|
-
]);
|
|
790
|
-
var trimToUndefined = (value) => {
|
|
791
|
-
if (typeof value !== "string") {
|
|
792
|
-
return void 0;
|
|
41
|
+
if (analytics.appId === void 0 && authority.appId) {
|
|
42
|
+
analytics.appId = authority.appId;
|
|
793
43
|
}
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
};
|
|
797
|
-
var normalizeHostname = (value) => value.trim().replace(/^\[|\]$/g, "").toLowerCase();
|
|
798
|
-
var isLocalDatabaseHostname = (hostname) => LOCAL_DATABASE_HOSTS.has(normalizeHostname(hostname));
|
|
799
|
-
var resolveNodeEnv = (env) => trimToUndefined(env.NODE_ENV) ?? "development";
|
|
800
|
-
var REMOTE_DATABASE_BLOCKED_MESSAGE = "Non-local DATABASE_URL is blocked outside production unless AIR_JAM_ALLOW_REMOTE_DATABASE=enabled.";
|
|
801
|
-
var isLocalDatabaseUrl = (databaseUrl) => {
|
|
802
|
-
try {
|
|
803
|
-
const parsed = new URL(databaseUrl);
|
|
804
|
-
if (!parsed.hostname) {
|
|
805
|
-
return true;
|
|
806
|
-
}
|
|
807
|
-
return isLocalDatabaseHostname(parsed.hostname);
|
|
808
|
-
} catch {
|
|
809
|
-
return false;
|
|
44
|
+
if (analytics.gameId === void 0 && authority.gameId) {
|
|
45
|
+
analytics.gameId = authority.gameId;
|
|
810
46
|
}
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
const databaseUrl = trimToUndefined(env.DATABASE_URL);
|
|
814
|
-
if (!databaseUrl) {
|
|
815
|
-
return { remoteDatabaseBlocked: false };
|
|
47
|
+
if (analytics.hostVerifiedVia === void 0 && authority.verifiedVia) {
|
|
48
|
+
analytics.hostVerifiedVia = authority.verifiedVia;
|
|
816
49
|
}
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
if (allowRemoteDatabase || isLocalDatabaseUrl(databaseUrl)) {
|
|
820
|
-
return {
|
|
821
|
-
databaseUrl,
|
|
822
|
-
remoteDatabaseBlocked: false
|
|
823
|
-
};
|
|
50
|
+
if (analytics.hostVerifiedOrigin === void 0 && authority.verifiedOrigin !== void 0) {
|
|
51
|
+
analytics.hostVerifiedOrigin = authority.verifiedOrigin;
|
|
824
52
|
}
|
|
825
|
-
|
|
826
|
-
remoteDatabaseBlocked: true
|
|
827
|
-
};
|
|
53
|
+
analytics.hostSessionKind = authority.hostSessionKind;
|
|
828
54
|
};
|
|
55
|
+
var createRuntimeUsageEvent = (event) => ({
|
|
56
|
+
id: crypto.randomUUID(),
|
|
57
|
+
occurredAt: event.occurredAt ?? Date.now(),
|
|
58
|
+
...event
|
|
59
|
+
});
|
|
60
|
+
var createRoomRuntimeUsageEvent = (session, event) => createRuntimeUsageEvent({
|
|
61
|
+
...event,
|
|
62
|
+
runtimeSessionId: session.analytics.runtimeSessionId,
|
|
63
|
+
runtimeSessionStartedAt: session.analytics.startedAt,
|
|
64
|
+
roomId: session.roomId,
|
|
65
|
+
appId: session.analytics.appId,
|
|
66
|
+
gameId: event.gameId ?? session.activeGameId ?? session.analytics.gameId,
|
|
67
|
+
hostVerifiedVia: session.analytics.hostVerifiedVia,
|
|
68
|
+
hostVerifiedOrigin: session.analytics.hostVerifiedOrigin
|
|
69
|
+
});
|
|
829
70
|
|
|
830
71
|
// src/env/server-env.ts
|
|
831
72
|
import { z } from "zod";
|
|
832
|
-
var
|
|
73
|
+
var trimToUndefined = (value) => {
|
|
833
74
|
if (typeof value !== "string") {
|
|
834
75
|
return void 0;
|
|
835
76
|
}
|
|
836
77
|
const normalized = value.trim();
|
|
837
78
|
return normalized.length > 0 ? normalized : void 0;
|
|
838
79
|
};
|
|
839
|
-
var optionalEnvString = z.string().optional().transform((value) =>
|
|
80
|
+
var optionalEnvString = z.string().optional().transform((value) => trimToUndefined(value));
|
|
840
81
|
var createOptionalEnumSchema = (envKey, values) => optionalEnvString.transform((value, context) => {
|
|
841
82
|
if (!value) {
|
|
842
83
|
return void 0;
|
|
@@ -874,15 +115,6 @@ var normalizeAllowedOrigins = (rawAllowedOrigins) => {
|
|
|
874
115
|
}
|
|
875
116
|
return parsed;
|
|
876
117
|
};
|
|
877
|
-
var resolveAuthMode = ({
|
|
878
|
-
configuredAuthMode,
|
|
879
|
-
nodeEnv
|
|
880
|
-
}) => {
|
|
881
|
-
if (configuredAuthMode) {
|
|
882
|
-
return configuredAuthMode;
|
|
883
|
-
}
|
|
884
|
-
return nodeEnv === "production" ? "required" : "disabled";
|
|
885
|
-
};
|
|
886
118
|
var rawServerEnvSchema = z.object({
|
|
887
119
|
NODE_ENV: optionalEnvString,
|
|
888
120
|
PORT: createPositiveIntegerSchema("PORT", 4e3),
|
|
@@ -902,6 +134,10 @@ var rawServerEnvSchema = z.object({
|
|
|
902
134
|
"AIR_JAM_STATIC_APP_RATE_LIMIT_MAX",
|
|
903
135
|
120
|
|
904
136
|
),
|
|
137
|
+
AIR_JAM_RUNTIME_ERROR_REPORT_RATE_LIMIT_MAX: createPositiveIntegerSchema(
|
|
138
|
+
"AIR_JAM_RUNTIME_ERROR_REPORT_RATE_LIMIT_MAX",
|
|
139
|
+
30
|
|
140
|
+
),
|
|
905
141
|
AIR_JAM_ALLOWED_ORIGINS: optionalEnvString,
|
|
906
142
|
AIR_JAM_DEV_LOG_COLLECTOR: createOptionalEnumSchema(
|
|
907
143
|
"AIR_JAM_DEV_LOG_COLLECTOR",
|
|
@@ -916,64 +152,23 @@ var rawServerEnvSchema = z.object({
|
|
|
916
152
|
"AIR_JAM_TRUST_PROXY_HEADERS",
|
|
917
153
|
["auto", "enabled", "disabled"]
|
|
918
154
|
),
|
|
919
|
-
AIR_JAM_ALLOW_REMOTE_DATABASE: createOptionalEnumSchema(
|
|
920
|
-
"AIR_JAM_ALLOW_REMOTE_DATABASE",
|
|
921
|
-
["enabled", "disabled"]
|
|
922
|
-
),
|
|
923
155
|
AIR_JAM_MASTER_KEY: optionalEnvString,
|
|
924
|
-
AIR_JAM_HOST_GRANT_SECRET: optionalEnvString,
|
|
925
|
-
DATABASE_URL: optionalEnvString,
|
|
926
156
|
AIR_JAM_LOG_LEVEL: optionalEnvString,
|
|
927
157
|
AIR_JAM_MAINTENANCE_MODE: createOptionalEnumSchema(
|
|
928
158
|
"AIR_JAM_MAINTENANCE_MODE",
|
|
929
159
|
["enabled", "disabled"]
|
|
930
160
|
)
|
|
931
|
-
}).superRefine((value, context) => {
|
|
932
|
-
const nodeEnv = value.NODE_ENV ?? "development";
|
|
933
|
-
const authMode = resolveAuthMode({
|
|
934
|
-
configuredAuthMode: value.AIR_JAM_AUTH_MODE,
|
|
935
|
-
nodeEnv
|
|
936
|
-
});
|
|
937
|
-
const databasePolicy = resolveServerRuntimeDatabaseUrl({
|
|
938
|
-
NODE_ENV: nodeEnv,
|
|
939
|
-
DATABASE_URL: value.DATABASE_URL,
|
|
940
|
-
AIR_JAM_ALLOW_REMOTE_DATABASE: value.AIR_JAM_ALLOW_REMOTE_DATABASE
|
|
941
|
-
});
|
|
942
|
-
if (authMode === "required" && !value.AIR_JAM_MASTER_KEY && !databasePolicy.databaseUrl && !value.AIR_JAM_HOST_GRANT_SECRET) {
|
|
943
|
-
context.addIssue({
|
|
944
|
-
code: "custom",
|
|
945
|
-
path: databasePolicy.remoteDatabaseBlocked ? ["DATABASE_URL"] : ["AIR_JAM_AUTH_MODE"],
|
|
946
|
-
message: databasePolicy.remoteDatabaseBlocked ? [
|
|
947
|
-
REMOTE_DATABASE_BLOCKED_MESSAGE,
|
|
948
|
-
"Required auth cannot rely on that blocked database URL without AIR_JAM_ALLOW_REMOTE_DATABASE=enabled."
|
|
949
|
-
].join(" ") : "AIR_JAM_AUTH_MODE=required requires at least one auth backend: AIR_JAM_MASTER_KEY, DATABASE_URL, or AIR_JAM_HOST_GRANT_SECRET."
|
|
950
|
-
});
|
|
951
|
-
}
|
|
952
161
|
});
|
|
953
162
|
var loadServerEnv = (env = process.env) => {
|
|
954
163
|
const parsed = validateEnv({
|
|
955
164
|
boundary: "air-jam-server",
|
|
956
165
|
schema: rawServerEnvSchema,
|
|
957
166
|
env,
|
|
958
|
-
docsHint: "Set AIR_JAM_* values in .env.local
|
|
959
|
-
keyHints: {
|
|
960
|
-
AIR_JAM_AUTH_MODE: "Choose disabled/required. If required, configure AIR_JAM_MASTER_KEY, DATABASE_URL, or AIR_JAM_HOST_GRANT_SECRET.",
|
|
961
|
-
AIR_JAM_ALLOW_REMOTE_DATABASE: "Choose enabled only when local or test server workflows intentionally need a non-local DATABASE_URL.",
|
|
962
|
-
AIR_JAM_TRUST_PROXY_HEADERS: "Choose auto/enabled/disabled. Use auto to trust proxy headers only when the socket peer looks like a local/private proxy hop.",
|
|
963
|
-
AIR_JAM_ALLOWED_ORIGINS: "Use a comma-separated list of origins, or '*' to allow all origins.",
|
|
964
|
-
PORT: "Set a positive integer port (for example: PORT=4000)."
|
|
965
|
-
}
|
|
167
|
+
docsHint: "Set AIR_JAM_* values in .env.local or packages/server/.env and retry."
|
|
966
168
|
});
|
|
967
169
|
const nodeEnv = parsed.NODE_ENV ?? "development";
|
|
968
|
-
const authMode =
|
|
969
|
-
|
|
970
|
-
nodeEnv
|
|
971
|
-
});
|
|
972
|
-
const databasePolicy = resolveServerRuntimeDatabaseUrl({
|
|
973
|
-
NODE_ENV: nodeEnv,
|
|
974
|
-
DATABASE_URL: parsed.DATABASE_URL,
|
|
975
|
-
AIR_JAM_ALLOW_REMOTE_DATABASE: parsed.AIR_JAM_ALLOW_REMOTE_DATABASE
|
|
976
|
-
});
|
|
170
|
+
const authMode = parsed.AIR_JAM_AUTH_MODE ?? (nodeEnv === "production" ? "required" : "disabled");
|
|
171
|
+
const proxyHeaderTrustMode = parsed.AIR_JAM_TRUST_PROXY_HEADERS ?? "auto";
|
|
977
172
|
return {
|
|
978
173
|
nodeEnv,
|
|
979
174
|
port: parsed.PORT,
|
|
@@ -981,15 +176,13 @@ var loadServerEnv = (env = process.env) => {
|
|
|
981
176
|
hostRegistrationRateLimitMax: parsed.AIR_JAM_HOST_REGISTRATION_RATE_LIMIT_MAX,
|
|
982
177
|
controllerJoinRateLimitMax: parsed.AIR_JAM_CONTROLLER_JOIN_RATE_LIMIT_MAX,
|
|
983
178
|
staticAppRateLimitMax: parsed.AIR_JAM_STATIC_APP_RATE_LIMIT_MAX,
|
|
179
|
+
runtimeErrorReportRateLimitMax: parsed.AIR_JAM_RUNTIME_ERROR_REPORT_RATE_LIMIT_MAX,
|
|
984
180
|
allowedOrigins: normalizeAllowedOrigins(parsed.AIR_JAM_ALLOWED_ORIGINS),
|
|
985
181
|
devLogCollectorEnabled: parsed.AIR_JAM_DEV_LOG_COLLECTOR ? parsed.AIR_JAM_DEV_LOG_COLLECTOR === "enabled" : nodeEnv !== "production",
|
|
986
182
|
devLogDir: parsed.AIR_JAM_DEV_LOG_DIR,
|
|
987
183
|
authMode,
|
|
988
|
-
proxyHeaderTrustMode
|
|
989
|
-
|
|
990
|
-
masterKey: parsed.AIR_JAM_MASTER_KEY,
|
|
991
|
-
hostGrantSecret: parsed.AIR_JAM_HOST_GRANT_SECRET,
|
|
992
|
-
databaseUrl: databasePolicy.databaseUrl,
|
|
184
|
+
proxyHeaderTrustMode,
|
|
185
|
+
masterKey: nodeEnv === "production" ? void 0 : parsed.AIR_JAM_MASTER_KEY,
|
|
993
186
|
logLevel: parsed.AIR_JAM_LOG_LEVEL,
|
|
994
187
|
maintenanceMode: parsed.AIR_JAM_MAINTENANCE_MODE === "enabled"
|
|
995
188
|
};
|
|
@@ -1116,52 +309,10 @@ import {
|
|
|
1116
309
|
inferControllerSourceFromDeviceId
|
|
1117
310
|
} from "@air-jam/sdk/protocol";
|
|
1118
311
|
import Color from "color";
|
|
1119
|
-
|
|
1120
|
-
// src/analytics/runtime-usage.ts
|
|
1121
|
-
var createRoomAnalyticsState = (authority, now = Date.now()) => ({
|
|
1122
|
-
runtimeSessionId: crypto.randomUUID(),
|
|
1123
|
-
startedAt: now,
|
|
1124
|
-
appId: authority?.appId,
|
|
1125
|
-
gameId: authority?.gameId,
|
|
1126
|
-
hostVerifiedVia: authority?.verifiedVia,
|
|
1127
|
-
hostVerifiedOrigin: authority?.verifiedOrigin,
|
|
1128
|
-
hostSessionKind: authority?.hostSessionKind ?? "system"
|
|
1129
|
-
});
|
|
1130
|
-
var syncRoomAnalyticsState = (analytics, authority) => {
|
|
1131
|
-
if (!authority) {
|
|
1132
|
-
return;
|
|
1133
|
-
}
|
|
1134
|
-
if (analytics.appId === void 0 && authority.appId) {
|
|
1135
|
-
analytics.appId = authority.appId;
|
|
1136
|
-
}
|
|
1137
|
-
if (analytics.gameId === void 0 && authority.gameId) {
|
|
1138
|
-
analytics.gameId = authority.gameId;
|
|
1139
|
-
}
|
|
1140
|
-
if (analytics.hostVerifiedVia === void 0 && authority.verifiedVia) {
|
|
1141
|
-
analytics.hostVerifiedVia = authority.verifiedVia;
|
|
1142
|
-
}
|
|
1143
|
-
if (analytics.hostVerifiedOrigin === void 0 && authority.verifiedOrigin !== void 0) {
|
|
1144
|
-
analytics.hostVerifiedOrigin = authority.verifiedOrigin;
|
|
1145
|
-
}
|
|
1146
|
-
analytics.hostSessionKind = authority.hostSessionKind;
|
|
1147
|
-
};
|
|
1148
|
-
var createRuntimeUsageEvent = (event) => ({
|
|
1149
|
-
id: crypto.randomUUID(),
|
|
1150
|
-
occurredAt: event.occurredAt ?? Date.now(),
|
|
1151
|
-
...event
|
|
1152
|
-
});
|
|
1153
|
-
var createRoomRuntimeUsageEvent = (session, event) => createRuntimeUsageEvent({
|
|
1154
|
-
...event,
|
|
1155
|
-
runtimeSessionId: session.analytics.runtimeSessionId,
|
|
1156
|
-
runtimeSessionStartedAt: session.analytics.startedAt,
|
|
1157
|
-
roomId: session.roomId,
|
|
1158
|
-
appId: session.analytics.appId,
|
|
1159
|
-
gameId: event.gameId ?? session.activeGameId ?? session.analytics.gameId,
|
|
1160
|
-
hostVerifiedVia: session.analytics.hostVerifiedVia,
|
|
1161
|
-
hostVerifiedOrigin: session.analytics.hostVerifiedOrigin
|
|
1162
|
-
});
|
|
312
|
+
import { randomBytes } from "crypto";
|
|
1163
313
|
|
|
1164
314
|
// src/domain/room-session-domain.ts
|
|
315
|
+
import { AIR_JAM_ARCADE_SURFACE_STORE_DOMAIN } from "@air-jam/sdk/arcade/surface";
|
|
1165
316
|
var ROOM_LIFECYCLE_TRANSITIONS = {
|
|
1166
317
|
SYSTEM_IDLE: ["GAME_LAUNCH_PENDING", "CLOSING", "TEARDOWN"],
|
|
1167
318
|
GAME_LAUNCH_PENDING: ["GAME_ACTIVE", "SYSTEM_IDLE", "CLOSING"],
|
|
@@ -1296,6 +447,19 @@ var buildArcadeSessionForHostAck = (session, issueToken) => {
|
|
|
1296
447
|
launchCapability: refreshedCapability
|
|
1297
448
|
};
|
|
1298
449
|
};
|
|
450
|
+
var buildArcadeSurfaceCheckpointForHostAck = (session) => {
|
|
451
|
+
const snapshot = session.replicatedStoreSnapshots.get(
|
|
452
|
+
AIR_JAM_ARCADE_SURFACE_STORE_DOMAIN
|
|
453
|
+
);
|
|
454
|
+
if (!snapshot && !session.activeGameId) {
|
|
455
|
+
return void 0;
|
|
456
|
+
}
|
|
457
|
+
const snapshotEpoch = snapshot?.data.epoch;
|
|
458
|
+
return {
|
|
459
|
+
epoch: typeof snapshotEpoch === "number" && Number.isSafeInteger(snapshotEpoch) && snapshotEpoch >= 0 ? snapshotEpoch : 1,
|
|
460
|
+
revision: snapshot?.revision ?? 0
|
|
461
|
+
};
|
|
462
|
+
};
|
|
1299
463
|
var buildControllerCapabilityForHostAck = (session, issueToken) => {
|
|
1300
464
|
const currentCapability = session.controllerCapability;
|
|
1301
465
|
if (currentCapability && !isControllerPrivilegedCapabilityExpired(currentCapability)) {
|
|
@@ -1618,6 +782,7 @@ var registerControllerHandlers = (context) => {
|
|
|
1618
782
|
io,
|
|
1619
783
|
socket,
|
|
1620
784
|
roomManager: roomManager2,
|
|
785
|
+
realtimeAdmissionService,
|
|
1621
786
|
runtimeUsagePublisher,
|
|
1622
787
|
isControllerAuthorizedForRoom,
|
|
1623
788
|
hasControllerPrivilegeForRoom,
|
|
@@ -1625,6 +790,9 @@ var registerControllerHandlers = (context) => {
|
|
|
1625
790
|
} = context;
|
|
1626
791
|
const logger = context.logger.child({ component: "controller" });
|
|
1627
792
|
let lastServerInputFailLogTime = 0;
|
|
793
|
+
let controllerAdmissionPending = false;
|
|
794
|
+
let controllerLifecycleEpoch = 0;
|
|
795
|
+
let lastAcceptedLeave = null;
|
|
1628
796
|
const controllerInputSummary = createWindowedEventSummary({
|
|
1629
797
|
logger,
|
|
1630
798
|
event: AIRJAM_DEV_LOG_EVENTS.controller.inputSummary,
|
|
@@ -1672,6 +840,7 @@ var registerControllerHandlers = (context) => {
|
|
|
1672
840
|
target.info({ event }, msg);
|
|
1673
841
|
};
|
|
1674
842
|
socket.on("disconnect", () => {
|
|
843
|
+
controllerLifecycleEpoch += 1;
|
|
1675
844
|
controllerInputSummary.flushAll();
|
|
1676
845
|
controllerInputDroppedSummary.flushAll();
|
|
1677
846
|
});
|
|
@@ -1698,262 +867,301 @@ var registerControllerHandlers = (context) => {
|
|
|
1698
867
|
}
|
|
1699
868
|
});
|
|
1700
869
|
};
|
|
1701
|
-
socket.on(
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
context.
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
ok: false,
|
|
1714
|
-
message: "Too many join attempts. Please try again.",
|
|
1715
|
-
code: ErrorCode.SERVICE_UNAVAILABLE
|
|
1716
|
-
});
|
|
1717
|
-
return;
|
|
1718
|
-
}
|
|
1719
|
-
const parsed = controllerJoinSchema.safeParse(payload);
|
|
1720
|
-
if (!parsed.success) {
|
|
1721
|
-
logControllerEvent(
|
|
1722
|
-
"warn",
|
|
1723
|
-
AIRJAM_DEV_LOG_EVENTS.controller.joinRejected,
|
|
1724
|
-
"Rejected controller join with invalid payload",
|
|
1725
|
-
{
|
|
1726
|
-
reason: "invalid_payload",
|
|
1727
|
-
issues: parsed.error.issues
|
|
1728
|
-
}
|
|
1729
|
-
);
|
|
1730
|
-
callback({
|
|
1731
|
-
ok: false,
|
|
1732
|
-
message: parsed.error.message,
|
|
1733
|
-
code: ErrorCode.INVALID_PAYLOAD
|
|
1734
|
-
});
|
|
1735
|
-
return;
|
|
1736
|
-
}
|
|
1737
|
-
const {
|
|
1738
|
-
roomId,
|
|
1739
|
-
controllerId,
|
|
1740
|
-
deviceId: rawDeviceId,
|
|
1741
|
-
nickname,
|
|
1742
|
-
avatarId,
|
|
1743
|
-
capabilityToken
|
|
1744
|
-
} = parsed.data;
|
|
1745
|
-
const deviceId = rawDeviceId ?? controllerId;
|
|
1746
|
-
const session = roomManager2.getRoom(roomId);
|
|
1747
|
-
if (!session) {
|
|
1748
|
-
logControllerEvent(
|
|
1749
|
-
"warn",
|
|
1750
|
-
AIRJAM_DEV_LOG_EVENTS.controller.joinRejected,
|
|
1751
|
-
"Rejected controller join because room was not found",
|
|
1752
|
-
{
|
|
1753
|
-
roomId,
|
|
1754
|
-
controllerId,
|
|
1755
|
-
reason: "room_not_found"
|
|
1756
|
-
}
|
|
1757
|
-
);
|
|
1758
|
-
callback({
|
|
1759
|
-
ok: false,
|
|
1760
|
-
message: "Room not found",
|
|
1761
|
-
code: ErrorCode.ROOM_NOT_FOUND
|
|
1762
|
-
});
|
|
1763
|
-
emitError(socket.id, {
|
|
1764
|
-
code: ErrorCode.ROOM_NOT_FOUND,
|
|
1765
|
-
message: "Room not found"
|
|
1766
|
-
});
|
|
1767
|
-
return;
|
|
1768
|
-
}
|
|
1769
|
-
const existing = session.controllers.get(controllerId);
|
|
1770
|
-
const isResumedJoin = Boolean(existing);
|
|
1771
|
-
const isResumeCandidate = Boolean(existing) && existing?.deviceId === deviceId;
|
|
1772
|
-
const roomCapability = session.controllerCapability;
|
|
1773
|
-
const hasProvidedCapability = typeof capabilityToken === "string";
|
|
1774
|
-
const capabilityExpired = roomCapability ? isControllerPrivilegedCapabilityExpired(roomCapability) : false;
|
|
1775
|
-
const hasValidCapability = Boolean(roomCapability) && !capabilityExpired && roomCapability?.token === capabilityToken;
|
|
1776
|
-
if (hasProvidedCapability && !hasValidCapability && !isResumeCandidate) {
|
|
1777
|
-
logControllerEvent(
|
|
1778
|
-
"warn",
|
|
1779
|
-
AIRJAM_DEV_LOG_EVENTS.controller.joinRejected,
|
|
1780
|
-
"Rejected controller join because privileged capability was invalid",
|
|
1781
|
-
{
|
|
1782
|
-
roomId,
|
|
1783
|
-
controllerId,
|
|
1784
|
-
reason: capabilityExpired ? "capability_expired" : "invalid_capability"
|
|
1785
|
-
}
|
|
1786
|
-
);
|
|
1787
|
-
callback({
|
|
1788
|
-
ok: false,
|
|
1789
|
-
message: capabilityExpired ? "Controller link expired. Please re-open it from the host." : "Invalid controller link",
|
|
1790
|
-
code: ErrorCode.UNAUTHORIZED
|
|
1791
|
-
});
|
|
1792
|
-
return;
|
|
1793
|
-
}
|
|
1794
|
-
const previousController = roomManager2.getControllerInfo(socket.id);
|
|
1795
|
-
if (previousController && (previousController.roomId !== roomId || previousController.controllerId !== controllerId)) {
|
|
1796
|
-
const previousSession = roomManager2.getRoom(previousController.roomId);
|
|
1797
|
-
const previousEntry = previousSession?.controllers.get(
|
|
1798
|
-
previousController.controllerId
|
|
1799
|
-
);
|
|
1800
|
-
if (previousSession && previousEntry?.socketId === socket.id) {
|
|
1801
|
-
previousSession.controllers.delete(previousController.controllerId);
|
|
1802
|
-
emitControllerLeftNotice(
|
|
1803
|
-
io,
|
|
1804
|
-
previousSession,
|
|
1805
|
-
previousController.controllerId
|
|
870
|
+
socket.on(
|
|
871
|
+
"controller:join",
|
|
872
|
+
async (payload, callback) => {
|
|
873
|
+
if (context.isRateLimited(
|
|
874
|
+
"controller-join",
|
|
875
|
+
context.controllerJoinRateLimitMax
|
|
876
|
+
)) {
|
|
877
|
+
logControllerEvent(
|
|
878
|
+
"warn",
|
|
879
|
+
AIRJAM_DEV_LOG_EVENTS.controller.joinRejected,
|
|
880
|
+
"Rejected controller join due to socket rate limit",
|
|
881
|
+
{ reason: "rate_limited" }
|
|
1806
882
|
);
|
|
883
|
+
callback({
|
|
884
|
+
ok: false,
|
|
885
|
+
message: "Too many join attempts. Please try again.",
|
|
886
|
+
code: ErrorCode.SERVICE_UNAVAILABLE
|
|
887
|
+
});
|
|
888
|
+
return;
|
|
1807
889
|
}
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
890
|
+
const parsed = controllerJoinSchema.safeParse(payload);
|
|
891
|
+
if (!parsed.success) {
|
|
892
|
+
logControllerEvent(
|
|
893
|
+
"warn",
|
|
894
|
+
AIRJAM_DEV_LOG_EVENTS.controller.joinRejected,
|
|
895
|
+
"Rejected controller join with invalid payload",
|
|
896
|
+
{
|
|
897
|
+
reason: "invalid_payload",
|
|
898
|
+
issues: parsed.error.issues
|
|
899
|
+
}
|
|
900
|
+
);
|
|
901
|
+
callback({
|
|
902
|
+
ok: false,
|
|
903
|
+
message: parsed.error.message,
|
|
904
|
+
code: ErrorCode.INVALID_PAYLOAD
|
|
905
|
+
});
|
|
906
|
+
return;
|
|
907
|
+
}
|
|
908
|
+
const {
|
|
909
|
+
roomId,
|
|
910
|
+
controllerId,
|
|
911
|
+
deviceId: rawDeviceId,
|
|
912
|
+
nickname,
|
|
913
|
+
avatarId,
|
|
914
|
+
capabilityToken,
|
|
915
|
+
resumeCapabilityToken
|
|
916
|
+
} = parsed.data;
|
|
917
|
+
const deviceId = rawDeviceId ?? controllerId;
|
|
918
|
+
const session = roomManager2.getRoom(roomId);
|
|
919
|
+
if (!session) {
|
|
1837
920
|
logControllerEvent(
|
|
1838
921
|
"warn",
|
|
1839
922
|
AIRJAM_DEV_LOG_EVENTS.controller.joinRejected,
|
|
1840
|
-
"Rejected controller join because
|
|
923
|
+
"Rejected controller join because room was not found",
|
|
1841
924
|
{
|
|
1842
925
|
roomId,
|
|
1843
926
|
controllerId,
|
|
1844
|
-
reason: "
|
|
927
|
+
reason: "room_not_found"
|
|
1845
928
|
}
|
|
1846
929
|
);
|
|
1847
930
|
callback({
|
|
1848
931
|
ok: false,
|
|
1849
|
-
message: "
|
|
1850
|
-
code: ErrorCode.
|
|
932
|
+
message: "Room not found",
|
|
933
|
+
code: ErrorCode.ROOM_NOT_FOUND
|
|
934
|
+
});
|
|
935
|
+
emitError(socket.id, {
|
|
936
|
+
code: ErrorCode.ROOM_NOT_FOUND,
|
|
937
|
+
message: "Room not found"
|
|
1851
938
|
});
|
|
1852
939
|
return;
|
|
1853
940
|
}
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
941
|
+
const existing = session.controllers.get(controllerId);
|
|
942
|
+
const existingSocketId = existing?.socketId;
|
|
943
|
+
const existingLeaseToken = existing?.admissionLease.leaseToken;
|
|
944
|
+
const isResumedJoin = Boolean(existing);
|
|
945
|
+
const isResumeCandidate = existing !== void 0 && existing.retiredAt === void 0 && (existing.resumeLeaseExpiresAt === null || existing.resumeLeaseExpiresAt > Date.now()) && (existing.socketId === socket.id || existing.resumeCapabilityToken === resumeCapabilityToken);
|
|
946
|
+
if (existing && !isResumeCandidate) {
|
|
947
|
+
logControllerEvent(
|
|
948
|
+
"warn",
|
|
949
|
+
AIRJAM_DEV_LOG_EVENTS.controller.joinRejected,
|
|
950
|
+
"Rejected controller resume without valid slot authority",
|
|
951
|
+
{ roomId, controllerId, reason: "invalid_resume_authority" }
|
|
952
|
+
);
|
|
953
|
+
callback({
|
|
954
|
+
ok: false,
|
|
955
|
+
message: "Controller session cannot be resumed. Please join again.",
|
|
956
|
+
code: ErrorCode.UNAUTHORIZED
|
|
957
|
+
});
|
|
958
|
+
return;
|
|
1857
959
|
}
|
|
1858
|
-
|
|
1859
|
-
|
|
960
|
+
const roomCapability = session.controllerCapability;
|
|
961
|
+
const hasProvidedCapability = typeof capabilityToken === "string";
|
|
962
|
+
const capabilityExpired = roomCapability ? isControllerPrivilegedCapabilityExpired(roomCapability) : false;
|
|
963
|
+
const hasValidCapability = Boolean(roomCapability) && !capabilityExpired && roomCapability?.token === capabilityToken;
|
|
964
|
+
if (hasProvidedCapability && !hasValidCapability && !isResumeCandidate) {
|
|
965
|
+
logControllerEvent(
|
|
966
|
+
"warn",
|
|
967
|
+
AIRJAM_DEV_LOG_EVENTS.controller.joinRejected,
|
|
968
|
+
"Rejected controller join because privileged capability was invalid",
|
|
969
|
+
{
|
|
970
|
+
roomId,
|
|
971
|
+
controllerId,
|
|
972
|
+
reason: capabilityExpired ? "capability_expired" : "invalid_capability"
|
|
973
|
+
}
|
|
974
|
+
);
|
|
975
|
+
callback({
|
|
976
|
+
ok: false,
|
|
977
|
+
message: capabilityExpired ? "Controller link expired. Please re-open it from the host." : "Invalid controller link",
|
|
978
|
+
code: ErrorCode.UNAUTHORIZED
|
|
979
|
+
});
|
|
980
|
+
return;
|
|
1860
981
|
}
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
982
|
+
const previousController = roomManager2.getControllerInfo(socket.id);
|
|
983
|
+
const switchesController = previousController && (previousController.roomId !== roomId || previousController.controllerId !== controllerId);
|
|
984
|
+
const previousSession = switchesController ? roomManager2.getRoom(previousController.roomId) : void 0;
|
|
985
|
+
const previousEntry = switchesController ? previousSession?.controllers.get(previousController.controllerId) : void 0;
|
|
986
|
+
const replacingLease = previousEntry?.socketId === socket.id ? previousEntry.admissionLease : void 0;
|
|
987
|
+
if (controllerAdmissionPending) {
|
|
988
|
+
callback({
|
|
989
|
+
ok: false,
|
|
990
|
+
message: "A controller join is already in progress. Please retry.",
|
|
991
|
+
code: ErrorCode.SERVICE_UNAVAILABLE,
|
|
992
|
+
retryAfterSeconds: 1
|
|
993
|
+
});
|
|
994
|
+
return;
|
|
995
|
+
}
|
|
996
|
+
controllerAdmissionPending = true;
|
|
997
|
+
const operationEpoch = controllerLifecycleEpoch;
|
|
998
|
+
const roomLeaseToken = session.admissionLease.leaseToken;
|
|
999
|
+
let admission;
|
|
1000
|
+
try {
|
|
1001
|
+
admission = await realtimeAdmissionService.admitController({
|
|
1002
|
+
roomLease: session.admissionLease,
|
|
1003
|
+
controllerId,
|
|
1004
|
+
existingLease: existing?.admissionLease,
|
|
1005
|
+
replacingLease
|
|
1006
|
+
});
|
|
1007
|
+
if (admission.ok && (!socket.connected || controllerLifecycleEpoch !== operationEpoch || roomManager2.getRoom(roomId) !== session || session.admissionLease.leaseToken !== roomLeaseToken || session.controllers.get(controllerId) !== existing || existing !== void 0 && (existing.retiredAt !== void 0 || existing.socketId !== existingSocketId || existing.admissionLease.leaseToken !== existingLeaseToken || existing.resumeLeaseExpiresAt !== null && existing.resumeLeaseExpiresAt <= Date.now()) || previousEntry !== void 0 && previousEntry.socketId === socket.id && previousEntry.retiredAt !== void 0)) {
|
|
1008
|
+
await realtimeAdmissionService.releaseController(admission.lease);
|
|
1009
|
+
admission = {
|
|
1010
|
+
ok: false,
|
|
1011
|
+
reason: "operation_cancelled",
|
|
1012
|
+
message: "The controller state changed before joining completed.",
|
|
1013
|
+
retryAfterSeconds: null
|
|
1014
|
+
};
|
|
1015
|
+
}
|
|
1016
|
+
} finally {
|
|
1017
|
+
controllerAdmissionPending = false;
|
|
1018
|
+
}
|
|
1019
|
+
if (!admission.ok) {
|
|
1020
|
+
logControllerEvent(
|
|
1021
|
+
"warn",
|
|
1022
|
+
AIRJAM_DEV_LOG_EVENTS.controller.joinRejected,
|
|
1023
|
+
"Rejected controller join by realtime admission authority",
|
|
1024
|
+
{ roomId, controllerId, reason: admission.reason }
|
|
1025
|
+
);
|
|
1026
|
+
callback({
|
|
1027
|
+
ok: false,
|
|
1028
|
+
message: admission.message,
|
|
1029
|
+
code: admission.reason === "room_full" ? ErrorCode.ROOM_FULL : ErrorCode.SERVICE_UNAVAILABLE,
|
|
1030
|
+
...admission.retryAfterSeconds ? { retryAfterSeconds: admission.retryAfterSeconds } : {}
|
|
1031
|
+
});
|
|
1032
|
+
return;
|
|
1033
|
+
}
|
|
1034
|
+
if (previousController && (previousController.roomId !== roomId || previousController.controllerId !== controllerId)) {
|
|
1035
|
+
if (previousSession && previousEntry?.socketId === socket.id) {
|
|
1036
|
+
previousEntry.retiredAt = Date.now();
|
|
1037
|
+
previousSession.controllers.delete(previousController.controllerId);
|
|
1038
|
+
emitControllerLeftNotice(
|
|
1039
|
+
io,
|
|
1040
|
+
previousSession,
|
|
1041
|
+
previousController.controllerId
|
|
1042
|
+
);
|
|
1043
|
+
}
|
|
1044
|
+
roomManager2.deleteController(socket.id);
|
|
1045
|
+
}
|
|
1046
|
+
const grantedPrivileges = hasValidCapability ? [...roomCapability.grants] : existing?.privilegedGrants.length ? [...existing.privilegedGrants] : getDefaultControllerPrivilegedGrants();
|
|
1047
|
+
const resumed = isResumedJoin;
|
|
1048
|
+
if (existing) {
|
|
1049
|
+
if (existing.pendingDisconnectTimer) {
|
|
1050
|
+
clearTimeout(existing.pendingDisconnectTimer);
|
|
1051
|
+
existing.pendingDisconnectTimer = void 0;
|
|
1052
|
+
}
|
|
1053
|
+
if (existing.socketId && existing.socketId !== socket.id) {
|
|
1054
|
+
roomManager2.deleteController(existing.socketId);
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
const colorHex = PLAYER_COLORS[session.controllers.size % PLAYER_COLORS.length];
|
|
1058
|
+
let color;
|
|
1059
|
+
try {
|
|
1060
|
+
color = Color(colorHex).hex();
|
|
1061
|
+
} catch {
|
|
1062
|
+
color = Color("#38bdf8").hex();
|
|
1063
|
+
}
|
|
1064
|
+
let controllerSession = existing;
|
|
1065
|
+
if (controllerSession) {
|
|
1066
|
+
controllerSession.retiredAt = void 0;
|
|
1067
|
+
controllerSession.nickname = nickname ?? controllerSession.nickname;
|
|
1068
|
+
controllerSession.connected = true;
|
|
1069
|
+
controllerSession.resumeLeaseExpiresAt = null;
|
|
1070
|
+
controllerSession.socketId = socket.id;
|
|
1071
|
+
controllerSession.privilegedGrants = grantedPrivileges;
|
|
1072
|
+
controllerSession.admissionLease = admission.lease;
|
|
1073
|
+
controllerSession.playerProfile = {
|
|
1074
|
+
...controllerSession.playerProfile,
|
|
1075
|
+
label: nickname ?? controllerSession.nickname ?? controllerSession.playerProfile.label,
|
|
1076
|
+
...avatarId !== void 0 ? { avatarId } : controllerSession.playerProfile.avatarId ? { avatarId: controllerSession.playerProfile.avatarId } : {}
|
|
1077
|
+
};
|
|
1078
|
+
session.controllers.set(controllerId, controllerSession);
|
|
1079
|
+
} else {
|
|
1080
|
+
const playerProfile = {
|
|
1081
|
+
id: controllerId,
|
|
1082
|
+
label: nickname ?? `Player ${session.controllers.size}`,
|
|
1083
|
+
color,
|
|
1084
|
+
...avatarId ? { avatarId } : {}
|
|
1085
|
+
};
|
|
1086
|
+
controllerSession = {
|
|
1087
|
+
controllerId,
|
|
1088
|
+
resumeCapabilityToken: randomBytes(32).toString("base64url"),
|
|
1089
|
+
deviceId,
|
|
1090
|
+
nickname,
|
|
1091
|
+
socketId: socket.id,
|
|
1092
|
+
connected: true,
|
|
1093
|
+
resumeLeaseExpiresAt: null,
|
|
1094
|
+
playerProfile,
|
|
1095
|
+
privilegedGrants: grantedPrivileges,
|
|
1096
|
+
source: inferControllerSourceFromDeviceId(deviceId),
|
|
1097
|
+
admissionLease: admission.lease
|
|
1098
|
+
};
|
|
1099
|
+
session.controllers.set(controllerId, controllerSession);
|
|
1100
|
+
}
|
|
1101
|
+
roomManager2.setController(socket.id, { roomId, controllerId });
|
|
1102
|
+
socket.data.controllerAuthority = {
|
|
1103
|
+
roomId,
|
|
1889
1104
|
controllerId,
|
|
1890
1105
|
deviceId,
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
connected: true,
|
|
1894
|
-
resumeLeaseExpiresAt: null,
|
|
1895
|
-
playerProfile,
|
|
1896
|
-
privilegedGrants: grantedPrivileges,
|
|
1897
|
-
source: inferControllerSourceFromDeviceId(deviceId)
|
|
1106
|
+
joinedAt: Date.now(),
|
|
1107
|
+
privilegedGrants: grantedPrivileges
|
|
1898
1108
|
};
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1109
|
+
lastAcceptedLeave = null;
|
|
1110
|
+
socket.join(roomId);
|
|
1111
|
+
emitControllerJoinedNotice(io, session, controllerSession, { resumed });
|
|
1112
|
+
if (resumed) {
|
|
1113
|
+
logControllerEvent(
|
|
1114
|
+
"info",
|
|
1115
|
+
AIRJAM_DEV_LOG_EVENTS.controller.resumeAccepted,
|
|
1116
|
+
"Controller resumed existing room binding",
|
|
1117
|
+
{
|
|
1118
|
+
roomId,
|
|
1119
|
+
controllerId,
|
|
1120
|
+
nickname: nickname ?? void 0,
|
|
1121
|
+
privilegedGrantCount: grantedPrivileges.length
|
|
1122
|
+
}
|
|
1123
|
+
);
|
|
1124
|
+
}
|
|
1912
1125
|
logControllerEvent(
|
|
1913
1126
|
"info",
|
|
1914
|
-
AIRJAM_DEV_LOG_EVENTS.controller.
|
|
1915
|
-
"Controller
|
|
1127
|
+
AIRJAM_DEV_LOG_EVENTS.controller.joinAccepted,
|
|
1128
|
+
"Controller joined room",
|
|
1916
1129
|
{
|
|
1917
1130
|
roomId,
|
|
1918
1131
|
controllerId,
|
|
1919
1132
|
nickname: nickname ?? void 0,
|
|
1920
|
-
|
|
1133
|
+
resumed,
|
|
1134
|
+
privilegedGrantCount: grantedPrivileges.length,
|
|
1135
|
+
hasCapability: hasValidCapability
|
|
1921
1136
|
}
|
|
1922
1137
|
);
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1138
|
+
runtimeUsagePublisher.publish(
|
|
1139
|
+
createRoomRuntimeUsageEvent(session, {
|
|
1140
|
+
kind: "controller_joined",
|
|
1141
|
+
payload: {
|
|
1142
|
+
controllerId,
|
|
1143
|
+
rejoined: resumed,
|
|
1144
|
+
resumed
|
|
1145
|
+
}
|
|
1146
|
+
})
|
|
1147
|
+
);
|
|
1148
|
+
callback({
|
|
1149
|
+
ok: true,
|
|
1930
1150
|
controllerId,
|
|
1931
|
-
|
|
1932
|
-
resumed,
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
})
|
|
1946
|
-
);
|
|
1947
|
-
callback({ ok: true, controllerId, roomId, resumed });
|
|
1948
|
-
socket.emit("server:welcome", {
|
|
1949
|
-
controllerId,
|
|
1950
|
-
roomId,
|
|
1951
|
-
resumed,
|
|
1952
|
-
player: controllerSession.playerProfile,
|
|
1953
|
-
players: listRoomPlayers(session)
|
|
1954
|
-
});
|
|
1955
|
-
socket.emit("server:state", buildRoomStateMessage(roomId, session));
|
|
1956
|
-
});
|
|
1151
|
+
roomId,
|
|
1152
|
+
resumed,
|
|
1153
|
+
resumeCapabilityToken: controllerSession.resumeCapabilityToken
|
|
1154
|
+
});
|
|
1155
|
+
socket.emit("server:welcome", {
|
|
1156
|
+
controllerId,
|
|
1157
|
+
roomId,
|
|
1158
|
+
resumed,
|
|
1159
|
+
player: controllerSession.playerProfile,
|
|
1160
|
+
players: listRoomPlayers(session)
|
|
1161
|
+
});
|
|
1162
|
+
socket.emit("server:state", buildRoomStateMessage(roomId, session));
|
|
1163
|
+
}
|
|
1164
|
+
);
|
|
1957
1165
|
socket.on(
|
|
1958
1166
|
"controller:updatePlayerProfile",
|
|
1959
1167
|
(payload, callback) => {
|
|
@@ -2063,7 +1271,7 @@ var registerControllerHandlers = (context) => {
|
|
|
2063
1271
|
);
|
|
2064
1272
|
socket.on(
|
|
2065
1273
|
"controller:leave",
|
|
2066
|
-
(payload, callback) => {
|
|
1274
|
+
async (payload, callback) => {
|
|
2067
1275
|
const parsed = controllerLeaveSchema.safeParse(payload);
|
|
2068
1276
|
if (!parsed.success) {
|
|
2069
1277
|
logControllerEvent(
|
|
@@ -2083,7 +1291,8 @@ var registerControllerHandlers = (context) => {
|
|
|
2083
1291
|
return;
|
|
2084
1292
|
}
|
|
2085
1293
|
const { roomId, controllerId } = parsed.data;
|
|
2086
|
-
|
|
1294
|
+
const repeatsAcceptedLeave = !socket.data.controllerAuthority && lastAcceptedLeave?.roomId === roomId && lastAcceptedLeave.controllerId === controllerId;
|
|
1295
|
+
if (!repeatsAcceptedLeave && !isControllerAuthorizedForRoom(roomId, controllerId)) {
|
|
2087
1296
|
logControllerEvent(
|
|
2088
1297
|
"warn",
|
|
2089
1298
|
AIRJAM_DEV_LOG_EVENTS.controller.leaveRejected,
|
|
@@ -2103,21 +1312,21 @@ var registerControllerHandlers = (context) => {
|
|
|
2103
1312
|
}
|
|
2104
1313
|
const session = roomManager2.getRoom(roomId);
|
|
2105
1314
|
if (!session) {
|
|
1315
|
+
roomManager2.deleteController(socket.id);
|
|
1316
|
+
delete socket.data.controllerAuthority;
|
|
1317
|
+
lastAcceptedLeave = { roomId, controllerId };
|
|
1318
|
+
socket.leave(roomId);
|
|
2106
1319
|
logControllerEvent(
|
|
2107
|
-
"
|
|
2108
|
-
AIRJAM_DEV_LOG_EVENTS.controller.
|
|
2109
|
-
"
|
|
1320
|
+
"info",
|
|
1321
|
+
AIRJAM_DEV_LOG_EVENTS.controller.leaveAccepted,
|
|
1322
|
+
"Controller leave was already complete",
|
|
2110
1323
|
{
|
|
2111
1324
|
roomId,
|
|
2112
1325
|
controllerId,
|
|
2113
|
-
|
|
1326
|
+
alreadyAbsent: true
|
|
2114
1327
|
}
|
|
2115
1328
|
);
|
|
2116
|
-
callback({
|
|
2117
|
-
ok: false,
|
|
2118
|
-
message: "Room not found",
|
|
2119
|
-
code: ErrorCode.ROOM_NOT_FOUND
|
|
2120
|
-
});
|
|
1329
|
+
callback({ ok: true });
|
|
2121
1330
|
return;
|
|
2122
1331
|
}
|
|
2123
1332
|
const controllerSession = session.controllers.get(controllerId);
|
|
@@ -2125,28 +1334,39 @@ var registerControllerHandlers = (context) => {
|
|
|
2125
1334
|
clearTimeout(controllerSession.pendingDisconnectTimer);
|
|
2126
1335
|
controllerSession.pendingDisconnectTimer = void 0;
|
|
2127
1336
|
}
|
|
2128
|
-
|
|
1337
|
+
if (controllerSession) {
|
|
1338
|
+
controllerLifecycleEpoch += 1;
|
|
1339
|
+
controllerSession.retiredAt = Date.now();
|
|
1340
|
+
session.controllers.delete(controllerId);
|
|
1341
|
+
}
|
|
2129
1342
|
roomManager2.deleteController(socket.id);
|
|
2130
1343
|
delete socket.data.controllerAuthority;
|
|
2131
|
-
|
|
1344
|
+
lastAcceptedLeave = { roomId, controllerId };
|
|
2132
1345
|
socket.leave(roomId);
|
|
2133
1346
|
logControllerEvent(
|
|
2134
1347
|
"info",
|
|
2135
1348
|
AIRJAM_DEV_LOG_EVENTS.controller.leaveAccepted,
|
|
2136
|
-
"Controller left room",
|
|
1349
|
+
controllerSession ? "Controller left room" : "Controller leave was already complete",
|
|
2137
1350
|
{
|
|
2138
1351
|
roomId,
|
|
2139
|
-
controllerId
|
|
1352
|
+
controllerId,
|
|
1353
|
+
alreadyAbsent: !controllerSession
|
|
2140
1354
|
}
|
|
2141
1355
|
);
|
|
2142
|
-
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
1356
|
+
if (controllerSession) {
|
|
1357
|
+
emitControllerLeftNotice(io, session, controllerId);
|
|
1358
|
+
runtimeUsagePublisher.publish(
|
|
1359
|
+
createRoomRuntimeUsageEvent(session, {
|
|
1360
|
+
kind: "controller_left",
|
|
1361
|
+
payload: {
|
|
1362
|
+
controllerId
|
|
1363
|
+
}
|
|
1364
|
+
})
|
|
1365
|
+
);
|
|
1366
|
+
await realtimeAdmissionService.releaseController(
|
|
1367
|
+
controllerSession.admissionLease
|
|
1368
|
+
);
|
|
1369
|
+
}
|
|
2150
1370
|
callback({ ok: true });
|
|
2151
1371
|
}
|
|
2152
1372
|
);
|
|
@@ -2378,7 +1598,13 @@ var registerControllerHandlers = (context) => {
|
|
|
2378
1598
|
// src/gateway/handlers/register-disconnect-handler.ts
|
|
2379
1599
|
import { AIRJAM_DEV_LOG_EVENTS as AIRJAM_DEV_LOG_EVENTS2 } from "@air-jam/sdk/protocol";
|
|
2380
1600
|
var registerDisconnectHandler = (context) => {
|
|
2381
|
-
const {
|
|
1601
|
+
const {
|
|
1602
|
+
io,
|
|
1603
|
+
socket,
|
|
1604
|
+
roomManager: roomManager2,
|
|
1605
|
+
runtimeUsagePublisher,
|
|
1606
|
+
realtimeAdmissionService
|
|
1607
|
+
} = context;
|
|
2382
1608
|
const logger = context.logger.child({ component: "disconnect" });
|
|
2383
1609
|
const getDisconnectLogger = (bindings = {}) => {
|
|
2384
1610
|
const mergedBindings = {
|
|
@@ -2488,6 +1714,9 @@ var registerDisconnectHandler = (context) => {
|
|
|
2488
1714
|
"Room closed after master host disconnect"
|
|
2489
1715
|
);
|
|
2490
1716
|
roomManager2.removeRoom(roomId, io, "Host disconnected");
|
|
1717
|
+
void realtimeAdmissionService.releaseRoom(
|
|
1718
|
+
currentSession.admissionLease
|
|
1719
|
+
);
|
|
2491
1720
|
}
|
|
2492
1721
|
}, 3e3);
|
|
2493
1722
|
}
|
|
@@ -2524,7 +1753,11 @@ var registerDisconnectHandler = (context) => {
|
|
|
2524
1753
|
return;
|
|
2525
1754
|
}
|
|
2526
1755
|
currentController.pendingDisconnectTimer = void 0;
|
|
1756
|
+
currentController.retiredAt = Date.now();
|
|
2527
1757
|
currentSession.controllers.delete(controller.controllerId);
|
|
1758
|
+
void realtimeAdmissionService.releaseController(
|
|
1759
|
+
currentController.admissionLease
|
|
1760
|
+
);
|
|
2528
1761
|
emitControllerLeftNotice(
|
|
2529
1762
|
io,
|
|
2530
1763
|
currentSession,
|
|
@@ -2553,7 +1786,11 @@ var registerDisconnectHandler = (context) => {
|
|
|
2553
1786
|
);
|
|
2554
1787
|
}, resumeLeaseMs);
|
|
2555
1788
|
} else {
|
|
1789
|
+
controllerSession.retiredAt = Date.now();
|
|
2556
1790
|
session.controllers.delete(controller.controllerId);
|
|
1791
|
+
void realtimeAdmissionService.releaseController(
|
|
1792
|
+
controllerSession.admissionLease
|
|
1793
|
+
);
|
|
2557
1794
|
emitControllerLeftNotice(io, session, controller.controllerId);
|
|
2558
1795
|
runtimeUsagePublisher.publish(
|
|
2559
1796
|
createRoomRuntimeUsageEvent(session, {
|
|
@@ -2579,6 +1816,12 @@ var registerDisconnectHandler = (context) => {
|
|
|
2579
1816
|
}
|
|
2580
1817
|
}
|
|
2581
1818
|
if (resumeLeaseMs > 0) {
|
|
1819
|
+
if (controllerSession && resumeLeaseExpiresAt !== null) {
|
|
1820
|
+
void realtimeAdmissionService.markControllerDisconnected(
|
|
1821
|
+
controllerSession.admissionLease,
|
|
1822
|
+
resumeLeaseMs
|
|
1823
|
+
);
|
|
1824
|
+
}
|
|
2582
1825
|
runtimeUsagePublisher.publish(
|
|
2583
1826
|
createRoomRuntimeUsageEvent(session, {
|
|
2584
1827
|
kind: "controller_disconnected",
|
|
@@ -2610,16 +1853,16 @@ var registerDisconnectHandler = (context) => {
|
|
|
2610
1853
|
};
|
|
2611
1854
|
|
|
2612
1855
|
// src/gateway/handlers/register-host-lifecycle-handlers.ts
|
|
2613
|
-
import {
|
|
1856
|
+
import { AIR_JAM_ARCADE_SURFACE_STORE_DOMAIN as AIR_JAM_ARCADE_SURFACE_STORE_DOMAIN2 } from "@air-jam/sdk/arcade/surface";
|
|
2614
1857
|
import {
|
|
2615
1858
|
AIRJAM_DEV_LOG_EVENTS as AIRJAM_DEV_LOG_EVENTS3,
|
|
1859
|
+
DEFAULT_ROOM_PLATFORM_SETTINGS,
|
|
2616
1860
|
ErrorCode as ErrorCode2,
|
|
2617
1861
|
hostActivateEmbeddedGameSchema,
|
|
2618
1862
|
hostBootstrapSchema,
|
|
2619
1863
|
hostCreateRoomSchema,
|
|
2620
1864
|
hostJoinAsChildSchema,
|
|
2621
1865
|
hostReconnectSchema,
|
|
2622
|
-
hostRegisterSystemSchema,
|
|
2623
1866
|
hostRemoveControllerSchema,
|
|
2624
1867
|
hostResetRoomSchema,
|
|
2625
1868
|
systemLaunchGameSchema
|
|
@@ -2640,29 +1883,43 @@ var generateRoomCode = () => {
|
|
|
2640
1883
|
|
|
2641
1884
|
// src/gateway/handlers/register-host-lifecycle-handlers.ts
|
|
2642
1885
|
var registerHostLifecycleHandlers = (context) => {
|
|
2643
|
-
const {
|
|
1886
|
+
const {
|
|
1887
|
+
io,
|
|
1888
|
+
socket,
|
|
1889
|
+
roomManager: roomManager2,
|
|
1890
|
+
authService,
|
|
1891
|
+
runtimeUsagePublisher,
|
|
1892
|
+
realtimeAdmissionService
|
|
1893
|
+
} = context;
|
|
2644
1894
|
const logger = context.logger.child({ component: "host-lifecycle" });
|
|
2645
1895
|
const requestOrigin = typeof socket.handshake.headers.origin === "string" ? socket.handshake.headers.origin : void 0;
|
|
2646
|
-
|
|
1896
|
+
let hostAdmissionPending = false;
|
|
1897
|
+
let hostLifecycleEpoch = 0;
|
|
1898
|
+
socket.on("disconnect", () => {
|
|
1899
|
+
hostLifecycleEpoch += 1;
|
|
1900
|
+
});
|
|
1901
|
+
const bindHostAuthority = (verification) => {
|
|
2647
1902
|
const traceId = `host_${uuidv4().replace(/-/g, "").slice(0, 12)}`;
|
|
2648
1903
|
socket.data.hostAuthority = {
|
|
2649
|
-
appId,
|
|
2650
|
-
gameId,
|
|
1904
|
+
appId: verification.appId,
|
|
1905
|
+
gameId: verification.gameId,
|
|
1906
|
+
creatorId: verification.creatorId,
|
|
2651
1907
|
traceId,
|
|
2652
1908
|
verifiedAt: Date.now(),
|
|
2653
|
-
verifiedVia,
|
|
2654
|
-
verifiedOrigin,
|
|
2655
|
-
hostSessionKind
|
|
1909
|
+
verifiedVia: verification.verifiedVia,
|
|
1910
|
+
verifiedOrigin: verification.verifiedOrigin,
|
|
1911
|
+
hostSessionKind: verification.hostSessionKind
|
|
2656
1912
|
};
|
|
2657
1913
|
return traceId;
|
|
2658
1914
|
};
|
|
2659
|
-
const createInitialRoomSession = (roomId, maxPlayers, hostSessionKind) => {
|
|
1915
|
+
const createInitialRoomSession = (roomId, maxPlayers, hostSessionKind, admissionLease) => {
|
|
2660
1916
|
const analytics = createRoomAnalyticsState(socket.data.hostAuthority);
|
|
2661
1917
|
analytics.hostSessionKind = hostSessionKind;
|
|
2662
1918
|
const startsInGameFocus = hostSessionKind === "game";
|
|
2663
1919
|
return {
|
|
2664
1920
|
roomId,
|
|
2665
1921
|
masterHostSocketId: socket.id,
|
|
1922
|
+
hostResumeCapability: { token: uuidv4() },
|
|
2666
1923
|
analytics,
|
|
2667
1924
|
focus: startsInGameFocus ? "GAME" : "SYSTEM",
|
|
2668
1925
|
launchCapability: void 0,
|
|
@@ -2675,7 +1932,8 @@ var registerHostLifecycleHandlers = (context) => {
|
|
|
2675
1932
|
stateVersion: 0,
|
|
2676
1933
|
controllerOrientation: "portrait",
|
|
2677
1934
|
roomSettings: DEFAULT_ROOM_PLATFORM_SETTINGS,
|
|
2678
|
-
lifecycleState: startsInGameFocus ? "GAME_ACTIVE" : "SYSTEM_IDLE"
|
|
1935
|
+
lifecycleState: startsInGameFocus ? "GAME_ACTIVE" : "SYSTEM_IDLE",
|
|
1936
|
+
admissionLease
|
|
2679
1937
|
};
|
|
2680
1938
|
};
|
|
2681
1939
|
const buildHostRosterSnapshot = (session) => Array.from(
|
|
@@ -2684,7 +1942,10 @@ var registerHostLifecycleHandlers = (context) => {
|
|
|
2684
1942
|
);
|
|
2685
1943
|
const buildHostControllerSnapshot = (session) => listRoomControllerPresences(session);
|
|
2686
1944
|
const emitReplicatedStoreSnapshotsToHost = (targetSocket, session) => {
|
|
2687
|
-
for (const snapshot of session.replicatedStoreSnapshots
|
|
1945
|
+
for (const [storeDomain, snapshot] of session.replicatedStoreSnapshots) {
|
|
1946
|
+
if (storeDomain === AIR_JAM_ARCADE_SURFACE_STORE_DOMAIN2) {
|
|
1947
|
+
continue;
|
|
1948
|
+
}
|
|
2688
1949
|
targetSocket.emit("airjam:state_sync", snapshot);
|
|
2689
1950
|
}
|
|
2690
1951
|
};
|
|
@@ -2708,31 +1969,86 @@ var registerHostLifecycleHandlers = (context) => {
|
|
|
2708
1969
|
} while (roomManager2.getRoom(roomId));
|
|
2709
1970
|
return roomId;
|
|
2710
1971
|
};
|
|
2711
|
-
const createAndBindRoomForHost = ({
|
|
1972
|
+
const createAndBindRoomForHost = async ({
|
|
2712
1973
|
roomId,
|
|
2713
1974
|
maxPlayers,
|
|
2714
|
-
hostSessionKind
|
|
1975
|
+
hostSessionKind,
|
|
1976
|
+
replacingLease
|
|
2715
1977
|
}) => {
|
|
2716
|
-
|
|
2717
|
-
|
|
2718
|
-
|
|
1978
|
+
if (hostAdmissionPending) {
|
|
1979
|
+
return {
|
|
1980
|
+
ok: false,
|
|
1981
|
+
denial: {
|
|
1982
|
+
ok: false,
|
|
1983
|
+
reason: "operation_in_progress",
|
|
1984
|
+
message: "A room operation is already in progress. Please retry.",
|
|
1985
|
+
retryAfterSeconds: 1
|
|
1986
|
+
}
|
|
1987
|
+
};
|
|
2719
1988
|
}
|
|
2720
|
-
|
|
2721
|
-
|
|
2722
|
-
|
|
2723
|
-
|
|
2724
|
-
|
|
2725
|
-
|
|
2726
|
-
|
|
2727
|
-
|
|
2728
|
-
|
|
1989
|
+
hostAdmissionPending = true;
|
|
1990
|
+
const operationEpoch = hostLifecycleEpoch;
|
|
1991
|
+
const authority = socket.data.hostAuthority;
|
|
1992
|
+
const attempts = roomId ? 1 : 10;
|
|
1993
|
+
try {
|
|
1994
|
+
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
1995
|
+
const nextRoomId = roomId ?? generateUniqueRoomId();
|
|
1996
|
+
if (!nextRoomId) return { ok: false };
|
|
1997
|
+
const admission = await realtimeAdmissionService.admitRoom({
|
|
1998
|
+
roomId: nextRoomId,
|
|
1999
|
+
appId: authority?.appId,
|
|
2000
|
+
gameId: authority?.gameId,
|
|
2001
|
+
creatorId: authority?.creatorId,
|
|
2002
|
+
maxControllers: maxPlayers,
|
|
2003
|
+
replacingLease
|
|
2004
|
+
});
|
|
2005
|
+
if (!admission.ok) {
|
|
2006
|
+
if (!roomId && admission.reason === "room_conflict") continue;
|
|
2007
|
+
return { ok: false, denial: admission };
|
|
2008
|
+
}
|
|
2009
|
+
if (!socket.connected || hostLifecycleEpoch !== operationEpoch) {
|
|
2010
|
+
await realtimeAdmissionService.releaseRoom(admission.lease);
|
|
2011
|
+
return {
|
|
2012
|
+
ok: false,
|
|
2013
|
+
denial: {
|
|
2014
|
+
ok: false,
|
|
2015
|
+
reason: "operation_cancelled",
|
|
2016
|
+
message: "The host disconnected before the room was ready.",
|
|
2017
|
+
retryAfterSeconds: null
|
|
2018
|
+
}
|
|
2019
|
+
};
|
|
2020
|
+
}
|
|
2021
|
+
const session = createInitialRoomSession(
|
|
2022
|
+
nextRoomId,
|
|
2023
|
+
maxPlayers,
|
|
2024
|
+
hostSessionKind,
|
|
2025
|
+
admission.lease
|
|
2026
|
+
);
|
|
2027
|
+
roomManager2.setRoom(nextRoomId, session);
|
|
2028
|
+
roomManager2.setHostRoom(socket.id, nextRoomId);
|
|
2029
|
+
socket.join(nextRoomId);
|
|
2030
|
+
return { ok: true, session };
|
|
2031
|
+
}
|
|
2032
|
+
return { ok: false };
|
|
2033
|
+
} finally {
|
|
2034
|
+
hostAdmissionPending = false;
|
|
2035
|
+
}
|
|
2036
|
+
};
|
|
2037
|
+
const rejectAdmission = (denial2, callback) => {
|
|
2038
|
+
callback({
|
|
2039
|
+
ok: false,
|
|
2040
|
+
message: denial2?.message ?? "Failed to reserve room capacity",
|
|
2041
|
+
code: ErrorCode2.SERVICE_UNAVAILABLE,
|
|
2042
|
+
...denial2?.retryAfterSeconds ? { retryAfterSeconds: denial2.retryAfterSeconds } : {}
|
|
2043
|
+
});
|
|
2729
2044
|
};
|
|
2730
2045
|
const buildHostRegistrationAck = (session) => ({
|
|
2731
2046
|
ok: true,
|
|
2732
2047
|
roomId: session.roomId,
|
|
2733
2048
|
players: buildHostRosterSnapshot(session),
|
|
2734
2049
|
controllers: buildHostControllerSnapshot(session),
|
|
2735
|
-
controllerCapability: getControllerCapabilityForAck(session)
|
|
2050
|
+
controllerCapability: getControllerCapabilityForAck(session),
|
|
2051
|
+
hostResumeCapability: session.hostResumeCapability
|
|
2736
2052
|
});
|
|
2737
2053
|
const getHostLogger = (bindings = {}) => {
|
|
2738
2054
|
const traceId = socket.data.hostAuthority?.traceId;
|
|
@@ -2843,9 +2159,13 @@ var registerHostLifecycleHandlers = (context) => {
|
|
|
2843
2159
|
const verification = await authService.verifyHostBootstrap({
|
|
2844
2160
|
appId: parsed.data.appId,
|
|
2845
2161
|
hostGrant: parsed.data.hostGrant,
|
|
2846
|
-
origin: requestOrigin
|
|
2162
|
+
origin: requestOrigin,
|
|
2163
|
+
hostSessionKind: parsed.data.hostSessionKind
|
|
2847
2164
|
});
|
|
2848
|
-
if (!
|
|
2165
|
+
if (!socket.connected) {
|
|
2166
|
+
return;
|
|
2167
|
+
}
|
|
2168
|
+
if (!verification.isVerified || !verification.hostSessionKind) {
|
|
2849
2169
|
logHostEvent(
|
|
2850
2170
|
"warn",
|
|
2851
2171
|
AIRJAM_DEV_LOG_EVENTS3.host.bootstrapRejected,
|
|
@@ -2885,13 +2205,10 @@ var registerHostLifecycleHandlers = (context) => {
|
|
|
2885
2205
|
});
|
|
2886
2206
|
return;
|
|
2887
2207
|
}
|
|
2888
|
-
const traceId = bindHostAuthority(
|
|
2889
|
-
verification
|
|
2890
|
-
verification.
|
|
2891
|
-
|
|
2892
|
-
verification.verifiedOrigin,
|
|
2893
|
-
parsed.data.hostSessionKind
|
|
2894
|
-
);
|
|
2208
|
+
const traceId = bindHostAuthority({
|
|
2209
|
+
...verification,
|
|
2210
|
+
hostSessionKind: verification.hostSessionKind
|
|
2211
|
+
});
|
|
2895
2212
|
logHostEvent(
|
|
2896
2213
|
"info",
|
|
2897
2214
|
AIRJAM_DEV_LOG_EVENTS3.host.bootstrapVerified,
|
|
@@ -2913,95 +2230,6 @@ var registerHostLifecycleHandlers = (context) => {
|
|
|
2913
2230
|
callback({ ok: true, traceId });
|
|
2914
2231
|
}
|
|
2915
2232
|
);
|
|
2916
|
-
socket.on(
|
|
2917
|
-
"host:registerSystem",
|
|
2918
|
-
async (payload, callback) => {
|
|
2919
|
-
if (context.isRateLimited(
|
|
2920
|
-
"host-registration",
|
|
2921
|
-
context.hostRegistrationRateLimitMax
|
|
2922
|
-
)) {
|
|
2923
|
-
logHostEvent(
|
|
2924
|
-
"warn",
|
|
2925
|
-
AIRJAM_DEV_LOG_EVENTS3.host.registerSystemRejected,
|
|
2926
|
-
"Rejected host registerSystem due to socket rate limit",
|
|
2927
|
-
{ reason: "rate_limited" }
|
|
2928
|
-
);
|
|
2929
|
-
callback({
|
|
2930
|
-
ok: false,
|
|
2931
|
-
message: "Too many host registration attempts. Please try again.",
|
|
2932
|
-
code: ErrorCode2.SERVICE_UNAVAILABLE
|
|
2933
|
-
});
|
|
2934
|
-
return;
|
|
2935
|
-
}
|
|
2936
|
-
if (!ensureHostAuthority("host:registerSystem", callback)) {
|
|
2937
|
-
return;
|
|
2938
|
-
}
|
|
2939
|
-
if (isStaticAppRateLimited("static-app-lifecycle")) {
|
|
2940
|
-
logHostEvent(
|
|
2941
|
-
"warn",
|
|
2942
|
-
AIRJAM_DEV_LOG_EVENTS3.host.registerSystemRejected,
|
|
2943
|
-
"Rejected host registerSystem due to static app quota",
|
|
2944
|
-
{ reason: "static_app_quota" }
|
|
2945
|
-
);
|
|
2946
|
-
callback({
|
|
2947
|
-
ok: false,
|
|
2948
|
-
message: "Too many host lifecycle attempts for this app. Please try again.",
|
|
2949
|
-
code: ErrorCode2.SERVICE_UNAVAILABLE
|
|
2950
|
-
});
|
|
2951
|
-
return;
|
|
2952
|
-
}
|
|
2953
|
-
const parsed = hostRegisterSystemSchema.safeParse(payload);
|
|
2954
|
-
if (!parsed.success) {
|
|
2955
|
-
logHostEvent(
|
|
2956
|
-
"warn",
|
|
2957
|
-
AIRJAM_DEV_LOG_EVENTS3.host.registerSystemRejected,
|
|
2958
|
-
"Rejected host registerSystem with invalid payload",
|
|
2959
|
-
{
|
|
2960
|
-
reason: "invalid_payload",
|
|
2961
|
-
issues: parsed.error.issues
|
|
2962
|
-
}
|
|
2963
|
-
);
|
|
2964
|
-
callback({
|
|
2965
|
-
ok: false,
|
|
2966
|
-
message: parsed.error.message,
|
|
2967
|
-
code: ErrorCode2.INVALID_PAYLOAD
|
|
2968
|
-
});
|
|
2969
|
-
return;
|
|
2970
|
-
}
|
|
2971
|
-
const { roomId } = parsed.data;
|
|
2972
|
-
let session = roomManager2.getRoom(roomId);
|
|
2973
|
-
if (session) {
|
|
2974
|
-
clearPendingRoomCloseTimer(session);
|
|
2975
|
-
session.masterHostSocketId = socket.id;
|
|
2976
|
-
syncRoomAnalyticsState(session.analytics, socket.data.hostAuthority);
|
|
2977
|
-
roomManager2.setRoom(roomId, session);
|
|
2978
|
-
} else {
|
|
2979
|
-
session = createInitialRoomSession(roomId, 32, "system");
|
|
2980
|
-
roomManager2.setRoom(roomId, session);
|
|
2981
|
-
}
|
|
2982
|
-
roomManager2.setHostRoom(socket.id, roomId);
|
|
2983
|
-
socket.join(roomId);
|
|
2984
|
-
logHostEvent(
|
|
2985
|
-
"info",
|
|
2986
|
-
AIRJAM_DEV_LOG_EVENTS3.host.registerSystemAccepted,
|
|
2987
|
-
"Host registered as system host",
|
|
2988
|
-
{
|
|
2989
|
-
roomId
|
|
2990
|
-
}
|
|
2991
|
-
);
|
|
2992
|
-
runtimeUsagePublisher.publish(
|
|
2993
|
-
createRoomRuntimeUsageEvent(session, {
|
|
2994
|
-
kind: "room_registered"
|
|
2995
|
-
})
|
|
2996
|
-
);
|
|
2997
|
-
callback({
|
|
2998
|
-
ok: true,
|
|
2999
|
-
roomId,
|
|
3000
|
-
controllerCapability: getControllerCapabilityForAck(session)
|
|
3001
|
-
});
|
|
3002
|
-
io.to(roomId).emit("server:roomReady", { roomId });
|
|
3003
|
-
}
|
|
3004
|
-
);
|
|
3005
2233
|
socket.on(
|
|
3006
2234
|
"host:createRoom",
|
|
3007
2235
|
async (payload, callback) => {
|
|
@@ -3076,24 +2304,23 @@ var registerHostLifecycleHandlers = (context) => {
|
|
|
3076
2304
|
return;
|
|
3077
2305
|
}
|
|
3078
2306
|
}
|
|
3079
|
-
const
|
|
2307
|
+
const created = await createAndBindRoomForHost({
|
|
3080
2308
|
maxPlayers: maxPlayers ?? 8,
|
|
3081
|
-
hostSessionKind: socket.data.hostAuthority
|
|
2309
|
+
hostSessionKind: socket.data.hostAuthority.hostSessionKind
|
|
3082
2310
|
});
|
|
3083
|
-
if (!
|
|
2311
|
+
if (!created.ok) {
|
|
3084
2312
|
logHostEvent(
|
|
3085
2313
|
"warn",
|
|
3086
2314
|
AIRJAM_DEV_LOG_EVENTS3.host.createRoomRejected,
|
|
3087
|
-
"Rejected host createRoom because a unique room ID could not be generated",
|
|
3088
|
-
{
|
|
2315
|
+
created.denial ? "Rejected host createRoom by realtime admission authority" : "Rejected host createRoom because a unique room ID could not be generated",
|
|
2316
|
+
{
|
|
2317
|
+
reason: created.denial?.reason ?? "room_id_generation_failed"
|
|
2318
|
+
}
|
|
3089
2319
|
);
|
|
3090
|
-
callback
|
|
3091
|
-
ok: false,
|
|
3092
|
-
message: "Failed to generate unique room ID",
|
|
3093
|
-
code: ErrorCode2.CONNECTION_FAILED
|
|
3094
|
-
});
|
|
2320
|
+
rejectAdmission(created.denial, callback);
|
|
3095
2321
|
return;
|
|
3096
2322
|
}
|
|
2323
|
+
const session = created.session;
|
|
3097
2324
|
logHostEvent(
|
|
3098
2325
|
"info",
|
|
3099
2326
|
AIRJAM_DEV_LOG_EVENTS3.host.createRoomAccepted,
|
|
@@ -3188,7 +2415,7 @@ var registerHostLifecycleHandlers = (context) => {
|
|
|
3188
2415
|
});
|
|
3189
2416
|
return;
|
|
3190
2417
|
}
|
|
3191
|
-
const { roomId } = parsed.data;
|
|
2418
|
+
const { roomId, resumeCapabilityToken } = parsed.data;
|
|
3192
2419
|
const session = roomManager2.getRoom(roomId);
|
|
3193
2420
|
if (!session) {
|
|
3194
2421
|
logHostEvent(
|
|
@@ -3207,6 +2434,23 @@ var registerHostLifecycleHandlers = (context) => {
|
|
|
3207
2434
|
});
|
|
3208
2435
|
return;
|
|
3209
2436
|
}
|
|
2437
|
+
if (session.hostResumeCapability.token !== resumeCapabilityToken) {
|
|
2438
|
+
logHostEvent(
|
|
2439
|
+
"warn",
|
|
2440
|
+
AIRJAM_DEV_LOG_EVENTS3.host.reconnectRejected,
|
|
2441
|
+
"Rejected host reconnect with an invalid resume capability",
|
|
2442
|
+
{
|
|
2443
|
+
roomId,
|
|
2444
|
+
reason: "invalid_resume_capability"
|
|
2445
|
+
}
|
|
2446
|
+
);
|
|
2447
|
+
callback({
|
|
2448
|
+
ok: false,
|
|
2449
|
+
message: "Invalid host resume capability",
|
|
2450
|
+
code: ErrorCode2.UNAUTHORIZED
|
|
2451
|
+
});
|
|
2452
|
+
return;
|
|
2453
|
+
}
|
|
3210
2454
|
const previousMasterSocket = io.sockets.sockets.get(
|
|
3211
2455
|
session.masterHostSocketId
|
|
3212
2456
|
);
|
|
@@ -3215,7 +2459,6 @@ var registerHostLifecycleHandlers = (context) => {
|
|
|
3215
2459
|
clearPendingRoomCloseTimer(session);
|
|
3216
2460
|
const previousGameState = session.runtimeState;
|
|
3217
2461
|
session.masterHostSocketId = socket.id;
|
|
3218
|
-
syncRoomAnalyticsState(session.analytics, socket.data.hostAuthority);
|
|
3219
2462
|
roomManager2.setRoom(roomId, session);
|
|
3220
2463
|
roomManager2.setHostRoom(socket.id, roomId);
|
|
3221
2464
|
socket.join(roomId);
|
|
@@ -3245,12 +2488,9 @@ var registerHostLifecycleHandlers = (context) => {
|
|
|
3245
2488
|
}
|
|
3246
2489
|
);
|
|
3247
2490
|
callback({
|
|
3248
|
-
|
|
3249
|
-
roomId,
|
|
2491
|
+
...buildHostRegistrationAck(session),
|
|
3250
2492
|
arcadeSession: buildArcadeSessionForHostAck(session, uuidv4),
|
|
3251
|
-
|
|
3252
|
-
controllers: buildHostControllerSnapshot(session),
|
|
3253
|
-
controllerCapability: getControllerCapabilityForAck(session)
|
|
2493
|
+
arcadeSurfaceCheckpoint: buildArcadeSurfaceCheckpointForHostAck(session)
|
|
3254
2494
|
});
|
|
3255
2495
|
socket.emit("server:state", buildRoomStateMessage(roomId, session));
|
|
3256
2496
|
emitReplicatedStoreSnapshotsToHost(socket, session);
|
|
@@ -3368,20 +2608,19 @@ var registerHostLifecycleHandlers = (context) => {
|
|
|
3368
2608
|
});
|
|
3369
2609
|
return;
|
|
3370
2610
|
}
|
|
3371
|
-
|
|
3372
|
-
const nextSession = createAndBindRoomForHost({
|
|
2611
|
+
const created = await createAndBindRoomForHost({
|
|
3373
2612
|
roomId: nextRoomId,
|
|
3374
2613
|
maxPlayers: session.maxPlayers,
|
|
3375
|
-
hostSessionKind: session.analytics.hostSessionKind
|
|
2614
|
+
hostSessionKind: session.analytics.hostSessionKind,
|
|
2615
|
+
replacingLease: session.admissionLease
|
|
3376
2616
|
});
|
|
3377
|
-
if (!
|
|
3378
|
-
callback
|
|
3379
|
-
ok: false,
|
|
3380
|
-
message: "Failed to create a fresh room after reset",
|
|
3381
|
-
code: ErrorCode2.CONNECTION_FAILED
|
|
3382
|
-
});
|
|
2617
|
+
if (!created.ok) {
|
|
2618
|
+
rejectAdmission(created.denial, callback);
|
|
3383
2619
|
return;
|
|
3384
2620
|
}
|
|
2621
|
+
const nextSession = created.session;
|
|
2622
|
+
roomManager2.removeRoom(roomId, io, "room_reset");
|
|
2623
|
+
roomManager2.setHostRoom(socket.id, nextRoomId);
|
|
3385
2624
|
logHostEvent(
|
|
3386
2625
|
"info",
|
|
3387
2626
|
AIRJAM_DEV_LOG_EVENTS3.host.resetRoomAccepted,
|
|
@@ -3468,6 +2707,7 @@ var registerHostLifecycleHandlers = (context) => {
|
|
|
3468
2707
|
clearTimeout(controllerSession.pendingDisconnectTimer);
|
|
3469
2708
|
controllerSession.pendingDisconnectTimer = void 0;
|
|
3470
2709
|
}
|
|
2710
|
+
controllerSession.retiredAt = Date.now();
|
|
3471
2711
|
session.controllers.delete(controllerId);
|
|
3472
2712
|
emitControllerLeftNotice(io, session, controllerId);
|
|
3473
2713
|
runtimeUsagePublisher.publish(
|
|
@@ -3494,6 +2734,9 @@ var registerHostLifecycleHandlers = (context) => {
|
|
|
3494
2734
|
controllerSocket.disconnect(true);
|
|
3495
2735
|
}
|
|
3496
2736
|
}
|
|
2737
|
+
await realtimeAdmissionService.releaseController(
|
|
2738
|
+
controllerSession.admissionLease
|
|
2739
|
+
);
|
|
3497
2740
|
callback({ ok: true });
|
|
3498
2741
|
}
|
|
3499
2742
|
);
|
|
@@ -4091,9 +3334,9 @@ import {
|
|
|
4091
3334
|
controllerStateSchema,
|
|
4092
3335
|
controllerStateSyncRequestSchema,
|
|
4093
3336
|
controllerSystemSchema as controllerSystemSchema2,
|
|
4094
|
-
hostActionRpcSchema,
|
|
4095
3337
|
hostStateSyncSchema,
|
|
4096
|
-
isAirJamArcadePlatformPrefixAction
|
|
3338
|
+
isAirJamArcadePlatformPrefixAction,
|
|
3339
|
+
runtimeErrorReportSchema
|
|
4097
3340
|
} from "@air-jam/sdk/protocol";
|
|
4098
3341
|
var registerRealtimeHandlers = (context) => {
|
|
4099
3342
|
const logger = context.logger.child({ component: "realtime" });
|
|
@@ -4158,17 +3401,91 @@ var registerRealtimeHandlers = (context) => {
|
|
|
4158
3401
|
controllerActionRpcSummary.flushAll();
|
|
4159
3402
|
hostStateBroadcastSummary.flushAll();
|
|
4160
3403
|
});
|
|
3404
|
+
socket.on("runtime:error_report", (payload, callback) => {
|
|
3405
|
+
const acknowledge = (ack) => {
|
|
3406
|
+
if (typeof callback === "function") callback(ack);
|
|
3407
|
+
};
|
|
3408
|
+
const parsed = runtimeErrorReportSchema.safeParse(payload);
|
|
3409
|
+
if (!parsed.success) {
|
|
3410
|
+
logRealtimeEvent(
|
|
3411
|
+
"warn",
|
|
3412
|
+
AIRJAM_DEV_LOG_EVENTS4.browser.runtime,
|
|
3413
|
+
"Rejected an invalid hosted-runtime error report",
|
|
3414
|
+
{ reason: "invalid_payload" }
|
|
3415
|
+
);
|
|
3416
|
+
acknowledge({ ok: false, code: "invalid_payload" });
|
|
3417
|
+
return;
|
|
3418
|
+
}
|
|
3419
|
+
const report = parsed.data;
|
|
3420
|
+
if (context.isRateLimited(
|
|
3421
|
+
"runtime-error-report",
|
|
3422
|
+
context.runtimeErrorReportRateLimitMax
|
|
3423
|
+
)) {
|
|
3424
|
+
acknowledge({
|
|
3425
|
+
ok: false,
|
|
3426
|
+
reportId: report.reportId,
|
|
3427
|
+
code: "rate_limited"
|
|
3428
|
+
});
|
|
3429
|
+
return;
|
|
3430
|
+
}
|
|
3431
|
+
const authorized = report.role === "host" ? context.isHostAuthorizedForRoom(report.roomId) : context.isControllerAuthorizedForRoom(report.roomId);
|
|
3432
|
+
const session = authorized ? roomManager2.getRoom(report.roomId) : void 0;
|
|
3433
|
+
if (!authorized || !session) {
|
|
3434
|
+
acknowledge({
|
|
3435
|
+
ok: false,
|
|
3436
|
+
reportId: report.reportId,
|
|
3437
|
+
code: "unauthorized"
|
|
3438
|
+
});
|
|
3439
|
+
return;
|
|
3440
|
+
}
|
|
3441
|
+
if (context.isScopedRateLimited(
|
|
3442
|
+
"runtime-error-report-room",
|
|
3443
|
+
report.roomId,
|
|
3444
|
+
context.runtimeErrorReportRateLimitMax
|
|
3445
|
+
)) {
|
|
3446
|
+
acknowledge({
|
|
3447
|
+
ok: false,
|
|
3448
|
+
reportId: report.reportId,
|
|
3449
|
+
code: "rate_limited"
|
|
3450
|
+
});
|
|
3451
|
+
return;
|
|
3452
|
+
}
|
|
3453
|
+
const controllerId = report.role === "controller" ? socket.data.controllerAuthority?.controllerId : void 0;
|
|
3454
|
+
void context.operationalEventPublisher.publishRuntimeErrorReport({
|
|
3455
|
+
reportId: report.reportId,
|
|
3456
|
+
roomId: report.roomId,
|
|
3457
|
+
runtimeSessionId: session.analytics.runtimeSessionId,
|
|
3458
|
+
...controllerId ? { controllerId } : {},
|
|
3459
|
+
...session.activeGameId || session.analytics.gameId ? { gameId: session.activeGameId ?? session.analytics.gameId } : {},
|
|
3460
|
+
role: report.role,
|
|
3461
|
+
code: report.code,
|
|
3462
|
+
errorName: report.errorName,
|
|
3463
|
+
digest: report.digest,
|
|
3464
|
+
clientOccurredAt: report.occurredAt
|
|
3465
|
+
}).then(() => acknowledge({ ok: true, reportId: report.reportId })).catch((error) => {
|
|
3466
|
+
getRealtimeLogger({
|
|
3467
|
+
event: "runtime.error_report_persistence_failed",
|
|
3468
|
+
reportId: report.reportId,
|
|
3469
|
+
roomId: report.roomId,
|
|
3470
|
+
causeCode: error instanceof Error ? error.name : "unknown_error"
|
|
3471
|
+
}).warn("Failed to persist a hosted-runtime error report");
|
|
3472
|
+
acknowledge({
|
|
3473
|
+
ok: false,
|
|
3474
|
+
reportId: report.reportId,
|
|
3475
|
+
code: "unavailable"
|
|
3476
|
+
});
|
|
3477
|
+
});
|
|
3478
|
+
});
|
|
4161
3479
|
const routeControllerActionRpc = ({
|
|
4162
3480
|
payload,
|
|
4163
|
-
callback
|
|
4164
|
-
actorRole
|
|
3481
|
+
callback
|
|
4165
3482
|
}) => {
|
|
4166
|
-
const parsed =
|
|
3483
|
+
const parsed = controllerActionRpcSchema.safeParse(payload);
|
|
4167
3484
|
if (!parsed.success) {
|
|
4168
3485
|
logRealtimeEvent(
|
|
4169
3486
|
"warn",
|
|
4170
3487
|
AIRJAM_DEV_LOG_EVENTS4.controller.actionRpcRejected,
|
|
4171
|
-
`Rejected
|
|
3488
|
+
`Rejected controller action RPC with invalid payload`,
|
|
4172
3489
|
{
|
|
4173
3490
|
reason: "invalid_payload",
|
|
4174
3491
|
issues: parsed.error.issues
|
|
@@ -4177,7 +3494,7 @@ var registerRealtimeHandlers = (context) => {
|
|
|
4177
3494
|
rejectActionRpc(
|
|
4178
3495
|
callback,
|
|
4179
3496
|
"invalid_payload",
|
|
4180
|
-
`Rejected
|
|
3497
|
+
`Rejected controller action RPC with invalid payload.`
|
|
4181
3498
|
);
|
|
4182
3499
|
return;
|
|
4183
3500
|
}
|
|
@@ -4191,7 +3508,7 @@ var registerRealtimeHandlers = (context) => {
|
|
|
4191
3508
|
logRealtimeEvent(
|
|
4192
3509
|
"warn",
|
|
4193
3510
|
AIRJAM_DEV_LOG_EVENTS4.controller.actionRpcRejected,
|
|
4194
|
-
`Rejected
|
|
3511
|
+
`Rejected controller action RPC because action name is reserved`,
|
|
4195
3512
|
{
|
|
4196
3513
|
roomId,
|
|
4197
3514
|
actionName,
|
|
@@ -4202,7 +3519,7 @@ var registerRealtimeHandlers = (context) => {
|
|
|
4202
3519
|
rejectActionRpc(
|
|
4203
3520
|
callback,
|
|
4204
3521
|
"reserved_action",
|
|
4205
|
-
`Rejected
|
|
3522
|
+
`Rejected controller action RPC because action "${actionName}" is reserved.`,
|
|
4206
3523
|
{
|
|
4207
3524
|
actionName,
|
|
4208
3525
|
storeDomain
|
|
@@ -4214,7 +3531,7 @@ var registerRealtimeHandlers = (context) => {
|
|
|
4214
3531
|
logRealtimeEvent(
|
|
4215
3532
|
"warn",
|
|
4216
3533
|
AIRJAM_DEV_LOG_EVENTS4.controller.actionRpcRejected,
|
|
4217
|
-
`Rejected
|
|
3534
|
+
`Rejected controller action RPC because socket is unauthorized`,
|
|
4218
3535
|
{
|
|
4219
3536
|
roomId,
|
|
4220
3537
|
actionName,
|
|
@@ -4225,7 +3542,7 @@ var registerRealtimeHandlers = (context) => {
|
|
|
4225
3542
|
rejectActionRpc(
|
|
4226
3543
|
callback,
|
|
4227
3544
|
"unauthorized",
|
|
4228
|
-
`Rejected
|
|
3545
|
+
`Rejected controller action RPC because socket is unauthorized for this room.`,
|
|
4229
3546
|
{
|
|
4230
3547
|
roomId,
|
|
4231
3548
|
actionName,
|
|
@@ -4238,7 +3555,7 @@ var registerRealtimeHandlers = (context) => {
|
|
|
4238
3555
|
logRealtimeEvent(
|
|
4239
3556
|
"warn",
|
|
4240
3557
|
AIRJAM_DEV_LOG_EVENTS4.controller.actionRpcRejected,
|
|
4241
|
-
`Rejected
|
|
3558
|
+
`Rejected controller action RPC because privileged capability is missing`,
|
|
4242
3559
|
{
|
|
4243
3560
|
roomId,
|
|
4244
3561
|
actionName,
|
|
@@ -4249,7 +3566,7 @@ var registerRealtimeHandlers = (context) => {
|
|
|
4249
3566
|
rejectActionRpc(
|
|
4250
3567
|
callback,
|
|
4251
3568
|
"missing_capability",
|
|
4252
|
-
`Rejected
|
|
3569
|
+
`Rejected controller action RPC because the controller capability is missing.`,
|
|
4253
3570
|
{
|
|
4254
3571
|
roomId,
|
|
4255
3572
|
actionName,
|
|
@@ -4263,7 +3580,7 @@ var registerRealtimeHandlers = (context) => {
|
|
|
4263
3580
|
logRealtimeEvent(
|
|
4264
3581
|
"warn",
|
|
4265
3582
|
AIRJAM_DEV_LOG_EVENTS4.controller.actionRpcRejected,
|
|
4266
|
-
`Rejected
|
|
3583
|
+
`Rejected controller action RPC because room was not found`,
|
|
4267
3584
|
{
|
|
4268
3585
|
roomId,
|
|
4269
3586
|
actionName,
|
|
@@ -4274,7 +3591,7 @@ var registerRealtimeHandlers = (context) => {
|
|
|
4274
3591
|
rejectActionRpc(
|
|
4275
3592
|
callback,
|
|
4276
3593
|
"room_not_found",
|
|
4277
|
-
`Rejected
|
|
3594
|
+
`Rejected controller action RPC because the room was not found.`,
|
|
4278
3595
|
{
|
|
4279
3596
|
roomId,
|
|
4280
3597
|
actionName,
|
|
@@ -4288,7 +3605,7 @@ var registerRealtimeHandlers = (context) => {
|
|
|
4288
3605
|
logRealtimeEvent(
|
|
4289
3606
|
"warn",
|
|
4290
3607
|
AIRJAM_DEV_LOG_EVENTS4.controller.actionRpcRejected,
|
|
4291
|
-
`Rejected
|
|
3608
|
+
`Rejected controller action RPC because controller mapping was missing`,
|
|
4292
3609
|
{
|
|
4293
3610
|
roomId,
|
|
4294
3611
|
actionName,
|
|
@@ -4299,7 +3616,7 @@ var registerRealtimeHandlers = (context) => {
|
|
|
4299
3616
|
rejectActionRpc(
|
|
4300
3617
|
callback,
|
|
4301
3618
|
"controller_mapping_missing",
|
|
4302
|
-
`Rejected
|
|
3619
|
+
`Rejected controller action RPC because the controller mapping was missing.`,
|
|
4303
3620
|
{
|
|
4304
3621
|
roomId,
|
|
4305
3622
|
actionName,
|
|
@@ -4314,7 +3631,7 @@ var registerRealtimeHandlers = (context) => {
|
|
|
4314
3631
|
logRealtimeEvent(
|
|
4315
3632
|
"warn",
|
|
4316
3633
|
AIRJAM_DEV_LOG_EVENTS4.controller.actionRpcRejected,
|
|
4317
|
-
`Rejected
|
|
3634
|
+
`Rejected controller action RPC because controller session was not found`,
|
|
4318
3635
|
{
|
|
4319
3636
|
roomId,
|
|
4320
3637
|
controllerId,
|
|
@@ -4326,7 +3643,7 @@ var registerRealtimeHandlers = (context) => {
|
|
|
4326
3643
|
rejectActionRpc(
|
|
4327
3644
|
callback,
|
|
4328
3645
|
"controller_session_missing",
|
|
4329
|
-
`Rejected
|
|
3646
|
+
`Rejected controller action RPC because the controller session was not found.`,
|
|
4330
3647
|
{
|
|
4331
3648
|
roomId,
|
|
4332
3649
|
controllerId,
|
|
@@ -4336,13 +3653,13 @@ var registerRealtimeHandlers = (context) => {
|
|
|
4336
3653
|
);
|
|
4337
3654
|
return;
|
|
4338
3655
|
}
|
|
4339
|
-
const shouldRouteToMaster =
|
|
3656
|
+
const shouldRouteToMaster = isAirJamArcadePlatformPrefixAction(actionName);
|
|
4340
3657
|
const hostId = shouldRouteToMaster ? session.masterHostSocketId : roomManager2.getActiveHostId(session);
|
|
4341
3658
|
if (!hostId) {
|
|
4342
3659
|
logRealtimeEvent(
|
|
4343
3660
|
"warn",
|
|
4344
3661
|
AIRJAM_DEV_LOG_EVENTS4.controller.actionRpcRejected,
|
|
4345
|
-
`Rejected
|
|
3662
|
+
`Rejected controller action RPC because no host target was available`,
|
|
4346
3663
|
{
|
|
4347
3664
|
roomId,
|
|
4348
3665
|
controllerId,
|
|
@@ -4354,7 +3671,7 @@ var registerRealtimeHandlers = (context) => {
|
|
|
4354
3671
|
rejectActionRpc(
|
|
4355
3672
|
callback,
|
|
4356
3673
|
"host_target_missing",
|
|
4357
|
-
`Rejected
|
|
3674
|
+
`Rejected controller action RPC because no host target was available.`,
|
|
4358
3675
|
{
|
|
4359
3676
|
roomId,
|
|
4360
3677
|
controllerId,
|
|
@@ -4369,7 +3686,7 @@ var registerRealtimeHandlers = (context) => {
|
|
|
4369
3686
|
rejectActionRpc(
|
|
4370
3687
|
callback,
|
|
4371
3688
|
"host_target_missing",
|
|
4372
|
-
`Rejected
|
|
3689
|
+
`Rejected controller action RPC because the host target was not available.`,
|
|
4373
3690
|
{
|
|
4374
3691
|
roomId,
|
|
4375
3692
|
controllerId,
|
|
@@ -4384,8 +3701,8 @@ var registerRealtimeHandlers = (context) => {
|
|
|
4384
3701
|
payload: actionPayload,
|
|
4385
3702
|
storeDomain,
|
|
4386
3703
|
actor: {
|
|
4387
|
-
id:
|
|
4388
|
-
role:
|
|
3704
|
+
id: controllerId,
|
|
3705
|
+
role: "controller"
|
|
4389
3706
|
}
|
|
4390
3707
|
};
|
|
4391
3708
|
hostSocket.timeout(1500).emit("airjam:action_rpc", rpcPayload, (error, acknowledgement) => {
|
|
@@ -4418,7 +3735,7 @@ var registerRealtimeHandlers = (context) => {
|
|
|
4418
3735
|
callback?.(acknowledgement);
|
|
4419
3736
|
});
|
|
4420
3737
|
controllerActionRpcSummary.record({
|
|
4421
|
-
key: `${roomId}:${controllerId}:${storeDomain}:${actionName}:${
|
|
3738
|
+
key: `${roomId}:${controllerId}:${storeDomain}:${actionName}:controller:${shouldRouteToMaster ? "master" : "active"}`,
|
|
4422
3739
|
bindings: {
|
|
4423
3740
|
roomId,
|
|
4424
3741
|
controllerId
|
|
@@ -4426,7 +3743,7 @@ var registerRealtimeHandlers = (context) => {
|
|
|
4426
3743
|
data: {
|
|
4427
3744
|
actionName,
|
|
4428
3745
|
storeDomain,
|
|
4429
|
-
actorRole,
|
|
3746
|
+
actorRole: "controller",
|
|
4430
3747
|
target: shouldRouteToMaster ? "master_host" : "active_host"
|
|
4431
3748
|
},
|
|
4432
3749
|
metrics: {
|
|
@@ -4848,18 +4165,7 @@ var registerRealtimeHandlers = (context) => {
|
|
|
4848
4165
|
(payload, callback) => {
|
|
4849
4166
|
routeControllerActionRpc({
|
|
4850
4167
|
payload,
|
|
4851
|
-
callback
|
|
4852
|
-
actorRole: "controller"
|
|
4853
|
-
});
|
|
4854
|
-
}
|
|
4855
|
-
);
|
|
4856
|
-
socket.on(
|
|
4857
|
-
"controller:host_action_rpc",
|
|
4858
|
-
(payload, callback) => {
|
|
4859
|
-
routeControllerActionRpc({
|
|
4860
|
-
payload,
|
|
4861
|
-
callback,
|
|
4862
|
-
actorRole: "host"
|
|
4168
|
+
callback
|
|
4863
4169
|
});
|
|
4864
4170
|
}
|
|
4865
4171
|
);
|
|
@@ -4871,13 +4177,16 @@ var registerSocketHandlers = ({
|
|
|
4871
4177
|
socket,
|
|
4872
4178
|
logger,
|
|
4873
4179
|
roomManager: roomManager2,
|
|
4180
|
+
realtimeAdmissionService,
|
|
4874
4181
|
rateLimitService: rateLimitService2,
|
|
4875
4182
|
authService,
|
|
4876
4183
|
runtimeUsagePublisher,
|
|
4184
|
+
operationalEventPublisher,
|
|
4877
4185
|
rateLimitWindowMs,
|
|
4878
4186
|
hostRegistrationRateLimitMax,
|
|
4879
4187
|
controllerJoinRateLimitMax,
|
|
4880
4188
|
staticAppRateLimitMax,
|
|
4189
|
+
runtimeErrorReportRateLimitMax,
|
|
4881
4190
|
proxyHeaderTrustMode,
|
|
4882
4191
|
maintenanceMode
|
|
4883
4192
|
}) => {
|
|
@@ -4915,11 +4224,14 @@ var registerSocketHandlers = ({
|
|
|
4915
4224
|
socket,
|
|
4916
4225
|
logger: socketLogger,
|
|
4917
4226
|
roomManager: roomManager2,
|
|
4227
|
+
realtimeAdmissionService,
|
|
4918
4228
|
authService,
|
|
4919
4229
|
runtimeUsagePublisher,
|
|
4230
|
+
operationalEventPublisher,
|
|
4920
4231
|
hostRegistrationRateLimitMax,
|
|
4921
4232
|
controllerJoinRateLimitMax,
|
|
4922
4233
|
staticAppRateLimitMax,
|
|
4234
|
+
runtimeErrorReportRateLimitMax,
|
|
4923
4235
|
emitError,
|
|
4924
4236
|
isRateLimited,
|
|
4925
4237
|
isScopedRateLimited,
|
|
@@ -5127,434 +4439,131 @@ var DevLogCollector = class {
|
|
|
5127
4439
|
}
|
|
5128
4440
|
};
|
|
5129
4441
|
|
|
5130
|
-
// src/
|
|
5131
|
-
|
|
5132
|
-
|
|
5133
|
-
|
|
5134
|
-
|
|
5135
|
-
|
|
5136
|
-
|
|
5137
|
-
|
|
5138
|
-
|
|
4442
|
+
// src/logging/server-logging.ts
|
|
4443
|
+
var createServerLogging = (options, envConfig) => {
|
|
4444
|
+
const devLogCollector = options.devLogCollector === false ? null : options.devLogCollector ?? new DevLogCollector({
|
|
4445
|
+
enabled: envConfig.devLogCollectorEnabled,
|
|
4446
|
+
logDir: options.devLogDir ?? envConfig.devLogDir ?? resolveDefaultDevLogDir()
|
|
4447
|
+
});
|
|
4448
|
+
const logger = options.logger ?? createServerLogger(
|
|
4449
|
+
{ service: "air-jam-server" },
|
|
4450
|
+
void 0,
|
|
4451
|
+
devLogCollector,
|
|
4452
|
+
{
|
|
4453
|
+
level: envConfig.logLevel
|
|
4454
|
+
}
|
|
4455
|
+
);
|
|
4456
|
+
return {
|
|
4457
|
+
logger,
|
|
4458
|
+
devLogCollector: devLogCollector ?? false
|
|
4459
|
+
};
|
|
4460
|
+
};
|
|
4461
|
+
|
|
4462
|
+
// src/operations/operational-event-publisher.ts
|
|
4463
|
+
var createNoopServerOperationalEventPublisher = () => ({
|
|
4464
|
+
publishFailure: async () => void 0,
|
|
4465
|
+
publishRuntimeErrorReport: async () => void 0
|
|
4466
|
+
});
|
|
4467
|
+
var publishServerOperationalFailureSafely = ({
|
|
4468
|
+
publisher,
|
|
4469
|
+
logger,
|
|
4470
|
+
input
|
|
4471
|
+
}) => {
|
|
4472
|
+
void publisher.publishFailure(input).catch((error) => {
|
|
4473
|
+
logger.warn(
|
|
4474
|
+
{
|
|
4475
|
+
event: "operational_event.publish_failed",
|
|
4476
|
+
failureCode: input.code,
|
|
4477
|
+
causeCode: error instanceof Error ? error.name : "unknown_error"
|
|
4478
|
+
},
|
|
4479
|
+
"Failed to enqueue a structured operational event"
|
|
4480
|
+
);
|
|
4481
|
+
});
|
|
4482
|
+
};
|
|
4483
|
+
|
|
4484
|
+
// src/origin-policy.ts
|
|
4485
|
+
var LEADING_SUBDOMAIN_PATTERN = /^(https?):\/\/\*\.([^/:]+)(?::(\d+))?$/i;
|
|
4486
|
+
var HOSTNAME_PATTERN = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i;
|
|
4487
|
+
var SUBDOMAIN_LABEL_PATTERN = "[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?";
|
|
4488
|
+
var escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
4489
|
+
var compileOrigin = (origin) => {
|
|
4490
|
+
if (!origin.includes("*")) {
|
|
4491
|
+
return origin;
|
|
5139
4492
|
}
|
|
5140
|
-
|
|
5141
|
-
|
|
5142
|
-
|
|
5143
|
-
|
|
4493
|
+
const match = LEADING_SUBDOMAIN_PATTERN.exec(origin);
|
|
4494
|
+
if (!match) {
|
|
4495
|
+
throw new Error(
|
|
4496
|
+
`Invalid AIR_JAM_ALLOWED_ORIGINS pattern "${origin}". Use a leading subdomain wildcard such as "https://*.vercel.app".`
|
|
4497
|
+
);
|
|
4498
|
+
}
|
|
4499
|
+
const [, protocol, hostname, port] = match;
|
|
4500
|
+
if (!hostname || !HOSTNAME_PATTERN.test(hostname)) {
|
|
4501
|
+
throw new Error(
|
|
4502
|
+
`Invalid AIR_JAM_ALLOWED_ORIGINS hostname in pattern "${origin}".`
|
|
4503
|
+
);
|
|
5144
4504
|
}
|
|
4505
|
+
const portPattern = port ? `:${escapeRegExp(port)}` : "";
|
|
4506
|
+
return new RegExp(
|
|
4507
|
+
`^${escapeRegExp(protocol)}://${SUBDOMAIN_LABEL_PATTERN}\\.${escapeRegExp(hostname)}${portPattern}$`,
|
|
4508
|
+
"i"
|
|
4509
|
+
);
|
|
5145
4510
|
};
|
|
5146
|
-
var
|
|
5147
|
-
|
|
5148
|
-
|
|
5149
|
-
}) => {
|
|
5150
|
-
if (!appId || !db) {
|
|
5151
|
-
return null;
|
|
4511
|
+
var resolveCorsOrigin = (input, fallback) => {
|
|
4512
|
+
if (input === "*") {
|
|
4513
|
+
return "*";
|
|
5152
4514
|
}
|
|
5153
|
-
const
|
|
5154
|
-
|
|
4515
|
+
const origins = input && input.length > 0 ? input : fallback;
|
|
4516
|
+
if (origins === "*" || origins.includes("*")) {
|
|
4517
|
+
return "*";
|
|
4518
|
+
}
|
|
4519
|
+
return origins.map(compileOrigin);
|
|
5155
4520
|
};
|
|
4521
|
+
|
|
4522
|
+
// src/services/auth-service.ts
|
|
5156
4523
|
var AuthService = class {
|
|
5157
|
-
logger;
|
|
5158
|
-
masterKey;
|
|
5159
|
-
hostGrantSecret;
|
|
5160
|
-
databaseUrl;
|
|
5161
|
-
authMode;
|
|
5162
|
-
db;
|
|
5163
4524
|
constructor(options = {}) {
|
|
5164
|
-
this.
|
|
5165
|
-
this.masterKey = options.env?.masterKey ?? process.env.AIR_JAM_MASTER_KEY;
|
|
5166
|
-
this.hostGrantSecret = options.env?.hostGrantSecret ?? process.env.AIR_JAM_HOST_GRANT_SECRET;
|
|
5167
|
-
this.databaseUrl = options.env?.databaseUrl ?? resolveServerRuntimeDatabaseUrl(process.env).databaseUrl;
|
|
5168
|
-
this.authMode = this.resolveAuthMode(options.env);
|
|
5169
|
-
this.db = options.db ?? null;
|
|
5170
|
-
if (this.authMode === "disabled") {
|
|
5171
|
-
this.logger.info(
|
|
5172
|
-
{ event: AIRJAM_DEV_LOG_EVENTS7.auth.modeDisabled },
|
|
5173
|
-
"Authentication disabled (set AIR_JAM_AUTH_MODE=required to enforce app identity checks)"
|
|
5174
|
-
);
|
|
5175
|
-
} else if (this.masterKey && !this.databaseUrl && !this.hostGrantSecret) {
|
|
5176
|
-
this.logger.info(
|
|
5177
|
-
{ event: AIRJAM_DEV_LOG_EVENTS7.auth.modeMasterKey },
|
|
5178
|
-
"Running with master key authentication (no database required)"
|
|
5179
|
-
);
|
|
5180
|
-
} else if (this.databaseUrl && this.hostGrantSecret) {
|
|
5181
|
-
this.logger.info(
|
|
5182
|
-
{ event: AIRJAM_DEV_LOG_EVENTS7.auth.modeDatabaseAndHostGrant },
|
|
5183
|
-
"Running with database authentication and signed host-grant verification"
|
|
5184
|
-
);
|
|
5185
|
-
} else if (this.databaseUrl) {
|
|
5186
|
-
this.logger.info(
|
|
5187
|
-
{ event: AIRJAM_DEV_LOG_EVENTS7.auth.modeDatabase },
|
|
5188
|
-
"Running with database authentication"
|
|
5189
|
-
);
|
|
5190
|
-
} else if (this.hostGrantSecret) {
|
|
5191
|
-
this.logger.info(
|
|
5192
|
-
{ event: AIRJAM_DEV_LOG_EVENTS7.auth.modeHostGrantOnly },
|
|
5193
|
-
"Running with signed host-grant authentication only (app ID bootstrap disabled because DATABASE_URL is not configured)"
|
|
5194
|
-
);
|
|
5195
|
-
} else {
|
|
5196
|
-
this.logger.warn(
|
|
5197
|
-
{ event: AIRJAM_DEV_LOG_EVENTS7.auth.backendMissing },
|
|
5198
|
-
"Authentication required, but no auth backend is configured (set AIR_JAM_MASTER_KEY or DATABASE_URL)"
|
|
5199
|
-
);
|
|
5200
|
-
}
|
|
4525
|
+
this.options = options;
|
|
5201
4526
|
}
|
|
5202
4527
|
getStartupConfigurationError() {
|
|
5203
|
-
|
|
5204
|
-
return null;
|
|
5205
|
-
}
|
|
5206
|
-
if (this.masterKey || this.databaseUrl || this.hostGrantSecret) {
|
|
5207
|
-
return null;
|
|
5208
|
-
}
|
|
5209
|
-
return [
|
|
5210
|
-
"AIR_JAM_AUTH_MODE=required requires an auth backend.",
|
|
5211
|
-
"Configure DATABASE_URL for app ID bootstrap, AIR_JAM_HOST_GRANT_SECRET for signed host grants, or AIR_JAM_MASTER_KEY for the legacy fallback."
|
|
5212
|
-
].join(" ");
|
|
4528
|
+
return this.options.env?.authMode === "required" && !this.options.env.masterKey ? "Required authentication needs an explicit authService adapter. AIR_JAM_MASTER_KEY is available only for local development and tests." : null;
|
|
5213
4529
|
}
|
|
5214
4530
|
async verifyHostBootstrap({
|
|
5215
4531
|
appId,
|
|
5216
4532
|
hostGrant,
|
|
5217
|
-
origin
|
|
4533
|
+
origin,
|
|
4534
|
+
hostSessionKind
|
|
5218
4535
|
}) {
|
|
5219
|
-
const normalizedOrigin = normalizeOrigin(origin) ?? void 0;
|
|
5220
4536
|
if (hostGrant) {
|
|
5221
|
-
if (!this.hostGrantSecret) {
|
|
5222
|
-
return {
|
|
5223
|
-
isVerified: false,
|
|
5224
|
-
error: "Unauthorized: Host grant verification is not configured on the server"
|
|
5225
|
-
};
|
|
5226
|
-
}
|
|
5227
|
-
const grantResult = await verifyHostGrant({
|
|
5228
|
-
secret: this.hostGrantSecret,
|
|
5229
|
-
token: hostGrant
|
|
5230
|
-
});
|
|
5231
|
-
if (!grantResult.ok || !grantResult.claims) {
|
|
5232
|
-
return {
|
|
5233
|
-
isVerified: false,
|
|
5234
|
-
error: grantResult.error ?? "Unauthorized: Invalid Host Grant"
|
|
5235
|
-
};
|
|
5236
|
-
}
|
|
5237
|
-
const grantOrigins = (grantResult.claims.origins ?? []).map((value) => normalizeOrigin(value)).filter((value) => value !== null);
|
|
5238
|
-
if (grantOrigins.length > 0) {
|
|
5239
|
-
if (!normalizedOrigin) {
|
|
5240
|
-
return {
|
|
5241
|
-
isVerified: false,
|
|
5242
|
-
error: "Unauthorized: Missing or Invalid Origin"
|
|
5243
|
-
};
|
|
5244
|
-
}
|
|
5245
|
-
if (!grantOrigins.includes(normalizedOrigin)) {
|
|
5246
|
-
return {
|
|
5247
|
-
isVerified: false,
|
|
5248
|
-
error: "Unauthorized: Origin not allowed by Host Grant"
|
|
5249
|
-
};
|
|
5250
|
-
}
|
|
5251
|
-
}
|
|
5252
|
-
const keyRecord = await resolveActiveAppIdRecord({
|
|
5253
|
-
appId: grantResult.claims.appId,
|
|
5254
|
-
db: this.db
|
|
5255
|
-
});
|
|
5256
|
-
return {
|
|
5257
|
-
isVerified: true,
|
|
5258
|
-
appId: grantResult.claims.appId,
|
|
5259
|
-
gameId: keyRecord?.gameId,
|
|
5260
|
-
verifiedVia: "hostGrant",
|
|
5261
|
-
verifiedOrigin: normalizedOrigin,
|
|
5262
|
-
grantClaims: grantResult.claims
|
|
5263
|
-
};
|
|
5264
|
-
}
|
|
5265
|
-
const appIdResult = await this.verifyAppId(appId, { origin });
|
|
5266
|
-
return {
|
|
5267
|
-
...appIdResult,
|
|
5268
|
-
appId: appIdResult.isVerified ? appId : void 0,
|
|
5269
|
-
verifiedVia: appIdResult.isVerified ? "appId" : void 0,
|
|
5270
|
-
verifiedOrigin: appIdResult.isVerified ? normalizedOrigin : void 0
|
|
5271
|
-
};
|
|
5272
|
-
}
|
|
5273
|
-
/**
|
|
5274
|
-
* Verify a browser-supplied app ID.
|
|
5275
|
-
* Returns verification result with optional error message
|
|
5276
|
-
* In local/dev mode, always returns success
|
|
5277
|
-
*/
|
|
5278
|
-
async verifyAppId(appId, context) {
|
|
5279
|
-
if (this.authMode === "disabled") {
|
|
5280
|
-
return { isVerified: true };
|
|
5281
|
-
}
|
|
5282
|
-
if (!appId) {
|
|
5283
|
-
return {
|
|
5284
|
-
isVerified: false,
|
|
5285
|
-
error: "Unauthorized: Invalid or Missing App ID"
|
|
5286
|
-
};
|
|
5287
|
-
}
|
|
5288
|
-
if (this.masterKey && appId === this.masterKey) {
|
|
5289
|
-
return { isVerified: true };
|
|
5290
|
-
}
|
|
5291
|
-
if (!this.databaseUrl || !this.db) {
|
|
5292
|
-
return {
|
|
5293
|
-
isVerified: false,
|
|
5294
|
-
error: "Unauthorized: Invalid or Missing App ID"
|
|
5295
|
-
};
|
|
5296
|
-
}
|
|
5297
|
-
try {
|
|
5298
|
-
const keyRecord = await resolveActiveAppIdRecord({
|
|
5299
|
-
appId,
|
|
5300
|
-
db: this.db
|
|
5301
|
-
});
|
|
5302
|
-
if (keyRecord) {
|
|
5303
|
-
const allowedOrigins = keyRecord.allowedOrigins ?? [];
|
|
5304
|
-
if (allowedOrigins.length > 0) {
|
|
5305
|
-
const requestOrigin = normalizeOrigin(context?.origin);
|
|
5306
|
-
if (!requestOrigin) {
|
|
5307
|
-
return {
|
|
5308
|
-
isVerified: false,
|
|
5309
|
-
error: "Unauthorized: Missing or Invalid Origin"
|
|
5310
|
-
};
|
|
5311
|
-
}
|
|
5312
|
-
const normalizedAllowedOrigins = allowedOrigins.map((value) => normalizeOrigin(value)).filter((value) => value !== null);
|
|
5313
|
-
if (!normalizedAllowedOrigins.includes(requestOrigin)) {
|
|
5314
|
-
return {
|
|
5315
|
-
isVerified: false,
|
|
5316
|
-
error: "Unauthorized: Origin not allowed for this App ID"
|
|
5317
|
-
};
|
|
5318
|
-
}
|
|
5319
|
-
}
|
|
5320
|
-
this.db.update(appIds).set({ lastUsedAt: /* @__PURE__ */ new Date() }).where(eq3(appIds.id, keyRecord.id)).catch((err) => {
|
|
5321
|
-
this.logger.warn(
|
|
5322
|
-
{
|
|
5323
|
-
event: AIRJAM_DEV_LOG_EVENTS7.auth.appIdLastUsedAtUpdateFailed,
|
|
5324
|
-
err
|
|
5325
|
-
},
|
|
5326
|
-
"Failed to update app ID lastUsedAt"
|
|
5327
|
-
);
|
|
5328
|
-
});
|
|
5329
|
-
return { isVerified: true };
|
|
5330
|
-
}
|
|
5331
4537
|
return {
|
|
5332
4538
|
isVerified: false,
|
|
5333
|
-
error: "Unauthorized:
|
|
4539
|
+
error: "Unauthorized: Host grant verification is not configured on the server"
|
|
5334
4540
|
};
|
|
5335
|
-
} catch (error) {
|
|
5336
|
-
this.logger.error(
|
|
5337
|
-
{
|
|
5338
|
-
event: AIRJAM_DEV_LOG_EVENTS7.auth.appIdVerificationDatabaseError,
|
|
5339
|
-
err: error
|
|
5340
|
-
},
|
|
5341
|
-
"Database error during app ID verification"
|
|
5342
|
-
);
|
|
5343
|
-
return {
|
|
5344
|
-
isVerified: false,
|
|
5345
|
-
error: "Internal Server Error"
|
|
5346
|
-
};
|
|
5347
|
-
}
|
|
5348
|
-
}
|
|
5349
|
-
resolveAuthMode(env) {
|
|
5350
|
-
const configuredMode = env?.authMode ?? process.env.AIR_JAM_AUTH_MODE?.toLowerCase();
|
|
5351
|
-
if (configuredMode === "disabled") {
|
|
5352
|
-
return "disabled";
|
|
5353
4541
|
}
|
|
5354
|
-
|
|
5355
|
-
|
|
5356
|
-
|
|
5357
|
-
|
|
5358
|
-
|
|
5359
|
-
|
|
5360
|
-
|
|
5361
|
-
}
|
|
5362
|
-
};
|
|
5363
|
-
|
|
5364
|
-
// src/services/dev-harness-registry.ts
|
|
5365
|
-
import { randomUUID } from "crypto";
|
|
5366
|
-
var ACTIVE_SESSION_TTL_MS = 3e4;
|
|
5367
|
-
var DEFAULT_INVOKE_TIMEOUT_MS = 1e4;
|
|
5368
|
-
var DEFAULT_WAIT_TIMEOUT_MS = 2e4;
|
|
5369
|
-
var toTimestamp = (value) => {
|
|
5370
|
-
const parsed = Date.parse(value);
|
|
5371
|
-
return Number.isFinite(parsed) ? parsed : 0;
|
|
5372
|
-
};
|
|
5373
|
-
var DevHarnessRegistry = class {
|
|
5374
|
-
sessions = /* @__PURE__ */ new Map();
|
|
5375
|
-
pendingCommands = /* @__PURE__ */ new Map();
|
|
5376
|
-
pendingCommandWaiters = /* @__PURE__ */ new Map();
|
|
5377
|
-
pendingInvocations = /* @__PURE__ */ new Map();
|
|
5378
|
-
register(payload) {
|
|
5379
|
-
this.pruneStaleSessions();
|
|
5380
|
-
const existing = this.sessions.get(payload.sessionId);
|
|
5381
|
-
const nowIso = (/* @__PURE__ */ new Date()).toISOString();
|
|
5382
|
-
const nextRecord = {
|
|
5383
|
-
sessionId: payload.sessionId,
|
|
5384
|
-
gameId: payload.gameId,
|
|
5385
|
-
role: payload.role,
|
|
5386
|
-
roomId: payload.roomId,
|
|
5387
|
-
origin: payload.origin,
|
|
5388
|
-
href: payload.href,
|
|
5389
|
-
title: payload.title,
|
|
5390
|
-
actions: [...payload.actions].sort(
|
|
5391
|
-
(left, right) => left.name.localeCompare(right.name)
|
|
5392
|
-
),
|
|
5393
|
-
actionNames: payload.actions.map((action) => action.name).sort((left, right) => left.localeCompare(right)),
|
|
5394
|
-
snapshot: payload.snapshot,
|
|
5395
|
-
registeredAt: existing?.registeredAt ?? nowIso,
|
|
5396
|
-
lastSeenAt: nowIso
|
|
5397
|
-
};
|
|
5398
|
-
this.sessions.set(payload.sessionId, nextRecord);
|
|
5399
|
-
return nextRecord;
|
|
5400
|
-
}
|
|
5401
|
-
listSessions(filters = {}) {
|
|
5402
|
-
this.pruneStaleSessions();
|
|
5403
|
-
const roomId = filters.roomId?.trim().toUpperCase();
|
|
5404
|
-
return [...this.sessions.values()].filter((session) => {
|
|
5405
|
-
if (filters.gameId && session.gameId !== filters.gameId) {
|
|
5406
|
-
return false;
|
|
5407
|
-
}
|
|
5408
|
-
if (roomId && session.roomId !== roomId) {
|
|
5409
|
-
return false;
|
|
5410
|
-
}
|
|
5411
|
-
if (filters.role && session.role !== filters.role) {
|
|
5412
|
-
return false;
|
|
4542
|
+
const verification = await this.verifyAppId(appId);
|
|
4543
|
+
let verifiedOrigin;
|
|
4544
|
+
if (origin) {
|
|
4545
|
+
try {
|
|
4546
|
+
verifiedOrigin = new URL(origin).origin;
|
|
4547
|
+
} catch {
|
|
4548
|
+
verifiedOrigin = void 0;
|
|
5413
4549
|
}
|
|
5414
|
-
return true;
|
|
5415
|
-
}).sort((left, right) => {
|
|
5416
|
-
return toTimestamp(right.lastSeenAt) - toTimestamp(left.lastSeenAt);
|
|
5417
|
-
});
|
|
5418
|
-
}
|
|
5419
|
-
async awaitNextCommand(sessionId, waitMs = DEFAULT_WAIT_TIMEOUT_MS) {
|
|
5420
|
-
this.pruneStaleSessions();
|
|
5421
|
-
const queued = this.pendingCommands.get(sessionId);
|
|
5422
|
-
if (queued && queued.length > 0) {
|
|
5423
|
-
const command = queued.shift() ?? null;
|
|
5424
|
-
if (queued.length === 0) {
|
|
5425
|
-
this.pendingCommands.delete(sessionId);
|
|
5426
|
-
}
|
|
5427
|
-
return command;
|
|
5428
4550
|
}
|
|
5429
|
-
return
|
|
5430
|
-
|
|
5431
|
-
|
|
5432
|
-
|
|
5433
|
-
|
|
5434
|
-
|
|
5435
|
-
const timer = setTimeout(() => {
|
|
5436
|
-
this.pendingCommandWaiters.delete(sessionId);
|
|
5437
|
-
resolve(null);
|
|
5438
|
-
}, waitMs);
|
|
5439
|
-
this.pendingCommandWaiters.set(sessionId, {
|
|
5440
|
-
resolve: (command) => {
|
|
5441
|
-
clearTimeout(timer);
|
|
5442
|
-
resolve(command);
|
|
5443
|
-
},
|
|
5444
|
-
timer
|
|
5445
|
-
});
|
|
5446
|
-
});
|
|
5447
|
-
}
|
|
5448
|
-
async invoke(payload) {
|
|
5449
|
-
this.pruneStaleSessions();
|
|
5450
|
-
const session = this.resolveTargetSession(payload);
|
|
5451
|
-
if (!session) {
|
|
5452
|
-
throw new Error("No matching live harness session found.");
|
|
5453
|
-
}
|
|
5454
|
-
const commandId = randomUUID();
|
|
5455
|
-
const command = {
|
|
5456
|
-
commandId,
|
|
5457
|
-
actionName: payload.actionName,
|
|
5458
|
-
payload: payload.payload,
|
|
5459
|
-
issuedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
4551
|
+
return {
|
|
4552
|
+
...verification,
|
|
4553
|
+
appId: verification.isVerified ? appId : void 0,
|
|
4554
|
+
verifiedVia: verification.isVerified ? "appId" : void 0,
|
|
4555
|
+
verifiedOrigin: verification.isVerified ? verifiedOrigin : void 0,
|
|
4556
|
+
hostSessionKind: verification.isVerified ? this.options.env?.authMode === "required" ? "game" : hostSessionKind ?? "system" : void 0
|
|
5460
4557
|
};
|
|
5461
|
-
const timeoutMs = payload.timeoutMs && payload.timeoutMs > 0 ? payload.timeoutMs : DEFAULT_INVOKE_TIMEOUT_MS;
|
|
5462
|
-
const resultPromise = new Promise(
|
|
5463
|
-
(resolve, reject) => {
|
|
5464
|
-
const timer = setTimeout(() => {
|
|
5465
|
-
this.pendingInvocations.delete(commandId);
|
|
5466
|
-
reject(
|
|
5467
|
-
new Error(
|
|
5468
|
-
`Timed out waiting for harness action "${payload.actionName}" on session "${session.sessionId}".`
|
|
5469
|
-
)
|
|
5470
|
-
);
|
|
5471
|
-
}, timeoutMs);
|
|
5472
|
-
this.pendingInvocations.set(commandId, {
|
|
5473
|
-
sessionId: session.sessionId,
|
|
5474
|
-
resolve,
|
|
5475
|
-
reject,
|
|
5476
|
-
timer
|
|
5477
|
-
});
|
|
5478
|
-
}
|
|
5479
|
-
);
|
|
5480
|
-
const waiter = this.pendingCommandWaiters.get(session.sessionId);
|
|
5481
|
-
if (waiter) {
|
|
5482
|
-
this.pendingCommandWaiters.delete(session.sessionId);
|
|
5483
|
-
waiter.resolve(command);
|
|
5484
|
-
} else {
|
|
5485
|
-
const queue = this.pendingCommands.get(session.sessionId) ?? [];
|
|
5486
|
-
queue.push(command);
|
|
5487
|
-
this.pendingCommands.set(session.sessionId, queue);
|
|
5488
|
-
}
|
|
5489
|
-
return resultPromise;
|
|
5490
4558
|
}
|
|
5491
|
-
|
|
5492
|
-
|
|
5493
|
-
if (
|
|
5494
|
-
return
|
|
5495
|
-
|
|
5496
|
-
|
|
5497
|
-
|
|
5498
|
-
const session = this.sessions.get(pending.sessionId);
|
|
5499
|
-
if (!session) {
|
|
5500
|
-
const error = new Error(
|
|
5501
|
-
`Harness session "${pending.sessionId}" disappeared before completion.`
|
|
5502
|
-
);
|
|
5503
|
-
pending.reject(error);
|
|
5504
|
-
return null;
|
|
5505
|
-
}
|
|
5506
|
-
const completedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
5507
|
-
const updatedSession = {
|
|
5508
|
-
...session,
|
|
5509
|
-
roomId: payload.result.roomId ?? session.roomId,
|
|
5510
|
-
snapshot: payload.result.snapshotAfter ?? session.snapshot,
|
|
5511
|
-
lastSeenAt: completedAt
|
|
5512
|
-
};
|
|
5513
|
-
this.sessions.set(session.sessionId, updatedSession);
|
|
5514
|
-
if (payload.result.error?.message) {
|
|
5515
|
-
const error = new Error(payload.result.error.message);
|
|
5516
|
-
pending.reject(error);
|
|
5517
|
-
return null;
|
|
5518
|
-
}
|
|
5519
|
-
const response = {
|
|
5520
|
-
session: updatedSession,
|
|
5521
|
-
invocation: {
|
|
5522
|
-
...payload.result,
|
|
5523
|
-
commandId: payload.commandId,
|
|
5524
|
-
completedAt
|
|
5525
|
-
}
|
|
4559
|
+
async verifyAppId(appId) {
|
|
4560
|
+
if (this.options.env?.authMode !== "required") return { isVerified: true };
|
|
4561
|
+
if (this.options.env.masterKey && appId === this.options.env.masterKey)
|
|
4562
|
+
return { isVerified: true };
|
|
4563
|
+
return {
|
|
4564
|
+
isVerified: false,
|
|
4565
|
+
error: "Unauthorized: Invalid or Missing App ID"
|
|
5526
4566
|
};
|
|
5527
|
-
pending.resolve(response);
|
|
5528
|
-
return response;
|
|
5529
|
-
}
|
|
5530
|
-
pruneStaleSessions() {
|
|
5531
|
-
const now = Date.now();
|
|
5532
|
-
for (const [sessionId, session] of this.sessions) {
|
|
5533
|
-
if (now - toTimestamp(session.lastSeenAt) <= ACTIVE_SESSION_TTL_MS) {
|
|
5534
|
-
continue;
|
|
5535
|
-
}
|
|
5536
|
-
this.sessions.delete(sessionId);
|
|
5537
|
-
this.pendingCommands.delete(sessionId);
|
|
5538
|
-
const waiter = this.pendingCommandWaiters.get(sessionId);
|
|
5539
|
-
if (waiter) {
|
|
5540
|
-
clearTimeout(waiter.timer);
|
|
5541
|
-
this.pendingCommandWaiters.delete(sessionId);
|
|
5542
|
-
waiter.resolve(null);
|
|
5543
|
-
}
|
|
5544
|
-
}
|
|
5545
|
-
}
|
|
5546
|
-
resolveTargetSession(payload) {
|
|
5547
|
-
const sessionId = payload.sessionId?.trim();
|
|
5548
|
-
if (sessionId) {
|
|
5549
|
-
return this.sessions.get(sessionId) ?? null;
|
|
5550
|
-
}
|
|
5551
|
-
const roomId = payload.roomId?.trim().toUpperCase();
|
|
5552
|
-
const candidates = this.listSessions({
|
|
5553
|
-
gameId: payload.gameId,
|
|
5554
|
-
roomId,
|
|
5555
|
-
role: "host"
|
|
5556
|
-
});
|
|
5557
|
-
return candidates[0] ?? null;
|
|
5558
4567
|
}
|
|
5559
4568
|
};
|
|
5560
4569
|
|
|
@@ -5599,6 +4608,153 @@ var RateLimitService = class {
|
|
|
5599
4608
|
};
|
|
5600
4609
|
var rateLimitService = new RateLimitService();
|
|
5601
4610
|
|
|
4611
|
+
// src/services/realtime-admission-service.ts
|
|
4612
|
+
var denial = (reason, message, retryAfterSeconds = 15) => ({
|
|
4613
|
+
ok: false,
|
|
4614
|
+
reason,
|
|
4615
|
+
message,
|
|
4616
|
+
retryAfterSeconds
|
|
4617
|
+
});
|
|
4618
|
+
var createLeaseToken = () => crypto.randomUUID();
|
|
4619
|
+
var createLocalRealtimeAdmissionService = ({
|
|
4620
|
+
instanceId = `local-${crypto.randomUUID()}`
|
|
4621
|
+
} = {}) => {
|
|
4622
|
+
let draining = false;
|
|
4623
|
+
const rooms = /* @__PURE__ */ new Map();
|
|
4624
|
+
const readRoom = (lease) => {
|
|
4625
|
+
const room = rooms.get(lease.roomId);
|
|
4626
|
+
return room?.lease.leaseToken === lease.leaseToken ? room : null;
|
|
4627
|
+
};
|
|
4628
|
+
const readController = (lease) => {
|
|
4629
|
+
const controller = rooms.get(lease.roomId)?.controllers.get(lease.controllerId);
|
|
4630
|
+
return controller?.leaseToken === lease.leaseToken ? controller : null;
|
|
4631
|
+
};
|
|
4632
|
+
const deleteController = (lease) => {
|
|
4633
|
+
if (!readController(lease)) return;
|
|
4634
|
+
rooms.get(lease.roomId)?.controllers.delete(lease.controllerId);
|
|
4635
|
+
};
|
|
4636
|
+
return {
|
|
4637
|
+
start: async () => void 0,
|
|
4638
|
+
beginDrain: async () => {
|
|
4639
|
+
draining = true;
|
|
4640
|
+
},
|
|
4641
|
+
stop: async () => {
|
|
4642
|
+
draining = true;
|
|
4643
|
+
rooms.clear();
|
|
4644
|
+
},
|
|
4645
|
+
admitRoom: async ({ roomId, maxControllers, replacingLease }) => {
|
|
4646
|
+
if (draining) {
|
|
4647
|
+
return denial(
|
|
4648
|
+
"instance_draining",
|
|
4649
|
+
"This server is draining. Please try again."
|
|
4650
|
+
);
|
|
4651
|
+
}
|
|
4652
|
+
if (rooms.has(roomId)) {
|
|
4653
|
+
return denial(
|
|
4654
|
+
"room_conflict",
|
|
4655
|
+
"That room code is already in use. Please try again.",
|
|
4656
|
+
1
|
|
4657
|
+
);
|
|
4658
|
+
}
|
|
4659
|
+
if (replacingLease && !readRoom(replacingLease)) {
|
|
4660
|
+
return denial(
|
|
4661
|
+
"authority_unavailable",
|
|
4662
|
+
"The previous room reservation could not be replaced safely."
|
|
4663
|
+
);
|
|
4664
|
+
}
|
|
4665
|
+
const lease = { roomId, leaseToken: createLeaseToken() };
|
|
4666
|
+
if (replacingLease) rooms.delete(replacingLease.roomId);
|
|
4667
|
+
rooms.set(roomId, {
|
|
4668
|
+
lease,
|
|
4669
|
+
maxControllers,
|
|
4670
|
+
controllers: /* @__PURE__ */ new Map()
|
|
4671
|
+
});
|
|
4672
|
+
return { ok: true, lease };
|
|
4673
|
+
},
|
|
4674
|
+
releaseRoom: async (lease) => {
|
|
4675
|
+
if (readRoom(lease)) rooms.delete(lease.roomId);
|
|
4676
|
+
},
|
|
4677
|
+
admitController: async ({
|
|
4678
|
+
roomLease,
|
|
4679
|
+
controllerId,
|
|
4680
|
+
existingLease,
|
|
4681
|
+
replacingLease
|
|
4682
|
+
}) => {
|
|
4683
|
+
if (draining && !existingLease) {
|
|
4684
|
+
return denial(
|
|
4685
|
+
"instance_draining",
|
|
4686
|
+
"This server is draining. Please try again."
|
|
4687
|
+
);
|
|
4688
|
+
}
|
|
4689
|
+
const room = readRoom(roomLease);
|
|
4690
|
+
if (!room) {
|
|
4691
|
+
return denial(
|
|
4692
|
+
"authority_unavailable",
|
|
4693
|
+
"Room capacity authority expired. Please retry from the host."
|
|
4694
|
+
);
|
|
4695
|
+
}
|
|
4696
|
+
const current = room.controllers.get(controllerId);
|
|
4697
|
+
if (current && (!existingLease || current.leaseToken !== existingLease.leaseToken)) {
|
|
4698
|
+
return denial(
|
|
4699
|
+
"controller_conflict",
|
|
4700
|
+
"Controller slot is unavailable.",
|
|
4701
|
+
null
|
|
4702
|
+
);
|
|
4703
|
+
}
|
|
4704
|
+
if (existingLease && !readController(existingLease)) {
|
|
4705
|
+
return denial(
|
|
4706
|
+
"controller_conflict",
|
|
4707
|
+
"Controller slot is unavailable.",
|
|
4708
|
+
null
|
|
4709
|
+
);
|
|
4710
|
+
}
|
|
4711
|
+
if (replacingLease && !readController(replacingLease)) {
|
|
4712
|
+
return denial(
|
|
4713
|
+
"authority_unavailable",
|
|
4714
|
+
"The previous controller reservation could not be replaced safely."
|
|
4715
|
+
);
|
|
4716
|
+
}
|
|
4717
|
+
const lease = {
|
|
4718
|
+
roomId: roomLease.roomId,
|
|
4719
|
+
controllerId,
|
|
4720
|
+
leaseToken: createLeaseToken()
|
|
4721
|
+
};
|
|
4722
|
+
if (current && existingLease) {
|
|
4723
|
+
room.controllers.set(controllerId, lease);
|
|
4724
|
+
if (replacingLease && replacingLease.leaseToken !== existingLease.leaseToken) {
|
|
4725
|
+
deleteController(replacingLease);
|
|
4726
|
+
}
|
|
4727
|
+
return { ok: true, lease };
|
|
4728
|
+
}
|
|
4729
|
+
const replacementUsesTargetRoom = replacingLease?.roomId === roomLease.roomId;
|
|
4730
|
+
const effectiveControllerCount = room.controllers.size - (replacementUsesTargetRoom ? 1 : 0);
|
|
4731
|
+
if (effectiveControllerCount >= room.maxControllers) {
|
|
4732
|
+
return denial("room_full", "Room full", null);
|
|
4733
|
+
}
|
|
4734
|
+
if (replacingLease) deleteController(replacingLease);
|
|
4735
|
+
room.controllers.set(controllerId, lease);
|
|
4736
|
+
return { ok: true, lease };
|
|
4737
|
+
},
|
|
4738
|
+
markControllerDisconnected: async () => void 0,
|
|
4739
|
+
releaseController: async (lease) => {
|
|
4740
|
+
deleteController(lease);
|
|
4741
|
+
},
|
|
4742
|
+
getStatus: () => ({
|
|
4743
|
+
contractVersion: 1,
|
|
4744
|
+
authority: "local",
|
|
4745
|
+
budgetRequirement: "not_applicable",
|
|
4746
|
+
instanceId,
|
|
4747
|
+
acceptingNewWork: !draining,
|
|
4748
|
+
draining,
|
|
4749
|
+
terminalAuthorityLost: false,
|
|
4750
|
+
pendingReconciliations: 0,
|
|
4751
|
+
lastHeartbeatAt: null,
|
|
4752
|
+
lastError: null
|
|
4753
|
+
}),
|
|
4754
|
+
onTerminalAuthorityLoss: () => () => void 0
|
|
4755
|
+
};
|
|
4756
|
+
};
|
|
4757
|
+
|
|
5602
4758
|
// src/services/room-manager.ts
|
|
5603
4759
|
var RoomManager = class {
|
|
5604
4760
|
rooms = /* @__PURE__ */ new Map();
|
|
@@ -5716,65 +4872,63 @@ var RoomManager = class {
|
|
|
5716
4872
|
var roomManager = new RoomManager();
|
|
5717
4873
|
|
|
5718
4874
|
// src/index.ts
|
|
5719
|
-
var
|
|
5720
|
-
|
|
5721
|
-
|
|
5722
|
-
|
|
5723
|
-
|
|
5724
|
-
|
|
5725
|
-
|
|
5726
|
-
|
|
5727
|
-
|
|
5728
|
-
|
|
4875
|
+
var projectPublicRealtimeAdmissionStatus = (status) => ({
|
|
4876
|
+
contractVersion: status.contractVersion,
|
|
4877
|
+
authority: status.authority,
|
|
4878
|
+
budgetRequirement: status.budgetRequirement,
|
|
4879
|
+
acceptingNewWork: status.acceptingNewWork,
|
|
4880
|
+
draining: status.draining,
|
|
4881
|
+
terminalAuthorityLost: status.terminalAuthorityLost,
|
|
4882
|
+
pendingReconciliations: status.pendingReconciliations,
|
|
4883
|
+
lastHeartbeatAt: status.lastHeartbeatAt,
|
|
4884
|
+
hasError: status.lastError !== null
|
|
4885
|
+
});
|
|
5729
4886
|
var createAirJamServer = (options = {}) => {
|
|
5730
4887
|
const envConfig = options.envConfig ?? loadServerEnv();
|
|
5731
4888
|
let activePort = null;
|
|
5732
|
-
|
|
5733
|
-
|
|
5734
|
-
|
|
5735
|
-
|
|
5736
|
-
const
|
|
5737
|
-
|
|
5738
|
-
|
|
5739
|
-
devLogCollector,
|
|
5740
|
-
{ level: envConfig.logLevel }
|
|
5741
|
-
);
|
|
5742
|
-
if (envConfig.remoteDatabaseBlocked && !hasWarnedAboutBlockedRemoteDatabase) {
|
|
5743
|
-
hasWarnedAboutBlockedRemoteDatabase = true;
|
|
5744
|
-
logger.warn(
|
|
5745
|
-
{ component: "env", nodeEnv: envConfig.nodeEnv },
|
|
5746
|
-
REMOTE_DATABASE_BLOCKED_MESSAGE
|
|
5747
|
-
);
|
|
5748
|
-
}
|
|
4889
|
+
let admissionStarted = false;
|
|
4890
|
+
let stopPromise = null;
|
|
4891
|
+
let terminalFailure = null;
|
|
4892
|
+
const terminalFailureListeners = /* @__PURE__ */ new Set();
|
|
4893
|
+
const logging = createServerLogging(options, envConfig);
|
|
4894
|
+
const { logger } = logging;
|
|
4895
|
+
const devLogCollector = logging.devLogCollector || null;
|
|
5749
4896
|
const roomManagerInstance = options.roomManager ?? new RoomManager();
|
|
5750
|
-
const devHarnessRegistry = new DevHarnessRegistry();
|
|
5751
4897
|
const rateLimitServiceInstance = options.rateLimitService ?? new RateLimitService();
|
|
5752
|
-
const
|
|
4898
|
+
const realtimeAdmissionService = options.realtimeAdmissionService ?? createLocalRealtimeAdmissionService();
|
|
4899
|
+
const operationalEventPublisher = options.operationalEventPublisher ?? createNoopServerOperationalEventPublisher();
|
|
5753
4900
|
const authServiceInstance = options.authService ?? new AuthService({
|
|
5754
|
-
|
|
5755
|
-
env: {
|
|
5756
|
-
authMode: envConfig.authMode,
|
|
5757
|
-
masterKey: envConfig.masterKey,
|
|
5758
|
-
hostGrantSecret: envConfig.hostGrantSecret,
|
|
5759
|
-
databaseUrl: envConfig.databaseUrl,
|
|
5760
|
-
nodeEnv: envConfig.nodeEnv
|
|
5761
|
-
},
|
|
5762
|
-
db
|
|
4901
|
+
env: { authMode: envConfig.authMode, masterKey: envConfig.masterKey }
|
|
5763
4902
|
});
|
|
5764
|
-
const runtimeUsagePublisher = options.runtimeUsagePublisher ??
|
|
5765
|
-
|
|
5766
|
-
|
|
5767
|
-
)
|
|
5768
|
-
|
|
5769
|
-
|
|
5770
|
-
|
|
4903
|
+
const runtimeUsagePublisher = options.runtimeUsagePublisher ?? createNoopRuntimeUsagePublisher();
|
|
4904
|
+
const startupConfigurationError = authServiceInstance.getStartupConfigurationError?.();
|
|
4905
|
+
if (startupConfigurationError) throw new Error(startupConfigurationError);
|
|
4906
|
+
if (!options.authService) {
|
|
4907
|
+
if (envConfig.authMode === "disabled") {
|
|
4908
|
+
logger[envConfig.nodeEnv === "production" ? "warn" : "info"](
|
|
4909
|
+
{
|
|
4910
|
+
event: AIRJAM_DEV_LOG_EVENTS7.auth.modeDisabled,
|
|
4911
|
+
authMode: "disabled"
|
|
4912
|
+
},
|
|
4913
|
+
"Host authentication is disabled; any host may create a room."
|
|
4914
|
+
);
|
|
4915
|
+
} else if (envConfig.masterKey) {
|
|
4916
|
+
logger.info(
|
|
4917
|
+
{
|
|
4918
|
+
event: AIRJAM_DEV_LOG_EVENTS7.auth.modeMasterKey,
|
|
4919
|
+
authMode: "required"
|
|
4920
|
+
},
|
|
4921
|
+
"Local master-key host authentication is enabled."
|
|
4922
|
+
);
|
|
4923
|
+
}
|
|
5771
4924
|
}
|
|
5772
4925
|
const defaultPort = envConfig.port;
|
|
5773
4926
|
const rateLimitWindowMs = options.rateLimitWindowMs ?? envConfig.rateLimitWindowMs;
|
|
5774
4927
|
const hostRegistrationRateLimitMax = options.hostRegistrationRateLimitMax ?? envConfig.hostRegistrationRateLimitMax;
|
|
5775
4928
|
const controllerJoinRateLimitMax = options.controllerJoinRateLimitMax ?? envConfig.controllerJoinRateLimitMax;
|
|
5776
4929
|
const staticAppRateLimitMax = options.staticAppRateLimitMax ?? envConfig.staticAppRateLimitMax;
|
|
5777
|
-
const
|
|
4930
|
+
const runtimeErrorReportRateLimitMax = options.runtimeErrorReportRateLimitMax ?? envConfig.runtimeErrorReportRateLimitMax;
|
|
4931
|
+
const corsOrigin = resolveCorsOrigin(
|
|
5778
4932
|
options.allowedOrigins,
|
|
5779
4933
|
envConfig.allowedOrigins
|
|
5780
4934
|
);
|
|
@@ -5787,12 +4941,27 @@ var createAirJamServer = (options = {}) => {
|
|
|
5787
4941
|
for (const session of rooms.values()) {
|
|
5788
4942
|
controllerCount += session.controllers.size;
|
|
5789
4943
|
}
|
|
4944
|
+
const realtimeAdmission = projectPublicRealtimeAdmissionStatus(
|
|
4945
|
+
realtimeAdmissionService.getStatus()
|
|
4946
|
+
);
|
|
5790
4947
|
res.json({
|
|
5791
|
-
ok:
|
|
4948
|
+
ok: true,
|
|
5792
4949
|
uptime: Math.floor(process.uptime()),
|
|
5793
4950
|
rooms: rooms.size,
|
|
5794
4951
|
controllers: controllerCount,
|
|
5795
|
-
maintenance: envConfig.maintenanceMode
|
|
4952
|
+
maintenance: envConfig.maintenanceMode,
|
|
4953
|
+
realtimeAdmission
|
|
4954
|
+
});
|
|
4955
|
+
});
|
|
4956
|
+
app.get("/ready", (_, res) => {
|
|
4957
|
+
const realtimeAdmission = projectPublicRealtimeAdmissionStatus(
|
|
4958
|
+
realtimeAdmissionService.getStatus()
|
|
4959
|
+
);
|
|
4960
|
+
const ok = !envConfig.maintenanceMode && realtimeAdmission.acceptingNewWork;
|
|
4961
|
+
res.status(ok ? 200 : 503).json({
|
|
4962
|
+
ok,
|
|
4963
|
+
maintenance: envConfig.maintenanceMode,
|
|
4964
|
+
realtimeAdmission
|
|
5796
4965
|
});
|
|
5797
4966
|
});
|
|
5798
4967
|
app.post("/__airjam/dev/browser-logs", async (req, res) => {
|
|
@@ -5835,69 +5004,6 @@ var createAirJamServer = (options = {}) => {
|
|
|
5835
5004
|
res.status(204).end();
|
|
5836
5005
|
}
|
|
5837
5006
|
);
|
|
5838
|
-
app.post("/__airjam/dev/harness/register", async (req, res) => {
|
|
5839
|
-
const payload = req.body;
|
|
5840
|
-
if (!payload || typeof payload.sessionId !== "string" || !payload.sessionId || typeof payload.gameId !== "string" || !payload.gameId || payload.role !== "host" && payload.role !== "controller" || !Array.isArray(payload.actions)) {
|
|
5841
|
-
res.status(400).json({ ok: false, message: "Invalid dev harness register payload" });
|
|
5842
|
-
return;
|
|
5843
|
-
}
|
|
5844
|
-
const session = devHarnessRegistry.register(payload);
|
|
5845
|
-
res.json({ ok: true, session });
|
|
5846
|
-
});
|
|
5847
|
-
app.get("/__airjam/dev/harness/sessions", async (req, res) => {
|
|
5848
|
-
const roomId = typeof req.query.roomId === "string" ? req.query.roomId : void 0;
|
|
5849
|
-
const gameId = typeof req.query.gameId === "string" ? req.query.gameId : void 0;
|
|
5850
|
-
const role = req.query.role === "host" || req.query.role === "controller" ? req.query.role : void 0;
|
|
5851
|
-
res.json({
|
|
5852
|
-
sessions: devHarnessRegistry.listSessions({ roomId, gameId, role })
|
|
5853
|
-
});
|
|
5854
|
-
});
|
|
5855
|
-
app.get("/__airjam/dev/harness/commands", async (req, res) => {
|
|
5856
|
-
const sessionId = typeof req.query.sessionId === "string" ? req.query.sessionId : null;
|
|
5857
|
-
const waitMsRaw = typeof req.query.waitMs === "string" ? Number(req.query.waitMs) : NaN;
|
|
5858
|
-
const waitMs = Number.isFinite(waitMsRaw) && waitMsRaw > 0 ? waitMsRaw : void 0;
|
|
5859
|
-
if (!sessionId) {
|
|
5860
|
-
res.status(400).json({ ok: false, message: "Missing harness sessionId query param" });
|
|
5861
|
-
return;
|
|
5862
|
-
}
|
|
5863
|
-
const command = await devHarnessRegistry.awaitNextCommand(
|
|
5864
|
-
sessionId,
|
|
5865
|
-
waitMs
|
|
5866
|
-
);
|
|
5867
|
-
if (!command) {
|
|
5868
|
-
res.status(204).end();
|
|
5869
|
-
return;
|
|
5870
|
-
}
|
|
5871
|
-
res.json(command);
|
|
5872
|
-
});
|
|
5873
|
-
app.post("/__airjam/dev/harness/commands/complete", async (req, res) => {
|
|
5874
|
-
const payload = req.body;
|
|
5875
|
-
if (!payload || typeof payload.commandId !== "string" || !payload.commandId || typeof payload.result !== "object" || payload.result === null) {
|
|
5876
|
-
res.status(400).json({ ok: false, message: "Invalid dev harness completion payload" });
|
|
5877
|
-
return;
|
|
5878
|
-
}
|
|
5879
|
-
devHarnessRegistry.completeCommand(payload);
|
|
5880
|
-
res.status(204).end();
|
|
5881
|
-
});
|
|
5882
|
-
app.post("/__airjam/dev/harness/invoke", async (req, res) => {
|
|
5883
|
-
const payload = req.body;
|
|
5884
|
-
if (!payload || typeof payload.actionName !== "string" || !payload.actionName) {
|
|
5885
|
-
res.status(400).json({ ok: false, message: "Invalid dev harness invoke payload" });
|
|
5886
|
-
return;
|
|
5887
|
-
}
|
|
5888
|
-
try {
|
|
5889
|
-
const result = await devHarnessRegistry.invoke(payload);
|
|
5890
|
-
res.json(result);
|
|
5891
|
-
} catch (error) {
|
|
5892
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
5893
|
-
res.status(
|
|
5894
|
-
message === "No matching live harness session found." ? 404 : 500
|
|
5895
|
-
).json({
|
|
5896
|
-
ok: false,
|
|
5897
|
-
message
|
|
5898
|
-
});
|
|
5899
|
-
}
|
|
5900
|
-
});
|
|
5901
5007
|
const httpServer = createServer(app);
|
|
5902
5008
|
const io = new Server(httpServer, {
|
|
5903
5009
|
cors: { origin: corsOrigin },
|
|
@@ -5913,13 +5019,16 @@ var createAirJamServer = (options = {}) => {
|
|
|
5913
5019
|
socket,
|
|
5914
5020
|
logger,
|
|
5915
5021
|
roomManager: roomManagerInstance,
|
|
5022
|
+
realtimeAdmissionService,
|
|
5916
5023
|
rateLimitService: rateLimitServiceInstance,
|
|
5917
5024
|
authService: authServiceInstance,
|
|
5918
5025
|
runtimeUsagePublisher,
|
|
5026
|
+
operationalEventPublisher,
|
|
5919
5027
|
rateLimitWindowMs,
|
|
5920
5028
|
hostRegistrationRateLimitMax,
|
|
5921
5029
|
controllerJoinRateLimitMax,
|
|
5922
5030
|
staticAppRateLimitMax,
|
|
5031
|
+
runtimeErrorReportRateLimitMax,
|
|
5923
5032
|
proxyHeaderTrustMode: options.proxyHeaderTrustMode ?? envConfig.proxyHeaderTrustMode,
|
|
5924
5033
|
maintenanceMode: envConfig.maintenanceMode
|
|
5925
5034
|
});
|
|
@@ -5936,44 +5045,142 @@ var createAirJamServer = (options = {}) => {
|
|
|
5936
5045
|
resolve();
|
|
5937
5046
|
});
|
|
5938
5047
|
});
|
|
5048
|
+
await realtimeAdmissionService.start();
|
|
5049
|
+
admissionStarted = true;
|
|
5939
5050
|
const address = httpServer.address();
|
|
5940
5051
|
activePort = typeof address === "object" && address?.port ? address.port : resolvedPort;
|
|
5941
5052
|
logger.info(
|
|
5942
5053
|
{
|
|
5943
|
-
event:
|
|
5054
|
+
event: AIRJAM_DEV_LOG_EVENTS7.server.started,
|
|
5944
5055
|
port: activePort,
|
|
5945
|
-
corsOrigin
|
|
5056
|
+
corsOrigin,
|
|
5057
|
+
authMode: envConfig.authMode
|
|
5946
5058
|
},
|
|
5947
5059
|
`Server listening on http://localhost:${activePort}`
|
|
5948
5060
|
);
|
|
5949
5061
|
return activePort;
|
|
5950
5062
|
};
|
|
5951
|
-
const
|
|
5952
|
-
|
|
5953
|
-
|
|
5063
|
+
const drain = async (timeoutMs = options.drainTimeoutMs ?? 25e3) => {
|
|
5064
|
+
const startedAt = Date.now();
|
|
5065
|
+
await realtimeAdmissionService.beginDrain();
|
|
5066
|
+
while (roomManagerInstance.getAllRooms().size > 0) {
|
|
5067
|
+
const remainingMs = timeoutMs - (Date.now() - startedAt);
|
|
5068
|
+
if (remainingMs <= 0) break;
|
|
5069
|
+
await new Promise((resolve) => {
|
|
5070
|
+
const timer = setTimeout(resolve, Math.min(100, remainingMs));
|
|
5071
|
+
timer.unref?.();
|
|
5072
|
+
});
|
|
5954
5073
|
}
|
|
5955
|
-
roomManagerInstance.
|
|
5956
|
-
|
|
5957
|
-
|
|
5958
|
-
|
|
5959
|
-
|
|
5960
|
-
|
|
5074
|
+
const remainingRooms = roomManagerInstance.getAllRooms().size;
|
|
5075
|
+
return {
|
|
5076
|
+
completed: remainingRooms === 0,
|
|
5077
|
+
remainingRooms,
|
|
5078
|
+
waitedMs: Date.now() - startedAt
|
|
5079
|
+
};
|
|
5080
|
+
};
|
|
5081
|
+
const stop = async () => {
|
|
5082
|
+
if (stopPromise) return stopPromise;
|
|
5083
|
+
stopPromise = (async () => {
|
|
5084
|
+
const cleanupErrors = [];
|
|
5085
|
+
const attempt = async (cleanup) => {
|
|
5086
|
+
try {
|
|
5087
|
+
await cleanup();
|
|
5088
|
+
} catch (error) {
|
|
5089
|
+
cleanupErrors.push(error);
|
|
5090
|
+
}
|
|
5091
|
+
};
|
|
5092
|
+
if (admissionStarted) {
|
|
5093
|
+
await attempt(() => realtimeAdmissionService.beginDrain());
|
|
5094
|
+
}
|
|
5095
|
+
await attempt(
|
|
5096
|
+
() => roomManagerInstance.clearAllRooms(io, "Server shutting down")
|
|
5097
|
+
);
|
|
5098
|
+
if (httpServer.listening) {
|
|
5099
|
+
await attempt(
|
|
5100
|
+
() => new Promise((resolve) => {
|
|
5101
|
+
io.close(() => resolve());
|
|
5102
|
+
})
|
|
5103
|
+
);
|
|
5104
|
+
}
|
|
5105
|
+
activePort = null;
|
|
5106
|
+
if (admissionStarted) {
|
|
5107
|
+
await attempt(() => realtimeAdmissionService.stop());
|
|
5108
|
+
admissionStarted = false;
|
|
5109
|
+
}
|
|
5110
|
+
await attempt(async () => devLogCollector?.flush());
|
|
5111
|
+
unsubscribeAdmissionFailure();
|
|
5112
|
+
if (cleanupErrors.length > 0) {
|
|
5113
|
+
throw new AggregateError(
|
|
5114
|
+
cleanupErrors,
|
|
5115
|
+
"Realtime server cleanup failed"
|
|
5116
|
+
);
|
|
5117
|
+
}
|
|
5118
|
+
})();
|
|
5119
|
+
return stopPromise;
|
|
5961
5120
|
};
|
|
5962
5121
|
const flushDevLogs = async () => {
|
|
5963
5122
|
await devLogCollector?.flush();
|
|
5964
5123
|
};
|
|
5965
5124
|
const getPort = () => activePort;
|
|
5125
|
+
const onTerminalFailure = (listener) => {
|
|
5126
|
+
terminalFailureListeners.add(listener);
|
|
5127
|
+
if (terminalFailure) {
|
|
5128
|
+
queueMicrotask(() => {
|
|
5129
|
+
if (terminalFailure && terminalFailureListeners.has(listener)) {
|
|
5130
|
+
listener(terminalFailure);
|
|
5131
|
+
}
|
|
5132
|
+
});
|
|
5133
|
+
}
|
|
5134
|
+
return () => terminalFailureListeners.delete(listener);
|
|
5135
|
+
};
|
|
5136
|
+
const unsubscribeAdmissionFailure = realtimeAdmissionService.onTerminalAuthorityLoss((failure) => {
|
|
5137
|
+
if (terminalFailure) return;
|
|
5138
|
+
terminalFailure = failure;
|
|
5139
|
+
publishServerOperationalFailureSafely({
|
|
5140
|
+
publisher: operationalEventPublisher,
|
|
5141
|
+
logger,
|
|
5142
|
+
input: {
|
|
5143
|
+
code: "realtime_admission.instance_lease_lost",
|
|
5144
|
+
failureClass: "dependency",
|
|
5145
|
+
summary: "The realtime server lost its database-backed admission authority.",
|
|
5146
|
+
retryable: false,
|
|
5147
|
+
component: "realtime-admission",
|
|
5148
|
+
subject: { type: "service", id: "realtime_server" },
|
|
5149
|
+
correlation: {
|
|
5150
|
+
contractVersion: 1,
|
|
5151
|
+
correlationId: `realtime-admission:${crypto.randomUUID()}`
|
|
5152
|
+
},
|
|
5153
|
+
details: {
|
|
5154
|
+
authorityFailureCode: failure.code,
|
|
5155
|
+
action: "drain_and_stop_instance"
|
|
5156
|
+
}
|
|
5157
|
+
}
|
|
5158
|
+
});
|
|
5159
|
+
for (const listener of terminalFailureListeners) listener(failure);
|
|
5160
|
+
});
|
|
5966
5161
|
return {
|
|
5967
5162
|
app,
|
|
5968
5163
|
httpServer,
|
|
5969
5164
|
io,
|
|
5970
5165
|
start,
|
|
5166
|
+
drain,
|
|
5971
5167
|
stop,
|
|
5972
5168
|
flushDevLogs,
|
|
5973
|
-
getPort
|
|
5169
|
+
getPort,
|
|
5170
|
+
onTerminalFailure
|
|
5974
5171
|
};
|
|
5975
5172
|
};
|
|
5976
5173
|
export {
|
|
5977
|
-
|
|
5174
|
+
RateLimitService,
|
|
5175
|
+
RoomManager,
|
|
5176
|
+
createAirJamServer,
|
|
5177
|
+
createLocalRealtimeAdmissionService,
|
|
5178
|
+
createRuntimeUsageEvent,
|
|
5179
|
+
createServerLogger,
|
|
5180
|
+
createServerLogging,
|
|
5181
|
+
installServerProcessSignalHandlers,
|
|
5182
|
+
loadServerEnv,
|
|
5183
|
+
loadWorkspaceEnv,
|
|
5184
|
+
publishServerOperationalFailureSafely
|
|
5978
5185
|
};
|
|
5979
5186
|
//# sourceMappingURL=index.js.map
|