@maniumek/suwgate 0.6.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
@@ -47,7 +47,7 @@ exceptions:
47
47
  across the board overrides it with `SUWGATE_QUICK_LIMIT=<seconds>`.
48
48
  - `exceptions` let one target through one guard, always with a `reason`; `suwgate check` counts them in its report, and an
49
49
  exception that no longer matches anything fails the gate until it is deleted. Two optional fields, for the repository guards
50
- (the .NET packages match by target only):
50
+ and the .NET guards alike:
51
51
  - `message` narrows it to the target's findings whose message contains that text, so a second finding in the same file still
52
52
  fails: `{ guard: no-raw-colors, target: Myapp.Web/src/mail.tsx, message: "#1e66f5", reason: … }`.
53
53
  - `once: true` makes it a one-time exception, for a finding that goes away once the change is on master, such as an
@@ -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
 
@@ -257,15 +256,16 @@ the solution, `layers.json`, the sources and the migrations itself, and takes fr
257
256
  - `test-timing` (`dotnet`, `web`, `library`): no test measures, sleeps on, waits for or limits real time, because a test that
258
257
  waits on the clock flakes on a slow machine and a speed promise, in milliseconds or in steps counted instead of them, does not
259
258
  belong on the gate. It reads the `.cs` files of the `*.Tests` and `*.Testing` projects (`Stopwatch`, `GetTimestamp`,
260
- `GetElapsedTime`, `TickCount`, `DateTime.Now`, `UtcNow` and `Today`, `Thread.Sleep`, `Task.Delay`, `Timeout =` in an attribute),
259
+ `GetElapsedTime`, `TickCount`, `DateTime.Now`, `UtcNow` and `Today`, `TimeProvider.System`, `Thread.Sleep`, `Task.Delay`, `Timeout =` in an attribute,
260
+ a `TimeSpan.From…` or `new TimeSpan(…)` handed to a constructor that gets no `TimeProvider`),
261
261
  and the `*.test`, `*.spec`, `*.e2e`, `*.visual`
262
262
  and `*.stories` files and the helpers of an `e2e/` folder (`performance.now`, `Date.now()` in a subtraction, `setTimeout`,
263
263
  `sleep(<n>)`, `waitForTimeout`, `interruptAfterTimeLimit`, and `timeout: <n>` in a Vitest file, such as the options of `it`, `test`
264
264
  or `describe`). It lets through a call that is
265
- handed a `TimeProvider` (a `FakeTimeProvider` in the tests), `Task.Delay` inside a `while`, `for`, `foreach` or `do` loop (a poll)
265
+ handed a `TimeProvider` (a `FakeTimeProvider` in the tests; `TimeProvider.System` is the real clock and fails), `Task.Delay` inside a `while`, `for`, `foreach` or `do` loop (a poll)
266
266
  or with `Timeout.Infinite`, the timers and the clock of a file that calls `vi.useFakeTimers()`, Playwright's auto-waiting
267
267
  `expect` with its own `timeout`, a ceiling against a hang (`CancelAfter`, `new CancellationTokenSource(<delay>)`,
268
- `WaitAsync(<TimeSpan>)`, and the `timeout` option of a Vitest wait for an event: `vi.waitFor`, `vi.waitUntil`, `expect.poll`,
268
+ `WaitAsync(<TimeSpan>)`, an `HttpClient`'s `Timeout`, and the `timeout` option of a Vitest wait for an event: `vi.waitFor`, `vi.waitUntil`, `expect.poll`,
269
269
  Testing Library's `waitFor`, `findBy*` and `findAllBy*`; the test waits for the event and fails fast, with its name, if it never
270
270
  comes: a ceiling, not a speed promise), and the tools' configs
271
271
  (`playwright.config.ts`), whose ceilings stop a hang.
@@ -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":
package/dist/dev/logs.js CHANGED
@@ -1,4 +1,4 @@
1
- import { readdirSync, readFileSync, statSync } from "node:fs";
1
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { parseArgs } from "node:util";
4
4
  import { composeBase } from "./db.js";
@@ -106,6 +106,42 @@ export function newestLog(directory) {
106
106
  const files = names.map((name) => ({ file: path.join(directory, name), time: statSync(path.join(directory, name)).mtimeMs }));
107
107
  return files.sort((left, right) => right.time - left.time)[0]?.file ?? null;
108
108
  }
109
+ const RECIPE = /^@?([A-Za-z_][\w-]*)(?:\s[^:]*)?:(?!=)/;
110
+ function justFiles(root) {
111
+ const entries = (() => {
112
+ try {
113
+ return readdirSync(root, { withFileTypes: true });
114
+ }
115
+ catch {
116
+ return [];
117
+ }
118
+ })();
119
+ return entries.flatMap((entry) => {
120
+ if (entry.isFile() && entry.name === "justfile")
121
+ return [{ file: path.join(root, entry.name), module: "" }];
122
+ if (entry.isFile() && entry.name.endsWith(".just"))
123
+ return [{ file: path.join(root, entry.name), module: entry.name.replace(/\.just$/, "") }];
124
+ const nested = path.join(root, entry.name, "mod.just");
125
+ return entry.isDirectory() && existsSync(nested) ? [{ file: nested, module: entry.name }] : [];
126
+ });
127
+ }
128
+ function recipeRunning(root, command) {
129
+ for (const { file, module } of justFiles(root)) {
130
+ let recipe;
131
+ for (const text of readFileSync(file, "utf8").split("\n")) {
132
+ if (!/^\s/.test(text))
133
+ recipe = text.trim() === "" ? recipe : RECIPE.exec(text)?.[1];
134
+ else if (recipe !== undefined && command.test(text))
135
+ return `just ${module === "" ? "" : `${module} `}${recipe}`;
136
+ }
137
+ }
138
+ return null;
139
+ }
140
+ function startHint(root) {
141
+ const stack = recipeRunning(root, /\bdev\s+tmux\s+start\b/) ?? "suwgate dev tmux start";
142
+ const server = recipeRunning(root, /\bdev\s+server\b/) ?? "suwgate dev server";
143
+ return `Start the server with \`${stack}\` (or \`${server}\`)`;
144
+ }
109
145
  export async function runLogs(command, settings, exec, io, cwd) {
110
146
  let sourceName;
111
147
  let content;
@@ -118,7 +154,7 @@ export async function runLogs(command, settings, exec, io, cwd) {
118
154
  else {
119
155
  const file = command.file === "" ? newestLog(path.dirname(path.join(settings.root, settings.logFile))) : path.resolve(cwd, command.file);
120
156
  if (file === null) {
121
- throw new Failure("suwgate dev logs: no log file yet. Start the server with `suwgate dev tmux start` (or `suwgate dev server`), or run the browser tests (they write the logs), or read the container stack with --compose.");
157
+ throw new Failure(`suwgate dev logs: no log file yet. ${startHint(settings.root)}, or run the browser tests (they write the logs), or read the container stack with --compose.`);
122
158
  }
123
159
  try {
124
160
  content = readFileSync(file, "utf8");
@@ -29,6 +29,7 @@ export interface DevSettings {
29
29
  psql: string | null;
30
30
  };
31
31
  serverProject: string | null;
32
+ dotnetDirectory: string | null;
32
33
  webDirectory: string | null;
33
34
  logFile: string;
34
35
  smokeChecks: SmokeCheck[];
@@ -1,4 +1,4 @@
1
- import { existsSync, readFileSync } from "node:fs";
1
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { parse } from "yaml";
4
4
  import { Failure } from "./process.js";
@@ -128,7 +128,8 @@ export function resolveSettings(raw, directories, root) {
128
128
  up: databaseRaw["up"] === undefined ? null : text(databaseRaw, "up", "dev.database", "", problems),
129
129
  psql: databaseRaw["psql"] === undefined ? null : text(databaseRaw, "psql", "dev.database", "", problems),
130
130
  },
131
- serverProject: typeof serverRaw["project"] === "string" ? serverRaw["project"] : stringOrNull(directories["dotnet"]),
131
+ serverProject: serverRaw["project"] === undefined ? null : text(serverRaw, "project", "dev.server", "", problems),
132
+ dotnetDirectory: stringOrNull(directories["dotnet"]),
132
133
  webDirectory: stringOrNull(directories["web"]),
133
134
  logFile: text(serverRaw, "logFile", "dev.server", ".artifacts/logs/server.jsonl", problems),
134
135
  smokeChecks: smokeChecks(top["smoke"], problems),
@@ -149,11 +150,35 @@ export function loadSettings(root) {
149
150
  const directories = typeof data["directories"] === "object" && data["directories"] !== null ? data["directories"] : {};
150
151
  return resolveSettings(data["dev"], directories, root);
151
152
  }
152
- export function needServerProject(settings) {
153
- if (settings.serverProject === null) {
154
- throw new Failure("no server project: set directories.dotnet (or dev.server.project) in suwgate.yml to the folder of the server's .csproj", 2);
153
+ const WEB_SDK = /\bSdk\s*=\s*"Microsoft\.NET\.Sdk\.Web[/"]|<Sdk\s+Name\s*=\s*"Microsoft\.NET\.Sdk\.Web"/;
154
+ const NOT_SOURCES = new Set(["node_modules", "bin", "obj"]);
155
+ function webProjects(root, folder) {
156
+ let entries;
157
+ try {
158
+ entries = readdirSync(path.join(root, folder), { withFileTypes: true });
159
+ }
160
+ catch {
161
+ return [];
155
162
  }
156
- return settings.serverProject;
163
+ return entries.flatMap((entry) => {
164
+ const relative = folder === "" ? entry.name : `${folder}/${entry.name}`;
165
+ if (entry.isDirectory())
166
+ return entry.name.startsWith(".") || NOT_SOURCES.has(entry.name) ? [] : webProjects(root, relative);
167
+ return entry.name.endsWith(".csproj") && WEB_SDK.test(readFileSync(path.join(root, relative), "utf8")) ? [relative] : [];
168
+ });
169
+ }
170
+ export function needServerProject(settings) {
171
+ if (settings.serverProject !== null)
172
+ return settings.serverProject;
173
+ const under = settings.dotnetDirectory ?? "";
174
+ const found = webProjects(settings.root, under.replace(/^\.\/?|\/+$/g, "")).sort();
175
+ const [project] = found;
176
+ if (project !== undefined && found.length === 1)
177
+ return path.posix.dirname(project);
178
+ const where = under === "" ? "the repository" : under;
179
+ throw new Failure(found.length === 0
180
+ ? `no server project: no .csproj in ${where} uses Sdk="Microsoft.NET.Sdk.Web"; set dev.server.project in suwgate.yml to the folder of the server's .csproj`
181
+ : `${found.length} server projects use Sdk="Microsoft.NET.Sdk.Web" (${found.join(", ")}): set dev.server.project in suwgate.yml to the folder of the one suwgate dev server runs`, 2);
157
182
  }
158
183
  export function needWebDirectory(settings) {
159
184
  if (settings.webDirectory === null) {
@@ -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,5 +1,5 @@
1
1
  import { resolveSettings } from "./settings.js";
2
- export function settingsOf(raw = { name: "myapp" }, directories = { dotnet: "Myapp.Server", web: "Myapp.Web" }) {
2
+ export function settingsOf(raw = { name: "myapp", server: { project: "Myapp.Server" } }, directories = { web: "Myapp.Web" }) {
3
3
  return resolveSettings(raw, directories, "/repo");
4
4
  }
5
5
  export function fakeExec(answer = () => ({})) {
@@ -71,9 +71,6 @@ function checkExceptions(raw, catalog, problem) {
71
71
  problem(where, `no guard "${exception.guard}": the guards are ${catalog.guards.map((guard) => guard.id).join(", ")} (and architecture/*, database/* of the .NET packages)`);
72
72
  }
73
73
  else if (profiles === "dotnet-guard") {
74
- if (exception.message !== undefined || exception.once !== undefined) {
75
- problem(where, `"${exception.guard}" is a .NET guard, and the .NET packages match an exception by its target only: delete message and once`);
76
- }
77
74
  const prefix = Object.keys(DOTNET_GUARD_PREFIXES).find((candidate) => exception.guard.startsWith(candidate)) ?? "";
78
75
  const needed = DOTNET_GUARD_PREFIXES[prefix];
79
76
  if (needed !== undefined && !raw.profiles.includes(needed)) {
@@ -59,6 +59,9 @@ export async function runGuards(input) {
59
59
  lines.push(`${guard.id}: ${done.target}: the one-time exception is on master now and excepts nothing: delete it from ${CONFIG_FILE}`);
60
60
  }
61
61
  }
62
+ for (const done of (input.merged ?? []).filter((exception) => !input.guards.some((guard) => guard.id === exception.guard))) {
63
+ lines.push(`${done.guard}: ${done.target}: the one-time exception is on master now and excepts nothing: delete it from ${CONFIG_FILE}`);
64
+ }
62
65
  const header = `${input.guards.length} guard${input.guards.length === 1 ? "" : "s"}, ${excepted} findings excepted in ${CONFIG_FILE}`;
63
66
  return { passed: !failed, log: [header, ...lines].join("\n") };
64
67
  }
@@ -11,13 +11,20 @@ const MEASURES = "measures real time";
11
11
  const READS_CLOCK = "reads the real clock";
12
12
  const WAITS = "waits on real time";
13
13
  const LIMITS = "limits the test in real time";
14
+ const REAL_CLOCK_FIX = "a test runs on a FakeTimeProvider (Microsoft.Extensions.Time.Testing), never on the real clock: hand the code a new FakeTimeProvider() and move time with its Advance or SetUtcNow";
14
15
  const CSHARP_RULES = [
15
16
  { pattern: /\b(?<found>Stopwatch|GetElapsedTime|GetTimestamp|TickCount64|TickCount)\b/dg, verb: MEASURES },
16
17
  { pattern: /\b(?<found>(DateTime|DateTimeOffset)\.(Now|UtcNow|Today))\b/dg, verb: READS_CLOCK },
17
18
  { pattern: /\b(?<found>Thread\.Sleep)\b/dg, verb: "sleeps on real time" },
18
19
  { pattern: /\[[^[\]]*?\b(?<found>Timeout\s*=)(?!=)/dg, verb: LIMITS },
20
+ { pattern: /\b(?<found>TimeProvider\.System)\b/dg, verb: "is the real clock, not a FakeTimeProvider", fix: REAL_CLOCK_FIX },
19
21
  ];
20
- const onFakeClock = (call) => call.args.slice(1).some((arg) => /provider|clock/i.test(arg));
22
+ const FAKE_CLOCK = /provider|clock/i;
23
+ const onFakeClock = (call) => call.args.slice(1).some((arg) => FAKE_CLOCK.test(arg));
24
+ const CONSTRUCTED = /\bnew\s+(?<type>[A-Za-z_][\w.]*)\s*(?:<[^<>()]*>)?\s*\(|\bnew\s*\(/g;
25
+ const INTERVAL = /^(?:\w+\s*:\s*)?(?:TimeSpan\.From\w+\s*\(|new\s+TimeSpan\s*\()/;
26
+ const NOT_A_WAIT = new Set(["CancellationTokenSource", "DateTimeOffset", "TimeSpan"]);
27
+ const DECLARED_TYPE = /\b(?<type>[A-Za-z_]\w*)\s*(?:<[^<>()]*>)?\s+[A-Za-z_]\w*\s*=\s*$/;
21
28
  const CSHARP_CALLS = [
22
29
  {
23
30
  pattern: /\bTask\.Delay\s*\(/g,
@@ -179,19 +186,39 @@ function argumentsOf(text, open) {
179
186
  }
180
187
  return args.filter((arg) => arg !== "");
181
188
  }
182
- function finding(file, line, found, verb) {
183
- return { target: file, line, message: `${found.replace(/\s+/g, " ")} ${verb}: ${FIX}` };
189
+ function finding(file, line, found, verb, fix = FIX) {
190
+ return { target: file, line, message: `${found.replace(/\s+/g, " ")} ${verb}: ${fix}` };
191
+ }
192
+ function constructedType(text, match) {
193
+ const named = match.groups?.["type"];
194
+ if (named !== undefined)
195
+ return named.split(".").at(-1) ?? named;
196
+ return DECLARED_TYPE.exec(text.slice(0, match.index))?.groups?.["type"] ?? "";
197
+ }
198
+ function constructorFindings(file, text) {
199
+ return [...text.matchAll(CONSTRUCTED)].flatMap((match) => {
200
+ const type = constructedType(text, match);
201
+ if (NOT_A_WAIT.has(type))
202
+ return [];
203
+ const args = argumentsOf(text, match.index + match[0].length - 1);
204
+ const interval = args.find((arg) => INTERVAL.test(arg));
205
+ if (interval === undefined || args.some((arg) => FAKE_CLOCK.test(arg)))
206
+ return [];
207
+ return [
208
+ finding(file, lineAt(text, match.index), `${interval.replace(/^\w+\s*:\s*/, "")} handed to new ${type}(…)`, "gives the code a real-time interval without a TimeProvider", `${FIX}; a ceiling against a hang stays allowed (new CancellationTokenSource(<delay>), CancelAfter, WaitAsync(<TimeSpan>), an HttpClient's Timeout)`),
209
+ ];
210
+ });
184
211
  }
185
212
  function csharpFindings(file, source) {
186
213
  const text = codeOnly(source);
187
214
  const plain = CSHARP_RULES.flatMap((rule) => [...text.matchAll(rule.pattern)].flatMap((match) => {
188
215
  const found = match.indices?.groups?.["found"];
189
- return found === undefined ? [] : [finding(file, lineAt(text, found[0]), text.slice(found[0], found[1]), rule.verb)];
216
+ return found === undefined ? [] : [finding(file, lineAt(text, found[0]), text.slice(found[0], found[1]), rule.verb, rule.fix)];
190
217
  }));
191
218
  const calls = CSHARP_CALLS.flatMap((rule) => [...text.matchAll(rule.pattern)]
192
219
  .filter((match) => !rule.allowed({ text, at: match.index, args: argumentsOf(text, match.index + match[0].length - 1) }))
193
220
  .map((match) => finding(file, lineAt(text, match.index), match[0].replace(/^\.|\s*\($/g, ""), rule.verb)));
194
- return [...plain, ...calls].sort((a, b) => (a.line ?? 0) - (b.line ?? 0));
221
+ return [...plain, ...calls, ...constructorFindings(file, text)].sort((a, b) => (a.line ?? 0) - (b.line ?? 0));
195
222
  }
196
223
  function webFindings(file, source) {
197
224
  const faked = FAKE_TIMERS.test(source);
@@ -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.6.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",
@@ -137,11 +137,11 @@
137
137
  "message": {
138
138
  "type": "string",
139
139
  "minLength": 1,
140
- "description": "Narrows the exception to the target's findings whose message contains this text; without it, every finding of the target is excepted. Repository guards only."
140
+ "description": "Narrows the exception to the target's findings whose message contains this text; without it, every finding of the target is excepted."
141
141
  },
142
142
  "once": {
143
143
  "type": "boolean",
144
- "description": "A one-time exception: it holds only while master's suwgate.yml does not have it yet (on the branch that adds it). After the merge it excepts nothing and is never stale; the report asks to delete it. Repository guards only."
144
+ "description": "A one-time exception: it holds only while master's suwgate.yml does not have it yet (on the branch that adds it). After the merge it excepts nothing and is never stale; the report asks to delete it."
145
145
  }
146
146
  }
147
147
  }
@@ -224,7 +224,7 @@
224
224
  "properties": {
225
225
  "project": {
226
226
  "$ref": "#/$defs/relativePath",
227
- "description": "The folder of the server's .csproj (default directories.dotnet)."
227
+ "description": "The folder of the server's .csproj (default: the folder of the one .csproj on Sdk=\"Microsoft.NET.Sdk.Web\" in directories.dotnet, or in the repository)."
228
228
  },
229
229
  "logFile": {
230
230
  "$ref": "#/$defs/relativePath",