@rine-kit/pubg-sync 0.0.0-stage → 0.1.2
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/LICENSE +21 -0
- package/README.md +29 -2
- package/dist/hourly-prefetch.d.ts +25 -0
- package/dist/hourly-prefetch.js +76 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +8 -0
- package/dist/player-resolver.d.ts +35 -0
- package/dist/player-resolver.js +127 -0
- package/dist/public-egress.d.ts +5 -0
- package/dist/public-egress.js +34 -0
- package/dist/request-limiter.d.ts +16 -0
- package/dist/request-limiter.js +85 -0
- package/dist/sync-worker.d.ts +59 -0
- package/dist/sync-worker.js +292 -0
- package/dist/worker-alerts.d.ts +46 -0
- package/dist/worker-alerts.js +43 -0
- package/dist/worker-health-server.d.ts +7 -0
- package/dist/worker-health-server.js +79 -0
- package/dist/worker-main.d.ts +3 -0
- package/dist/worker-main.js +161 -0
- package/dist/worker-metrics.d.ts +25 -0
- package/dist/worker-metrics.js +94 -0
- package/package.json +41 -3
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
import { createTeamContext, PubgApiClient, PubgApiTelemetryDownloader, PubgDomainService, TelemetryWorker, } from '@rine-kit/pubg-domain/core';
|
|
2
|
+
import { validatePublicPubgShard } from './player-resolver.js';
|
|
3
|
+
import { MAX_TEAM_ROSTER_SIZE, PostgresPubgRepository, PublicSyncQueue, } from '@rine-kit/pubg-postgres';
|
|
4
|
+
const API_ORIGIN = 'https://api.pubg.com';
|
|
5
|
+
const TELEMETRY_HOSTS = new Set(['telemetry-cdn.pubg.com', 'telemetry-cdn.playbattlegrounds.com']);
|
|
6
|
+
const MAX_API_RESPONSE_BYTES = 5 * 1024 * 1024;
|
|
7
|
+
const MAX_TELEMETRY_RESPONSE_BYTES = 96 * 1024 * 1024;
|
|
8
|
+
const DEFAULT_MAX_MATCHES = 500;
|
|
9
|
+
const DEFAULT_MAX_TELEMETRY_FETCHES = 20;
|
|
10
|
+
const DEFAULT_TELEMETRY_CONCURRENCY = 2;
|
|
11
|
+
const DEFAULT_TEAM_CONCURRENCY = 2;
|
|
12
|
+
const DEFAULT_SYNC_INTERVAL_MS = 5 * 60_000;
|
|
13
|
+
const ACCOUNT_ID = /^account\.[A-Za-z0-9_-]{1,128}$/u;
|
|
14
|
+
const MATCH_ID = /^[A-Za-z0-9_.-]{1,128}$/u;
|
|
15
|
+
function boundedInteger(value, fallback, minimum, maximum) {
|
|
16
|
+
if (!Number.isSafeInteger(value) || value < minimum || value > maximum)
|
|
17
|
+
throw new Error('public_sync_config_invalid');
|
|
18
|
+
return value || fallback;
|
|
19
|
+
}
|
|
20
|
+
function boundedResponse(response, maxBytes) {
|
|
21
|
+
const contentLength = Number(response.headers.get('content-length'));
|
|
22
|
+
if (Number.isFinite(contentLength) && contentLength > maxBytes) {
|
|
23
|
+
void response.body?.cancel().catch(() => undefined);
|
|
24
|
+
throw new Error('public_sync_response_too_large');
|
|
25
|
+
}
|
|
26
|
+
if (!response.body || response.status === 204 || response.status === 304)
|
|
27
|
+
return response;
|
|
28
|
+
let size = 0;
|
|
29
|
+
const body = response.body.pipeThrough(new TransformStream({
|
|
30
|
+
transform(chunk, controller) {
|
|
31
|
+
size += chunk.byteLength;
|
|
32
|
+
if (size > maxBytes) {
|
|
33
|
+
controller.error(new Error('public_sync_response_too_large'));
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
controller.enqueue(chunk);
|
|
37
|
+
},
|
|
38
|
+
}));
|
|
39
|
+
const headers = new Headers(response.headers);
|
|
40
|
+
headers.delete('content-length');
|
|
41
|
+
headers.delete('content-encoding');
|
|
42
|
+
headers.delete('transfer-encoding');
|
|
43
|
+
return new Response(body, { status: response.status, statusText: response.statusText, headers });
|
|
44
|
+
}
|
|
45
|
+
function endpoint(url) {
|
|
46
|
+
if (url.protocol !== 'https:' || url.username || url.password || url.port || url.hash)
|
|
47
|
+
throw new Error('public_sync_endpoint_invalid');
|
|
48
|
+
if (url.origin === API_ORIGIN) {
|
|
49
|
+
const isPlayers = /^\/shards\/(steam|kakao|psn|xbox)\/players$/u.test(url.pathname);
|
|
50
|
+
const isMatch = /^\/shards\/(steam|kakao|psn|xbox)\/matches\/[A-Za-z0-9_.-]{1,128}$/u.test(url.pathname);
|
|
51
|
+
if (isPlayers) {
|
|
52
|
+
const ids = url.searchParams.getAll('filter[playerIds]');
|
|
53
|
+
if (url.searchParams.size !== 1 || ids.length !== 1 || ids[0].split(',').length > MAX_TEAM_ROSTER_SIZE
|
|
54
|
+
|| ids[0].split(',').some((id) => !ACCOUNT_ID.test(id)))
|
|
55
|
+
throw new Error('public_sync_endpoint_invalid');
|
|
56
|
+
}
|
|
57
|
+
else if (!isMatch || url.search !== '') {
|
|
58
|
+
throw new Error('public_sync_endpoint_invalid');
|
|
59
|
+
}
|
|
60
|
+
// PUBG's rate-limited player discovery endpoint uses shared admission.
|
|
61
|
+
// Match detail requests are not counted by PUBG and follow Kurisu's
|
|
62
|
+
// behavior without an extra public-only gate.
|
|
63
|
+
return { kind: 'api', rateLimited: isPlayers, maxBytes: MAX_API_RESPONSE_BYTES };
|
|
64
|
+
}
|
|
65
|
+
if (TELEMETRY_HOSTS.has(url.hostname) && url.search === ''
|
|
66
|
+
&& /^\/(?:[A-Za-z0-9._-]+\/)*[A-Za-z0-9._-]*-telemetry\.json$/u.test(url.pathname)) {
|
|
67
|
+
return { kind: 'telemetry', rateLimited: false, maxBytes: MAX_TELEMETRY_RESPONSE_BYTES };
|
|
68
|
+
}
|
|
69
|
+
throw new Error('public_sync_endpoint_invalid');
|
|
70
|
+
}
|
|
71
|
+
/** Restricts the worker to official public PUBG API and telemetry endpoints.
|
|
72
|
+
* Rate-limited player discovery uses shared admission; match details follow the
|
|
73
|
+
* provider's unmetered endpoint policy. Public telemetry CDN objects never
|
|
74
|
+
* receive the API key. Redirects are rejected. */
|
|
75
|
+
export function createPublicSyncFetch(admission, fetchImpl = fetch) {
|
|
76
|
+
return async (input, init) => {
|
|
77
|
+
const url = new URL(typeof input === 'string' || input instanceof URL ? String(input) : input.url);
|
|
78
|
+
const target = endpoint(url);
|
|
79
|
+
if ((init?.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase() !== 'GET')
|
|
80
|
+
throw new Error('public_sync_method_invalid');
|
|
81
|
+
const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));
|
|
82
|
+
if (target.kind === 'telemetry' && headers.has('authorization'))
|
|
83
|
+
throw new Error('public_sync_telemetry_auth_forbidden');
|
|
84
|
+
if (target.kind === 'api' && !/^Bearer\s+\S+$/iu.test(headers.get('authorization') ?? ''))
|
|
85
|
+
throw new Error('public_sync_api_auth_missing');
|
|
86
|
+
if (target.rateLimited)
|
|
87
|
+
await admission.acquire(init?.signal ?? (input instanceof Request ? input.signal : undefined));
|
|
88
|
+
const response = await fetchImpl(url, { ...init, headers, redirect: 'error' });
|
|
89
|
+
if (target.rateLimited)
|
|
90
|
+
await admission.observe(response.headers, response.status);
|
|
91
|
+
return boundedResponse(response, target.maxBytes);
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
class InvalidTeamError extends Error {
|
|
95
|
+
constructor() { super('public_sync_team_invalid'); }
|
|
96
|
+
}
|
|
97
|
+
async function registeredTeam(pool, tenantId, teamId) {
|
|
98
|
+
const result = await pool.query(`SELECT team.tenant_id,team.team_id,team.label,team.pubg_shard,member.pubg_account_id,
|
|
99
|
+
COALESCE(account.display_name,member.pubg_account_id) AS official_name,alias.display_alias
|
|
100
|
+
FROM pubg_teams team
|
|
101
|
+
LEFT JOIN pubg_team_members member ON member.tenant_id=team.tenant_id AND member.team_id=team.team_id
|
|
102
|
+
LEFT JOIN pubg_account_names account ON account.shard=team.pubg_shard AND account.account_id=member.pubg_account_id
|
|
103
|
+
LEFT JOIN pubg_team_aliases alias ON alias.tenant_id=member.tenant_id AND alias.team_id=member.team_id
|
|
104
|
+
AND alias.pubg_account_id=member.pubg_account_id
|
|
105
|
+
WHERE team.tenant_id=$1 AND team.team_id=$2
|
|
106
|
+
ORDER BY member.pubg_account_id,alias.alias_key`, [tenantId, teamId]);
|
|
107
|
+
if (!result.rows.length)
|
|
108
|
+
throw new InvalidTeamError();
|
|
109
|
+
const first = result.rows[0];
|
|
110
|
+
const players = new Map();
|
|
111
|
+
for (const row of result.rows) {
|
|
112
|
+
if (!row.pubg_account_id)
|
|
113
|
+
continue;
|
|
114
|
+
let player = players.get(row.pubg_account_id);
|
|
115
|
+
if (!player) {
|
|
116
|
+
player = { id: row.pubg_account_id, name: row.official_name?.trim() || row.pubg_account_id, aliases: [] };
|
|
117
|
+
players.set(row.pubg_account_id, player);
|
|
118
|
+
}
|
|
119
|
+
if (row.display_alias?.trim() && !player.aliases.includes(row.display_alias.trim()))
|
|
120
|
+
player.aliases.push(row.display_alias.trim());
|
|
121
|
+
}
|
|
122
|
+
try {
|
|
123
|
+
validatePublicPubgShard(first.pubg_shard);
|
|
124
|
+
const team = {
|
|
125
|
+
id: first.team_id,
|
|
126
|
+
label: first.label,
|
|
127
|
+
platform: first.pubg_shard,
|
|
128
|
+
players: [...players.values()],
|
|
129
|
+
};
|
|
130
|
+
if (team.players.length < 1 || team.players.length > MAX_TEAM_ROSTER_SIZE
|
|
131
|
+
|| team.players.some((player) => !ACCOUNT_ID.test(player.id) || player.name.length > 100
|
|
132
|
+
|| player.aliases.some((alias) => alias.length > 100 || /[\u0000-\u001f]/u.test(alias)))) {
|
|
133
|
+
throw new InvalidTeamError();
|
|
134
|
+
}
|
|
135
|
+
return createTeamContext(first.tenant_id, team);
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
if (error instanceof InvalidTeamError)
|
|
139
|
+
throw error;
|
|
140
|
+
throw new InvalidTeamError();
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
function numberFrom(value) {
|
|
144
|
+
const result = Number(value);
|
|
145
|
+
return Number.isFinite(result) && result >= 0 ? Math.trunc(result) : 0;
|
|
146
|
+
}
|
|
147
|
+
function telemetryRun(value) {
|
|
148
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
149
|
+
return { discovered: 0, fetched: 0, unavailable: 0 };
|
|
150
|
+
const data = value;
|
|
151
|
+
const run = data.run && typeof data.run === 'object' && !Array.isArray(data.run)
|
|
152
|
+
? data.run
|
|
153
|
+
: {};
|
|
154
|
+
return {
|
|
155
|
+
discovered: numberFrom(run.discoveredMatchCount),
|
|
156
|
+
fetched: numberFrom(run.fetchedCount),
|
|
157
|
+
unavailable: numberFrom(run.unavailableCount),
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
/** Independent public-SaaS ingestion process. It loads only registered SaaS
|
|
161
|
+
* rosters, syncs them through the shared PUBG Domain and writes to PG through
|
|
162
|
+
* the tenant/team scoped repository. */
|
|
163
|
+
export class PublicSyncWorker {
|
|
164
|
+
pool;
|
|
165
|
+
client;
|
|
166
|
+
telemetryDownloader;
|
|
167
|
+
now;
|
|
168
|
+
maxMatches;
|
|
169
|
+
maxTelemetryFetches;
|
|
170
|
+
telemetryConcurrency;
|
|
171
|
+
teamConcurrency;
|
|
172
|
+
syncIntervalMs;
|
|
173
|
+
nextSyncDelayMs;
|
|
174
|
+
leaseMs;
|
|
175
|
+
queue;
|
|
176
|
+
constructor(pool, options) {
|
|
177
|
+
this.pool = pool;
|
|
178
|
+
if (!options.apiKey.trim())
|
|
179
|
+
throw new Error('public_pubg_api_key_missing');
|
|
180
|
+
this.maxMatches = boundedInteger(options.maxMatches ?? DEFAULT_MAX_MATCHES, DEFAULT_MAX_MATCHES, 1, 1000);
|
|
181
|
+
this.maxTelemetryFetches = boundedInteger(options.maxTelemetryFetches ?? DEFAULT_MAX_TELEMETRY_FETCHES, DEFAULT_MAX_TELEMETRY_FETCHES, 1, 50);
|
|
182
|
+
this.telemetryConcurrency = boundedInteger(options.telemetryConcurrency ?? DEFAULT_TELEMETRY_CONCURRENCY, DEFAULT_TELEMETRY_CONCURRENCY, 1, 4);
|
|
183
|
+
this.teamConcurrency = boundedInteger(options.teamConcurrency ?? DEFAULT_TEAM_CONCURRENCY, DEFAULT_TEAM_CONCURRENCY, 1, 16);
|
|
184
|
+
this.syncIntervalMs = boundedInteger(options.syncIntervalMs ?? DEFAULT_SYNC_INTERVAL_MS, DEFAULT_SYNC_INTERVAL_MS, 1_000, 24 * 60 * 60_000);
|
|
185
|
+
this.nextSyncDelayMs = options.nextSyncDelayMs;
|
|
186
|
+
this.leaseMs = boundedInteger(options.leaseMs ?? 120_000, 120_000, 1_000, 15 * 60_000);
|
|
187
|
+
this.queue = new PublicSyncQueue(pool, { leaseMs: this.leaseMs });
|
|
188
|
+
this.now = options.now ?? (() => new Date());
|
|
189
|
+
const fetchImpl = createPublicSyncFetch(options.admission, options.fetchImpl);
|
|
190
|
+
// Use the shared Domain client's retry, concurrency, and timeout defaults,
|
|
191
|
+
// matching the private Kurisu plugin configuration. Upstream admission is
|
|
192
|
+
// still enforced independently by the shared PostgreSQL limiter.
|
|
193
|
+
this.client = new PubgApiClient({ apiKey: options.apiKey, baseUrl: API_ORIGIN, fetchImpl });
|
|
194
|
+
this.telemetryDownloader = new PubgApiTelemetryDownloader({
|
|
195
|
+
apiKey: options.apiKey,
|
|
196
|
+
baseUrl: API_ORIGIN,
|
|
197
|
+
timeoutMs: 60_000,
|
|
198
|
+
fetchImpl,
|
|
199
|
+
...(options.rawTelemetryArchive ? { archive: options.rawTelemetryArchive } : {}),
|
|
200
|
+
});
|
|
201
|
+
this.onTeamError = options.onTeamError ?? (() => undefined);
|
|
202
|
+
}
|
|
203
|
+
onTeamError;
|
|
204
|
+
async runOnce(signal) {
|
|
205
|
+
const teamsDiscovered = await this.queue.ensureTeams();
|
|
206
|
+
const summary = {
|
|
207
|
+
teamsDiscovered,
|
|
208
|
+
teamsAttempted: 0,
|
|
209
|
+
teamsCompleted: 0,
|
|
210
|
+
teamsFailed: 0,
|
|
211
|
+
matchesDiscovered: 0,
|
|
212
|
+
telemetryFetched: 0,
|
|
213
|
+
telemetryUnavailable: 0,
|
|
214
|
+
};
|
|
215
|
+
// A stop request prevents new claims. Jobs already leased finish and are
|
|
216
|
+
// checkpointed before the caller closes the PG pool, which gives shutdown
|
|
217
|
+
// a bounded, recoverable boundary without dropping in-flight work.
|
|
218
|
+
while (!signal?.aborted) {
|
|
219
|
+
const jobs = await this.queue.claimDue(this.teamConcurrency);
|
|
220
|
+
if (jobs.length === 0)
|
|
221
|
+
break;
|
|
222
|
+
summary.teamsAttempted += jobs.length;
|
|
223
|
+
const results = await Promise.all(jobs.map((job) => this.processJob(job)));
|
|
224
|
+
for (const result of results) {
|
|
225
|
+
if (!result.ok) {
|
|
226
|
+
summary.teamsFailed += 1;
|
|
227
|
+
this.onTeamError(result.invalid ? 'public_sync_team_invalid' : 'public_sync_team_failed');
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
230
|
+
summary.teamsCompleted += 1;
|
|
231
|
+
summary.matchesDiscovered += result.telemetry.discovered;
|
|
232
|
+
summary.telemetryFetched += result.telemetry.fetched;
|
|
233
|
+
summary.telemetryUnavailable += result.telemetry.unavailable;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
return summary;
|
|
237
|
+
}
|
|
238
|
+
getQueueSnapshot() {
|
|
239
|
+
return this.queue.getSnapshot();
|
|
240
|
+
}
|
|
241
|
+
async processJob(job) {
|
|
242
|
+
const stopIfLeaseLost = new AbortController();
|
|
243
|
+
let renewalInFlight = false;
|
|
244
|
+
const heartbeat = setInterval(() => {
|
|
245
|
+
if (renewalInFlight)
|
|
246
|
+
return;
|
|
247
|
+
renewalInFlight = true;
|
|
248
|
+
void this.queue.renew(job).then((renewed) => {
|
|
249
|
+
if (!renewed)
|
|
250
|
+
stopIfLeaseLost.abort();
|
|
251
|
+
}).catch(() => stopIfLeaseLost.abort()).finally(() => { renewalInFlight = false; });
|
|
252
|
+
}, Math.max(250, Math.floor(this.leaseMs / 3)));
|
|
253
|
+
heartbeat.unref?.();
|
|
254
|
+
try {
|
|
255
|
+
const teamContext = await registeredTeam(this.pool, job.tenantId, job.teamId);
|
|
256
|
+
const repository = new PostgresPubgRepository(this.pool, teamContext);
|
|
257
|
+
const telemetryWorker = new TelemetryWorker({
|
|
258
|
+
team: teamContext.team,
|
|
259
|
+
store: repository,
|
|
260
|
+
downloader: this.telemetryDownloader,
|
|
261
|
+
});
|
|
262
|
+
const service = new PubgDomainService({
|
|
263
|
+
teamContext,
|
|
264
|
+
repository,
|
|
265
|
+
apiClient: this.client,
|
|
266
|
+
telemetryWorker,
|
|
267
|
+
maxMatches: this.maxMatches,
|
|
268
|
+
now: this.now,
|
|
269
|
+
});
|
|
270
|
+
const result = await service.prefetchTelemetry({
|
|
271
|
+
maxMatches: this.maxMatches,
|
|
272
|
+
maxFetches: this.maxTelemetryFetches,
|
|
273
|
+
concurrency: this.telemetryConcurrency,
|
|
274
|
+
trigger: 'hourly',
|
|
275
|
+
signal: stopIfLeaseLost.signal,
|
|
276
|
+
});
|
|
277
|
+
const delayMs = this.nextSyncDelayMs ? this.nextSyncDelayMs(this.now()) : this.syncIntervalMs;
|
|
278
|
+
if (stopIfLeaseLost.signal.aborted || !await this.queue.complete(job, delayMs)) {
|
|
279
|
+
return { ok: false, invalid: false };
|
|
280
|
+
}
|
|
281
|
+
return { ok: true, telemetry: telemetryRun(result.data) };
|
|
282
|
+
}
|
|
283
|
+
catch (error) {
|
|
284
|
+
const invalid = error instanceof InvalidTeamError;
|
|
285
|
+
await this.queue.fail(job, invalid ? 'public_sync_team_invalid' : 'public_sync_team_failed').catch(() => false);
|
|
286
|
+
return { ok: false, invalid };
|
|
287
|
+
}
|
|
288
|
+
finally {
|
|
289
|
+
clearInterval(heartbeat);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { PublicSyncQueueSnapshot } from '@rine-kit/pubg-postgres';
|
|
2
|
+
import type { PublicSyncCycleResult } from './sync-worker.js';
|
|
3
|
+
export declare const PUBLIC_SYNC_ALERT_THRESHOLDS: Readonly<{
|
|
4
|
+
oldestDueAgeSeconds: number;
|
|
5
|
+
workerRssBytes: number;
|
|
6
|
+
}>;
|
|
7
|
+
export type PublicSyncAlertCode = 'public_sync_queue_snapshot_unavailable' | 'public_sync_queue_lag_high' | 'public_sync_queue_expired_lease' | 'public_sync_team_failures' | 'public_sync_worker_rss_high';
|
|
8
|
+
export interface PublicSyncAlert {
|
|
9
|
+
code: PublicSyncAlertCode;
|
|
10
|
+
severity: 'warning' | 'critical';
|
|
11
|
+
}
|
|
12
|
+
/** Stable, identifier-free alert signals for host log collection. This only
|
|
13
|
+
* derives warnings; service health and worker admission remain independent. */
|
|
14
|
+
export declare function evaluatePublicSyncAlerts(input: {
|
|
15
|
+
cycle: Pick<PublicSyncCycleResult, 'teamsFailed'>;
|
|
16
|
+
queue: PublicSyncQueueSnapshot | null;
|
|
17
|
+
rssBytes: number;
|
|
18
|
+
}): PublicSyncAlert[];
|
|
19
|
+
export declare function createPublicSyncCycleLog(input: {
|
|
20
|
+
observedAt: string;
|
|
21
|
+
cycle: PublicSyncCycleResult;
|
|
22
|
+
durationMs: number;
|
|
23
|
+
queue: PublicSyncQueueSnapshot | null;
|
|
24
|
+
rssBytes: number;
|
|
25
|
+
heapUsedBytes: number;
|
|
26
|
+
}): {
|
|
27
|
+
event: string;
|
|
28
|
+
observedAt: string;
|
|
29
|
+
cycle: {
|
|
30
|
+
durationMs: number;
|
|
31
|
+
teamsDiscovered: number;
|
|
32
|
+
teamsAttempted: number;
|
|
33
|
+
teamsCompleted: number;
|
|
34
|
+
teamsFailed: number;
|
|
35
|
+
matchesDiscovered: number;
|
|
36
|
+
telemetryFetched: number;
|
|
37
|
+
telemetryUnavailable: number;
|
|
38
|
+
};
|
|
39
|
+
queue: PublicSyncQueueSnapshot | null;
|
|
40
|
+
queueSnapshotError: boolean;
|
|
41
|
+
process: {
|
|
42
|
+
rssBytes: number;
|
|
43
|
+
heapUsedBytes: number;
|
|
44
|
+
};
|
|
45
|
+
alerts: PublicSyncAlert[];
|
|
46
|
+
};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
export const PUBLIC_SYNC_ALERT_THRESHOLDS = Object.freeze({
|
|
2
|
+
oldestDueAgeSeconds: 15 * 60,
|
|
3
|
+
workerRssBytes: Math.floor(2 * 1024 * 1024 * 1024 * 0.8),
|
|
4
|
+
});
|
|
5
|
+
/** Stable, identifier-free alert signals for host log collection. This only
|
|
6
|
+
* derives warnings; service health and worker admission remain independent. */
|
|
7
|
+
export function evaluatePublicSyncAlerts(input) {
|
|
8
|
+
const alerts = [];
|
|
9
|
+
if (input.queue === null) {
|
|
10
|
+
alerts.push({ code: 'public_sync_queue_snapshot_unavailable', severity: 'critical' });
|
|
11
|
+
}
|
|
12
|
+
else {
|
|
13
|
+
if (input.queue.oldestDueAgeSeconds !== null
|
|
14
|
+
&& input.queue.oldestDueAgeSeconds >= PUBLIC_SYNC_ALERT_THRESHOLDS.oldestDueAgeSeconds) {
|
|
15
|
+
alerts.push({ code: 'public_sync_queue_lag_high', severity: 'warning' });
|
|
16
|
+
}
|
|
17
|
+
if (input.queue.expiredLeases > 0) {
|
|
18
|
+
alerts.push({ code: 'public_sync_queue_expired_lease', severity: 'warning' });
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
if (input.cycle.teamsFailed > 0) {
|
|
22
|
+
alerts.push({ code: 'public_sync_team_failures', severity: 'warning' });
|
|
23
|
+
}
|
|
24
|
+
if (input.rssBytes >= PUBLIC_SYNC_ALERT_THRESHOLDS.workerRssBytes) {
|
|
25
|
+
alerts.push({ code: 'public_sync_worker_rss_high', severity: 'warning' });
|
|
26
|
+
}
|
|
27
|
+
return alerts;
|
|
28
|
+
}
|
|
29
|
+
export function createPublicSyncCycleLog(input) {
|
|
30
|
+
return {
|
|
31
|
+
event: 'pubg_saas_sync_cycle',
|
|
32
|
+
observedAt: input.observedAt,
|
|
33
|
+
cycle: { ...input.cycle, durationMs: input.durationMs },
|
|
34
|
+
queue: input.queue,
|
|
35
|
+
queueSnapshotError: input.queue === null,
|
|
36
|
+
process: { rssBytes: input.rssBytes, heapUsedBytes: input.heapUsedBytes },
|
|
37
|
+
alerts: evaluatePublicSyncAlerts({
|
|
38
|
+
cycle: input.cycle,
|
|
39
|
+
queue: input.queue,
|
|
40
|
+
rssBytes: input.rssBytes,
|
|
41
|
+
}),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type Server } from 'node:http';
|
|
2
|
+
export declare function startWorkerHealthServer(port?: number): Promise<Server>;
|
|
3
|
+
/** Prometheus-format aggregate metrics for host-local scraping. Compose must
|
|
4
|
+
* publish this listener only on 127.0.0.1; no tenant or actor labels are used. */
|
|
5
|
+
export declare function startWorkerMetricsServer(render: () => string, port?: number): Promise<Server>;
|
|
6
|
+
export declare function stopWorkerHealthServer(server: Server): Promise<void>;
|
|
7
|
+
export declare function stopWorkerMetricsServer(server: Server): Promise<void>;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { createServer } from 'node:http';
|
|
2
|
+
export function startWorkerHealthServer(port = 8081) {
|
|
3
|
+
const server = createServer((request, response) => {
|
|
4
|
+
if (request.method !== 'GET' || request.url !== '/healthz') {
|
|
5
|
+
response.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
|
|
6
|
+
response.end('not_found\n');
|
|
7
|
+
return;
|
|
8
|
+
}
|
|
9
|
+
response.writeHead(200, {
|
|
10
|
+
'cache-control': 'no-store',
|
|
11
|
+
'content-type': 'text/plain; charset=utf-8',
|
|
12
|
+
});
|
|
13
|
+
response.end('ok\n');
|
|
14
|
+
});
|
|
15
|
+
return new Promise((resolve, reject) => {
|
|
16
|
+
const onError = (error) => {
|
|
17
|
+
server.off('listening', onListening);
|
|
18
|
+
reject(error);
|
|
19
|
+
};
|
|
20
|
+
const onListening = () => {
|
|
21
|
+
server.off('error', onError);
|
|
22
|
+
resolve(server);
|
|
23
|
+
};
|
|
24
|
+
server.once('error', onError);
|
|
25
|
+
server.once('listening', onListening);
|
|
26
|
+
server.listen(port, '127.0.0.1');
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
/** Prometheus-format aggregate metrics for host-local scraping. Compose must
|
|
30
|
+
* publish this listener only on 127.0.0.1; no tenant or actor labels are used. */
|
|
31
|
+
export function startWorkerMetricsServer(render, port = 9464) {
|
|
32
|
+
const server = createServer((request, response) => {
|
|
33
|
+
if (request.method !== 'GET' || request.url !== '/metrics') {
|
|
34
|
+
response.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
|
|
35
|
+
response.end('not_found\n');
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
let body;
|
|
39
|
+
try {
|
|
40
|
+
body = render();
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
response.writeHead(503, { 'cache-control': 'no-store', 'content-type': 'text/plain; charset=utf-8' });
|
|
44
|
+
response.end('metrics_unavailable\n');
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
response.writeHead(200, {
|
|
48
|
+
'cache-control': 'no-store',
|
|
49
|
+
'content-type': 'text/plain; version=0.0.4; charset=utf-8',
|
|
50
|
+
});
|
|
51
|
+
response.end(body);
|
|
52
|
+
});
|
|
53
|
+
return new Promise((resolve, reject) => {
|
|
54
|
+
const onError = (error) => {
|
|
55
|
+
server.off('listening', onListening);
|
|
56
|
+
reject(error);
|
|
57
|
+
};
|
|
58
|
+
const onListening = () => {
|
|
59
|
+
server.off('error', onError);
|
|
60
|
+
resolve(server);
|
|
61
|
+
};
|
|
62
|
+
server.once('error', onError);
|
|
63
|
+
server.once('listening', onListening);
|
|
64
|
+
server.listen(port, '0.0.0.0');
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
function stopServer(server) {
|
|
68
|
+
if (!server.listening)
|
|
69
|
+
return Promise.resolve();
|
|
70
|
+
return new Promise((resolve, reject) => {
|
|
71
|
+
server.close(error => error ? reject(error) : resolve());
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
export function stopWorkerHealthServer(server) {
|
|
75
|
+
return stopServer(server);
|
|
76
|
+
}
|
|
77
|
+
export function stopWorkerMetricsServer(server) {
|
|
78
|
+
return stopServer(server);
|
|
79
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { pathToFileURL } from 'node:url';
|
|
2
|
+
import { Pool } from 'pg';
|
|
3
|
+
import { assertArchiveOutsideRepository } from '@rine-kit/pubg-intelligence/backfill';
|
|
4
|
+
import { RawTelemetryArchive } from '@rine-kit/pubg-intelligence/archive';
|
|
5
|
+
import { clampSyncDelayMs, HOURLY_PREFETCH_MINUTE, HOURLY_PREFETCH_TIMEZONE, nextHourlyPrefetchDelayMs, syncCyclePauseMs, } from './hourly-prefetch.js';
|
|
6
|
+
import { PublicSyncWorker } from './sync-worker.js';
|
|
7
|
+
import { PostgresPublicPubgAdmission } from './request-limiter.js';
|
|
8
|
+
import { configurePublicEgress } from './public-egress.js';
|
|
9
|
+
import { startWorkerHealthServer, startWorkerMetricsServer, stopWorkerHealthServer, stopWorkerMetricsServer, } from './worker-health-server.js';
|
|
10
|
+
import { createPublicSyncCycleLog } from './worker-alerts.js';
|
|
11
|
+
import { PublicSyncWorkerMetrics } from './worker-metrics.js';
|
|
12
|
+
const DEFAULT_INTERVAL_MS = 5 * 60_000;
|
|
13
|
+
function hourMinute(value, fallback) {
|
|
14
|
+
if (value === undefined || value.trim() === '')
|
|
15
|
+
return fallback;
|
|
16
|
+
const result = Number(value);
|
|
17
|
+
if (!Number.isSafeInteger(result) || result < 0 || result > 59)
|
|
18
|
+
throw new Error('pubg_saas_worker_config_invalid');
|
|
19
|
+
return result;
|
|
20
|
+
}
|
|
21
|
+
function positiveInteger(value, fallback, maximum) {
|
|
22
|
+
if (value === undefined || value.trim() === '')
|
|
23
|
+
return fallback;
|
|
24
|
+
const result = Number(value);
|
|
25
|
+
if (!Number.isSafeInteger(result) || result < 1 || result > maximum)
|
|
26
|
+
throw new Error('pubg_saas_worker_config_invalid');
|
|
27
|
+
return result;
|
|
28
|
+
}
|
|
29
|
+
function wait(ms, signal) {
|
|
30
|
+
if (signal.aborted)
|
|
31
|
+
return Promise.resolve();
|
|
32
|
+
return new Promise(resolve => {
|
|
33
|
+
const finish = () => { signal.removeEventListener('abort', finish); clearTimeout(timer); resolve(); };
|
|
34
|
+
const timer = setTimeout(finish, ms);
|
|
35
|
+
signal.addEventListener('abort', finish, { once: true });
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
/** Without --apply this entrypoint is a side-effect-free preview. --once keeps
|
|
39
|
+
* an explicitly applied worker run bounded for local acceptance and recovery. */
|
|
40
|
+
export async function publicSyncWorkerMain(args, env = process.env) {
|
|
41
|
+
if (args.length === 0) {
|
|
42
|
+
process.stdout.write('PUBG_SAAS_SYNC_WORKER=dry-run; start requires --apply, DATABASE_URL, and PUBLIC_PUBG_API_KEY.\n');
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
const once = args.includes('--once');
|
|
46
|
+
if (!args.includes('--apply') || args.length !== (once ? 2 : 1) || args.some(value => value !== '--apply' && value !== '--once')) {
|
|
47
|
+
throw new Error('pubg_saas_worker_arguments_invalid');
|
|
48
|
+
}
|
|
49
|
+
const databaseUrl = env.DATABASE_URL;
|
|
50
|
+
const apiKey = env.PUBLIC_PUBG_API_KEY;
|
|
51
|
+
if (!databaseUrl || !apiKey?.trim())
|
|
52
|
+
throw new Error('pubg_saas_worker_config_missing');
|
|
53
|
+
configurePublicEgress(env);
|
|
54
|
+
let parsed;
|
|
55
|
+
try {
|
|
56
|
+
parsed = new URL(databaseUrl);
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
throw new Error('pubg_saas_database_url_invalid');
|
|
60
|
+
}
|
|
61
|
+
if (!['postgres:', 'postgresql:'].includes(parsed.protocol))
|
|
62
|
+
throw new Error('pubg_saas_database_url_invalid');
|
|
63
|
+
const requestsPerMinute = positiveInteger(env.PUBLIC_PUBG_REQUESTS_PER_MINUTE, 10, 1000);
|
|
64
|
+
const explicitInterval = env.PUBLIC_SYNC_INTERVAL_MS?.trim();
|
|
65
|
+
const hourly = !explicitInterval;
|
|
66
|
+
const intervalMs = positiveInteger(explicitInterval, DEFAULT_INTERVAL_MS, 24 * 60 * 60_000);
|
|
67
|
+
const timeZone = env.PUBLIC_SYNC_TIMEZONE?.trim() || HOURLY_PREFETCH_TIMEZONE;
|
|
68
|
+
const minute = hourMinute(env.PUBLIC_SYNC_HOURLY_MINUTE, HOURLY_PREFETCH_MINUTE);
|
|
69
|
+
if (hourly)
|
|
70
|
+
nextHourlyPrefetchDelayMs(new Date(), { timeZone, minute });
|
|
71
|
+
const maxMatches = positiveInteger(env.PUBLIC_SYNC_MAX_MATCHES, 500, 1000);
|
|
72
|
+
const maxTelemetryFetches = positiveInteger(env.PUBLIC_SYNC_MAX_TELEMETRY_FETCHES, 20, 50);
|
|
73
|
+
const teamConcurrency = positiveInteger(env.PUBLIC_SYNC_TEAM_CONCURRENCY, 2, 16);
|
|
74
|
+
const leaseMs = positiveInteger(env.PUBLIC_SYNC_LEASE_MS, 120_000, 15 * 60_000);
|
|
75
|
+
const archiveDirectory = env.PUBLIC_TELEMETRY_ARCHIVE_DIR?.trim() || undefined;
|
|
76
|
+
const pool = new Pool({ connectionString: databaseUrl, max: 4, connectionTimeoutMillis: 5000, idleTimeoutMillis: 10000, statement_timeout: 30_000 });
|
|
77
|
+
const stop = new AbortController();
|
|
78
|
+
const metrics = new PublicSyncWorkerMetrics();
|
|
79
|
+
let healthServer;
|
|
80
|
+
let metricsServer;
|
|
81
|
+
const onStop = () => stop.abort();
|
|
82
|
+
process.once('SIGINT', onStop);
|
|
83
|
+
process.once('SIGTERM', onStop);
|
|
84
|
+
try {
|
|
85
|
+
const ready = await pool.query("SELECT 1 FROM pubg_schema_migrations WHERE migration_id='0001_pubg_schema.sql'");
|
|
86
|
+
if (!ready.rowCount)
|
|
87
|
+
throw new Error('pubg_saas_schema_upgrade_required');
|
|
88
|
+
healthServer = await startWorkerHealthServer();
|
|
89
|
+
const metricsPort = positiveInteger(env.PUBG_SAAS_WORKER_METRICS_PORT, 9464, 65_535);
|
|
90
|
+
metricsServer = await startWorkerMetricsServer(() => {
|
|
91
|
+
const memory = process.memoryUsage();
|
|
92
|
+
return metrics.render({
|
|
93
|
+
rssBytes: memory.rss,
|
|
94
|
+
heapUsedBytes: memory.heapUsed,
|
|
95
|
+
pool: { totalCount: pool.totalCount, idleCount: pool.idleCount, waitingCount: pool.waitingCount },
|
|
96
|
+
});
|
|
97
|
+
}, metricsPort);
|
|
98
|
+
const worker = new PublicSyncWorker(pool, {
|
|
99
|
+
apiKey,
|
|
100
|
+
admission: new PostgresPublicPubgAdmission(pool, requestsPerMinute, 30_000),
|
|
101
|
+
maxMatches,
|
|
102
|
+
maxTelemetryFetches,
|
|
103
|
+
teamConcurrency,
|
|
104
|
+
syncIntervalMs: intervalMs,
|
|
105
|
+
leaseMs,
|
|
106
|
+
...(archiveDirectory ? { rawTelemetryArchive: new RawTelemetryArchive(await assertArchiveOutsideRepository(archiveDirectory, env.PUBLIC_SYNC_REPOSITORY_ROOT?.trim() || process.cwd())) } : {}),
|
|
107
|
+
...(hourly ? { nextSyncDelayMs: (now) => clampSyncDelayMs(nextHourlyPrefetchDelayMs(now, { timeZone, minute })) } : {}),
|
|
108
|
+
onTeamError: code => process.stderr.write(`${code}\n`),
|
|
109
|
+
});
|
|
110
|
+
do {
|
|
111
|
+
const cycleStartedAt = performance.now();
|
|
112
|
+
const result = await worker.runOnce(stop.signal);
|
|
113
|
+
let queue = null;
|
|
114
|
+
try {
|
|
115
|
+
queue = await worker.getQueueSnapshot();
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
// A telemetry read failure must not discard a completed sync cycle or
|
|
119
|
+
// print database details into collected worker logs.
|
|
120
|
+
}
|
|
121
|
+
const memory = process.memoryUsage();
|
|
122
|
+
const cycleLog = createPublicSyncCycleLog({
|
|
123
|
+
observedAt: new Date().toISOString(),
|
|
124
|
+
cycle: result,
|
|
125
|
+
durationMs: Math.round((performance.now() - cycleStartedAt) * 10) / 10,
|
|
126
|
+
queue,
|
|
127
|
+
rssBytes: memory.rss,
|
|
128
|
+
heapUsedBytes: memory.heapUsed,
|
|
129
|
+
});
|
|
130
|
+
metrics.recordCycle(cycleLog);
|
|
131
|
+
process.stdout.write(`${JSON.stringify(cycleLog)}\n`);
|
|
132
|
+
if (once || stop.signal.aborted)
|
|
133
|
+
break;
|
|
134
|
+
await wait(syncCyclePauseMs({ hourly, intervalMs, now: new Date(), timeZone, minute }), stop.signal);
|
|
135
|
+
} while (!stop.signal.aborted);
|
|
136
|
+
}
|
|
137
|
+
finally {
|
|
138
|
+
stop.abort();
|
|
139
|
+
process.removeListener('SIGINT', onStop);
|
|
140
|
+
process.removeListener('SIGTERM', onStop);
|
|
141
|
+
try {
|
|
142
|
+
if (metricsServer)
|
|
143
|
+
await stopWorkerMetricsServer(metricsServer);
|
|
144
|
+
}
|
|
145
|
+
finally {
|
|
146
|
+
try {
|
|
147
|
+
if (healthServer)
|
|
148
|
+
await stopWorkerHealthServer(healthServer);
|
|
149
|
+
}
|
|
150
|
+
finally {
|
|
151
|
+
await pool.end();
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
157
|
+
void publicSyncWorkerMain(process.argv.slice(2)).catch(() => {
|
|
158
|
+
process.stderr.write('pubg_saas_sync_worker_startup_failed\n');
|
|
159
|
+
process.exitCode = 1;
|
|
160
|
+
});
|
|
161
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { createPublicSyncCycleLog } from './worker-alerts.js';
|
|
2
|
+
type CycleLog = ReturnType<typeof createPublicSyncCycleLog>;
|
|
3
|
+
/** Process-local, aggregate Worker metrics. Label values are fixed codes/states;
|
|
4
|
+
* tenant, team, player, guild, channel and actor identifiers never enter this registry. */
|
|
5
|
+
export declare class PublicSyncWorkerMetrics {
|
|
6
|
+
private cycles;
|
|
7
|
+
private readonly counters;
|
|
8
|
+
private readonly alertCounts;
|
|
9
|
+
private readonly durationBuckets;
|
|
10
|
+
private durationCount;
|
|
11
|
+
private durationSumMs;
|
|
12
|
+
private latestDurationMs;
|
|
13
|
+
private latestQueue;
|
|
14
|
+
recordCycle(log: CycleLog): void;
|
|
15
|
+
render(input: {
|
|
16
|
+
rssBytes: number;
|
|
17
|
+
heapUsedBytes: number;
|
|
18
|
+
pool: {
|
|
19
|
+
totalCount: number;
|
|
20
|
+
idleCount: number;
|
|
21
|
+
waitingCount: number;
|
|
22
|
+
};
|
|
23
|
+
}): string;
|
|
24
|
+
}
|
|
25
|
+
export {};
|