@rine-kit/pubg-postgres 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.
@@ -0,0 +1,485 @@
1
+ import { normalizeRecords, parseTeamContext } from '@rine-kit/pubg-domain/core';
2
+ import { createHash } from 'node:crypto';
3
+ import { parseStoredTeamLeaderboardMetric } from './contracts/team-preferences.js';
4
+ function requiredText(value, name) {
5
+ const normalized = value.trim();
6
+ if (!normalized)
7
+ throw new Error(`invalid_${name}`);
8
+ return normalized;
9
+ }
10
+ function teamConfigHash(team) {
11
+ const canonical = {
12
+ id: team.id,
13
+ label: team.label,
14
+ platform: team.platform,
15
+ players: [...team.players]
16
+ .map(player => ({ id: player.id, name: player.name, aliases: [...player.aliases].sort() }))
17
+ .sort((left, right) => left.id.localeCompare(right.id)),
18
+ };
19
+ return createHash('sha256').update(JSON.stringify(canonical)).digest('hex');
20
+ }
21
+ function number(value, fallback = 0) {
22
+ const parsed = Number(value);
23
+ return Number.isFinite(parsed) ? parsed : fallback;
24
+ }
25
+ function nullableNumber(value) {
26
+ if (value === null || value === undefined || value === '')
27
+ return null;
28
+ const parsed = Number(value);
29
+ return Number.isFinite(parsed) ? parsed : null;
30
+ }
31
+ function boolean(value) {
32
+ return value === true || value === 1 || value === '1';
33
+ }
34
+ function objectValue(value, fallback) {
35
+ if (typeof value === 'string') {
36
+ try {
37
+ return JSON.parse(value);
38
+ }
39
+ catch {
40
+ return fallback;
41
+ }
42
+ }
43
+ return value === null || value === undefined ? fallback : value;
44
+ }
45
+ function rowToPlayer(row) {
46
+ return {
47
+ accountId: String(row.account_id),
48
+ playerName: String(row.player_name ?? row.account_id),
49
+ displayName: String(row.display_name ?? row.player_name ?? row.account_id),
50
+ rank: nullableNumber(row.rank),
51
+ kills: number(row.kills),
52
+ assists: number(row.assists),
53
+ damage: number(row.damage),
54
+ dbnos: number(row.dbnos),
55
+ revives: number(row.revives),
56
+ headshotKills: number(row.headshot_kills),
57
+ survivalTime: number(row.survival_time),
58
+ longestKill: number(row.longest_kill),
59
+ deaths: nullableNumber(row.deaths),
60
+ deathSemantics: String(row.death_semantics ?? 'unknown'),
61
+ };
62
+ }
63
+ function rowToMatch(row, players) {
64
+ return {
65
+ schemaVersion: number(row.schema_version, 3),
66
+ matchId: String(row.match_id),
67
+ shard: String(row.shard ?? 'steam'),
68
+ createdAt: row.created_at === null || row.created_at === undefined ? null : String(row.created_at),
69
+ timestamp: number(row.timestamp_ms),
70
+ matchType: String(row.match_type ?? ''),
71
+ gameMode: String(row.game_mode ?? ''),
72
+ isCompetitive: boolean(row.is_competitive),
73
+ mapName: String(row.map_name ?? ''),
74
+ duration: number(row.duration),
75
+ patchVersion: String(row.patch_version ?? ''),
76
+ players,
77
+ telemetryUrl: row.telemetry_url ? String(row.telemetry_url) : null,
78
+ };
79
+ }
80
+ function runFromRow(row) {
81
+ return {
82
+ runId: String(row.run_id),
83
+ reportDate: String(row.report_date),
84
+ startedAt: new Date(row.started_at).toISOString(),
85
+ finishedAt: new Date(row.finished_at).toISOString(),
86
+ trigger: String(row.trigger),
87
+ discoveredMatchCount: number(row.discovered_match_count),
88
+ newMatchCount: number(row.new_match_count),
89
+ candidateMatchCount: number(row.candidate_match_count),
90
+ fetchedCount: number(row.fetched_count),
91
+ cacheHitCount: number(row.cache_hit_count),
92
+ unavailableCount: number(row.unavailable_count),
93
+ pendingCount: number(row.pending_count),
94
+ failedMatchIds: objectValue(row.failed_match_ids_json, []),
95
+ };
96
+ }
97
+ function attemptFromRow(row) {
98
+ return {
99
+ matchId: String(row.match_id),
100
+ parserVersion: String(row.parser_version),
101
+ featureVersion: String(row.feature_version),
102
+ status: String(row.status),
103
+ attemptCount: number(row.attempt_count),
104
+ lastAttemptedAt: row.last_attempted_at ? new Date(row.last_attempted_at).toISOString() : null,
105
+ nextRetryAt: row.next_retry_at ? new Date(row.next_retry_at).toISOString() : null,
106
+ ...(row.error ? { error: String(row.error) } : {}),
107
+ updatedAt: new Date(row.updated_at).toISOString(),
108
+ };
109
+ }
110
+ async function withTransaction(pool, action) {
111
+ const client = await pool.connect();
112
+ try {
113
+ await client.query('BEGIN');
114
+ const value = await action(client);
115
+ await client.query('COMMIT');
116
+ return value;
117
+ }
118
+ catch (error) {
119
+ try {
120
+ await client.query('ROLLBACK');
121
+ }
122
+ catch { /* preserve the original error */ }
123
+ throw error;
124
+ }
125
+ finally {
126
+ client.release();
127
+ }
128
+ }
129
+ /** PostgreSQL implementation of the PUBG repository port. Its team and optional
130
+ * conversation scopes are fixed from server-verified authorization state. */
131
+ export class PostgresPubgRepository {
132
+ pool;
133
+ options;
134
+ store = 'postgres';
135
+ scope;
136
+ conversation;
137
+ accountIds;
138
+ shard;
139
+ teamConfigHash;
140
+ constructor(pool, scope, conversation = null, options = {}) {
141
+ this.pool = pool;
142
+ this.options = options;
143
+ if (options.requireConversation && !conversation)
144
+ throw new Error('conversation_scope_required');
145
+ this.scope = parseTeamContext(scope);
146
+ this.shard = this.scope.team.platform;
147
+ this.accountIds = this.scope.team.players.map((player) => player.id);
148
+ this.teamConfigHash = teamConfigHash(this.scope.team);
149
+ this.conversation = conversation ? {
150
+ kind: requiredText(conversation.kind, 'conversation_kind'),
151
+ actorId: requiredText(conversation.actorId, 'actor_id'),
152
+ channelId: requiredText(conversation.channelId, 'channel_id'),
153
+ sessionId: requiredText(conversation.sessionId, 'session_id'),
154
+ } : null;
155
+ }
156
+ async assertTeamScope(client) {
157
+ const result = await client.query(`SELECT team.pubg_shard,COALESCE(array_agg(member.pubg_account_id ORDER BY member.pubg_account_id)
158
+ FILTER (WHERE member.pubg_account_id IS NOT NULL),'{}') AS accounts
159
+ FROM pubg_teams team LEFT JOIN pubg_team_members member ON member.tenant_id=team.tenant_id AND member.team_id=team.team_id
160
+ WHERE team.tenant_id=$1 AND team.team_id=$2 GROUP BY team.pubg_shard`, [this.scope.tenantId, this.scope.teamId]);
161
+ const row = result.rows[0];
162
+ if (!row || row.pubg_shard !== this.shard || !Array.isArray(row.accounts)
163
+ || row.accounts.length !== this.accountIds.length || row.accounts.some((account) => !this.accountIds.includes(String(account))))
164
+ throw new Error('repository_team_scope_mismatch');
165
+ }
166
+ async assertReadScope(client) {
167
+ await this.assertTeamScope(client);
168
+ if (this.conversation)
169
+ await this.assertConversation(this.conversation.sessionId, client);
170
+ }
171
+ async assertConversation(sessionId, client) {
172
+ await this.assertTeamScope(client);
173
+ const trusted = this.conversation;
174
+ if (!trusted)
175
+ throw new Error('conversation_scope_required');
176
+ if (sessionId !== trusted.sessionId)
177
+ throw new Error('conversation_scope_mismatch');
178
+ if (this.options.authorize) {
179
+ const team = await client.query('SELECT query_revision FROM pubg_teams WHERE tenant_id=$1 AND team_id=$2', [this.scope.tenantId, this.scope.teamId]);
180
+ await this.options.authorize(client, {
181
+ tenantId: this.scope.tenantId,
182
+ teamId: this.scope.teamId,
183
+ teamRevision: number(team.rows[0]?.query_revision),
184
+ conversation: trusted,
185
+ });
186
+ }
187
+ return trusted;
188
+ }
189
+ /** Lock the team revision and conversation authority until the bounded read
190
+ * finishes. Roster/admin triggers update teams.query_revision, so a revoke
191
+ * either commits before this read (and is rejected) or after it completes. */
192
+ async withReadScope(action) {
193
+ return withTransaction(this.pool, async (client) => {
194
+ const team = await client.query('SELECT query_revision FROM pubg_teams WHERE tenant_id=$1 AND team_id=$2 FOR SHARE', [this.scope.tenantId, this.scope.teamId]);
195
+ if (!team.rowCount)
196
+ throw new Error('repository_team_scope_mismatch');
197
+ await this.assertReadScope(client);
198
+ return action(client);
199
+ });
200
+ }
201
+ async verifyScope() {
202
+ await this.withReadScope(async () => undefined);
203
+ }
204
+ async getLeaderboardMetricPreference() {
205
+ return this.withReadScope(async (client) => {
206
+ const result = await client.query(`SELECT preference_json FROM pubg_team_preferences
207
+ WHERE tenant_id=$1 AND team_id=$2 AND preference_key='leaderboard_metric'`, [this.scope.tenantId, this.scope.team.id]);
208
+ return parseStoredTeamLeaderboardMetric(result.rows[0]?.preference_json);
209
+ });
210
+ }
211
+ async withConversationScope(sessionId, action) {
212
+ return this.withReadScope(async (client) => action(client, await this.assertConversation(sessionId, client)));
213
+ }
214
+ async matchVisible(client, matchId) {
215
+ const result = await client.query(`SELECT 1 FROM pubg_matches AS match WHERE match.match_id=$1 AND match.shard=$3 AND EXISTS (
216
+ SELECT 1 FROM pubg_match_players AS member WHERE member.shard=match.shard AND member.match_id=match.match_id
217
+ AND member.account_id=ANY($2::TEXT[])
218
+ )`, [matchId, this.accountIds, this.shard]);
219
+ return result.rowCount === 1;
220
+ }
221
+ async countMatches() {
222
+ return this.withReadScope(async (client) => {
223
+ const result = await client.query(`SELECT COUNT(*)::bigint AS count FROM pubg_matches AS match
224
+ WHERE match.shard=$2 AND EXISTS (
225
+ SELECT 1 FROM pubg_match_players AS member
226
+ WHERE member.shard=match.shard AND member.match_id = match.match_id AND member.account_id = ANY($1::text[])
227
+ )`, [this.accountIds, this.shard]);
228
+ return number(result.rows[0]?.count);
229
+ });
230
+ }
231
+ async getMatch(matchId) {
232
+ return this.withReadScope(async (client) => {
233
+ const result = await client.query(`SELECT match.* FROM pubg_matches AS match
234
+ WHERE match.match_id = $1 AND match.shard=$3 AND EXISTS (
235
+ SELECT 1 FROM pubg_match_players AS member
236
+ WHERE member.shard=match.shard AND member.match_id = match.match_id AND member.account_id = ANY($2::text[])
237
+ )`, [matchId, this.accountIds, this.shard]);
238
+ const row = result.rows[0];
239
+ if (!row)
240
+ return null;
241
+ const players = await client.query('SELECT * FROM pubg_match_players WHERE match_id = $1 AND shard=$2 AND account_id=ANY($3::text[]) ORDER BY account_id', [matchId, this.shard, this.accountIds]);
242
+ return rowToMatch(row, players.rows.map(rowToPlayer));
243
+ });
244
+ }
245
+ async listMatches(options = {}) {
246
+ return this.withReadScope(async (client) => {
247
+ const clauses = ['match.shard=$2', 'EXISTS (SELECT 1 FROM pubg_match_players AS member WHERE member.shard=match.shard AND member.match_id = match.match_id AND member.account_id = ANY($1::text[]))'];
248
+ const values = [this.accountIds, this.shard];
249
+ if (options.fromMs !== undefined) {
250
+ values.push(options.fromMs);
251
+ clauses.push(`match.timestamp_ms >= $${values.length}`);
252
+ }
253
+ if (options.toMs !== undefined) {
254
+ values.push(options.toMs);
255
+ clauses.push(`match.timestamp_ms < $${values.length}`);
256
+ }
257
+ const limit = Math.min(Math.max(Math.trunc(options.limit ?? 10000), 1), 10000);
258
+ values.push(limit);
259
+ const selected = await client.query(`SELECT match.* FROM pubg_matches AS match WHERE ${clauses.join(' AND ')}
260
+ ORDER BY match.timestamp_ms ASC, match.match_id ASC LIMIT $${values.length}`, values);
261
+ if (!selected.rowCount)
262
+ return [];
263
+ const matchIds = selected.rows.map((row) => String(row.match_id));
264
+ const players = await client.query(`SELECT player.*, selected.timestamp_ms AS selected_timestamp
265
+ FROM unnest($1::text[]) AS chosen(match_id)
266
+ JOIN pubg_matches AS selected ON selected.match_id = chosen.match_id AND selected.shard=$2
267
+ JOIN pubg_match_players AS player ON player.match_id = selected.match_id AND player.shard=selected.shard AND player.account_id=ANY($3::text[])
268
+ ORDER BY selected.timestamp_ms ASC, selected.match_id ASC, player.account_id ASC`, [matchIds, this.shard, this.accountIds]);
269
+ const byMatch = new Map();
270
+ for (const player of players.rows) {
271
+ const id = String(player.match_id);
272
+ const group = byMatch.get(id) ?? [];
273
+ group.push(rowToPlayer(player));
274
+ byMatch.set(id, group);
275
+ }
276
+ return selected.rows.map((row) => rowToMatch(row, byMatch.get(String(row.match_id)) ?? []));
277
+ });
278
+ }
279
+ async upsertMatches(input, metadata = {}) {
280
+ await this.verifyScope();
281
+ const individuallyNormalized = input.flatMap((item) => normalizeRecords([item]));
282
+ if (individuallyNormalized.some(match => match.shard !== this.shard))
283
+ throw new Error('repository_shard_mismatch');
284
+ const records = normalizeRecords(input).filter((match) => match.matchId && Number.isFinite(match.timestamp));
285
+ const duplicateInputs = Math.max(0, individuallyNormalized.length - records.length);
286
+ const invalidInputs = Math.max(0, input.length - individuallyNormalized.length);
287
+ const fetchedAt = metadata.fetchedAt ?? new Date().toISOString();
288
+ let inserted = 0;
289
+ let updated = 0;
290
+ await withTransaction(this.pool, async (client) => {
291
+ for (const match of records) {
292
+ const prior = await client.query('SELECT 1 FROM pubg_matches WHERE match_id = $1 AND shard=$2', [match.matchId, this.shard]);
293
+ await client.query(`INSERT INTO pubg_matches (
294
+ match_id, shard, created_at, timestamp_ms, match_type, game_mode, is_competitive,
295
+ map_name, duration, patch_version, telemetry_url, schema_version, parser_version,
296
+ fetched_at, source, checked_player_ids_json, raw_json
297
+ ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16::jsonb,$17::jsonb)
298
+ ON CONFLICT (shard,match_id) DO UPDATE SET
299
+ shard=EXCLUDED.shard, created_at=EXCLUDED.created_at, timestamp_ms=EXCLUDED.timestamp_ms,
300
+ match_type=EXCLUDED.match_type, game_mode=EXCLUDED.game_mode,
301
+ is_competitive=EXCLUDED.is_competitive, map_name=EXCLUDED.map_name,
302
+ duration=EXCLUDED.duration, patch_version=EXCLUDED.patch_version,
303
+ telemetry_url=EXCLUDED.telemetry_url, schema_version=EXCLUDED.schema_version,
304
+ parser_version=EXCLUDED.parser_version, fetched_at=EXCLUDED.fetched_at,
305
+ source=EXCLUDED.source, checked_player_ids_json=EXCLUDED.checked_player_ids_json,
306
+ raw_json=EXCLUDED.raw_json`, [match.matchId, match.shard, match.createdAt, match.timestamp, match.matchType, match.gameMode,
307
+ match.isCompetitive, match.mapName, match.duration, match.patchVersion, match.telemetryUrl ?? null,
308
+ match.schemaVersion, metadata.parserVersion ?? null, fetchedAt, metadata.source ?? 'unknown',
309
+ JSON.stringify(metadata.checkedPlayerIds ?? match.players.map((player) => player.accountId)),
310
+ metadata.rawJson === undefined ? null : JSON.stringify(metadata.rawJson)]);
311
+ for (const player of match.players) {
312
+ await client.query(`INSERT INTO pubg_match_players (
313
+ match_id, account_id, player_name, display_name, rank, kills, assists, damage,
314
+ dbnos, revives, headshot_kills, survival_time, longest_kill, deaths, death_semantics,shard
315
+ ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16)
316
+ ON CONFLICT (shard,match_id,account_id) DO UPDATE SET
317
+ player_name=EXCLUDED.player_name, display_name=EXCLUDED.display_name, rank=EXCLUDED.rank,
318
+ kills=EXCLUDED.kills, assists=EXCLUDED.assists, damage=EXCLUDED.damage, dbnos=EXCLUDED.dbnos,
319
+ revives=EXCLUDED.revives, headshot_kills=EXCLUDED.headshot_kills, survival_time=EXCLUDED.survival_time,
320
+ longest_kill=EXCLUDED.longest_kill, deaths=EXCLUDED.deaths, death_semantics=EXCLUDED.death_semantics`, [match.matchId, player.accountId, player.playerName, player.displayName, player.rank,
321
+ player.kills, player.assists, player.damage, player.dbnos, player.revives,
322
+ player.headshotKills, player.survivalTime, player.longestKill, player.deaths, player.deathSemantics, this.shard]);
323
+ }
324
+ if (prior.rowCount)
325
+ updated += 1;
326
+ else
327
+ inserted += 1;
328
+ }
329
+ });
330
+ return { inserted, updated, duplicateInputs, invalidInputs };
331
+ }
332
+ async setSyncState(state) {
333
+ await this.withReadScope(async (client) => client.query(`INSERT INTO pubg_sync_state(tenant_id, team_id, state_key, checked_at, state_json)
334
+ VALUES ($1,$2,$3,$4,$5::jsonb)
335
+ ON CONFLICT (tenant_id, team_id, state_key) DO UPDATE
336
+ SET checked_at=EXCLUDED.checked_at, state_json=EXCLUDED.state_json`, [this.scope.tenantId, this.scope.teamId, state.key, state.checkedAt, JSON.stringify(state)]).then(() => undefined));
337
+ }
338
+ async getSyncState(key) {
339
+ return this.withReadScope(async (client) => {
340
+ const result = await client.query('SELECT state_json FROM pubg_sync_state WHERE tenant_id=$1 AND team_id=$2 AND state_key=$3', [this.scope.tenantId, this.scope.teamId, key]);
341
+ return result.rows[0] ? objectValue(result.rows[0].state_json, null) : null;
342
+ });
343
+ }
344
+ async get(key) {
345
+ return this.withReadScope(async (client) => {
346
+ if (!await this.matchVisible(client, key.matchId))
347
+ return null;
348
+ const result = await client.query(`SELECT facts_json, created_at FROM pubg_telemetry_team_features
349
+ WHERE tenant_id=$1 AND team_id=$2 AND team_config_hash=$3 AND match_id=$4
350
+ AND parser_version=$5 AND feature_version=$6 AND shard=$7`, [this.scope.tenantId, this.scope.teamId, this.teamConfigHash, key.matchId, key.parserVersion, key.featureVersion, this.shard]);
351
+ const row = result.rows[0];
352
+ if (!row)
353
+ return null;
354
+ const facts = objectValue(row.facts_json, null);
355
+ if (!facts || typeof facts !== 'object')
356
+ return null;
357
+ return { ...key, facts: facts, createdAt: new Date(row.created_at).toISOString() };
358
+ });
359
+ }
360
+ async set(record) {
361
+ await this.withReadScope(async (client) => {
362
+ if (!await this.matchVisible(client, record.matchId))
363
+ throw new Error('telemetry_match_not_in_team');
364
+ await client.query(`INSERT INTO pubg_telemetry_team_features(tenant_id,team_id,team_config_hash,match_id,parser_version,feature_version,facts_json,created_at,shard)
365
+ VALUES ($1,$2,$3,$4,$5,$6,$7::jsonb,$8,$9)
366
+ ON CONFLICT (tenant_id,team_id,team_config_hash,shard,match_id,parser_version,feature_version) DO UPDATE
367
+ SET facts_json=EXCLUDED.facts_json, created_at=EXCLUDED.created_at`, [this.scope.tenantId, this.scope.teamId, this.teamConfigHash, record.matchId, record.parserVersion, record.featureVersion, JSON.stringify(record.facts), record.createdAt, this.shard]);
368
+ });
369
+ }
370
+ async getTelemetryPrefetchAttempt(key) {
371
+ return this.withReadScope(async (client) => {
372
+ if (!await this.matchVisible(client, key.matchId))
373
+ return null;
374
+ const result = await client.query(`SELECT * FROM pubg_telemetry_team_prefetch_attempts
375
+ WHERE tenant_id=$1 AND team_id=$2 AND team_config_hash=$3 AND match_id=$4
376
+ AND parser_version=$5 AND feature_version=$6 AND shard=$7`, [this.scope.tenantId, this.scope.teamId, this.teamConfigHash, key.matchId, key.parserVersion, key.featureVersion, this.shard]);
377
+ return result.rows[0] ? attemptFromRow(result.rows[0]) : null;
378
+ });
379
+ }
380
+ async listDueTelemetryPrefetchAttempts(parserVersion, featureVersion, now, limit = 100) {
381
+ return this.withReadScope(async (client) => {
382
+ const bounded = Math.min(Math.max(Math.trunc(limit), 1), 1000);
383
+ const result = await client.query(`SELECT attempt.* FROM pubg_telemetry_team_prefetch_attempts attempt
384
+ WHERE tenant_id=$1 AND team_id=$2 AND team_config_hash=$3 AND parser_version=$4 AND feature_version=$5 AND attempt.shard=$8
385
+ AND EXISTS (SELECT 1 FROM pubg_match_players member WHERE member.shard=attempt.shard AND member.match_id=attempt.match_id AND member.account_id=ANY($7::TEXT[]))
386
+ AND status IN ('PENDING','UNAVAILABLE') AND (next_retry_at IS NULL OR next_retry_at <= $9)
387
+ ORDER BY COALESCE(next_retry_at, '-infinity'::timestamptz), updated_at, match_id
388
+ LIMIT $6`, [this.scope.tenantId, this.scope.teamId, this.teamConfigHash, parserVersion, featureVersion, bounded, this.accountIds, this.shard, now]);
389
+ return result.rows.map(attemptFromRow);
390
+ });
391
+ }
392
+ async setTelemetryPrefetchAttempt(attempt) {
393
+ await this.withReadScope(async (client) => {
394
+ if (!await this.matchVisible(client, attempt.matchId))
395
+ throw new Error('telemetry_match_not_in_team');
396
+ await client.query(`INSERT INTO pubg_telemetry_team_prefetch_attempts(
397
+ tenant_id,team_id,team_config_hash,shard,match_id,parser_version,feature_version,status,attempt_count,
398
+ last_attempted_at, next_retry_at, error, updated_at
399
+ ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)
400
+ ON CONFLICT (tenant_id,team_id,team_config_hash,shard,match_id,parser_version,feature_version) DO UPDATE SET
401
+ status=EXCLUDED.status, attempt_count=EXCLUDED.attempt_count,
402
+ last_attempted_at=EXCLUDED.last_attempted_at, next_retry_at=EXCLUDED.next_retry_at,
403
+ error=EXCLUDED.error, updated_at=EXCLUDED.updated_at`, [this.scope.tenantId, this.scope.teamId, this.teamConfigHash, this.shard, attempt.matchId, attempt.parserVersion, attempt.featureVersion, attempt.status,
404
+ attempt.attemptCount, attempt.lastAttemptedAt, attempt.nextRetryAt, attempt.error ?? null, attempt.updatedAt]);
405
+ });
406
+ }
407
+ async recordTelemetryPrefetchRun(run) {
408
+ await this.withReadScope(async (client) => client.query(`INSERT INTO pubg_telemetry_prefetch_runs(
409
+ tenant_id, team_id, run_id, report_date, started_at, finished_at, trigger,
410
+ discovered_match_count, new_match_count, candidate_match_count, fetched_count,
411
+ cache_hit_count, unavailable_count, pending_count, failed_match_ids_json
412
+ ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15::jsonb)
413
+ ON CONFLICT (tenant_id, team_id, run_id) DO UPDATE SET
414
+ report_date=EXCLUDED.report_date, started_at=EXCLUDED.started_at,
415
+ finished_at=EXCLUDED.finished_at, trigger=EXCLUDED.trigger,
416
+ discovered_match_count=EXCLUDED.discovered_match_count, new_match_count=EXCLUDED.new_match_count,
417
+ candidate_match_count=EXCLUDED.candidate_match_count, fetched_count=EXCLUDED.fetched_count,
418
+ cache_hit_count=EXCLUDED.cache_hit_count, unavailable_count=EXCLUDED.unavailable_count,
419
+ pending_count=EXCLUDED.pending_count, failed_match_ids_json=EXCLUDED.failed_match_ids_json`, [this.scope.tenantId, this.scope.teamId, run.runId, run.reportDate, run.startedAt, run.finishedAt,
420
+ run.trigger, run.discoveredMatchCount, run.newMatchCount, run.candidateMatchCount,
421
+ run.fetchedCount, run.cacheHitCount, run.unavailableCount, run.pendingCount,
422
+ JSON.stringify([...new Set(run.failedMatchIds)])]).then(() => undefined));
423
+ }
424
+ async listTelemetryPrefetchRuns(reportDate) {
425
+ return this.withReadScope(async (client) => {
426
+ const result = await client.query(`SELECT * FROM pubg_telemetry_prefetch_runs
427
+ WHERE tenant_id=$1 AND team_id=$2 AND report_date=$3 ORDER BY started_at, run_id`, [this.scope.tenantId, this.scope.teamId, reportDate]);
428
+ return result.rows.map(runFromRow);
429
+ });
430
+ }
431
+ async setResultSet(record) {
432
+ await this.withConversationScope(record.sessionId, async (client, conversation) => client.query(`INSERT INTO pubg_result_sets(
433
+ tenant_id, team_id, actor_id, channel_id, session_id,
434
+ result_set_id, expires_at, result_json
435
+ ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8::jsonb)
436
+ ON CONFLICT (tenant_id, team_id, actor_id, channel_id, session_id, result_set_id)
437
+ DO UPDATE SET expires_at=EXCLUDED.expires_at, result_json=EXCLUDED.result_json`, [this.scope.tenantId, this.scope.teamId, conversation.actorId, conversation.channelId,
438
+ conversation.sessionId, record.id, record.expiresAt, JSON.stringify(record)]).then(() => undefined));
439
+ }
440
+ async getResultSet(sessionId, resultSetId, now = new Date()) {
441
+ return this.withConversationScope(sessionId, async (client, conversation) => {
442
+ const result = await client.query(`SELECT result_json FROM pubg_result_sets
443
+ WHERE tenant_id=$1 AND team_id=$2 AND actor_id=$3 AND channel_id=$4
444
+ AND session_id=$5 AND result_set_id=$6 AND expires_at>$7`, [this.scope.tenantId, this.scope.teamId, conversation.actorId, conversation.channelId,
445
+ conversation.sessionId, resultSetId, now]);
446
+ return result.rows[0] ? objectValue(result.rows[0].result_json, null) : null;
447
+ });
448
+ }
449
+ async setContext(context) {
450
+ await this.withConversationScope(context.sessionId, async (client, conversation) => client.query(`INSERT INTO pubg_session_contexts(
451
+ tenant_id, team_id, actor_id, channel_id, session_id,
452
+ expires_at, context_json
453
+ ) VALUES ($1,$2,$3,$4,$5,'infinity'::timestamptz,$6::jsonb)
454
+ ON CONFLICT (tenant_id, team_id, actor_id, channel_id, session_id)
455
+ DO UPDATE SET expires_at='infinity'::timestamptz, context_json=EXCLUDED.context_json`, [this.scope.tenantId, this.scope.teamId, conversation.actorId, conversation.channelId,
456
+ conversation.sessionId, JSON.stringify(context)]).then(() => undefined));
457
+ }
458
+ async getContext(sessionId, now = new Date()) {
459
+ return this.withConversationScope(sessionId, async (client, conversation) => {
460
+ const result = await client.query(`SELECT context_json FROM pubg_session_contexts
461
+ WHERE tenant_id=$1 AND team_id=$2 AND actor_id=$3 AND channel_id=$4
462
+ AND session_id=$5 AND expires_at>$6`, [this.scope.tenantId, this.scope.teamId, conversation.actorId, conversation.channelId,
463
+ conversation.sessionId, now]);
464
+ return result.rows[0] ? objectValue(result.rows[0].context_json, null) : null;
465
+ });
466
+ }
467
+ async recordModelUsage(sessionId, usage) {
468
+ const requestId = requiredText(usage.requestId, 'request_id');
469
+ const provider = requiredText(usage.provider, 'model_provider');
470
+ const modelId = requiredText(usage.modelId, 'model_id');
471
+ if (requestId.length > 256 || provider.length > 100 || modelId.length > 200)
472
+ throw new Error('model_usage_record_invalid');
473
+ const tokens = (value) => value !== null && Number.isSafeInteger(value)
474
+ && value >= 0 && value <= 2_147_483_647 ? value : null;
475
+ await this.withConversationScope(sessionId, async (client, conversation) => client.query(`INSERT INTO pubg_usage_records(tenant_id,team_id,actor_id,request_id,provider,model_id,input_tokens,output_tokens)
476
+ VALUES($1,$2,$3,$4,$5,$6,$7,$8) ON CONFLICT (tenant_id,request_id) DO NOTHING`, [this.scope.tenantId, this.scope.teamId, conversation.actorId,
477
+ requestId, provider, modelId, tokens(usage.inputTokens), tokens(usage.outputTokens)]).then(() => undefined));
478
+ }
479
+ async cleanupExpired(now = new Date()) {
480
+ await this.withReadScope(async (client) => {
481
+ await client.query('DELETE FROM pubg_result_sets WHERE tenant_id=$1 AND team_id=$2 AND expires_at <= $3', [this.scope.tenantId, this.scope.teamId, now]);
482
+ await client.query('DELETE FROM pubg_session_contexts WHERE tenant_id=$1 AND team_id=$2 AND expires_at <= $3', [this.scope.tenantId, this.scope.teamId, now]);
483
+ });
484
+ }
485
+ }
@@ -0,0 +1,42 @@
1
+ import type { Pool } from 'pg';
2
+ import { type TeamContext } from '@rine-kit/pubg-domain/core';
3
+ export interface PubgClaim {
4
+ actorId: string;
5
+ accountId: string;
6
+ shard: string;
7
+ displayName: string;
8
+ status: 'self_declared' | 'verified';
9
+ claimedAt: string;
10
+ }
11
+ export interface ClaimInput {
12
+ tenantId: string;
13
+ teamId: string;
14
+ /** The team's display label, used the first time the team is created. */
15
+ teamLabel: string;
16
+ actorId: string;
17
+ shard: string;
18
+ accountId: string;
19
+ displayName: string;
20
+ }
21
+ /** Claims and rosters for teams made of claimed PUBG accounts. Every method is scoped by tenant and team. */
22
+ export declare class PostgresPubgRosterStore {
23
+ private readonly pool;
24
+ constructor(pool: Pool);
25
+ /**
26
+ * Declares `accountId` as the actor's account in the team, creating the team on the first claim. A second
27
+ * claim by the same actor replaces the first. Throws `pubg_team_shard_conflict` when the team already has
28
+ * members on another shard, `pubg_account_taken` when someone else claimed the account, and
29
+ * `pubg_team_full` beyond MAX_TEAM_ROSTER_SIZE. The team's next sync is scheduled at once.
30
+ */
31
+ claim(input: ClaimInput): Promise<void>;
32
+ /** Removes the actor's claim and roster entry; the team disappears with its last member. */
33
+ release(tenantId: string, teamId: string, actorId: string): Promise<boolean>;
34
+ private dropMember;
35
+ /** Forgets a whole team (its room was closed): roster, claims, sync job and cached team data. */
36
+ deleteTeam(tenantId: string, teamId: string): Promise<void>;
37
+ listClaims(tenantId: string, teamId: string): Promise<PubgClaim[]>;
38
+ /** The actor's own account in this team, or null. */
39
+ getClaim(tenantId: string, teamId: string, actorId: string): Promise<PubgClaim | null>;
40
+ /** The team as the Domain wants it (roster with in-game names), or null when nobody has claimed yet. */
41
+ getTeamContext(tenantId: string, teamId: string): Promise<TeamContext | null>;
42
+ }
@@ -0,0 +1,129 @@
1
+ import { createTeamContext } from '@rine-kit/pubg-domain/core';
2
+ import { MAX_TEAM_ROSTER_SIZE } from './contracts/team-roster.js';
3
+ const SHARDS = new Set(['steam', 'kakao', 'psn', 'xbox']);
4
+ async function transaction(pool, work) {
5
+ const client = await pool.connect();
6
+ try {
7
+ await client.query('BEGIN');
8
+ const value = await work(client);
9
+ await client.query('COMMIT');
10
+ return value;
11
+ }
12
+ catch (error) {
13
+ await client.query('ROLLBACK').catch(() => undefined);
14
+ throw error;
15
+ }
16
+ finally {
17
+ client.release();
18
+ }
19
+ }
20
+ /** Claims and rosters for teams made of claimed PUBG accounts. Every method is scoped by tenant and team. */
21
+ export class PostgresPubgRosterStore {
22
+ pool;
23
+ constructor(pool) {
24
+ this.pool = pool;
25
+ }
26
+ /**
27
+ * Declares `accountId` as the actor's account in the team, creating the team on the first claim. A second
28
+ * claim by the same actor replaces the first. Throws `pubg_team_shard_conflict` when the team already has
29
+ * members on another shard, `pubg_account_taken` when someone else claimed the account, and
30
+ * `pubg_team_full` beyond MAX_TEAM_ROSTER_SIZE. The team's next sync is scheduled at once.
31
+ */
32
+ async claim(input) {
33
+ if (!SHARDS.has(input.shard))
34
+ throw new Error('pubg_shard_invalid');
35
+ await transaction(this.pool, async (client) => {
36
+ await client.query('INSERT INTO pubg_tenants(tenant_id) VALUES ($1) ON CONFLICT DO NOTHING', [
37
+ input.tenantId,
38
+ ]);
39
+ await client.query('INSERT INTO pubg_teams(tenant_id,team_id,label,pubg_shard) VALUES ($1,$2,$3,$4) ON CONFLICT DO NOTHING', [input.tenantId, input.teamId, input.teamLabel, input.shard]);
40
+ const team = await client.query('SELECT pubg_shard FROM pubg_teams WHERE tenant_id=$1 AND team_id=$2 FOR UPDATE', [input.tenantId, input.teamId]);
41
+ const others = await client.query('SELECT count(*)::int AS n FROM pubg_account_claims WHERE tenant_id=$1 AND team_id=$2 AND actor_id<>$3', [input.tenantId, input.teamId, input.actorId]);
42
+ const otherCount = Number(others.rows[0]?.n ?? 0);
43
+ if (team.rows[0]?.pubg_shard !== input.shard) {
44
+ // An empty team may still change shard (its only member is re-claiming on another one).
45
+ if (otherCount > 0)
46
+ throw new Error('pubg_team_shard_conflict');
47
+ await client.query('UPDATE pubg_teams SET pubg_shard=$3 WHERE tenant_id=$1 AND team_id=$2', [
48
+ input.tenantId,
49
+ input.teamId,
50
+ input.shard,
51
+ ]);
52
+ }
53
+ if (otherCount >= MAX_TEAM_ROSTER_SIZE)
54
+ throw new Error('pubg_team_full');
55
+ const taken = await client.query(`SELECT 1 FROM pubg_account_claims WHERE tenant_id=$1 AND team_id=$2
56
+ AND pubg_account_id=$3 AND actor_id<>$4`, [input.tenantId, input.teamId, input.accountId, input.actorId]);
57
+ if (taken.rowCount)
58
+ throw new Error('pubg_account_taken');
59
+ await this.dropMember(client, input.tenantId, input.teamId, input.actorId);
60
+ await client.query(`INSERT INTO pubg_account_names(shard,account_id,display_name) VALUES ($1,$2,$3)
61
+ ON CONFLICT (shard,account_id) DO UPDATE SET display_name=EXCLUDED.display_name, last_resolved_at=now()`, [input.shard, input.accountId, input.displayName]);
62
+ await client.query(`INSERT INTO pubg_team_members(tenant_id,team_id,pubg_account_id,added_by) VALUES ($1,$2,$3,$4)
63
+ ON CONFLICT DO NOTHING`, [input.tenantId, input.teamId, input.accountId, input.actorId]);
64
+ await client.query(`INSERT INTO pubg_account_claims(tenant_id,team_id,actor_id,pubg_shard,pubg_account_id)
65
+ 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]);
69
+ });
70
+ }
71
+ /** Removes the actor's claim and roster entry; the team disappears with its last member. */
72
+ async release(tenantId, teamId, actorId) {
73
+ return transaction(this.pool, async (client) => {
74
+ const removed = await this.dropMember(client, tenantId, teamId, actorId);
75
+ const left = await client.query('SELECT 1 FROM pubg_account_claims WHERE tenant_id=$1 AND team_id=$2 LIMIT 1', [tenantId, teamId]);
76
+ if (!left.rowCount) {
77
+ await client.query('DELETE FROM pubg_teams WHERE tenant_id=$1 AND team_id=$2', [tenantId, teamId]);
78
+ }
79
+ return removed;
80
+ });
81
+ }
82
+ async dropMember(client, tenantId, teamId, actorId) {
83
+ const previous = await client.query(`DELETE FROM pubg_account_claims WHERE tenant_id=$1 AND team_id=$2 AND actor_id=$3
84
+ RETURNING pubg_account_id`, [tenantId, teamId, actorId]);
85
+ const accountId = previous.rows[0]?.pubg_account_id;
86
+ if (accountId) {
87
+ await client.query('DELETE FROM pubg_team_members WHERE tenant_id=$1 AND team_id=$2 AND pubg_account_id=$3', [tenantId, teamId, accountId]);
88
+ }
89
+ return Boolean(accountId);
90
+ }
91
+ /** Forgets a whole team (its room was closed): roster, claims, sync job and cached team data. */
92
+ async deleteTeam(tenantId, teamId) {
93
+ await this.pool.query('DELETE FROM pubg_teams WHERE tenant_id=$1 AND team_id=$2', [tenantId, teamId]);
94
+ }
95
+ async listClaims(tenantId, teamId) {
96
+ const result = await this.pool.query(`SELECT claim.actor_id, claim.pubg_account_id, claim.pubg_shard, claim.claim_status, claim.claimed_at,
97
+ COALESCE(name.display_name, claim.pubg_account_id) AS display_name
98
+ FROM pubg_account_claims claim
99
+ LEFT JOIN pubg_account_names name
100
+ ON name.shard=claim.pubg_shard AND name.account_id=claim.pubg_account_id
101
+ WHERE claim.tenant_id=$1 AND claim.team_id=$2 ORDER BY claim.claimed_at, claim.actor_id`, [tenantId, teamId]);
102
+ return result.rows.map((row) => ({
103
+ actorId: String(row.actor_id),
104
+ accountId: String(row.pubg_account_id),
105
+ shard: String(row.pubg_shard),
106
+ displayName: String(row.display_name),
107
+ status: row.claim_status,
108
+ claimedAt: new Date(row.claimed_at).toISOString(),
109
+ }));
110
+ }
111
+ /** The actor's own account in this team, or null. */
112
+ async getClaim(tenantId, teamId, actorId) {
113
+ return (await this.listClaims(tenantId, teamId)).find((claim) => claim.actorId === actorId) ?? null;
114
+ }
115
+ /** The team as the Domain wants it (roster with in-game names), or null when nobody has claimed yet. */
116
+ async getTeamContext(tenantId, teamId) {
117
+ const team = await this.pool.query('SELECT label, pubg_shard FROM pubg_teams WHERE tenant_id=$1 AND team_id=$2', [tenantId, teamId]);
118
+ const claims = await this.listClaims(tenantId, teamId);
119
+ const row = team.rows[0];
120
+ if (!row || claims.length === 0)
121
+ return null;
122
+ return createTeamContext(tenantId, {
123
+ id: teamId,
124
+ label: String(row.label),
125
+ platform: String(row.pubg_shard),
126
+ players: claims.map((claim) => ({ id: claim.accountId, name: claim.displayName, aliases: [] })),
127
+ });
128
+ }
129
+ }