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
10 changes: 7 additions & 3 deletions packages/runtime-cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,9 +180,13 @@ autter-runtime sourcemaps upload <dir> [--release <r>] [--url-prefix <prefix>]
as fit the 32 MB limit), so issues show the lines around each frame;
`--no-sources-content` leaves it out. For server output, `--url-prefix` is
any tail of the path the server runs the files from (`/dist/` for
`/app/dist/server.js`), or `/`. Release: `--release`, else `GITHUB_SHA`,
`VERCEL_GIT_COMMIT_SHA`, `CF_PAGES_COMMIT_SHA`, `GIT_SHA`, then
`git rev-parse HEAD`.
`/app/dist/server.js`), or `/`. Release: `--release`, else `AUTTER_RELEASE`, else
the first of `GITHUB_SHA`, `VERCEL_GIT_COMMIT_SHA`, `CF_PAGES_COMMIT_SHA`,
`GIT_SHA` that is set (any value), else the first commit (7 to 40
hexadecimal characters) in the other commit variables `@autter/runtime-node`
reads (`AUTTER_COMMIT`, `GIT_COMMIT`, `COMMIT_SHA`, `SOURCE_COMMIT`,
`RENDER_GIT_COMMIT`, `RAILWAY_GIT_COMMIT_SHA`, `HEROKU_SLUG_COMMIT`,
`SOURCE_VERSION`), else `git rev-parse HEAD`.
- **upload --best-effort** is for build scripts that also run locally and in
fork PRs: without a key, or when the upload fails, it says so and exits 0;
with `--delete-after-upload`, every `.map` under `<dir>` is then deleted
Expand Down
2 changes: 1 addition & 1 deletion packages/runtime-cli/src/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { uploadDir, type UploadSummary } from "./upload.js";

/** Options shared by the Vite/Rollup, webpack and Next.js integrations. */
export interface AutterSourceMapsOptions {
/** Default: GITHUB_SHA, VERCEL_GIT_COMMIT_SHA, CF_PAGES_COMMIT_SHA, GIT_SHA, then `git rev-parse HEAD`. */
/** Default: AUTTER_RELEASE, else GITHUB_SHA, VERCEL_GIT_COMMIT_SHA, CF_PAGES_COMMIT_SHA, GIT_SHA (any value), else a commit in @autter/runtime-node's other commit variables (AUTTER_COMMIT, GIT_COMMIT, ...), else `git rev-parse HEAD`. */
release?: string;
/** Where the build output is served from. Default: the bundler's public
* path (Vite `base`, webpack `output.publicPath`, Next `/_next/`), else "/". */
Expand Down
7 changes: 5 additions & 2 deletions packages/runtime-cli/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,11 @@ upload Sends every map to <endpoint>/v1/sourcemaps with AUTTER_RUNTIME_KEY,
dependencies'), so issues show the lines around each frame.

Options:
--release <r> Default: $GITHUB_SHA, $VERCEL_GIT_COMMIT_SHA,
$CF_PAGES_COMMIT_SHA, $GIT_SHA, then git rev-parse HEAD
--release <r> Default: $AUTTER_RELEASE, else $GITHUB_SHA,
$VERCEL_GIT_COMMIT_SHA, $CF_PAGES_COMMIT_SHA, $GIT_SHA
(any value), else a commit in the SDK's other commit
variables ($AUTTER_COMMIT, $GIT_COMMIT, ...), else
git rev-parse HEAD
--url-prefix <prefix> Where <dir> is served from: "/" (default), "/static/",
or "https://cdn.example.com/app/". For server output,
any tail of the path the server runs it from
Expand Down
69 changes: 47 additions & 22 deletions packages/runtime-cli/src/release.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,31 @@
import { execFileSync } from "node:child_process";
// The commit variables are shared with the SDK: the file is dependency-free
// and bundled into the CLI at build time (tsup), so the published package
// gains no dependency.
import { COMMIT_ENV_VARS, COMMIT_RE, LEGACY_RELEASE_ENV_VARS } from "../../runtime-node/src/deployment.js";

/** What the ingester accepts as a release. */
export const RELEASE_RE = /^[a-zA-Z0-9._-]{1,200}$/;

/** CI variables that carry the commit being built, in the order they are tried. */
export const RELEASE_ENV_VARS = [
"GITHUB_SHA",
"VERCEL_GIT_COMMIT_SHA",
"CF_PAGES_COMMIT_SHA",
"GIT_SHA",
] as const;
/**
* CI variables the release is named after, any value, in the order they are
* tried (after --release and AUTTER_RELEASE): unchanged, so existing builds
* keep uploading under the release their bundles report (the browser
* snippets `autter-runtime setup` prints read GITHUB_SHA first too).
*/
export const RELEASE_ENV_VARS = LEGACY_RELEASE_ENV_VARS;

/**
* The rest of @autter/runtime-node's commit variables, tried after
* RELEASE_ENV_VARS: only a 7-40 character hexadecimal value counts.
*/
const OTHER_COMMIT_ENV_VARS = COMMIT_ENV_VARS.filter(
(name) => !(LEGACY_RELEASE_ENV_VARS as readonly string[]).includes(name),
);

export interface ResolvedRelease {
release: string;
/** Where it came from: "--release", an env var name, or "git". */
/** Where it came from: "--release", "AUTTER_RELEASE", a commit variable's name, or "git". */
source: string;
}

Expand All @@ -32,34 +44,47 @@ export function gitHead(cwd: string = process.cwd()): string | null {
}
}

function checked(release: string, source: string): ResolvedRelease {
if (!RELEASE_RE.test(release)) {
throw new Error(
`release "${release}" (from ${source}) is not valid: use 1-200 letters, digits, ".", "_" or "-" (a commit SHA works)`,
);
}
return { release, source };
}

/**
* The release to upload under: the explicit value, else the first CI commit
* variable that is set (GITHUB_SHA, VERCEL_GIT_COMMIT_SHA, CF_PAGES_COMMIT_SHA,
* GIT_SHA), else `git rev-parse HEAD`. Throws with a usable message when none
* is available or the value has characters the ingester rejects.
* The release to upload under: `--release`, else AUTTER_RELEASE, else the
* first non-empty RELEASE_ENV_VARS value (GITHUB_SHA, VERCEL_GIT_COMMIT_SHA,
* CF_PAGES_COMMIT_SHA, GIT_SHA; any value, as before), else the first commit
* (7-40 hexadecimal characters) among the SDK's other commit variables
* (AUTTER_COMMIT, GIT_COMMIT, COMMIT_SHA, SOURCE_COMMIT, RENDER_GIT_COMMIT,
* RAILWAY_GIT_COMMIT_SHA, HEROKU_SLUG_COMMIT, SOURCE_VERSION), else
* `git rev-parse HEAD` (build time only; the SDK never runs git). Throws with
* a usable message when none is available or the value has characters the
* ingester rejects.
*/
export function resolveRelease(
explicit?: string | null,
env: NodeJS.ProcessEnv = process.env,
cwd: string = process.cwd(),
): ResolvedRelease {
const candidates: Array<[string, string | undefined | null]> = [
const named: Array<[string, string | undefined | null]> = [
["--release", explicit],
["AUTTER_RELEASE", env.AUTTER_RELEASE],
...RELEASE_ENV_VARS.map((name): [string, string | undefined] => [name, env[name]]),
];
for (const [source, value] of candidates) {
for (const [source, value] of named) {
const release = value?.trim();
if (!release) continue;
if (!RELEASE_RE.test(release)) {
throw new Error(
`release "${release}" (from ${source}) is not valid: use 1-200 letters, digits, ".", "_" or "-" (a commit SHA works)`,
);
}
return { release, source };
if (release) return checked(release, source);
}
for (const source of OTHER_COMMIT_ENV_VARS) {
const value = env[source]?.trim();
if (value && COMMIT_RE.test(value)) return { release: value, source };
}
const head = gitHead(cwd);
if (head) return { release: head, source: "git" };
throw new Error(
`no release: pass --release <release>, or set one of ${RELEASE_ENV_VARS.join(", ")}, or run inside a git checkout`,
`no release: pass --release <release>, or set AUTTER_RELEASE, one of ${RELEASE_ENV_VARS.join(", ")}, or a commit in one of ${OTHER_COMMIT_ENV_VARS.join(", ")}, or run inside a git checkout`,
);
}
18 changes: 16 additions & 2 deletions packages/runtime-cli/test/upload.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
injectDir,
isInAppSource,
MAX_MAP_CHARS,
RELEASE_ENV_VARS,
resolveEndpoint,
resolveRelease,
servedFilename,
Expand Down Expand Up @@ -239,16 +240,29 @@ test("--delete-after-upload removes uploaded maps and their sourceMappingURL com
assert.match(read(dir, "app.js"), /\/\/# debugId=/);
});

test("release comes from --release, then CI variables, then git", () => {
assert.deepEqual(resolveRelease("v1.2.3", { GITHUB_SHA: "aaa" }), { release: "v1.2.3", source: "--release" });
test("release comes from --release, then AUTTER_RELEASE, then CI variables (any value, as before), then other commit variables, then git", () => {
const a = "aaaaaaa", c = "cccccccccccccccccccccccccccccccccccccccc", d = "ddddddd";
assert.deepEqual(resolveRelease("v1.2.3", { GITHUB_SHA: "aaa", AUTTER_RELEASE: "r9" }), { release: "v1.2.3", source: "--release" });
assert.deepEqual(resolveRelease(undefined, { GITHUB_SHA: "aaa", AUTTER_RELEASE: "r9" }), { release: "r9", source: "AUTTER_RELEASE" });
// Unchanged for existing builds: the four CI variables, in their order, any value.
assert.deepEqual(resolveRelease(undefined, { GITHUB_SHA: "aaa", GIT_SHA: "ddd" }), { release: "aaa", source: "GITHUB_SHA" });
assert.deepEqual(resolveRelease(undefined, { GITHUB_SHA: a, GIT_SHA: d }), { release: a, source: "GITHUB_SHA" }, "both set and different: GITHUB_SHA wins, as before");
assert.deepEqual(resolveRelease(undefined, { VERCEL_GIT_COMMIT_SHA: "bbb", GIT_SHA: "ddd" }), { release: "bbb", source: "VERCEL_GIT_COMMIT_SHA" });
assert.deepEqual(resolveRelease(undefined, { CF_PAGES_COMMIT_SHA: "ccc", GIT_SHA: "ddd" }), { release: "ccc", source: "CF_PAGES_COMMIT_SHA" });
assert.deepEqual(resolveRelease(undefined, { GIT_SHA: "ddd" }), { release: "ddd", source: "GIT_SHA" });
assert.deepEqual(resolveRelease(undefined, { GIT_SHA: "v1.2.3" }), { release: "v1.2.3", source: "GIT_SHA" }, "a name, not a commit: still the release, as before");
assert.deepEqual(resolveRelease(undefined, { GIT_SHA: "v1.2.3", AUTTER_COMMIT: c }), { release: "v1.2.3", source: "GIT_SHA" });
assert.deepEqual([...RELEASE_ENV_VARS], ["GITHUB_SHA", "VERCEL_GIT_COMMIT_SHA", "CF_PAGES_COMMIT_SHA", "GIT_SHA"]);
// Then the SDK's other commit variables, in its order: only a commit counts.
assert.deepEqual(resolveRelease(undefined, { HEROKU_SLUG_COMMIT: c, AUTTER_COMMIT: d }), { release: d, source: "AUTTER_COMMIT" });
assert.deepEqual(resolveRelease(undefined, { SOURCE_VERSION: "refs/heads/main", RENDER_GIT_COMMIT: c }), { release: c, source: "RENDER_GIT_COMMIT" });
const head = execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim();
assert.deepEqual(resolveRelease(undefined, {}), { release: head, source: "git" });
assert.deepEqual(resolveRelease(undefined, { SOURCE_VERSION: "pr/12" }), { release: head, source: "git" });
assert.throws(() => resolveRelease(undefined, {}, tempDir()), /no release/);
assert.throws(() => resolveRelease("my app@1.0", {}), /not valid/);
assert.throws(() => resolveRelease(undefined, { AUTTER_RELEASE: "my app@1.0" }), /from AUTTER_RELEASE\) is not valid/);
assert.throws(() => resolveRelease(undefined, { GIT_SHA: "my app@1.0" }), /from GIT_SHA\) is not valid/);
});

test("served filenames and endpoints are normalised", () => {
Expand Down
120 changes: 120 additions & 0 deletions packages/runtime-node/src/deployment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
/**
* What this process is running: its commit, its default release and its
* default environment, read from environment variables only. Never runs git
* or any other subprocess: the SDK reads what the platform or the build put
* in the environment, nothing else.
*
* Dependency-free on purpose: `@autter/runtime-cli` (src/release.ts) imports
* this file by path and bundles it, so the source-map upload picks the same
* commit variables, in the same order, as the SDK that reports the errors.
* `runtime-core` is not an option there: it is a private package the CLI
* does not depend on.
*/

/**
* Environment variables that carry the commit being built or run, in the
* order they are tried: Autter's own, then the four the source-map upload
* CLI has always read, in its order (LEGACY_RELEASE_ENV_VARS), then the
* other generic names and hosting platforms. One list for
* `initAutterServer` / `initAutterLogging`, `enrichDeployment`,
* `autter-runtime verify` and the source-map upload CLI (and the same list
* as the Python adapter). With a commit in any one of the CLI's four, the
* SDK's default release is the release the CLI uploads maps under.
*/
export const COMMIT_ENV_VARS = [
"AUTTER_COMMIT",
"GITHUB_SHA",
"VERCEL_GIT_COMMIT_SHA",
"CF_PAGES_COMMIT_SHA",
"GIT_SHA",
"GIT_COMMIT",
"COMMIT_SHA",
"SOURCE_COMMIT",
"RENDER_GIT_COMMIT",
"RAILWAY_GIT_COMMIT_SHA",
"HEROKU_SLUG_COMMIT",
"SOURCE_VERSION",
] as const;

/**
* The variables @autter/runtime-cli named its upload release after before
* the shared list, in its order. The CLI still takes any value from these
* (a release is a name there), so existing builds keep uploading under the
* release their bundles report.
*/
export const LEGACY_RELEASE_ENV_VARS = ["GITHUB_SHA", "VERCEL_GIT_COMMIT_SHA", "CF_PAGES_COMMIT_SHA", "GIT_SHA"] as const;

/** A commit: 7 to 40 hexadecimal characters (an abbreviated or full git SHA-1). */
export const COMMIT_RE = /^[0-9a-fA-F]{7,40}$/;

type Env = Record<string, string | undefined>;

export interface DetectedCommit {
commit: string;
/** The variable it came from. */
source: (typeof COMMIT_ENV_VARS)[number];
}

/**
* The first commit variable whose (trimmed) value is a commit. A variable set
* to anything else (a branch, a tag, `refs/heads/main`) is skipped, so the
* next one can still answer.
*/
export function detectCommitFrom(env: Env = process.env): DetectedCommit | null {
for (const source of COMMIT_ENV_VARS) {
const value = env[source]?.trim();
if (value && COMMIT_RE.test(value)) return { commit: value, source };
}
return null;
}

/** The running commit, or undefined. See {@link detectCommitFrom}. */
export function detectCommit(env: Env = process.env): string | undefined {
return detectCommitFrom(env)?.commit;
}

const OFF = new Set(["false", "0", "no", "off"]);

/** `AUTTER_DETECT_RELEASE=false` (or 0 / no / off) turns the default release off. */
export function releaseDetectionDisabled(env: Env = process.env): boolean {
const value = env.AUTTER_DETECT_RELEASE?.trim().toLowerCase();
return value !== undefined && OFF.has(value);
}

/**
* The release when the app passed none: `AUTTER_RELEASE`, else the detected
* commit (the full value, so Autter can resolve it to the commit and its
* pull request). Undefined when `AUTTER_DETECT_RELEASE=false`.
*/
export function defaultRelease(env: Env = process.env): string | undefined {
if (releaseDetectionDisabled(env)) return undefined;
return env.AUTTER_RELEASE?.trim() || detectCommit(env);
}

/**
* The release an SDK reports: an explicit non-empty `release` always wins;
* `release: false` means none; unset (or empty) falls back to
* {@link defaultRelease}.
*/
export function resolveRelease(release: string | false | null | undefined, env: Env = process.env): string | undefined {
if (release === false) return undefined;
if (typeof release === "string" && release) return release;
return defaultRelease(env);
}

/** Variables test runners set in the processes that run tests. */
export const TEST_RUNNER_ENV_VARS = ["JEST_WORKER_ID", "VITEST", "NODE_TEST_CONTEXT"] as const;

/** True inside Jest, Vitest or `node --test`. */
export function testRunnerDetected(env: Env = process.env): boolean {
return TEST_RUNNER_ENV_VARS.some((name) => !!env[name]);
}

/**
* The environment an SDK reports: the explicit option, else `NODE_ENV`, else
* `test` under a test runner (Jest, Vitest, `node --test`), else
* `production`. An explicit value (option or `NODE_ENV`) always wins.
*/
export function resolveEnvironment(environment: string | undefined, env: Env = process.env): string {
return environment ?? env.NODE_ENV ?? (testRunnerDetected(env) ? "test" : "production");
}
24 changes: 8 additions & 16 deletions packages/runtime-node/src/enrichers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { parseUserAgent } from "@autter/runtime-core";
import { detectCommit } from "./deployment.js";
import type { RuntimeEnricher } from "./logger.js";

/**
Expand Down Expand Up @@ -80,29 +81,20 @@ const REGION_VARS = [
"RENDER_REGION",
"AZURE_REGION",
];
const COMMIT_VARS = [
"AUTTER_COMMIT",
"GIT_SHA",
"GIT_COMMIT",
"COMMIT_SHA",
"SOURCE_COMMIT",
"VERCEL_GIT_COMMIT_SHA",
"GITHUB_SHA",
"RENDER_GIT_COMMIT",
"RAILWAY_GIT_COMMIT_SHA",
"CF_PAGES_COMMIT_SHA",
"HEROKU_SLUG_COMMIT",
"SOURCE_VERSION",
];

/** `deployment.region` and `deployment.commit` from common platform environment variables. */
/**
* `deployment.region` and `deployment.commit` from common platform
* environment variables. The commit is read from COMMIT_ENV_VARS
* (deployment.ts), the same list initAutterServer uses, and only a 7-40
* character hexadecimal value counts.
*/
export function enrichDeployment(
env: Record<string, string | undefined> = process.env,
): RuntimeEnricher {
const pick = (names: string[]) =>
names.map((name) => env[name]?.trim()).find((value) => value);
const region = pick(REGION_VARS)?.slice(0, 64);
const commit = pick(COMMIT_VARS)?.slice(0, 64);
const commit = detectCommit(env);
return (event) => {
if (region) event.attributes["deployment.region"] = region;
if (commit) event.attributes["deployment.commit"] = commit;
Expand Down
10 changes: 7 additions & 3 deletions packages/runtime-node/src/logging-only.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import {
unregisterFlushTargets,
type AutoFlushHandle,
} from "./lifecycle.js";
import { resolveEnvironment, resolveRelease } from "./deployment.js";
import { makeRedactor, type RedactOptions } from "./redact.js";
import { markCaptured } from "./requests.js";
import {
Expand Down Expand Up @@ -77,8 +78,10 @@ export interface AutterLoggingOptions {
/** Ingester base URL. Default: https://otlp.autter.dev */
endpoint?: string;
service: string;
/** Same default as initAutterServer: NODE_ENV, else `test` under a test runner, else `production`. */
environment?: string;
release?: string;
/** Same default as initAutterServer: AUTTER_RELEASE, else the detected commit; `false` for none. */
release?: string | false;
logging?: RuntimeLoggingOptions;
/** Same semantics as initAutterServer. Default true. */
redactAttributes?: boolean | RedactOptions;
Expand Down Expand Up @@ -133,7 +136,8 @@ export function initAutterLogging(options: AutterLoggingOptions): AutterLogging
}
if (isDebugEnabled() || options.debug === true) setDebugMode(true);
const endpoint = (options.endpoint ?? "https://otlp.autter.dev").replace(/\/$/, "");
const environment = options.environment ?? process.env.NODE_ENV ?? "production";
const environment = resolveEnvironment(options.environment);
const release = resolveRelease(options.release);
const redact = makeRedactor(options.redactAttributes ?? true);
const mode = options.exceptions ?? "auto";
debugLog(`initialising logger-only service=${options.service} endpoint=${endpoint}`);
Expand Down Expand Up @@ -221,7 +225,7 @@ export function initAutterLogging(options: AutterLoggingOptions): AutterLogging
apiKey: resolveIngestKey(options.apiKey, {}) ?? "",
service: options.service,
environment,
...(options.release ? { release: options.release } : {}),
...(release ? { release } : {}),
...(options.logging ? { options: options.logging } : {}),
redact,
reportOutcome: (name, message, attributes) => {
Expand Down
Loading
Loading