@reinsjs/store-pg 0.1.0
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/CHANGELOG.md +22 -0
- package/LICENSE +21 -0
- package/README.md +39 -0
- package/dist/index.d.ts +122 -0
- package/dist/index.js +322 -0
- package/dist/index.js.map +1 -0
- package/package.json +48 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# @reinsjs/store-pg
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- First public release.
|
|
8
|
+
|
|
9
|
+
- **Timeline first.** Append-only event log with `schemaVersion` on every event and fail-closed upcast on read; projection decides what the model sees each turn; replay and fork from the log alone.
|
|
10
|
+
- **A loop you can copy.** `runLoop` as an exported async generator: pause/resume is a return value with a small signed state, bounded retry on transient failures only while nothing has been written, tool pipeline `beforeTool → validate → approval → execute → afterTool`, sub-agent pause bubbling (`Interruption { kind: "subagent" }`).
|
|
11
|
+
- **Brain modules** (`@reinsjs/brain`): perception, compact (with folded-result manifest and `recall`; recommended on after measuring 100% recall at lower token cost on two model families), pins, spill, handoff, memory (`memory_20250818` shape, namespace isolation), approval (deny → ask → allow, fail-closed), budget (five limits, sub-agent usage included).
|
|
12
|
+
- **Lowering** (`@reinsjs/lowering-pi`): Anthropic Messages and OpenAI Responses via pi-ai with a declared loss matrix, trust markers on untrusted content, cache-breakpoint handling.
|
|
13
|
+
- **Serving** (`@reinsjs/server`, `@reinsjs/ui-agui`): Web-standard handler with SSE replay from `lastSeq`, per-session run lock, `authorizeSession` (only `true` allows), AG-UI as the first-class UI protocol.
|
|
14
|
+
- **Stores**: SQLite (`node:sqlite` / `bun:sqlite`) and Postgres (`pg` / PGlite), conformance-tested; configurable memory table for per-role isolation.
|
|
15
|
+
- **Tools**: MCP servers as one socket (`@reinsjs/tools-mcp`, tools bound per run, annotations as defaults not permissions); `asTool(agent)` in `reins`.
|
|
16
|
+
- **TanStack AI** middleware (`@reinsjs/adapter-tanstack-ai`): the brain on TanStack's loop with the log as the single source of truth; idempotent client-message import; runtime check for the approval interrupt.
|
|
17
|
+
- **Eval harness** (`@reinsjs/eval`): fixtures from real recordings, recorded tools, arm-vs-arm runner, metrics, the four-rule gate.
|
|
18
|
+
|
|
19
|
+
### Patch Changes
|
|
20
|
+
|
|
21
|
+
- Updated dependencies
|
|
22
|
+
- @reinsjs/core@0.1.0
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 NewRate Limited
|
|
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
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# @reinsjs/store-pg
|
|
2
|
+
|
|
3
|
+
PostgreSQL-backed `EventLog`, `BlobStore` and `MemoryStore` for [reins](../../README.md). It needs exactly one method from your client — `query(text, params) → { rows }` — so `pg`'s `Pool` or `Client`, PGlite, and most pooled drivers work unchanged. No `node:*` imports.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pnpm add @reinsjs/store-pg
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { pgStores } from "@reinsjs/store-pg"
|
|
11
|
+
import pg from "pg"
|
|
12
|
+
|
|
13
|
+
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL })
|
|
14
|
+
const store = await pgStores(pool) // creates tables if missing
|
|
15
|
+
const perRole = await pgStores(pool, { memoryTable: "analyst_memory" })
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
`pgStores` returns `{ log, blobs, memory }`, ready for `createAgent({ store })`. PGlite (`new PGlite("./data")`) is a drop-in for local development and tests — `examples/team` uses it.
|
|
19
|
+
|
|
20
|
+
## Layout and two deliberate choices
|
|
21
|
+
|
|
22
|
+
| table | keyed by | notes |
|
|
23
|
+
| --- | --- | --- |
|
|
24
|
+
| `reins_events` | `session_id, seq` | append-only, contiguous `seq` per session enforced in SQL (`seq_conflict` on violation) |
|
|
25
|
+
| `reins_blobs` | `session_id, id` | large payloads spilled out of the context |
|
|
26
|
+
| `reins_memory` (configurable) | `path` | the model's memory files; `memoryTable` gives each role or tenant its own table |
|
|
27
|
+
|
|
28
|
+
- **`data` is `json`, not `jsonb`.** `jsonb` reorders object keys; reins hashes pending tool calls and configuration with `JSON.stringify`, and a resumed run compares those hashes against what it reads back. With `jsonb`, every resume of a Postgres-backed session would be flagged as tampered. `json` stores the text verbatim. The price is no `jsonb_set` and no JSON indexes — `fork` copies a session prefix by reading and re-inserting in JavaScript.
|
|
29
|
+
- **No transactions.** Every write is a single statement, so handing in a connection pool is correct by construction. Do not add read-then-write logic on top without revisiting this.
|
|
30
|
+
|
|
31
|
+
Table names are validated against `^[A-Za-z_][A-Za-z0-9_]{0,62}$` before any SQL is assembled; an invalid name throws `invalid_argument` and touches nothing. Only the memory table is renamable.
|
|
32
|
+
|
|
33
|
+
Passes the conformance suite in `@reinsjs/core/testing` (run against PGlite in CI).
|
|
34
|
+
|
|
35
|
+
## Documentation
|
|
36
|
+
|
|
37
|
+
`docs/模块盘点/store.md` and `docs/技术方案.md` §5 — in Chinese, at the repository root.
|
|
38
|
+
|
|
39
|
+
MIT © 2026 NewRate Limited.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { BlobStore, BlobMeta, EventLog, Event, ReadOptions, MemoryStore, Stores } from '@reinsjs/core';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Postgres 客户端的最小形状:`query(text, params) → { rows }`。
|
|
5
|
+
* `pg` 的 Pool / Client、`@electric-sql/pglite` 的 PGlite 都直接满足;postgres.js 之类用标签模板的库包一层即可。
|
|
6
|
+
*
|
|
7
|
+
* 本包**不依赖事务**:每个写操作都是单条语句(append 用 unnest 一次插入整批、fork 用 INSERT … SELECT),
|
|
8
|
+
* 单条语句在 Postgres 里天然原子,所以传连接池进来也是对的 —— 不必为了 BEGIN/COMMIT 从池里借同一条连接。
|
|
9
|
+
*/
|
|
10
|
+
interface PgQueryResult {
|
|
11
|
+
rows: Record<string, unknown>[];
|
|
12
|
+
}
|
|
13
|
+
interface PgClient {
|
|
14
|
+
query(text: string, params?: readonly unknown[]): Promise<PgQueryResult>;
|
|
15
|
+
}
|
|
16
|
+
/** Postgres 的唯一约束冲突(SQLSTATE 23505);pg 与 PGlite 都把它放在 err.code */
|
|
17
|
+
declare function isUniqueViolation(err: unknown): boolean;
|
|
18
|
+
|
|
19
|
+
/** Postgres 大对象存储:bytea 列;`slice` 用 substring 在库内切 */
|
|
20
|
+
declare class PgBlobStore implements BlobStore {
|
|
21
|
+
private readonly client;
|
|
22
|
+
private readonly now;
|
|
23
|
+
constructor(client: PgClient, now?: () => number);
|
|
24
|
+
put(bytes: Uint8Array | string, meta: {
|
|
25
|
+
mime: string;
|
|
26
|
+
sessionId: string;
|
|
27
|
+
}): Promise<{
|
|
28
|
+
id: string;
|
|
29
|
+
}>;
|
|
30
|
+
get(id: string): Promise<{
|
|
31
|
+
bytes: Uint8Array;
|
|
32
|
+
meta: BlobMeta;
|
|
33
|
+
}>;
|
|
34
|
+
slice(id: string, range: {
|
|
35
|
+
start: number;
|
|
36
|
+
end: number;
|
|
37
|
+
}): Promise<Uint8Array>;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Postgres 事件日志。契约与内存实现一致(技术方案 §5)。
|
|
42
|
+
*
|
|
43
|
+
* append 是**一条语句**:`INSERT … SELECT FROM unnest(...) WHERE 当前末尾 = 首条 seq − 1`。
|
|
44
|
+
* 末尾不符(别人已经写了)→ 一行都不插,返回空 → seq_conflict;两个写入者同时通过 WHERE 检查 → 主键冲突(23505)→ seq_conflict。
|
|
45
|
+
* 不开事务、不借连接,传连接池也正确。
|
|
46
|
+
*/
|
|
47
|
+
declare class PgEventLog implements EventLog {
|
|
48
|
+
private readonly client;
|
|
49
|
+
constructor(client: PgClient);
|
|
50
|
+
append(events: readonly Event[]): Promise<void>;
|
|
51
|
+
private lastSeqOf;
|
|
52
|
+
read(sessionId: string, opts?: ReadOptions): AsyncIterable<Event>;
|
|
53
|
+
tail(sessionId: string, n: number): Promise<Event[]>;
|
|
54
|
+
fork(fromSessionId: string, atSeq: number, toSessionId: string): Promise<void>;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
interface PgMemoryStoreOptions {
|
|
58
|
+
/** 表名。缺省 `reins_memory` */
|
|
59
|
+
table?: string;
|
|
60
|
+
/** 测试注入时间 */
|
|
61
|
+
now?: () => number;
|
|
62
|
+
}
|
|
63
|
+
/** Postgres 记忆后端:路径 → 文本。前缀匹配用 left(),不用 LIKE(免转义);排序用 "C" 排序规则得到与内存实现一致的字节序 */
|
|
64
|
+
declare class PgMemoryStore implements MemoryStore {
|
|
65
|
+
private readonly client;
|
|
66
|
+
private readonly table;
|
|
67
|
+
private readonly now;
|
|
68
|
+
constructor(client: PgClient, opts?: PgMemoryStoreOptions);
|
|
69
|
+
list(prefix: string): Promise<string[]>;
|
|
70
|
+
read(path: string): Promise<string | null>;
|
|
71
|
+
write(path: string, content: string): Promise<void>;
|
|
72
|
+
delete(path: string): Promise<void>;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** 记忆表缺省名。事件表与 blob 表不可配:它们由 EventLog / BlobStore 的契约唯一确定,隔离靠 session_id */
|
|
76
|
+
declare const DEFAULT_MEMORY_TABLE = "reins_memory";
|
|
77
|
+
/**
|
|
78
|
+
* 表名只认 `字母 / 下划线开头 + 字母数字下划线`,长度 ≤ 63(Postgres 标识符上限,超长会被静默截断成别的名字)。
|
|
79
|
+
* 表名会被字面拼进 SQL(参数绑定不了标识符),这个白名单就是防注入的唯一一道闸;不合规直接抛,不碰数据库。
|
|
80
|
+
* 不加引号:未加引号的标识符 Postgres 统一折成小写,DDL 与查询走同一条折叠规则,两边一致。
|
|
81
|
+
*/
|
|
82
|
+
declare function assertTableName(name: string, what?: string): string;
|
|
83
|
+
interface PgSchemaOptions {
|
|
84
|
+
/** 记忆表名。缺省 `reins_memory`;多套记忆共用一个库时按表隔离(技术方案 §9.6 隔离第一层) */
|
|
85
|
+
memoryTable?: string;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* 三张表。事件整条存 `json`(`data`),壳字段抽几列做主键与查询;主键 (session_id, seq) 的唯一约束是并发写入者的最后一道闸。
|
|
89
|
+
* `at` / `created_at` / `updated_at` 是 Unix 毫秒(bigint),读事件时不用它们 —— 事件从 data 整条还原。
|
|
90
|
+
*
|
|
91
|
+
* **为什么是 json 不是 jsonb**:jsonb 会重排对象键序,读回来 `JSON.stringify` 就变了;而 T10 的 pendingDigest / configHash
|
|
92
|
+
* 正是按 JSON.stringify 算的,存 Postgres 的会话一续跑就会误报"pending 被篡改"。json 按文本原样存取,各后端逐字节一致。
|
|
93
|
+
*/
|
|
94
|
+
declare function pgSchemaStatements(opts?: PgSchemaOptions): readonly string[];
|
|
95
|
+
/** 缺省表名的逐条 DDL */
|
|
96
|
+
declare const PG_SCHEMA_STATEMENTS: readonly string[];
|
|
97
|
+
/** 缺省表名的整段 DDL(给 psql / 迁移工具用) */
|
|
98
|
+
declare const PG_SCHEMA_SQL: string;
|
|
99
|
+
/**
|
|
100
|
+
* 建表(幂等)。pgStores() 缺省会调;自己管迁移的宿主可直接执行 PG_SCHEMA_SQL / pgSchemaStatements(opts)。
|
|
101
|
+
* 逐条执行:走扩展协议的客户端(PGlite、pg 的带参查询)不接受一次多条语句。
|
|
102
|
+
*/
|
|
103
|
+
declare function migratePg(client: PgClient, opts?: PgSchemaOptions): Promise<void>;
|
|
104
|
+
|
|
105
|
+
interface PgStoresOptions {
|
|
106
|
+
/** 起步时建表(幂等)。缺省 true;自己管迁移的宿主传 false */
|
|
107
|
+
migrate?: boolean;
|
|
108
|
+
/**
|
|
109
|
+
* 记忆表名,缺省 `reins_memory`。多个 agent 共用一个库、各自一套记忆时,每个传不同的表名;
|
|
110
|
+
* 事件表与 blob 表始终共用(按 session_id 隔离),建表语句随表名同步。
|
|
111
|
+
*/
|
|
112
|
+
memoryTable?: string;
|
|
113
|
+
/** 测试注入时间 */
|
|
114
|
+
now?: () => number;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* 一套 Postgres 存储:`createAgent({ store: await pgStores(pool) })`。
|
|
118
|
+
* client 是任何有 `query(text, params) → { rows }` 的对象:pg 的 Pool / Client、PGlite 实例。
|
|
119
|
+
*/
|
|
120
|
+
declare function pgStores(client: PgClient, opts?: PgStoresOptions): Promise<Stores>;
|
|
121
|
+
|
|
122
|
+
export { DEFAULT_MEMORY_TABLE, PG_SCHEMA_SQL, PG_SCHEMA_STATEMENTS, PgBlobStore, type PgClient, PgEventLog, PgMemoryStore, type PgMemoryStoreOptions, type PgQueryResult, type PgSchemaOptions, type PgStoresOptions, assertTableName, isUniqueViolation, migratePg, pgSchemaStatements, pgStores };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
// src/blob-store.ts
|
|
2
|
+
import { StoreError, uuidv7 } from "@reinsjs/core";
|
|
3
|
+
var PgBlobStore = class {
|
|
4
|
+
constructor(client, now = () => Date.now()) {
|
|
5
|
+
this.client = client;
|
|
6
|
+
this.now = now;
|
|
7
|
+
}
|
|
8
|
+
client;
|
|
9
|
+
now;
|
|
10
|
+
async put(bytes, meta) {
|
|
11
|
+
const data = typeof bytes === "string" ? new TextEncoder().encode(bytes) : bytes;
|
|
12
|
+
const id = uuidv7();
|
|
13
|
+
await this.client.query(
|
|
14
|
+
"INSERT INTO reins_blobs (id, session_id, mime, size, created_at, bytes) VALUES ($1, $2, $3, $4, $5, $6)",
|
|
15
|
+
[id, meta.sessionId, meta.mime, data.byteLength, this.now(), data]
|
|
16
|
+
);
|
|
17
|
+
return { id };
|
|
18
|
+
}
|
|
19
|
+
async get(id) {
|
|
20
|
+
const res = await this.client.query(
|
|
21
|
+
"SELECT session_id, mime, size, created_at, bytes FROM reins_blobs WHERE id = $1",
|
|
22
|
+
[id]
|
|
23
|
+
);
|
|
24
|
+
const row = res.rows[0];
|
|
25
|
+
if (!row) throw new StoreError("not_found", `blob \u4E0D\u5B58\u5728\uFF1A${id}`, { id });
|
|
26
|
+
return { bytes: new Uint8Array(row.bytes), meta: metaOf(row) };
|
|
27
|
+
}
|
|
28
|
+
async slice(id, range) {
|
|
29
|
+
const start = Math.max(0, Math.floor(range.start));
|
|
30
|
+
const length = Math.max(0, Math.floor(range.end) - start);
|
|
31
|
+
const res = await this.client.query(
|
|
32
|
+
"SELECT substring(bytes FROM $2 FOR $3) AS part FROM reins_blobs WHERE id = $1",
|
|
33
|
+
[id, start + 1, length]
|
|
34
|
+
);
|
|
35
|
+
const row = res.rows[0];
|
|
36
|
+
if (!row) throw new StoreError("not_found", `blob \u4E0D\u5B58\u5728\uFF1A${id}`, { id });
|
|
37
|
+
return row.part ? new Uint8Array(row.part) : new Uint8Array(0);
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
function metaOf(row) {
|
|
41
|
+
return {
|
|
42
|
+
mime: row.mime,
|
|
43
|
+
sessionId: row.session_id,
|
|
44
|
+
size: Number(row.size),
|
|
45
|
+
createdAt: Number(row.created_at)
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// src/client.ts
|
|
50
|
+
function isUniqueViolation(err) {
|
|
51
|
+
return typeof err === "object" && err !== null && err.code === "23505";
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// src/event-log.ts
|
|
55
|
+
import { StoreError as StoreError2 } from "@reinsjs/core";
|
|
56
|
+
async function collect(iter) {
|
|
57
|
+
const out = [];
|
|
58
|
+
for await (const x of iter) out.push(x);
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
var READ_PAGE = 500;
|
|
62
|
+
var PgEventLog = class {
|
|
63
|
+
constructor(client) {
|
|
64
|
+
this.client = client;
|
|
65
|
+
}
|
|
66
|
+
client;
|
|
67
|
+
async append(events) {
|
|
68
|
+
if (events.length === 0) throw new StoreError2("empty_batch", "append \u7684\u4E8B\u4EF6\u6570\u7EC4\u4E3A\u7A7A");
|
|
69
|
+
const first = events[0];
|
|
70
|
+
const sessionId = first.sessionId;
|
|
71
|
+
let expected = first.seq;
|
|
72
|
+
for (const e of events) {
|
|
73
|
+
if (e.sessionId !== sessionId) {
|
|
74
|
+
throw new StoreError2("session_mismatch", "\u540C\u4E00\u6279 append \u5FC5\u987B\u5C5E\u4E8E\u540C\u4E00\u4E2A\u4F1A\u8BDD", {
|
|
75
|
+
expected: sessionId,
|
|
76
|
+
got: e.sessionId
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
if (e.seq !== expected) {
|
|
80
|
+
throw new StoreError2(
|
|
81
|
+
"seq_conflict",
|
|
82
|
+
`\u4F1A\u8BDD ${sessionId} \u4E00\u6279\u5185 seq \u4E0D\u8FDE\u7EED\uFF1A\u671F\u671B ${expected}\uFF0C\u6536\u5230 ${e.seq}`,
|
|
83
|
+
{
|
|
84
|
+
sessionId,
|
|
85
|
+
expected,
|
|
86
|
+
got: e.seq
|
|
87
|
+
}
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
expected++;
|
|
91
|
+
}
|
|
92
|
+
if (first.seq < 1) {
|
|
93
|
+
throw new StoreError2("seq_conflict", `\u4F1A\u8BDD ${sessionId} \u7684 seq \u5FC5\u987B\u4ECE 1 \u8D77\uFF0C\u6536\u5230 ${first.seq}`, {
|
|
94
|
+
sessionId,
|
|
95
|
+
got: first.seq
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
let inserted;
|
|
99
|
+
try {
|
|
100
|
+
const res = await this.client.query(
|
|
101
|
+
`INSERT INTO reins_events (session_id, seq, id, type, at, data)
|
|
102
|
+
SELECT $1, u.seq, u.id, u.type, u.at, u.data
|
|
103
|
+
FROM unnest($2::int[], $3::text[], $4::text[], $5::bigint[], $6::json[]) AS u(seq, id, type, at, data)
|
|
104
|
+
WHERE (SELECT COALESCE(MAX(seq), 0) FROM reins_events WHERE session_id = $1) = $7
|
|
105
|
+
RETURNING seq`,
|
|
106
|
+
[
|
|
107
|
+
sessionId,
|
|
108
|
+
events.map((e) => e.seq),
|
|
109
|
+
events.map((e) => e.id),
|
|
110
|
+
events.map((e) => e.type),
|
|
111
|
+
events.map((e) => e.at),
|
|
112
|
+
events.map((e) => JSON.stringify(e)),
|
|
113
|
+
first.seq - 1
|
|
114
|
+
]
|
|
115
|
+
);
|
|
116
|
+
inserted = res.rows.length;
|
|
117
|
+
} catch (err) {
|
|
118
|
+
if (isUniqueViolation(err)) {
|
|
119
|
+
throw new StoreError2("seq_conflict", `\u4F1A\u8BDD ${sessionId} \u7684 seq \u5DF2\u88AB\u522B\u7684\u5199\u5165\u8005\u5360\u7528`, { sessionId });
|
|
120
|
+
}
|
|
121
|
+
throw err;
|
|
122
|
+
}
|
|
123
|
+
if (inserted === 0) {
|
|
124
|
+
const last = await this.lastSeqOf(sessionId);
|
|
125
|
+
throw new StoreError2("seq_conflict", `\u4F1A\u8BDD ${sessionId} \u671F\u671B seq=${last + 1}\uFF0C\u6536\u5230 ${first.seq}`, {
|
|
126
|
+
sessionId,
|
|
127
|
+
expected: last + 1,
|
|
128
|
+
got: first.seq
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
async lastSeqOf(sessionId) {
|
|
133
|
+
const res = await this.client.query(
|
|
134
|
+
"SELECT COALESCE(MAX(seq), 0)::int AS last FROM reins_events WHERE session_id = $1",
|
|
135
|
+
[sessionId]
|
|
136
|
+
);
|
|
137
|
+
return Number(res.rows[0]?.last ?? 0);
|
|
138
|
+
}
|
|
139
|
+
async *read(sessionId, opts = {}) {
|
|
140
|
+
let from = Math.max(opts.fromSeq ?? 1, 1);
|
|
141
|
+
const to = opts.toSeq ?? 2147483647;
|
|
142
|
+
while (from <= to) {
|
|
143
|
+
const res = await this.client.query(
|
|
144
|
+
"SELECT data FROM reins_events WHERE session_id = $1 AND seq >= $2 AND seq <= $3 ORDER BY seq LIMIT $4",
|
|
145
|
+
[sessionId, from, to, READ_PAGE]
|
|
146
|
+
);
|
|
147
|
+
for (const row of res.rows) yield eventOf(row.data);
|
|
148
|
+
if (res.rows.length < READ_PAGE) return;
|
|
149
|
+
from += res.rows.length;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
async tail(sessionId, n) {
|
|
153
|
+
if (!Number.isInteger(n) || n < 0)
|
|
154
|
+
throw new StoreError2("invalid_argument", `tail \u7684 n \u5FC5\u987B\u662F\u975E\u8D1F\u6574\u6570\uFF1A${n}`);
|
|
155
|
+
if (n === 0) return [];
|
|
156
|
+
const res = await this.client.query(
|
|
157
|
+
"SELECT data FROM reins_events WHERE session_id = $1 ORDER BY seq DESC LIMIT $2",
|
|
158
|
+
[sessionId, n]
|
|
159
|
+
);
|
|
160
|
+
return res.rows.reverse().map((r) => eventOf(r.data));
|
|
161
|
+
}
|
|
162
|
+
async fork(fromSessionId, atSeq, toSessionId) {
|
|
163
|
+
const lastSeq = await this.lastSeqOf(fromSessionId);
|
|
164
|
+
if (!Number.isInteger(atSeq) || atSeq < 1 || atSeq > lastSeq) {
|
|
165
|
+
throw new StoreError2(
|
|
166
|
+
"out_of_range",
|
|
167
|
+
`fork \u70B9 ${atSeq} \u8D85\u51FA\u4F1A\u8BDD ${fromSessionId} \u7684\u8303\u56F4 [1, ${lastSeq}]`,
|
|
168
|
+
{
|
|
169
|
+
fromSessionId,
|
|
170
|
+
atSeq,
|
|
171
|
+
lastSeq
|
|
172
|
+
}
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
if (await this.lastSeqOf(toSessionId) > 0) {
|
|
176
|
+
throw new StoreError2("target_not_empty", `\u76EE\u6807\u4F1A\u8BDD ${toSessionId} \u5DF2\u6709\u4E8B\u4EF6`, { toSessionId });
|
|
177
|
+
}
|
|
178
|
+
const source = (await collect(this.read(fromSessionId, { toSeq: atSeq }))).map((e) => ({
|
|
179
|
+
...e,
|
|
180
|
+
sessionId: toSessionId
|
|
181
|
+
}));
|
|
182
|
+
let inserted;
|
|
183
|
+
try {
|
|
184
|
+
const res = await this.client.query(
|
|
185
|
+
`INSERT INTO reins_events (session_id, seq, id, type, at, data)
|
|
186
|
+
SELECT $1, u.seq, u.id, u.type, u.at, u.data
|
|
187
|
+
FROM unnest($2::int[], $3::text[], $4::text[], $5::bigint[], $6::json[]) AS u(seq, id, type, at, data)
|
|
188
|
+
WHERE NOT EXISTS (SELECT 1 FROM reins_events WHERE session_id = $1)
|
|
189
|
+
RETURNING seq`,
|
|
190
|
+
[
|
|
191
|
+
toSessionId,
|
|
192
|
+
source.map((e) => e.seq),
|
|
193
|
+
source.map((e) => e.id),
|
|
194
|
+
source.map((e) => e.type),
|
|
195
|
+
source.map((e) => e.at),
|
|
196
|
+
source.map((e) => JSON.stringify(e))
|
|
197
|
+
]
|
|
198
|
+
);
|
|
199
|
+
inserted = res.rows.length;
|
|
200
|
+
} catch (err) {
|
|
201
|
+
if (isUniqueViolation(err)) {
|
|
202
|
+
throw new StoreError2("target_not_empty", `\u76EE\u6807\u4F1A\u8BDD ${toSessionId} \u5DF2\u6709\u4E8B\u4EF6`, { toSessionId });
|
|
203
|
+
}
|
|
204
|
+
throw err;
|
|
205
|
+
}
|
|
206
|
+
if (inserted === 0)
|
|
207
|
+
throw new StoreError2("target_not_empty", `\u76EE\u6807\u4F1A\u8BDD ${toSessionId} \u5DF2\u6709\u4E8B\u4EF6`, { toSessionId });
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
function eventOf(data) {
|
|
211
|
+
return typeof data === "string" ? JSON.parse(data) : data;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// src/schema.ts
|
|
215
|
+
import { StoreError as StoreError3 } from "@reinsjs/core";
|
|
216
|
+
var DEFAULT_MEMORY_TABLE = "reins_memory";
|
|
217
|
+
function assertTableName(name, what = "memoryTable") {
|
|
218
|
+
if (typeof name !== "string" || !/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(name)) {
|
|
219
|
+
throw new StoreError3("invalid_argument", `${what} \u4E0D\u662F\u5408\u6CD5\u8868\u540D\uFF08^[A-Za-z_][A-Za-z0-9_]{0,62}$\uFF09`, {
|
|
220
|
+
[what]: name
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
return name;
|
|
224
|
+
}
|
|
225
|
+
function pgSchemaStatements(opts = {}) {
|
|
226
|
+
const memoryTable = assertTableName(opts.memoryTable ?? DEFAULT_MEMORY_TABLE);
|
|
227
|
+
return [
|
|
228
|
+
`CREATE TABLE IF NOT EXISTS reins_events (
|
|
229
|
+
session_id text NOT NULL,
|
|
230
|
+
seq integer NOT NULL,
|
|
231
|
+
id text NOT NULL,
|
|
232
|
+
type text NOT NULL,
|
|
233
|
+
at bigint NOT NULL,
|
|
234
|
+
data json NOT NULL,
|
|
235
|
+
PRIMARY KEY (session_id, seq)
|
|
236
|
+
)`,
|
|
237
|
+
`CREATE TABLE IF NOT EXISTS reins_blobs (
|
|
238
|
+
id text PRIMARY KEY,
|
|
239
|
+
session_id text NOT NULL,
|
|
240
|
+
mime text NOT NULL,
|
|
241
|
+
size integer NOT NULL,
|
|
242
|
+
created_at bigint NOT NULL,
|
|
243
|
+
bytes bytea NOT NULL
|
|
244
|
+
)`,
|
|
245
|
+
`CREATE TABLE IF NOT EXISTS ${memoryTable} (
|
|
246
|
+
path text PRIMARY KEY,
|
|
247
|
+
content text NOT NULL,
|
|
248
|
+
updated_at bigint NOT NULL
|
|
249
|
+
)`
|
|
250
|
+
];
|
|
251
|
+
}
|
|
252
|
+
var PG_SCHEMA_STATEMENTS = pgSchemaStatements();
|
|
253
|
+
var PG_SCHEMA_SQL = `${PG_SCHEMA_STATEMENTS.join(";\n")};
|
|
254
|
+
`;
|
|
255
|
+
async function migratePg(client, opts = {}) {
|
|
256
|
+
for (const statement of pgSchemaStatements(opts)) await client.query(statement);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// src/memory-store.ts
|
|
260
|
+
var PgMemoryStore = class {
|
|
261
|
+
constructor(client, opts = {}) {
|
|
262
|
+
this.client = client;
|
|
263
|
+
this.table = assertTableName(opts.table ?? DEFAULT_MEMORY_TABLE, "table");
|
|
264
|
+
this.now = opts.now ?? (() => Date.now());
|
|
265
|
+
}
|
|
266
|
+
client;
|
|
267
|
+
table;
|
|
268
|
+
now;
|
|
269
|
+
async list(prefix) {
|
|
270
|
+
const res = await this.client.query(
|
|
271
|
+
`SELECT path FROM ${this.table} WHERE left(path, $2) = $1 ORDER BY path COLLATE "C"`,
|
|
272
|
+
[prefix, prefix.length]
|
|
273
|
+
);
|
|
274
|
+
return res.rows.map((r) => r.path);
|
|
275
|
+
}
|
|
276
|
+
async read(path) {
|
|
277
|
+
const res = await this.client.query(`SELECT content FROM ${this.table} WHERE path = $1`, [path]);
|
|
278
|
+
const row = res.rows[0];
|
|
279
|
+
return row ? row.content : null;
|
|
280
|
+
}
|
|
281
|
+
async write(path, content) {
|
|
282
|
+
await this.client.query(
|
|
283
|
+
`INSERT INTO ${this.table} (path, content, updated_at) VALUES ($1, $2, $3)
|
|
284
|
+
ON CONFLICT (path) DO UPDATE SET content = EXCLUDED.content, updated_at = EXCLUDED.updated_at`,
|
|
285
|
+
[path, content, this.now()]
|
|
286
|
+
);
|
|
287
|
+
}
|
|
288
|
+
async delete(path) {
|
|
289
|
+
await this.client.query(`DELETE FROM ${this.table} WHERE path = $1`, [path]);
|
|
290
|
+
}
|
|
291
|
+
};
|
|
292
|
+
|
|
293
|
+
// src/stores.ts
|
|
294
|
+
async function pgStores(client, opts = {}) {
|
|
295
|
+
const schema = {};
|
|
296
|
+
const memoryOpts = {};
|
|
297
|
+
if (opts.memoryTable !== void 0) {
|
|
298
|
+
schema.memoryTable = opts.memoryTable;
|
|
299
|
+
memoryOpts.table = opts.memoryTable;
|
|
300
|
+
}
|
|
301
|
+
if (opts.now !== void 0) memoryOpts.now = opts.now;
|
|
302
|
+
if (opts.migrate !== false) await migratePg(client, schema);
|
|
303
|
+
return {
|
|
304
|
+
log: new PgEventLog(client),
|
|
305
|
+
blobs: new PgBlobStore(client, opts.now),
|
|
306
|
+
memory: new PgMemoryStore(client, memoryOpts)
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
export {
|
|
310
|
+
DEFAULT_MEMORY_TABLE,
|
|
311
|
+
PG_SCHEMA_SQL,
|
|
312
|
+
PG_SCHEMA_STATEMENTS,
|
|
313
|
+
PgBlobStore,
|
|
314
|
+
PgEventLog,
|
|
315
|
+
PgMemoryStore,
|
|
316
|
+
assertTableName,
|
|
317
|
+
isUniqueViolation,
|
|
318
|
+
migratePg,
|
|
319
|
+
pgSchemaStatements,
|
|
320
|
+
pgStores
|
|
321
|
+
};
|
|
322
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/blob-store.ts","../src/client.ts","../src/event-log.ts","../src/schema.ts","../src/memory-store.ts","../src/stores.ts"],"sourcesContent":["import { type BlobMeta, type BlobStore, StoreError, uuidv7 } from \"@reinsjs/core\"\nimport type { PgClient } from \"./client.js\"\n\ninterface MetaRow {\n session_id: string\n mime: string\n size: number | string\n created_at: number | string\n}\n\n/** Postgres 大对象存储:bytea 列;`slice` 用 substring 在库内切 */\nexport class PgBlobStore implements BlobStore {\n constructor(\n private readonly client: PgClient,\n private readonly now: () => number = () => Date.now(),\n ) {}\n\n async put(bytes: Uint8Array | string, meta: { mime: string; sessionId: string }): Promise<{ id: string }> {\n const data = typeof bytes === \"string\" ? new TextEncoder().encode(bytes) : bytes\n const id = uuidv7()\n await this.client.query(\n \"INSERT INTO reins_blobs (id, session_id, mime, size, created_at, bytes) VALUES ($1, $2, $3, $4, $5, $6)\",\n [id, meta.sessionId, meta.mime, data.byteLength, this.now(), data],\n )\n return { id }\n }\n\n async get(id: string): Promise<{ bytes: Uint8Array; meta: BlobMeta }> {\n const res = await this.client.query(\n \"SELECT session_id, mime, size, created_at, bytes FROM reins_blobs WHERE id = $1\",\n [id],\n )\n const row = res.rows[0] as (MetaRow & { bytes: Uint8Array }) | undefined\n if (!row) throw new StoreError(\"not_found\", `blob 不存在:${id}`, { id })\n return { bytes: new Uint8Array(row.bytes), meta: metaOf(row) }\n }\n\n async slice(id: string, range: { start: number; end: number }): Promise<Uint8Array> {\n const start = Math.max(0, Math.floor(range.start))\n const length = Math.max(0, Math.floor(range.end) - start)\n const res = await this.client.query(\n \"SELECT substring(bytes FROM $2 FOR $3) AS part FROM reins_blobs WHERE id = $1\",\n [id, start + 1, length],\n )\n const row = res.rows[0] as { part: Uint8Array | null } | undefined\n if (!row) throw new StoreError(\"not_found\", `blob 不存在:${id}`, { id })\n return row.part ? new Uint8Array(row.part) : new Uint8Array(0)\n }\n}\n\n/** pg 把 bigint 当字符串返回,integer 是数字;统一成 number */\nfunction metaOf(row: MetaRow): BlobMeta {\n return {\n mime: row.mime,\n sessionId: row.session_id,\n size: Number(row.size),\n createdAt: Number(row.created_at),\n }\n}\n","/**\n * Postgres 客户端的最小形状:`query(text, params) → { rows }`。\n * `pg` 的 Pool / Client、`@electric-sql/pglite` 的 PGlite 都直接满足;postgres.js 之类用标签模板的库包一层即可。\n *\n * 本包**不依赖事务**:每个写操作都是单条语句(append 用 unnest 一次插入整批、fork 用 INSERT … SELECT),\n * 单条语句在 Postgres 里天然原子,所以传连接池进来也是对的 —— 不必为了 BEGIN/COMMIT 从池里借同一条连接。\n */\nexport interface PgQueryResult {\n rows: Record<string, unknown>[]\n}\n\nexport interface PgClient {\n query(text: string, params?: readonly unknown[]): Promise<PgQueryResult>\n}\n\n/** Postgres 的唯一约束冲突(SQLSTATE 23505);pg 与 PGlite 都把它放在 err.code */\nexport function isUniqueViolation(err: unknown): boolean {\n return typeof err === \"object\" && err !== null && (err as { code?: unknown }).code === \"23505\"\n}\n","import { type Event, type EventLog, type ReadOptions, StoreError } from \"@reinsjs/core\"\nimport { isUniqueViolation, type PgClient } from \"./client.js\"\n\nasync function collect<T>(iter: AsyncIterable<T>): Promise<T[]> {\n const out: T[] = []\n for await (const x of iter) out.push(x)\n return out\n}\n\nconst READ_PAGE = 500\n\n/**\n * Postgres 事件日志。契约与内存实现一致(技术方案 §5)。\n *\n * append 是**一条语句**:`INSERT … SELECT FROM unnest(...) WHERE 当前末尾 = 首条 seq − 1`。\n * 末尾不符(别人已经写了)→ 一行都不插,返回空 → seq_conflict;两个写入者同时通过 WHERE 检查 → 主键冲突(23505)→ seq_conflict。\n * 不开事务、不借连接,传连接池也正确。\n */\nexport class PgEventLog implements EventLog {\n constructor(private readonly client: PgClient) {}\n\n async append(events: readonly Event[]): Promise<void> {\n if (events.length === 0) throw new StoreError(\"empty_batch\", \"append 的事件数组为空\")\n const first = events[0] as Event\n const sessionId = first.sessionId\n let expected = first.seq\n for (const e of events) {\n if (e.sessionId !== sessionId) {\n throw new StoreError(\"session_mismatch\", \"同一批 append 必须属于同一个会话\", {\n expected: sessionId,\n got: e.sessionId,\n })\n }\n if (e.seq !== expected) {\n throw new StoreError(\n \"seq_conflict\",\n `会话 ${sessionId} 一批内 seq 不连续:期望 ${expected},收到 ${e.seq}`,\n {\n sessionId,\n expected,\n got: e.seq,\n },\n )\n }\n expected++\n }\n if (first.seq < 1) {\n throw new StoreError(\"seq_conflict\", `会话 ${sessionId} 的 seq 必须从 1 起,收到 ${first.seq}`, {\n sessionId,\n got: first.seq,\n })\n }\n\n let inserted: number\n try {\n const res = await this.client.query(\n `INSERT INTO reins_events (session_id, seq, id, type, at, data)\n SELECT $1, u.seq, u.id, u.type, u.at, u.data\n FROM unnest($2::int[], $3::text[], $4::text[], $5::bigint[], $6::json[]) AS u(seq, id, type, at, data)\n WHERE (SELECT COALESCE(MAX(seq), 0) FROM reins_events WHERE session_id = $1) = $7\n RETURNING seq`,\n [\n sessionId,\n events.map((e) => e.seq),\n events.map((e) => e.id),\n events.map((e) => e.type),\n events.map((e) => e.at),\n events.map((e) => JSON.stringify(e)),\n first.seq - 1,\n ],\n )\n inserted = res.rows.length\n } catch (err) {\n if (isUniqueViolation(err)) {\n throw new StoreError(\"seq_conflict\", `会话 ${sessionId} 的 seq 已被别的写入者占用`, { sessionId })\n }\n throw err\n }\n if (inserted === 0) {\n const last = await this.lastSeqOf(sessionId)\n throw new StoreError(\"seq_conflict\", `会话 ${sessionId} 期望 seq=${last + 1},收到 ${first.seq}`, {\n sessionId,\n expected: last + 1,\n got: first.seq,\n })\n }\n }\n\n private async lastSeqOf(sessionId: string): Promise<number> {\n const res = await this.client.query(\n \"SELECT COALESCE(MAX(seq), 0)::int AS last FROM reins_events WHERE session_id = $1\",\n [sessionId],\n )\n return Number(res.rows[0]?.last ?? 0)\n }\n\n async *read(sessionId: string, opts: ReadOptions = {}): AsyncIterable<Event> {\n let from = Math.max(opts.fromSeq ?? 1, 1)\n const to = opts.toSeq ?? 2_147_483_647\n while (from <= to) {\n const res = await this.client.query(\n \"SELECT data FROM reins_events WHERE session_id = $1 AND seq >= $2 AND seq <= $3 ORDER BY seq LIMIT $4\",\n [sessionId, from, to, READ_PAGE],\n )\n for (const row of res.rows) yield eventOf(row.data)\n if (res.rows.length < READ_PAGE) return\n from += res.rows.length\n }\n }\n\n async tail(sessionId: string, n: number): Promise<Event[]> {\n if (!Number.isInteger(n) || n < 0)\n throw new StoreError(\"invalid_argument\", `tail 的 n 必须是非负整数:${n}`)\n if (n === 0) return []\n const res = await this.client.query(\n \"SELECT data FROM reins_events WHERE session_id = $1 ORDER BY seq DESC LIMIT $2\",\n [sessionId, n],\n )\n return res.rows.reverse().map((r) => eventOf(r.data))\n }\n\n async fork(fromSessionId: string, atSeq: number, toSessionId: string): Promise<void> {\n const lastSeq = await this.lastSeqOf(fromSessionId)\n if (!Number.isInteger(atSeq) || atSeq < 1 || atSeq > lastSeq) {\n throw new StoreError(\n \"out_of_range\",\n `fork 点 ${atSeq} 超出会话 ${fromSessionId} 的范围 [1, ${lastSeq}]`,\n {\n fromSessionId,\n atSeq,\n lastSeq,\n },\n )\n }\n if ((await this.lastSeqOf(toSessionId)) > 0) {\n throw new StoreError(\"target_not_empty\", `目标会话 ${toSessionId} 已有事件`, { toSessionId })\n }\n // 读出 → 改 sessionId → 整批插回。json 列没有 jsonb_set 可用,而改成 jsonb 会重排键序(见 schema.ts),\n // 所以在 JS 里改;插回用与 append 相同的\"目标末尾必须为 0\"守卫 + 主键约束,检查与插入之间有人写了目标会话也不会交错\n const source = (await collect(this.read(fromSessionId, { toSeq: atSeq }))).map((e) => ({\n ...e,\n sessionId: toSessionId,\n }))\n let inserted: number\n try {\n const res = await this.client.query(\n `INSERT INTO reins_events (session_id, seq, id, type, at, data)\n SELECT $1, u.seq, u.id, u.type, u.at, u.data\n FROM unnest($2::int[], $3::text[], $4::text[], $5::bigint[], $6::json[]) AS u(seq, id, type, at, data)\n WHERE NOT EXISTS (SELECT 1 FROM reins_events WHERE session_id = $1)\n RETURNING seq`,\n [\n toSessionId,\n source.map((e) => e.seq),\n source.map((e) => e.id),\n source.map((e) => e.type),\n source.map((e) => e.at),\n source.map((e) => JSON.stringify(e)),\n ],\n )\n inserted = res.rows.length\n } catch (err) {\n if (isUniqueViolation(err)) {\n throw new StoreError(\"target_not_empty\", `目标会话 ${toSessionId} 已有事件`, { toSessionId })\n }\n throw err\n }\n if (inserted === 0)\n throw new StoreError(\"target_not_empty\", `目标会话 ${toSessionId} 已有事件`, { toSessionId })\n }\n}\n\n/** json 列:pg 与 PGlite 都已解析成对象(文本原样 → 键序不变);万一驱动给的是字符串也兼容 */\nfunction eventOf(data: unknown): Event {\n return (typeof data === \"string\" ? JSON.parse(data) : data) as Event\n}\n","import { StoreError } from \"@reinsjs/core\"\nimport type { PgClient } from \"./client.js\"\n\n/** 记忆表缺省名。事件表与 blob 表不可配:它们由 EventLog / BlobStore 的契约唯一确定,隔离靠 session_id */\nexport const DEFAULT_MEMORY_TABLE = \"reins_memory\"\n\n/**\n * 表名只认 `字母 / 下划线开头 + 字母数字下划线`,长度 ≤ 63(Postgres 标识符上限,超长会被静默截断成别的名字)。\n * 表名会被字面拼进 SQL(参数绑定不了标识符),这个白名单就是防注入的唯一一道闸;不合规直接抛,不碰数据库。\n * 不加引号:未加引号的标识符 Postgres 统一折成小写,DDL 与查询走同一条折叠规则,两边一致。\n */\nexport function assertTableName(name: string, what = \"memoryTable\"): string {\n if (typeof name !== \"string\" || !/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(name)) {\n throw new StoreError(\"invalid_argument\", `${what} 不是合法表名(^[A-Za-z_][A-Za-z0-9_]{0,62}$)`, {\n [what]: name,\n })\n }\n return name\n}\n\nexport interface PgSchemaOptions {\n /** 记忆表名。缺省 `reins_memory`;多套记忆共用一个库时按表隔离(技术方案 §9.6 隔离第一层) */\n memoryTable?: string\n}\n\n/**\n * 三张表。事件整条存 `json`(`data`),壳字段抽几列做主键与查询;主键 (session_id, seq) 的唯一约束是并发写入者的最后一道闸。\n * `at` / `created_at` / `updated_at` 是 Unix 毫秒(bigint),读事件时不用它们 —— 事件从 data 整条还原。\n *\n * **为什么是 json 不是 jsonb**:jsonb 会重排对象键序,读回来 `JSON.stringify` 就变了;而 T10 的 pendingDigest / configHash\n * 正是按 JSON.stringify 算的,存 Postgres 的会话一续跑就会误报\"pending 被篡改\"。json 按文本原样存取,各后端逐字节一致。\n */\nexport function pgSchemaStatements(opts: PgSchemaOptions = {}): readonly string[] {\n const memoryTable = assertTableName(opts.memoryTable ?? DEFAULT_MEMORY_TABLE)\n return [\n `CREATE TABLE IF NOT EXISTS reins_events (\n session_id text NOT NULL,\n seq integer NOT NULL,\n id text NOT NULL,\n type text NOT NULL,\n at bigint NOT NULL,\n data json NOT NULL,\n PRIMARY KEY (session_id, seq)\n)`,\n `CREATE TABLE IF NOT EXISTS reins_blobs (\n id text PRIMARY KEY,\n session_id text NOT NULL,\n mime text NOT NULL,\n size integer NOT NULL,\n created_at bigint NOT NULL,\n bytes bytea NOT NULL\n)`,\n `CREATE TABLE IF NOT EXISTS ${memoryTable} (\n path text PRIMARY KEY,\n content text NOT NULL,\n updated_at bigint NOT NULL\n)`,\n ]\n}\n\n/** 缺省表名的逐条 DDL */\nexport const PG_SCHEMA_STATEMENTS: readonly string[] = pgSchemaStatements()\n\n/** 缺省表名的整段 DDL(给 psql / 迁移工具用) */\nexport const PG_SCHEMA_SQL = `${PG_SCHEMA_STATEMENTS.join(\";\\n\")};\\n`\n\n/**\n * 建表(幂等)。pgStores() 缺省会调;自己管迁移的宿主可直接执行 PG_SCHEMA_SQL / pgSchemaStatements(opts)。\n * 逐条执行:走扩展协议的客户端(PGlite、pg 的带参查询)不接受一次多条语句。\n */\nexport async function migratePg(client: PgClient, opts: PgSchemaOptions = {}): Promise<void> {\n for (const statement of pgSchemaStatements(opts)) await client.query(statement)\n}\n","import type { MemoryStore } from \"@reinsjs/core\"\nimport type { PgClient } from \"./client.js\"\nimport { assertTableName, DEFAULT_MEMORY_TABLE } from \"./schema.js\"\n\nexport interface PgMemoryStoreOptions {\n /** 表名。缺省 `reins_memory` */\n table?: string\n /** 测试注入时间 */\n now?: () => number\n}\n\n/** Postgres 记忆后端:路径 → 文本。前缀匹配用 left(),不用 LIKE(免转义);排序用 \"C\" 排序规则得到与内存实现一致的字节序 */\nexport class PgMemoryStore implements MemoryStore {\n private readonly table: string\n private readonly now: () => number\n\n constructor(\n private readonly client: PgClient,\n opts: PgMemoryStoreOptions = {},\n ) {\n // 表名字面拼进 SQL,先过白名单(schema.ts 同一条规则)\n this.table = assertTableName(opts.table ?? DEFAULT_MEMORY_TABLE, \"table\")\n this.now = opts.now ?? (() => Date.now())\n }\n\n async list(prefix: string): Promise<string[]> {\n const res = await this.client.query(\n `SELECT path FROM ${this.table} WHERE left(path, $2) = $1 ORDER BY path COLLATE \"C\"`,\n [prefix, prefix.length],\n )\n return res.rows.map((r) => r.path as string)\n }\n\n async read(path: string): Promise<string | null> {\n const res = await this.client.query(`SELECT content FROM ${this.table} WHERE path = $1`, [path])\n const row = res.rows[0]\n return row ? (row.content as string) : null\n }\n\n async write(path: string, content: string): Promise<void> {\n await this.client.query(\n `INSERT INTO ${this.table} (path, content, updated_at) VALUES ($1, $2, $3)\n ON CONFLICT (path) DO UPDATE SET content = EXCLUDED.content, updated_at = EXCLUDED.updated_at`,\n [path, content, this.now()],\n )\n }\n\n async delete(path: string): Promise<void> {\n await this.client.query(`DELETE FROM ${this.table} WHERE path = $1`, [path])\n }\n}\n","import type { Stores } from \"@reinsjs/core\"\nimport { PgBlobStore } from \"./blob-store.js\"\nimport type { PgClient } from \"./client.js\"\nimport { PgEventLog } from \"./event-log.js\"\nimport { PgMemoryStore, type PgMemoryStoreOptions } from \"./memory-store.js\"\nimport { migratePg, type PgSchemaOptions } from \"./schema.js\"\n\nexport interface PgStoresOptions {\n /** 起步时建表(幂等)。缺省 true;自己管迁移的宿主传 false */\n migrate?: boolean\n /**\n * 记忆表名,缺省 `reins_memory`。多个 agent 共用一个库、各自一套记忆时,每个传不同的表名;\n * 事件表与 blob 表始终共用(按 session_id 隔离),建表语句随表名同步。\n */\n memoryTable?: string\n /** 测试注入时间 */\n now?: () => number\n}\n\n/**\n * 一套 Postgres 存储:`createAgent({ store: await pgStores(pool) })`。\n * client 是任何有 `query(text, params) → { rows }` 的对象:pg 的 Pool / Client、PGlite 实例。\n */\nexport async function pgStores(client: PgClient, opts: PgStoresOptions = {}): Promise<Stores> {\n const schema: PgSchemaOptions = {}\n const memoryOpts: PgMemoryStoreOptions = {}\n if (opts.memoryTable !== undefined) {\n schema.memoryTable = opts.memoryTable\n memoryOpts.table = opts.memoryTable\n }\n if (opts.now !== undefined) memoryOpts.now = opts.now\n if (opts.migrate !== false) await migratePg(client, schema)\n return {\n log: new PgEventLog(client),\n blobs: new PgBlobStore(client, opts.now),\n memory: new PgMemoryStore(client, memoryOpts),\n }\n}\n"],"mappings":";AAAA,SAAwC,YAAY,cAAc;AAW3D,IAAM,cAAN,MAAuC;AAAA,EAC5C,YACmB,QACA,MAAoB,MAAM,KAAK,IAAI,GACpD;AAFiB;AACA;AAAA,EAChB;AAAA,EAFgB;AAAA,EACA;AAAA,EAGnB,MAAM,IAAI,OAA4B,MAAoE;AACxG,UAAM,OAAO,OAAO,UAAU,WAAW,IAAI,YAAY,EAAE,OAAO,KAAK,IAAI;AAC3E,UAAM,KAAK,OAAO;AAClB,UAAM,KAAK,OAAO;AAAA,MAChB;AAAA,MACA,CAAC,IAAI,KAAK,WAAW,KAAK,MAAM,KAAK,YAAY,KAAK,IAAI,GAAG,IAAI;AAAA,IACnE;AACA,WAAO,EAAE,GAAG;AAAA,EACd;AAAA,EAEA,MAAM,IAAI,IAA4D;AACpE,UAAM,MAAM,MAAM,KAAK,OAAO;AAAA,MAC5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.json
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@reinsjs/store-pg",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "reins — PostgreSQL-backed EventLog / BlobStore / MemoryStore. Works with any client exposing query(text, params) → { rows } (pg, PGlite, …)",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"agent",
|
|
7
|
+
"event-log",
|
|
8
|
+
"postgres",
|
|
9
|
+
"postgresql",
|
|
10
|
+
"pglite"
|
|
11
|
+
],
|
|
12
|
+
"license": "MIT",
|
|
13
|
+
"author": "NewRate Limited (https://www.adrate.io)",
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "git+https://github.com/AdRate-io/reins.git",
|
|
17
|
+
"directory": "packages/store-pg"
|
|
18
|
+
},
|
|
19
|
+
"homepage": "https://github.com/AdRate-io/reins/tree/main/packages/store-pg#readme",
|
|
20
|
+
"bugs": "https://github.com/AdRate-io/reins/issues",
|
|
21
|
+
"type": "module",
|
|
22
|
+
"sideEffects": false,
|
|
23
|
+
"exports": {
|
|
24
|
+
".": {
|
|
25
|
+
"types": "./dist/index.d.ts",
|
|
26
|
+
"import": "./dist/index.js"
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
"files": [
|
|
30
|
+
"dist",
|
|
31
|
+
"CHANGELOG.md"
|
|
32
|
+
],
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"@reinsjs/core": "0.1.0"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@electric-sql/pglite": "0.5.8",
|
|
38
|
+
"@types/node": "^22.0.0",
|
|
39
|
+
"@types/pg": "^8.23.0",
|
|
40
|
+
"pg": "^8.23.0"
|
|
41
|
+
},
|
|
42
|
+
"engines": {
|
|
43
|
+
"node": ">=22"
|
|
44
|
+
},
|
|
45
|
+
"scripts": {
|
|
46
|
+
"build": "tsup"
|
|
47
|
+
}
|
|
48
|
+
}
|