@execution-associates/isb-alchemy 0.0.0-stage → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/Project.ts ADDED
@@ -0,0 +1,87 @@
1
+ import * as Provider from "alchemy/Provider";
2
+ import { Resource } from "alchemy/Resource";
3
+ import * as Effect from "effect/Effect";
4
+ import { call, callFound } from "./Client.ts";
5
+ import { replaceWhen } from "./Replace.ts";
6
+
7
+ export interface ProjectProps {
8
+ /** The project's name in isb: lowercase letters, digits and `-`. */
9
+ name: string;
10
+ description?: string;
11
+ /**
12
+ * The environments to make sure exist. Each one runs as its own stack,
13
+ * `<project>-<environment>`.
14
+ * @default ["production"]
15
+ */
16
+ environments?: string[];
17
+ }
18
+
19
+ export interface ProjectAttributes {
20
+ name: string;
21
+ environments: string[];
22
+ }
23
+
24
+ export type Project = Resource<"Isb.Project", ProjectProps, ProjectAttributes>;
25
+
26
+ interface ProjectRow {
27
+ name: string;
28
+ environments: (string | { name: string })[];
29
+ }
30
+
31
+ const environmentsOf = (p: ProjectRow): string[] =>
32
+ p.environments.map((e) => (typeof e === "string" ? e : e.name));
33
+
34
+ const find = (name: string) =>
35
+ call<{ projects: ProjectRow[] }>("project_list").pipe(
36
+ Effect.map((r) => r.projects.find((p) => p.name === name)),
37
+ );
38
+
39
+ /**
40
+ * An isb project: the group apps and stacks belong to, with one or more
41
+ * environments.
42
+ *
43
+ * ```typescript
44
+ * const shop = yield* Isb.Project("shop", {
45
+ * name: "shop",
46
+ * environments: ["production", "staging"],
47
+ * });
48
+ * ```
49
+ *
50
+ * Removing an environment from `environments` leaves it in isb. Destroying
51
+ * the project deletes it only once it holds no apps and no stacks.
52
+ */
53
+ export const Project = Resource<Project>("Isb.Project");
54
+
55
+ export const ProjectProvider = () =>
56
+ Provider.succeed(Project, {
57
+ stables: ["name"],
58
+ // A project cannot be renamed.
59
+ diff: replaceWhen<ProjectProps>((p) => p.name),
60
+ reconcile: Effect.fn(function* ({ news }) {
61
+ const wanted = news.environments ?? ["production"];
62
+ let project = yield* find(news.name);
63
+ if (project === undefined) {
64
+ yield* call("project_create", {
65
+ name: news.name,
66
+ description: news.description ?? "",
67
+ environments: wanted,
68
+ });
69
+ project = yield* find(news.name);
70
+ }
71
+ const have = project ? environmentsOf(project) : [];
72
+ for (const env of wanted.filter((e) => !have.includes(e))) {
73
+ yield* call("environment_create", { project: news.name, name: env });
74
+ have.push(env);
75
+ }
76
+ return { name: news.name, environments: have };
77
+ }),
78
+ delete: Effect.fn(function* ({ output }) {
79
+ yield* callFound("project_delete", { name: output.name });
80
+ }),
81
+ read: Effect.fn(function* ({ olds, output }) {
82
+ const name = output?.name ?? olds?.name;
83
+ if (name === undefined) return undefined;
84
+ const project = yield* find(name);
85
+ return project && { name, environments: environmentsOf(project) };
86
+ }),
87
+ });
@@ -0,0 +1,30 @@
1
+ import * as Provider from "alchemy/Provider";
2
+ import * as Layer from "effect/Layer";
3
+ import { App, AppProvider } from "./App.ts";
4
+ import { type CredentialsInput, fromConfig, fromEnv } from "./Client.ts";
5
+ import { Project, ProjectProvider } from "./Project.ts";
6
+ import { Secret, SecretProvider } from "./Secret.ts";
7
+ import { Stack, StackProvider } from "./Stack.ts";
8
+
9
+ export class Providers extends Provider.ProviderCollection<Providers>()("Isb") {}
10
+
11
+ /**
12
+ * The isb resources (`Project`, `Secret`, `App`, `Stack`) and the
13
+ * connection they use: the one given, or `ISB_URL`, `ISB_TOKEN` and
14
+ * `ISB_ORG` from the environment.
15
+ *
16
+ * ```typescript
17
+ * export default Alchemy.Stack(
18
+ * "shop",
19
+ * { providers: Isb.providers(), state: Alchemy.localState() },
20
+ * Effect.gen(function* () { ... }),
21
+ * );
22
+ * ```
23
+ */
24
+ export const providers = (connection?: CredentialsInput) =>
25
+ Layer.effect(Providers, Provider.collection([App, Project, Secret, Stack])).pipe(
26
+ Layer.provide(
27
+ Layer.mergeAll(AppProvider(), ProjectProvider(), SecretProvider(), StackProvider()),
28
+ ),
29
+ Layer.provideMerge(connection ? fromConfig(connection) : fromEnv()),
30
+ );
package/src/Replace.ts ADDED
@@ -0,0 +1,18 @@
1
+ import { isResolved, type ReplaceDiff } from "alchemy/Diff";
2
+ import type { Input } from "alchemy/Input";
3
+ import * as Effect from "effect/Effect";
4
+
5
+ /**
6
+ * A provider `diff` for resources whose identity isb cannot change: when
7
+ * what `identity` returns differs between the old and new props, the
8
+ * resource is replaced. Anything else is left to alchemy's own comparison
9
+ * of the props.
10
+ */
11
+ export const replaceWhen =
12
+ <P>(identity: (props: P) => unknown, options: { deleteFirst?: boolean } = {}) =>
13
+ ({ news, olds }: { news: Input<P>; olds: P }): Effect.Effect<ReplaceDiff | undefined> =>
14
+ Effect.sync(() => {
15
+ if (!isResolved(news) || olds === undefined) return undefined;
16
+ const same = JSON.stringify(identity(news)) === JSON.stringify(identity(olds));
17
+ return same ? undefined : { action: "replace", deleteFirst: options.deleteFirst };
18
+ });
package/src/Secret.ts ADDED
@@ -0,0 +1,73 @@
1
+ import * as Provider from "alchemy/Provider";
2
+ import { Resource } from "alchemy/Resource";
3
+ import * as Effect from "effect/Effect";
4
+ import * as Redacted from "effect/Redacted";
5
+ import { call, callFound } from "./Client.ts";
6
+ import { replaceWhen } from "./Replace.ts";
7
+
8
+ export interface SecretProps {
9
+ /** The secret's name in the org's store. */
10
+ name: string;
11
+ /** Its value. Use `Redacted.make(...)` or `Config.redacted(...)`. */
12
+ value: Redacted.Redacted<string>;
13
+ }
14
+
15
+ export interface SecretAttributes {
16
+ name: string;
17
+ /** The version isb holds now. */
18
+ version: number;
19
+ /** SHA-256 of the value last written, to tell whether it changed. */
20
+ valueHash: string;
21
+ /** What an app's `env` takes to read this secret: `{ secret: name }`. */
22
+ ref: { secret: string };
23
+ }
24
+
25
+ export type Secret = Resource<"Isb.Secret", SecretProps, SecretAttributes>;
26
+
27
+ const sha256 = (text: string) =>
28
+ Effect.promise(async () => {
29
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
30
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
31
+ });
32
+
33
+ const base64 = (text: string) => Buffer.from(text, "utf8").toString("base64");
34
+
35
+ /**
36
+ * A secret in the org's store. isb holds the value; apps and stacks name
37
+ * it, and it reaches them as the one variable or file that asks for it.
38
+ *
39
+ * ```typescript
40
+ * const dbUrl = yield* Isb.Secret("db-url", {
41
+ * name: "shop-db-url",
42
+ * value: yield* Config.redacted("DATABASE_URL"),
43
+ * });
44
+ * yield* Isb.App("web", { ..., env: { DATABASE_URL: dbUrl.ref } });
45
+ * ```
46
+ *
47
+ * A new value is a new version in isb, and the services that use the
48
+ * secret roll (or do what their `on_change` says). The same value again
49
+ * writes nothing.
50
+ */
51
+ export const Secret = Resource<Secret>("Isb.Secret");
52
+
53
+ export const SecretProvider = () =>
54
+ Provider.succeed(Secret, {
55
+ stables: ["name", "ref"],
56
+ diff: replaceWhen<SecretProps>((p) => p.name),
57
+ reconcile: Effect.fn(function* ({ news, output }) {
58
+ const valueHash = yield* sha256(Redacted.value(news.value));
59
+ const observed = yield* callFound<{ version: number }>("secret_inspect", {
60
+ name: news.name,
61
+ });
62
+ // The value cannot be read back, so what tells a change is the hash
63
+ // of what this resource last wrote.
64
+ if (observed === undefined || output?.valueHash !== valueHash) {
65
+ yield* call("secret_set", { name: news.name, value: base64(Redacted.value(news.value)) });
66
+ }
67
+ const now = yield* call<{ version: number }>("secret_inspect", { name: news.name });
68
+ return { name: news.name, version: now.version, valueHash, ref: { secret: news.name } };
69
+ }),
70
+ delete: Effect.fn(function* ({ output }) {
71
+ yield* callFound("secret_delete", { name: output.name });
72
+ }),
73
+ });
package/src/Stack.ts ADDED
@@ -0,0 +1,124 @@
1
+ import * as Provider from "alchemy/Provider";
2
+ import { Resource } from "alchemy/Resource";
3
+ import * as Effect from "effect/Effect";
4
+ import { call, callFound, IsbError } from "./Client.ts";
5
+ import { replaceWhen } from "./Replace.ts";
6
+
7
+ export interface StackProps {
8
+ /** The stack's name: lowercase letters, digits and `-`, at most 30. */
9
+ name: string;
10
+ /** The compose file, as YAML text. */
11
+ compose: string;
12
+ /** Values for `${VAR}` in the compose file. */
13
+ vars?: Record<string, string>;
14
+ /**
15
+ * The project a new stack belongs to. Default: one named like the stack,
16
+ * which isb makes and which is deleted with the stack.
17
+ */
18
+ project?: string;
19
+ /** The project's environment. Default: `production`. */
20
+ environment?: string;
21
+ /**
22
+ * Delete the stack's named volumes when the stack is destroyed.
23
+ * @default false
24
+ */
25
+ removeVolumes?: boolean;
26
+ /**
27
+ * How long the services may take to converge, in seconds.
28
+ * @default 600
29
+ */
30
+ timeoutSeconds?: number;
31
+ }
32
+
33
+ export interface StackAttributes {
34
+ name: string;
35
+ /** Each service's revision: it changes when the service is replaced. */
36
+ revisions: Record<string, string>;
37
+ }
38
+
39
+ export type Stack = Resource<"Isb.Stack", StackProps, StackAttributes>;
40
+
41
+ interface Status {
42
+ converged: boolean;
43
+ services: { service: string; rev: string; state: string; message?: string }[];
44
+ }
45
+
46
+ /** Poll until every service has converged, or one has given up. */
47
+ const settle = (name: string, timeoutSeconds: number) =>
48
+ Effect.gen(function* () {
49
+ const deadline = Date.now() + timeoutSeconds * 1000;
50
+ while (true) {
51
+ const status = yield* call<Status>("stack_status", { name });
52
+ if (status.converged) return status;
53
+ const stuck = status.services.filter((s) => s.state === "paused" || s.state === "failing");
54
+ const late = Date.now() > deadline;
55
+ if (stuck.length > 0 || late) {
56
+ const why = (
57
+ stuck.length > 0 ? stuck : status.services.filter((s) => s.state !== "converged")
58
+ )
59
+ .map((s) => `${s.service}: ${s.state}${s.message ? ` (${s.message})` : ""}`)
60
+ .join("; ");
61
+ return yield* Effect.fail(
62
+ new IsbError({
63
+ tool: "stack_deploy",
64
+ code: late && stuck.length === 0 ? "timeout" : "deploy_failed",
65
+ status: 0,
66
+ message: `isb: stack ${name} did not converge: ${why}`,
67
+ }),
68
+ );
69
+ }
70
+ yield* Effect.sleep("1 second");
71
+ }
72
+ });
73
+
74
+ /**
75
+ * A compose file run as an isb stack: long-running services with
76
+ * replicas, health checks, a load balancer on published ports and rolling
77
+ * updates.
78
+ *
79
+ * ```typescript
80
+ * yield* Isb.Stack("wiki", {
81
+ * name: "wiki",
82
+ * compose: yield* Effect.promise(() => Bun.file("compose.yaml").text()),
83
+ * vars: { TAG: "1.27" },
84
+ * });
85
+ * ```
86
+ *
87
+ * A deploy replaces only the services whose settings or image digest
88
+ * changed, so deploying the same file again rolls nothing. A stack's name
89
+ * cannot change; changing it replaces the stack.
90
+ */
91
+ export const Stack = Resource<Stack>("Isb.Stack");
92
+
93
+ export const StackProvider = () =>
94
+ Provider.succeed(Stack, {
95
+ stables: ["name"],
96
+ diff: replaceWhen<StackProps>((p) => p.name),
97
+ reconcile: Effect.fn(function* ({ news }) {
98
+ yield* call("stack_deploy", {
99
+ name: news.name,
100
+ compose: news.compose,
101
+ ...(news.vars && { vars: news.vars }),
102
+ ...(news.project && { project: news.project }),
103
+ ...(news.environment && { environment: news.environment }),
104
+ });
105
+ const status = yield* settle(news.name, news.timeoutSeconds ?? 600);
106
+ return {
107
+ name: news.name,
108
+ revisions: Object.fromEntries(status.services.map((s) => [s.service, s.rev])),
109
+ };
110
+ }),
111
+ delete: Effect.fn(function* ({ olds, output }) {
112
+ yield* callFound("stack_remove", {
113
+ name: output.name,
114
+ volumes: olds.removeVolumes ?? false,
115
+ });
116
+ // A stack deployed without `project` got one of its own name from
117
+ // isb. It goes with the stack, unless something else moved in.
118
+ if (olds.project === undefined) {
119
+ yield* call("project_delete", { name: output.name }).pipe(
120
+ Effect.catchTag("IsbError", () => Effect.void),
121
+ );
122
+ }
123
+ }),
124
+ });
package/src/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ export * from "./App.ts";
2
+ export * from "./Client.ts";
3
+ export * from "./Project.ts";
4
+ export * from "./Providers.ts";
5
+ export * from "./Secret.ts";
6
+ export * from "./Stack.ts";