@rine-kit/pubg-postgres 0.1.4 → 0.1.6

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/dist/migrate.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { readFile } from 'node:fs/promises';
2
- const MIGRATIONS = ['0001_pubg_schema.sql', '0002_pubg_account_claims.sql', '0003_review_shares.sql'];
2
+ const MIGRATIONS = ['0001_pubg_schema.sql', '0002_pubg_account_claims.sql', '0003_review_shares.sql', '0004_sync_job_dirty.sql'];
3
3
  const LOCK_ID = 7192041303;
4
4
  /** Applies the schema to an empty or existing database; safe to run on every start. */
5
5
  export async function migratePubgDatabase(pool) {
@@ -1,5 +1,6 @@
1
1
  import { createTeamContext } from '@rine-kit/pubg-domain/core';
2
2
  import { MAX_TEAM_ROSTER_SIZE } from './contracts/team-roster.js';
3
+ import { requeueTeamJob } from './sync-queue.js';
3
4
  const SHARDS = new Set(['steam', 'kakao', 'psn', 'xbox']);
4
5
  async function transaction(pool, work) {
5
6
  const client = await pool.connect();
@@ -63,9 +64,7 @@ export class PostgresPubgRosterStore {
63
64
  ON CONFLICT DO NOTHING`, [input.tenantId, input.teamId, input.accountId, input.actorId]);
64
65
  await client.query(`INSERT INTO pubg_account_claims(tenant_id,team_id,actor_id,pubg_shard,pubg_account_id)
65
66
  VALUES ($1,$2,$3,$4,$5)`, [input.tenantId, input.teamId, input.actorId, input.shard, input.accountId]);
66
- await client.query(`INSERT INTO pubg_sync_jobs(tenant_id,team_id) VALUES ($1,$2)
67
- ON CONFLICT (tenant_id,team_id) DO UPDATE SET next_attempt_at=now(), updated_at=now()
68
- WHERE pubg_sync_jobs.lease_token IS NULL`, [input.tenantId, input.teamId]);
67
+ await requeueTeamJob(client, input.tenantId, input.teamId);
69
68
  });
70
69
  }
71
70
  /** Removes the actor's claim and roster entry; the team disappears with its last member. */
@@ -19,6 +19,10 @@ export interface PublicSyncQueueSnapshot {
19
19
  retryingJobs: number;
20
20
  oldestDueAgeSeconds: number | null;
21
21
  }
22
+ type Queryable = Pick<Pool, 'query'>;
23
+ /** Makes the team's job due now. While a worker holds a live lease the job keeps its schedule but is marked
24
+ * dirty, so completing that lease runs the team again right away. Creates the job row when the team has none. */
25
+ export declare function requeueTeamJob(db: Queryable, tenantId: string, teamId: string): Promise<void>;
22
26
  /** Durable, team-scoped scheduling for the independent public SaaS worker.
23
27
  * Queue rows are keyed and cascaded by (tenant_id, team_id); each claim uses a
24
28
  * per-job fencing token so expired workers cannot complete a newer lease. */
@@ -35,6 +39,12 @@ export declare class PublicSyncQueue {
35
39
  getSnapshot(): Promise<PublicSyncQueueSnapshot>;
36
40
  /** Claims at most `limit` due teams atomically across all worker processes. */
37
41
  claimDue(limit: number): Promise<PublicSyncJob[]>;
42
+ /** Asks for the team to be synced again soon (a retry, or a new member). Safe while a worker is running it. */
43
+ requeue(tenantId: string, teamId: string): Promise<void>;
44
+ /** Leases one team now, due or not, unless a live lease holds it. Null: the team is unknown or busy. */
45
+ claimTeam(tenantId: string, teamId: string): Promise<PublicSyncJob | null>;
46
+ /** Whether the team exists and a live lease currently holds its job. */
47
+ leaseState(tenantId: string, teamId: string): Promise<'unknown' | 'leased' | 'free'>;
38
48
  renew(job: PublicSyncJob): Promise<boolean>;
39
49
  complete(job: PublicSyncJob, intervalMs: number): Promise<boolean>;
40
50
  /** Failures retain the durable job and use capped exponential retry. Error
@@ -42,3 +52,4 @@ export declare class PublicSyncQueue {
42
52
  * are never persisted in the queue. */
43
53
  fail(job: PublicSyncJob, errorCode: string): Promise<boolean>;
44
54
  }
55
+ export {};
@@ -1,4 +1,14 @@
1
1
  import { randomBytes } from 'node:crypto';
2
+ /** Makes the team's job due now. While a worker holds a live lease the job keeps its schedule but is marked
3
+ * dirty, so completing that lease runs the team again right away. Creates the job row when the team has none. */
4
+ export async function requeueTeamJob(db, tenantId, teamId) {
5
+ await db.query(`INSERT INTO pubg_sync_jobs(tenant_id,team_id) VALUES ($1,$2)
6
+ ON CONFLICT (tenant_id,team_id) DO UPDATE SET
7
+ next_attempt_at=CASE WHEN pubg_sync_jobs.lease_until>now() THEN pubg_sync_jobs.next_attempt_at ELSE now() END,
8
+ dirty_at=CASE WHEN pubg_sync_jobs.lease_until>now() THEN now() ELSE pubg_sync_jobs.dirty_at END,
9
+ last_error_code=CASE WHEN pubg_sync_jobs.lease_until>now() THEN pubg_sync_jobs.last_error_code ELSE NULL END,
10
+ updated_at=now()`, [tenantId, teamId]);
11
+ }
2
12
  async function transaction(pool, work) {
3
13
  const client = await pool.connect();
4
14
  try {
@@ -84,7 +94,7 @@ export class PublicSyncQueue {
84
94
  const leaseToken = randomBytes(24).toString('base64url');
85
95
  const claimed = await client.query(`UPDATE pubg_sync_jobs SET lease_token=$3,
86
96
  lease_until=now()+($4::BIGINT*interval '1 millisecond'),attempt_count=LEAST(attempt_count+1,32767),
87
- updated_at=now() WHERE tenant_id=$1 AND team_id=$2 RETURNING attempt_count`, [candidate.tenant_id, candidate.team_id, leaseToken, this.leaseMs]);
97
+ dirty_at=NULL,updated_at=now() WHERE tenant_id=$1 AND team_id=$2 RETURNING attempt_count`, [candidate.tenant_id, candidate.team_id, leaseToken, this.leaseMs]);
88
98
  if (claimed.rowCount !== 1)
89
99
  throw new Error('public_sync_queue_claim_lost');
90
100
  jobs.push({
@@ -97,6 +107,37 @@ export class PublicSyncQueue {
97
107
  return jobs;
98
108
  });
99
109
  }
110
+ /** Asks for the team to be synced again soon (a retry, or a new member). Safe while a worker is running it. */
111
+ async requeue(tenantId, teamId) {
112
+ await requeueTeamJob(this.pool, tenantId, teamId);
113
+ }
114
+ /** Leases one team now, due or not, unless a live lease holds it. Null: the team is unknown or busy. */
115
+ async claimTeam(tenantId, teamId) {
116
+ return transaction(this.pool, async (client) => {
117
+ await client.query(`INSERT INTO pubg_sync_jobs(tenant_id,team_id)
118
+ SELECT tenant_id,team_id FROM pubg_teams WHERE tenant_id=$1 AND team_id=$2
119
+ ON CONFLICT (tenant_id,team_id) DO NOTHING`, [tenantId, teamId]);
120
+ const leaseToken = randomBytes(24).toString('base64url');
121
+ const claimed = await client.query(`UPDATE pubg_sync_jobs SET lease_token=$3,
122
+ lease_until=now()+($4::BIGINT*interval '1 millisecond'),attempt_count=LEAST(attempt_count+1,32767),
123
+ dirty_at=NULL,updated_at=now()
124
+ WHERE tenant_id=$1 AND team_id=$2 AND (lease_until IS NULL OR lease_until<=now())
125
+ AND EXISTS (SELECT 1 FROM pubg_teams team WHERE team.tenant_id=$1 AND team.team_id=$2)
126
+ RETURNING attempt_count`, [tenantId, teamId, leaseToken, this.leaseMs]);
127
+ if (claimed.rowCount !== 1)
128
+ return null;
129
+ return { tenantId, teamId, leaseToken, attemptCount: Number(claimed.rows[0]?.attempt_count ?? 1) };
130
+ });
131
+ }
132
+ /** Whether the team exists and a live lease currently holds its job. */
133
+ async leaseState(tenantId, teamId) {
134
+ const row = await this.pool.query(`SELECT COALESCE(job.lease_until>now(),false) AS leased
135
+ FROM pubg_teams team LEFT JOIN pubg_sync_jobs job ON job.tenant_id=team.tenant_id AND job.team_id=team.team_id
136
+ WHERE team.tenant_id=$1 AND team.team_id=$2`, [tenantId, teamId]);
137
+ if (!row.rowCount)
138
+ return 'unknown';
139
+ return row.rows[0]?.leased ? 'leased' : 'free';
140
+ }
100
141
  async renew(job) {
101
142
  const result = await this.pool.query(`UPDATE pubg_sync_jobs SET
102
143
  lease_until=now()+($4::BIGINT*interval '1 millisecond'),updated_at=now()
@@ -106,7 +147,9 @@ export class PublicSyncQueue {
106
147
  async complete(job, intervalMs) {
107
148
  boundedInteger(intervalMs, 1_000, 24 * 60 * 60_000);
108
149
  const result = await this.pool.query(`UPDATE pubg_sync_jobs SET lease_token=NULL,lease_until=NULL,
109
- attempt_count=0,last_error_code=NULL,next_attempt_at=now()+($4::BIGINT*interval '1 millisecond'),updated_at=now()
150
+ attempt_count=0,last_error_code=NULL,
151
+ next_attempt_at=CASE WHEN dirty_at IS NOT NULL THEN now() ELSE now()+($4::BIGINT*interval '1 millisecond') END,
152
+ dirty_at=NULL,updated_at=now()
110
153
  WHERE tenant_id=$1 AND team_id=$2 AND lease_token=$3 AND lease_until>now()`, [job.tenantId, job.teamId, job.leaseToken, intervalMs]);
111
154
  return result.rowCount === 1;
112
155
  }
@@ -117,7 +160,9 @@ export class PublicSyncQueue {
117
160
  const code = /^[a-z0-9_]{1,64}$/u.test(errorCode) ? errorCode : 'public_sync_team_failed';
118
161
  const retryMs = Math.min(this.maxRetryMs, this.baseRetryMs * 2 ** Math.min(job.attemptCount - 1, 20));
119
162
  const result = await this.pool.query(`UPDATE pubg_sync_jobs SET lease_token=NULL,lease_until=NULL,
120
- last_error_code=$4,next_attempt_at=now()+($5::BIGINT*interval '1 millisecond'),updated_at=now()
163
+ last_error_code=$4,
164
+ next_attempt_at=CASE WHEN dirty_at IS NOT NULL THEN now() ELSE now()+($5::BIGINT*interval '1 millisecond') END,
165
+ dirty_at=NULL,updated_at=now()
121
166
  WHERE tenant_id=$1 AND team_id=$2 AND lease_token=$3 AND lease_until>now()`, [job.tenantId, job.teamId, job.leaseToken, code, retryMs]);
122
167
  return result.rowCount === 1;
123
168
  }
@@ -0,0 +1,4 @@
1
+ -- A team's roster changed (an account was linked) or a retry was asked for while a worker held the team's
2
+ -- lease. The lease keeps the next-attempt time untouched, so the change used to wait for the next hourly slot.
3
+ -- dirty_at records it; completing the lease then leaves the team due now instead. Additive: older code ignores it.
4
+ ALTER TABLE pubg_sync_jobs ADD COLUMN IF NOT EXISTS dirty_at TIMESTAMPTZ;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rine-kit/pubg-postgres",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "type": "module",
5
5
  "description": "PostgreSQL storage for PUBG team data (matches, telemetry features, sync queue, query sessions) behind @rine-kit/pubg-domain's PubgRepositoryPort. Extracted from Gate; tenancy is a host-supplied scope, no KOOK dependency.",
6
6
  "license": "MIT",
@@ -21,7 +21,7 @@
21
21
  "dependencies": {
22
22
  "pg": "^8.13.0",
23
23
  "zod": "^4.6.7",
24
- "@rine-kit/pubg-domain": "0.1.4"
24
+ "@rine-kit/pubg-domain": "0.1.6"
25
25
  },
26
26
  "devDependencies": {
27
27
  "@types/node": "^26.6.5",