Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
chore: improve extensionless key migration (#2163)
gbirmanac8016041fc8
diff --git a/scripts/migrate-s3-keys-extensionless/.gitignore b/scripts/migrate-s3-keys-extensionless/.gitignoreindex c2658d7d1b..385061fb50 100644--- a/scripts/migrate-s3-keys-extensionless/.gitignore+++ b/scripts/migrate-s3-keys-extensionless/.gitignore@@ -1 +1,4 @@node_modules/+*.log+cursor-*.txt+copied-keys-*.txtdiff --git a/scripts/migrate-s3-keys-extensionless/delete-old-keys.ts b/scripts/migrate-s3-keys-extensionless/delete-old-keys.tsnew file mode 100644index 0000000000..8eef5c5a9e--- /dev/null+++ b/scripts/migrate-s3-keys-extensionless/delete-old-keys.ts@@ -0,0 +1,261 @@+import {+ S3Client,+ ListObjectsV2Command,+ DeleteObjectsCommand,+ HeadObjectCommand,+} from "@aws-sdk/client-s3";+import {+ appendFileSync,+ writeFileSync,+ readFileSync,+ createReadStream,+ existsSync,+} 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 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 CURSOR_FILE = `delete-cursor-${S3_BUCKET}.txt`;++if (!S3_BUCKET) {+ console.error("S3_BUCKET is required");+ process.exit(1);+}++const s3 = new S3Client({});++const timestamp = new Date().toISOString().replace(/[:.]/g, "-");+const LOG_FILE = `delete-${S3_BUCKET}-${timestamp}.log`;++function log(message: string) {+ const line = `[${new Date().toISOString()}] ${message}`;+ console.log(line);+ appendFileSync(LOG_FILE, line + "\n");+}++function buildPrefix(): string | undefined {+ if (USER && DOCUMENT_ID) return `${USER}/${DOCUMENT_ID}/`;+ if (USER) return `${USER}/`;+ return PREFIX || undefined;+}++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\//];++function stripExtension(key: string): string {+ return key.replace(/(\d+)\..+$/, "$1");+}++function shouldDelete(key: string): boolean {+ if (!VERSION_WITH_EXT_REGEX.test(key)) return false;+ return !SKIP_PATTERNS.some((p) => p.test(key));+}++async function extensionlessExists(key: string): Promise<boolean> {+ try {+ await s3.send(+ new HeadObjectCommand({ Bucket: S3_BUCKET, Key: stripExtension(key) })+ );+ return true;+ } catch (err: any) {+ if (err?.$metadata?.httpStatusCode === 404 || err?.name === "NotFound") {+ return false;+ }+ throw err;+ }+}++interface Stats {+ scanned: number;+ deleted: number;+ skipped: number;+ errors: number;+}++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++;+ }+ })+ );++ if (safeToDelete.length === 0) return;++ if (DRY_RUN) {+ stats.deleted += safeToDelete.length;+ return;+ }++ // S3 DeleteObjects supports up to 1000 keys per call+ for (let i = 0; i < safeToDelete.length; i += 1000) {+ const batch = safeToDelete.slice(i, i + 1000);+ try {+ const result = await s3.send(+ new DeleteObjectsCommand({+ Bucket: S3_BUCKET,+ Delete: {+ Objects: batch.map((key) => ({ Key: key })),+ Quiet: true,+ },+ })+ );+ const errorCount = result.Errors?.length ?? 0;+ stats.deleted += batch.length - errorCount;+ if (errorCount > 0) {+ for (const err of result.Errors ?? []) {+ log(`ERROR deleting ${err.Key}: ${err.Message}`);+ }+ stats.errors += errorCount;+ }+ } catch (err) {+ log(`ERROR batch delete: ${err}`);+ stats.errors += batch.length;+ }+ }+}++async function deleteFromFile(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.deleted + stats.skipped >= LIMIT) break;+ await deleteBatch(batch);+ batch = [];++ if (stats.scanned % 1000 === 0) {+ log(`... scanned=${stats.scanned} deleted=${stats.deleted} skipped=${stats.skipped}`);+ }+ }+ }++ if (batch.length > 0) {+ await deleteBatch(batch);+ }+}++function loadCursor(): string | undefined {+ if (USER || DOCUMENT_ID) return undefined;+ if (!existsSync(CURSOR_FILE)) return undefined;+ const cursor = readFileSync(CURSOR_FILE, "utf-8").trim();+ if (!cursor) return undefined;+ log(`Resuming from cursor: ${cursor}`);+ return cursor;+}++function saveCursor(lastKey: string) {+ if (DRY_RUN || USER || DOCUMENT_ID) return;+ writeFileSync(CURSOR_FILE, lastKey + "\n");+}++function clearCursor() {+ if (existsSync(CURSOR_FILE)) {+ writeFileSync(CURSOR_FILE, "");+ }+}++async function deleteFromScan() {+ log("Scanning bucket for keys to delete");++ 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 } : {}),+ })+ );++ const keys = (response.Contents ?? [])+ .filter((obj) => obj.Key)+ .map((obj) => obj.Key!);++ stats.scanned += keys.length;++ let toDelete = keys.filter(shouldDelete);++ if (LIMIT !== undefined) {+ const remaining = LIMIT - stats.deleted - stats.skipped;+ if (remaining <= 0) break;+ toDelete = toDelete.slice(0, remaining);+ }++ for (let i = 0; i < toDelete.length; i += CONCURRENCY) {+ const batch = toDelete.slice(i, i + CONCURRENCY);+ await deleteBatch(batch);+ }++ const lastKey = keys[keys.length - 1];+ if (lastKey) saveCursor(lastKey);++ continuationToken = response.IsTruncated+ ? response.NextContinuationToken+ : undefined;++ if (continuationToken) {+ log(`... scanned=${stats.scanned} deleted=${stats.deleted} skipped=${stats.skipped}`);+ }+ } while (continuationToken);++ if (!DRY_RUN && !USER && !DOCUMENT_ID) clearCursor();+}++async function main() {+ log("=== Deleting old legacy S3 keys ===");+ log(`Bucket: ${S3_BUCKET}`);+ if (KEYS_FILE) log(`Keys file: ${KEYS_FILE}`);+ 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 (KEYS_FILE) {+ await deleteFromFile(KEYS_FILE);+ } else {+ await deleteFromScan();+ }++ log("=== Delete complete ===");+ log(`Scanned: ${stats.scanned}`);+ log(`Deleted: ${stats.deleted}`);+ log(`Skipped: ${stats.skipped} (no extensionless copy found)`);+ log(`Errors: ${stats.errors}`);+}++main().catch((err) => {+ log(`Fatal error: ${err}`);+ process.exit(1);+});diff --git a/scripts/migrate-s3-keys-extensionless/index.ts b/scripts/migrate-s3-keys-extensionless/index.tsindex e4e974df13..fd0c35cb03 100644--- a/scripts/migrate-s3-keys-extensionless/index.ts+++ b/scripts/migrate-s3-keys-extensionless/index.ts@@ -4,15 +4,17 @@ import {CopyObjectCommand,HeadObjectCommand,} from "@aws-sdk/client-s3";+import { appendFileSync, writeFileSync, readFileSync, existsSync } from "fs";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 ?? "100", 10);+const PAGE_SIZE = parseInt(process.env.PAGE_SIZE ?? "1000", 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";if (!S3_BUCKET) {console.error("S3_BUCKET is required");@@ -21,6 +23,41 @@ if (!S3_BUCKET) {const s3 = new S3Client({});+const CURSOR_FILE = `cursor-${S3_BUCKET}.txt`;+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");+}++function loadCursor(): string | undefined {+ if (RESET) {+ clearCursor();+ return undefined;+ }+ if (USER || DOCUMENT_ID) return undefined;+ if (!existsSync(CURSOR_FILE)) return undefined;+ const cursor = readFileSync(CURSOR_FILE, "utf-8").trim();+ if (!cursor) return undefined;+ log(`Resuming from cursor: ${cursor}`);+ return cursor;+}++function saveCursor(lastKey: string) {+ if (DRY_RUN || USER || DOCUMENT_ID) return;+ writeFileSync(CURSOR_FILE, lastKey + "\n");+}++function clearCursor() {+ if (existsSync(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.pdfconst UUID_V4 = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";@@ -69,19 +106,13 @@ async function exists(key: string): Promise<boolean> {async function copyKey(oldKey: string, newKey: string): Promise<void> {if (await exists(newKey)) {- if (DRY_RUN) console.log(` [dry run] SKIP (exists): ${newKey}`);+ if (DRY_RUN && (USER || DOCUMENT_ID)) log(`[dry run] SKIP (exists): ${newKey}`);stats.skipped++;return;}- if (!(await exists(oldKey))) {- console.warn(` WARNING: source missing: ${oldKey}`);- stats.missing++;- return;- }-if (DRY_RUN) {- console.log(` [dry run] ${oldKey} -> ${newKey}`);+ if (USER || DOCUMENT_ID) log(`[dry run] ${oldKey} -> ${newKey}`);stats.copied++;return;}@@ -94,10 +125,10 @@ async function copyKey(oldKey: string, newKey: string): Promise<void> {Key: newKey,}));- console.log(` Copied: ${oldKey} -> ${newKey}`);+ appendFileSync(COPIED_KEYS_FILE, oldKey + "\n");stats.copied++;} catch (err) {- console.error(` ERROR copying ${oldKey}:`, err);+ log(`ERROR copying ${oldKey}: ${err}`);stats.errors++;}}@@ -108,15 +139,17 @@ async function processBatch(keys: string[]): Promise<void> {}async function main() {- console.log("=== Migrating S3 keys to extensionless convention ===");- console.log(` Bucket: ${S3_BUCKET}`);- console.log(` Prefix: ${PREFIX || "<all>"}`);- console.log(` Concurrency: ${CONCURRENCY}`);- if (USER) console.log(` User: ${USER}`);- if (DOCUMENT_ID) console.log(` Document: ${DOCUMENT_ID}`);- if (DRY_RUN) console.log(` === DRY RUN MODE ===${LIMIT ? ` (limit: ${LIMIT})` : ""}`);-- console.log();+ 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}`);++ const startAfter = loadCursor();let continuationToken: string | undefined;@@ -127,6 +160,7 @@ async function main() {Prefix: buildPrefix(),MaxKeys: PAGE_SIZE,ContinuationToken: continuationToken,+ ...(startAfter && !continuationToken ? { StartAfter: startAfter } : {}),}));@@ -150,27 +184,31 @@ async function main() {await processBatch(batch);}+ // Save cursor to last scanned key for resumability+ const lastKey = keys[keys.length - 1];+ if (lastKey) saveCursor(lastKey);+continuationToken = response.IsTruncated? response.NextContinuationToken: undefined;if (continuationToken) {- console.log(- ` ... scanned=${stats.scanned} copied=${stats.copied} skipped=${stats.skipped}`- );+ log(`... scanned=${stats.scanned} copied=${stats.copied} skipped=${stats.skipped}`);}} while (continuationToken);- console.log();- console.log("=== Migration complete ===");- console.log(` Scanned: ${stats.scanned}`);- console.log(` Copied: ${stats.copied}`);- console.log(` Skipped: ${stats.skipped} (extensionless key already exists)`);- console.log(` Missing: ${stats.missing} (source key not found)`);- console.log(` Errors: ${stats.errors}`);+ // Clear cursor on successful completion+ if (!DRY_RUN && !USER && !DOCUMENT_ID) clearCursor();++ log("=== Migration complete ===");+ log(`Scanned: ${stats.scanned}`);+ log(`Copied: ${stats.copied}`);+ log(`Skipped: ${stats.skipped} (extensionless key already exists)`);+ log(`Missing: ${stats.missing} (source key not found)`);+ log(`Errors: ${stats.errors}`);}main().catch((err) => {- console.error("Fatal error:", err);+ log(`Fatal error: ${err}`);process.exit(1);});diff --git a/scripts/migrate-s3-keys-extensionless/package.json b/scripts/migrate-s3-keys-extensionless/package.jsonindex baf2b7cfee..8d55a2ee1a 100644--- a/scripts/migrate-s3-keys-extensionless/package.json+++ b/scripts/migrate-s3-keys-extensionless/package.json@@ -3,7 +3,8 @@"private": true,"type": "module","scripts": {- "migrate": "bun run index.ts"+ "migrate": "bun run index.ts",+ "delete": "bun run delete-old-keys.ts"},"dependencies": {"@aws-sdk/client-s3": "^3.700.0"