@rulvar/store-postgres 1.57.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 +27 -0
- package/dist/index.d.ts +115 -0
- package/dist/index.js +409 -0
- package/package.json +50 -0
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
|
+
http://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
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# @rulvar/store-postgres
|
|
2
|
+
|
|
3
|
+
PostgreSQL journal store implementing the Rulvar storage SPI with the
|
|
4
|
+
lease capability and a fencing epoch, on node-postgres (`pg`); the
|
|
5
|
+
production reference for multi-process and multi-host deployments.
|
|
6
|
+
Exports `PostgresStore`.
|
|
7
|
+
|
|
8
|
+
Part of [Rulvar](https://rulvar.com), an embeddable TypeScript engine
|
|
9
|
+
for durable, budget-bounded multi-agent LLM workflows, where a completed
|
|
10
|
+
LLM call is never paid for twice. Full documentation:
|
|
11
|
+
[docs.rulvar.com](https://docs.rulvar.com).
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pnpm add @rulvar/core @rulvar/store-postgres
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Documentation
|
|
20
|
+
|
|
21
|
+
- [Stores](https://docs.rulvar.com/guide/stores)
|
|
22
|
+
- [Store authors](https://docs.rulvar.com/guide/store-authors)
|
|
23
|
+
- [API reference](https://docs.rulvar.com/api/%40rulvar/store-postgres/)
|
|
24
|
+
|
|
25
|
+
## License
|
|
26
|
+
|
|
27
|
+
[Apache-2.0](https://github.com/o-stepper/rulvar/blob/main/LICENSE)
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { JournalEntry, LeasableStore, Lease, MetaLookupStore, RunFilter, RunMeta, TranscriptStore } from "@rulvar/core";
|
|
2
|
+
|
|
3
|
+
//#region src/store.d.ts
|
|
4
|
+
/** Appendix A interim reference, shared with the sqlite store. */
|
|
5
|
+
declare const DEFAULT_LEASE_TTL_MS = 6e4;
|
|
6
|
+
/** Default pg Pool size; every operation is a short transaction. */
|
|
7
|
+
declare const DEFAULT_POOL_MAX = 10;
|
|
8
|
+
/**
|
|
9
|
+
* The fenced transcript twin over a PostgresStore database (the fenced
|
|
10
|
+
* run state RFC, F2): blobs live in the SAME database as the lease
|
|
11
|
+
* rows, so a lease-carrying put or delete verifies the current holder
|
|
12
|
+
* atomically with the blob mutation. Obtain it from
|
|
13
|
+
* {@link PostgresStore.transcripts}; its lifetime is the owning
|
|
14
|
+
* store's (one shared pool, one `close()`).
|
|
15
|
+
*/
|
|
16
|
+
interface PostgresTranscriptStore extends TranscriptStore {
|
|
17
|
+
readonly fencedWrites: true;
|
|
18
|
+
}
|
|
19
|
+
interface PostgresStoreOptions {
|
|
20
|
+
/**
|
|
21
|
+
* A postgres connection string
|
|
22
|
+
* (`postgres://user:password@host:port/database`). Every coordinating
|
|
23
|
+
* process and host points at the same database and schema.
|
|
24
|
+
*/
|
|
25
|
+
url: string;
|
|
26
|
+
/**
|
|
27
|
+
* Schema holding this store's tables; default `public`. A non-public
|
|
28
|
+
* schema is created on boot (`CREATE SCHEMA IF NOT EXISTS`), which
|
|
29
|
+
* also gives tests and multi-tenant hosts cheap isolation. Must be a
|
|
30
|
+
* plain SQL identifier.
|
|
31
|
+
*/
|
|
32
|
+
schema?: string;
|
|
33
|
+
/** Lease ttl; default the Appendix A interim reference (60000 ms). */
|
|
34
|
+
ttlMs?: number;
|
|
35
|
+
/** Pool size ceiling; default 10. */
|
|
36
|
+
max?: number;
|
|
37
|
+
/** Injectable clock for lease-expiry tests. */
|
|
38
|
+
now?: () => number;
|
|
39
|
+
}
|
|
40
|
+
declare class PostgresStore implements MetaLookupStore, LeasableStore {
|
|
41
|
+
/** The fenced writes promise (fenced run state RFC, phase 2). */
|
|
42
|
+
readonly fencedWrites = true;
|
|
43
|
+
private readonly pool;
|
|
44
|
+
private readonly schema;
|
|
45
|
+
private readonly ttlMs;
|
|
46
|
+
private readonly now;
|
|
47
|
+
private boot;
|
|
48
|
+
private transcriptTwin;
|
|
49
|
+
/**
|
|
50
|
+
* Per-run append chains: within ONE store instance, appends execute
|
|
51
|
+
* in submission order. The synchronous drivers of the other shipped
|
|
52
|
+
* stores get this for free (a sync append completes before the next
|
|
53
|
+
* call starts); over a genuinely async pool, the advisory lock alone
|
|
54
|
+
* hands the lock out in arrival order, and a later-submitted seq
|
|
55
|
+
* reaching the server first would trip the A5 tail guard on its
|
|
56
|
+
* earlier sibling. Cross-instance ordering stays the guard's job.
|
|
57
|
+
*/
|
|
58
|
+
private readonly appendChains;
|
|
59
|
+
constructor(options: PostgresStoreOptions);
|
|
60
|
+
/** `"schema".rulvar_<name>`, always schema-qualified. */
|
|
61
|
+
private table;
|
|
62
|
+
/**
|
|
63
|
+
* The lazy idempotent bootstrap, memoized so it runs once per store;
|
|
64
|
+
* a rejected boot clears the memo so the next call retries. The
|
|
65
|
+
* schema-scoped advisory transaction lock serializes a fleet of
|
|
66
|
+
* processes bootstrapping the same fresh database.
|
|
67
|
+
*/
|
|
68
|
+
private booted;
|
|
69
|
+
private runBootstrap;
|
|
70
|
+
/**
|
|
71
|
+
* One serialized run-scoped transaction: BEGIN, take the per-run
|
|
72
|
+
* advisory transaction lock, run `fn`, COMMIT. Every mutation of a
|
|
73
|
+
* run's state goes through here, which is what makes the fence check
|
|
74
|
+
* and the guarded mutation one unit across processes and hosts.
|
|
75
|
+
*/
|
|
76
|
+
private withRunLock;
|
|
77
|
+
close(): Promise<void>;
|
|
78
|
+
private liveLease;
|
|
79
|
+
/**
|
|
80
|
+
* A lease fences exactly the run it names (the sqlite rule): guarding
|
|
81
|
+
* a mutation of a DIFFERENT run would pass the holder check while
|
|
82
|
+
* touching state the lease never protected.
|
|
83
|
+
*/
|
|
84
|
+
private requireRunMatch;
|
|
85
|
+
private assertFencing;
|
|
86
|
+
/** Fence check plus guarded mutation as ONE serialized transaction. */
|
|
87
|
+
private fenced;
|
|
88
|
+
private insertEntry;
|
|
89
|
+
/** Chains run-scoped work in submission order for this instance. */
|
|
90
|
+
private chained;
|
|
91
|
+
append(runId: string, e: JournalEntry, lease?: Lease): Promise<void>;
|
|
92
|
+
load(runId: string): Promise<JournalEntry[]>;
|
|
93
|
+
private upsertMeta;
|
|
94
|
+
putMeta(m: RunMeta, lease?: Lease): Promise<void>;
|
|
95
|
+
getMeta(runId: string): Promise<RunMeta | undefined>;
|
|
96
|
+
listRuns(f?: RunFilter): Promise<RunMeta[]>;
|
|
97
|
+
private deleteRows;
|
|
98
|
+
delete(runId: string, lease?: Lease): Promise<void>;
|
|
99
|
+
/**
|
|
100
|
+
* The fenced transcript twin (RFC F2): blobs live in this store's
|
|
101
|
+
* database beside the lease rows, so a lease-carrying put or delete
|
|
102
|
+
* verifies the current holder of the run the ref's leading path
|
|
103
|
+
* segment names atomically with the blob mutation. Wire it as the
|
|
104
|
+
* engine's transcript store next to this store as the journal;
|
|
105
|
+
* `assertFencedWrites({ journal, transcripts })` verifies the pair.
|
|
106
|
+
*/
|
|
107
|
+
transcripts(): PostgresTranscriptStore;
|
|
108
|
+
/** TTL introspection (the LeasableStore optional capability). */
|
|
109
|
+
get leaseTtlMs(): number;
|
|
110
|
+
acquire(runId: string, owner: string): Promise<Lease>;
|
|
111
|
+
renew(l: Lease): Promise<void>;
|
|
112
|
+
release(l: Lease): Promise<void>;
|
|
113
|
+
}
|
|
114
|
+
//#endregion
|
|
115
|
+
export { DEFAULT_LEASE_TTL_MS, DEFAULT_POOL_MAX, PostgresStore, type PostgresStoreOptions, type PostgresTranscriptStore };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
import pg from "pg";
|
|
2
|
+
import { ConfigError, JournalOrderViolation, LeaseHeldError, metaMatchesFilter } from "@rulvar/core";
|
|
3
|
+
//#region src/store.ts
|
|
4
|
+
/**
|
|
5
|
+
* PostgresStore (RV-214): JournalStore plus LeasableStore with fencing
|
|
6
|
+
* epochs over node-postgres (`pg`); the production reference for
|
|
7
|
+
* multi-process AND multi-host deployments, where SqliteStore's
|
|
8
|
+
* one-file-per-host boundary ends.
|
|
9
|
+
*
|
|
10
|
+
* Contract highlights (executable definition: @rulvar/store-conformance):
|
|
11
|
+
* - A1-A4: a single INSERT is atomic; per-run order is the append order
|
|
12
|
+
* (a BIGSERIAL id); payloads are opaque TEXT JSON, unknown fields pass
|
|
13
|
+
* through byte-for-byte (deliberately NOT a jsonb column: jsonb
|
|
14
|
+
* normalizes key order and duplicate keys, and A4 forbids
|
|
15
|
+
* normalization; jsonb is used only in query-side casts and
|
|
16
|
+
* expression indexes).
|
|
17
|
+
* - Serialization: every run-scoped mutation (fenced or not) runs inside
|
|
18
|
+
* one transaction that first takes a per-run advisory transaction lock
|
|
19
|
+
* (`pg_advisory_xact_lock` over a hash of schema and runId). That is
|
|
20
|
+
* this store's translation of the sqlite BEGIN IMMEDIATE lesson (the
|
|
21
|
+
* fenced-run-state RFC, F3): the fence check and the guarded mutation
|
|
22
|
+
* commit as ONE serialized unit, so a takeover from another process or
|
|
23
|
+
* HOST cannot land between the check and the write. The lock is
|
|
24
|
+
* per-run, so unrelated runs never queue behind each other.
|
|
25
|
+
* - Fencing: the epoch is monotonic per run for the store's lifetime; an
|
|
26
|
+
* append carrying a stale or released lease rejects with the typed
|
|
27
|
+
* LeaseHeldError and the entry never becomes visible. `fencedWrites:
|
|
28
|
+
* true` on both the journal side and the transcript twin: putMeta,
|
|
29
|
+
* delete, and blob writes accept the same optional lease under the
|
|
30
|
+
* same atomic rule, and every lease-guarded mutation additionally
|
|
31
|
+
* requires the lease's runId to BE the mutated run.
|
|
32
|
+
* - A5 monotonic seq: the tail check and the insert are one conditional
|
|
33
|
+
* INSERT under the run's advisory lock, so a second writer racing the
|
|
34
|
+
* journal from a stale tail loses with a typed JournalOrderViolation.
|
|
35
|
+
* - Concurrent boot: the idempotent schema bootstrap runs lazily on
|
|
36
|
+
* first use, inside a schema-scoped advisory transaction lock, so a
|
|
37
|
+
* fleet start over one fresh database serializes instead of colliding
|
|
38
|
+
* in the DDL (the sqlite boot-race lesson, translated: postgres
|
|
39
|
+
* queues on the lock and needs no busy retry).
|
|
40
|
+
* - Clocks: lease expiry uses the CLIENT clock (injectable `now`),
|
|
41
|
+
* mirroring SqliteStore, so coordinating worker hosts must be
|
|
42
|
+
* NTP-synced and the lease ttl must dwarf their skew (the default
|
|
43
|
+
* 60000 ms dwarfs sane NTP drift). One write region per run: this
|
|
44
|
+
* store proves single-region multi-host fencing; a multi-region
|
|
45
|
+
* protocol is out of scope until proven.
|
|
46
|
+
* - Pooling and backpressure: one pg Pool per store (default max 10
|
|
47
|
+
* connections); every operation is a short transaction, so the pool
|
|
48
|
+
* IS the backpressure (excess operations queue for a client). Size it
|
|
49
|
+
* below the server's connection budget across all workers, or front
|
|
50
|
+
* the fleet with pgbouncer in session mode.
|
|
51
|
+
*/
|
|
52
|
+
/** Appendix A interim reference, shared with the sqlite store. */
|
|
53
|
+
const DEFAULT_LEASE_TTL_MS = 6e4;
|
|
54
|
+
/** Default pg Pool size; every operation is a short transaction. */
|
|
55
|
+
const DEFAULT_POOL_MAX = 10;
|
|
56
|
+
/** The advisory-lock hash seed; a constant namespace for this store. */
|
|
57
|
+
const LOCK_SEED = 8214;
|
|
58
|
+
const wallClock = Date.now.bind(globalThis);
|
|
59
|
+
/** A conservative SQL identifier gate for the schema option. */
|
|
60
|
+
const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
61
|
+
var PostgresStore = class {
|
|
62
|
+
/** The fenced writes promise (fenced run state RFC, phase 2). */
|
|
63
|
+
fencedWrites = true;
|
|
64
|
+
pool;
|
|
65
|
+
schema;
|
|
66
|
+
ttlMs;
|
|
67
|
+
now;
|
|
68
|
+
boot;
|
|
69
|
+
transcriptTwin;
|
|
70
|
+
/**
|
|
71
|
+
* Per-run append chains: within ONE store instance, appends execute
|
|
72
|
+
* in submission order. The synchronous drivers of the other shipped
|
|
73
|
+
* stores get this for free (a sync append completes before the next
|
|
74
|
+
* call starts); over a genuinely async pool, the advisory lock alone
|
|
75
|
+
* hands the lock out in arrival order, and a later-submitted seq
|
|
76
|
+
* reaching the server first would trip the A5 tail guard on its
|
|
77
|
+
* earlier sibling. Cross-instance ordering stays the guard's job.
|
|
78
|
+
*/
|
|
79
|
+
appendChains = /* @__PURE__ */ new Map();
|
|
80
|
+
constructor(options) {
|
|
81
|
+
if (typeof options.url !== "string" || options.url === "") throw new ConfigError("PostgresStoreOptions.url must be a nonempty connection string");
|
|
82
|
+
const schema = options.schema ?? "public";
|
|
83
|
+
if (!IDENTIFIER.test(schema)) throw new ConfigError(`PostgresStoreOptions.schema must be a plain SQL identifier; got '${schema}'`);
|
|
84
|
+
const ttlMs = options.ttlMs ?? 6e4;
|
|
85
|
+
if (!Number.isInteger(ttlMs) || ttlMs < 1 || ttlMs > 2147483647) throw new ConfigError(`PostgresStoreOptions.ttlMs must be an integer between 1 and 2147483647 ms (workers renew on Node timers at ttl/3); got ${String(ttlMs)}`);
|
|
86
|
+
if (options.max !== void 0 && (!Number.isInteger(options.max) || options.max < 1)) throw new ConfigError(`PostgresStoreOptions.max must be a positive integer; got ${String(options.max)}`);
|
|
87
|
+
this.schema = schema;
|
|
88
|
+
this.ttlMs = ttlMs;
|
|
89
|
+
this.now = options.now ?? wallClock;
|
|
90
|
+
this.pool = new pg.Pool({
|
|
91
|
+
connectionString: options.url,
|
|
92
|
+
max: options.max ?? 10
|
|
93
|
+
});
|
|
94
|
+
this.pool.on("error", () => void 0);
|
|
95
|
+
}
|
|
96
|
+
/** `"schema".rulvar_<name>`, always schema-qualified. */
|
|
97
|
+
table(name) {
|
|
98
|
+
return `"${this.schema}".rulvar_${name}`;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* The lazy idempotent bootstrap, memoized so it runs once per store;
|
|
102
|
+
* a rejected boot clears the memo so the next call retries. The
|
|
103
|
+
* schema-scoped advisory transaction lock serializes a fleet of
|
|
104
|
+
* processes bootstrapping the same fresh database.
|
|
105
|
+
*/
|
|
106
|
+
booted() {
|
|
107
|
+
this.boot ??= this.runBootstrap().catch((thrown) => {
|
|
108
|
+
this.boot = void 0;
|
|
109
|
+
throw thrown;
|
|
110
|
+
});
|
|
111
|
+
return this.boot;
|
|
112
|
+
}
|
|
113
|
+
async runBootstrap() {
|
|
114
|
+
const client = await this.pool.connect();
|
|
115
|
+
try {
|
|
116
|
+
await client.query("BEGIN");
|
|
117
|
+
await client.query("SELECT pg_advisory_xact_lock(hashtextextended($1, $2))", [`rulvar-boot:${this.schema}`, LOCK_SEED]);
|
|
118
|
+
if (this.schema !== "public") await client.query(`CREATE SCHEMA IF NOT EXISTS "${this.schema}"`);
|
|
119
|
+
await client.query(`
|
|
120
|
+
CREATE TABLE IF NOT EXISTS ${this.table("entries")} (
|
|
121
|
+
id BIGSERIAL PRIMARY KEY,
|
|
122
|
+
run_id TEXT NOT NULL,
|
|
123
|
+
payload TEXT NOT NULL
|
|
124
|
+
);
|
|
125
|
+
CREATE INDEX IF NOT EXISTS rulvar_entries_by_run
|
|
126
|
+
ON ${this.table("entries")} (run_id, id);
|
|
127
|
+
CREATE INDEX IF NOT EXISTS rulvar_entries_run_seq
|
|
128
|
+
ON ${this.table("entries")} (run_id, (((payload::jsonb ->> 'seq'))::numeric));
|
|
129
|
+
CREATE TABLE IF NOT EXISTS ${this.table("meta")} (
|
|
130
|
+
run_id TEXT PRIMARY KEY,
|
|
131
|
+
payload TEXT NOT NULL
|
|
132
|
+
);
|
|
133
|
+
CREATE INDEX IF NOT EXISTS rulvar_meta_by_status
|
|
134
|
+
ON ${this.table("meta")} (((payload::jsonb ->> 'status')));
|
|
135
|
+
CREATE INDEX IF NOT EXISTS rulvar_meta_by_name
|
|
136
|
+
ON ${this.table("meta")} (((payload::jsonb ->> 'name')));
|
|
137
|
+
CREATE TABLE IF NOT EXISTS ${this.table("leases")} (
|
|
138
|
+
run_id TEXT PRIMARY KEY,
|
|
139
|
+
owner TEXT NOT NULL,
|
|
140
|
+
epoch BIGINT NOT NULL,
|
|
141
|
+
expires_at BIGINT NOT NULL
|
|
142
|
+
);
|
|
143
|
+
CREATE TABLE IF NOT EXISTS ${this.table("epochs")} (
|
|
144
|
+
run_id TEXT PRIMARY KEY,
|
|
145
|
+
epoch BIGINT NOT NULL
|
|
146
|
+
);
|
|
147
|
+
CREATE TABLE IF NOT EXISTS ${this.table("blobs")} (
|
|
148
|
+
ref TEXT PRIMARY KEY,
|
|
149
|
+
run_id TEXT NOT NULL,
|
|
150
|
+
data BYTEA NOT NULL
|
|
151
|
+
);
|
|
152
|
+
CREATE INDEX IF NOT EXISTS rulvar_blobs_by_run
|
|
153
|
+
ON ${this.table("blobs")} (run_id);
|
|
154
|
+
`);
|
|
155
|
+
await client.query("COMMIT");
|
|
156
|
+
} catch (thrown) {
|
|
157
|
+
await client.query("ROLLBACK").catch(() => void 0);
|
|
158
|
+
throw thrown;
|
|
159
|
+
} finally {
|
|
160
|
+
client.release();
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* One serialized run-scoped transaction: BEGIN, take the per-run
|
|
165
|
+
* advisory transaction lock, run `fn`, COMMIT. Every mutation of a
|
|
166
|
+
* run's state goes through here, which is what makes the fence check
|
|
167
|
+
* and the guarded mutation one unit across processes and hosts.
|
|
168
|
+
*/
|
|
169
|
+
async withRunLock(runId, fn) {
|
|
170
|
+
await this.booted();
|
|
171
|
+
const client = await this.pool.connect();
|
|
172
|
+
try {
|
|
173
|
+
await client.query("BEGIN");
|
|
174
|
+
await client.query("SELECT pg_advisory_xact_lock(hashtextextended($1, $2))", [`${this.schema}:${runId}`, LOCK_SEED]);
|
|
175
|
+
const result = await fn(client);
|
|
176
|
+
await client.query("COMMIT");
|
|
177
|
+
return result;
|
|
178
|
+
} catch (thrown) {
|
|
179
|
+
await client.query("ROLLBACK").catch(() => void 0);
|
|
180
|
+
throw thrown;
|
|
181
|
+
} finally {
|
|
182
|
+
client.release();
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
async close() {
|
|
186
|
+
await this.pool.end();
|
|
187
|
+
}
|
|
188
|
+
async liveLease(client, runId) {
|
|
189
|
+
const row = (await client.query(`SELECT owner, epoch::int8 AS epoch, expires_at::int8 AS expires_at
|
|
190
|
+
FROM ${this.table("leases")} WHERE run_id = $1`, [runId])).rows[0];
|
|
191
|
+
if (row === void 0) return;
|
|
192
|
+
const lease = {
|
|
193
|
+
owner: row.owner,
|
|
194
|
+
epoch: Number(row.epoch),
|
|
195
|
+
expires_at: Number(row.expires_at)
|
|
196
|
+
};
|
|
197
|
+
return lease.expires_at <= this.now() ? void 0 : lease;
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* A lease fences exactly the run it names (the sqlite rule): guarding
|
|
201
|
+
* a mutation of a DIFFERENT run would pass the holder check while
|
|
202
|
+
* touching state the lease never protected.
|
|
203
|
+
*/
|
|
204
|
+
requireRunMatch(lease, runId, mutation) {
|
|
205
|
+
if (lease.runId !== runId) throw new LeaseHeldError(`lease for run '${lease.runId}' (owner ${lease.owner}, epoch ${lease.epoch}) cannot guard a ${mutation} of run '${runId}'; the mutation is rejected and nothing changed`);
|
|
206
|
+
}
|
|
207
|
+
async assertFencing(client, lease) {
|
|
208
|
+
const live = await this.liveLease(client, lease.runId);
|
|
209
|
+
if (live === void 0 || live.owner !== lease.owner || live.epoch !== lease.epoch) throw new LeaseHeldError(`stale fencing epoch for run '${lease.runId}': lease (owner ${lease.owner}, epoch ${lease.epoch}) is not the current holder; the append or renew is rejected and nothing became visible`);
|
|
210
|
+
}
|
|
211
|
+
/** Fence check plus guarded mutation as ONE serialized transaction. */
|
|
212
|
+
fenced(lease, mutate) {
|
|
213
|
+
return this.withRunLock(lease.runId, async (client) => {
|
|
214
|
+
await this.assertFencing(client, lease);
|
|
215
|
+
await mutate(client);
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
async insertEntry(client, runId, e) {
|
|
219
|
+
if (!Number.isFinite(e.seq)) {
|
|
220
|
+
await client.query(`INSERT INTO ${this.table("entries")} (run_id, payload) VALUES ($1, $2)`, [runId, JSON.stringify(e)]);
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
if ((await client.query(`INSERT INTO ${this.table("entries")} (run_id, payload)
|
|
224
|
+
SELECT $1, $2 WHERE NOT EXISTS (
|
|
225
|
+
SELECT 1 FROM ${this.table("entries")}
|
|
226
|
+
WHERE run_id = $1 AND ((payload::jsonb ->> 'seq'))::numeric >= $3)`, [
|
|
227
|
+
runId,
|
|
228
|
+
JSON.stringify(e),
|
|
229
|
+
e.seq
|
|
230
|
+
])).rowCount === 0) throw new JournalOrderViolation(`PostgresStore: append of seq ${e.seq} to run '${runId}' is not after the stored tail seq; a concurrent writer raced this journal from a stale tail`);
|
|
231
|
+
}
|
|
232
|
+
/** Chains run-scoped work in submission order for this instance. */
|
|
233
|
+
chained(runId, work) {
|
|
234
|
+
const next = (this.appendChains.get(runId) ?? Promise.resolve()).catch(() => void 0).then(work);
|
|
235
|
+
const tail = next.then(() => void 0, () => void 0);
|
|
236
|
+
this.appendChains.set(runId, tail);
|
|
237
|
+
tail.then(() => {
|
|
238
|
+
if (this.appendChains.get(runId) === tail) this.appendChains.delete(runId);
|
|
239
|
+
});
|
|
240
|
+
return next;
|
|
241
|
+
}
|
|
242
|
+
append(runId, e, lease) {
|
|
243
|
+
if (lease !== void 0) {
|
|
244
|
+
this.requireRunMatch(lease, runId, "journal append");
|
|
245
|
+
return this.chained(runId, () => this.fenced(lease, (client) => this.insertEntry(client, runId, e)));
|
|
246
|
+
}
|
|
247
|
+
return this.chained(runId, () => this.withRunLock(runId, (client) => this.insertEntry(client, runId, e)));
|
|
248
|
+
}
|
|
249
|
+
async load(runId) {
|
|
250
|
+
await this.booted();
|
|
251
|
+
return (await this.pool.query(`SELECT payload FROM ${this.table("entries")} WHERE run_id = $1 ORDER BY id`, [runId])).rows.map((row) => JSON.parse(row.payload));
|
|
252
|
+
}
|
|
253
|
+
async upsertMeta(client, m) {
|
|
254
|
+
await client.query(`INSERT INTO ${this.table("meta")} (run_id, payload) VALUES ($1, $2)
|
|
255
|
+
ON CONFLICT (run_id) DO UPDATE SET payload = excluded.payload`, [m.runId, JSON.stringify(m)]);
|
|
256
|
+
}
|
|
257
|
+
async putMeta(m, lease) {
|
|
258
|
+
if (lease !== void 0) {
|
|
259
|
+
this.requireRunMatch(lease, m.runId, "meta write");
|
|
260
|
+
await this.fenced(lease, (client) => this.upsertMeta(client, m));
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
await this.booted();
|
|
264
|
+
await this.upsertMeta(this.pool, m);
|
|
265
|
+
}
|
|
266
|
+
async getMeta(runId) {
|
|
267
|
+
await this.booted();
|
|
268
|
+
const row = (await this.pool.query(`SELECT payload FROM ${this.table("meta")} WHERE run_id = $1`, [runId])).rows[0];
|
|
269
|
+
return row === void 0 ? void 0 : JSON.parse(row.payload);
|
|
270
|
+
}
|
|
271
|
+
async listRuns(f) {
|
|
272
|
+
await this.booted();
|
|
273
|
+
const where = [];
|
|
274
|
+
const params = [];
|
|
275
|
+
if (f?.status !== void 0 || f?.statuses !== void 0) {
|
|
276
|
+
const wanted = [...f.status === void 0 ? [] : [f.status], ...f.statuses ?? []];
|
|
277
|
+
if (wanted.length === 0) where.push("1 = 0");
|
|
278
|
+
else {
|
|
279
|
+
const marks = wanted.map((_, i) => `$${params.length + i + 1}`);
|
|
280
|
+
where.push(`(payload::jsonb ->> 'status') IN (${marks.join(", ")})`);
|
|
281
|
+
params.push(...wanted);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
if (f?.name !== void 0) {
|
|
285
|
+
where.push(`(payload::jsonb ->> 'name') = $${params.length + 1}`);
|
|
286
|
+
params.push(f.name);
|
|
287
|
+
}
|
|
288
|
+
const sql = `SELECT payload FROM ${this.table("meta")}` + (where.length === 0 ? "" : ` WHERE ${where.join(" AND ")}`) + " ORDER BY run_id";
|
|
289
|
+
return (await this.pool.query(sql, params)).rows.map((row) => JSON.parse(row.payload)).filter((meta) => metaMatchesFilter(meta, f));
|
|
290
|
+
}
|
|
291
|
+
async deleteRows(client, runId) {
|
|
292
|
+
await client.query(`DELETE FROM ${this.table("entries")} WHERE run_id = $1`, [runId]);
|
|
293
|
+
await client.query(`DELETE FROM ${this.table("meta")} WHERE run_id = $1`, [runId]);
|
|
294
|
+
await client.query(`DELETE FROM ${this.table("leases")} WHERE run_id = $1`, [runId]);
|
|
295
|
+
await client.query(`DELETE FROM ${this.table("epochs")} WHERE run_id = $1`, [runId]);
|
|
296
|
+
}
|
|
297
|
+
async delete(runId, lease) {
|
|
298
|
+
if (lease !== void 0) {
|
|
299
|
+
this.requireRunMatch(lease, runId, "run deletion");
|
|
300
|
+
await this.fenced(lease, (client) => this.deleteRows(client, runId));
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
await this.withRunLock(runId, (client) => this.deleteRows(client, runId));
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* The fenced transcript twin (RFC F2): blobs live in this store's
|
|
307
|
+
* database beside the lease rows, so a lease-carrying put or delete
|
|
308
|
+
* verifies the current holder of the run the ref's leading path
|
|
309
|
+
* segment names atomically with the blob mutation. Wire it as the
|
|
310
|
+
* engine's transcript store next to this store as the journal;
|
|
311
|
+
* `assertFencedWrites({ journal, transcripts })` verifies the pair.
|
|
312
|
+
*/
|
|
313
|
+
transcripts() {
|
|
314
|
+
if (this.transcriptTwin !== void 0) return this.transcriptTwin;
|
|
315
|
+
const runOf = (ref) => ref.split("/", 1)[0] ?? ref;
|
|
316
|
+
const upsertBlob = async (client, ref, blob) => {
|
|
317
|
+
await client.query(`INSERT INTO ${this.table("blobs")} (ref, run_id, data) VALUES ($1, $2, $3)
|
|
318
|
+
ON CONFLICT (ref) DO UPDATE SET run_id = excluded.run_id, data = excluded.data`, [
|
|
319
|
+
ref,
|
|
320
|
+
runOf(ref),
|
|
321
|
+
Buffer.from(blob)
|
|
322
|
+
]);
|
|
323
|
+
};
|
|
324
|
+
const deleteBlob = async (client, ref) => {
|
|
325
|
+
await client.query(`DELETE FROM ${this.table("blobs")} WHERE ref = $1`, [ref]);
|
|
326
|
+
};
|
|
327
|
+
this.transcriptTwin = {
|
|
328
|
+
fencedWrites: true,
|
|
329
|
+
put: async (ref, blob, lease) => {
|
|
330
|
+
if (lease !== void 0) {
|
|
331
|
+
this.requireRunMatch(lease, runOf(ref), "transcript write");
|
|
332
|
+
await this.fenced(lease, (client) => upsertBlob(client, ref, blob));
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
await this.booted();
|
|
336
|
+
await upsertBlob(this.pool, ref, blob);
|
|
337
|
+
},
|
|
338
|
+
get: async (ref) => {
|
|
339
|
+
await this.booted();
|
|
340
|
+
const row = (await this.pool.query(`SELECT data FROM ${this.table("blobs")} WHERE ref = $1`, [ref])).rows[0];
|
|
341
|
+
return row === void 0 ? null : new Uint8Array(row.data);
|
|
342
|
+
},
|
|
343
|
+
list: async (runId) => {
|
|
344
|
+
await this.booted();
|
|
345
|
+
return (await this.pool.query(`SELECT ref FROM ${this.table("blobs")} WHERE run_id = $1 AND ref <> run_id ORDER BY ref`, [runId])).rows.map((row) => row.ref);
|
|
346
|
+
},
|
|
347
|
+
delete: async (ref, lease) => {
|
|
348
|
+
if (lease !== void 0) {
|
|
349
|
+
this.requireRunMatch(lease, runOf(ref), "transcript deletion");
|
|
350
|
+
await this.fenced(lease, (client) => deleteBlob(client, ref));
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
await this.booted();
|
|
354
|
+
await deleteBlob(this.pool, ref);
|
|
355
|
+
}
|
|
356
|
+
};
|
|
357
|
+
return this.transcriptTwin;
|
|
358
|
+
}
|
|
359
|
+
/** TTL introspection (the LeasableStore optional capability). */
|
|
360
|
+
get leaseTtlMs() {
|
|
361
|
+
return this.ttlMs;
|
|
362
|
+
}
|
|
363
|
+
acquire(runId, owner) {
|
|
364
|
+
return this.withRunLock(runId, async (client) => {
|
|
365
|
+
const live = await this.liveLease(client, runId);
|
|
366
|
+
if (live !== void 0) throw new LeaseHeldError(`run '${runId}' is leased by '${live.owner}' (epoch ${live.epoch}); acquire on a held lease rejects`);
|
|
367
|
+
const prior = (await client.query(`SELECT epoch::int8 AS epoch FROM ${this.table("epochs")} WHERE run_id = $1`, [runId])).rows;
|
|
368
|
+
const epoch = Number(prior[0]?.epoch ?? 0) + 1;
|
|
369
|
+
await client.query(`INSERT INTO ${this.table("epochs")} (run_id, epoch) VALUES ($1, $2)
|
|
370
|
+
ON CONFLICT (run_id) DO UPDATE SET epoch = excluded.epoch`, [runId, epoch]);
|
|
371
|
+
await client.query(`INSERT INTO ${this.table("leases")} (run_id, owner, epoch, expires_at)
|
|
372
|
+
VALUES ($1, $2, $3, $4)
|
|
373
|
+
ON CONFLICT (run_id) DO UPDATE SET owner = excluded.owner,
|
|
374
|
+
epoch = excluded.epoch, expires_at = excluded.expires_at`, [
|
|
375
|
+
runId,
|
|
376
|
+
owner,
|
|
377
|
+
epoch,
|
|
378
|
+
this.now() + this.ttlMs
|
|
379
|
+
]);
|
|
380
|
+
return {
|
|
381
|
+
runId,
|
|
382
|
+
owner,
|
|
383
|
+
epoch
|
|
384
|
+
};
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
renew(l) {
|
|
388
|
+
return this.fenced(l, async (client) => {
|
|
389
|
+
await client.query(`UPDATE ${this.table("leases")} SET expires_at = $1
|
|
390
|
+
WHERE run_id = $2 AND owner = $3 AND epoch = $4`, [
|
|
391
|
+
this.now() + this.ttlMs,
|
|
392
|
+
l.runId,
|
|
393
|
+
l.owner,
|
|
394
|
+
l.epoch
|
|
395
|
+
]);
|
|
396
|
+
});
|
|
397
|
+
}
|
|
398
|
+
release(l) {
|
|
399
|
+
return this.fenced(l, async (client) => {
|
|
400
|
+
await client.query(`DELETE FROM ${this.table("leases")} WHERE run_id = $1 AND owner = $2 AND epoch = $3`, [
|
|
401
|
+
l.runId,
|
|
402
|
+
l.owner,
|
|
403
|
+
l.epoch
|
|
404
|
+
]);
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
};
|
|
408
|
+
//#endregion
|
|
409
|
+
export { DEFAULT_LEASE_TTL_MS, DEFAULT_POOL_MAX, PostgresStore };
|
package/package.json
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@rulvar/store-postgres",
|
|
3
|
+
"version": "1.57.0",
|
|
4
|
+
"description": "Rulvar PostgreSQL store implementing JournalStore and LeasableStore with a fencing epoch, for multi-process and multi-host deployments.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=22.12.0"
|
|
9
|
+
},
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"./package.json": "./package.json"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"dist"
|
|
19
|
+
],
|
|
20
|
+
"sideEffects": false,
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"access": "public"
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"pg": "^8.22.0",
|
|
26
|
+
"@rulvar/core": "1.57.0"
|
|
27
|
+
},
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"@types/node": "^22.20.0",
|
|
30
|
+
"@types/pg": "^8.16.0",
|
|
31
|
+
"tsdown": "^0.22.3",
|
|
32
|
+
"typescript": "~6.0.3",
|
|
33
|
+
"@rulvar/store-conformance": "1.57.0"
|
|
34
|
+
},
|
|
35
|
+
"repository": {
|
|
36
|
+
"type": "git",
|
|
37
|
+
"url": "git+https://github.com/o-stepper/rulvar.git",
|
|
38
|
+
"directory": "packages/store-postgres"
|
|
39
|
+
},
|
|
40
|
+
"homepage": "https://rulvar.com",
|
|
41
|
+
"bugs": {
|
|
42
|
+
"url": "https://github.com/o-stepper/rulvar/issues"
|
|
43
|
+
},
|
|
44
|
+
"scripts": {
|
|
45
|
+
"build": "tsdown",
|
|
46
|
+
"typecheck": "tsc --noEmit",
|
|
47
|
+
"lint": "eslint .",
|
|
48
|
+
"pack-check": "publint --pack pnpm && attw --pack . --profile esm-only"
|
|
49
|
+
}
|
|
50
|
+
}
|