@maniumek/suwgate 0.7.0 → 0.8.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/README.md CHANGED
@@ -160,8 +160,7 @@ The settings of the steps:
160
160
 
161
161
  A database that is not the compose service `db` (a `docker run` container that also creates a database per tenant) is named
162
162
  once, in the `dev` section: `dev.database.up` and `dev.database.psql` ([docs/dev.md](docs/dev.md)). `suwgate dev db up`, the
163
- `database-up` step and the `e2e` step run them instead of docker compose; in CI, the `database-command` input of `gate.yml`
164
- ([docs/ci.md](docs/ci.md)).
163
+ `database-up` step and the `e2e` step run them instead of docker compose, in CI as well ([docs/ci.md](docs/ci.md)).
165
164
 
166
165
  ### The steps of the profiles
167
166
 
@@ -1,7 +1,7 @@
1
1
  import { type Exec, type Io } from "./process.ts";
2
2
  import { type DevSettings } from "./settings.ts";
3
- import { type Fetch } from "./smoke.ts";
4
- export declare const DEV_USAGE = "usage: suwgate dev <db|logs|smoke|server|tmux|checkout-env> [arguments] (every one takes --help)\nThe dev scripts of the template as commands, configured by the dev section of suwgate.yml:\n db the local PostgreSQL of the compose file: up | down | reset | psql | logs | status\n logs why did it fail? the last warnings and errors of the server's JSON log\n smoke read-only requests against a running stack\n server the server under dotnet watch, restarted when it exits\n tmux the whole local stack in one tmux session: start [--restart] | stop\n checkout-env eval \"$(suwgate dev checkout-env)\": own test databases and e2e ports for a linked worktree";
3
+ import { type Fetch, type SmokeCiEnvironment } from "./smoke.ts";
4
+ export declare const DEV_USAGE = "usage: suwgate dev <db|logs|smoke|server|tmux|checkout-env> [arguments] (every one takes --help)\nThe dev scripts of the template as commands, configured by the dev section of suwgate.yml:\n db the local PostgreSQL of the compose file: up | down | reset | psql | logs | status\n logs why did it fail? the last warnings and errors of the server's JSON log\n smoke read-only requests against a running stack; --ci builds and starts its own stack first\n server the server under dotnet watch, restarted when it exits\n tmux the whole local stack in one tmux session: start [--restart] | stop\n checkout-env eval \"$(suwgate dev checkout-env)\": own test databases and e2e ports for a linked worktree";
5
5
  export interface DevEnvironment {
6
6
  cwd: string;
7
7
  env: Readonly<Record<string, string | undefined>>;
@@ -12,5 +12,7 @@ export interface DevEnvironment {
12
12
  interactive: boolean;
13
13
  ask: (question: string) => Promise<string>;
14
14
  loadSettings: (cwd: string) => DevSettings;
15
+ temporaryFile: SmokeCiEnvironment["temporaryFile"];
16
+ onInterrupt: SmokeCiEnvironment["onInterrupt"];
15
17
  }
16
18
  export declare function dev(argv: readonly string[], environment?: DevEnvironment): Promise<number>;
package/dist/dev/index.js CHANGED
@@ -1,17 +1,20 @@
1
1
  import { execFileSync } from "node:child_process";
2
+ import { mkdtempSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
2
5
  import { askOnTerminal, DB_USAGE, parseDb, runDb } from "./db.js";
3
6
  import { CHECKOUT_ENV_USAGE, runCheckoutEnv } from "./checkoutEnv.js";
4
7
  import { LOGS_USAGE, parseLogs, runLogs } from "./logs.js";
5
8
  import { exec, Failure, UsageError } from "./process.js";
6
9
  import { runServer, SERVER_USAGE } from "./server.js";
7
10
  import { loadSettings } from "./settings.js";
8
- import { parseSmoke, realFetch, runSmoke, SMOKE_USAGE } from "./smoke.js";
11
+ import { parseSmoke, realFetch, runSmoke, runSmokeCi, SMOKE_USAGE } from "./smoke.js";
9
12
  import { parseTmux, runTmux, TMUX_USAGE } from "./tmux.js";
10
13
  export const DEV_USAGE = `usage: suwgate dev <db|logs|smoke|server|tmux|checkout-env> [arguments] (every one takes --help)
11
14
  The dev scripts of the template as commands, configured by the dev section of suwgate.yml:
12
15
  db the local PostgreSQL of the compose file: up | down | reset | psql | logs | status
13
16
  logs why did it fail? the last warnings and errors of the server's JSON log
14
- smoke read-only requests against a running stack
17
+ smoke read-only requests against a running stack; --ci builds and starts its own stack first
15
18
  server the server under dotnet watch, restarted when it exits
16
19
  tmux the whole local stack in one tmux session: start [--restart] | stop
17
20
  checkout-env eval "$(suwgate dev checkout-env)": own test databases and e2e ports for a linked worktree`;
@@ -31,6 +34,29 @@ function repositoryRootOf(cwd) {
31
34
  return cwd;
32
35
  }
33
36
  }
37
+ function temporaryFile(name, text) {
38
+ const file = path.join(mkdtempSync(path.join(tmpdir(), "suwgate-")), name);
39
+ writeFileSync(file, text);
40
+ return file;
41
+ }
42
+ const INTERRUPTED = 130;
43
+ function onInterrupt(cleanup) {
44
+ const [program = "", ...args] = cleanup;
45
+ const stop = () => {
46
+ try {
47
+ execFileSync(program, args, { stdio: "inherit" });
48
+ }
49
+ finally {
50
+ process.exit(INTERRUPTED);
51
+ }
52
+ };
53
+ process.once("SIGINT", stop);
54
+ process.once("SIGTERM", stop);
55
+ return () => {
56
+ process.off("SIGINT", stop);
57
+ process.off("SIGTERM", stop);
58
+ };
59
+ }
34
60
  function realEnvironment() {
35
61
  return {
36
62
  cwd: process.cwd(),
@@ -42,6 +68,8 @@ function realEnvironment() {
42
68
  interactive: process.stdin.isTTY,
43
69
  ask: askOnTerminal,
44
70
  loadSettings: (cwd) => loadSettings(repositoryRootOf(cwd)),
71
+ temporaryFile,
72
+ onInterrupt,
45
73
  };
46
74
  }
47
75
  async function dispatch(command, args, environment) {
@@ -60,8 +88,20 @@ async function dispatch(command, args, environment) {
60
88
  }
61
89
  case "logs":
62
90
  return runLogs(parseLogs(args), settings(), environment.exec, io, environment.cwd);
63
- case "smoke":
64
- return runSmoke(parseSmoke(args), settings(), environment.fetch, io);
91
+ case "smoke": {
92
+ const parsed = parseSmoke(args);
93
+ if (!parsed.ci)
94
+ return runSmoke(parsed, settings(), environment.fetch, io);
95
+ const { exec, fetch } = environment;
96
+ return runSmokeCi({
97
+ settings: settings(),
98
+ exec,
99
+ fetch,
100
+ io,
101
+ temporaryFile: environment.temporaryFile,
102
+ onInterrupt: environment.onInterrupt,
103
+ });
104
+ }
65
105
  case "server":
66
106
  return runServer(args, settings(), io);
67
107
  case "tmux":
@@ -1,15 +1,33 @@
1
- import { type Io } from "./process.ts";
1
+ import { type Exec, type Io } from "./process.ts";
2
2
  import type { DevSettings, SmokeCheck } from "./settings.ts";
3
- export declare const SMOKE_USAGE = "usage: suwgate dev smoke [<base-url>] e.g. suwgate dev smoke http://127.0.0.1:8190\nSmoke test of a running stack. Read-only requests through the web's nginx, the way traffic arrives: the page answers, and\nthe server behind it answers with its database. The base url defaults to the stack's web port (dev.ports.stack);\nthe requests are dev.smoke.checks (default: /healthz and /api/health). Prints what failed and what to look at;\nthe exit code is non-zero on any failure.";
3
+ export declare const SMOKE_USAGE = "usage: suwgate dev smoke [<base-url> | --ci] e.g. suwgate dev smoke http://127.0.0.1:8190\nSmoke test of a running stack. Read-only requests through the web's nginx, the way traffic arrives: the page answers, and\nthe server behind it answers with its database. The base url defaults to the stack's web port (dev.ports.stack);\nthe requests are dev.smoke.checks (default: /healthz and /api/health). Prints what failed and what to look at;\nthe exit code is non-zero on any failure.\n --ci build the images and start the whole stack of the compose file (with dev.compose.profile) as its own compose project\n <dev.name>-ci with the image tag ci, every published port moved to a free loopback port so nothing collides with a stack\n already running on the machine; smoke-test it through the port that stands for dev.ports.stack, print the logs when\n anything fails, and always remove the project with its volumes, also when the run is interrupted";
4
4
  export type Fetch = (url: string) => Promise<{
5
5
  status: number;
6
6
  body: string;
7
7
  }>;
8
8
  export interface SmokeCommand {
9
9
  baseUrl: string | null;
10
+ ci: boolean;
10
11
  }
11
12
  export declare function parseSmoke(args: readonly string[]): SmokeCommand;
12
13
  export declare function baseUrlOf(settings: DevSettings, command: SmokeCommand): string;
13
14
  export declare const realFetch: Fetch;
14
15
  export declare function checkOne(base: string, check: SmokeCheck, fetcher: Fetch): Promise<string | null>;
15
16
  export declare function runSmoke(command: SmokeCommand, settings: DevSettings, fetcher: Fetch, io: Io): Promise<number>;
17
+ export interface PublishedPort {
18
+ service: string;
19
+ target: number;
20
+ published: string;
21
+ protocol: string;
22
+ }
23
+ export interface SmokeCiEnvironment {
24
+ settings: DevSettings;
25
+ exec: Exec;
26
+ fetch: Fetch;
27
+ io: Io;
28
+ temporaryFile: (name: string, text: string) => string;
29
+ onInterrupt: (cleanup: readonly string[]) => () => void;
30
+ }
31
+ export declare function publishedPorts(configJson: string): PublishedPort[];
32
+ export declare function loopbackOverride(ports: readonly PublishedPort[]): string;
33
+ export declare function runSmokeCi(environment: SmokeCiEnvironment): Promise<number>;
package/dist/dev/smoke.js CHANGED
@@ -1,15 +1,23 @@
1
- import { UsageError } from "./process.js";
2
- export const SMOKE_USAGE = `usage: suwgate dev smoke [<base-url>] e.g. suwgate dev smoke http://127.0.0.1:8190
1
+ import { Failure, UsageError } from "./process.js";
2
+ export const SMOKE_USAGE = `usage: suwgate dev smoke [<base-url> | --ci] e.g. suwgate dev smoke http://127.0.0.1:8190
3
3
  Smoke test of a running stack. Read-only requests through the web's nginx, the way traffic arrives: the page answers, and
4
4
  the server behind it answers with its database. The base url defaults to the stack's web port (dev.ports.stack);
5
5
  the requests are dev.smoke.checks (default: /healthz and /api/health). Prints what failed and what to look at;
6
- the exit code is non-zero on any failure.`;
6
+ the exit code is non-zero on any failure.
7
+ --ci build the images and start the whole stack of the compose file (with dev.compose.profile) as its own compose project
8
+ <dev.name>-ci with the image tag ci, every published port moved to a free loopback port so nothing collides with a stack
9
+ already running on the machine; smoke-test it through the port that stands for dev.ports.stack, print the logs when
10
+ anything fails, and always remove the project with its volumes, also when the run is interrupted`;
7
11
  const TIMEOUT_MS = 10_000;
8
12
  export function parseSmoke(args) {
9
13
  const [first, ...rest] = args;
10
- if (rest.length > 0 || first?.startsWith("-") === true)
14
+ if (rest.length > 0)
11
15
  throw new UsageError(SMOKE_USAGE);
12
- return { baseUrl: first ?? null };
16
+ if (first === "--ci")
17
+ return { baseUrl: null, ci: true };
18
+ if (first?.startsWith("-") === true)
19
+ throw new UsageError(SMOKE_USAGE);
20
+ return { baseUrl: first ?? null, ci: false };
13
21
  }
14
22
  export function baseUrlOf(settings, command) {
15
23
  return (command.baseUrl ?? `http://127.0.0.1:${settings.ports.stack}`).replace(/\/+$/, "");
@@ -48,3 +56,92 @@ export async function runSmoke(command, settings, fetcher, io) {
48
56
  }
49
57
  return failed ? 1 : 0;
50
58
  }
59
+ const CI_ENV = { IMAGE_TAG: "ci" };
60
+ function ciProject(settings) {
61
+ return `${settings.name}-ci`;
62
+ }
63
+ function composeCi(settings, override) {
64
+ return [
65
+ "docker",
66
+ "compose",
67
+ "-f",
68
+ `${settings.root}/${settings.compose.file}`,
69
+ ...(override === null ? [] : ["-f", override]),
70
+ "-p",
71
+ ciProject(settings),
72
+ "--profile",
73
+ settings.compose.profile,
74
+ ];
75
+ }
76
+ export function publishedPorts(configJson) {
77
+ const config = JSON.parse(configJson);
78
+ return Object.entries(config.services ?? {}).flatMap(([service, definition]) => (definition.ports ?? []).map((port) => ({
79
+ service,
80
+ target: port.target,
81
+ published: String(port.published ?? ""),
82
+ protocol: port.protocol ?? "tcp",
83
+ })));
84
+ }
85
+ export function loopbackOverride(ports) {
86
+ const services = [...new Set(ports.map((port) => port.service))];
87
+ const lines = services.flatMap((service) => [
88
+ ` ${service}:`,
89
+ " ports: !override",
90
+ ...ports
91
+ .filter((port) => port.service === service)
92
+ .map((port) => ` - "127.0.0.1::${String(port.target)}${port.protocol === "tcp" ? "" : `/${port.protocol}`}"`),
93
+ ]);
94
+ return ["services:", ...lines, ""].join("\n");
95
+ }
96
+ function hostPortOf(output) {
97
+ const match = /:(\d+)\s*$/m.exec(output.trim().split("\n")[0] ?? "");
98
+ return match?.[1] ?? null;
99
+ }
100
+ async function stackOf(environment) {
101
+ const { settings, exec } = environment;
102
+ const config = await exec([...composeCi(settings, null), "config", "--format", "json"], { capture: true, env: CI_ENV });
103
+ if (config.status !== 0) {
104
+ throw new Failure(`suwgate dev smoke --ci: the compose file does not resolve: ${composeCi(settings, null).join(" ")} config`);
105
+ }
106
+ const ports = publishedPorts(config.stdout);
107
+ const stack = String(settings.ports.stack);
108
+ const entry = ports.find((port) => port.published === stack);
109
+ if (entry === undefined) {
110
+ throw new Failure(`suwgate dev smoke --ci: no service of ${settings.compose.file} publishes dev.ports.stack (${stack}): publish the web's port as ${stack}, or set dev.ports.stack in suwgate.yml to the port the web publishes`, 2);
111
+ }
112
+ return { ports, entry };
113
+ }
114
+ async function smokeStack(compose, entry, environment) {
115
+ const { exec, io } = environment;
116
+ const up = await exec([...compose, "up", "-d", "--build", "--wait"], { env: CI_ENV });
117
+ if (up.status !== 0) {
118
+ io.err(`FAIL the stack did not start healthy (${compose.join(" ")} up -d --build --wait); its logs follow`);
119
+ return 1;
120
+ }
121
+ const port = await exec([...compose, "port", entry.service, String(entry.target)], { capture: true, env: CI_ENV });
122
+ const hostPort = port.status === 0 ? hostPortOf(port.stdout) : null;
123
+ if (hostPort === null) {
124
+ io.err(`FAIL ${entry.service} publishes no port for ${String(entry.target)} (${compose.join(" ")} port); its logs follow`);
125
+ return 1;
126
+ }
127
+ return runSmoke({ baseUrl: `http://127.0.0.1:${hostPort}`, ci: false }, environment.settings, environment.fetch, io);
128
+ }
129
+ export async function runSmokeCi(environment) {
130
+ const { settings, exec, io } = environment;
131
+ const { ports, entry } = await stackOf(environment);
132
+ const compose = composeCi(settings, environment.temporaryFile("compose.ci.yaml", loopbackOverride(ports)));
133
+ const down = [...compose, "down", "--remove-orphans", "--volumes"];
134
+ const release = environment.onInterrupt(down);
135
+ try {
136
+ const status = await smokeStack(compose, entry, environment);
137
+ if (status !== 0)
138
+ await exec([...compose, "logs", "--no-color"], { env: CI_ENV });
139
+ return status;
140
+ }
141
+ finally {
142
+ release();
143
+ const removed = await exec(down, { env: CI_ENV });
144
+ if (removed.status !== 0)
145
+ io.err(`suwgate dev smoke --ci: the project ${ciProject(settings)} was not removed: ${down.join(" ")}`);
146
+ }
147
+ }
@@ -1,19 +1,19 @@
1
- import { databaseUpCommand, has, script, suwgate } from "./shell.js";
1
+ import { databaseUpCommand, has, hasDevSection, script, suwgate } from "./shell.js";
2
2
  export const DATABASE_UP = "database-up";
3
3
  const COMPOSE_FILES = ["compose.yaml", "compose.yml", "docker-compose.yaml", "docker-compose.yml"];
4
- const IN_CI = 'if [ -n "${CI:-}" ]; then echo "CI: the workflow starts the database (database: true of the reusable gate workflow)"; exit 0; fi';
5
- const UP = script([
6
- IN_CI,
4
+ const COMPOSE_UP = script([
7
5
  "docker compose --profile db up -d --wait db >/dev/null 2>&1 || {",
8
6
  ' echo "postgres did not start — see: docker compose --profile db logs db" >&2',
9
7
  " exit 1",
10
8
  "}",
11
9
  ]);
12
- const OWN_UP = script([IN_CI, `${suwgate("dev db up")} >/dev/null`]);
10
+ const DEV_UP = `${suwgate("dev db up")} >/dev/null`;
13
11
  function databaseUp(context) {
14
12
  if (databaseUpCommand(context) !== null)
15
- return OWN_UP;
16
- return composeFile(context) ? UP : null;
13
+ return DEV_UP;
14
+ if (!composeFile(context))
15
+ return null;
16
+ return hasDevSection(context) ? DEV_UP : COMPOSE_UP;
17
17
  }
18
18
  export function composeFile(context) {
19
19
  return COMPOSE_FILES.some((file) => has(context, file));
@@ -21,7 +21,7 @@ export function composeFile(context) {
21
21
  export const databaseSteps = [
22
22
  {
23
23
  id: DATABASE_UP,
24
- title: "the local database for the tests (docker compose --profile db up --wait db, or dev.database.up of suwgate.yml; in CI the workflow starts it)",
24
+ title: "the database for the tests, locally and in CI (suwgate dev db up with a dev section in suwgate.yml, else docker compose --profile db up --wait db)",
25
25
  profile: "database",
26
26
  needs: ["docker"],
27
27
  run: databaseUp,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maniumek/suwgate",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "One quality gate for every repository: suwgate check runs the steps of the repository's profiles and its guards, configured in suwgate.yml",
5
5
  "license": "MIT",
6
6
  "author": "Manomenu",