@rindle/router 0.1.0-rc.5
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 +201 -0
- package/README.md +44 -0
- package/dist/hrw.d.ts +15 -0
- package/dist/hrw.d.ts.map +1 -0
- package/dist/hrw.js +48 -0
- package/dist/hrw.js.map +1 -0
- package/dist/http.d.ts +37 -0
- package/dist/http.d.ts.map +1 -0
- package/dist/http.js +86 -0
- package/dist/http.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -0
- package/dist/registry.d.ts +38 -0
- package/dist/registry.d.ts.map +1 -0
- package/dist/registry.js +36 -0
- package/dist/registry.js.map +1 -0
- package/dist/router.d.ts +45 -0
- package/dist/router.d.ts.map +1 -0
- package/dist/router.js +118 -0
- package/dist/router.js.map +1 -0
- package/package.json +39 -0
- package/src/hrw.ts +56 -0
- package/src/http.ts +118 -0
- package/src/index.ts +16 -0
- package/src/registry.ts +65 -0
- package/src/router.ts +169 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# @rindle/router
|
|
2
|
+
|
|
3
|
+
The **stateless read-routing control-plane proxy** (`designs/READ-ROUTER-DESIGN.md`). In a
|
|
4
|
+
multi-follower replicator topology, a read lease is **follower-local** — the `leaseToken` minted by
|
|
5
|
+
`materialize` is valid only on the follower that minted it, and the browser must open its
|
|
6
|
+
subscription ws to that same follower. The router is the **placement authority** that puts both legs
|
|
7
|
+
on one node.
|
|
8
|
+
|
|
9
|
+
It is:
|
|
10
|
+
|
|
11
|
+
- **Stateless.** Placement is one pure function — `route(key) = HRW(key, live())` (weighted
|
|
12
|
+
rendezvous hashing, tie-broken on follower id so replicas agree). No binding cache, no per-session
|
|
13
|
+
state, no pin state. Restart is free; run it active/active.
|
|
14
|
+
- **Off the data plane.** It interposes on the control plane only — `materialize` / `query` route to
|
|
15
|
+
one follower and the output is stamped with that follower's public `wsEndpoint`. The browser opens
|
|
16
|
+
its ws **directly** to the follower.
|
|
17
|
+
- **Reads only.** Writes never route through the router (`executeSqlTxn` / `migrate` / … reject as a
|
|
18
|
+
misconfiguration backstop). The api-server's `SplitDaemonClient` sends writes to the master.
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import { RoutingReadClient, StaticFollowerRegistry, createRouterServer, createRouterPinClient } from "@rindle/router";
|
|
22
|
+
|
|
23
|
+
const registry = new StaticFollowerRegistry([
|
|
24
|
+
{ id: "f1", controlPlaneUrl: "http://f1.internal:7600", wsEndpoint: "wss://f1.example.com/ws" },
|
|
25
|
+
{ id: "f2", controlPlaneUrl: "http://f2.internal:7600", wsEndpoint: "wss://f2.example.com/ws" },
|
|
26
|
+
]);
|
|
27
|
+
const router = new RoutingReadClient({ registry, daemonToken: process.env.DAEMON_TOKEN });
|
|
28
|
+
await createRouterServer({ router, token: process.env.ROUTER_TOKEN, port: 7650 });
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
The api-server points its reads leg at the router (an ordinary `HttpRindleDaemonClient` to the
|
|
32
|
+
router's URL) and its writes leg at the master, composed via `SplitDaemonClient`. The fleet pin
|
|
33
|
+
fan-out (`assertPins`) is reached over the same hop via `createRouterPinClient`.
|
|
34
|
+
|
|
35
|
+
## Exports
|
|
36
|
+
|
|
37
|
+
- `route` / `hashUnit` — the pure HRW placement function.
|
|
38
|
+
- `StaticFollowerRegistry` / `FollowerRegistry` / `Follower` — the membership view.
|
|
39
|
+
- `RoutingReadClient` — the routing read-proxy (implements `RindleDaemonClient` for the read legs,
|
|
40
|
+
plus the explicit `assertPins` fleet fan-out).
|
|
41
|
+
- `NoLiveFollowersError` — thrown when placement finds no live follower for a key (no node to
|
|
42
|
+
route the read leg to).
|
|
43
|
+
- `createRouterServer` / `dispatchRouter` / `ROUTER_PATHS` — the HTTP front.
|
|
44
|
+
- `createRouterPinClient` — the api-server's `pinFanout` over HTTP.
|
package/dist/hrw.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** Map a string to a stable unit float in the OPEN interval (0,1) — deterministic across runtimes
|
|
2
|
+
* (FNV-1a 64-bit over UTF-8 bytes in exact BigInt, then folded to a 53-bit double mantissa). The
|
|
3
|
+
* open interval matters: HRW needs `hashUnit ∈ (0,1)` so `-ln(hashUnit) > 0` (never 0 or ∞). */
|
|
4
|
+
export declare function hashUnit(s: string): number;
|
|
5
|
+
/** The minimum a follower must expose to be placed: a stable `id` and an optional `weight`
|
|
6
|
+
* (load share ∝ weight; default 1; a weight ≤ 0 opts the follower out of placement). */
|
|
7
|
+
export interface RoutableFollower {
|
|
8
|
+
id: string;
|
|
9
|
+
weight?: number;
|
|
10
|
+
}
|
|
11
|
+
/** Place `key` on exactly one of `followers` by weighted HRW. Returns `undefined` only when the set
|
|
12
|
+
* is empty (or every follower has weight ≤ 0) — the caller turns that into a 503. Order-independent:
|
|
13
|
+
* shuffling `followers` never changes the result (max score, then lexicographically-smallest `id`). */
|
|
14
|
+
export declare function route<F extends RoutableFollower>(key: string, followers: readonly F[]): F | undefined;
|
|
15
|
+
//# sourceMappingURL=hrw.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hrw.d.ts","sourceRoot":"","sources":["../src/hrw.ts"],"names":[],"mappings":"AASA;;iGAEiG;AACjG,wBAAgB,QAAQ,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,CAkB1C;AAED;yFACyF;AACzF,MAAM,WAAW,gBAAgB;IAC/B,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;wGAEwG;AACxG,wBAAgB,KAAK,CAAC,CAAC,SAAS,gBAAgB,EAAE,GAAG,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,CAAC,EAAE,GAAG,CAAC,GAAG,SAAS,CAarG"}
|
package/dist/hrw.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// Weighted rendezvous hashing (HRW) — the router's one pure placement function
|
|
2
|
+
// (READ-ROUTER-DESIGN.md §1.4, §2.2). `route(key, followers)` is a deterministic function of the
|
|
3
|
+
// membership SET + key: HRW's logarithmic method gives each follower a score
|
|
4
|
+
// `weight / -ln(hashUnit(key‖id))` and the max wins, tie-broken on `id` so the result is
|
|
5
|
+
// INDEPENDENT of the followers' order (two router replicas over the same set agree). HRW's
|
|
6
|
+
// minimal-disruption property is what bounds churn to ~1/N keys on a membership change.
|
|
7
|
+
const encoder = new TextEncoder();
|
|
8
|
+
/** Map a string to a stable unit float in the OPEN interval (0,1) — deterministic across runtimes
|
|
9
|
+
* (FNV-1a 64-bit over UTF-8 bytes in exact BigInt, then folded to a 53-bit double mantissa). The
|
|
10
|
+
* open interval matters: HRW needs `hashUnit ∈ (0,1)` so `-ln(hashUnit) > 0` (never 0 or ∞). */
|
|
11
|
+
export function hashUnit(s) {
|
|
12
|
+
const bytes = encoder.encode(s);
|
|
13
|
+
const mask = 0xffffffffffffffffn;
|
|
14
|
+
let h = 0xcbf29ce484222325n; // FNV offset basis (64-bit)
|
|
15
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
16
|
+
h ^= BigInt(bytes[i]);
|
|
17
|
+
h = (h * 0x100000001b3n) & mask; // FNV prime
|
|
18
|
+
}
|
|
19
|
+
// FNV's LOW bits are weakly mixed (a multiplicative hash barely diffuses high bits downward), so
|
|
20
|
+
// folding them straight to a mantissa biases placement. Run Murmur3's fmix64 avalanche first —
|
|
21
|
+
// afterward every bit depends on every input bit, so the low 53 are uniform.
|
|
22
|
+
h ^= h >> 33n;
|
|
23
|
+
h = (h * 0xff51afd7ed558ccdn) & mask;
|
|
24
|
+
h ^= h >> 33n;
|
|
25
|
+
h = (h * 0xc4ceb9fe1a85ec53n) & mask;
|
|
26
|
+
h ^= h >> 33n;
|
|
27
|
+
const bits = Number(h & ((1n << 53n) - 1n)); // 0 .. 2^53 - 1
|
|
28
|
+
return (bits + 0.5) / 2 ** 53; // strictly inside (0, 1)
|
|
29
|
+
}
|
|
30
|
+
/** Place `key` on exactly one of `followers` by weighted HRW. Returns `undefined` only when the set
|
|
31
|
+
* is empty (or every follower has weight ≤ 0) — the caller turns that into a 503. Order-independent:
|
|
32
|
+
* shuffling `followers` never changes the result (max score, then lexicographically-smallest `id`). */
|
|
33
|
+
export function route(key, followers) {
|
|
34
|
+
let best;
|
|
35
|
+
let bestScore = -Infinity;
|
|
36
|
+
for (const f of followers) {
|
|
37
|
+
const weight = f.weight ?? 1;
|
|
38
|
+
if (weight <= 0)
|
|
39
|
+
continue;
|
|
40
|
+
const score = weight / -Math.log(hashUnit(`${key}\u0000${f.id}`));
|
|
41
|
+
if (score > bestScore || (score === bestScore && best !== undefined && f.id < best.id)) {
|
|
42
|
+
best = f;
|
|
43
|
+
bestScore = score;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return best;
|
|
47
|
+
}
|
|
48
|
+
//# sourceMappingURL=hrw.js.map
|
package/dist/hrw.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hrw.js","sourceRoot":"","sources":["../src/hrw.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,iGAAiG;AACjG,6EAA6E;AAC7E,yFAAyF;AACzF,2FAA2F;AAC3F,wFAAwF;AAExF,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAElC;;iGAEiG;AACjG,MAAM,UAAU,QAAQ,CAAC,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;YAAE,SAAS;QAC1B,MAAM,KAAK,GAAG,MAAM,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,GAAG,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;QAClE,IAAI,KAAK,GAAG,SAAS,IAAI,CAAC,KAAK,KAAK,SAAS,IAAI,IAAI,KAAK,SAAS,IAAI,CAAC,CAAC,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC,EAAE,CAAC;YACvF,IAAI,GAAG,CAAC,CAAC;YACT,SAAS,GAAG,KAAK,CAAC;QACpB,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC"}
|
package/dist/http.d.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { MaterializeInput } from "@rindle/daemon-client";
|
|
2
|
+
import type { RoutingReadClient } from "./router.ts";
|
|
3
|
+
export declare const ROUTER_PATHS: {
|
|
4
|
+
readonly materialize: "/materialize";
|
|
5
|
+
readonly query: "/query";
|
|
6
|
+
readonly dematerialize: "/dematerialize";
|
|
7
|
+
readonly assertPins: "/assert-pins";
|
|
8
|
+
};
|
|
9
|
+
/** Dispatch one parsed request to the router (the runtime-agnostic core — drive it from any HTTP
|
|
10
|
+
* shell). Throws `{ status: 404 }` for an unknown path; routing errors carry their own `status`
|
|
11
|
+
* (e.g. {@link NoLiveFollowersError} → 503). */
|
|
12
|
+
export declare function dispatchRouter(router: RoutingReadClient, path: string, body: unknown): Promise<unknown>;
|
|
13
|
+
export interface RouterServerOptions {
|
|
14
|
+
router: RoutingReadClient;
|
|
15
|
+
/** Inbound bearer token the api-server must present. Omit to disable auth (dev/tests only). */
|
|
16
|
+
token?: string;
|
|
17
|
+
port?: number;
|
|
18
|
+
}
|
|
19
|
+
export interface RouterServer {
|
|
20
|
+
readonly port: number;
|
|
21
|
+
close(): Promise<void>;
|
|
22
|
+
}
|
|
23
|
+
/** Start the router's Node HTTP server. Resolves once listening (port resolved when `port: 0`). */
|
|
24
|
+
export declare function createRouterServer(opts: RouterServerOptions): Promise<RouterServer>;
|
|
25
|
+
/** The api-server's `pinFanout`: invokes the router's explicit fleet pin-assert over HTTP
|
|
26
|
+
* (`POST /assert-pins`). Mirrors how the api-server reaches the router for reads, so a routed
|
|
27
|
+
* deploy uses one `RINDLE_ROUTER_URL` (+ token) for both legs. */
|
|
28
|
+
export interface RouterPinClient {
|
|
29
|
+
assertPins(pins: readonly MaterializeInput[]): Promise<void>;
|
|
30
|
+
}
|
|
31
|
+
export interface RouterPinClientOptions {
|
|
32
|
+
baseUrl: string;
|
|
33
|
+
token?: string;
|
|
34
|
+
fetch?: typeof fetch;
|
|
35
|
+
}
|
|
36
|
+
export declare function createRouterPinClient(opts: RouterPinClientOptions): RouterPinClient;
|
|
37
|
+
//# sourceMappingURL=http.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../src/http.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAE9D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAErD,eAAO,MAAM,YAAY;;;;;CAKf,CAAC;AAEX;;iDAEiD;AACjD,wBAAgB,cAAc,CAAC,MAAM,EAAE,iBAAiB,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAgBvG;AAED,MAAM,WAAW,mBAAmB;IAClC,MAAM,EAAE,iBAAiB,CAAC;IAC1B,+FAA+F;IAC/F,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB;AAED,mGAAmG;AACnG,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,mBAAmB,GAAG,OAAO,CAAC,YAAY,CAAC,CAyBnF;AAOD;;mEAEmE;AACnE,MAAM,WAAW,eAAe;IAC9B,UAAU,CAAC,IAAI,EAAE,SAAS,gBAAgB,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC9D;AAED,MAAM,WAAW,sBAAsB;IACrC,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;CACtB;AAED,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,sBAAsB,GAAG,eAAe,CAgBnF"}
|
package/dist/http.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// The router's HTTP front (READ-ROUTER-DESIGN.md §9) — it speaks the daemon control-plane read
|
|
2
|
+
// surface so the api-server reaches it through an ordinary `HttpRindleDaemonClient`, plus the one
|
|
3
|
+
// extra fleet route `/assert-pins`. The api-server's `RINDLE_ROUTER_URL` points here for the reads
|
|
4
|
+
// leg; `RINDLE_MASTER_URL` points at the master for writes (the `SplitDaemonClient`, §2.1).
|
|
5
|
+
//
|
|
6
|
+
// `createRouterPinClient` is the counterpart the api-server's `pinFanout` uses to invoke the fleet
|
|
7
|
+
// pin-assert over that same HTTP hop.
|
|
8
|
+
import { createServer } from "node:http";
|
|
9
|
+
export const ROUTER_PATHS = {
|
|
10
|
+
materialize: "/materialize",
|
|
11
|
+
query: "/query",
|
|
12
|
+
dematerialize: "/dematerialize",
|
|
13
|
+
assertPins: "/assert-pins",
|
|
14
|
+
};
|
|
15
|
+
/** Dispatch one parsed request to the router (the runtime-agnostic core — drive it from any HTTP
|
|
16
|
+
* shell). Throws `{ status: 404 }` for an unknown path; routing errors carry their own `status`
|
|
17
|
+
* (e.g. {@link NoLiveFollowersError} → 503). */
|
|
18
|
+
export function dispatchRouter(router, path, body) {
|
|
19
|
+
// The body is untrusted JSON off the wire — cast through `unknown` to the control-plane input
|
|
20
|
+
// shapes (the followers' control plane validates the contents).
|
|
21
|
+
const msg = (body ?? {});
|
|
22
|
+
switch (path) {
|
|
23
|
+
case ROUTER_PATHS.materialize:
|
|
24
|
+
return router.materialize(msg);
|
|
25
|
+
case ROUTER_PATHS.query:
|
|
26
|
+
return router.query(msg);
|
|
27
|
+
case ROUTER_PATHS.dematerialize:
|
|
28
|
+
return router.dematerialize(msg);
|
|
29
|
+
case ROUTER_PATHS.assertPins:
|
|
30
|
+
return router.assertPins(msg.pins ?? []).then(() => ({ ok: true }));
|
|
31
|
+
default:
|
|
32
|
+
throw Object.assign(new Error(`read router: not found: ${path}`), { status: 404 });
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
/** Start the router's Node HTTP server. Resolves once listening (port resolved when `port: 0`). */
|
|
36
|
+
export function createRouterServer(opts) {
|
|
37
|
+
const handle = async (req, res) => {
|
|
38
|
+
try {
|
|
39
|
+
if (req.method !== "POST")
|
|
40
|
+
return send(res, 405, { error: "method not allowed" });
|
|
41
|
+
if (opts.token && req.headers.authorization !== `Bearer ${opts.token}`) {
|
|
42
|
+
return send(res, 401, { error: "unauthorized" });
|
|
43
|
+
}
|
|
44
|
+
const chunks = [];
|
|
45
|
+
for await (const chunk of req)
|
|
46
|
+
chunks.push(chunk);
|
|
47
|
+
const body = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
|
|
48
|
+
const out = await dispatchRouter(opts.router, req.url ?? "", body);
|
|
49
|
+
send(res, 200, out ?? {});
|
|
50
|
+
}
|
|
51
|
+
catch (err) {
|
|
52
|
+
const status = err?.status ?? 500;
|
|
53
|
+
send(res, status, { error: String(err?.message ?? err) });
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
const server = createServer((req, res) => void handle(req, res));
|
|
57
|
+
return new Promise((resolve) => {
|
|
58
|
+
server.listen(opts.port ?? 0, () => {
|
|
59
|
+
const port = server.address().port;
|
|
60
|
+
resolve({ port, close: () => new Promise((r) => server.close(() => r())) });
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
function send(res, status, body) {
|
|
65
|
+
res.writeHead(status, { "content-type": "application/json" });
|
|
66
|
+
res.end(JSON.stringify(body));
|
|
67
|
+
}
|
|
68
|
+
export function createRouterPinClient(opts) {
|
|
69
|
+
const base = opts.baseUrl.endsWith("/") ? opts.baseUrl.slice(0, -1) : opts.baseUrl;
|
|
70
|
+
const fetchImpl = opts.fetch ?? ((...args) => fetch(...args));
|
|
71
|
+
return {
|
|
72
|
+
async assertPins(pins) {
|
|
73
|
+
const res = await fetchImpl(`${base}${ROUTER_PATHS.assertPins}`, {
|
|
74
|
+
method: "POST",
|
|
75
|
+
headers: {
|
|
76
|
+
"content-type": "application/json",
|
|
77
|
+
...(opts.token ? { authorization: `Bearer ${opts.token}` } : {}),
|
|
78
|
+
},
|
|
79
|
+
body: JSON.stringify({ pins }),
|
|
80
|
+
});
|
|
81
|
+
if (!res.ok)
|
|
82
|
+
throw new Error(`read router assert-pins failed: ${res.status} ${await res.text()}`);
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
//# sourceMappingURL=http.js.map
|
package/dist/http.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"http.js","sourceRoot":"","sources":["../src/http.ts"],"names":[],"mappings":"AAAA,+FAA+F;AAC/F,kGAAkG;AAClG,mGAAmG;AACnG,4FAA4F;AAC5F,EAAE;AACF,mGAAmG;AACnG,sCAAsC;AAEtC,OAAO,EAAE,YAAY,EAA6C,MAAM,WAAW,CAAC;AAOpF,MAAM,CAAC,MAAM,YAAY,GAAG;IAC1B,WAAW,EAAE,cAAc;IAC3B,KAAK,EAAE,QAAQ;IACf,aAAa,EAAE,gBAAgB;IAC/B,UAAU,EAAE,cAAc;CAClB,CAAC;AAEX;;iDAEiD;AACjD,MAAM,UAAU,cAAc,CAAC,MAAyB,EAAE,IAAY,EAAE,IAAa;IACnF,8FAA8F;I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I,EAAE,EAAE,CAAC,CAAC;QACpG,CAAC;KACF,CAAC;AACJ,CAAC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { hashUnit, route } from "./hrw.ts";
|
|
2
|
+
export type { RoutableFollower } from "./hrw.ts";
|
|
3
|
+
export { StaticFollowerRegistry } from "./registry.ts";
|
|
4
|
+
export type { Follower, FollowerRegistry } from "./registry.ts";
|
|
5
|
+
export { NoLiveFollowersError, RoutingReadClient } from "./router.ts";
|
|
6
|
+
export type { FollowerClientFactory, RoutingReadClientOptions } from "./router.ts";
|
|
7
|
+
export { ROUTER_PATHS, createRouterPinClient, createRouterServer, dispatchRouter } from "./http.ts";
|
|
8
|
+
export type { RouterPinClient, RouterPinClientOptions, RouterServer, RouterServerOptions } from "./http.ts";
|
|
9
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,UAAU,CAAC;AAC3C,YAAY,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAEjD,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AACvD,YAAY,EAAE,QAAQ,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAEhE,OAAO,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AACtE,YAAY,EAAE,qBAAqB,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAEnF,OAAO,EAAE,YAAY,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AACpG,YAAY,EAAE,eAAe,EAAE,sBAAsB,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// @rindle/router — the stateless read-routing control-plane proxy (READ-ROUTER-DESIGN.md).
|
|
2
|
+
// Placement is one pure function (`route = HRW(key, live())`); the router holds the follower
|
|
3
|
+
// membership view and NO per-session / NO pin state. The api-server's `SplitDaemonClient` points
|
|
4
|
+
// its reads leg here (writes go to the master); the browser↔follower ws data path stays direct.
|
|
5
|
+
export { hashUnit, route } from "./hrw.js";
|
|
6
|
+
export { StaticFollowerRegistry } from "./registry.js";
|
|
7
|
+
export { NoLiveFollowersError, RoutingReadClient } from "./router.js";
|
|
8
|
+
export { ROUTER_PATHS, createRouterPinClient, createRouterServer, dispatchRouter } from "./http.js";
|
|
9
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,2FAA2F;AAC3F,6FAA6F;AAC7F,iGAAiG;AACjG,gGAAgG;AAEhG,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,UAAU,CAAC;AAG3C,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAGvD,OAAO,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAGtE,OAAO,EAAE,YAAY,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { RoutableFollower } from "./hrw.ts";
|
|
2
|
+
export interface Follower extends RoutableFollower {
|
|
3
|
+
/** Stable identity — the HRW input and the client-cache key. Survives restarts (same id ⇒ a key
|
|
4
|
+
* still HRWs to it, so a reboot needs no re-placement, §3). */
|
|
5
|
+
id: string;
|
|
6
|
+
/** PRIVATE control-plane URL (router → follower `/materialize`, `/query`, `/dematerialize`).
|
|
7
|
+
* Never exposed to the browser. */
|
|
8
|
+
controlPlaneUrl: string;
|
|
9
|
+
/** PUBLIC ws endpoint (`wss:443`) the browser opens its subscription to — the lease's
|
|
10
|
+
* `wsEndpoint`. Browser-reachable; the only follower address that crosses a provider boundary. */
|
|
11
|
+
wsEndpoint: string;
|
|
12
|
+
/** Load share ∝ weight (default 1). A weight ≤ 0 opts the follower out of placement. */
|
|
13
|
+
weight?: number;
|
|
14
|
+
/** Routable when not explicitly false (the default). Set false to drain/quarantine — it drops
|
|
15
|
+
* out of `live()` and its keys re-HRW elsewhere on their next lease. */
|
|
16
|
+
healthy?: boolean;
|
|
17
|
+
}
|
|
18
|
+
export interface FollowerRegistry {
|
|
19
|
+
/** The currently routable (healthy) followers. HRW runs over exactly this set, so the result is
|
|
20
|
+
* a pure function of what `live()` returns at call time. */
|
|
21
|
+
live(): readonly Follower[];
|
|
22
|
+
}
|
|
23
|
+
/** A registry backed by an in-memory list — the dev/test source, and the substrate a health probe
|
|
24
|
+
* or discovery loop drives via {@link set}/{@link setHealthy}. Copies entries on the way in so the
|
|
25
|
+
* caller can't mutate the routed set behind the router's back. */
|
|
26
|
+
export declare class StaticFollowerRegistry implements FollowerRegistry {
|
|
27
|
+
private followers;
|
|
28
|
+
constructor(followers?: readonly Follower[]);
|
|
29
|
+
live(): readonly Follower[];
|
|
30
|
+
/** The full routable set, healthy or not (for diagnostics / a health probe). */
|
|
31
|
+
all(): readonly Follower[];
|
|
32
|
+
/** Replace the whole membership set (a discovery refresh). */
|
|
33
|
+
set(followers: readonly Follower[]): void;
|
|
34
|
+
/** Mark one follower healthy/unhealthy — drops it from / restores it to `live()`. No-op for an
|
|
35
|
+
* unknown id. */
|
|
36
|
+
setHealthy(id: string, healthy: boolean): void;
|
|
37
|
+
}
|
|
38
|
+
//# sourceMappingURL=registry.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../src/registry.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAEjD,MAAM,WAAW,QAAS,SAAQ,gBAAgB;IAChD;oEACgE;IAChE,EAAE,EAAE,MAAM,CAAC;IACX;wCACoC;IACpC,eAAe,EAAE,MAAM,CAAC;IACxB;uGACmG;IACnG,UAAU,EAAE,MAAM,CAAC;IACnB,wFAAwF;IACxF,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;6EACyE;IACzE,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED,MAAM,WAAW,gBAAgB;IAC/B;iEAC6D;IAC7D,IAAI,IAAI,SAAS,QAAQ,EAAE,CAAC;CAC7B;AAED;;mEAEmE;AACnE,qBAAa,sBAAuB,YAAW,gBAAgB;IAC7D,OAAO,CAAC,SAAS,CAAa;gBAElB,SAAS,GAAE,SAAS,QAAQ,EAAO;IAI/C,IAAI,IAAI,SAAS,QAAQ,EAAE;IAI3B,gFAAgF;IAChF,GAAG,IAAI,SAAS,QAAQ,EAAE;IAI1B,8DAA8D;IAC9D,GAAG,CAAC,SAAS,EAAE,SAAS,QAAQ,EAAE,GAAG,IAAI;IAIzC;sBACkB;IAClB,UAAU,CAAC,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,IAAI;CAI/C"}
|
package/dist/registry.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// The follower membership view (READ-ROUTER-DESIGN.md §2.2, §9). The router holds NO per-session
|
|
2
|
+
// or pin state — the registry's `live()` set is the only input HRW routes over. "Unhealthy"
|
|
3
|
+
// (unreachable / draining) ⇒ dropped from `live()`, which is what re-HRWs its sessions on their
|
|
4
|
+
// next lease. A merely *lagging* follower stays in `live()` (it still serves reads).
|
|
5
|
+
//
|
|
6
|
+
// Source of the set: a static list (dev) → Fly 6PN `.internal` / orchestrator API (prod) → gossip
|
|
7
|
+
// later — all behind this interface. Each entry carries TWO addresses: the PRIVATE control-plane
|
|
8
|
+
// URL the router POSTs to, and the PUBLIC ws endpoint handed to the browser as `wsEndpoint`.
|
|
9
|
+
/** A registry backed by an in-memory list — the dev/test source, and the substrate a health probe
|
|
10
|
+
* or discovery loop drives via {@link set}/{@link setHealthy}. Copies entries on the way in so the
|
|
11
|
+
* caller can't mutate the routed set behind the router's back. */
|
|
12
|
+
export class StaticFollowerRegistry {
|
|
13
|
+
followers;
|
|
14
|
+
constructor(followers = []) {
|
|
15
|
+
this.followers = followers.map((f) => ({ ...f }));
|
|
16
|
+
}
|
|
17
|
+
live() {
|
|
18
|
+
return this.followers.filter((f) => f.healthy !== false);
|
|
19
|
+
}
|
|
20
|
+
/** The full routable set, healthy or not (for diagnostics / a health probe). */
|
|
21
|
+
all() {
|
|
22
|
+
return this.followers;
|
|
23
|
+
}
|
|
24
|
+
/** Replace the whole membership set (a discovery refresh). */
|
|
25
|
+
set(followers) {
|
|
26
|
+
this.followers = followers.map((f) => ({ ...f }));
|
|
27
|
+
}
|
|
28
|
+
/** Mark one follower healthy/unhealthy — drops it from / restores it to `live()`. No-op for an
|
|
29
|
+
* unknown id. */
|
|
30
|
+
setHealthy(id, healthy) {
|
|
31
|
+
const f = this.followers.find((x) => x.id === id);
|
|
32
|
+
if (f)
|
|
33
|
+
f.healthy = healthy;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
//# sourceMappingURL=registry.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"registry.js","sourceRoot":"","sources":["../src/registry.ts"],"names":[],"mappings":"AAAA,iGAAiG;AACjG,4FAA4F;AAC5F,gGAAgG;AAChG,qFAAqF;AACrF,EAAE;AACF,kGAAkG;AAClG,iGAAiG;AACjG,6FAA6F;AA2B7F;;mEAEmE;AACnE,MAAM,OAAO,sBAAsB;IACzB,SAAS,CAAa;IAE9B,YAAY,YAAiC,EAAE;QAC7C,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;IACpD,CAAC;IAED,IAAI;QACF,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,KAAK,KAAK,CAAC,CAAC;IAC3D,CAAC;IAED,gFAAgF;IAChF,GAAG;QACD,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IAED,8DAA8D;IAC9D,GAAG,CAAC,SAA8B;QAChC,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;IACpD,CAAC;IAED;sBACkB;IAClB,UAAU,CAAC,EAAU,EAAE,OAAgB;QACrC,MAAM,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;QAClD,IAAI,CAAC;YAAE,CAAC,CAAC,OAAO,GAAG,OAAO,CAAC;IAC7B,CAAC;CACF"}
|
package/dist/router.d.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { type DematerializeInput, type DematerializeOutput, type MaterializeInput, type MaterializeOutput, type MigrateInput, type MigrateOutput, type MutationRejection, type MutationRejectionOutput, type QueryOnceInput, type QueryOnceOutput, type RindleDaemonClient, type RowChangeTxn, type RowChangeTxnOutput, type SqlTxn, type SqlTxnOutput } from "@rindle/daemon-client";
|
|
2
|
+
import type { Follower, FollowerRegistry } from "./registry.ts";
|
|
3
|
+
/** Build a control-plane client for one follower (the seam tests inject recording fakes through). */
|
|
4
|
+
export type FollowerClientFactory = (follower: Follower) => RindleDaemonClient;
|
|
5
|
+
export interface RoutingReadClientOptions {
|
|
6
|
+
registry: FollowerRegistry;
|
|
7
|
+
/** Build a control-plane client for a follower. Default: an {@link HttpRindleDaemonClient} to the
|
|
8
|
+
* follower's `controlPlaneUrl` carrying a Bearer `daemonToken`. */
|
|
9
|
+
clientFor?: FollowerClientFactory;
|
|
10
|
+
/** Bearer token the router presents OUTBOUND to follower control planes (the existing
|
|
11
|
+
* `DAEMON_TOKEN`). Used only by the default {@link clientFor}. */
|
|
12
|
+
daemonToken?: string;
|
|
13
|
+
}
|
|
14
|
+
/** Returned (rejected) when there is no follower to place a read on — the honest 503 surface
|
|
15
|
+
* (§5/§8.1): while the live set is empty no new query can materialize. */
|
|
16
|
+
export declare class NoLiveFollowersError extends Error {
|
|
17
|
+
readonly status = 503;
|
|
18
|
+
constructor();
|
|
19
|
+
}
|
|
20
|
+
export declare class RoutingReadClient implements RindleDaemonClient {
|
|
21
|
+
private readonly registry;
|
|
22
|
+
private readonly clientForFollower;
|
|
23
|
+
/** Memoized per-follower control-plane clients, keyed by id; rebuilt if a follower's
|
|
24
|
+
* `controlPlaneUrl` changes (membership churn). Pure cache — no routing/pin state. */
|
|
25
|
+
private readonly clients;
|
|
26
|
+
constructor(opts: RoutingReadClientOptions);
|
|
27
|
+
materialize(input: MaterializeInput): Promise<MaterializeOutput>;
|
|
28
|
+
query(input: QueryOnceInput): Promise<QueryOnceOutput>;
|
|
29
|
+
/** Un-pin / drop by query identity — fans across ALL live followers, because a `materializationId`
|
|
30
|
+
* is follower-local and unroutable and un-pin is by NAME (§4.2). `removed` is true if any
|
|
31
|
+
* follower removed it. */
|
|
32
|
+
dematerialize(input: DematerializeInput): Promise<DematerializeOutput>;
|
|
33
|
+
/** Fan EACH already-resolved pin (authoritative AST + `pinned` policy) across ALL live followers.
|
|
34
|
+
* Best-effort and stateless: the router sprays the currently-live set and remembers nothing — a
|
|
35
|
+
* follower not live at push time catches up via the lazy floor (§4.1). Rejects if any
|
|
36
|
+
* follower×pin call failed, so the api-server retries on its next trigger. */
|
|
37
|
+
assertPins(pins: readonly MaterializeInput[]): Promise<void>;
|
|
38
|
+
executeSqlTxn(_input: SqlTxn): Promise<SqlTxnOutput>;
|
|
39
|
+
rejectMutation(_input: MutationRejection): Promise<MutationRejectionOutput>;
|
|
40
|
+
applyRowChangeTxn(_input: RowChangeTxn): Promise<RowChangeTxnOutput>;
|
|
41
|
+
migrate(_input: MigrateInput): Promise<MigrateOutput>;
|
|
42
|
+
private place;
|
|
43
|
+
private clientOf;
|
|
44
|
+
}
|
|
45
|
+
//# sourceMappingURL=router.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../src/router.ts"],"names":[],"mappings":"AAWA,OAAO,EAEL,KAAK,kBAAkB,EACvB,KAAK,mBAAmB,EACxB,KAAK,gBAAgB,EACrB,KAAK,iBAAiB,EACtB,KAAK,YAAY,EACjB,KAAK,aAAa,EAClB,KAAK,iBAAiB,EACtB,KAAK,uBAAuB,EAC5B,KAAK,cAAc,EACnB,KAAK,eAAe,EACpB,KAAK,kBAAkB,EACvB,KAAK,YAAY,EACjB,KAAK,kBAAkB,EACvB,KAAK,MAAM,EACX,KAAK,YAAY,EAClB,MAAM,uBAAuB,CAAC;AAG/B,OAAO,KAAK,EAAE,QAAQ,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAEhE,qGAAqG;AACrG,MAAM,MAAM,qBAAqB,GAAG,CAAC,QAAQ,EAAE,QAAQ,KAAK,kBAAkB,CAAC;AAE/E,MAAM,WAAW,wBAAwB;IACvC,QAAQ,EAAE,gBAAgB,CAAC;IAC3B;wEACoE;IACpE,SAAS,CAAC,EAAE,qBAAqB,CAAC;IAClC;uEACmE;IACnE,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED;2EAC2E;AAC3E,qBAAa,oBAAqB,SAAQ,KAAK;IAC7C,QAAQ,CAAC,MAAM,OAAO;;CAKvB;AAED,qBAAa,iBAAkB,YAAW,kBAAkB;IAC1D,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAmB;IAC5C,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAwB;IAC1D;2FACuF;IACvF,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAkE;gBAE9E,IAAI,EAAE,wBAAwB;IAapC,WAAW,CAAC,KAAK,EAAE,gBAAgB,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAMhE,KAAK,CAAC,KAAK,EAAE,cAAc,GAAG,OAAO,CAAC,eAAe,CAAC;IAQ5D;;+BAE2B;IACrB,aAAa,CAAC,KAAK,EAAE,kBAAkB,GAAG,OAAO,CAAC,mBAAmB,CAAC;IAS5E;;;mFAG+E;IACzE,UAAU,CAAC,IAAI,EAAE,SAAS,gBAAgB,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAmBlE,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC;IAGpD,cAAc,CAAC,MAAM,EAAE,iBAAiB,GAAG,OAAO,CAAC,uBAAuB,CAAC;IAG3E,iBAAiB,CAAC,MAAM,EAAE,YAAY,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAGpE,OAAO,CAAC,MAAM,EAAE,YAAY,GAAG,OAAO,CAAC,aAAa,CAAC;IAMrD,OAAO,CAAC,KAAK;IAMb,OAAO,CAAC,QAAQ;CAOjB"}
|
package/dist/router.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// The stateless routing read-client (READ-ROUTER-DESIGN.md §2.1). From the api-server's view it IS
|
|
2
|
+
// the read daemon — it implements `RindleDaemonClient` for the read legs (`materialize`, `query`)
|
|
3
|
+
// and routes each to ONE follower by HRW, stamping that follower's public `wsEndpoint` onto the
|
|
4
|
+
// output so the browser connects to the node holding its lease. It also exposes an EXPLICIT fleet
|
|
5
|
+
// pin-assert (`assertPins`) that fans a pin across ALL live followers — distinct, on purpose, from a
|
|
6
|
+
// per-viewer `materialize` (never inferred from `policy.kind`, §4). It holds NO per-session and NO
|
|
7
|
+
// pin state: routing is a pure function of `(key, live())`, so a fresh instance routes identically.
|
|
8
|
+
//
|
|
9
|
+
// Writes NEVER route through the read router (§2.1): the write methods reject loudly as a
|
|
10
|
+
// misconfiguration backstop — the api-server's `SplitDaemonClient` sends them to the master instead.
|
|
11
|
+
import { HttpRindleDaemonClient, } from "@rindle/daemon-client";
|
|
12
|
+
import { route } from "./hrw.js";
|
|
13
|
+
/** Returned (rejected) when there is no follower to place a read on — the honest 503 surface
|
|
14
|
+
* (§5/§8.1): while the live set is empty no new query can materialize. */
|
|
15
|
+
export class NoLiveFollowersError extends Error {
|
|
16
|
+
status = 503;
|
|
17
|
+
constructor() {
|
|
18
|
+
super("read router: no live follower to place this query on");
|
|
19
|
+
this.name = "NoLiveFollowersError";
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
export class RoutingReadClient {
|
|
23
|
+
registry;
|
|
24
|
+
clientForFollower;
|
|
25
|
+
/** Memoized per-follower control-plane clients, keyed by id; rebuilt if a follower's
|
|
26
|
+
* `controlPlaneUrl` changes (membership churn). Pure cache — no routing/pin state. */
|
|
27
|
+
clients = new Map();
|
|
28
|
+
constructor(opts) {
|
|
29
|
+
this.registry = opts.registry;
|
|
30
|
+
this.clientForFollower =
|
|
31
|
+
opts.clientFor ??
|
|
32
|
+
((f) => new HttpRindleDaemonClient({
|
|
33
|
+
baseUrl: f.controlPlaneUrl,
|
|
34
|
+
headers: opts.daemonToken ? { authorization: `Bearer ${opts.daemonToken}` } : undefined,
|
|
35
|
+
}));
|
|
36
|
+
}
|
|
37
|
+
// --- the read legs: route to ONE follower, stamp its public ws endpoint -----------
|
|
38
|
+
async materialize(input) {
|
|
39
|
+
const f = this.place(routingKeyOf(input.subject, input.metadata));
|
|
40
|
+
const out = await this.clientOf(f).materialize(input);
|
|
41
|
+
return { ...out, wsEndpoint: f.wsEndpoint };
|
|
42
|
+
}
|
|
43
|
+
async query(input) {
|
|
44
|
+
// The api-server sets `visibilityKey = subject ?? routingKey`, so it IS the read's routing key
|
|
45
|
+
// (co-locating the SSR read with the browser's follow-up subscribe, §2.4).
|
|
46
|
+
const f = this.place(input.visibilityKey ?? "");
|
|
47
|
+
const out = await this.clientOf(f).query(input);
|
|
48
|
+
return { ...out, wsEndpoint: f.wsEndpoint };
|
|
49
|
+
}
|
|
50
|
+
/** Un-pin / drop by query identity — fans across ALL live followers, because a `materializationId`
|
|
51
|
+
* is follower-local and unroutable and un-pin is by NAME (§4.2). `removed` is true if any
|
|
52
|
+
* follower removed it. */
|
|
53
|
+
async dematerialize(input) {
|
|
54
|
+
const results = await Promise.allSettled(this.registry.live().map((f) => this.clientOf(f).dematerialize(input)));
|
|
55
|
+
return { removed: results.some((r) => r.status === "fulfilled" && r.value.removed) };
|
|
56
|
+
}
|
|
57
|
+
// --- the explicit fleet pin-assert (§4.2 push) ------------------------------------
|
|
58
|
+
/** Fan EACH already-resolved pin (authoritative AST + `pinned` policy) across ALL live followers.
|
|
59
|
+
* Best-effort and stateless: the router sprays the currently-live set and remembers nothing — a
|
|
60
|
+
* follower not live at push time catches up via the lazy floor (§4.1). Rejects if any
|
|
61
|
+
* follower×pin call failed, so the api-server retries on its next trigger. */
|
|
62
|
+
async assertPins(pins) {
|
|
63
|
+
const live = this.registry.live();
|
|
64
|
+
const tasks = [];
|
|
65
|
+
for (const f of live) {
|
|
66
|
+
const client = this.clientOf(f);
|
|
67
|
+
for (const pin of pins)
|
|
68
|
+
tasks.push(client.materialize(pin));
|
|
69
|
+
}
|
|
70
|
+
const results = await Promise.allSettled(tasks);
|
|
71
|
+
const failures = results.filter((r) => r.status === "rejected");
|
|
72
|
+
if (failures.length) {
|
|
73
|
+
throw new Error(`read router: pin fan-out had ${failures.length}/${tasks.length} failures — ` +
|
|
74
|
+
failures.map((r) => String(r.reason?.message ?? r.reason)).join("; "));
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
// --- writes NEVER route through the read router (§2.1) -----------------------------
|
|
78
|
+
executeSqlTxn(_input) {
|
|
79
|
+
return Promise.reject(writeRejected("executeSqlTxn"));
|
|
80
|
+
}
|
|
81
|
+
rejectMutation(_input) {
|
|
82
|
+
return Promise.reject(writeRejected("rejectMutation"));
|
|
83
|
+
}
|
|
84
|
+
applyRowChangeTxn(_input) {
|
|
85
|
+
return Promise.reject(writeRejected("applyRowChangeTxn"));
|
|
86
|
+
}
|
|
87
|
+
migrate(_input) {
|
|
88
|
+
return Promise.reject(writeRejected("migrate"));
|
|
89
|
+
}
|
|
90
|
+
// --- internals --------------------------------------------------------------------
|
|
91
|
+
place(key) {
|
|
92
|
+
const f = route(key, this.registry.live());
|
|
93
|
+
if (!f)
|
|
94
|
+
throw new NoLiveFollowersError();
|
|
95
|
+
return f;
|
|
96
|
+
}
|
|
97
|
+
clientOf(f) {
|
|
98
|
+
const cached = this.clients.get(f.id);
|
|
99
|
+
if (cached && cached.url === f.controlPlaneUrl)
|
|
100
|
+
return cached.client;
|
|
101
|
+
const client = this.clientForFollower(f);
|
|
102
|
+
this.clients.set(f.id, { url: f.controlPlaneUrl, client });
|
|
103
|
+
return client;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
/** The routing key: the authenticated `subject` first (co-locates a user's tabs/devices), else the
|
|
107
|
+
* anonymous key the api-server forwarded on `metadata.routingKey` (cookie ?? clientId). A routing
|
|
108
|
+
* HINT, not authorization (§1.5) — leases stay follower-local and subject-authorized regardless. */
|
|
109
|
+
function routingKeyOf(subject, metadata) {
|
|
110
|
+
if (subject)
|
|
111
|
+
return subject;
|
|
112
|
+
const rk = metadata?.routingKey;
|
|
113
|
+
return typeof rk === "string" ? rk : "";
|
|
114
|
+
}
|
|
115
|
+
function writeRejected(op) {
|
|
116
|
+
return new Error(`read router: ${op} is a write — writes go to the master, never the router (READ-ROUTER-DESIGN.md §2.1)`);
|
|
117
|
+
}
|
|
118
|
+
//# sourceMappingURL=router.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"router.js","sourceRoot":"","sources":["../src/router.ts"],"names":[],"mappings":"AAAA,mGAAmG;AACnG,kGAAkG;AAClG,gGAAgG;AAChG,kGAAkG;AAClG,qGAAqG;AACrG,mGAAmG;AACnG,oGAAoG;AACpG,EAAE;AACF,0FAA0F;AAC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AM,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;QACtC,IAAI,MAAM,IAAI,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,eAAe;YAAE,OAAO,MAAM,CAAC,MAAM,CAAC;QACrE,MAAM,MAAM,GAAG,IAAI,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC;QACzC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,GAAG,EAAE,CAAC,CAAC,eAAe,EAAE,MAAM,EAAE,CAAC,CAAC;QAC3D,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AAED;;qGAEqG;AACrG,SAAS,YAAY,CAAC,OAA2B,EAAE,QAA6C;IAC9F,IAAI,OAAO;QAAE,OAAO,OAAO,CAAC;IAC5B,MAAM,EAAE,GAAG,QAAQ,EAAE,UAAU,CAAC;IAChC,OAAO,OAAO,EAAE,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;AAC1C,CAAC;AAED,SAAS,aAAa,CAAC,EAAU;IAC/B,OAAO,IAAI,KAAK,CACd,gBAAgB,EAAE,sFAAsF,CACzG,CAAC;AACJ,CAAC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@rindle/router",
|
|
3
|
+
"version": "0.1.0-rc.5",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/rindle-sh/rindle.git",
|
|
8
|
+
"directory": "packages/router"
|
|
9
|
+
},
|
|
10
|
+
"type": "module",
|
|
11
|
+
"description": "Stateless read-routing control-plane proxy: HRW follower placement + explicit fleet pin fan-out (READ-ROUTER-DESIGN.md).",
|
|
12
|
+
"main": "./dist/index.js",
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"sideEffects": false,
|
|
15
|
+
"exports": {
|
|
16
|
+
".": {
|
|
17
|
+
"@rindle/source": "./src/index.ts",
|
|
18
|
+
"types": "./dist/index.d.ts",
|
|
19
|
+
"default": "./dist/index.js"
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"dist",
|
|
24
|
+
"src",
|
|
25
|
+
"README.md"
|
|
26
|
+
],
|
|
27
|
+
"dependencies": {
|
|
28
|
+
"@rindle/daemon-client": "0.1.0-rc.5"
|
|
29
|
+
},
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"@types/node": "^22.10.0",
|
|
32
|
+
"typescript": "^5.7.0"
|
|
33
|
+
},
|
|
34
|
+
"scripts": {
|
|
35
|
+
"build": "tsc -p tsconfig.build.json",
|
|
36
|
+
"typecheck": "tsc --noEmit",
|
|
37
|
+
"test": "tsc --noEmit && node --conditions=@rindle/source --test test/*.test.ts"
|
|
38
|
+
}
|
|
39
|
+
}
|
package/src/hrw.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// Weighted rendezvous hashing (HRW) — the router's one pure placement function
|
|
2
|
+
// (READ-ROUTER-DESIGN.md §1.4, §2.2). `route(key, followers)` is a deterministic function of the
|
|
3
|
+
// membership SET + key: HRW's logarithmic method gives each follower a score
|
|
4
|
+
// `weight / -ln(hashUnit(key‖id))` and the max wins, tie-broken on `id` so the result is
|
|
5
|
+
// INDEPENDENT of the followers' order (two router replicas over the same set agree). HRW's
|
|
6
|
+
// minimal-disruption property is what bounds churn to ~1/N keys on a membership change.
|
|
7
|
+
|
|
8
|
+
const encoder = new TextEncoder();
|
|
9
|
+
|
|
10
|
+
/** Map a string to a stable unit float in the OPEN interval (0,1) — deterministic across runtimes
|
|
11
|
+
* (FNV-1a 64-bit over UTF-8 bytes in exact BigInt, then folded to a 53-bit double mantissa). The
|
|
12
|
+
* open interval matters: HRW needs `hashUnit ∈ (0,1)` so `-ln(hashUnit) > 0` (never 0 or ∞). */
|
|
13
|
+
export function hashUnit(s: string): number {
|
|
14
|
+
const bytes = encoder.encode(s);
|
|
15
|
+
const mask = 0xffffffffffffffffn;
|
|
16
|
+
let h = 0xcbf29ce484222325n; // FNV offset basis (64-bit)
|
|
17
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
18
|
+
h ^= BigInt(bytes[i]);
|
|
19
|
+
h = (h * 0x100000001b3n) & mask; // FNV prime
|
|
20
|
+
}
|
|
21
|
+
// FNV's LOW bits are weakly mixed (a multiplicative hash barely diffuses high bits downward), so
|
|
22
|
+
// folding them straight to a mantissa biases placement. Run Murmur3's fmix64 avalanche first —
|
|
23
|
+
// afterward every bit depends on every input bit, so the low 53 are uniform.
|
|
24
|
+
h ^= h >> 33n;
|
|
25
|
+
h = (h * 0xff51afd7ed558ccdn) & mask;
|
|
26
|
+
h ^= h >> 33n;
|
|
27
|
+
h = (h * 0xc4ceb9fe1a85ec53n) & mask;
|
|
28
|
+
h ^= h >> 33n;
|
|
29
|
+
const bits = Number(h & ((1n << 53n) - 1n)); // 0 .. 2^53 - 1
|
|
30
|
+
return (bits + 0.5) / 2 ** 53; // strictly inside (0, 1)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The minimum a follower must expose to be placed: a stable `id` and an optional `weight`
|
|
34
|
+
* (load share ∝ weight; default 1; a weight ≤ 0 opts the follower out of placement). */
|
|
35
|
+
export interface RoutableFollower {
|
|
36
|
+
id: string;
|
|
37
|
+
weight?: number;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Place `key` on exactly one of `followers` by weighted HRW. Returns `undefined` only when the set
|
|
41
|
+
* is empty (or every follower has weight ≤ 0) — the caller turns that into a 503. Order-independent:
|
|
42
|
+
* shuffling `followers` never changes the result (max score, then lexicographically-smallest `id`). */
|
|
43
|
+
export function route<F extends RoutableFollower>(key: string, followers: readonly F[]): F | undefined {
|
|
44
|
+
let best: F | undefined;
|
|
45
|
+
let bestScore = -Infinity;
|
|
46
|
+
for (const f of followers) {
|
|
47
|
+
const weight = f.weight ?? 1;
|
|
48
|
+
if (weight <= 0) continue;
|
|
49
|
+
const score = weight / -Math.log(hashUnit(`${key}\u0000${f.id}`));
|
|
50
|
+
if (score > bestScore || (score === bestScore && best !== undefined && f.id < best.id)) {
|
|
51
|
+
best = f;
|
|
52
|
+
bestScore = score;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return best;
|
|
56
|
+
}
|
package/src/http.ts
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// The router's HTTP front (READ-ROUTER-DESIGN.md §9) — it speaks the daemon control-plane read
|
|
2
|
+
// surface so the api-server reaches it through an ordinary `HttpRindleDaemonClient`, plus the one
|
|
3
|
+
// extra fleet route `/assert-pins`. The api-server's `RINDLE_ROUTER_URL` points here for the reads
|
|
4
|
+
// leg; `RINDLE_MASTER_URL` points at the master for writes (the `SplitDaemonClient`, §2.1).
|
|
5
|
+
//
|
|
6
|
+
// `createRouterPinClient` is the counterpart the api-server's `pinFanout` uses to invoke the fleet
|
|
7
|
+
// pin-assert over that same HTTP hop.
|
|
8
|
+
|
|
9
|
+
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
|
|
10
|
+
import type { AddressInfo } from "node:net";
|
|
11
|
+
|
|
12
|
+
import type { MaterializeInput } from "@rindle/daemon-client";
|
|
13
|
+
|
|
14
|
+
import type { RoutingReadClient } from "./router.ts";
|
|
15
|
+
|
|
16
|
+
export const ROUTER_PATHS = {
|
|
17
|
+
materialize: "/materialize",
|
|
18
|
+
query: "/query",
|
|
19
|
+
dematerialize: "/dematerialize",
|
|
20
|
+
assertPins: "/assert-pins",
|
|
21
|
+
} as const;
|
|
22
|
+
|
|
23
|
+
/** Dispatch one parsed request to the router (the runtime-agnostic core — drive it from any HTTP
|
|
24
|
+
* shell). Throws `{ status: 404 }` for an unknown path; routing errors carry their own `status`
|
|
25
|
+
* (e.g. {@link NoLiveFollowersError} → 503). */
|
|
26
|
+
export function dispatchRouter(router: RoutingReadClient, path: string, body: unknown): Promise<unknown> {
|
|
27
|
+
// The body is untrusted JSON off the wire — cast through `unknown` to the control-plane input
|
|
28
|
+
// shapes (the followers' control plane validates the contents).
|
|
29
|
+
const msg = (body ?? {}) as Record<string, unknown>;
|
|
30
|
+
switch (path) {
|
|
31
|
+
case ROUTER_PATHS.materialize:
|
|
32
|
+
return router.materialize(msg as unknown as MaterializeInput);
|
|
33
|
+
case ROUTER_PATHS.query:
|
|
34
|
+
return router.query(msg as unknown as Parameters<RoutingReadClient["query"]>[0]);
|
|
35
|
+
case ROUTER_PATHS.dematerialize:
|
|
36
|
+
return router.dematerialize(msg as Parameters<RoutingReadClient["dematerialize"]>[0]);
|
|
37
|
+
case ROUTER_PATHS.assertPins:
|
|
38
|
+
return router.assertPins((msg.pins as MaterializeInput[]) ?? []).then(() => ({ ok: true }));
|
|
39
|
+
default:
|
|
40
|
+
throw Object.assign(new Error(`read router: not found: ${path}`), { status: 404 });
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface RouterServerOptions {
|
|
45
|
+
router: RoutingReadClient;
|
|
46
|
+
/** Inbound bearer token the api-server must present. Omit to disable auth (dev/tests only). */
|
|
47
|
+
token?: string;
|
|
48
|
+
port?: number;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface RouterServer {
|
|
52
|
+
readonly port: number;
|
|
53
|
+
close(): Promise<void>;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Start the router's Node HTTP server. Resolves once listening (port resolved when `port: 0`). */
|
|
57
|
+
export function createRouterServer(opts: RouterServerOptions): Promise<RouterServer> {
|
|
58
|
+
const handle = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {
|
|
59
|
+
try {
|
|
60
|
+
if (req.method !== "POST") return send(res, 405, { error: "method not allowed" });
|
|
61
|
+
if (opts.token && req.headers.authorization !== `Bearer ${opts.token}`) {
|
|
62
|
+
return send(res, 401, { error: "unauthorized" });
|
|
63
|
+
}
|
|
64
|
+
const chunks: Buffer[] = [];
|
|
65
|
+
for await (const chunk of req) chunks.push(chunk as Buffer);
|
|
66
|
+
const body = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
|
|
67
|
+
const out = await dispatchRouter(opts.router, req.url ?? "", body);
|
|
68
|
+
send(res, 200, out ?? {});
|
|
69
|
+
} catch (err) {
|
|
70
|
+
const status = (err as { status?: number })?.status ?? 500;
|
|
71
|
+
send(res, status, { error: String((err as Error)?.message ?? err) });
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
const server = createServer((req, res) => void handle(req, res));
|
|
76
|
+
return new Promise((resolve) => {
|
|
77
|
+
server.listen(opts.port ?? 0, () => {
|
|
78
|
+
const port = (server.address() as AddressInfo).port;
|
|
79
|
+
resolve({ port, close: () => new Promise<void>((r) => server.close(() => r())) });
|
|
80
|
+
});
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function send(res: ServerResponse, status: number, body: unknown): void {
|
|
85
|
+
res.writeHead(status, { "content-type": "application/json" });
|
|
86
|
+
res.end(JSON.stringify(body));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The api-server's `pinFanout`: invokes the router's explicit fleet pin-assert over HTTP
|
|
90
|
+
* (`POST /assert-pins`). Mirrors how the api-server reaches the router for reads, so a routed
|
|
91
|
+
* deploy uses one `RINDLE_ROUTER_URL` (+ token) for both legs. */
|
|
92
|
+
export interface RouterPinClient {
|
|
93
|
+
assertPins(pins: readonly MaterializeInput[]): Promise<void>;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export interface RouterPinClientOptions {
|
|
97
|
+
baseUrl: string;
|
|
98
|
+
token?: string;
|
|
99
|
+
fetch?: typeof fetch;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function createRouterPinClient(opts: RouterPinClientOptions): RouterPinClient {
|
|
103
|
+
const base = opts.baseUrl.endsWith("/") ? opts.baseUrl.slice(0, -1) : opts.baseUrl;
|
|
104
|
+
const fetchImpl = opts.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));
|
|
105
|
+
return {
|
|
106
|
+
async assertPins(pins) {
|
|
107
|
+
const res = await fetchImpl(`${base}${ROUTER_PATHS.assertPins}`, {
|
|
108
|
+
method: "POST",
|
|
109
|
+
headers: {
|
|
110
|
+
"content-type": "application/json",
|
|
111
|
+
...(opts.token ? { authorization: `Bearer ${opts.token}` } : {}),
|
|
112
|
+
},
|
|
113
|
+
body: JSON.stringify({ pins }),
|
|
114
|
+
});
|
|
115
|
+
if (!res.ok) throw new Error(`read router assert-pins failed: ${res.status} ${await res.text()}`);
|
|
116
|
+
},
|
|
117
|
+
};
|
|
118
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// @rindle/router — the stateless read-routing control-plane proxy (READ-ROUTER-DESIGN.md).
|
|
2
|
+
// Placement is one pure function (`route = HRW(key, live())`); the router holds the follower
|
|
3
|
+
// membership view and NO per-session / NO pin state. The api-server's `SplitDaemonClient` points
|
|
4
|
+
// its reads leg here (writes go to the master); the browser↔follower ws data path stays direct.
|
|
5
|
+
|
|
6
|
+
export { hashUnit, route } from "./hrw.ts";
|
|
7
|
+
export type { RoutableFollower } from "./hrw.ts";
|
|
8
|
+
|
|
9
|
+
export { StaticFollowerRegistry } from "./registry.ts";
|
|
10
|
+
export type { Follower, FollowerRegistry } from "./registry.ts";
|
|
11
|
+
|
|
12
|
+
export { NoLiveFollowersError, RoutingReadClient } from "./router.ts";
|
|
13
|
+
export type { FollowerClientFactory, RoutingReadClientOptions } from "./router.ts";
|
|
14
|
+
|
|
15
|
+
export { ROUTER_PATHS, createRouterPinClient, createRouterServer, dispatchRouter } from "./http.ts";
|
|
16
|
+
export type { RouterPinClient, RouterPinClientOptions, RouterServer, RouterServerOptions } from "./http.ts";
|
package/src/registry.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// The follower membership view (READ-ROUTER-DESIGN.md §2.2, §9). The router holds NO per-session
|
|
2
|
+
// or pin state — the registry's `live()` set is the only input HRW routes over. "Unhealthy"
|
|
3
|
+
// (unreachable / draining) ⇒ dropped from `live()`, which is what re-HRWs its sessions on their
|
|
4
|
+
// next lease. A merely *lagging* follower stays in `live()` (it still serves reads).
|
|
5
|
+
//
|
|
6
|
+
// Source of the set: a static list (dev) → Fly 6PN `.internal` / orchestrator API (prod) → gossip
|
|
7
|
+
// later — all behind this interface. Each entry carries TWO addresses: the PRIVATE control-plane
|
|
8
|
+
// URL the router POSTs to, and the PUBLIC ws endpoint handed to the browser as `wsEndpoint`.
|
|
9
|
+
|
|
10
|
+
import type { RoutableFollower } from "./hrw.ts";
|
|
11
|
+
|
|
12
|
+
export interface Follower extends RoutableFollower {
|
|
13
|
+
/** Stable identity — the HRW input and the client-cache key. Survives restarts (same id ⇒ a key
|
|
14
|
+
* still HRWs to it, so a reboot needs no re-placement, §3). */
|
|
15
|
+
id: string;
|
|
16
|
+
/** PRIVATE control-plane URL (router → follower `/materialize`, `/query`, `/dematerialize`).
|
|
17
|
+
* Never exposed to the browser. */
|
|
18
|
+
controlPlaneUrl: string;
|
|
19
|
+
/** PUBLIC ws endpoint (`wss:443`) the browser opens its subscription to — the lease's
|
|
20
|
+
* `wsEndpoint`. Browser-reachable; the only follower address that crosses a provider boundary. */
|
|
21
|
+
wsEndpoint: string;
|
|
22
|
+
/** Load share ∝ weight (default 1). A weight ≤ 0 opts the follower out of placement. */
|
|
23
|
+
weight?: number;
|
|
24
|
+
/** Routable when not explicitly false (the default). Set false to drain/quarantine — it drops
|
|
25
|
+
* out of `live()` and its keys re-HRW elsewhere on their next lease. */
|
|
26
|
+
healthy?: boolean;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface FollowerRegistry {
|
|
30
|
+
/** The currently routable (healthy) followers. HRW runs over exactly this set, so the result is
|
|
31
|
+
* a pure function of what `live()` returns at call time. */
|
|
32
|
+
live(): readonly Follower[];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** A registry backed by an in-memory list — the dev/test source, and the substrate a health probe
|
|
36
|
+
* or discovery loop drives via {@link set}/{@link setHealthy}. Copies entries on the way in so the
|
|
37
|
+
* caller can't mutate the routed set behind the router's back. */
|
|
38
|
+
export class StaticFollowerRegistry implements FollowerRegistry {
|
|
39
|
+
private followers: Follower[];
|
|
40
|
+
|
|
41
|
+
constructor(followers: readonly Follower[] = []) {
|
|
42
|
+
this.followers = followers.map((f) => ({ ...f }));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
live(): readonly Follower[] {
|
|
46
|
+
return this.followers.filter((f) => f.healthy !== false);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The full routable set, healthy or not (for diagnostics / a health probe). */
|
|
50
|
+
all(): readonly Follower[] {
|
|
51
|
+
return this.followers;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Replace the whole membership set (a discovery refresh). */
|
|
55
|
+
set(followers: readonly Follower[]): void {
|
|
56
|
+
this.followers = followers.map((f) => ({ ...f }));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Mark one follower healthy/unhealthy — drops it from / restores it to `live()`. No-op for an
|
|
60
|
+
* unknown id. */
|
|
61
|
+
setHealthy(id: string, healthy: boolean): void {
|
|
62
|
+
const f = this.followers.find((x) => x.id === id);
|
|
63
|
+
if (f) f.healthy = healthy;
|
|
64
|
+
}
|
|
65
|
+
}
|
package/src/router.ts
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
// The stateless routing read-client (READ-ROUTER-DESIGN.md §2.1). From the api-server's view it IS
|
|
2
|
+
// the read daemon — it implements `RindleDaemonClient` for the read legs (`materialize`, `query`)
|
|
3
|
+
// and routes each to ONE follower by HRW, stamping that follower's public `wsEndpoint` onto the
|
|
4
|
+
// output so the browser connects to the node holding its lease. It also exposes an EXPLICIT fleet
|
|
5
|
+
// pin-assert (`assertPins`) that fans a pin across ALL live followers — distinct, on purpose, from a
|
|
6
|
+
// per-viewer `materialize` (never inferred from `policy.kind`, §4). It holds NO per-session and NO
|
|
7
|
+
// pin state: routing is a pure function of `(key, live())`, so a fresh instance routes identically.
|
|
8
|
+
//
|
|
9
|
+
// Writes NEVER route through the read router (§2.1): the write methods reject loudly as a
|
|
10
|
+
// misconfiguration backstop — the api-server's `SplitDaemonClient` sends them to the master instead.
|
|
11
|
+
|
|
12
|
+
import {
|
|
13
|
+
HttpRindleDaemonClient,
|
|
14
|
+
type DematerializeInput,
|
|
15
|
+
type DematerializeOutput,
|
|
16
|
+
type MaterializeInput,
|
|
17
|
+
type MaterializeOutput,
|
|
18
|
+
type MigrateInput,
|
|
19
|
+
type MigrateOutput,
|
|
20
|
+
type MutationRejection,
|
|
21
|
+
type MutationRejectionOutput,
|
|
22
|
+
type QueryOnceInput,
|
|
23
|
+
type QueryOnceOutput,
|
|
24
|
+
type RindleDaemonClient,
|
|
25
|
+
type RowChangeTxn,
|
|
26
|
+
type RowChangeTxnOutput,
|
|
27
|
+
type SqlTxn,
|
|
28
|
+
type SqlTxnOutput,
|
|
29
|
+
} from "@rindle/daemon-client";
|
|
30
|
+
|
|
31
|
+
import { route } from "./hrw.ts";
|
|
32
|
+
import type { Follower, FollowerRegistry } from "./registry.ts";
|
|
33
|
+
|
|
34
|
+
/** Build a control-plane client for one follower (the seam tests inject recording fakes through). */
|
|
35
|
+
export type FollowerClientFactory = (follower: Follower) => RindleDaemonClient;
|
|
36
|
+
|
|
37
|
+
export interface RoutingReadClientOptions {
|
|
38
|
+
registry: FollowerRegistry;
|
|
39
|
+
/** Build a control-plane client for a follower. Default: an {@link HttpRindleDaemonClient} to the
|
|
40
|
+
* follower's `controlPlaneUrl` carrying a Bearer `daemonToken`. */
|
|
41
|
+
clientFor?: FollowerClientFactory;
|
|
42
|
+
/** Bearer token the router presents OUTBOUND to follower control planes (the existing
|
|
43
|
+
* `DAEMON_TOKEN`). Used only by the default {@link clientFor}. */
|
|
44
|
+
daemonToken?: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Returned (rejected) when there is no follower to place a read on — the honest 503 surface
|
|
48
|
+
* (§5/§8.1): while the live set is empty no new query can materialize. */
|
|
49
|
+
export class NoLiveFollowersError extends Error {
|
|
50
|
+
readonly status = 503;
|
|
51
|
+
constructor() {
|
|
52
|
+
super("read router: no live follower to place this query on");
|
|
53
|
+
this.name = "NoLiveFollowersError";
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export class RoutingReadClient implements RindleDaemonClient {
|
|
58
|
+
private readonly registry: FollowerRegistry;
|
|
59
|
+
private readonly clientForFollower: FollowerClientFactory;
|
|
60
|
+
/** Memoized per-follower control-plane clients, keyed by id; rebuilt if a follower's
|
|
61
|
+
* `controlPlaneUrl` changes (membership churn). Pure cache — no routing/pin state. */
|
|
62
|
+
private readonly clients = new Map<string, { url: string; client: RindleDaemonClient }>();
|
|
63
|
+
|
|
64
|
+
constructor(opts: RoutingReadClientOptions) {
|
|
65
|
+
this.registry = opts.registry;
|
|
66
|
+
this.clientForFollower =
|
|
67
|
+
opts.clientFor ??
|
|
68
|
+
((f) =>
|
|
69
|
+
new HttpRindleDaemonClient({
|
|
70
|
+
baseUrl: f.controlPlaneUrl,
|
|
71
|
+
headers: opts.daemonToken ? { authorization: `Bearer ${opts.daemonToken}` } : undefined,
|
|
72
|
+
}));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// --- the read legs: route to ONE follower, stamp its public ws endpoint -----------
|
|
76
|
+
|
|
77
|
+
async materialize(input: MaterializeInput): Promise<MaterializeOutput> {
|
|
78
|
+
const f = this.place(routingKeyOf(input.subject, input.metadata));
|
|
79
|
+
const out = await this.clientOf(f).materialize(input);
|
|
80
|
+
return { ...out, wsEndpoint: f.wsEndpoint };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async query(input: QueryOnceInput): Promise<QueryOnceOutput> {
|
|
84
|
+
// The api-server sets `visibilityKey = subject ?? routingKey`, so it IS the read's routing key
|
|
85
|
+
// (co-locating the SSR read with the browser's follow-up subscribe, §2.4).
|
|
86
|
+
const f = this.place(input.visibilityKey ?? "");
|
|
87
|
+
const out = await this.clientOf(f).query(input);
|
|
88
|
+
return { ...out, wsEndpoint: f.wsEndpoint };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Un-pin / drop by query identity — fans across ALL live followers, because a `materializationId`
|
|
92
|
+
* is follower-local and unroutable and un-pin is by NAME (§4.2). `removed` is true if any
|
|
93
|
+
* follower removed it. */
|
|
94
|
+
async dematerialize(input: DematerializeInput): Promise<DematerializeOutput> {
|
|
95
|
+
const results = await Promise.allSettled(
|
|
96
|
+
this.registry.live().map((f) => this.clientOf(f).dematerialize(input)),
|
|
97
|
+
);
|
|
98
|
+
return { removed: results.some((r) => r.status === "fulfilled" && r.value.removed) };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// --- the explicit fleet pin-assert (§4.2 push) ------------------------------------
|
|
102
|
+
|
|
103
|
+
/** Fan EACH already-resolved pin (authoritative AST + `pinned` policy) across ALL live followers.
|
|
104
|
+
* Best-effort and stateless: the router sprays the currently-live set and remembers nothing — a
|
|
105
|
+
* follower not live at push time catches up via the lazy floor (§4.1). Rejects if any
|
|
106
|
+
* follower×pin call failed, so the api-server retries on its next trigger. */
|
|
107
|
+
async assertPins(pins: readonly MaterializeInput[]): Promise<void> {
|
|
108
|
+
const live = this.registry.live();
|
|
109
|
+
const tasks: Promise<unknown>[] = [];
|
|
110
|
+
for (const f of live) {
|
|
111
|
+
const client = this.clientOf(f);
|
|
112
|
+
for (const pin of pins) tasks.push(client.materialize(pin));
|
|
113
|
+
}
|
|
114
|
+
const results = await Promise.allSettled(tasks);
|
|
115
|
+
const failures = results.filter((r): r is PromiseRejectedResult => r.status === "rejected");
|
|
116
|
+
if (failures.length) {
|
|
117
|
+
throw new Error(
|
|
118
|
+
`read router: pin fan-out had ${failures.length}/${tasks.length} failures — ` +
|
|
119
|
+
failures.map((r) => String((r.reason as Error)?.message ?? r.reason)).join("; "),
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// --- writes NEVER route through the read router (§2.1) -----------------------------
|
|
125
|
+
|
|
126
|
+
executeSqlTxn(_input: SqlTxn): Promise<SqlTxnOutput> {
|
|
127
|
+
return Promise.reject(writeRejected("executeSqlTxn"));
|
|
128
|
+
}
|
|
129
|
+
rejectMutation(_input: MutationRejection): Promise<MutationRejectionOutput> {
|
|
130
|
+
return Promise.reject(writeRejected("rejectMutation"));
|
|
131
|
+
}
|
|
132
|
+
applyRowChangeTxn(_input: RowChangeTxn): Promise<RowChangeTxnOutput> {
|
|
133
|
+
return Promise.reject(writeRejected("applyRowChangeTxn"));
|
|
134
|
+
}
|
|
135
|
+
migrate(_input: MigrateInput): Promise<MigrateOutput> {
|
|
136
|
+
return Promise.reject(writeRejected("migrate"));
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// --- internals --------------------------------------------------------------------
|
|
140
|
+
|
|
141
|
+
private place(key: string): Follower {
|
|
142
|
+
const f = route(key, this.registry.live());
|
|
143
|
+
if (!f) throw new NoLiveFollowersError();
|
|
144
|
+
return f;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
private clientOf(f: Follower): RindleDaemonClient {
|
|
148
|
+
const cached = this.clients.get(f.id);
|
|
149
|
+
if (cached && cached.url === f.controlPlaneUrl) return cached.client;
|
|
150
|
+
const client = this.clientForFollower(f);
|
|
151
|
+
this.clients.set(f.id, { url: f.controlPlaneUrl, client });
|
|
152
|
+
return client;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** The routing key: the authenticated `subject` first (co-locates a user's tabs/devices), else the
|
|
157
|
+
* anonymous key the api-server forwarded on `metadata.routingKey` (cookie ?? clientId). A routing
|
|
158
|
+
* HINT, not authorization (§1.5) — leases stay follower-local and subject-authorized regardless. */
|
|
159
|
+
function routingKeyOf(subject: string | undefined, metadata: Record<string, unknown> | undefined): string {
|
|
160
|
+
if (subject) return subject;
|
|
161
|
+
const rk = metadata?.routingKey;
|
|
162
|
+
return typeof rk === "string" ? rk : "";
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function writeRejected(op: string): Error {
|
|
166
|
+
return new Error(
|
|
167
|
+
`read router: ${op} is a write — writes go to the master, never the router (READ-ROUTER-DESIGN.md §2.1)`,
|
|
168
|
+
);
|
|
169
|
+
}
|