@rine-kit/pubg-sync 0.0.0-stage → 0.1.1

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ChristmasFox / Arthur Xu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,30 @@
1
- # Temporary Holding Version
1
+ # @rine-kit/pubg-sync
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ PUBG 数据同步:团队同步 worker、玩家名解析、官方 API 额度准入(限流)、出口代理配置、worker 指标/健康检查。
4
+ 提取自 Gate 的 `pubg-saas`,逻辑、默认值与测试保持一致;表名换成 `@rine-kit/pubg-postgres` 的 `pubg_*`。
5
+
6
+ ## 额度准入(限流)
7
+
8
+ `PostgresPublicPubgAdmission` 用数据库里 `pubg_api_admission` 的一行(`quota_scope='public-pubg'`)排队放行:
9
+ 同一数据库的所有进程共用一个额度,默认每分钟 10 次、最长等待 8 秒;收到 429 或剩余额度为 0 时按响应头封锁到重置时间。
10
+ **同一个 PUBG API key 只能由使用同一个数据库的进程共用**,否则各自限流会叠加超限。
11
+
12
+ ## 运行 worker
13
+
14
+ ```bash
15
+ DATABASE_URL=postgres://... PUBLIC_PUBG_API_KEY=... node dist/worker-main.js --apply [--once]
16
+ ```
17
+
18
+ 不带 `--apply` 只打印提示(空跑)。其余环境变量(均有默认值):`PUBLIC_PUBG_REQUESTS_PER_MINUTE`、`PUBLIC_SYNC_INTERVAL_MS`、
19
+ `PUBLIC_SYNC_MAX_MATCHES`、`PUBLIC_SYNC_MAX_TELEMETRY_FETCHES`、`PUBLIC_SYNC_TEAM_CONCURRENCY`、`PUBLIC_SYNC_LEASE_MS`、
20
+ `PUBG_SAAS_WORKER_METRICS_PORT`。先用 `migratePubgDatabase`(`@rine-kit/pubg-postgres`)建好库表。
21
+
22
+ ## 测试
23
+
24
+ ```bash
25
+ pnpm --filter @rine-kit/pubg-sync test:pg # 一次性 pgvector 容器
26
+ ```
27
+
28
+ ## 没有提取的
29
+
30
+ - `egress-proxy.ts`(Gate 容器网络里的 CONNECT 出口代理及其测试):属于 Gate 的部署形态,RINE 走本机代理即可。
@@ -0,0 +1,8 @@
1
+ export * from './request-limiter.js';
2
+ export * from './player-resolver.js';
3
+ export * from './sync-worker.js';
4
+ export * from './worker-alerts.js';
5
+ export * from './worker-metrics.js';
6
+ export * from './worker-health-server.js';
7
+ export * from './public-egress.js';
8
+ export * from './worker-main.js';
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ export * from './request-limiter.js';
2
+ export * from './player-resolver.js';
3
+ export * from './sync-worker.js';
4
+ export * from './worker-alerts.js';
5
+ export * from './worker-metrics.js';
6
+ export * from './worker-health-server.js';
7
+ export * from './public-egress.js';
8
+ export * from './worker-main.js';
@@ -0,0 +1,35 @@
1
+ import type { PublicPubgAdmission } from './request-limiter.js';
2
+ export interface ResolvedPubgPlayer {
3
+ accountId: string;
4
+ name: string;
5
+ }
6
+ export interface PubgNameResolution {
7
+ players: ResolvedPubgPlayer[];
8
+ missingNames: string[];
9
+ ambiguousNames: string[];
10
+ }
11
+ export interface PublicPubgPlayerResolverPort {
12
+ resolveNames(shard: string, names: string[], signal?: AbortSignal): Promise<PubgNameResolution>;
13
+ }
14
+ export declare function validatePublicPubgShard(shard: string): string;
15
+ /** Synthetic identities are intentionally available only to isolated acceptance
16
+ * runs. Unknown names never fall through to the real PUBG API. */
17
+ export declare function createConfiguredPublicPubgPlayerResolver(options: {
18
+ env: NodeJS.ProcessEnv;
19
+ apiKey?: string;
20
+ admission: PublicPubgAdmission;
21
+ }): {
22
+ resolver: PublicPubgPlayerResolverPort;
23
+ synthetic: boolean;
24
+ };
25
+ /** Uses the shared API implementation with independent public credentials and
26
+ * a mandatory public admission controller. No private team/plugin is loaded. */
27
+ export declare class PublicPubgPlayerResolver implements PublicPubgPlayerResolverPort {
28
+ private readonly client;
29
+ constructor(options: {
30
+ apiKey: string;
31
+ admission: PublicPubgAdmission;
32
+ fetcher?: typeof fetch;
33
+ });
34
+ resolveNames(shard: string, names: string[], signal?: AbortSignal): Promise<PubgNameResolution>;
35
+ }
@@ -0,0 +1,127 @@
1
+ import { PubgApiClient, PubgApiError } from '@rine-kit/pubg-domain/core';
2
+ import { MAX_TEAM_ROSTER_SIZE } from '@rine-kit/pubg-postgres';
3
+ const ACCEPTANCE_PLAYERS = new Map([
4
+ ['p3syntheticalpha', { accountId: 'account.p3synthetic_alpha', name: 'P3SyntheticAlpha' }],
5
+ ['p3syntheticbravo', { accountId: 'account.p3synthetic_bravo', name: 'P3SyntheticBravo' }],
6
+ ['p3syntheticcharlie', { accountId: 'account.p3synthetic_charlie', name: 'P3SyntheticCharlie' }],
7
+ ['p3syntheticdelta', { accountId: 'account.p3synthetic_delta', name: 'P3SyntheticDelta' }],
8
+ ]);
9
+ export function validatePublicPubgShard(shard) {
10
+ if (!['steam', 'kakao', 'psn', 'xbox'].includes(shard))
11
+ throw new Error('public_pubg_shard_invalid');
12
+ return shard;
13
+ }
14
+ class AcceptanceSyntheticPlayerResolver {
15
+ async resolveNames(shard, names) {
16
+ validatePublicPubgShard(shard);
17
+ if (!Array.isArray(names) || names.length < 1 || names.length > MAX_TEAM_ROSTER_SIZE
18
+ || names.some(name => typeof name !== 'string' || !name.trim() || name.length > 100 || /[,\u0000-\u001f]/u.test(name))
19
+ || new Set(names.map(name => name.trim().toLowerCase())).size !== names.length)
20
+ throw new Error('public_pubg_names_invalid');
21
+ const requested = names.map(name => name.trim());
22
+ const players = shard === 'steam'
23
+ ? requested.flatMap(name => {
24
+ const player = ACCEPTANCE_PLAYERS.get(name.toLowerCase());
25
+ return player ? [player] : [];
26
+ })
27
+ : [];
28
+ const resolvedNames = new Set(players.map(player => player.name.toLowerCase()));
29
+ return {
30
+ players,
31
+ missingNames: requested.filter(name => !resolvedNames.has(name.toLowerCase())),
32
+ ambiguousNames: [],
33
+ };
34
+ }
35
+ }
36
+ /** Synthetic identities are intentionally available only to isolated acceptance
37
+ * runs. Unknown names never fall through to the real PUBG API. */
38
+ export function createConfiguredPublicPubgPlayerResolver(options) {
39
+ const acceptanceRequested = options.env.PUBG_SAAS_ACCEPTANCE_MODE !== undefined
40
+ || options.env.PUBG_SAAS_SYNTHETIC_PUBG_PLAYERS !== undefined;
41
+ if (acceptanceRequested) {
42
+ if (options.env.PUBG_SAAS_ACCEPTANCE_MODE !== 'isolated'
43
+ || options.env.PUBG_SAAS_SYNTHETIC_PUBG_PLAYERS !== '1'
44
+ || options.env.NODE_ENV === 'production')
45
+ throw new Error('pubg_saas_synthetic_resolver_forbidden');
46
+ return { resolver: new AcceptanceSyntheticPlayerResolver(), synthetic: true };
47
+ }
48
+ if (!options.apiKey?.trim())
49
+ throw new Error('public_pubg_api_key_missing');
50
+ return { resolver: new PublicPubgPlayerResolver({ apiKey: options.apiKey, admission: options.admission }), synthetic: false };
51
+ }
52
+ /** Uses the shared API implementation with independent public credentials and
53
+ * a mandatory public admission controller. No private team/plugin is loaded. */
54
+ export class PublicPubgPlayerResolver {
55
+ client;
56
+ constructor(options) {
57
+ if (!options.apiKey.trim())
58
+ throw new Error('public_pubg_api_key_missing');
59
+ const fetcher = options.fetcher ?? fetch;
60
+ this.client = new PubgApiClient({
61
+ apiKey: options.apiKey, baseUrl: 'https://api.pubg.com',
62
+ fetchImpl: async (input, init) => {
63
+ const url = new URL(String(input));
64
+ if (url.origin !== 'https://api.pubg.com' || !/^\/shards\/(steam|kakao|psn|xbox)\/players$/u.test(url.pathname))
65
+ throw new Error('public_pubg_endpoint_invalid');
66
+ try {
67
+ await options.admission.acquire(init?.signal ?? undefined);
68
+ }
69
+ catch (error) {
70
+ if (error instanceof Error && error.message === 'public_pubg_lookup_rate_limited')
71
+ throw new PubgApiError('rate_limited', 'Public PUBG admission busy', false);
72
+ throw error;
73
+ }
74
+ const response = await fetcher(url, { ...init, redirect: 'error' });
75
+ await options.admission.observe(response.headers, response.status);
76
+ return response;
77
+ },
78
+ });
79
+ }
80
+ async resolveNames(shard, names, signal) {
81
+ validatePublicPubgShard(shard);
82
+ if (!Array.isArray(names) || names.length < 1 || names.length > MAX_TEAM_ROSTER_SIZE
83
+ || names.some(name => typeof name !== 'string' || !name.trim() || name.length > 100 || /[,\u0000-\u001f]/u.test(name))
84
+ || new Set(names.map(name => name.trim().toLowerCase())).size !== names.length)
85
+ throw new Error('public_pubg_names_invalid');
86
+ const requested = names.map(name => name.trim());
87
+ let entries;
88
+ try {
89
+ entries = await this.client.discoverPlayers(shard, [], requested, signal);
90
+ }
91
+ catch (error) {
92
+ if (error instanceof PubgApiError && error.code === 'not_found')
93
+ return { players: [], missingNames: requested, ambiguousNames: [] };
94
+ if (error instanceof PubgApiError && error.code === 'rate_limited')
95
+ throw new Error('public_pubg_lookup_rate_limited');
96
+ if (error instanceof Error && error.message === 'public_pubg_lookup_rate_limited')
97
+ throw error;
98
+ // Shared client may normalize fetch/admission failures into PubgApiError;
99
+ // never pass upstream details or credential values to user messages.
100
+ throw new Error('public_pubg_lookup_unavailable');
101
+ }
102
+ const players = [], missingNames = [], ambiguousNames = [];
103
+ for (const name of requested) {
104
+ const matches = entries.filter(entry => entry.type === 'player' && entry.attributes && typeof entry.attributes === 'object'
105
+ && typeof entry.attributes.name === 'string'
106
+ && (entry.attributes.name).toLowerCase() === name.toLowerCase());
107
+ const unique = new Map();
108
+ for (const entry of matches) {
109
+ if (typeof entry.id !== 'string' || !/^account\.[A-Za-z0-9_-]{1,128}$/u.test(entry.id))
110
+ throw new Error('public_pubg_lookup_invalid_response');
111
+ const apiName = entry.attributes.name;
112
+ if (!apiName.trim() || apiName.length > 100)
113
+ throw new Error('public_pubg_lookup_invalid_response');
114
+ unique.set(entry.id, { accountId: entry.id, name: apiName });
115
+ }
116
+ if (!unique.size)
117
+ missingNames.push(name);
118
+ else if (unique.size > 1)
119
+ ambiguousNames.push(name);
120
+ else
121
+ players.push([...unique.values()][0]);
122
+ }
123
+ if (new Set(players.map(player => player.accountId)).size !== players.length)
124
+ throw new Error('public_pubg_lookup_invalid_response');
125
+ return { players, missingNames, ambiguousNames };
126
+ }
127
+ }
@@ -0,0 +1,5 @@
1
+ export declare function parsePublicEgressProxy(value: string | undefined): URL | null;
2
+ /** Install one process-wide egress proxy for Node fetch, the AI SDK and the
3
+ * Node WebSocket implementation. Compose keeps application containers on
4
+ * internal networks and points this dispatcher at the guarded proxy service. */
5
+ export declare function configurePublicEgress(env?: NodeJS.ProcessEnv): boolean;
@@ -0,0 +1,34 @@
1
+ import { ProxyAgent, setGlobalDispatcher } from 'undici';
2
+ const proxyKey = 'PUBG_SAAS_EGRESS_PROXY';
3
+ export function parsePublicEgressProxy(value) {
4
+ if (value === undefined || value.trim() === '')
5
+ return null;
6
+ let url;
7
+ try {
8
+ url = new URL(value);
9
+ }
10
+ catch {
11
+ throw new Error('pubg_saas_egress_proxy_invalid');
12
+ }
13
+ if (url.protocol !== 'http:' || !url.hostname || url.username || url.password
14
+ || url.pathname !== '/' || url.search || url.hash || !url.port
15
+ || !/^[a-z0-9.-]+$/u.test(url.hostname) || url.hostname.startsWith('.')
16
+ || url.hostname.endsWith('.') || url.hostname.includes('..')) {
17
+ throw new Error('pubg_saas_egress_proxy_invalid');
18
+ }
19
+ return url;
20
+ }
21
+ /** Install one process-wide egress proxy for Node fetch, the AI SDK and the
22
+ * Node WebSocket implementation. Compose keeps application containers on
23
+ * internal networks and points this dispatcher at the guarded proxy service. */
24
+ export function configurePublicEgress(env = process.env) {
25
+ const proxy = parsePublicEgressProxy(env[proxyKey]);
26
+ if (!proxy) {
27
+ if (env.PUBG_SAAS_EGRESS_PROXY_REQUIRED === '1') {
28
+ throw new Error('pubg_saas_egress_proxy_required');
29
+ }
30
+ return false;
31
+ }
32
+ setGlobalDispatcher(new ProxyAgent(proxy.toString()));
33
+ return true;
34
+ }
@@ -0,0 +1,16 @@
1
+ import type { Pool } from 'pg';
2
+ export interface PublicPubgAdmission {
3
+ acquire(signal?: AbortSignal): Promise<void>;
4
+ observe(headers: Headers, status: number): Promise<void>;
5
+ }
6
+ /** Public-only admission shared by app/worker connections. It spaces requests
7
+ * conservatively rather than assuming a provider-aligned fixed minute window. */
8
+ export declare class PostgresPublicPubgAdmission implements PublicPubgAdmission {
9
+ private readonly pool;
10
+ private readonly requestsPerMinute;
11
+ private readonly maxWaitMs;
12
+ constructor(pool: Pool, requestsPerMinute?: number, maxWaitMs?: number);
13
+ tryAcquire(): Promise<number>;
14
+ acquire(signal?: AbortSignal): Promise<void>;
15
+ observe(headers: Headers, status: number): Promise<void>;
16
+ }
@@ -0,0 +1,85 @@
1
+ function delay(ms, signal) {
2
+ if (signal?.aborted)
3
+ return Promise.reject(new Error('public_pubg_lookup_cancelled'));
4
+ return new Promise((resolve, reject) => {
5
+ const timer = setTimeout(finish, ms);
6
+ function finish() { signal?.removeEventListener('abort', abort); resolve(); }
7
+ function abort() { clearTimeout(timer); signal?.removeEventListener('abort', abort); reject(new Error('public_pubg_lookup_cancelled')); }
8
+ signal?.addEventListener('abort', abort, { once: true });
9
+ if (signal?.aborted)
10
+ abort();
11
+ });
12
+ }
13
+ /** Public-only admission shared by app/worker connections. It spaces requests
14
+ * conservatively rather than assuming a provider-aligned fixed minute window. */
15
+ export class PostgresPublicPubgAdmission {
16
+ pool;
17
+ requestsPerMinute;
18
+ maxWaitMs;
19
+ constructor(pool, requestsPerMinute = 10, maxWaitMs = 8000) {
20
+ this.pool = pool;
21
+ this.requestsPerMinute = requestsPerMinute;
22
+ this.maxWaitMs = maxWaitMs;
23
+ if (!Number.isSafeInteger(requestsPerMinute) || requestsPerMinute < 1 || requestsPerMinute > 1000
24
+ || !Number.isSafeInteger(maxWaitMs) || maxWaitMs < 0 || maxWaitMs > 30_000)
25
+ throw new Error('public_pubg_admission_config_invalid');
26
+ }
27
+ async tryAcquire() {
28
+ const client = await this.pool.connect();
29
+ try {
30
+ await client.query('BEGIN');
31
+ await client.query("INSERT INTO pubg_api_admission(quota_scope) VALUES ('public-pubg') ON CONFLICT DO NOTHING");
32
+ const state = await client.query(`SELECT observed_limit,CEIL(EXTRACT(EPOCH FROM
33
+ (GREATEST(next_request_at,COALESCE(blocked_until,next_request_at))-clock_timestamp()))*1000) AS wait_ms
34
+ FROM pubg_api_admission WHERE quota_scope='public-pubg' FOR UPDATE`);
35
+ const wait = Math.max(0, Number(state.rows[0]?.wait_ms));
36
+ if (wait === 0) {
37
+ const observed = Number(state.rows[0]?.observed_limit);
38
+ const limit = observed > 0 ? Math.min(observed, this.requestsPerMinute) : this.requestsPerMinute;
39
+ await client.query(`UPDATE pubg_api_admission SET next_request_at=clock_timestamp()+($1::BIGINT*interval '1 millisecond'),reserved_at=clock_timestamp(),
40
+ updated_at=now() WHERE quota_scope='public-pubg'`, [Math.ceil(60_000 / limit)]);
41
+ }
42
+ await client.query('COMMIT');
43
+ return wait;
44
+ }
45
+ catch (error) {
46
+ await client.query('ROLLBACK').catch(() => undefined);
47
+ throw error;
48
+ }
49
+ finally {
50
+ client.release();
51
+ }
52
+ }
53
+ async acquire(signal) {
54
+ const deadline = Date.now() + this.maxWaitMs;
55
+ while (!signal?.aborted) {
56
+ const wait = await this.tryAcquire();
57
+ if (wait === 0)
58
+ return;
59
+ if (wait > deadline - Date.now())
60
+ throw new Error('public_pubg_lookup_rate_limited');
61
+ await delay(Math.max(1, Math.min(wait, 1000)), signal);
62
+ }
63
+ throw new Error('public_pubg_lookup_cancelled');
64
+ }
65
+ async observe(headers, status) {
66
+ const rawLimit = headers.get('x-ratelimit-limit');
67
+ const limit = rawLimit === null ? null : Number(rawLimit);
68
+ const validLimit = limit !== null && Number.isSafeInteger(limit) && limit > 0 && limit <= 100_000 ? limit : null;
69
+ const remaining = headers.get('x-ratelimit-remaining');
70
+ let blockedUntil = null;
71
+ if (status === 429 || (remaining !== null && Number(remaining) === 0)) {
72
+ const reset = Number(headers.get('x-ratelimit-reset')) * 1000;
73
+ const retry = headers.get('retry-after');
74
+ const retrySeconds = retry === null ? NaN : Number(retry);
75
+ const retryAt = Number.isFinite(retrySeconds) ? Date.now() + retrySeconds * 1000 : Date.parse(retry ?? '');
76
+ const providerReset = Number.isFinite(reset) && reset > Date.now() ? reset : Date.now() + 60_000;
77
+ blockedUntil = new Date(Math.min(Date.now() + 24 * 60 * 60_000, Math.max(providerReset, Number.isFinite(retryAt) ? retryAt : 0)));
78
+ }
79
+ await this.pool.query(`UPDATE pubg_api_admission SET observed_limit=COALESCE($1,observed_limit),
80
+ next_request_at=CASE WHEN $1::INTEGER IS NULL THEN next_request_at ELSE
81
+ GREATEST(next_request_at,COALESCE(reserved_at,next_request_at)+($3::BIGINT*interval '1 millisecond')) END,
82
+ blocked_until=CASE WHEN $2::TIMESTAMPTZ IS NULL THEN blocked_until ELSE GREATEST(COALESCE(blocked_until,$2),$2) END,
83
+ updated_at=now() WHERE quota_scope='public-pubg'`, [validLimit, blockedUntil, validLimit ? Math.ceil(60_000 / Math.min(validLimit, this.requestsPerMinute)) : 0]);
84
+ }
85
+ }
@@ -0,0 +1,51 @@
1
+ import type { Pool } from 'pg';
2
+ import type { PublicPubgAdmission } from './request-limiter.js';
3
+ import { type PublicSyncQueueSnapshot } from '@rine-kit/pubg-postgres';
4
+ export interface PublicSyncCycleResult {
5
+ teamsDiscovered: number;
6
+ teamsAttempted: number;
7
+ teamsCompleted: number;
8
+ teamsFailed: number;
9
+ matchesDiscovered: number;
10
+ telemetryFetched: number;
11
+ telemetryUnavailable: number;
12
+ }
13
+ export interface PublicSyncWorkerOptions {
14
+ apiKey: string;
15
+ admission: PublicPubgAdmission;
16
+ fetchImpl?: typeof fetch;
17
+ now?: () => Date;
18
+ maxMatches?: number;
19
+ maxTelemetryFetches?: number;
20
+ telemetryConcurrency?: number;
21
+ teamConcurrency?: number;
22
+ syncIntervalMs?: number;
23
+ leaseMs?: number;
24
+ onTeamError?: (code: 'public_sync_team_invalid' | 'public_sync_team_failed') => void;
25
+ }
26
+ /** Restricts the worker to official public PUBG API and telemetry endpoints.
27
+ * Rate-limited player discovery uses shared admission; match details follow the
28
+ * provider's unmetered endpoint policy. Public telemetry CDN objects never
29
+ * receive the API key. Redirects are rejected. */
30
+ export declare function createPublicSyncFetch(admission: PublicPubgAdmission, fetchImpl?: typeof fetch): typeof fetch;
31
+ /** Independent public-SaaS ingestion process. It loads only registered SaaS
32
+ * rosters, syncs them through the shared PUBG Domain and writes to PG through
33
+ * the tenant/team scoped repository. */
34
+ export declare class PublicSyncWorker {
35
+ private readonly pool;
36
+ private readonly client;
37
+ private readonly telemetryDownloader;
38
+ private readonly now;
39
+ private readonly maxMatches;
40
+ private readonly maxTelemetryFetches;
41
+ private readonly telemetryConcurrency;
42
+ private readonly teamConcurrency;
43
+ private readonly syncIntervalMs;
44
+ private readonly leaseMs;
45
+ private readonly queue;
46
+ constructor(pool: Pool, options: PublicSyncWorkerOptions);
47
+ private readonly onTeamError;
48
+ runOnce(signal?: AbortSignal): Promise<PublicSyncCycleResult>;
49
+ getQueueSnapshot(): Promise<PublicSyncQueueSnapshot>;
50
+ private processJob;
51
+ }
@@ -0,0 +1,288 @@
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
+ leaseMs;
174
+ queue;
175
+ constructor(pool, options) {
176
+ this.pool = pool;
177
+ if (!options.apiKey.trim())
178
+ throw new Error('public_pubg_api_key_missing');
179
+ this.maxMatches = boundedInteger(options.maxMatches ?? DEFAULT_MAX_MATCHES, DEFAULT_MAX_MATCHES, 1, 1000);
180
+ this.maxTelemetryFetches = boundedInteger(options.maxTelemetryFetches ?? DEFAULT_MAX_TELEMETRY_FETCHES, DEFAULT_MAX_TELEMETRY_FETCHES, 1, 50);
181
+ this.telemetryConcurrency = boundedInteger(options.telemetryConcurrency ?? DEFAULT_TELEMETRY_CONCURRENCY, DEFAULT_TELEMETRY_CONCURRENCY, 1, 4);
182
+ this.teamConcurrency = boundedInteger(options.teamConcurrency ?? DEFAULT_TEAM_CONCURRENCY, DEFAULT_TEAM_CONCURRENCY, 1, 16);
183
+ this.syncIntervalMs = boundedInteger(options.syncIntervalMs ?? DEFAULT_SYNC_INTERVAL_MS, DEFAULT_SYNC_INTERVAL_MS, 1_000, 24 * 60 * 60_000);
184
+ this.leaseMs = boundedInteger(options.leaseMs ?? 120_000, 120_000, 1_000, 15 * 60_000);
185
+ this.queue = new PublicSyncQueue(pool, { leaseMs: this.leaseMs });
186
+ this.now = options.now ?? (() => new Date());
187
+ const fetchImpl = createPublicSyncFetch(options.admission, options.fetchImpl);
188
+ // Use the shared Domain client's retry, concurrency, and timeout defaults,
189
+ // matching the private Kurisu plugin configuration. Upstream admission is
190
+ // still enforced independently by the shared PostgreSQL limiter.
191
+ this.client = new PubgApiClient({ apiKey: options.apiKey, baseUrl: API_ORIGIN, fetchImpl });
192
+ this.telemetryDownloader = new PubgApiTelemetryDownloader({
193
+ apiKey: options.apiKey,
194
+ baseUrl: API_ORIGIN,
195
+ timeoutMs: 60_000,
196
+ fetchImpl,
197
+ });
198
+ this.onTeamError = options.onTeamError ?? (() => undefined);
199
+ }
200
+ onTeamError;
201
+ async runOnce(signal) {
202
+ const teamsDiscovered = await this.queue.ensureTeams();
203
+ const summary = {
204
+ teamsDiscovered,
205
+ teamsAttempted: 0,
206
+ teamsCompleted: 0,
207
+ teamsFailed: 0,
208
+ matchesDiscovered: 0,
209
+ telemetryFetched: 0,
210
+ telemetryUnavailable: 0,
211
+ };
212
+ // A stop request prevents new claims. Jobs already leased finish and are
213
+ // checkpointed before the caller closes the PG pool, which gives shutdown
214
+ // a bounded, recoverable boundary without dropping in-flight work.
215
+ while (!signal?.aborted) {
216
+ const jobs = await this.queue.claimDue(this.teamConcurrency);
217
+ if (jobs.length === 0)
218
+ break;
219
+ summary.teamsAttempted += jobs.length;
220
+ const results = await Promise.all(jobs.map((job) => this.processJob(job)));
221
+ for (const result of results) {
222
+ if (!result.ok) {
223
+ summary.teamsFailed += 1;
224
+ this.onTeamError(result.invalid ? 'public_sync_team_invalid' : 'public_sync_team_failed');
225
+ continue;
226
+ }
227
+ summary.teamsCompleted += 1;
228
+ summary.matchesDiscovered += result.telemetry.discovered;
229
+ summary.telemetryFetched += result.telemetry.fetched;
230
+ summary.telemetryUnavailable += result.telemetry.unavailable;
231
+ }
232
+ }
233
+ return summary;
234
+ }
235
+ getQueueSnapshot() {
236
+ return this.queue.getSnapshot();
237
+ }
238
+ async processJob(job) {
239
+ const stopIfLeaseLost = new AbortController();
240
+ let renewalInFlight = false;
241
+ const heartbeat = setInterval(() => {
242
+ if (renewalInFlight)
243
+ return;
244
+ renewalInFlight = true;
245
+ void this.queue.renew(job).then((renewed) => {
246
+ if (!renewed)
247
+ stopIfLeaseLost.abort();
248
+ }).catch(() => stopIfLeaseLost.abort()).finally(() => { renewalInFlight = false; });
249
+ }, Math.max(250, Math.floor(this.leaseMs / 3)));
250
+ heartbeat.unref?.();
251
+ try {
252
+ const teamContext = await registeredTeam(this.pool, job.tenantId, job.teamId);
253
+ const repository = new PostgresPubgRepository(this.pool, teamContext);
254
+ const telemetryWorker = new TelemetryWorker({
255
+ team: teamContext.team,
256
+ store: repository,
257
+ downloader: this.telemetryDownloader,
258
+ });
259
+ const service = new PubgDomainService({
260
+ teamContext,
261
+ repository,
262
+ apiClient: this.client,
263
+ telemetryWorker,
264
+ maxMatches: this.maxMatches,
265
+ now: this.now,
266
+ });
267
+ const result = await service.prefetchTelemetry({
268
+ maxMatches: this.maxMatches,
269
+ maxFetches: this.maxTelemetryFetches,
270
+ concurrency: this.telemetryConcurrency,
271
+ trigger: 'hourly',
272
+ signal: stopIfLeaseLost.signal,
273
+ });
274
+ if (stopIfLeaseLost.signal.aborted || !await this.queue.complete(job, this.syncIntervalMs)) {
275
+ return { ok: false, invalid: false };
276
+ }
277
+ return { ok: true, telemetry: telemetryRun(result.data) };
278
+ }
279
+ catch (error) {
280
+ const invalid = error instanceof InvalidTeamError;
281
+ await this.queue.fail(job, invalid ? 'public_sync_team_invalid' : 'public_sync_team_failed').catch(() => false);
282
+ return { ok: false, invalid };
283
+ }
284
+ finally {
285
+ clearInterval(heartbeat);
286
+ }
287
+ }
288
+ }
@@ -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,3 @@
1
+ /** Without --apply this entrypoint is a side-effect-free preview. --once keeps
2
+ * an explicitly applied worker run bounded for local acceptance and recovery. */
3
+ export declare function publicSyncWorkerMain(args: string[], env?: NodeJS.ProcessEnv): Promise<void>;
@@ -0,0 +1,141 @@
1
+ import { pathToFileURL } from 'node:url';
2
+ import { Pool } from 'pg';
3
+ import { PublicSyncWorker } from './sync-worker.js';
4
+ import { PostgresPublicPubgAdmission } from './request-limiter.js';
5
+ import { configurePublicEgress } from './public-egress.js';
6
+ import { startWorkerHealthServer, startWorkerMetricsServer, stopWorkerHealthServer, stopWorkerMetricsServer, } from './worker-health-server.js';
7
+ import { createPublicSyncCycleLog } from './worker-alerts.js';
8
+ import { PublicSyncWorkerMetrics } from './worker-metrics.js';
9
+ const DEFAULT_INTERVAL_MS = 5 * 60_000;
10
+ function positiveInteger(value, fallback, maximum) {
11
+ if (value === undefined || value.trim() === '')
12
+ return fallback;
13
+ const result = Number(value);
14
+ if (!Number.isSafeInteger(result) || result < 1 || result > maximum)
15
+ throw new Error('pubg_saas_worker_config_invalid');
16
+ return result;
17
+ }
18
+ function wait(ms, signal) {
19
+ if (signal.aborted)
20
+ return Promise.resolve();
21
+ return new Promise(resolve => {
22
+ const finish = () => { signal.removeEventListener('abort', finish); clearTimeout(timer); resolve(); };
23
+ const timer = setTimeout(finish, ms);
24
+ signal.addEventListener('abort', finish, { once: true });
25
+ });
26
+ }
27
+ /** Without --apply this entrypoint is a side-effect-free preview. --once keeps
28
+ * an explicitly applied worker run bounded for local acceptance and recovery. */
29
+ export async function publicSyncWorkerMain(args, env = process.env) {
30
+ if (args.length === 0) {
31
+ process.stdout.write('PUBG_SAAS_SYNC_WORKER=dry-run; start requires --apply, DATABASE_URL, and PUBLIC_PUBG_API_KEY.\n');
32
+ return;
33
+ }
34
+ const once = args.includes('--once');
35
+ if (!args.includes('--apply') || args.length !== (once ? 2 : 1) || args.some(value => value !== '--apply' && value !== '--once')) {
36
+ throw new Error('pubg_saas_worker_arguments_invalid');
37
+ }
38
+ const databaseUrl = env.DATABASE_URL;
39
+ const apiKey = env.PUBLIC_PUBG_API_KEY;
40
+ if (!databaseUrl || !apiKey?.trim())
41
+ throw new Error('pubg_saas_worker_config_missing');
42
+ configurePublicEgress(env);
43
+ let parsed;
44
+ try {
45
+ parsed = new URL(databaseUrl);
46
+ }
47
+ catch {
48
+ throw new Error('pubg_saas_database_url_invalid');
49
+ }
50
+ if (!['postgres:', 'postgresql:'].includes(parsed.protocol))
51
+ throw new Error('pubg_saas_database_url_invalid');
52
+ const requestsPerMinute = positiveInteger(env.PUBLIC_PUBG_REQUESTS_PER_MINUTE, 10, 1000);
53
+ const intervalMs = positiveInteger(env.PUBLIC_SYNC_INTERVAL_MS, DEFAULT_INTERVAL_MS, 24 * 60 * 60_000);
54
+ const maxMatches = positiveInteger(env.PUBLIC_SYNC_MAX_MATCHES, 500, 1000);
55
+ const maxTelemetryFetches = positiveInteger(env.PUBLIC_SYNC_MAX_TELEMETRY_FETCHES, 20, 50);
56
+ const teamConcurrency = positiveInteger(env.PUBLIC_SYNC_TEAM_CONCURRENCY, 2, 16);
57
+ const leaseMs = positiveInteger(env.PUBLIC_SYNC_LEASE_MS, 120_000, 15 * 60_000);
58
+ const pool = new Pool({ connectionString: databaseUrl, max: 4, connectionTimeoutMillis: 5000, idleTimeoutMillis: 10000, statement_timeout: 30_000 });
59
+ const stop = new AbortController();
60
+ const metrics = new PublicSyncWorkerMetrics();
61
+ let healthServer;
62
+ let metricsServer;
63
+ const onStop = () => stop.abort();
64
+ process.once('SIGINT', onStop);
65
+ process.once('SIGTERM', onStop);
66
+ try {
67
+ const ready = await pool.query("SELECT 1 FROM pubg_schema_migrations WHERE migration_id='0001_pubg_schema.sql'");
68
+ if (!ready.rowCount)
69
+ throw new Error('pubg_saas_schema_upgrade_required');
70
+ healthServer = await startWorkerHealthServer();
71
+ const metricsPort = positiveInteger(env.PUBG_SAAS_WORKER_METRICS_PORT, 9464, 65_535);
72
+ metricsServer = await startWorkerMetricsServer(() => {
73
+ const memory = process.memoryUsage();
74
+ return metrics.render({
75
+ rssBytes: memory.rss,
76
+ heapUsedBytes: memory.heapUsed,
77
+ pool: { totalCount: pool.totalCount, idleCount: pool.idleCount, waitingCount: pool.waitingCount },
78
+ });
79
+ }, metricsPort);
80
+ const worker = new PublicSyncWorker(pool, {
81
+ apiKey,
82
+ admission: new PostgresPublicPubgAdmission(pool, requestsPerMinute, 30_000),
83
+ maxMatches,
84
+ maxTelemetryFetches,
85
+ teamConcurrency,
86
+ syncIntervalMs: intervalMs,
87
+ leaseMs,
88
+ onTeamError: code => process.stderr.write(`${code}\n`),
89
+ });
90
+ do {
91
+ const cycleStartedAt = performance.now();
92
+ const result = await worker.runOnce(stop.signal);
93
+ let queue = null;
94
+ try {
95
+ queue = await worker.getQueueSnapshot();
96
+ }
97
+ catch {
98
+ // A telemetry read failure must not discard a completed sync cycle or
99
+ // print database details into collected worker logs.
100
+ }
101
+ const memory = process.memoryUsage();
102
+ const cycleLog = createPublicSyncCycleLog({
103
+ observedAt: new Date().toISOString(),
104
+ cycle: result,
105
+ durationMs: Math.round((performance.now() - cycleStartedAt) * 10) / 10,
106
+ queue,
107
+ rssBytes: memory.rss,
108
+ heapUsedBytes: memory.heapUsed,
109
+ });
110
+ metrics.recordCycle(cycleLog);
111
+ process.stdout.write(`${JSON.stringify(cycleLog)}\n`);
112
+ if (once || stop.signal.aborted)
113
+ break;
114
+ await wait(intervalMs, stop.signal);
115
+ } while (!stop.signal.aborted);
116
+ }
117
+ finally {
118
+ stop.abort();
119
+ process.removeListener('SIGINT', onStop);
120
+ process.removeListener('SIGTERM', onStop);
121
+ try {
122
+ if (metricsServer)
123
+ await stopWorkerMetricsServer(metricsServer);
124
+ }
125
+ finally {
126
+ try {
127
+ if (healthServer)
128
+ await stopWorkerHealthServer(healthServer);
129
+ }
130
+ finally {
131
+ await pool.end();
132
+ }
133
+ }
134
+ }
135
+ }
136
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
137
+ void publicSyncWorkerMain(process.argv.slice(2)).catch(() => {
138
+ process.stderr.write('pubg_saas_sync_worker_startup_failed\n');
139
+ process.exitCode = 1;
140
+ });
141
+ }
@@ -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 {};
@@ -0,0 +1,94 @@
1
+ const DURATION_BUCKETS_MS = [10, 50, 100, 250, 500, 1_000, 5_000, 30_000];
2
+ const ALERT_CODES = [
3
+ { code: 'public_sync_queue_snapshot_unavailable', severity: 'critical' },
4
+ { code: 'public_sync_queue_lag_high', severity: 'warning' },
5
+ { code: 'public_sync_queue_expired_lease', severity: 'warning' },
6
+ { code: 'public_sync_team_failures', severity: 'warning' },
7
+ { code: 'public_sync_worker_rss_high', severity: 'warning' },
8
+ ];
9
+ function number(value) {
10
+ return Number.isFinite(value) && value >= 0 ? String(value) : '0';
11
+ }
12
+ function gauge(name, help, value) {
13
+ return [`# HELP ${name} ${help}`, `# TYPE ${name} gauge`, `${name} ${number(value)}`];
14
+ }
15
+ function counter(name, help, value) {
16
+ return [`# HELP ${name} ${help}`, `# TYPE ${name} counter`, `${name} ${number(value)}`];
17
+ }
18
+ /** Process-local, aggregate Worker metrics. Label values are fixed codes/states;
19
+ * tenant, team, player, guild, channel and actor identifiers never enter this registry. */
20
+ export class PublicSyncWorkerMetrics {
21
+ cycles = 0;
22
+ counters = {
23
+ teamsDiscovered: 0,
24
+ teamsAttempted: 0,
25
+ teamsCompleted: 0,
26
+ teamsFailed: 0,
27
+ matchesDiscovered: 0,
28
+ telemetryFetched: 0,
29
+ telemetryUnavailable: 0,
30
+ };
31
+ alertCounts = new Map(ALERT_CODES.map(({ code }) => [code, 0]));
32
+ durationBuckets = DURATION_BUCKETS_MS.map(() => 0);
33
+ durationCount = 0;
34
+ durationSumMs = 0;
35
+ latestDurationMs = 0;
36
+ latestQueue = null;
37
+ recordCycle(log) {
38
+ this.cycles += 1;
39
+ this.counters.teamsDiscovered += log.cycle.teamsDiscovered;
40
+ this.counters.teamsAttempted += log.cycle.teamsAttempted;
41
+ this.counters.teamsCompleted += log.cycle.teamsCompleted;
42
+ this.counters.teamsFailed += log.cycle.teamsFailed;
43
+ this.counters.matchesDiscovered += log.cycle.matchesDiscovered;
44
+ this.counters.telemetryFetched += log.cycle.telemetryFetched;
45
+ this.counters.telemetryUnavailable += log.cycle.telemetryUnavailable;
46
+ this.latestDurationMs = log.cycle.durationMs;
47
+ this.durationCount += 1;
48
+ this.durationSumMs += log.cycle.durationMs;
49
+ DURATION_BUCKETS_MS.forEach((bound, index) => {
50
+ if (log.cycle.durationMs <= bound)
51
+ this.durationBuckets[index] += 1;
52
+ });
53
+ this.latestQueue = log.queue;
54
+ for (const alert of log.alerts)
55
+ this.alertCounts.set(alert.code, (this.alertCounts.get(alert.code) ?? 0) + 1);
56
+ }
57
+ render(input) {
58
+ const lines = [
59
+ ...gauge('pubg_saas_worker_up', 'Worker process is serving metrics.', 1),
60
+ ...gauge('pubg_saas_worker_process_rss_bytes', 'Current Worker resident memory in bytes.', input.rssBytes),
61
+ ...gauge('pubg_saas_worker_process_heap_used_bytes', 'Current Worker V8 heap used in bytes.', input.heapUsedBytes),
62
+ ...gauge('pubg_saas_worker_pg_pool_total', 'Current PostgreSQL pool connections.', input.pool.totalCount),
63
+ ...gauge('pubg_saas_worker_pg_pool_idle', 'Idle PostgreSQL pool connections.', input.pool.idleCount),
64
+ ...gauge('pubg_saas_worker_pg_pool_waiting', 'Clients waiting for a PostgreSQL pool connection.', input.pool.waitingCount),
65
+ ...gauge('pubg_saas_worker_sync_cycle_duration_ms', 'Duration of the most recently completed sync cycle.', this.latestDurationMs),
66
+ ...gauge('pubg_saas_worker_queue_snapshot_available', 'Whether the most recent queue snapshot was available.', this.latestQueue === null ? 0 : 1),
67
+ ...gauge('pubg_saas_worker_queue_jobs_total', 'Jobs in the most recent queue snapshot.', this.latestQueue?.totalJobs ?? 0),
68
+ ...gauge('pubg_saas_worker_queue_jobs_due', 'Due jobs in the most recent queue snapshot.', this.latestQueue?.dueJobs ?? 0),
69
+ ...gauge('pubg_saas_worker_queue_jobs_delayed', 'Delayed jobs in the most recent queue snapshot.', this.latestQueue?.delayedJobs ?? 0),
70
+ ...gauge('pubg_saas_worker_queue_active_leases', 'Active leases in the most recent queue snapshot.', this.latestQueue?.activeLeases ?? 0),
71
+ ...gauge('pubg_saas_worker_queue_expired_leases', 'Expired leases in the most recent queue snapshot.', this.latestQueue?.expiredLeases ?? 0),
72
+ ...gauge('pubg_saas_worker_queue_retrying_jobs', 'Retrying jobs in the most recent queue snapshot.', this.latestQueue?.retryingJobs ?? 0),
73
+ ...gauge('pubg_saas_worker_queue_oldest_due_age_seconds', 'Age of the oldest due job in seconds; zero when no due job exists.', this.latestQueue?.oldestDueAgeSeconds ?? 0),
74
+ '# HELP pubg_saas_worker_sync_cycle_duration_milliseconds Sync cycle duration histogram since process start.',
75
+ '# TYPE pubg_saas_worker_sync_cycle_duration_milliseconds histogram',
76
+ ];
77
+ lines.push(...counter('pubg_saas_worker_sync_cycles_total', 'Completed public sync cycles since process start.', this.cycles));
78
+ lines.push(...counter('pubg_saas_worker_sync_teams_discovered_total', 'Teams discovered since process start.', this.counters.teamsDiscovered));
79
+ lines.push(...counter('pubg_saas_worker_sync_teams_attempted_total', 'Teams attempted since process start.', this.counters.teamsAttempted));
80
+ lines.push(...counter('pubg_saas_worker_sync_teams_completed_total', 'Teams completed since process start.', this.counters.teamsCompleted));
81
+ lines.push(...counter('pubg_saas_worker_sync_teams_failed_total', 'Teams failed since process start.', this.counters.teamsFailed));
82
+ lines.push(...counter('pubg_saas_worker_sync_matches_discovered_total', 'Matches discovered since process start.', this.counters.matchesDiscovered));
83
+ lines.push(...counter('pubg_saas_worker_sync_telemetry_fetched_total', 'Telemetry files fetched since process start.', this.counters.telemetryFetched));
84
+ lines.push(...counter('pubg_saas_worker_sync_telemetry_unavailable_total', 'Telemetry files unavailable since process start.', this.counters.telemetryUnavailable));
85
+ DURATION_BUCKETS_MS.forEach((bound, index) => {
86
+ lines.push(`pubg_saas_worker_sync_cycle_duration_milliseconds_bucket{le="${bound}"} ${number(this.durationBuckets[index])}`);
87
+ });
88
+ lines.push(`pubg_saas_worker_sync_cycle_duration_milliseconds_bucket{le="+Inf"} ${number(this.durationCount)}`, `pubg_saas_worker_sync_cycle_duration_milliseconds_sum ${number(this.durationSumMs)}`, `pubg_saas_worker_sync_cycle_duration_milliseconds_count ${number(this.durationCount)}`, '# HELP pubg_saas_worker_alerts_total Worker alert codes observed since process start.', '# TYPE pubg_saas_worker_alerts_total counter');
89
+ for (const { code, severity } of ALERT_CODES) {
90
+ lines.push(`pubg_saas_worker_alerts_total{code="${code}",severity="${severity}"} ${this.alertCounts.get(code) ?? 0}`);
91
+ }
92
+ return `${lines.join('\n')}\n`;
93
+ }
94
+ }
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@rine-kit/pubg-sync",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "type": "module",
5
+ "description": "PUBG provider sync for @rine-kit/pubg-postgres: team sync worker, player-name resolver, shared API admission (rate limit), egress proxy config, worker metrics. Extracted from Gate; no KOOK dependency.",
6
+ "license": "MIT",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "import": "./dist/index.js",
11
+ "default": "./dist/index.js"
12
+ }
13
+ },
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "dependencies": {
21
+ "pg": "^8.13.0",
22
+ "undici": "^8.10.2",
23
+ "@rine-kit/pubg-domain": "0.1.1",
24
+ "@rine-kit/pubg-postgres": "0.1.1"
25
+ },
26
+ "devDependencies": {
27
+ "@types/node": "^26.6.5",
28
+ "@types/pg": "^8.11.10",
29
+ "tsx": "^4.23.15",
30
+ "typescript": "^5.9.2"
31
+ },
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+ssh://git@github.com/ChristmasFox/rine-kit.git",
35
+ "directory": "packages/pubg-sync"
36
+ },
37
+ "scripts": {
38
+ "build": "tsc -p tsconfig.build.json",
39
+ "typecheck": "tsc -p tsconfig.json --noEmit",
40
+ "test": "tsx --test \"tests/**/*.test.ts\"",
41
+ "test:pg": "bash ../../scripts/with-pgvector.sh npx tsx --test \"tests/*.test.ts\""
42
+ }
6
43
  }