@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 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_SYNC_INTERVAL_MS` 时,调度与 Lab 的 `amadeus-pubg-telemetry-hourly` 相同:每小时第 5 分(`PUBLIC_SYNC_TIMEZONE` 默认 `Asia/Shanghai`,`PUBLIC_SYNC_HOURLY_MINUTE` 可改)刷新玩家列表,只拉本地没有的新比赛,并为新对局或到期重试对局取遥测(`maxMatches=500`、`maxFetches=20`、并发 2)。空闲时最多每分钟看一眼队列,所以新登记的小队不用等整点;这一眼不打 PUBG。设置 `PUBLIC_SYNC_INTERVAL_MS` 则改回固定间隔。
19
+
20
+ 其余环境变量(均有默认值):`PUBLIC_PUBG_REQUESTS_PER_MINUTE`、`PUBLIC_SYNC_MAX_MATCHES`、`PUBLIC_SYNC_MAX_TELEMETRY_FETCHES`、`PUBLIC_SYNC_TEAM_CONCURRENCY`、`PUBLIC_SYNC_LEASE_MS`、`PUBG_SAAS_WORKER_METRICS_PORT`。可选 `PUBLIC_TELEMETRY_ARCHIVE_DIR`:设置后,下载的原始遥测先落入该目录(必须在进程工作目录之外;`RawTelemetryArchive`,gzip、按 Match ID、校验 SHA-256)。提问侧要把同一个目录传给 `PubgDomainService` 的 `rawTelemetryArchive`。不设置则特征缓存未命中时仍向遥测 CDN 取原始文件。先用 `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,25 @@
1
+ /** Lab's `amadeus-pubg-telemetry-hourly` cron: minute 5 of every hour, Asia/Shanghai. */
2
+ export declare const HOURLY_PREFETCH_MINUTE = 5;
3
+ export declare const HOURLY_PREFETCH_TIMEZONE = "Asia/Shanghai";
4
+ /** How often an idle worker looks for a newly linked team. Those jobs are already due; this does not call PUBG. */
5
+ export declare const HOURLY_PREFETCH_IDLE_POLL_MS = 60000;
6
+ export interface HourlyPrefetchClock {
7
+ timeZone?: string;
8
+ minute?: number;
9
+ }
10
+ /** Milliseconds until the next minute-:MM slot strictly after `now`. */
11
+ export declare function nextHourlyPrefetchDelayMs(now: Date, clock?: HourlyPrefetchClock): number;
12
+ /** Queue delay accepted by the sync job table: at least one second, at most one day. */
13
+ export declare function clampSyncDelayMs(delayMs: number): number;
14
+ /**
15
+ * Fixed interval when the operator set one. Otherwise sleep only until the next hourly slot,
16
+ * but wake at least once a minute so a newly linked team (already marked due) is not left waiting.
17
+ */
18
+ export declare function syncCyclePauseMs(options: {
19
+ hourly: boolean;
20
+ intervalMs: number;
21
+ now: Date;
22
+ timeZone?: string;
23
+ minute?: number;
24
+ idlePollMs?: number;
25
+ }): number;
@@ -0,0 +1,76 @@
1
+ /** Lab's `amadeus-pubg-telemetry-hourly` cron: minute 5 of every hour, Asia/Shanghai. */
2
+ export const HOURLY_PREFETCH_MINUTE = 5;
3
+ export const HOURLY_PREFETCH_TIMEZONE = 'Asia/Shanghai';
4
+ /** How often an idle worker looks for a newly linked team. Those jobs are already due; this does not call PUBG. */
5
+ export const HOURLY_PREFETCH_IDLE_POLL_MS = 60_000;
6
+ const MIN_SYNC_DELAY_MS = 1_000;
7
+ const MAX_SYNC_DELAY_MS = 24 * 60 * 60_000;
8
+ function zonedParts(instant, timeZone) {
9
+ const names = new Intl.DateTimeFormat('en-US', {
10
+ timeZone,
11
+ hourCycle: 'h23',
12
+ year: 'numeric',
13
+ month: '2-digit',
14
+ day: '2-digit',
15
+ hour: '2-digit',
16
+ minute: '2-digit',
17
+ second: '2-digit',
18
+ }).formatToParts(instant);
19
+ const value = (type) => Number(names.find((part) => part.type === type)?.value);
20
+ const hour = value('hour');
21
+ return {
22
+ year: value('year'),
23
+ month: value('month'),
24
+ day: value('day'),
25
+ hour: hour === 24 ? 0 : hour,
26
+ minute: value('minute'),
27
+ second: value('second'),
28
+ };
29
+ }
30
+ function offsetMs(instant, timeZone) {
31
+ const parts = zonedParts(instant, timeZone);
32
+ return Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second) - instant.getTime();
33
+ }
34
+ function zonedToUtc(year, month, day, hour, minute, timeZone) {
35
+ const guess = new Date(Date.UTC(year, month - 1, day, hour, minute, 0));
36
+ const corrected = new Date(guess.getTime() - offsetMs(guess, timeZone));
37
+ return new Date(guess.getTime() - offsetMs(corrected, timeZone));
38
+ }
39
+ /** Milliseconds until the next minute-:MM slot strictly after `now`. */
40
+ export function nextHourlyPrefetchDelayMs(now, clock = {}) {
41
+ const timeZone = clock.timeZone?.trim() || HOURLY_PREFETCH_TIMEZONE;
42
+ const minute = clock.minute ?? HOURLY_PREFETCH_MINUTE;
43
+ if (!Number.isInteger(minute) || minute < 0 || minute > 59)
44
+ throw new Error('public_sync_hourly_minute_invalid');
45
+ let local;
46
+ try {
47
+ local = zonedParts(now, timeZone);
48
+ }
49
+ catch {
50
+ throw new Error('public_sync_hourly_timezone_invalid');
51
+ }
52
+ const thisHour = zonedToUtc(local.year, local.month, local.day, local.hour, minute, timeZone);
53
+ const target = thisHour.getTime() > now.getTime()
54
+ ? thisHour
55
+ : zonedToUtc(local.year, local.month, local.day, local.hour + 1, minute, timeZone);
56
+ const delay = target.getTime() - now.getTime();
57
+ if (!Number.isFinite(delay) || delay <= 0)
58
+ throw new Error('public_sync_hourly_clock_invalid');
59
+ return delay;
60
+ }
61
+ /** Queue delay accepted by the sync job table: at least one second, at most one day. */
62
+ export function clampSyncDelayMs(delayMs) {
63
+ return Math.min(MAX_SYNC_DELAY_MS, Math.max(MIN_SYNC_DELAY_MS, Math.trunc(delayMs)));
64
+ }
65
+ /**
66
+ * Fixed interval when the operator set one. Otherwise sleep only until the next hourly slot,
67
+ * but wake at least once a minute so a newly linked team (already marked due) is not left waiting.
68
+ */
69
+ export function syncCyclePauseMs(options) {
70
+ if (!options.hourly)
71
+ return options.intervalMs;
72
+ return Math.min(options.idlePollMs ?? HOURLY_PREFETCH_IDLE_POLL_MS, nextHourlyPrefetchDelayMs(options.now, {
73
+ ...(options.timeZone ? { timeZone: options.timeZone } : {}),
74
+ ...(options.minute !== undefined ? { minute: options.minute } : {}),
75
+ }));
76
+ }
@@ -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,59 @@
1
+ import { type RawTelemetryArchivePort } from '@rine-kit/pubg-domain/core';
2
+ import type { Pool } from 'pg';
3
+ import type { PublicPubgAdmission } from './request-limiter.js';
4
+ import { type PublicSyncQueueSnapshot } from '@rine-kit/pubg-postgres';
5
+ export interface PublicSyncCycleResult {
6
+ teamsDiscovered: number;
7
+ teamsAttempted: number;
8
+ teamsCompleted: number;
9
+ teamsFailed: number;
10
+ matchesDiscovered: number;
11
+ telemetryFetched: number;
12
+ telemetryUnavailable: number;
13
+ }
14
+ export interface PublicSyncWorkerOptions {
15
+ apiKey: string;
16
+ admission: PublicPubgAdmission;
17
+ fetchImpl?: typeof fetch;
18
+ now?: () => Date;
19
+ maxMatches?: number;
20
+ maxTelemetryFetches?: number;
21
+ telemetryConcurrency?: number;
22
+ teamConcurrency?: number;
23
+ syncIntervalMs?: number;
24
+ leaseMs?: number;
25
+ /** Where raw telemetry files are kept once downloaded, so any process (this worker, the AI that answers
26
+ * questions) reads a match's telemetry from disk instead of fetching it again. Optional. */
27
+ rawTelemetryArchive?: RawTelemetryArchivePort;
28
+ /** When set, a finished team is scheduled with this delay instead of `syncIntervalMs`.
29
+ * Lab's hourly prefetch uses the delay until the next minute-5 slot. */
30
+ nextSyncDelayMs?: (now: Date) => number;
31
+ onTeamError?: (code: 'public_sync_team_invalid' | 'public_sync_team_failed') => void;
32
+ }
33
+ /** Restricts the worker to official public PUBG API and telemetry endpoints.
34
+ * Rate-limited player discovery uses shared admission; match details follow the
35
+ * provider's unmetered endpoint policy. Public telemetry CDN objects never
36
+ * receive the API key. Redirects are rejected. */
37
+ export declare function createPublicSyncFetch(admission: PublicPubgAdmission, fetchImpl?: typeof fetch): typeof fetch;
38
+ /** Independent public-SaaS ingestion process. It loads only registered SaaS
39
+ * rosters, syncs them through the shared PUBG Domain and writes to PG through
40
+ * the tenant/team scoped repository. */
41
+ export declare class PublicSyncWorker {
42
+ private readonly pool;
43
+ private readonly client;
44
+ private readonly telemetryDownloader;
45
+ private readonly now;
46
+ private readonly maxMatches;
47
+ private readonly maxTelemetryFetches;
48
+ private readonly telemetryConcurrency;
49
+ private readonly teamConcurrency;
50
+ private readonly syncIntervalMs;
51
+ private readonly nextSyncDelayMs;
52
+ private readonly leaseMs;
53
+ private readonly queue;
54
+ constructor(pool: Pool, options: PublicSyncWorkerOptions);
55
+ private readonly onTeamError;
56
+ runOnce(signal?: AbortSignal): Promise<PublicSyncCycleResult>;
57
+ getQueueSnapshot(): Promise<PublicSyncQueueSnapshot>;
58
+ private processJob;
59
+ }