@moondeck/station 1.0.4 → 1.0.6

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.
@@ -1,6 +1,7 @@
1
1
  import type { TaskEnvironmentHandle } from "./task-environment/types";
2
2
  import { isEnvironmentTransportProvider } from "./task-environment/types";
3
3
  import { MACHINE_GATEWAY_TUNNEL_PORT } from "./machine-gateway-tunnel";
4
+ import { MACHINE_SSH_CONNECT_TIMEOUT_SECONDS } from "./machine-exec";
4
5
  import {
5
6
  installMachineProjectEnvLoader,
6
7
  installMachineTaskForwarderAsset,
@@ -23,16 +24,51 @@ type TaskForwarderNodePath =
23
24
  | "/usr/local/bin/node"
24
25
  | typeof APPLE_FORWARDER_NODE_PATH;
25
26
 
27
+ /**
28
+ * How long the launcher waits for the forwarder's READY (F5, test 6.2: 2 of 5
29
+ * AWS-host starts failed at the old 5 s). It must outlast the child's own
30
+ * verdict, so a slow child reports its own failure instead of being cut off:
31
+ * node start-up, then up to SECONDS of SECRET_INPUT_TIMEOUT_MS (5 s,
32
+ * uai-task-forwarder.mjs) reading the secret from stdin, then a loopback
33
+ * listen. The old 5 s deadline equalled that stdin budget alone.
34
+ */
35
+ export const TASK_FORWARDER_READY_SECONDS = 20;
36
+ /** Bound on stopping a previous forwarder before the new one starts. */
37
+ export const OLD_FORWARDER_STOP_SECONDS = 5;
38
+ /**
39
+ * The exec budget, built from what may happen before the launcher answers
40
+ * (review #tgxadc: an 8 s connect, a 5 s old-forwarder stop and a child
41
+ * ready at 18 s exceeded the old 30 s, and the kill took the diagnostics):
42
+ * ssh's connect and handshake (MACHINE_SSH_CONNECT_TIMEOUT_SECONDS, 10 s),
43
+ * the old-forwarder stop (5 s) and the READY wait (20 s), each measured on
44
+ * a whole-second clock (+1 s each), and 4 s for the remaining shell steps
45
+ * and the answer: 41 s. On a direct exec (no ssh) the connect term only
46
+ * adds slack. The launcher thus always answers, with its report, before
47
+ * the exec is killed.
48
+ */
49
+ export const LAUNCH_EXEC_TIMEOUT_MS =
50
+ (MACHINE_SSH_CONNECT_TIMEOUT_SECONDS + OLD_FORWARDER_STOP_SECONDS + 1 + TASK_FORWARDER_READY_SECONDS + 1 + 4) * 1_000;
51
+ /** The whole thrown message, in UTF-8 bytes. */
52
+ export const MAX_LAUNCH_ERROR_BYTES = 2_048;
53
+ const ERROR_LOG_TAIL_BYTES = 1_024;
54
+
26
55
  // Shared by initial machine provisioning and every recovery topology. Keep
27
56
  // the ownership/process proof in lockstep with task-up.sh's container
28
57
  // launcher. The generation secret arrives on stdin; no task file, argv entry,
29
58
  // or environment variable ever contains it.
30
- const START_TASK_FORWARDER = String.raw`set -eu
59
+ //
60
+ // On failure it names which one (the child exited, with its status, or was
61
+ // not ready in time) and appends the tail of the child's error.log, so the
62
+ // thrown error carries the real cause before any cleanup removes the machine.
63
+ export const START_TASK_FORWARDER = String.raw`set -eu
31
64
  task_id=$1
32
65
  generation=$2
33
66
  gateway_host=$3
34
67
  gateway_port=$4
35
68
  node_path=$5
69
+ ready_seconds=$6
70
+ case "$ready_seconds" in ''|*[!0-9]*) exit 1 ;; esac
71
+ [ "$ready_seconds" -ge 1 ] && [ "$ready_seconds" -le 25 ] || exit 1
36
72
  case "$node_path" in
37
73
  /usr/bin/node | /usr/local/bin/node) ;;
38
74
  ${APPLE_FORWARDER_NODE_PATH})
@@ -66,10 +102,11 @@ if [ -f "$pid_file" ] && [ ! -L "$pid_file" ]; then
66
102
  && printf '%s\n' "$old_args" | /bin/grep -Fxq '/usr/local/share/uai/uai-task-forwarder.mjs' \
67
103
  && printf '%s\n' "$old_args" | /bin/grep -Fxq "$task_id"; then
68
104
  /bin/kill -TERM "$old_pid"
69
- attempts=0
70
- while /bin/kill -0 "$old_pid" 2>/dev/null && [ "$attempts" -lt 50 ]; do
105
+ # Wall clock, so the stop stays within the exec budget however slow
106
+ # each fork is on a cold machine.
107
+ stop_deadline=$((SECONDS + ${OLD_FORWARDER_STOP_SECONDS}))
108
+ while /bin/kill -0 "$old_pid" 2>/dev/null && [ "$SECONDS" -lt "$stop_deadline" ]; do
71
109
  /bin/sleep 0.1
72
- attempts=$((attempts + 1))
73
110
  done
74
111
  if /bin/kill -0 "$old_pid" 2>/dev/null; then
75
112
  /bin/kill -KILL "$old_pid"
@@ -102,22 +139,91 @@ forwarder_pid=$!
102
139
  exec 3<&-
103
140
  printf '%s\n' "$forwarder_pid" > "$pid_file"
104
141
 
105
- attempts=0
106
- while [ "$attempts" -lt 50 ]; do
107
- /bin/kill -0 "$forwarder_pid" 2>/dev/null || exit 1
142
+ report_log() {
143
+ if [ -s "$error_file" ] && [ ! -L "$error_file" ]; then
144
+ printf '%s\n' "forwarder error.log (last ${ERROR_LOG_TAIL_BYTES} bytes):" >&2
145
+ /usr/bin/tail -c ${ERROR_LOG_TAIL_BYTES} "$error_file" >&2 || true
146
+ else
147
+ printf '%s\n' "forwarder error.log is empty" >&2
148
+ fi
149
+ }
150
+
151
+ # Wall clock, not an iteration count: on a cold machine each /bin/sleep fork
152
+ # is slow too, and the deadline must hold inside the exec budget.
153
+ deadline=$((SECONDS + ready_seconds))
154
+ while :; do
155
+ if ! /bin/kill -0 "$forwarder_pid" 2>/dev/null; then
156
+ status=0
157
+ wait "$forwarder_pid" || status=$?
158
+ printf '%s\n' "task env forwarder exited with status $status before it was ready" >&2
159
+ report_log
160
+ exit 1
161
+ fi
108
162
  if [ -f "$ready_file" ] \
109
163
  && [ "$(/bin/cat "$ready_file" 2>/dev/null || true)" = READY ]; then
110
164
  exit 0
111
165
  fi
166
+ # SECONDS counts whole seconds: -gt waits at least ready_seconds, at most
167
+ # one more.
168
+ if [ "$SECONDS" -gt "$deadline" ]; then
169
+ printf '%s\n' "task env forwarder was not ready within $ready_seconds s (pid $forwarder_pid still running)" >&2
170
+ report_log
171
+ exit 1
172
+ fi
112
173
  /bin/sleep 0.1
113
- attempts=$((attempts + 1))
114
- done
115
- exit 1`;
174
+ done`;
116
175
 
117
176
  export interface TaskEnvForwarderLaunchOptions {
118
177
  gatewayHost: string;
119
178
  gatewayPort: number;
120
179
  nodePath: TaskForwarderNodePath;
180
+ /** Test seam; production always uses TASK_FORWARDER_READY_SECONDS. */
181
+ readySeconds?: number;
182
+ }
183
+
184
+ /**
185
+ * The thrown message, at most MAX_LAUNCH_ERROR_BYTES of UTF-8 (review
186
+ * #tgxadc: the detail alone was bounded, and invalid bytes from the child's
187
+ * log grow threefold as U+FFFD). Keeps the launcher's verdict line (which
188
+ * failure, the child's status) and as much of the log's END as fits, the
189
+ * newest lines, cut between characters, never inside one.
190
+ */
191
+ export function launchFailureMessage(outcome: string, detail: string): string {
192
+ const head = `task env forwarder failed to start (${outcome})`;
193
+ const whole = detail ? `${head}: ${detail}` : head;
194
+ if (Buffer.byteLength(whole) <= MAX_LAUNCH_ERROR_BYTES) return whole;
195
+ const newline = detail.indexOf("\n");
196
+ const verdict = newline === -1 ? "" : detail.slice(0, newline);
197
+ const rest = newline === -1 ? detail : detail.slice(newline + 1);
198
+ const lead = `${head}: ${utf8Prefix(verdict, 512)}${verdict ? "\n" : ""}…`;
199
+ return lead + utf8Suffix(rest, MAX_LAUNCH_ERROR_BYTES - Buffer.byteLength(lead));
200
+ }
201
+
202
+ /** The longest prefix of `text` within `bytes` UTF-8 bytes, whole code points. */
203
+ function utf8Prefix(text: string, bytes: number): string {
204
+ let used = 0;
205
+ let out = "";
206
+ for (const char of text) {
207
+ const size = Buffer.byteLength(char);
208
+ if (used + size > bytes) break;
209
+ used += size;
210
+ out += char;
211
+ }
212
+ return out;
213
+ }
214
+
215
+ /** The longest suffix of `text` within `bytes` UTF-8 bytes, whole code points. */
216
+ function utf8Suffix(text: string, bytes: number): string {
217
+ const chars = Array.from(text);
218
+ let used = 0;
219
+ let start = chars.length;
220
+ while (start > 0) {
221
+ const size = Buffer.byteLength(chars[start - 1]!);
222
+ if (used + size > bytes) break;
223
+ used += size;
224
+ start -= 1;
225
+ }
226
+ return chars.slice(start).join("");
121
227
  }
122
228
 
123
229
  /** Launch or replace one authenticated task forwarder. Consumes and wipes
@@ -149,11 +255,12 @@ export async function launchTaskEnvForwarder(
149
255
  options.gatewayHost,
150
256
  String(options.gatewayPort),
151
257
  options.nodePath,
258
+ String(options.readySeconds ?? TASK_FORWARDER_READY_SECONDS),
152
259
  ],
153
260
  user: "root",
154
261
  projectEnvProfile: "maintenance",
155
262
  stdin: secret,
156
- timeoutMs: 30_000,
263
+ timeoutMs: LAUNCH_EXEC_TIMEOUT_MS,
157
264
  maxOutputBytes: STEP_OUTPUT_BYTES,
158
265
  });
159
266
  if (
@@ -162,12 +269,11 @@ export async function launchTaskEnvForwarder(
162
269
  result.stdoutTruncated ||
163
270
  result.stderrTruncated
164
271
  ) {
165
- throw new Error(
166
- `task env forwarder failed to start: ${Buffer.from(result.stderr)
167
- .toString("utf8")
168
- .trim()
169
- .slice(-512) || `exit ${String(result.exitCode)}`}`,
170
- );
272
+ const detail = Buffer.from(result.stderr).toString("utf8").trim();
273
+ const outcome = result.signal !== null
274
+ ? `killed by ${result.signal} (the ${LAUNCH_EXEC_TIMEOUT_MS / 1000} s launch budget ran out)`
275
+ : `exit ${String(result.exitCode)}`;
276
+ throw new Error(launchFailureMessage(outcome, detail));
171
277
  }
172
278
  } finally {
173
279
  secret.fill(0);
@@ -1230,6 +1230,9 @@ export function createMachineHostTaskEnvironmentProvider(
1230
1230
  throw error;
1231
1231
  }
1232
1232
  return {
1233
+ // The Station posts the replacement note and, once the cloud has it,
1234
+ // clears the notice (src/index.ts): never before.
1235
+ ...(provisioned.lossNotices?.length ? { lossNotices: provisioned.lossNotices } : {}),
1233
1236
  handle: withTaskDownResult(handle),
1234
1237
  result: {
1235
1238
  // Recorded as the task's runtime identity (the compose-project
@@ -1241,6 +1244,7 @@ export function createMachineHostTaskEnvironmentProvider(
1241
1244
  ...(warnings.length > 0
1242
1245
  ? { initWarning: warnings.join("\n") }
1243
1246
  : {}),
1247
+ ...(provisioned.replacedLostEnvironment ? { environmentReplaced: true as const } : {}),
1244
1248
  },
1245
1249
  };
1246
1250
  },