File size: 10,842 Bytes
6111b2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
import { execFile, spawn } from "node:child_process";
import { closeSync, mkdirSync, openSync, existsSync } from "node:fs";
import { access } from "node:fs/promises";
import path from "node:path";
import { promisify } from "node:util";

const execFileAsync = promisify(execFile);

type ComposeCommand = "docker compose" | "docker-compose";
export type AutoUpdateMode = "npm" | "docker-compose" | "source";

type ExecFileLike = typeof execFileAsync;
type SpawnLike = typeof spawn;

export type AutoUpdateConfig = {
  mode: AutoUpdateMode;
  repoDir: string;
  composeFile: string;
  composeProfile: string;
  composeService: string;
  gitRemote: string;
  patchCommits: string[];
  logPath: string;
};

export type AutoUpdateValidation = {
  supported: boolean;
  reason: string | null;
  composeCommand: ComposeCommand | null;
};

export type AutoUpdateLaunchResult = {
  started: boolean;
  channel: AutoUpdateMode;
  logPath: string;
  composeCommand: ComposeCommand | null;
  error?: string;
};

function normalizeMode(raw: string | undefined): AutoUpdateMode {
  if (raw === "docker-compose" || raw === "source") {
    return raw;
  }
  return "npm";
}

async function pathExists(targetPath: string): Promise<boolean> {
  try {
    await access(targetPath);
    return true;
  } catch {
    return false;
  }
}

function shellQuote(value: string): string {
  return `'${value.replace(/'/g, `'"'"'`)}'`;

}



function parsePatchCommits(raw: string | undefined): string[] {

  return (raw || "")

    .split(/[\s,]+/)

    .map((value) => value.trim())

    .filter(Boolean);

}



export function getAutoUpdateConfig(env: NodeJS.ProcessEnv = process.env): AutoUpdateConfig {

  const dataDir = env.DATA_DIR || "/tmp/omniroute";

  const repoDir = env.AUTO_UPDATE_REPO_DIR || "/workspace/omniroute";



  let mode = normalizeMode(env.AUTO_UPDATE_MODE);

  if (mode === "npm") {

    const isGitRepo = existsSync(path.join(process.cwd(), ".git"));

    const currentDir = typeof __dirname !== "undefined" ? __dirname : process.cwd();

    const isGlobalNodeModules = currentDir.includes("node_modules");



    // If we are not in a global node_modules directory, we are likely a local source install/build.

    // Even if .git is missing (downloaded zip), we should treat it as source.

    if (isGitRepo || !isGlobalNodeModules) {

      mode = "source";

    }

  }



  return {

    mode,

    repoDir,

    composeFile: env.AUTO_UPDATE_COMPOSE_FILE || path.join(repoDir, "docker-compose.yml"),

    composeProfile: env.AUTO_UPDATE_COMPOSE_PROFILE || "cli",

    composeService: env.AUTO_UPDATE_SERVICE || "omniroute-cli",

    gitRemote: env.AUTO_UPDATE_GIT_REMOTE || "origin",

    patchCommits: parsePatchCommits(env.AUTO_UPDATE_PATCH_COMMITS),

    logPath: env.AUTO_UPDATE_LOG_PATH || path.join(dataDir, "logs", "auto-update.log"),

  };

}



export async function detectComposeCommand(

  execFileImpl: ExecFileLike = execFileAsync

): Promise<ComposeCommand | null> {

  try {

    await execFileImpl("docker", ["compose", "version"], { timeout: 10_000 });

    return "docker compose";

  } catch {

    // Fall through.

  }



  try {

    await execFileImpl("docker-compose", ["version"], { timeout: 10_000 });

    return "docker-compose";

  } catch {

    return null;

  }

}



export async function validateAutoUpdateRuntime(

  config: AutoUpdateConfig,

  execFileImpl: ExecFileLike = execFileAsync,

  existsImpl: (targetPath: string) => Promise<boolean> = pathExists

): Promise<AutoUpdateValidation> {

  if (config.mode === "source") {

    const gitDir = path.join(process.cwd(), ".git");

    if (!(await existsImpl(gitDir))) {

      return {

        supported: false,

        reason: "Not a git repository. Download source or use npm install -g.",

        composeCommand: null,

      };

    }



    try {

      await execFileImpl("git", ["--version"], { timeout: 10_000 });

    } catch {

      return {

        supported: false,

        reason: "git is not available. Install git to enable auto-update.",

        composeCommand: null,

      };

    }



    return {

      supported: true,

      reason: null,

      composeCommand: null,

    };

  }



  if (config.mode !== "docker-compose") {

    return { supported: true, reason: null, composeCommand: null };

  }



  if (!(await existsImpl(config.repoDir))) {

    return {

      supported: false,

      reason: `Repository directory not found: ${config.repoDir}`,

      composeCommand: null,

    };

  }



  if (!(await existsImpl(config.composeFile))) {

    return {

      supported: false,

      reason: `Compose file not found: ${config.composeFile}`,

      composeCommand: null,

    };

  }



  if (!(await existsImpl("/var/run/docker.sock"))) {

    return {

      supported: false,

      reason: "Docker socket is not mounted into the OmniRoute container.",

      composeCommand: null,

    };

  }



  try {

    await execFileImpl("git", ["--version"], { timeout: 10_000 });

  } catch {

    return {

      supported: false,

      reason: "git is not available inside the OmniRoute container.",

      composeCommand: null,

    };

  }



  const composeCommand = await detectComposeCommand(execFileImpl);

  if (!composeCommand) {

    return {

      supported: false,

      reason:

        "Neither docker compose nor docker-compose is available inside the OmniRoute container.",

      composeCommand: null,

    };

  }



  return { supported: true, reason: null, composeCommand };

}



export async function ensureGitTagExists(

  targetTag: string,

  execFileImpl: ExecFileLike = execFileAsync,

  cwd = process.cwd()

): Promise<void> {

  try {

    await execFileImpl("git", ["rev-parse", "-q", "--verify", `refs/tags/${targetTag}`], {

      timeout: 10_000,

      cwd,

    });

  } catch {

    throw new Error(`Git tag not found: ${targetTag}`);

  }

}



export function buildNpmUpdateScript(latest: string): string {

  return [

    "set -eu",

    `npm install -g omniroute@${latest} --ignore-scripts --legacy-peer-deps`,

    "if command -v pm2 >/dev/null 2>&1; then",

    "  pm2 restart omniroute || true",

    "fi",

    `echo \"[AutoUpdate] Successfully updated to v${latest}.\"`,

  ].join("\n");

}



export function buildSourceUpdateScript(latest: string, gitRemote = "origin"): string {

  const targetTag = latest.startsWith("v") ? latest : `v${latest}`;



  return [

    "set -eu",

    "git stash --include-untracked 2>/dev/null || true",

    `git fetch --tags ${shellQuote(gitRemote)}`,

    `if ! git rev-parse -q --verify "refs/tags/${targetTag}" >/dev/null 2>&1; then`,

    `  echo "[AutoUpdate] Tag ${targetTag} not found." >&2`,

    "  exit 1",

    "fi",

    'backup_branch="pre-update/$(git rev-parse --short HEAD)-$(date +%Y%m%d-%H%M%S)"',

    'git branch "$backup_branch" 2>/dev/null || true',

    `git checkout "${targetTag}"`,

    "npm install --legacy-peer-deps",

    "node scripts/dev/sync-env.mjs 2>/dev/null || true",

    "npm run build",

    "if command -v pm2 >/dev/null 2>&1; then",

    "  pm2 restart omniroute --update-env || true",

    "fi",

    `echo "[AutoUpdate] Successfully updated to ${targetTag}."`,

  ].join("\n");

}



export function buildDockerComposeUpdateScript({

  latest,

  config,

  composeCommand,

}: {

  latest: string;

  config: AutoUpdateConfig;

  composeCommand: ComposeCommand;

}): string {

  const targetTag = latest.startsWith("v") ? latest : `v${latest}`;

  const composeInvocation =

    composeCommand === "docker compose"

      ? 'docker compose -f "$COMPOSE_FILE" up -d --build "$SERVICE"'

      : 'docker-compose -f "$COMPOSE_FILE" up -d --build "$SERVICE"';

  const patchLines = config.patchCommits.length

    ? [`git cherry-pick --keep-redundant-commits ${config.patchCommits.map(shellQuote).join(" ")}`]

    : [];



  return [

    "set -eu",

    'export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:$PATH"',

    `REPO_DIR=${shellQuote(config.repoDir)}`,

    `COMPOSE_FILE=${shellQuote(config.composeFile)}`,

    `PROFILE=${shellQuote(config.composeProfile)}`,

    `SERVICE=${shellQuote(config.composeService)}`,

    `REMOTE=${shellQuote(config.gitRemote)}`,

    `TARGET_TAG=${shellQuote(targetTag)}`,

    'cd "$REPO_DIR"',

    'git config --global --add safe.directory "$REPO_DIR" >/dev/null 2>&1 || true',

    'if [ -n "$(git status --porcelain)" ]; then',

    '  echo "[AutoUpdate] Refusing update: git worktree has local changes." >&2',

    "  exit 1",

    "fi",

    'git fetch --tags "$REMOTE"',

    'if ! git rev-parse -q --verify "refs/tags/$TARGET_TAG" >/dev/null 2>&1; then',

    '  echo "[AutoUpdate] Tag $TARGET_TAG not found on remote $REMOTE." >&2',

    "  exit 1",

    "fi",

    'backup_branch="autoupdate/pre-${TARGET_TAG#v}-$(date +%Y%m%d-%H%M%S)"',

    'git branch "$backup_branch" >/dev/null 2>&1 || true',

    'git checkout -B "autoupdate/${TARGET_TAG#v}" "$TARGET_TAG"',

    ...patchLines,

    'export COMPOSE_PROFILES="$PROFILE"',

    composeInvocation,

    `echo "[AutoUpdate] Successfully switched to ${targetTag} via ${composeCommand}."`,

  ].join("\n");

}



export async function launchAutoUpdate({

  latest,

  env = process.env,

  execFileImpl = execFileAsync,

  spawnImpl = spawn,

  existsImpl = pathExists,

}: {

  latest: string;

  env?: NodeJS.ProcessEnv;

  execFileImpl?: ExecFileLike;

  spawnImpl?: SpawnLike;

  existsImpl?: (targetPath: string) => Promise<boolean>;

}): Promise<AutoUpdateLaunchResult> {

  const config = getAutoUpdateConfig(env);

  const validation = await validateAutoUpdateRuntime(config, execFileImpl, existsImpl);



  if (!validation.supported) {

    return {

      started: false,

      channel: config.mode,

      logPath: config.logPath,

      composeCommand: validation.composeCommand,

      error: validation.reason || "Auto-update runtime is not available.",

    };

  }



  const script =

    config.mode === "docker-compose"

      ? buildDockerComposeUpdateScript({

          latest,

          config,

          composeCommand: validation.composeCommand || "docker-compose",

        })

      : config.mode === "source"

        ? buildSourceUpdateScript(latest, config.gitRemote)

        : buildNpmUpdateScript(latest);



  mkdirSync(path.dirname(config.logPath), { recursive: true });

  const logFd = openSync(config.logPath, "a");

  const child = spawnImpl("sh", ["-lc", script], {

    detached: true,

    stdio: ["ignore", logFd, logFd],

    env: { ...process.env, ...env },

  });

  closeSync(logFd);

  child.unref();



  return {

    started: true,

    channel: config.mode,

    logPath: config.logPath,

    composeCommand: validation.composeCommand,

  };

}