@soiljs/storage-postgres 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +98 -2
- package/dist/chunk-ZGVSDKKX.js +111 -0
- package/dist/chunk-ZGVSDKKX.js.map +1 -0
- package/dist/index.d.ts +41 -0
- package/dist/index.js +1423 -0
- package/dist/index.js.map +1 -0
- package/dist/s3/index.d.ts +18 -0
- package/dist/s3/index.js +3 -0
- package/dist/s3/index.js.map +1 -0
- package/package.json +52 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ximing
|
|
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,99 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @soiljs/storage-postgres
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
把 Soil 的结构化账本与 Outbox 存入 PostgreSQL,并按需将大产物放到 S3。它是依赖 SPI 与 `pg` 的 Layer 1 存储包,不在运行时依赖 Agent/models,也不执行工具;适合已有 PostgreSQL 运维体系、需要作用域分区的服务,要求 Node.js ≥22.19。
|
|
4
|
+
|
|
5
|
+
## 安装与入口
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
pnpm add @soiljs/storage-postgres
|
|
9
|
+
# 仅在使用真实 S3 时安装可选 peer
|
|
10
|
+
pnpm add @aws-sdk/client-s3
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
| 导出入口 | 用途 |
|
|
14
|
+
| --- | --- |
|
|
15
|
+
| `@soiljs/storage-postgres` | `postgresStorage`、配置/结构化连接类型、`postgresMigrations`、`POSTGRES_SCHEMA_VERSION`、`s3Artifacts` |
|
|
16
|
+
| `@soiljs/storage-postgres/s3` | S3 产物适配器与配置/客户端类型 |
|
|
17
|
+
|
|
18
|
+
SDK 在首次 S3 操作时动态加载,导入任一入口不会加载。所有导出指向 `dist`。
|
|
19
|
+
|
|
20
|
+
## 最小可运行示例
|
|
21
|
+
|
|
22
|
+
准备专用 PostgreSQL 数据库并设置 `DATABASE_URL`,下面打开存储、执行迁移后关闭。与 Runtime 组合时将其传入 `openRuntime({ storage, agents })`,由 Runtime 管理生命周期。
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
import { postgresStorage } from "@soiljs/storage-postgres";
|
|
26
|
+
|
|
27
|
+
const connectionString = process.env.DATABASE_URL;
|
|
28
|
+
if (!connectionString) throw new Error("请配置专用 DATABASE_URL");
|
|
29
|
+
|
|
30
|
+
const storage = postgresStorage({
|
|
31
|
+
connectionString,
|
|
32
|
+
schema: "soil",
|
|
33
|
+
scope: { tenantId: "shop", projectId: "orders" },
|
|
34
|
+
});
|
|
35
|
+
await storage.open();
|
|
36
|
+
try {
|
|
37
|
+
console.log(storage.kind); // postgres;产物默认内联数据库
|
|
38
|
+
} finally {
|
|
39
|
+
await storage.close();
|
|
40
|
+
}
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
S3 可独立选择,与账本连接配置组合:
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
import { s3Artifacts } from "@soiljs/storage-postgres/s3";
|
|
47
|
+
|
|
48
|
+
const artifacts = s3Artifacts({
|
|
49
|
+
bucket: "my-agent-artifacts",
|
|
50
|
+
prefix: "soil-artifacts/",
|
|
51
|
+
clientConfig: { region: "ap-southeast-1" },
|
|
52
|
+
});
|
|
53
|
+
// postgresStorage({ connectionString, artifacts })
|
|
54
|
+
console.log(typeof artifacts.put);
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## 连接、配置与迁移
|
|
58
|
+
|
|
59
|
+
| 配置 | 约束与生命周期 |
|
|
60
|
+
| --- | --- |
|
|
61
|
+
| `connectionString` / `pool` / `client` | **三选一**;字符串创建自有 pg.Pool 并随 close 结束;注入 Pool 由调用者关闭 |
|
|
62
|
+
| `client` | 已连接且独占的结构化 `PgClientLike`,适配器串行化事务且不替调用者关闭 |
|
|
63
|
+
| `schema` | 默认 `soil`,仅简单 PostgreSQL 标识符 |
|
|
64
|
+
| `migrate` | 默认在 open 时迁移;集中迁移后可设 false |
|
|
65
|
+
| `scope` | 固定 `{ tenantId?, projectId? }` 分区绑定 |
|
|
66
|
+
| `artifacts` | 默认 PostgreSQL 内联;可注入 `s3Artifacts(...)` |
|
|
67
|
+
|
|
68
|
+
`open()` 在事务 advisory lock 下按版本应用 `postgresMigrations(schema)`;DDL 与记录可重复执行,`POSTGRES_SCHEMA_VERSION` 指示版本。集中管理时按版本顺序应用导出 SQL,再设 `migrate: false`。适配器本身不自动读取 `DATABASE_URL` 或 `ARTIFACT_BUCKET`,示例由宿主读取;S3 客户端可用 AWS SDK 标准凭证配置,勿在代码中硬编码凭证。
|
|
69
|
+
|
|
70
|
+
`PgPoolLike` / `PgClientLike` 是结构化端口,支持真实 pg 与确定性离线传输。绑定 scope 从创建起固定,所有账本、命令、游标、Outbox 与内联产物 SQL 使用该分区;相同实体 ID 在不同绑定分区独立。Session 省略 scope 时继承,冲突 scope 拒绝。未绑定适配器使用默认分区,适合可信应用的全局唯一 ID,不应作为面向不可信调用者的授权边界。
|
|
71
|
+
|
|
72
|
+
## 账本、Outbox 与产物
|
|
73
|
+
|
|
74
|
+
每次修改在同一连接内执行 BEGIN、分区元数据行 `SELECT ... FOR UPDATE`、领域检查、变更行、Outbox 与 COMMIT;失败整体回滚。T1–T7 覆盖准入/FIFO、Steering、派发、独立 Step/Attempt 提交、子 Turn 唤醒、命令与终态激活。分区内写入串行化,不同分区可并发;只读取所需 Turn 家族/队列/历史并写变化行,快照支持独占 `afterStepId` 分页。
|
|
75
|
+
|
|
76
|
+
租约 holder、持久 epoch 与过期时间先于 Step 版本/状态检查;时钟取获取分区锁后的数据库时间。每次取得租约都递增 epoch,丢失所有权抛 `LeaseLostError`。终态 Attempt 不覆盖,命令在 Runtime 授权后仍经过存储 scope/状态校验。分区行锁优先保障正确性,不能据此宣称最高写吞吐或已有多工作进程调度。
|
|
77
|
+
|
|
78
|
+
Outbox 与账本同事务写入,使用 BIGSERIAL,回滚/其他 scope 活动可能导致序号跳跃。消费者确认在 scoped 游标上单调前进,裁剪保存高水位与原因,落后读返回显式 gap;超过 JavaScript 安全整数范围直接失败。
|
|
79
|
+
|
|
80
|
+
默认内联产物保存在 `artifact_blobs_meta`,读时验证长度与摘要;回收在分区锁内最终重查 Turn/Step/Attempt 引用。S3 对象为 `<prefix>sha256/<前两位>/<sha256>`,条件写保持不可变并去重,读只接受本 bucket/prefix 的精确引用并验证摘要/大小。注入的 AWS client 由调用者持有,也可 `clientConfig` 延迟创建。
|
|
81
|
+
|
|
82
|
+
`pruneUnreferenced({ olderThan, isReferenced, limit })` 分页扫描寻址对象。S3 与账本没有共同事务,调用者必须提供完整引用谓词、传播查询失败,并协调 GC 与新引用写入的竞争;采用保守保护期,例如 24 小时。先写字节、再提交引用、最后异步回收遗留写入,没有分布式两阶段提交。
|
|
83
|
+
|
|
84
|
+
## 关键边界与测试覆盖
|
|
85
|
+
|
|
86
|
+
存储不提供 exactly-once,也不自行运行恢复循环。外部操作失败/中断保持 `unknown`,由对账证据或显式授权裁决决定;租约丢失和幂等键都不意味着远端未执行。
|
|
87
|
+
|
|
88
|
+
离线 SQL 传输跑九组 SPI 契约及 SQL、回滚、栅栏、scope 隔离与重建;模拟 S3 覆盖寻址、去重、读取与回收保护。这些不证明真实 PostgreSQL 锁/DDL 或 live S3 行为。设置 `SOIL_TEST_POSTGRES_URL` 或 `DATABASE_URL` 指向专用测试库才会执行真实九组合约,使用唯一 schema 并清理;均未设置则显式跳过,显式配置但不可达则失败,不打印连接凭证。
|
|
89
|
+
|
|
90
|
+
## 深入阅读与本地校验
|
|
91
|
+
|
|
92
|
+
[在线 API](https://ximing.github.io/agent-foundation/#/api/storage) · [PostgreSQL 示例](../../examples/03-postgres-storage.ts) · [SPI 契约](../../docs/03-spi-storage-contracts.md)
|
|
93
|
+
|
|
94
|
+
```sh
|
|
95
|
+
pnpm build
|
|
96
|
+
pnpm --filter @soiljs/storage-postgres typecheck
|
|
97
|
+
pnpm --filter @soiljs/storage-postgres exec tsup
|
|
98
|
+
pnpm exec vitest run packages/storage-postgres/src/__tests__
|
|
99
|
+
```
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { createHash } from 'crypto';
|
|
2
|
+
|
|
3
|
+
// src/s3/index.ts
|
|
4
|
+
function status(error) {
|
|
5
|
+
return error?.$metadata?.httpStatusCode;
|
|
6
|
+
}
|
|
7
|
+
function name(error) {
|
|
8
|
+
return error?.name;
|
|
9
|
+
}
|
|
10
|
+
function s3Artifacts(config) {
|
|
11
|
+
if (!config.bucket || /[/?#]/.test(config.bucket)) throw new Error("Invalid S3 artifact bucket.");
|
|
12
|
+
const prefix = config.prefix ? `${config.prefix.replace(/\/+$/, "")}/` : "";
|
|
13
|
+
const keyFor = (hash) => `${prefix}sha256/${hash.slice(0, 2)}/${hash}`;
|
|
14
|
+
let transport;
|
|
15
|
+
function connect() {
|
|
16
|
+
return transport ??= import('@aws-sdk/client-s3').then((sdk) => ({
|
|
17
|
+
sdk,
|
|
18
|
+
client: config.client ?? new sdk.S3Client(config.clientConfig ?? {})
|
|
19
|
+
}));
|
|
20
|
+
}
|
|
21
|
+
return {
|
|
22
|
+
async put(input) {
|
|
23
|
+
const data = new Uint8Array(input.data);
|
|
24
|
+
const sha256 = createHash("sha256").update(data).digest("hex");
|
|
25
|
+
const { sdk, client } = await connect();
|
|
26
|
+
const command = new sdk.PutObjectCommand({
|
|
27
|
+
Bucket: config.bucket,
|
|
28
|
+
Key: keyFor(sha256),
|
|
29
|
+
Body: data,
|
|
30
|
+
ContentType: input.contentType,
|
|
31
|
+
IfNoneMatch: "*",
|
|
32
|
+
ChecksumSHA256: Buffer.from(sha256, "hex").toString("base64")
|
|
33
|
+
});
|
|
34
|
+
for (let attempt = 0; ; attempt++) {
|
|
35
|
+
try {
|
|
36
|
+
await client.send(command);
|
|
37
|
+
break;
|
|
38
|
+
} catch (error) {
|
|
39
|
+
if (status(error) === 412 || name(error) === "PreconditionFailed") break;
|
|
40
|
+
if (status(error) === 409 && attempt < 2) continue;
|
|
41
|
+
throw error;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return {
|
|
45
|
+
uri: `s3://${config.bucket}/${keyFor(sha256)}`,
|
|
46
|
+
sha256,
|
|
47
|
+
byteSize: data.byteLength,
|
|
48
|
+
contentType: input.contentType
|
|
49
|
+
};
|
|
50
|
+
},
|
|
51
|
+
async get(ref) {
|
|
52
|
+
if (!/^[a-f0-9]{64}$/.test(ref.sha256) || ref.uri !== `s3://${config.bucket}/${keyFor(ref.sha256)}`)
|
|
53
|
+
return null;
|
|
54
|
+
const { sdk, client } = await connect();
|
|
55
|
+
try {
|
|
56
|
+
const result = await client.send(
|
|
57
|
+
new sdk.GetObjectCommand({ Bucket: config.bucket, Key: keyFor(ref.sha256) })
|
|
58
|
+
);
|
|
59
|
+
if (!result.Body) throw new Error("S3 returned an empty artifact body.");
|
|
60
|
+
const bytes = result.Body instanceof Uint8Array ? result.Body : await result.Body.transformToByteArray();
|
|
61
|
+
if (bytes.byteLength !== ref.byteSize || createHash("sha256").update(bytes).digest("hex") !== ref.sha256)
|
|
62
|
+
throw new Error("Artifact integrity check failed.");
|
|
63
|
+
return new Uint8Array(bytes);
|
|
64
|
+
} catch (error) {
|
|
65
|
+
if (name(error) === "NoSuchKey" || status(error) === 404) return null;
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
68
|
+
},
|
|
69
|
+
async pruneUnreferenced(options) {
|
|
70
|
+
if (!Number.isFinite(Date.parse(options.olderThan))) throw new Error("Invalid olderThan.");
|
|
71
|
+
if (options.limit !== void 0 && (!Number.isSafeInteger(options.limit) || options.limit < 0))
|
|
72
|
+
throw new Error("Invalid prune limit.");
|
|
73
|
+
const { sdk, client } = await connect();
|
|
74
|
+
let deletedCount = 0, freedBytes = 0;
|
|
75
|
+
let token;
|
|
76
|
+
do {
|
|
77
|
+
const page = await client.send(
|
|
78
|
+
new sdk.ListObjectsV2Command({
|
|
79
|
+
Bucket: config.bucket,
|
|
80
|
+
Prefix: `${prefix}sha256/`,
|
|
81
|
+
...token ? { ContinuationToken: token } : {}
|
|
82
|
+
})
|
|
83
|
+
);
|
|
84
|
+
for (const object of page.Contents ?? []) {
|
|
85
|
+
if (deletedCount >= (options.limit ?? Infinity)) return { deletedCount, freedBytes };
|
|
86
|
+
const hash = object.Key?.slice(-64);
|
|
87
|
+
if (!hash || !/^[a-f0-9]{64}$/.test(hash) || object.Key !== keyFor(hash) || !object.LastModified || object.LastModified.getTime() >= Date.parse(options.olderThan))
|
|
88
|
+
continue;
|
|
89
|
+
if (await options.isReferenced(hash)) continue;
|
|
90
|
+
await client.send(
|
|
91
|
+
new sdk.DeleteObjectCommand({
|
|
92
|
+
Bucket: config.bucket,
|
|
93
|
+
Key: object.Key,
|
|
94
|
+
...object.ETag ? { IfMatch: object.ETag } : {}
|
|
95
|
+
})
|
|
96
|
+
);
|
|
97
|
+
deletedCount++;
|
|
98
|
+
freedBytes += object.Size ?? 0;
|
|
99
|
+
}
|
|
100
|
+
token = page.IsTruncated ? page.NextContinuationToken : void 0;
|
|
101
|
+
if (page.IsTruncated && !token)
|
|
102
|
+
throw new Error("Truncated S3 listing has no continuation token.");
|
|
103
|
+
} while (token);
|
|
104
|
+
return { deletedCount, freedBytes };
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export { s3Artifacts };
|
|
110
|
+
//# sourceMappingURL=chunk-ZGVSDKKX.js.map
|
|
111
|
+
//# sourceMappingURL=chunk-ZGVSDKKX.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/s3/index.ts"],"names":[],"mappings":";;;AAcA,SAAS,OAAO,KAAA,EAAoC;AAClD,EAAA,OAAQ,OAAuD,SAAA,EAAW,cAAA;AAC5E;AACA,SAAS,KAAK,KAAA,EAAoC;AAChD,EAAA,OAAQ,KAAA,EAA6B,IAAA;AACvC;AAGO,SAAS,YAAY,MAAA,EAA0C;AACpE,EAAA,IAAI,CAAC,MAAA,CAAO,MAAA,IAAU,OAAA,CAAQ,IAAA,CAAK,MAAA,CAAO,MAAM,CAAA,EAAG,MAAM,IAAI,KAAA,CAAM,6BAA6B,CAAA;AAChG,EAAA,MAAM,MAAA,GAAS,MAAA,CAAO,MAAA,GAAS,CAAA,EAAG,MAAA,CAAO,OAAO,OAAA,CAAQ,MAAA,EAAQ,EAAE,CAAC,CAAA,CAAA,CAAA,GAAM,EAAA;AACzE,EAAA,MAAM,MAAA,GAAS,CAAC,IAAA,KAAiB,CAAA,EAAG,MAA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IAAU,IAAA,CAAK,QAAA,IAAY,EAAC,EAAG;AACxC,UAAA,IAAI,iBAAiB,OAAA,CAAQ,KAAA,IAAS,WAAW,OAAO,EAAE,cAAc,UAAA,EAAW;AACnF,UAAA,MAAM,IAAA,GAAO,MAAA,CAAO,GAAA,EAAK,KAAA,CAAM,GAAG,CAAA;AAClC,UAAA,IACE,CAAC,QACD,CAAC,gBAAA,CAAiB,KAAK,IAAI,CAAA,IAC3B,MAAA,CAAO,GAAA,KAAQ,MAAA,CAAO,IAAI,KAC1B,CAAC,MAAA,CAAO,gBACR,MAAA,CAAO,YAAA,CAAa,SAAQ,IAAK,IAAA,CAAK,KAAA,CAAM,OAAA,CAAQ,SAAS,CAAA;AAE7D,YAAA;AACF,UAAA,IAAI,MAAM,OAAA,CAAQ,YAAA,CAAa,IAAI,CAAA,EAAG;AACtC,UAAA,MAAM,MAAA,CAAO,IAAA;AAAA,YACX,IAAI,IAAI,mBAAA,CAAoB;AAAA,cAC1B,QAAQ,MAAA,CAAO,MAAA;AAAA,cACf,KAAK,MAAA,CAAO,GAAA;AAAA,cACZ,GAAI,OAAO,IAAA,GAAO,EAAE,SAAS,MAAA,CAAO,IAAA,KAAS;AAAC,aAC/C;AAAA,WACH;AACA,UAAA,YAAA,EAAA;AACA,UAAA,UAAA,IAAc,OAAO,IAAA,IAAQ,CAAA;AAAA,QAC/B;AACA,QAAA,KAAA,GAAQ,IAAA,CAAK,WAAA,GAAc,IAAA,CAAK,qBAAA,GAAwB,MAAA;AACxD,QAAA,IAAI,IAAA,CAAK,eAAe,CAAC,KAAA;AACvB,UAAA,MAAM,IAAI,MAAM,iDAAiD,CAAA;AAAA,MACrE,CAAA,QAAS,KAAA;AACT,MAAA,OAAO,EAAE,cAAc,UAAA,EAAW;AAAA,IACpC;AAAA,GACF;AACF","file":"chunk-ZGVSDKKX.js","sourcesContent":["import { createHash } from \"node:crypto\";\nimport type { ArtifactStore } from \"@soiljs/spi\";\n\n/** Structural command transport; a real AWS SDK S3Client also satisfies this. */\nexport interface S3ClientLike {\n send(command: { input: object }): Promise<unknown>;\n}\nexport interface S3ArtifactsConfig {\n bucket: string;\n prefix?: string;\n client?: S3ClientLike;\n clientConfig?: Record<string, unknown>;\n}\n\nfunction status(error: unknown): number | undefined {\n return (error as { $metadata?: { httpStatusCode?: number } })?.$metadata?.httpStatusCode;\n}\nfunction name(error: unknown): string | undefined {\n return (error as { name?: string })?.name;\n}\n\n/** Content-addressed immutable objects. The optional SDK is loaded on first use. */\nexport function s3Artifacts(config: S3ArtifactsConfig): ArtifactStore {\n if (!config.bucket || /[/?#]/.test(config.bucket)) throw new Error(\"Invalid S3 artifact bucket.\");\n const prefix = config.prefix ? `${config.prefix.replace(/\\/+$/, \"\")}/` : \"\";\n const keyFor = (hash: string) => `${prefix}sha256/${hash.slice(0, 2)}/${hash}`;\n let transport:\n Promise<{ sdk: typeof import(\"@aws-sdk/client-s3\"); client: S3ClientLike }> | undefined;\n function connect() {\n return (transport ??= import(\"@aws-sdk/client-s3\").then((sdk) => ({\n sdk,\n client: (config.client ?? new sdk.S3Client(config.clientConfig ?? {})) as S3ClientLike,\n })));\n }\n return {\n async put(input) {\n const data = new Uint8Array(input.data);\n const sha256 = createHash(\"sha256\").update(data).digest(\"hex\");\n const { sdk, client } = await connect();\n const command = new sdk.PutObjectCommand({\n Bucket: config.bucket,\n Key: keyFor(sha256),\n Body: data,\n ContentType: input.contentType,\n IfNoneMatch: \"*\",\n ChecksumSHA256: Buffer.from(sha256, \"hex\").toString(\"base64\"),\n });\n for (let attempt = 0; ; attempt++) {\n try {\n await client.send(command);\n break;\n } catch (error) {\n if (status(error) === 412 || name(error) === \"PreconditionFailed\") break;\n if (status(error) === 409 && attempt < 2) continue;\n throw error;\n }\n }\n return {\n uri: `s3://${config.bucket}/${keyFor(sha256)}`,\n sha256,\n byteSize: data.byteLength,\n contentType: input.contentType,\n };\n },\n async get(ref) {\n if (\n !/^[a-f0-9]{64}$/.test(ref.sha256) ||\n ref.uri !== `s3://${config.bucket}/${keyFor(ref.sha256)}`\n )\n return null;\n const { sdk, client } = await connect();\n try {\n const result = (await client.send(\n new sdk.GetObjectCommand({ Bucket: config.bucket, Key: keyFor(ref.sha256) }),\n )) as {\n Body?: Uint8Array | { transformToByteArray(): Promise<Uint8Array> };\n };\n if (!result.Body) throw new Error(\"S3 returned an empty artifact body.\");\n const bytes =\n result.Body instanceof Uint8Array\n ? result.Body\n : await result.Body.transformToByteArray();\n if (\n bytes.byteLength !== ref.byteSize ||\n createHash(\"sha256\").update(bytes).digest(\"hex\") !== ref.sha256\n )\n throw new Error(\"Artifact integrity check failed.\");\n return new Uint8Array(bytes);\n } catch (error) {\n if (name(error) === \"NoSuchKey\" || status(error) === 404) return null;\n throw error;\n }\n },\n async pruneUnreferenced(options) {\n if (!Number.isFinite(Date.parse(options.olderThan))) throw new Error(\"Invalid olderThan.\");\n if (\n options.limit !== undefined &&\n (!Number.isSafeInteger(options.limit) || options.limit < 0)\n )\n throw new Error(\"Invalid prune limit.\");\n const { sdk, client } = await connect();\n let deletedCount = 0,\n freedBytes = 0;\n let token: string | undefined;\n do {\n const page = (await client.send(\n new sdk.ListObjectsV2Command({\n Bucket: config.bucket,\n Prefix: `${prefix}sha256/`,\n ...(token ? { ContinuationToken: token } : {}),\n }),\n )) as {\n Contents?: { Key?: string; LastModified?: Date; Size?: number; ETag?: string }[];\n IsTruncated?: boolean;\n NextContinuationToken?: string;\n };\n for (const object of page.Contents ?? []) {\n if (deletedCount >= (options.limit ?? Infinity)) return { deletedCount, freedBytes };\n const hash = object.Key?.slice(-64);\n if (\n !hash ||\n !/^[a-f0-9]{64}$/.test(hash) ||\n object.Key !== keyFor(hash) ||\n !object.LastModified ||\n object.LastModified.getTime() >= Date.parse(options.olderThan)\n )\n continue;\n if (await options.isReferenced(hash)) continue;\n await client.send(\n new sdk.DeleteObjectCommand({\n Bucket: config.bucket,\n Key: object.Key,\n ...(object.ETag ? { IfMatch: object.ETag } : {}),\n }),\n );\n deletedCount++;\n freedBytes += object.Size ?? 0;\n }\n token = page.IsTruncated ? page.NextContinuationToken : undefined;\n if (page.IsTruncated && !token)\n throw new Error(\"Truncated S3 listing has no continuation token.\");\n } while (token);\n return { deletedCount, freedBytes };\n },\n };\n}\n"]}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { ScopeRef, ArtifactStore, StorageAdapter } from '@soiljs/spi';
|
|
2
|
+
export { S3ArtifactsConfig, S3ClientLike, s3Artifacts } from './s3/index.js';
|
|
3
|
+
|
|
4
|
+
interface PgClientLike {
|
|
5
|
+
query(text: string, values?: unknown[]): Promise<{
|
|
6
|
+
rows: Record<string, unknown>[];
|
|
7
|
+
rowCount?: number | null;
|
|
8
|
+
}>;
|
|
9
|
+
release?(error?: Error | boolean): void;
|
|
10
|
+
}
|
|
11
|
+
interface PgPoolLike {
|
|
12
|
+
connect(): Promise<PgClientLike>;
|
|
13
|
+
end?(): Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
interface PostgresStorageConfig {
|
|
16
|
+
connectionString?: string;
|
|
17
|
+
pool?: PgPoolLike;
|
|
18
|
+
/** A connected, exclusively owned connection. Calls on it are serialized. */
|
|
19
|
+
client?: PgClientLike;
|
|
20
|
+
schema?: string;
|
|
21
|
+
/** Bind an adapter to a tenant/project; every SQL operation uses this partition. */
|
|
22
|
+
scope?: ScopeRef;
|
|
23
|
+
artifacts?: ArtifactStore;
|
|
24
|
+
/** Disable only when the exported migrations have already been applied. */
|
|
25
|
+
migrate?: boolean;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* All domain writes use a short, scope-partition lock. Only changed rows are
|
|
29
|
+
* persisted; terminal history is never rewritten and model/tool work stays outside.
|
|
30
|
+
*/
|
|
31
|
+
declare function postgresStorage(config: PostgresStorageConfig): StorageAdapter;
|
|
32
|
+
|
|
33
|
+
interface PostgresMigration {
|
|
34
|
+
readonly version: number;
|
|
35
|
+
readonly sql: string;
|
|
36
|
+
}
|
|
37
|
+
/** Idempotent DDL, also exported for deployments that migrate separately. */
|
|
38
|
+
declare function postgresMigrations(schema?: string): readonly PostgresMigration[];
|
|
39
|
+
declare const POSTGRES_SCHEMA_VERSION = 1;
|
|
40
|
+
|
|
41
|
+
export { POSTGRES_SCHEMA_VERSION, type PgClientLike, type PgPoolLike, type PostgresMigration, type PostgresStorageConfig, postgresMigrations, postgresStorage };
|