Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat: more updates to s3 key migration script (#2222)

gbirmancce7f38da337
diff --git a/scripts/migrate-s3-keys-extensionless/.gitignore b/scripts/migrate-s3-keys-extensionless/.gitignore
index 385061fb50..8a61699c9b 100644
--- a/scripts/migrate-s3-keys-extensionless/.gitignore
+++ b/scripts/migrate-s3-keys-extensionless/.gitignore
@@ -1,4 +1,3 @@
node_modules/
*.log
-cursor-*.txt
-copied-keys-*.txt
+*.txt
diff --git a/scripts/migrate-s3-keys-extensionless/delete-old-keys.ts b/scripts/migrate-s3-keys-extensionless/delete-old-keys.ts
index 8eef5c5a9e..a5dab9b681 100644
--- a/scripts/migrate-s3-keys-extensionless/delete-old-keys.ts
+++ b/scripts/migrate-s3-keys-extensionless/delete-old-keys.ts
@@ -22,6 +22,7 @@ const LIMIT = process.env.LIMIT ? parseInt(process.env.LIMIT, 10) : undefined;
const USER = process.env.USER_PREFIX;
const DOCUMENT_ID = process.env.DOCUMENT_ID;
const KEYS_FILE = process.env.KEYS_FILE;
+const SKIP_VERIFY = process.env.SKIP_VERIFY === "true";
const CURSOR_FILE = `delete-cursor-${S3_BUCKET}.txt`;
if (!S3_BUCKET) {
@@ -83,18 +84,23 @@ interface Stats {
const stats: Stats = { scanned: 0, deleted: 0, skipped: 0, errors: 0 };
async function deleteBatch(keys: string[]): Promise<void> {
- // Verify extensionless copy exists before deleting
- const safeToDelete: string[] = [];
- await Promise.all(
- keys.map(async (key) => {
- if (await extensionlessExists(key)) {
- safeToDelete.push(key);
- } else {
- log(`SKIP (no extensionless copy): ${key}`);
- stats.skipped++;
- }
- })
- );
+ let safeToDelete: string[];
+
+ if (SKIP_VERIFY) {
+ safeToDelete = keys;
+ } else {
+ safeToDelete = [];
+ await Promise.all(
+ keys.map(async (key) => {
+ if (await extensionlessExists(key)) {
+ safeToDelete.push(key);
+ } else {
+ log(`SKIP (no extensionless copy): ${key}`);
+ stats.skipped++;
+ }
+ })
+ );
+ }
if (safeToDelete.length === 0) return;
@@ -146,7 +152,7 @@ async function deleteFromFile(filePath: string) {
stats.scanned++;
batch.push(key);
- if (batch.length >= CONCURRENCY) {
+ if (batch.length >= 1000) {
if (LIMIT !== undefined && stats.deleted + stats.skipped >= LIMIT) break;
await deleteBatch(batch);
batch = [];
@@ -237,6 +243,7 @@ async function main() {
log("=== Deleting old legacy S3 keys ===");
log(`Bucket: ${S3_BUCKET}`);
if (KEYS_FILE) log(`Keys file: ${KEYS_FILE}`);
+ if (SKIP_VERIFY) log(`Skipping extensionless verification`);
if (USER) log(`User: ${USER}`);
if (DOCUMENT_ID) log(`Document: ${DOCUMENT_ID}`);
if (DRY_RUN) log(`=== DRY RUN MODE ===${LIMIT ? ` (limit: ${LIMIT})` : ""}`);
diff --git a/scripts/migrate-s3-keys-extensionless/index.ts b/scripts/migrate-s3-keys-extensionless/index.ts
index fd0c35cb03..585f4b986e 100644
--- a/scripts/migrate-s3-keys-extensionless/index.ts
+++ b/scripts/migrate-s3-keys-extensionless/index.ts
@@ -1,37 +1,45 @@
import {
- S3Client,
- ListObjectsV2Command,
CopyObjectCommand,
HeadObjectCommand,
-} from "@aws-sdk/client-s3";
-import { appendFileSync, writeFileSync, readFileSync, existsSync } from "fs";
+ ListObjectsV2Command,
+ S3Client,
+} from '@aws-sdk/client-s3';
+import {
+ appendFileSync,
+ createReadStream,
+ existsSync,
+ readFileSync,
+ writeFileSync,
+} from 'fs';
+import { createInterface } from 'readline';
const S3_BUCKET = process.env.S3_BUCKET;
-const DRY_RUN = process.env.DRY_RUN === "true";
-const PREFIX = process.env.PREFIX ?? "macro|";
-const CONCURRENCY = parseInt(process.env.CONCURRENCY ?? "20", 10);
-const PAGE_SIZE = parseInt(process.env.PAGE_SIZE ?? "1000", 10);
+const DRY_RUN = process.env.DRY_RUN === 'true';
+const PREFIX = process.env.PREFIX ?? 'macro|';
+const CONCURRENCY = parseInt(process.env.CONCURRENCY ?? '20', 10);
+const PAGE_SIZE = parseInt(process.env.PAGE_SIZE ?? '100', 10);
const LIMIT = process.env.LIMIT ? parseInt(process.env.LIMIT, 10) : undefined;
const USER = process.env.USER_PREFIX;
const DOCUMENT_ID = process.env.DOCUMENT_ID;
-const RESET = process.env.RESET === "true";
+const KEYS_FILE = process.env.KEYS_FILE;
+const RESET = process.env.RESET === 'true';
if (!S3_BUCKET) {
- console.error("S3_BUCKET is required");
+ console.error('S3_BUCKET is required');
process.exit(1);
}
const s3 = new S3Client({});
const CURSOR_FILE = `cursor-${S3_BUCKET}.txt`;
-const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
+const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const LOG_FILE = `migration-${S3_BUCKET}-${timestamp}.log`;
const COPIED_KEYS_FILE = `copied-keys-${S3_BUCKET}-${timestamp}.txt`;
function log(message: string) {
const line = `[${new Date().toISOString()}] ${message}`;
console.log(line);
- appendFileSync(LOG_FILE, line + "\n");
+ appendFileSync(LOG_FILE, line + '\n');
}
function loadCursor(): string | undefined {
@@ -41,7 +49,7 @@ function loadCursor(): string | undefined {
}
if (USER || DOCUMENT_ID) return undefined;
if (!existsSync(CURSOR_FILE)) return undefined;
- const cursor = readFileSync(CURSOR_FILE, "utf-8").trim();
+ const cursor = readFileSync(CURSOR_FILE, 'utf-8').trim();
if (!cursor) return undefined;
log(`Resuming from cursor: ${cursor}`);
return cursor;
@@ -49,22 +57,24 @@ function loadCursor(): string | undefined {
function saveCursor(lastKey: string) {
if (DRY_RUN || USER || DOCUMENT_ID) return;
- writeFileSync(CURSOR_FILE, lastKey + "\n");
+ writeFileSync(CURSOR_FILE, lastKey + '\n');
}
function clearCursor() {
if (existsSync(CURSOR_FILE)) {
- writeFileSync(CURSOR_FILE, "");
+ writeFileSync(CURSOR_FILE, '');
}
}
// Matches keys in the format: {owner}/{uuid_v4}/{version_id}.{extension}
// e.g. macro|[email protected]/12f9a0ac-d445-45e3-94c1-5e8c02f0a6d8/564457.pdf
-const UUID_V4 = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
-const VERSION_WITH_EXT_REGEX = new RegExp(
- `${UUID_V4}/(\\d+)\\..+$`
-);
-const SKIP_PATTERNS = [/converted\.pdf$/, /^temp_files\//, /^ONBOARDING_DOCUMENTS\//];
+const UUID_V4 = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';
+const VERSION_WITH_EXT_REGEX = new RegExp(`${UUID_V4}/(\\d+)\\..+$`);
+const SKIP_PATTERNS = [
+ /converted\.pdf$/,
+ /^temp_files\//,
+ /^ONBOARDING_DOCUMENTS\//,
+];
interface Stats {
scanned: number;
@@ -74,7 +84,13 @@ interface Stats {
errors: number;
}
-const stats: Stats = { scanned: 0, copied: 0, skipped: 0, missing: 0, errors: 0 };
+const stats: Stats = {
+ scanned: 0,
+ copied: 0,
+ skipped: 0,
+ missing: 0,
+ errors: 0,
+};
function buildPrefix(): string | undefined {
if (USER && DOCUMENT_ID) return `${USER}/${DOCUMENT_ID}/`;
@@ -84,7 +100,7 @@ function buildPrefix(): string | undefined {
function stripExtension(key: string): string {
// Strip everything after the version_id (handles multipart extensions like .js.map)
- return key.replace(/(\d+)\..+$/, "$1");
+ return key.replace(/(\d+)\..+$/, '$1');
}
function shouldProcess(key: string): boolean {
@@ -97,7 +113,7 @@ async function exists(key: string): Promise<boolean> {
await s3.send(new HeadObjectCommand({ Bucket: S3_BUCKET, Key: key }));
return true;
} catch (err: any) {
- if (err?.$metadata?.httpStatusCode === 404 || err?.name === "NotFound") {
+ if (err?.$metadata?.httpStatusCode === 404 || err?.name === 'NotFound') {
return false;
}
throw err;
@@ -106,7 +122,8 @@ async function exists(key: string): Promise<boolean> {
async function copyKey(oldKey: string, newKey: string): Promise<void> {
if (await exists(newKey)) {
- if (DRY_RUN && (USER || DOCUMENT_ID)) log(`[dry run] SKIP (exists): ${newKey}`);
+ if (DRY_RUN && (USER || DOCUMENT_ID))
+ log(`[dry run] SKIP (exists): ${newKey}`);
stats.skipped++;
return;
}
@@ -121,11 +138,11 @@ async function copyKey(oldKey: string, newKey: string): Promise<void> {
await s3.send(
new CopyObjectCommand({
Bucket: S3_BUCKET,
- CopySource: `${S3_BUCKET}/${oldKey}`,
+ CopySource: `${S3_BUCKET}/${oldKey.split('/').map(encodeURIComponent).join('/')}`,
Key: newKey,
})
);
- appendFileSync(COPIED_KEYS_FILE, oldKey + "\n");
+ appendFileSync(COPIED_KEYS_FILE, oldKey + '\n');
stats.copied++;
} catch (err) {
log(`ERROR copying ${oldKey}: ${err}`);
@@ -138,35 +155,65 @@ async function processBatch(keys: string[]): Promise<void> {
await Promise.all(tasks);
}
-async function main() {
- log("=== Migrating S3 keys to extensionless convention ===");
- log(`Bucket: ${S3_BUCKET}`);
- log(`Prefix: ${PREFIX || "<all>"}`);
- log(`Concurrency: ${CONCURRENCY}`);
- if (USER) log(`User: ${USER}`);
- if (DOCUMENT_ID) log(`Document: ${DOCUMENT_ID}`);
- if (DRY_RUN) log(`=== DRY RUN MODE ===${LIMIT ? ` (limit: ${LIMIT})` : ""}`);
- log(`Log file: ${LOG_FILE}`);
- if (!DRY_RUN) log(`Copied keys file: ${COPIED_KEYS_FILE}`);
+async function migrateFromFile(filePath: string) {
+ log(`Reading keys from: ${filePath}`);
+
+ const rl = createInterface({
+ input: createReadStream(filePath),
+ crlfDelay: Infinity,
+ });
+
+ let batch: string[] = [];
+ for await (const line of rl) {
+ const key = line.trim();
+ if (!key) continue;
+ stats.scanned++;
+ batch.push(key);
+
+ if (batch.length >= CONCURRENCY) {
+ if (LIMIT !== undefined && stats.copied + stats.skipped >= LIMIT) break;
+ await processBatch(batch);
+ batch = [];
+ if (stats.scanned % 1000 === 0) {
+ log(
+ `... scanned=${stats.scanned} copied=${stats.copied} skipped=${stats.skipped}`
+ );
+ }
+ }
+ }
+
+ if (batch.length > 0) await processBatch(batch);
+}
+
+async function migrateFromScan() {
const startAfter = loadCursor();
let continuationToken: string | undefined;
do {
- const response = await s3.send(
- new ListObjectsV2Command({
- Bucket: S3_BUCKET,
- Prefix: buildPrefix(),
- MaxKeys: PAGE_SIZE,
- ContinuationToken: continuationToken,
- ...(startAfter && !continuationToken ? { StartAfter: startAfter } : {}),
- })
- );
+ let response;
+ try {
+ response = await s3.send(
+ new ListObjectsV2Command({
+ Bucket: S3_BUCKET,
+ Prefix: buildPrefix(),
+ MaxKeys: PAGE_SIZE,
+ EncodingType: 'url',
+ ContinuationToken: continuationToken,
+ ...(startAfter && !continuationToken
+ ? { StartAfter: startAfter }
+ : {}),
+ })
+ );
+ } catch (err) {
+ log(`ERROR listing objects: ${err}`);
+ throw err;
+ }
const keys = (response.Contents ?? [])
.filter((obj) => obj.Key)
- .map((obj) => obj.Key!);
+ .map((obj) => decodeURIComponent(obj.Key!));
stats.scanned += keys.length;
@@ -193,14 +240,35 @@ async function main() {
: undefined;
if (continuationToken) {
- log(`... scanned=${stats.scanned} copied=${stats.copied} skipped=${stats.skipped}`);
+ log(
+ `... scanned=${stats.scanned} copied=${stats.copied} skipped=${stats.skipped}`
+ );
}
} while (continuationToken);
// Clear cursor on successful completion
if (!DRY_RUN && !USER && !DOCUMENT_ID) clearCursor();
+}
- log("=== Migration complete ===");
+async function main() {
+ log('=== Migrating S3 keys to extensionless convention ===');
+ log(`Bucket: ${S3_BUCKET}`);
+ if (KEYS_FILE) log(`Keys file: ${KEYS_FILE}`);
+ if (!KEYS_FILE) log(`Prefix: ${PREFIX || '<all>'}`);
+ log(`Concurrency: ${CONCURRENCY}`);
+ if (USER) log(`User: ${USER}`);
+ if (DOCUMENT_ID) log(`Document: ${DOCUMENT_ID}`);
+ if (DRY_RUN) log(`=== DRY RUN MODE ===${LIMIT ? ` (limit: ${LIMIT})` : ''}`);
+ log(`Log file: ${LOG_FILE}`);
+ if (!DRY_RUN) log(`Copied keys file: ${COPIED_KEYS_FILE}`);
+
+ if (KEYS_FILE) {
+ await migrateFromFile(KEYS_FILE);
+ } else {
+ await migrateFromScan();
+ }
+
+ log('=== Migration complete ===');
log(`Scanned: ${stats.scanned}`);
log(`Copied: ${stats.copied}`);
log(`Skipped: ${stats.skipped} (extensionless key already exists)`);
@@ -208,6 +276,11 @@ async function main() {
log(`Errors: ${stats.errors}`);
}
+process.on('unhandledRejection', (err) => {
+ log(`Unhandled rejection: ${err}`);
+ process.exit(1);
+});
+
main().catch((err) => {
log(`Fatal error: ${err}`);
process.exit(1);
diff --git a/scripts/migrate-s3-keys-extensionless/run-until-done.sh b/scripts/migrate-s3-keys-extensionless/run-until-done.sh
new file mode 100755
index 0000000000..2e5b46d5a4
--- /dev/null
+++ b/scripts/migrate-s3-keys-extensionless/run-until-done.sh
@@ -0,0 +1,26 @@
+#!/bin/bash
+set -u
+
+export S3_BUCKET="${S3_BUCKET:?S3_BUCKET is required}"
+
+attempt=0
+while true; do
+ attempt=$((attempt + 1))
+ echo "=== Attempt $attempt ($(date)) ==="
+ bun run migrate
+ exit_code=$?
+
+ if [ $exit_code -eq 0 ]; then
+ # Check if cursor was cleared (migration complete)
+ cursor_file="cursor-${S3_BUCKET}.txt"
+ if [ ! -f "$cursor_file" ] || [ ! -s "$cursor_file" ]; then
+ echo "=== Migration complete after $attempt attempts ==="
+ break
+ fi
+ echo "Exited cleanly but cursor still set, resuming..."
+ else
+ echo "Exited with code $exit_code, resuming from cursor..."
+ fi
+
+ sleep 1
+done