@alchemy.run/fly 0.0.0-stage → 2.0.0-beta.84

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.
Files changed (499) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +61 -2
  3. package/lib/App.d.ts +230 -0
  4. package/lib/App.d.ts.map +1 -0
  5. package/lib/App.js +340 -0
  6. package/lib/App.js.map +1 -0
  7. package/lib/AuthProvider.d.ts +22 -0
  8. package/lib/AuthProvider.d.ts.map +1 -0
  9. package/lib/AuthProvider.js +48 -0
  10. package/lib/AuthProvider.js.map +1 -0
  11. package/lib/BindService.d.ts +159 -0
  12. package/lib/BindService.d.ts.map +1 -0
  13. package/lib/BindService.js +222 -0
  14. package/lib/BindService.js.map +1 -0
  15. package/lib/Bootstrap.d.ts +8 -0
  16. package/lib/Bootstrap.d.ts.map +1 -0
  17. package/lib/Bootstrap.js +41 -0
  18. package/lib/Bootstrap.js.map +1 -0
  19. package/lib/Bucket.d.ts +278 -0
  20. package/lib/Bucket.d.ts.map +1 -0
  21. package/lib/Bucket.js +658 -0
  22. package/lib/Bucket.js.map +1 -0
  23. package/lib/BucketBinding.d.ts +33 -0
  24. package/lib/BucketBinding.d.ts.map +1 -0
  25. package/lib/BucketBinding.js +70 -0
  26. package/lib/BucketBinding.js.map +1 -0
  27. package/lib/Catalog.d.ts +28 -0
  28. package/lib/Catalog.d.ts.map +1 -0
  29. package/lib/Catalog.js +31 -0
  30. package/lib/Catalog.js.map +1 -0
  31. package/lib/Certificate.d.ts +189 -0
  32. package/lib/Certificate.d.ts.map +1 -0
  33. package/lib/Certificate.js +380 -0
  34. package/lib/Certificate.js.map +1 -0
  35. package/lib/Checkpoint.d.ts +55 -0
  36. package/lib/Checkpoint.d.ts.map +1 -0
  37. package/lib/Checkpoint.js +3 -0
  38. package/lib/Checkpoint.js.map +1 -0
  39. package/lib/CheckpointHttp.d.ts +22 -0
  40. package/lib/CheckpointHttp.d.ts.map +1 -0
  41. package/lib/CheckpointHttp.js +53 -0
  42. package/lib/CheckpointHttp.js.map +1 -0
  43. package/lib/ConnectPostgres.d.ts +58 -0
  44. package/lib/ConnectPostgres.d.ts.map +1 -0
  45. package/lib/ConnectPostgres.js +13 -0
  46. package/lib/ConnectPostgres.js.map +1 -0
  47. package/lib/ConnectPostgresHttp.d.ts +26 -0
  48. package/lib/ConnectPostgresHttp.d.ts.map +1 -0
  49. package/lib/ConnectPostgresHttp.js +57 -0
  50. package/lib/ConnectPostgresHttp.js.map +1 -0
  51. package/lib/Contributions.d.ts +7 -0
  52. package/lib/Contributions.d.ts.map +1 -0
  53. package/lib/Contributions.js +6 -0
  54. package/lib/Contributions.js.map +1 -0
  55. package/lib/Credentials.d.ts +33 -0
  56. package/lib/Credentials.d.ts.map +1 -0
  57. package/lib/Credentials.js +59 -0
  58. package/lib/Credentials.js.map +1 -0
  59. package/lib/Decrypt.d.ts +52 -0
  60. package/lib/Decrypt.d.ts.map +1 -0
  61. package/lib/Decrypt.js +3 -0
  62. package/lib/Decrypt.js.map +1 -0
  63. package/lib/DecryptHttp.d.ts +22 -0
  64. package/lib/DecryptHttp.d.ts.map +1 -0
  65. package/lib/DecryptHttp.js +43 -0
  66. package/lib/DecryptHttp.js.map +1 -0
  67. package/lib/DeleteObject.d.ts +29 -0
  68. package/lib/DeleteObject.d.ts.map +1 -0
  69. package/lib/DeleteObject.js +3 -0
  70. package/lib/DeleteObject.js.map +1 -0
  71. package/lib/DeleteObjectHttp.d.ts +12 -0
  72. package/lib/DeleteObjectHttp.d.ts.map +1 -0
  73. package/lib/DeleteObjectHttp.js +17 -0
  74. package/lib/DeleteObjectHttp.js.map +1 -0
  75. package/lib/Deployment.d.ts +51 -0
  76. package/lib/Deployment.d.ts.map +1 -0
  77. package/lib/Deployment.js +62 -0
  78. package/lib/Deployment.js.map +1 -0
  79. package/lib/DeploymentImages.d.ts +18 -0
  80. package/lib/DeploymentImages.d.ts.map +1 -0
  81. package/lib/DeploymentImages.js +61 -0
  82. package/lib/DeploymentImages.js.map +1 -0
  83. package/lib/DeploymentState.d.ts +17 -0
  84. package/lib/DeploymentState.d.ts.map +1 -0
  85. package/lib/DeploymentState.js +87 -0
  86. package/lib/DeploymentState.js.map +1 -0
  87. package/lib/Encrypt.d.ts +50 -0
  88. package/lib/Encrypt.d.ts.map +1 -0
  89. package/lib/Encrypt.js +3 -0
  90. package/lib/Encrypt.js.map +1 -0
  91. package/lib/EncryptHttp.d.ts +22 -0
  92. package/lib/EncryptHttp.d.ts.map +1 -0
  93. package/lib/EncryptHttp.js +39 -0
  94. package/lib/EncryptHttp.js.map +1 -0
  95. package/lib/Environment.d.ts +45 -0
  96. package/lib/Environment.d.ts.map +1 -0
  97. package/lib/Environment.js +43 -0
  98. package/lib/Environment.js.map +1 -0
  99. package/lib/Errors.d.ts +18 -0
  100. package/lib/Errors.d.ts.map +1 -0
  101. package/lib/Errors.js +13 -0
  102. package/lib/Errors.js.map +1 -0
  103. package/lib/Exec.d.ts +41 -0
  104. package/lib/Exec.d.ts.map +1 -0
  105. package/lib/Exec.js +3 -0
  106. package/lib/Exec.js.map +1 -0
  107. package/lib/ExecHttp.d.ts +22 -0
  108. package/lib/ExecHttp.d.ts.map +1 -0
  109. package/lib/ExecHttp.js +39 -0
  110. package/lib/ExecHttp.js.map +1 -0
  111. package/lib/GetObject.d.ts +34 -0
  112. package/lib/GetObject.d.ts.map +1 -0
  113. package/lib/GetObject.js +3 -0
  114. package/lib/GetObject.js.map +1 -0
  115. package/lib/GetObjectHttp.d.ts +12 -0
  116. package/lib/GetObjectHttp.d.ts.map +1 -0
  117. package/lib/GetObjectHttp.js +17 -0
  118. package/lib/GetObjectHttp.js.map +1 -0
  119. package/lib/GetSecret.d.ts +44 -0
  120. package/lib/GetSecret.d.ts.map +1 -0
  121. package/lib/GetSecret.js +3 -0
  122. package/lib/GetSecret.js.map +1 -0
  123. package/lib/GetSecretHttp.d.ts +22 -0
  124. package/lib/GetSecretHttp.d.ts.map +1 -0
  125. package/lib/GetSecretHttp.js +50 -0
  126. package/lib/GetSecretHttp.js.map +1 -0
  127. package/lib/HeadObject.d.ts +29 -0
  128. package/lib/HeadObject.d.ts.map +1 -0
  129. package/lib/HeadObject.js +3 -0
  130. package/lib/HeadObject.js.map +1 -0
  131. package/lib/HeadObjectHttp.d.ts +12 -0
  132. package/lib/HeadObjectHttp.d.ts.map +1 -0
  133. package/lib/HeadObjectHttp.js +17 -0
  134. package/lib/HeadObjectHttp.js.map +1 -0
  135. package/lib/IpAssignment.d.ts +258 -0
  136. package/lib/IpAssignment.d.ts.map +1 -0
  137. package/lib/IpAssignment.js +376 -0
  138. package/lib/IpAssignment.js.map +1 -0
  139. package/lib/ListObjectsV2.d.ts +29 -0
  140. package/lib/ListObjectsV2.d.ts.map +1 -0
  141. package/lib/ListObjectsV2.js +3 -0
  142. package/lib/ListObjectsV2.js.map +1 -0
  143. package/lib/ListObjectsV2Http.d.ts +12 -0
  144. package/lib/ListObjectsV2Http.d.ts.map +1 -0
  145. package/lib/ListObjectsV2Http.js +17 -0
  146. package/lib/ListObjectsV2Http.js.map +1 -0
  147. package/lib/ListSecrets.d.ts +53 -0
  148. package/lib/ListSecrets.d.ts.map +1 -0
  149. package/lib/ListSecrets.js +3 -0
  150. package/lib/ListSecrets.js.map +1 -0
  151. package/lib/ListSecretsHttp.d.ts +22 -0
  152. package/lib/ListSecretsHttp.d.ts.map +1 -0
  153. package/lib/ListSecretsHttp.js +35 -0
  154. package/lib/ListSecretsHttp.js.map +1 -0
  155. package/lib/Machine.d.ts +802 -0
  156. package/lib/Machine.d.ts.map +1 -0
  157. package/lib/Machine.js +773 -0
  158. package/lib/Machine.js.map +1 -0
  159. package/lib/MachineContainers.d.ts +44 -0
  160. package/lib/MachineContainers.d.ts.map +1 -0
  161. package/lib/MachineContainers.js +115 -0
  162. package/lib/MachineContainers.js.map +1 -0
  163. package/lib/Metadata.d.ts +109 -0
  164. package/lib/Metadata.d.ts.map +1 -0
  165. package/lib/Metadata.js +159 -0
  166. package/lib/Metadata.js.map +1 -0
  167. package/lib/MountVolume.d.ts +295 -0
  168. package/lib/MountVolume.d.ts.map +1 -0
  169. package/lib/MountVolume.js +20 -0
  170. package/lib/MountVolume.js.map +1 -0
  171. package/lib/Postgres.d.ts +298 -0
  172. package/lib/Postgres.d.ts.map +1 -0
  173. package/lib/Postgres.js +508 -0
  174. package/lib/Postgres.js.map +1 -0
  175. package/lib/PostgresMigrations.d.ts +35 -0
  176. package/lib/PostgresMigrations.d.ts.map +1 -0
  177. package/lib/PostgresMigrations.js +110 -0
  178. package/lib/PostgresMigrations.js.map +1 -0
  179. package/lib/Providers.d.ts +38 -0
  180. package/lib/Providers.d.ts.map +1 -0
  181. package/lib/Providers.js +95 -0
  182. package/lib/Providers.js.map +1 -0
  183. package/lib/PutObject.d.ts +35 -0
  184. package/lib/PutObject.d.ts.map +1 -0
  185. package/lib/PutObject.js +3 -0
  186. package/lib/PutObject.js.map +1 -0
  187. package/lib/PutObjectHttp.d.ts +12 -0
  188. package/lib/PutObjectHttp.d.ts.map +1 -0
  189. package/lib/PutObjectHttp.js +17 -0
  190. package/lib/PutObjectHttp.js.map +1 -0
  191. package/lib/ReadRedis.d.ts +26 -0
  192. package/lib/ReadRedis.d.ts.map +1 -0
  193. package/lib/ReadRedis.js +3 -0
  194. package/lib/ReadRedis.js.map +1 -0
  195. package/lib/ReadRedisHttp.d.ts +11 -0
  196. package/lib/ReadRedisHttp.d.ts.map +1 -0
  197. package/lib/ReadRedisHttp.js +15 -0
  198. package/lib/ReadRedisHttp.js.map +1 -0
  199. package/lib/ReadWriteRedis.d.ts +29 -0
  200. package/lib/ReadWriteRedis.d.ts.map +1 -0
  201. package/lib/ReadWriteRedis.js +3 -0
  202. package/lib/ReadWriteRedis.js.map +1 -0
  203. package/lib/ReadWriteRedisHttp.d.ts +11 -0
  204. package/lib/ReadWriteRedisHttp.d.ts.map +1 -0
  205. package/lib/ReadWriteRedisHttp.js +15 -0
  206. package/lib/ReadWriteRedisHttp.js.map +1 -0
  207. package/lib/Redis.d.ts +252 -0
  208. package/lib/Redis.d.ts.map +1 -0
  209. package/lib/Redis.js +608 -0
  210. package/lib/Redis.js.map +1 -0
  211. package/lib/RedisBinding.d.ts +7 -0
  212. package/lib/RedisBinding.d.ts.map +1 -0
  213. package/lib/RedisBinding.js +53 -0
  214. package/lib/RedisBinding.js.map +1 -0
  215. package/lib/RedisHttp.d.ts +8 -0
  216. package/lib/RedisHttp.d.ts.map +1 -0
  217. package/lib/RedisHttp.js +8 -0
  218. package/lib/RedisHttp.js.map +1 -0
  219. package/lib/Region.d.ts +16 -0
  220. package/lib/Region.d.ts.map +1 -0
  221. package/lib/Region.js +13 -0
  222. package/lib/Region.js.map +1 -0
  223. package/lib/Secret.d.ts +190 -0
  224. package/lib/Secret.d.ts.map +1 -0
  225. package/lib/Secret.js +310 -0
  226. package/lib/Secret.js.map +1 -0
  227. package/lib/SecretHttp.d.ts +54 -0
  228. package/lib/SecretHttp.d.ts.map +1 -0
  229. package/lib/SecretHttp.js +66 -0
  230. package/lib/SecretHttp.js.map +1 -0
  231. package/lib/SecretKey.d.ts +164 -0
  232. package/lib/SecretKey.d.ts.map +1 -0
  233. package/lib/SecretKey.js +277 -0
  234. package/lib/SecretKey.js.map +1 -0
  235. package/lib/SecretKeyHttp.d.ts +14 -0
  236. package/lib/SecretKeyHttp.d.ts.map +1 -0
  237. package/lib/SecretKeyHttp.js +5 -0
  238. package/lib/SecretKeyHttp.js.map +1 -0
  239. package/lib/Service.d.ts +1022 -0
  240. package/lib/Service.d.ts.map +1 -0
  241. package/lib/Service.js +1397 -0
  242. package/lib/Service.js.map +1 -0
  243. package/lib/Sign.d.ts +36 -0
  244. package/lib/Sign.d.ts.map +1 -0
  245. package/lib/Sign.js +3 -0
  246. package/lib/Sign.js.map +1 -0
  247. package/lib/SignHttp.d.ts +22 -0
  248. package/lib/SignHttp.d.ts.map +1 -0
  249. package/lib/SignHttp.js +36 -0
  250. package/lib/SignHttp.js.map +1 -0
  251. package/lib/Sprite.d.ts +283 -0
  252. package/lib/Sprite.d.ts.map +1 -0
  253. package/lib/Sprite.js +469 -0
  254. package/lib/Sprite.js.map +1 -0
  255. package/lib/SpriteHttp.d.ts +25 -0
  256. package/lib/SpriteHttp.d.ts.map +1 -0
  257. package/lib/SpriteHttp.js +33 -0
  258. package/lib/SpriteHttp.js.map +1 -0
  259. package/lib/Verify.d.ts +37 -0
  260. package/lib/Verify.d.ts.map +1 -0
  261. package/lib/Verify.js +3 -0
  262. package/lib/Verify.js.map +1 -0
  263. package/lib/VerifyHttp.d.ts +22 -0
  264. package/lib/VerifyHttp.d.ts.map +1 -0
  265. package/lib/VerifyHttp.js +38 -0
  266. package/lib/VerifyHttp.js.map +1 -0
  267. package/lib/Volume.d.ts +53 -0
  268. package/lib/Volume.d.ts.map +1 -0
  269. package/lib/Volume.js +188 -0
  270. package/lib/Volume.js.map +1 -0
  271. package/lib/VolumeSnapshot.d.ts +135 -0
  272. package/lib/VolumeSnapshot.d.ts.map +1 -0
  273. package/lib/VolumeSnapshot.js +213 -0
  274. package/lib/VolumeSnapshot.js.map +1 -0
  275. package/lib/Website/AssetDeployment.d.ts +43 -0
  276. package/lib/Website/AssetDeployment.d.ts.map +1 -0
  277. package/lib/Website/AssetDeployment.js +162 -0
  278. package/lib/Website/AssetDeployment.js.map +1 -0
  279. package/lib/Website/Astro.d.ts +87 -0
  280. package/lib/Website/Astro.d.ts.map +1 -0
  281. package/lib/Website/Astro.js +55 -0
  282. package/lib/Website/Astro.js.map +1 -0
  283. package/lib/Website/Foldkit.d.ts +52 -0
  284. package/lib/Website/Foldkit.d.ts.map +1 -0
  285. package/lib/Website/Foldkit.js +45 -0
  286. package/lib/Website/Foldkit.js.map +1 -0
  287. package/lib/Website/FrameworkSite.d.ts +175 -0
  288. package/lib/Website/FrameworkSite.d.ts.map +1 -0
  289. package/lib/Website/FrameworkSite.js +162 -0
  290. package/lib/Website/FrameworkSite.js.map +1 -0
  291. package/lib/Website/Nextjs.d.ts +54 -0
  292. package/lib/Website/Nextjs.d.ts.map +1 -0
  293. package/lib/Website/Nextjs.js +46 -0
  294. package/lib/Website/Nextjs.js.map +1 -0
  295. package/lib/Website/Nuxt.d.ts +51 -0
  296. package/lib/Website/Nuxt.d.ts.map +1 -0
  297. package/lib/Website/Nuxt.js +36 -0
  298. package/lib/Website/Nuxt.js.map +1 -0
  299. package/lib/Website/Octane.d.ts +49 -0
  300. package/lib/Website/Octane.d.ts.map +1 -0
  301. package/lib/Website/Octane.js +39 -0
  302. package/lib/Website/Octane.js.map +1 -0
  303. package/lib/Website/ReactRouter.d.ts +80 -0
  304. package/lib/Website/ReactRouter.d.ts.map +1 -0
  305. package/lib/Website/ReactRouter.js +70 -0
  306. package/lib/Website/ReactRouter.js.map +1 -0
  307. package/lib/Website/SolidStart.d.ts +93 -0
  308. package/lib/Website/SolidStart.d.ts.map +1 -0
  309. package/lib/Website/SolidStart.js +71 -0
  310. package/lib/Website/SolidStart.js.map +1 -0
  311. package/lib/Website/StaticSite.d.ts +155 -0
  312. package/lib/Website/StaticSite.d.ts.map +1 -0
  313. package/lib/Website/StaticSite.js +168 -0
  314. package/lib/Website/StaticSite.js.map +1 -0
  315. package/lib/Website/SvelteKit.d.ts +52 -0
  316. package/lib/Website/SvelteKit.d.ts.map +1 -0
  317. package/lib/Website/SvelteKit.js +37 -0
  318. package/lib/Website/SvelteKit.js.map +1 -0
  319. package/lib/Website/TanStackStart.d.ts +76 -0
  320. package/lib/Website/TanStackStart.d.ts.map +1 -0
  321. package/lib/Website/TanStackStart.js +66 -0
  322. package/lib/Website/TanStackStart.js.map +1 -0
  323. package/lib/Website/Vinext.d.ts +73 -0
  324. package/lib/Website/Vinext.d.ts.map +1 -0
  325. package/lib/Website/Vinext.js +67 -0
  326. package/lib/Website/Vinext.js.map +1 -0
  327. package/lib/Website/Vite.d.ts +103 -0
  328. package/lib/Website/Vite.d.ts.map +1 -0
  329. package/lib/Website/Vite.js +91 -0
  330. package/lib/Website/Vite.js.map +1 -0
  331. package/lib/Website/Vocs.d.ts +52 -0
  332. package/lib/Website/Vocs.d.ts.map +1 -0
  333. package/lib/Website/Vocs.js +38 -0
  334. package/lib/Website/Vocs.js.map +1 -0
  335. package/lib/Website/Waku.d.ts +64 -0
  336. package/lib/Website/Waku.d.ts.map +1 -0
  337. package/lib/Website/Waku.js +39 -0
  338. package/lib/Website/Waku.js.map +1 -0
  339. package/lib/Website/index.d.ts +17 -0
  340. package/lib/Website/index.d.ts.map +1 -0
  341. package/lib/Website/index.js +17 -0
  342. package/lib/Website/index.js.map +1 -0
  343. package/lib/WriteCertificates.d.ts +63 -0
  344. package/lib/WriteCertificates.d.ts.map +1 -0
  345. package/lib/WriteCertificates.js +3 -0
  346. package/lib/WriteCertificates.js.map +1 -0
  347. package/lib/WriteCertificatesHttp.d.ts +25 -0
  348. package/lib/WriteCertificatesHttp.d.ts.map +1 -0
  349. package/lib/WriteCertificatesHttp.js +67 -0
  350. package/lib/WriteCertificatesHttp.js.map +1 -0
  351. package/lib/WriteRedis.d.ts +26 -0
  352. package/lib/WriteRedis.d.ts.map +1 -0
  353. package/lib/WriteRedis.js +3 -0
  354. package/lib/WriteRedis.js.map +1 -0
  355. package/lib/WriteRedisHttp.d.ts +11 -0
  356. package/lib/WriteRedisHttp.d.ts.map +1 -0
  357. package/lib/WriteRedisHttp.js +15 -0
  358. package/lib/WriteRedisHttp.js.map +1 -0
  359. package/lib/WriteSecret.d.ts +68 -0
  360. package/lib/WriteSecret.d.ts.map +1 -0
  361. package/lib/WriteSecret.js +4 -0
  362. package/lib/WriteSecret.js.map +1 -0
  363. package/lib/WriteSecretHttp.d.ts +26 -0
  364. package/lib/WriteSecretHttp.d.ts.map +1 -0
  365. package/lib/WriteSecretHttp.js +54 -0
  366. package/lib/WriteSecretHttp.js.map +1 -0
  367. package/lib/bluegreen.d.ts +36 -0
  368. package/lib/bluegreen.d.ts.map +1 -0
  369. package/lib/bluegreen.js +458 -0
  370. package/lib/bluegreen.js.map +1 -0
  371. package/lib/hosted.d.ts +172 -0
  372. package/lib/hosted.d.ts.map +1 -0
  373. package/lib/hosted.js +458 -0
  374. package/lib/hosted.js.map +1 -0
  375. package/lib/index.d.ts +65 -0
  376. package/lib/index.d.ts.map +1 -0
  377. package/lib/index.js +63 -0
  378. package/lib/index.js.map +1 -0
  379. package/lib/internal/RemoteBuilder.d.ts +28 -0
  380. package/lib/internal/RemoteBuilder.d.ts.map +1 -0
  381. package/lib/internal/RemoteBuilder.js +145 -0
  382. package/lib/internal/RemoteBuilder.js.map +1 -0
  383. package/lib/leases.d.ts +53 -0
  384. package/lib/leases.d.ts.map +1 -0
  385. package/lib/leases.js +279 -0
  386. package/lib/leases.js.map +1 -0
  387. package/lib/ports.d.ts +51 -0
  388. package/lib/ports.d.ts.map +1 -0
  389. package/lib/ports.js +123 -0
  390. package/lib/ports.js.map +1 -0
  391. package/lib/replicas.d.ts +270 -0
  392. package/lib/replicas.d.ts.map +1 -0
  393. package/lib/replicas.js +969 -0
  394. package/lib/replicas.js.map +1 -0
  395. package/lib/rpc.d.ts +35 -0
  396. package/lib/rpc.d.ts.map +1 -0
  397. package/lib/rpc.js +113 -0
  398. package/lib/rpc.js.map +1 -0
  399. package/package.json +97 -3
  400. package/src/App.ts +516 -0
  401. package/src/AuthProvider.ts +68 -0
  402. package/src/BindService.ts +304 -0
  403. package/src/Bootstrap.ts +66 -0
  404. package/src/Bucket.ts +916 -0
  405. package/src/BucketBinding.ts +128 -0
  406. package/src/Catalog.ts +43 -0
  407. package/src/Certificate.ts +548 -0
  408. package/src/Checkpoint.ts +69 -0
  409. package/src/CheckpointHttp.ts +66 -0
  410. package/src/ConnectPostgres.ts +68 -0
  411. package/src/ConnectPostgresHttp.ts +77 -0
  412. package/src/Contributions.ts +9 -0
  413. package/src/Credentials.ts +102 -0
  414. package/src/Decrypt.ts +62 -0
  415. package/src/DecryptHttp.ts +52 -0
  416. package/src/DeleteObject.ts +43 -0
  417. package/src/DeleteObjectHttp.ts +20 -0
  418. package/src/Deployment.ts +121 -0
  419. package/src/DeploymentImages.ts +84 -0
  420. package/src/DeploymentState.ts +104 -0
  421. package/src/Encrypt.ts +60 -0
  422. package/src/EncryptHttp.ts +48 -0
  423. package/src/Environment.ts +81 -0
  424. package/src/Errors.ts +14 -0
  425. package/src/Exec.ts +50 -0
  426. package/src/ExecHttp.ts +47 -0
  427. package/src/GetObject.ts +48 -0
  428. package/src/GetObjectHttp.ts +20 -0
  429. package/src/GetSecret.ts +48 -0
  430. package/src/GetSecretHttp.ts +60 -0
  431. package/src/HeadObject.ts +43 -0
  432. package/src/HeadObjectHttp.ts +20 -0
  433. package/src/IpAssignment.ts +522 -0
  434. package/src/ListObjectsV2.ts +43 -0
  435. package/src/ListObjectsV2Http.ts +20 -0
  436. package/src/ListSecrets.ts +57 -0
  437. package/src/ListSecretsHttp.ts +43 -0
  438. package/src/Machine.ts +1268 -0
  439. package/src/MachineContainers.ts +152 -0
  440. package/src/Metadata.ts +195 -0
  441. package/src/MountVolume.ts +315 -0
  442. package/src/Postgres.ts +777 -0
  443. package/src/PostgresMigrations.ts +153 -0
  444. package/src/Providers.ts +155 -0
  445. package/src/PutObject.ts +49 -0
  446. package/src/PutObjectHttp.ts +20 -0
  447. package/src/ReadRedis.ts +31 -0
  448. package/src/ReadRedisHttp.ts +18 -0
  449. package/src/ReadWriteRedis.ts +33 -0
  450. package/src/ReadWriteRedisHttp.ts +18 -0
  451. package/src/Redis.ts +820 -0
  452. package/src/RedisBinding.ts +64 -0
  453. package/src/RedisHttp.ts +11 -0
  454. package/src/Region.ts +44 -0
  455. package/src/Secret.ts +405 -0
  456. package/src/SecretHttp.ts +149 -0
  457. package/src/SecretKey.ts +389 -0
  458. package/src/SecretKeyHttp.ts +23 -0
  459. package/src/Service.ts +1934 -0
  460. package/src/Sign.ts +46 -0
  461. package/src/SignHttp.ts +44 -0
  462. package/src/Sprite.ts +671 -0
  463. package/src/SpriteHttp.ts +50 -0
  464. package/src/Verify.ts +47 -0
  465. package/src/VerifyHttp.ts +46 -0
  466. package/src/Volume.ts +264 -0
  467. package/src/VolumeSnapshot.ts +321 -0
  468. package/src/Website/AssetDeployment.ts +294 -0
  469. package/src/Website/Astro.ts +87 -0
  470. package/src/Website/Foldkit.ts +54 -0
  471. package/src/Website/FrameworkSite.ts +363 -0
  472. package/src/Website/Nextjs.ts +50 -0
  473. package/src/Website/Nuxt.ts +48 -0
  474. package/src/Website/Octane.ts +44 -0
  475. package/src/Website/ReactRouter.ts +76 -0
  476. package/src/Website/SolidStart.ts +90 -0
  477. package/src/Website/StaticSite.ts +275 -0
  478. package/src/Website/SvelteKit.ts +49 -0
  479. package/src/Website/TanStackStart.ts +72 -0
  480. package/src/Website/Vinext.ts +79 -0
  481. package/src/Website/Vite.ts +112 -0
  482. package/src/Website/Vocs.ts +50 -0
  483. package/src/Website/Waku.ts +65 -0
  484. package/src/Website/index.ts +16 -0
  485. package/src/WriteCertificates.ts +90 -0
  486. package/src/WriteCertificatesHttp.ts +93 -0
  487. package/src/WriteRedis.ts +31 -0
  488. package/src/WriteRedisHttp.ts +18 -0
  489. package/src/WriteSecret.ts +86 -0
  490. package/src/WriteSecretHttp.ts +71 -0
  491. package/src/bluegreen.ts +708 -0
  492. package/src/globals.d.ts +2 -0
  493. package/src/hosted.ts +668 -0
  494. package/src/index.ts +64 -0
  495. package/src/internal/RemoteBuilder.ts +224 -0
  496. package/src/leases.ts +437 -0
  497. package/src/ports.ts +177 -0
  498. package/src/replicas.ts +1480 -0
  499. package/src/rpc.ts +136 -0
package/src/Service.ts ADDED
@@ -0,0 +1,1934 @@
1
+ import { DockerLive, Docker } from "@alchemy.run/docker/Docker";
2
+ import type {
3
+ FlyMachineConfig,
4
+ FlyMachineGuest,
5
+ FlyMachineMount,
6
+ FlyMachineService,
7
+ FlyStatic,
8
+ Machine as FlyMachine,
9
+ } from "@distilled.cloud/fly-io/machines";
10
+ import * as machines from "@distilled.cloud/fly-io/machines";
11
+ import { AlchemyContext } from "alchemy/AlchemyContext";
12
+ import * as Bundle from "alchemy/Bundle/Bundle";
13
+ import { deepEqual, isResolved } from "alchemy/Diff";
14
+ import type { Input } from "alchemy/Input";
15
+ import { Platform, type Main, type MainRpc, type PlatformProps } from "alchemy/Platform";
16
+ import * as Provider from "alchemy/Provider";
17
+ import { makeRandom } from "alchemy/Random";
18
+ import type { Resource } from "alchemy/Resource";
19
+ import type { ServerHost } from "alchemy/Runtime/Process";
20
+ import { packEnvValue } from "alchemy/RuntimeContext";
21
+ import { Stack } from "alchemy/Stack";
22
+ import * as Data from "effect/Data";
23
+ import * as Effect from "effect/Effect";
24
+ import * as Layer from "effect/Layer";
25
+ import * as Redacted from "effect/Redacted";
26
+ import { App, deleteApp, ensureApp } from "./App.ts";
27
+ import { boundTargetEnvKeys } from "./BindService.ts";
28
+ import { attachBucketSecrets } from "./Bucket.ts";
29
+ import {
30
+ deploymentPolicy,
31
+ validateDeployment,
32
+ type MachineDeploy,
33
+ type MachineShutdown,
34
+ type MachineCheck,
35
+ } from "./Deployment.ts";
36
+ import { resolveOrgSlug } from "./Environment.ts";
37
+ import {
38
+ collectBindingState,
39
+ createFlyHostedSupport,
40
+ createFlyHostRuntimeContext,
41
+ defaultHttpServices,
42
+ DEFAULT_PORT,
43
+ toEnvRecord,
44
+ type FlyBuildOptions,
45
+ type FlyHostRuntimeContext,
46
+ type HostedProgramProps,
47
+ } from "./hosted.ts";
48
+ import { ensureFlycastAddress, hasPublicAddress, syncOwnedAppAddresses } from "./IpAssignment.ts";
49
+ import type { MachineGuest, MachineImageRef, MachineService } from "./Machine.ts";
50
+ import {
51
+ alchemyMetadataKeys,
52
+ createFlyAppName,
53
+ createFlyResourceName,
54
+ diffMachineMetadata,
55
+ sanitizeFlyAppName,
56
+ } from "./Metadata.ts";
57
+ import type { BoundTarget, MountedDisk, ServiceBinding } from "./MountVolume.ts";
58
+ import { bindingPortOf, findPortConflict, portsOfFly } from "./ports.ts";
59
+ import { attachPostgresSecrets } from "./Postgres.ts";
60
+ import type { Providers } from "./Providers.ts";
61
+ import { attachRedisSecrets } from "./Redis.ts";
62
+ import { type Region, regionList } from "./Region.ts";
63
+ import {
64
+ deleteReplicaSet,
65
+ hasPublishedService,
66
+ listReplicaSets,
67
+ observeReplicaSet,
68
+ reconcileReplicas,
69
+ resolveCount,
70
+ sameServices,
71
+ toFlyService,
72
+ volumeIdsOf,
73
+ type Replica,
74
+ type ReplicaSet,
75
+ } from "./replicas.ts";
76
+ import { BINDING_PORT_ENV, DEFAULT_BINDING_PORT, RPC_ORG_ENV, RPC_TOKEN_ENV } from "./rpc.ts";
77
+
78
+ /**
79
+ * A resource-valued prop: the resource itself, or an Effect that produces
80
+ * it (so `yield* App(...)` and `App(...)` both type-check).
81
+ */
82
+ type Ref<T> = T | Effect.Effect<T, never, Providers>;
83
+
84
+ const DEFAULT_REGION = "iad";
85
+ const DEFAULT_CPU_KIND = "shared";
86
+ const DEFAULT_CPUS = 1;
87
+ const DEFAULT_MEMORY_MB = 256;
88
+
89
+ export interface ServiceProps extends PlatformProps {
90
+ /** Deployment strategy and readiness deadline. Defaults to in-place rolling updates. */
91
+ deploy?: MachineDeploy;
92
+ /** Graceful process shutdown. Defaults to SIGTERM / 30 seconds when blue/green is enabled. */
93
+ shutdown?: MachineShutdown;
94
+ /** Named readiness checks for workers without public services. */
95
+ checks?: Record<string, MachineCheck>;
96
+ /**
97
+ * Run inside an existing {@link App} instead of the Service's own App.
98
+ * The Service then shares that App's hostname, addresses, and secrets,
99
+ * and Alchemy does not manage addresses for it. Accepts a `Fly.App` or
100
+ * an Effect that produces one. Changing it, or adding or removing it,
101
+ * replaces the Service.
102
+ *
103
+ * By default each Service owns its App, so it gets its own
104
+ * `{name}.fly.dev` hostname, addresses, logs, and metrics.
105
+ */
106
+ app?: Ref<App>;
107
+ /**
108
+ * Whether the Service is reachable from the internet. A public Service
109
+ * gets a shared IPv4 and an IPv6 and serves `https://{name}.fly.dev`. A
110
+ * private Service is reachable only from other Apps in the organization,
111
+ * at `http://{name}.flycast`. Every address is free. Only applies when
112
+ * the Service owns its App (no `app`).
113
+ *
114
+ * @default true
115
+ */
116
+ public?: boolean;
117
+ /**
118
+ * Private network the Service's App joins. Only Apps on the same
119
+ * network can reach it, over `privateUrl` or `.internal`; every other
120
+ * App in the organization, including those on the default network,
121
+ * cannot resolve it. Services on one network reach each other freely.
122
+ * Use {@link stackNetwork} for a network unique to the stack and stage.
123
+ * Fly creates the network with the first App that names it. Changing
124
+ * it replaces the Service. Only applies when the Service owns its App
125
+ * (no `app`).
126
+ *
127
+ * @default the organization's default network, shared by every App
128
+ */
129
+ network?: string;
130
+ /**
131
+ * Plain-HTTP port Alchemy publishes for callers that bind this Service
132
+ * with {@link bindService}, when the Service publishes no plain-HTTP port
133
+ * of its own (a public Service's defaults are an HTTPS redirect on 80 and
134
+ * HTTPS on 443). Fly issues no certificate for `.flycast`, so bound
135
+ * callers use plain HTTP inside Fly's WireGuard-encrypted private network.
136
+ * Requests on this port must come from Fly's private network. Change it
137
+ * when the port collides with another Service in the same App.
138
+ *
139
+ * @default 7780
140
+ */
141
+ bindingPort?: number;
142
+ /**
143
+ * Caller token for bound callers. Set automatically from an
144
+ * `Alchemy.Random` child resource; do not pass it.
145
+ * @internal
146
+ */
147
+ rpcToken?: Redacted.Redacted<string>;
148
+ /**
149
+ * Module entrypoint bundled with rolldown and baked into a Docker
150
+ * image pushed to `registry.fly.io`. Typically `import.meta.url`.
151
+ * A content-hash change updates the workload using the selected deployment strategy.
152
+ */
153
+ main: string;
154
+ /**
155
+ * Region or regions to run in (`"iad"`, `["iad", "lhr"]`). The
156
+ * Service runs `count` Machines in each region behind one hostname;
157
+ * Fly's proxy sends each request to the nearest healthy Machine.
158
+ * Adding or removing a region updates the Service in place: Machines
159
+ * in a removed region are deleted, new regions get new Machines.
160
+ *
161
+ * @default "iad"
162
+ */
163
+ region?: Region | Region[];
164
+ /**
165
+ * Number of Machines to provision in each region, including
166
+ * stopped/suspended idle capacity. Fly's proxy load-balances
167
+ * `{app}.fly.dev` across available replicas.
168
+ * Blue/green checks a representative and the required running floor while
169
+ * preserving idle nonrepresentatives. Each replica gets its own Volume
170
+ * from every `MountVolume` binding; attached volumes require rolling updates.
171
+ *
172
+ * @default 1
173
+ */
174
+ count?: number;
175
+ /**
176
+ * Guest size. Defaults to shared-cpu-1x 256 MB.
177
+ */
178
+ guest?: MachineGuest;
179
+ /**
180
+ * Port the hosted HTTP server listens on. Written to `PORT` and used
181
+ * as the Fly proxy `internal_port`.
182
+ *
183
+ * @default 3000
184
+ */
185
+ port?: number;
186
+ /**
187
+ * Named export to load from `main`.
188
+ *
189
+ * @default "default"
190
+ */
191
+ handler?: string;
192
+ /**
193
+ * Additional environment variables for the hosted process. Merged
194
+ * after binding-injected `env`.
195
+ */
196
+ env?: Record<string, any>;
197
+ /**
198
+ * Bundler configuration for `main`: rolldown `input`/`output`
199
+ * overrides, pure-annotation options (`pure`), and `install` for
200
+ * packages that must ship as real `node_modules` (see {@link FlyBuildOptions}).
201
+ */
202
+ build?: FlyBuildOptions;
203
+ /**
204
+ * Environment image used as the generated Dockerfile's `FROM`. Must
205
+ * be able to run Node (websites and Effect-native Services use Node
206
+ * in production).
207
+ *
208
+ * @default "node:26-slim"
209
+ */
210
+ image?: string;
211
+ /**
212
+ * Fly proxy services. Defaults to HTTP 80 + HTTPS 443 → {@link port}.
213
+ */
214
+ services?: MachineService[];
215
+ /**
216
+ * Name of the Service's App, which is its `{name}.fly.dev` and
217
+ * `{name}.flycast` hostname. Globally unique across Fly. If omitted, a
218
+ * unique name is generated from the stack, stage and logical ID.
219
+ * Changing it replaces the Service.
220
+ *
221
+ * When `app` is set, this is instead the Machine name (unique per App;
222
+ * in blue/green mode a base for generation-qualified physical names).
223
+ */
224
+ name?: string;
225
+ /**
226
+ * Extra host directories copied into the Machine image next to the
227
+ * bundled entry (e.g. a website `clientDirectory` at `/app/dist`).
228
+ * Hashed into `code.hash` so asset changes update the image.
229
+ * Destination is relative to `/app`.
230
+ */
231
+ extraFiles?: ReadonlyArray<{ source: string; dest: string }>;
232
+ /**
233
+ * Fly proxy static-file maps. Matching GET paths skip the process and
234
+ * are served from the image (`guestPath`) or a Tigris bucket
235
+ * (`tigrisBucket`). Website composites publish hashed client assets
236
+ * this way.
237
+ */
238
+ statics?: ReadonlyArray<{
239
+ /** Path inside the image, or key prefix in {@link tigrisBucket}. */
240
+ guestPath: string;
241
+ /** URL prefix, e.g. `"/"`. */
242
+ urlPrefix: string;
243
+ /** Tigris bucket name. When set, files come from the bucket. */
244
+ tigrisBucket?: string;
245
+ /** Directory index file (`index.html`) for Tigris statics. */
246
+ indexDocument?: string;
247
+ }>;
248
+ }
249
+
250
+ /** A port the Service publishes on Fly's proxy. */
251
+ export interface ServiceEndpoint {
252
+ /**
253
+ * Hostname the port is published on: `{appName}.fly.dev`, or
254
+ * `{appName}.flycast` for a private Service.
255
+ */
256
+ host: string;
257
+ /** Port on Fly's proxy. */
258
+ port: number;
259
+ /** Port the process listens on inside the Machine. */
260
+ internalPort: number | undefined;
261
+ /** `tcp` or `udp`. */
262
+ protocol: string;
263
+ /** Fly proxy handlers (`tls`, `http`, `pg_tls`, …). Empty for raw TCP or UDP. */
264
+ handlers: string[];
265
+ /**
266
+ * URL when the port speaks HTTP: `https://` for `tls` + `http`, `http://`
267
+ * for plain `http`, with `:{port}` unless it is 443 or 80. `undefined`
268
+ * for other protocols, and for TLS ports on `.flycast` (Fly issues no
269
+ * certificate there).
270
+ */
271
+ url: string | undefined;
272
+ }
273
+
274
+ export type Service = Resource<
275
+ "Fly.Service",
276
+ ServiceProps,
277
+ {
278
+ /** Whether recovery must finish an interrupted deployment. */
279
+ rolloutPending?: boolean;
280
+ /** Fly App name the Machines run in. */
281
+ appName: string;
282
+ /** Whether the Service created and manages {@link appName}. */
283
+ ownsApp?: boolean;
284
+ /**
285
+ * Private network the Service's Machines are on: `network`, or the
286
+ * shared App's network. `undefined` for the organization's default.
287
+ */
288
+ network?: string;
289
+ /** Token bound callers send with RPC calls. */
290
+ rpcToken?: Redacted.Redacted<string>;
291
+ /** Fly Machine id of replica 0. */
292
+ machineId: string;
293
+ /** Fly Machine ids of every replica. */
294
+ machineIds: string[];
295
+ /** Logical base for generation-qualified Machine names. */
296
+ baseName?: string;
297
+ /** Machine name of replica 0 (unique per App). Changes during blue/green deployment. */
298
+ name: string;
299
+ /** Region of the first Machine. */
300
+ region: string;
301
+ /** Every region the Service's Machines run in. */
302
+ regions: string[];
303
+ /** Observed state of replica 0 (`created`, `started`, `stopped`, …). */
304
+ state: string;
305
+ /**
306
+ * Main public HTTP endpoint: the first published `tls` + `http` port
307
+ * as `https://{appName}.fly.dev[:port]`, else the first plain `http`
308
+ * port as `http://{appName}.fly.dev[:port]`. `https://{appName}.fly.dev`
309
+ * for the default services. `undefined` for a private Service or when
310
+ * no port speaks HTTP. When `app` is set, the App's addresses are
311
+ * managed elsewhere, so this is where the Service answers once the App
312
+ * is reachable. See {@link endpoints} for every published port.
313
+ */
314
+ url: string | undefined;
315
+ /**
316
+ * Every port the Service publishes, in declaration order. Ports that
317
+ * only redirect HTTP to HTTPS (`forceHttps`) and port ranges are
318
+ * omitted. Empty when nothing is published.
319
+ */
320
+ endpoints: ServiceEndpoint[];
321
+ /**
322
+ * Address bound callers use over Fly's private network:
323
+ * `http://{appName}.flycast`, with the port when it is not 80. It is
324
+ * the Service's first plain-HTTP port, or {@link ServiceProps.bindingPort}
325
+ * when it has none. Reachable only from Apps on the Service's network.
326
+ * `undefined` when nothing is published.
327
+ */
328
+ privateUrl: string | undefined;
329
+ /** Parsed image reference from Fly. */
330
+ imageRef: MachineImageRef | undefined;
331
+ /** Number of Machines in each region. */
332
+ count: number;
333
+ /** Disks mounted on replica 0. */
334
+ mounts: MountedDisk[];
335
+ /** Every replica in the set. */
336
+ replicas: Replica[];
337
+ /** Content hash of the bundled program's image. */
338
+ code: { hash: string };
339
+ },
340
+ ServiceBinding,
341
+ Providers
342
+ >;
343
+
344
+ export const isService = (value: unknown): value is Service =>
345
+ typeof value === "object" &&
346
+ value !== null &&
347
+ (value as { Type?: string }).Type === "Fly.Service";
348
+
349
+ export type ServiceServices = ServerHost;
350
+
351
+ /**
352
+ * What a Service's program returns: `fetch` for HTTP, `run` for a
353
+ * background loop, and any other methods, which bound callers invoke
354
+ * with {@link bindService}.
355
+ */
356
+ export type ServiceShape =
357
+ | Main<ServiceServices>
358
+ | (Exclude<Main<ServiceServices>, void> & MainRpc<ServiceServices>);
359
+
360
+ export type ServiceRuntimeContext = FlyHostRuntimeContext;
361
+
362
+ /**
363
+ * A Service is an Effect program running on Fly.io Machines in its own
364
+ * Fly App. It gets its own `{name}.fly.dev` hostname, addresses, logs,
365
+ * and metrics, the way each Cloudflare Worker is its own endpoint. Set
366
+ * `count` to scale it up or down.
367
+ *
368
+ * @see https://fly.io/docs/machines/api/machines-resource/
369
+ *
370
+ * ### Declare a Service
371
+ * A Service is a class. Props describe the Machine. The Effect is the
372
+ * program that runs on it.
373
+ *
374
+ * The Service creates its Fly App, and deleting the Service deletes it.
375
+ * `main: import.meta.url` is the bundle entrypoint. Alchemy bundles this
376
+ * file with Rolldown, builds a Docker image (default `node:26-slim`), and
377
+ * pushes it to `registry.fly.io/{app}:{id}-{hash}`.
378
+ *
379
+ * **Example:** Class + main
380
+ * ```typescript
381
+ * // src/api.ts
382
+ * import * as Fly from "@alchemy.run/fly";
383
+ * import * as Effect from "effect/Effect";
384
+ *
385
+ * export default class Api extends Fly.Service<Api>()(
386
+ * "Api",
387
+ * { main: import.meta.url },
388
+ * Effect.gen(function* () {
389
+ * return {};
390
+ * }),
391
+ * ) {}
392
+ * ```
393
+ *
394
+ * ### Serve HTTP with fetch
395
+ * Return `fetch` from the init Effect to boot an HTTP server. Omit
396
+ * `fetch` for a background service.
397
+ *
398
+ * **Example:** Hello
399
+ * ```typescript
400
+ * export default class Api extends Fly.Service<Api>()(
401
+ * "Api",
402
+ * { main: import.meta.url },
403
+ * Effect.gen(function* () {
404
+ * return {
405
+ * fetch: Effect.succeed(HttpServerResponse.text("hello")),
406
+ * };
407
+ * }),
408
+ * ) {}
409
+ * ```
410
+ *
411
+ * ### Pin a region
412
+ * Fly Machines live in a region. Default is `iad`. See
413
+ * [Regions](/fly/compute/regions) for the list of codes.
414
+ *
415
+ * **Example:** Region
416
+ * ```typescript
417
+ * export default class Api extends Fly.Service<Api>()(
418
+ * "Api",
419
+ * { main: import.meta.url, region: "iad" },
420
+ * Effect.gen(function* () {
421
+ * return {
422
+ * fetch: Effect.succeed(HttpServerResponse.text("hello")),
423
+ * };
424
+ * }),
425
+ * ) {}
426
+ * ```
427
+ *
428
+ * ### Run in several regions
429
+ * Pass a list to run the same program in several regions behind one
430
+ * hostname. `count` Machines run in each region, and Fly's proxy sends
431
+ * each request to the nearest healthy one. `regions` on the Service
432
+ * lists where it runs.
433
+ *
434
+ * **Example:** Two regions, two Machines each
435
+ * ```typescript
436
+ * export default class Api extends Fly.Service<Api>()(
437
+ * "Api",
438
+ * { main: import.meta.url, region: ["iad", "lhr"], count: 2 },
439
+ * Effect.gen(function* () {
440
+ * return {
441
+ * fetch: Effect.succeed(HttpServerResponse.text("hello")),
442
+ * };
443
+ * }),
444
+ * ) {}
445
+ * ```
446
+ *
447
+ * Adding or removing a region updates the Service in place and keeps
448
+ * its App and hostname. Machines already in a kept region stay; a
449
+ * removed region's Machines are deleted. Each Machine's Volume from
450
+ * `MountVolume` is created in that Machine's region.
451
+ *
452
+ * ### Set the port
453
+ * `port` is the port the process listens on inside the Machine.
454
+ * Alchemy writes it to `PORT`. Default is `3000`.
455
+ *
456
+ * **Example:** Port 3000
457
+ * ```typescript
458
+ * export default class Api extends Fly.Service<Api>()(
459
+ * "Api",
460
+ * { main: import.meta.url, region: "iad", port: 3000 },
461
+ * Effect.gen(function* () {
462
+ * return {
463
+ * fetch: Effect.succeed(HttpServerResponse.text("hello")),
464
+ * };
465
+ * }),
466
+ * ) {}
467
+ * ```
468
+ *
469
+ * ### The public URL
470
+ * A Service is public by default. Alchemy allocates a shared IPv4 and
471
+ * an IPv6 on its App (both free) and `api.url` is
472
+ * `https://{appName}.fly.dev`.
473
+ *
474
+ * **Example:** Stack output
475
+ * ```typescript
476
+ * export default Alchemy.Stack(
477
+ * "MyApp",
478
+ * { providers: Fly.providers(), state: Alchemy.localState() },
479
+ * Effect.gen(function* () {
480
+ * const api = yield* Api;
481
+ * return { url: api.url };
482
+ * }),
483
+ * );
484
+ * ```
485
+ *
486
+ * `url` is `undefined` when you pass `services: []` (nothing is
487
+ * published).
488
+ *
489
+ * ### Every published port
490
+ * `url` is one endpoint. A Service that publishes several ports has one
491
+ * endpoint per port at the same hostname, listed in `endpoints` with
492
+ * its port, handlers, and a URL when the port speaks HTTP. Ports that
493
+ * only redirect to HTTPS are left out.
494
+ *
495
+ * **Example:** An admin UI on 8443 and raw TCP on 7000
496
+ * ```typescript
497
+ * export default class Api extends Fly.Service<Api>()(
498
+ * "Api",
499
+ * {
500
+ * main: import.meta.url,
501
+ * services: [
502
+ * {
503
+ * internalPort: 3000,
504
+ * ports: [
505
+ * { port: 80, handlers: ["http"], forceHttps: true },
506
+ * { port: 443, handlers: ["tls", "http"] },
507
+ * ],
508
+ * },
509
+ * { internalPort: 9000, ports: [{ port: 8443, handlers: ["tls", "http"] }] },
510
+ * { internalPort: 7000, ports: [{ port: 7000 }] },
511
+ * ],
512
+ * },
513
+ * Effect.gen(function* () {
514
+ * return {};
515
+ * }),
516
+ * ) {}
517
+ *
518
+ * api.url; // "https://{appName}.fly.dev"
519
+ * api.endpoints.map((endpoint) => endpoint.url);
520
+ * // ["https://{appName}.fly.dev", "https://{appName}.fly.dev:8443", undefined]
521
+ * ```
522
+ *
523
+ * :::note[Plain HTTP on other ports needs IPv6]
524
+ * The free shared IPv4 serves TLS on any port but plain HTTP only on
525
+ * port 80. A plain-HTTP port such as 8080 answers over IPv6 only.
526
+ * :::
527
+ *
528
+ * ### Private Services
529
+ * `public: false` keeps a Service off the internet. It gets only a
530
+ * Flycast address and publishes plain HTTP on port 80 (Fly issues no
531
+ * certificate for `.flycast`). `url` is `undefined`, and `privateUrl` is
532
+ * `http://{appName}.flycast`. Calls go through Fly's proxy, so service
533
+ * checks, `autostart`, and blue/green cutover still apply.
534
+ *
535
+ * Turning `public` on or off updates the Service in place. Its App and
536
+ * hostname stay the same.
537
+ *
538
+ * ### Call another Service
539
+ * A Service can return methods next to `fetch`. Another Service calls
540
+ * them by binding it with {@link bindService}, which returns a typed
541
+ * client. Binding makes the caller deploy after the Service, and only
542
+ * callers that bind a Service receive its caller token, so only they
543
+ * can call its methods.
544
+ *
545
+ * **Example:** A private Service with methods
546
+ * ```typescript
547
+ * export default class Users extends Fly.Service<Users>()(
548
+ * "Users",
549
+ * { main: import.meta.url, public: false },
550
+ * Effect.gen(function* () {
551
+ * return {
552
+ * list: () => Effect.succeed(USERS),
553
+ * get: (id: string) =>
554
+ * Effect.succeed(USERS.find((user) => user.id === id)),
555
+ * };
556
+ * }),
557
+ * ) {}
558
+ * ```
559
+ *
560
+ * **Example:** Bind it from another Service
561
+ * ```typescript
562
+ * export default class Gateway extends Fly.Service<Gateway>()(
563
+ * "Gateway",
564
+ * { main: import.meta.url },
565
+ * Effect.gen(function* () {
566
+ * const users = yield* Fly.bindService(Users);
567
+ * return {
568
+ * fetch: Effect.gen(function* () {
569
+ * return yield* HttpServerResponse.json(yield* users.list());
570
+ * }).pipe(Effect.orDie),
571
+ * };
572
+ * }),
573
+ * ) {}
574
+ * ```
575
+ *
576
+ * Calls use plain HTTP to `privateUrl` inside Fly's WireGuard-encrypted
577
+ * private network. The Service accepts a method call only with its
578
+ * caller token and a `Fly-Src` signature from Fly's proxy for the same
579
+ * organization, so the public internet can never call it. A public
580
+ * Service publishes an extra plain-HTTP port for bound callers,
581
+ * `bindingPort` (default 7780), since its own ports are an HTTPS
582
+ * redirect and HTTPS. `client.fetch` sends a request to the Service's
583
+ * `fetch` routes, and {@link bindEndpoint} targets one published port.
584
+ * Two Services can bind each other; declare them as tag classes and
585
+ * provide their `.make` layers (see the
586
+ * [Connect Services guide](/fly/compute/connecting-services)).
587
+ *
588
+ * ### Isolate Services on a private network
589
+ * Fly's default private network spans the whole organization, so any
590
+ * App in it can reach a private Service's address. Put a stack's
591
+ * Services on their own network with `network`. {@link stackNetwork}
592
+ * names one per stack and stage. Apps on other networks, including the
593
+ * default one, cannot resolve them, and binding a Service on another
594
+ * network fails the caller's deploy with `Fly.ServiceUnreachable`
595
+ * before anything is created. A public Service on the network still
596
+ * serves `url`, which makes it the stack's single entry point.
597
+ *
598
+ * **Example:** Private backend behind a public gateway
599
+ * ```typescript
600
+ * export class Users extends Fly.Service<Users>()(
601
+ * "Users",
602
+ * Effect.gen(function* () {
603
+ * return {
604
+ * main: import.meta.url,
605
+ * public: false,
606
+ * network: yield* Fly.stackNetwork,
607
+ * };
608
+ * }),
609
+ * Effect.gen(function* () {
610
+ * return { list: () => Effect.succeed(USERS) };
611
+ * }),
612
+ * ) {}
613
+ *
614
+ * export class Gateway extends Fly.Service<Gateway>()(
615
+ * "Gateway",
616
+ * Effect.gen(function* () {
617
+ * return { main: import.meta.url, network: yield* Fly.stackNetwork };
618
+ * }),
619
+ * Effect.gen(function* () {
620
+ * const users = yield* Fly.bindService(Users);
621
+ * return {
622
+ * fetch: Effect.gen(function* () {
623
+ * return yield* HttpServerResponse.json(yield* users.list());
624
+ * }).pipe(Effect.orDie),
625
+ * };
626
+ * }),
627
+ * ) {}
628
+ * ```
629
+ *
630
+ * :::caution[Changing `network` replaces the Service]
631
+ * Fly cannot move an App between networks. Alchemy creates the Service
632
+ * on the new network, then deletes the old App.
633
+ * :::
634
+ *
635
+ * ### Fly's proxy is the load balancer
636
+ * There is no LoadBalancer resource. Fly runs an Anycast proxy at
637
+ * the edge.
638
+ *
639
+ * **Example:** Published ports
640
+ * ```typescript
641
+ * export default class Api extends Fly.Service<Api>()(
642
+ * "Api",
643
+ * { main: import.meta.url, region: "iad", port: 3000 },
644
+ * Effect.gen(function* () {
645
+ * return {
646
+ * fetch: Effect.succeed(HttpServerResponse.text("hello")),
647
+ * };
648
+ * }),
649
+ * ) {}
650
+ * ```
651
+ *
652
+ * Unless you override `services`, Alchemy publishes HTTP 80 and
653
+ * HTTPS 443 on that proxy and points them at `port` inside each
654
+ * Machine (`internal_port`). A request to
655
+ * `https://{appName}.fly.dev` lands on Fly's edge. Fly terminates
656
+ * TLS on 443, picks one started Machine that published this service,
657
+ * and forwards to `port` where `fetch` runs.
658
+ *
659
+ * ### Configure routing health checks
660
+ * The generated service includes a TCP check on `port`. To customize
661
+ * it, provide `services` and configure each service's `checks` property.
662
+ * With rolling updates, reconcile waits for each started replica's checks
663
+ * before updating the next replica. Missing or non-passing results are
664
+ * polled within `deploy.healthTimeout` (60 seconds by default), then fail
665
+ * deployment with `Fly.ReplicaChecksNotPassing`. Later replicas remain
666
+ * unchanged; earlier updates are not rolled back. A single rolling replica
667
+ * can be unavailable. Blue/green checks replacements before retiring the
668
+ * old set, with representative/floor readiness for idle capacity.
669
+ *
670
+ * **Example:** HTTP readiness check
671
+ * ```typescript
672
+ * export default class Api extends Fly.Service<Api>()(
673
+ * "Api",
674
+ * {
675
+ * main: import.meta.url,
676
+ * port: 3000,
677
+ * services: [
678
+ * {
679
+ * protocol: "tcp",
680
+ * internalPort: 3000,
681
+ * ports: [
682
+ * { port: 80, handlers: ["http"], forceHttps: true },
683
+ * { port: 443, handlers: ["tls", "http"] },
684
+ * ],
685
+ * checks: [
686
+ * {
687
+ * type: "http",
688
+ * port: 3000,
689
+ * method: "GET",
690
+ * path: "/health",
691
+ * protocol: "http",
692
+ * interval: "15s",
693
+ * timeout: "2s",
694
+ * gracePeriod: "30s",
695
+ * },
696
+ * ],
697
+ * },
698
+ * ],
699
+ * },
700
+ * Effect.gen(function* () {
701
+ * return {
702
+ * fetch: Effect.succeed(HttpServerResponse.text("hello")),
703
+ * };
704
+ * }),
705
+ * ) {}
706
+ * ```
707
+ *
708
+ * ### Scale with count
709
+ * `count` is how many Machines to provision, including idle capacity.
710
+ * Default is `1`. Replicas publish the same proxy service behind
711
+ * `{appName}.fly.dev`; Fly's proxy picks an available Machine per request.
712
+ * Each replica gets its own Volume from every {@link MountVolume} binding;
713
+ * attached volumes require rolling updates.
714
+ *
715
+ * **Example:** Three replicas
716
+ * ```typescript
717
+ * export default class Api extends Fly.Service<Api>()(
718
+ * "Api",
719
+ * { main: import.meta.url, region: "iad", count: 3, port: 3000 },
720
+ * Effect.gen(function* () {
721
+ * return {
722
+ * fetch: Effect.succeed(HttpServerResponse.text("hello")),
723
+ * };
724
+ * }),
725
+ * ) {}
726
+ * ```
727
+ *
728
+ * ### Config
729
+ * Yield `Config` in init. Alchemy reads the value from the env of
730
+ * whoever deploys and writes it onto the Machine, so there is no need
731
+ * to copy it into `env`.
732
+ *
733
+ * `Config.Redacted("API_KEY")` is `Redacted<string>`. Unwrap with
734
+ * `Redacted.value` only where you need the raw string.
735
+ *
736
+ * Alchemy also injects `PORT` (when `port` is set) and stack metadata.
737
+ * For a secret Fly should own and inject into every Machine on an App,
738
+ * run the Service in an {@link App} (`app`) and use {@link Secret}.
739
+ *
740
+ * **Example:** Config.Redacted
741
+ * ```typescript
742
+ * import * as Config from "effect/Config";
743
+ * import * as Redacted from "effect/Redacted";
744
+ *
745
+ * export default class Api extends Fly.Service<Api>()(
746
+ * "Api",
747
+ * { main: import.meta.url, port: 3000 },
748
+ * Effect.gen(function* () {
749
+ * const apiKey = yield* Config.Redacted("API_KEY");
750
+ *
751
+ * return {
752
+ * fetch: Effect.gen(function* () {
753
+ * const token = Redacted.value(apiKey);
754
+ * return HttpServerResponse.text("ok");
755
+ * }),
756
+ * };
757
+ * }),
758
+ * ) {}
759
+ * ```
760
+ *
761
+ * ### Mount a disk
762
+ * Bind {@link MountVolume} inside init. App and region come from the
763
+ * Service. `count: 3` creates three Volumes, one per replica. Provide
764
+ * {@link MountVolumeLive}.
765
+ *
766
+ * **Example:** Per-replica disk
767
+ * ```typescript
768
+ * export default class Api extends Fly.Service<Api>()(
769
+ * "Api",
770
+ * { main: import.meta.url, region: "iad", count: 3, port: 3000 },
771
+ * Effect.gen(function* () {
772
+ * const disk = yield* Fly.MountVolume({ path: "/data", sizeGb: 1 });
773
+ * const fs = yield* FileSystem.FileSystem;
774
+ * return {
775
+ * fetch: Effect.gen(function* () {
776
+ * const text = yield* fs.readFileString(`${disk.path}/hello.txt`);
777
+ * return HttpServerResponse.text(text);
778
+ * }),
779
+ * };
780
+ * }).pipe(Effect.provide(Fly.MountVolumeLive)),
781
+ * ) {}
782
+ * ```
783
+ *
784
+ * ### Guest size
785
+ * `guest` is CPU kind, CPU count, and memory. Default is shared-cpu,
786
+ * 1 CPU, 256 MB. Set `gpuKind` and `gpus` for a GPU. Guest updates in
787
+ * place.
788
+ *
789
+ * **Example:** Bigger guest
790
+ * ```typescript
791
+ * export default class Api extends Fly.Service<Api>()(
792
+ * "Api",
793
+ * {
794
+ * main: import.meta.url,
795
+ * region: "iad",
796
+ * port: 3000,
797
+ * guest: { cpuKind: "shared", cpus: 2, memoryMb: 512 },
798
+ * },
799
+ * Effect.gen(function* () {
800
+ * return {
801
+ * fetch: Effect.succeed(HttpServerResponse.text("hello")),
802
+ * };
803
+ * }),
804
+ * ) {}
805
+ * ```
806
+ *
807
+ * ### A stable hostname
808
+ * `name` names the Service's App, so it is the `{name}.fly.dev`
809
+ * hostname. App names are globally unique across Fly. Omit `name` and
810
+ * Alchemy generates one from the stack, stage, and logical ID.
811
+ *
812
+ * **Example:** Explicit name
813
+ * ```typescript
814
+ * export default class Api extends Fly.Service<Api>()(
815
+ * "Api",
816
+ * { main: import.meta.url, name: "api", port: 3000 },
817
+ * Effect.gen(function* () {
818
+ * return {
819
+ * fetch: Effect.succeed(HttpServerResponse.text("hello")),
820
+ * };
821
+ * }),
822
+ * ) {}
823
+ * ```
824
+ *
825
+ * :::caution[Changing `name` replaces the Service]
826
+ * Fly cannot rename an App. Alchemy creates the Service under the new
827
+ * name, then deletes the old App.
828
+ * :::
829
+ *
830
+ * ### Named export
831
+ * `handler` is the named export to load from `main`. Default is
832
+ * `"default"`.
833
+ *
834
+ * **Example:** Custom handler
835
+ * ```typescript
836
+ * export default class Api extends Fly.Service<Api>()(
837
+ * "Api",
838
+ * { main: import.meta.url, handler: "api", port: 3000 },
839
+ * Effect.gen(function* () {
840
+ * return {
841
+ * fetch: Effect.succeed(HttpServerResponse.text("hello")),
842
+ * };
843
+ * }),
844
+ * ) {}
845
+ * ```
846
+ *
847
+ * ### Base image
848
+ * `image` is the generated Dockerfile's `FROM`. Default is
849
+ * `node:26-slim`. A content-hash change of `main` updates the
850
+ * Machine in place.
851
+ *
852
+ * **Example:** Override FROM
853
+ * ```typescript
854
+ * export default class Api extends Fly.Service<Api>()(
855
+ * "Api",
856
+ * {
857
+ * main: import.meta.url,
858
+ * image: "node:26",
859
+ * port: 3000,
860
+ * },
861
+ * Effect.gen(function* () {
862
+ * return {
863
+ * fetch: Effect.succeed(HttpServerResponse.text("hello")),
864
+ * };
865
+ * }),
866
+ * ) {}
867
+ * ```
868
+ *
869
+ * ### Custom proxy services
870
+ * `services` defaults to HTTP 80 (redirecting to HTTPS) + HTTPS 443
871
+ * toward `port`, or plain HTTP 80 for a private Service. Pass a custom
872
+ * list to change handlers or autostop. Pass `[]` so Fly does not
873
+ * publish a proxy.
874
+ *
875
+ * **Example:** Unpublished process
876
+ * ```typescript
877
+ * export default class Worker extends Fly.Service<Worker>()(
878
+ * "Worker",
879
+ * { main: import.meta.url, region: "iad", services: [] },
880
+ * Effect.gen(function* () {
881
+ * return {};
882
+ * }),
883
+ * ) {}
884
+ * ```
885
+ *
886
+ * ### Background services
887
+ * Omit `port` and `fetch`. Pass `services: []`. Use `ServerHost.run`
888
+ * for a long-running loop. If the process exits, Fly restarts it.
889
+ *
890
+ * **Example:** ServerHost.run
891
+ * ```typescript
892
+ * import { ServerHost } from "alchemy/Runtime/Process";
893
+ *
894
+ * export default class Worker extends Fly.Service<Worker>()(
895
+ * "Worker",
896
+ * { main: import.meta.url, region: "iad", services: [] },
897
+ * Effect.gen(function* () {
898
+ * const host = yield* ServerHost;
899
+ *
900
+ * yield* host.run(
901
+ * Effect.gen(function* () {
902
+ * return yield* Effect.never;
903
+ * }).pipe(Effect.orDie),
904
+ * );
905
+ * }),
906
+ * ) {}
907
+ * ```
908
+ *
909
+ * ### Bundle config
910
+ * `build` is Rolldown `input` / `output` overrides plus
911
+ * pure-annotation options. Use it when `main` needs extra entry
912
+ * points or externals.
913
+ *
914
+ * **Example:** Externals
915
+ * ```typescript
916
+ * export default class Api extends Fly.Service<Api>()(
917
+ * "Api",
918
+ * {
919
+ * main: import.meta.url,
920
+ * port: 3000,
921
+ * build: { input: { external: ["sharp"] } },
922
+ * },
923
+ * Effect.gen(function* () {
924
+ * return {
925
+ * fetch: Effect.succeed(HttpServerResponse.text("hello")),
926
+ * };
927
+ * }),
928
+ * ) {}
929
+ * ```
930
+ *
931
+ * **Example:** Install `pg` unbundled
932
+ * `pg` is CommonJS. Rolldown's interop turns `Client` into a namespace.
933
+ * Install it into the image so `@effect/sql-pg` / `Drizzle.Postgres` load
934
+ * it with Node's CJS semantics — same `build.install` as Lambda.
935
+ * ```typescript
936
+ * export default class Api extends Fly.Service<Api>()(
937
+ * "Api",
938
+ * {
939
+ * main: import.meta.url,
940
+ * port: 3000,
941
+ * build: { install: ["pg"] },
942
+ * },
943
+ * Effect.gen(function* () {
944
+ * const conn = yield* Fly.ConnectPostgres(Db);
945
+ * const db = yield* Drizzle.Postgres(conn.connectionString);
946
+ * return {
947
+ * fetch: Effect.gen(function* () {
948
+ * const rows = yield* db.execute("select 1 as ok");
949
+ * return HttpServerResponse.json({ rows });
950
+ * }),
951
+ * };
952
+ * }).pipe(Effect.provide(Fly.ConnectPostgresHttp)),
953
+ * ) {}
954
+ * ```
955
+ *
956
+ * ### Group Services in one App
957
+ * Pass `app` to run a Service inside an existing {@link App} instead of
958
+ * its own. The Services share the App's hostname, addresses, and
959
+ * {@link Secret}s, and a {@link Certificate} on the App covers them.
960
+ * Alchemy manages no addresses for a Service in a shared App: allocate
961
+ * an {@link IpAssignment} on the App. `url` and `endpoints` follow the
962
+ * Service's own ports, so Services in one App tell themselves apart by
963
+ * port (`https://{appName}.fly.dev` and `https://{appName}.fly.dev:8443`).
964
+ * `public` does not apply.
965
+ *
966
+ * **Example:** API and worker sharing a secret
967
+ * ```typescript
968
+ * export const Site = Fly.App("Site");
969
+ *
970
+ * class Api extends Fly.Service<Api>()(
971
+ * "Api",
972
+ * { app: Site, main: import.meta.url, port: 3000 },
973
+ * Effect.gen(function* () {
974
+ * return {
975
+ * fetch: Effect.succeed(HttpServerResponse.text("hello")),
976
+ * };
977
+ * }),
978
+ * ) {}
979
+ *
980
+ * class Worker extends Fly.Service<Worker>()(
981
+ * "Worker",
982
+ * { app: Site, main: import.meta.url, services: [] },
983
+ * Effect.gen(function* () {
984
+ * return {};
985
+ * }),
986
+ * ) {}
987
+ * ```
988
+ *
989
+ * Fly's proxy routes an App's traffic by port only, so each Service in
990
+ * the App needs its own ports, including its own `bindingPort` when
991
+ * Alchemy adds one. Two Services on the same port and protocol fail with
992
+ * `Fly.ServicePortConflict` before any Machine is created: at plan time
993
+ * when the App already exists, otherwise when the App deploys. Grouped
994
+ * Services can be bound like any other; they cannot bind each other in
995
+ * a cycle.
996
+ *
997
+ * ### Blue/green deployments
998
+ * Opt into healthy replacement Machines instead of in-place updates.
999
+ * The default TCP service check proves the server is listening; supply
1000
+ * service HTTP checks when readiness also depends on application state.
1001
+ *
1002
+ * **Example:** Single-replica HTTP replacement
1003
+ * ```typescript
1004
+ * export default class Api extends Fly.Service<Api>()(
1005
+ * "Api",
1006
+ * {
1007
+ * main: import.meta.url,
1008
+ * deploy: { strategy: "bluegreen" },
1009
+ * shutdown: { timeout: "30 seconds" },
1010
+ * },
1011
+ * Effect.succeed({ fetch: Effect.succeed(HttpServerResponse.text("ready")) }),
1012
+ * ) {}
1013
+ * ```
1014
+ *
1015
+ * Keep one Service declaration. The old process retains its own shutdown
1016
+ * signal and deadline when the replacement's policy changes. Managed
1017
+ * SIGTERM/SIGINT shutdown drains HTTP while runtime resource finalizers run;
1018
+ * shared dependencies remain alive until both settle or the deadline expires.
1019
+ * Applications own stop-acquisition barriers, separately scoped jobs, and
1020
+ * bounded drain or checkpoint logic using ordinary finalizers, not a new
1021
+ * shutdown hook. External servers own their signal handling. An old bootstrap
1022
+ * cannot gain handlers retroactively. Volumes are incompatible with blue/green;
1023
+ * physical IDs and names change. Service-bound secret versions are floors,
1024
+ * not vault snapshots, and native Machine leases are not deployment-wide locks.
1025
+ * Leases do not serialize vault writers or every simultaneous first deployment;
1026
+ * serialize CI invocations for the same resource.
1027
+ *
1028
+ * Stop and suspend autostop policies preserve idle nonrepresentatives while
1029
+ * a representative and the required running floor pass readiness. Requested
1030
+ * idle policy is restored before old retirement; a new instance needs fresh
1031
+ * checks. Suspension is not SIGTERM shutdown and does not run ordinary
1032
+ * shutdown finalizers. Replacements do not inherit suspended process memory.
1033
+ * See the [deployment guide](/fly/compute/deployments) for recovery,
1034
+ * idle capacity, application responsibilities, and verification limits.
1035
+ *
1036
+ * @resource
1037
+ * @product Service
1038
+ */
1039
+ export const Service: Platform<Service, ServiceServices, ServiceShape, ServiceRuntimeContext> =
1040
+ Platform("Fly.Service", {
1041
+ createRuntimeContext: createFlyHostRuntimeContext("Fly.Service"),
1042
+ // `{ app: Site }` at module scope is an Effect. Yield it here so the
1043
+ // App is registered and `news.app` is resolved attributes at
1044
+ // reconcile (same DX as `yield* App(...)` inside Effect.gen).
1045
+ transformProps: (id, props) =>
1046
+ Effect.gen(function* () {
1047
+ if (globalThis.__ALCHEMY_RUNTIME__) return props;
1048
+ const app = Effect.isEffect(props.app)
1049
+ ? yield* props.app as Effect.Effect<App, never, Providers>
1050
+ : props.app;
1051
+ // Only callers that bind this Service receive the token.
1052
+ const rpcToken = yield* makeRandom(`${id}RpcToken`);
1053
+ if (app !== undefined) {
1054
+ // Report the ports this Service publishes so the App can reject
1055
+ // two Services on the same port before either one is deployed.
1056
+ yield* app.bind(id, {
1057
+ service: id,
1058
+ services: props.services,
1059
+ bindingPort: props.bindingPort,
1060
+ });
1061
+ }
1062
+ return { ...props, app, rpcToken } as typeof props;
1063
+ }),
1064
+ });
1065
+
1066
+ export class ServiceNotCreated extends Data.TaggedError("Fly.ServiceNotCreated")<{
1067
+ name: string;
1068
+ appName: string;
1069
+ }> {}
1070
+
1071
+ export class InvalidServiceProps extends Data.TaggedError("Fly.InvalidServiceProps")<{
1072
+ message: string;
1073
+ }> {}
1074
+
1075
+ export class ServiceAppNotResolved extends Data.TaggedError("Fly.ServiceAppNotResolved")<{
1076
+ message: string;
1077
+ }> {}
1078
+
1079
+ const appNameOf = (value: unknown): string | undefined => {
1080
+ if (value == null || typeof value !== "object") return undefined;
1081
+ const name = (value as { appName?: unknown }).appName;
1082
+ return typeof name === "string" && name.length > 0 ? name : undefined;
1083
+ };
1084
+
1085
+ const compactRecord = (
1086
+ record: Record<string, string | undefined> | null | undefined,
1087
+ ): Record<string, string> =>
1088
+ Object.fromEntries(
1089
+ Object.entries(record ?? {}).flatMap(([key, value]) =>
1090
+ value === undefined ? [] : [[key, value]],
1091
+ ),
1092
+ );
1093
+
1094
+ const toEnv = toEnvRecord;
1095
+
1096
+ const resolveMachineName = (id: string, name: string | undefined, existing?: string) =>
1097
+ Effect.gen(function* () {
1098
+ if (name !== undefined) return sanitizeFlyAppName(name);
1099
+ if (existing !== undefined) return existing;
1100
+ return yield* createFlyResourceName(id);
1101
+ });
1102
+
1103
+ const toFlyGuest = (guest: MachineGuest | undefined): FlyMachineGuest => {
1104
+ const fly: FlyMachineGuest = {
1105
+ cpu_kind: guest?.cpuKind ?? DEFAULT_CPU_KIND,
1106
+ cpus: guest?.cpus ?? DEFAULT_CPUS,
1107
+ memory_mb: guest?.memoryMb ?? DEFAULT_MEMORY_MB,
1108
+ };
1109
+ if (guest?.gpuKind !== undefined) fly.gpu_kind = guest.gpuKind;
1110
+ if (guest?.gpus !== undefined) fly.gpus = guest.gpus;
1111
+ return fly;
1112
+ };
1113
+
1114
+ const desiredEnv = (
1115
+ props: ServiceProps,
1116
+ bindingEnv: Record<string, any>,
1117
+ alchemyEnv: Record<string, string>,
1118
+ port: number,
1119
+ ): Record<string, string> => ({
1120
+ ...toEnv(bindingEnv),
1121
+ ...alchemyEnv,
1122
+ PORT: String(port),
1123
+ ...toEnv(props.env),
1124
+ });
1125
+
1126
+ const toFlyStatics = (
1127
+ statics:
1128
+ | ReadonlyArray<{
1129
+ guestPath: string;
1130
+ urlPrefix: string;
1131
+ tigrisBucket?: string;
1132
+ indexDocument?: string;
1133
+ }>
1134
+ | undefined,
1135
+ ): FlyStatic[] | undefined => {
1136
+ if (statics === undefined || statics.length === 0) return undefined;
1137
+ return statics.map((entry) => ({
1138
+ guest_path: entry.guestPath,
1139
+ url_prefix: entry.urlPrefix,
1140
+ ...(entry.tigrisBucket !== undefined ? { tigris_bucket: entry.tigrisBucket } : {}),
1141
+ ...(entry.indexDocument !== undefined ? { index_document: entry.indexDocument } : {}),
1142
+ }));
1143
+ };
1144
+
1145
+ const buildConfig = (input: {
1146
+ image: string;
1147
+ guest: FlyMachineGuest;
1148
+ env: Record<string, string>;
1149
+ services: FlyMachineService[];
1150
+ mounts: FlyMachineMount[];
1151
+ metadata: Record<string, string>;
1152
+ statics?: FlyStatic[];
1153
+ }): FlyMachineConfig => ({
1154
+ image: input.image,
1155
+ guest: input.guest,
1156
+ env: Object.keys(input.env).length > 0 ? input.env : undefined,
1157
+ services: input.services.length > 0 ? input.services : undefined,
1158
+ mounts: input.mounts.length > 0 ? input.mounts : undefined,
1159
+ metadata: input.metadata,
1160
+ statics: input.statics !== undefined && input.statics.length > 0 ? input.statics : undefined,
1161
+ });
1162
+
1163
+ const sameImage = (machine: FlyMachine, image: string) => {
1164
+ const configImage = machine.config?.image;
1165
+ if (configImage === image) return true;
1166
+ const ref = machine.image_ref;
1167
+ const colon = image.lastIndexOf(":");
1168
+ const slash = image.lastIndexOf("/");
1169
+ const split = colon > slash ? colon : -1;
1170
+ const repo = split === -1 ? image : image.slice(0, split);
1171
+ const tag = split === -1 ? "latest" : image.slice(split + 1);
1172
+ const observedRepo = ref?.repository;
1173
+ if (observedRepo === undefined || ref?.tag !== tag) return false;
1174
+ return observedRepo === repo || observedRepo.endsWith(`/${repo}`);
1175
+ };
1176
+
1177
+ const sameGuest = (observed: FlyMachineGuest | undefined, desired: FlyMachineGuest) =>
1178
+ (observed?.cpu_kind ?? DEFAULT_CPU_KIND) === desired.cpu_kind &&
1179
+ (observed?.cpus ?? DEFAULT_CPUS) === desired.cpus &&
1180
+ (observed?.memory_mb ?? DEFAULT_MEMORY_MB) === desired.memory_mb &&
1181
+ observed?.gpu_kind === desired.gpu_kind &&
1182
+ observed?.gpus === desired.gpus;
1183
+
1184
+ const sameEnv = (
1185
+ observed: Record<string, string | undefined> | undefined,
1186
+ desired: Record<string, string>,
1187
+ ) => deepEqual(compactRecord(observed), desired);
1188
+
1189
+ const sameMounts = (observed: FlyMachineMount[] | undefined, desired: FlyMachineMount[]) => {
1190
+ const key = (mount: FlyMachineMount) => `${mount.volume ?? ""}:${mount.path ?? ""}`;
1191
+ const left = [...(observed ?? [])].map(key).sort();
1192
+ const right = desired.map(key).sort();
1193
+ return deepEqual(left, right);
1194
+ };
1195
+
1196
+ const metadataChanged = (
1197
+ observed: Record<string, string | undefined> | undefined,
1198
+ desired: Record<string, string>,
1199
+ ) => {
1200
+ const { removed, added, updated } = diffMachineMetadata(compactRecord(observed), desired);
1201
+ return removed.length > 0 || Object.keys(added).length > 0 || Object.keys(updated).length > 0;
1202
+ };
1203
+
1204
+ const sameStatics = (observed: FlyStatic[] | undefined, desired: FlyStatic[] | undefined) => {
1205
+ const normalize = (statics: FlyStatic[] | undefined) =>
1206
+ (statics ?? []).map((entry) => ({
1207
+ ...entry,
1208
+ // Empty and omitted index documents both disable directory indexes.
1209
+ index_document: entry.index_document === "" ? undefined : entry.index_document,
1210
+ }));
1211
+ return deepEqual(normalize(observed), normalize(desired), { stripNullish: true });
1212
+ };
1213
+
1214
+ const configDrifted = (
1215
+ machine: FlyMachine,
1216
+ desired: {
1217
+ image: string;
1218
+ guest: FlyMachineGuest;
1219
+ env: Record<string, string>;
1220
+ services: FlyMachineService[];
1221
+ mounts: FlyMachineMount[];
1222
+ metadata: Record<string, string>;
1223
+ statics?: FlyStatic[];
1224
+ },
1225
+ ) => {
1226
+ const config = machine.config;
1227
+ return (
1228
+ !sameImage(machine, desired.image) ||
1229
+ !sameGuest(config?.guest, desired.guest) ||
1230
+ !sameEnv(config?.env, desired.env) ||
1231
+ !sameServices(config?.services, desired.services) ||
1232
+ !sameMounts(config?.mounts, desired.mounts) ||
1233
+ metadataChanged(config?.metadata, desired.metadata) ||
1234
+ !sameStatics(config?.statics, desired.statics)
1235
+ );
1236
+ };
1237
+
1238
+ const portsOf = (services: FlyMachineService[] | undefined) =>
1239
+ (services ?? []).flatMap((service) => service.ports ?? []);
1240
+
1241
+ const withPort = (base: string, port: number, standard: number) =>
1242
+ port === standard ? base : `${base}:${port}`;
1243
+
1244
+ const isRedirect = (handlers: string[], forceHttps: boolean | undefined) =>
1245
+ forceHttps === true && handlers.includes("http") && !handlers.includes("tls");
1246
+
1247
+ /** Every published port on `host`, excluding HTTPS redirects and ranges. */
1248
+ const endpointListOf = (
1249
+ host: string,
1250
+ services: FlyMachineService[] | undefined,
1251
+ ): ServiceEndpoint[] => {
1252
+ const flycast = host.endsWith(".flycast");
1253
+ return (services ?? []).flatMap((service) =>
1254
+ (service.ports ?? []).flatMap((entry) => {
1255
+ const handlers = entry.handlers ?? [];
1256
+ if (entry.port === undefined || isRedirect(handlers, entry.force_https)) return [];
1257
+ const http = handlers.includes("http");
1258
+ const tls = handlers.includes("tls");
1259
+ const url = !http
1260
+ ? undefined
1261
+ : tls
1262
+ ? flycast
1263
+ ? undefined
1264
+ : withPort(`https://${host}`, entry.port, 443)
1265
+ : withPort(`http://${host}`, entry.port, 80);
1266
+ return [
1267
+ {
1268
+ host,
1269
+ port: entry.port,
1270
+ internalPort: service.internal_port,
1271
+ protocol: service.protocol ?? "tcp",
1272
+ handlers,
1273
+ url,
1274
+ },
1275
+ ];
1276
+ }),
1277
+ );
1278
+ };
1279
+
1280
+ /** HTTPS on the first TLS port, else HTTP on the first plain HTTP port. */
1281
+ const mainUrlOf = (endpoints: ServiceEndpoint[]) =>
1282
+ endpoints.find((endpoint) => endpoint.url?.startsWith("https://"))?.url ??
1283
+ endpoints.find((endpoint) => endpoint.url !== undefined)?.url;
1284
+
1285
+ /** `public` and `network` configure the Service's own App. */
1286
+ const validateOwnership = (props: Partial<Pick<ServiceProps, "app" | "public" | "network">>) => {
1287
+ if (props.app === undefined) return Effect.void;
1288
+ const conflicting = (["public", "network"] as const).filter((key) => props[key] !== undefined);
1289
+ return conflicting.length === 0
1290
+ ? Effect.void
1291
+ : Effect.fail(
1292
+ new InvalidServiceProps({
1293
+ message: `Fly.Service ${conflicting.map((key) => `\`${key}\``).join(" and ")} only apply when the Service owns its App; remove \`app\` or ${conflicting.map((key) => `\`${key}\``).join(" and ")}.`,
1294
+ }),
1295
+ );
1296
+ };
1297
+
1298
+ /**
1299
+ * A private network name unique to the current stack and stage, for the
1300
+ * Service `network` prop. Services in one stage reach each other; other
1301
+ * stages and every other App in the organization cannot.
1302
+ */
1303
+ export const stackNetwork = Effect.gen(function* () {
1304
+ const stack = yield* Stack;
1305
+ const name = `${stack.name}-${stack.stage}`
1306
+ .toLowerCase()
1307
+ .replace(/[^a-z0-9-]+/g, "-")
1308
+ .replace(/-+/g, "-")
1309
+ .replace(/^-|-$/g, "")
1310
+ .slice(0, 63)
1311
+ .replace(/-$/, "");
1312
+ return /^[a-z]/.test(name) ? name : `n-${name}`.slice(0, 63);
1313
+ });
1314
+
1315
+ interface Access {
1316
+ ownsApp: boolean;
1317
+ isPublic: boolean;
1318
+ network: string | undefined;
1319
+ bindingPort: number;
1320
+ rpcToken: Redacted.Redacted<string> | undefined;
1321
+ }
1322
+
1323
+ /** Drop the port Alchemy added for bindings from a services list. */
1324
+ const withoutBindingPort = (services: FlyMachineService[] | undefined, bindingPort: number) =>
1325
+ (services ?? []).flatMap((service) => {
1326
+ const ports = (service.ports ?? []).filter(
1327
+ (entry) =>
1328
+ !(
1329
+ entry.port === bindingPort &&
1330
+ (entry.handlers ?? []).includes("http") &&
1331
+ !(entry.handlers ?? []).includes("tls")
1332
+ ),
1333
+ );
1334
+ return ports.length === 0 ? [] : [{ ...service, ports }];
1335
+ });
1336
+
1337
+ const endpointsOf = (set: ReplicaSet, access: Access) => {
1338
+ if (!hasPublishedService(set.services))
1339
+ return { url: undefined, privateUrl: undefined, endpoints: [] };
1340
+ const isPublic = !access.ownsApp || access.isPublic;
1341
+ const binding = bindingPortOf(portsOfFly(set.services), access.bindingPort);
1342
+ const visible = binding?.added ? withoutBindingPort(set.services, binding.port) : set.services;
1343
+ const endpoints = endpointListOf(`${set.appName}.${isPublic ? "fly.dev" : "flycast"}`, visible);
1344
+ return {
1345
+ url: isPublic ? mainUrlOf(endpoints) : undefined,
1346
+ privateUrl:
1347
+ binding === undefined
1348
+ ? undefined
1349
+ : withPort(`http://${set.appName}.flycast`, binding.port, 80),
1350
+ endpoints,
1351
+ };
1352
+ };
1353
+
1354
+ /**
1355
+ * The Service's Fly services plus the plain-HTTP port for bound callers,
1356
+ * when none of its published ports serves plain HTTP.
1357
+ */
1358
+ const withBindingService = (
1359
+ services: FlyMachineService[],
1360
+ internalPort: number,
1361
+ bindingPort: number,
1362
+ ): { services: FlyMachineService[]; added: boolean } => {
1363
+ const binding = bindingPortOf(portsOfFly(services), bindingPort);
1364
+ if (binding?.added !== true) return { services, added: false };
1365
+ if (portsOfFly(services).some((entry) => entry.start === bindingPort))
1366
+ return { services, added: true };
1367
+ // Add the port to the first TCP service so it shares that service's
1368
+ // internal port and health checks (blue/green requires checks on every
1369
+ // published service).
1370
+ const index = services.findIndex((service) => (service.protocol ?? "tcp") === "tcp");
1371
+ if (index === -1) {
1372
+ return {
1373
+ added: true,
1374
+ services: [
1375
+ ...services,
1376
+ {
1377
+ protocol: "tcp",
1378
+ internal_port: internalPort,
1379
+ ports: [{ port: bindingPort, handlers: ["http"] }],
1380
+ },
1381
+ ],
1382
+ };
1383
+ }
1384
+ return {
1385
+ added: true,
1386
+ services: services.map((service, i) =>
1387
+ i === index
1388
+ ? {
1389
+ ...service,
1390
+ ports: [...(service.ports ?? []), { port: bindingPort, handlers: ["http"] }],
1391
+ }
1392
+ : service,
1393
+ ),
1394
+ };
1395
+ };
1396
+
1397
+ /** Fly reports the organization's default network as `default`. */
1398
+ const normalizeNetwork = (network: string | undefined | null) =>
1399
+ network === undefined || network === null || network === "" || network === "default"
1400
+ ? undefined
1401
+ : network;
1402
+
1403
+ export class ServiceUnreachable extends Data.TaggedError("Fly.ServiceUnreachable")<{
1404
+ service: string;
1405
+ target: string;
1406
+ network: string | undefined;
1407
+ targetNetwork: string | undefined;
1408
+ }> {
1409
+ get message() {
1410
+ return `Fly Service ${this.service} binds ${this.target}, but ${this.service} is on the ${this.network ?? "default"} network and ${this.target} is on the ${this.targetNetwork ?? "default"} network. Put both on the same \`network\`.`;
1411
+ }
1412
+ }
1413
+
1414
+ export class ServiceNotBindable extends Data.TaggedError("Fly.ServiceNotBindable")<{
1415
+ service: string;
1416
+ target: string;
1417
+ }> {
1418
+ get message() {
1419
+ return `Fly Service ${this.service} binds ${this.target}, which publishes no ports (\`services: []\`), so it has no private address.`;
1420
+ }
1421
+ }
1422
+
1423
+ export class EndpointNotPublished extends Data.TaggedError("Fly.EndpointNotPublished")<{
1424
+ service: string;
1425
+ target: string;
1426
+ port: number;
1427
+ }> {
1428
+ get message() {
1429
+ return `Fly Service ${this.service} binds port ${this.port} of ${this.target}, which does not publish it.`;
1430
+ }
1431
+ }
1432
+
1433
+ /** Check every Service this one binds is reachable from its network. */
1434
+ const validateTargets = (
1435
+ service: string,
1436
+ network: string | undefined,
1437
+ targets: readonly BoundTarget[],
1438
+ ) =>
1439
+ Effect.gen(function* () {
1440
+ for (const target of targets) {
1441
+ const targetNetwork = normalizeNetwork(target.network);
1442
+ if (targetNetwork !== normalizeNetwork(network)) {
1443
+ return yield* new ServiceUnreachable({
1444
+ service,
1445
+ target: target.service,
1446
+ network: normalizeNetwork(network),
1447
+ targetNetwork,
1448
+ });
1449
+ }
1450
+ if (target.privateUrl === undefined) {
1451
+ return yield* new ServiceNotBindable({ service, target: target.service });
1452
+ }
1453
+ if (
1454
+ target.port !== undefined &&
1455
+ !(target.endpoints ?? []).some((entry) => entry.port === target.port)
1456
+ ) {
1457
+ return yield* new EndpointNotPublished({
1458
+ service,
1459
+ target: target.service,
1460
+ port: target.port,
1461
+ });
1462
+ }
1463
+ }
1464
+ });
1465
+
1466
+ /**
1467
+ * Fail when a Machine outside this Service already publishes one of its
1468
+ * ports in a shared App. Catches Machines the App's bindings do not list:
1469
+ * other stacks, the `fly` CLI, or plain `Fly.Machine`s.
1470
+ */
1471
+ const validateObservedPorts = (
1472
+ appName: string,
1473
+ fqn: string,
1474
+ id: string,
1475
+ services: FlyMachineService[],
1476
+ ) =>
1477
+ Effect.gen(function* () {
1478
+ const listed = yield* machines
1479
+ .listMachines({ app_name: appName })
1480
+ .pipe(Effect.catchTag(["NotFound"], () => Effect.succeed([])));
1481
+ const others = new Map<string, FlyMachineService[] | undefined>();
1482
+ for (const machine of listed) {
1483
+ if (machine.state === "destroyed") continue;
1484
+ const owner = machine.config?.metadata?.[alchemyMetadataKeys.fqn] ?? machine.id ?? "";
1485
+ if (owner === fqn || others.has(owner)) continue;
1486
+ others.set(owner, machine.config?.services);
1487
+ }
1488
+ const mine = portsOfFly(services);
1489
+ for (const [owner, theirs] of others) {
1490
+ const conflict = findPortConflict(appName, [
1491
+ { id, ports: mine },
1492
+ { id: owner, ports: portsOfFly(theirs) },
1493
+ ]);
1494
+ if (conflict !== undefined && conflict.publishers[0] !== conflict.publishers[1])
1495
+ return yield* conflict;
1496
+ }
1497
+ });
1498
+
1499
+ const toAttrs = (set: ReplicaSet, codeHash: string, access: Access): Service["Attributes"] => ({
1500
+ appName: set.appName,
1501
+ ownsApp: access.ownsApp,
1502
+ network: normalizeNetwork(access.network),
1503
+ rpcToken: access.rpcToken,
1504
+ ...endpointsOf(set, access),
1505
+ rolloutPending: set.rolloutPending,
1506
+ machineId: set.machineId,
1507
+ machineIds: set.machineIds,
1508
+ name: set.name,
1509
+ baseName: set.baseName,
1510
+ region: set.region,
1511
+ regions: set.regions,
1512
+ state: set.state,
1513
+ imageRef: set.imageRef,
1514
+ count: Math.round(set.count / Math.max(1, set.regions.length)),
1515
+ mounts: set.mounts,
1516
+ replicas: set.replicas,
1517
+ code: { hash: codeHash },
1518
+ });
1519
+
1520
+ const machineIdsOf = (output: Service["Attributes"] | undefined) =>
1521
+ output?.machineIds ??
1522
+ (output?.machineId !== undefined && output.machineId.length > 0 ? [output.machineId] : []);
1523
+
1524
+ /** The private network the Service's Machines join. */
1525
+ const networkOf = (props: ServiceProps) =>
1526
+ normalizeNetwork(
1527
+ props.app === undefined ? props.network : (props.app as { network?: string }).network,
1528
+ );
1529
+
1530
+ /**
1531
+ * Resolve the App the Service runs in. A Service that owns its App creates
1532
+ * it with its addresses; one placed in an App gets a Flycast address on it
1533
+ * so bound callers can reach it.
1534
+ */
1535
+ const ensureServiceApp = Effect.fn(function* (
1536
+ id: string,
1537
+ props: ServiceProps,
1538
+ output: Service["Attributes"] | undefined,
1539
+ ) {
1540
+ yield* validateOwnership(props);
1541
+ const ownsApp = props.app === undefined;
1542
+ const isPublic = !ownsApp || props.public !== false;
1543
+ if (ownsApp) {
1544
+ const desired =
1545
+ props.name !== undefined
1546
+ ? sanitizeFlyAppName(props.name)
1547
+ : output?.ownsApp === true
1548
+ ? output.appName
1549
+ : yield* createFlyAppName(id);
1550
+ const app = yield* ensureApp({
1551
+ name: desired,
1552
+ network: props.network,
1553
+ previousName: output?.ownsApp === true ? output.appName : undefined,
1554
+ });
1555
+ const appName = app.name ?? desired;
1556
+ yield* syncOwnedAppAddresses(appName, isPublic, props.network);
1557
+ return { appName, ownsApp, isPublic, network: props.network };
1558
+ }
1559
+ const appName = appNameOf(props.app) ?? output?.appName;
1560
+ if (appName === undefined) {
1561
+ return yield* new ServiceAppNotResolved({
1562
+ message: "Fly.Service requires a resolved App with appName.",
1563
+ });
1564
+ }
1565
+ const network = networkOf(props);
1566
+ yield* ensureFlycastAddress(appName, network);
1567
+ return { appName, ownsApp, isPublic, network };
1568
+ });
1569
+
1570
+ export const ServiceProvider = () =>
1571
+ Provider.effect(
1572
+ Service,
1573
+ Effect.gen(function* () {
1574
+ const stack = yield* Stack;
1575
+ const docker = yield* Docker;
1576
+ const { dotAlchemy } = yield* AlchemyContext;
1577
+ const virtualEntryPlugin = yield* Bundle.virtualEntryPlugin;
1578
+ const hosted = createFlyHostedSupport({
1579
+ stackName: stack.name,
1580
+ stage: stack.stage,
1581
+ virtualEntryPlugin,
1582
+ docker,
1583
+ dotAlchemy,
1584
+ });
1585
+
1586
+ return Service.Provider.of({
1587
+ stables: ["appName"],
1588
+ nuke: { dependsOn: ["Fly.App"] },
1589
+
1590
+ diff: Effect.fn(function* ({ id, news, output }) {
1591
+ if (news === undefined) return;
1592
+ const shape = news as Partial<Pick<ServiceProps, "app" | "public" | "network">>;
1593
+ const ownsApp = shape.app === undefined;
1594
+ yield* validateOwnership(shape);
1595
+ if ("main" in news) {
1596
+ const settings: Input<
1597
+ Pick<
1598
+ ServiceProps,
1599
+ "deploy" | "shutdown" | "checks" | "services" | "port" | "isExternal" | "public"
1600
+ >
1601
+ > = {
1602
+ deploy: news.deploy,
1603
+ shutdown: news.shutdown,
1604
+ services: news.services,
1605
+ checks: news.checks,
1606
+ port: news.port,
1607
+ isExternal: news.isExternal,
1608
+ public: news.public,
1609
+ };
1610
+ if (
1611
+ isResolved<
1612
+ Pick<
1613
+ ServiceProps,
1614
+ "deploy" | "shutdown" | "checks" | "services" | "port" | "isExternal" | "public"
1615
+ >
1616
+ >(settings)
1617
+ ) {
1618
+ yield* validateDeployment(
1619
+ yield* deploymentPolicy(settings.deploy, settings.shutdown, !settings.isExternal),
1620
+ {
1621
+ services:
1622
+ settings.services?.map(toFlyService) ??
1623
+ defaultHttpServices(
1624
+ settings.port ?? DEFAULT_PORT,
1625
+ 1,
1626
+ !ownsApp || settings.public !== false,
1627
+ ),
1628
+ checks: settings.checks,
1629
+ },
1630
+ false,
1631
+ );
1632
+ }
1633
+ }
1634
+ if (output === undefined) return;
1635
+ // Moving into or out of a shared App changes the hostname.
1636
+ if (ownsApp !== (output.ownsApp === true)) {
1637
+ return { action: "replace" as const, deleteFirst: false };
1638
+ }
1639
+ if (ownsApp && isResolved(news)) {
1640
+ const desiredAppName =
1641
+ news.name !== undefined ? sanitizeFlyAppName(news.name) : output.appName;
1642
+ const nameChanged = desiredAppName !== output.appName;
1643
+ // Fly cannot move an App to another network.
1644
+ const networkChanged =
1645
+ normalizeNetwork(news.network) !== normalizeNetwork(output.network);
1646
+ if (nameChanged || networkChanged) {
1647
+ return {
1648
+ action: "replace" as const,
1649
+ // A pinned App name cannot exist twice.
1650
+ deleteFirst: !nameChanged && news.name !== undefined,
1651
+ };
1652
+ }
1653
+ }
1654
+ if (!ownsApp && isResolved(news)) {
1655
+ const desiredAppName = appNameOf(news.app);
1656
+ const appChanged = desiredAppName !== undefined && desiredAppName !== output.appName;
1657
+ const desiredName =
1658
+ news.name !== undefined
1659
+ ? sanitizeFlyAppName(news.name)
1660
+ : (output.baseName ?? output.name);
1661
+ const nameChanged = desiredName !== (output.baseName ?? output.name);
1662
+ if (appChanged || nameChanged) {
1663
+ return {
1664
+ action: "replace" as const,
1665
+ deleteFirst: nameChanged === false && appChanged === false,
1666
+ };
1667
+ }
1668
+ }
1669
+ // The code hash depends only on statically-known props (`main`,
1670
+ // `build`, `image`, `port`, `extraFiles`, `isExternal`). Never
1671
+ // gate it on the WHOLE props being resolved: `app` is a resource
1672
+ // reference that stays unresolved at diff time, so a whole-props
1673
+ // guard makes code-only changes silently noop. By diff time the
1674
+ // effect-config form has been evaluated, so the object view is
1675
+ // safe to read.
1676
+ const statics = news as Partial<
1677
+ Pick<ServiceProps, "main" | "build" | "image" | "port" | "extraFiles" | "isExternal">
1678
+ >;
1679
+ if (
1680
+ isResolved({
1681
+ main: statics.main,
1682
+ build: statics.build,
1683
+ image: statics.image,
1684
+ port: statics.port,
1685
+ extraFiles: statics.extraFiles,
1686
+ isExternal: statics.isExternal,
1687
+ }) &&
1688
+ statics.main !== undefined
1689
+ ) {
1690
+ const hash = yield* hosted.hash(statics as HostedProgramProps);
1691
+ if (hash !== output.code.hash) {
1692
+ return { action: "update" as const };
1693
+ }
1694
+ }
1695
+ return output.rolloutPending ? { action: "update" as const } : undefined;
1696
+ }),
1697
+
1698
+ read: Effect.fn(function* ({ id, fqn, instanceId, olds, output }) {
1699
+ const ownsApp = output?.ownsApp ?? (olds !== undefined && olds.app === undefined);
1700
+ const appName = ownsApp
1701
+ ? (output?.appName ??
1702
+ (olds?.name !== undefined
1703
+ ? sanitizeFlyAppName(olds.name)
1704
+ : yield* createFlyAppName(id)))
1705
+ : (appNameOf(olds?.app) ?? output?.appName);
1706
+ const name = yield* resolveMachineName(
1707
+ id,
1708
+ ownsApp ? undefined : olds?.name,
1709
+ output?.baseName ?? output?.name,
1710
+ );
1711
+ const found = yield* observeReplicaSet({
1712
+ appName,
1713
+ id,
1714
+ type: "Fly.Service",
1715
+ fqn,
1716
+ resourceInstanceId: instanceId,
1717
+ machineIds: machineIdsOf(output),
1718
+ baseName: name,
1719
+ });
1720
+ if (found === undefined) return undefined;
1721
+ return toAttrs(found, output?.code.hash ?? "", {
1722
+ ownsApp,
1723
+ isPublic: ownsApp && (yield* hasPublicAddress(found.appName)),
1724
+ network: output?.network ?? (ownsApp ? olds?.network : undefined),
1725
+ bindingPort: olds?.bindingPort ?? DEFAULT_BINDING_PORT,
1726
+ rpcToken: output?.rpcToken,
1727
+ });
1728
+ }),
1729
+
1730
+ list: Effect.fn(function* () {
1731
+ const sets = yield* listReplicaSets("Fly.Service");
1732
+ // Owned Apps are also listed (and nuked) as Fly.App rows.
1733
+ return sets.map((set) =>
1734
+ toAttrs(set, "", {
1735
+ ownsApp: false,
1736
+ isPublic: true,
1737
+ network: undefined,
1738
+ bindingPort: DEFAULT_BINDING_PORT,
1739
+ rpcToken: undefined,
1740
+ }),
1741
+ );
1742
+ }),
1743
+
1744
+ reconcile: Effect.fn(function* ({ id, fqn, instanceId, news, output, bindings, session }) {
1745
+ const props = news;
1746
+ const policy = yield* deploymentPolicy(props.deploy, props.shutdown, !props.isExternal);
1747
+ yield* validateOwnership(props);
1748
+ const bound = collectBindingState(bindings ?? []);
1749
+ // Before creating anything: every bound Service must be reachable.
1750
+ yield* validateTargets(id, networkOf(props), bound.targets);
1751
+ const { appName, ownsApp, isPublic, network } = yield* ensureServiceApp(
1752
+ id,
1753
+ props,
1754
+ output,
1755
+ );
1756
+ const name = yield* resolveMachineName(
1757
+ id,
1758
+ ownsApp ? undefined : props.name,
1759
+ output?.baseName ?? output?.name,
1760
+ );
1761
+ const regions = regionList(props.region, DEFAULT_REGION);
1762
+ const count = resolveCount(props.count);
1763
+ const port = props.port ?? DEFAULT_PORT;
1764
+ const bindingPort = props.bindingPort ?? DEFAULT_BINDING_PORT;
1765
+ const secretVersions: number[] = [];
1766
+ const redisVersion = yield* attachRedisSecrets(appName, bound.redis);
1767
+ if (redisVersion !== undefined) secretVersions.push(redisVersion);
1768
+ const bucketVersion = yield* attachBucketSecrets(appName, bound.buckets, {
1769
+ ...bound.env,
1770
+ ...toEnv(props.env),
1771
+ });
1772
+ if (bucketVersion !== undefined) secretVersions.push(bucketVersion);
1773
+ for (const pg of bound.postgres) {
1774
+ const version = yield* attachPostgresSecrets(appName, pg.clusterId, pg.variableName);
1775
+ if (version !== undefined) secretVersions.push(version);
1776
+ }
1777
+ const minSecretsVersion =
1778
+ secretVersions.length > 0 ? Math.max(...secretVersions) : undefined;
1779
+ const env = desiredEnv(props, bound.env, hosted.alchemyEnv, port);
1780
+ if (policy.shutdown && !props.isExternal) {
1781
+ env.ALCHEMY_FLY_SHUTDOWN_TIMEOUT_MS = String(policy.shutdown.timeoutMs);
1782
+ }
1783
+ const guest = toFlyGuest(props.guest);
1784
+ const published = withBindingService(
1785
+ props.services !== undefined
1786
+ ? props.services.map(toFlyService)
1787
+ : defaultHttpServices(port, count, isPublic),
1788
+ port,
1789
+ bindingPort,
1790
+ );
1791
+ const services = published.services;
1792
+ if (!ownsApp) yield* validateObservedPorts(appName, fqn, id, services);
1793
+ if (props.rpcToken !== undefined) env[RPC_TOKEN_ENV] = Redacted.value(props.rpcToken);
1794
+ for (const target of bound.targets) {
1795
+ const keys = boundTargetEnvKeys(target.service);
1796
+ env[keys.appName] = packEnvValue(target.appName);
1797
+ if (target.privateUrl !== undefined) env[keys.url] = packEnvValue(target.privateUrl);
1798
+ if (target.rpcToken !== undefined) env[keys.token] = packEnvValue(target.rpcToken);
1799
+ }
1800
+ env[RPC_ORG_ENV] = yield* resolveOrgSlug();
1801
+ if (published.added) env[BINDING_PORT_ENV] = String(bindingPort);
1802
+ const statics = toFlyStatics(props.statics);
1803
+
1804
+ const { imageRef, codeHash } = yield* hosted.resolveImage({
1805
+ id,
1806
+ appName,
1807
+ props,
1808
+ previousHash: output?.code.hash,
1809
+ session,
1810
+ });
1811
+
1812
+ const set = yield* reconcileReplicas({
1813
+ id,
1814
+ type: "Fly.Service",
1815
+ fqn,
1816
+ resourceInstanceId: instanceId,
1817
+ policy,
1818
+ checks: props.checks,
1819
+ appName,
1820
+ baseName: name,
1821
+ regions,
1822
+ // `count` is per region.
1823
+ count: count * regions.length,
1824
+ disks: bound.mounts,
1825
+ minSecretsVersion,
1826
+ outputMachineIds: machineIdsOf(output),
1827
+ preferVolumeIds: (output?.replicas ?? []).map((replica) =>
1828
+ replica.mounts.map((mount) => mount.volumeId),
1829
+ ),
1830
+ configDrifted: (machine, desired) =>
1831
+ configDrifted(machine, {
1832
+ image: imageRef,
1833
+ guest,
1834
+ env,
1835
+ services,
1836
+ mounts: desired.mounts,
1837
+ metadata: desired.metadata,
1838
+ statics,
1839
+ }),
1840
+ buildConfig: ({ mounts, metadata }) =>
1841
+ buildConfig({ image: imageRef, guest, env, services, mounts, metadata, statics }),
1842
+ }).pipe(
1843
+ Effect.catchTag("Fly.ReplicaNotCreated", (error) =>
1844
+ Effect.fail(new ServiceNotCreated({ name: error.name, appName: error.appName })),
1845
+ ),
1846
+ );
1847
+ return toAttrs(set, codeHash, {
1848
+ ownsApp,
1849
+ isPublic,
1850
+ network,
1851
+ bindingPort,
1852
+ rpcToken: props.rpcToken,
1853
+ });
1854
+ }),
1855
+
1856
+ // Create the App, its addresses, and the caller token before any
1857
+ // Machine, so two Services that bind each other can both resolve
1858
+ // the other's private address and token.
1859
+ precreate: Effect.fn(function* ({ id, news }) {
1860
+ const props = news;
1861
+ // Precreate runs before dependencies resolve. A Service placed in
1862
+ // an App cannot see the App yet, so it has no stub to offer;
1863
+ // cycles are supported between Services that own their App.
1864
+ const inert =
1865
+ props.app !== undefined ||
1866
+ !isResolved(props.name) ||
1867
+ !isResolved(props.network) ||
1868
+ !isResolved(props.services) ||
1869
+ !isResolved(props.bindingPort);
1870
+ // No stub: a failed create then recovers through `read`, which
1871
+ // finds the App from the persisted props.
1872
+ if (inert) return undefined as unknown as Service["Attributes"];
1873
+ const { appName, ownsApp, isPublic, network } = yield* ensureServiceApp(
1874
+ id,
1875
+ props,
1876
+ undefined,
1877
+ );
1878
+ const port = props.port ?? DEFAULT_PORT;
1879
+ const count = resolveCount(props.count);
1880
+ const bindingPort = props.bindingPort ?? DEFAULT_BINDING_PORT;
1881
+ const { services } = withBindingService(
1882
+ props.services !== undefined
1883
+ ? props.services.map(toFlyService)
1884
+ : defaultHttpServices(port, count, isPublic),
1885
+ port,
1886
+ bindingPort,
1887
+ );
1888
+ const name = yield* resolveMachineName(id, ownsApp ? undefined : props.name);
1889
+ const stub: ReplicaSet = {
1890
+ appName,
1891
+ machineId: "",
1892
+ machineIds: [],
1893
+ name,
1894
+ baseName: name,
1895
+ region: regionList(props.region, DEFAULT_REGION)[0]!,
1896
+ regions: regionList(props.region, DEFAULT_REGION),
1897
+ state: "created",
1898
+ instanceId: undefined,
1899
+ privateIp: undefined,
1900
+ imageRef: undefined,
1901
+ guest: undefined,
1902
+ services,
1903
+ count: 0,
1904
+ mounts: [],
1905
+ replicas: [],
1906
+ };
1907
+ return toAttrs(stub, "", {
1908
+ ownsApp,
1909
+ isPublic,
1910
+ network,
1911
+ bindingPort,
1912
+ rpcToken: isResolved(props.rpcToken) ? props.rpcToken : undefined,
1913
+ });
1914
+ }),
1915
+
1916
+ delete: Effect.fn(function* ({ id, fqn, instanceId, olds, output, force }) {
1917
+ const appName = output.appName || appNameOf(olds.app);
1918
+ // A precreate stub that never reached its App has nothing to delete.
1919
+ if (appName === undefined || appName.length === 0) return;
1920
+ yield* deleteReplicaSet({
1921
+ appName,
1922
+ id,
1923
+ type: "Fly.Service",
1924
+ fqn,
1925
+ resourceInstanceId: instanceId,
1926
+ machineIds: machineIdsOf(output),
1927
+ volumeIds: volumeIdsOf(output),
1928
+ force,
1929
+ });
1930
+ if (output.ownsApp === true) yield* deleteApp(appName);
1931
+ }),
1932
+ });
1933
+ }),
1934
+ ).pipe(Layer.provide(DockerLive));