From ec6e010eb3aee4daae35e8f834c84eaf9224fd0d Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 25 Nov 2026 04:37:24 -0500 Subject: [PATCH 1/4] feat(packs): railway emitter for .railway/railway.ts, secret sync, deploy and doctor scripts The railway pack now generates Railway's Infrastructure as Code file (.railway/railway.ts, the railway/iac DSL of the railway npm package 3.17.0, as a named partial) from deployment.railway and the app it places, plus deploy/unexpressed.md (the facts the file cannot hold), deploy/sync-secrets.sh (declared secrets copied from the vault scope to Railway through keys-axi and railway variable set --stdin, never printed or on a command line), deploy/deploy.sh, deploy/doctor.sh and a deploy skill. The generators write files only; the library talks to no platform. Vocabulary: deployment.railway gains @repo, @image and @checkSuites (a plan with no source disconnects a service); the delivery pack gains @watchInclude on build.* and @path on value.ref. The railway pack now requires the config pack for settings and vaults. Two new conformance fixtures (one service, unmanaged variables; two services from one monorepo, managed variables with references) carry golden output tests, and model checks refuse what Railway cannot do. TypeScript only. No core vocabulary or version change. --- bun.lock | 3 + packs/README.md | 2 +- packs/delivery/CHANGELOG.md | 4 + packs/delivery/README.md | 8 +- .../fixtures/expected-vocabulary.json | 43 +- packs/delivery/metamodel/delivery.json | 6 +- packs/delivery/typescript/src/constants.ts | 18 + packs/railway/CHANGELOG.md | 14 +- packs/railway/README.md | 111 +++- .../railway-emit-one-service/expected.json | 155 ++++++ .../input/meta.game.json | 59 ++ .../railway-emit-one-service/providers.json | 1 + .../railway-emit-two-services/expected.json | 312 +++++++++++ .../input/meta.tables.json | 100 ++++ .../railway-emit-two-services/providers.json | 1 + .../railway/fixtures/expected-vocabulary.json | 21 + packs/railway/metamodel/railway.json | 5 +- packs/railway/pack.json | 4 +- packs/railway/typescript/package.json | 5 +- packs/railway/typescript/src/constants.ts | 50 ++ packs/railway/typescript/src/files.ts | 404 ++++++++++++++ packs/railway/typescript/src/generators.ts | 108 ++++ packs/railway/typescript/src/index.ts | 47 +- packs/railway/typescript/src/model.ts | 524 ++++++++++++++++++ packs/railway/typescript/src/railway-ts.ts | 170 ++++++ packs/railway/typescript/test/emit.test.ts | 55 ++ .../.claude/skills/deploy/SKILL.md | 42 ++ .../.railway/railway.ts | 56 ++ .../railway-emit-one-service/deploy/deploy.sh | 59 ++ .../railway-emit-one-service/deploy/doctor.sh | 71 +++ .../deploy/sync-secrets.sh | 33 ++ .../deploy/unexpressed.md | 18 + .../.claude/skills/deploy/SKILL.md | 43 ++ .../.railway/railway.ts | 77 +++ .../deploy/deploy.sh | 61 ++ .../deploy/doctor.sh | 72 +++ .../deploy/sync-secrets.sh | 36 ++ .../deploy/unexpressed.md | 27 + packs/railway/typescript/test/model.test.ts | 132 +++++ packs/railway/typescript/test/model.ts | 32 ++ packs/railway/typescript/tsconfig.json | 3 +- 41 files changed, 2948 insertions(+), 44 deletions(-) create mode 100644 packs/railway/fixtures/conformance/railway-emit-one-service/expected.json create mode 100644 packs/railway/fixtures/conformance/railway-emit-one-service/input/meta.game.json create mode 100644 packs/railway/fixtures/conformance/railway-emit-one-service/providers.json create mode 100644 packs/railway/fixtures/conformance/railway-emit-two-services/expected.json create mode 100644 packs/railway/fixtures/conformance/railway-emit-two-services/input/meta.tables.json create mode 100644 packs/railway/fixtures/conformance/railway-emit-two-services/providers.json create mode 100644 packs/railway/typescript/src/constants.ts create mode 100644 packs/railway/typescript/src/files.ts create mode 100644 packs/railway/typescript/src/generators.ts create mode 100644 packs/railway/typescript/src/model.ts create mode 100644 packs/railway/typescript/src/railway-ts.ts create mode 100644 packs/railway/typescript/test/emit.test.ts create mode 100644 packs/railway/typescript/test/golden/railway-emit-one-service/.claude/skills/deploy/SKILL.md create mode 100644 packs/railway/typescript/test/golden/railway-emit-one-service/.railway/railway.ts create mode 100644 packs/railway/typescript/test/golden/railway-emit-one-service/deploy/deploy.sh create mode 100644 packs/railway/typescript/test/golden/railway-emit-one-service/deploy/doctor.sh create mode 100644 packs/railway/typescript/test/golden/railway-emit-one-service/deploy/sync-secrets.sh create mode 100644 packs/railway/typescript/test/golden/railway-emit-one-service/deploy/unexpressed.md create mode 100644 packs/railway/typescript/test/golden/railway-emit-two-services/.claude/skills/deploy/SKILL.md create mode 100644 packs/railway/typescript/test/golden/railway-emit-two-services/.railway/railway.ts create mode 100644 packs/railway/typescript/test/golden/railway-emit-two-services/deploy/deploy.sh create mode 100644 packs/railway/typescript/test/golden/railway-emit-two-services/deploy/doctor.sh create mode 100644 packs/railway/typescript/test/golden/railway-emit-two-services/deploy/sync-secrets.sh create mode 100644 packs/railway/typescript/test/golden/railway-emit-two-services/deploy/unexpressed.md create mode 100644 packs/railway/typescript/test/model.test.ts create mode 100644 packs/railway/typescript/test/model.ts diff --git a/bun.lock b/bun.lock index db918b869..4e0c0e79f 100644 --- a/bun.lock +++ b/bun.lock @@ -181,13 +181,16 @@ "name": "@metaobjectsdev/pack-railway", "version": "0.1.0", "dependencies": { + "@metaobjectsdev/pack-config": "workspace:*", "@metaobjectsdev/pack-delivery": "workspace:*", "@metaobjectsdev/pack-systems": "workspace:*", }, "devDependencies": { + "@metaobjectsdev/codegen-ts": "workspace:*", "@metaobjectsdev/metadata": "workspace:*", }, "peerDependencies": { + "@metaobjectsdev/codegen-ts": ">=1.3.0 <2.0.0", "@metaobjectsdev/metadata": ">=1.3.0 <2.0.0", }, }, diff --git a/packs/README.md b/packs/README.md index 930c45252..ffe883f31 100644 --- a/packs/README.md +++ b/packs/README.md @@ -9,7 +9,7 @@ that is not part of core, built and versioned as if it were its own repository | [`config`](config/README.md) | settings groups, `@secret` / `@envName` / `@phase`, vaults (Infisical) and their scopes; `.env.example`, key manifest and `.keys-axi.toml` generators | core | TypeScript | | [`systems`](systems/README.md) | systems, apps (service, client, job), resources | core | TypeScript | | [`delivery`](delivery/README.md) | environments, builds, runtime processes, deployments, value bindings | `systems` | TypeScript | -| [`railway`](railway/README.md) | `deployment.railway` (vocabulary only; the emitter is later work) | `delivery` | TypeScript | +| [`railway`](railway/README.md) | `deployment.railway`; `.railway/railway.ts` (Railway Infrastructure as Code), unexpressed-facts list, secret sync, deploy and doctor scripts and a deploy skill | `delivery`, `config` | TypeScript | An independent pack is not in the default bundle. A project opts in by naming its provider. It is never in `fixtures/registry-conformance/expected-registry.json` and never moves diff --git a/packs/delivery/CHANGELOG.md b/packs/delivery/CHANGELOG.md index 252b8a193..383f3ba73 100644 --- a/packs/delivery/CHANGELOG.md +++ b/packs/delivery/CHANGELOG.md @@ -11,3 +11,7 @@ This pack's own changelog (ADR-0069). The root `CHANGELOG.md` records core only. `@secrets` and `@setting` are names only. A deployment holds one value per `@setting` (`ERR_DELIVERY_DUPLICATE_SETTING`) and a model one deployment per (`@app`, `@environment`) (`ERR_DELIVERY_DUPLICATE_DEPLOYMENT`). TypeScript port. +- `@watchInclude` on every `build.*`, beside `@watchExclude`: the paths whose change starts a + build, for an app that lives in one directory of a monorepo. +- `@path` on `value.ref`: a path appended to a URL output (`/api`), for a setting that addresses + one context of another app. diff --git a/packs/delivery/README.md b/packs/delivery/README.md index b986b87d2..e060e17bb 100644 --- a/packs/delivery/README.md +++ b/packs/delivery/README.md @@ -13,13 +13,13 @@ in one environment on one platform, and holds only what differs there. | Node | Where | What it is | Attributes | |---|---|---|---| | `environment.standing`, `.ephemeral`, `.local` | document root | A named environment: production, a pull-request preview, a workstation | (documentation only) | -| `build.dockerfile` | under an `app.*`, at most one build | Built as an image from a Dockerfile | `@path`, `@context`, `@watchExclude` | -| `build.command` | under an `app.*` | Built by a command the platform's builder runs | `@command`, `@watchExclude` | -| `build.static` | under an `app.*` | A directory of files served as they are | `@directory`, `@command`, `@watchExclude` | +| `build.dockerfile` | under an `app.*`, at most one build | Built as an image from a Dockerfile | `@path`, `@context`, `@watchInclude`, `@watchExclude` | +| `build.command` | under an `app.*` | Built by a command the platform's builder runs | `@command`, `@watchInclude`, `@watchExclude` | +| `build.static` | under an `app.*` | A directory of files served as they are | `@directory`, `@command`, `@watchInclude`, `@watchExclude` | | `runtime.process` | under an `app.*` | How one of its processes runs | `@command`, `@port`, `@healthPath`, `@healthTimeoutSeconds`, `@drainSeconds`, `@restart` (`always`, `onFailure`, `never`) | | `deployment.` | document root | An app in an environment on a platform. A **platform pack** registers the subtype (the [`railway`](../railway/README.md) pack registers `deployment.railway`) | `@app`, `@environment`, `@domains`, `@replicas`, `@region`, `@branch`, `@secrets`, plus the platform's own | | `value.literal` | under a deployment | A setting's fixed value there | `@setting`, `@literal` | -| `value.ref` | under a deployment | A setting's value produced by another node at deploy time | `@setting`, `@producedBy`, `@output` | +| `value.ref` | under a deployment | A setting's value produced by another node at deploy time | `@setting`, `@producedBy`, `@output`, `@path` | `deployment.base` is the abstract anchor platform packs specialise (`extendsBase: true`); this pack registers no concrete deployment, and an authored `deployment.base` fails to load diff --git a/packs/delivery/fixtures/expected-vocabulary.json b/packs/delivery/fixtures/expected-vocabulary.json index 465adba7b..c2b1aa709 100644 --- a/packs/delivery/fixtures/expected-vocabulary.json +++ b/packs/delivery/fixtures/expected-vocabulary.json @@ -11,7 +11,14 @@ "valueType": "string", "isArray": true, "required": false, - "description": "Repository path globs whose change must not start a new build (`docs/**`, `*.md`). A platform that has no place for them in its own file gets them as a fact to set by hand, which its generator lists." + "description": "Repository path globs whose change must not start a new build (`docs/**`, `/*.md`), written as gitignore-style globs from the repository root; an exclusion wins over an inclusion. A platform that has no place for them in its own file gets them as a fact to set by hand, which its generator lists." + }, + { + "name": "watchInclude", + "valueType": "string", + "isArray": true, + "required": false, + "description": "Repository path globs whose change starts a new build (`api/**`), written as gitignore-style globs from the repository root. Absent means every path: a monorepo app names only its own directories. A platform that has no place for them in its own file gets them as a fact to set by hand, which its generator lists." } ], "children": [] @@ -34,7 +41,14 @@ "valueType": "string", "isArray": true, "required": false, - "description": "Repository path globs whose change must not start a new build (`docs/**`, `*.md`). A platform that has no place for them in its own file gets them as a fact to set by hand, which its generator lists." + "description": "Repository path globs whose change must not start a new build (`docs/**`, `/*.md`), written as gitignore-style globs from the repository root; an exclusion wins over an inclusion. A platform that has no place for them in its own file gets them as a fact to set by hand, which its generator lists." + }, + { + "name": "watchInclude", + "valueType": "string", + "isArray": true, + "required": false, + "description": "Repository path globs whose change starts a new build (`api/**`), written as gitignore-style globs from the repository root. Absent means every path: a monorepo app names only its own directories. A platform that has no place for them in its own file gets them as a fact to set by hand, which its generator lists." } ], "children": [] @@ -64,7 +78,14 @@ "valueType": "string", "isArray": true, "required": false, - "description": "Repository path globs whose change must not start a new build (`docs/**`, `*.md`). A platform that has no place for them in its own file gets them as a fact to set by hand, which its generator lists." + "description": "Repository path globs whose change must not start a new build (`docs/**`, `/*.md`), written as gitignore-style globs from the repository root; an exclusion wins over an inclusion. A platform that has no place for them in its own file gets them as a fact to set by hand, which its generator lists." + }, + { + "name": "watchInclude", + "valueType": "string", + "isArray": true, + "required": false, + "description": "Repository path globs whose change starts a new build (`api/**`), written as gitignore-style globs from the repository root. Absent means every path: a monorepo app names only its own directories. A platform that has no place for them in its own file gets them as a fact to set by hand, which its generator lists." } ], "children": [] @@ -94,7 +115,14 @@ "valueType": "string", "isArray": true, "required": false, - "description": "Repository path globs whose change must not start a new build (`docs/**`, `*.md`). A platform that has no place for them in its own file gets them as a fact to set by hand, which its generator lists." + "description": "Repository path globs whose change must not start a new build (`docs/**`, `/*.md`), written as gitignore-style globs from the repository root; an exclusion wins over an inclusion. A platform that has no place for them in its own file gets them as a fact to set by hand, which its generator lists." + }, + { + "name": "watchInclude", + "valueType": "string", + "isArray": true, + "required": false, + "description": "Repository path globs whose change starts a new build (`api/**`), written as gitignore-style globs from the repository root. Absent means every path: a monorepo app names only its own directories. A platform that has no place for them in its own file gets them as a fact to set by hand, which its generator lists." } ], "children": [] @@ -314,6 +342,13 @@ ], "description": "Which of its values: url, host, port, user, password, privateUrl, publicUrl. A platform generator maps the name to the platform's own reference and refuses one it cannot supply." }, + { + "name": "path", + "valueType": "string", + "isArray": false, + "required": false, + "description": "A path appended to a URL output (`/api`): the address of one context of the producing app. Only on a url, privateUrl or publicUrl output; a platform generator refuses it on another." + }, { "name": "producedBy", "valueType": "string", diff --git a/packs/delivery/metamodel/delivery.json b/packs/delivery/metamodel/delivery.json index 342498fc1..55da30d74 100644 --- a/packs/delivery/metamodel/delivery.json +++ b/packs/delivery/metamodel/delivery.json @@ -14,7 +14,8 @@ "subType": "base", "description": "Abstract build base: the attributes every build.* shares. A build is a child of an app and says how its deployable is made, the same in every environment. Not authored directly: a `build.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED).", "children": [ - { "type": "attr", "subType": "string", "name": "watchExclude", "isArray": true, "min": 0, "max": 1, "description": "Repository path globs whose change must not start a new build (`docs/**`, `*.md`). A platform that has no place for them in its own file gets them as a fact to set by hand, which its generator lists." } + { "type": "attr", "subType": "string", "name": "watchInclude", "isArray": true, "min": 0, "max": 1, "description": "Repository path globs whose change starts a new build (`api/**`), written as gitignore-style globs from the repository root. Absent means every path: a monorepo app names only its own directories. A platform that has no place for them in its own file gets them as a fact to set by hand, which its generator lists." }, + { "type": "attr", "subType": "string", "name": "watchExclude", "isArray": true, "min": 0, "max": 1, "description": "Repository path globs whose change must not start a new build (`docs/**`, `/*.md`), written as gitignore-style globs from the repository root; an exclusion wins over an inclusion. A platform that has no place for them in its own file gets them as a fact to set by hand, which its generator lists." } ] }, { @@ -104,7 +105,8 @@ "whenToUse": "A setting whose value only the platform knows once the resource or app exists.", "children": [ { "type": "attr", "subType": "string", "name": "producedBy", "min": 1, "max": 1, "description": "The node that produces the value: a resource.* or app.*, as `System.child` (`Shop.db`, or `pkg::System.child`). It must resolve (ERR_DELIVERY_UNRESOLVED_REF)." }, - { "type": "attr", "subType": "string", "name": "output", "min": 1, "max": 1, "allowedValues": ["url", "host", "port", "user", "password", "privateUrl", "publicUrl"], "description": "Which of its values: url, host, port, user, password, privateUrl, publicUrl. A platform generator maps the name to the platform's own reference and refuses one it cannot supply." } + { "type": "attr", "subType": "string", "name": "output", "min": 1, "max": 1, "allowedValues": ["url", "host", "port", "user", "password", "privateUrl", "publicUrl"], "description": "Which of its values: url, host, port, user, password, privateUrl, publicUrl. A platform generator maps the name to the platform's own reference and refuses one it cannot supply." }, + { "type": "attr", "subType": "string", "name": "path", "min": 0, "max": 1, "description": "A path appended to a URL output (`/api`): the address of one context of the producing app. Only on a url, privateUrl or publicUrl output; a platform generator refuses it on another." } ] } ], diff --git a/packs/delivery/typescript/src/constants.ts b/packs/delivery/typescript/src/constants.ts index 257f5b218..d20528f21 100644 --- a/packs/delivery/typescript/src/constants.ts +++ b/packs/delivery/typescript/src/constants.ts @@ -12,9 +12,24 @@ export const TYPE_BUILD = "build"; export const BUILD_SUBTYPE_DOCKERFILE = "dockerfile"; export const BUILD_SUBTYPE_COMMAND = "command"; export const BUILD_SUBTYPE_STATIC = "static"; +export const BUILD_ATTR_WATCH_INCLUDE = "watchInclude"; +export const BUILD_ATTR_WATCH_EXCLUDE = "watchExclude"; +export const BUILD_ATTR_PATH = "path"; +export const BUILD_ATTR_CONTEXT = "context"; +export const BUILD_ATTR_COMMAND = "command"; +export const BUILD_ATTR_DIRECTORY = "directory"; export const TYPE_RUNTIME = "runtime"; export const RUNTIME_SUBTYPE_PROCESS = "process"; +export const RUNTIME_ATTR_COMMAND = "command"; +export const RUNTIME_ATTR_PORT = "port"; +export const RUNTIME_ATTR_HEALTH_PATH = "healthPath"; +export const RUNTIME_ATTR_HEALTH_TIMEOUT_SECONDS = "healthTimeoutSeconds"; +export const RUNTIME_ATTR_DRAIN_SECONDS = "drainSeconds"; +export const RUNTIME_ATTR_RESTART = "restart"; +export const RESTART_ALWAYS = "always"; +export const RESTART_ON_FAILURE = "onFailure"; +export const RESTART_NEVER = "never"; /** A platform pack registers the concrete `deployment.` subtype. */ export const TYPE_DEPLOYMENT = "deployment"; @@ -33,6 +48,9 @@ export const VALUE_ATTR_SETTING = "setting"; export const VALUE_ATTR_LITERAL = "literal"; export const VALUE_ATTR_PRODUCED_BY = "producedBy"; export const VALUE_ATTR_OUTPUT = "output"; +export const VALUE_ATTR_PATH = "path"; +export const VALUE_OUTPUTS = ["url", "host", "port", "user", "password", "privateUrl", "publicUrl"] as const; +export type ValueOutput = (typeof VALUE_OUTPUTS)[number]; /** Raised when a deployment's @app / @environment or a value.ref's @producedBy names nothing, or the wrong kind of node. */ export const ERR_DELIVERY_UNRESOLVED_REF = "ERR_DELIVERY_UNRESOLVED_REF"; diff --git a/packs/railway/CHANGELOG.md b/packs/railway/CHANGELOG.md index 07c23ae5d..51057d822 100644 --- a/packs/railway/CHANGELOG.md +++ b/packs/railway/CHANGELOG.md @@ -4,7 +4,13 @@ This pack's own changelog (ADR-0069). The root `CHANGELOG.md` records core only. ## [0.1.0] - unreleased -- **First version: vocabulary only.** `deployment.railway` (`@project`, `@service`) on the - delivery pack's `deployment.base`, held to its references. The worked example (an app's model - plus an estate repository's additions and overlay) is the `railway-worked-example` fixture. - TypeScript port. +- **First version.** `deployment.railway` (`@project`, `@service`) on the delivery pack's + `deployment.base`, held to its references. The worked example (an app's model plus an estate + repository's additions and overlay) is the `railway-worked-example` fixture. TypeScript port. +- `@repo`, `@image` and `@checkSuites` on `deployment.railway`: the service's source. +- **Generators**: `.railway/railway.ts` in Railway's Infrastructure as Code format (the `railway` + npm package 3.17.0's `railway/iac` DSL, a named partial), `deploy/unexpressed.md` (the facts the + file does not hold), `deploy/sync-secrets.sh` (vault to Railway through `keys-axi`), + `deploy/deploy.sh`, `deploy/doctor.sh` and a deploy skill. The pack now requires the config pack, + for settings and vaults. Fixtures `railway-emit-one-service` and `railway-emit-two-services`, + with golden output. TypeScript port. diff --git a/packs/railway/README.md b/packs/railway/README.md index e56ab311b..60f465536 100644 --- a/packs/railway/README.md +++ b/packs/railway/README.md @@ -2,30 +2,115 @@ `metaobjects-railway`, version 0.1.0, **preview**, unpublished. An independent pack ([ADR-0069](../../spec/decisions/ADR-0069-independent-packs.md)). Requires -[`delivery`](../delivery/README.md). +[`delivery`](../delivery/README.md) and [`config`](../config/README.md). -Railway as a deployment platform. **Vocabulary only so far:** it registers `deployment.railway`, -so a model can place an app on Railway and be checked. The generators (the `.railway/railway.ts` -file, the list of facts that file cannot hold, the secret sync, deploy and doctor scripts) are -later work in this pack. +Railway as a deployment platform. It registers `deployment.railway`, and it generates Railway's +Infrastructure as Code file `.railway/railway.ts` with the files beside it: the facts that file +cannot hold, a script that copies the declared secrets from the vault to Railway, a deploy script, +a doctor script and a deploy skill. The generators write files and stop: MetaObjects never talks to +Railway or to a vault. The scripts do, with the `railway` and `keys-axi` CLIs, when someone runs +them. ## Vocabulary | Node | Attributes | |---|---| -| `deployment.railway` | every `deployment.base` attribute (`@app`, `@environment`, `@domains`, `@replicas`, `@region`, `@branch`, `@secrets`, and `value.*` children), plus `@project` (required) and `@service` (absent: the app's name) | +| `deployment.railway` | every `deployment.base` attribute (`@app`, `@environment`, `@domains`, `@replicas`, `@region`, `@branch`, `@secrets`, and `value.*` children), plus `@project` (required), `@service` (absent: the app's name), `@repo` (GitHub `owner/name`) or `@image` (a container image), and `@checkSuites` (whether a deploy waits for GitHub check suites; absent leaves Railway's setting alone) | A `deployment.railway` is held to the delivery pack's references: `@app` must name an `app.*`, `@environment` an `environment.*` (`ERR_DELIVERY_UNRESOLVED_REF`). -## The worked example +## Generators -[`fixtures/conformance/railway-worked-example/`](fixtures/conformance/railway-worked-example/) is -an app's systems model (one service with its build and process facts, a database, a cache, an -outside bucket, two outside systems, a production deployment with a database URL by reference and a -literal profile) and an estate repository's additions (a staging environment and deployment it -declares itself, and an overlay that runs production on two replicas). Names, domains and project -names are placeholders. +| Generator | Writes | What it is | +|---|---|---| +| `railwayTsFile()` | `.railway/railway.ts` | The Railway project in the `railway/iac` DSL (`railway` npm package 3.17.0): one named partial, one branch per environment, one `service()` per deployment | +| `railwayUnexpressedFile()` | `deploy/unexpressed.md` | Per deployment, each fact the file does not hold and how it is carried instead | +| `railwaySyncSecretsScript()` | `deploy/sync-secrets.sh` | Copies each secret setting from its vault scope to the Railway service (`keys-axi run`, then `railway variable set --stdin --skip-deploys`) | +| `railwayDeployScript()` | `deploy/deploy.sh` | Syncs the secrets, then `railway config plan` and `apply`; `--redeploy` redeploys and waits for the health path; then runs the doctor | +| `railwayDoctorScript()` | `deploy/doctor.sh` | Checks, by name only, that each secret is in the vault and on Railway, that the file matches Railway (`railway config plan --detailed-exit-code`), and that each domain answers on the health path | +| `railwayDeploySkill()` | `.claude/skills/deploy/SKILL.md` | How an agent deploys with those scripts, and the rules it keeps | +| `railwayFiles()` | all six | The six generators with the same options | + +Each takes `{ path?, target?, project?, partial? }`. A model that deploys to more than one +Railway project needs `project`, since one file declares one project. `partial` defaults to the +service's name when the project has one service, else the project's name. + +### What the file says + +| Model | `.railway/railway.ts` | +|---|---| +| `@repo` / `@branch` / `@checkSuites`, or `@image` | `source: github(repo, { branch, checkSuites })` or `image(ref)`. One of `@repo` and `@image` is required: a plan of a service with no source disconnects it | +| `build.* @watchInclude` / `@watchExclude` | `build.watchPatterns`: the inclusions (`**` when there are none), then each exclusion with `!` | +| `build.dockerfile @path` | `build.builder: "DOCKERFILE"`, `build.dockerfilePath` | +| `build.command @command` | `build.buildCommand` | +| the first `runtime.process` | `deploy.startCommand`, `healthcheckPath`, `healthcheckTimeout`, `restartPolicyType` (`always` `ALWAYS`, `onFailure` `ON_FAILURE`, `never` `NEVER`), `drainingSeconds` | +| `app.job @schedule` | `deploy.cronSchedule` | +| `@domains` | `domains`, each with the process's `@port` when it has one | +| `@replicas`, `@region` | `replicas`, per region when `@region` is set | +| `value.literal` | an `env` entry with the literal | +| `value.ref` of a database or cache | the Railway reference to its template's variable (`${{db.DATABASE_URL}}`; postgres, mysql, redis, mongo) | +| `value.ref` of another app | `host` `${{svc.RAILWAY_PRIVATE_DOMAIN}}`, `port` its `@port`, `privateUrl` `http://${{svc.RAILWAY_PRIVATE_DOMAIN}}:port`, `publicUrl` `https://${{svc.RAILWAY_PUBLIC_DOMAIN}}`, with `@path` appended | + +Variables: when no deployment in the project declares a `value.*` node, the file says +`variables: { managed: false }` and an apply changes no variable (the CLI reads it; the railway +3.17.0 SDK's types do not declare it, so a type-check of the file with them reports that line). +When one does, the file manages every variable of its services: each setting of the app's +`@settings` groups is declared, a secret as `preserve()` (the sync script sets it), a non-secret +with no value as its `@default` or `preserve()`. An apply deletes a variable a managed file does not +declare, so in that case every app in the project must read its settings groups. + +The file is a named partial: databases, volumes and anything else it does not declare are left as +they are. Railway does not read the file during a deploy; `railway config apply` does, against the +linked environment, with the SDK installed beside it +(`npm install --no-save --prefix .railway railway@3.17.0`, which `deploy.sh` and `doctor.sh` run). + +### Checks + +The generators refuse, naming each node, a model whose deploy Railway could not do: a deployment +with no source or two, a secret setting with no vault (`@secrets`) or no scope for the +environment, a vault other than `vault.infisical`, a value for a secret setting or for a setting +nobody declared, a reference to a resource managed outside Railway or to an output its engine does +not supply, `@path` on an output that is not a URL, an `@settings` group that is not in the model, +an app with no settings in a managed file, and a partial name Railway refuses. + +### Wiring + +These files belong at the repository root, so give them a target whose `outDir` is `"."`. As for +the config pack, `meta gen` runs no generator over a model with no object at all: systems, +deployments and vaults are not objects, so the model needs its settings groups (`object.settings`) +for these files to be written. + +```ts +import { defineConfig } from "@metaobjectsdev/cli"; +import { configProvider } from "@metaobjectsdev/pack-config"; +import { provider as deliveryProvider } from "@metaobjectsdev/pack-delivery"; +import { provider as railwayProvider, railwayFiles } from "@metaobjectsdev/pack-railway"; +import { provider as systemsProvider } from "@metaobjectsdev/pack-systems"; + +export default defineConfig({ + outDir: "src/generated", // the project's existing setting + providers: [systemsProvider, deliveryProvider, configProvider, railwayProvider], + targets: { root: { outDir: "." } }, + generators: [...railwayFiles({ target: "root" })], +}); +``` + +## Fixtures + +- [`railway-worked-example/`](fixtures/conformance/railway-worked-example/): an app's systems model + (one service with its build and process facts, a database, a cache, an outside bucket, two + outside systems, a production deployment with a database URL by reference and a literal profile) + and an estate repository's additions (a staging environment and deployment it declares itself, + and an overlay that runs production on two replicas). +- [`railway-emit-one-service/`](fixtures/conformance/railway-emit-one-service/): one Spring service + from one repository, unmanaged variables, secrets from the vault. Its generated files are in + [`typescript/test/golden/`](typescript/test/golden/). +- [`railway-emit-two-services/`](fixtures/conformance/railway-emit-two-services/): two services + from one monorepo, each built from its own directory, one calling the other over Railway's + private network, managed variables. + +Names, domains, repositories and project names are placeholders. ## Ports diff --git a/packs/railway/fixtures/conformance/railway-emit-one-service/expected.json b/packs/railway/fixtures/conformance/railway-emit-one-service/expected.json new file mode 100644 index 000000000..bc6b07f5d --- /dev/null +++ b/packs/railway/fixtures/conformance/railway-emit-one-service/expected.json @@ -0,0 +1,155 @@ +{ + "metadata.root": { + "package": "acme::game", + "children": [ + { + "system.internal": { + "name": "Game", + "@description": "One Spring service in one repository, with its database and cache beside it on Railway.", + "children": [ + { + "app.service": { + "name": "server", + "@needs": [ + "db", + "cache" + ], + "@settings": [ + "Database", + "Redis", + "Llm" + ], + "children": [ + { + "build.dockerfile": { + "name": "image", + "@watchExclude": [ + "/.archive/**", + "/.claude/**", + "/.docs/**", + "/.github/**", + "/.githooks/**", + "/.metaobjects/*.md", + "/.metaobjects/.agent-context.json", + "/.specify/**", + "/.test-prompts/**", + "/assets/**", + "/docs/**", + "/e2e-tests/**", + "/scripts/**", + "/*.md", + "/TODOs" + ] + } + }, + { + "runtime.process": { + "name": "web", + "@drainSeconds": 180, + "@healthPath": "/actuator/health/container", + "@healthTimeoutSeconds": 300, + "@port": 8080, + "@restart": "onFailure" + } + } + ] + } + }, + { + "resource.database": { + "name": "db", + "@engine": "postgres", + "@version": "18" + } + }, + { + "resource.cache": { + "name": "cache", + "@engine": "redis" + } + } + ] + } + }, + { + "object.settings": { + "name": "Database", + "children": [ + { + "field.string": { + "name": "url", + "@required": true + } + } + ] + } + }, + { + "object.settings": { + "name": "Redis", + "children": [ + { + "field.string": { + "name": "url", + "@required": true + } + } + ] + } + }, + { + "object.settings": { + "name": "Llm", + "children": [ + { + "field.string": { + "name": "apiKey", + "@envName": "LLM_API_KEY", + "@required": true, + "@secret": true + } + }, + { + "field.string": { + "name": "model", + "@default": "small" + } + } + ] + } + }, + { + "vault.infisical": { + "name": "keys", + "children": [ + { + "scope.env": { + "name": "production", + "@env": "prod", + "@project": "acme-game" + } + } + ] + } + }, + { + "environment.standing": { + "name": "production" + } + }, + { + "deployment.railway": { + "name": "server-production", + "@app": "Game.server", + "@branch": "main", + "@checkSuites": false, + "@environment": "production", + "@project": "game", + "@repo": "acme/game", + "@secrets": "keys", + "@service": "game" + } + } + ] + } +} diff --git a/packs/railway/fixtures/conformance/railway-emit-one-service/input/meta.game.json b/packs/railway/fixtures/conformance/railway-emit-one-service/input/meta.game.json new file mode 100644 index 000000000..0cbba2d17 --- /dev/null +++ b/packs/railway/fixtures/conformance/railway-emit-one-service/input/meta.game.json @@ -0,0 +1,59 @@ +{ + "metadata.root": { + "package": "acme::game", + "children": [ + { "system.internal": { + "name": "Game", + "@description": "One Spring service in one repository, with its database and cache beside it on Railway.", + "children": [ + { "app.service": { + "name": "server", + "@needs": ["db", "cache"], + "@settings": ["Database", "Redis", "Llm"], + "children": [ + { "build.dockerfile": { + "name": "image", + "@watchExclude": ["/.archive/**", "/.claude/**", "/.docs/**", "/.github/**", "/.githooks/**", "/.metaobjects/*.md", "/.metaobjects/.agent-context.json", "/.specify/**", "/.test-prompts/**", "/assets/**", "/docs/**", "/e2e-tests/**", "/scripts/**", "/*.md", "/TODOs"] + } }, + { "runtime.process": { + "name": "web", + "@port": 8080, + "@healthPath": "/actuator/health/container", + "@healthTimeoutSeconds": 300, + "@drainSeconds": 180, + "@restart": "onFailure" + } } + ] + } }, + { "resource.database": { "name": "db", "@engine": "postgres", "@version": "18" } }, + { "resource.cache": { "name": "cache", "@engine": "redis" } } + ] + } }, + { "object.settings": { "name": "Database", "children": [ + { "field.string": { "name": "url", "@required": true } } + ]}}, + { "object.settings": { "name": "Redis", "children": [ + { "field.string": { "name": "url", "@required": true } } + ]}}, + { "object.settings": { "name": "Llm", "children": [ + { "field.string": { "name": "apiKey", "@required": true, "@secret": true, "@envName": "LLM_API_KEY" } }, + { "field.string": { "name": "model", "@default": "small" } } + ]}}, + { "vault.infisical": { "name": "keys", "children": [ + { "scope.env": { "name": "production", "@project": "acme-game", "@env": "prod" } } + ]}}, + { "environment.standing": { "name": "production" } }, + { "deployment.railway": { + "name": "server-production", + "@app": "Game.server", + "@environment": "production", + "@project": "game", + "@service": "game", + "@repo": "acme/game", + "@branch": "main", + "@checkSuites": false, + "@secrets": "keys" + } } + ] + } +} diff --git a/packs/railway/fixtures/conformance/railway-emit-one-service/providers.json b/packs/railway/fixtures/conformance/railway-emit-one-service/providers.json new file mode 100644 index 000000000..916757f19 --- /dev/null +++ b/packs/railway/fixtures/conformance/railway-emit-one-service/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-documentation", "metaobjects-systems", "metaobjects-delivery", "metaobjects-config", "metaobjects-railway"] diff --git a/packs/railway/fixtures/conformance/railway-emit-two-services/expected.json b/packs/railway/fixtures/conformance/railway-emit-two-services/expected.json new file mode 100644 index 000000000..21191a3f1 --- /dev/null +++ b/packs/railway/fixtures/conformance/railway-emit-two-services/expected.json @@ -0,0 +1,312 @@ +{ + "metadata.root": { + "package": "acme::tables", + "children": [ + { + "system.internal": { + "name": "Tables", + "@description": "Two services from one monorepo: a web arena and a Java backend it calls over Railway's private network, sharing a database and a cache.", + "children": [ + { + "app.service": { + "name": "arena", + "@calls": [ + "java" + ], + "@needs": [ + "Postgres", + "Redis" + ], + "@settings": [ + "Database", + "Cache", + "Router", + "Backend", + "Session", + "Llm", + "Commentary" + ], + "children": [ + { + "build.dockerfile": { + "name": "image", + "@path": "arena/Dockerfile", + "@watchExclude": [ + "arena/tests/**", + "metaobjects/**" + ], + "@watchInclude": [ + "arena/**" + ] + } + }, + { + "runtime.process": { + "name": "web" + } + } + ] + } + }, + { + "app.service": { + "name": "java", + "@needs": [ + "Postgres" + ], + "@settings": [ + "Database" + ], + "children": [ + { + "build.dockerfile": { + "name": "image", + "@path": "java/Dockerfile", + "@watchInclude": [ + "java/**", + "poker/**", + "framework/**" + ] + } + }, + { + "runtime.process": { + "name": "tomcat", + "@healthPath": "/health", + "@port": 8080 + } + } + ] + } + }, + { + "resource.database": { + "name": "Postgres", + "@engine": "postgres", + "@version": "18" + } + }, + { + "resource.cache": { + "name": "Redis", + "@engine": "redis" + } + } + ] + } + }, + { + "object.settings": { + "name": "Database", + "children": [ + { + "field.string": { + "name": "url", + "@required": true + } + } + ] + } + }, + { + "object.settings": { + "name": "Cache", + "children": [ + { + "field.string": { + "name": "url", + "@envName": "REDIS_URL", + "@required": true + } + } + ] + } + }, + { + "object.settings": { + "name": "Router", + "children": [ + { + "field.string": { + "name": "host", + "@required": true + } + }, + { + "field.int": { + "name": "port", + "@required": true + } + }, + { + "field.string": { + "name": "password", + "@required": true, + "@secret": true + } + } + ] + } + }, + { + "object.settings": { + "name": "Backend", + "children": [ + { + "field.string": { + "name": "apiUrl", + "@envName": "JAVA_API_URL", + "@required": true + } + } + ] + } + }, + { + "object.settings": { + "name": "Session", + "children": [ + { + "field.string": { + "name": "secret", + "@required": true, + "@secret": true + } + } + ] + } + }, + { + "object.settings": { + "name": "Llm", + "children": [ + { + "field.string": { + "name": "anthropicKey", + "@envName": "ANTHROPIC_API_KEY", + "@secret": true + } + }, + { + "field.string": { + "name": "openaiKey", + "@envName": "OPENAI_API_KEY", + "@secret": true + } + } + ] + } + }, + { + "object.settings": { + "name": "Commentary", + "children": [ + { + "field.string": { + "name": "baseUrl" + } + } + ] + } + }, + { + "vault.infisical": { + "name": "keys", + "children": [ + { + "scope.env": { + "name": "production", + "@env": "prod", + "@project": "acme-tables" + } + } + ] + } + }, + { + "environment.standing": { + "name": "production" + } + }, + { + "deployment.railway": { + "name": "arena-production", + "@app": "Tables.arena", + "@branch": "main", + "@domains": [ + "example.com" + ], + "@environment": "production", + "@project": "acme-prod", + "@repo": "acme/tables", + "@secrets": "keys", + "children": [ + { + "value.ref": { + "name": "db", + "@output": "url", + "@producedBy": "Tables.Postgres", + "@setting": "Database.url" + } + }, + { + "value.ref": { + "name": "cache", + "@output": "url", + "@producedBy": "Tables.Redis", + "@setting": "Cache.url" + } + }, + { + "value.ref": { + "name": "routerHost", + "@output": "host", + "@producedBy": "Tables.java", + "@setting": "Router.host" + } + }, + { + "value.literal": { + "name": "routerPort", + "@literal": "8891", + "@setting": "Router.port" + } + }, + { + "value.ref": { + "name": "api", + "@output": "privateUrl", + "@path": "/api", + "@producedBy": "Tables.java", + "@setting": "Backend.apiUrl" + } + } + ] + } + }, + { + "deployment.railway": { + "name": "java-production", + "@app": "Tables.java", + "@branch": "main", + "@domains": [ + "admin.example.com" + ], + "@environment": "production", + "@project": "acme-prod", + "@repo": "acme/tables", + "children": [ + { + "value.ref": { + "name": "db", + "@output": "url", + "@producedBy": "Tables.Postgres", + "@setting": "Database.url" + } + } + ] + } + } + ] + } +} diff --git a/packs/railway/fixtures/conformance/railway-emit-two-services/input/meta.tables.json b/packs/railway/fixtures/conformance/railway-emit-two-services/input/meta.tables.json new file mode 100644 index 000000000..2326e4503 --- /dev/null +++ b/packs/railway/fixtures/conformance/railway-emit-two-services/input/meta.tables.json @@ -0,0 +1,100 @@ +{ + "metadata.root": { + "package": "acme::tables", + "children": [ + { "system.internal": { + "name": "Tables", + "@description": "Two services from one monorepo: a web arena and a Java backend it calls over Railway's private network, sharing a database and a cache.", + "children": [ + { "app.service": { + "name": "arena", + "@needs": ["Postgres", "Redis"], + "@calls": ["java"], + "@settings": ["Database", "Cache", "Router", "Backend", "Session", "Llm", "Commentary"], + "children": [ + { "build.dockerfile": { + "name": "image", + "@path": "arena/Dockerfile", + "@watchInclude": ["arena/**"], + "@watchExclude": ["arena/tests/**", "metaobjects/**"] + } }, + { "runtime.process": { "name": "web" } } + ] + } }, + { "app.service": { + "name": "java", + "@needs": ["Postgres"], + "@settings": ["Database"], + "children": [ + { "build.dockerfile": { + "name": "image", + "@path": "java/Dockerfile", + "@watchInclude": ["java/**", "poker/**", "framework/**"] + } }, + { "runtime.process": { "name": "tomcat", "@port": 8080, "@healthPath": "/health" } } + ] + } }, + { "resource.database": { "name": "Postgres", "@engine": "postgres", "@version": "18" } }, + { "resource.cache": { "name": "Redis", "@engine": "redis" } } + ] + } }, + { "object.settings": { "name": "Database", "children": [ + { "field.string": { "name": "url", "@required": true } } + ]}}, + { "object.settings": { "name": "Cache", "children": [ + { "field.string": { "name": "url", "@required": true, "@envName": "REDIS_URL" } } + ]}}, + { "object.settings": { "name": "Router", "children": [ + { "field.string": { "name": "host", "@required": true } }, + { "field.int": { "name": "port", "@required": true } }, + { "field.string": { "name": "password", "@required": true, "@secret": true } } + ]}}, + { "object.settings": { "name": "Backend", "children": [ + { "field.string": { "name": "apiUrl", "@required": true, "@envName": "JAVA_API_URL" } } + ]}}, + { "object.settings": { "name": "Session", "children": [ + { "field.string": { "name": "secret", "@required": true, "@secret": true } } + ]}}, + { "object.settings": { "name": "Llm", "children": [ + { "field.string": { "name": "anthropicKey", "@secret": true, "@envName": "ANTHROPIC_API_KEY" } }, + { "field.string": { "name": "openaiKey", "@secret": true, "@envName": "OPENAI_API_KEY" } } + ]}}, + { "object.settings": { "name": "Commentary", "children": [ + { "field.string": { "name": "baseUrl" } } + ]}}, + { "vault.infisical": { "name": "keys", "children": [ + { "scope.env": { "name": "production", "@project": "acme-tables", "@env": "prod" } } + ]}}, + { "environment.standing": { "name": "production" } }, + { "deployment.railway": { + "name": "arena-production", + "@app": "Tables.arena", + "@environment": "production", + "@project": "acme-prod", + "@repo": "acme/tables", + "@branch": "main", + "@domains": ["example.com"], + "@secrets": "keys", + "children": [ + { "value.ref": { "name": "db", "@setting": "Database.url", "@producedBy": "Tables.Postgres", "@output": "url" } }, + { "value.ref": { "name": "cache", "@setting": "Cache.url", "@producedBy": "Tables.Redis", "@output": "url" } }, + { "value.ref": { "name": "routerHost", "@setting": "Router.host", "@producedBy": "Tables.java", "@output": "host" } }, + { "value.literal": { "name": "routerPort", "@setting": "Router.port", "@literal": "8891" } }, + { "value.ref": { "name": "api", "@setting": "Backend.apiUrl", "@producedBy": "Tables.java", "@output": "privateUrl", "@path": "/api" } } + ] + } }, + { "deployment.railway": { + "name": "java-production", + "@app": "Tables.java", + "@environment": "production", + "@project": "acme-prod", + "@repo": "acme/tables", + "@branch": "main", + "@domains": ["admin.example.com"], + "children": [ + { "value.ref": { "name": "db", "@setting": "Database.url", "@producedBy": "Tables.Postgres", "@output": "url" } } + ] + } } + ] + } +} diff --git a/packs/railway/fixtures/conformance/railway-emit-two-services/providers.json b/packs/railway/fixtures/conformance/railway-emit-two-services/providers.json new file mode 100644 index 000000000..916757f19 --- /dev/null +++ b/packs/railway/fixtures/conformance/railway-emit-two-services/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-documentation", "metaobjects-systems", "metaobjects-delivery", "metaobjects-config", "metaobjects-railway"] diff --git a/packs/railway/fixtures/expected-vocabulary.json b/packs/railway/fixtures/expected-vocabulary.json index 3427e092b..8ec472323 100644 --- a/packs/railway/fixtures/expected-vocabulary.json +++ b/packs/railway/fixtures/expected-vocabulary.json @@ -21,6 +21,13 @@ "required": false, "description": "The repository branch whose pushes deploy here." }, + { + "name": "checkSuites", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "Whether a push waits for the repository's GitHub check suites to pass before Railway deploys it. Absent means Railway's own setting is left as it is." + }, { "name": "domains", "valueType": "string", @@ -35,6 +42,13 @@ "required": true, "description": "The environment.* node it deploys to, by name (or `pkg::name`). It must resolve (ERR_DELIVERY_UNRESOLVED_REF)." }, + { + "name": "image", + "valueType": "string", + "isArray": false, + "required": false, + "description": "The container image Railway runs instead of building from a repository (`ghcr.io/acme/worker:1.2.3`)." + }, { "name": "project", "valueType": "string", @@ -56,6 +70,13 @@ "required": false, "description": "How many copies run. Absent means the platform's default." }, + { + "name": "repo", + "valueType": "string", + "isArray": false, + "required": false, + "description": "The GitHub repository Railway builds the service from, as `owner/name`. A deployment names a @repo or an @image: the generated file must declare the source, because a plan of a service with none disconnects it." + }, { "name": "secrets", "valueType": "string", diff --git a/packs/railway/metamodel/railway.json b/packs/railway/metamodel/railway.json index 715712f81..a7e871cac 100644 --- a/packs/railway/metamodel/railway.json +++ b/packs/railway/metamodel/railway.json @@ -9,7 +9,10 @@ "whenToUse": "Each (app, environment) pair that runs on Railway.", "children": [ { "type": "attr", "subType": "string", "name": "project", "min": 1, "max": 1, "description": "The Railway project's name." }, - { "type": "attr", "subType": "string", "name": "service", "min": 0, "max": 1, "description": "The Railway service's name. Absent means the app's name." } + { "type": "attr", "subType": "string", "name": "service", "min": 0, "max": 1, "description": "The Railway service's name. Absent means the app's name." }, + { "type": "attr", "subType": "string", "name": "repo", "min": 0, "max": 1, "description": "The GitHub repository Railway builds the service from, as `owner/name`. A deployment names a @repo or an @image: the generated file must declare the source, because a plan of a service with none disconnects it." }, + { "type": "attr", "subType": "string", "name": "image", "min": 0, "max": 1, "description": "The container image Railway runs instead of building from a repository (`ghcr.io/acme/worker:1.2.3`)." }, + { "type": "attr", "subType": "boolean", "name": "checkSuites", "min": 0, "max": 1, "description": "Whether a push waits for the repository's GitHub check suites to pass before Railway deploys it. Absent means Railway's own setting is left as it is." } ] } ] diff --git a/packs/railway/pack.json b/packs/railway/pack.json index ae41bba08..452d48b97 100644 --- a/packs/railway/pack.json +++ b/packs/railway/pack.json @@ -2,8 +2,8 @@ "id": "metaobjects-railway", "version": "0.1.0", "stability": "preview", - "description": "Railway as a deployment platform: deployment.railway. Vocabulary only so far; the emitter comes later.", - "requires": { "metamodel": ">=1.3 <2", "packs": { "metaobjects-delivery": ">=0.1.0 <0.2.0" } }, + "description": "Railway as a deployment platform: deployment.railway, and generators for the .railway/railway.ts Infrastructure as Code file, the facts that file cannot hold, the secret sync, deploy and doctor scripts, and a deploy skill.", + "requires": { "metamodel": ">=1.3 <2", "packs": { "metaobjects-delivery": ">=0.1.0 <0.2.0", "metaobjects-config": ">=0.1.0 <0.2.0" } }, "ports": { "typescript": { "package": "@metaobjectsdev/pack-railway", "core": ">=1.3.0 <2.0.0", "publish": false } } diff --git a/packs/railway/typescript/package.json b/packs/railway/typescript/package.json index cfe321dc2..00df1ba9f 100644 --- a/packs/railway/typescript/package.json +++ b/packs/railway/typescript/package.json @@ -1,7 +1,7 @@ { "name": "@metaobjectsdev/pack-railway", "version": "0.1.0", - "description": "The railway pack: deployment.railway (ADR-0069 independent pack, preview).", + "description": "The railway pack: deployment.railway and its generators (.railway/railway.ts, the unexpressed facts, secret sync, deploy and doctor scripts, a deploy skill). ADR-0069 independent pack, preview.", "private": true, "type": "module", "exports": { @@ -14,13 +14,16 @@ "typecheck": "tsc --noEmit -p ." }, "dependencies": { + "@metaobjectsdev/pack-config": "workspace:*", "@metaobjectsdev/pack-delivery": "workspace:*", "@metaobjectsdev/pack-systems": "workspace:*" }, "peerDependencies": { + "@metaobjectsdev/codegen-ts": ">=1.3.0 <2.0.0", "@metaobjectsdev/metadata": ">=1.3.0 <2.0.0" }, "devDependencies": { + "@metaobjectsdev/codegen-ts": "workspace:*", "@metaobjectsdev/metadata": "workspace:*" }, "license": "Apache-2.0" diff --git a/packs/railway/typescript/src/constants.ts b/packs/railway/typescript/src/constants.ts new file mode 100644 index 000000000..11221d9b9 --- /dev/null +++ b/packs/railway/typescript/src/constants.ts @@ -0,0 +1,50 @@ +// The railway pack's vocabulary names and the Railway spellings it writes, one constant each +// (metamodel/railway.json is the vocabulary's definition). + +export const RAILWAY_PROVIDER_ID = "metaobjects-railway"; +export const DEPLOYMENT_SUBTYPE_RAILWAY = "railway"; +export const RAILWAY_ATTR_PROJECT = "project"; +export const RAILWAY_ATTR_SERVICE = "service"; +export const RAILWAY_ATTR_REPO = "repo"; +export const RAILWAY_ATTR_IMAGE = "image"; +export const RAILWAY_ATTR_CHECK_SUITES = "checkSuites"; + +/** The `railway` npm package version the generated file and scripts were written against. */ +export const RAILWAY_SDK_VERSION = "3.17.0"; + +/** The module the generated file imports the DSL from. */ +export const RAILWAY_IAC_MODULE = "railway/iac"; + +/** A Railway named partial: 1 to 64 of `a-z A-Z 0-9 . _ -` (Railway's IaC page). */ +export const PARTIAL_PATTERN = /^[A-Za-z0-9._-]{1,64}$/; + +/** `runtime.process @restart` → Railway's `deploy.restartPolicyType`. */ +export const RESTART_POLICY: Readonly> = { + always: "ALWAYS", + onFailure: "ON_FAILURE", + never: "NEVER", +}; + +/** + * The variable a Railway database template provides for each `value.ref @output`, by + * `resource.* @engine`. Railway names them on its database templates (and the `railway` + * SDK's `PostgresVariable` / `RedisVariable` / `MySqlVariable` / `MongoVariable` types). + */ +export const DATABASE_OUTPUTS: Readonly>>> = { + postgres: { url: "DATABASE_URL", publicUrl: "DATABASE_PUBLIC_URL", host: "PGHOST", port: "PGPORT", user: "PGUSER", password: "PGPASSWORD" }, + mysql: { url: "MYSQL_URL", publicUrl: "MYSQL_PUBLIC_URL", host: "MYSQLHOST", port: "MYSQLPORT", user: "MYSQLUSER", password: "MYSQLPASSWORD" }, + redis: { url: "REDIS_URL", publicUrl: "REDIS_PUBLIC_URL", host: "REDISHOST", port: "REDISPORT", user: "REDISUSER", password: "REDISPASSWORD" }, + mongo: { url: "MONGO_URL", publicUrl: "MONGO_PUBLIC_URL", host: "MONGOHOST", port: "MONGOPORT", user: "MONGOUSER", password: "MONGOPASSWORD" }, +}; + +/** Railway's variables for another service's addresses. */ +export const RAILWAY_PRIVATE_DOMAIN = "RAILWAY_PRIVATE_DOMAIN"; +export const RAILWAY_PUBLIC_DOMAIN = "RAILWAY_PUBLIC_DOMAIN"; + +/** Default output paths, relative to the generator's target (the repository root). */ +export const PATH_RAILWAY_TS = ".railway/railway.ts"; +export const PATH_UNEXPRESSED = "deploy/unexpressed.md"; +export const PATH_SYNC_SECRETS = "deploy/sync-secrets.sh"; +export const PATH_DEPLOY = "deploy/deploy.sh"; +export const PATH_DOCTOR = "deploy/doctor.sh"; +export const PATH_DEPLOY_SKILL = ".claude/skills/deploy/SKILL.md"; diff --git a/packs/railway/typescript/src/files.ts b/packs/railway/typescript/src/files.ts new file mode 100644 index 000000000..72ecba228 --- /dev/null +++ b/packs/railway/typescript/src/files.ts @@ -0,0 +1,404 @@ +/** + * The files beside `.railway/railway.ts`: the facts that file cannot hold, the scripts that + * copy secrets to Railway, deploy and check, and the skill an agent follows to deploy. + * + * The scripts call `railway`, `keys-axi`, `jq`, `npm` and `curl`; MetaObjects writes them and + * stops. A secret's value only ever passes from `keys-axi run`'s environment through a pipe + * into `railway variable set --stdin`: no script prints one or puts one on a command line. + */ +import { RAILWAY_SDK_VERSION } from "./constants.js"; +import { isStatic, type RailwayDeployment, type RailwayProject } from "./model.js"; + +/** A shell word: bare when it is safe, else single-quoted. */ +function sh(s: string): string { + return /^[A-Za-z0-9_./:@-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`; +} + +function secretsOf(d: RailwayDeployment): string[] { + return d.settings.filter((s) => s.secret).map((s) => s.envName); +} + +function md(s: string): string { + return `\`${s}\``; +} + +// ── deploy/unexpressed.md ──────────────────────────────────────────────────── + +interface Fact { + readonly fact: string; + readonly how: string; +} + +/** The facts of one deployment `.railway/railway.ts` does not carry, and how each is carried instead. */ +export function unexpressedFacts(d: RailwayDeployment, manageVariables: boolean): Fact[] { + const out: Fact[] = []; + const b = d.build; + if (b?.context !== undefined && b.context !== "." && b.context !== "/") { + out.push({ + fact: `Build context ${md(b.context)} (build.${b.kind})`, + how: "Railway builds from the repository root; the file has no build context. Set the service's root directory in Railway, or build from the root.", + }); + } + if (isStatic(b)) { + out.push({ + fact: `Static directory ${md(b?.directory ?? "")} (build.static)`, + how: "Railway has no setting that serves a directory of files. Serve it with a process (runtime.process @command), or deploy the app on a static host.", + }); + } + for (const p of d.processes.slice(1)) { + out.push({ + fact: `Second process ${md(p.name)} (runtime.process)`, + how: "A Railway service runs one process; the file declares the first. Run this one as its own app with its own deployment.", + }); + } + for (const r of d.resources) { + const what = [r.engine, r.version].filter((x) => x !== undefined).join(" "); + out.push({ + fact: `${r.kind} ${md(r.name)}${what === "" ? "" : ` (${what})`}`, + how: `Not declared, so the partial neither creates nor deletes it. It must exist in the Railway project under the name ${md(r.name)}, which every reference to it uses.`, + }); + } + if (d.domains.length > 0) { + out.push({ + fact: `DNS for ${d.domains.map(md).join(", ")}`, + how: "The file attaches the domains to the service; the DNS record each needs (the CNAME Railway shows for it) is set at the DNS provider. deploy/doctor.sh checks each answers on the health path.", + }); + } + const secrets = secretsOf(d); + if (secrets.length > 0 && d.vault !== undefined) { + out.push({ + fact: `Secret values: ${secrets.map(md).join(", ")}`, + how: `Never in the file. deploy/sync-secrets.sh ${d.environment} copies them from the vault scope ${md(`${d.vault.scope.project}/${d.vault.scope.env}`)}; deploy/doctor.sh checks the names are in the vault and on Railway.`, + }); + } + const plain = d.settings.filter((s) => !s.secret).map((s) => s.envName); + if (!manageVariables && plain.length > 0) { + out.push({ + fact: `Non-secret settings: ${plain.map(md).join(", ")}`, + how: "The file leaves variables unmanaged, so these keep the value set on Railway (or the application's default). Declare a value.* node on the deployment to have the file manage variables.", + }); + } + return out; +} + +export function renderUnexpressed(project: RailwayProject, header: string): string { + const lines = [ + header, + "", + `# What \`.railway/railway.ts\` does not hold: Railway project ${md(project.name)}`, + "", + "Facts the model declares that Railway's Infrastructure as Code file cannot carry, or that this", + "file leaves to something else, each with how it is carried instead. Generated from the model:", + "change the model, not this file.", + ]; + for (const d of project.deployments) { + const facts = unexpressedFacts(d, project.manageVariables); + lines.push("", `## ${d.service} in ${d.environment}`, "", `From deployment.railway ${md(d.key)}.`, ""); + if (facts.length === 0) { + lines.push("Nothing: the file holds every fact the model declares for this deployment."); + continue; + } + lines.push("| Fact | How it is carried |", "|---|---|"); + for (const f of facts) lines.push(`| ${f.fact} | ${f.how} |`); + } + return `${lines.join("\n")}\n`; +} + +// ── shared shell pieces ────────────────────────────────────────────────────── + +function shellHead(header: string, purpose: readonly string[], usage: string): string[] { + return ["#!/usr/bin/env bash", header, ...purpose.map((l) => (l === "" ? "#" : `# ${l}`)), "#", `# ${usage}`]; +} + +function caseBlock(project: RailwayProject, body: (ds: readonly RailwayDeployment[], env: string) => string[], usage: string): string[] { + const lines = ['case "$ENVIRONMENT" in']; + for (const env of project.environments) { + const ds = project.deployments.filter((d) => d.environment === env); + lines.push(` ${sh(env)})`, ...body(ds, env).map((l) => ` ${l}`), " ;;"); + } + lines.push(` *) echo ${sh(`usage: ${usage} (environments: ${project.environments.join(", ")})`)} >&2; exit 2 ;;`, "esac"); + return lines; +} + +const ENSURE_SDK = [ + "ensure_sdk() {", + ` [ -d .railway/node_modules/railway ] || npm install --no-save --prefix .railway railway@${RAILWAY_SDK_VERSION} >/dev/null`, + "}", +]; + +// ── deploy/sync-secrets.sh ─────────────────────────────────────────────────── + +const SYNC_USAGE = "bash deploy/sync-secrets.sh [--dry-run]"; + +export function renderSyncSecrets(project: RailwayProject, header: string): string { + const lines = [ + ...shellHead( + header, + [ + `Copies every secret setting the model declares from the vault to Railway project ${project.name},`, + "for one environment. A value goes from keys-axi's environment through a pipe into", + "`railway variable set --stdin`: it is never printed and never on a command line. It sets", + "with --skip-deploys, so the next deploy picks the values up.", + "", + "Needs: keys-axi (an identity that may read the vault scope) and railway (logged in, run", + "from the linked repository).", + ], + SYNC_USAGE, + ), + "set -euo pipefail", + 'cd "$(dirname "$0")/.."', + "", + 'ENVIRONMENT="${1:-}"', + 'DRY_RUN=0; [ "${2:-}" = "--dry-run" ] && DRY_RUN=1', + "", + "# copy ", + "copy() {", + ' if [ "$DRY_RUN" = 1 ]; then echo "would copy $5 from $1/$2 to service $3 ($4)"; return; fi', + ` keys-axi run --project "$1" --env "$2" --only "$5" -- bash -c '`, + ` [ -n "\${!1+set}" ] || { echo "sync-secrets: $1 is not in the vault scope" >&2; exit 1; }`, + ` printf %s "\${!1}" | railway variable set "$1" --stdin --service "$2" --environment "$3" --skip-deploys >/dev/null`, + ` ' sync-secret "$5" "$3" "$4"`, + ' echo "copied $5 to service $3 ($4)"', + "}", + "", + ...caseBlock( + project, + (ds, env) => { + const body: string[] = []; + for (const d of ds) { + const secrets = secretsOf(d); + if (secrets.length === 0 || d.vault === undefined) continue; + for (const s of secrets) body.push(`copy ${sh(d.vault.scope.project)} ${sh(d.vault.scope.env)} ${sh(d.service)} ${sh(env)} ${s}`); + } + return body.length > 0 ? body : [`echo ${sh(`no secret settings to copy in ${env}`)}`]; + }, + SYNC_USAGE, + ), + ]; + return `${lines.join("\n")}\n`; +} + +// ── deploy/doctor.sh ───────────────────────────────────────────────────────── + +const DOCTOR_USAGE = "bash deploy/doctor.sh "; + +function healthUrls(d: RailwayDeployment): string[] { + const path = d.processes[0]?.healthPath; + return path === undefined ? [] : d.domains.map((domain) => `https://${domain}${path}`); +} + +export function renderDoctor(project: RailwayProject, header: string): string { + const lines = [ + ...shellHead( + header, + [ + `Checks Railway project ${project.name} against the model, for one environment, by name only:`, + "every secret the model declares is in the vault and on Railway; `.railway/railway.ts`", + "matches what Railway runs (`railway config plan`); each domain answers on the health path.", + "Exits 1 when a check fails. It prints names, never a value.", + "", + "Needs: railway (logged in, run from the linked repository), keys-axi, jq, npm, curl.", + ], + DOCTOR_USAGE, + ), + "set -uo pipefail", + 'cd "$(dirname "$0")/.." || exit 2', + "", + 'ENVIRONMENT="${1:-}"', + "FAIL=0", + "ok() { echo \"ok $*\"; }", + "bad() { echo \"FAIL $*\"; FAIL=1; }", + "for tool in railway keys-axi jq npm curl; do", + ' command -v "$tool" >/dev/null || { echo "doctor: $tool is not installed" >&2; exit 2; }', + "done", + ...ENSURE_SDK, + "", + "# in_vault ...", + "in_vault() {", + " local names", + ` names=$(keys-axi ls --project "$1" --env "$2" --json | jq -r '.secrets[].name') || { bad "cannot list vault scope $1/$2"; return; }`, + " local where=\"$1/$2\"; shift 2", + ' for n in "$@"; do', + ' if grep -qx "$n" <<<"$names"; then ok "$n is in the vault ($where)"; else bad "$n is declared secret and is not in the vault ($where)"; fi', + " done", + "}", + "", + "# on_railway ...", + "on_railway() {", + " local names", + ` names=$(railway variable list --service "$1" --environment "$2" --json | jq -r 'if type == "object" then keys[] else .[].name end') || { bad "cannot list the variables of service $1 ($2)"; return; }`, + " local where=\"service $1 ($2)\"; shift 2", + ' for n in "$@"; do', + ' if grep -qx "$n" <<<"$names"; then ok "$n is set on $where"; else bad "$n is declared and not set on $where (run deploy/sync-secrets.sh)"; fi', + " done", + "}", + "", + "# plan_clean : the file matches Railway", + "plan_clean() {", + ' railway environment "$1" >/dev/null || { bad "cannot link Railway environment $1"; return; }', + " ensure_sdk || { bad \"cannot install the railway SDK into .railway\"; return; }", + " railway config plan --detailed-exit-code >/dev/null 2>&1", + " case $? in", + ' 0) ok ".railway/railway.ts matches Railway ($1)" ;;', + ' 2) bad ".railway/railway.ts differs from Railway ($1): run deploy/deploy.sh $1" ;;', + ' *) bad "railway config plan failed ($1): run it by hand to see why" ;;', + " esac", + "}", + "", + "# answers ", + "answers() {", + ' if curl -fsS -o /dev/null --max-time 10 "$1"; then ok "$1 answers"; else bad "$1 does not answer 2xx"; fi', + "}", + "", + ...caseBlock( + project, + (ds, env) => { + const body: string[] = []; + for (const d of ds) { + const secrets = secretsOf(d); + if (secrets.length > 0 && d.vault !== undefined) { + body.push(`in_vault ${sh(d.vault.scope.project)} ${sh(d.vault.scope.env)} ${secrets.join(" ")}`); + body.push(`on_railway ${sh(d.service)} ${sh(env)} ${secrets.join(" ")}`); + } + } + body.push(`plan_clean ${sh(env)}`); + for (const d of ds) for (const url of healthUrls(d)) body.push(`answers ${sh(url)}`); + return body; + }, + DOCTOR_USAGE, + ), + "", + 'exit "$FAIL"', + ]; + return `${lines.join("\n")}\n`; +} + +// ── deploy/deploy.sh ───────────────────────────────────────────────────────── + +const DEPLOY_USAGE = "bash deploy/deploy.sh [--yes] [--redeploy]"; + +export function renderDeploy(project: RailwayProject, header: string): string { + const lines = [ + ...shellHead( + header, + [ + `Deploys Railway project ${project.name} to one environment from the model:`, + " 1. copies the secrets from the vault (deploy/sync-secrets.sh),", + " 2. plans and applies `.railway/railway.ts` (`railway config plan`, then `apply`),", + " 3. with --redeploy, redeploys each service and waits for its health path,", + " 4. runs deploy/doctor.sh.", + "A push to the deployment's branch also deploys on Railway; this script is for settings and", + "secrets, and for a deploy that cannot wait for a push. --yes applies without the prompt", + "(never a destructive change: Railway refuses one without --confirm-destructive).", + "", + "Needs: railway (logged in, run from the linked repository), keys-axi, jq, npm, curl.", + ], + DEPLOY_USAGE, + ), + "set -euo pipefail", + 'cd "$(dirname "$0")/.."', + "", + 'ENVIRONMENT="${1:-}"', + "YES=(); REDEPLOY=0", + 'for arg in "${@:2}"; do', + ' case "$arg" in', + " --yes) YES=(--yes) ;;", + " --redeploy) REDEPLOY=1 ;;", + ` *) echo ${sh(`usage: ${DEPLOY_USAGE}`)} >&2; exit 2 ;;`, + " esac", + "done", + ...ENSURE_SDK, + "", + "# wait_healthy ", + "wait_healthy() {", + ' local deadline=$((SECONDS + $2))', + ' until curl -fsS -o /dev/null --max-time 10 "$1"; do', + ' [ "$SECONDS" -lt "$deadline" ] || { echo "deploy: $1 did not answer 2xx within $2 seconds" >&2; return 1; }', + " sleep 10", + " done", + ' echo "healthy: $1"', + "}", + "", + "# settle : sync secrets, then plan and apply the file", + "settle() {", + ' bash deploy/sync-secrets.sh "$1"', + ' railway environment "$1" >/dev/null', + " ensure_sdk", + " railway config plan", + ' railway config apply "${YES[@]}"', + "}", + "", + ...caseBlock( + project, + (ds, env) => { + const body = [`settle ${sh(env)}`, 'if [ "$REDEPLOY" = 1 ]; then']; + for (const d of ds) { + body.push(` railway redeploy --service ${sh(d.service)} --yes`); + const wait = d.processes[0]?.healthTimeoutSeconds ?? 300; + for (const url of healthUrls(d)) body.push(` wait_healthy ${sh(url)} ${wait}`); + } + body.push("fi", `bash deploy/doctor.sh ${sh(env)}`); + return body; + }, + DEPLOY_USAGE, + ), + ]; + return `${lines.join("\n")}\n`; +} + +// ── the deploy skill ───────────────────────────────────────────────────────── + +export function renderDeploySkill(project: RailwayProject, header: string): string { + const services = [...new Set(project.deployments.map((d) => d.service))]; + const rows = project.deployments.map((d) => { + const secrets = secretsOf(d); + const vault = d.vault === undefined ? "none" : md(`${d.vault.scope.project}/${d.vault.scope.env}`); + return `| ${md(d.environment)} | ${md(d.service)} | ${d.branch === undefined ? "none" : md(d.branch)} | ${d.domains.length === 0 ? "none" : d.domains.map(md).join(", ")} | ${vault} (${secrets.length} secret${secrets.length === 1 ? "" : "s"}) |`; + }); + const lines = [ + "---", + "name: deploy", + `description: Deploy Railway project ${project.name} (${services.join(", ")}) to ${project.environments.join(" or ")} from the generated deploy scripts. Use when asked to deploy, ship to Railway, rotate a secret on Railway, or check a Railway deployment.`, + "---", + "", + header, + "", + `# Deploy ${project.name} to Railway`, + "", + "Generated from the model (railway pack). Every deploy fact lives in the model; the files in", + "`.railway/` and `deploy/` are written from it. To change a deploy setting, change the model and", + "regenerate, never the generated files.", + "", + "| Environment | Service | Deploys on push to | Domains | Secrets from |", + "|---|---|---|---|---|", + ...rows, + "", + "## Before the first deploy", + "", + "- `railway login`, then `railway link` in the repository (it writes `.railway/config.json`).", + "- A `keys-axi` identity that may read each vault scope above (`keys-axi` with no arguments shows it).", + "- `jq`, `npm` and `curl` on the path.", + "- If the service still has a Config as Code file (`railway.json` or `railway.toml`): Railway", + " stops reading it on 2026-12-01. Run `railway config migrate cutover` before the first plan, and", + " delete the old file only after cutover and the first apply.", + "", + "## Deploy", + "", + "1. `bash deploy/doctor.sh ` to see where things stand. It prints names, never values.", + "2. `bash deploy/sync-secrets.sh --dry-run` to see which secrets will be copied.", + "3. `bash deploy/deploy.sh `: copies the secrets, shows the plan of `.railway/railway.ts`", + " and applies it after confirmation. Read the plan before confirming: stop if it deletes a", + " service, a database or a volume. Add `--redeploy` to redeploy now and wait for the health", + " check instead of waiting for the next push.", + "4. `bash deploy/doctor.sh ` again. Every line should be `ok`.", + "", + "## Rules", + "", + "- Never print a secret value, put one on a command line, or paste one into a file. The vault is", + " the source of truth: rotate a key there, then run `deploy/sync-secrets.sh`.", + "- Never pass `--confirm-destructive` without a person's explicit go-ahead for that plan.", + "- A fact Railway's file cannot hold is listed in `deploy/unexpressed.md` with how it is carried.", + "", + ]; + return lines.join("\n"); +} diff --git a/packs/railway/typescript/src/generators.ts b/packs/railway/typescript/src/generators.ts new file mode 100644 index 000000000..c0c056bc6 --- /dev/null +++ b/packs/railway/typescript/src/generators.ts @@ -0,0 +1,108 @@ +/** + * The railway pack's generators. Each writes one file for the model's Railway project and + * stops: none talks to Railway or to a vault, and no secret value reaches their output (the + * model holds none). + * + * - `railwayTsFile()` `.railway/railway.ts`, Railway's Infrastructure as Code file. + * - `railwayUnexpressedFile()` `deploy/unexpressed.md`, the facts that file cannot hold. + * - `railwaySyncSecretsScript()` `deploy/sync-secrets.sh`, vault → Railway at deploy (keys-axi). + * - `railwayDeployScript()` `deploy/deploy.sh`, sync, plan, apply, check. + * - `railwayDoctorScript()` `deploy/doctor.sh`, the model against the vault and Railway. + * - `railwayDeploySkill()` `.claude/skills/deploy/SKILL.md`, how an agent deploys. + * - `railwayFiles()` all six. + * + * Paths are relative to the generator's target; these files belong at the repository root, + * so wire them to a target whose `outDir` is `"."` (README, "Wiring"). A model that deploys + * nothing to Railway gets no files. + */ +import { GENERATED_EDIT_NOTE, type EmittedFile, type Generator, type GenContext } from "@metaobjectsdev/codegen-ts"; +import { + PATH_DEPLOY, + PATH_DEPLOY_SKILL, + PATH_DOCTOR, + PATH_RAILWAY_TS, + PATH_SYNC_SECRETS, + PATH_UNEXPRESSED, +} from "./constants.js"; +import { renderDeploy, renderDeploySkill, renderDoctor, renderSyncSecrets, renderUnexpressed } from "./files.js"; +import { pickProject, readRailway, type RailwayProject, type ReadRailwayOptions } from "./model.js"; +import { renderRailwayTs } from "./railway-ts.js"; + +const PACKAGE = "@metaobjectsdev/pack-railway"; + +export interface RailwayGeneratorOptions extends ReadRailwayOptions { + /** The output path, relative to the target. */ + readonly path?: string; + /** The named output target (`targets` in metaobjects.config.ts). Default: `"default"`. */ + readonly target?: string; +} + +export function header(generator: string, comment: string): string { + return `${comment} @generated by ${PACKAGE} (${generator}) — ${GENERATED_EDIT_NOTE}`; +} + +/** The model read once per run and per options (a run shares one `entities` array). */ +const cache = new WeakMap>(); + +function projectFor(ctx: GenContext, opts: ReadRailwayOptions): RailwayProject | undefined { + const k = JSON.stringify([opts.project ?? null, opts.partial ?? null]); + let perRun = cache.get(ctx.entities); + if (perRun === undefined) { + perRun = new Map(); + cache.set(ctx.entities, perRun); + } + if (!perRun.has(k)) { + const read: ReadRailwayOptions = { + ...(opts.project !== undefined ? { project: opts.project } : {}), + ...(opts.partial !== undefined ? { partial: opts.partial } : {}), + }; + const projects = readRailway(ctx.loadedRoot, ctx.entities.filter(ctx.matches), (key) => ctx.select?.(key) ?? true, read); + perRun.set(k, pickProject(projects)); + } + return perRun.get(k); +} + +function generator( + name: string, + defaultPath: string, + opts: RailwayGeneratorOptions, + render: (project: RailwayProject) => string, +): Generator { + return { + name, + ...(opts.target !== undefined ? { target: opts.target } : {}), + generate(ctx): EmittedFile[] { + const project = projectFor(ctx, opts); + return project === undefined ? [] : [{ path: opts.path ?? defaultPath, content: render(project) }]; + }, + }; +} + +export function railwayTsFile(opts: RailwayGeneratorOptions = {}): Generator { + return generator("railway-ts", PATH_RAILWAY_TS, opts, (p) => renderRailwayTs(p, header("railway-ts", "//"))); +} + +export function railwayUnexpressedFile(opts: RailwayGeneratorOptions = {}): Generator { + return generator("railway-unexpressed", PATH_UNEXPRESSED, opts, (p) => renderUnexpressed(p, header("railway-unexpressed", ""))); +} + +export function railwaySyncSecretsScript(opts: RailwayGeneratorOptions = {}): Generator { + return generator("railway-sync-secrets", PATH_SYNC_SECRETS, opts, (p) => renderSyncSecrets(p, header("railway-sync-secrets", "#"))); +} + +export function railwayDeployScript(opts: RailwayGeneratorOptions = {}): Generator { + return generator("railway-deploy", PATH_DEPLOY, opts, (p) => renderDeploy(p, header("railway-deploy", "#"))); +} + +export function railwayDoctorScript(opts: RailwayGeneratorOptions = {}): Generator { + return generator("railway-doctor", PATH_DOCTOR, opts, (p) => renderDoctor(p, header("railway-doctor", "#"))); +} + +export function railwayDeploySkill(opts: RailwayGeneratorOptions = {}): Generator { + return generator("railway-deploy-skill", PATH_DEPLOY_SKILL, opts, (p) => renderDeploySkill(p, header("railway-deploy-skill", ""))); +} + +/** All six generators with the same options (`path` is ignored: each keeps its own). */ +export function railwayFiles(opts: Omit = {}): Generator[] { + return [railwayTsFile(opts), railwayUnexpressedFile(opts), railwaySyncSecretsScript(opts), railwayDeployScript(opts), railwayDoctorScript(opts), railwayDeploySkill(opts)]; +} diff --git a/packs/railway/typescript/src/index.ts b/packs/railway/typescript/src/index.ts index 3d270fdd8..13a3b9c59 100644 --- a/packs/railway/typescript/src/index.ts +++ b/packs/railway/typescript/src/index.ts @@ -1,17 +1,42 @@ -// @metaobjectsdev/pack-railway: Railway as a deployment platform (ADR-0069 independent -// pack). It registers `deployment.railway` on the delivery pack's `deployment.base`, and -// holds it to the delivery pack's deployment references. Vocabulary only so far: the -// `.railway/railway.ts` emitter, the secret sync and the deploy scripts come later. - -import { applyProviderDefinition, type MetaDataTypeProvider, type ProviderDefinition, type TypeRegistry } from "@metaobjectsdev/metadata"; +/** + * @metaobjectsdev/pack-railway — the railway pack (ADR-0069): deployment.railway, and the + * generators that turn it into Railway's `.railway/railway.ts` and the scripts beside it. + * + * import { provider as railwayProvider, railwayFiles } from "@metaobjectsdev/pack-railway"; + * export default defineConfig({ providers: [..., railwayProvider], generators: [...railwayFiles()] }); + */ +import { applyProviderDefinition, type MetaDataTypeProvider, type ProviderDefinition } from "@metaobjectsdev/metadata"; import { DELIVERY_PROVIDER_ID, TYPE_DEPLOYMENT, validateDeployment } from "@metaobjectsdev/pack-delivery"; import { packTypeMaps } from "@metaobjectsdev/pack-systems"; import definition from "../../metamodel/railway.json" with { type: "json" }; +import { RAILWAY_PROVIDER_ID } from "./constants.js"; -export const RAILWAY_PROVIDER_ID = "metaobjects-railway"; -export const DEPLOYMENT_SUBTYPE_RAILWAY = "railway"; -export const RAILWAY_ATTR_PROJECT = "project"; -export const RAILWAY_ATTR_SERVICE = "service"; +export * from "./constants.js"; +export { + RailwayModelError, + isRailwayDeployment, + pickProject, + readRailway, + type RailwayBuild, + type RailwayDeployment, + type RailwayProcess, + type RailwayProject, + type RailwayResource, + type RailwayVariable, + type ReadRailwayOptions, +} from "./model.js"; +export { renderRailwayTs } from "./railway-ts.js"; +export { renderDeploy, renderDeploySkill, renderDoctor, renderSyncSecrets, renderUnexpressed, unexpressedFacts } from "./files.js"; +export { + railwayDeployScript, + railwayDeploySkill, + railwayDoctorScript, + railwayFiles, + railwaySyncSecretsScript, + railwayTsFile, + railwayUnexpressedFile, + type RailwayGeneratorOptions, +} from "./generators.js"; export const RAILWAY_DEFINITION = definition as ProviderDefinition; @@ -19,7 +44,7 @@ export const provider: MetaDataTypeProvider = { id: RAILWAY_PROVIDER_ID, dependencies: ["metaobjects-core-types", DELIVERY_PROVIDER_ID], description: "Railway: deployment.railway.", - registerTypes(registry: TypeRegistry): void { + registerTypes(registry) { const { factories, validators } = packTypeMaps(RAILWAY_DEFINITION, { [TYPE_DEPLOYMENT]: validateDeployment }); applyProviderDefinition(registry, RAILWAY_DEFINITION, factories, validators); }, diff --git a/packs/railway/typescript/src/model.ts b/packs/railway/typescript/src/model.ts new file mode 100644 index 000000000..714e8c295 --- /dev/null +++ b/packs/railway/typescript/src/model.ts @@ -0,0 +1,524 @@ +/** + * What the model says about Railway, read once for every generator in the pack. + * + * A deployment.railway names its app and environment; the app holds the facts true + * everywhere (its build, its processes, the settings groups it reads); the deployment adds + * what differs here. This module joins them into one plain record per deployment and groups + * the deployments by Railway project, which is what one `.railway/railway.ts` declares. + * + * Accessors are the resolving ones (ADR-0039), so an estate overlay or an `extends` reads + * like a fact declared in place. Problems a loader cannot see (a value for a setting nobody + * declared, a reference Railway cannot supply, a secret with no vault) are collected and + * thrown together, each naming its node. + */ +import type { MetaData, MetaObject, MetaRoot } from "@metaobjectsdev/metadata"; +import { + readSettings, + readVaults, + ConfigModelError, + VAULT_SUBTYPE_INFISICAL, + type Setting, + type SettingsGroup, + type Vault, + type VaultScope, +} from "@metaobjectsdev/pack-config"; +import { + BUILD_ATTR_COMMAND, + BUILD_ATTR_CONTEXT, + BUILD_ATTR_DIRECTORY, + BUILD_ATTR_PATH, + BUILD_ATTR_WATCH_EXCLUDE, + BUILD_ATTR_WATCH_INCLUDE, + BUILD_SUBTYPE_STATIC, + DEPLOYMENT_ATTR_APP, + DEPLOYMENT_ATTR_BRANCH, + DEPLOYMENT_ATTR_DOMAINS, + DEPLOYMENT_ATTR_ENVIRONMENT, + DEPLOYMENT_ATTR_REGION, + DEPLOYMENT_ATTR_REPLICAS, + DEPLOYMENT_ATTR_SECRETS, + RUNTIME_ATTR_COMMAND, + RUNTIME_ATTR_DRAIN_SECONDS, + RUNTIME_ATTR_HEALTH_PATH, + RUNTIME_ATTR_HEALTH_TIMEOUT_SECONDS, + RUNTIME_ATTR_PORT, + RUNTIME_ATTR_RESTART, + TYPE_BUILD, + TYPE_DEPLOYMENT, + TYPE_ENVIRONMENT, + TYPE_RUNTIME, + TYPE_VALUE, + VALUE_ATTR_LITERAL, + VALUE_ATTR_OUTPUT, + VALUE_ATTR_PATH, + VALUE_ATTR_PRODUCED_BY, + VALUE_ATTR_SETTING, + VALUE_SUBTYPE_LITERAL, +} from "@metaobjectsdev/pack-delivery"; +import { + APP_ATTR_NEEDS, + APP_ATTR_SCHEDULE, + APP_ATTR_SETTINGS, + RESOURCE_ATTR_ENGINE, + RESOURCE_ATTR_MANAGED_BY, + RESOURCE_ATTR_VERSION, + TYPE_APP, + TYPE_RESOURCE, + refList, + resolveSystemRef, +} from "@metaobjectsdev/pack-systems"; +import { + DATABASE_OUTPUTS, + DEPLOYMENT_SUBTYPE_RAILWAY, + PARTIAL_PATTERN, + RAILWAY_ATTR_CHECK_SUITES, + RAILWAY_ATTR_IMAGE, + RAILWAY_ATTR_PROJECT, + RAILWAY_ATTR_REPO, + RAILWAY_ATTR_SERVICE, + RAILWAY_PRIVATE_DOMAIN, + RAILWAY_PUBLIC_DOMAIN, +} from "./constants.js"; + +/** Thrown with every problem found, one per line, each naming its node. */ +export class RailwayModelError extends Error { + constructor(readonly problems: readonly string[]) { + super(`railway pack: ${problems.length} problem(s) in the model:\n${problems.map((p) => ` - ${p}`).join("\n")}`); + this.name = "RailwayModelError"; + } +} + +export interface RailwayBuild { + /** The build subtype: dockerfile, command or static. */ + readonly kind: string; + readonly watchInclude: readonly string[]; + readonly watchExclude: readonly string[]; + readonly path?: string; + readonly context?: string; + readonly command?: string; + readonly directory?: string; +} + +export interface RailwayProcess { + readonly name: string; + readonly command?: string; + readonly port?: number; + readonly healthPath?: string; + readonly healthTimeoutSeconds?: number; + readonly drainSeconds?: number; + /** The model's restart value: always, onFailure or never. */ + readonly restart?: string; +} + +/** One variable a managed file declares on a service. */ +export interface RailwayVariable { + readonly name: string; + /** `literal`: a fixed string (a value.literal, a value.ref's reference template, a default). `preserve`: keep Railway's value. */ + readonly kind: "literal" | "preserve"; + readonly value?: string; + /** Where it comes from, for the comment beside it. */ + readonly from: string; +} + +/** A resource an app needs that Railway runs beside it and the file does not declare. */ +export interface RailwayResource { + readonly name: string; + readonly kind: string; + readonly engine?: string; + readonly version?: string; +} + +export interface RailwayDeployment { + readonly key: string; + readonly name: string; + readonly environment: string; + readonly project: string; + readonly service: string; + readonly appKey: string; + /** The app subtype: service, client or job. */ + readonly appKind: string; + readonly schedule?: string; + readonly repo?: string; + readonly image?: string; + readonly branch?: string; + readonly checkSuites?: boolean; + readonly domains: readonly string[]; + readonly replicas?: number; + readonly region?: string; + readonly build?: RailwayBuild; + readonly processes: readonly RailwayProcess[]; + /** Whether the deployment declares value.* nodes (the file then manages variables). */ + readonly hasValues: boolean; + /** The variables a managed file declares, in name order. Empty for an unmanaged file. */ + readonly variables: readonly RailwayVariable[]; + /** Every setting of the settings groups the app reads. */ + readonly settings: readonly Setting[]; + /** Where the secret settings are read from at deploy. Absent when the app reads none. */ + readonly vault?: { readonly key: string; readonly scope: VaultScope }; + readonly resources: readonly RailwayResource[]; +} + +export interface RailwayProject { + /** The Railway project's name. */ + readonly name: string; + /** The named partial the file exports. */ + readonly partial: string; + /** Whether the file manages variables (some deployment declares value.* nodes). */ + readonly manageVariables: boolean; + /** The deployments, in model order. */ + readonly deployments: readonly RailwayDeployment[]; + /** The environments, in first-declared order. */ + readonly environments: readonly string[]; +} + +export interface ReadRailwayOptions { + /** The Railway project to read, when the model deploys to more than one. */ + readonly project?: string; + /** The named partial to export. Absent: the service's name when there is one, else the project's. */ + readonly partial?: string; +} + +function text(v: unknown): string | undefined { + return typeof v === "string" && v !== "" ? v : undefined; +} + +function int(v: unknown): number | undefined { + return typeof v === "number" && Number.isInteger(v) ? v : undefined; +} + +function strings(node: MetaData, attr: string): string[] { + return refList(node, attr); +} + +export function isRailwayDeployment(node: MetaData): boolean { + return node.type === TYPE_DEPLOYMENT && node.subType === DEPLOYMENT_SUBTYPE_RAILWAY; +} + +function readBuild(app: MetaData): RailwayBuild | undefined { + // ADR-0039: resolving, so a build an app inherits through `extends` counts. + const b = app.children().find((c) => c.type === TYPE_BUILD); + if (b === undefined) return undefined; + const path = text(b.attr(BUILD_ATTR_PATH)); + const context = text(b.attr(BUILD_ATTR_CONTEXT)); + const command = text(b.attr(BUILD_ATTR_COMMAND)); + const directory = text(b.attr(BUILD_ATTR_DIRECTORY)); + return { + kind: b.subType, + watchInclude: strings(b, BUILD_ATTR_WATCH_INCLUDE), + watchExclude: strings(b, BUILD_ATTR_WATCH_EXCLUDE), + ...(path !== undefined ? { path } : {}), + ...(context !== undefined ? { context } : {}), + ...(command !== undefined ? { command } : {}), + ...(directory !== undefined ? { directory } : {}), + }; +} + +function readProcesses(app: MetaData): RailwayProcess[] { + // ADR-0039: resolving, as for the build. + return app + .children() + .filter((c) => c.type === TYPE_RUNTIME) + .map((p) => { + const command = text(p.attr(RUNTIME_ATTR_COMMAND)); + const port = int(p.attr(RUNTIME_ATTR_PORT)); + const healthPath = text(p.attr(RUNTIME_ATTR_HEALTH_PATH)); + const healthTimeoutSeconds = int(p.attr(RUNTIME_ATTR_HEALTH_TIMEOUT_SECONDS)); + const drainSeconds = int(p.attr(RUNTIME_ATTR_DRAIN_SECONDS)); + const restart = text(p.attr(RUNTIME_ATTR_RESTART)); + return { + name: p.name, + ...(command !== undefined ? { command } : {}), + ...(port !== undefined ? { port } : {}), + ...(healthPath !== undefined ? { healthPath } : {}), + ...(healthTimeoutSeconds !== undefined ? { healthTimeoutSeconds } : {}), + ...(drainSeconds !== undefined ? { drainSeconds } : {}), + ...(restart !== undefined ? { restart } : {}), + }; + }); +} + +/** The settings groups `names` (each a group's name or resolution key) name, reporting each that matches none or several. */ +function groupsNamed(names: readonly string[], groups: readonly SettingsGroup[], where: string, problems: string[]): SettingsGroup[] { + const out: SettingsGroup[] = []; + for (const n of names) { + const hits = groups.filter((g) => g.key === n || g.name === n); + if (hits.length === 1) out.push(hits[0]!); + else if (hits.length === 0) { + problems.push(`${where}: @${APP_ATTR_SETTINGS} names "${n}", which is no object.settings in the model; declare it (config pack) so its secrets can be synced, or remove it`); + } else { + problems.push(`${where}: @${APP_ATTR_SETTINGS} "${n}" matches ${hits.map((g) => g.key).join(" and ")}; name it by its package`); + } + } + return out; +} + +/** The setting `Group.field` names, among every group in the model. */ +function settingNamed(ref: string, groups: readonly SettingsGroup[]): Setting | undefined { + const dot = ref.lastIndexOf("."); + if (dot <= 0) return undefined; + const group = ref.slice(0, dot); + const field = ref.slice(dot + 1); + const hits = groups.filter((g) => g.key === group || g.name === group); + if (hits.length !== 1) return undefined; + return hits[0]!.settings.find((s) => s.setting === `${hits[0]!.key}.${field}`); +} + +interface Context { + readonly root: MetaRoot; + readonly all: readonly MetaData[]; + readonly groups: readonly SettingsGroup[]; + readonly vaults: readonly Vault[]; +} + +/** The service name the deployment of `app` in `env` runs as, or undefined when Railway runs it nowhere there. */ +function serviceOf(app: MetaData, env: MetaData, all: readonly MetaData[]): string | undefined { + for (const d of all) { + const a = refList(d, DEPLOYMENT_ATTR_APP)[0]; + const e = refList(d, DEPLOYMENT_ATTR_ENVIRONMENT)[0]; + if (a === undefined || e === undefined) continue; + if (resolveSystemRef(d, a, DEPLOYMENT_ATTR_APP, [TYPE_APP]) !== app) continue; + if (resolveSystemRef(d, e, DEPLOYMENT_ATTR_ENVIRONMENT, [TYPE_ENVIRONMENT]) !== env) continue; + return text(d.attr(RAILWAY_ATTR_SERVICE)) ?? app.name; + } + return undefined; +} + +const URL_OUTPUTS: readonly string[] = ["url", "privateUrl", "publicUrl"]; + +/** A value.ref as the reference template Railway resolves at deploy, its `@path` appended (`${{db.DATABASE_URL}}`), or a problem. */ +function referenceTemplate(value: MetaData, env: MetaData, ctx: Context, where: string, problems: string[]): string | undefined { + const path = text(value.attr(VALUE_ATTR_PATH)); + const output = text(value.attr(VALUE_ATTR_OUTPUT)) ?? ""; + if (path !== undefined && !URL_OUTPUTS.includes(output)) { + problems.push(`${where}: @${VALUE_ATTR_PATH} is appended to a URL, and @${VALUE_ATTR_OUTPUT} ${output} is not one (${URL_OUTPUTS.join(", ")})`); + return undefined; + } + const base = outputTemplate(value, env, ctx, where, problems); + return base === undefined ? undefined : `${base}${path ?? ""}`; +} + +function outputTemplate(value: MetaData, env: MetaData, ctx: Context, where: string, problems: string[]): string | undefined { + const producedBy = text(value.attr(VALUE_ATTR_PRODUCED_BY)) ?? ""; + const output = text(value.attr(VALUE_ATTR_OUTPUT)) ?? ""; + const target = resolveSystemRef(value, producedBy, VALUE_ATTR_PRODUCED_BY, [TYPE_RESOURCE, TYPE_APP]); + if (target === undefined) return undefined; // the delivery pack reports it at load + if (target.type === TYPE_RESOURCE) { + if (text(target.attr(RESOURCE_ATTR_MANAGED_BY)) === "external") { + problems.push(`${where}: @${VALUE_ATTR_PRODUCED_BY} "${producedBy}" is managed outside Railway, which cannot supply its ${output}; give the setting its value from the vault (@secret) or a value.literal`); + return undefined; + } + const engine = text(target.attr(RESOURCE_ATTR_ENGINE)) ?? ""; + const outputs = DATABASE_OUTPUTS[engine]; + const variable = outputs?.[output]; + if (variable === undefined) { + problems.push( + outputs === undefined + ? `${where}: ${target.type}.${target.subType} "${target.name}" has @engine "${engine}"; Railway's database templates are ${Object.keys(DATABASE_OUTPUTS).join(", ")}` + : `${where}: a Railway ${engine} supplies ${Object.keys(outputs).join(", ")}, not ${output}`, + ); + return undefined; + } + return `\${{${target.name}.${variable}}}`; + } + const service = serviceOf(target, env, ctx.all); + if (service === undefined) { + problems.push(`${where}: app "${target.name}" has no deployment.railway in environment ${env.name}, so Railway has no address for it there`); + return undefined; + } + const port = readProcesses(target).find((p) => p.port !== undefined)?.port; + switch (output) { + case "host": + return `\${{${service}.${RAILWAY_PRIVATE_DOMAIN}}}`; + case "publicUrl": + return `https://\${{${service}.${RAILWAY_PUBLIC_DOMAIN}}}`; + case "port": + case "privateUrl": + if (port === undefined) { + problems.push(`${where}: app "${target.name}" declares no runtime.process @port, so its ${output} is unknown`); + return undefined; + } + return output === "port" ? String(port) : `http://\${{${service}.${RAILWAY_PRIVATE_DOMAIN}}}:${port}`; + default: + problems.push(`${where}: an app supplies host, port, privateUrl or publicUrl, not ${output}`); + return undefined; + } +} + +function readDeployment(node: MetaData, ctx: Context, problems: string[]): RailwayDeployment | undefined { + const where = `deployment.railway ${node.resolutionKey()}`; + const appRef = refList(node, DEPLOYMENT_ATTR_APP)[0]; + const envRef = refList(node, DEPLOYMENT_ATTR_ENVIRONMENT)[0]; + const app = appRef === undefined ? undefined : resolveSystemRef(node, appRef, DEPLOYMENT_ATTR_APP, [TYPE_APP]); + const env = envRef === undefined ? undefined : resolveSystemRef(node, envRef, DEPLOYMENT_ATTR_ENVIRONMENT, [TYPE_ENVIRONMENT]); + if (app === undefined || env === undefined) return undefined; // the delivery pack reports it at load + + const repo = text(node.attr(RAILWAY_ATTR_REPO)); + const image = text(node.attr(RAILWAY_ATTR_IMAGE)); + if (repo === undefined && image === undefined) { + problems.push(`${where}: declare @${RAILWAY_ATTR_REPO} or @${RAILWAY_ATTR_IMAGE}; a Railway plan of a service with no source disconnects it`); + } else if (repo !== undefined && image !== undefined) { + problems.push(`${where}: declares both @${RAILWAY_ATTR_REPO} and @${RAILWAY_ATTR_IMAGE}; a Railway service has one source`); + } + + const groups = groupsNamed(refList(app, APP_ATTR_SETTINGS), ctx.groups, `${app.type}.${app.subType} ${app.name}`, problems); + const settings = groups.flatMap((g) => g.settings); + + // ADR-0039: resolving, so a value an estate overlay adds counts. + const valueNodes = node.children().filter((c) => c.type === TYPE_VALUE); + const variables = new Map(); + for (const v of valueNodes) { + const vWhere = `${where} value.${v.subType} ${v.name}`; + const settingRef = text(v.attr(VALUE_ATTR_SETTING)) ?? ""; + const setting = settingNamed(settingRef, ctx.groups); + if (setting === undefined) { + problems.push(`${vWhere}: @${VALUE_ATTR_SETTING} "${settingRef}" names no setting (Group.field) of an object.settings in the model`); + continue; + } + if (!settings.includes(setting)) { + problems.push(`${vWhere}: ${settingRef} is not a setting of the groups ${app.name} reads (@${APP_ATTR_SETTINGS})`); + } + if (setting.secret) { + problems.push(`${vWhere}: ${settingRef} is @secret; its value comes from the vault, never from a value node`); + continue; + } + const value = + v.subType === VALUE_SUBTYPE_LITERAL ? text(v.attr(VALUE_ATTR_LITERAL)) ?? "" : referenceTemplate(v, env, ctx, vWhere, problems); + if (value !== undefined) variables.set(setting.envName, { name: setting.envName, kind: "literal", value, from: `value.${v.subType} ${v.name}` }); + } + if (valueNodes.length > 0) { + for (const s of settings) { + if (variables.has(s.envName)) continue; + if (s.secret) variables.set(s.envName, { name: s.envName, kind: "preserve", from: `${s.setting}, secret: copied from the vault by the sync script` }); + else if (s.default !== undefined) variables.set(s.envName, { name: s.envName, kind: "literal", value: s.default, from: `${s.setting} default` }); + else variables.set(s.envName, { name: s.envName, kind: "preserve", from: `${s.setting}, no value in the model: kept as set on Railway` }); + } + } + + let vault: RailwayDeployment["vault"]; + const secrets = settings.filter((s) => s.secret); + const vaultRef = text(node.attr(DEPLOYMENT_ATTR_SECRETS)); + if (vaultRef !== undefined) { + const v = ctx.vaults.find((x) => x.name === vaultRef || x.key === vaultRef); + const scope = v?.scopes.find((s) => s.name === env.name); + if (v === undefined) problems.push(`${where}: @${DEPLOYMENT_ATTR_SECRETS} "${vaultRef}" names no vault.* in the model`); + else if (v.product !== VAULT_SUBTYPE_INFISICAL) problems.push(`${where}: vault ${v.key} is vault.${v.product}; the sync script reads vault.${VAULT_SUBTYPE_INFISICAL} through keys-axi`); + else if (scope === undefined) problems.push(`${where}: vault ${v.key} has no scope.env named "${env.name}", so the environment's secrets have no place`); + else vault = { key: v.key, scope }; + } else if (secrets.length > 0) { + problems.push(`${where}: ${app.name} reads ${secrets.length} secret setting(s) (${secrets.map((s) => s.envName).join(", ")}) and the deployment names no vault; set @${DEPLOYMENT_ATTR_SECRETS}`); + } + + const resources: RailwayResource[] = []; + for (const ref of refList(app, APP_ATTR_NEEDS)) { + const r = resolveSystemRef(app, ref, APP_ATTR_NEEDS, [TYPE_RESOURCE]); + if (r === undefined || text(r.attr(RESOURCE_ATTR_MANAGED_BY)) === "external") continue; + const engine = text(r.attr(RESOURCE_ATTR_ENGINE)); + const version = text(r.attr(RESOURCE_ATTR_VERSION)); + resources.push({ name: r.name, kind: `${r.type}.${r.subType}`, ...(engine !== undefined ? { engine } : {}), ...(version !== undefined ? { version } : {}) }); + } + + const build = readBuild(app); + const schedule = text(app.attr(APP_ATTR_SCHEDULE)); + const branch = text(node.attr(DEPLOYMENT_ATTR_BRANCH)); + const checkSuites = node.attr(RAILWAY_ATTR_CHECK_SUITES); + const replicas = int(node.attr(DEPLOYMENT_ATTR_REPLICAS)); + const region = text(node.attr(DEPLOYMENT_ATTR_REGION)); + return { + key: node.resolutionKey(), + name: node.name, + environment: env.name, + project: text(node.attr(RAILWAY_ATTR_PROJECT)) ?? "", + service: text(node.attr(RAILWAY_ATTR_SERVICE)) ?? app.name, + appKey: `${app.type}.${app.subType} ${app.name}`, + appKind: app.subType, + ...(schedule !== undefined ? { schedule } : {}), + ...(repo !== undefined ? { repo } : {}), + ...(image !== undefined ? { image } : {}), + ...(branch !== undefined ? { branch } : {}), + ...(typeof checkSuites === "boolean" ? { checkSuites } : {}), + domains: strings(node, DEPLOYMENT_ATTR_DOMAINS), + ...(replicas !== undefined ? { replicas } : {}), + ...(region !== undefined ? { region } : {}), + ...(build !== undefined ? { build } : {}), + processes: readProcesses(app), + hasValues: valueNodes.length > 0, + variables: [...variables.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)), + settings, + ...(vault !== undefined ? { vault } : {}), + resources, + }; +} + +/** The config pack's readers, their problems folded into this pack's list. */ +function configRead(read: () => T, problems: string[], fallback: T): T { + try { + return read(); + } catch (e) { + if (!(e instanceof ConfigModelError)) throw e; + problems.push(...e.problems); + return fallback; + } +} + +/** + * Every Railway project the model deploys to, with its deployments. `objects` are the run's + * objects (the settings groups are among them); `inScope` is the run's scope over a node's + * resolution key. Throws a {@link RailwayModelError} listing every problem. + */ +export function readRailway( + root: MetaRoot, + objects: readonly MetaObject[], + inScope: (key: string) => boolean = () => true, + opts: ReadRailwayOptions = {}, +): RailwayProject[] { + const problems: string[] = []; + const groups = configRead(() => readSettings(objects), problems, []); + const vaults = configRead(() => readVaults(root, inScope), problems, []); + // ADR-0039: resolving, the deployments the model effectively holds. + const all = root.children().filter(isRailwayDeployment); + const ctx: Context = { root, all, groups, vaults }; + const deployments = all + .filter((d) => inScope(d.resolutionKey())) + .map((d) => readDeployment(d, ctx, problems)) + .filter((d): d is RailwayDeployment => d !== undefined) + .filter((d) => opts.project === undefined || d.project === opts.project); + + const byProject = new Map(); + for (const d of deployments) byProject.set(d.project, [...(byProject.get(d.project) ?? []), d]); + if (opts.project !== undefined && byProject.size === 0 && all.length > 0) { + problems.push(`no deployment.railway has @${RAILWAY_ATTR_PROJECT} "${opts.project}" (the model deploys to: ${[...new Set(all.map((d) => text(d.attr(RAILWAY_ATTR_PROJECT))))].join(", ")})`); + } + + const projects: RailwayProject[] = []; + for (const [name, ds] of byProject) { + const services = [...new Set(ds.map((d) => d.service))]; + const partial = opts.partial ?? (services.length === 1 ? services[0]! : name); + if (!PARTIAL_PATTERN.test(partial)) { + problems.push(`Railway project ${name}: the partial name "${partial}" is not 1 to 64 of a-z A-Z 0-9 . _ -; pass { partial } to the generator`); + } + const manageVariables = ds.some((d) => d.hasValues); + if (manageVariables) { + for (const d of ds.filter((x) => x.settings.length === 0)) { + problems.push( + `deployment.railway ${d.key}: another deployment in Railway project ${name} declares value.* nodes, so the file manages variables, and ${d.appKey} reads no settings group: an apply would delete every variable of service ${d.service}. Declare its settings (@${APP_ATTR_SETTINGS})`, + ); + } + } + projects.push({ name, partial, manageVariables, deployments: ds, environments: [...new Set(ds.map((d) => d.environment))] }); + } + if (problems.length > 0) throw new RailwayModelError(problems); + return projects; +} + +/** The one project a generator writes for: `opts.project`, or the model's only one. Undefined when the model deploys nothing to Railway. */ +export function pickProject(projects: readonly RailwayProject[]): RailwayProject | undefined { + if (projects.length > 1) { + throw new RailwayModelError([`the model deploys to ${projects.length} Railway projects (${projects.map((p) => p.name).join(", ")}); one .railway/railway.ts declares one, so pass { project } to the generator`]); + } + return projects[0]; +} + +/** Whether a build or process fact belongs on the file (used by the unexpressed list too). */ +export function isStatic(build: RailwayBuild | undefined): boolean { + return build?.kind === BUILD_SUBTYPE_STATIC; +} diff --git a/packs/railway/typescript/src/railway-ts.ts b/packs/railway/typescript/src/railway-ts.ts new file mode 100644 index 000000000..95ea7cea2 --- /dev/null +++ b/packs/railway/typescript/src/railway-ts.ts @@ -0,0 +1,170 @@ +/** + * `.railway/railway.ts`: Railway's Infrastructure as Code file, in the `railway/iac` DSL of + * the `railway` npm package (3.17.0; docs.railway.com/infrastructure-as-code/reference). The + * `build` and `deploy` blocks use the SDK's `BuildConfig` and `DeployConfig` names, which the + * reference page does not list. + * + * The file is a named partial, so it manages only the services it declares: the databases + * and anything else Railway runs beside them are left alone. One branch per environment the + * model deploys to; Railway passes the environment being planned in `ctx.environment`. + */ +import { RESTART_POLICY, RAILWAY_IAC_MODULE, RAILWAY_SDK_VERSION } from "./constants.js"; +import type { RailwayDeployment, RailwayProject } from "./model.js"; + +/** Code written as it is, not as a JSON value. */ +class Code { + constructor(readonly text: string) {} +} + +type Value = string | number | boolean | Code | readonly Value[] | { readonly [key: string]: Value | undefined }; + +const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/; + +function key(k: string): string { + return IDENT.test(k) ? k : JSON.stringify(k); +} + +/** A value as TypeScript source, one entry per line, at `indent`. */ +function lit(v: Value, indent: string, comments: ReadonlyMap = new Map()): string { + if (v instanceof Code) return v.text; + if (typeof v !== "object") return JSON.stringify(v); + const inner = `${indent} `; + if (Array.isArray(v)) { + if (v.length === 0) return "[]"; + return `[\n${v.map((x) => `${inner}${lit(x as Value, inner)},`).join("\n")}\n${indent}]`; + } + const entries = Object.entries(v as Record).filter((e): e is [string, Value] => e[1] !== undefined); + if (entries.length === 0) return "{}"; + const lines = entries.map(([k, x]) => { + const note = comments.get(k); + return `${inner}${key(k)}: ${lit(x, inner)},${note === undefined ? "" : ` // ${note}`}`; + }); + return `{\n${lines.join("\n")}\n${indent}}`; +} + +function watchPatterns(d: RailwayDeployment): string[] | undefined { + const b = d.build; + if (b === undefined || (b.watchInclude.length === 0 && b.watchExclude.length === 0)) return undefined; + const include = b.watchInclude.length > 0 ? b.watchInclude : ["**"]; + return [...include, ...b.watchExclude.map((g) => `!${g}`)]; +} + +function buildBlock(d: RailwayDeployment): Record | undefined { + const b = d.build; + const out: Record = {}; + if (b?.kind === "dockerfile" && b.path !== undefined) { + out["builder"] = "DOCKERFILE"; + out["dockerfilePath"] = b.path; + } + if (b?.kind === "command" && b.command !== undefined) out["buildCommand"] = b.command; + out["watchPatterns"] = watchPatterns(d); + return Object.values(out).some((x) => x !== undefined) ? out : undefined; +} + +function deployBlock(d: RailwayDeployment): Record | undefined { + const p = d.processes[0]; + const out: Record = { + startCommand: p?.command, + healthcheckPath: p?.healthPath, + healthcheckTimeout: p?.healthTimeoutSeconds, + restartPolicyType: p?.restart === undefined ? undefined : RESTART_POLICY[p.restart], + drainingSeconds: p?.drainSeconds, + cronSchedule: d.schedule, + }; + return Object.values(out).some((x) => x !== undefined) ? out : undefined; +} + +function sourceCall(d: RailwayDeployment, imports: Set): Code | undefined { + if (d.image !== undefined) { + imports.add("image"); + return new Code(`image(${JSON.stringify(d.image)})`); + } + if (d.repo === undefined) return undefined; + imports.add("github"); + const opts: Record = { branch: d.branch, checkSuites: d.checkSuites }; + const set = Object.entries(opts).filter(([, v]) => v !== undefined); + const tail = set.length === 0 ? "" : `, { ${set.map(([k, v]) => `${k}: ${JSON.stringify(v)}`).join(", ")} }`; + return new Code(`github(${JSON.stringify(d.repo)}${tail})`); +} + +function serviceCall(d: RailwayDeployment, manageVariables: boolean, imports: Set, indent: string): string { + const port = d.processes.find((p) => p.port !== undefined)?.port; + const domains = d.domains.map((domain) => (port === undefined ? domain : { domain, port })); + const replicas: Value | undefined = + d.region !== undefined ? { [d.region]: d.replicas ?? 1 } : d.replicas; + let env: Record | undefined; + const notes = new Map(); + if (manageVariables) { + env = {}; + for (const v of d.variables) { + if (v.kind === "preserve") imports.add("preserve"); + env[v.name] = v.kind === "preserve" ? new Code("preserve()") : v.value ?? ""; + notes.set(v.name, v.from); + } + } + const config: Record = { + source: sourceCall(d, imports), + build: buildBlock(d), + deploy: deployBlock(d), + domains: domains.length === 0 ? undefined : domains, + replicas, + }; + const body = lit(config, indent); + const envText = env === undefined ? "" : `\n${indent} env: ${lit(env, `${indent} `, notes)},`; + // `env` goes last, with a comment per variable; splice it before the closing brace. + const withEnv = envText === "" ? body : `${body.slice(0, body.lastIndexOf("\n"))}${envText}\n${indent}}`; + return `service(${JSON.stringify(d.service)}, ${withEnv})`; +} + +function projectCall(project: RailwayProject, ds: readonly RailwayDeployment[], imports: Set, indent: string): string { + const inner = `${indent} `; + const services = ds.map((d) => `${inner} ${serviceCall(d, project.manageVariables, imports, `${inner} `)},`).join("\n"); + // The CLI reads `variables` (its variable policy); the railway 3.17.0 SDK's types do not declare + // it, so a type-check of the file with those types reports it, and Railway still honours it. + const variables = project.manageVariables + ? "" + : `${inner}// Read by the Railway CLI; the railway ${RAILWAY_SDK_VERSION} SDK's types do not declare it yet.\n${inner}variables: { managed: false },\n`; + return `project(${JSON.stringify(project.name)}, {\n${variables}${inner}resources: [\n${services}\n${inner}],\n${indent}})`; +} + +export function renderRailwayTs(project: RailwayProject, header: string): string { + const imports = new Set(["defineRailway", "project", "service"]); + const branches = project.environments.map((env) => { + const ds = project.deployments.filter((d) => d.environment === env); + return ` if (ctx.environment === ${JSON.stringify(env)}) {\n return ${projectCall(project, ds, imports, " ")};\n }`; + }); + const declared = project.environments.join(", "); + const variablesNote = project.manageVariables + ? [ + "// Variables are managed: the file declares every variable of its services, and an apply", + "// deletes one it does not declare. A secret is preserve(): deploy/sync-secrets.sh copies its", + "// value from the vault.", + ] + : [ + "// Variables are unmanaged (`variables: { managed: false }`): an apply changes no variable.", + "// Secrets reach Railway through deploy/sync-secrets.sh, which copies them from the vault.", + ]; + const lines = [ + header, + `// Railway Infrastructure as Code for project ${project.name}, from the model (railway pack).`, + `// The \`${RAILWAY_IAC_MODULE}\` DSL of the \`railway\` npm package ${RAILWAY_SDK_VERSION}.`, + "//", + "// Railway does not read this file during a deploy. It takes effect when `railway config apply`", + "// runs against an environment; `railway config plan` previews it. Both need the SDK beside it:", + `// \`npm install --no-save --prefix .railway railway@${RAILWAY_SDK_VERSION}\`. deploy/deploy.sh does both.`, + "//", + `// A named partial: it manages only the services below. Databases and anything else it does`, + "// not declare are left as they are, and the facts it cannot hold are in deploy/unexpressed.md.", + ...variablesNote, + `import { ${[...imports].sort().join(", ")} } from ${JSON.stringify(RAILWAY_IAC_MODULE)};`, + "", + `export const partial = ${JSON.stringify(project.partial)};`, + "", + "export default defineRailway((ctx) => {", + ...branches, + ` throw new Error(\`.railway/railway.ts: the model deploys nothing to environment "\${ctx.environment}" (it deploys to: ${declared})\`);`, + "});", + "", + ]; + return lines.join("\n"); +} diff --git a/packs/railway/typescript/test/emit.test.ts b/packs/railway/typescript/test/emit.test.ts new file mode 100644 index 000000000..97a56986c --- /dev/null +++ b/packs/railway/typescript/test/emit.test.ts @@ -0,0 +1,55 @@ +import { afterAll, describe, expect, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join, relative } from "node:path"; +import { defineConfig, runGen, type Generator } from "@metaobjectsdev/codegen-ts"; +import type { MetaRoot } from "@metaobjectsdev/metadata"; +import { railwayFiles } from "../src/index.js"; +import { loadFixture } from "./model.js"; + +const scratch = mkdtempSync(join(process.env.DEV_SCRATCH ?? tmpdir(), "pack-railway-")); +afterAll(() => rmSync(scratch, { recursive: true, force: true })); + +const GOLDEN = join(import.meta.dir, "golden"); +/** `UPDATE_GOLDEN=1 bun test` rewrites the golden files from the generators. */ +const UPDATE = process.env["UPDATE_GOLDEN"] === "1"; + +/** A dry run: every rendered file by its path relative to the output directory, nothing written. */ +export async function render(metadata: MetaRoot, generators: Generator[], warnings?: string[]): Promise> { + const out = join(scratch, "out"); + const res = await runGen({ + config: defineConfig({ outDir: out, extStyle: "none", dbImport: "../db", dialect: "sqlite", generators }), + metadata, + projectRoot: scratch, + dryRun: true, + }); + warnings?.push(...res.warnings); + const files = new Map(); + for (const [abs, content] of res.rendered ?? []) files.set(abs.slice(out.length + 1), content); + return files; +} + +function walk(dir: string): string[] { + return readdirSync(dir).flatMap((f) => { + const p = join(dir, f); + return statSync(p).isDirectory() ? walk(p) : [p]; + }); +} + +describe.each(["railway-emit-one-service", "railway-emit-two-services"])("%s", (scenario) => { + test("the generators write the golden files, and only those", async () => { + const files = await render(await loadFixture(scenario), railwayFiles()); + const golden = join(GOLDEN, scenario); + if (UPDATE) { + rmSync(golden, { recursive: true, force: true }); + for (const [path, content] of files) { + mkdirSync(dirname(join(golden, path)), { recursive: true }); + writeFileSync(join(golden, path), content); + } + } + expect(existsSync(golden)).toBe(true); + const expected = new Map(walk(golden).map((p) => [relative(golden, p), readFileSync(p, "utf8")])); + expect([...files.keys()].sort()).toEqual([...expected.keys()].sort()); + for (const [path, content] of files) expect(content).toBe(expected.get(path)!); + }); +}); diff --git a/packs/railway/typescript/test/golden/railway-emit-one-service/.claude/skills/deploy/SKILL.md b/packs/railway/typescript/test/golden/railway-emit-one-service/.claude/skills/deploy/SKILL.md new file mode 100644 index 000000000..6597747a0 --- /dev/null +++ b/packs/railway/typescript/test/golden/railway-emit-one-service/.claude/skills/deploy/SKILL.md @@ -0,0 +1,42 @@ +--- +name: deploy +description: Deploy Railway project game (game) to production from the generated deploy scripts. Use when asked to deploy, ship to Railway, rotate a secret on Railway, or check a Railway deployment. +--- + + + +# Deploy game to Railway + +Generated from the model (railway pack). Every deploy fact lives in the model; the files in +`.railway/` and `deploy/` are written from it. To change a deploy setting, change the model and +regenerate, never the generated files. + +| Environment | Service | Deploys on push to | Domains | Secrets from | +|---|---|---|---|---| +| `production` | `game` | `main` | none | `acme-game/prod` (1 secret) | + +## Before the first deploy + +- `railway login`, then `railway link` in the repository (it writes `.railway/config.json`). +- A `keys-axi` identity that may read each vault scope above (`keys-axi` with no arguments shows it). +- `jq`, `npm` and `curl` on the path. +- If the service still has a Config as Code file (`railway.json` or `railway.toml`): Railway + stops reading it on 2026-12-01. Run `railway config migrate cutover` before the first plan, and + delete the old file only after cutover and the first apply. + +## Deploy + +1. `bash deploy/doctor.sh ` to see where things stand. It prints names, never values. +2. `bash deploy/sync-secrets.sh --dry-run` to see which secrets will be copied. +3. `bash deploy/deploy.sh `: copies the secrets, shows the plan of `.railway/railway.ts` + and applies it after confirmation. Read the plan before confirming: stop if it deletes a + service, a database or a volume. Add `--redeploy` to redeploy now and wait for the health + check instead of waiting for the next push. +4. `bash deploy/doctor.sh ` again. Every line should be `ok`. + +## Rules + +- Never print a secret value, put one on a command line, or paste one into a file. The vault is + the source of truth: rotate a key there, then run `deploy/sync-secrets.sh`. +- Never pass `--confirm-destructive` without a person's explicit go-ahead for that plan. +- A fact Railway's file cannot hold is listed in `deploy/unexpressed.md` with how it is carried. diff --git a/packs/railway/typescript/test/golden/railway-emit-one-service/.railway/railway.ts b/packs/railway/typescript/test/golden/railway-emit-one-service/.railway/railway.ts new file mode 100644 index 000000000..861233a7b --- /dev/null +++ b/packs/railway/typescript/test/golden/railway-emit-one-service/.railway/railway.ts @@ -0,0 +1,56 @@ +// @generated by @metaobjectsdev/pack-railway (railway-ts) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Railway Infrastructure as Code for project game, from the model (railway pack). +// The `railway/iac` DSL of the `railway` npm package 3.17.0. +// +// Railway does not read this file during a deploy. It takes effect when `railway config apply` +// runs against an environment; `railway config plan` previews it. Both need the SDK beside it: +// `npm install --no-save --prefix .railway railway@3.17.0`. deploy/deploy.sh does both. +// +// A named partial: it manages only the services below. Databases and anything else it does +// not declare are left as they are, and the facts it cannot hold are in deploy/unexpressed.md. +// Variables are unmanaged (`variables: { managed: false }`): an apply changes no variable. +// Secrets reach Railway through deploy/sync-secrets.sh, which copies them from the vault. +import { defineRailway, github, project, service } from "railway/iac"; + +export const partial = "game"; + +export default defineRailway((ctx) => { + if (ctx.environment === "production") { + return project("game", { + // Read by the Railway CLI; the railway 3.17.0 SDK's types do not declare it yet. + variables: { managed: false }, + resources: [ + service("game", { + source: github("acme/game", { branch: "main", checkSuites: false }), + build: { + watchPatterns: [ + "**", + "!/.archive/**", + "!/.claude/**", + "!/.docs/**", + "!/.github/**", + "!/.githooks/**", + "!/.metaobjects/*.md", + "!/.metaobjects/.agent-context.json", + "!/.specify/**", + "!/.test-prompts/**", + "!/assets/**", + "!/docs/**", + "!/e2e-tests/**", + "!/scripts/**", + "!/*.md", + "!/TODOs", + ], + }, + deploy: { + healthcheckPath: "/actuator/health/container", + healthcheckTimeout: 300, + restartPolicyType: "ON_FAILURE", + drainingSeconds: 180, + }, + }), + ], + }); + } + throw new Error(`.railway/railway.ts: the model deploys nothing to environment "${ctx.environment}" (it deploys to: production)`); +}); diff --git a/packs/railway/typescript/test/golden/railway-emit-one-service/deploy/deploy.sh b/packs/railway/typescript/test/golden/railway-emit-one-service/deploy/deploy.sh new file mode 100644 index 000000000..c236ca353 --- /dev/null +++ b/packs/railway/typescript/test/golden/railway-emit-one-service/deploy/deploy.sh @@ -0,0 +1,59 @@ +#!/usr/bin/env bash +# @generated by @metaobjectsdev/pack-railway (railway-deploy) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +# Deploys Railway project game to one environment from the model: +# 1. copies the secrets from the vault (deploy/sync-secrets.sh), +# 2. plans and applies `.railway/railway.ts` (`railway config plan`, then `apply`), +# 3. with --redeploy, redeploys each service and waits for its health path, +# 4. runs deploy/doctor.sh. +# A push to the deployment's branch also deploys on Railway; this script is for settings and +# secrets, and for a deploy that cannot wait for a push. --yes applies without the prompt +# (never a destructive change: Railway refuses one without --confirm-destructive). +# +# Needs: railway (logged in, run from the linked repository), keys-axi, jq, npm, curl. +# +# bash deploy/deploy.sh [--yes] [--redeploy] +set -euo pipefail +cd "$(dirname "$0")/.." + +ENVIRONMENT="${1:-}" +YES=(); REDEPLOY=0 +for arg in "${@:2}"; do + case "$arg" in + --yes) YES=(--yes) ;; + --redeploy) REDEPLOY=1 ;; + *) echo 'usage: bash deploy/deploy.sh [--yes] [--redeploy]' >&2; exit 2 ;; + esac +done +ensure_sdk() { + [ -d .railway/node_modules/railway ] || npm install --no-save --prefix .railway railway@3.17.0 >/dev/null +} + +# wait_healthy +wait_healthy() { + local deadline=$((SECONDS + $2)) + until curl -fsS -o /dev/null --max-time 10 "$1"; do + [ "$SECONDS" -lt "$deadline" ] || { echo "deploy: $1 did not answer 2xx within $2 seconds" >&2; return 1; } + sleep 10 + done + echo "healthy: $1" +} + +# settle : sync secrets, then plan and apply the file +settle() { + bash deploy/sync-secrets.sh "$1" + railway environment "$1" >/dev/null + ensure_sdk + railway config plan + railway config apply "${YES[@]}" +} + +case "$ENVIRONMENT" in + production) + settle production + if [ "$REDEPLOY" = 1 ]; then + railway redeploy --service game --yes + fi + bash deploy/doctor.sh production + ;; + *) echo 'usage: bash deploy/deploy.sh [--yes] [--redeploy] (environments: production)' >&2; exit 2 ;; +esac diff --git a/packs/railway/typescript/test/golden/railway-emit-one-service/deploy/doctor.sh b/packs/railway/typescript/test/golden/railway-emit-one-service/deploy/doctor.sh new file mode 100644 index 000000000..f23fe5708 --- /dev/null +++ b/packs/railway/typescript/test/golden/railway-emit-one-service/deploy/doctor.sh @@ -0,0 +1,71 @@ +#!/usr/bin/env bash +# @generated by @metaobjectsdev/pack-railway (railway-doctor) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +# Checks Railway project game against the model, for one environment, by name only: +# every secret the model declares is in the vault and on Railway; `.railway/railway.ts` +# matches what Railway runs (`railway config plan`); each domain answers on the health path. +# Exits 1 when a check fails. It prints names, never a value. +# +# Needs: railway (logged in, run from the linked repository), keys-axi, jq, npm, curl. +# +# bash deploy/doctor.sh +set -uo pipefail +cd "$(dirname "$0")/.." || exit 2 + +ENVIRONMENT="${1:-}" +FAIL=0 +ok() { echo "ok $*"; } +bad() { echo "FAIL $*"; FAIL=1; } +for tool in railway keys-axi jq npm curl; do + command -v "$tool" >/dev/null || { echo "doctor: $tool is not installed" >&2; exit 2; } +done +ensure_sdk() { + [ -d .railway/node_modules/railway ] || npm install --no-save --prefix .railway railway@3.17.0 >/dev/null +} + +# in_vault ... +in_vault() { + local names + names=$(keys-axi ls --project "$1" --env "$2" --json | jq -r '.secrets[].name') || { bad "cannot list vault scope $1/$2"; return; } + local where="$1/$2"; shift 2 + for n in "$@"; do + if grep -qx "$n" <<<"$names"; then ok "$n is in the vault ($where)"; else bad "$n is declared secret and is not in the vault ($where)"; fi + done +} + +# on_railway ... +on_railway() { + local names + names=$(railway variable list --service "$1" --environment "$2" --json | jq -r 'if type == "object" then keys[] else .[].name end') || { bad "cannot list the variables of service $1 ($2)"; return; } + local where="service $1 ($2)"; shift 2 + for n in "$@"; do + if grep -qx "$n" <<<"$names"; then ok "$n is set on $where"; else bad "$n is declared and not set on $where (run deploy/sync-secrets.sh)"; fi + done +} + +# plan_clean : the file matches Railway +plan_clean() { + railway environment "$1" >/dev/null || { bad "cannot link Railway environment $1"; return; } + ensure_sdk || { bad "cannot install the railway SDK into .railway"; return; } + railway config plan --detailed-exit-code >/dev/null 2>&1 + case $? in + 0) ok ".railway/railway.ts matches Railway ($1)" ;; + 2) bad ".railway/railway.ts differs from Railway ($1): run deploy/deploy.sh $1" ;; + *) bad "railway config plan failed ($1): run it by hand to see why" ;; + esac +} + +# answers +answers() { + if curl -fsS -o /dev/null --max-time 10 "$1"; then ok "$1 answers"; else bad "$1 does not answer 2xx"; fi +} + +case "$ENVIRONMENT" in + production) + in_vault acme-game prod LLM_API_KEY + on_railway game production LLM_API_KEY + plan_clean production + ;; + *) echo 'usage: bash deploy/doctor.sh (environments: production)' >&2; exit 2 ;; +esac + +exit "$FAIL" diff --git a/packs/railway/typescript/test/golden/railway-emit-one-service/deploy/sync-secrets.sh b/packs/railway/typescript/test/golden/railway-emit-one-service/deploy/sync-secrets.sh new file mode 100644 index 000000000..497dd2f64 --- /dev/null +++ b/packs/railway/typescript/test/golden/railway-emit-one-service/deploy/sync-secrets.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# @generated by @metaobjectsdev/pack-railway (railway-sync-secrets) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +# Copies every secret setting the model declares from the vault to Railway project game, +# for one environment. A value goes from keys-axi's environment through a pipe into +# `railway variable set --stdin`: it is never printed and never on a command line. It sets +# with --skip-deploys, so the next deploy picks the values up. +# +# Needs: keys-axi (an identity that may read the vault scope) and railway (logged in, run +# from the linked repository). +# +# bash deploy/sync-secrets.sh [--dry-run] +set -euo pipefail +cd "$(dirname "$0")/.." + +ENVIRONMENT="${1:-}" +DRY_RUN=0; [ "${2:-}" = "--dry-run" ] && DRY_RUN=1 + +# copy +copy() { + if [ "$DRY_RUN" = 1 ]; then echo "would copy $5 from $1/$2 to service $3 ($4)"; return; fi + keys-axi run --project "$1" --env "$2" --only "$5" -- bash -c ' + [ -n "${!1+set}" ] || { echo "sync-secrets: $1 is not in the vault scope" >&2; exit 1; } + printf %s "${!1}" | railway variable set "$1" --stdin --service "$2" --environment "$3" --skip-deploys >/dev/null + ' sync-secret "$5" "$3" "$4" + echo "copied $5 to service $3 ($4)" +} + +case "$ENVIRONMENT" in + production) + copy acme-game prod game production LLM_API_KEY + ;; + *) echo 'usage: bash deploy/sync-secrets.sh [--dry-run] (environments: production)' >&2; exit 2 ;; +esac diff --git a/packs/railway/typescript/test/golden/railway-emit-one-service/deploy/unexpressed.md b/packs/railway/typescript/test/golden/railway-emit-one-service/deploy/unexpressed.md new file mode 100644 index 000000000..2e801d342 --- /dev/null +++ b/packs/railway/typescript/test/golden/railway-emit-one-service/deploy/unexpressed.md @@ -0,0 +1,18 @@ + + +# What `.railway/railway.ts` does not hold: Railway project `game` + +Facts the model declares that Railway's Infrastructure as Code file cannot carry, or that this +file leaves to something else, each with how it is carried instead. Generated from the model: +change the model, not this file. + +## game in production + +From deployment.railway `acme::game::server-production`. + +| Fact | How it is carried | +|---|---| +| resource.database `db` (postgres 18) | Not declared, so the partial neither creates nor deletes it. It must exist in the Railway project under the name `db`, which every reference to it uses. | +| resource.cache `cache` (redis) | Not declared, so the partial neither creates nor deletes it. It must exist in the Railway project under the name `cache`, which every reference to it uses. | +| Secret values: `LLM_API_KEY` | Never in the file. deploy/sync-secrets.sh production copies them from the vault scope `acme-game/prod`; deploy/doctor.sh checks the names are in the vault and on Railway. | +| Non-secret settings: `DATABASE_URL`, `REDIS_URL`, `LLM_MODEL` | The file leaves variables unmanaged, so these keep the value set on Railway (or the application's default). Declare a value.* node on the deployment to have the file manage variables. | diff --git a/packs/railway/typescript/test/golden/railway-emit-two-services/.claude/skills/deploy/SKILL.md b/packs/railway/typescript/test/golden/railway-emit-two-services/.claude/skills/deploy/SKILL.md new file mode 100644 index 000000000..ec5fa881c --- /dev/null +++ b/packs/railway/typescript/test/golden/railway-emit-two-services/.claude/skills/deploy/SKILL.md @@ -0,0 +1,43 @@ +--- +name: deploy +description: Deploy Railway project acme-prod (arena, java) to production from the generated deploy scripts. Use when asked to deploy, ship to Railway, rotate a secret on Railway, or check a Railway deployment. +--- + + + +# Deploy acme-prod to Railway + +Generated from the model (railway pack). Every deploy fact lives in the model; the files in +`.railway/` and `deploy/` are written from it. To change a deploy setting, change the model and +regenerate, never the generated files. + +| Environment | Service | Deploys on push to | Domains | Secrets from | +|---|---|---|---|---| +| `production` | `arena` | `main` | `example.com` | `acme-tables/prod` (4 secrets) | +| `production` | `java` | `main` | `admin.example.com` | none (0 secrets) | + +## Before the first deploy + +- `railway login`, then `railway link` in the repository (it writes `.railway/config.json`). +- A `keys-axi` identity that may read each vault scope above (`keys-axi` with no arguments shows it). +- `jq`, `npm` and `curl` on the path. +- If the service still has a Config as Code file (`railway.json` or `railway.toml`): Railway + stops reading it on 2026-12-01. Run `railway config migrate cutover` before the first plan, and + delete the old file only after cutover and the first apply. + +## Deploy + +1. `bash deploy/doctor.sh ` to see where things stand. It prints names, never values. +2. `bash deploy/sync-secrets.sh --dry-run` to see which secrets will be copied. +3. `bash deploy/deploy.sh `: copies the secrets, shows the plan of `.railway/railway.ts` + and applies it after confirmation. Read the plan before confirming: stop if it deletes a + service, a database or a volume. Add `--redeploy` to redeploy now and wait for the health + check instead of waiting for the next push. +4. `bash deploy/doctor.sh ` again. Every line should be `ok`. + +## Rules + +- Never print a secret value, put one on a command line, or paste one into a file. The vault is + the source of truth: rotate a key there, then run `deploy/sync-secrets.sh`. +- Never pass `--confirm-destructive` without a person's explicit go-ahead for that plan. +- A fact Railway's file cannot hold is listed in `deploy/unexpressed.md` with how it is carried. diff --git a/packs/railway/typescript/test/golden/railway-emit-two-services/.railway/railway.ts b/packs/railway/typescript/test/golden/railway-emit-two-services/.railway/railway.ts new file mode 100644 index 000000000..e3fb17e0a --- /dev/null +++ b/packs/railway/typescript/test/golden/railway-emit-two-services/.railway/railway.ts @@ -0,0 +1,77 @@ +// @generated by @metaobjectsdev/pack-railway (railway-ts) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Railway Infrastructure as Code for project acme-prod, from the model (railway pack). +// The `railway/iac` DSL of the `railway` npm package 3.17.0. +// +// Railway does not read this file during a deploy. It takes effect when `railway config apply` +// runs against an environment; `railway config plan` previews it. Both need the SDK beside it: +// `npm install --no-save --prefix .railway railway@3.17.0`. deploy/deploy.sh does both. +// +// A named partial: it manages only the services below. Databases and anything else it does +// not declare are left as they are, and the facts it cannot hold are in deploy/unexpressed.md. +// Variables are managed: the file declares every variable of its services, and an apply +// deletes one it does not declare. A secret is preserve(): deploy/sync-secrets.sh copies its +// value from the vault. +import { defineRailway, github, preserve, project, service } from "railway/iac"; + +export const partial = "acme-prod"; + +export default defineRailway((ctx) => { + if (ctx.environment === "production") { + return project("acme-prod", { + resources: [ + service("arena", { + source: github("acme/tables", { branch: "main" }), + build: { + builder: "DOCKERFILE", + dockerfilePath: "arena/Dockerfile", + watchPatterns: [ + "arena/**", + "!arena/tests/**", + "!metaobjects/**", + ], + }, + domains: [ + "example.com", + ], + env: { + ANTHROPIC_API_KEY: preserve(), // acme::tables::Llm.anthropicKey, secret: copied from the vault by the sync script + COMMENTARY_BASE_URL: preserve(), // acme::tables::Commentary.baseUrl, no value in the model: kept as set on Railway + DATABASE_URL: "${{Postgres.DATABASE_URL}}", // value.ref db + JAVA_API_URL: "http://${{java.RAILWAY_PRIVATE_DOMAIN}}:8080/api", // value.ref api + OPENAI_API_KEY: preserve(), // acme::tables::Llm.openaiKey, secret: copied from the vault by the sync script + REDIS_URL: "${{Redis.REDIS_URL}}", // value.ref cache + ROUTER_HOST: "${{java.RAILWAY_PRIVATE_DOMAIN}}", // value.ref routerHost + ROUTER_PASSWORD: preserve(), // acme::tables::Router.password, secret: copied from the vault by the sync script + ROUTER_PORT: "8891", // value.literal routerPort + SESSION_SECRET: preserve(), // acme::tables::Session.secret, secret: copied from the vault by the sync script + }, + }), + service("java", { + source: github("acme/tables", { branch: "main" }), + build: { + builder: "DOCKERFILE", + dockerfilePath: "java/Dockerfile", + watchPatterns: [ + "java/**", + "poker/**", + "framework/**", + ], + }, + deploy: { + healthcheckPath: "/health", + }, + domains: [ + { + domain: "admin.example.com", + port: 8080, + }, + ], + env: { + DATABASE_URL: "${{Postgres.DATABASE_URL}}", // value.ref db + }, + }), + ], + }); + } + throw new Error(`.railway/railway.ts: the model deploys nothing to environment "${ctx.environment}" (it deploys to: production)`); +}); diff --git a/packs/railway/typescript/test/golden/railway-emit-two-services/deploy/deploy.sh b/packs/railway/typescript/test/golden/railway-emit-two-services/deploy/deploy.sh new file mode 100644 index 000000000..66a3ed966 --- /dev/null +++ b/packs/railway/typescript/test/golden/railway-emit-two-services/deploy/deploy.sh @@ -0,0 +1,61 @@ +#!/usr/bin/env bash +# @generated by @metaobjectsdev/pack-railway (railway-deploy) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +# Deploys Railway project acme-prod to one environment from the model: +# 1. copies the secrets from the vault (deploy/sync-secrets.sh), +# 2. plans and applies `.railway/railway.ts` (`railway config plan`, then `apply`), +# 3. with --redeploy, redeploys each service and waits for its health path, +# 4. runs deploy/doctor.sh. +# A push to the deployment's branch also deploys on Railway; this script is for settings and +# secrets, and for a deploy that cannot wait for a push. --yes applies without the prompt +# (never a destructive change: Railway refuses one without --confirm-destructive). +# +# Needs: railway (logged in, run from the linked repository), keys-axi, jq, npm, curl. +# +# bash deploy/deploy.sh [--yes] [--redeploy] +set -euo pipefail +cd "$(dirname "$0")/.." + +ENVIRONMENT="${1:-}" +YES=(); REDEPLOY=0 +for arg in "${@:2}"; do + case "$arg" in + --yes) YES=(--yes) ;; + --redeploy) REDEPLOY=1 ;; + *) echo 'usage: bash deploy/deploy.sh [--yes] [--redeploy]' >&2; exit 2 ;; + esac +done +ensure_sdk() { + [ -d .railway/node_modules/railway ] || npm install --no-save --prefix .railway railway@3.17.0 >/dev/null +} + +# wait_healthy +wait_healthy() { + local deadline=$((SECONDS + $2)) + until curl -fsS -o /dev/null --max-time 10 "$1"; do + [ "$SECONDS" -lt "$deadline" ] || { echo "deploy: $1 did not answer 2xx within $2 seconds" >&2; return 1; } + sleep 10 + done + echo "healthy: $1" +} + +# settle : sync secrets, then plan and apply the file +settle() { + bash deploy/sync-secrets.sh "$1" + railway environment "$1" >/dev/null + ensure_sdk + railway config plan + railway config apply "${YES[@]}" +} + +case "$ENVIRONMENT" in + production) + settle production + if [ "$REDEPLOY" = 1 ]; then + railway redeploy --service arena --yes + railway redeploy --service java --yes + wait_healthy https://admin.example.com/health 300 + fi + bash deploy/doctor.sh production + ;; + *) echo 'usage: bash deploy/deploy.sh [--yes] [--redeploy] (environments: production)' >&2; exit 2 ;; +esac diff --git a/packs/railway/typescript/test/golden/railway-emit-two-services/deploy/doctor.sh b/packs/railway/typescript/test/golden/railway-emit-two-services/deploy/doctor.sh new file mode 100644 index 000000000..6f83093f4 --- /dev/null +++ b/packs/railway/typescript/test/golden/railway-emit-two-services/deploy/doctor.sh @@ -0,0 +1,72 @@ +#!/usr/bin/env bash +# @generated by @metaobjectsdev/pack-railway (railway-doctor) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +# Checks Railway project acme-prod against the model, for one environment, by name only: +# every secret the model declares is in the vault and on Railway; `.railway/railway.ts` +# matches what Railway runs (`railway config plan`); each domain answers on the health path. +# Exits 1 when a check fails. It prints names, never a value. +# +# Needs: railway (logged in, run from the linked repository), keys-axi, jq, npm, curl. +# +# bash deploy/doctor.sh +set -uo pipefail +cd "$(dirname "$0")/.." || exit 2 + +ENVIRONMENT="${1:-}" +FAIL=0 +ok() { echo "ok $*"; } +bad() { echo "FAIL $*"; FAIL=1; } +for tool in railway keys-axi jq npm curl; do + command -v "$tool" >/dev/null || { echo "doctor: $tool is not installed" >&2; exit 2; } +done +ensure_sdk() { + [ -d .railway/node_modules/railway ] || npm install --no-save --prefix .railway railway@3.17.0 >/dev/null +} + +# in_vault ... +in_vault() { + local names + names=$(keys-axi ls --project "$1" --env "$2" --json | jq -r '.secrets[].name') || { bad "cannot list vault scope $1/$2"; return; } + local where="$1/$2"; shift 2 + for n in "$@"; do + if grep -qx "$n" <<<"$names"; then ok "$n is in the vault ($where)"; else bad "$n is declared secret and is not in the vault ($where)"; fi + done +} + +# on_railway ... +on_railway() { + local names + names=$(railway variable list --service "$1" --environment "$2" --json | jq -r 'if type == "object" then keys[] else .[].name end') || { bad "cannot list the variables of service $1 ($2)"; return; } + local where="service $1 ($2)"; shift 2 + for n in "$@"; do + if grep -qx "$n" <<<"$names"; then ok "$n is set on $where"; else bad "$n is declared and not set on $where (run deploy/sync-secrets.sh)"; fi + done +} + +# plan_clean : the file matches Railway +plan_clean() { + railway environment "$1" >/dev/null || { bad "cannot link Railway environment $1"; return; } + ensure_sdk || { bad "cannot install the railway SDK into .railway"; return; } + railway config plan --detailed-exit-code >/dev/null 2>&1 + case $? in + 0) ok ".railway/railway.ts matches Railway ($1)" ;; + 2) bad ".railway/railway.ts differs from Railway ($1): run deploy/deploy.sh $1" ;; + *) bad "railway config plan failed ($1): run it by hand to see why" ;; + esac +} + +# answers +answers() { + if curl -fsS -o /dev/null --max-time 10 "$1"; then ok "$1 answers"; else bad "$1 does not answer 2xx"; fi +} + +case "$ENVIRONMENT" in + production) + in_vault acme-tables prod ROUTER_PASSWORD SESSION_SECRET ANTHROPIC_API_KEY OPENAI_API_KEY + on_railway arena production ROUTER_PASSWORD SESSION_SECRET ANTHROPIC_API_KEY OPENAI_API_KEY + plan_clean production + answers https://admin.example.com/health + ;; + *) echo 'usage: bash deploy/doctor.sh (environments: production)' >&2; exit 2 ;; +esac + +exit "$FAIL" diff --git a/packs/railway/typescript/test/golden/railway-emit-two-services/deploy/sync-secrets.sh b/packs/railway/typescript/test/golden/railway-emit-two-services/deploy/sync-secrets.sh new file mode 100644 index 000000000..2f1bd952b --- /dev/null +++ b/packs/railway/typescript/test/golden/railway-emit-two-services/deploy/sync-secrets.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# @generated by @metaobjectsdev/pack-railway (railway-sync-secrets) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +# Copies every secret setting the model declares from the vault to Railway project acme-prod, +# for one environment. A value goes from keys-axi's environment through a pipe into +# `railway variable set --stdin`: it is never printed and never on a command line. It sets +# with --skip-deploys, so the next deploy picks the values up. +# +# Needs: keys-axi (an identity that may read the vault scope) and railway (logged in, run +# from the linked repository). +# +# bash deploy/sync-secrets.sh [--dry-run] +set -euo pipefail +cd "$(dirname "$0")/.." + +ENVIRONMENT="${1:-}" +DRY_RUN=0; [ "${2:-}" = "--dry-run" ] && DRY_RUN=1 + +# copy +copy() { + if [ "$DRY_RUN" = 1 ]; then echo "would copy $5 from $1/$2 to service $3 ($4)"; return; fi + keys-axi run --project "$1" --env "$2" --only "$5" -- bash -c ' + [ -n "${!1+set}" ] || { echo "sync-secrets: $1 is not in the vault scope" >&2; exit 1; } + printf %s "${!1}" | railway variable set "$1" --stdin --service "$2" --environment "$3" --skip-deploys >/dev/null + ' sync-secret "$5" "$3" "$4" + echo "copied $5 to service $3 ($4)" +} + +case "$ENVIRONMENT" in + production) + copy acme-tables prod arena production ROUTER_PASSWORD + copy acme-tables prod arena production SESSION_SECRET + copy acme-tables prod arena production ANTHROPIC_API_KEY + copy acme-tables prod arena production OPENAI_API_KEY + ;; + *) echo 'usage: bash deploy/sync-secrets.sh [--dry-run] (environments: production)' >&2; exit 2 ;; +esac diff --git a/packs/railway/typescript/test/golden/railway-emit-two-services/deploy/unexpressed.md b/packs/railway/typescript/test/golden/railway-emit-two-services/deploy/unexpressed.md new file mode 100644 index 000000000..e518920ed --- /dev/null +++ b/packs/railway/typescript/test/golden/railway-emit-two-services/deploy/unexpressed.md @@ -0,0 +1,27 @@ + + +# What `.railway/railway.ts` does not hold: Railway project `acme-prod` + +Facts the model declares that Railway's Infrastructure as Code file cannot carry, or that this +file leaves to something else, each with how it is carried instead. Generated from the model: +change the model, not this file. + +## arena in production + +From deployment.railway `acme::tables::arena-production`. + +| Fact | How it is carried | +|---|---| +| resource.database `Postgres` (postgres 18) | Not declared, so the partial neither creates nor deletes it. It must exist in the Railway project under the name `Postgres`, which every reference to it uses. | +| resource.cache `Redis` (redis) | Not declared, so the partial neither creates nor deletes it. It must exist in the Railway project under the name `Redis`, which every reference to it uses. | +| DNS for `example.com` | The file attaches the domains to the service; the DNS record each needs (the CNAME Railway shows for it) is set at the DNS provider. deploy/doctor.sh checks each answers on the health path. | +| Secret values: `ROUTER_PASSWORD`, `SESSION_SECRET`, `ANTHROPIC_API_KEY`, `OPENAI_API_KEY` | Never in the file. deploy/sync-secrets.sh production copies them from the vault scope `acme-tables/prod`; deploy/doctor.sh checks the names are in the vault and on Railway. | + +## java in production + +From deployment.railway `acme::tables::java-production`. + +| Fact | How it is carried | +|---|---| +| resource.database `Postgres` (postgres 18) | Not declared, so the partial neither creates nor deletes it. It must exist in the Railway project under the name `Postgres`, which every reference to it uses. | +| DNS for `admin.example.com` | The file attaches the domains to the service; the DNS record each needs (the CNAME Railway shows for it) is set at the DNS provider. deploy/doctor.sh checks each answers on the health path. | diff --git a/packs/railway/typescript/test/model.test.ts b/packs/railway/typescript/test/model.test.ts new file mode 100644 index 000000000..cd2356b66 --- /dev/null +++ b/packs/railway/typescript/test/model.test.ts @@ -0,0 +1,132 @@ +import { describe, expect, test } from "bun:test"; +import { isMetaObject, type MetaObject } from "@metaobjectsdev/metadata"; +import { RailwayModelError, pickProject, readRailway } from "../src/index.js"; +import { fixtureSources, loadModels } from "./model.js"; + +type Json = { "metadata.root": { package: string; children: Record>[] } }; + +/** The one-service fixture, changed by `edit`. */ +function oneService(edit: (children: Record>[]) => void): string { + const model = JSON.parse(fixtureSources("railway-emit-one-service")[0]!.json) as Json; + edit(model["metadata.root"].children); + return JSON.stringify(model); +} + +function deployment(children: Record>[]): Record { + return children.find((c) => "deployment.railway" in c)!["deployment.railway"]!; +} + +async function problems(json: string): Promise { + const root = await loadModels([{ id: "meta.game.json", json }]); + const objects = root.children().filter(isMetaObject) as MetaObject[]; + try { + pickProject(readRailway(root, objects)); + } catch (e) { + if (e instanceof RailwayModelError) return [...e.problems]; + throw e; + } + return []; +} + +describe("readRailway refuses what Railway cannot do", () => { + test("the fixture as written has no problems", async () => { + expect(await problems(oneService(() => {}))).toEqual([]); + }); + + test("a deployment with no source: a plan would disconnect the service", async () => { + const p = await problems(oneService((c) => delete deployment(c)["@repo"])); + expect(p.join("\n")).toContain("declare @repo or @image"); + }); + + test("both @repo and @image", async () => { + const p = await problems(oneService((c) => (deployment(c)["@image"] = "ghcr.io/acme/game:1"))); + expect(p.join("\n")).toContain("both @repo and @image"); + }); + + test("secret settings with no vault named", async () => { + const p = await problems(oneService((c) => delete deployment(c)["@secrets"])); + expect(p.join("\n")).toContain("LLM_API_KEY"); + expect(p.join("\n")).toContain("set @secrets"); + }); + + test("a vault with no scope for the environment", async () => { + const p = await problems(oneService((c) => (deployment(c)["@environment"] = "staging", c.push({ "environment.standing": { name: "staging" } })))); + expect(p.join("\n")).toContain('no scope.env named "staging"'); + }); + + test("a value node for a secret setting", async () => { + const p = await problems( + oneService((c) => (deployment(c)["children"] = [{ "value.literal": { name: "k", "@setting": "Llm.apiKey", "@literal": "x" } }])), + ); + expect(p.join("\n")).toContain("is @secret"); + }); + + test("a value node for a setting nobody declared", async () => { + const p = await problems( + oneService((c) => (deployment(c)["children"] = [{ "value.literal": { name: "k", "@setting": "Nope.thing", "@literal": "x" } }])), + ); + expect(p.join("\n")).toContain('"Nope.thing" names no setting'); + }); + + test("@path on an output that is not a URL", async () => { + const p = await problems( + oneService( + (c) => (deployment(c)["children"] = [{ "value.ref": { name: "h", "@setting": "Database.url", "@producedBy": "Game.db", "@output": "host", "@path": "/x" } }]), + ), + ); + expect(p.join("\n")).toContain("@path is appended to a URL"); + }); + + test("an output the engine does not supply", async () => { + const p = await problems( + oneService((c) => { + const game = c.find((x) => "system.internal" in x)!["system.internal"]!["children"] as Record>[]; + game.push({ "resource.bucket": { name: "files", "@engine": "r2", "@managedBy": "external" } }); + deployment(c)["children"] = [{ "value.ref": { name: "f", "@setting": "Database.url", "@producedBy": "Game.files", "@output": "url" } }]; + }), + ); + expect(p.join("\n")).toContain("managed outside Railway"); + }); + + test("an @settings group that is not in the model", async () => { + const p = await problems( + oneService((c) => { + const game = c.find((x) => "system.internal" in x)!["system.internal"]!["children"] as Record>[]; + (game[0]!["app.service"] as Record)["@settings"] = ["Database", "Missing"]; + }), + ); + expect(p.join("\n")).toContain('"Missing", which is no object.settings'); + }); + + test("a value node makes the file manage variables, and the values resolve", async () => { + const json = oneService( + (c) => (deployment(c)["children"] = [{ "value.ref": { name: "db", "@setting": "Database.url", "@producedBy": "Game.db", "@output": "url" } }]), + ); + const root = await loadModels([{ id: "meta.game.json", json }]); + const p = pickProject(readRailway(root, root.children().filter(isMetaObject) as MetaObject[]))!; + expect(p.manageVariables).toBe(true); + expect(p.deployments[0]!.variables.map((v) => [v.name, v.kind, v.value])).toEqual([ + ["DATABASE_URL", "literal", "${{db.DATABASE_URL}}"], + ["LLM_API_KEY", "preserve", undefined], + ["LLM_MODEL", "literal", "small"], + ["REDIS_URL", "preserve", undefined], + ]); + }); + + test("two Railway projects need { project }", async () => { + const json = oneService((c) => { + c.push({ "environment.standing": { name: "staging" } }); + c.push({ "vault.infisical": { name: "keys2", children: [{ "scope.env": { name: "staging", "@project": "acme-game" } }] } }); + c.push({ "deployment.railway": { ...deployment(c), name: "server-staging", "@environment": "staging", "@project": "other", "@secrets": "keys2" } }); + }); + const root = await loadModels([{ id: "meta.game.json", json }]); + const objects = root.children().filter(isMetaObject) as MetaObject[]; + expect(() => pickProject(readRailway(root, objects))).toThrow("pass { project }"); + expect(pickProject(readRailway(root, objects, () => true, { project: "other" }))!.name).toBe("other"); + }); + + test("a partial name Railway refuses", async () => { + const p = await problems(oneService((c) => (deployment(c)["@service"] = "game server"))); + expect(p.join("\n")).toContain("partial name"); + }); +}); diff --git a/packs/railway/typescript/test/model.ts b/packs/railway/typescript/test/model.ts new file mode 100644 index 000000000..c2db21fbb --- /dev/null +++ b/packs/railway/typescript/test/model.ts @@ -0,0 +1,32 @@ +// Loads a conformance fixture's input/ with the pack and every pack it requires composed. +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { MetaDataLoader, InMemoryStringSource, composeRegistry, coreProviders, type MetaRoot } from "@metaobjectsdev/metadata"; +import { configProvider } from "@metaobjectsdev/pack-config"; +import { provider as deliveryProvider } from "@metaobjectsdev/pack-delivery"; +import { provider as systemsProvider } from "@metaobjectsdev/pack-systems"; +import { provider as railwayProvider } from "../src/index.js"; + +export const CORPUS = join(import.meta.dir, "../../fixtures/conformance"); + +/** One source per model, or one per file of a fixture's input/ directory. */ +export async function loadModels(sources: readonly { id: string; json: string }[]): Promise { + const registry = composeRegistry([...coreProviders, systemsProvider, deliveryProvider, configProvider, railwayProvider]); + const res = await new MetaDataLoader({ registry, strict: true }).load( + sources.map((s) => new InMemoryStringSource(s.json, { id: s.id, format: "json" })), + ); + if (res.errors.length > 0) throw new Error(res.errors.map((e) => e.message).join("\n")); + return res.root; +} + +export function fixtureSources(scenario: string): { id: string; json: string }[] { + const dir = join(CORPUS, scenario, "input"); + return readdirSync(dir) + .filter((f) => f.endsWith(".json")) + .sort() + .map((f) => ({ id: f, json: readFileSync(join(dir, f), "utf8") })); +} + +export function loadFixture(scenario: string): Promise { + return loadModels(fixtureSources(scenario)); +} diff --git a/packs/railway/typescript/tsconfig.json b/packs/railway/typescript/tsconfig.json index b33fae1d4..66c8af379 100644 --- a/packs/railway/typescript/tsconfig.json +++ b/packs/railway/typescript/tsconfig.json @@ -1,7 +1,8 @@ { "extends": "../../../server/typescript/tsconfig.base.json", "compilerOptions": { - "noEmit": true + "noEmit": true, + "customConditions": ["bun"] }, "include": ["src/**/*", "test/**/*"] } From a00db48dad7c15f37ad59c097caea596c998d3c7 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 25 Nov 2026 04:47:55 -0500 Subject: [PATCH 2/4] fix(packs): railway emitter review fixes, coverage bar, delivery readers and output check - The generated .railway/railway.ts type-checks against the railway SDK: the unmanaged variables policy is spread from a constant, which the excess-property check skips. - Each service names the app and deployment it comes from. - A coverage test holds the generated file to every fact of the hand-written configuration the emit fixtures are modelled on, fact by fact, instead of byte identity. - A managed file declares every setting even for a deployment with no values; a reference resolves only within its Railway project; a settings problem is reported alone. - delivery: readBuild/readProcesses readers, and ERR_DELIVERY_UNSUPPORTED_OUTPUT at load for a value.ref asking for an output its producer lacks (railway fixture error-value-ref-unsupported-output). - Scripts: unknown flags refused, deploy --yes quoted safely, doctor's cd guarded, shellcheck clean at every level. --- packs/delivery/CHANGELOG.md | 5 + packs/delivery/README.md | 13 +- .../fixtures/conformance/ERROR-CODES.json | 3 +- packs/delivery/typescript/src/constants.ts | 15 ++ packs/delivery/typescript/src/index.ts | 31 +++ packs/delivery/typescript/src/readers.ts | 99 +++++++++ packs/railway/CHANGELOG.md | 4 +- packs/railway/README.md | 18 +- .../expected-errors.json | 35 ++++ .../input/meta.shop.json | 25 +++ .../providers.json | 1 + packs/railway/typescript/src/constants.ts | 8 +- packs/railway/typescript/src/files.ts | 55 ++--- packs/railway/typescript/src/generators.ts | 51 ++--- packs/railway/typescript/src/model.ts | 195 +++++------------- packs/railway/typescript/src/railway-ts.ts | 70 ++++--- .../railway/typescript/test/coverage.test.ts | 85 ++++++++ .../.railway/railway.ts | 7 +- .../railway-emit-one-service/deploy/deploy.sh | 7 +- .../railway-emit-one-service/deploy/doctor.sh | 5 - .../deploy/sync-secrets.sh | 9 +- .../.railway/railway.ts | 2 + .../deploy/deploy.sh | 7 +- .../deploy/sync-secrets.sh | 9 +- packs/railway/typescript/test/model.test.ts | 34 ++- packs/systems/typescript/src/constants.ts | 2 + 26 files changed, 551 insertions(+), 244 deletions(-) create mode 100644 packs/delivery/typescript/src/readers.ts create mode 100644 packs/railway/fixtures/conformance/error-value-ref-unsupported-output/expected-errors.json create mode 100644 packs/railway/fixtures/conformance/error-value-ref-unsupported-output/input/meta.shop.json create mode 100644 packs/railway/fixtures/conformance/error-value-ref-unsupported-output/providers.json create mode 100644 packs/railway/typescript/test/coverage.test.ts diff --git a/packs/delivery/CHANGELOG.md b/packs/delivery/CHANGELOG.md index 383f3ba73..badd9bf01 100644 --- a/packs/delivery/CHANGELOG.md +++ b/packs/delivery/CHANGELOG.md @@ -15,3 +15,8 @@ This pack's own changelog (ADR-0069). The root `CHANGELOG.md` records core only. build, for an app that lives in one directory of a monorepo. - `@path` on `value.ref`: a path appended to a URL output (`/api`), for a setting that addresses one context of another app. +- `readBuild(app)` and `readProcesses(app)`: an app's build and processes as plain records, for a + platform pack's generator to read instead of decoding the attributes itself. +- `ERR_DELIVERY_UNSUPPORTED_OUTPUT`: a `value.ref` that asks for an output its producer does not + have fails the load: `@path` on an output that is not a URL, an app asked for its `url`, `user` + or `password`, or for its `port` or `privateUrl` when no process declares a `@port`. diff --git a/packs/delivery/README.md b/packs/delivery/README.md index e060e17bb..81b40c37e 100644 --- a/packs/delivery/README.md +++ b/packs/delivery/README.md @@ -46,7 +46,12 @@ the config pack and the deployment names its vault in `@secrets`. The full defin - A model holds at most one deployment per (`@app`, `@environment`), compared as resolved nodes, so `Game.server` and `acme::game::Game.server` collide (`ERR_DELIVERY_DUPLICATE_DEPLOYMENT`). -Each fails the load with `ERR_DELIVERY_UNRESOLVED_REF` when it resolves to nothing or to the wrong +A `value.ref` asks only for an output its producer has (`ERR_DELIVERY_UNSUPPORTED_OUTPUT`): `@path` +extends a URL output only (`url`, `privateUrl`, `publicUrl`); an app produces `host`, `port`, +`privateUrl` and `publicUrl`, and `port` and `privateUrl` need a process that declares `@port`. A +resource's outputs depend on its engine and are left to the platform pack. + +A reference fails the load with `ERR_DELIVERY_UNRESOLVED_REF` when it resolves to nothing or to the wrong kind of node. A platform pack holds its deployments to the same rule by passing `validateDeployment` as its subtype's validator. `@secrets` (a config pack `vault.*`) and `@setting` (`Group.field` of an `object.settings`) are names only: this pack does not require the @@ -66,6 +71,12 @@ overlay, using the loader's existing merge: The `railway` pack's `railway-worked-example` fixture is the whole example, both sides. +## Readers + +`readBuild(app)` and `readProcesses(app)` return an app's build and processes as plain records +(resolving accessors, so an inherited build counts). A platform pack's generator reads through +them. + ## Ports TypeScript only (ADR-0069's port rule: elsewhere a model that uses it fails by name). diff --git a/packs/delivery/fixtures/conformance/ERROR-CODES.json b/packs/delivery/fixtures/conformance/ERROR-CODES.json index 1fc83ab60..e24dd1a9b 100644 --- a/packs/delivery/fixtures/conformance/ERROR-CODES.json +++ b/packs/delivery/fixtures/conformance/ERROR-CODES.json @@ -3,6 +3,7 @@ "codes": { "ERR_DELIVERY_UNRESOLVED_REF": "A deployment's @app or @environment, or a value.ref's @producedBy, names no node, or names a node of the wrong kind (@app takes an app.*, @environment an environment.*, @producedBy a resource.* or an app.*).", "ERR_DELIVERY_DUPLICATE_SETTING": "A deployment holds two value.* nodes for one @setting. An estate overlay that overrides a value must reuse the value node's name so it merges.", - "ERR_DELIVERY_DUPLICATE_DEPLOYMENT": "Two deployments target the same (@app, @environment), compared as resolved nodes." + "ERR_DELIVERY_DUPLICATE_DEPLOYMENT": "Two deployments target the same (@app, @environment), compared as resolved nodes.", + "ERR_DELIVERY_UNSUPPORTED_OUTPUT": "A value.ref asks its producer for an output it does not have: @path on an output that is not a URL (url, privateUrl, publicUrl), an app asked for anything but host, port, privateUrl or publicUrl, or an app with no runtime.process @port asked for its port or privateUrl." } } diff --git a/packs/delivery/typescript/src/constants.ts b/packs/delivery/typescript/src/constants.ts index d20528f21..20da13be7 100644 --- a/packs/delivery/typescript/src/constants.ts +++ b/packs/delivery/typescript/src/constants.ts @@ -51,6 +51,11 @@ export const VALUE_ATTR_OUTPUT = "output"; export const VALUE_ATTR_PATH = "path"; export const VALUE_OUTPUTS = ["url", "host", "port", "user", "password", "privateUrl", "publicUrl"] as const; export type ValueOutput = (typeof VALUE_OUTPUTS)[number]; +export const OUTPUT_URL = "url"; +export const OUTPUT_HOST = "host"; +export const OUTPUT_PORT = "port"; +export const OUTPUT_PRIVATE_URL = "privateUrl"; +export const OUTPUT_PUBLIC_URL = "publicUrl"; /** Raised when a deployment's @app / @environment or a value.ref's @producedBy names nothing, or the wrong kind of node. */ export const ERR_DELIVERY_UNRESOLVED_REF = "ERR_DELIVERY_UNRESOLVED_REF"; @@ -60,3 +65,13 @@ export const ERR_DELIVERY_DUPLICATE_SETTING = "ERR_DELIVERY_DUPLICATE_SETTING"; /** Raised when two deployments target the same (@app, @environment). */ export const ERR_DELIVERY_DUPLICATE_DEPLOYMENT = "ERR_DELIVERY_DUPLICATE_DEPLOYMENT"; + +/** Raised when a value.ref asks its producer for an output it does not have: `@path` on an output that is not a URL, or an app asked for its url, user or password, or for its port with none declared. */ +export const ERR_DELIVERY_UNSUPPORTED_OUTPUT = "ERR_DELIVERY_UNSUPPORTED_OUTPUT"; + +/** The outputs that are URLs, the only ones a value.ref `@path` may extend. */ +export const URL_OUTPUTS: readonly ValueOutput[] = [OUTPUT_URL, OUTPUT_PRIVATE_URL, OUTPUT_PUBLIC_URL]; +/** The outputs an app produces: its addresses. A resource produces every output its engine has. */ +export const APP_OUTPUTS: readonly ValueOutput[] = [OUTPUT_HOST, OUTPUT_PORT, OUTPUT_PRIVATE_URL, OUTPUT_PUBLIC_URL]; +/** The app outputs that need a runtime.process `@port`. */ +export const PORT_OUTPUTS: readonly ValueOutput[] = [OUTPUT_PORT, OUTPUT_PRIVATE_URL]; diff --git a/packs/delivery/typescript/src/index.ts b/packs/delivery/typescript/src/index.ts index 1631503f1..2a396c121 100644 --- a/packs/delivery/typescript/src/index.ts +++ b/packs/delivery/typescript/src/index.ts @@ -20,22 +20,32 @@ import { } from "@metaobjectsdev/metadata"; import { SYSTEMS_PROVIDER_ID, TYPE_APP, TYPE_RESOURCE, checkRefs, packTypeMaps, refList, resolveSystemRef } from "@metaobjectsdev/pack-systems"; import definition from "../../metamodel/delivery.json" with { type: "json" }; +import { readProcesses } from "./readers.js"; import { + APP_OUTPUTS, DELIVERY_PROVIDER_ID, DEPLOYMENT_ATTR_APP, DEPLOYMENT_ATTR_ENVIRONMENT, ERR_DELIVERY_DUPLICATE_DEPLOYMENT, ERR_DELIVERY_DUPLICATE_SETTING, ERR_DELIVERY_UNRESOLVED_REF, + ERR_DELIVERY_UNSUPPORTED_OUTPUT, + PORT_OUTPUTS, TYPE_BUILD, TYPE_DEPLOYMENT, TYPE_ENVIRONMENT, TYPE_VALUE, + URL_OUTPUTS, + VALUE_ATTR_OUTPUT, + VALUE_ATTR_PATH, VALUE_ATTR_PRODUCED_BY, VALUE_ATTR_SETTING, + VALUE_SUBTYPE_REF, + type ValueOutput, } from "./constants.js"; export * from "./constants.js"; +export { readBuild, readProcesses, type Build, type Process } from "./readers.js"; export const DELIVERY_DEFINITION = definition as ProviderDefinition; @@ -131,8 +141,29 @@ const validateValue: NodeValidator = (node, ctx) => { } } checkRefs(node, VALUE_ATTR_PRODUCED_BY, [TYPE_RESOURCE, TYPE_APP], ERR_DELIVERY_UNRESOLVED_REF, ctx); + if (node.subType === VALUE_SUBTYPE_REF) checkOutput(node, ctx); }; +// What a value.ref may ask for, whatever the platform: `@path` extends only a URL, and an app +// produces only its addresses, the port-bearing ones only when a process declares a port. A +// platform generator maps what passes to its own references; a resource's outputs depend on +// its engine, which only the platform knows. +function checkOutput(node: MetaData, ctx: ValidationContext): void { + const output = node.attr(VALUE_ATTR_OUTPUT) as ValueOutput; + const where = `${node.type}.${node.subType} "${node.name}"`; + if (node.attr(VALUE_ATTR_PATH) !== undefined && !URL_OUTPUTS.includes(output)) { + ctx.error(ERR_DELIVERY_UNSUPPORTED_OUTPUT, node, `${where} has @path, which extends a URL, and @output ${output} is not one (${URL_OUTPUTS.join(", ")}).`); + } + const ref = refList(node, VALUE_ATTR_PRODUCED_BY)[0]; + const app = ref === undefined ? undefined : resolveSystemRef(node, ref, VALUE_ATTR_PRODUCED_BY, [TYPE_APP]); + if (app?.type !== TYPE_APP) return; // a resource's outputs depend on its engine + if (!APP_OUTPUTS.includes(output)) { + ctx.error(ERR_DELIVERY_UNSUPPORTED_OUTPUT, node, `${where} asks app "${app.name}" for its ${output}; an app produces ${APP_OUTPUTS.join(", ")}.`); + } else if (PORT_OUTPUTS.includes(output) && !readProcesses(app).some((p) => p.port !== undefined)) { + ctx.error(ERR_DELIVERY_UNSUPPORTED_OUTPUT, node, `${where} asks app "${app.name}" for its ${output}, and it declares no runtime.process @port.`); + } +} + export const provider: MetaDataTypeProvider = { id: DELIVERY_PROVIDER_ID, dependencies: ["metaobjects-core-types", SYSTEMS_PROVIDER_ID], diff --git a/packs/delivery/typescript/src/readers.ts b/packs/delivery/typescript/src/readers.ts new file mode 100644 index 000000000..a3712cc14 --- /dev/null +++ b/packs/delivery/typescript/src/readers.ts @@ -0,0 +1,99 @@ +// An app's delivery facts as plain records: its build and its processes, the same in every +// environment. A platform pack's generator reads them through here rather than decoding the +// attributes itself, so a new build.* or runtime.process attribute is read in one place. +// Accessors are the resolving ones (ADR-0039): a build or process an app inherits through +// `extends` counts. + +import type { MetaData } from "@metaobjectsdev/metadata"; +import { refList } from "@metaobjectsdev/pack-systems"; +import { + BUILD_ATTR_COMMAND, + BUILD_ATTR_CONTEXT, + BUILD_ATTR_DIRECTORY, + BUILD_ATTR_PATH, + BUILD_ATTR_WATCH_EXCLUDE, + BUILD_ATTR_WATCH_INCLUDE, + RUNTIME_ATTR_COMMAND, + RUNTIME_ATTR_DRAIN_SECONDS, + RUNTIME_ATTR_HEALTH_PATH, + RUNTIME_ATTR_HEALTH_TIMEOUT_SECONDS, + RUNTIME_ATTR_PORT, + RUNTIME_ATTR_RESTART, + TYPE_BUILD, + TYPE_RUNTIME, +} from "./constants.js"; + +export interface Build { + /** The build subtype: dockerfile, command or static. */ + readonly kind: string; + readonly watchInclude: readonly string[]; + readonly watchExclude: readonly string[]; + readonly path?: string; + readonly context?: string; + readonly command?: string; + readonly directory?: string; +} + +export interface Process { + readonly name: string; + readonly command?: string; + readonly port?: number; + readonly healthPath?: string; + readonly healthTimeoutSeconds?: number; + readonly drainSeconds?: number; + /** always, onFailure or never. */ + readonly restart?: string; +} + +function text(v: unknown): string | undefined { + return typeof v === "string" && v !== "" ? v : undefined; +} + +function int(v: unknown): number | undefined { + return typeof v === "number" && Number.isInteger(v) ? v : undefined; +} + +/** `T` with each field that may be undefined made optional instead. */ +type Defined = { [K in keyof T as undefined extends T[K] ? never : K]: T[K] } & { + [K in keyof T as undefined extends T[K] ? K : never]?: Exclude; +}; + +/** The fields of `values` that are set: an absent fact stays absent, not `undefined`. */ +function defined(values: T): Defined { + return Object.fromEntries(Object.entries(values).filter(([, v]) => v !== undefined)) as Defined; +} + +/** The app's build, or undefined when it declares none. */ +export function readBuild(app: MetaData): Build | undefined { + // ADR-0039: resolving, so a build the app inherits through `extends` counts. + const b = app.children().find((c) => c.type === TYPE_BUILD); + if (b === undefined) return undefined; + return defined({ + kind: b.subType, + watchInclude: refList(b, BUILD_ATTR_WATCH_INCLUDE), + watchExclude: refList(b, BUILD_ATTR_WATCH_EXCLUDE), + path: text(b.attr(BUILD_ATTR_PATH)), + context: text(b.attr(BUILD_ATTR_CONTEXT)), + command: text(b.attr(BUILD_ATTR_COMMAND)), + directory: text(b.attr(BUILD_ATTR_DIRECTORY)), + }); +} + +/** The app's processes, in model order. */ +export function readProcesses(app: MetaData): Process[] { + // ADR-0039: resolving, as for the build. + return app + .children() + .filter((c) => c.type === TYPE_RUNTIME) + .map((p) => + defined({ + name: p.name, + command: text(p.attr(RUNTIME_ATTR_COMMAND)), + port: int(p.attr(RUNTIME_ATTR_PORT)), + healthPath: text(p.attr(RUNTIME_ATTR_HEALTH_PATH)), + healthTimeoutSeconds: int(p.attr(RUNTIME_ATTR_HEALTH_TIMEOUT_SECONDS)), + drainSeconds: int(p.attr(RUNTIME_ATTR_DRAIN_SECONDS)), + restart: text(p.attr(RUNTIME_ATTR_RESTART)), + }), + ); +} diff --git a/packs/railway/CHANGELOG.md b/packs/railway/CHANGELOG.md index 51057d822..84eb62a60 100644 --- a/packs/railway/CHANGELOG.md +++ b/packs/railway/CHANGELOG.md @@ -13,4 +13,6 @@ This pack's own changelog (ADR-0069). The root `CHANGELOG.md` records core only. file does not hold), `deploy/sync-secrets.sh` (vault to Railway through `keys-axi`), `deploy/deploy.sh`, `deploy/doctor.sh` and a deploy skill. The pack now requires the config pack, for settings and vaults. Fixtures `railway-emit-one-service` and `railway-emit-two-services`, - with golden output. TypeScript port. + with golden output, and a coverage test that holds the generated file to every fact of the + hand-written configuration the fixtures are modelled on. The generated file type-checks against + the SDK and names, beside each service and variable, the model node it comes from. TypeScript port. diff --git a/packs/railway/README.md b/packs/railway/README.md index 60f465536..3c4b45ae1 100644 --- a/packs/railway/README.md +++ b/packs/railway/README.md @@ -53,8 +53,9 @@ service's name when the project has one service, else the project's name. | `value.ref` of another app | `host` `${{svc.RAILWAY_PRIVATE_DOMAIN}}`, `port` its `@port`, `privateUrl` `http://${{svc.RAILWAY_PRIVATE_DOMAIN}}:port`, `publicUrl` `https://${{svc.RAILWAY_PUBLIC_DOMAIN}}`, with `@path` appended | Variables: when no deployment in the project declares a `value.*` node, the file says -`variables: { managed: false }` and an apply changes no variable (the CLI reads it; the railway -3.17.0 SDK's types do not declare it, so a type-check of the file with them reports that line). +`variables: { managed: false }` and an apply changes no variable. The CLI reads that key and the +railway 3.17.0 SDK's types do not declare it yet, so the file spreads it from a constant +(`...unmanagedVariables`): the file type-checks against the SDK, where an object literal would not. When one does, the file manages every variable of its services: each setting of the app's `@settings` groups is declared, a secret as `preserve()` (the sync script sets it), a non-secret with no value as its `@default` or `preserve()`. An apply deletes a variable a managed file does not @@ -112,6 +113,19 @@ export default defineConfig({ Names, domains, repositories and project names are placeholders. +The two emit fixtures are modelled on two adopters' hand-written Railway configuration (a +hand-migrated `.railway/railway.ts`, and two `railway.json` files). The bar is coverage, not +identity: `typescript/test/coverage.test.ts` evaluates the generated file and checks that every +fact of that configuration is in it, fact by fact (source, watch patterns, Dockerfile path, health +check, restart policy, draining, variable policy). Where the generated file goes further: + +- it type-checks against the railway SDK; +- each service carries a comment naming the app and deployment it comes from, and each variable + the node it comes from; +- secrets are never written: they are `preserve()` and the sync script copies them from the vault; +- the facts the format cannot hold are listed in `deploy/unexpressed.md` instead of dropped; +- domains, the health path and every reference to another service come from the model. + ## Ports TypeScript only. diff --git a/packs/railway/fixtures/conformance/error-value-ref-unsupported-output/expected-errors.json b/packs/railway/fixtures/conformance/error-value-ref-unsupported-output/expected-errors.json new file mode 100644 index 000000000..824aa8aa8 --- /dev/null +++ b/packs/railway/fixtures/conformance/error-value-ref-unsupported-output/expected-errors.json @@ -0,0 +1,35 @@ +{ + "errors": [ + { + "code": "ERR_DELIVERY_UNSUPPORTED_OUTPUT", + "source": { + "format": "json", + "files": [ + "meta.shop.json" + ], + "jsonPath": "$['metadata.root'].children[2]['deployment.railway'].children[0]['value.ref']" + } + }, + { + "code": "ERR_DELIVERY_UNSUPPORTED_OUTPUT", + "source": { + "format": "json", + "files": [ + "meta.shop.json" + ], + "jsonPath": "$['metadata.root'].children[2]['deployment.railway'].children[1]['value.ref']" + } + }, + { + "code": "ERR_DELIVERY_UNSUPPORTED_OUTPUT", + "source": { + "format": "json", + "files": [ + "meta.shop.json" + ], + "jsonPath": "$['metadata.root'].children[2]['deployment.railway'].children[2]['value.ref']" + } + } + ], + "warnings": [] +} diff --git a/packs/railway/fixtures/conformance/error-value-ref-unsupported-output/input/meta.shop.json b/packs/railway/fixtures/conformance/error-value-ref-unsupported-output/input/meta.shop.json new file mode 100644 index 000000000..92ebb9555 --- /dev/null +++ b/packs/railway/fixtures/conformance/error-value-ref-unsupported-output/input/meta.shop.json @@ -0,0 +1,25 @@ +{ + "metadata.root": { + "package": "acme::shop", + "children": [ + { "system.internal": { "name": "Shop", "children": [ + { "app.service": { "name": "web" } }, + { "app.service": { "name": "api", "children": [ { "runtime.process": { "name": "main" } } ] } }, + { "resource.database": { "name": "db", "@engine": "postgres" } } + ] } }, + { "environment.standing": { "name": "production" } }, + { "deployment.railway": { + "name": "web-production", + "@app": "Shop.web", + "@environment": "production", + "@project": "shop", + "children": [ + { "value.ref": { "name": "dbHost", "@setting": "Database.host", "@producedBy": "Shop.db", "@output": "host", "@path": "/x" } }, + { "value.ref": { "name": "apiUrl", "@setting": "Api.url", "@producedBy": "Shop.api", "@output": "url" } }, + { "value.ref": { "name": "apiPrivate", "@setting": "Api.privateUrl", "@producedBy": "Shop.api", "@output": "privateUrl" } }, + { "value.ref": { "name": "apiHost", "@setting": "Api.host", "@producedBy": "Shop.api", "@output": "host" } } + ] + } } + ] + } +} diff --git a/packs/railway/fixtures/conformance/error-value-ref-unsupported-output/providers.json b/packs/railway/fixtures/conformance/error-value-ref-unsupported-output/providers.json new file mode 100644 index 000000000..aac0d894b --- /dev/null +++ b/packs/railway/fixtures/conformance/error-value-ref-unsupported-output/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-documentation", "metaobjects-systems", "metaobjects-delivery", "metaobjects-railway"] diff --git a/packs/railway/typescript/src/constants.ts b/packs/railway/typescript/src/constants.ts index 11221d9b9..98d59e8ac 100644 --- a/packs/railway/typescript/src/constants.ts +++ b/packs/railway/typescript/src/constants.ts @@ -1,3 +1,5 @@ +import { RESTART_ALWAYS, RESTART_NEVER, RESTART_ON_FAILURE } from "@metaobjectsdev/pack-delivery"; + // The railway pack's vocabulary names and the Railway spellings it writes, one constant each // (metamodel/railway.json is the vocabulary's definition). @@ -20,9 +22,9 @@ export const PARTIAL_PATTERN = /^[A-Za-z0-9._-]{1,64}$/; /** `runtime.process @restart` → Railway's `deploy.restartPolicyType`. */ export const RESTART_POLICY: Readonly> = { - always: "ALWAYS", - onFailure: "ON_FAILURE", - never: "NEVER", + [RESTART_ALWAYS]: "ALWAYS", + [RESTART_ON_FAILURE]: "ON_FAILURE", + [RESTART_NEVER]: "NEVER", }; /** diff --git a/packs/railway/typescript/src/files.ts b/packs/railway/typescript/src/files.ts index 72ecba228..e08660581 100644 --- a/packs/railway/typescript/src/files.ts +++ b/packs/railway/typescript/src/files.ts @@ -7,17 +7,14 @@ * into `railway variable set --stdin`: no script prints one or puts one on a command line. */ import { RAILWAY_SDK_VERSION } from "./constants.js"; -import { isStatic, type RailwayDeployment, type RailwayProject } from "./model.js"; +import { BUILD_SUBTYPE_STATIC } from "@metaobjectsdev/pack-delivery"; +import type { RailwayDeployment, RailwayProject } from "./model.js"; /** A shell word: bare when it is safe, else single-quoted. */ function sh(s: string): string { return /^[A-Za-z0-9_./:@-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`; } -function secretsOf(d: RailwayDeployment): string[] { - return d.settings.filter((s) => s.secret).map((s) => s.envName); -} - function md(s: string): string { return `\`${s}\``; } @@ -39,9 +36,9 @@ export function unexpressedFacts(d: RailwayDeployment, manageVariables: boolean) how: "Railway builds from the repository root; the file has no build context. Set the service's root directory in Railway, or build from the root.", }); } - if (isStatic(b)) { + if (b?.kind === BUILD_SUBTYPE_STATIC && b.directory !== undefined) { out.push({ - fact: `Static directory ${md(b?.directory ?? "")} (build.static)`, + fact: `Static directory ${md(b.directory)} (build.static)`, how: "Railway has no setting that serves a directory of files. Serve it with a process (runtime.process @command), or deploy the app on a static host.", }); } @@ -64,7 +61,7 @@ export function unexpressedFacts(d: RailwayDeployment, manageVariables: boolean) how: "The file attaches the domains to the service; the DNS record each needs (the CNAME Railway shows for it) is set at the DNS provider. deploy/doctor.sh checks each answers on the health path.", }); } - const secrets = secretsOf(d); + const secrets = d.secrets; if (secrets.length > 0 && d.vault !== undefined) { out.push({ fact: `Secret values: ${secrets.map(md).join(", ")}`, @@ -149,11 +146,18 @@ export function renderSyncSecrets(project: RailwayProject, header: string): stri 'cd "$(dirname "$0")/.."', "", 'ENVIRONMENT="${1:-}"', - 'DRY_RUN=0; [ "${2:-}" = "--dry-run" ] && DRY_RUN=1', + "DRY_RUN=0", + 'for arg in "${@:2}"; do', + ' case "$arg" in', + " --dry-run) DRY_RUN=1 ;;", + ` *) echo ${sh(`usage: ${SYNC_USAGE}`)} >&2; exit 2 ;;`, + " esac", + "done", "", "# copy ", "copy() {", ' if [ "$DRY_RUN" = 1 ]; then echo "would copy $5 from $1/$2 to service $3 ($4)"; return; fi', + " # shellcheck disable=SC2016 # the inner shell expands it: the value never enters this one", ` keys-axi run --project "$1" --env "$2" --only "$5" -- bash -c '`, ` [ -n "\${!1+set}" ] || { echo "sync-secrets: $1 is not in the vault scope" >&2; exit 1; }`, ` printf %s "\${!1}" | railway variable set "$1" --stdin --service "$2" --environment "$3" --skip-deploys >/dev/null`, @@ -166,7 +170,7 @@ export function renderSyncSecrets(project: RailwayProject, header: string): stri (ds, env) => { const body: string[] = []; for (const d of ds) { - const secrets = secretsOf(d); + const secrets = d.secrets; if (secrets.length === 0 || d.vault === undefined) continue; for (const s of secrets) body.push(`copy ${sh(d.vault.scope.project)} ${sh(d.vault.scope.env)} ${sh(d.service)} ${sh(env)} ${s}`); } @@ -245,20 +249,24 @@ export function renderDoctor(project: RailwayProject, header: string): string { " esac", "}", "", - "# answers ", - "answers() {", - ' if curl -fsS -o /dev/null --max-time 10 "$1"; then ok "$1 answers"; else bad "$1 does not answer 2xx"; fi', - "}", - "", + // Only when some domain is checked: shellcheck flags a function nothing calls. + ...(project.deployments.some((d) => healthUrls(d).length > 0) + ? [ + "# answers ", + "answers() {", + ' if curl -fsS -o /dev/null --max-time 10 "$1"; then ok "$1 answers"; else bad "$1 does not answer 2xx"; fi', + "}", + "", + ] + : []), ...caseBlock( project, (ds, env) => { const body: string[] = []; for (const d of ds) { - const secrets = secretsOf(d); - if (secrets.length > 0 && d.vault !== undefined) { - body.push(`in_vault ${sh(d.vault.scope.project)} ${sh(d.vault.scope.env)} ${secrets.join(" ")}`); - body.push(`on_railway ${sh(d.service)} ${sh(env)} ${secrets.join(" ")}`); + if (d.secrets.length > 0 && d.vault !== undefined) { + body.push(`in_vault ${sh(d.vault.scope.project)} ${sh(d.vault.scope.env)} ${d.secrets.join(" ")}`); + body.push(`on_railway ${sh(d.service)} ${sh(env)} ${d.secrets.join(" ")}`); } } body.push(`plan_clean ${sh(env)}`); @@ -299,10 +307,10 @@ export function renderDeploy(project: RailwayProject, header: string): string { 'cd "$(dirname "$0")/.."', "", 'ENVIRONMENT="${1:-}"', - "YES=(); REDEPLOY=0", + 'YES=""; REDEPLOY=0', 'for arg in "${@:2}"; do', ' case "$arg" in', - " --yes) YES=(--yes) ;;", + " --yes) YES=--yes ;;", " --redeploy) REDEPLOY=1 ;;", ` *) echo ${sh(`usage: ${DEPLOY_USAGE}`)} >&2; exit 2 ;;`, " esac", @@ -325,7 +333,8 @@ export function renderDeploy(project: RailwayProject, header: string): string { ' railway environment "$1" >/dev/null', " ensure_sdk", " railway config plan", - ' railway config apply "${YES[@]}"', + " # shellcheck disable=SC2086 # YES is empty or one word", + " railway config apply $YES", "}", "", ...caseBlock( @@ -351,7 +360,7 @@ export function renderDeploy(project: RailwayProject, header: string): string { export function renderDeploySkill(project: RailwayProject, header: string): string { const services = [...new Set(project.deployments.map((d) => d.service))]; const rows = project.deployments.map((d) => { - const secrets = secretsOf(d); + const secrets = d.secrets; const vault = d.vault === undefined ? "none" : md(`${d.vault.scope.project}/${d.vault.scope.env}`); return `| ${md(d.environment)} | ${md(d.service)} | ${d.branch === undefined ? "none" : md(d.branch)} | ${d.domains.length === 0 ? "none" : d.domains.map(md).join(", ")} | ${vault} (${secrets.length} secret${secrets.length === 1 ? "" : "s"}) |`; }); diff --git a/packs/railway/typescript/src/generators.ts b/packs/railway/typescript/src/generators.ts index c0c056bc6..a84910113 100644 --- a/packs/railway/typescript/src/generators.ts +++ b/packs/railway/typescript/src/generators.ts @@ -16,6 +16,7 @@ * nothing to Railway gets no files. */ import { GENERATED_EDIT_NOTE, type EmittedFile, type Generator, type GenContext } from "@metaobjectsdev/codegen-ts"; +import type { ConfigGeneratorOptions } from "@metaobjectsdev/pack-config"; import { PATH_DEPLOY, PATH_DEPLOY_SKILL, @@ -25,41 +26,41 @@ import { PATH_UNEXPRESSED, } from "./constants.js"; import { renderDeploy, renderDeploySkill, renderDoctor, renderSyncSecrets, renderUnexpressed } from "./files.js"; -import { pickProject, readRailway, type RailwayProject, type ReadRailwayOptions } from "./model.js"; +import { RailwayModelError, pickProject, readRailway, type RailwayProject, type ReadRailwayOptions } from "./model.js"; import { renderRailwayTs } from "./railway-ts.js"; const PACKAGE = "@metaobjectsdev/pack-railway"; -export interface RailwayGeneratorOptions extends ReadRailwayOptions { - /** The output path, relative to the target. */ - readonly path?: string; - /** The named output target (`targets` in metaobjects.config.ts). Default: `"default"`. */ - readonly target?: string; -} +export interface RailwayGeneratorOptions extends ConfigGeneratorOptions, ReadRailwayOptions {} export function header(generator: string, comment: string): string { return `${comment} @generated by ${PACKAGE} (${generator}) — ${GENERATED_EDIT_NOTE}`; } -/** The model read once per run and per options (a run shares one `entities` array). */ -const cache = new WeakMap>(); +/** The header as an HTML comment, for a Markdown file. */ +function htmlHeader(generator: string): string { + return ``; +} + +/** The model read once per run and per options, a refusal included (a run shares one `entities` array). */ +const cache = new WeakMap>(); -function projectFor(ctx: GenContext, opts: ReadRailwayOptions): RailwayProject | undefined { - const k = JSON.stringify([opts.project ?? null, opts.partial ?? null]); - let perRun = cache.get(ctx.entities); - if (perRun === undefined) { - perRun = new Map(); - cache.set(ctx.entities, perRun); - } +function projectFor(ctx: GenContext, { project, partial }: ReadRailwayOptions): RailwayProject | undefined { + const k = JSON.stringify([project ?? null, partial ?? null]); + const perRun = cache.get(ctx.entities) ?? new Map(); + cache.set(ctx.entities, perRun); if (!perRun.has(k)) { - const read: ReadRailwayOptions = { - ...(opts.project !== undefined ? { project: opts.project } : {}), - ...(opts.partial !== undefined ? { partial: opts.partial } : {}), - }; - const projects = readRailway(ctx.loadedRoot, ctx.entities.filter(ctx.matches), (key) => ctx.select?.(key) ?? true, read); - perRun.set(k, pickProject(projects)); + const read = { ...(project !== undefined ? { project } : {}), ...(partial !== undefined ? { partial } : {}) }; + try { + perRun.set(k, pickProject(readRailway(ctx.loadedRoot, ctx.entities.filter(ctx.matches), (key) => ctx.select?.(key) ?? true, read))); + } catch (e) { + if (!(e instanceof RailwayModelError)) throw e; + perRun.set(k, e); + } } - return perRun.get(k); + const got = perRun.get(k); + if (got instanceof RailwayModelError) throw got; + return got; } function generator( @@ -83,7 +84,7 @@ export function railwayTsFile(opts: RailwayGeneratorOptions = {}): Generator { } export function railwayUnexpressedFile(opts: RailwayGeneratorOptions = {}): Generator { - return generator("railway-unexpressed", PATH_UNEXPRESSED, opts, (p) => renderUnexpressed(p, header("railway-unexpressed", ""))); + return generator("railway-unexpressed", PATH_UNEXPRESSED, opts, (p) => renderUnexpressed(p, htmlHeader("railway-unexpressed"))); } export function railwaySyncSecretsScript(opts: RailwayGeneratorOptions = {}): Generator { @@ -99,7 +100,7 @@ export function railwayDoctorScript(opts: RailwayGeneratorOptions = {}): Generat } export function railwayDeploySkill(opts: RailwayGeneratorOptions = {}): Generator { - return generator("railway-deploy-skill", PATH_DEPLOY_SKILL, opts, (p) => renderDeploySkill(p, header("railway-deploy-skill", ""))); + return generator("railway-deploy-skill", PATH_DEPLOY_SKILL, opts, (p) => renderDeploySkill(p, htmlHeader("railway-deploy-skill"))); } /** All six generators with the same options (`path` is ignored: each keeps its own). */ diff --git a/packs/railway/typescript/src/model.ts b/packs/railway/typescript/src/model.ts index 714e8c295..49fef476f 100644 --- a/packs/railway/typescript/src/model.ts +++ b/packs/railway/typescript/src/model.ts @@ -23,13 +23,6 @@ import { type VaultScope, } from "@metaobjectsdev/pack-config"; import { - BUILD_ATTR_COMMAND, - BUILD_ATTR_CONTEXT, - BUILD_ATTR_DIRECTORY, - BUILD_ATTR_PATH, - BUILD_ATTR_WATCH_EXCLUDE, - BUILD_ATTR_WATCH_INCLUDE, - BUILD_SUBTYPE_STATIC, DEPLOYMENT_ATTR_APP, DEPLOYMENT_ATTR_BRANCH, DEPLOYMENT_ATTR_DOMAINS, @@ -37,16 +30,11 @@ import { DEPLOYMENT_ATTR_REGION, DEPLOYMENT_ATTR_REPLICAS, DEPLOYMENT_ATTR_SECRETS, - RUNTIME_ATTR_COMMAND, - RUNTIME_ATTR_DRAIN_SECONDS, - RUNTIME_ATTR_HEALTH_PATH, - RUNTIME_ATTR_HEALTH_TIMEOUT_SECONDS, - RUNTIME_ATTR_PORT, - RUNTIME_ATTR_RESTART, - TYPE_BUILD, + OUTPUT_HOST, + OUTPUT_PORT, + OUTPUT_PUBLIC_URL, TYPE_DEPLOYMENT, TYPE_ENVIRONMENT, - TYPE_RUNTIME, TYPE_VALUE, VALUE_ATTR_LITERAL, VALUE_ATTR_OUTPUT, @@ -54,11 +42,16 @@ import { VALUE_ATTR_PRODUCED_BY, VALUE_ATTR_SETTING, VALUE_SUBTYPE_LITERAL, + readBuild, + readProcesses, + type Build, + type Process, } from "@metaobjectsdev/pack-delivery"; import { APP_ATTR_NEEDS, APP_ATTR_SCHEDULE, APP_ATTR_SETTINGS, + MANAGED_BY_EXTERNAL, RESOURCE_ATTR_ENGINE, RESOURCE_ATTR_MANAGED_BY, RESOURCE_ATTR_VERSION, @@ -88,27 +81,9 @@ export class RailwayModelError extends Error { } } -export interface RailwayBuild { - /** The build subtype: dockerfile, command or static. */ - readonly kind: string; - readonly watchInclude: readonly string[]; - readonly watchExclude: readonly string[]; - readonly path?: string; - readonly context?: string; - readonly command?: string; - readonly directory?: string; -} - -export interface RailwayProcess { - readonly name: string; - readonly command?: string; - readonly port?: number; - readonly healthPath?: string; - readonly healthTimeoutSeconds?: number; - readonly drainSeconds?: number; - /** The model's restart value: always, onFailure or never. */ - readonly restart?: string; -} +/** An app's build and processes, as the delivery pack reads them. */ +export type RailwayBuild = Build; +export type RailwayProcess = Process; /** One variable a managed file declares on a service. */ export interface RailwayVariable { @@ -130,13 +105,10 @@ export interface RailwayResource { export interface RailwayDeployment { readonly key: string; - readonly name: string; readonly environment: string; readonly project: string; readonly service: string; readonly appKey: string; - /** The app subtype: service, client or job. */ - readonly appKind: string; readonly schedule?: string; readonly repo?: string; readonly image?: string; @@ -149,10 +121,12 @@ export interface RailwayDeployment { readonly processes: readonly RailwayProcess[]; /** Whether the deployment declares value.* nodes (the file then manages variables). */ readonly hasValues: boolean; - /** The variables a managed file declares, in name order. Empty for an unmanaged file. */ + /** The variables a managed file declares, in name order: the values, then every other setting. Written only when the project's file manages variables. */ readonly variables: readonly RailwayVariable[]; /** Every setting of the settings groups the app reads. */ readonly settings: readonly Setting[]; + /** The environment variables of the secret settings, in model order. */ + readonly secrets: readonly string[]; /** Where the secret settings are read from at deploy. Absent when the app reads none. */ readonly vault?: { readonly key: string; readonly scope: VaultScope }; readonly resources: readonly RailwayResource[]; @@ -186,57 +160,10 @@ function int(v: unknown): number | undefined { return typeof v === "number" && Number.isInteger(v) ? v : undefined; } -function strings(node: MetaData, attr: string): string[] { - return refList(node, attr); -} - export function isRailwayDeployment(node: MetaData): boolean { return node.type === TYPE_DEPLOYMENT && node.subType === DEPLOYMENT_SUBTYPE_RAILWAY; } -function readBuild(app: MetaData): RailwayBuild | undefined { - // ADR-0039: resolving, so a build an app inherits through `extends` counts. - const b = app.children().find((c) => c.type === TYPE_BUILD); - if (b === undefined) return undefined; - const path = text(b.attr(BUILD_ATTR_PATH)); - const context = text(b.attr(BUILD_ATTR_CONTEXT)); - const command = text(b.attr(BUILD_ATTR_COMMAND)); - const directory = text(b.attr(BUILD_ATTR_DIRECTORY)); - return { - kind: b.subType, - watchInclude: strings(b, BUILD_ATTR_WATCH_INCLUDE), - watchExclude: strings(b, BUILD_ATTR_WATCH_EXCLUDE), - ...(path !== undefined ? { path } : {}), - ...(context !== undefined ? { context } : {}), - ...(command !== undefined ? { command } : {}), - ...(directory !== undefined ? { directory } : {}), - }; -} - -function readProcesses(app: MetaData): RailwayProcess[] { - // ADR-0039: resolving, as for the build. - return app - .children() - .filter((c) => c.type === TYPE_RUNTIME) - .map((p) => { - const command = text(p.attr(RUNTIME_ATTR_COMMAND)); - const port = int(p.attr(RUNTIME_ATTR_PORT)); - const healthPath = text(p.attr(RUNTIME_ATTR_HEALTH_PATH)); - const healthTimeoutSeconds = int(p.attr(RUNTIME_ATTR_HEALTH_TIMEOUT_SECONDS)); - const drainSeconds = int(p.attr(RUNTIME_ATTR_DRAIN_SECONDS)); - const restart = text(p.attr(RUNTIME_ATTR_RESTART)); - return { - name: p.name, - ...(command !== undefined ? { command } : {}), - ...(port !== undefined ? { port } : {}), - ...(healthPath !== undefined ? { healthPath } : {}), - ...(healthTimeoutSeconds !== undefined ? { healthTimeoutSeconds } : {}), - ...(drainSeconds !== undefined ? { drainSeconds } : {}), - ...(restart !== undefined ? { restart } : {}), - }; - }); -} - /** The settings groups `names` (each a group's name or resolution key) name, reporting each that matches none or several. */ function groupsNamed(names: readonly string[], groups: readonly SettingsGroup[], where: string, problems: string[]): SettingsGroup[] { const out: SettingsGroup[] = []; @@ -264,15 +191,15 @@ function settingNamed(ref: string, groups: readonly SettingsGroup[]): Setting | } interface Context { - readonly root: MetaRoot; readonly all: readonly MetaData[]; readonly groups: readonly SettingsGroup[]; readonly vaults: readonly Vault[]; } -/** The service name the deployment of `app` in `env` runs as, or undefined when Railway runs it nowhere there. */ -function serviceOf(app: MetaData, env: MetaData, all: readonly MetaData[]): string | undefined { +/** The service name the deployment of `app` in `env` runs as in Railway project `project` (a reference does not cross projects), or undefined. */ +function serviceOf(app: MetaData, env: MetaData, project: string, all: readonly MetaData[]): string | undefined { for (const d of all) { + if ((text(d.attr(RAILWAY_ATTR_PROJECT)) ?? "") !== project) continue; const a = refList(d, DEPLOYMENT_ATTR_APP)[0]; const e = refList(d, DEPLOYMENT_ATTR_ENVIRONMENT)[0]; if (a === undefined || e === undefined) continue; @@ -283,27 +210,19 @@ function serviceOf(app: MetaData, env: MetaData, all: readonly MetaData[]): stri return undefined; } -const URL_OUTPUTS: readonly string[] = ["url", "privateUrl", "publicUrl"]; - /** A value.ref as the reference template Railway resolves at deploy, its `@path` appended (`${{db.DATABASE_URL}}`), or a problem. */ -function referenceTemplate(value: MetaData, env: MetaData, ctx: Context, where: string, problems: string[]): string | undefined { - const path = text(value.attr(VALUE_ATTR_PATH)); - const output = text(value.attr(VALUE_ATTR_OUTPUT)) ?? ""; - if (path !== undefined && !URL_OUTPUTS.includes(output)) { - problems.push(`${where}: @${VALUE_ATTR_PATH} is appended to a URL, and @${VALUE_ATTR_OUTPUT} ${output} is not one (${URL_OUTPUTS.join(", ")})`); - return undefined; - } - const base = outputTemplate(value, env, ctx, where, problems); - return base === undefined ? undefined : `${base}${path ?? ""}`; +function referenceTemplate(value: MetaData, env: MetaData, project: string, ctx: Context, where: string, problems: string[]): string | undefined { + const base = outputTemplate(value, env, project, ctx, where, problems); + return base === undefined ? undefined : `${base}${text(value.attr(VALUE_ATTR_PATH)) ?? ""}`; } -function outputTemplate(value: MetaData, env: MetaData, ctx: Context, where: string, problems: string[]): string | undefined { +function outputTemplate(value: MetaData, env: MetaData, project: string, ctx: Context, where: string, problems: string[]): string | undefined { const producedBy = text(value.attr(VALUE_ATTR_PRODUCED_BY)) ?? ""; const output = text(value.attr(VALUE_ATTR_OUTPUT)) ?? ""; const target = resolveSystemRef(value, producedBy, VALUE_ATTR_PRODUCED_BY, [TYPE_RESOURCE, TYPE_APP]); if (target === undefined) return undefined; // the delivery pack reports it at load if (target.type === TYPE_RESOURCE) { - if (text(target.attr(RESOURCE_ATTR_MANAGED_BY)) === "external") { + if (text(target.attr(RESOURCE_ATTR_MANAGED_BY)) === MANAGED_BY_EXTERNAL) { problems.push(`${where}: @${VALUE_ATTR_PRODUCED_BY} "${producedBy}" is managed outside Railway, which cannot supply its ${output}; give the setting its value from the vault (@secret) or a value.literal`); return undefined; } @@ -320,27 +239,23 @@ function outputTemplate(value: MetaData, env: MetaData, ctx: Context, where: str } return `\${{${target.name}.${variable}}}`; } - const service = serviceOf(target, env, ctx.all); + const service = serviceOf(target, env, project, ctx.all); if (service === undefined) { - problems.push(`${where}: app "${target.name}" has no deployment.railway in environment ${env.name}, so Railway has no address for it there`); + problems.push(`${where}: app "${target.name}" has no deployment.railway in environment ${env.name} in Railway project ${project}, so Railway has no address for it there (a reference does not cross projects)`); return undefined; } + // The delivery pack refuses, at load, an output an app does not produce and a port-bearing + // one from an app with no @port; what is left maps onto Railway's domain variables. const port = readProcesses(target).find((p) => p.port !== undefined)?.port; switch (output) { - case "host": + case OUTPUT_HOST: return `\${{${service}.${RAILWAY_PRIVATE_DOMAIN}}}`; - case "publicUrl": + case OUTPUT_PUBLIC_URL: return `https://\${{${service}.${RAILWAY_PUBLIC_DOMAIN}}}`; - case "port": - case "privateUrl": - if (port === undefined) { - problems.push(`${where}: app "${target.name}" declares no runtime.process @port, so its ${output} is unknown`); - return undefined; - } - return output === "port" ? String(port) : `http://\${{${service}.${RAILWAY_PRIVATE_DOMAIN}}}:${port}`; + case OUTPUT_PORT: + return String(port); default: - problems.push(`${where}: an app supplies host, port, privateUrl or publicUrl, not ${output}`); - return undefined; + return `http://\${{${service}.${RAILWAY_PRIVATE_DOMAIN}}}:${port}`; } } @@ -366,6 +281,9 @@ function readDeployment(node: MetaData, ctx: Context, problems: string[]): Railw // ADR-0039: resolving, so a value an estate overlay adds counts. const valueNodes = node.children().filter((c) => c.type === TYPE_VALUE); const variables = new Map(); + const put = (name: string, kind: RailwayVariable["kind"], from: string, value?: string): void => { + variables.set(name, { name, kind, from, ...(value !== undefined ? { value } : {}) }); + }; for (const v of valueNodes) { const vWhere = `${where} value.${v.subType} ${v.name}`; const settingRef = text(v.attr(VALUE_ATTR_SETTING)) ?? ""; @@ -382,20 +300,20 @@ function readDeployment(node: MetaData, ctx: Context, problems: string[]): Railw continue; } const value = - v.subType === VALUE_SUBTYPE_LITERAL ? text(v.attr(VALUE_ATTR_LITERAL)) ?? "" : referenceTemplate(v, env, ctx, vWhere, problems); - if (value !== undefined) variables.set(setting.envName, { name: setting.envName, kind: "literal", value, from: `value.${v.subType} ${v.name}` }); + v.subType === VALUE_SUBTYPE_LITERAL ? text(v.attr(VALUE_ATTR_LITERAL)) ?? "" : referenceTemplate(v, env, text(node.attr(RAILWAY_ATTR_PROJECT)) ?? "", ctx, vWhere, problems); + if (value !== undefined) put(setting.envName, "literal", `value.${v.subType} ${v.name}`, value); } - if (valueNodes.length > 0) { - for (const s of settings) { - if (variables.has(s.envName)) continue; - if (s.secret) variables.set(s.envName, { name: s.envName, kind: "preserve", from: `${s.setting}, secret: copied from the vault by the sync script` }); - else if (s.default !== undefined) variables.set(s.envName, { name: s.envName, kind: "literal", value: s.default, from: `${s.setting} default` }); - else variables.set(s.envName, { name: s.envName, kind: "preserve", from: `${s.setting}, no value in the model: kept as set on Railway` }); - } + // Every setting, whether or not this deployment has values: when any deployment of the + // project has one, the file manages the variables of all of its services. + for (const s of settings) { + if (variables.has(s.envName)) continue; + if (s.secret) put(s.envName, "preserve", `${s.setting}, secret: copied from the vault by the sync script`); + else if (s.default !== undefined) put(s.envName, "literal", `${s.setting} default`, s.default); + else put(s.envName, "preserve", `${s.setting}, no value in the model: kept as set on Railway`); } let vault: RailwayDeployment["vault"]; - const secrets = settings.filter((s) => s.secret); + const secrets = settings.filter((s) => s.secret).map((s) => s.envName); const vaultRef = text(node.attr(DEPLOYMENT_ATTR_SECRETS)); if (vaultRef !== undefined) { const v = ctx.vaults.find((x) => x.name === vaultRef || x.key === vaultRef); @@ -405,13 +323,13 @@ function readDeployment(node: MetaData, ctx: Context, problems: string[]): Railw else if (scope === undefined) problems.push(`${where}: vault ${v.key} has no scope.env named "${env.name}", so the environment's secrets have no place`); else vault = { key: v.key, scope }; } else if (secrets.length > 0) { - problems.push(`${where}: ${app.name} reads ${secrets.length} secret setting(s) (${secrets.map((s) => s.envName).join(", ")}) and the deployment names no vault; set @${DEPLOYMENT_ATTR_SECRETS}`); + problems.push(`${where}: ${app.name} reads ${secrets.length} secret setting(s) (${secrets.join(", ")}) and the deployment names no vault; set @${DEPLOYMENT_ATTR_SECRETS}`); } const resources: RailwayResource[] = []; for (const ref of refList(app, APP_ATTR_NEEDS)) { const r = resolveSystemRef(app, ref, APP_ATTR_NEEDS, [TYPE_RESOURCE]); - if (r === undefined || text(r.attr(RESOURCE_ATTR_MANAGED_BY)) === "external") continue; + if (r === undefined || text(r.attr(RESOURCE_ATTR_MANAGED_BY)) === MANAGED_BY_EXTERNAL) continue; const engine = text(r.attr(RESOURCE_ATTR_ENGINE)); const version = text(r.attr(RESOURCE_ATTR_VERSION)); resources.push({ name: r.name, kind: `${r.type}.${r.subType}`, ...(engine !== undefined ? { engine } : {}), ...(version !== undefined ? { version } : {}) }); @@ -425,18 +343,16 @@ function readDeployment(node: MetaData, ctx: Context, problems: string[]): Railw const region = text(node.attr(DEPLOYMENT_ATTR_REGION)); return { key: node.resolutionKey(), - name: node.name, environment: env.name, project: text(node.attr(RAILWAY_ATTR_PROJECT)) ?? "", service: text(node.attr(RAILWAY_ATTR_SERVICE)) ?? app.name, - appKey: `${app.type}.${app.subType} ${app.name}`, - appKind: app.subType, + appKey: `${app.type}.${app.subType} ${app.parent === undefined ? app.resolutionKey() : `${app.parent.resolutionKey()}.${app.name}`}`, ...(schedule !== undefined ? { schedule } : {}), ...(repo !== undefined ? { repo } : {}), ...(image !== undefined ? { image } : {}), ...(branch !== undefined ? { branch } : {}), ...(typeof checkSuites === "boolean" ? { checkSuites } : {}), - domains: strings(node, DEPLOYMENT_ATTR_DOMAINS), + domains: refList(node, DEPLOYMENT_ATTR_DOMAINS), ...(replicas !== undefined ? { replicas } : {}), ...(region !== undefined ? { region } : {}), ...(build !== undefined ? { build } : {}), @@ -444,6 +360,7 @@ function readDeployment(node: MetaData, ctx: Context, problems: string[]): Railw hasValues: valueNodes.length > 0, variables: [...variables.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)), settings, + secrets, ...(vault !== undefined ? { vault } : {}), resources, }; @@ -474,14 +391,17 @@ export function readRailway( const problems: string[] = []; const groups = configRead(() => readSettings(objects), problems, []); const vaults = configRead(() => readVaults(root, inScope), problems, []); + // A settings or vault problem makes every deployment that reads them look wrong too: report it alone. + if (problems.length > 0) throw new RailwayModelError(problems); // ADR-0039: resolving, the deployments the model effectively holds. const all = root.children().filter(isRailwayDeployment); - const ctx: Context = { root, all, groups, vaults }; + const ctx: Context = { all, groups, vaults }; const deployments = all .filter((d) => inScope(d.resolutionKey())) + // Before reading, so a problem in another project's deployment does not stop this one. + .filter((d) => opts.project === undefined || text(d.attr(RAILWAY_ATTR_PROJECT)) === opts.project) .map((d) => readDeployment(d, ctx, problems)) - .filter((d): d is RailwayDeployment => d !== undefined) - .filter((d) => opts.project === undefined || d.project === opts.project); + .filter((d): d is RailwayDeployment => d !== undefined); const byProject = new Map(); for (const d of deployments) byProject.set(d.project, [...(byProject.get(d.project) ?? []), d]); @@ -517,8 +437,3 @@ export function pickProject(projects: readonly RailwayProject[]): RailwayProject } return projects[0]; } - -/** Whether a build or process fact belongs on the file (used by the unexpressed list too). */ -export function isStatic(build: RailwayBuild | undefined): boolean { - return build?.kind === BUILD_SUBTYPE_STATIC; -} diff --git a/packs/railway/typescript/src/railway-ts.ts b/packs/railway/typescript/src/railway-ts.ts index 95ea7cea2..e93f9474c 100644 --- a/packs/railway/typescript/src/railway-ts.ts +++ b/packs/railway/typescript/src/railway-ts.ts @@ -8,6 +8,7 @@ * and anything else Railway runs beside them are left alone. One branch per environment the * model deploys to; Railway passes the environment being planned in `ctx.environment`. */ +import { BUILD_SUBTYPE_COMMAND, BUILD_SUBTYPE_DOCKERFILE } from "@metaobjectsdev/pack-delivery"; import { RESTART_POLICY, RAILWAY_IAC_MODULE, RAILWAY_SDK_VERSION } from "./constants.js"; import type { RailwayDeployment, RailwayProject } from "./model.js"; @@ -16,7 +17,7 @@ class Code { constructor(readonly text: string) {} } -type Value = string | number | boolean | Code | readonly Value[] | { readonly [key: string]: Value | undefined }; +type Value = string | number | boolean | Code | Commented | readonly Value[] | { readonly [key: string]: Value | undefined }; const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/; @@ -24,8 +25,21 @@ function key(k: string): string { return IDENT.test(k) ? k : JSON.stringify(k); } +/** An object whose entries each carry a trailing `// comment`. */ +class Commented { + constructor( + readonly entries: Readonly>, + readonly comments: ReadonlyMap, + ) {} +} + /** A value as TypeScript source, one entry per line, at `indent`. */ -function lit(v: Value, indent: string, comments: ReadonlyMap = new Map()): string { +function lit(v: Value, indent: string): string { + let comments: ReadonlyMap = new Map(); + if (v instanceof Commented) { + comments = v.comments; + v = v.entries; + } if (v instanceof Code) return v.text; if (typeof v !== "object") return JSON.stringify(v); const inner = `${indent} `; @@ -49,29 +63,33 @@ function watchPatterns(d: RailwayDeployment): string[] | undefined { return [...include, ...b.watchExclude.map((g) => `!${g}`)]; } +/** The block when any of its entries is set, else undefined (the key is then left out). */ +function nonEmpty(block: Record): Record | undefined { + return Object.values(block).some((x) => x !== undefined) ? block : undefined; +} + function buildBlock(d: RailwayDeployment): Record | undefined { const b = d.build; const out: Record = {}; - if (b?.kind === "dockerfile" && b.path !== undefined) { + if (b?.kind === BUILD_SUBTYPE_DOCKERFILE && b.path !== undefined) { out["builder"] = "DOCKERFILE"; out["dockerfilePath"] = b.path; } - if (b?.kind === "command" && b.command !== undefined) out["buildCommand"] = b.command; + if (b?.kind === BUILD_SUBTYPE_COMMAND && b.command !== undefined) out["buildCommand"] = b.command; out["watchPatterns"] = watchPatterns(d); - return Object.values(out).some((x) => x !== undefined) ? out : undefined; + return nonEmpty(out); } function deployBlock(d: RailwayDeployment): Record | undefined { const p = d.processes[0]; - const out: Record = { + return nonEmpty({ startCommand: p?.command, healthcheckPath: p?.healthPath, healthcheckTimeout: p?.healthTimeoutSeconds, restartPolicyType: p?.restart === undefined ? undefined : RESTART_POLICY[p.restart], drainingSeconds: p?.drainSeconds, cronSchedule: d.schedule, - }; - return Object.values(out).some((x) => x !== undefined) ? out : undefined; + }); } function sourceCall(d: RailwayDeployment, imports: Set): Code | undefined { @@ -92,15 +110,14 @@ function serviceCall(d: RailwayDeployment, manageVariables: boolean, imports: Se const domains = d.domains.map((domain) => (port === undefined ? domain : { domain, port })); const replicas: Value | undefined = d.region !== undefined ? { [d.region]: d.replicas ?? 1 } : d.replicas; - let env: Record | undefined; - const notes = new Map(); + let env: Commented | undefined; if (manageVariables) { - env = {}; + const entries: Record = {}; for (const v of d.variables) { if (v.kind === "preserve") imports.add("preserve"); - env[v.name] = v.kind === "preserve" ? new Code("preserve()") : v.value ?? ""; - notes.set(v.name, v.from); + entries[v.name] = v.kind === "preserve" ? new Code("preserve()") : v.value ?? ""; } + env = new Commented(entries, new Map(d.variables.map((v) => [v.name, v.from]))); } const config: Record = { source: sourceCall(d, imports), @@ -108,22 +125,20 @@ function serviceCall(d: RailwayDeployment, manageVariables: boolean, imports: Se deploy: deployBlock(d), domains: domains.length === 0 ? undefined : domains, replicas, + env, }; - const body = lit(config, indent); - const envText = env === undefined ? "" : `\n${indent} env: ${lit(env, `${indent} `, notes)},`; - // `env` goes last, with a comment per variable; splice it before the closing brace. - const withEnv = envText === "" ? body : `${body.slice(0, body.lastIndexOf("\n"))}${envText}\n${indent}}`; - return `service(${JSON.stringify(d.service)}, ${withEnv})`; + return `service(${JSON.stringify(d.service)}, ${lit(config, indent)})`; } function projectCall(project: RailwayProject, ds: readonly RailwayDeployment[], imports: Set, indent: string): string { const inner = `${indent} `; - const services = ds.map((d) => `${inner} ${serviceCall(d, project.manageVariables, imports, `${inner} `)},`).join("\n"); - // The CLI reads `variables` (its variable policy); the railway 3.17.0 SDK's types do not declare - // it, so a type-check of the file with those types reports it, and Railway still honours it. - const variables = project.manageVariables - ? "" - : `${inner}// Read by the Railway CLI; the railway ${RAILWAY_SDK_VERSION} SDK's types do not declare it yet.\n${inner}variables: { managed: false },\n`; + // Each service names the model nodes its facts come from. + const services = ds + .map((d) => `${inner} // ${d.appKey}, deployed by deployment.railway ${d.key}\n${inner} ${serviceCall(d, project.manageVariables, imports, `${inner} `)},`) + .join("\n"); + // Spread from a constant: the railway SDK's types do not declare `variables`, which only an + // object literal's excess-property check would refuse, so the file type-checks. + const variables = project.manageVariables ? "" : `${inner}...unmanagedVariables,\n`; return `project(${JSON.stringify(project.name)}, {\n${variables}${inner}resources: [\n${services}\n${inner}],\n${indent}})`; } @@ -160,6 +175,13 @@ export function renderRailwayTs(project: RailwayProject, header: string): string "", `export const partial = ${JSON.stringify(project.partial)};`, "", + ...(project.manageVariables + ? [] + : [ + `/** Read by the Railway CLI (its variable policy); the railway ${RAILWAY_SDK_VERSION} SDK's types do not declare it yet. */`, + "const unmanagedVariables = { variables: { managed: false } };", + "", + ]), "export default defineRailway((ctx) => {", ...branches, ` throw new Error(\`.railway/railway.ts: the model deploys nothing to environment "\${ctx.environment}" (it deploys to: ${declared})\`);`, diff --git a/packs/railway/typescript/test/coverage.test.ts b/packs/railway/typescript/test/coverage.test.ts new file mode 100644 index 000000000..1cbd072c5 --- /dev/null +++ b/packs/railway/typescript/test/coverage.test.ts @@ -0,0 +1,85 @@ +// The emitter's acceptance bar: the generated `.railway/railway.ts` carries every fact the +// adopters' hand-written Railway configuration carries, checked fact by fact. The references +// below are those facts with the adopters' names replaced by the fixtures' placeholders: a +// hand-migrated `.railway/railway.ts` for the one-service shape, and two `railway.json` files +// (watch patterns; the Dockerfile path came from a service variable) for the two-service shape. +// The generated file is evaluated through a recording stand-in for `railway/iac`, so the +// check reads what the file declares, not how it is laid out. More facts than these (domains, +// health checks, variables) are allowed: that is where the generated file does better. +import { describe, expect, mock, test } from "bun:test"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +mock.module("railway/iac", () => ({ + defineRailway: (fn: unknown) => fn, + project: (name: string, o: object) => ({ name, ...o }), + service: (name: string, o: object) => ({ name, ...o }), + github: (repo: string, o: object = {}) => ({ type: "github", repo, ...o }), + image: (ref: string) => ({ type: "image", image: ref }), + preserve: () => ({ preserve: true }), +})); + +const GOLDEN = join(import.meta.dir, "golden"); + +type Json = null | boolean | number | string | Json[] | { [k: string]: Json }; + +/** Every fact of `expected` (a leaf, by its path) that `actual` lacks or holds differently. */ +function missing(expected: Json, actual: unknown, path = ""): string[] { + if (expected === null || typeof expected !== "object") { + return Object.is(expected, actual) ? [] : [`${path}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`]; + } + if (Array.isArray(expected)) { + // A list is one fact: watch patterns are ordered (a later exclusion wins). + return JSON.stringify(expected) === JSON.stringify(actual) ? [] : [`${path}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`]; + } + if (actual === null || typeof actual !== "object") return [`${path}: missing`]; + return Object.entries(expected).flatMap(([k, v]) => missing(v, (actual as Record)[k], `${path}.${k}`)); +} + +async function evaluate(scenario: string, environment: string): Promise<{ partial: string; project: Record }> { + // The golden file, imported from a copy so "railway/iac" resolves to the stand-in. + const dir = mkdtempSync(join(process.env.DEV_SCRATCH ?? tmpdir(), "railway-coverage-")); + try { + const file = join(dir, "railway.ts"); + writeFileSync(file, await Bun.file(join(GOLDEN, scenario, ".railway/railway.ts")).text()); + const m = (await import(file)) as { partial: string; default: (ctx: { environment: string }) => Record }; + return { partial: m.partial, project: m.default({ environment }) }; + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + +function serviceNamed(project: Record, name: string): unknown { + return (project["resources"] as { name: string }[]).find((s) => s.name === name); +} + +describe("the generated file carries every fact of the hand-written configuration", () => { + test("one service: the hand-migrated .railway/railway.ts", async () => { + const { partial, project } = await evaluate("railway-emit-one-service", "production"); + expect(partial).toBe("game"); + expect(missing({ name: "game", variables: { managed: false } }, project)).toEqual([]); + expect( + missing( + { + source: { type: "github", repo: "acme/game", branch: "main", checkSuites: false }, + build: { + watchPatterns: ["**", "!/.archive/**", "!/.claude/**", "!/.docs/**", "!/.github/**", "!/.githooks/**", "!/.metaobjects/*.md", "!/.metaobjects/.agent-context.json", "!/.specify/**", "!/.test-prompts/**", "!/assets/**", "!/docs/**", "!/e2e-tests/**", "!/scripts/**", "!/*.md", "!/TODOs"], + }, + deploy: { healthcheckPath: "/actuator/health/container", healthcheckTimeout: 300, restartPolicyType: "ON_FAILURE", drainingSeconds: 180 }, + }, + serviceNamed(project, "game"), + ), + ).toEqual([]); + }); + + test("two services: each railway.json, and the Dockerfile path its service variable held", async () => { + const { project } = await evaluate("railway-emit-two-services", "production"); + expect(missing({ build: { watchPatterns: ["arena/**", "!arena/tests/**", "!metaobjects/**"], dockerfilePath: "arena/Dockerfile" } }, serviceNamed(project, "arena"))).toEqual([]); + expect(missing({ build: { watchPatterns: ["java/**", "poker/**", "framework/**"], dockerfilePath: "java/Dockerfile" } }, serviceNamed(project, "java"))).toEqual([]); + }); + + test("an environment the model does not deploy to is refused, not given a guess", async () => { + await expect(evaluate("railway-emit-one-service", "staging")).rejects.toThrow('deploys nothing to environment "staging"'); + }); +}); diff --git a/packs/railway/typescript/test/golden/railway-emit-one-service/.railway/railway.ts b/packs/railway/typescript/test/golden/railway-emit-one-service/.railway/railway.ts index 861233a7b..c339c2b93 100644 --- a/packs/railway/typescript/test/golden/railway-emit-one-service/.railway/railway.ts +++ b/packs/railway/typescript/test/golden/railway-emit-one-service/.railway/railway.ts @@ -14,12 +14,15 @@ import { defineRailway, github, project, service } from "railway/iac"; export const partial = "game"; +/** Read by the Railway CLI (its variable policy); the railway 3.17.0 SDK's types do not declare it yet. */ +const unmanagedVariables = { variables: { managed: false } }; + export default defineRailway((ctx) => { if (ctx.environment === "production") { return project("game", { - // Read by the Railway CLI; the railway 3.17.0 SDK's types do not declare it yet. - variables: { managed: false }, + ...unmanagedVariables, resources: [ + // app.service acme::game::Game.server, deployed by deployment.railway acme::game::server-production service("game", { source: github("acme/game", { branch: "main", checkSuites: false }), build: { diff --git a/packs/railway/typescript/test/golden/railway-emit-one-service/deploy/deploy.sh b/packs/railway/typescript/test/golden/railway-emit-one-service/deploy/deploy.sh index c236ca353..827b262c3 100644 --- a/packs/railway/typescript/test/golden/railway-emit-one-service/deploy/deploy.sh +++ b/packs/railway/typescript/test/golden/railway-emit-one-service/deploy/deploy.sh @@ -16,10 +16,10 @@ set -euo pipefail cd "$(dirname "$0")/.." ENVIRONMENT="${1:-}" -YES=(); REDEPLOY=0 +YES=""; REDEPLOY=0 for arg in "${@:2}"; do case "$arg" in - --yes) YES=(--yes) ;; + --yes) YES=--yes ;; --redeploy) REDEPLOY=1 ;; *) echo 'usage: bash deploy/deploy.sh [--yes] [--redeploy]' >&2; exit 2 ;; esac @@ -44,7 +44,8 @@ settle() { railway environment "$1" >/dev/null ensure_sdk railway config plan - railway config apply "${YES[@]}" + # shellcheck disable=SC2086 # YES is empty or one word + railway config apply $YES } case "$ENVIRONMENT" in diff --git a/packs/railway/typescript/test/golden/railway-emit-one-service/deploy/doctor.sh b/packs/railway/typescript/test/golden/railway-emit-one-service/deploy/doctor.sh index f23fe5708..4e40f160d 100644 --- a/packs/railway/typescript/test/golden/railway-emit-one-service/deploy/doctor.sh +++ b/packs/railway/typescript/test/golden/railway-emit-one-service/deploy/doctor.sh @@ -54,11 +54,6 @@ plan_clean() { esac } -# answers -answers() { - if curl -fsS -o /dev/null --max-time 10 "$1"; then ok "$1 answers"; else bad "$1 does not answer 2xx"; fi -} - case "$ENVIRONMENT" in production) in_vault acme-game prod LLM_API_KEY diff --git a/packs/railway/typescript/test/golden/railway-emit-one-service/deploy/sync-secrets.sh b/packs/railway/typescript/test/golden/railway-emit-one-service/deploy/sync-secrets.sh index 497dd2f64..5ddf82435 100644 --- a/packs/railway/typescript/test/golden/railway-emit-one-service/deploy/sync-secrets.sh +++ b/packs/railway/typescript/test/golden/railway-emit-one-service/deploy/sync-secrets.sh @@ -13,11 +13,18 @@ set -euo pipefail cd "$(dirname "$0")/.." ENVIRONMENT="${1:-}" -DRY_RUN=0; [ "${2:-}" = "--dry-run" ] && DRY_RUN=1 +DRY_RUN=0 +for arg in "${@:2}"; do + case "$arg" in + --dry-run) DRY_RUN=1 ;; + *) echo 'usage: bash deploy/sync-secrets.sh [--dry-run]' >&2; exit 2 ;; + esac +done # copy copy() { if [ "$DRY_RUN" = 1 ]; then echo "would copy $5 from $1/$2 to service $3 ($4)"; return; fi + # shellcheck disable=SC2016 # the inner shell expands it: the value never enters this one keys-axi run --project "$1" --env "$2" --only "$5" -- bash -c ' [ -n "${!1+set}" ] || { echo "sync-secrets: $1 is not in the vault scope" >&2; exit 1; } printf %s "${!1}" | railway variable set "$1" --stdin --service "$2" --environment "$3" --skip-deploys >/dev/null diff --git a/packs/railway/typescript/test/golden/railway-emit-two-services/.railway/railway.ts b/packs/railway/typescript/test/golden/railway-emit-two-services/.railway/railway.ts index e3fb17e0a..9c0f3b88f 100644 --- a/packs/railway/typescript/test/golden/railway-emit-two-services/.railway/railway.ts +++ b/packs/railway/typescript/test/golden/railway-emit-two-services/.railway/railway.ts @@ -19,6 +19,7 @@ export default defineRailway((ctx) => { if (ctx.environment === "production") { return project("acme-prod", { resources: [ + // app.service acme::tables::Tables.arena, deployed by deployment.railway acme::tables::arena-production service("arena", { source: github("acme/tables", { branch: "main" }), build: { @@ -46,6 +47,7 @@ export default defineRailway((ctx) => { SESSION_SECRET: preserve(), // acme::tables::Session.secret, secret: copied from the vault by the sync script }, }), + // app.service acme::tables::Tables.java, deployed by deployment.railway acme::tables::java-production service("java", { source: github("acme/tables", { branch: "main" }), build: { diff --git a/packs/railway/typescript/test/golden/railway-emit-two-services/deploy/deploy.sh b/packs/railway/typescript/test/golden/railway-emit-two-services/deploy/deploy.sh index 66a3ed966..5b9caf05d 100644 --- a/packs/railway/typescript/test/golden/railway-emit-two-services/deploy/deploy.sh +++ b/packs/railway/typescript/test/golden/railway-emit-two-services/deploy/deploy.sh @@ -16,10 +16,10 @@ set -euo pipefail cd "$(dirname "$0")/.." ENVIRONMENT="${1:-}" -YES=(); REDEPLOY=0 +YES=""; REDEPLOY=0 for arg in "${@:2}"; do case "$arg" in - --yes) YES=(--yes) ;; + --yes) YES=--yes ;; --redeploy) REDEPLOY=1 ;; *) echo 'usage: bash deploy/deploy.sh [--yes] [--redeploy]' >&2; exit 2 ;; esac @@ -44,7 +44,8 @@ settle() { railway environment "$1" >/dev/null ensure_sdk railway config plan - railway config apply "${YES[@]}" + # shellcheck disable=SC2086 # YES is empty or one word + railway config apply $YES } case "$ENVIRONMENT" in diff --git a/packs/railway/typescript/test/golden/railway-emit-two-services/deploy/sync-secrets.sh b/packs/railway/typescript/test/golden/railway-emit-two-services/deploy/sync-secrets.sh index 2f1bd952b..05db6ef5b 100644 --- a/packs/railway/typescript/test/golden/railway-emit-two-services/deploy/sync-secrets.sh +++ b/packs/railway/typescript/test/golden/railway-emit-two-services/deploy/sync-secrets.sh @@ -13,11 +13,18 @@ set -euo pipefail cd "$(dirname "$0")/.." ENVIRONMENT="${1:-}" -DRY_RUN=0; [ "${2:-}" = "--dry-run" ] && DRY_RUN=1 +DRY_RUN=0 +for arg in "${@:2}"; do + case "$arg" in + --dry-run) DRY_RUN=1 ;; + *) echo 'usage: bash deploy/sync-secrets.sh [--dry-run]' >&2; exit 2 ;; + esac +done # copy copy() { if [ "$DRY_RUN" = 1 ]; then echo "would copy $5 from $1/$2 to service $3 ($4)"; return; fi + # shellcheck disable=SC2016 # the inner shell expands it: the value never enters this one keys-axi run --project "$1" --env "$2" --only "$5" -- bash -c ' [ -n "${!1+set}" ] || { echo "sync-secrets: $1 is not in the vault scope" >&2; exit 1; } printf %s "${!1}" | railway variable set "$1" --stdin --service "$2" --environment "$3" --skip-deploys >/dev/null diff --git a/packs/railway/typescript/test/model.test.ts b/packs/railway/typescript/test/model.test.ts index cd2356b66..4477f2f4b 100644 --- a/packs/railway/typescript/test/model.test.ts +++ b/packs/railway/typescript/test/model.test.ts @@ -68,15 +68,6 @@ describe("readRailway refuses what Railway cannot do", () => { expect(p.join("\n")).toContain('"Nope.thing" names no setting'); }); - test("@path on an output that is not a URL", async () => { - const p = await problems( - oneService( - (c) => (deployment(c)["children"] = [{ "value.ref": { name: "h", "@setting": "Database.url", "@producedBy": "Game.db", "@output": "host", "@path": "/x" } }]), - ), - ); - expect(p.join("\n")).toContain("@path is appended to a URL"); - }); - test("an output the engine does not supply", async () => { const p = await problems( oneService((c) => { @@ -129,4 +120,29 @@ describe("readRailway refuses what Railway cannot do", () => { const p = await problems(oneService((c) => (deployment(c)["@service"] = "game server"))); expect(p.join("\n")).toContain("partial name"); }); + test("a deployment with no values still declares its settings, for a project whose file manages variables", async () => { + const root = await loadModels([{ id: "meta.game.json", json: oneService(() => {}) }]); + const d = pickProject(readRailway(root, root.children().filter(isMetaObject) as MetaObject[]))!.deployments[0]!; + expect(d.hasValues).toBe(false); + expect(d.variables.map((v) => [v.name, v.kind])).toEqual([ + ["DATABASE_URL", "preserve"], + ["LLM_API_KEY", "preserve"], + ["LLM_MODEL", "literal"], + ["REDIS_URL", "preserve"], + ]); + }); + + test("a settings problem is reported alone, not as every deployment that reads the settings", async () => { + const p = await problems( + oneService((c) => { + const redis = c.find((x) => (x["object.settings"] as { name?: string } | undefined)?.name === "Redis")!["object.settings"]!; + (redis["children"] as Record>[])[0]!["field.string"]!["@envName"] = "DATABASE_URL"; + deployment(c)["children"] = [ + { "value.literal": { name: "a", "@setting": "Database.url", "@literal": "x" } }, + { "value.literal": { name: "b", "@setting": "Redis.url", "@literal": "y" } }, + ]; + }), + ); + expect(p).toEqual(["acme::game::Redis.url: environment variable DATABASE_URL is also acme::game::Database.url"]); + }); }); diff --git a/packs/systems/typescript/src/constants.ts b/packs/systems/typescript/src/constants.ts index 2aaebd4d5..a33006b96 100644 --- a/packs/systems/typescript/src/constants.ts +++ b/packs/systems/typescript/src/constants.ts @@ -23,6 +23,8 @@ export const APP_ATTR_SCHEDULE = "schedule"; export const RESOURCE_ATTR_ENGINE = "engine"; export const RESOURCE_ATTR_VERSION = "version"; export const RESOURCE_ATTR_MANAGED_BY = "managedBy"; +export const MANAGED_BY_PLATFORM = "platform"; +export const MANAGED_BY_EXTERNAL = "external"; /** Raised when an app's @needs or @calls names nothing, or the wrong kind of node. */ export const ERR_SYSTEMS_UNRESOLVED_REF = "ERR_SYSTEMS_UNRESOLVED_REF"; From fbb63386ecf688a6e4cdb951163eef19c79a7961 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 25 Nov 2026 04:53:31 -0500 Subject: [PATCH 3/4] no-mistakes(review): list dropped facts, support abstract deployments --- packs/delivery/CHANGELOG.md | 3 + packs/delivery/README.md | 12 ++ packs/delivery/typescript/src/index.ts | 3 +- packs/railway/CHANGELOG.md | 6 + packs/railway/README.md | 6 + .../expected.json | 48 ++++++ .../input/meta.shop.json | 27 ++++ .../providers.json | 1 + .../railway-emit-environments/expected.json | 137 ++++++++++++++++++ .../input/meta.shop.json | 68 +++++++++ .../railway-emit-environments/providers.json | 1 + packs/railway/typescript/src/constants.ts | 5 +- packs/railway/typescript/src/files.ts | 19 +++ packs/railway/typescript/src/model.ts | 2 +- packs/railway/typescript/test/emit.test.ts | 2 +- .../typescript/test/generated-types.test.ts | 102 +++++++++++++ .../.claude/skills/deploy/SKILL.md | 43 ++++++ .../.railway/railway.ts | 81 +++++++++++ .../deploy/deploy.sh | 69 +++++++++ .../deploy/doctor.sh | 74 ++++++++++ .../deploy/sync-secrets.sh | 43 ++++++ .../deploy/unexpressed.md | 23 +++ .../deploy/unexpressed.md | 1 + packs/railway/typescript/test/model.test.ts | 70 ++++++++- 24 files changed, 841 insertions(+), 5 deletions(-) create mode 100644 packs/railway/fixtures/conformance/abstract-deployment-with-environment/expected.json create mode 100644 packs/railway/fixtures/conformance/abstract-deployment-with-environment/input/meta.shop.json create mode 100644 packs/railway/fixtures/conformance/abstract-deployment-with-environment/providers.json create mode 100644 packs/railway/fixtures/conformance/railway-emit-environments/expected.json create mode 100644 packs/railway/fixtures/conformance/railway-emit-environments/input/meta.shop.json create mode 100644 packs/railway/fixtures/conformance/railway-emit-environments/providers.json create mode 100644 packs/railway/typescript/test/generated-types.test.ts create mode 100644 packs/railway/typescript/test/golden/railway-emit-environments/.claude/skills/deploy/SKILL.md create mode 100644 packs/railway/typescript/test/golden/railway-emit-environments/.railway/railway.ts create mode 100644 packs/railway/typescript/test/golden/railway-emit-environments/deploy/deploy.sh create mode 100644 packs/railway/typescript/test/golden/railway-emit-environments/deploy/doctor.sh create mode 100644 packs/railway/typescript/test/golden/railway-emit-environments/deploy/sync-secrets.sh create mode 100644 packs/railway/typescript/test/golden/railway-emit-environments/deploy/unexpressed.md diff --git a/packs/delivery/CHANGELOG.md b/packs/delivery/CHANGELOG.md index badd9bf01..1055c1848 100644 --- a/packs/delivery/CHANGELOG.md +++ b/packs/delivery/CHANGELOG.md @@ -11,6 +11,9 @@ This pack's own changelog (ADR-0069). The root `CHANGELOG.md` records core only. `@secrets` and `@setting` are names only. A deployment holds one value per `@setting` (`ERR_DELIVERY_DUPLICATE_SETTING`) and a model one deployment per (`@app`, `@environment`) (`ERR_DELIVERY_DUPLICATE_DEPLOYMENT`). TypeScript port. +- An abstract deployment (`"abstract": true`) is a template for the deployments that extend it: + the one-deployment-per-(`@app`, `@environment`) check skips it, so a base that names an + environment no longer collides with its own child. - `@watchInclude` on every `build.*`, beside `@watchExclude`: the paths whose change starts a build, for an app that lives in one directory of a monorepo. - `@path` on `value.ref`: a path appended to a URL output (`/api`), for a setting that addresses diff --git a/packs/delivery/README.md b/packs/delivery/README.md index 81b40c37e..1cd7b2935 100644 --- a/packs/delivery/README.md +++ b/packs/delivery/README.md @@ -71,6 +71,18 @@ overlay, using the loader's existing merge: The `railway` pack's `railway-worked-example` fixture is the whole example, both sides. +### One abstract deployment, one per environment + +What is true of every environment (the app, the project, the service, the repository, the values +that do not change) is written once, in an abstract deployment (`"abstract": true`, which is core's +structural keyword, not a new attribute). Each environment's deployment `extends` it and holds only +the differences: its `@environment`, `@branch`, `@domains`, `@replicas` and its own `value.*` +children. A child value that reuses the base value's name overrides it. An abstract deployment may +omit `@app` and `@environment`, a concrete one must resolve both (its own or inherited), and an +abstract one is never counted by the one-deployment-per-(`@app`, `@environment`) check or +deployed. The `railway` pack's `railway-emit-environments` fixture shows it, and +`abstract-deployment-with-environment` is the case where the base also names an environment. + ## Readers `readBuild(app)` and `readProcesses(app)` return an app's build and processes as plain records diff --git a/packs/delivery/typescript/src/index.ts b/packs/delivery/typescript/src/index.ts index 2a396c121..3a15689b5 100644 --- a/packs/delivery/typescript/src/index.ts +++ b/packs/delivery/typescript/src/index.ts @@ -64,11 +64,12 @@ function deploymentTarget(node: MetaData): [MetaData, MetaData] | undefined { // An app runs once per environment: two deployments for one (app, environment) leave a // generator to pick by load order. The error lands on the later one. function checkDeploymentUnique(node: MetaData, ctx: ValidationContext): void { + if (node.isAbstract) return; // a template for the deployments that extend it, never deployed itself const mine = deploymentTarget(node); const root = topLevelNodeOf(node).parent; if (mine === undefined || root === undefined) return; // ADR-0039: resolving, the deployments the model effectively holds. - const deployments = root.children().filter((c) => c.type === TYPE_DEPLOYMENT); + const deployments = root.children().filter((c) => c.type === TYPE_DEPLOYMENT && !c.isAbstract); const first = deployments.find((d) => { const t = deploymentTarget(d); return t !== undefined && t[0] === mine[0] && t[1] === mine[1]; diff --git a/packs/railway/CHANGELOG.md b/packs/railway/CHANGELOG.md index 84eb62a60..f94469686 100644 --- a/packs/railway/CHANGELOG.md +++ b/packs/railway/CHANGELOG.md @@ -8,6 +8,12 @@ This pack's own changelog (ADR-0069). The root `CHANGELOG.md` records core only. `deployment.base`, held to its references. The worked example (an app's model plus an estate repository's additions and overlay) is the `railway-worked-example` fixture. TypeScript port. - `@repo`, `@image` and `@checkSuites` on `deployment.railway`: the service's source. +- An abstract `deployment.railway` is a template and is never rendered; each environment's + deployment `extends` it and holds only its differences. Fixture `railway-emit-environments` + renders both environments from one model (golden output); `abstract-deployment-with-environment` + loads a base that names an environment beside its concrete child. +- `deploy/unexpressed.md` also lists `@branch` and `@checkSuites` on an `@image` source, and a + `runtime.process @port` on a deployment with no domain to carry it. - **Generators**: `.railway/railway.ts` in Railway's Infrastructure as Code format (the `railway` npm package 3.17.0's `railway/iac` DSL, a named partial), `deploy/unexpressed.md` (the facts the file does not hold), `deploy/sync-secrets.sh` (vault to Railway through `keys-axi`), diff --git a/packs/railway/README.md b/packs/railway/README.md index 3c4b45ae1..a0bc0f20d 100644 --- a/packs/railway/README.md +++ b/packs/railway/README.md @@ -110,6 +110,12 @@ export default defineConfig({ - [`railway-emit-two-services/`](fixtures/conformance/railway-emit-two-services/): two services from one monorepo, each built from its own directory, one calling the other over Railway's private network, managed variables. +- [`railway-emit-environments/`](fixtures/conformance/railway-emit-environments/): one service in + production and staging from one abstract `deployment.railway` that holds what both share (app, + project, service, repository, a value); each environment's deployment `extends` it and holds its + own `@environment`, `@branch`, `@domains`, `@replicas` and values, and staging overrides the base + value by reusing its name. The abstract base is never rendered as a service. The pattern is + described in the delivery pack's README ("One abstract deployment, one per environment"). Names, domains, repositories and project names are placeholders. diff --git a/packs/railway/fixtures/conformance/abstract-deployment-with-environment/expected.json b/packs/railway/fixtures/conformance/abstract-deployment-with-environment/expected.json new file mode 100644 index 000000000..645961a0b --- /dev/null +++ b/packs/railway/fixtures/conformance/abstract-deployment-with-environment/expected.json @@ -0,0 +1,48 @@ +{ + "metadata.root": { + "package": "acme::shop", + "children": [ + { + "system.internal": { + "name": "Shop", + "children": [ + { + "app.service": { + "name": "server", + "children": [ + { + "runtime.process": { + "name": "web" + } + } + ] + } + } + ] + } + }, + { + "environment.standing": { + "name": "production" + } + }, + { + "deployment.railway": { + "name": "server-base", + "abstract": true, + "@app": "Shop.server", + "@environment": "production", + "@project": "acme-shop", + "@repo": "acme/shop" + } + }, + { + "deployment.railway": { + "name": "server-production", + "extends": "acme::shop::server-base", + "@branch": "main" + } + } + ] + } +} diff --git a/packs/railway/fixtures/conformance/abstract-deployment-with-environment/input/meta.shop.json b/packs/railway/fixtures/conformance/abstract-deployment-with-environment/input/meta.shop.json new file mode 100644 index 000000000..a200df983 --- /dev/null +++ b/packs/railway/fixtures/conformance/abstract-deployment-with-environment/input/meta.shop.json @@ -0,0 +1,27 @@ +{ + "metadata.root": { + "package": "acme::shop", + "children": [ + { "system.internal": { + "name": "Shop", + "children": [ + { "app.service": { "name": "server", "children": [ { "runtime.process": { "name": "web" } } ] } } + ] + } }, + { "environment.standing": { "name": "production" } }, + { "deployment.railway": { + "name": "server-base", + "abstract": true, + "@app": "Shop.server", + "@environment": "production", + "@project": "acme-shop", + "@repo": "acme/shop" + } }, + { "deployment.railway": { + "name": "server-production", + "extends": "server-base", + "@branch": "main" + } } + ] + } +} diff --git a/packs/railway/fixtures/conformance/abstract-deployment-with-environment/providers.json b/packs/railway/fixtures/conformance/abstract-deployment-with-environment/providers.json new file mode 100644 index 000000000..916757f19 --- /dev/null +++ b/packs/railway/fixtures/conformance/abstract-deployment-with-environment/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-documentation", "metaobjects-systems", "metaobjects-delivery", "metaobjects-config", "metaobjects-railway"] diff --git a/packs/railway/fixtures/conformance/railway-emit-environments/expected.json b/packs/railway/fixtures/conformance/railway-emit-environments/expected.json new file mode 100644 index 000000000..9dda602ad --- /dev/null +++ b/packs/railway/fixtures/conformance/railway-emit-environments/expected.json @@ -0,0 +1,137 @@ +{ + "metadata.root": { + "package": "acme::shop", + "children": [ + { + "system.internal": { + "name": "Shop", + "@description": "One service deployed to two environments from one abstract deployment: the base holds what is true in both, each environment's deployment holds only what differs.", + "children": [ + { + "app.service": { + "name": "server", + "@settings": [ + "Runtime" + ], + "children": [ + { + "build.dockerfile": { + "name": "image", + "@path": "server/Dockerfile", + "@watchInclude": [ + "server/**" + ] + } + }, + { + "runtime.process": { + "name": "web", + "@healthPath": "/health", + "@port": 8080 + } + } + ] + } + } + ] + } + }, + { + "object.settings": { + "name": "Runtime", + "children": [ + { + "field.string": { + "name": "logLevel", + "@envName": "LOG_LEVEL" + } + }, + { + "field.string": { + "name": "banner", + "@envName": "BANNER" + } + } + ] + } + }, + { + "environment.standing": { + "name": "production" + } + }, + { + "environment.standing": { + "name": "staging" + } + }, + { + "deployment.railway": { + "name": "server-base", + "abstract": true, + "@app": "Shop.server", + "@project": "acme-shop", + "@repo": "acme/shop", + "@service": "shop", + "children": [ + { + "value.literal": { + "name": "log", + "@literal": "info", + "@setting": "Runtime.logLevel" + } + } + ] + } + }, + { + "deployment.railway": { + "name": "server-production", + "extends": "acme::shop::server-base", + "@branch": "main", + "@domains": [ + "shop.example.com" + ], + "@environment": "production", + "@replicas": 2, + "children": [ + { + "value.literal": { + "name": "banner", + "@literal": "production", + "@setting": "Runtime.banner" + } + } + ] + } + }, + { + "deployment.railway": { + "name": "server-staging", + "extends": "acme::shop::server-base", + "@branch": "staging", + "@domains": [ + "staging.shop.example.com" + ], + "@environment": "staging", + "children": [ + { + "value.literal": { + "name": "log", + "@literal": "debug", + "@setting": "Runtime.logLevel" + } + }, + { + "value.literal": { + "name": "banner", + "@literal": "staging", + "@setting": "Runtime.banner" + } + } + ] + } + } + ] + } +} diff --git a/packs/railway/fixtures/conformance/railway-emit-environments/input/meta.shop.json b/packs/railway/fixtures/conformance/railway-emit-environments/input/meta.shop.json new file mode 100644 index 000000000..fad50b454 --- /dev/null +++ b/packs/railway/fixtures/conformance/railway-emit-environments/input/meta.shop.json @@ -0,0 +1,68 @@ +{ + "metadata.root": { + "package": "acme::shop", + "children": [ + { "system.internal": { + "name": "Shop", + "@description": "One service deployed to two environments from one abstract deployment: the base holds what is true in both, each environment's deployment holds only what differs.", + "children": [ + { "app.service": { + "name": "server", + "@settings": ["Runtime"], + "children": [ + { "build.dockerfile": { + "name": "image", + "@path": "server/Dockerfile", + "@watchInclude": ["server/**"] + } }, + { "runtime.process": { + "name": "web", + "@port": 8080, + "@healthPath": "/health" + } } + ] + } } + ] + } }, + { "object.settings": { "name": "Runtime", "children": [ + { "field.string": { "name": "logLevel", "@envName": "LOG_LEVEL" } }, + { "field.string": { "name": "banner", "@envName": "BANNER" } } + ]}}, + { "environment.standing": { "name": "production" } }, + { "environment.standing": { "name": "staging" } }, + { "deployment.railway": { + "name": "server-base", + "abstract": true, + "@app": "Shop.server", + "@project": "acme-shop", + "@service": "shop", + "@repo": "acme/shop", + "children": [ + { "value.literal": { "name": "log", "@setting": "Runtime.logLevel", "@literal": "info" } } + ] + } }, + { "deployment.railway": { + "name": "server-production", + "extends": "server-base", + "@environment": "production", + "@branch": "main", + "@domains": ["shop.example.com"], + "@replicas": 2, + "children": [ + { "value.literal": { "name": "banner", "@setting": "Runtime.banner", "@literal": "production" } } + ] + } }, + { "deployment.railway": { + "name": "server-staging", + "extends": "server-base", + "@environment": "staging", + "@branch": "staging", + "@domains": ["staging.shop.example.com"], + "children": [ + { "value.literal": { "name": "log", "@setting": "Runtime.logLevel", "@literal": "debug" } }, + { "value.literal": { "name": "banner", "@setting": "Runtime.banner", "@literal": "staging" } } + ] + } } + ] + } +} diff --git a/packs/railway/fixtures/conformance/railway-emit-environments/providers.json b/packs/railway/fixtures/conformance/railway-emit-environments/providers.json new file mode 100644 index 000000000..916757f19 --- /dev/null +++ b/packs/railway/fixtures/conformance/railway-emit-environments/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types", "metaobjects-documentation", "metaobjects-systems", "metaobjects-delivery", "metaobjects-config", "metaobjects-railway"] diff --git a/packs/railway/typescript/src/constants.ts b/packs/railway/typescript/src/constants.ts index 98d59e8ac..02b3ab971 100644 --- a/packs/railway/typescript/src/constants.ts +++ b/packs/railway/typescript/src/constants.ts @@ -20,8 +20,11 @@ export const RAILWAY_IAC_MODULE = "railway/iac"; /** A Railway named partial: 1 to 64 of `a-z A-Z 0-9 . _ -` (Railway's IaC page). */ export const PARTIAL_PATTERN = /^[A-Za-z0-9._-]{1,64}$/; +/** The values of Railway's `deploy.restartPolicyType`. */ +export type RestartPolicyType = "ALWAYS" | "ON_FAILURE" | "NEVER"; + /** `runtime.process @restart` → Railway's `deploy.restartPolicyType`. */ -export const RESTART_POLICY: Readonly> = { +export const RESTART_POLICY: Readonly> = { [RESTART_ALWAYS]: "ALWAYS", [RESTART_ON_FAILURE]: "ON_FAILURE", [RESTART_NEVER]: "NEVER", diff --git a/packs/railway/typescript/src/files.ts b/packs/railway/typescript/src/files.ts index e08660581..eb30a81d6 100644 --- a/packs/railway/typescript/src/files.ts +++ b/packs/railway/typescript/src/files.ts @@ -55,6 +55,25 @@ export function unexpressedFacts(d: RailwayDeployment, manageVariables: boolean) how: `Not declared, so the partial neither creates nor deletes it. It must exist in the Railway project under the name ${md(r.name)}, which every reference to it uses.`, }); } + if (d.image !== undefined && d.branch !== undefined) { + out.push({ + fact: `Branch ${md(d.branch)} (deployment.railway @branch)`, + how: `The service's source is the image ${md(d.image)}, which has no branch to deploy from. The file leaves the branch out.`, + }); + } + if (d.image !== undefined && d.checkSuites !== undefined) { + out.push({ + fact: `Check suites ${md(String(d.checkSuites))} (deployment.railway @checkSuites)`, + how: `The service's source is the image ${md(d.image)}, which has no check suites to wait for. The file leaves the setting out.`, + }); + } + const port = d.processes.find((p) => p.port !== undefined)?.port; + if (port !== undefined && d.domains.length === 0) { + out.push({ + fact: `Port ${md(String(port))} (runtime.process @port)`, + how: `The file carries a port only beside a domain, and this deployment has none. Railway takes the port from the service's PORT variable (or a domain's target port): set PORT=${port} on the service in Railway. References from other services to this port use the model's value.`, + }); + } if (d.domains.length > 0) { out.push({ fact: `DNS for ${d.domains.map(md).join(", ")}`, diff --git a/packs/railway/typescript/src/model.ts b/packs/railway/typescript/src/model.ts index 49fef476f..3e4cf88fc 100644 --- a/packs/railway/typescript/src/model.ts +++ b/packs/railway/typescript/src/model.ts @@ -394,7 +394,7 @@ export function readRailway( // A settings or vault problem makes every deployment that reads them look wrong too: report it alone. if (problems.length > 0) throw new RailwayModelError(problems); // ADR-0039: resolving, the deployments the model effectively holds. - const all = root.children().filter(isRailwayDeployment); + const all = root.children().filter((d) => isRailwayDeployment(d) && !d.isAbstract); const ctx: Context = { all, groups, vaults }; const deployments = all .filter((d) => inScope(d.resolutionKey())) diff --git a/packs/railway/typescript/test/emit.test.ts b/packs/railway/typescript/test/emit.test.ts index 97a56986c..3cba8aa5c 100644 --- a/packs/railway/typescript/test/emit.test.ts +++ b/packs/railway/typescript/test/emit.test.ts @@ -36,7 +36,7 @@ function walk(dir: string): string[] { }); } -describe.each(["railway-emit-one-service", "railway-emit-two-services"])("%s", (scenario) => { +describe.each(["railway-emit-one-service", "railway-emit-two-services", "railway-emit-environments"])("%s", (scenario) => { test("the generators write the golden files, and only those", async () => { const files = await render(await loadFixture(scenario), railwayFiles()); const golden = join(GOLDEN, scenario); diff --git a/packs/railway/typescript/test/generated-types.test.ts b/packs/railway/typescript/test/generated-types.test.ts new file mode 100644 index 000000000..6ad06a6c4 --- /dev/null +++ b/packs/railway/typescript/test/generated-types.test.ts @@ -0,0 +1,102 @@ +// The generated `.railway/railway.ts` type-checks against the railway 3.17.0 SDK where the +// hand-written one did not. The full check was run against the SDK's own types outside this +// suite (the `railway` package is not a dependency: its install downloads a CLI binary). What +// it found, and what these tests keep from coming back, is read from the golden files, which +// are the generator's public output: +// - `restartPolicyType` is the SDK's literal union, so only "ALWAYS" | "ON_FAILURE" | "NEVER"; +// a widened `string` is refused. +// - `variables` is not declared in the SDK's types, so an object literal that names it is +// refused by the excess-property check; the file spreads it from a declared constant. +// The golden files are parsed, not matched as text, so a comment or a string that mentions +// `variables` is not mistaken for a key. +import { describe, expect, test } from "bun:test"; +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import ts from "typescript"; +import { RESTART_POLICY, type RestartPolicyType } from "../src/index.js"; + +/** The SDK's `restartPolicyType` union (railway 3.17.0), the independent oracle for the values. */ +const SDK_RESTART_POLICY_TYPES: readonly string[] = ["ALWAYS", "ON_FAILURE", "NEVER"]; + +// A widened `string` value type fails `bun run typecheck`. +export const restartPolicyIsTheLiteralUnion: Readonly> = RESTART_POLICY; + +const GOLDEN = join(import.meta.dir, "golden"); +const scenarios = readdirSync(GOLDEN); + +function parse(scenario: string): ts.SourceFile { + const file = join(GOLDEN, scenario, ".railway/railway.ts"); + return ts.createSourceFile(file, readFileSync(file, "utf8"), ts.ScriptTarget.Latest, true); +} + +function visit(node: ts.Node, fn: (n: ts.Node) => void): void { + fn(node); + ts.forEachChild(node, (c) => visit(c, fn)); +} + +function propertyName(p: ts.ObjectLiteralElementLike): string | undefined { + return p.name !== undefined && (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)) ? p.name.text : undefined; +} + +describe("the RESTART_POLICY map is the SDK's literal union", () => { + test("its values are exactly the SDK's restartPolicyType values", () => { + expect([...new Set(Object.values(RESTART_POLICY))].sort()).toEqual([...SDK_RESTART_POLICY_TYPES].sort()); + }); +}); + +describe.each(scenarios)("golden %s", (scenario) => { + const source = parse(scenario); + + test("`variables` is never a key of a project(...) object, only spread from the declared constant", () => { + const projects: ts.ObjectLiteralExpression[] = []; + visit(source, (n) => { + if (ts.isCallExpression(n) && ts.isIdentifier(n.expression) && n.expression.text === "project") { + const arg = n.arguments[1]; + if (arg !== undefined && ts.isObjectLiteralExpression(arg)) projects.push(arg); + } + }); + expect(projects.length).toBeGreaterThan(0); + for (const p of projects) { + for (const el of p.properties) expect(propertyName(el)).not.toBe("variables"); + } + }); + + test("an unmanaged-variables spread names a top-level const declaring `variables`", () => { + const declared = new Set(); + for (const st of source.statements) { + if (!ts.isVariableStatement(st)) continue; + for (const d of st.declarationList.declarations) { + if (ts.isIdentifier(d.name) && d.initializer !== undefined && ts.isObjectLiteralExpression(d.initializer) && d.initializer.properties.some((p) => propertyName(p) === "variables")) { + declared.add(d.name.text); + } + } + } + visit(source, (n) => { + if (ts.isSpreadAssignment(n) && ts.isIdentifier(n.expression) && /ariables/.test(n.expression.text)) { + expect(declared.has(n.expression.text)).toBe(true); + } + }); + }); + + test("every restartPolicyType is a string literal of the SDK's union", () => { + visit(source, (n) => { + if (ts.isPropertyAssignment(n) && propertyName(n) === "restartPolicyType") { + expect(ts.isStringLiteral(n.initializer)).toBe(true); + expect(SDK_RESTART_POLICY_TYPES).toContain((n.initializer as ts.StringLiteral).text); + } + }); + }); +}); + +test("the checks are not vacuous: some golden spreads the constant and some sets a restart policy", () => { + let spreads = 0; + let policies = 0; + for (const scenario of scenarios) { + visit(parse(scenario), (n) => { + if (ts.isSpreadAssignment(n) && ts.isIdentifier(n.expression) && n.expression.text === "unmanagedVariables") spreads++; + if (ts.isPropertyAssignment(n) && propertyName(n) === "restartPolicyType") policies++; + }); + } + expect(spreads).toBeGreaterThan(0); + expect(policies).toBeGreaterThan(0); +}); diff --git a/packs/railway/typescript/test/golden/railway-emit-environments/.claude/skills/deploy/SKILL.md b/packs/railway/typescript/test/golden/railway-emit-environments/.claude/skills/deploy/SKILL.md new file mode 100644 index 000000000..a80affa97 --- /dev/null +++ b/packs/railway/typescript/test/golden/railway-emit-environments/.claude/skills/deploy/SKILL.md @@ -0,0 +1,43 @@ +--- +name: deploy +description: Deploy Railway project acme-shop (shop) to production or staging from the generated deploy scripts. Use when asked to deploy, ship to Railway, rotate a secret on Railway, or check a Railway deployment. +--- + + + +# Deploy acme-shop to Railway + +Generated from the model (railway pack). Every deploy fact lives in the model; the files in +`.railway/` and `deploy/` are written from it. To change a deploy setting, change the model and +regenerate, never the generated files. + +| Environment | Service | Deploys on push to | Domains | Secrets from | +|---|---|---|---|---| +| `production` | `shop` | `main` | `shop.example.com` | none (0 secrets) | +| `staging` | `shop` | `staging` | `staging.shop.example.com` | none (0 secrets) | + +## Before the first deploy + +- `railway login`, then `railway link` in the repository (it writes `.railway/config.json`). +- A `keys-axi` identity that may read each vault scope above (`keys-axi` with no arguments shows it). +- `jq`, `npm` and `curl` on the path. +- If the service still has a Config as Code file (`railway.json` or `railway.toml`): Railway + stops reading it on 2026-12-01. Run `railway config migrate cutover` before the first plan, and + delete the old file only after cutover and the first apply. + +## Deploy + +1. `bash deploy/doctor.sh ` to see where things stand. It prints names, never values. +2. `bash deploy/sync-secrets.sh --dry-run` to see which secrets will be copied. +3. `bash deploy/deploy.sh `: copies the secrets, shows the plan of `.railway/railway.ts` + and applies it after confirmation. Read the plan before confirming: stop if it deletes a + service, a database or a volume. Add `--redeploy` to redeploy now and wait for the health + check instead of waiting for the next push. +4. `bash deploy/doctor.sh ` again. Every line should be `ok`. + +## Rules + +- Never print a secret value, put one on a command line, or paste one into a file. The vault is + the source of truth: rotate a key there, then run `deploy/sync-secrets.sh`. +- Never pass `--confirm-destructive` without a person's explicit go-ahead for that plan. +- A fact Railway's file cannot hold is listed in `deploy/unexpressed.md` with how it is carried. diff --git a/packs/railway/typescript/test/golden/railway-emit-environments/.railway/railway.ts b/packs/railway/typescript/test/golden/railway-emit-environments/.railway/railway.ts new file mode 100644 index 000000000..a63968155 --- /dev/null +++ b/packs/railway/typescript/test/golden/railway-emit-environments/.railway/railway.ts @@ -0,0 +1,81 @@ +// @generated by @metaobjectsdev/pack-railway (railway-ts) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +// Railway Infrastructure as Code for project acme-shop, from the model (railway pack). +// The `railway/iac` DSL of the `railway` npm package 3.17.0. +// +// Railway does not read this file during a deploy. It takes effect when `railway config apply` +// runs against an environment; `railway config plan` previews it. Both need the SDK beside it: +// `npm install --no-save --prefix .railway railway@3.17.0`. deploy/deploy.sh does both. +// +// A named partial: it manages only the services below. Databases and anything else it does +// not declare are left as they are, and the facts it cannot hold are in deploy/unexpressed.md. +// Variables are managed: the file declares every variable of its services, and an apply +// deletes one it does not declare. A secret is preserve(): deploy/sync-secrets.sh copies its +// value from the vault. +import { defineRailway, github, project, service } from "railway/iac"; + +export const partial = "shop"; + +export default defineRailway((ctx) => { + if (ctx.environment === "production") { + return project("acme-shop", { + resources: [ + // app.service acme::shop::Shop.server, deployed by deployment.railway acme::shop::server-production + service("shop", { + source: github("acme/shop", { branch: "main" }), + build: { + builder: "DOCKERFILE", + dockerfilePath: "server/Dockerfile", + watchPatterns: [ + "server/**", + ], + }, + deploy: { + healthcheckPath: "/health", + }, + domains: [ + { + domain: "shop.example.com", + port: 8080, + }, + ], + replicas: 2, + env: { + BANNER: "production", // value.literal banner + LOG_LEVEL: "info", // value.literal log + }, + }), + ], + }); + } + if (ctx.environment === "staging") { + return project("acme-shop", { + resources: [ + // app.service acme::shop::Shop.server, deployed by deployment.railway acme::shop::server-staging + service("shop", { + source: github("acme/shop", { branch: "staging" }), + build: { + builder: "DOCKERFILE", + dockerfilePath: "server/Dockerfile", + watchPatterns: [ + "server/**", + ], + }, + deploy: { + healthcheckPath: "/health", + }, + domains: [ + { + domain: "staging.shop.example.com", + port: 8080, + }, + ], + env: { + BANNER: "staging", // value.literal banner + LOG_LEVEL: "debug", // value.literal log + }, + }), + ], + }); + } + throw new Error(`.railway/railway.ts: the model deploys nothing to environment "${ctx.environment}" (it deploys to: production, staging)`); +}); diff --git a/packs/railway/typescript/test/golden/railway-emit-environments/deploy/deploy.sh b/packs/railway/typescript/test/golden/railway-emit-environments/deploy/deploy.sh new file mode 100644 index 000000000..a7c8c45cc --- /dev/null +++ b/packs/railway/typescript/test/golden/railway-emit-environments/deploy/deploy.sh @@ -0,0 +1,69 @@ +#!/usr/bin/env bash +# @generated by @metaobjectsdev/pack-railway (railway-deploy) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +# Deploys Railway project acme-shop to one environment from the model: +# 1. copies the secrets from the vault (deploy/sync-secrets.sh), +# 2. plans and applies `.railway/railway.ts` (`railway config plan`, then `apply`), +# 3. with --redeploy, redeploys each service and waits for its health path, +# 4. runs deploy/doctor.sh. +# A push to the deployment's branch also deploys on Railway; this script is for settings and +# secrets, and for a deploy that cannot wait for a push. --yes applies without the prompt +# (never a destructive change: Railway refuses one without --confirm-destructive). +# +# Needs: railway (logged in, run from the linked repository), keys-axi, jq, npm, curl. +# +# bash deploy/deploy.sh [--yes] [--redeploy] +set -euo pipefail +cd "$(dirname "$0")/.." + +ENVIRONMENT="${1:-}" +YES=""; REDEPLOY=0 +for arg in "${@:2}"; do + case "$arg" in + --yes) YES=--yes ;; + --redeploy) REDEPLOY=1 ;; + *) echo 'usage: bash deploy/deploy.sh [--yes] [--redeploy]' >&2; exit 2 ;; + esac +done +ensure_sdk() { + [ -d .railway/node_modules/railway ] || npm install --no-save --prefix .railway railway@3.17.0 >/dev/null +} + +# wait_healthy +wait_healthy() { + local deadline=$((SECONDS + $2)) + until curl -fsS -o /dev/null --max-time 10 "$1"; do + [ "$SECONDS" -lt "$deadline" ] || { echo "deploy: $1 did not answer 2xx within $2 seconds" >&2; return 1; } + sleep 10 + done + echo "healthy: $1" +} + +# settle : sync secrets, then plan and apply the file +settle() { + bash deploy/sync-secrets.sh "$1" + railway environment "$1" >/dev/null + ensure_sdk + railway config plan + # shellcheck disable=SC2086 # YES is empty or one word + railway config apply $YES +} + +case "$ENVIRONMENT" in + production) + settle production + if [ "$REDEPLOY" = 1 ]; then + railway redeploy --service shop --yes + wait_healthy https://shop.example.com/health 300 + fi + bash deploy/doctor.sh production + ;; + staging) + settle staging + if [ "$REDEPLOY" = 1 ]; then + railway redeploy --service shop --yes + wait_healthy https://staging.shop.example.com/health 300 + fi + bash deploy/doctor.sh staging + ;; + *) echo 'usage: bash deploy/deploy.sh [--yes] [--redeploy] (environments: production, staging)' >&2; exit 2 ;; +esac diff --git a/packs/railway/typescript/test/golden/railway-emit-environments/deploy/doctor.sh b/packs/railway/typescript/test/golden/railway-emit-environments/deploy/doctor.sh new file mode 100644 index 000000000..2176761e8 --- /dev/null +++ b/packs/railway/typescript/test/golden/railway-emit-environments/deploy/doctor.sh @@ -0,0 +1,74 @@ +#!/usr/bin/env bash +# @generated by @metaobjectsdev/pack-railway (railway-doctor) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +# Checks Railway project acme-shop against the model, for one environment, by name only: +# every secret the model declares is in the vault and on Railway; `.railway/railway.ts` +# matches what Railway runs (`railway config plan`); each domain answers on the health path. +# Exits 1 when a check fails. It prints names, never a value. +# +# Needs: railway (logged in, run from the linked repository), keys-axi, jq, npm, curl. +# +# bash deploy/doctor.sh +set -uo pipefail +cd "$(dirname "$0")/.." || exit 2 + +ENVIRONMENT="${1:-}" +FAIL=0 +ok() { echo "ok $*"; } +bad() { echo "FAIL $*"; FAIL=1; } +for tool in railway keys-axi jq npm curl; do + command -v "$tool" >/dev/null || { echo "doctor: $tool is not installed" >&2; exit 2; } +done +ensure_sdk() { + [ -d .railway/node_modules/railway ] || npm install --no-save --prefix .railway railway@3.17.0 >/dev/null +} + +# in_vault ... +in_vault() { + local names + names=$(keys-axi ls --project "$1" --env "$2" --json | jq -r '.secrets[].name') || { bad "cannot list vault scope $1/$2"; return; } + local where="$1/$2"; shift 2 + for n in "$@"; do + if grep -qx "$n" <<<"$names"; then ok "$n is in the vault ($where)"; else bad "$n is declared secret and is not in the vault ($where)"; fi + done +} + +# on_railway ... +on_railway() { + local names + names=$(railway variable list --service "$1" --environment "$2" --json | jq -r 'if type == "object" then keys[] else .[].name end') || { bad "cannot list the variables of service $1 ($2)"; return; } + local where="service $1 ($2)"; shift 2 + for n in "$@"; do + if grep -qx "$n" <<<"$names"; then ok "$n is set on $where"; else bad "$n is declared and not set on $where (run deploy/sync-secrets.sh)"; fi + done +} + +# plan_clean : the file matches Railway +plan_clean() { + railway environment "$1" >/dev/null || { bad "cannot link Railway environment $1"; return; } + ensure_sdk || { bad "cannot install the railway SDK into .railway"; return; } + railway config plan --detailed-exit-code >/dev/null 2>&1 + case $? in + 0) ok ".railway/railway.ts matches Railway ($1)" ;; + 2) bad ".railway/railway.ts differs from Railway ($1): run deploy/deploy.sh $1" ;; + *) bad "railway config plan failed ($1): run it by hand to see why" ;; + esac +} + +# answers +answers() { + if curl -fsS -o /dev/null --max-time 10 "$1"; then ok "$1 answers"; else bad "$1 does not answer 2xx"; fi +} + +case "$ENVIRONMENT" in + production) + plan_clean production + answers https://shop.example.com/health + ;; + staging) + plan_clean staging + answers https://staging.shop.example.com/health + ;; + *) echo 'usage: bash deploy/doctor.sh (environments: production, staging)' >&2; exit 2 ;; +esac + +exit "$FAIL" diff --git a/packs/railway/typescript/test/golden/railway-emit-environments/deploy/sync-secrets.sh b/packs/railway/typescript/test/golden/railway-emit-environments/deploy/sync-secrets.sh new file mode 100644 index 000000000..5c519105f --- /dev/null +++ b/packs/railway/typescript/test/golden/railway-emit-environments/deploy/sync-secrets.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# @generated by @metaobjectsdev/pack-railway (railway-sync-secrets) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. +# Copies every secret setting the model declares from the vault to Railway project acme-shop, +# for one environment. A value goes from keys-axi's environment through a pipe into +# `railway variable set --stdin`: it is never printed and never on a command line. It sets +# with --skip-deploys, so the next deploy picks the values up. +# +# Needs: keys-axi (an identity that may read the vault scope) and railway (logged in, run +# from the linked repository). +# +# bash deploy/sync-secrets.sh [--dry-run] +set -euo pipefail +cd "$(dirname "$0")/.." + +ENVIRONMENT="${1:-}" +DRY_RUN=0 +for arg in "${@:2}"; do + case "$arg" in + --dry-run) DRY_RUN=1 ;; + *) echo 'usage: bash deploy/sync-secrets.sh [--dry-run]' >&2; exit 2 ;; + esac +done + +# copy +copy() { + if [ "$DRY_RUN" = 1 ]; then echo "would copy $5 from $1/$2 to service $3 ($4)"; return; fi + # shellcheck disable=SC2016 # the inner shell expands it: the value never enters this one + keys-axi run --project "$1" --env "$2" --only "$5" -- bash -c ' + [ -n "${!1+set}" ] || { echo "sync-secrets: $1 is not in the vault scope" >&2; exit 1; } + printf %s "${!1}" | railway variable set "$1" --stdin --service "$2" --environment "$3" --skip-deploys >/dev/null + ' sync-secret "$5" "$3" "$4" + echo "copied $5 to service $3 ($4)" +} + +case "$ENVIRONMENT" in + production) + echo 'no secret settings to copy in production' + ;; + staging) + echo 'no secret settings to copy in staging' + ;; + *) echo 'usage: bash deploy/sync-secrets.sh [--dry-run] (environments: production, staging)' >&2; exit 2 ;; +esac diff --git a/packs/railway/typescript/test/golden/railway-emit-environments/deploy/unexpressed.md b/packs/railway/typescript/test/golden/railway-emit-environments/deploy/unexpressed.md new file mode 100644 index 000000000..5f6c1bb81 --- /dev/null +++ b/packs/railway/typescript/test/golden/railway-emit-environments/deploy/unexpressed.md @@ -0,0 +1,23 @@ + + +# What `.railway/railway.ts` does not hold: Railway project `acme-shop` + +Facts the model declares that Railway's Infrastructure as Code file cannot carry, or that this +file leaves to something else, each with how it is carried instead. Generated from the model: +change the model, not this file. + +## shop in production + +From deployment.railway `acme::shop::server-production`. + +| Fact | How it is carried | +|---|---| +| DNS for `shop.example.com` | The file attaches the domains to the service; the DNS record each needs (the CNAME Railway shows for it) is set at the DNS provider. deploy/doctor.sh checks each answers on the health path. | + +## shop in staging + +From deployment.railway `acme::shop::server-staging`. + +| Fact | How it is carried | +|---|---| +| DNS for `staging.shop.example.com` | The file attaches the domains to the service; the DNS record each needs (the CNAME Railway shows for it) is set at the DNS provider. deploy/doctor.sh checks each answers on the health path. | diff --git a/packs/railway/typescript/test/golden/railway-emit-one-service/deploy/unexpressed.md b/packs/railway/typescript/test/golden/railway-emit-one-service/deploy/unexpressed.md index 2e801d342..31b214f87 100644 --- a/packs/railway/typescript/test/golden/railway-emit-one-service/deploy/unexpressed.md +++ b/packs/railway/typescript/test/golden/railway-emit-one-service/deploy/unexpressed.md @@ -14,5 +14,6 @@ From deployment.railway `acme::game::server-production`. |---|---| | resource.database `db` (postgres 18) | Not declared, so the partial neither creates nor deletes it. It must exist in the Railway project under the name `db`, which every reference to it uses. | | resource.cache `cache` (redis) | Not declared, so the partial neither creates nor deletes it. It must exist in the Railway project under the name `cache`, which every reference to it uses. | +| Port `8080` (runtime.process @port) | The file carries a port only beside a domain, and this deployment has none. Railway takes the port from the service's PORT variable (or a domain's target port): set PORT=8080 on the service in Railway. References from other services to this port use the model's value. | | Secret values: `LLM_API_KEY` | Never in the file. deploy/sync-secrets.sh production copies them from the vault scope `acme-game/prod`; deploy/doctor.sh checks the names are in the vault and on Railway. | | Non-secret settings: `DATABASE_URL`, `REDIS_URL`, `LLM_MODEL` | The file leaves variables unmanaged, so these keep the value set on Railway (or the application's default). Declare a value.* node on the deployment to have the file manage variables. | diff --git a/packs/railway/typescript/test/model.test.ts b/packs/railway/typescript/test/model.test.ts index 4477f2f4b..746cbbae1 100644 --- a/packs/railway/typescript/test/model.test.ts +++ b/packs/railway/typescript/test/model.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "bun:test"; import { isMetaObject, type MetaObject } from "@metaobjectsdev/metadata"; -import { RailwayModelError, pickProject, readRailway } from "../src/index.js"; +import { RailwayModelError, pickProject, readRailway, unexpressedFacts } from "../src/index.js"; import { fixtureSources, loadModels } from "./model.js"; type Json = { "metadata.root": { package: string; children: Record>[] } }; @@ -146,3 +146,71 @@ describe("readRailway refuses what Railway cannot do", () => { expect(p).toEqual(["acme::game::Redis.url: environment variable DATABASE_URL is also acme::game::Database.url"]); }); }); + +async function readFixture(scenario: string, edit?: (children: Record>[]) => void) { + const sources = fixtureSources(scenario).map((s) => { + if (edit === undefined) return s; + const model = JSON.parse(s.json) as Json; + edit(model["metadata.root"].children); + return { id: s.id, json: JSON.stringify(model) }; + }); + const root = await loadModels(sources); + const objects = root.children().filter(isMetaObject) as MetaObject[]; + return pickProject(readRailway(root, objects))!; +} + +describe("an abstract deployment is the shared part of each environment's deployment", () => { + test("the abstract base yields no service; each environment's deployment is one", async () => { + const project = await readFixture("railway-emit-environments"); + expect(project.deployments.map((d) => `${d.environment}:${d.key}`).sort()).toEqual(["production:acme::shop::server-production", "staging:acme::shop::server-staging"]); + expect(project.environments).toEqual(["production", "staging"]); + }); + + test("each inherits the base's facts and holds its own differences; staging overrides the base's value by name", async () => { + const project = await readFixture("railway-emit-environments"); + const production = project.deployments.find((d) => d.environment === "production")!; + const staging = project.deployments.find((d) => d.environment === "staging")!; + for (const d of [production, staging]) { + expect(d.repo).toBe("acme/shop"); + expect(d.service).toBe("shop"); + expect(d.project).toBe("acme-shop"); + } + expect([production.branch, production.replicas, [...production.domains]]).toEqual(["main", 2, ["shop.example.com"]]); + expect([staging.branch, staging.replicas, [...staging.domains]]).toEqual(["staging", undefined, ["staging.shop.example.com"]]); + const value = (d: typeof production, name: string) => d.variables.find((v) => v.name === name)?.value; + expect(value(production, "LOG_LEVEL")).toBe("info"); + expect(value(staging, "LOG_LEVEL")).toBe("debug"); + expect([value(production, "BANNER"), value(staging, "BANNER")]).toEqual(["production", "staging"]); + }); + + test("a base that names an environment does not collide with its own concrete child", async () => { + const project = await readFixture("abstract-deployment-with-environment"); + expect(project.deployments.map((d) => d.key)).toEqual(["acme::shop::server-production"]); + }); +}); + +describe("a declared fact the file cannot hold is listed, not dropped", () => { + test("@branch and @checkSuites on an image source", async () => { + const project = await readFixture("railway-emit-one-service", (c) => { + const d = deployment(c); + delete d["@repo"]; + d["@image"] = "ghcr.io/acme/game:1"; + }); + const facts = unexpressedFacts(project.deployments[0]!, project.manageVariables).map((f) => f.fact); + expect(facts.some((f) => f.includes("@branch"))).toBe(true); + expect(facts.some((f) => f.includes("@checkSuites"))).toBe(true); + }); + + test("a runtime.process @port with no domain to carry it", async () => { + const project = await readFixture("railway-emit-one-service"); + const facts = unexpressedFacts(project.deployments[0]!, project.manageVariables).map((f) => f.fact); + expect(facts.some((f) => f.includes("8080") && f.includes("@port"))).toBe(true); + }); + + test("no port row when a domain carries the port, and no branch row on a repository source", async () => { + const project = await readFixture("railway-emit-two-services"); + const java = project.deployments.find((d) => d.service === "java")!; + const facts = unexpressedFacts(java, project.manageVariables).map((f) => f.fact); + expect(facts.some((f) => f.includes("@port") || f.includes("@branch"))).toBe(false); + }); +}); From feb12f295c8ec0754ff6287df1491dd1c69255c6 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 25 Nov 2026 05:05:34 -0500 Subject: [PATCH 4/4] no-mistakes(document): sync railway pack docs with generators --- packs/config/README.md | 2 +- packs/railway/README.md | 12 +++++++----- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/packs/config/README.md b/packs/config/README.md index bf5d9aaca..91dd42d9a 100644 --- a/packs/config/README.md +++ b/packs/config/README.md @@ -53,7 +53,7 @@ environment name, in the scope the vault maps to the environment being deployed. | Generator | Writes | Holds | |---|---|---| | `envExampleFile()` | `.env.example` | Every setting by name, grouped; the default of a non-secret setting; a comment line with type, required, secret and build-time | -| `keyManifestFile()` | `keys.manifest.json` | Every setting's name, model name, type, required, secret, phase and default, sorted by name; each vault and its scopes. What a deploy or doctor script compares a vault and a platform against | +| `keyManifestFile()` | `keys.manifest.json` | Every setting's name, model name, type, required, secret, phase and default, sorted by name; each vault and its scopes. A script or agent reads the names and vault scopes here without the model; the `railway` pack's deploy scripts read the model instead | | `keysAxiTomlFile({ vault? })` | `.keys-axi.toml` | The vault's backend, default scope and one `[environments.]` table per scope, the file `keys-axi` reads so `keys-axi run` needs no project flag. Name the vault when the model declares more than one | Each takes `path` and `target`. No value of a secret ever reaches their output: the model diff --git a/packs/railway/README.md b/packs/railway/README.md index a0bc0f20d..f721eda74 100644 --- a/packs/railway/README.md +++ b/packs/railway/README.md @@ -72,8 +72,9 @@ The generators refuse, naming each node, a model whose deploy Railway could not with no source or two, a secret setting with no vault (`@secrets`) or no scope for the environment, a vault other than `vault.infisical`, a value for a secret setting or for a setting nobody declared, a reference to a resource managed outside Railway or to an output its engine does -not supply, `@path` on an output that is not a URL, an `@settings` group that is not in the model, -an app with no settings in a managed file, and a partial name Railway refuses. +not supply, an `@settings` group that is not in the model, an app with no settings in a managed +file, and a partial name Railway refuses. (A `value.ref` asking for an output its producer lacks, +such as `@path` on a non-URL output, fails the load in the delivery pack.) ### Wiring @@ -119,9 +120,10 @@ export default defineConfig({ Names, domains, repositories and project names are placeholders. -The two emit fixtures are modelled on two adopters' hand-written Railway configuration (a -hand-migrated `.railway/railway.ts`, and two `railway.json` files). The bar is coverage, not -identity: `typescript/test/coverage.test.ts` evaluates the generated file and checks that every +The `railway-emit-one-service` and `railway-emit-two-services` fixtures are modelled on two +adopters' hand-written Railway configuration (a hand-migrated `.railway/railway.ts`, and two +`railway.json` files). The bar is coverage, not identity: `typescript/test/coverage.test.ts` +evaluates the generated file and checks that every fact of that configuration is in it, fact by fact (source, watch patterns, Dockerfile path, health check, restart policy, draining, variable policy). Where the generated file goes further: