Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Inherit the previous version's env and home files on redeploy (#1302)

Sina Matian060a81b57197
diff --git a/skills-seed/publish/SKILL.md b/skills-seed/publish/SKILL.md
index 0f81bff9d..b4fc55a9f 100644
--- a/skills-seed/publish/SKILL.md
+++ b/skills-seed/publish/SKILL.md
@@ -131,6 +131,9 @@ publish({
`renameFrom` lets you change it on request without losing history or shares.
- **Immutable versions + rollback.** Every publish is a new immutable version; `rollbackTo`
is an instant pointer flip. Safe to ship often.
+- **Env carries over.** `env` is baked into each version; a republish that omits `env` keeps
+ the most recent version's (including a failed attempt), and passing `env` replaces it
+ (`{}` clears).
- **Posture-aware egress.** Deployment network access follows the operator's configured
deployment provider and egress policy. Declare required hosts and credentials explicitly;
never assume arbitrary outbound access.
diff --git a/src/api/app-types.ts b/src/api/app-types.ts
index bed5afce2..7c252407f 100644
--- a/src/api/app-types.ts
+++ b/src/api/app-types.ts
@@ -96,8 +96,8 @@ import type { DeploymentLayerRuntime } from "../deployment/load-layer.ts";
import { type ArtifactHome, type ArtifactType } from "./artifact-share.ts";
import type {
DeployService,
- DeployFile,
DeployInput,
+ RedeployInput,
Reach,
ReachOptions,
DeploymentGrantee,
@@ -505,10 +505,7 @@ export interface App {
reachNow(input: ReachNowInput): Promise<ReachNowResult>;
resolveReachTarget(target: ReachTarget, authorityId: string, opts?: ReachOpts): Promise<ReachResolution>;
deploy(input: DeployInput): Promise<Deployment>;
- redeploy(
- id: string,
- input: { entrypoint: string; files: DeployFile[]; env?: Record<string, string> },
- ): Promise<Deployment>;
+ redeploy(id: string, input: RedeployInput): Promise<Deployment>;
listDeployments(): Promise<Deployment[]>;
getDeployment(idOrName: string): Promise<Deployment | null>;
listDeploymentsForViewer(principalId: string): Promise<ViewerDeployment[]>;
diff --git a/src/api/app.ts b/src/api/app.ts
index 9378fafc8..ba51327eb 100644
--- a/src/api/app.ts
+++ b/src/api/app.ts
@@ -12,7 +12,7 @@ import { createSearchMethods } from "./app-search.ts";
export type { App, AppDeps, ContextSummary, ProjectView, VisibleCron } from "./app-types.ts";
export { deploymentView, STALE_LEASE_GRACE_MS } from "./app-types.ts";
-export type { DeployInput } from "../deploy/deploy-service.ts";
+export type { DeployInput, RedeployInput } from "../deploy/deploy-service.ts";
export function createApp(deps: AppDeps): App {
const app = {} as App;
diff --git a/src/api/routes/deployments.ts b/src/api/routes/deployments.ts
index 1afb20064..2010f11ab 100644
--- a/src/api/routes/deployments.ts
+++ b/src/api/routes/deployments.ts
@@ -10,7 +10,7 @@ import {
} from "node:http2";
import { spawn } from "node:child_process";
import { basename, dirname } from "node:path";
-import { deploymentView, type App, type DeployInput } from "../app.ts";
+import { deploymentView, type App, type DeployInput, type RedeployInput } from "../app.ts";
import { errMessage } from "../../util/errors.ts";
import { canonicalPayload, escapeHtml, sendJson, verifyOrReject } from "../http.ts";
import { mintPortalIdentity, verifyPortalIdentity, PORTAL_IDENTITY_HEADER } from "../../auth/portal-identity.ts";
@@ -31,16 +31,25 @@ function deploymentProxyAgent(port?: number): { agent?: SocksProxyAgent } {
return { agent: new SocksProxyAgent(`socks5h://127.0.0.1:${port}`, { keepAlive: false }) };
}
-function isDeployInput(b: unknown): b is DeployInput {
+const isStringRecord = (v: unknown): v is Record<string, string> =>
+ isObj(v) && !Array.isArray(v) && Object.values(v).every((x) => typeof x === "string");
+
+function isRedeployInput(b: unknown): b is RedeployInput {
return (
isObj(b) &&
- typeof b.ownerScopeId === "string" &&
- typeof b.createdBy === "string" &&
typeof b.entrypoint === "string" &&
- Array.isArray(b.files)
+ Array.isArray(b.files) &&
+ (b.homeFiles === undefined || Array.isArray(b.homeFiles)) &&
+ (b.env === undefined || isStringRecord(b.env)) &&
+ b.stampEnv === undefined &&
+ (b.alwaysOn === undefined || typeof b.alwaysOn === "boolean")
);
}
+function isDeployInput(b: unknown): b is DeployInput {
+ return isObj(b) && typeof b.ownerScopeId === "string" && typeof b.createdBy === "string" && isRedeployInput(b);
+}
+
async function proxyDeployment(ctx: BaseCtx): Promise<void> {
const { req, res, app, deps, secret, auth, url, pathname, method } = ctx;
const rest = pathname.slice("/d/".length);
@@ -1192,7 +1201,7 @@ async function createDeployment(ctx: ApiCtx): Promise<void> {
const principalId = ctx.capability?.actorId ?? ctx.actor?.p;
if (principalId && body.createdBy !== principalId) return sendJson(res, 403, { error: "forbidden" });
try {
- return sendJson(res, 200, { deployment: await app.deploy(body) });
+ return sendJson(res, 200, { deployment: deploymentView(await app.deploy(body)) });
} catch (e) {
return sendJson(res, 400, { error: "deploy_failed", message: errMessage(e) });
}
@@ -1321,12 +1330,15 @@ async function redeployDeployment(ctx: ApiCtx): Promise<void> {
const id = await deploymentId(app, params.id!);
if (!id) return sendJson(res, 404, { error: "not_found" });
if (!(await callerMayManageDeployment(ctx, id))) return sendJson(res, 403, { error: "forbidden" });
- const b = body as { entrypoint?: unknown; files?: unknown };
- if (typeof b.entrypoint !== "string" || !Array.isArray(b.files)) {
- return sendJson(res, 400, { error: "bad_request", message: "entrypoint (string) and files (array) required" });
+ if (!isRedeployInput(body)) {
+ return sendJson(res, 400, {
+ error: "bad_request",
+ message:
+ "entrypoint (string) and files (array) required; env must be a string map, homeFiles an array, alwaysOn a boolean",
+ });
}
try {
- return sendJson(res, 200, { deployment: await app.redeploy(id, { entrypoint: b.entrypoint, files: b.files }) });
+ return sendJson(res, 200, { deployment: deploymentView(await app.redeploy(id, body)) });
} catch (e) {
return sendJson(res, 400, { error: "deploy_failed", message: errMessage(e) });
}
diff --git a/src/deploy/deploy-service.ts b/src/deploy/deploy-service.ts
index 9f55bb1f9..d52a57221 100644
--- a/src/deploy/deploy-service.ts
+++ b/src/deploy/deploy-service.ts
@@ -9,6 +9,7 @@ import { normalizeRelPath } from "./deploy-fs.ts";
import { samePerson } from "../directory/person.ts";
import type { AuditLog } from "../audit/audit-log.ts";
import {
+ currentVersionOf,
deployCurrentGitRef,
type DeployStore,
type Deployment,
@@ -26,18 +27,22 @@ export interface DeployFile {
data: string | Uint8Array;
}
-export interface DeployInput {
- ownerScopeId: ScopeId;
- createdBy: string;
- createdInScope?: ScopeId;
+export interface RedeployInput {
entrypoint: string;
files: DeployFile[];
homeFiles?: DeployFile[];
- name?: string;
env?: Record<string, string>;
+ stampEnv?: Record<string, string>;
alwaysOn?: boolean;
}
+export interface DeployInput extends RedeployInput {
+ ownerScopeId: ScopeId;
+ createdBy: string;
+ createdInScope?: ScopeId;
+ name?: string;
+}
+
export type Reach =
{ status: "ok"; id: string; endpoint: DeployEndpoint } | { status: "denied" } | { status: "not_found" };
@@ -49,6 +54,7 @@ export interface DeployOrUpdateInput {
files?: DeployFile[];
homeFiles?: DeployFile[];
env?: Record<string, string>;
+ stampEnv?: Record<string, string>;
renameFrom?: string;
rollbackTo?: number;
share?: Array<{ scope: ScopeId; permission: Permission }>;
@@ -64,16 +70,7 @@ export interface ReachOptions {
export interface DeployService {
readonly providerProfile: DeployProfile;
deploy(input: DeployInput): Promise<Deployment>;
- redeploy(
- id: string,
- input: {
- entrypoint: string;
- files: DeployFile[];
- homeFiles?: DeployFile[];
- env?: Record<string, string>;
- alwaysOn?: boolean;
- },
- ): Promise<Deployment>;
+ redeploy(id: string, input: RedeployInput): Promise<Deployment>;
getDeployment(idOrName: string): Promise<Deployment | null>;
listDeployments(): Promise<Deployment[]>;
rollbackDeployment(id: string, version: number, options?: { alwaysOn?: boolean }): Promise<void>;
@@ -143,9 +140,8 @@ function validateDisplayName(displayName: string): void {
if (displayName.length > DISPLAY_NAME_MAX) throw new Error(`display name too long (max ${DISPLAY_NAME_MAX} chars)`);
}
-function deploymentEntrypoint(d: Deployment | null): string | undefined {
- if (!d) return undefined;
- return d.versions.find((v) => v.version === d.currentVersion)?.entrypoint || undefined;
+export function deploymentEntrypoint(d: Deployment | null): string | undefined {
+ return currentVersionOf(d)?.entrypoint || undefined;
}
function requiredEntrypoint(input: string | undefined, d: Deployment | null): string {
@@ -208,7 +204,7 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {
const liveEndpoint = async (d: Deployment): Promise<DeployEndpoint> => {
if (!deps.provider.resolveEndpoint || d.endpoint == null) return d.endpoint!;
- const version = d.versions.find((v) => v.version === d.currentVersion);
+ const version = currentVersionOf(d);
if (!version) return d.endpoint;
const resolved = await deps.provider.resolveEndpoint(d, version);
if (resolved) {
@@ -217,7 +213,7 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {
}
return withDeployLock(d.id, async () => {
const cur = (await deps.deployStore.get(d.id)) ?? d;
- const v = cur.versions.find((x) => x.version === cur.currentVersion) ?? version;
+ const v = currentVersionOf(cur) ?? version;
const again = await deps.provider.resolveEndpoint!(cur, v);
if (again) {
if (!endpointsEqual(again, cur.endpoint)) await deps.deployStore.setEndpoint(cur.id, again);
@@ -360,6 +356,7 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {
}
const snapshotDir = await snapshotFiles(deps.deployDir, input.files);
const homeDir = input.homeFiles?.length ? await snapshotFiles(deps.deployDir, input.homeFiles) : undefined;
+ const env = input.stampEnv ? { ...input.env, ...input.stampEnv } : input.env;
const d = await deps.deployStore.create({
ownerScopeId: input.ownerScopeId,
createdBy: input.createdBy,
@@ -369,7 +366,7 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {
...(homeDir ? { homeDir } : {}),
...(input.name !== undefined ? { name: input.name } : {}),
...(input.createdInScope !== undefined ? { createdInScope: input.createdInScope } : {}),
- ...(input.env ? { env: input.env } : {}),
+ ...(env ? { env } : {}),
...(input.alwaysOn !== undefined ? { alwaysOn: input.alwaysOn } : {}),
});
const endpoint = await applyVersion(d.id, d.versions[0]!);
@@ -387,25 +384,28 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {
async redeploy(id, input) {
return withDeployLock(id, async () => {
const before = await deps.deployStore.get(id);
+ if (!before) throw new Error(`unknown deployment: ${id}`);
+ const current = currentVersionOf(before);
const snapshotDir = await snapshotFiles(deps.deployDir, input.files);
- const homeDir = input.homeFiles?.length ? await snapshotFiles(deps.deployDir, input.homeFiles) : undefined;
+ let homeDir = input.homeFiles === undefined ? current?.homeDir : undefined;
+ if (input.homeFiles?.length) homeDir = await snapshotFiles(deps.deployDir, input.homeFiles);
+ const inherited = input.env ?? current?.env;
+ const env = input.stampEnv ? { ...inherited, ...input.stampEnv } : inherited;
const v = await deps.deployStore.addVersion(id, {
entrypoint: input.entrypoint,
snapshotDir,
files: input.files,
...(homeDir ? { homeDir } : {}),
- ...(input.env ? { env: input.env } : {}),
+ ...(env ? { env } : {}),
});
- const d = await deps.deployStore.get(id);
- if (!d) throw new Error(`unknown deployment: ${id}`);
- const endpoint = await applyVersion(id, v, before?.appliedVersion ?? before?.currentVersion, input.alwaysOn);
+ const endpoint = await applyVersion(id, v, before.appliedVersion ?? before.currentVersion, input.alwaysOn);
await markVersionRunning(id, v.version, endpoint);
deps.auditLog.record({
at: Date.now(),
- principalId: d.createdBy,
+ principalId: before.createdBy,
action: "deploy_version",
resource: `${id}@v${v.version}`,
- scopeLabel: d.ownerScopeId,
+ scopeLabel: before.ownerScopeId,
});
return (await deps.deployStore.get(id))!;
});
@@ -454,7 +454,7 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {
if (!d) throw new Error(`unknown deployment: ${id}`);
if (d.status === "running") return d;
if (d.status !== "archived") throw new Error(`deployment is not archived: ${id}`);
- const version = d.versions.find((v) => v.version === d.currentVersion);
+ const version = currentVersionOf(d);
if (!version) throw new Error(`no such version ${d.currentVersion}`);
try {
const endpoint = await applyVersion(id, version, d.appliedVersion);
@@ -655,7 +655,7 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {
resource: existing.id,
scopeLabel: existing.ownerScopeId,
});
- if ((input.entrypoint !== undefined || input.files !== undefined) && input.files) {
+ if (input.files?.length) {
const entrypoint = requiredEntrypoint(input.entrypoint, existing);
await this.redeploy(existing.id, {
entrypoint,
@@ -663,6 +663,7 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {
...(input.alwaysOn !== undefined ? { alwaysOn: input.alwaysOn } : {}),
...(input.homeFiles ? { homeFiles: input.homeFiles } : {}),
...(input.env ? { env: input.env } : {}),
+ ...(input.stampEnv ? { stampEnv: input.stampEnv } : {}),
});
if (input.defaultAudience)
await reconcileDefaultAudience((await deps.deployStore.get(existing.id))!, input.defaultAudience, false);
@@ -704,6 +705,7 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {
...(input.alwaysOn !== undefined ? { alwaysOn: input.alwaysOn } : {}),
...(input.homeFiles ? { homeFiles: input.homeFiles } : {}),
...(input.env ? { env: input.env } : {}),
+ ...(input.stampEnv ? { stampEnv: input.stampEnv } : {}),
});
isCreate = false;
} else {
@@ -717,6 +719,7 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {
...(input.name !== undefined ? { name: input.name } : {}),
...(input.createdInScope !== undefined ? { createdInScope: input.createdInScope } : {}),
...(input.env ? { env: input.env } : {}),
+ ...(input.stampEnv ? { stampEnv: input.stampEnv } : {}),
...(input.alwaysOn !== undefined ? { alwaysOn: input.alwaysOn } : {}),
});
isCreate = true;
diff --git a/src/deploy/deploy-store.ts b/src/deploy/deploy-store.ts
index 9fea7aa53..81b088a76 100644
--- a/src/deploy/deploy-store.ts
+++ b/src/deploy/deploy-store.ts
@@ -73,6 +73,10 @@ export interface Deployment {
versions: DeploymentVersion[];
}
+export function currentVersionOf(d: Deployment | null): DeploymentVersion | undefined {
+ return d?.versions.find((v) => v.version === d.currentVersion);
+}
+
interface VersionInput {
entrypoint: string;
snapshotDir: string;
@@ -328,7 +332,7 @@ export function createDeployStore(backing?: DurableMap<Deployment> | DeployStore
const d = await backingMap.get(id);
if (!d) throw new Error(`unknown deployment: ${id}`);
const version = d.versions.length + 1;
- const parentCommit = d.versions.find((x) => x.version === d.currentVersion)?.commit;
+ const parentCommit = currentVersionOf(d)?.commit;
const v = await makeVersion(id, version, input, parentCommit);
d.versions.push(v);
d.currentVersion = version;
@@ -339,7 +343,7 @@ export function createDeployStore(backing?: DurableMap<Deployment> | DeployStore
async addVersionFromCommit(id, commit) {
const d = await backingMap.get(id);
if (!d) throw new Error(`unknown deployment: ${id}`);
- const current = d.versions.find((x) => x.version === d.currentVersion);
+ const current = currentVersionOf(d);
if (current?.commit === commit) return null;
const version = d.versions.length + 1;
const v: DeploymentVersion = {
diff --git a/src/harness/agent-tools.ts b/src/harness/agent-tools.ts
index e244a7b89..67bc425d1 100644
--- a/src/harness/agent-tools.ts
+++ b/src/harness/agent-tools.ts
@@ -1108,7 +1108,10 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
),
renameFrom: Type.Optional(Type.String({ description: "Rename the deployment currently named this to `name`." })),
env: Type.Optional(
- Type.Record(Type.String(), Type.String(), { description: "Env vars baked into the immutable version." }),
+ Type.Record(Type.String(), Type.String(), {
+ description:
+ "Env vars baked into the version. When republishing, omit to keep the env of the most recent version (including a failed attempt); pass an object to replace it ({} clears).",
+ }),
),
rollbackTo: Type.Optional(
Type.Integer({ description: "Flip the deployment named `name` back to this version number." }),
diff --git a/src/tools/primitives.ts b/src/tools/primitives.ts
index 940250ded..8d7a8bf80 100644
--- a/src/tools/primitives.ts
+++ b/src/tools/primitives.ts
@@ -47,8 +47,8 @@ import type {
BackgroundJobSummary,
} from "../connectors/background-exec-broker.ts";
import type { MonitorBroker, BackgroundWatchResult, BackgroundUnwatchResult } from "../monitors/monitor-broker.ts";
-import type { DeployService, DeployFile } from "../deploy/deploy-service.ts";
-import { publicUrlOf, type Deployment } from "../deploy/deploy-store.ts";
+import { deploymentEntrypoint, type DeployService, type DeployFile } from "../deploy/deploy-service.ts";
+import { publicUrlOf } from "../deploy/deploy-store.ts";
import { carriesGitMetadata } from "../deploy/deploy-fs.ts";
import type { AclStore } from "../acl/acl-store.ts";
import type { AuditLog } from "../audit/audit-log.ts";
@@ -120,11 +120,6 @@ interface PublishResult {
alwaysOn?: boolean;
}
-function deploymentEntrypoint(d: Deployment | null): string | undefined {
- if (!d) return undefined;
- return d.versions.find((v) => v.version === d.currentVersion)?.entrypoint || undefined;
-}
-
export class NeedsApproval extends Error {
command: string;
approvalReason: string;
@@ -1001,7 +996,6 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {
),
)
: {};
- const env = { ...input.env, ...authEnv };
const pc = deps.publishContext;
const aud: PublishAudience =
@@ -1036,7 +1030,8 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {
...(input.entrypoint ? { entrypoint: input.entrypoint } : {}),
...(input.name !== undefined ? { name: input.name } : {}),
...(input.renameFrom !== undefined ? { renameFrom: input.renameFrom } : {}),
- ...(Object.keys(env).length ? { env } : {}),
+ ...(input.env !== undefined ? { env: input.env } : {}),
+ ...(Object.keys(authEnv).length ? { stampEnv: authEnv } : {}),
...(input.rollbackTo !== undefined ? { rollbackTo: input.rollbackTo } : {}),
...(input.alwaysOn !== undefined ? { alwaysOn: input.alwaysOn } : {}),
...(doReconcile
diff --git a/test/deploy-environment.test.ts b/test/deploy-environment.test.ts
index 7b2e3189d..9e8007ede 100644
--- a/test/deploy-environment.test.ts
+++ b/test/deploy-environment.test.ts
@@ -61,3 +61,36 @@ test("deploy-service: without deploymentEnv the provider sees no deployment env"
await s.service.deploy({ ownerScopeId: scopeId("personal", "U1"), createdBy: "U1", entrypoint: "node x", files: [] });
assert.equal(s.applied?.env?.AGENT_CREDENTIAL_TOKEN, undefined);
});
+
+test("deploy-service: redeploy inherits the current version's env and home files unless the input replaces them", async () => {
+ const s = svc(async () => ({ VIEWER_IDENTITY_KEY: "viewer" }));
+ const d = await s.service.deploy({
+ ownerScopeId: scopeId("personal", "U1"),
+ createdBy: "U1",
+ entrypoint: "node x",
+ files: [],
+ homeFiles: [{ path: ".npmrc", data: "token" }],
+ env: { DB_URL: "postgres://one" },
+ });
+ const versionAt = async (n: number) => (await s.deployStore.get(d.id))!.versions[n - 1]!;
+
+ await s.service.redeploy(d.id, { entrypoint: "node x", files: [] });
+ assert.deepEqual((await versionAt(2)).env, { DB_URL: "postgres://one" }, "omitted env inherits");
+ assert.equal((await versionAt(2)).homeDir, (await versionAt(1)).homeDir, "omitted homeFiles inherit");
+ assert.deepEqual(s.applied?.env, { DB_URL: "postgres://one", VIEWER_IDENTITY_KEY: "viewer" }, "deploymentEnv on top");
+
+ await s.service.redeploy(d.id, { entrypoint: "node x", files: [], env: { DB_URL: "postgres://two" } });
+ assert.deepEqual((await versionAt(3)).env, { DB_URL: "postgres://two" }, "provided env replaces");
+
+ await s.service.redeploy(d.id, { entrypoint: "node x", files: [], env: {}, homeFiles: [] });
+ assert.deepEqual((await versionAt(4)).env, {}, "an empty env clears");
+ assert.equal((await versionAt(4)).homeDir, undefined, "empty homeFiles clear");
+ assert.deepEqual(s.applied?.env, { VIEWER_IDENTITY_KEY: "viewer" });
+
+ await s.service.rollbackDeployment(d.id, 3);
+ await s.service.redeploy(d.id, { entrypoint: "node x", files: [] });
+ assert.deepEqual((await versionAt(5)).env, { DB_URL: "postgres://two" }, "inherits from the rolled-back version");
+
+ await s.service.redeploy(d.id, { entrypoint: "node x", files: [], stampEnv: { STAMP: "s" } });
+ assert.deepEqual((await versionAt(6)).env, { DB_URL: "postgres://two", STAMP: "s" }, "stampEnv merges on top");
+});
diff --git a/test/deploy-redeploy-route.test.ts b/test/deploy-redeploy-route.test.ts
new file mode 100644
index 000000000..e14b1e134
--- /dev/null
+++ b/test/deploy-redeploy-route.test.ts
@@ -0,0 +1,91 @@
+import { after, before, describe, it } from "node:test";
+import assert from "node:assert/strict";
+import type { Server } from "node:http";
+import type { AddressInfo } from "node:net";
+import { createServer } from "../src/api/server.ts";
+import type { App, RedeployInput } from "../src/api/app.ts";
+import { signRequest } from "../src/auth/source-auth.ts";
+import { scopeId } from "../src/types.ts";
+
+const SECRET = "deploy-redeploy-route-secret".repeat(2);
+
+describe("deployment redeploy route", () => {
+ let server: Server;
+ let base: string;
+ let received: RedeployInput | undefined;
+
+ const post = async (path: string, body: unknown) => {
+ const raw = JSON.stringify(body);
+ const ts = Math.floor(Date.now() / 1000);
+ return fetch(`${base}${path}`, {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ "x-timestamp": String(ts),
+ "x-signature": signRequest(SECRET, ts, `POST\n${path}\n${raw}`),
+ },
+ body: raw,
+ });
+ };
+
+ before(async () => {
+ const deployment = {
+ id: "dep-1",
+ name: "envy",
+ ownerScopeId: scopeId("personal", "U1"),
+ createdBy: "U1",
+ currentVersion: 1,
+ status: "running" as const,
+ endpoint: null,
+ versions: [{ version: 1, createdAt: 1, entrypoint: "x", snapshotDir: "/tmp" }],
+ };
+ const app = {
+ listDeployments: async () => [deployment],
+ canManageDeployment: async () => true,
+ redeploy: async (_id: string, input: RedeployInput) => {
+ received = input;
+ return deployment;
+ },
+ } as unknown as App;
+ server = createServer(app, { signingSecret: SECRET });
+ await new Promise<void>((resolve) => server.listen(0, resolve));
+ base = `http://localhost:${(server.address() as AddressInfo).port}`;
+ });
+
+ after(async () => {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ });
+
+ it("forwards env, home files and alwaysOn to the deploy service and answers with the view", async () => {
+ const body = {
+ entrypoint: "node app.js",
+ files: [{ path: "app.js", data: "listen" }],
+ homeFiles: [{ path: ".npmrc", data: "token" }],
+ env: { DB_URL: "postgres://one" },
+ alwaysOn: false,
+ };
+ const response = await post("/v1/deployments/envy/redeploy", body);
+ assert.equal(response.status, 200);
+ assert.deepEqual(received, body);
+ const { deployment } = (await response.json()) as { deployment: { versions: Record<string, unknown>[] } };
+ assert.deepEqual(Object.keys(deployment.versions[0]!), ["version", "createdAt"], "no snapshot paths or env");
+ });
+
+ it("still requires an entrypoint and files", async () => {
+ assert.equal((await post("/v1/deployments/envy/redeploy", { env: { A: "1" } })).status, 400);
+ });
+
+ it("rejects malformed optional fields", async () => {
+ const valid = { entrypoint: "node app.js", files: [] };
+ for (const bad of [
+ { alwaysOn: "false" },
+ { env: "DB=two" },
+ { env: null },
+ { env: ["A=1"] },
+ { homeFiles: null },
+ ]) {
+ const response = await post("/v1/deployments/envy/redeploy", { ...valid, ...bad });
+ assert.equal(response.status, 400, JSON.stringify(bad));
+ }
+ });
+});
diff --git a/test/publish-primitive.test.ts b/test/publish-primitive.test.ts
index 188263250..990fa99f2 100644
--- a/test/publish-primitive.test.ts
+++ b/test/publish-primitive.test.ts
@@ -48,6 +48,7 @@ interface CtxOpts {
ledger?: ToolLedger;
runId?: string;
rw?: boolean;
+ splitEnv?: Record<string, string>;
}
function fileSandbox(files: Array<{ path: string; data: Uint8Array }>): Sandbox {
@@ -81,6 +82,9 @@ function ctx(deploy: DeployService, opts: CtxOpts = {}) {
createdBy: "U1",
...(opts.ledger ? { ledger: opts.ledger } : {}),
...(opts.runId ? { runId: opts.runId } : {}),
+ ...(opts.splitEnv
+ ? { actingSlackUserId: "U1", layerAuth: { credentialPaths: [], splitEnvTemplates: [opts.splitEnv] } }
+ : {}),
});
}
@@ -201,6 +205,42 @@ test("publish by name inherits the current entrypoint when redeploying without o
);
});
+test("publish by name keeps the previous version's env unless the call replaces it", async () => {
+ const s = svc();
+ const files = [{ path: "app/server.js", data: bytes("v1") }];
+ await ctx(s.deploy, { files }).publish({
+ dir: "app",
+ entrypoint: "node server.js",
+ name: "dash",
+ env: { DB: "one" },
+ });
+ await ctx(s.deploy, { files }).publish({ dir: "app", name: "dash" });
+ await ctx(s.deploy, { files }).publish({ dir: "app", name: "dash", env: { OTHER: "x" } });
+ await ctx(s.deploy, { files }).publish({ dir: "app", name: "dash", env: {} });
+ const envs = (await s.deployStore.getByName("dash"))!.versions.map((v) => v.env);
+ assert.deepEqual(envs, [{ DB: "one" }, { DB: "one" }, { OTHER: "x" }, {}]);
+});
+
+test("publish from a layer with split env stamps it on top of the previous version's env when env is omitted", async () => {
+ const s = svc();
+ const files = [{ path: "app/server.js", data: bytes("v1") }];
+ const splitEnv = { ACTING: "{actingSlackUserId}" };
+ await ctx(s.deploy, { files, splitEnv }).publish({
+ dir: "app",
+ entrypoint: "node server.js",
+ name: "dash",
+ env: { DB: "one" },
+ });
+ await ctx(s.deploy, { files, splitEnv }).publish({ dir: "app", name: "dash", env: { DB: "two" } });
+ await ctx(s.deploy, { files, splitEnv }).publish({ dir: "app", name: "dash" });
+ const envs = (await s.deployStore.getByName("dash"))!.versions.map((v) => v.env);
+ assert.deepEqual(envs, [
+ { DB: "one", ACTING: "U1" },
+ { DB: "two", ACTING: "U1" },
+ { DB: "two", ACTING: "U1" },
+ ]);
+});
+
test("publish without an entrypoint and without a prior version fails before provisioning", async () => {
const s = svc();
let provisioned = false;
@@ -248,6 +288,7 @@ test("publish: renameFrom moves the link but keeps the id (and shares ride the i
assert.equal(renamed.id, created.id);
assert.equal(renamed.url, "/d/new-name/");
+ assert.equal((await s.deployStore.getByName("new-name"))!.versions.length, 1, "a pure rename ships no version");
assert.equal(await s.deployStore.getByName("old-name"), null);
assert.equal((await s.deployStore.getByName("new-name"))!.id, created.id);
assert.equal((await s.acl.grantsFor(scopeId("personal", "U1"), `deployment:${created.id}`)).length, 1);