@molecule/api-deploy-rollout-fly 0.0.0-stage → 0.0.1-stage

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 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,316 @@
1
- # Temporary Holding Version
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-19T18:05:45.688Z
7
+ -->
2
8
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
9
+ # @molecule/api-deploy-rollout-fly
10
+
11
+ Fly Machines provider bonds for the deploy-rollout core.
12
+
13
+ In-place (restart the same Machines one at a time, with a restore path) and
14
+ grow-then-shrink (clone a Machine beside the old set, retire the old one when the
15
+ new one serves). Commands run through an injected runner, so tests need no Fly
16
+ account.
17
+
18
+ > **Auto-generated, AI-first package reference** for the [molecule.dev](https://molecule.dev) ecosystem.
19
+ > It is written to be read by coding agents as much as by people, and is generated from this
20
+ > package's source — edit `src/index.ts` JSDoc, not this file.
21
+
22
+ ## Quick Start
23
+
24
+ ```typescript
25
+ import { runInPlaceRollout, setProvider } from '@molecule/api-deploy-rollout'
26
+ import { provider } from '@molecule/api-deploy-rollout-default'
27
+ import { createFlyInPlaceProvider } from '@molecule/api-deploy-rollout-fly'
28
+
29
+ setProvider(provider)
30
+ await runInPlaceRollout({
31
+ provider: createFlyInPlaceProvider({
32
+ app: 'molecule-api',
33
+ isServing: (id) => probeMachine(id),
34
+ restore: (id) => clearPatchAndRestart(id),
35
+ }),
36
+ policy: { soakMs: 30_000 },
37
+ })
38
+ ```
39
+
40
+ ## Type
41
+
42
+ `provider`
43
+
44
+ ## Installation
45
+
46
+ ```bash
47
+ npm install @molecule/api-deploy-rollout-fly @molecule/api-deploy-rollout
48
+ ```
49
+
50
+ ## API
51
+
52
+ ### Interfaces
53
+
54
+ #### `FlyMachine`
55
+
56
+ One Fly Machine, as the rollout needs to see it.
57
+
58
+ ```typescript
59
+ interface FlyMachine extends RolloutInstance {
60
+ /** The Machine's Fly state (`started`, `stopped`, …). */
61
+ state: string
62
+ /** The image the Machine runs, tag or digest form. */
63
+ imageRef: string | null
64
+ /** The Machine's configuration version (`instance_id`/`version`). */
65
+ version: string | null
66
+ /**
67
+ * The longest service-check grace period the Machine declares, in milliseconds.
68
+ *
69
+ * Fly reports a check inside its grace window as PASSING and can route traffic
70
+ * to a Machine that has not booted; a rolling restart must know the number to
71
+ * refuse it. Zero when the Machine's checks have no grace.
72
+ */
73
+ gracePeriodMs: number
74
+ }
75
+ ```
76
+
77
+ #### `FlyCommandResult`
78
+
79
+ The result of one flyctl invocation.
80
+
81
+ ```typescript
82
+ interface FlyCommandResult {
83
+ /** Exit status, or `null` when the process did not exit normally. */
84
+ status: number | null
85
+ /** Standard output. */
86
+ stdout: string
87
+ /** Standard error. */
88
+ stderr?: string
89
+ }
90
+ ```
91
+
92
+ #### `FlyMachinesOptions`
93
+
94
+ Where and how the adapter reaches one Fly app.
95
+
96
+ ```typescript
97
+ interface FlyMachinesOptions {
98
+ /** The Fly app name. */
99
+ app: string
100
+ /** The runner; defaults to spawning the local `flyctl`. */
101
+ run?: FlyCommandRunner
102
+ }
103
+ ```
104
+
105
+ #### `FlyInPlaceOptions`
106
+
107
+ What an in-place Fly rollout supplies that Fly itself does not know.
108
+
109
+ The adapter knows how to list, restart and start a Machine. Whether a Machine is
110
+ SERVING, what "replace" means (a patch volume swap, a new image) and how to undo it
111
+ are properties of the app being deployed, so the caller states them.
112
+
113
+ ```typescript
114
+ interface FlyInPlaceOptions extends FlyMachinesOptions {
115
+ /** Whether a Machine answers its readiness probe right now. */
116
+ isServing: (machineId: string) => Promise<boolean>
117
+ /**
118
+ * Change one Machine to the new build and leave it serving. Defaults to a restart
119
+ * that waits for the Machine to reach `started`.
120
+ */
121
+ replace?: (machineId: string) => Promise<void>
122
+ /** Put one Machine back on the old build. */
123
+ restore?: (machineId: string) => Promise<void>
124
+ /** How long a restart may take to reach `started`. Defaults to 6 minutes. */
125
+ restartBudgetMs?: number
126
+ /** Sleep between state polls. Defaults to 5000 ms. */
127
+ pollMs?: number
128
+ }
129
+ ```
130
+
131
+ #### `FlyInstanceOptions`
132
+
133
+ What a grow-then-shrink Fly rollout supplies that Fly itself does not know.
134
+
135
+ `launch` builds the Machine (image, volume, env, mounts) — that is the app's
136
+ deployment recipe. `join`/`leave` change whatever edge routes to the app; Fly's own
137
+ proxy balances by service, not by a caller-held set.
138
+
139
+ ```typescript
140
+ interface FlyInstanceOptions extends FlyMachinesOptions {
141
+ /** Create the Machine for `index` and resolve once it exists. */
142
+ launch: (index: number) => Promise<FlyMachine>
143
+ /** Whether a Machine answers its readiness probe right now. */
144
+ isServing: (machine: FlyMachine) => Promise<boolean>
145
+ /** Add a ready Machine to the caller's routable set. */
146
+ join?: (machine: FlyMachine) => Promise<void>
147
+ /** Remove a Machine from the caller's routable set. */
148
+ leave?: (machine: FlyMachine) => Promise<void>
149
+ /** How long `machine stop` may take. Defaults to 60 s. */
150
+ stopBudgetMs?: number
151
+ }
152
+ ```
153
+
154
+ ### Types
155
+
156
+ #### `FlyCommandRunner`
157
+
158
+ Runs one flyctl command (without the leading `flyctl`).
159
+
160
+ ```typescript
161
+ type FlyCommandRunner = (args: string[]) => Promise<FlyCommandResult>
162
+ ```
163
+
164
+ ### Functions
165
+
166
+ #### `flyctlRunner(options)`
167
+
168
+ A runner that spawns the local `flyctl`.
169
+
170
+ ```typescript
171
+ function flyctlRunner(options?: { cwd?: string }): FlyCommandRunner
172
+ ```
173
+
174
+ - `options` — The working directory flyctl should see.
175
+
176
+ **Returns:** The runner.
177
+
178
+ #### `parseFlyDurationMs(value)`
179
+
180
+ Parse a Fly duration (`500ms`, `5s`, `1m0s`, `1h30m`) into milliseconds.
181
+
182
+ ```typescript
183
+ function parseFlyDurationMs(value: unknown): number
184
+ ```
185
+
186
+ - `value` — The configured value.
187
+
188
+ **Returns:** Milliseconds; 0 when absent or not a duration.
189
+
190
+ #### `serviceCheckGraceMs(machine)`
191
+
192
+ The longest service-check grace period any of a Machine's checks declares.
193
+
194
+ ```typescript
195
+ function serviceCheckGraceMs(machine: unknown): number
196
+ ```
197
+
198
+ - `machine` — One entry from `flyctl machine list --json`.
199
+
200
+ **Returns:** Milliseconds; 0 when the Machine's checks have no grace.
201
+
202
+ #### `parseFlyMachineList(json)`
203
+
204
+ Parse `flyctl machine list --app <app> --json` into the facts a rollout needs.
205
+
206
+ ```typescript
207
+ function parseFlyMachineList(json: string): FlyMachine[]
208
+ ```
209
+
210
+ - `json` — The command's stdout.
211
+
212
+ **Returns:** Every Machine, in the order Fly listed them.
213
+
214
+ #### `assertHomogeneousFlyMachines(machines)`
215
+
216
+ Validate a Machine list as a rollout target set and return what to act on.
217
+
218
+ Every Machine must be started (a stopped one cannot be reached over SSH, and its
219
+ patch volume would keep an older build), and all must run the SAME image and
220
+ configuration version: a mixed set is a deploy in flight, and changing half of it
221
+ would record a binding that is already stale on the other half.
222
+
223
+ ```typescript
224
+ function assertHomogeneousFlyMachines(machines: readonly FlyMachine[]): {
225
+ ids: string[]
226
+ imageRef: string
227
+ version: string
228
+ }
229
+ ```
230
+
231
+ - `machines` — Parsed Machines.
232
+
233
+ **Returns:** The target set's ids, image ref and configuration version.
234
+
235
+ #### `listFlyMachines(options)`
236
+
237
+ List one Fly app's Machines.
238
+
239
+ ```typescript
240
+ function listFlyMachines(options: FlyMachinesOptions): Promise<FlyMachine[]>
241
+ ```
242
+
243
+ - `options` — The app and the runner.
244
+
245
+ **Returns:** Every Machine the app has.
246
+
247
+ #### `restartFlyMachine(options, machineId)`
248
+
249
+ Restart one Machine and wait until it is `started` again.
250
+
251
+ A Machine that comes back `stopped` or `suspended` is started explicitly — Fly
252
+ occasionally parks one after a restart, and a role that leaves it parked turns a
253
+ successful roll into an outage.
254
+
255
+ ```typescript
256
+ function restartFlyMachine(
257
+ options: FlyMachinesOptions & { restartBudgetMs?: number; pollMs?: number },
258
+ machineId: string,
259
+ ): Promise<boolean>
260
+ ```
261
+
262
+ - `options` — The app, the runner and the waits.
263
+ - `machineId` — The Machine to restart.
264
+
265
+ **Returns:** Whether it reached `started` inside the budget.
266
+
267
+ #### `createFlyInPlaceProvider(options)`
268
+
269
+ Create an in-place Fly Machines provider for the rollout core.
270
+
271
+ ```typescript
272
+ function createFlyInPlaceProvider(options: FlyInPlaceOptions): InPlaceInstanceProvider<FlyMachine>
273
+ ```
274
+
275
+ - `options` — The app, the runner, the readiness probe and the restore path.
276
+
277
+ **Returns:** An `InPlaceInstanceProvider` over Fly Machines.
278
+
279
+ #### `createFlyInstanceProvider(options)`
280
+
281
+ Create a grow-then-shrink Fly Machines provider for the rollout core.
282
+
283
+ `create` delegates to the caller's `launch`; `drain` asks Fly to stop the Machine
284
+ (a SIGTERM with a bounded wait), and `destroy` removes it.
285
+
286
+ ```typescript
287
+ function createFlyInstanceProvider(options: FlyInstanceOptions): InstanceProvider<FlyMachine>
288
+ ```
289
+
290
+ - `options` — The app, the runner and the app-specific operations.
291
+
292
+ **Returns:** An `InstanceProvider` over Fly Machines.
293
+
294
+ ## Core Interface
295
+
296
+ Implements `@molecule/api-deploy-rollout` interface.
297
+
298
+ ## Injection Notes
299
+
300
+ ### Requirements
301
+
302
+ Peer dependencies:
303
+
304
+ - `@molecule/api-deploy-rollout` ^1.0.0
305
+
306
+ ### Runtime Dependencies
307
+
308
+ - `@molecule/api-deploy-rollout`
309
+
310
+ - **`parseFlyMachineList` is the only JSON the adapter trusts.** A Machine list
311
+ that is not an array is an error, never an empty set.
312
+ - **A mixed set is refused.** `assertHomogeneousFlyMachines` rejects Machines on
313
+ different images or configuration versions: that is a deploy in flight, and
314
+ changing half of it records a binding that is already stale on the other half.
315
+ - **A restart that parks is started explicitly.** A Machine that comes back
316
+ `stopped`/`suspended` after a restart is started, not left parked.
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=browser-guard.d.ts.map
@@ -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-deploy-rollout-fly` 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-deploy-rollout-fly 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/fly.d.ts ADDED
@@ -0,0 +1,186 @@
1
+ /**
2
+ * Fly Machines adapter for the deploy-rollout core.
3
+ *
4
+ * Two shapes, because Fly supports both deployment topologies:
5
+ *
6
+ * - {@link createFlyInPlaceProvider} — the same Machines restarted onto a new build
7
+ * one at a time, with a restore path. This is what the platform's own deploy tools
8
+ * do today (a patch volume, an image deploy).
9
+ * - {@link createFlyInstanceProvider} — a new Machine cloned beside the old set and
10
+ * retired when it is serving. Used when the deployment changes its instance count.
11
+ *
12
+ * The commands are executed through an injected {@link FlyCommandRunner}, so tests
13
+ * need no Fly account and a caller can decide how flyctl is reached (a checkout
14
+ * directory, a remote builder, a wrapper). What the adapter owns is the Fly-specific
15
+ * part: the command arguments and the `machine list --json` parse.
16
+ *
17
+ * @module
18
+ */
19
+ import type { InPlaceInstanceProvider, InstanceProvider, RolloutInstance } from '@molecule/api-deploy-rollout';
20
+ /** One Fly Machine, as the rollout needs to see it. */
21
+ export interface FlyMachine extends RolloutInstance {
22
+ /** The Machine's Fly state (`started`, `stopped`, …). */
23
+ state: string;
24
+ /** The image the Machine runs, tag or digest form. */
25
+ imageRef: string | null;
26
+ /** The Machine's configuration version (`instance_id`/`version`). */
27
+ version: string | null;
28
+ /**
29
+ * The longest service-check grace period the Machine declares, in milliseconds.
30
+ *
31
+ * Fly reports a check inside its grace window as PASSING and can route traffic
32
+ * to a Machine that has not booted; a rolling restart must know the number to
33
+ * refuse it. Zero when the Machine's checks have no grace.
34
+ */
35
+ gracePeriodMs: number;
36
+ }
37
+ /** The result of one flyctl invocation. */
38
+ export interface FlyCommandResult {
39
+ /** Exit status, or `null` when the process did not exit normally. */
40
+ status: number | null;
41
+ /** Standard output. */
42
+ stdout: string;
43
+ /** Standard error. */
44
+ stderr?: string;
45
+ }
46
+ /** Runs one flyctl command (without the leading `flyctl`). */
47
+ export type FlyCommandRunner = (args: string[]) => Promise<FlyCommandResult>;
48
+ /**
49
+ * A runner that spawns the local `flyctl`.
50
+ *
51
+ * @param options - The working directory flyctl should see.
52
+ * @returns The runner.
53
+ */
54
+ export declare const flyctlRunner: (options?: {
55
+ cwd?: string;
56
+ }) => FlyCommandRunner;
57
+ /**
58
+ * Parse a Fly duration (`500ms`, `5s`, `1m0s`, `1h30m`) into milliseconds.
59
+ *
60
+ * @param value - The configured value.
61
+ * @returns Milliseconds; 0 when absent or not a duration.
62
+ */
63
+ export declare function parseFlyDurationMs(value: unknown): number;
64
+ /**
65
+ * The longest service-check grace period any of a Machine's checks declares.
66
+ *
67
+ * @param machine - One entry from `flyctl machine list --json`.
68
+ * @returns Milliseconds; 0 when the Machine's checks have no grace.
69
+ */
70
+ export declare function serviceCheckGraceMs(machine: unknown): number;
71
+ /**
72
+ * Parse `flyctl machine list --app <app> --json` into the facts a rollout needs.
73
+ *
74
+ * @param json - The command's stdout.
75
+ * @returns Every Machine, in the order Fly listed them.
76
+ * @throws {Error} When the output is not a JSON array.
77
+ */
78
+ export declare const parseFlyMachineList: (json: string) => FlyMachine[];
79
+ /**
80
+ * Validate a Machine list as a rollout target set and return what to act on.
81
+ *
82
+ * Every Machine must be started (a stopped one cannot be reached over SSH, and its
83
+ * patch volume would keep an older build), and all must run the SAME image and
84
+ * configuration version: a mixed set is a deploy in flight, and changing half of it
85
+ * would record a binding that is already stale on the other half.
86
+ *
87
+ * @param machines - Parsed Machines.
88
+ * @returns The target set's ids, image ref and configuration version.
89
+ * @throws {Error} A plain, operator-readable refusal.
90
+ */
91
+ export declare const assertHomogeneousFlyMachines: (machines: readonly FlyMachine[], options?: {
92
+ appName?: string;
93
+ }) => {
94
+ ids: string[];
95
+ imageRef: string;
96
+ version: string;
97
+ };
98
+ /** Where and how the adapter reaches one Fly app. */
99
+ export interface FlyMachinesOptions {
100
+ /** The Fly app name. */
101
+ app: string;
102
+ /** The runner; defaults to spawning the local `flyctl`. */
103
+ run?: FlyCommandRunner;
104
+ }
105
+ /**
106
+ * List one Fly app's Machines.
107
+ *
108
+ * @param options - The app and the runner.
109
+ * @returns Every Machine the app has.
110
+ * @throws {Error} When flyctl refuses or its output is unreadable.
111
+ */
112
+ export declare const listFlyMachines: (options: FlyMachinesOptions) => Promise<FlyMachine[]>;
113
+ /**
114
+ * What an in-place Fly rollout supplies that Fly itself does not know.
115
+ *
116
+ * The adapter knows how to list, restart and start a Machine. Whether a Machine is
117
+ * SERVING, what "replace" means (a patch volume swap, a new image) and how to undo it
118
+ * are properties of the app being deployed, so the caller states them.
119
+ */
120
+ export interface FlyInPlaceOptions extends FlyMachinesOptions {
121
+ /** Whether a Machine answers its readiness probe right now. */
122
+ isServing: (machineId: string) => Promise<boolean>;
123
+ /**
124
+ * Change one Machine to the new build and leave it serving. Defaults to a restart
125
+ * that waits for the Machine to reach `started`.
126
+ */
127
+ replace?: (machineId: string) => Promise<void>;
128
+ /** Put one Machine back on the old build. */
129
+ restore?: (machineId: string) => Promise<void>;
130
+ /** How long a restart may take to reach `started`. Defaults to 6 minutes. */
131
+ restartBudgetMs?: number;
132
+ /** Sleep between state polls. Defaults to 5000 ms. */
133
+ pollMs?: number;
134
+ }
135
+ /**
136
+ * Restart one Machine and wait until it is `started` again.
137
+ *
138
+ * A Machine that comes back `stopped` or `suspended` is started explicitly — Fly
139
+ * occasionally parks one after a restart, and a role that leaves it parked turns a
140
+ * successful roll into an outage.
141
+ *
142
+ * @param options - The app, the runner and the waits.
143
+ * @param machineId - The Machine to restart.
144
+ * @returns Whether it reached `started` inside the budget.
145
+ */
146
+ export declare const restartFlyMachine: (options: FlyMachinesOptions & {
147
+ restartBudgetMs?: number;
148
+ pollMs?: number;
149
+ }, machineId: string) => Promise<boolean>;
150
+ /**
151
+ * Create an in-place Fly Machines provider for the rollout core.
152
+ *
153
+ * @param options - The app, the runner, the readiness probe and the restore path.
154
+ * @returns An `InPlaceInstanceProvider` over Fly Machines.
155
+ */
156
+ export declare const createFlyInPlaceProvider: (options: FlyInPlaceOptions) => InPlaceInstanceProvider<FlyMachine>;
157
+ /**
158
+ * What a grow-then-shrink Fly rollout supplies that Fly itself does not know.
159
+ *
160
+ * `launch` builds the Machine (image, volume, env, mounts) — that is the app's
161
+ * deployment recipe. `join`/`leave` change whatever edge routes to the app; Fly's own
162
+ * proxy balances by service, not by a caller-held set.
163
+ */
164
+ export interface FlyInstanceOptions extends FlyMachinesOptions {
165
+ /** Create the Machine for `index` and resolve once it exists. */
166
+ launch: (index: number) => Promise<FlyMachine>;
167
+ /** Whether a Machine answers its readiness probe right now. */
168
+ isServing: (machine: FlyMachine) => Promise<boolean>;
169
+ /** Add a ready Machine to the caller's routable set. */
170
+ join?: (machine: FlyMachine) => Promise<void>;
171
+ /** Remove a Machine from the caller's routable set. */
172
+ leave?: (machine: FlyMachine) => Promise<void>;
173
+ /** How long `machine stop` may take. Defaults to 60 s. */
174
+ stopBudgetMs?: number;
175
+ }
176
+ /**
177
+ * Create a grow-then-shrink Fly Machines provider for the rollout core.
178
+ *
179
+ * `create` delegates to the caller's `launch`; `drain` asks Fly to stop the Machine
180
+ * (a SIGTERM with a bounded wait), and `destroy` removes it.
181
+ *
182
+ * @param options - The app, the runner and the app-specific operations.
183
+ * @returns An `InstanceProvider` over Fly Machines.
184
+ */
185
+ export declare const createFlyInstanceProvider: (options: FlyInstanceOptions) => InstanceProvider<FlyMachine>;
186
+ //# sourceMappingURL=fly.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fly.d.ts","sourceRoot":"","sources":["../src/fly.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAIH,OAAO,KAAK,EACV,uBAAuB,EACvB,gBAAgB,EAChB,eAAe,EAChB,MAAM,8BAA8B,CAAA;AAErC,uDAAuD;AACvD,MAAM,WAAW,UAAW,SAAQ,eAAe;IACjD,yDAAyD;IACzD,KAAK,EAAE,MAAM,CAAA;IACb,sDAAsD;IACtD,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAA;IACvB,qEAAqE;IACrE,OAAO,EAAE,MAAM,GAAG,IAAI,CAAA;IACtB;;;;;;OAMG;IACH,aAAa,EAAE,MAAM,CAAA;CACtB;AAED,2CAA2C;AAC3C,MAAM,WAAW,gBAAgB;IAC/B,qEAAqE;IACrE,MAAM,EAAE,MAAM,GAAG,IAAI,CAAA;IACrB,uBAAuB;IACvB,MAAM,EAAE,MAAM,CAAA;IACd,sBAAsB;IACtB,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB;AAED,8DAA8D;AAC9D,MAAM,MAAM,gBAAgB,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,OAAO,CAAC,gBAAgB,CAAC,CAAA;AAE5E;;;;;GAKG;AACH,eAAO,MAAM,YAAY,GAAI,UAAS;IAAE,GAAG,CAAC,EAAE,MAAM,CAAA;CAAO,KAAG,gBAiB7D,CAAA;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAUzD;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,CAa5D;AAED;;;;;;GAMG;AACH,eAAO,MAAM,mBAAmB,GAAI,MAAM,MAAM,KAAG,UAAU,EAwC5D,CAAA;AAED;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,4BAA4B,GACvC,UAAU,SAAS,UAAU,EAAE,EAC/B,UAAS;IAAE,OAAO,CAAC,EAAE,MAAM,CAAA;CAAO,KACjC;IAAE,GAAG,EAAE,MAAM,EAAE,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAyCpD,CAAA;AAED,qDAAqD;AACrD,MAAM,WAAW,kBAAkB;IACjC,wBAAwB;IACxB,GAAG,EAAE,MAAM,CAAA;IACX,2DAA2D;IAC3D,GAAG,CAAC,EAAE,gBAAgB,CAAA;CACvB;AAED;;;;;;GAMG;AACH,eAAO,MAAM,eAAe,GAAU,SAAS,kBAAkB,KAAG,OAAO,CAAC,UAAU,EAAE,CASvF,CAAA;AAED;;;;;;GAMG;AACH,MAAM,WAAW,iBAAkB,SAAQ,kBAAkB;IAC3D,+DAA+D;IAC/D,SAAS,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;IAClD;;;OAGG;IACH,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IAC9C,6CAA6C;IAC7C,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IAC9C,6EAA6E;IAC7E,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,sDAAsD;IACtD,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB;AAED;;;;;;;;;;GAUG;AACH,eAAO,MAAM,iBAAiB,GAC5B,SAAS,kBAAkB,GAAG;IAAE,eAAe,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,EAC3E,WAAW,MAAM,KAChB,OAAO,CAAC,OAAO,CAkBjB,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,wBAAwB,GACnC,SAAS,iBAAiB,KACzB,uBAAuB,CAAC,UAAU,CAqBpC,CAAA;AAED;;;;;;GAMG;AACH,MAAM,WAAW,kBAAmB,SAAQ,kBAAkB;IAC5D,iEAAiE;IACjE,MAAM,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,UAAU,CAAC,CAAA;IAC9C,+DAA+D;IAC/D,SAAS,EAAE,CAAC,OAAO,EAAE,UAAU,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;IACpD,wDAAwD;IACxD,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,UAAU,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IAC7C,uDAAuD;IACvD,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,UAAU,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IAC9C,0DAA0D;IAC1D,YAAY,CAAC,EAAE,MAAM,CAAA;CACtB;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,yBAAyB,GACpC,SAAS,kBAAkB,KAC1B,gBAAgB,CAAC,UAAU,CA8B7B,CAAA"}
package/dist/fly.js ADDED
@@ -0,0 +1,281 @@
1
+ /**
2
+ * Fly Machines adapter for the deploy-rollout core.
3
+ *
4
+ * Two shapes, because Fly supports both deployment topologies:
5
+ *
6
+ * - {@link createFlyInPlaceProvider} — the same Machines restarted onto a new build
7
+ * one at a time, with a restore path. This is what the platform's own deploy tools
8
+ * do today (a patch volume, an image deploy).
9
+ * - {@link createFlyInstanceProvider} — a new Machine cloned beside the old set and
10
+ * retired when it is serving. Used when the deployment changes its instance count.
11
+ *
12
+ * The commands are executed through an injected {@link FlyCommandRunner}, so tests
13
+ * need no Fly account and a caller can decide how flyctl is reached (a checkout
14
+ * directory, a remote builder, a wrapper). What the adapter owns is the Fly-specific
15
+ * part: the command arguments and the `machine list --json` parse.
16
+ *
17
+ * @module
18
+ */
19
+ import { execFile } from 'node:child_process';
20
+ /**
21
+ * A runner that spawns the local `flyctl`.
22
+ *
23
+ * @param options - The working directory flyctl should see.
24
+ * @returns The runner.
25
+ */
26
+ export const flyctlRunner = (options = {}) => {
27
+ return async (args) => {
28
+ return new Promise((resolve) => {
29
+ execFile('flyctl', args, { cwd: options.cwd, maxBuffer: 32 * 1024 * 1024, timeout: 300_000 }, (error, stdout, stderr) => {
30
+ resolve({
31
+ status: error ? (error.code ?? null) : 0,
32
+ stdout: String(stdout ?? ''),
33
+ stderr: String(stderr ?? ''),
34
+ });
35
+ });
36
+ });
37
+ };
38
+ };
39
+ /**
40
+ * Parse a Fly duration (`500ms`, `5s`, `1m0s`, `1h30m`) into milliseconds.
41
+ *
42
+ * @param value - The configured value.
43
+ * @returns Milliseconds; 0 when absent or not a duration.
44
+ */
45
+ export function parseFlyDurationMs(value) {
46
+ if (typeof value !== 'string')
47
+ return 0;
48
+ let total = 0;
49
+ let matched = false;
50
+ for (const match of value.matchAll(/(\d+)(ms|s|m|h)/g)) {
51
+ matched = true;
52
+ const scale = { ms: 1, s: 1_000, m: 60_000, h: 3_600_000 }[match[2] ?? ''] ?? 0;
53
+ total += Number(match[1] ?? 0) * scale;
54
+ }
55
+ return matched ? total : 0;
56
+ }
57
+ /**
58
+ * The longest service-check grace period any of a Machine's checks declares.
59
+ *
60
+ * @param machine - One entry from `flyctl machine list --json`.
61
+ * @returns Milliseconds; 0 when the Machine's checks have no grace.
62
+ */
63
+ export function serviceCheckGraceMs(machine) {
64
+ let longest = 0;
65
+ const services = machine?.config?.services ?? [];
66
+ for (const service of services) {
67
+ const checks = service?.checks ?? [];
68
+ for (const check of checks) {
69
+ longest = Math.max(longest, parseFlyDurationMs(check?.grace_period));
70
+ }
71
+ }
72
+ return longest;
73
+ }
74
+ /**
75
+ * Parse `flyctl machine list --app <app> --json` into the facts a rollout needs.
76
+ *
77
+ * @param json - The command's stdout.
78
+ * @returns Every Machine, in the order Fly listed them.
79
+ * @throws {Error} When the output is not a JSON array.
80
+ */
81
+ export const parseFlyMachineList = (json) => {
82
+ let parsed;
83
+ try {
84
+ parsed = JSON.parse(json);
85
+ }
86
+ catch (error) {
87
+ throw new Error(`could not parse 'flyctl machine list --json': ${error.message}`, {
88
+ cause: error,
89
+ });
90
+ }
91
+ if (!Array.isArray(parsed))
92
+ throw new Error('flyctl machine list did not return an array');
93
+ return parsed.map((machine) => {
94
+ const config = machine?.config;
95
+ // `config.image` is the live shape; `image_ref` is what older flyctl output
96
+ // (and the fixtures) carry at the top level.
97
+ const image = config?.image ?? machine?.image_ref;
98
+ let imageRef = null;
99
+ if (typeof image === 'string')
100
+ imageRef = image;
101
+ else if (image && typeof image.digest === 'string') {
102
+ // A Machine deployed BY DIGEST reports no tag; the tag form would be
103
+ // `…:undefined`, which never matches the Machine's real FLY_IMAGE_REF.
104
+ const ref = image;
105
+ imageRef = `${String(ref.registry)}/${String(ref.repository)}@${String(ref.digest)}`;
106
+ }
107
+ else if (image) {
108
+ const ref = image;
109
+ imageRef = `${String(ref.registry)}/${String(ref.repository)}:${String(ref.tag)}`;
110
+ }
111
+ const id = typeof machine?.id === 'string' ? machine.id : '';
112
+ const version = typeof (machine?.instance_id ?? machine?.version) === 'string'
113
+ ? (machine.instance_id ?? machine.version)
114
+ : null;
115
+ return {
116
+ id,
117
+ upstreamUrl: undefined,
118
+ state: typeof machine?.state === 'string' ? machine.state : '',
119
+ imageRef,
120
+ version,
121
+ gracePeriodMs: serviceCheckGraceMs(machine),
122
+ };
123
+ });
124
+ };
125
+ /**
126
+ * Validate a Machine list as a rollout target set and return what to act on.
127
+ *
128
+ * Every Machine must be started (a stopped one cannot be reached over SSH, and its
129
+ * patch volume would keep an older build), and all must run the SAME image and
130
+ * configuration version: a mixed set is a deploy in flight, and changing half of it
131
+ * would record a binding that is already stale on the other half.
132
+ *
133
+ * @param machines - Parsed Machines.
134
+ * @returns The target set's ids, image ref and configuration version.
135
+ * @throws {Error} A plain, operator-readable refusal.
136
+ */
137
+ export const assertHomogeneousFlyMachines = (machines, options = {}) => {
138
+ const app = options.appName ?? 'the app';
139
+ if (machines.length === 0)
140
+ throw new Error(`${app} has no Machines`);
141
+ const stopped = machines.filter((machine) => machine.state !== 'started');
142
+ if (stopped.length > 0) {
143
+ throw new Error(`${app} machine(s) ${stopped.map((m) => `${m.id} (${m.state})`).join(', ')} are not ` +
144
+ 'started — start them before rolling so every Machine gets the change');
145
+ }
146
+ for (const machine of machines) {
147
+ if (!/^[0-9a-f]{14}$/.test(machine.id)) {
148
+ throw new Error(`unexpected machine id from flyctl: ${JSON.stringify(machine.id)}`);
149
+ }
150
+ if (!machine.imageRef) {
151
+ throw new Error(`machine ${machine.id} has no readable image ref — a change that cannot name its image ` +
152
+ 'would outlive it');
153
+ }
154
+ if (!machine.version) {
155
+ throw new Error(`machine ${machine.id} has no configuration version (instance_id/version) — a change ` +
156
+ 'bound only to the image ref survives a same-tag redeploy');
157
+ }
158
+ }
159
+ const imageRefs = [...new Set(machines.map((machine) => machine.imageRef))];
160
+ const versions = [...new Set(machines.map((machine) => machine.version))];
161
+ if (imageRefs.length > 1 || versions.length > 1) {
162
+ throw new Error(`${app} Machines are running MIXED builds ` +
163
+ `(images: ${imageRefs.join(', ')}; versions: ${versions.join(', ')}) — a deploy is in ` +
164
+ 'flight or a Machine was started separately. Wait for it to settle, then re-run.');
165
+ }
166
+ return {
167
+ ids: machines.map((machine) => machine.id),
168
+ imageRef: imageRefs[0],
169
+ version: versions[0],
170
+ };
171
+ };
172
+ /**
173
+ * List one Fly app's Machines.
174
+ *
175
+ * @param options - The app and the runner.
176
+ * @returns Every Machine the app has.
177
+ * @throws {Error} When flyctl refuses or its output is unreadable.
178
+ */
179
+ export const listFlyMachines = async (options) => {
180
+ const run = options.run ?? flyctlRunner();
181
+ const result = await run(['machine', 'list', '--app', options.app, '--json']);
182
+ if (result.status !== 0) {
183
+ throw new Error(`flyctl machine list failed for ${options.app}: ${(result.stderr ?? '').trim().slice(0, 300)}`);
184
+ }
185
+ return parseFlyMachineList(result.stdout);
186
+ };
187
+ /**
188
+ * Restart one Machine and wait until it is `started` again.
189
+ *
190
+ * A Machine that comes back `stopped` or `suspended` is started explicitly — Fly
191
+ * occasionally parks one after a restart, and a role that leaves it parked turns a
192
+ * successful roll into an outage.
193
+ *
194
+ * @param options - The app, the runner and the waits.
195
+ * @param machineId - The Machine to restart.
196
+ * @returns Whether it reached `started` inside the budget.
197
+ */
198
+ export const restartFlyMachine = async (options, machineId) => {
199
+ const run = options.run ?? flyctlRunner();
200
+ const budgetMs = Math.max(0, options.restartBudgetMs ?? 6 * 60_000);
201
+ const pollMs = Math.max(1, options.pollMs ?? 5_000);
202
+ await run(['machine', 'restart', machineId, '--app', options.app]);
203
+ for (let waited = 0; waited <= budgetMs; waited += pollMs) {
204
+ const state = (await listFlyMachines({ app: options.app, run })).find((machine) => machine.id === machineId)?.state;
205
+ if (state === 'started')
206
+ return true;
207
+ if (state === 'stopped' || state === 'suspended') {
208
+ await run(['machine', 'start', machineId, '--app', options.app]);
209
+ }
210
+ await new Promise((resolve) => {
211
+ setTimeout(resolve, pollMs);
212
+ });
213
+ }
214
+ return false;
215
+ };
216
+ /**
217
+ * Create an in-place Fly Machines provider for the rollout core.
218
+ *
219
+ * @param options - The app, the runner, the readiness probe and the restore path.
220
+ * @returns An `InPlaceInstanceProvider` over Fly Machines.
221
+ */
222
+ export const createFlyInPlaceProvider = (options) => {
223
+ const run = options.run ?? flyctlRunner();
224
+ return {
225
+ name: `fly:${options.app}`,
226
+ list: () => listFlyMachines({ app: options.app, run }),
227
+ isServing: (machine) => options.isServing(machine.id),
228
+ replace: async (machine) => {
229
+ if (options.replace)
230
+ return options.replace(machine.id);
231
+ const started = await restartFlyMachine({ app: options.app, run, restartBudgetMs: options.restartBudgetMs, pollMs: options.pollMs }, machine.id);
232
+ if (!started)
233
+ throw new Error(`machine ${machine.id} did not reach started after a restart`);
234
+ },
235
+ restore: async (machine) => {
236
+ if (!options.restore) {
237
+ throw new Error('Fly in-place rollout has no restore path — pass options.restore');
238
+ }
239
+ return options.restore(machine.id);
240
+ },
241
+ };
242
+ };
243
+ /**
244
+ * Create a grow-then-shrink Fly Machines provider for the rollout core.
245
+ *
246
+ * `create` delegates to the caller's `launch`; `drain` asks Fly to stop the Machine
247
+ * (a SIGTERM with a bounded wait), and `destroy` removes it.
248
+ *
249
+ * @param options - The app, the runner and the app-specific operations.
250
+ * @returns An `InstanceProvider` over Fly Machines.
251
+ */
252
+ export const createFlyInstanceProvider = (options) => {
253
+ const run = options.run ?? flyctlRunner();
254
+ return {
255
+ name: `fly:${options.app}`,
256
+ list: () => listFlyMachines({ app: options.app, run }),
257
+ create: (index) => options.launch(index),
258
+ waitReady: async (machine) => options.isServing(machine),
259
+ isServing: (machine) => options.isServing(machine),
260
+ join: async (machine) => options.join?.(machine),
261
+ leave: async (machine) => options.leave?.(machine),
262
+ drain: async (machine, drainMs) => {
263
+ await run(['machine', 'stop', machine.id, '--app', options.app]);
264
+ const budget = Math.min(drainMs, options.stopBudgetMs ?? 60_000);
265
+ const pollMs = 2_000;
266
+ for (let waited = 0; waited <= budget; waited += pollMs) {
267
+ const state = (await listFlyMachines({ app: options.app, run })).find((candidate) => candidate.id === machine.id)?.state;
268
+ if (state === 'stopped' || state === 'destroyed' || state === undefined)
269
+ return;
270
+ await new Promise((resolve) => {
271
+ setTimeout(resolve, pollMs);
272
+ });
273
+ }
274
+ // The stop is best-effort by design: a Machine that will not stop is still
275
+ // destroyed next, and the rollout must not hang on it.
276
+ },
277
+ destroy: async (machine) => {
278
+ await run(['machine', 'destroy', machine.id, '--app', options.app, '--force']);
279
+ },
280
+ };
281
+ };
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Fly Machines provider bonds for the deploy-rollout core.
3
+ *
4
+ * In-place (restart the same Machines one at a time, with a restore path) and
5
+ * grow-then-shrink (clone a Machine beside the old set, retire the old one when the
6
+ * new one serves). Commands run through an injected runner, so tests need no Fly
7
+ * account.
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * import { runInPlaceRollout, setProvider } from '@molecule/api-deploy-rollout'
12
+ * import { provider } from '@molecule/api-deploy-rollout-default'
13
+ * import { createFlyInPlaceProvider } from '@molecule/api-deploy-rollout-fly'
14
+ *
15
+ * setProvider(provider)
16
+ * await runInPlaceRollout({
17
+ * provider: createFlyInPlaceProvider({
18
+ * app: 'molecule-api',
19
+ * isServing: (id) => probeMachine(id),
20
+ * restore: (id) => clearPatchAndRestart(id),
21
+ * }),
22
+ * policy: { soakMs: 30_000 },
23
+ * })
24
+ * ```
25
+ *
26
+ * @remarks
27
+ * - **`parseFlyMachineList` is the only JSON the adapter trusts.** A Machine list
28
+ * that is not an array is an error, never an empty set.
29
+ * - **A mixed set is refused.** `assertHomogeneousFlyMachines` rejects Machines on
30
+ * different images or configuration versions: that is a deploy in flight, and
31
+ * changing half of it records a binding that is already stale on the other half.
32
+ * - **A restart that parks is started explicitly.** A Machine that comes back
33
+ * `stopped`/`suspended` after a restart is started, not left parked.
34
+ *
35
+ * @module
36
+ */
37
+ export * from './browser-guard.js';
38
+ export * from './fly.js';
39
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,UAAU,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Fly Machines provider bonds for the deploy-rollout core.
3
+ *
4
+ * In-place (restart the same Machines one at a time, with a restore path) and
5
+ * grow-then-shrink (clone a Machine beside the old set, retire the old one when the
6
+ * new one serves). Commands run through an injected runner, so tests need no Fly
7
+ * account.
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * import { runInPlaceRollout, setProvider } from '@molecule/api-deploy-rollout'
12
+ * import { provider } from '@molecule/api-deploy-rollout-default'
13
+ * import { createFlyInPlaceProvider } from '@molecule/api-deploy-rollout-fly'
14
+ *
15
+ * setProvider(provider)
16
+ * await runInPlaceRollout({
17
+ * provider: createFlyInPlaceProvider({
18
+ * app: 'molecule-api',
19
+ * isServing: (id) => probeMachine(id),
20
+ * restore: (id) => clearPatchAndRestart(id),
21
+ * }),
22
+ * policy: { soakMs: 30_000 },
23
+ * })
24
+ * ```
25
+ *
26
+ * @remarks
27
+ * - **`parseFlyMachineList` is the only JSON the adapter trusts.** A Machine list
28
+ * that is not an array is an error, never an empty set.
29
+ * - **A mixed set is refused.** `assertHomogeneousFlyMachines` rejects Machines on
30
+ * different images or configuration versions: that is a deploy in flight, and
31
+ * changing half of it records a binding that is already stale on the other half.
32
+ * - **A restart that parks is started explicitly.** A Machine that comes back
33
+ * `stopped`/`suspended` after a restart is started, not left parked.
34
+ *
35
+ * @module
36
+ */
37
+ export * from './browser-guard.js';
38
+ export * from './fly.js';
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@molecule/api-deploy-rollout-fly",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1-stage",
4
+ "description": "Fly Machines provider bond for @molecule/api-deploy-rollout: in-place restarts with a restore path and grow-then-shrink clones, over an injected flyctl runner.",
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
+ "deploy",
28
+ "rollout",
29
+ "fly",
30
+ "fly machines"
31
+ ],
32
+ "author": "Molecule Dev, Inc. (https://molecule.dev)",
33
+ "license": "Apache-2.0",
34
+ "engines": {
35
+ "node": ">=20"
36
+ },
37
+ "peerDependencies": {
38
+ "@molecule/api-deploy-rollout": "^1.0.0"
39
+ },
40
+ "devDependencies": {
41
+ "@molecule/api-deploy-rollout": "1.0.0",
42
+ "@types/node": "26.1.2",
43
+ "typescript": "6.0.3",
44
+ "vitest": "4.1.11"
45
+ },
46
+ "repository": {
47
+ "type": "git",
48
+ "url": "https://github.com/molecule-dev/molecule.git",
49
+ "directory": "packages/api/bonds/deploy-rollout/fly"
50
+ },
51
+ "homepage": "https://www.molecule.dev/packages/api-deploy-rollout-fly",
52
+ "bugs": "https://github.com/molecule-dev/molecule/issues",
53
+ "publishConfig": {
54
+ "access": "public"
55
+ }
56
+ }