Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/chant.yml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ jobs:
npm run --prefix lexicons/helm prepack
npm run --prefix lexicons/docker prepack
npm run --prefix lexicons/temporal prepack
npm run --prefix lexicons/fly prepack

- name: Typecheck
run: npx tsc --noEmit -p packages/core/tsconfig.json
Expand Down Expand Up @@ -118,6 +119,7 @@ jobs:
npm run --prefix lexicons/helm prepack
npm run --prefix lexicons/docker prepack
npm run --prefix lexicons/temporal prepack
npm run --prefix lexicons/fly prepack

- name: Run tests
run: npx vitest run
Expand Down
10 changes: 7 additions & 3 deletions lexicons/fly/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ export { flyPlugin } from "./plugin";
// Serializer
export { flySerializer } from "./serializer";

// Generated resources — export everything from generated index
// After running `chant generate`, this re-exports all resource classes
// export * from "./generated/index";
// Ownership marker convention (machine config.metadata keys)
export { FLY_METADATA_OWNERSHIP_KEYS } from "./ownership";

// Generated resources — export everything from generated index.
// Provides `App`, `Machine`, `Volume`, and the property types
// (`MachineConfig`, `MachineGuest`, `MachineService`, ...) for authoring.
export * from "./generated/index";
17 changes: 17 additions & 0 deletions lexicons/fly/src/ownership.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* The fly lexicon's ownership marker convention. Fly machines carry ownership
* in their `config.metadata` map (a flat `Record<string, string>`), not in
* cloud tags or k8s labels. Decision D2 fixes the managed-by key as the bare
* `managed-by`, so chant's marker uses that key with the stack/env keys
* namespaced alongside it. Core owns the generic stamp/detect logic
* (@intentius/chant/ownership); this is the fly-specific key naming it stamps.
*/

import type { ChannelKeys } from "@intentius/chant/ownership";

/** Machine `config.metadata` keys for chant's ownership markers (D2). */
export const FLY_METADATA_OWNERSHIP_KEYS: ChannelKeys = {
managedBy: "managed-by",
stack: "chant-stack",
env: "chant-env",
};
107 changes: 105 additions & 2 deletions lexicons/fly/src/serializer.test.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,117 @@
import { describe, expect, it } from "vitest";
import type { Declarable } from "@intentius/chant";
import { flySerializer } from "./serializer";
import { App, Machine, MachineConfig, MachineGuest } from "./generated/index";

/** Author a map of declarables keyed by logical name, in insertion order. */
function stack(...entries: Array<[string, unknown]>): Map<string, Declarable> {
return new Map(entries as Array<[string, Declarable]>);
}

describe("fly serializer", () => {
it("serializes an empty map to valid JSON", () => {
const result = flySerializer.serialize(new Map());
expect(typeof result).toBe("string");
expect(() => JSON.parse(result)).not.toThrow();
expect(JSON.parse(result)).toEqual({});
});

it("has the correct name", () => {
it("has the correct name and rule prefix", () => {
expect(flySerializer.name).toBe("fly");
expect(flySerializer.rulePrefix).toBe("FLY");
});

it("emits the App create body with app_name/org_slug (flaps CreateAppRequest)", () => {
const entities = stack([
"web",
new App({ name: "my-app", org_slug: "acme" }),
]);

const out = JSON.parse(flySerializer.serialize(entities));
expect(out.web).toEqual({
endpoint: "/v1/apps",
method: "POST",
body: { app_name: "my-app", org_slug: "acme" },
});
});

it("falls back to the entity name for app_name when no explicit name", () => {
const out = JSON.parse(flySerializer.serialize(stack(["billing", new App({ org_slug: "acme" })])));
expect(out.billing.body.app_name).toBe("billing");
});

it("emits the Machine create body with config image/guest and endpoints the owning app", () => {
const entities = stack(
["app", new App({ name: "my-app", org_slug: "acme" })],
[
"api",
new Machine({
name: "api-1",
region: "iad",
config: new MachineConfig({
image: "flyio/hellofly:latest",
guest: new MachineGuest({ cpu_kind: "shared", cpus: 1, memory_mb: 256 }),
env: { LOG_LEVEL: "info" },
}),
}),
],
);

const out = JSON.parse(flySerializer.serialize(entities));
expect(out.api.endpoint).toBe("/v1/apps/my-app/machines");
expect(out.api.method).toBe("POST");
expect(out.api.body.name).toBe("api-1");
expect(out.api.body.region).toBe("iad");
expect(out.api.body.config.image).toBe("flyio/hellofly:latest");
expect(out.api.body.config.guest).toEqual({ cpu_kind: "shared", cpus: 1, memory_mb: 256 });
expect(out.api.body.config.env).toEqual({ LOG_LEVEL: "info" });
});

it("stamps managed-by: chant on every machine, including one with no metadata", () => {
const entities = stack(
["app", new App({ name: "my-app" })],
["bare", new Machine({ config: new MachineConfig({ image: "nginx" }) })],
[
"withMeta",
new Machine({
config: new MachineConfig({ image: "nginx", metadata: { role: "cache" } }),
}),
],
);

const out = JSON.parse(flySerializer.serialize(entities));
// No user metadata → marker still present.
expect(out.bare.body.config.metadata["managed-by"]).toBe("chant");
// User metadata is preserved and the marker is merged in.
expect(out.withMeta.body.config.metadata["managed-by"]).toBe("chant");
expect(out.withMeta.body.config.metadata.role).toBe("cache");
});

it("stamps the stack/env ownership identity when context.ownership is passed", () => {
const entities = stack(
["app", new App({ name: "my-app" })],
["api", new Machine({ config: new MachineConfig({ image: "nginx" }) })],
);

const out = JSON.parse(
flySerializer.serialize(entities, undefined, { ownership: { stack: "billing", env: "prod" } }),
);
const meta = out.api.body.config.metadata;
expect(meta["managed-by"]).toBe("chant");
expect(meta["chant-stack"]).toBe("billing");
expect(meta["chant-env"]).toBe("prod");
});

it("matches the mudflaps CreateMachineRequest field names (name/region/config)", () => {
const entities = stack(
["app", new App({ name: "my-app" })],
[
"api",
new Machine({ name: "api-1", region: "iad", config: new MachineConfig({ image: "nginx" }) }),
],
);
const body = JSON.parse(flySerializer.serialize(entities)).api.body;
// Only fields present on flaps CreateMachineRequest / MachineConfig.
expect(Object.keys(body).sort()).toEqual(["config", "name", "region"]);
expect(Object.keys(body.config.guest ?? {})).toEqual([]);
});
});
182 changes: 170 additions & 12 deletions lexicons/fly/src/serializer.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,182 @@
import type { Serializer, Declarable } from "@intentius/chant";

/**
* fly serializer — produces minimal JSON output.
* fly (Machines API / "flaps") serializer.
*
* Turns declared `App` and `Machine` resources into the JSON create bodies the
* flaps REST API accepts, so #739's applier can POST them straight through and
* mudflaps (#740) can round-trip them.
*
* Output shape — a JSON object keyed by entity name. Each value is a single
* flaps request:
*
* {
* "<entityName>": {
* "endpoint": "/v1/apps", // or /v1/apps/{app}/machines
* "method": "POST",
* "body": { ... } // the create body
* }
* }
*
* TODO: Replace with your lexicon's output format.
* Field names are taken from mudflaps' Go structs (the wire oracle), which win
* over the OpenAPI-generated TypeScript names:
* - App → CreateAppRequest `{ app_name, org_slug? }` (NOT `name`).
* - Machine→ CreateMachineRequest `{ name?, region?, config?, skip_launch? }`;
* `config` is the full MachineConfig. The owning app is a URL path segment,
* not a body field, so it lands in `endpoint`.
*
* D2: every serialized Machine carries the `managed-by: chant` ownership marker
* (plus the stack/env identity from `context.ownership`) merged into
* `config.metadata`, even when the user supplied no metadata.
*/

import type { Declarable } from "@intentius/chant/declarable";
import { isPropertyDeclarable } from "@intentius/chant/declarable";
import type { Serializer, SerializeContext } from "@intentius/chant/serializer";
import type { LexiconOutput } from "@intentius/chant/lexicon-output";
import { ownershipEntries, OWNERSHIP_MANAGED_BY_VALUE } from "@intentius/chant/ownership";
import { walkValue, type SerializerVisitor } from "@intentius/chant/serializer-walker";
import { FLY_METADATA_OWNERSHIP_KEYS } from "./ownership";

const APP_ENTITY_TYPE = "Fly::Machines::App";
const MACHINE_ENTITY_TYPE = "Fly::Machines::Machine";

/** A single flaps REST call the applier can issue verbatim. */
interface FlapsRequest {
endpoint: string;
method: "POST";
body: Record<string, unknown>;
}

/**
* Visitor for the generic serializer walker. Property declarables (MachineConfig,
* MachineGuest, MachineService, ...) are unwrapped to plain objects; resource
* references resolve to their logical name.
*/
function flyVisitor(): SerializerVisitor {
return {
attrRef: (name) => name,
resourceRef: (name) => name,
propertyDeclarable: (entity, walk) => {
const props = (entity as unknown as { props?: unknown }).props;
if (!props || typeof props !== "object") return undefined;
const result: Record<string, unknown> = {};
for (const [key, value] of Object.entries(props)) {
if (value !== undefined) result[key] = walk(value);
}
return Object.keys(result).length > 0 ? result : undefined;
},
};
}

function readProps(entity: Declarable): Record<string, unknown> {
const props = (entity as unknown as { props?: unknown }).props;
return props && typeof props === "object" ? (props as Record<string, unknown>) : {};
}

/** The app_name flaps expects: an explicit `name` prop, else the entity name. */
function appName(entity: Declarable, entityName: string): string {
const name = readProps(entity).name;
return typeof name === "string" ? name : entityName;
}

/**
* fly flaps serializer.
*/
export const flySerializer: Serializer = {
name: "fly",
rulePrefix: "FLY",

serialize(entities: Map<string, Declarable>): string {
const resources: Record<string, unknown> = {};
serialize(
entities: Map<string, Declarable>,
_outputs?: LexiconOutput[],
context?: SerializeContext,
): string {
const entityNames = new Map<Declarable, string>();
for (const [name, entity] of entities) entityNames.set(entity, name);
const visitor = flyVisitor();

// D2 ownership marker. `managed-by: chant` is always stamped; stack/env are
// added when the build threads an ownership marker through the context.
const ownershipMeta: Record<string, string> = context?.ownership
? ownershipEntries(FLY_METADATA_OWNERSHIP_KEYS, context.ownership)
: { [FLY_METADATA_OWNERSHIP_KEYS.managedBy]: OWNERSHIP_MANAGED_BY_VALUE };

// Resolve which app a machine belongs to (a URL path segment, not a body
// field). A machine may name its app explicitly via an `app` prop (a string
// or an `App` reference); otherwise, when the stack declares exactly one
// app, machines default to it. Failing both, a `{app}` placeholder is left
// for the applier to fill.
const apps: Array<[string, Declarable]> = [];
for (const [name, entity] of entities) {
if ((entity as unknown as { entityType?: string }).entityType === APP_ENTITY_TYPE) {
apps.push([name, entity]);
}
}
const soleApp = apps.length === 1 ? appName(apps[0][1], apps[0][0]) : undefined;

const resolveMachineApp = (machine: Declarable): string => {
const app = readProps(machine).app;
if (typeof app === "string") return app;
if (app && typeof app === "object" && "entityType" in app) {
const decl = app as Declarable;
return appName(decl, entityNames.get(decl) ?? "{app}");
}
return soleApp ?? "{app}";
};

const requests: Record<string, FlapsRequest> = {};

for (const [name, entity] of entities) {
if (isPropertyDeclarable(entity)) continue;
const entityType = (entity as unknown as { entityType?: string }).entityType;
const props = readProps(entity);

if (entityType === APP_ENTITY_TYPE) {
const body: Record<string, unknown> = { app_name: appName(entity, name) };
if (props.org_slug !== undefined) body.org_slug = props.org_slug;
if (props.network !== undefined) body.network = props.network;
if (props.enable_subdomains !== undefined) body.enable_subdomains = props.enable_subdomains;
requests[name] = { endpoint: "/v1/apps", method: "POST", body };
continue;
}

if (entityType === MACHINE_ENTITY_TYPE) {
const walkedConfig = props.config
? walkValue(props.config, entityNames, visitor)
: undefined;
const config: Record<string, unknown> =
walkedConfig && typeof walkedConfig === "object"
? { ...(walkedConfig as Record<string, unknown>) }
: {};

// Merge the ownership marker into config.metadata. The marker wins over
// any colliding user key so ownership can never be silently unset.
const userMeta =
config.metadata && typeof config.metadata === "object"
? (config.metadata as Record<string, unknown>)
: {};
config.metadata = { ...userMeta, ...ownershipMeta };

// Spread the create-body fields (name, region, skip_launch, ...) and
// override with the walked config. `app` is our association hint, not a
// flaps field, so it is dropped.
const body: Record<string, unknown> = {};
for (const [key, value] of Object.entries(props)) {
if (key === "config" || key === "app" || value === undefined) continue;
body[key] = walkValue(value, entityNames, visitor);
}
body.config = config;

requests[name] = {
endpoint: `/v1/apps/${resolveMachineApp(entity)}/machines`,
method: "POST",
body,
};
continue;
}

for (const [entityName, entity] of entities) {
resources[entityName] = {
type: entity.entityType,
// TODO: Convert entity properties to your output format
};
// Other resource types (e.g. Volume) are out of scope for #738.
}

return JSON.stringify({ resources }, null, 2);
return JSON.stringify(requests, null, 2);
},
};
9 changes: 8 additions & 1 deletion lexicons/fly/src/spec/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
import { join } from "path";
import { homedir } from "os";
import { fetchWithCache } from "@intentius/chant/codegen/fetch";

/** Fly's published Machines API (flaps) OpenAPI 3.0.1 spec. */
const SCHEMA_URL = "https://docs.machines.dev/openapi.json";
const CACHE_FILE = ".cache/openapi3.json";
/**
* Cache under `~/.chant` (like the k8s lexicon) so CI's `~/.chant` schema
* cache covers it — a `docs.machines.dev` hiccup then falls back to the cache
* instead of failing the generate step.
*/
const CACHE_FILE = join(homedir(), ".chant", "fly-machines-openapi.json");

/**
* Fetch the flaps OpenAPI spec and return it as a Map<typeName, Buffer>
Expand Down