@molecule/api-instance-leadership-postgresql 0.0.0-stage → 1.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 +286 -2
- package/dist/browser-guard.d.ts +2 -0
- package/dist/browser-guard.d.ts.map +1 -0
- package/dist/browser-guard.js +18 -0
- package/dist/index.d.ts +46 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +45 -0
- package/dist/lock.d.ts +86 -0
- package/dist/lock.d.ts.map +1 -0
- package/dist/lock.js +128 -0
- package/dist/provider.d.ts +69 -0
- package/dist/provider.d.ts.map +1 -0
- package/dist/provider.js +167 -0
- package/package.json +61 -4
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
CHANGED
|
@@ -1,3 +1,287 @@
|
|
|
1
|
-
|
|
1
|
+
<!--
|
|
2
|
+
AUTO-GENERATED — DO NOT EDIT THIS FILE.
|
|
3
|
+
Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
|
|
4
|
+
Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
|
|
5
|
+
To change this document, edit the module-level JSDoc in src/index.ts.
|
|
6
|
+
Generated: 2026-10-19T22:02:10.972Z
|
|
7
|
+
-->
|
|
2
8
|
|
|
3
|
-
|
|
9
|
+
# @molecule/api-instance-leadership-postgresql
|
|
10
|
+
|
|
11
|
+
PostgreSQL provider for `@molecule/api-instance-leadership`: elect ONE API
|
|
12
|
+
instance to run platform-wide singleton work, using a PostgreSQL SESSION
|
|
13
|
+
advisory lock held on a dedicated connection.
|
|
14
|
+
|
|
15
|
+
```typescript
|
|
16
|
+
import { acquireLeadership, setProvider } from '@molecule/api-instance-leadership'
|
|
17
|
+
import { provider } from '@molecule/api-instance-leadership-postgresql'
|
|
18
|
+
|
|
19
|
+
setProvider(provider) // reads DATABASE_URL lazily; nothing connects here
|
|
20
|
+
acquireLeadership({
|
|
21
|
+
onAcquired: () => startPoolManager(),
|
|
22
|
+
onLost: () => stopPoolManager(),
|
|
23
|
+
})
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Use this bond whenever the API runs as more than one process or Machine: a
|
|
27
|
+
host-local lock (a loopback port, a file) elects one leader PER HOST, so
|
|
28
|
+
every singleton — pool managers, hibernation, retention sweeps, status
|
|
29
|
+
recorders — runs once per Machine instead of once per platform.
|
|
30
|
+
|
|
31
|
+
> **Auto-generated, AI-first package reference** for the [molecule.dev](https://molecule.dev) ecosystem.
|
|
32
|
+
> It is written to be read by coding agents as much as by people, and is generated from this
|
|
33
|
+
> package's source — edit `src/index.ts` JSDoc, not this file.
|
|
34
|
+
|
|
35
|
+
## Type
|
|
36
|
+
|
|
37
|
+
`provider`
|
|
38
|
+
|
|
39
|
+
## Installation
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
npm install @molecule/api-instance-leadership-postgresql @molecule/api-bond @molecule/api-instance-leadership pg
|
|
43
|
+
npm install -D @types/pg
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## API
|
|
47
|
+
|
|
48
|
+
### Interfaces
|
|
49
|
+
|
|
50
|
+
#### `PostgresLeaderLockOptions`
|
|
51
|
+
|
|
52
|
+
How to open the dedicated leadership connection.
|
|
53
|
+
|
|
54
|
+
```typescript
|
|
55
|
+
interface PostgresLeaderLockOptions {
|
|
56
|
+
/**
|
|
57
|
+
* The lock id to hold. This is an arbitrary 64-bit integer that must be
|
|
58
|
+
* unique across everything sharing the database: leadership must never
|
|
59
|
+
* contend with a migration lock or another feature's advisory lock.
|
|
60
|
+
*/
|
|
61
|
+
lockId: number
|
|
62
|
+
|
|
63
|
+
/** Connection string. Defaults to `process.env.DATABASE_URL`. */
|
|
64
|
+
connectionString?: string
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* TLS configuration passed to `pg`. Omit to let the driver decide from the
|
|
68
|
+
* connection string (`sslmode=require` still enables TLS).
|
|
69
|
+
*/
|
|
70
|
+
ssl?: pg.ConnectionConfig['ssl']
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Open a connected client. Injected by a host that owns its own connection
|
|
74
|
+
* settings (e.g. a platform API with a shared SSL derivation helper); the
|
|
75
|
+
* default creates a `pg.Client` from {@link PostgresLeaderLockOptions.connectionString}.
|
|
76
|
+
*
|
|
77
|
+
* @param connectionString - The resolved connection string.
|
|
78
|
+
* @param ssl - The configured TLS options.
|
|
79
|
+
* @returns A connected `pg.Client`.
|
|
80
|
+
*/
|
|
81
|
+
connect?: (connectionString: string, ssl: pg.ConnectionConfig['ssl']) => Promise<pg.Client>
|
|
82
|
+
}
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
#### `PostgresLeadershipProviderOptions`
|
|
86
|
+
|
|
87
|
+
How to build a leadership provider.
|
|
88
|
+
|
|
89
|
+
```typescript
|
|
90
|
+
interface PostgresLeadershipProviderOptions {
|
|
91
|
+
/**
|
|
92
|
+
* Opens one dedicated lock session per attempt. Use
|
|
93
|
+
* {@link createPostgresLockFactory} for the production PostgreSQL session,
|
|
94
|
+
* or a fake that shares one "held by" flag in tests.
|
|
95
|
+
*/
|
|
96
|
+
createSession: LeaderLockFactory
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* How often a follower retries, in milliseconds. A function keeps the value
|
|
100
|
+
* lazy so a host can read it from configuration after import. Defaults to
|
|
101
|
+
* 2000; values below 50 are clamped so a misconfiguration cannot spin.
|
|
102
|
+
*/
|
|
103
|
+
retryMs?: number | (() => number)
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* The advisory lock id, used only in log lines (the factory owns the actual
|
|
107
|
+
* lock). Defaults to 0 when omitted.
|
|
108
|
+
*/
|
|
109
|
+
lockId?: number
|
|
110
|
+
}
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### Classes
|
|
114
|
+
|
|
115
|
+
#### `PgLeaderLockSession`
|
|
116
|
+
|
|
117
|
+
The production session: one `pg.Client`, one advisory lock.
|
|
118
|
+
|
|
119
|
+
Exported so a host that owns its own connection settings (the platform API's
|
|
120
|
+
SSL derivation, a Vault-backed URL resolver) can build a session directly and
|
|
121
|
+
pass it to the provider as its `createSession` factory.
|
|
122
|
+
|
|
123
|
+
```typescript
|
|
124
|
+
class PgLeaderLockSession implements LeaderLockSession {
|
|
125
|
+
private lostHandler: (() => void) | null = null
|
|
126
|
+
private lost = false
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Track the connection's lifecycle so a lost session demotes the leader.
|
|
130
|
+
*
|
|
131
|
+
* @param client - A connected client owned exclusively by this session.
|
|
132
|
+
* @param lockId - The advisory lock id to hold.
|
|
133
|
+
*/
|
|
134
|
+
constructor(
|
|
135
|
+
private readonly client: pg.Client,
|
|
136
|
+
private readonly lockId: number,
|
|
137
|
+
) {
|
|
138
|
+
const lost = (): void => {
|
|
139
|
+
if (this.lost) return
|
|
140
|
+
this.lost = true
|
|
141
|
+
this.lostHandler?.()
|
|
142
|
+
}
|
|
143
|
+
// `error` covers a socket/network failure; `end` covers the backend ending
|
|
144
|
+
// the session (a server restart, an idle-session kill). Either way the lock
|
|
145
|
+
// is gone.
|
|
146
|
+
this.client.on('error', (error) => {
|
|
147
|
+
getLogger().warn('Leadership lock connection error', { error })
|
|
148
|
+
lost()
|
|
149
|
+
})
|
|
150
|
+
this.client.on('end', lost)
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** {@inheritDoc LeaderLockSession.tryLock} */
|
|
154
|
+
async tryLock(): Promise<boolean> {
|
|
155
|
+
const { rows } = await this.client.query<{ locked: boolean }>(
|
|
156
|
+
'SELECT pg_try_advisory_lock($1) AS locked',
|
|
157
|
+
[this.lockId],
|
|
158
|
+
)
|
|
159
|
+
return rows[0]?.locked === true
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** {@inheritDoc LeaderLockSession.release} */
|
|
163
|
+
async release(): Promise<void> {
|
|
164
|
+
if (!this.lost) {
|
|
165
|
+
try {
|
|
166
|
+
await this.client.query('SELECT pg_advisory_unlock($1)', [this.lockId])
|
|
167
|
+
} catch (error) {
|
|
168
|
+
// The session is ending either way, and a session lock is released by
|
|
169
|
+
// the backend when it ends — an unlock failure changes nothing.
|
|
170
|
+
getLogger().debug('Leadership advisory unlock failed; the session end releases it', {
|
|
171
|
+
error,
|
|
172
|
+
})
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
try {
|
|
176
|
+
await this.client.end()
|
|
177
|
+
} catch (_error) {
|
|
178
|
+
// Already ended.
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** {@inheritDoc LeaderLockSession.onLost} */
|
|
183
|
+
onLost(handler: () => void): void {
|
|
184
|
+
this.lostHandler = handler
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
### Functions
|
|
190
|
+
|
|
191
|
+
#### `createPostgresLockFactory(options)`
|
|
192
|
+
|
|
193
|
+
Builds a {@link LeaderLockFactory} that opens PostgreSQL session locks.
|
|
194
|
+
|
|
195
|
+
Each call to the factory opens a NEW dedicated connection — a follower
|
|
196
|
+
retries on its own connection, and a leader reconnects on a fresh one after
|
|
197
|
+
losing the old.
|
|
198
|
+
|
|
199
|
+
```typescript
|
|
200
|
+
function createPostgresLockFactory(options: PostgresLeaderLockOptions): LeaderLockFactory
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
- `options` — The lock id, connection settings and optional connect hook.
|
|
204
|
+
|
|
205
|
+
**Returns:** A factory the leadership provider calls to open each session.
|
|
206
|
+
|
|
207
|
+
#### `createProvider(options)`
|
|
208
|
+
|
|
209
|
+
Creates an instance-leadership provider.
|
|
210
|
+
|
|
211
|
+
```typescript
|
|
212
|
+
function createProvider(options: PostgresLeadershipProviderOptions): InstanceLeadershipProvider
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
- `options` — The lock-session factory and retry interval.
|
|
216
|
+
|
|
217
|
+
**Returns:** A provider implementing the core `InstanceLeadershipProvider` contract.
|
|
218
|
+
|
|
219
|
+
### Constants
|
|
220
|
+
|
|
221
|
+
#### `provider`
|
|
222
|
+
|
|
223
|
+
A provider that reads its connection settings from `DATABASE_URL`.
|
|
224
|
+
|
|
225
|
+
Its lock session is opened lazily, so importing (and bonding) this provider
|
|
226
|
+
never connects. The lock id is the same one the API platform API has used
|
|
227
|
+
for its singleton work; an app that shares a database with another
|
|
228
|
+
leadership user must pass its OWN `lockId`.
|
|
229
|
+
|
|
230
|
+
```typescript
|
|
231
|
+
const provider: InstanceLeadershipProvider
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
## Core Interface
|
|
235
|
+
|
|
236
|
+
Implements `@molecule/api-instance-leadership` interface.
|
|
237
|
+
|
|
238
|
+
## Bond Wiring
|
|
239
|
+
|
|
240
|
+
Setup function to register this provider with the core interface:
|
|
241
|
+
|
|
242
|
+
```typescript
|
|
243
|
+
import { setProvider } from '@molecule/api-instance-leadership'
|
|
244
|
+
import { provider } from '@molecule/api-instance-leadership-postgresql'
|
|
245
|
+
|
|
246
|
+
export function setupInstanceLeadershipPostgresql(): void {
|
|
247
|
+
setProvider(provider)
|
|
248
|
+
}
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
## Injection Notes
|
|
252
|
+
|
|
253
|
+
### Requirements
|
|
254
|
+
|
|
255
|
+
Peer dependencies:
|
|
256
|
+
|
|
257
|
+
- `@molecule/api-bond` ^1.0.1
|
|
258
|
+
- `@molecule/api-instance-leadership` ^1.0.0
|
|
259
|
+
|
|
260
|
+
### Environment Variables
|
|
261
|
+
|
|
262
|
+
- `DATABASE_URL` _(required)_ — PostgreSQL connection string
|
|
263
|
+
- Setup: Use a direct connection or a session-mode pooler; transaction-mode pooling cannot retain advisory locks.
|
|
264
|
+
|
|
265
|
+
### Runtime Dependencies
|
|
266
|
+
|
|
267
|
+
- `@molecule/api-bond`
|
|
268
|
+
- `@molecule/api-instance-leadership`
|
|
269
|
+
- `pg`
|
|
270
|
+
|
|
271
|
+
- **A session lock dies with its connection.** The holder's process exiting,
|
|
272
|
+
crashing, or losing the network ends the backend session and PostgreSQL
|
|
273
|
+
releases the lock — no TTL to tune, no lock row left stale.
|
|
274
|
+
- **A leader that loses its connection demotes itself.** The provider stops
|
|
275
|
+
treating itself as leader and calls `onLost`; a follower retries every
|
|
276
|
+
`retryMs` (default 2 s) and takes over within seconds.
|
|
277
|
+
- **`prepareThreshold`/pooling caveat.** The lock MUST be taken on a direct
|
|
278
|
+
client connection, never through a transaction-mode pooler (PgBouncer in
|
|
279
|
+
transaction mode), which multiplexes statements from many clients onto a
|
|
280
|
+
session: a lock "held" there is held by an unrelated session. Use a
|
|
281
|
+
session-mode pooler or a direct connection.
|
|
282
|
+
- **Pick a lock id nobody else uses.** Advisory locks share one namespace per
|
|
283
|
+
database. The exported `provider` uses `8675310`; a second application
|
|
284
|
+
sharing the same database must pass its own id to
|
|
285
|
+
`createPostgresLockFactory`.
|
|
286
|
+
- **This bond runs no singleton work itself.** It only tells the application
|
|
287
|
+
which instance leads; the loops belong to the app (`onAcquired`/`onLost`).
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"browser-guard.d.ts","sourceRoot":"","sources":["../src/browser-guard.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,CAAA"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser guard — `@molecule/api-instance-leadership-postgresql` is SERVER-ONLY.
|
|
3
|
+
*
|
|
4
|
+
* Generated by scripts/gen-browser-guards.mjs (workspace root) — edit THAT, not this.
|
|
5
|
+
* Evaluating a server package in a browser bundle is always an import-graph mistake
|
|
6
|
+
* (node APIs, secrets); without this guard it surfaces as a cryptic downstream crash
|
|
7
|
+
* ("Buffer is not defined") far from the culprit. Throwing here names the package and
|
|
8
|
+
* the fix at the exact moment the client bundle evaluates it. jsdom tests and SSR are
|
|
9
|
+
* unaffected: the throw requires browser globals AND the absence of a node runtime.
|
|
10
|
+
*/
|
|
11
|
+
const g = globalThis;
|
|
12
|
+
if (g.window !== undefined && g.document !== undefined && !g.process?.versions?.node) {
|
|
13
|
+
throw new Error('@molecule/api-instance-leadership-postgresql is SERVER-ONLY: it was bundled into browser/client code. Import it only ' +
|
|
14
|
+
'from server code (a server route/function or your API), or dynamic-import it inside ' +
|
|
15
|
+
'the server handler — never from components or shared client modules, and never ' +
|
|
16
|
+
'polyfill Buffer/process to silence this.');
|
|
17
|
+
}
|
|
18
|
+
export {};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PostgreSQL provider for `@molecule/api-instance-leadership`: elect ONE API
|
|
3
|
+
* instance to run platform-wide singleton work, using a PostgreSQL SESSION
|
|
4
|
+
* advisory lock held on a dedicated connection.
|
|
5
|
+
*
|
|
6
|
+
* ```typescript
|
|
7
|
+
* import { acquireLeadership, setProvider } from '@molecule/api-instance-leadership'
|
|
8
|
+
* import { provider } from '@molecule/api-instance-leadership-postgresql'
|
|
9
|
+
*
|
|
10
|
+
* setProvider(provider) // reads DATABASE_URL lazily; nothing connects here
|
|
11
|
+
* acquireLeadership({
|
|
12
|
+
* onAcquired: () => startPoolManager(),
|
|
13
|
+
* onLost: () => stopPoolManager(),
|
|
14
|
+
* })
|
|
15
|
+
* ```
|
|
16
|
+
*
|
|
17
|
+
* Use this bond whenever the API runs as more than one process or Machine: a
|
|
18
|
+
* host-local lock (a loopback port, a file) elects one leader PER HOST, so
|
|
19
|
+
* every singleton — pool managers, hibernation, retention sweeps, status
|
|
20
|
+
* recorders — runs once per Machine instead of once per platform.
|
|
21
|
+
*
|
|
22
|
+
* @remarks
|
|
23
|
+
* - **A session lock dies with its connection.** The holder's process exiting,
|
|
24
|
+
* crashing, or losing the network ends the backend session and PostgreSQL
|
|
25
|
+
* releases the lock — no TTL to tune, no lock row left stale.
|
|
26
|
+
* - **A leader that loses its connection demotes itself.** The provider stops
|
|
27
|
+
* treating itself as leader and calls `onLost`; a follower retries every
|
|
28
|
+
* `retryMs` (default 2 s) and takes over within seconds.
|
|
29
|
+
* - **`prepareThreshold`/pooling caveat.** The lock MUST be taken on a direct
|
|
30
|
+
* client connection, never through a transaction-mode pooler (PgBouncer in
|
|
31
|
+
* transaction mode), which multiplexes statements from many clients onto a
|
|
32
|
+
* session: a lock "held" there is held by an unrelated session. Use a
|
|
33
|
+
* session-mode pooler or a direct connection.
|
|
34
|
+
* - **Pick a lock id nobody else uses.** Advisory locks share one namespace per
|
|
35
|
+
* database. The exported `provider` uses `8675310`; a second application
|
|
36
|
+
* sharing the same database must pass its own id to
|
|
37
|
+
* `createPostgresLockFactory`.
|
|
38
|
+
* - **This bond runs no singleton work itself.** It only tells the application
|
|
39
|
+
* which instance leads; the loops belong to the app (`onAcquired`/`onLost`).
|
|
40
|
+
*
|
|
41
|
+
* @module
|
|
42
|
+
*/
|
|
43
|
+
export * from './browser-guard.js';
|
|
44
|
+
export * from './lock.js';
|
|
45
|
+
export * from './provider.js';
|
|
46
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,WAAW,CAAA;AACzB,cAAc,eAAe,CAAA"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PostgreSQL provider for `@molecule/api-instance-leadership`: elect ONE API
|
|
3
|
+
* instance to run platform-wide singleton work, using a PostgreSQL SESSION
|
|
4
|
+
* advisory lock held on a dedicated connection.
|
|
5
|
+
*
|
|
6
|
+
* ```typescript
|
|
7
|
+
* import { acquireLeadership, setProvider } from '@molecule/api-instance-leadership'
|
|
8
|
+
* import { provider } from '@molecule/api-instance-leadership-postgresql'
|
|
9
|
+
*
|
|
10
|
+
* setProvider(provider) // reads DATABASE_URL lazily; nothing connects here
|
|
11
|
+
* acquireLeadership({
|
|
12
|
+
* onAcquired: () => startPoolManager(),
|
|
13
|
+
* onLost: () => stopPoolManager(),
|
|
14
|
+
* })
|
|
15
|
+
* ```
|
|
16
|
+
*
|
|
17
|
+
* Use this bond whenever the API runs as more than one process or Machine: a
|
|
18
|
+
* host-local lock (a loopback port, a file) elects one leader PER HOST, so
|
|
19
|
+
* every singleton — pool managers, hibernation, retention sweeps, status
|
|
20
|
+
* recorders — runs once per Machine instead of once per platform.
|
|
21
|
+
*
|
|
22
|
+
* @remarks
|
|
23
|
+
* - **A session lock dies with its connection.** The holder's process exiting,
|
|
24
|
+
* crashing, or losing the network ends the backend session and PostgreSQL
|
|
25
|
+
* releases the lock — no TTL to tune, no lock row left stale.
|
|
26
|
+
* - **A leader that loses its connection demotes itself.** The provider stops
|
|
27
|
+
* treating itself as leader and calls `onLost`; a follower retries every
|
|
28
|
+
* `retryMs` (default 2 s) and takes over within seconds.
|
|
29
|
+
* - **`prepareThreshold`/pooling caveat.** The lock MUST be taken on a direct
|
|
30
|
+
* client connection, never through a transaction-mode pooler (PgBouncer in
|
|
31
|
+
* transaction mode), which multiplexes statements from many clients onto a
|
|
32
|
+
* session: a lock "held" there is held by an unrelated session. Use a
|
|
33
|
+
* session-mode pooler or a direct connection.
|
|
34
|
+
* - **Pick a lock id nobody else uses.** Advisory locks share one namespace per
|
|
35
|
+
* database. The exported `provider` uses `8675310`; a second application
|
|
36
|
+
* sharing the same database must pass its own id to
|
|
37
|
+
* `createPostgresLockFactory`.
|
|
38
|
+
* - **This bond runs no singleton work itself.** It only tells the application
|
|
39
|
+
* which instance leads; the loops belong to the app (`onAcquired`/`onLost`).
|
|
40
|
+
*
|
|
41
|
+
* @module
|
|
42
|
+
*/
|
|
43
|
+
export * from './browser-guard.js';
|
|
44
|
+
export * from './lock.js';
|
|
45
|
+
export * from './provider.js';
|
package/dist/lock.d.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PostgreSQL session-advisory-lock sessions for instance leadership.
|
|
3
|
+
*
|
|
4
|
+
* A session is one dedicated `pg.Client` (never a pool: a session lock is owned
|
|
5
|
+
* by its backend connection, and returning it to a pool would let unrelated
|
|
6
|
+
* queries run inside the lock's session) holding one advisory lock id.
|
|
7
|
+
*
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
import pg from 'pg';
|
|
11
|
+
import type { LeaderLockFactory, LeaderLockSession } from '@molecule/api-instance-leadership';
|
|
12
|
+
/**
|
|
13
|
+
* How to open the dedicated leadership connection.
|
|
14
|
+
*/
|
|
15
|
+
export interface PostgresLeaderLockOptions {
|
|
16
|
+
/**
|
|
17
|
+
* The lock id to hold. This is an arbitrary 64-bit integer that must be
|
|
18
|
+
* unique across everything sharing the database: leadership must never
|
|
19
|
+
* contend with a migration lock or another feature's advisory lock.
|
|
20
|
+
*/
|
|
21
|
+
lockId: number;
|
|
22
|
+
/** Connection string. Defaults to `process.env.DATABASE_URL`. */
|
|
23
|
+
connectionString?: string;
|
|
24
|
+
/**
|
|
25
|
+
* TLS configuration passed to `pg`. Omit to let the driver decide from the
|
|
26
|
+
* connection string (`sslmode=require` still enables TLS).
|
|
27
|
+
*/
|
|
28
|
+
ssl?: pg.ConnectionConfig['ssl'];
|
|
29
|
+
/**
|
|
30
|
+
* Open a connected client. Injected by a host that owns its own connection
|
|
31
|
+
* settings (e.g. a platform API with a shared SSL derivation helper); the
|
|
32
|
+
* default creates a `pg.Client` from {@link PostgresLeaderLockOptions.connectionString}.
|
|
33
|
+
*
|
|
34
|
+
* @param connectionString - The resolved connection string.
|
|
35
|
+
* @param ssl - The configured TLS options.
|
|
36
|
+
* @returns A connected `pg.Client`.
|
|
37
|
+
*/
|
|
38
|
+
connect?: (connectionString: string, ssl: pg.ConnectionConfig['ssl']) => Promise<pg.Client>;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* The production session: one `pg.Client`, one advisory lock.
|
|
42
|
+
*
|
|
43
|
+
* Exported so a host that owns its own connection settings (the platform API's
|
|
44
|
+
* SSL derivation, a Vault-backed URL resolver) can build a session directly and
|
|
45
|
+
* pass it to the provider as its `createSession` factory.
|
|
46
|
+
*/
|
|
47
|
+
export declare class PgLeaderLockSession implements LeaderLockSession {
|
|
48
|
+
private readonly client;
|
|
49
|
+
private readonly lockId;
|
|
50
|
+
private lostHandler;
|
|
51
|
+
private lost;
|
|
52
|
+
/**
|
|
53
|
+
* Track the connection's lifecycle so a lost session demotes the leader.
|
|
54
|
+
*
|
|
55
|
+
* @param client - A connected client owned exclusively by this session.
|
|
56
|
+
* @param lockId - The advisory lock id to hold.
|
|
57
|
+
*/
|
|
58
|
+
constructor(client: pg.Client, lockId: number);
|
|
59
|
+
/** {@inheritDoc LeaderLockSession.tryLock} */
|
|
60
|
+
tryLock(): Promise<boolean>;
|
|
61
|
+
/** {@inheritDoc LeaderLockSession.release} */
|
|
62
|
+
release(): Promise<void>;
|
|
63
|
+
/** {@inheritDoc LeaderLockSession.onLost} */
|
|
64
|
+
onLost(handler: () => void): void;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Builds a {@link LeaderLockFactory} that opens PostgreSQL session locks.
|
|
68
|
+
*
|
|
69
|
+
* Each call to the factory opens a NEW dedicated connection — a follower
|
|
70
|
+
* retries on its own connection, and a leader reconnects on a fresh one after
|
|
71
|
+
* losing the old.
|
|
72
|
+
*
|
|
73
|
+
* @param options - The lock id, connection settings and optional connect hook.
|
|
74
|
+
* @returns A factory the leadership provider calls to open each session.
|
|
75
|
+
* @throws {Error} When no connection string is configured (at factory-call
|
|
76
|
+
* time, so a boot fails with an actionable message rather than hanging).
|
|
77
|
+
*
|
|
78
|
+
* @example
|
|
79
|
+
* ```typescript
|
|
80
|
+
* import { createProvider } from '@molecule/api-instance-leadership-postgresql'
|
|
81
|
+
*
|
|
82
|
+
* const leadership = createProvider({ createSession: createPostgresLockFactory({ lockId: 8675310 }) })
|
|
83
|
+
* ```
|
|
84
|
+
*/
|
|
85
|
+
export declare function createPostgresLockFactory(options: PostgresLeaderLockOptions): LeaderLockFactory;
|
|
86
|
+
//# sourceMappingURL=lock.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lock.d.ts","sourceRoot":"","sources":["../src/lock.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,MAAM,IAAI,CAAA;AAGnB,OAAO,KAAK,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAA;AAE7F;;GAEG;AACH,MAAM,WAAW,yBAAyB;IACxC;;;;OAIG;IACH,MAAM,EAAE,MAAM,CAAA;IAEd,iEAAiE;IACjE,gBAAgB,CAAC,EAAE,MAAM,CAAA;IAEzB;;;OAGG;IACH,GAAG,CAAC,EAAE,EAAE,CAAC,gBAAgB,CAAC,KAAK,CAAC,CAAA;IAEhC;;;;;;;;OAQG;IACH,OAAO,CAAC,EAAE,CAAC,gBAAgB,EAAE,MAAM,EAAE,GAAG,EAAE,EAAE,CAAC,gBAAgB,CAAC,KAAK,CAAC,KAAK,OAAO,CAAC,EAAE,CAAC,MAAM,CAAC,CAAA;CAC5F;AAED;;;;;;GAMG;AACH,qBAAa,mBAAoB,YAAW,iBAAiB;IAWzD,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,MAAM;IAXzB,OAAO,CAAC,WAAW,CAA4B;IAC/C,OAAO,CAAC,IAAI,CAAQ;IAEpB;;;;;OAKG;gBAEgB,MAAM,EAAE,EAAE,CAAC,MAAM,EACjB,MAAM,EAAE,MAAM;IAiBjC,8CAA8C;IACxC,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC;IAQjC,8CAA8C;IACxC,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAmB9B,6CAA6C;IAC7C,MAAM,CAAC,OAAO,EAAE,MAAM,IAAI,GAAG,IAAI;CAGlC;AAyBD;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,yBAAyB,GAAG,iBAAiB,CAa/F"}
|
package/dist/lock.js
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PostgreSQL session-advisory-lock sessions for instance leadership.
|
|
3
|
+
*
|
|
4
|
+
* A session is one dedicated `pg.Client` (never a pool: a session lock is owned
|
|
5
|
+
* by its backend connection, and returning it to a pool would let unrelated
|
|
6
|
+
* queries run inside the lock's session) holding one advisory lock id.
|
|
7
|
+
*
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
import pg from 'pg';
|
|
11
|
+
import { getLogger } from '@molecule/api-bond';
|
|
12
|
+
/**
|
|
13
|
+
* The production session: one `pg.Client`, one advisory lock.
|
|
14
|
+
*
|
|
15
|
+
* Exported so a host that owns its own connection settings (the platform API's
|
|
16
|
+
* SSL derivation, a Vault-backed URL resolver) can build a session directly and
|
|
17
|
+
* pass it to the provider as its `createSession` factory.
|
|
18
|
+
*/
|
|
19
|
+
export class PgLeaderLockSession {
|
|
20
|
+
client;
|
|
21
|
+
lockId;
|
|
22
|
+
lostHandler = null;
|
|
23
|
+
lost = false;
|
|
24
|
+
/**
|
|
25
|
+
* Track the connection's lifecycle so a lost session demotes the leader.
|
|
26
|
+
*
|
|
27
|
+
* @param client - A connected client owned exclusively by this session.
|
|
28
|
+
* @param lockId - The advisory lock id to hold.
|
|
29
|
+
*/
|
|
30
|
+
constructor(client, lockId) {
|
|
31
|
+
this.client = client;
|
|
32
|
+
this.lockId = lockId;
|
|
33
|
+
const lost = () => {
|
|
34
|
+
if (this.lost)
|
|
35
|
+
return;
|
|
36
|
+
this.lost = true;
|
|
37
|
+
this.lostHandler?.();
|
|
38
|
+
};
|
|
39
|
+
// `error` covers a socket/network failure; `end` covers the backend ending
|
|
40
|
+
// the session (a server restart, an idle-session kill). Either way the lock
|
|
41
|
+
// is gone.
|
|
42
|
+
this.client.on('error', (error) => {
|
|
43
|
+
getLogger().warn('Leadership lock connection error', { error });
|
|
44
|
+
lost();
|
|
45
|
+
});
|
|
46
|
+
this.client.on('end', lost);
|
|
47
|
+
}
|
|
48
|
+
/** {@inheritDoc LeaderLockSession.tryLock} */
|
|
49
|
+
async tryLock() {
|
|
50
|
+
const { rows } = await this.client.query('SELECT pg_try_advisory_lock($1) AS locked', [this.lockId]);
|
|
51
|
+
return rows[0]?.locked === true;
|
|
52
|
+
}
|
|
53
|
+
/** {@inheritDoc LeaderLockSession.release} */
|
|
54
|
+
async release() {
|
|
55
|
+
if (!this.lost) {
|
|
56
|
+
try {
|
|
57
|
+
await this.client.query('SELECT pg_advisory_unlock($1)', [this.lockId]);
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
// The session is ending either way, and a session lock is released by
|
|
61
|
+
// the backend when it ends — an unlock failure changes nothing.
|
|
62
|
+
getLogger().debug('Leadership advisory unlock failed; the session end releases it', {
|
|
63
|
+
error,
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
try {
|
|
68
|
+
await this.client.end();
|
|
69
|
+
}
|
|
70
|
+
catch (_error) {
|
|
71
|
+
// Already ended.
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/** {@inheritDoc LeaderLockSession.onLost} */
|
|
75
|
+
onLost(handler) {
|
|
76
|
+
this.lostHandler = handler;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Opens a dedicated PostgreSQL session for leadership.
|
|
81
|
+
*
|
|
82
|
+
* The connect timeout bounds a hung database: without it a boot could sit in
|
|
83
|
+
* `acquire()` forever with no leader and no log line.
|
|
84
|
+
*
|
|
85
|
+
* @param connectionString - The connection string to dial.
|
|
86
|
+
* @param ssl - TLS options for the client.
|
|
87
|
+
* @returns A connected client.
|
|
88
|
+
*/
|
|
89
|
+
async function defaultConnect(connectionString, ssl) {
|
|
90
|
+
const client = new pg.Client({
|
|
91
|
+
connectionString,
|
|
92
|
+
ssl,
|
|
93
|
+
connectionTimeoutMillis: 10_000,
|
|
94
|
+
});
|
|
95
|
+
await client.connect();
|
|
96
|
+
return client;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Builds a {@link LeaderLockFactory} that opens PostgreSQL session locks.
|
|
100
|
+
*
|
|
101
|
+
* Each call to the factory opens a NEW dedicated connection — a follower
|
|
102
|
+
* retries on its own connection, and a leader reconnects on a fresh one after
|
|
103
|
+
* losing the old.
|
|
104
|
+
*
|
|
105
|
+
* @param options - The lock id, connection settings and optional connect hook.
|
|
106
|
+
* @returns A factory the leadership provider calls to open each session.
|
|
107
|
+
* @throws {Error} When no connection string is configured (at factory-call
|
|
108
|
+
* time, so a boot fails with an actionable message rather than hanging).
|
|
109
|
+
*
|
|
110
|
+
* @example
|
|
111
|
+
* ```typescript
|
|
112
|
+
* import { createProvider } from '@molecule/api-instance-leadership-postgresql'
|
|
113
|
+
*
|
|
114
|
+
* const leadership = createProvider({ createSession: createPostgresLockFactory({ lockId: 8675310 }) })
|
|
115
|
+
* ```
|
|
116
|
+
*/
|
|
117
|
+
export function createPostgresLockFactory(options) {
|
|
118
|
+
const connect = options.connect ?? defaultConnect;
|
|
119
|
+
return async () => {
|
|
120
|
+
const connectionString = options.connectionString ?? process.env.DATABASE_URL;
|
|
121
|
+
if (!connectionString) {
|
|
122
|
+
throw new Error('Instance leadership needs DATABASE_URL (or an explicit connectionString): a PostgreSQL ' +
|
|
123
|
+
'session advisory lock is how one API instance is elected leader across every Machine.');
|
|
124
|
+
}
|
|
125
|
+
const client = await connect(connectionString, options.ssl);
|
|
126
|
+
return new PgLeaderLockSession(client, options.lockId);
|
|
127
|
+
};
|
|
128
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The instance-leadership state machine.
|
|
3
|
+
*
|
|
4
|
+
* One leader across every API instance, elected by a shared lock session, with
|
|
5
|
+
* demotion when the holder loses its connection and background re-acquisition
|
|
6
|
+
* (a follower retries every `retryMs`, default 2 s).
|
|
7
|
+
*
|
|
8
|
+
* The state is per-provider, never module-global, so a host process can create
|
|
9
|
+
* several providers (its server test suite boots multiple apps in one process)
|
|
10
|
+
* without them sharing a leader flag.
|
|
11
|
+
*
|
|
12
|
+
* @module
|
|
13
|
+
*/
|
|
14
|
+
import type { InstanceLeadershipProvider, LeaderLockFactory } from '@molecule/api-instance-leadership';
|
|
15
|
+
/**
|
|
16
|
+
* How to build a leadership provider.
|
|
17
|
+
*/
|
|
18
|
+
export interface PostgresLeadershipProviderOptions {
|
|
19
|
+
/**
|
|
20
|
+
* Opens one dedicated lock session per attempt. Use
|
|
21
|
+
* {@link createPostgresLockFactory} for the production PostgreSQL session,
|
|
22
|
+
* or a fake that shares one "held by" flag in tests.
|
|
23
|
+
*/
|
|
24
|
+
createSession: LeaderLockFactory;
|
|
25
|
+
/**
|
|
26
|
+
* How often a follower retries, in milliseconds. A function keeps the value
|
|
27
|
+
* lazy so a host can read it from configuration after import. Defaults to
|
|
28
|
+
* 2000; values below 50 are clamped so a misconfiguration cannot spin.
|
|
29
|
+
*/
|
|
30
|
+
retryMs?: number | (() => number);
|
|
31
|
+
/**
|
|
32
|
+
* The advisory lock id, used only in log lines (the factory owns the actual
|
|
33
|
+
* lock). Defaults to 0 when omitted.
|
|
34
|
+
*/
|
|
35
|
+
lockId?: number;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Creates an instance-leadership provider.
|
|
39
|
+
*
|
|
40
|
+
* @param options - The lock-session factory and retry interval.
|
|
41
|
+
* @returns A provider implementing the core `InstanceLeadershipProvider` contract.
|
|
42
|
+
*
|
|
43
|
+
* @example
|
|
44
|
+
* ```typescript
|
|
45
|
+
* import { createProvider, createPostgresLockFactory } from '@molecule/api-instance-leadership-postgresql'
|
|
46
|
+
* import { setProvider, acquireLeadership } from '@molecule/api-instance-leadership'
|
|
47
|
+
*
|
|
48
|
+
* const leadership = createProvider({
|
|
49
|
+
* createSession: createPostgresLockFactory({ lockId: 8675310 }),
|
|
50
|
+
* })
|
|
51
|
+
* setProvider(leadership)
|
|
52
|
+
*
|
|
53
|
+
* acquireLeadership({
|
|
54
|
+
* onAcquired: () => startPeriodicSweeps(),
|
|
55
|
+
* onLost: () => stopPeriodicSweeps(),
|
|
56
|
+
* })
|
|
57
|
+
* ```
|
|
58
|
+
*/
|
|
59
|
+
export declare function createProvider(options: PostgresLeadershipProviderOptions): InstanceLeadershipProvider;
|
|
60
|
+
/**
|
|
61
|
+
* A provider that reads its connection settings from `DATABASE_URL`.
|
|
62
|
+
*
|
|
63
|
+
* Its lock session is opened lazily, so importing (and bonding) this provider
|
|
64
|
+
* never connects. The lock id is the same one the API platform API has used
|
|
65
|
+
* for its singleton work; an app that shares a database with another
|
|
66
|
+
* leadership user must pass its OWN `lockId`.
|
|
67
|
+
*/
|
|
68
|
+
export declare const provider: InstanceLeadershipProvider;
|
|
69
|
+
//# sourceMappingURL=provider.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAGH,OAAO,KAAK,EAEV,0BAA0B,EAC1B,iBAAiB,EAGlB,MAAM,mCAAmC,CAAA;AAI1C;;GAEG;AACH,MAAM,WAAW,iCAAiC;IAChD;;;;OAIG;IACH,aAAa,EAAE,iBAAiB,CAAA;IAEhC;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,GAAG,CAAC,MAAM,MAAM,CAAC,CAAA;IAEjC;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB;AAQD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,cAAc,CAC5B,OAAO,EAAE,iCAAiC,GACzC,0BAA0B,CA+G5B;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,QAAQ,EAAE,0BAGrB,CAAA"}
|
package/dist/provider.js
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The instance-leadership state machine.
|
|
3
|
+
*
|
|
4
|
+
* One leader across every API instance, elected by a shared lock session, with
|
|
5
|
+
* demotion when the holder loses its connection and background re-acquisition
|
|
6
|
+
* (a follower retries every `retryMs`, default 2 s).
|
|
7
|
+
*
|
|
8
|
+
* The state is per-provider, never module-global, so a host process can create
|
|
9
|
+
* several providers (its server test suite boots multiple apps in one process)
|
|
10
|
+
* without them sharing a leader flag.
|
|
11
|
+
*
|
|
12
|
+
* @module
|
|
13
|
+
*/
|
|
14
|
+
import { getLogger } from '@molecule/api-bond';
|
|
15
|
+
import { createPostgresLockFactory } from './lock.js';
|
|
16
|
+
/** The clamped, lazily-resolved retry interval. */
|
|
17
|
+
function resolveRetryMs(retryMs) {
|
|
18
|
+
const raw = typeof retryMs === 'function' ? retryMs() : (retryMs ?? 2000);
|
|
19
|
+
return Math.max(50, Number.isFinite(raw) ? raw : 2000);
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Creates an instance-leadership provider.
|
|
23
|
+
*
|
|
24
|
+
* @param options - The lock-session factory and retry interval.
|
|
25
|
+
* @returns A provider implementing the core `InstanceLeadershipProvider` contract.
|
|
26
|
+
*
|
|
27
|
+
* @example
|
|
28
|
+
* ```typescript
|
|
29
|
+
* import { createProvider, createPostgresLockFactory } from '@molecule/api-instance-leadership-postgresql'
|
|
30
|
+
* import { setProvider, acquireLeadership } from '@molecule/api-instance-leadership'
|
|
31
|
+
*
|
|
32
|
+
* const leadership = createProvider({
|
|
33
|
+
* createSession: createPostgresLockFactory({ lockId: 8675310 }),
|
|
34
|
+
* })
|
|
35
|
+
* setProvider(leadership)
|
|
36
|
+
*
|
|
37
|
+
* acquireLeadership({
|
|
38
|
+
* onAcquired: () => startPeriodicSweeps(),
|
|
39
|
+
* onLost: () => stopPeriodicSweeps(),
|
|
40
|
+
* })
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
export function createProvider(options) {
|
|
44
|
+
const logger = getLogger();
|
|
45
|
+
let leader = false;
|
|
46
|
+
let session = null;
|
|
47
|
+
let retryTimer = null;
|
|
48
|
+
let released = false;
|
|
49
|
+
let attemptInFlight = false;
|
|
50
|
+
let acquireOptions = null;
|
|
51
|
+
/** Schedule the next acquisition attempt, never keeping the process alive for it. */
|
|
52
|
+
const scheduleRetry = () => {
|
|
53
|
+
if (released || retryTimer)
|
|
54
|
+
return;
|
|
55
|
+
retryTimer = setTimeout(() => {
|
|
56
|
+
retryTimer = null;
|
|
57
|
+
void tryAcquire();
|
|
58
|
+
}, resolveRetryMs(options.retryMs));
|
|
59
|
+
retryTimer.unref?.();
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* One acquisition attempt: open a session (if needed) and ask for the lock.
|
|
63
|
+
*
|
|
64
|
+
* Serialized by `attemptInFlight` — a retry tick landing while a slow connect
|
|
65
|
+
* is in flight must not open a second connection.
|
|
66
|
+
*/
|
|
67
|
+
const tryAcquire = async () => {
|
|
68
|
+
if (released || leader || attemptInFlight || !acquireOptions)
|
|
69
|
+
return;
|
|
70
|
+
attemptInFlight = true;
|
|
71
|
+
try {
|
|
72
|
+
if (!session) {
|
|
73
|
+
session = await options.createSession();
|
|
74
|
+
session.onLost(() => {
|
|
75
|
+
// The connection is gone, so the store has released the lock.
|
|
76
|
+
// Demote FIRST, then let the operator-facing stop run; a new leader
|
|
77
|
+
// may already be starting its own copy of every singleton.
|
|
78
|
+
const wasLeader = leader;
|
|
79
|
+
leader = false;
|
|
80
|
+
session = null;
|
|
81
|
+
if (wasLeader) {
|
|
82
|
+
logger.warn('Lost platform leadership — stopping singleton subsystems', {
|
|
83
|
+
retryMs: resolveRetryMs(options.retryMs),
|
|
84
|
+
});
|
|
85
|
+
Promise.resolve()
|
|
86
|
+
.then(() => acquireOptions?.onLost?.())
|
|
87
|
+
.catch((error) => logger.error('Leader-lost shutdown failed', { error }));
|
|
88
|
+
}
|
|
89
|
+
scheduleRetry();
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
const acquired = await session.tryLock();
|
|
93
|
+
if (!acquired) {
|
|
94
|
+
scheduleRetry();
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
leader = true;
|
|
98
|
+
if (retryTimer) {
|
|
99
|
+
clearTimeout(retryTimer);
|
|
100
|
+
retryTimer = null;
|
|
101
|
+
}
|
|
102
|
+
logger.info('Acquired platform leadership — starting singleton subsystems', {
|
|
103
|
+
lockId: options.lockId ?? 0,
|
|
104
|
+
});
|
|
105
|
+
Promise.resolve()
|
|
106
|
+
.then(() => acquireOptions?.onAcquired())
|
|
107
|
+
.catch((error) => {
|
|
108
|
+
logger.error('Leader-only startup failed', { error });
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
catch (error) {
|
|
112
|
+
// Store unreachable or the connect timed out. Drop the session (a
|
|
113
|
+
// half-open one would keep retrying against a dead socket) and try again.
|
|
114
|
+
logger.warn('Leadership lock attempt failed (will retry)', {
|
|
115
|
+
error,
|
|
116
|
+
retryMs: resolveRetryMs(options.retryMs),
|
|
117
|
+
});
|
|
118
|
+
const stale = session;
|
|
119
|
+
session = null;
|
|
120
|
+
void stale?.release().catch(() => undefined);
|
|
121
|
+
scheduleRetry();
|
|
122
|
+
}
|
|
123
|
+
finally {
|
|
124
|
+
attemptInFlight = false;
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
return {
|
|
128
|
+
isLeader() {
|
|
129
|
+
return leader;
|
|
130
|
+
},
|
|
131
|
+
state() {
|
|
132
|
+
if (released)
|
|
133
|
+
return 'stopped';
|
|
134
|
+
return leader ? 'leader' : 'follower';
|
|
135
|
+
},
|
|
136
|
+
acquire(nextOptions) {
|
|
137
|
+
if (leader || session || released)
|
|
138
|
+
return;
|
|
139
|
+
acquireOptions = nextOptions;
|
|
140
|
+
void tryAcquire();
|
|
141
|
+
},
|
|
142
|
+
async release() {
|
|
143
|
+
released = true;
|
|
144
|
+
if (retryTimer) {
|
|
145
|
+
clearTimeout(retryTimer);
|
|
146
|
+
retryTimer = null;
|
|
147
|
+
}
|
|
148
|
+
leader = false;
|
|
149
|
+
const current = session;
|
|
150
|
+
session = null;
|
|
151
|
+
if (current)
|
|
152
|
+
await current.release();
|
|
153
|
+
},
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* A provider that reads its connection settings from `DATABASE_URL`.
|
|
158
|
+
*
|
|
159
|
+
* Its lock session is opened lazily, so importing (and bonding) this provider
|
|
160
|
+
* never connects. The lock id is the same one the API platform API has used
|
|
161
|
+
* for its singleton work; an app that shares a database with another
|
|
162
|
+
* leadership user must pass its OWN `lockId`.
|
|
163
|
+
*/
|
|
164
|
+
export const provider = createProvider({
|
|
165
|
+
createSession: createPostgresLockFactory({ lockId: 8675310 }),
|
|
166
|
+
lockId: 8675310,
|
|
167
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,63 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@molecule/api-instance-leadership-postgresql",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"description": "PostgreSQL provider for @molecule/api-instance-leadership: one leader across every API instance via a session advisory lock on a dedicated connection, with demotion when the connection is lost.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist",
|
|
16
|
+
"README.md"
|
|
17
|
+
],
|
|
18
|
+
"scripts": {
|
|
19
|
+
"build": "tsc",
|
|
20
|
+
"dev": "tsc --watch",
|
|
21
|
+
"test": "vitest run",
|
|
22
|
+
"test:watch": "vitest",
|
|
23
|
+
"test:coverage": "vitest run --coverage"
|
|
24
|
+
},
|
|
25
|
+
"keywords": [
|
|
26
|
+
"molecule",
|
|
27
|
+
"leadership",
|
|
28
|
+
"leader election",
|
|
29
|
+
"advisory lock",
|
|
30
|
+
"postgresql",
|
|
31
|
+
"multi-instance"
|
|
32
|
+
],
|
|
33
|
+
"author": "Molecule Dev, Inc. (https://molecule.dev)",
|
|
34
|
+
"license": "Apache-2.0",
|
|
35
|
+
"engines": {
|
|
36
|
+
"node": ">=20"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"pg": "8.22.0"
|
|
40
|
+
},
|
|
41
|
+
"peerDependencies": {
|
|
42
|
+
"@molecule/api-bond": "^1.0.1",
|
|
43
|
+
"@molecule/api-instance-leadership": "^1.0.0"
|
|
44
|
+
},
|
|
45
|
+
"devDependencies": {
|
|
46
|
+
"@molecule/api-bond": "1.0.2",
|
|
47
|
+
"@molecule/api-instance-leadership": "1.1.0",
|
|
48
|
+
"@types/node": "26.1.2",
|
|
49
|
+
"@types/pg": "8.20.0",
|
|
50
|
+
"typescript": "6.0.3",
|
|
51
|
+
"vitest": "4.1.11"
|
|
52
|
+
},
|
|
53
|
+
"repository": {
|
|
54
|
+
"type": "git",
|
|
55
|
+
"url": "https://github.com/molecule-dev/molecule.git",
|
|
56
|
+
"directory": "packages/api/bonds/instance-leadership/postgresql"
|
|
57
|
+
},
|
|
58
|
+
"homepage": "https://www.molecule.dev/packages/api-instance-leadership-postgresql",
|
|
59
|
+
"bugs": "https://github.com/molecule-dev/molecule/issues",
|
|
60
|
+
"publishConfig": {
|
|
61
|
+
"access": "public"
|
|
62
|
+
}
|
|
63
|
+
}
|