@rine-kit/pubg-sync 0.1.1 → 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/README.md CHANGED
@@ -15,9 +15,9 @@ PUBG 数据同步:团队同步 worker、玩家名解析、官方 API 额度准
15
15
  DATABASE_URL=postgres://... PUBLIC_PUBG_API_KEY=... node dist/worker-main.js --apply [--once]
16
16
  ```
17
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`)建好库表。
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
21
 
22
22
  ## 测试
23
23
 
@@ -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
+ }
@@ -1,3 +1,4 @@
1
+ import { type RawTelemetryArchivePort } from '@rine-kit/pubg-domain/core';
1
2
  import type { Pool } from 'pg';
2
3
  import type { PublicPubgAdmission } from './request-limiter.js';
3
4
  import { type PublicSyncQueueSnapshot } from '@rine-kit/pubg-postgres';
@@ -21,6 +22,12 @@ export interface PublicSyncWorkerOptions {
21
22
  teamConcurrency?: number;
22
23
  syncIntervalMs?: number;
23
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;
24
31
  onTeamError?: (code: 'public_sync_team_invalid' | 'public_sync_team_failed') => void;
25
32
  }
26
33
  /** Restricts the worker to official public PUBG API and telemetry endpoints.
@@ -41,6 +48,7 @@ export declare class PublicSyncWorker {
41
48
  private readonly telemetryConcurrency;
42
49
  private readonly teamConcurrency;
43
50
  private readonly syncIntervalMs;
51
+ private readonly nextSyncDelayMs;
44
52
  private readonly leaseMs;
45
53
  private readonly queue;
46
54
  constructor(pool: Pool, options: PublicSyncWorkerOptions);
@@ -170,6 +170,7 @@ export class PublicSyncWorker {
170
170
  telemetryConcurrency;
171
171
  teamConcurrency;
172
172
  syncIntervalMs;
173
+ nextSyncDelayMs;
173
174
  leaseMs;
174
175
  queue;
175
176
  constructor(pool, options) {
@@ -181,6 +182,7 @@ export class PublicSyncWorker {
181
182
  this.telemetryConcurrency = boundedInteger(options.telemetryConcurrency ?? DEFAULT_TELEMETRY_CONCURRENCY, DEFAULT_TELEMETRY_CONCURRENCY, 1, 4);
182
183
  this.teamConcurrency = boundedInteger(options.teamConcurrency ?? DEFAULT_TEAM_CONCURRENCY, DEFAULT_TEAM_CONCURRENCY, 1, 16);
183
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;
184
186
  this.leaseMs = boundedInteger(options.leaseMs ?? 120_000, 120_000, 1_000, 15 * 60_000);
185
187
  this.queue = new PublicSyncQueue(pool, { leaseMs: this.leaseMs });
186
188
  this.now = options.now ?? (() => new Date());
@@ -194,6 +196,7 @@ export class PublicSyncWorker {
194
196
  baseUrl: API_ORIGIN,
195
197
  timeoutMs: 60_000,
196
198
  fetchImpl,
199
+ ...(options.rawTelemetryArchive ? { archive: options.rawTelemetryArchive } : {}),
197
200
  });
198
201
  this.onTeamError = options.onTeamError ?? (() => undefined);
199
202
  }
@@ -271,7 +274,8 @@ export class PublicSyncWorker {
271
274
  trigger: 'hourly',
272
275
  signal: stopIfLeaseLost.signal,
273
276
  });
274
- if (stopIfLeaseLost.signal.aborted || !await this.queue.complete(job, this.syncIntervalMs)) {
277
+ const delayMs = this.nextSyncDelayMs ? this.nextSyncDelayMs(this.now()) : this.syncIntervalMs;
278
+ if (stopIfLeaseLost.signal.aborted || !await this.queue.complete(job, delayMs)) {
275
279
  return { ok: false, invalid: false };
276
280
  }
277
281
  return { ok: true, telemetry: telemetryRun(result.data) };
@@ -1,5 +1,8 @@
1
1
  import { pathToFileURL } from 'node:url';
2
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';
3
6
  import { PublicSyncWorker } from './sync-worker.js';
4
7
  import { PostgresPublicPubgAdmission } from './request-limiter.js';
5
8
  import { configurePublicEgress } from './public-egress.js';
@@ -7,6 +10,14 @@ import { startWorkerHealthServer, startWorkerMetricsServer, stopWorkerHealthServ
7
10
  import { createPublicSyncCycleLog } from './worker-alerts.js';
8
11
  import { PublicSyncWorkerMetrics } from './worker-metrics.js';
9
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
+ }
10
21
  function positiveInteger(value, fallback, maximum) {
11
22
  if (value === undefined || value.trim() === '')
12
23
  return fallback;
@@ -50,11 +61,18 @@ export async function publicSyncWorkerMain(args, env = process.env) {
50
61
  if (!['postgres:', 'postgresql:'].includes(parsed.protocol))
51
62
  throw new Error('pubg_saas_database_url_invalid');
52
63
  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);
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 });
54
71
  const maxMatches = positiveInteger(env.PUBLIC_SYNC_MAX_MATCHES, 500, 1000);
55
72
  const maxTelemetryFetches = positiveInteger(env.PUBLIC_SYNC_MAX_TELEMETRY_FETCHES, 20, 50);
56
73
  const teamConcurrency = positiveInteger(env.PUBLIC_SYNC_TEAM_CONCURRENCY, 2, 16);
57
74
  const leaseMs = positiveInteger(env.PUBLIC_SYNC_LEASE_MS, 120_000, 15 * 60_000);
75
+ const archiveDirectory = env.PUBLIC_TELEMETRY_ARCHIVE_DIR?.trim() || undefined;
58
76
  const pool = new Pool({ connectionString: databaseUrl, max: 4, connectionTimeoutMillis: 5000, idleTimeoutMillis: 10000, statement_timeout: 30_000 });
59
77
  const stop = new AbortController();
60
78
  const metrics = new PublicSyncWorkerMetrics();
@@ -85,6 +103,8 @@ export async function publicSyncWorkerMain(args, env = process.env) {
85
103
  teamConcurrency,
86
104
  syncIntervalMs: intervalMs,
87
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 })) } : {}),
88
108
  onTeamError: code => process.stderr.write(`${code}\n`),
89
109
  });
90
110
  do {
@@ -111,7 +131,7 @@ export async function publicSyncWorkerMain(args, env = process.env) {
111
131
  process.stdout.write(`${JSON.stringify(cycleLog)}\n`);
112
132
  if (once || stop.signal.aborted)
113
133
  break;
114
- await wait(intervalMs, stop.signal);
134
+ await wait(syncCyclePauseMs({ hourly, intervalMs, now: new Date(), timeZone, minute }), stop.signal);
115
135
  } while (!stop.signal.aborted);
116
136
  }
117
137
  finally {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rine-kit/pubg-sync",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "type": "module",
5
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
6
  "license": "MIT",
@@ -20,8 +20,9 @@
20
20
  "dependencies": {
21
21
  "pg": "^8.13.0",
22
22
  "undici": "^8.10.2",
23
- "@rine-kit/pubg-domain": "0.1.1",
24
- "@rine-kit/pubg-postgres": "0.1.1"
23
+ "@rine-kit/pubg-domain": "0.1.2",
24
+ "@rine-kit/pubg-intelligence": "0.1.2",
25
+ "@rine-kit/pubg-postgres": "0.1.2"
25
26
  },
26
27
  "devDependencies": {
27
28
  "@types/node": "^26.6.5",