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(iac): update script for email updated_at_seconds (#631)

Will Hutchinson8e85aaaa8493
diff --git a/infra/stacks/opensearch/helpers/scripts/update_updated_at_seconds_for_email.ts b/infra/stacks/opensearch/helpers/scripts/update_updated_at_seconds_for_email.ts
new file mode 100644
index 0000000000..c8c6666237
--- /dev/null
+++ b/infra/stacks/opensearch/helpers/scripts/update_updated_at_seconds_for_email.ts
@@ -0,0 +1,77 @@
+require('dotenv').config();
+
+import { client } from '../client';
+import { EMAIL_INDEX, IS_DRY_RUN } from '../constants';
+import { checkIndexExists } from '../utils/check_index_exists';
+import { copyFieldData } from '../utils/copy_field';
+
+const MIGRATION = {
+ indexName: EMAIL_INDEX,
+ field: { valueField: 'sent_at_seconds', updateField: 'updated_at_seconds' },
+};
+
+async function run(dryRun: boolean = true) {
+ const opensearchClient = client();
+
+ console.log('\n' + '='.repeat(60));
+ console.log(
+ `Update Updated At Seconds for Email ${dryRun ? '(DRY-RUN MODE)' : '(LIVE MODE)'}`
+ );
+ console.log('='.repeat(60));
+ console.log(
+ '\nThis script updates updated_at_seconds field to be the same as sent_at_seconds.'
+ );
+ console.log("\n💡 Safe to run multiple times - it's idempotent!");
+
+ if (dryRun) {
+ console.log('\n⚠️ DRY-RUN MODE: No changes will be made to the database');
+ } else {
+ console.log('\n🚨 LIVE MODE: Data will be copied');
+ }
+
+ try {
+ const indexExists = await checkIndexExists(
+ opensearchClient,
+ MIGRATION.indexName
+ );
+
+ if (!indexExists) {
+ console.log(
+ `⚠️ Index "${MIGRATION.indexName}" does not exist. Skipping...`
+ );
+ return;
+ }
+
+ await copyFieldData(
+ opensearchClient,
+ MIGRATION.indexName,
+ MIGRATION.field.valueField,
+ MIGRATION.field.updateField,
+ dryRun,
+ true // includeNonNull
+ );
+
+ console.log('\n' + '='.repeat(60));
+ console.log('Data copy completed successfully!');
+ console.log('='.repeat(60));
+
+ if (dryRun) {
+ console.log(
+ '\nTo run for real, set DRY_RUN=false environment variable\n'
+ );
+ } else {
+ console.log(
+ '\n✓ All updated_at_seconds have been updated to match sent_at_seconds.'
+ );
+ console.log(
+ '💡 Run this script again after deploying new code to catch any documents'
+ );
+ console.log(' added during the migration.\n');
+ }
+ } catch (error) {
+ console.error('\n❌ Data copy failed:', error);
+ throw error;
+ }
+}
+
+run(IS_DRY_RUN);
diff --git a/infra/stacks/opensearch/helpers/utils/copy_field.ts b/infra/stacks/opensearch/helpers/utils/copy_field.ts
index 3d6b45a49c..4eed30bd3a 100644
--- a/infra/stacks/opensearch/helpers/utils/copy_field.ts
+++ b/infra/stacks/opensearch/helpers/utils/copy_field.ts
@@ -7,40 +7,60 @@ import type { Client } from '@opensearch-project/opensearch';
* @param oldField The name of the field to copy data from.
* @param newField The name of the field to copy data to.
* @param dryRun A boolean indicating whether to perform a dry run.
- * @returns A Promise that resolves when the data has been copied.
+ * @param includeNonNull A boolean indicating whether to overwrite existing non-null values in newField.
+ * If false (default), only updates documents where newField doesn't exist.
+ * If true, updates all documents regardless of existing newField values.
+ * @returns A Promise that resolves to the number of documents updated.
*/
export async function copyFieldData(
opensearchClient: Client,
indexName: string,
oldField: string,
newField: string,
- dryRun: boolean
+ dryRun: boolean,
+ includeNonNull: boolean = false
): Promise<number> {
const script = {
+ // If the oldField exists and is not null, copy the value to the new field
source: `if (ctx._source.containsKey('${oldField}') && ctx._source.${oldField} != null) { ctx._source.${newField} = ctx._source.${oldField}; }`,
lang: 'painless',
};
console.log(
- ` ${dryRun ? '[DRY-RUN] Would copy' : 'Copying'} data from "${oldField}" to "${newField}" in index "${indexName}"`
+ ` ${dryRun ? '[DRY-RUN] Would copy' : 'Copying'} data from "${oldField}" to "${newField}" in index "${indexName}"${includeNonNull ? ' (overwriting existing values)' : ' (only where missing)'}`
);
+ const queryBody: any = {
+ script: dryRun ? undefined : script,
+ query: {
+ bool: {
+ must: [{ exists: { field: oldField } }],
+ },
+ },
+ };
+ // If not including non-null values, exclude documents where newField already exists
+ if (!includeNonNull) {
+ queryBody.query.bool.must_not = [{ exists: { field: newField } }];
+ }
+
if (dryRun) {
const countResponse = await opensearchClient.count({
index: indexName,
- body: {
- query: {
- bool: {
- must: [{ exists: { field: oldField } }],
- must_not: [{ exists: { field: newField } }],
- },
- },
- },
+ body: queryBody,
});
+
const docCount = countResponse.body.count;
- console.log(
- ` [DRY-RUN] Would update ${docCount} documents where ${newField} does not exist`
- );
+
+ if (includeNonNull) {
+ console.log(
+ ` [DRY-RUN] Would update ${docCount} documents (including those with existing ${newField} values)`
+ );
+ } else {
+ console.log(
+ ` [DRY-RUN] Would update ${docCount} documents where ${newField} does not exist`
+ );
+ }
+
return docCount;
}
@@ -50,15 +70,7 @@ export async function copyFieldData(
scroll_size: 5000, // Larger batches for better performance
slices: 'auto', // Enable parallel processing
refresh: false, // Don't refresh after each batch
- body: {
- script,
- query: {
- bool: {
- must: [{ exists: { field: oldField } }],
- must_not: [{ exists: { field: newField } }],
- },
- },
- },
+ body: queryBody,
});
const body = response.body;