-
Notifications
You must be signed in to change notification settings - Fork 4.5k
Expand file tree
/
Copy pathupgrade-binary.ts
More file actions
486 lines (430 loc) · 15.9 KB
/
upgrade-binary.ts
File metadata and controls
486 lines (430 loc) · 15.9 KB
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
import { Data, Effect, Config, Option } from 'effect';
import { HttpClient, FileSystem } from '@effect/platform';
import * as path from 'node:path';
import { APP_VERSION } from '../constants';
import { DEBUG_OVERRIDE_CONFIG } from 'src/effects/debug-config';
import { GITHUB_CONFIG } from 'src/effects/github-config';
import { detectPlatform, type PlatformArch } from 'src/effects/detect-platform';
import { CompareSemverError, semverComparator } from 'src/effects/compare-semver';
// Note: `node:zlib` does not support Github's zip files
import decompress from 'decompress';
import type { Predicate } from 'effect/Predicate';
import { renderPrettyError } from './utils/pretty-error';
import { TerminalUI } from './terminal-ui';
export class UpgradeBinaryError extends Data.TaggedError('services/UpgradeBinaryError')<{
readonly cause?: unknown;
readonly message?: string;
}> {}
/**
* CLI binary name constant
*/
export const CLI_BINARY_NAME = 'composio';
type GitHubRelease = {
tag_name: string;
prerelease?: boolean;
draft?: boolean;
assets: Array<{
name: string;
browser_download_url: string;
}>;
};
const CLI_RELEASE_TAG_PATTERN = /^@composio\/cli@\d+\.\d+\.\d+.*$/;
// Service to manage CLI binary upgrades
export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/UpgradeBinary', {
accessors: true,
// eslint-disable-next-line max-lines-per-function
effect: Effect.gen(function* () {
const httpClient = yield* HttpClient.HttpClient;
const fs = yield* FileSystem.FileSystem;
const githubConfig = yield* Config.all(GITHUB_CONFIG);
/**
* Fetch latest release from GitHub
*/
const fetchGitHubJson = <T>({
url,
fetchErrorMessage,
parseErrorMessage,
}: {
url: string;
fetchErrorMessage: string;
parseErrorMessage: string;
}): Effect.Effect<T, UpgradeBinaryError, never> =>
Effect.gen(function* () {
yield* Effect.logDebug(`GET ${url}`);
const response = yield* httpClient.get(url).pipe(
Effect.catchAll(error =>
Effect.fail(
new UpgradeBinaryError({
cause: error,
message: fetchErrorMessage,
})
)
)
);
if (response.status < 200 || response.status >= 300) {
const pretty = yield* response.json.pipe(
Effect.map(json => renderPrettyError(Object.entries(json as object))),
Effect.catchAll(() => Effect.succeed(''))
);
const cause = pretty ? `HTTP ${response.status}\n${pretty}` : `HTTP ${response.status}`;
return yield* Effect.fail(
new UpgradeBinaryError({
cause,
message: fetchErrorMessage,
})
);
}
return (yield* response.json.pipe(
Effect.catchAll(error =>
Effect.fail(
new UpgradeBinaryError({
cause: error,
message: parseErrorMessage,
})
)
)
)) as T;
});
const fetchLatestRelease = (
tag: string
): Effect.Effect<GitHubRelease, UpgradeBinaryError, never> =>
Effect.gen(function* () {
yield* Effect.logDebug(`Using tag: ${tag}`);
const encodedTag = encodeURIComponent(tag);
const url = `${githubConfig.API_BASE_URL}/repos/${githubConfig.OWNER}/${githubConfig.REPO}/releases/tags/${encodedTag}`;
return yield* fetchGitHubJson<GitHubRelease>({
url,
fetchErrorMessage: `Failed to fetch tags/${tag} release from GitHub`,
parseErrorMessage: 'Failed to parse GitHub release JSON response',
});
});
const getBinaryAssetName = (platformArch: PlatformArch): string =>
`${CLI_BINARY_NAME}-${platformArch.platform}-${platformArch.arch}.zip`;
const hasBinaryAssetForPlatform = (
release: GitHubRelease,
platformArch: PlatformArch
): boolean => {
const binaryName = getBinaryAssetName(platformArch);
return release.assets.some(asset => asset.name === binaryName);
};
const fetchLatestReleaseWithRequiredAssets = (
platformArch: PlatformArch
): Effect.Effect<GitHubRelease, UpgradeBinaryError, never> =>
Effect.gen(function* () {
const url = `${githubConfig.API_BASE_URL}/repos/${githubConfig.OWNER}/${githubConfig.REPO}/releases?per_page=100`;
const releases = yield* fetchGitHubJson<unknown>({
url,
fetchErrorMessage: 'Failed to fetch releases from GitHub',
parseErrorMessage: 'Failed to parse GitHub releases JSON response',
});
if (!Array.isArray(releases)) {
return yield* Effect.fail(
new UpgradeBinaryError({
cause: new Error('GitHub releases response was not an array'),
message: 'Unexpected response while resolving latest CLI release',
})
);
}
const cliReleases = releases.filter(
(release): release is GitHubRelease =>
typeof release === 'object' &&
release !== null &&
'tag_name' in release &&
typeof release.tag_name === 'string' &&
('prerelease' in release ? release.prerelease === false : true) &&
('draft' in release ? release.draft === false : true) &&
CLI_RELEASE_TAG_PATTERN.test(release.tag_name)
);
if (cliReleases.length === 0) {
return yield* Effect.fail(
new UpgradeBinaryError({
cause: new Error('No package-scoped CLI releases found'),
message: 'Failed to determine latest CLI release from @composio/cli tags on GitHub',
})
);
}
let best: GitHubRelease | null = null;
for (const candidate of cliReleases) {
if (!hasBinaryAssetForPlatform(candidate, platformArch)) continue;
if (best === null) {
best = candidate;
continue;
}
const comparison = yield* semverComparator(best.tag_name, candidate.tag_name).pipe(
Effect.mapError(
error =>
new UpgradeBinaryError({
cause: error,
message: 'Failed to compare CLI release versions',
})
)
);
if (comparison < 0) {
best = candidate;
}
}
const release = best;
if (!release) {
return yield* Effect.fail(
new UpgradeBinaryError({
cause: new Error(
`No @composio/cli release contains ${getBinaryAssetName(platformArch)} asset`
),
message: `No binary available for ${platformArch.platform}-${platformArch.arch}`,
})
);
}
yield* Effect.logDebug(
`Resolved latest CLI release with required assets: ${release.tag_name}`
);
return release;
});
/**
* Check if update is available
*/
const isUpdateAvailable = (
release: GitHubRelease
): Effect.Effect<boolean, CompareSemverError | UpgradeBinaryError, never> =>
Effect.gen(function* () {
// Current version is older than latest
const isVersionOutdated: Predicate<number> = comparison => comparison < 0;
const comparison = yield* semverComparator(APP_VERSION, release.tag_name);
return isVersionOutdated(comparison);
});
/**
* Download binary for current platform
*/
const downloadBinary = (
release: GitHubRelease,
platformArch: PlatformArch
): Effect.Effect<{ name: string; data: Uint8Array }, UpgradeBinaryError, never> =>
Effect.gen(function* () {
yield* Effect.logDebug(
`Looking up binary for ${platformArch.platform}-${platformArch.arch}`
);
const binaryName = `${CLI_BINARY_NAME}-${platformArch.platform}-${platformArch.arch}.zip`;
const asset = release.assets.find(asset => asset.name === binaryName);
if (!asset) {
return yield* Effect.fail(
new UpgradeBinaryError({
cause: new Error(`Binary not found: ${binaryName}`),
message: `No binary available for ${platformArch.platform}-${platformArch.arch}`,
})
);
}
yield* Effect.logDebug(`Downloading ${asset.name}...`);
const response = yield* Effect.gen(function* () {
const resp = yield* httpClient.get(asset.browser_download_url);
if (resp.status < 200 || resp.status >= 300) {
return yield* Effect.fail(
new UpgradeBinaryError({
cause: new Error(`HTTP ${resp.status}`),
message: `Failed to download binary: ${asset.name}`,
})
);
}
return resp;
}).pipe(
Effect.catchAll(error =>
Effect.fail(
new UpgradeBinaryError({
cause: new Error(String(error)),
message: `Failed to download binary: ${asset.name}`,
})
)
)
);
const arrayBuffer = yield* Effect.gen(function* () {
return yield* response.arrayBuffer;
}).pipe(
Effect.catchAll(error =>
Effect.fail(
new UpgradeBinaryError({
cause: error as Error,
message: 'Failed to read downloaded binary',
})
)
)
);
return {
name: binaryName,
data: new Uint8Array(arrayBuffer),
};
});
/**
* Extract binary from zip archive using FileSystem
*/
const extractBinary = (
{ name, data }: { name: string; data: Uint8Array },
tempDir: string
): Effect.Effect<string, UpgradeBinaryError, never> =>
Effect.gen(function* () {
const zipPath = path.join(tempDir, name);
const extractDir = path.join(tempDir, 'extract');
const binaryPath = path.join(extractDir, path.parse(name).name, CLI_BINARY_NAME);
yield* Effect.logDebug(`Download zip to ${extractDir}`);
// Write zip file
yield* fs.writeFile(zipPath, data).pipe(
Effect.catchAll(error =>
Effect.fail(
new UpgradeBinaryError({
cause: error as Error,
message: 'Failed to write zip file',
})
)
)
);
// Create extract directory
yield* fs.makeDirectory(extractDir, { recursive: true }).pipe(
Effect.catchAll(error =>
Effect.fail(
new UpgradeBinaryError({
cause: error as Error,
message: 'Failed to create extract directory',
})
)
)
);
yield* Effect.tryPromise({
try: async () => {
await decompress(zipPath, extractDir);
},
catch: error =>
new UpgradeBinaryError({
cause: error as Error,
message: 'Failed to extract zip archive',
}),
});
// Check if binary exists
const exists = yield* fs
.exists(binaryPath)
.pipe(Effect.catchAll(() => Effect.succeed(false)));
if (!exists) {
return yield* Effect.fail(
new UpgradeBinaryError({
cause: new Error(`Binary not found in archive: ${binaryPath}`),
message: 'Extracted archive does not contain expected binary',
})
);
}
// Make executable
yield* fs.chmod(binaryPath, 0o755).pipe(
Effect.catchAll(error =>
Effect.fail(
new UpgradeBinaryError({
cause: error as Error,
message: 'Failed to make binary executable',
})
)
)
);
return binaryPath;
});
/**
* Get current executable path
*/
const getCurrentExecutablePath = Effect.fn(function* () {
// E.g., ~/.composio/composio
const currentPath = process.execPath;
const runtimesPaths = [Bun.which('bun'), Bun.which('node')] as Array<string | null>;
if (runtimesPaths.includes(currentPath)) {
return yield* Effect.fail(
new UpgradeBinaryError({
cause: new Error(`Currently using Composio CLI via Bun or Node.js runtime`),
message:
'Cannot upgrade runtime binary. Please run the upgrade command from a self-contained Composio CLI binary.',
})
);
}
return currentPath;
});
/**
* Replace current executable binary with the new target one.
*/
const replaceBinary = (
sourcePath: string,
targetPath: string
): Effect.Effect<void, UpgradeBinaryError> =>
Effect.gen(function* () {
yield* Effect.logDebug(`Replacing binary: ${sourcePath} -> ${targetPath}`);
yield* fs
.copy(sourcePath, targetPath, {
// Note: without `overwrite: true`, the copy operation will silently bail out
overwrite: true,
})
.pipe(
Effect.catchAll(error =>
Effect.fail(
new UpgradeBinaryError({
cause: error as Error,
message: 'Failed to replace binary',
})
)
)
);
});
/**
* Main upgrade function
*/
const upgrade = () =>
Effect.gen(function* () {
const ui = yield* TerminalUI;
const upgradeTargetOpt = yield* DEBUG_OVERRIDE_CONFIG['UPGRADE_TARGET'];
const currentPath = yield* getCurrentExecutablePath();
yield* Effect.logDebug(`Current executable path: ${currentPath}`);
yield* ui.intro('composio upgrade');
// If local binary path is provided (for testing), use it directly
if (Option.isSome(upgradeTargetOpt)) {
yield* ui.log.info(`New local version available (current: ${APP_VERSION})`);
yield* replaceBinary(upgradeTargetOpt.value, currentPath);
yield* ui.outro('Upgrade completed');
return;
}
const platformArch = yield* detectPlatform;
const didUpgrade = yield* ui.useMakeSpinner('Checking for updates...', spinner =>
Effect.gen(function* () {
const release = yield* githubConfig.TAG.pipe(
Option.match({
onNone: () => fetchLatestReleaseWithRequiredAssets(platformArch),
onSome: tag => fetchLatestRelease(tag),
})
);
const updateAvailable = yield* isUpdateAvailable(release);
if (!updateAvailable) {
yield* spinner.stop('You are already running the latest version!');
return false;
}
yield* spinner.message(
`New version available: ${release.tag_name} (current: ${APP_VERSION}). Downloading...`
);
const { name, data } = yield* downloadBinary(release, platformArch);
yield* spinner.message('Extracting...');
// The temporary directory is automatically cleaned up
const tmpDir = yield* fs
.makeTempDirectoryScoped({ prefix: `${CLI_BINARY_NAME}-upgrade}` })
.pipe(
Effect.catchAll(error =>
Effect.fail(
new UpgradeBinaryError({
cause: error as Error,
message: 'Failed to create temporary directory',
})
)
)
);
const extractedBinaryPath = yield* extractBinary({ name, data }, tmpDir);
yield* replaceBinary(extractedBinaryPath, currentPath);
yield* spinner.stop('Upgrade completed!');
return true;
})
);
yield* ui.outro(
didUpgrade ? 'Restart your terminal to use the new version.' : 'No upgrade needed.'
);
});
return {
upgrade,
} as const;
}),
dependencies: [],
}) {}