@agentropy/store-postgres 0.0.0-bootstrap.0 → 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 +202 -0
- package/README.md +39 -1
- package/dist/index.d.ts +133 -0
- package/dist/index.js +601 -0
- package/package.json +39 -5
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
https://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,41 @@
|
|
|
1
1
|
# @agentropy/store-postgres
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**PostgreSQL store for Agentropy.** Part of [Agentropy](https://github.com/bassemZohdy/agentropy), a TypeScript framework for durable, capability-driven multi-agent work. Version 0.x: the API can still change between minor versions.
|
|
4
|
+
|
|
5
|
+
The `Store` adapter for PostgreSQL on a driver-neutral client port: several workers share one database with exactly-once dispatch. Transactions are SERIALIZABLE and retried on conflict; `statementTimeoutMs` and `lockTimeoutMs` bound a stuck statement or lock wait. Bring your own driver: a `pg` pool fits as is.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install @agentropy/store-postgres
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Node 24 or newer.
|
|
14
|
+
|
|
15
|
+
## Use
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { Pool } from 'pg';
|
|
19
|
+
import { PostgresStore } from '@agentropy/store-postgres';
|
|
20
|
+
|
|
21
|
+
const pool = new Pool({ connectionString: process.env.DATABASE_URL, connectionTimeoutMillis: 10_000 });
|
|
22
|
+
pool.on('error', (err) => console.error('pg pool error', err.name)); // an idle connection can drop
|
|
23
|
+
const store = new PostgresStore({
|
|
24
|
+
pool,
|
|
25
|
+
ownsConnection: true,
|
|
26
|
+
statementTimeoutMs: 30_000,
|
|
27
|
+
lockTimeoutMs: 10_000,
|
|
28
|
+
});
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
It does not depend on a driver: install `pg` (or any client with the same `query` shape) yourself.
|
|
32
|
+
|
|
33
|
+
## Learn more
|
|
34
|
+
|
|
35
|
+
- [PostgreSQL adapter decision](https://github.com/bassemZohdy/agentropy/blob/main/docs/adr/0028-postgresql-store-adapter.md)
|
|
36
|
+
- [Deployment guide](https://github.com/bassemZohdy/agentropy/blob/main/docs/deployment.md)
|
|
37
|
+
- [Every export](https://github.com/bassemZohdy/agentropy/blob/main/docs/api.md)
|
|
38
|
+
|
|
39
|
+
## License
|
|
40
|
+
|
|
41
|
+
Apache-2.0. See the [repository](https://github.com/bassemZohdy/agentropy) for the source, issues and contributing guide.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @agentropy/store-postgres — Store port adapter for PostgreSQL (ADR-0017, ADR-0028).
|
|
3
|
+
*
|
|
4
|
+
* Driver-neutral: the adapter talks to a {@link PgPool} (node-postgres `Pool` fits as-is) or to a single
|
|
5
|
+
* {@link PgClient} connection (embedded PGlite fits as-is), so Agentropy carries no database driver dependency.
|
|
6
|
+
*
|
|
7
|
+
* Semantics, matching the SQLite adapter and the Store conformance suite:
|
|
8
|
+
* - one `transaction` = one `BEGIN ISOLATION LEVEL SERIALIZABLE … COMMIT`; a serialization failure or deadlock
|
|
9
|
+
* re-runs the callback (bounded), so transaction callbacks must only touch the store;
|
|
10
|
+
* - `seq` is assigned at commit (FEAT-032.3, ADR-0028 revision 2): just before `COMMIT`, a transaction that inserted
|
|
11
|
+
* rows takes a per-schema transaction advisory lock, draws one block from a PostgreSQL sequence and stamps its
|
|
12
|
+
* rows. The lock is held until the commit completes, so seq order equals commit order and readers paging with
|
|
13
|
+
* `afterSeq` never skip a row that commits late; neither the lock nor the sequence can cause a serialization
|
|
14
|
+
* failure, so concurrent writers no longer conflict on a counter row. Inside its own transaction an inserted row
|
|
15
|
+
* has a provisional seq above every committed one; the document `insert` returned carries the final seq once
|
|
16
|
+
* the transaction has committed;
|
|
17
|
+
* - writes are buffered (FEAT-032.2, option `batchWrites`): inserts, and updates of rows the transaction has read
|
|
18
|
+
* or written, are sent together in one statement before the next read that could see them or at commit; at
|
|
19
|
+
* commit that statement also draws the seq block when only inserts are buffered. A taken ID or a stale revision
|
|
20
|
+
* then fails the transaction at that point rather than at the call. An acceptance takes 10 round trips (was 17);
|
|
21
|
+
* - indexed fields live in typed side columns (`n_<field>` numeric, `s_<field>` text in "C" collation) so equality,
|
|
22
|
+
* ranges and ordering behave exactly like the in-memory reference (nulls first, code-unit string order).
|
|
23
|
+
*/
|
|
24
|
+
import { type Store, type StoreTx, type Telemetry } from '@agentropy/core';
|
|
25
|
+
export declare const packageName: "@agentropy/store-postgres";
|
|
26
|
+
/** Schema version this adapter writes; a newer database is refused with IncompatibleVersion. */
|
|
27
|
+
export declare const SCHEMA_VERSION = 2;
|
|
28
|
+
export interface PgResult<R> {
|
|
29
|
+
rows: R[];
|
|
30
|
+
/** node-postgres */
|
|
31
|
+
rowCount?: number | null;
|
|
32
|
+
/** PGlite */
|
|
33
|
+
affectedRows?: number;
|
|
34
|
+
}
|
|
35
|
+
/** One connection: `query(text, params)` with `$1…$n` placeholders. */
|
|
36
|
+
export interface PgClient {
|
|
37
|
+
query<R = Record<string, unknown>>(text: string, params?: unknown[]): Promise<PgResult<R>>;
|
|
38
|
+
}
|
|
39
|
+
/** A pool handing out dedicated connections (node-postgres `Pool`). */
|
|
40
|
+
export interface PgPool {
|
|
41
|
+
connect(): Promise<PgClient & {
|
|
42
|
+
release(err?: Error | boolean): void;
|
|
43
|
+
}>;
|
|
44
|
+
end?(): Promise<void>;
|
|
45
|
+
}
|
|
46
|
+
export interface PostgresStoreOptions {
|
|
47
|
+
/** Either a pool (concurrent transactions on separate connections) or one client (transactions serialized). */
|
|
48
|
+
pool?: PgPool;
|
|
49
|
+
client?: PgClient;
|
|
50
|
+
/** Schema (namespace) holding Agentropy's tables. Default `agentropy`. */
|
|
51
|
+
schema?: string;
|
|
52
|
+
/** Re-runs after a serialization failure or deadlock before giving up with StaleRevision. Default 8. */
|
|
53
|
+
maxRetries?: number;
|
|
54
|
+
/**
|
|
55
|
+
* From this re-run on, a retried transaction first takes a per-schema transaction-level advisory lock, so
|
|
56
|
+
* transactions that keep losing queue behind each other instead of colliding again. Default 2.
|
|
57
|
+
*/
|
|
58
|
+
serializeRetriesAfter?: number;
|
|
59
|
+
/**
|
|
60
|
+
* With a pool, prefer index scans inside transactions (`SET LOCAL enable_seqscan = off`) so serializable
|
|
61
|
+
* transactions on small tables do not conflict through whole-table predicate locks. Default true.
|
|
62
|
+
*/
|
|
63
|
+
preferIndexScans?: boolean;
|
|
64
|
+
/**
|
|
65
|
+
* Buffer inserts, and updates of rows the transaction has already read, and send them in one statement before
|
|
66
|
+
* the next read that could see them or at commit (FEAT-032.2). A taken ID or a stale revision then fails at that
|
|
67
|
+
* point instead of at the call; the transaction fails either way. Default true.
|
|
68
|
+
*/
|
|
69
|
+
batchWrites?: boolean;
|
|
70
|
+
/**
|
|
71
|
+
* `SET LOCAL statement_timeout` for every transaction, in ms (default: the server's). A statement that runs longer
|
|
72
|
+
* fails the transaction with `Timeout` instead of holding a connection (and, at commit, the seq lock) indefinitely.
|
|
73
|
+
*/
|
|
74
|
+
statementTimeoutMs?: number;
|
|
75
|
+
/** `SET LOCAL lock_timeout` for every transaction, in ms (default: the server's): waiting on a row lock fails with `Timeout`. */
|
|
76
|
+
lockTimeoutMs?: number;
|
|
77
|
+
/** Close the pool/client when the store closes. Default false (the caller owns the connection). */
|
|
78
|
+
ownsConnection?: boolean;
|
|
79
|
+
/**
|
|
80
|
+
* Counts serialization conflicts and deadlocks as `agentropy.store.conflicts` with `agentropy.store.outcome`
|
|
81
|
+
* `retried` (the transaction ran again) or `exhausted` (it failed StaleRevision after `maxRetries`).
|
|
82
|
+
*/
|
|
83
|
+
telemetry?: Telemetry;
|
|
84
|
+
}
|
|
85
|
+
/** PostgreSQL store. Durable when the database is; HA is the database's concern (ADR-0028). */
|
|
86
|
+
export declare class PostgresStore implements Store {
|
|
87
|
+
private readonly o;
|
|
88
|
+
readonly durability: "durable-execution";
|
|
89
|
+
private readonly schema;
|
|
90
|
+
private readonly maxRetries;
|
|
91
|
+
/** Serializes transactions when only one connection is available. */
|
|
92
|
+
private readonly mutex;
|
|
93
|
+
private ready?;
|
|
94
|
+
private closed;
|
|
95
|
+
/**
|
|
96
|
+
* Under SERIALIZABLE a sequential scan predicate-locks the whole table, so two writers that each scan a small
|
|
97
|
+
* table (where the planner prefers sequential scans even for primary-key lookups) conflict although they touch
|
|
98
|
+
* different rows. PostgreSQL's documentation for serializable workloads recommends steering the planner to index
|
|
99
|
+
* scans; pooled connections do so per transaction, in the same round trip as BEGIN. A single client serializes
|
|
100
|
+
* transactions itself and needs nothing.
|
|
101
|
+
*/
|
|
102
|
+
private beginTransaction;
|
|
103
|
+
private multiStatement?;
|
|
104
|
+
private get retryLockKey();
|
|
105
|
+
constructor(o: PostgresStoreOptions);
|
|
106
|
+
private t;
|
|
107
|
+
/** Creates or checks the schema. Called lazily by the first transaction; safe to run from many workers. */
|
|
108
|
+
migrate(): Promise<void>;
|
|
109
|
+
private createV1;
|
|
110
|
+
/**
|
|
111
|
+
* Schema 2 (FEAT-032.3): seq comes from a sequence that continues after the old counter row. Every worker must run
|
|
112
|
+
* a schema-2 adapter: a schema-1 worker still running would take seqs from the counter, below the sequence.
|
|
113
|
+
*/
|
|
114
|
+
private migrateV2;
|
|
115
|
+
/**
|
|
116
|
+
* Sends the writes this transaction has buffered in one statement (FEAT-032.2). At commit (`final`) the same
|
|
117
|
+
* statement also takes the per-schema seq lock, draws one block from the sequence for every row this transaction
|
|
118
|
+
* inserted, inserts the buffered rows with their final seq and stamps rows sent earlier with a provisional one.
|
|
119
|
+
* The lock is held until COMMIT, so blocks are drawn in commit order. Returns the first value of the block.
|
|
120
|
+
*/
|
|
121
|
+
private flush;
|
|
122
|
+
private current;
|
|
123
|
+
/**
|
|
124
|
+
* Additive schema evolution (FEAT-028.3): collections and index fields added by newer releases get their tables
|
|
125
|
+
* and columns on start, and new columns are backfilled from the stored JSON. Runs under the migration lock.
|
|
126
|
+
*/
|
|
127
|
+
private evolve;
|
|
128
|
+
private createCollection;
|
|
129
|
+
private withConnection;
|
|
130
|
+
transaction<T>(fn: (tx: StoreTx) => Promise<T>): Promise<T>;
|
|
131
|
+
close(): Promise<void>;
|
|
132
|
+
private tx;
|
|
133
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,601 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @agentropy/store-postgres — Store port adapter for PostgreSQL (ADR-0017, ADR-0028).
|
|
3
|
+
*
|
|
4
|
+
* Driver-neutral: the adapter talks to a {@link PgPool} (node-postgres `Pool` fits as-is) or to a single
|
|
5
|
+
* {@link PgClient} connection (embedded PGlite fits as-is), so Agentropy carries no database driver dependency.
|
|
6
|
+
*
|
|
7
|
+
* Semantics, matching the SQLite adapter and the Store conformance suite:
|
|
8
|
+
* - one `transaction` = one `BEGIN ISOLATION LEVEL SERIALIZABLE … COMMIT`; a serialization failure or deadlock
|
|
9
|
+
* re-runs the callback (bounded), so transaction callbacks must only touch the store;
|
|
10
|
+
* - `seq` is assigned at commit (FEAT-032.3, ADR-0028 revision 2): just before `COMMIT`, a transaction that inserted
|
|
11
|
+
* rows takes a per-schema transaction advisory lock, draws one block from a PostgreSQL sequence and stamps its
|
|
12
|
+
* rows. The lock is held until the commit completes, so seq order equals commit order and readers paging with
|
|
13
|
+
* `afterSeq` never skip a row that commits late; neither the lock nor the sequence can cause a serialization
|
|
14
|
+
* failure, so concurrent writers no longer conflict on a counter row. Inside its own transaction an inserted row
|
|
15
|
+
* has a provisional seq above every committed one; the document `insert` returned carries the final seq once
|
|
16
|
+
* the transaction has committed;
|
|
17
|
+
* - writes are buffered (FEAT-032.2, option `batchWrites`): inserts, and updates of rows the transaction has read
|
|
18
|
+
* or written, are sent together in one statement before the next read that could see them or at commit; at
|
|
19
|
+
* commit that statement also draws the seq block when only inserts are buffered. A taken ID or a stale revision
|
|
20
|
+
* then fails the transaction at that point rather than at the call. An acceptance takes 10 round trips (was 17);
|
|
21
|
+
* - indexed fields live in typed side columns (`n_<field>` numeric, `s_<field>` text in "C" collation) so equality,
|
|
22
|
+
* ranges and ordering behave exactly like the in-memory reference (nulls first, code-unit string order).
|
|
23
|
+
*/
|
|
24
|
+
import { AgentropyError, METRICS, AsyncMutex, STORE_COLLECTIONS, indexValues, staleRevision, } from '@agentropy/core';
|
|
25
|
+
export const packageName = '@agentropy/store-postgres';
|
|
26
|
+
/** Schema version this adapter writes; a newer database is refused with IncompatibleVersion. */
|
|
27
|
+
export const SCHEMA_VERSION = 2;
|
|
28
|
+
/** Provisional seq of rows inserted by a transaction that has not committed yet: above every committed seq. */
|
|
29
|
+
const PROVISIONAL_SEQ = 2 ** 52;
|
|
30
|
+
const keyOf = (c, id) => `${c}\u0000${id}`;
|
|
31
|
+
const RETRYABLE = new Set(['40001', '40P01']);
|
|
32
|
+
const SQLSTATE = /^[0-9A-Z]{5}$/;
|
|
33
|
+
const IDENT = /^[a-z_][a-z0-9_]{0,40}$/;
|
|
34
|
+
const toDoc = (r) => ({
|
|
35
|
+
id: r.id,
|
|
36
|
+
revision: Number(r.revision),
|
|
37
|
+
seq: Number(r.seq),
|
|
38
|
+
value: JSON.parse(r.value),
|
|
39
|
+
});
|
|
40
|
+
const affected = (r) => r.rowCount ?? r.affectedRows ?? r.rows.length;
|
|
41
|
+
const pgCode = (err) => typeof err === 'object' && err !== null && 'code' in err
|
|
42
|
+
? String(err.code)
|
|
43
|
+
: undefined;
|
|
44
|
+
/**
|
|
45
|
+
* Database errors never leave the adapter raw (they can carry SQL text and values): connection and shutdown
|
|
46
|
+
* classes become ProviderUnavailable (retryable), anything else Internal. Only the SQLSTATE is kept.
|
|
47
|
+
*/
|
|
48
|
+
function fromSqlState(code) {
|
|
49
|
+
// statement_timeout (57014) and lock_timeout (55P03) are the adapter's own bounds: a retryable Timeout.
|
|
50
|
+
if (code === '57014' || code === '55P03')
|
|
51
|
+
return new AgentropyError('Timeout', 'Database operation timed out', {
|
|
52
|
+
details: { sqlstate: code },
|
|
53
|
+
});
|
|
54
|
+
const unavailable = /^(08|53|57P|58)/.test(code);
|
|
55
|
+
return new AgentropyError(unavailable ? 'ProviderUnavailable' : 'Internal', unavailable ? 'Database unavailable' : 'Database error', { details: { sqlstate: code } });
|
|
56
|
+
}
|
|
57
|
+
/** PostgreSQL store. Durable when the database is; HA is the database's concern (ADR-0028). */
|
|
58
|
+
export class PostgresStore {
|
|
59
|
+
o;
|
|
60
|
+
durability = 'durable-execution';
|
|
61
|
+
schema;
|
|
62
|
+
maxRetries;
|
|
63
|
+
/** Serializes transactions when only one connection is available. */
|
|
64
|
+
mutex = new AsyncMutex();
|
|
65
|
+
ready;
|
|
66
|
+
closed = false;
|
|
67
|
+
/**
|
|
68
|
+
* Under SERIALIZABLE a sequential scan predicate-locks the whole table, so two writers that each scan a small
|
|
69
|
+
* table (where the planner prefers sequential scans even for primary-key lookups) conflict although they touch
|
|
70
|
+
* different rows. PostgreSQL's documentation for serializable workloads recommends steering the planner to index
|
|
71
|
+
* scans; pooled connections do so per transaction, in the same round trip as BEGIN. A single client serializes
|
|
72
|
+
* transactions itself and needs nothing.
|
|
73
|
+
*/
|
|
74
|
+
async beginTransaction(db) {
|
|
75
|
+
const begin = 'BEGIN ISOLATION LEVEL SERIALIZABLE';
|
|
76
|
+
const settings = [];
|
|
77
|
+
if (this.o.pool && this.o.preferIndexScans !== false)
|
|
78
|
+
settings.push('SET LOCAL enable_seqscan = off');
|
|
79
|
+
// Integers only: the values are interpolated into SQL.
|
|
80
|
+
for (const [name, ms] of [
|
|
81
|
+
['statement_timeout', this.o.statementTimeoutMs],
|
|
82
|
+
['lock_timeout', this.o.lockTimeoutMs],
|
|
83
|
+
])
|
|
84
|
+
if (ms !== undefined)
|
|
85
|
+
settings.push(`SET LOCAL ${name} = ${Math.max(0, Math.floor(ms))}`);
|
|
86
|
+
if (!settings.length) {
|
|
87
|
+
await db.query(begin);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
// One round trip where the driver accepts several statements in a query (node-postgres does); otherwise one each.
|
|
91
|
+
if (this.multiStatement !== false) {
|
|
92
|
+
try {
|
|
93
|
+
await db.query([begin, ...settings].join('; '));
|
|
94
|
+
this.multiStatement = true;
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
catch (err) {
|
|
98
|
+
if (this.multiStatement === true)
|
|
99
|
+
throw err;
|
|
100
|
+
this.multiStatement = false;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
await db.query(begin);
|
|
104
|
+
for (const setting of settings)
|
|
105
|
+
await db.query(setting);
|
|
106
|
+
}
|
|
107
|
+
multiStatement;
|
|
108
|
+
get retryLockKey() {
|
|
109
|
+
return `agentropy-retry:${this.schema}`;
|
|
110
|
+
}
|
|
111
|
+
constructor(o) {
|
|
112
|
+
this.o = o;
|
|
113
|
+
if (!o.pool === !o.client)
|
|
114
|
+
throw new AgentropyError('InvalidConfiguration', 'PostgresStore needs exactly one of pool or client');
|
|
115
|
+
this.schema = o.schema ?? 'agentropy';
|
|
116
|
+
if (!IDENT.test(this.schema))
|
|
117
|
+
throw new AgentropyError('InvalidConfiguration', `Invalid schema name ${this.schema}`);
|
|
118
|
+
this.maxRetries = o.maxRetries ?? 8;
|
|
119
|
+
}
|
|
120
|
+
t(c) {
|
|
121
|
+
return `"${this.schema}"."c_${c}"`;
|
|
122
|
+
}
|
|
123
|
+
/** Creates or checks the schema. Called lazily by the first transaction; safe to run from many workers. */
|
|
124
|
+
migrate() {
|
|
125
|
+
this.ready ??= this.withConnection(async (db) => {
|
|
126
|
+
await db.query('BEGIN');
|
|
127
|
+
try {
|
|
128
|
+
// One migrator at a time across every worker sharing the database.
|
|
129
|
+
await db.query('SELECT pg_advisory_xact_lock(hashtext($1))', [
|
|
130
|
+
`agentropy-migrate:${this.schema}`,
|
|
131
|
+
]);
|
|
132
|
+
await db.query(`CREATE SCHEMA IF NOT EXISTS "${this.schema}"`);
|
|
133
|
+
await db.query(`CREATE TABLE IF NOT EXISTS "${this.schema}".schema_migrations (version INTEGER PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT now())`);
|
|
134
|
+
const applied = (await db.query(`SELECT MAX(version) AS v FROM "${this.schema}".schema_migrations`)).rows[0]?.v;
|
|
135
|
+
if ((applied ?? 0) > SCHEMA_VERSION)
|
|
136
|
+
throw new AgentropyError('IncompatibleVersion', `Database schema ${applied} is newer than this adapter (${SCHEMA_VERSION})`, { details: { kind: 'store-schema' } });
|
|
137
|
+
if ((applied ?? 0) < 1)
|
|
138
|
+
await this.createV1(db);
|
|
139
|
+
if ((applied ?? 0) < 2)
|
|
140
|
+
await this.migrateV2(db);
|
|
141
|
+
await this.evolve(db);
|
|
142
|
+
await db.query('COMMIT');
|
|
143
|
+
}
|
|
144
|
+
catch (err) {
|
|
145
|
+
await db.query('ROLLBACK').catch(() => undefined);
|
|
146
|
+
throw err;
|
|
147
|
+
}
|
|
148
|
+
}).catch((err) => {
|
|
149
|
+
this.ready = undefined;
|
|
150
|
+
throw err;
|
|
151
|
+
});
|
|
152
|
+
return this.ready;
|
|
153
|
+
}
|
|
154
|
+
async createV1(db) {
|
|
155
|
+
const s = `"${this.schema}"`;
|
|
156
|
+
await db.query(`CREATE TABLE ${s}.meta (key TEXT PRIMARY KEY, value BIGINT NOT NULL)`);
|
|
157
|
+
await db.query(`INSERT INTO ${s}.meta (key, value) VALUES ('seq', 0)`);
|
|
158
|
+
for (const [c, fields] of Object.entries(STORE_COLLECTIONS))
|
|
159
|
+
await this.createCollection(db, c, fields);
|
|
160
|
+
await db.query(`INSERT INTO ${s}.schema_migrations (version) VALUES (1)`);
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Schema 2 (FEAT-032.3): seq comes from a sequence that continues after the old counter row. Every worker must run
|
|
164
|
+
* a schema-2 adapter: a schema-1 worker still running would take seqs from the counter, below the sequence.
|
|
165
|
+
*/
|
|
166
|
+
async migrateV2(db) {
|
|
167
|
+
const s = `"${this.schema}"`;
|
|
168
|
+
const last = (await db.query(`SELECT value FROM ${s}.meta WHERE key = 'seq'`)).rows[0]?.value;
|
|
169
|
+
await db.query(`CREATE SEQUENCE ${s}.seq AS BIGINT START WITH ${Number(last ?? 0) + 1}`);
|
|
170
|
+
await db.query(`INSERT INTO ${s}.schema_migrations (version) VALUES (2)`);
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Sends the writes this transaction has buffered in one statement (FEAT-032.2). At commit (`final`) the same
|
|
174
|
+
* statement also takes the per-schema seq lock, draws one block from the sequence for every row this transaction
|
|
175
|
+
* inserted, inserts the buffered rows with their final seq and stamps rows sent earlier with a provisional one.
|
|
176
|
+
* The lock is held until COMMIT, so blocks are drawn in commit order. Returns the first value of the block.
|
|
177
|
+
*/
|
|
178
|
+
async flush(db, st, final) {
|
|
179
|
+
const ops = [...st.pending.values()];
|
|
180
|
+
const draw = final && st.inserted.length > 0;
|
|
181
|
+
if (!ops.length && !draw)
|
|
182
|
+
return undefined;
|
|
183
|
+
// An update can wait on another transaction's row lock. It must not wait while holding the seq lock: every
|
|
184
|
+
// inserting commit would queue behind it, and a holder of that row that also inserts would deadlock with it.
|
|
185
|
+
if (draw && ops.some((op) => op.kind === 'update')) {
|
|
186
|
+
await this.flush(db, st, false);
|
|
187
|
+
return this.flush(db, st, true);
|
|
188
|
+
}
|
|
189
|
+
const params = [];
|
|
190
|
+
const p = (v) => {
|
|
191
|
+
params.push(v);
|
|
192
|
+
return `$${params.length}`;
|
|
193
|
+
};
|
|
194
|
+
const ctes = [];
|
|
195
|
+
if (draw) {
|
|
196
|
+
const seq = `'"${this.schema}".seq'`;
|
|
197
|
+
const n = p(st.inserted.length);
|
|
198
|
+
ctes.push(`blk AS (SELECT setval(${seq}, nextval(${seq}) + ${n}::bigint - 1) - ${n}::bigint + 1 AS first ` +
|
|
199
|
+
`FROM (SELECT pg_advisory_xact_lock(hashtext(${p(`agentropy-seq:${this.schema}`)}))) l)`);
|
|
200
|
+
}
|
|
201
|
+
ops.forEach((op, i) => {
|
|
202
|
+
if (op.kind === 'insert') {
|
|
203
|
+
const seq = draw
|
|
204
|
+
? `(SELECT first FROM blk) + ${p(op.row.k)}::bigint`
|
|
205
|
+
: p(PROVISIONAL_SEQ + op.row.k);
|
|
206
|
+
const values = [
|
|
207
|
+
p(op.id),
|
|
208
|
+
p(op.revision),
|
|
209
|
+
seq,
|
|
210
|
+
p(op.value),
|
|
211
|
+
...op.params.map(p),
|
|
212
|
+
];
|
|
213
|
+
ctes.push(`o${i} AS (INSERT INTO ${this.t(op.c)} (id, revision, seq, value${op.cols.map((c) => `, ${c}`).join('')}) ` +
|
|
214
|
+
`VALUES (${values.join(', ')}) ON CONFLICT (id) DO NOTHING RETURNING 1)`);
|
|
215
|
+
}
|
|
216
|
+
else {
|
|
217
|
+
const sets = [
|
|
218
|
+
`revision = ${p(op.revision)}`,
|
|
219
|
+
`value = ${p(op.value)}`,
|
|
220
|
+
...op.cols.map((c, j) => `${c} = ${p(op.params[j])}`),
|
|
221
|
+
];
|
|
222
|
+
ctes.push(`o${i} AS (UPDATE ${this.t(op.c)} SET ${sets.join(', ')} WHERE id = ${p(op.id)} AND revision = ${p(op.expected)} RETURNING 1)`);
|
|
223
|
+
}
|
|
224
|
+
});
|
|
225
|
+
if (draw) {
|
|
226
|
+
// Rows sent before the commit carry a provisional seq; give them their place in the block.
|
|
227
|
+
const byCollection = new Map();
|
|
228
|
+
for (const row of st.inserted)
|
|
229
|
+
if (row.sent) {
|
|
230
|
+
const e = byCollection.get(row.c) ?? { ids: [], ks: [] };
|
|
231
|
+
e.ids.push(row.id);
|
|
232
|
+
e.ks.push(row.k);
|
|
233
|
+
byCollection.set(row.c, e);
|
|
234
|
+
}
|
|
235
|
+
[...byCollection.entries()].forEach(([c, e], j) => ctes.push(`s${j} AS (UPDATE ${this.t(c)} t SET seq = blk.first + v.k FROM blk, ` +
|
|
236
|
+
`unnest(${p(e.ids)}::text[], ${p(e.ks)}::int[]) AS v(id, k) WHERE t.id = v.id)`));
|
|
237
|
+
}
|
|
238
|
+
const counts = ops.map((_, i) => `, (SELECT count(*) FROM o${i})::int AS c${i}`);
|
|
239
|
+
const res = await db.query(`WITH ${ctes.join(', ')} SELECT ${draw ? '(SELECT first FROM blk)' : 'NULL'} AS first${counts.join('')}`, params);
|
|
240
|
+
const row = res.rows[0];
|
|
241
|
+
for (const [i, op] of ops.entries()) {
|
|
242
|
+
if (Number(row[`c${i}`]) === 1)
|
|
243
|
+
continue;
|
|
244
|
+
if (op.kind === 'insert')
|
|
245
|
+
throw staleRevision(op.c, op.id, 'exists');
|
|
246
|
+
const cur = await this.current(db, op.c, op.id);
|
|
247
|
+
if (cur === undefined)
|
|
248
|
+
throw staleRevision(op.c, op.id, 'missing', op.expected);
|
|
249
|
+
throw staleRevision(op.c, op.id, 'revision', op.expected, cur);
|
|
250
|
+
}
|
|
251
|
+
st.pending.clear();
|
|
252
|
+
for (const op of ops) {
|
|
253
|
+
const key = keyOf(op.c, op.id);
|
|
254
|
+
if (op.kind === 'insert') {
|
|
255
|
+
op.row.sent = true;
|
|
256
|
+
st.known.set(key, {
|
|
257
|
+
revision: op.revision,
|
|
258
|
+
seq: PROVISIONAL_SEQ + op.row.k,
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
else
|
|
262
|
+
st.known.set(key, {
|
|
263
|
+
revision: op.revision,
|
|
264
|
+
seq: st.known.get(key).seq,
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
return draw ? Number(row.first) : undefined;
|
|
268
|
+
}
|
|
269
|
+
async current(db, c, id) {
|
|
270
|
+
const r = (await db.query(`SELECT revision FROM ${this.t(c)} WHERE id = $1`, [id])).rows[0];
|
|
271
|
+
return r ? Number(r.revision) : undefined;
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Additive schema evolution (FEAT-028.3): collections and index fields added by newer releases get their tables
|
|
275
|
+
* and columns on start, and new columns are backfilled from the stored JSON. Runs under the migration lock.
|
|
276
|
+
*/
|
|
277
|
+
async evolve(db) {
|
|
278
|
+
const existing = new Map();
|
|
279
|
+
for (const r of (await db.query('SELECT table_name, column_name FROM information_schema.columns WHERE table_schema = $1', [this.schema])).rows) {
|
|
280
|
+
const cols = existing.get(r.table_name) ?? new Set();
|
|
281
|
+
cols.add(r.column_name);
|
|
282
|
+
existing.set(r.table_name, cols);
|
|
283
|
+
}
|
|
284
|
+
for (const [c, fields] of Object.entries(STORE_COLLECTIONS)) {
|
|
285
|
+
const have = existing.get(`c_${c}`);
|
|
286
|
+
if (!have) {
|
|
287
|
+
await this.createCollection(db, c, fields);
|
|
288
|
+
continue;
|
|
289
|
+
}
|
|
290
|
+
const missing = fields.filter((f) => !have.has(`n_${f}`));
|
|
291
|
+
if (!missing.length)
|
|
292
|
+
continue;
|
|
293
|
+
for (const f of missing) {
|
|
294
|
+
await db.query(`ALTER TABLE ${this.t(c)} ADD COLUMN "n_${f}" DOUBLE PRECISION, ADD COLUMN "s_${f}" TEXT COLLATE "C"`);
|
|
295
|
+
await db.query(`CREATE INDEX "x_${c}_${f}" ON ${this.t(c)} ("n_${f}", "s_${f}", seq)`);
|
|
296
|
+
}
|
|
297
|
+
// Backfilled by the server in one statement, like `indexValues` does per document: numbers and booleans
|
|
298
|
+
// (1/0) fill the numeric column, strings the text column, anything else stays null. (A row per round trip
|
|
299
|
+
// took hours on a large table while holding the migration lock.)
|
|
300
|
+
const json = (f) => `(value::jsonb -> '${f}')`;
|
|
301
|
+
await db.query(`UPDATE ${this.t(c)} SET ${missing
|
|
302
|
+
.map((f) => `"n_${f}" = CASE jsonb_typeof${json(f)} WHEN 'number' THEN (${json(f)} #>> '{}')::double precision WHEN 'boolean' THEN CASE WHEN (${json(f)} #>> '{}')::boolean THEN 1 ELSE 0 END END, ` +
|
|
303
|
+
`"s_${f}" = CASE WHEN jsonb_typeof${json(f)} = 'string' THEN ${json(f)} #>> '{}' END`)
|
|
304
|
+
.join(', ')}`);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
async createCollection(db, c, fields) {
|
|
308
|
+
const cols = fields
|
|
309
|
+
.map((f) => `"n_${f}" DOUBLE PRECISION, "s_${f}" TEXT COLLATE "C"`)
|
|
310
|
+
.join(', ');
|
|
311
|
+
await db.query(`CREATE TABLE ${this.t(c)} (id TEXT COLLATE "C" PRIMARY KEY, revision INTEGER NOT NULL, seq BIGINT NOT NULL, value TEXT NOT NULL${cols ? `, ${cols}` : ''})`);
|
|
312
|
+
await db.query(`CREATE INDEX "x_${c}_seq" ON ${this.t(c)} (seq)`);
|
|
313
|
+
for (const f of fields)
|
|
314
|
+
await db.query(`CREATE INDEX "x_${c}_${f}" ON ${this.t(c)} ("n_${f}", "s_${f}", seq)`);
|
|
315
|
+
}
|
|
316
|
+
async withConnection(fn) {
|
|
317
|
+
if (this.o.client)
|
|
318
|
+
return this.mutex.run(() => fn(this.o.client));
|
|
319
|
+
const conn = await this.o.pool.connect();
|
|
320
|
+
let broken = false;
|
|
321
|
+
try {
|
|
322
|
+
return await fn(conn);
|
|
323
|
+
}
|
|
324
|
+
catch (err) {
|
|
325
|
+
// A connection that failed mid-protocol is not returned to the pool.
|
|
326
|
+
broken = pgCode(err) === undefined && !(err instanceof AgentropyError);
|
|
327
|
+
throw err;
|
|
328
|
+
}
|
|
329
|
+
finally {
|
|
330
|
+
conn.release(broken);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
async transaction(fn) {
|
|
334
|
+
if (this.closed)
|
|
335
|
+
throw new AgentropyError('ProviderUnavailable', 'Store is closed');
|
|
336
|
+
await this.migrate();
|
|
337
|
+
for (let attempt = 0;; attempt++) {
|
|
338
|
+
try {
|
|
339
|
+
return await this.withConnection(async (db) => {
|
|
340
|
+
// Taken before BEGIN: a SERIALIZABLE snapshot starts at the first statement, so waiting inside the
|
|
341
|
+
// transaction would hand the winner of the queue a stale snapshot.
|
|
342
|
+
const queued = attempt >= (this.o.serializeRetriesAfter ?? 2);
|
|
343
|
+
if (queued)
|
|
344
|
+
await db.query('SELECT pg_advisory_lock(hashtext($1))', [
|
|
345
|
+
this.retryLockKey,
|
|
346
|
+
]);
|
|
347
|
+
try {
|
|
348
|
+
await this.beginTransaction(db);
|
|
349
|
+
try {
|
|
350
|
+
const st = {
|
|
351
|
+
inserted: [],
|
|
352
|
+
rows: new Map(),
|
|
353
|
+
pending: new Map(),
|
|
354
|
+
known: new Map(),
|
|
355
|
+
};
|
|
356
|
+
const result = await fn(this.tx(db, st));
|
|
357
|
+
const first = await this.flush(db, st, true);
|
|
358
|
+
await db.query('COMMIT');
|
|
359
|
+
if (first !== undefined)
|
|
360
|
+
for (const row of st.inserted)
|
|
361
|
+
for (const doc of row.docs)
|
|
362
|
+
doc.seq = first + row.k;
|
|
363
|
+
return result;
|
|
364
|
+
}
|
|
365
|
+
catch (err) {
|
|
366
|
+
await db.query('ROLLBACK').catch(() => undefined);
|
|
367
|
+
throw err;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
finally {
|
|
371
|
+
if (queued)
|
|
372
|
+
await db.query('SELECT pg_advisory_unlock(hashtext($1))', [
|
|
373
|
+
this.retryLockKey,
|
|
374
|
+
]);
|
|
375
|
+
}
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
catch (err) {
|
|
379
|
+
if (err instanceof AgentropyError)
|
|
380
|
+
throw err;
|
|
381
|
+
const code = pgCode(err);
|
|
382
|
+
if (!code || !SQLSTATE.test(code))
|
|
383
|
+
throw err;
|
|
384
|
+
if (!RETRYABLE.has(code))
|
|
385
|
+
throw fromSqlState(code);
|
|
386
|
+
const exhausted = attempt >= this.maxRetries;
|
|
387
|
+
this.o.telemetry?.count(METRICS.storeConflicts, 1, {
|
|
388
|
+
'agentropy.store.adapter': 'postgres',
|
|
389
|
+
'agentropy.store.outcome': exhausted ? 'exhausted' : 'retried',
|
|
390
|
+
'agentropy.store.sqlstate': code,
|
|
391
|
+
});
|
|
392
|
+
if (exhausted)
|
|
393
|
+
throw new AgentropyError('StaleRevision', 'Transaction kept conflicting with concurrent writers', { details: { reason: 'serialization', attempts: attempt + 1 } });
|
|
394
|
+
await new Promise((r) => setTimeout(r, Math.random() * 5 * 2 ** Math.min(attempt, 5)));
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
async close() {
|
|
399
|
+
if (this.closed)
|
|
400
|
+
return;
|
|
401
|
+
this.closed = true;
|
|
402
|
+
if (this.o.ownsConnection) {
|
|
403
|
+
if (this.o.pool?.end)
|
|
404
|
+
await this.o.pool.end();
|
|
405
|
+
const c = this.o.client;
|
|
406
|
+
if (c?.close)
|
|
407
|
+
await this.mutex.run(() => c.close());
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
tx(db, st) {
|
|
411
|
+
const batch = this.o.batchWrites !== false;
|
|
412
|
+
const seen = (c, d) => {
|
|
413
|
+
st.known.set(keyOf(c, d.id), { revision: d.revision, seq: d.seq });
|
|
414
|
+
return d;
|
|
415
|
+
};
|
|
416
|
+
const get = async (c, id) => {
|
|
417
|
+
if (st.pending.has(keyOf(c, id)))
|
|
418
|
+
await this.flush(db, st, false);
|
|
419
|
+
const r = (await db.query(`SELECT id, revision, seq, value FROM ${this.t(c)} WHERE id = $1`, [id])).rows[0];
|
|
420
|
+
return r ? seen(c, toDoc(r)) : undefined;
|
|
421
|
+
};
|
|
422
|
+
const sendUnlessBatched = async () => {
|
|
423
|
+
if (!batch)
|
|
424
|
+
await this.flush(db, st, false);
|
|
425
|
+
};
|
|
426
|
+
const split = (v) => v === null ? [null, null] : typeof v === 'number' ? [v, null] : [null, v];
|
|
427
|
+
const indexParams = (c, value) => {
|
|
428
|
+
const idx = indexValues(c, value);
|
|
429
|
+
const fields = Object.keys(idx);
|
|
430
|
+
return {
|
|
431
|
+
cols: fields.flatMap((f) => [`"n_${f}"`, `"s_${f}"`]),
|
|
432
|
+
params: fields.flatMap((f) => split(idx[f])),
|
|
433
|
+
};
|
|
434
|
+
};
|
|
435
|
+
const allowed = (c, field) => {
|
|
436
|
+
if (!STORE_COLLECTIONS[c].includes(field))
|
|
437
|
+
throw new AgentropyError('Internal', `${c}.${field} is not indexed`);
|
|
438
|
+
};
|
|
439
|
+
return {
|
|
440
|
+
get,
|
|
441
|
+
insert: async (c, id, value) => {
|
|
442
|
+
const { cols, params } = indexParams(c, value);
|
|
443
|
+
const key = keyOf(c, id);
|
|
444
|
+
if (st.known.has(key) || st.pending.has(key))
|
|
445
|
+
throw staleRevision(c, id, 'exists');
|
|
446
|
+
// Buffered until the next read of this collection or the commit; the final seq is assigned at commit.
|
|
447
|
+
// Until then the row sorts after every committed row. A taken ID fails when the write is sent.
|
|
448
|
+
const row = {
|
|
449
|
+
c,
|
|
450
|
+
id,
|
|
451
|
+
k: st.inserted.length,
|
|
452
|
+
sent: false,
|
|
453
|
+
docs: [],
|
|
454
|
+
};
|
|
455
|
+
const doc = {
|
|
456
|
+
id,
|
|
457
|
+
revision: 1,
|
|
458
|
+
seq: PROVISIONAL_SEQ + row.k,
|
|
459
|
+
value: structuredClone(value),
|
|
460
|
+
};
|
|
461
|
+
row.docs.push(doc);
|
|
462
|
+
st.inserted.push(row);
|
|
463
|
+
st.rows.set(key, row);
|
|
464
|
+
st.pending.set(key, {
|
|
465
|
+
kind: 'insert',
|
|
466
|
+
c,
|
|
467
|
+
id,
|
|
468
|
+
revision: 1,
|
|
469
|
+
value: JSON.stringify(value),
|
|
470
|
+
cols,
|
|
471
|
+
params,
|
|
472
|
+
row,
|
|
473
|
+
});
|
|
474
|
+
await sendUnlessBatched();
|
|
475
|
+
return doc;
|
|
476
|
+
},
|
|
477
|
+
update: async (c, id, expected, value) => {
|
|
478
|
+
const { cols, params } = indexParams(c, value);
|
|
479
|
+
const key = keyOf(c, id);
|
|
480
|
+
const pending = st.pending.get(key);
|
|
481
|
+
const known = st.known.get(key);
|
|
482
|
+
if (pending || known) {
|
|
483
|
+
// A row this transaction has read or written: its revision and seq are known, so the write can wait.
|
|
484
|
+
const current = pending?.revision ?? known.revision;
|
|
485
|
+
if (current !== expected)
|
|
486
|
+
throw staleRevision(c, id, 'revision', expected, current);
|
|
487
|
+
const write = {
|
|
488
|
+
revision: expected + 1,
|
|
489
|
+
value: JSON.stringify(value),
|
|
490
|
+
cols,
|
|
491
|
+
params,
|
|
492
|
+
};
|
|
493
|
+
if (pending)
|
|
494
|
+
Object.assign(pending, write);
|
|
495
|
+
else
|
|
496
|
+
st.pending.set(key, {
|
|
497
|
+
kind: 'update',
|
|
498
|
+
c,
|
|
499
|
+
id,
|
|
500
|
+
expected,
|
|
501
|
+
...write,
|
|
502
|
+
});
|
|
503
|
+
const row = st.rows.get(key);
|
|
504
|
+
const doc = {
|
|
505
|
+
id,
|
|
506
|
+
revision: expected + 1,
|
|
507
|
+
seq: row ? PROVISIONAL_SEQ + row.k : known.seq,
|
|
508
|
+
value: structuredClone(value),
|
|
509
|
+
};
|
|
510
|
+
row?.docs.push(doc);
|
|
511
|
+
await sendUnlessBatched();
|
|
512
|
+
return doc;
|
|
513
|
+
}
|
|
514
|
+
const sets = ['revision', 'value', ...cols].map((col, i) => `${col} = $${i + 1}`);
|
|
515
|
+
const n = sets.length;
|
|
516
|
+
const res = await db.query(`UPDATE ${this.t(c)} SET ${sets.join(', ')} WHERE id = $${n + 1} AND revision = $${n + 2} RETURNING seq`, [expected + 1, JSON.stringify(value), ...params, id, expected]);
|
|
517
|
+
if (res.rows.length !== 1) {
|
|
518
|
+
const cur = await get(c, id);
|
|
519
|
+
if (!cur)
|
|
520
|
+
throw staleRevision(c, id, 'missing', expected);
|
|
521
|
+
throw staleRevision(c, id, 'revision', expected, cur.revision);
|
|
522
|
+
}
|
|
523
|
+
return seen(c, {
|
|
524
|
+
id,
|
|
525
|
+
revision: expected + 1,
|
|
526
|
+
seq: Number(res.rows[0].seq),
|
|
527
|
+
value: structuredClone(value),
|
|
528
|
+
});
|
|
529
|
+
},
|
|
530
|
+
remove: async (c, id, expected) => {
|
|
531
|
+
const key = keyOf(c, id);
|
|
532
|
+
if (st.pending.has(key))
|
|
533
|
+
await this.flush(db, st, false);
|
|
534
|
+
st.known.delete(key);
|
|
535
|
+
const res = await db.query(`DELETE FROM ${this.t(c)} WHERE id = $1 AND revision = $2`, [id, expected]);
|
|
536
|
+
if (affected(res) !== 1) {
|
|
537
|
+
const cur = await get(c, id);
|
|
538
|
+
if (!cur)
|
|
539
|
+
throw staleRevision(c, id, 'missing', expected);
|
|
540
|
+
throw staleRevision(c, id, 'revision', expected, cur.revision);
|
|
541
|
+
}
|
|
542
|
+
},
|
|
543
|
+
find: async (c, o = {}) => {
|
|
544
|
+
const clauses = [];
|
|
545
|
+
const params = [];
|
|
546
|
+
const p = (v) => {
|
|
547
|
+
params.push(v);
|
|
548
|
+
return `$${params.length}`;
|
|
549
|
+
};
|
|
550
|
+
const column = (f, v) => `"${typeof v === 'number' ? 'n' : 's'}_${f}"`;
|
|
551
|
+
for (const [field, v] of Object.entries(o.where ?? {})) {
|
|
552
|
+
allowed(c, field);
|
|
553
|
+
if (v === null)
|
|
554
|
+
clauses.push(`"n_${field}" IS NULL AND "s_${field}" IS NULL`);
|
|
555
|
+
else
|
|
556
|
+
clauses.push(`${column(field, v)} = ${p(v)}`);
|
|
557
|
+
}
|
|
558
|
+
if (o.range) {
|
|
559
|
+
const f = String(o.range.field);
|
|
560
|
+
allowed(c, f);
|
|
561
|
+
const { gte, lte } = o.range;
|
|
562
|
+
const probe = gte ?? lte;
|
|
563
|
+
if (probe === undefined || probe === null)
|
|
564
|
+
clauses.push(`("n_${f}" IS NOT NULL OR "s_${f}" IS NOT NULL)`);
|
|
565
|
+
else {
|
|
566
|
+
// Mixed-type comparisons follow the reference: numbers and strings are kept in separate columns.
|
|
567
|
+
const col = column(f, probe);
|
|
568
|
+
clauses.push(`${col} IS NOT NULL`);
|
|
569
|
+
if (gte !== undefined && gte !== null)
|
|
570
|
+
clauses.push(`${col} >= ${p(gte)}`);
|
|
571
|
+
if (lte !== undefined && lte !== null)
|
|
572
|
+
clauses.push(`${col} <= ${p(lte)}`);
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
if (o.afterSeq !== undefined)
|
|
576
|
+
clauses.push(`seq > ${p(o.afterSeq)}`);
|
|
577
|
+
if (o.beforeSeq !== undefined)
|
|
578
|
+
clauses.push(`seq < ${p(o.beforeSeq)}`);
|
|
579
|
+
// Read your own writes: buffered writes to this collection are sent first.
|
|
580
|
+
if ([...st.pending.values()].some((w) => w.c === c))
|
|
581
|
+
await this.flush(db, st, false);
|
|
582
|
+
const by = String(o.orderBy ?? 'seq');
|
|
583
|
+
if (by !== 'seq')
|
|
584
|
+
allowed(c, by);
|
|
585
|
+
const order = o.descending
|
|
586
|
+
? by === 'seq'
|
|
587
|
+
? 'seq DESC'
|
|
588
|
+
: `"n_${by}" DESC NULLS LAST, "s_${by}" DESC NULLS LAST, seq DESC`
|
|
589
|
+
: by === 'seq'
|
|
590
|
+
? 'seq'
|
|
591
|
+
: `"n_${by}" ASC NULLS FIRST, "s_${by}" ASC NULLS FIRST, seq`;
|
|
592
|
+
const where = clauses.length ? `WHERE ${clauses.join(' AND ')}` : '';
|
|
593
|
+
const limit = o.limit !== undefined
|
|
594
|
+
? `LIMIT ${Math.max(0, Math.floor(o.limit))}`
|
|
595
|
+
: '';
|
|
596
|
+
const rows = (await db.query(`SELECT id, revision, seq, value FROM ${this.t(c)} ${where} ORDER BY ${order} ${limit}`, params)).rows;
|
|
597
|
+
return rows.map((r) => seen(c, toDoc(r)));
|
|
598
|
+
},
|
|
599
|
+
};
|
|
600
|
+
}
|
|
601
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agentropy/store-postgres",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Agentropy Store adapter for PostgreSQL on a driver-neutral client port.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
|
@@ -9,7 +9,41 @@
|
|
|
9
9
|
"directory": "packages/store-postgres"
|
|
10
10
|
},
|
|
11
11
|
"homepage": "https://github.com/bassemZohdy/agentropy/tree/main/packages/store-postgres#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/bassemZohdy/agentropy/issues"
|
|
14
|
+
},
|
|
15
|
+
"keywords": [
|
|
16
|
+
"agents",
|
|
17
|
+
"postgresql",
|
|
18
|
+
"storage",
|
|
19
|
+
"durable-execution",
|
|
20
|
+
"agentropy"
|
|
21
|
+
],
|
|
22
|
+
"engines": {
|
|
23
|
+
"node": ">=24"
|
|
24
|
+
},
|
|
25
|
+
"type": "module",
|
|
26
|
+
"exports": {
|
|
27
|
+
".": {
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"default": "./dist/index.js"
|
|
30
|
+
}
|
|
31
|
+
},
|
|
12
32
|
"files": [
|
|
13
|
-
"
|
|
14
|
-
|
|
15
|
-
|
|
33
|
+
"dist",
|
|
34
|
+
"LICENSE"
|
|
35
|
+
],
|
|
36
|
+
"dependencies": {
|
|
37
|
+
"@agentropy/core": "0.1.0"
|
|
38
|
+
},
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"@electric-sql/pglite": "0.5.16",
|
|
41
|
+
"@types/pg": "^8.23.1",
|
|
42
|
+
"pg": "^8.23.1",
|
|
43
|
+
"@agentropy/testkit": "0.1.0"
|
|
44
|
+
},
|
|
45
|
+
"scripts": {
|
|
46
|
+
"build": "tsc -b",
|
|
47
|
+
"typecheck": "tsc --noEmit"
|
|
48
|
+
}
|
|
49
|
+
}
|