@tsplc/compiler 0.5.8 → 0.5.10
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/dist/bun-runtime.js +8 -2
- package/dist/bun-runtime.js.map +3 -3
- package/dist/cli.js +353 -58
- package/dist/cli.js.map +9 -7
- package/dist/codesys.js +1567 -1507
- package/dist/codesys.js.map +13 -13
- package/dist/index.js +818 -681
- package/dist/index.js.map +17 -16
- package/dist/ir.js +13 -42
- package/dist/ir.js.map +6 -5
- package/dist/telemetry.js +8 -2
- package/dist/telemetry.js.map +3 -3
- package/package.json +9 -9
- package/src/codesys/emit.ts +2 -1
- package/src/codesys/engineering.ts +27 -12
- package/src/codesys/plan.ts +9 -22
- package/src/codesys/programs.ts +61 -1
- package/src/codesys/types.ts +34 -12
- package/src/frontend/async.ts +14 -8
- package/src/frontend/coroutines.ts +55 -16
- package/src/frontend/elaborate/expressions.ts +10 -2
- package/src/frontend/elaborate/filtered-arrays.ts +5 -5
- package/src/frontend/elaborate/index.ts +26 -3
- package/src/frontend/elaborate/model.ts +48 -1
- package/src/frontend/elaborate/references.ts +6 -6
- package/src/frontend/elaborate/specialize.ts +18 -4
- package/src/frontend/elaborate/storage.ts +3 -2
- package/src/frontend/generated-names.ts +95 -0
- package/src/frontend/promise-chains.ts +22 -8
- package/src/frontend/promises.ts +8 -10
- package/src/frontend/tasks.ts +8 -8
- package/src/frontend/typescript.ts +2 -2
- package/src/ir/identity.ts +9 -0
- package/src/ir/index.ts +8 -2
- package/src/ir/job-errors.ts +14 -0
- package/src/ir/share.ts +0 -52
- package/src/project/cli.ts +14 -3
- package/src/project/deployments.ts +443 -0
- package/src/project/git.ts +35 -0
- package/src/project/plant.ts +68 -34
package/src/ir/index.ts
CHANGED
|
@@ -42,7 +42,14 @@ export {
|
|
|
42
42
|
nanosecondsPerMillisecond,
|
|
43
43
|
} from "./domains";
|
|
44
44
|
export { fold } from "./fold";
|
|
45
|
-
export {
|
|
45
|
+
export { identityDigest } from "./identity";
|
|
46
|
+
export {
|
|
47
|
+
errorName,
|
|
48
|
+
httpErrors,
|
|
49
|
+
jobError,
|
|
50
|
+
jobErrors,
|
|
51
|
+
reservedErrors,
|
|
52
|
+
} from "./job-errors";
|
|
46
53
|
export { layoutIssue, maxNestingDepth, maxScalarElements } from "./layouts";
|
|
47
54
|
export {
|
|
48
55
|
type Artifact,
|
|
@@ -91,7 +98,6 @@ export {
|
|
|
91
98
|
export { scalarIssue } from "./scalars";
|
|
92
99
|
export {
|
|
93
100
|
foldConstantRoutines,
|
|
94
|
-
joinPrograms,
|
|
95
101
|
type SharedRoutines,
|
|
96
102
|
shareRoutines,
|
|
97
103
|
} from "./share";
|
package/src/ir/job-errors.ts
CHANGED
|
@@ -7,11 +7,20 @@ export const jobError = {
|
|
|
7
7
|
network: 5,
|
|
8
8
|
tls: 6,
|
|
9
9
|
noRequestSlot: 7,
|
|
10
|
+
/**
|
|
11
|
+
* An online change replaced the code of a job that was running: its step and stored state
|
|
12
|
+
* were made for the old code, so it stops instead of resuming in the new. Like `cancelled`,
|
|
13
|
+
* it skips `catch`, so a retry can't send a request twice.
|
|
14
|
+
*/
|
|
15
|
+
codeChanged: 11001,
|
|
10
16
|
} as const;
|
|
11
17
|
|
|
12
18
|
/** An HTTP response fails a job with `base` + its status, up to `last`. */
|
|
13
19
|
export const httpErrors = { base: 10000, last: 10999 };
|
|
14
20
|
|
|
21
|
+
/** Codes tsPLC itself reports from 11000 on, which a program's own `throw` may not use. */
|
|
22
|
+
export const reservedErrors = { first: 11000, last: 11099 };
|
|
23
|
+
|
|
15
24
|
/** Job error codes, as every generated async block and service call reports them. */
|
|
16
25
|
export const jobErrors: Record<string, string> = {
|
|
17
26
|
[jobError.cancelled]: "cancelled",
|
|
@@ -21,6 +30,8 @@ export const jobErrors: Record<string, string> = {
|
|
|
21
30
|
[jobError.network]: "network error or server restarted",
|
|
22
31
|
[jobError.tls]: "TLS error",
|
|
23
32
|
[jobError.noRequestSlot]: "no free request slot",
|
|
33
|
+
[jobError.codeChanged]:
|
|
34
|
+
"an online change replaced the job's code while it ran",
|
|
24
35
|
[httpErrors.base]: "HTTP status: 10000 + status code",
|
|
25
36
|
};
|
|
26
37
|
|
|
@@ -29,5 +40,8 @@ export const errorName = (code: number): string | undefined => {
|
|
|
29
40
|
if (code > httpErrors.base && code <= httpErrors.last) {
|
|
30
41
|
return `HTTP ${code - httpErrors.base}`;
|
|
31
42
|
}
|
|
43
|
+
if (code >= reservedErrors.first && code <= reservedErrors.last) {
|
|
44
|
+
return jobErrors[code];
|
|
45
|
+
}
|
|
32
46
|
return code < httpErrors.base ? jobErrors[code] : undefined;
|
|
33
47
|
};
|
package/src/ir/share.ts
CHANGED
|
@@ -681,58 +681,6 @@ const returns = (items: readonly CoreStatement[]): boolean =>
|
|
|
681
681
|
(item) => item.kind === "return" || nestedBodies(item).some(returns),
|
|
682
682
|
);
|
|
683
683
|
|
|
684
|
-
/**
|
|
685
|
-
* Joins each group of programs into its first: one entry that runs the entries' bodies in the
|
|
686
|
-
* group's order, which is the order a task runs them in. An entry that can return early would
|
|
687
|
-
* skip the ones after it, so it stays a program of its own. `routines` maps each entry joined
|
|
688
|
-
* away to the entry that now runs it.
|
|
689
|
-
*/
|
|
690
|
-
export function joinPrograms(
|
|
691
|
-
core: VerifiedCoreModule,
|
|
692
|
-
groups: readonly (readonly string[])[],
|
|
693
|
-
): SharedRoutines {
|
|
694
|
-
const functions = new Map(core.functions.map((fn) => [fn.id, fn]));
|
|
695
|
-
const programs = new Map(core.programs.map((item) => [item.name, item]));
|
|
696
|
-
const joined = new Map<string, CoreFunction>();
|
|
697
|
-
const routines = new Map<string, string>();
|
|
698
|
-
const removed = new Set<string>();
|
|
699
|
-
for (const group of groups) {
|
|
700
|
-
const members = group.flatMap((name) => {
|
|
701
|
-
const program = programs.get(name);
|
|
702
|
-
const entry = program && functions.get(program.entry);
|
|
703
|
-
return program && entry && !returns(entry.body)
|
|
704
|
-
? [{ program, entry }]
|
|
705
|
-
: [];
|
|
706
|
-
});
|
|
707
|
-
const [first, ...rest] = members;
|
|
708
|
-
if (!first || !rest.length) {
|
|
709
|
-
continue;
|
|
710
|
-
}
|
|
711
|
-
joined.set(first.entry.id, {
|
|
712
|
-
...first.entry,
|
|
713
|
-
locals: members.flatMap(({ entry }) => entry.locals),
|
|
714
|
-
body: members.flatMap(({ entry }) => entry.body),
|
|
715
|
-
});
|
|
716
|
-
for (const { program, entry } of rest) {
|
|
717
|
-
removed.add(program.name);
|
|
718
|
-
routines.set(entry.id, first.entry.id);
|
|
719
|
-
}
|
|
720
|
-
}
|
|
721
|
-
if (!routines.size) {
|
|
722
|
-
return { core, routines };
|
|
723
|
-
}
|
|
724
|
-
return {
|
|
725
|
-
core: admitCore({
|
|
726
|
-
...core,
|
|
727
|
-
functions: core.functions.flatMap((fn) =>
|
|
728
|
-
routines.has(fn.id) ? [] : [joined.get(fn.id) ?? fn],
|
|
729
|
-
),
|
|
730
|
-
programs: core.programs.filter((item) => !removed.has(item.name)),
|
|
731
|
-
}),
|
|
732
|
-
routines,
|
|
733
|
-
};
|
|
734
|
-
}
|
|
735
|
-
|
|
736
684
|
/** A routine that only returns a constant, or does nothing: what each of its calls amounts to. */
|
|
737
685
|
function constantResult(
|
|
738
686
|
fn: CoreFunction,
|
package/src/project/cli.ts
CHANGED
|
@@ -20,7 +20,10 @@ Run the TypeScript program in Bun instead of CODESYS, with OPC UA on opc.tcp://1
|
|
|
20
20
|
tsplc run --simulate --bun [--foreground] [--target name]
|
|
21
21
|
|
|
22
22
|
Plant agent (the target's agent, else TSPLC_AGENT_URL; TSPLC_AGENT_TOKEN):
|
|
23
|
-
tsplc deploy [--target name] [--download] [--select] [--initialize-user] [--simulate]
|
|
23
|
+
tsplc deploy [--target name] [--download] [--select] [--initialize-user] [--simulate] [--review] [--wait]
|
|
24
|
+
tsplc deployments [--format json] | dashboard
|
|
25
|
+
tsplc rollback [id] [--wait] | redeploy <id> [--review] [--wait]
|
|
26
|
+
(--wait follows the deployment and exits 2 while it waits for approval; -y approves)
|
|
24
27
|
tsplc target | status | login | logout
|
|
25
28
|
tsplc vars [path] | read <expression>... | write <expression> <value>
|
|
26
29
|
tsplc force <expression> <value> | unforce [expression]... [--restore]
|
|
@@ -81,6 +84,8 @@ async function main() {
|
|
|
81
84
|
port: { type: "string" },
|
|
82
85
|
"server-url": { type: "string" },
|
|
83
86
|
opcua: { type: "boolean" },
|
|
87
|
+
review: { type: "boolean" },
|
|
88
|
+
wait: { type: "boolean" },
|
|
84
89
|
},
|
|
85
90
|
});
|
|
86
91
|
const values = {
|
|
@@ -120,12 +125,18 @@ async function main() {
|
|
|
120
125
|
// In a project, the target names the agent; elsewhere TSPLC_AGENT_URL does.
|
|
121
126
|
const loaded = existsSync(file) ? await load() : undefined;
|
|
122
127
|
const env = loaded?.env ?? process.env;
|
|
123
|
-
const
|
|
128
|
+
const outcome = await runPlantCommand(connect(env), plant, args, values, {
|
|
124
129
|
file,
|
|
125
130
|
load: loaded ? async () => loaded : load,
|
|
126
131
|
environment: env,
|
|
132
|
+
interactive: process.stdin.isTTY === true,
|
|
127
133
|
});
|
|
128
|
-
|
|
134
|
+
if (!outcome) {
|
|
135
|
+
return 0;
|
|
136
|
+
}
|
|
137
|
+
return "exitCode" in outcome
|
|
138
|
+
? outcome.exitCode
|
|
139
|
+
: report(outcome, values.format);
|
|
129
140
|
}
|
|
130
141
|
if (args.length) {
|
|
131
142
|
throw new Error("Specify one command.");
|
|
@@ -0,0 +1,443 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import type {
|
|
3
|
+
DeploymentMode,
|
|
4
|
+
DeploymentRecord,
|
|
5
|
+
DeployOptions,
|
|
6
|
+
GitSource,
|
|
7
|
+
} from "@tsplc/agent";
|
|
8
|
+
import {
|
|
9
|
+
type AgentClient,
|
|
10
|
+
AgentOperationError,
|
|
11
|
+
AgentUnreachable,
|
|
12
|
+
} from "@tsplc/agent/client";
|
|
13
|
+
import { describeFinding } from "@tsplc/build";
|
|
14
|
+
import { progress, timedProgress } from "./terminal";
|
|
15
|
+
|
|
16
|
+
/** `tsplc deploy --wait` and the like exit with this while the deployment waits on a person. */
|
|
17
|
+
export const awaitingApprovalExit = 2;
|
|
18
|
+
|
|
19
|
+
/** How a command that follows a deployment may ask before it approves one. */
|
|
20
|
+
export interface Approval {
|
|
21
|
+
/** Approve without asking: `--yes`. */
|
|
22
|
+
yes: boolean;
|
|
23
|
+
/** Someone at a terminal can answer. */
|
|
24
|
+
interactive: boolean;
|
|
25
|
+
/** Asks a yes-or-no question. */
|
|
26
|
+
confirm: (question: string) => Promise<boolean>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** What a command that queues a deployment does once it is queued. */
|
|
30
|
+
export interface Follow {
|
|
31
|
+
/** Follow it until it finishes: `--wait`. */
|
|
32
|
+
wait: boolean;
|
|
33
|
+
approval: Approval;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** How often, a second apart, following a deployment reconnects before it gives up. */
|
|
37
|
+
const reconnectAttempts = 5;
|
|
38
|
+
const reconnectDelay = 1000;
|
|
39
|
+
|
|
40
|
+
const stateMessage = (record: DeploymentRecord) => {
|
|
41
|
+
switch (record.state) {
|
|
42
|
+
case "queued":
|
|
43
|
+
return "Queued.";
|
|
44
|
+
case "building":
|
|
45
|
+
return "Building the release…";
|
|
46
|
+
case "applying":
|
|
47
|
+
return record.operation === "download"
|
|
48
|
+
? "Downloading the program; the application stops while it loads…"
|
|
49
|
+
: "Applying the online change…";
|
|
50
|
+
case "starting":
|
|
51
|
+
return "Starting the server…";
|
|
52
|
+
case "verifying":
|
|
53
|
+
return "Checking the deployment's health…";
|
|
54
|
+
default:
|
|
55
|
+
return undefined;
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
const printFindings = (record: DeploymentRecord) => {
|
|
60
|
+
if (!record.findings.length) {
|
|
61
|
+
progress("No findings.");
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
for (const finding of record.findings) {
|
|
65
|
+
progress(
|
|
66
|
+
`${finding.refuses ? "refuses" : "note"}: ${describeFinding(finding)}`,
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
/** Whether to approve: `--yes` does, a person may, and null when nobody can be asked. */
|
|
72
|
+
const decide = async (approval: Approval, question: string) => {
|
|
73
|
+
if (approval.yes) {
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
if (!approval.interactive) {
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
return approval.confirm(question);
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Shows what a deployment waits on and approves it when the deployer agrees. False when it is
|
|
84
|
+
* left waiting.
|
|
85
|
+
*/
|
|
86
|
+
const approve = async (
|
|
87
|
+
agent: AgentClient,
|
|
88
|
+
record: DeploymentRecord,
|
|
89
|
+
reason: "review" | "downloadRequired",
|
|
90
|
+
{ url, approval }: { url: string; approval: Approval },
|
|
91
|
+
) => {
|
|
92
|
+
const download = reason === "downloadRequired";
|
|
93
|
+
if (download) {
|
|
94
|
+
console.log(
|
|
95
|
+
"Only a full download can deploy this release, and a full download stops the running application while it loads.",
|
|
96
|
+
);
|
|
97
|
+
} else {
|
|
98
|
+
console.log("The review found what the online change would do:");
|
|
99
|
+
}
|
|
100
|
+
printFindings(record);
|
|
101
|
+
const approved = await decide(
|
|
102
|
+
approval,
|
|
103
|
+
download ? "Download now?" : "Apply it?",
|
|
104
|
+
);
|
|
105
|
+
if (!approved) {
|
|
106
|
+
console.log(
|
|
107
|
+
approved === null
|
|
108
|
+
? `It waits for approval on the dashboard: ${url}`
|
|
109
|
+
: `It waits for approval or cancellation on the dashboard: ${url}`,
|
|
110
|
+
);
|
|
111
|
+
return false;
|
|
112
|
+
}
|
|
113
|
+
await agent.approve(record.id, { download });
|
|
114
|
+
console.log(download ? "Approved the full download." : "Approved.");
|
|
115
|
+
return true;
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Follows a deployment until it finishes, printing its log and the states it goes through, and
|
|
120
|
+
* asking for approval when it waits on one. Reconnects from the last log line it printed. The
|
|
121
|
+
* exit code: 0 when it is ready, `awaitingApprovalExit` when it is left waiting; a failed or
|
|
122
|
+
* canceled deployment throws.
|
|
123
|
+
*/
|
|
124
|
+
export const followDeployment = async (
|
|
125
|
+
agent: AgentClient,
|
|
126
|
+
deployment: { id: string; url: string },
|
|
127
|
+
approval: Approval,
|
|
128
|
+
): Promise<number> => {
|
|
129
|
+
const seen: {
|
|
130
|
+
after: number;
|
|
131
|
+
state: DeploymentRecord["state"] | null;
|
|
132
|
+
approval: string | null;
|
|
133
|
+
failures: number;
|
|
134
|
+
} = { after: 0, state: null, approval: null, failures: 0 };
|
|
135
|
+
|
|
136
|
+
/** The exit code once the deployment is done with this command, else undefined. */
|
|
137
|
+
const onRecord = async (record: DeploymentRecord) => {
|
|
138
|
+
if (record.state !== seen.state) {
|
|
139
|
+
seen.state = record.state;
|
|
140
|
+
const message = stateMessage(record);
|
|
141
|
+
if (message) {
|
|
142
|
+
console.log(message);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
if (record.state !== "awaitingApproval" || !record.approval) {
|
|
146
|
+
seen.approval = null;
|
|
147
|
+
} else {
|
|
148
|
+
const asked = `${record.approval.reason}: ${record.approval.message}`;
|
|
149
|
+
if (asked !== seen.approval) {
|
|
150
|
+
seen.approval = asked;
|
|
151
|
+
console.log(record.approval.message);
|
|
152
|
+
const approved = await approve(agent, record, record.approval.reason, {
|
|
153
|
+
url: deployment.url,
|
|
154
|
+
approval,
|
|
155
|
+
});
|
|
156
|
+
if (!approved) {
|
|
157
|
+
return awaitingApprovalExit;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
if (record.state === "ready") {
|
|
162
|
+
const { health } = record;
|
|
163
|
+
console.log(
|
|
164
|
+
health
|
|
165
|
+
? `Ready: controller ${health.controller}, server ${health.server}, PLC ${health.plc}.${health.detail ? ` ${health.detail}` : ""}`
|
|
166
|
+
: "Ready.",
|
|
167
|
+
);
|
|
168
|
+
return 0;
|
|
169
|
+
}
|
|
170
|
+
if (record.state === "error") {
|
|
171
|
+
throw new Error(
|
|
172
|
+
`The deployment failed: ${record.error?.message ?? "no reason given"}. ${deployment.url}`,
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
if (record.state === "canceled") {
|
|
176
|
+
throw new Error(`The deployment was canceled. ${deployment.url}`);
|
|
177
|
+
}
|
|
178
|
+
return undefined;
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
while (true) {
|
|
182
|
+
try {
|
|
183
|
+
for await (const event of agent.deploymentEvents(
|
|
184
|
+
deployment.id,
|
|
185
|
+
seen.after,
|
|
186
|
+
)) {
|
|
187
|
+
seen.failures = 0;
|
|
188
|
+
if (event.kind === "record") {
|
|
189
|
+
const exit = await onRecord(event.record);
|
|
190
|
+
if (exit !== undefined) {
|
|
191
|
+
return exit;
|
|
192
|
+
}
|
|
193
|
+
} else if (event.line.seq > seen.after) {
|
|
194
|
+
seen.after = event.line.seq;
|
|
195
|
+
progress(
|
|
196
|
+
event.line.level === "info"
|
|
197
|
+
? event.line.message
|
|
198
|
+
: `${event.line.level}: ${event.line.message}`,
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
} catch (error) {
|
|
203
|
+
if (!(error instanceof AgentUnreachable)) {
|
|
204
|
+
throw error;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
// The stream broke, or ended before the deployment finished.
|
|
208
|
+
seen.failures += 1;
|
|
209
|
+
if (seen.failures > reconnectAttempts) {
|
|
210
|
+
throw new Error(
|
|
211
|
+
`Lost the connection to the plant agent; the deployment goes on: ${deployment.url}`,
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
await Bun.sleep(reconnectDelay);
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
/** Prints a queued deployment's page, then follows it when asked to. */
|
|
219
|
+
const queued = async (
|
|
220
|
+
agent: AgentClient,
|
|
221
|
+
created: { id: string; url: string },
|
|
222
|
+
follow: Follow,
|
|
223
|
+
) => {
|
|
224
|
+
console.log(`Deployment ${created.id} queued: ${created.url}`);
|
|
225
|
+
if (!follow.wait) {
|
|
226
|
+
return 0;
|
|
227
|
+
}
|
|
228
|
+
return followDeployment(agent, created, follow.approval);
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Uploads a built release as a queued deployment and prints its page. An agent without the
|
|
233
|
+
* deployments API deploys it at once instead, as `tsplc deploy` did before.
|
|
234
|
+
*/
|
|
235
|
+
export const submitDeployment = async (
|
|
236
|
+
agent: AgentClient,
|
|
237
|
+
release: Parameters<AgentClient["deploy"]>[0],
|
|
238
|
+
settings: Omit<DeployOptions, "deployment">,
|
|
239
|
+
request: { mode: DeploymentMode; git: GitSource | null },
|
|
240
|
+
follow: Follow,
|
|
241
|
+
) => {
|
|
242
|
+
const uploading = timedProgress();
|
|
243
|
+
const created = await agent.queueDeployment(
|
|
244
|
+
release,
|
|
245
|
+
{ ...settings, deployment: request },
|
|
246
|
+
uploading,
|
|
247
|
+
);
|
|
248
|
+
if (created) {
|
|
249
|
+
uploading("Uploaded");
|
|
250
|
+
if (request.mode === "review" && !follow.wait) {
|
|
251
|
+
console.log("Once reviewed, it waits for approval on its page.");
|
|
252
|
+
}
|
|
253
|
+
return queued(agent, created, follow);
|
|
254
|
+
}
|
|
255
|
+
if (request.mode === "review") {
|
|
256
|
+
throw new Error(
|
|
257
|
+
"This plant agent can't review a deployment before applying it; deploy without --review.",
|
|
258
|
+
);
|
|
259
|
+
}
|
|
260
|
+
console.log("This plant agent can't queue deployments; deploying at once.");
|
|
261
|
+
const deployed = await deployAtOnce(
|
|
262
|
+
agent,
|
|
263
|
+
release,
|
|
264
|
+
settings,
|
|
265
|
+
follow.approval,
|
|
266
|
+
);
|
|
267
|
+
console.log(`Deployed release ${deployed.id} (${deployed.operation}).`);
|
|
268
|
+
return 0;
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
/** Deploys through `POST /deploy`, offering a full download when only one can deploy. */
|
|
272
|
+
const deployAtOnce = async (
|
|
273
|
+
agent: AgentClient,
|
|
274
|
+
release: Parameters<AgentClient["deploy"]>[0],
|
|
275
|
+
settings: Omit<DeployOptions, "deployment">,
|
|
276
|
+
approval: Approval,
|
|
277
|
+
) => {
|
|
278
|
+
const deploying = timedProgress();
|
|
279
|
+
try {
|
|
280
|
+
return await agent.deploy(release, settings, deploying);
|
|
281
|
+
} catch (error) {
|
|
282
|
+
if (
|
|
283
|
+
!(error instanceof AgentOperationError && error.downloadRequired) ||
|
|
284
|
+
!(
|
|
285
|
+
approval.yes ||
|
|
286
|
+
(await approval.confirm(
|
|
287
|
+
`${error.message}. A full download stops the running application while it loads. Download now?`,
|
|
288
|
+
))
|
|
289
|
+
)
|
|
290
|
+
) {
|
|
291
|
+
throw error;
|
|
292
|
+
}
|
|
293
|
+
return agent.deploy(
|
|
294
|
+
release,
|
|
295
|
+
{ ...settings, download: true },
|
|
296
|
+
timedProgress(),
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
};
|
|
300
|
+
|
|
301
|
+
/** The deployments `GET /api/deployments` answers, newest first, with the running and last healthy ones. */
|
|
302
|
+
interface DeploymentList {
|
|
303
|
+
deployments: DeploymentRecord[];
|
|
304
|
+
current: string | null;
|
|
305
|
+
lastGood: string | null;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Where `tsplc rollback` goes without an id: the newest deployment before the running one that
|
|
310
|
+
* ran healthy with another release. Without a running one, the last healthy one.
|
|
311
|
+
*/
|
|
312
|
+
export const rollbackTarget = ({
|
|
313
|
+
deployments,
|
|
314
|
+
current,
|
|
315
|
+
lastGood,
|
|
316
|
+
}: DeploymentList) => {
|
|
317
|
+
const index = deployments.findIndex(({ id }) => id === current);
|
|
318
|
+
const running = deployments[index];
|
|
319
|
+
if (!running) {
|
|
320
|
+
return deployments.find(({ id }) => id === lastGood);
|
|
321
|
+
}
|
|
322
|
+
return deployments
|
|
323
|
+
.slice(index + 1)
|
|
324
|
+
.find(
|
|
325
|
+
(deployment) =>
|
|
326
|
+
deployment.state === "ready" &&
|
|
327
|
+
deployment.activeFrom !== null &&
|
|
328
|
+
deployment.release !== running.release,
|
|
329
|
+
);
|
|
330
|
+
};
|
|
331
|
+
|
|
332
|
+
const age = (from: string, now: number) => {
|
|
333
|
+
const seconds = Math.max(0, Math.round((now - Date.parse(from)) / 1000));
|
|
334
|
+
if (seconds < 60) {
|
|
335
|
+
return `${seconds}s`;
|
|
336
|
+
}
|
|
337
|
+
if (seconds < 3600) {
|
|
338
|
+
return `${Math.floor(seconds / 60)}m`;
|
|
339
|
+
}
|
|
340
|
+
if (seconds < 48 * 3600) {
|
|
341
|
+
return `${Math.floor(seconds / 3600)}h`;
|
|
342
|
+
}
|
|
343
|
+
return `${Math.floor(seconds / 86400)}d`;
|
|
344
|
+
};
|
|
345
|
+
|
|
346
|
+
const commitLabel = (git: GitSource | null) =>
|
|
347
|
+
git ? `${git.commit.slice(0, 7)}${git.dirty ? "*" : ""}` : "-";
|
|
348
|
+
|
|
349
|
+
const requester = ({ requestedBy }: DeploymentRecord) =>
|
|
350
|
+
requestedBy.user && requestedBy.host
|
|
351
|
+
? `${requestedBy.user}@${requestedBy.host}`
|
|
352
|
+
: (requestedBy.user ?? requestedBy.identity.name);
|
|
353
|
+
|
|
354
|
+
/** `tsplc deployments`: the agent's deployments, newest first, or as JSON. */
|
|
355
|
+
export const printDeployments = async (
|
|
356
|
+
agent: AgentClient,
|
|
357
|
+
flags: { format?: "json" | "text" },
|
|
358
|
+
) => {
|
|
359
|
+
const list = await agent.deployments();
|
|
360
|
+
if (flags.format === "json") {
|
|
361
|
+
console.log(JSON.stringify({ ok: true, ...list }));
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
if (!list.deployments.length) {
|
|
365
|
+
console.log("No deployments yet.");
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
const now = Date.now();
|
|
369
|
+
const rows = [
|
|
370
|
+
["ID", "STATE", "AGE", "RELEASE", "COMMIT", "BY", ""],
|
|
371
|
+
...list.deployments.map((deployment) => [
|
|
372
|
+
deployment.id,
|
|
373
|
+
deployment.state,
|
|
374
|
+
age(deployment.createdAt, now),
|
|
375
|
+
deployment.release,
|
|
376
|
+
commitLabel(deployment.git),
|
|
377
|
+
requester(deployment),
|
|
378
|
+
[
|
|
379
|
+
deployment.id === list.current ? "current" : "",
|
|
380
|
+
deployment.id === list.lastGood ? "last good" : "",
|
|
381
|
+
]
|
|
382
|
+
.filter(Boolean)
|
|
383
|
+
.join(", "),
|
|
384
|
+
]),
|
|
385
|
+
];
|
|
386
|
+
const widths = rows[0]?.map((_, column) =>
|
|
387
|
+
Math.max(...rows.map((row) => row[column]?.length ?? 0)),
|
|
388
|
+
);
|
|
389
|
+
for (const row of rows) {
|
|
390
|
+
console.log(
|
|
391
|
+
row
|
|
392
|
+
.map((cell, column) => cell.padEnd(widths?.[column] ?? 0))
|
|
393
|
+
.join(" ")
|
|
394
|
+
.trimEnd(),
|
|
395
|
+
);
|
|
396
|
+
}
|
|
397
|
+
};
|
|
398
|
+
|
|
399
|
+
/** `tsplc rollback [id]`: deploys that deployment's release again, by default the last good one before the running one. */
|
|
400
|
+
export const rollBack = async (
|
|
401
|
+
agent: AgentClient,
|
|
402
|
+
id: string | undefined,
|
|
403
|
+
follow: Follow,
|
|
404
|
+
) => {
|
|
405
|
+
const target = id ?? rollbackTarget(await agent.deployments())?.id;
|
|
406
|
+
if (!target) {
|
|
407
|
+
throw new Error(
|
|
408
|
+
"No earlier healthy deployment to roll back to; name one: tsplc rollback <id>",
|
|
409
|
+
);
|
|
410
|
+
}
|
|
411
|
+
console.log(`Rolling back to ${target}…`);
|
|
412
|
+
return queued(agent, await agent.rollback(target), follow);
|
|
413
|
+
};
|
|
414
|
+
|
|
415
|
+
/** `tsplc redeploy <id>`: deploys that deployment's release again. */
|
|
416
|
+
export const redeploy = async (
|
|
417
|
+
agent: AgentClient,
|
|
418
|
+
id: string,
|
|
419
|
+
mode: DeploymentMode,
|
|
420
|
+
follow: Follow,
|
|
421
|
+
) => queued(agent, await agent.redeploy(id, mode), follow);
|
|
422
|
+
|
|
423
|
+
/** The command that opens a URL in the desktop's browser, by platform. */
|
|
424
|
+
const openers: Partial<Record<NodeJS.Platform, string[]>> = {
|
|
425
|
+
darwin: ["open"],
|
|
426
|
+
win32: ["cmd", "/c", "start", ""],
|
|
427
|
+
};
|
|
428
|
+
|
|
429
|
+
/** `tsplc dashboard`: prints the agent's dashboard, and opens it when someone is at the terminal. */
|
|
430
|
+
export const openDashboard = (agent: AgentClient, interactive: boolean) => {
|
|
431
|
+
const url = new URL("/", agent.url).href;
|
|
432
|
+
console.log(url);
|
|
433
|
+
if (!interactive) {
|
|
434
|
+
return;
|
|
435
|
+
}
|
|
436
|
+
const [command = "xdg-open", ...args] = openers[process.platform] ?? [
|
|
437
|
+
"xdg-open",
|
|
438
|
+
];
|
|
439
|
+
// Without a desktop to open it on, the printed URL is the answer.
|
|
440
|
+
spawn(command, [...args, url], { stdio: "ignore", detached: true })
|
|
441
|
+
.on("error", () => {})
|
|
442
|
+
.unref();
|
|
443
|
+
};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import type { GitSource } from "@tsplc/agent";
|
|
3
|
+
|
|
4
|
+
/** What `git` prints for `args` in `directory`, or null when it fails or isn't installed. */
|
|
5
|
+
const git = (directory: string, args: readonly string[]) =>
|
|
6
|
+
new Promise<string | null>((resolve) => {
|
|
7
|
+
execFile("git", args, { cwd: directory }, (error, stdout) => {
|
|
8
|
+
resolve(error ? null : stdout.trim());
|
|
9
|
+
});
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The commit checked out in `directory`, for a deployment to record. Null outside a git checkout,
|
|
14
|
+
* before its first commit or without git: a deployment never fails for want of it.
|
|
15
|
+
*/
|
|
16
|
+
export const gitSource = async (
|
|
17
|
+
directory: string,
|
|
18
|
+
): Promise<GitSource | null> => {
|
|
19
|
+
const commit = await git(directory, ["rev-parse", "--verify", "HEAD"]);
|
|
20
|
+
if (!commit) {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
const [branch, status, message] = await Promise.all([
|
|
24
|
+
git(directory, ["symbolic-ref", "--quiet", "--short", "HEAD"]),
|
|
25
|
+
git(directory, ["status", "--porcelain"]),
|
|
26
|
+
git(directory, ["log", "-1", "--format=%s"]),
|
|
27
|
+
]);
|
|
28
|
+
return {
|
|
29
|
+
commit,
|
|
30
|
+
branch: branch || null,
|
|
31
|
+
// A status that can't be read can't vouch for a clean tree.
|
|
32
|
+
dirty: status !== "",
|
|
33
|
+
message: message || null,
|
|
34
|
+
};
|
|
35
|
+
};
|