@rine-kit/pubg-sync 0.1.5 → 0.1.7

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
@@ -17,7 +17,7 @@ DATABASE_URL=postgres://... PUBLIC_PUBG_API_KEY=... node dist/worker-main.js --a
17
17
 
18
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
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`)建好库表。
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_SYNC_HEALTH_PORT`(默认 8081)、`PUBLIC_SYNC_CATCHUP_MS`(每小时模式下遥测有积压时多久后再跑,默认 300000,0 关闭)。可选 `PUBLIC_TELEMETRY_ARCHIVE_DIR`:设置后,下载的原始遥测先落入该目录(必须在进程工作目录之外;`RawTelemetryArchive`,gzip、按 Match ID、校验 SHA-256)。提问侧要把同一个目录传给 `PubgDomainService` 的 `rawTelemetryArchive`。不设置则特征缓存未命中时仍向遥测 CDN 取原始文件。worker 启动时会自己执行 `migratePubgDatabase`(`@rine-kit/pubg-postgres`,幂等、带咨询锁),不依赖宿主 API 先迁移;宿主照常可以在自己启动时迁移。
21
21
 
22
22
  ## 测试
23
23
 
@@ -28,6 +28,9 @@ export interface PublicSyncWorkerOptions {
28
28
  /** When set, a finished team is scheduled with this delay instead of `syncIntervalMs`.
29
29
  * Lab's hourly prefetch uses the delay until the next minute-5 slot. */
30
30
  nextSyncDelayMs?: (now: Date) => number;
31
+ /** When a finished team still has telemetry waiting for a later run (more candidates than `maxTelemetryFetches`),
32
+ * schedule it again after this delay instead of at the normal slot, until the backlog is gone. Unset: off. */
33
+ catchupDelayMs?: number;
31
34
  onTeamError?: (code: 'public_sync_team_invalid' | 'public_sync_team_failed') => void;
32
35
  }
33
36
  /** Restricts the worker to official public PUBG API and telemetry endpoints.
@@ -35,6 +38,33 @@ export interface PublicSyncWorkerOptions {
35
38
  * provider's unmetered endpoint policy. Public telemetry CDN objects never
36
39
  * receive the API key. Redirects are rejected. */
37
40
  export declare function createPublicSyncFetch(admission: PublicPubgAdmission, fetchImpl?: typeof fetch): typeof fetch;
41
+ export type SyncTeamResult = {
42
+ status: 'synced';
43
+ telemetry: {
44
+ discovered: number;
45
+ fetched: number;
46
+ unavailable: number;
47
+ deferred: number;
48
+ };
49
+ }
50
+ /** Another process was already syncing the team; it had finished when this returned. */
51
+ | {
52
+ status: 'joined';
53
+ }
54
+ /** Another process still held the team when the wait ran out. */
55
+ | {
56
+ status: 'busy';
57
+ } | {
58
+ status: 'failed';
59
+ invalid: boolean;
60
+ } | {
61
+ status: 'unknown_team';
62
+ };
63
+ export interface SyncTeamOptions {
64
+ signal?: AbortSignal;
65
+ /** How long to wait for a worker that is already syncing the team. Default 0 (do not wait). */
66
+ waitMs?: number;
67
+ }
38
68
  /** Independent public-SaaS ingestion process. It loads only registered SaaS
39
69
  * rosters, syncs them through the shared PUBG Domain and writes to PG through
40
70
  * the tenant/team scoped repository. */
@@ -49,11 +79,23 @@ export declare class PublicSyncWorker {
49
79
  private readonly teamConcurrency;
50
80
  private readonly syncIntervalMs;
51
81
  private readonly nextSyncDelayMs;
82
+ private readonly catchupDelayMs;
52
83
  private readonly leaseMs;
53
84
  private readonly queue;
54
85
  constructor(pool: Pool, options: PublicSyncWorkerOptions);
55
86
  private readonly onTeamError;
56
87
  runOnce(signal?: AbortSignal): Promise<PublicSyncCycleResult>;
57
88
  getQueueSnapshot(): Promise<PublicSyncQueueSnapshot>;
89
+ /** Syncs one team now, due or not, through the same job (lease, heartbeat, schedule) the hourly run uses, so it
90
+ * never works in parallel with a worker on the same team. Where a live lease already holds the team it waits
91
+ * (up to `waitMs`) for that run to finish instead of starting a second one. */
92
+ syncTeam(tenantId: string, teamId: string, options?: SyncTeamOptions): Promise<SyncTeamResult>;
58
93
  private processJob;
59
94
  }
95
+ export interface SyncTeamNowOptions extends PublicSyncWorkerOptions, SyncTeamOptions {
96
+ tenantId: string;
97
+ teamId: string;
98
+ }
99
+ /** Syncs one team right now (a host calls it when a question arrives for a team whose data is behind). Same job,
100
+ * lease and schedule as the worker; see `PublicSyncWorker.syncTeam`. */
101
+ export declare function syncTeamNow(pool: Pool, options: SyncTeamNowOptions): Promise<SyncTeamResult>;
@@ -144,9 +144,9 @@ function numberFrom(value) {
144
144
  const result = Number(value);
145
145
  return Number.isFinite(result) && result >= 0 ? Math.trunc(result) : 0;
146
146
  }
147
- function telemetryRun(value) {
147
+ function telemetryRun(value, maxFetches) {
148
148
  if (!value || typeof value !== 'object' || Array.isArray(value))
149
- return { discovered: 0, fetched: 0, unavailable: 0 };
149
+ return { discovered: 0, fetched: 0, unavailable: 0, deferred: 0 };
150
150
  const data = value;
151
151
  const run = data.run && typeof data.run === 'object' && !Array.isArray(data.run)
152
152
  ? data.run
@@ -155,6 +155,8 @@ function telemetryRun(value) {
155
155
  discovered: numberFrom(run.discoveredMatchCount),
156
156
  fetched: numberFrom(run.fetchedCount),
157
157
  unavailable: numberFrom(run.unavailableCount),
158
+ // Candidates beyond this run's fetch budget were marked PENDING and wait for the next run.
159
+ deferred: Math.max(0, numberFrom(run.candidateMatchCount) - maxFetches),
158
160
  };
159
161
  }
160
162
  /** Independent public-SaaS ingestion process. It loads only registered SaaS
@@ -171,6 +173,7 @@ export class PublicSyncWorker {
171
173
  teamConcurrency;
172
174
  syncIntervalMs;
173
175
  nextSyncDelayMs;
176
+ catchupDelayMs;
174
177
  leaseMs;
175
178
  queue;
176
179
  constructor(pool, options) {
@@ -183,6 +186,9 @@ export class PublicSyncWorker {
183
186
  this.teamConcurrency = boundedInteger(options.teamConcurrency ?? DEFAULT_TEAM_CONCURRENCY, DEFAULT_TEAM_CONCURRENCY, 1, 16);
184
187
  this.syncIntervalMs = boundedInteger(options.syncIntervalMs ?? DEFAULT_SYNC_INTERVAL_MS, DEFAULT_SYNC_INTERVAL_MS, 1_000, 24 * 60 * 60_000);
185
188
  this.nextSyncDelayMs = options.nextSyncDelayMs;
189
+ this.catchupDelayMs = options.catchupDelayMs === undefined
190
+ ? undefined
191
+ : boundedInteger(options.catchupDelayMs, 1_000, 1_000, 24 * 60 * 60_000);
186
192
  this.leaseMs = boundedInteger(options.leaseMs ?? 120_000, 120_000, 1_000, 15 * 60_000);
187
193
  this.queue = new PublicSyncQueue(pool, { leaseMs: this.leaseMs });
188
194
  this.now = options.now ?? (() => new Date());
@@ -238,8 +244,40 @@ export class PublicSyncWorker {
238
244
  getQueueSnapshot() {
239
245
  return this.queue.getSnapshot();
240
246
  }
241
- async processJob(job) {
247
+ /** Syncs one team now, due or not, through the same job (lease, heartbeat, schedule) the hourly run uses, so it
248
+ * never works in parallel with a worker on the same team. Where a live lease already holds the team it waits
249
+ * (up to `waitMs`) for that run to finish instead of starting a second one. */
250
+ async syncTeam(tenantId, teamId, options = {}) {
251
+ const deadline = Date.now() + Math.max(0, options.waitMs ?? 0);
252
+ for (;;) {
253
+ if (options.signal?.aborted)
254
+ return { status: 'failed', invalid: false };
255
+ const job = await this.queue.claimTeam(tenantId, teamId);
256
+ if (job) {
257
+ const result = await this.processJob(job, options.signal);
258
+ if (result.ok)
259
+ return { status: 'synced', telemetry: result.telemetry };
260
+ this.onTeamError(result.invalid ? 'public_sync_team_invalid' : 'public_sync_team_failed');
261
+ return { status: 'failed', invalid: result.invalid };
262
+ }
263
+ const state = await this.queue.leaseState(tenantId, teamId);
264
+ if (state === 'unknown')
265
+ return { status: 'unknown_team' };
266
+ if (state === 'free')
267
+ continue; // released between the claim and this read
268
+ if (Date.now() >= deadline)
269
+ return { status: 'busy' };
270
+ while (Date.now() < deadline && !options.signal?.aborted && await this.queue.leaseState(tenantId, teamId) === 'leased') {
271
+ await new Promise((resolve) => setTimeout(resolve, 500));
272
+ }
273
+ if (Date.now() >= deadline && await this.queue.leaseState(tenantId, teamId) === 'leased')
274
+ return { status: 'busy' };
275
+ return { status: 'joined' };
276
+ }
277
+ }
278
+ async processJob(job, outer) {
242
279
  const stopIfLeaseLost = new AbortController();
280
+ const stop = outer ? AbortSignal.any([stopIfLeaseLost.signal, outer]) : stopIfLeaseLost.signal;
243
281
  let renewalInFlight = false;
244
282
  const heartbeat = setInterval(() => {
245
283
  if (renewalInFlight)
@@ -272,13 +310,17 @@ export class PublicSyncWorker {
272
310
  maxFetches: this.maxTelemetryFetches,
273
311
  concurrency: this.telemetryConcurrency,
274
312
  trigger: 'hourly',
275
- signal: stopIfLeaseLost.signal,
313
+ signal: stop,
276
314
  });
277
- const delayMs = this.nextSyncDelayMs ? this.nextSyncDelayMs(this.now()) : this.syncIntervalMs;
278
- if (stopIfLeaseLost.signal.aborted || !await this.queue.complete(job, delayMs)) {
315
+ const telemetry = telemetryRun(result.data, this.maxTelemetryFetches);
316
+ const regularDelayMs = this.nextSyncDelayMs ? this.nextSyncDelayMs(this.now()) : this.syncIntervalMs;
317
+ const delayMs = this.catchupDelayMs !== undefined && telemetry.deferred > 0
318
+ ? Math.min(this.catchupDelayMs, regularDelayMs)
319
+ : regularDelayMs;
320
+ if (stop.aborted || !await this.queue.complete(job, delayMs)) {
279
321
  return { ok: false, invalid: false };
280
322
  }
281
- return { ok: true, telemetry: telemetryRun(result.data) };
323
+ return { ok: true, telemetry };
282
324
  }
283
325
  catch (error) {
284
326
  const invalid = error instanceof InvalidTeamError;
@@ -290,3 +332,12 @@ export class PublicSyncWorker {
290
332
  }
291
333
  }
292
334
  }
335
+ /** Syncs one team right now (a host calls it when a question arrives for a team whose data is behind). Same job,
336
+ * lease and schedule as the worker; see `PublicSyncWorker.syncTeam`. */
337
+ export async function syncTeamNow(pool, options) {
338
+ const { tenantId, teamId, signal, waitMs, ...workerOptions } = options;
339
+ return new PublicSyncWorker(pool, workerOptions).syncTeam(tenantId, teamId, {
340
+ ...(signal ? { signal } : {}),
341
+ ...(waitMs !== undefined ? { waitMs } : {}),
342
+ });
343
+ }
@@ -1,5 +1,6 @@
1
1
  import { pathToFileURL } from 'node:url';
2
2
  import { Pool } from 'pg';
3
+ import { migratePubgDatabase } from '@rine-kit/pubg-postgres';
3
4
  import { assertArchiveOutsideRepository } from '@rine-kit/pubg-intelligence/backfill';
4
5
  import { RawTelemetryArchive } from '@rine-kit/pubg-intelligence/archive';
5
6
  import { clampSyncDelayMs, HOURLY_PREFETCH_MINUTE, HOURLY_PREFETCH_TIMEZONE, nextHourlyPrefetchDelayMs, syncCyclePauseMs, } from './hourly-prefetch.js';
@@ -71,6 +72,9 @@ export async function publicSyncWorkerMain(args, env = process.env) {
71
72
  const maxMatches = positiveInteger(env.PUBLIC_SYNC_MAX_MATCHES, 500, 1000);
72
73
  const maxTelemetryFetches = positiveInteger(env.PUBLIC_SYNC_MAX_TELEMETRY_FETCHES, 20, 50);
73
74
  const teamConcurrency = positiveInteger(env.PUBLIC_SYNC_TEAM_CONCURRENCY, 2, 16);
75
+ const catchupRaw = env.PUBLIC_SYNC_CATCHUP_MS?.trim();
76
+ // Hourly mode only: a team with telemetry still waiting is run again after this long (default 5 minutes; 0 = off).
77
+ const catchupDelayMs = hourly && catchupRaw !== '0' ? positiveInteger(catchupRaw, 5 * 60_000, 60 * 60_000) : undefined;
74
78
  const leaseMs = positiveInteger(env.PUBLIC_SYNC_LEASE_MS, 120_000, 15 * 60_000);
75
79
  const archiveDirectory = env.PUBLIC_TELEMETRY_ARCHIVE_DIR?.trim() || undefined;
76
80
  const pool = new Pool({ connectionString: databaseUrl, max: 4, connectionTimeoutMillis: 5000, idleTimeoutMillis: 10000, statement_timeout: 30_000 });
@@ -82,10 +86,11 @@ export async function publicSyncWorkerMain(args, env = process.env) {
82
86
  process.once('SIGINT', onStop);
83
87
  process.once('SIGTERM', onStop);
84
88
  try {
85
- const ready = await pool.query("SELECT 1 FROM pubg_schema_migrations WHERE migration_id='0001_pubg_schema.sql'");
86
- if (!ready.rowCount)
87
- throw new Error('pubg_saas_schema_upgrade_required');
88
- healthServer = await startWorkerHealthServer();
89
+ // The worker brings the schema it needs up to date itself (idempotent, serialised by an advisory lock), so it
90
+ // never depends on another process (the host API) having migrated first, and a deploy that starts both at
91
+ // once does not leave it crash-looping until the API is done.
92
+ await migratePubgDatabase(pool);
93
+ healthServer = await startWorkerHealthServer(positiveInteger(env.PUBLIC_SYNC_HEALTH_PORT, 8081, 65_535));
89
94
  const metricsPort = positiveInteger(env.PUBG_SAAS_WORKER_METRICS_PORT, 9464, 65_535);
90
95
  metricsServer = await startWorkerMetricsServer(() => {
91
96
  const memory = process.memoryUsage();
@@ -104,6 +109,7 @@ export async function publicSyncWorkerMain(args, env = process.env) {
104
109
  syncIntervalMs: intervalMs,
105
110
  leaseMs,
106
111
  ...(archiveDirectory ? { rawTelemetryArchive: new RawTelemetryArchive(await assertArchiveOutsideRepository(archiveDirectory, env.PUBLIC_SYNC_REPOSITORY_ROOT?.trim() || process.cwd())) } : {}),
112
+ ...(catchupDelayMs !== undefined ? { catchupDelayMs } : {}),
107
113
  ...(hourly ? { nextSyncDelayMs: (now) => clampSyncDelayMs(nextHourlyPrefetchDelayMs(now, { timeZone, minute })) } : {}),
108
114
  onTeamError: code => process.stderr.write(`${code}\n`),
109
115
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rine-kit/pubg-sync",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
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,9 +20,9 @@
20
20
  "dependencies": {
21
21
  "pg": "^8.13.0",
22
22
  "undici": "^8.10.2",
23
- "@rine-kit/pubg-domain": "0.1.5",
24
- "@rine-kit/pubg-intelligence": "0.1.5",
25
- "@rine-kit/pubg-postgres": "0.1.5"
23
+ "@rine-kit/pubg-domain": "0.1.7",
24
+ "@rine-kit/pubg-intelligence": "0.1.7",
25
+ "@rine-kit/pubg-postgres": "0.1.7"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.6.5",