@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.
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,53 @@
1
- # Temporary Holding Version
1
+ # @rine-kit/pubg-postgres
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
+ PostgreSQL 存储层,实现 `@rine-kit/pubg-domain` 的 `PubgRepositoryPort`:比赛与队员成绩、
4
+ 遥测特征、预取进度、会话上下文与结果集、同步队列、API 额度表。提取自 Gate 的 `pubg-saas`,
5
+ 逻辑与 SQL 保持一致;去掉了 KOOK 专属的租户元组与会话表。
6
+
7
+ ## 宿主要提供什么
8
+
9
+ - `tenantId`:不透明字符串,由宿主授权后给出(RINE:部署/命名空间)。
10
+ - `TeamContext`:小队与成员(RINE:一个房间 = 一个小队)。
11
+ - `TrustedConversationScope`:`{ kind, actorId, channelId, sessionId }`,必须由服务端生成,
12
+ 不得取自模型/工具参数。
13
+ - `authorize(client, scope)`:在每次受限读写的事务里、与团队行同一连接上执行;不允许就抛错。
14
+ 请对授权依据(绑定、成员关系)加 `FOR SHARE`,这样撤权要么先提交(读被拒绝),要么等读完成。
15
+
16
+ ## 使用
17
+
18
+ ```ts
19
+ import { migratePubgDatabase, PostgresPubgRepository, PublicSyncQueue } from '@rine-kit/pubg-postgres';
20
+
21
+ await migratePubgDatabase(pool); // 幂等,可每次启动执行
22
+ const repo = new PostgresPubgRepository(pool, teamContext, conversation, {
23
+ requireConversation: true,
24
+ authorize: async (client, { tenantId, teamId, conversation }) => { /* 宿主检查,不通过就 throw */ },
25
+ });
26
+ ```
27
+
28
+ ## 测试
29
+
30
+ ```bash
31
+ pnpm --filter @rine-kit/pubg-postgres test:pg # 在一次性 pgvector 容器里跑,不碰任何真实库
32
+ ```
33
+
34
+ 没有 `PUBG_POSTGRES_TEST_DATABASE_URL`(或 `MEMORY_TEST_DATABASE_URL`)时测试自动跳过。
35
+ 测试由 Gate 的 `postgres-repository` / `postgres-shard-scope` / `public-sync-queue` 原样移植。
36
+
37
+ ## 与 Gate 的差异
38
+
39
+ | Gate | 本包 |
40
+ |------|------|
41
+ | 表名无前缀 | `pubg_*` |
42
+ | `tenants(platform='kook', bot_account_id, guild_id)` | `pubg_tenants(tenant_id)` |
43
+ | 会话列 `(platform, bot_account_id, user_id, channel_id)` | `(actor_id, channel_id)` |
44
+ | 仓库内置 KOOK 会话/频道绑定/授权表校验 | 宿主传入 `authorize` 回调 |
45
+ | `public_sync_jobs`、`pubg_api_admission` | `pubg_sync_jobs`、`pubg_api_admission` |
46
+ | 31 个迁移 | 1 个压缩迁移(只含 PUBG 表;记忆表在 `agent-memory-postgres`) |
47
+ | 旧版"按分片回填"升级测试 | 不移植(新库无历史) |
48
+
49
+ ## 新写的部分(不是提取)
50
+
51
+ `roster-store.ts`(`PostgresPubgRosterStore`)与迁移 `0002_pubg_account_claims.sql`:当一个小队就是"在这里认领了账号的人"
52
+ 时(RINE:一个房间 = 一个小队)所需的最小名单管理——认领、改认领、释放、列出、生成 `TeamContext`,认领后立即安排一次同步。
53
+ Gate 对应的是 `team-admin-service`(围绕 KOOK 确认卡片,未提取)。这部分有自己的测试。
@@ -0,0 +1,6 @@
1
+ export interface NormalizedTeamAlias {
2
+ key: string;
3
+ displayAlias: string;
4
+ }
5
+ export declare function normalizeTeamAlias(value: unknown): NormalizedTeamAlias;
6
+ export declare function normalizeTeamMemberLookup(value: string): string;
@@ -0,0 +1,11 @@
1
+ export function normalizeTeamAlias(value) {
2
+ if (typeof value !== 'string')
3
+ throw new Error('team_alias_invalid');
4
+ const displayAlias = value.normalize('NFKC').trim();
5
+ if (!displayAlias || displayAlias.length > 100 || /[\u0000-\u001f\u007f]/u.test(displayAlias))
6
+ throw new Error('team_alias_invalid');
7
+ return { key: displayAlias.toLocaleLowerCase('en-US'), displayAlias };
8
+ }
9
+ export function normalizeTeamMemberLookup(value) {
10
+ return value.normalize('NFKC').trim().toLocaleLowerCase('en-US');
11
+ }
@@ -0,0 +1,5 @@
1
+ export declare const TEAM_LEADERBOARD_METRICS: readonly ["damage", "kills", "kd", "matches", "avg_damage"];
2
+ export type TeamLeaderboardMetric = typeof TEAM_LEADERBOARD_METRICS[number];
3
+ export declare function parseTeamLeaderboardMetric(value: unknown): TeamLeaderboardMetric | null;
4
+ export declare function parseStoredTeamLeaderboardMetric(value: unknown): TeamLeaderboardMetric | null;
5
+ export declare function teamLeaderboardMetricLabel(metric: TeamLeaderboardMetric): string;
@@ -0,0 +1,36 @@
1
+ export const TEAM_LEADERBOARD_METRICS = ['damage', 'kills', 'kd', 'matches', 'avg_damage'];
2
+ export function parseTeamLeaderboardMetric(value) {
3
+ if (typeof value !== 'string')
4
+ return null;
5
+ const normalized = value.trim().toLowerCase();
6
+ if (TEAM_LEADERBOARD_METRICS.includes(normalized))
7
+ return normalized;
8
+ if (['伤害', '伤害榜'].includes(normalized))
9
+ return 'damage';
10
+ if (['kill', '击杀', '击杀榜'].includes(normalized))
11
+ return 'kills';
12
+ if (normalized === 'kd')
13
+ return 'kd';
14
+ if (['match', '场次', '场次榜'].includes(normalized))
15
+ return 'matches';
16
+ if (['场均伤害', '场均伤害榜'].includes(normalized))
17
+ return 'avg_damage';
18
+ return null;
19
+ }
20
+ export function parseStoredTeamLeaderboardMetric(value) {
21
+ let preference = value;
22
+ if (typeof preference === 'string') {
23
+ try {
24
+ preference = JSON.parse(preference);
25
+ }
26
+ catch {
27
+ return null;
28
+ }
29
+ }
30
+ if (!preference || typeof preference !== 'object' || Array.isArray(preference))
31
+ return null;
32
+ return parseTeamLeaderboardMetric(preference.metric);
33
+ }
34
+ export function teamLeaderboardMetricLabel(metric) {
35
+ return { damage: '伤害榜', kills: '击杀榜', kd: 'KD 榜', matches: '场次榜', avg_damage: '场均伤害榜' }[metric];
36
+ }
@@ -0,0 +1,2 @@
1
+ /** Public KOOK teams may include two PUBG squads; every boundary enforces the same cap. */
2
+ export declare const MAX_TEAM_ROSTER_SIZE = 8;
@@ -0,0 +1,2 @@
1
+ /** Public KOOK teams may include two PUBG squads; every boundary enforces the same cap. */
2
+ export const MAX_TEAM_ROSTER_SIZE = 8;
@@ -0,0 +1,7 @@
1
+ export * from './migrate.js';
2
+ export * from './repository.js';
3
+ export * from './sync-queue.js';
4
+ export * from './contracts/team-aliases.js';
5
+ export * from './contracts/team-preferences.js';
6
+ export * from './contracts/team-roster.js';
7
+ export * from './roster-store.js';
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export * from './migrate.js';
2
+ export * from './repository.js';
3
+ export * from './sync-queue.js';
4
+ export * from './contracts/team-aliases.js';
5
+ export * from './contracts/team-preferences.js';
6
+ export * from './contracts/team-roster.js';
7
+ export * from './roster-store.js';
@@ -0,0 +1,3 @@
1
+ import type { Pool } from 'pg';
2
+ /** Applies the schema to an empty or existing database; safe to run on every start. */
3
+ export declare function migratePubgDatabase(pool: Pool): Promise<void>;
@@ -0,0 +1,37 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ const MIGRATIONS = ['0001_pubg_schema.sql', '0002_pubg_account_claims.sql'];
3
+ const LOCK_ID = 7192041303;
4
+ /** Applies the schema to an empty or existing database; safe to run on every start. */
5
+ export async function migratePubgDatabase(pool) {
6
+ const client = await pool.connect();
7
+ try {
8
+ await client.query('BEGIN');
9
+ await client.query('SELECT pg_advisory_xact_lock($1)', [LOCK_ID]);
10
+ await client.query(`CREATE TABLE IF NOT EXISTS pubg_schema_migrations (
11
+ migration_id TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT now())`);
12
+ for (const id of MIGRATIONS) {
13
+ const applied = await client.query('SELECT 1 FROM pubg_schema_migrations WHERE migration_id=$1', [id]);
14
+ if (applied.rowCount)
15
+ continue;
16
+ const sql = await readFile(new URL(`../migrations/${id}`, import.meta.url), 'utf8');
17
+ await client.query(sql);
18
+ await client.query('INSERT INTO pubg_schema_migrations(migration_id) VALUES ($1)', [id]);
19
+ }
20
+ await client.query('COMMIT');
21
+ }
22
+ catch (error) {
23
+ await rollbackQuietly(client);
24
+ throw error;
25
+ }
26
+ finally {
27
+ client.release();
28
+ }
29
+ }
30
+ async function rollbackQuietly(client) {
31
+ try {
32
+ await client.query('ROLLBACK');
33
+ }
34
+ catch {
35
+ /* keep the migration error */
36
+ }
37
+ }
@@ -0,0 +1,82 @@
1
+ import type { NormalizedMatch, ResultSetRecord, SessionContextRecord, TeamContext, TelemetryFeatureKey, TelemetryFeatureRecord, TelemetryPrefetchAttempt, TelemetryPrefetchRun, PubgRepositoryPort, SyncState, UpsertMatchesResult, MatchWriteMetadata } from '@rine-kit/pubg-domain/core';
2
+ import type { Pool, PoolClient } from 'pg';
3
+ import { type TeamLeaderboardMetric } from './contracts/team-preferences.js';
4
+ /** Who is asking, where, and in which server-created session. The host decides what these mean
5
+ * (RINE: the signed-in user, the room, a session it issued); never copy them from a model/tool argument. */
6
+ export interface TrustedConversationScope {
7
+ /** Host-defined kind of conversation (e.g. "room", "direct"); only the host's authorize() reads it. */
8
+ kind: string;
9
+ actorId: string;
10
+ channelId: string;
11
+ /** Server-derived opaque ID; never copy this from a model/tool argument. */
12
+ sessionId: string;
13
+ }
14
+ /** Runs inside every scoped transaction after the team check, on the same connection. It must throw to
15
+ * deny. Take row locks (FOR SHARE) on whatever grants access, so a revoke either commits before the read
16
+ * (and is rejected) or after it completes. */
17
+ export type ConversationAuthorizer = (client: PoolClient, scope: {
18
+ tenantId: string;
19
+ teamId: string;
20
+ teamRevision: number;
21
+ conversation: TrustedConversationScope;
22
+ }) => Promise<void>;
23
+ export interface PostgresPubgRepositoryOptions {
24
+ /** A conversation scope is mandatory (public query runtime). */
25
+ requireConversation?: boolean;
26
+ /** Host check that the conversation may read this team now; see ConversationAuthorizer. */
27
+ authorize?: ConversationAuthorizer;
28
+ }
29
+ export interface PublicModelUsageRecord {
30
+ requestId: string;
31
+ provider: string;
32
+ modelId: string;
33
+ inputTokens: number | null;
34
+ outputTokens: number | null;
35
+ }
36
+ /** PostgreSQL implementation of the PUBG repository port. Its team and optional
37
+ * conversation scopes are fixed from server-verified authorization state. */
38
+ export declare class PostgresPubgRepository implements PubgRepositoryPort {
39
+ private readonly pool;
40
+ private readonly options;
41
+ readonly store = "postgres";
42
+ readonly scope: TeamContext;
43
+ readonly conversation: TrustedConversationScope | null;
44
+ private readonly accountIds;
45
+ private readonly shard;
46
+ private readonly teamConfigHash;
47
+ constructor(pool: Pool, scope: TeamContext, conversation?: TrustedConversationScope | null, options?: PostgresPubgRepositoryOptions);
48
+ private assertTeamScope;
49
+ private assertReadScope;
50
+ private assertConversation;
51
+ /** Lock the team revision and conversation authority until the bounded read
52
+ * finishes. Roster/admin triggers update teams.query_revision, so a revoke
53
+ * either commits before this read (and is rejected) or after it completes. */
54
+ private withReadScope;
55
+ private verifyScope;
56
+ getLeaderboardMetricPreference(): Promise<TeamLeaderboardMetric | null>;
57
+ private withConversationScope;
58
+ private matchVisible;
59
+ countMatches(): Promise<number>;
60
+ getMatch(matchId: string): Promise<NormalizedMatch | null>;
61
+ listMatches(options?: {
62
+ fromMs?: number;
63
+ toMs?: number;
64
+ limit?: number;
65
+ }): Promise<NormalizedMatch[]>;
66
+ upsertMatches(input: unknown[], metadata?: MatchWriteMetadata): Promise<UpsertMatchesResult>;
67
+ setSyncState(state: SyncState): Promise<void>;
68
+ getSyncState(key: string): Promise<SyncState | null>;
69
+ get(key: TelemetryFeatureKey): Promise<TelemetryFeatureRecord | null>;
70
+ set(record: TelemetryFeatureRecord): Promise<void>;
71
+ getTelemetryPrefetchAttempt(key: TelemetryFeatureKey): Promise<TelemetryPrefetchAttempt | null>;
72
+ listDueTelemetryPrefetchAttempts(parserVersion: string, featureVersion: string, now: Date, limit?: number): Promise<TelemetryPrefetchAttempt[]>;
73
+ setTelemetryPrefetchAttempt(attempt: TelemetryPrefetchAttempt): Promise<void>;
74
+ recordTelemetryPrefetchRun(run: TelemetryPrefetchRun): Promise<void>;
75
+ listTelemetryPrefetchRuns(reportDate: string): Promise<TelemetryPrefetchRun[]>;
76
+ setResultSet(record: ResultSetRecord): Promise<void>;
77
+ getResultSet(sessionId: string, resultSetId: string, now?: Date): Promise<ResultSetRecord | null>;
78
+ setContext(context: SessionContextRecord): Promise<void>;
79
+ getContext(sessionId: string, now?: Date): Promise<SessionContextRecord | null>;
80
+ recordModelUsage(sessionId: string, usage: PublicModelUsageRecord): Promise<void>;
81
+ cleanupExpired(now?: Date): Promise<void>;
82
+ }