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
feat(call_recording): image placeholder (#3811)
Will Hutchinsoned5b6fdc845e
diff --git a/.github/services-config.json b/.github/services-config.jsonindex 6314c909dd..e37a0aafdf 100644--- a/.github/services-config.json+++ b/.github/services-config.json@@ -35,6 +35,15 @@"upload_extractor_lambda_trigger"]},+ "call-recording": {+ "source_paths": [+ "rust/cloud-storage/call_recording_preview_handler/**"+ ],+ "stack_path": "infra/stacks/call-recording/**",+ "deploy_lambdas": [+ "call_recording_preview_handler"+ ]+ },"connection-gateway": {"source_paths": ["rust/cloud-storage/connection_gateway/**"@@ -83,6 +92,7 @@"document-storage-service": {"source_paths": ["rust/cloud-storage/document_storage_service/**",+ "rust/cloud-storage/call/**","rust/cloud-storage/github/**","rust/cloud-storage/delete_chat_handler/**","rust/cloud-storage/docx_unzip_handler/**",diff --git a/flake.nix b/flake.nixindex 427b1f5419..04b223e400 100644--- a/flake.nix+++ b/flake.nix@@ -265,6 +265,9 @@[paralleldocker-compose+ curl+ xz+ unzipzipcargo-infocargo-udepsdiff --git a/infra/stacks/call-recording/Pulumi.dev.yaml b/infra/stacks/call-recording/Pulumi.dev.yamlindex 9cfd7a1eb5..929eadfb37 100644--- a/infra/stacks/call-recording/Pulumi.dev.yaml+++ b/infra/stacks/call-recording/Pulumi.dev.yaml@@ -1,3 +1,4 @@config:aws-native:region: us-east-1aws:region: us-east-1+ call-recording:macro_db_proxy_secret_key: macrodb-rds-proxy-devdiff --git a/infra/stacks/call-recording/Pulumi.prod.yaml b/infra/stacks/call-recording/Pulumi.prod.yamlindex 9cfd7a1eb5..ae38a92faa 100644--- a/infra/stacks/call-recording/Pulumi.prod.yaml+++ b/infra/stacks/call-recording/Pulumi.prod.yaml@@ -1,3 +1,4 @@config:aws-native:region: us-east-1aws:region: us-east-1+ call-recording:macro_db_proxy_secret_key: macrodb-rds-proxy-proddiff --git a/infra/stacks/call-recording/call-recording-preview-lambda.ts b/infra/stacks/call-recording/call-recording-preview-lambda.tsnew file mode 100644index 0000000000..30769e794b--- /dev/null+++ b/infra/stacks/call-recording/call-recording-preview-lambda.ts@@ -0,0 +1,167 @@+import * as aws from '@pulumi/aws';+import * as pulumi from '@pulumi/pulumi';+import { Lambda } from '../../packages/lambda';+import { CLOUD_TRAIL_SNS_TOPIC_ARN, stack } from '../../packages/shared';++const LAMBDA_BASE_NAME = 'call_recording_preview_handler';+const CLOUD_STORAGE_BASE = `../../../rust/cloud-storage`;+const ZIP_LOCATION = `${CLOUD_STORAGE_BASE}/target/lambda/${LAMBDA_BASE_NAME}/bootstrap.zip`;++export type CallRecordingPreviewLambdaEnvVars = {+ CALL_RECORDING_BUCKET_NAME: pulumi.Output<string> | string;+ DATABASE_URL: pulumi.Output<string> | string;+ ENVIRONMENT: pulumi.Output<string> | string;+ FFMPEG_PATH: pulumi.Output<string> | string;+ FFPROBE_PATH: pulumi.Output<string> | string;+ RUST_LOG: pulumi.Output<string> | string;+};++type VpcArgs = {+ vpcId: pulumi.Output<string> | string;+ publicSubnetIds: pulumi.Output<string[]> | string[];+ privateSubnetIds: pulumi.Output<string[]> | string[];+};++type CallRecordingPreviewLambdaArgs = {+ envVars: CallRecordingPreviewLambdaEnvVars;+ callRecordingBucketArn: pulumi.Output<string> | string;+ vpc: VpcArgs;+ tags: { [key: string]: string };+};++export class CallRecordingPreviewLambda extends pulumi.ComponentResource {+ role: aws.iam.Role;+ lambda: aws.lambda.Function;+ tags: { [key: string]: string };++ constructor(+ name: string,+ args: CallRecordingPreviewLambdaArgs,+ opts?: pulumi.ComponentResourceOptions+ ) {+ super('my:components:CallRecordingPreviewLambda', name, {}, opts);+ const { callRecordingBucketArn, vpc, envVars, tags } = args;++ this.tags = tags;++ const s3Policy = new aws.iam.Policy(+ `${LAMBDA_BASE_NAME}-s3-policy`,+ {+ name: `${LAMBDA_BASE_NAME}-s3-policy-${stack}`,+ policy: pulumi.output({+ Version: '2012-10-17',+ Statement: [+ {+ Effect: 'Allow',+ Action: ['s3:GetObject'],+ Resource: [+ pulumi.interpolate`${callRecordingBucketArn}/calls/*.mp4`,+ ],+ },+ {+ Effect: 'Allow',+ Action: ['s3:PutObject'],+ Resource: [+ pulumi.interpolate`${callRecordingBucketArn}/calls/*/PREVIEW.jpg`,+ ],+ },+ ],+ }),+ tags: this.tags,+ },+ { parent: this }+ );++ this.role = new aws.iam.Role(+ `${LAMBDA_BASE_NAME}-role`,+ {+ name: `${LAMBDA_BASE_NAME}-role-${stack}`,+ assumeRolePolicy: JSON.stringify({+ Version: '2012-10-17',+ Statement: [+ {+ Action: 'sts:AssumeRole',+ Effect: 'Allow',+ Principal: {+ Service: 'lambda.amazonaws.com',+ },+ },+ ],+ }),+ managedPolicyArns: [+ aws.iam.ManagedPolicy.AWSLambdaBasicExecutionRole,+ aws.iam.ManagedPolicy.AWSLambdaVPCAccessExecutionRole,+ s3Policy.arn,+ ],+ tags: { ...this.tags, 'call-recording-access': 'true' },+ },+ { parent: this, dependsOn: [s3Policy] }+ );++ const previewLambda = new Lambda<CallRecordingPreviewLambdaEnvVars>(+ `${LAMBDA_BASE_NAME}-lambda`,+ {+ baseName: LAMBDA_BASE_NAME,+ handlerBase: CLOUD_STORAGE_BASE,+ zipLocation: ZIP_LOCATION,+ envVars,+ role: this.role,+ vpc,+ timeout: 300,+ memorySize: stack === 'prod' ? 2048 : 1024,+ tags: this.tags,+ },+ { parent: this }+ );++ this.lambda = previewLambda.lambda;++ this.setupLambdaAlarms();+ }++ setupLambdaAlarms(): void {+ new aws.cloudwatch.MetricAlarm(+ `${LAMBDA_BASE_NAME}-throttle-alarm`,+ {+ name: `${LAMBDA_BASE_NAME}-throttle-count-${stack}`,+ metricName: 'Throttles',+ namespace: 'AWS/Lambda',+ statistic: 'Sum',+ period: 300,+ evaluationPeriods: 1,+ threshold: 1,+ comparisonOperator: 'GreaterThanOrEqualToThreshold',+ dimensions: {+ FunctionName: this.lambda.name,+ },+ alarmDescription: `Alarm when ${LAMBDA_BASE_NAME} lambda experiences throttling.`,+ actionsEnabled: true,+ alarmActions: [CLOUD_TRAIL_SNS_TOPIC_ARN],+ tags: this.tags,+ },+ { parent: this }+ );++ new aws.cloudwatch.MetricAlarm(+ `${LAMBDA_BASE_NAME}-error-alarm`,+ {+ name: `${LAMBDA_BASE_NAME}-error-count-${stack}`,+ metricName: 'Errors',+ namespace: 'AWS/Lambda',+ statistic: 'Sum',+ period: 300,+ evaluationPeriods: 1,+ threshold: 1,+ comparisonOperator: 'GreaterThanOrEqualToThreshold',+ dimensions: {+ FunctionName: this.lambda.name,+ },+ alarmDescription: `Alarm when ${LAMBDA_BASE_NAME} lambda experiences errors.`,+ actionsEnabled: true,+ alarmActions: [CLOUD_TRAIL_SNS_TOPIC_ARN],+ tags: this.tags,+ },+ { parent: this }+ );+ }+}diff --git a/infra/stacks/call-recording/index.ts b/infra/stacks/call-recording/index.tsindex e0fe83b9fd..fd2b291a11 100644--- a/infra/stacks/call-recording/index.ts+++ b/infra/stacks/call-recording/index.ts@@ -1,7 +1,12 @@import * as aws from '@pulumi/aws';import * as pulumi from '@pulumi/pulumi';import { createBucket } from '../../packages/resources';-import { stack } from '../../packages/shared';+import { config, stack } from '../../packages/shared';+import { get_coparse_api_vpc } from '../../packages/vpc';+import {+ CallRecordingPreviewLambda,+ type CallRecordingPreviewLambdaEnvVars,+} from './call-recording-preview-lambda';const tags = {environment: stack,@@ -227,3 +232,61 @@ const bucketPolicy = new aws.s3.BucketPolicy();export const bucketPolicyId = bucketPolicy.id;++// ---------------------------------------------------------------------------+// 4. Call recording preview Lambda+// ---------------------------------------------------------------------------++const DATABASE_URL = aws.secretsmanager+ .getSecretVersionOutput({+ secretId: config.require('macro_db_proxy_secret_key'),+ })+ .apply((secret) => secret.secretString);++const previewLambdaEnvVars: CallRecordingPreviewLambdaEnvVars = {+ CALL_RECORDING_BUCKET_NAME: pulumi.interpolate`${callRecordingBucket.id}`,+ DATABASE_URL: pulumi.interpolate`${DATABASE_URL}`,+ FFMPEG_PATH: '/var/task/bin/ffmpeg',+ FFPROBE_PATH: '/var/task/bin/ffprobe',+ ENVIRONMENT: stack,+ RUST_LOG: 'call_recording_preview_handler=trace',+};++const callRecordingPreviewLambda = new CallRecordingPreviewLambda(+ `call-recording-preview-lambda-${stack}`,+ {+ envVars: previewLambdaEnvVars,+ callRecordingBucketArn: callRecordingBucket.arn,+ vpc: get_coparse_api_vpc(),+ tags,+ }+);++const previewLambdaS3InvokePermission = new aws.lambda.Permission(+ `call-recording-preview-lambda-s3-permission-${stack}`,+ {+ action: 'lambda:InvokeFunction',+ function: callRecordingPreviewLambda.lambda.name,+ principal: 's3.amazonaws.com',+ sourceArn: callRecordingBucket.arn,+ }+);++new aws.s3.BucketNotification(+ `call-recording-preview-lambda-notification-${stack}`,+ {+ bucket: callRecordingBucket.id,+ lambdaFunctions: [+ {+ lambdaFunctionArn: callRecordingPreviewLambda.lambda.arn,+ events: ['s3:ObjectCreated:*'],+ filterPrefix: 'calls/',+ filterSuffix: '.mp4',+ },+ ],+ },+ { dependsOn: [previewLambdaS3InvokePermission] }+);++export const callRecordingPreviewLambdaName =+ callRecordingPreviewLambda?.lambda.name;diff --git a/js/app/packages/block-call/component/CallRecording/CallRecordingBody.tsx b/js/app/packages/block-call/component/CallRecording/CallRecordingBody.tsxindex 9b213879eb..a74e16b02f 100644--- a/js/app/packages/block-call/component/CallRecording/CallRecordingBody.tsx+++ b/js/app/packages/block-call/component/CallRecording/CallRecordingBody.tsx@@ -173,6 +173,7 @@ export function CallRecordingBody(props: {<div class="overflow-hidden rounded border border-edge-muted/50"><CallRecordingVideourl={url()}+ posterUrl={record().recordingPreviewUrl ?? undefined}onTimeUpdate={handleTimeUpdate}setVideoRef={setVideoRef}/>diff --git a/js/app/packages/block-call/component/CallRecording/CallRecordingMediaColumn.tsx b/js/app/packages/block-call/component/CallRecording/CallRecordingMediaColumn.tsxindex f4e0fe4cc3..8ca0ec48c5 100644--- a/js/app/packages/block-call/component/CallRecording/CallRecordingMediaColumn.tsx+++ b/js/app/packages/block-call/component/CallRecording/CallRecordingMediaColumn.tsx@@ -30,6 +30,7 @@ export function CallRecordingMediaColumn(props: {<div class="min-h-0 flex-1 overflow-hidden"><CallRecordingVideourl={url()}+ posterUrl={props.record().recordingPreviewUrl ?? undefined}onTimeUpdate={props.onTimeUpdate}setVideoRef={props.setVideoRef}/>diff --git a/js/app/packages/block-call/component/CallRecording/CallRecordingVideo.tsx b/js/app/packages/block-call/component/CallRecording/CallRecordingVideo.tsxindex c33e667d73..64325f4205 100644--- a/js/app/packages/block-call/component/CallRecording/CallRecordingVideo.tsx+++ b/js/app/packages/block-call/component/CallRecording/CallRecordingVideo.tsx@@ -2,6 +2,7 @@ import { createSignal, onCleanup } from 'solid-js';export function CallRecordingVideo(props: {url: string;+ posterUrl?: string;onTimeUpdate?: (seconds: number,source: 'playback' | 'seeking' | 'seeked'@@ -40,6 +41,7 @@ export function CallRecordingVideo(props: {classList={{ 'opacity-0': !isLoaded(), 'opacity-100': isLoaded() }}controlscrossorigin="anonymous"+ poster={props.posterUrl}src={props.url}onLoadedData={() => setIsLoaded(true)}onCanPlay={() => setIsLoaded(true)}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/callRecord.ts b/js/app/packages/service-clients/service-storage/generated/schemas/callRecord.tsindex 8316b88a43..ac45d94c85 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/callRecord.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/callRecord.ts@@ -10,6 +10,7 @@ import type { CallRecordDurationMs } from './callRecordDurationMs';import type { CallRecordEgressId } from './callRecordEgressId';import type { CallRecordEndedAt } from './callRecordEndedAt';import type { CallRecordParticipant } from './callRecordParticipant';+import type { CallRecordRecordingPreviewUrl } from './callRecordRecordingPreviewUrl';import type { CallRecordRecordingStartedAt } from './callRecordRecordingStartedAt';import type { CallRecordRecordingUrl } from './callRecordRecordingUrl';import type { CallRecordSummary } from './callRecordSummary';@@ -41,6 +42,8 @@ archived `call_records`; active calls always return `None`. */isActive: boolean;/** Participants (both active and historic). */participants: CallRecordParticipant[];+ /** Presigned URL for the call recording preview image, if available. */+ recordingPreviewUrl?: CallRecordRecordingPreviewUrl;/** When the egress recording actually began. `None` until the`egress_started` webhook arrives (typically a few seconds after`started_at`). Frontend should anchor transcript-to-audio sync todiff --git a/js/app/packages/service-clients/service-storage/generated/schemas/callRecordRecordingPreviewUrl.ts b/js/app/packages/service-clients/service-storage/generated/schemas/callRecordRecordingPreviewUrl.tsnew file mode 100644index 0000000000..85c4e6aaca--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/callRecordRecordingPreviewUrl.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Presigned URL for the call recording preview image, if available.+ */+export type CallRecordRecordingPreviewUrl = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.tsindex 571ca647f9..5dd2585c0b 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts@@ -128,6 +128,7 @@ export * from './callRecordPreviewOneOfAllOfType';export * from './callRecordPreviewOneOfFour';export * from './callRecordPreviewOneOfFourAllOf';export * from './callRecordPreviewOneOfFourAllOfType';+export * from './callRecordRecordingPreviewUrl';export * from './callRecordRecordingStartedAt';export * from './callRecordRecordingUrl';export * from './callRecordSummary';diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex decb4d81b6..d4fbc650c8 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -955,6 +955,12 @@ export const getCallRecordResponse = zod)).describe('Participants (both active and historic).'),+ recordingPreviewUrl: zod+ .string()+ .nullish()+ .describe(+ 'Presigned URL for the call recording preview image, if available.'+ ),recordingStartedAt: zod.iso.datetime({}).nullish()diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex 738ba5ac78..4b999f6082 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -9628,6 +9628,10 @@},"description": "Participants (both active and historic)."},+ "recordingPreviewUrl": {+ "type": ["string", "null"],+ "description": "Presigned URL for the call recording preview image, if available."+ },"recordingStartedAt": {"type": ["string", "null"],"format": "date-time",diff --git a/local_stack.just b/local_stack.justindex f590445e6b..4833071cc4 100644--- a/local_stack.just+++ b/local_stack.just@@ -92,8 +92,9 @@ create_local_buckets:aws --endpoint-url=http://localhost:4566 s3 mb s3://docx-upload || trueaws --endpoint-url=http://localhost:4566 s3 mb s3://static-file-storage || trueaws --endpoint-url=http://localhost:4566 s3 mb s3://bulk-upload-staging || true+ aws --endpoint-url=http://localhost:4566 s3 mb s3://macro-call-recording-local || true# Apply CORS configuration to all buckets- for bucket in macro-email-attachments doc-storage docx-upload static-file-storage bulk-upload-staging; do \+ for bucket in macro-email-attachments doc-storage docx-upload static-file-storage bulk-upload-staging macro-call-recording-local; do \aws --endpoint-url=http://localhost:4566 s3api put-bucket-cors --bucket $bucket --cors-configuration '{"CORSRules":[{"AllowedOrigins":["http://localhost:3000","http://localhost:3001","http://localhost:3002","http://localhost:3003","http://localhost:3004","http://localhost:3005","http://localhost:3006","http://localhost:3007","http://localhost:3008","http://localhost:3009"],"AllowedMethods":["GET","PUT","POST","DELETE","HEAD"],"AllowedHeaders":["*"],"ExposeHeaders":["ETag"],"MaxAgeSeconds":3600}]}' || true; \done@echo "S3 buckets created"diff --git a/rust/cloud-storage/.sqlx/query-275669451834ace05bb416ced2daa303d315804838e6d3847718eecd239864ee.json b/rust/cloud-storage/.sqlx/query-275669451834ace05bb416ced2daa303d315804838e6d3847718eecd239864ee.jsonnew file mode 100644index 0000000000..4186d5178a--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-275669451834ace05bb416ced2daa303d315804838e6d3847718eecd239864ee.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE calls\n SET preview_url = $2\n WHERE recording_key = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "275669451834ace05bb416ced2daa303d315804838e6d3847718eecd239864ee"+}diff --git a/rust/cloud-storage/.sqlx/query-5bdc882bef1ff0927cbf2e77174648b2c327ac6c646741bc6fcba7fc87c2733b.json b/rust/cloud-storage/.sqlx/query-35d32d2785c724360d20f94c8f10207caec56d853493823994679a4b081a1c38.jsonsimilarity index 83%rename from rust/cloud-storage/.sqlx/query-5bdc882bef1ff0927cbf2e77174648b2c327ac6c646741bc6fcba7fc87c2733b.jsonrename to rust/cloud-storage/.sqlx/query-35d32d2785c724360d20f94c8f10207caec56d853493823994679a4b081a1c38.jsonindex fa39b6acb8..81582bc4ad 100644--- a/rust/cloud-storage/.sqlx/query-5bdc882bef1ff0927cbf2e77174648b2c327ac6c646741bc6fcba7fc87c2733b.json+++ b/rust/cloud-storage/.sqlx/query-35d32d2785c724360d20f94c8f10207caec56d853493823994679a4b081a1c38.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id, channel_id, room_name, created_by, started_at, ended_at, duration_ms, egress_id, recording_key, recording_started_at, custom_name, summary, share_with_team\n FROM call_records\n WHERE id = $1\n ",+ "query": "\n SELECT id, channel_id, room_name, created_by, started_at, ended_at, duration_ms, egress_id, recording_key, preview_url, recording_started_at, custom_name, summary, share_with_team\n FROM call_records\n WHERE id = $1\n ","describe": {"columns": [{@@ -50,21 +50,26 @@},{"ordinal": 9,+ "name": "preview_url",+ "type_info": "Text"+ },+ {+ "ordinal": 10,"name": "recording_started_at","type_info": "Timestamptz"},{- "ordinal": 10,+ "ordinal": 11,"name": "custom_name","type_info": "Text"},{- "ordinal": 11,+ "ordinal": 12,"name": "summary","type_info": "Text"},{- "ordinal": 12,+ "ordinal": 13,"name": "share_with_team","type_info": "Bool"}@@ -87,8 +92,9 @@true,true,true,+ true,false]},- "hash": "5bdc882bef1ff0927cbf2e77174648b2c327ac6c646741bc6fcba7fc87c2733b"+ "hash": "35d32d2785c724360d20f94c8f10207caec56d853493823994679a4b081a1c38"}diff --git a/rust/cloud-storage/.sqlx/query-b977844d337884ba073f0e79bdb5c07193441de40e9097a4d52140a48ddab8c4.json b/rust/cloud-storage/.sqlx/query-40955b135c91071078ae79b3be1c76ed21031ab2497aa0c137a5644f7e7e6e7c.jsonsimilarity index 58%rename from rust/cloud-storage/.sqlx/query-b977844d337884ba073f0e79bdb5c07193441de40e9097a4d52140a48ddab8c4.jsonrename to rust/cloud-storage/.sqlx/query-40955b135c91071078ae79b3be1c76ed21031ab2497aa0c137a5644f7e7e6e7c.jsonindex e1bff89819..6d4d559663 100644--- a/rust/cloud-storage/.sqlx/query-b977844d337884ba073f0e79bdb5c07193441de40e9097a4d52140a48ddab8c4.json+++ b/rust/cloud-storage/.sqlx/query-40955b135c91071078ae79b3be1c76ed21031ab2497aa0c137a5644f7e7e6e7c.json@@ -1,12 +1,17 @@{"db_name": "PostgreSQL",- "query": "\n DELETE FROM call_records WHERE id = $1 RETURNING recording_key\n ",+ "query": "\n DELETE FROM call_records WHERE id = $1 RETURNING recording_key, preview_url\n ","describe": {"columns": [{"ordinal": 0,"name": "recording_key","type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "preview_url",+ "type_info": "Text"}],"parameters": {@@ -15,8 +20,9 @@]},"nullable": [+ true,true]},- "hash": "b977844d337884ba073f0e79bdb5c07193441de40e9097a4d52140a48ddab8c4"+ "hash": "40955b135c91071078ae79b3be1c76ed21031ab2497aa0c137a5644f7e7e6e7c"}diff --git a/rust/cloud-storage/.sqlx/query-dc95a38b8de9ded74150ab9f73406164e654829bbc05cc7717c7c8c497d16953.json b/rust/cloud-storage/.sqlx/query-4d4c2b67879a26c0ad31c817024f3e6bec03dc90a97d3082614d72ad35e6f5d7.jsonsimilarity index 62%rename from rust/cloud-storage/.sqlx/query-dc95a38b8de9ded74150ab9f73406164e654829bbc05cc7717c7c8c497d16953.jsonrename to rust/cloud-storage/.sqlx/query-4d4c2b67879a26c0ad31c817024f3e6bec03dc90a97d3082614d72ad35e6f5d7.jsonindex 814fa88fc7..82c45ef9d9 100644--- a/rust/cloud-storage/.sqlx/query-dc95a38b8de9ded74150ab9f73406164e654829bbc05cc7717c7c8c497d16953.json+++ b/rust/cloud-storage/.sqlx/query-4d4c2b67879a26c0ad31c817024f3e6bec03dc90a97d3082614d72ad35e6f5d7.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO call_records (id, channel_id, room_name, created_by, started_at, ended_at, duration_ms, egress_id, recording_key, recording_started_at, share_permission_id, share_with_team)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)\n ",+ "query": "\n INSERT INTO call_records (id, channel_id, room_name, created_by, started_at, ended_at, duration_ms, egress_id, recording_key, preview_url, recording_started_at, share_permission_id, share_with_team)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)\n ","describe": {"columns": [],"parameters": {@@ -14,6 +14,7 @@"Int8","Text","Text",+ "Text","Timestamptz","Text","Bool"@@ -21,5 +22,5 @@},"nullable": []},- "hash": "dc95a38b8de9ded74150ab9f73406164e654829bbc05cc7717c7c8c497d16953"+ "hash": "4d4c2b67879a26c0ad31c817024f3e6bec03dc90a97d3082614d72ad35e6f5d7"}diff --git a/rust/cloud-storage/.sqlx/query-9a097d6795fd9245014e53697e965ef12e37983d6939632758ec6c8accde3857.json b/rust/cloud-storage/.sqlx/query-8f57f79c4318149ab611e764372c035d54880fcc3d80b41bd5d255245e94263e.jsonsimilarity index 70%rename from rust/cloud-storage/.sqlx/query-9a097d6795fd9245014e53697e965ef12e37983d6939632758ec6c8accde3857.jsonrename to rust/cloud-storage/.sqlx/query-8f57f79c4318149ab611e764372c035d54880fcc3d80b41bd5d255245e94263e.jsonindex 3bd505623f..58b3d745cf 100644--- a/rust/cloud-storage/.sqlx/query-9a097d6795fd9245014e53697e965ef12e37983d6939632758ec6c8accde3857.json+++ b/rust/cloud-storage/.sqlx/query-8f57f79c4318149ab611e764372c035d54880fcc3d80b41bd5d255245e94263e.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id, channel_id, room_name, created_by, created_at, egress_id, recording_key, recording_started_at, share_with_team\n FROM calls\n WHERE id = $1\n ",+ "query": "\n SELECT id, channel_id, room_name, created_by, created_at, egress_id, recording_key, preview_url, recording_started_at, share_permission_id, share_with_team\n FROM calls\n WHERE id = $1\n FOR UPDATE\n ","describe": {"columns": [{@@ -40,11 +40,21 @@},{"ordinal": 7,+ "name": "preview_url",+ "type_info": "Text"+ },+ {+ "ordinal": 8,"name": "recording_started_at","type_info": "Timestamptz"},{- "ordinal": 8,+ "ordinal": 9,+ "name": "share_permission_id",+ "type_info": "Text"+ },+ {+ "ordinal": 10,"name": "share_with_team","type_info": "Bool"}@@ -63,8 +73,10 @@true,true,true,+ true,+ false,false]},- "hash": "9a097d6795fd9245014e53697e965ef12e37983d6939632758ec6c8accde3857"+ "hash": "8f57f79c4318149ab611e764372c035d54880fcc3d80b41bd5d255245e94263e"}diff --git a/rust/cloud-storage/.sqlx/query-a17f9063c77c648ab667942e9e6402ddd6d9b5adcde3a8b55c19c649ac3d5a18.json b/rust/cloud-storage/.sqlx/query-a17f9063c77c648ab667942e9e6402ddd6d9b5adcde3a8b55c19c649ac3d5a18.jsonnew file mode 100644index 0000000000..1c4982322c--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-a17f9063c77c648ab667942e9e6402ddd6d9b5adcde3a8b55c19c649ac3d5a18.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE call_records\n SET preview_url = $2\n WHERE recording_key = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "a17f9063c77c648ab667942e9e6402ddd6d9b5adcde3a8b55c19c649ac3d5a18"+}diff --git a/rust/cloud-storage/.sqlx/query-db72d933a9b6a70e81ea0b65424c72984b05eb102b424085e5ba1e20f75cd11c.json b/rust/cloud-storage/.sqlx/query-aed29afdb2f81b6f920bf65e54981999746302c6e40062c8aa892ab292a92d72.jsonsimilarity index 52%rename from rust/cloud-storage/.sqlx/query-db72d933a9b6a70e81ea0b65424c72984b05eb102b424085e5ba1e20f75cd11c.jsonrename to rust/cloud-storage/.sqlx/query-aed29afdb2f81b6f920bf65e54981999746302c6e40062c8aa892ab292a92d72.jsonindex d96b59a1b3..8b59ea0566 100644--- a/rust/cloud-storage/.sqlx/query-db72d933a9b6a70e81ea0b65424c72984b05eb102b424085e5ba1e20f75cd11c.json+++ b/rust/cloud-storage/.sqlx/query-aed29afdb2f81b6f920bf65e54981999746302c6e40062c8aa892ab292a92d72.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n WITH user_source_ids AS (\n SELECT cp.channel_id::text AS source_id\n FROM comms_channel_participants cp\n WHERE cp.user_id = $1 AND cp.left_at IS NULL\n UNION ALL\n SELECT t.team_id::text AS source_id\n FROM team_user t\n WHERE t.user_id = $1\n UNION ALL\n SELECT $1 AS source_id\n )\n SELECT\n id as \"call_id!\",\n channel_id as \"channel_id!\",\n room_name as \"room_name!\",\n created_by as \"created_by!\",\n created_at as \"started_at!\",\n NULL::timestamptz as \"ended_at\",\n NULL::bigint as \"duration_ms\",\n egress_id,\n recording_key,\n recording_started_at,\n NULL::text as \"custom_name\",\n NULL::text as \"summary\",\n share_with_team as \"share_with_team!\",\n true as \"is_active!\"\n FROM calls c\n WHERE EXISTS (\n SELECT 1 FROM entity_access ea\n JOIN user_source_ids u ON u.source_id = ea.source_id\n WHERE ea.entity_id = c.id\n AND ea.entity_type = 'call'\n )\n AND ($3::bool IS FALSE OR c.channel_id = ANY($4))\n AND ($5::bool IS NULL OR EXISTS (\n SELECT 1 FROM call_participants cp\n WHERE cp.call_id = c.id AND cp.user_id = $1\n ) = $5)\n AND ($6::bool IS FALSE OR c.id = ANY($7))\n UNION ALL\n SELECT\n id as \"call_id!\",\n channel_id as \"channel_id!\",\n room_name as \"room_name!\",\n created_by as \"created_by!\",\n started_at as \"started_at!\",\n ended_at as \"ended_at\",\n duration_ms as \"duration_ms\",\n egress_id,\n recording_key,\n recording_started_at,\n custom_name,\n summary,\n share_with_team as \"share_with_team!\",\n false as \"is_active!\"\n FROM call_records cr\n WHERE EXISTS (\n SELECT 1 FROM entity_access ea\n JOIN user_source_ids u ON u.source_id = ea.source_id\n WHERE ea.entity_id = cr.id\n AND ea.entity_type = 'call'\n )\n AND ($3::bool IS FALSE OR cr.channel_id = ANY($4))\n AND ($5::bool IS NULL OR EXISTS (\n SELECT 1 FROM call_record_participants crp\n WHERE crp.call_record_id = cr.id AND crp.user_id = $1\n ) = $5)\n AND ($6::bool IS FALSE OR cr.id = ANY($7))\n ORDER BY \"started_at!\" DESC\n LIMIT $2\n ",+ "query": "\n WITH user_source_ids AS (\n SELECT cp.channel_id::text AS source_id\n FROM comms_channel_participants cp\n WHERE cp.user_id = $1 AND cp.left_at IS NULL\n UNION ALL\n SELECT t.team_id::text AS source_id\n FROM team_user t\n WHERE t.user_id = $1\n UNION ALL\n SELECT $1 AS source_id\n )\n SELECT\n id as \"call_id!\",\n channel_id as \"channel_id!\",\n room_name as \"room_name!\",\n created_by as \"created_by!\",\n created_at as \"started_at!\",\n NULL::timestamptz as \"ended_at\",\n NULL::bigint as \"duration_ms\",\n egress_id,\n recording_key,\n preview_url,\n recording_started_at,\n NULL::text as \"custom_name\",\n NULL::text as \"summary\",\n share_with_team as \"share_with_team!\",\n true as \"is_active!\"\n FROM calls c\n WHERE EXISTS (\n SELECT 1 FROM entity_access ea\n JOIN user_source_ids u ON u.source_id = ea.source_id\n WHERE ea.entity_id = c.id\n AND ea.entity_type = 'call'\n )\n AND ($3::bool IS FALSE OR c.channel_id = ANY($4))\n AND ($5::bool IS NULL OR EXISTS (\n SELECT 1 FROM call_participants cp\n WHERE cp.call_id = c.id AND cp.user_id = $1\n ) = $5)\n AND ($6::bool IS FALSE OR c.id = ANY($7))\n UNION ALL\n SELECT\n id as \"call_id!\",\n channel_id as \"channel_id!\",\n room_name as \"room_name!\",\n created_by as \"created_by!\",\n started_at as \"started_at!\",\n ended_at as \"ended_at\",\n duration_ms as \"duration_ms\",\n egress_id,\n recording_key,\n preview_url,\n recording_started_at,\n custom_name,\n summary,\n share_with_team as \"share_with_team!\",\n false as \"is_active!\"\n FROM call_records cr\n WHERE EXISTS (\n SELECT 1 FROM entity_access ea\n JOIN user_source_ids u ON u.source_id = ea.source_id\n WHERE ea.entity_id = cr.id\n AND ea.entity_type = 'call'\n )\n AND ($3::bool IS FALSE OR cr.channel_id = ANY($4))\n AND ($5::bool IS NULL OR EXISTS (\n SELECT 1 FROM call_record_participants crp\n WHERE crp.call_record_id = cr.id AND crp.user_id = $1\n ) = $5)\n AND ($6::bool IS FALSE OR cr.id = ANY($7))\n ORDER BY \"started_at!\" DESC\n LIMIT $2\n ","describe": {"columns": [{@@ -50,26 +50,31 @@},{"ordinal": 9,+ "name": "preview_url",+ "type_info": "Text"+ },+ {+ "ordinal": 10,"name": "recording_started_at","type_info": "Timestamptz"},{- "ordinal": 10,+ "ordinal": 11,"name": "custom_name","type_info": "Text"},{- "ordinal": 11,+ "ordinal": 12,"name": "summary","type_info": "Text"},{- "ordinal": 12,+ "ordinal": 13,"name": "share_with_team!","type_info": "Bool"},{- "ordinal": 13,+ "ordinal": 14,"name": "is_active!","type_info": "Bool"}@@ -99,8 +104,9 @@null,null,null,+ null,null]},- "hash": "db72d933a9b6a70e81ea0b65424c72984b05eb102b424085e5ba1e20f75cd11c"+ "hash": "aed29afdb2f81b6f920bf65e54981999746302c6e40062c8aa892ab292a92d72"}diff --git a/rust/cloud-storage/.sqlx/query-3ed1f15b83384be34f4adf83a0f701620481dc4ad81853451add8d1bb7dfe7da.json b/rust/cloud-storage/.sqlx/query-c30711e82376ca92d1e4e346334517c98cfa67d86663cd13575bec99ee24c785.jsonsimilarity index 80%rename from rust/cloud-storage/.sqlx/query-3ed1f15b83384be34f4adf83a0f701620481dc4ad81853451add8d1bb7dfe7da.jsonrename to rust/cloud-storage/.sqlx/query-c30711e82376ca92d1e4e346334517c98cfa67d86663cd13575bec99ee24c785.jsonindex 492643cce7..8a8e0cd1b2 100644--- a/rust/cloud-storage/.sqlx/query-3ed1f15b83384be34f4adf83a0f701620481dc4ad81853451add8d1bb7dfe7da.json+++ b/rust/cloud-storage/.sqlx/query-c30711e82376ca92d1e4e346334517c98cfa67d86663cd13575bec99ee24c785.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id, channel_id, room_name, created_by, created_at, egress_id, recording_key, recording_started_at, share_permission_id, share_with_team\n FROM calls\n WHERE id = $1\n FOR UPDATE\n ",+ "query": "\n SELECT id, channel_id, room_name, created_by, created_at, egress_id, recording_key, preview_url, recording_started_at, share_with_team\n FROM calls\n WHERE id = $1\n ","describe": {"columns": [{@@ -40,13 +40,13 @@},{"ordinal": 7,- "name": "recording_started_at",- "type_info": "Timestamptz"+ "name": "preview_url",+ "type_info": "Text"},{"ordinal": 8,- "name": "share_permission_id",- "type_info": "Text"+ "name": "recording_started_at",+ "type_info": "Timestamptz"},{"ordinal": 9,@@ -68,9 +68,9 @@true,true,true,- false,+ true,false]},- "hash": "3ed1f15b83384be34f4adf83a0f701620481dc4ad81853451add8d1bb7dfe7da"+ "hash": "c30711e82376ca92d1e4e346334517c98cfa67d86663cd13575bec99ee24c785"}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 427890ae4f..4d8a72bf6c 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -1934,6 +1934,24 @@ dependencies = ["uuid",]+[[package]]+name = "call_recording_preview_handler"+version = "0.1.0"+dependencies = [+ "anyhow",+ "aws-sdk-s3",+ "aws_lambda_events",+ "lambda_runtime",+ "macro_aws_config",+ "macro_db_migrator",+ "macro_entrypoint",+ "sqlx",+ "tokio",+ "tracing",+ "urlencoding",+ "uuid",+]+[[package]]name = "cc"version = "1.2.62"diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex a0d5dba376..fcce49b391 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -7,6 +7,7 @@ members = ["backfill_entity_access","bot_id","bots",+ "call_recording_preview_handler","channel_bots","connection_gateway","contacts_service",diff --git a/rust/cloud-storage/call/src/domain/models.rs b/rust/cloud-storage/call/src/domain/models.rsindex bd6338ad35..60bd24ad6e 100644--- a/rust/cloud-storage/call/src/domain/models.rs+++ b/rust/cloud-storage/call/src/domain/models.rs@@ -341,8 +341,13 @@ pub struct CallRecord {/// S3 object key for the call recording (internal, not serialized).#[serde(skip_serializing)]pub recording_key: Option<String>,+ /// Stored S3 object key/path for the preview image (internal, not serialized).+ #[serde(skip_serializing)]+ pub preview_key: Option<String>,/// Presigned URL for the call recording, if available.pub recording_url: Option<String>,+ /// Presigned URL for the call recording preview image, if available.+ pub recording_preview_url: Option<String>,/// Resolved display name for the channel.pub channel_name: Option<String>,/// User-supplied or AI-generated display name for the call. Only set on@@ -361,6 +366,15 @@ pub struct CallRecord {pub transcript: Vec<CallRecordTranscriptSegment>,}+/// Storage object keys associated with a deleted archived call record.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct DeletedCallRecordStorageKeys {+ /// S3 object key for the MP4 recording, without the `calls/` prefix.+ pub recording_key: Option<String>,+ /// Stored S3 object key/path for the preview image.+ pub preview_key: Option<String>,+}+/// Lightweight preview of a call record, returned by the batch preview endpoint.////// Each requested id resolves to one of two outcomes: the call existsdiff --git a/rust/cloud-storage/call/src/domain/ports.rs b/rust/cloud-storage/call/src/domain/ports.rsindex ffc94afe99..0a1fddffcf 100644--- a/rust/cloud-storage/call/src/domain/ports.rs+++ b/rust/cloud-storage/call/src/domain/ports.rs@@ -13,7 +13,8 @@ use item_filters::ast::{LiteralTree, call::CallLiteral};use notification::domain::models::apple::VoipPushPayload;use crate::domain::models::{- CustomSpeakerAssignment, EditCallRecordRequest, EditCallTranscriptRequest,+ CustomSpeakerAssignment, DeletedCallRecordStorageKeys, EditCallRecordRequest,+ EditCallTranscriptRequest,};use super::models::{@@ -251,12 +252,12 @@ pub trait CallRepository: Send + Sync + 'static {/// Delete a row from `call_records` by id. Participants and transcript/// segments are removed via `ON DELETE CASCADE`. No-op if no row matches.- /// Returns the deleted row's `recording_key` (if any) so the caller can- /// clean up the associated recording object in storage.+ /// Returns the deleted row's storage object keys so the caller can clean+ /// up the associated recording and preview objects.fn delete_call_record(&self,call_record_id: &Uuid,- ) -> impl Future<Output = Result<Option<String>, Self::Err>> + Send;+ ) -> impl Future<Output = Result<Option<DeletedCallRecordStorageKeys>, Self::Err>> + Send;/// Patches a call record.fn patch_call_record(@@ -344,6 +345,15 @@ pub trait RecordingStorage: Send + Sync + 'static {recording_key: &str,) -> impl Future<Output = anyhow::Result<String>> + Send;+ /// Generate a presigned GET URL for a stored preview image key/path.+ ///+ /// The preview key/path is stored as a full S3 object key, for example+ /// `calls/{room}/{recording_file_name}/PREVIEW.jpg`.+ fn presign_recording_preview_url(+ &self,+ preview_key: &str,+ ) -> impl Future<Output = anyhow::Result<String>> + Send;+/// Delete the recording object identified by `recording_key`.////// Implementations must apply the same prefix as@@ -353,6 +363,15 @@ pub trait RecordingStorage: Send + Sync + 'static {&self,recording_key: &str,) -> impl Future<Output = anyhow::Result<()>> + Send;++ /// Delete the stored preview image object identified by `preview_key`.+ ///+ /// The preview key/path is stored as a full S3 object key. This operation+ /// should be idempotent — succeed if the key no longer exists.+ fn delete_recording_preview(+ &self,+ preview_key: &str,+ ) -> impl Future<Output = anyhow::Result<()>> + Send;}impl<T: RecordingStorage> RecordingStorage for Option<T> {@@ -363,12 +382,26 @@ impl<T: RecordingStorage> RecordingStorage for Option<T> {}}+ async fn presign_recording_preview_url(&self, preview_key: &str) -> anyhow::Result<String> {+ match self {+ Some(inner) => inner.presign_recording_preview_url(preview_key).await,+ None => anyhow::bail!("recording storage not configured"),+ }+ }+async fn delete_recording(&self, recording_key: &str) -> anyhow::Result<()> {match self {Some(inner) => inner.delete_recording(recording_key).await,None => anyhow::bail!("recording storage not configured"),}}++ async fn delete_recording_preview(&self, preview_key: &str) -> anyhow::Result<()> {+ match self {+ Some(inner) => inner.delete_recording_preview(preview_key).await,+ None => anyhow::bail!("recording storage not configured"),+ }+ }}/// Summarizer port for generating an AI summary of a finished call.diff --git a/rust/cloud-storage/call/src/domain/service.rs b/rust/cloud-storage/call/src/domain/service.rsindex ea11198f99..89cf754110 100644--- a/rust/cloud-storage/call/src/domain/service.rs+++ b/rust/cloud-storage/call/src/domain/service.rs@@ -984,6 +984,17 @@ impl<.ok();}+ if let Some(preview_key) = &record.preview_key {+ record.recording_preview_url = self+ .recording_storage+ .presign_recording_preview_url(preview_key)+ .await+ .inspect_err(+ |e| tracing::error!(error=?e, "failed to presign recording preview URL"),+ )+ .ok();+ }+record.channel_name = self.repo.resolve_channel_name(&record.channel_id, user_id.copied())@@ -1016,7 +1027,7 @@ impl<.map_err(|e| CallError::Internal(e.into()))?.map(|r| r.channel_id);- let recording_key = self+ let storage_keys = self.repo.delete_call_record(&call_id).await@@ -1031,14 +1042,33 @@ impl<tracing::error!(error=?e, call_id=%call_id, "failed to enqueue call record removal from search");}- if let Some(key) = recording_key {- self.recording_storage- .delete_recording(&key)- .await- .inspect_err(|e| {- tracing::error!(error=?e, recording_key=%key, "failed to delete call recording from storage");- })- .ok();+ if let Some(storage_keys) = storage_keys {+ if let Some(key) = storage_keys.recording_key.as_deref() {+ self.recording_storage+ .delete_recording(key)+ .await+ .inspect_err(|e| {+ tracing::error!(error=?e, recording_key=%key, "failed to delete call recording from storage");+ })+ .ok();+ }++ let preview_key = storage_keys.preview_key.or_else(|| {+ storage_keys+ .recording_key+ .as_deref()+ .and_then(derive_preview_key_from_recording_key)+ });++ if let Some(preview_key) = preview_key {+ self.recording_storage+ .delete_recording_preview(&preview_key)+ .await+ .inspect_err(|e| {+ tracing::error!(error=?e, preview_key=%preview_key, "failed to delete call recording preview from storage");+ })+ .ok();+ }}Ok(())@@ -1533,6 +1563,17 @@ fn extract_recording_key(file_url: &str) -> &str {.unwrap_or(file_url)}+fn derive_preview_key_from_recording_key(recording_key: &str) -> Option<String> {+ let recording_key = recording_key+ .strip_prefix("calls/")+ .unwrap_or(recording_key);+ let (parent, file_name) = recording_key.rsplit_once('/')?;+ if parent.is_empty() || file_name.is_empty() {+ return None;+ }+ Some(format!("calls/{parent}/{file_name}/PREVIEW.jpg"))+}+/// Zero-sized placeholder implementation of [`CallSummarizer`].////// [`CallServiceImpl`]'s summarizer generic defaults to this type so callersdiff --git a/rust/cloud-storage/call/src/domain/service/test.rs b/rust/cloud-storage/call/src/domain/service/test.rsindex ab8485bb8f..80a0b5d20e 100644--- a/rust/cloud-storage/call/src/domain/service/test.rs+++ b/rust/cloud-storage/call/src/domain/service/test.rs@@ -9,7 +9,9 @@ use uuid::Uuid;use crate::domain::models::{CallError, CallWebhookEvent, EgressS3Config, VoipPushPayloadRequest};use crate::domain::ports::CallRtcClient;-use super::{exclude_voip_recipients, extract_recording_key};+use super::{+ derive_preview_key_from_recording_key, exclude_voip_recipients, extract_recording_key,+};#[cfg(feature = "outbound")]use macro_db_migrator::MACRO_DB_MIGRATIONS;@@ -217,6 +219,27 @@ fn extract_key_from_bare_calls_path() {assert_eq!(extract_recording_key(url), "abc-123/recording.mp4");}+#[test]+fn derive_preview_key_from_recording_key_uses_recording_file_path() {+ assert_eq!(+ derive_preview_key_from_recording_key("abc-123/recording.mp4").as_deref(),+ Some("calls/abc-123/recording.mp4/PREVIEW.jpg")+ );+}++#[test]+fn derive_preview_key_from_recording_key_accepts_prefixed_recording_key() {+ assert_eq!(+ derive_preview_key_from_recording_key("calls/abc-123/recording.mp4").as_deref(),+ Some("calls/abc-123/recording.mp4/PREVIEW.jpg")+ );+}++#[test]+fn derive_preview_key_from_recording_key_returns_none_without_parent() {+ assert!(derive_preview_key_from_recording_key("recording.mp4").is_none());+}+#[test]fn exclude_voip_recipients_keeps_users_without_voip_delivery() {let alice = user("[email protected]");diff --git a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs b/rust/cloud-storage/call/src/outbound/pg_call_repo.rsindex 8c744f4a3f..99016f2660 100644--- a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs+++ b/rust/cloud-storage/call/src/outbound/pg_call_repo.rs@@ -21,7 +21,8 @@ use uuid::Uuid;use crate::domain::models::{AddParticipantError, Call, CallParticipant, CallRecord, CallRecordParticipant,CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CustomSpeakerAssignment,- EditCallRecordRequest, EnrichedCallTranscript, TranscriptSegmentRequest, WithCallId,+ DeletedCallRecordStorageKeys, EditCallRecordRequest, EnrichedCallTranscript,+ TranscriptSegmentRequest, WithCallId,};use crate::domain::ports::CallRepository;@@ -529,7 +530,7 @@ impl CallRepository for PgCallRepo {// Fetch and lock the active call so concurrent archive_call callers serialize.let call = sqlx::query!(r#"- SELECT id, channel_id, room_name, created_by, created_at, egress_id, recording_key, recording_started_at, share_permission_id, share_with_team+ SELECT id, channel_id, room_name, created_by, created_at, egress_id, recording_key, preview_url, recording_started_at, share_permission_id, share_with_teamFROM callsWHERE id = $1FOR UPDATE@@ -573,12 +574,12 @@ impl CallRepository for PgCallRepo {.signed_duration_since(call.created_at).num_milliseconds().max(0);- // Insert into call_records (including egress_id and any early recording_key).+ // Insert into call_records (including egress_id and any early recording keys).// The record keeps the same id as the original call.sqlx::query!(r#"- INSERT INTO call_records (id, channel_id, room_name, created_by, started_at, ended_at, duration_ms, egress_id, recording_key, recording_started_at, share_permission_id, share_with_team)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)+ INSERT INTO call_records (id, channel_id, room_name, created_by, started_at, ended_at, duration_ms, egress_id, recording_key, preview_url, recording_started_at, share_permission_id, share_with_team)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)"#,call_id,call.channel_id,@@ -589,6 +590,7 @@ impl CallRepository for PgCallRepo {duration_ms,call.egress_id,call.recording_key,+ call.preview_url,call.recording_started_at,&call.share_permission_id,call.share_with_team,@@ -927,7 +929,7 @@ impl CallRepository for PgCallRepo {// Try active `calls` first.if let Some(active) = sqlx::query!(r#"- SELECT id, channel_id, room_name, created_by, created_at, egress_id, recording_key, recording_started_at, share_with_team+ SELECT id, channel_id, room_name, created_by, created_at, egress_id, recording_key, preview_url, recording_started_at, share_with_teamFROM callsWHERE id = $1"#,@@ -991,7 +993,9 @@ impl CallRepository for PgCallRepo {egress_id: active.egress_id,recording_started_at: active.recording_started_at,recording_key: active.recording_key,+ preview_key: active.preview_url,recording_url: None,+ recording_preview_url: None,channel_name: None,custom_name: None,summary: None,@@ -1005,7 +1009,7 @@ impl CallRepository for PgCallRepo {// Fall back to archived `call_records`.let Some(archived) = sqlx::query!(r#"- SELECT id, channel_id, room_name, created_by, started_at, ended_at, duration_ms, egress_id, recording_key, recording_started_at, custom_name, summary, share_with_team+ SELECT id, channel_id, room_name, created_by, started_at, ended_at, duration_ms, egress_id, recording_key, preview_url, recording_started_at, custom_name, summary, share_with_teamFROM call_recordsWHERE id = $1"#,@@ -1073,7 +1077,9 @@ impl CallRepository for PgCallRepo {egress_id: archived.egress_id,recording_started_at: archived.recording_started_at,recording_key: archived.recording_key,+ preview_key: archived.preview_url,recording_url: None,+ recording_preview_url: None,channel_name: None,custom_name: archived.custom_name,summary: archived.summary,@@ -1222,6 +1228,7 @@ impl CallRepository for PgCallRepo {NULL::bigint as "duration_ms",egress_id,recording_key,+ preview_url,recording_started_at,NULL::text as "custom_name",NULL::text as "summary",@@ -1251,6 +1258,7 @@ impl CallRepository for PgCallRepo {duration_ms as "duration_ms",egress_id,recording_key,+ preview_url,recording_started_at,custom_name,summary,@@ -1337,7 +1345,9 @@ impl CallRepository for PgCallRepo {egress_id: row.egress_id,recording_started_at: row.recording_started_at,recording_key: row.recording_key,+ preview_key: row.preview_url,recording_url: None,+ recording_preview_url: None,channel_name: None,custom_name: row.custom_name,summary: row.summary,@@ -1426,12 +1436,15 @@ impl CallRepository for PgCallRepo {}#[tracing::instrument(err, skip(self))]- async fn delete_call_record(&self, call_record_id: &Uuid) -> Result<Option<String>, Self::Err> {+ async fn delete_call_record(+ &self,+ call_record_id: &Uuid,+ ) -> Result<Option<DeletedCallRecordStorageKeys>, Self::Err> {let mut tx = self.pool.begin().await?;let row = sqlx::query!(r#"- DELETE FROM call_records WHERE id = $1 RETURNING recording_key+ DELETE FROM call_records WHERE id = $1 RETURNING recording_key, preview_url"#,call_record_id,)@@ -1446,7 +1459,10 @@ impl CallRepository for PgCallRepo {.await?;tx.commit().await?;- Ok(row.and_then(|r| r.recording_key))+ Ok(row.map(|r| DeletedCallRecordStorageKeys {+ recording_key: r.recording_key,+ preview_key: r.preview_url,+ }))}#[tracing::instrument(skip(self), err)]diff --git a/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rs b/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rsindex d8e729526d..163b75a513 100644--- a/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rs+++ b/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rs@@ -711,31 +711,38 @@ async fn set_active_call_recording_key_updates_matching_call(// Set egress_id on the fixture call first.repo.set_egress_id(&CALL1, "egress-123").await?;+ let recording_key = "0195cea6-fc16-72f2-93b6-144df711f270/2026-04-10T210832.mp4";+ let preview_key =+ "calls/0195cea6-fc16-72f2-93b6-144df711f270/2026-04-10T210832.mp4/PREVIEW.jpg";+// Should update and return true.let updated = repo- .set_active_call_recording_key(- "egress-123",- "0195cea6-fc16-72f2-93b6-144df711f270/2026-04-10T210832.mp4",- )+ .set_active_call_recording_key("egress-123", recording_key).await?;assert!(updated);+ sqlx::query!(+ r#"UPDATE calls SET preview_url = $2 WHERE id = $1"#,+ CALL1,+ preview_key,+ )+ .execute(&pool)+ .await?;+// Verify the key is on the active call.let call = repo.get_call_by_channel_id(&CH1).await?.unwrap();assert_eq!(call.egress_id.as_deref(), Some("egress-123"));- // Now archive and verify recording_key carries forward.+ // Now archive and verify recording_key and preview key carry forward.let record_id = repo.archive_call(&CALL1).await?;- let key = sqlx::query_scalar!(- r#"SELECT recording_key FROM call_records WHERE id = $1"#,+ let archived = sqlx::query!(+ r#"SELECT recording_key, preview_url FROM call_records WHERE id = $1"#,record_id,).fetch_one(&pool).await?;- assert_eq!(- key.as_deref(),- Some("0195cea6-fc16-72f2-93b6-144df711f270/2026-04-10T210832.mp4")- );+ assert_eq!(archived.recording_key.as_deref(), Some(recording_key));+ assert_eq!(archived.preview_url.as_deref(), Some(preview_key));Ok(())}diff --git a/rust/cloud-storage/call/src/outbound/s3_recording_storage.rs b/rust/cloud-storage/call/src/outbound/s3_recording_storage.rsindex 7b3945db3b..5ca8a2d800 100644--- a/rust/cloud-storage/call/src/outbound/s3_recording_storage.rs+++ b/rust/cloud-storage/call/src/outbound/s3_recording_storage.rs@@ -19,9 +19,17 @@ impl S3RecordingStorage {}}+fn recording_object_key(recording_key: &str) -> String {+ format!("calls/{recording_key}")+}++fn preview_object_key(preview_key: &str) -> &str {+ preview_key+}+impl RecordingStorage for S3RecordingStorage {async fn presign_recording_url(&self, recording_key: &str) -> anyhow::Result<String> {- let full_key = format!("calls/{recording_key}");+ let full_key = recording_object_key(recording_key);let presigning_config =aws_sdk_s3::presigning::PresigningConfig::expires_in(Duration::from_secs(3600))?;@@ -29,7 +37,22 @@ impl RecordingStorage for S3RecordingStorage {.client.get_object().bucket(&self.bucket)- .key(&full_key)+ .key(full_key)+ .presigned(presigning_config)+ .await?;++ Ok(macro_aws_config::transform_aws_url(presigned.uri()))+ }++ async fn presign_recording_preview_url(&self, preview_key: &str) -> anyhow::Result<String> {+ let presigning_config =+ aws_sdk_s3::presigning::PresigningConfig::expires_in(Duration::from_secs(3600))?;++ let presigned = self+ .client+ .get_object()+ .bucket(&self.bucket)+ .key(preview_object_key(preview_key)).presigned(presigning_config).await?;@@ -37,13 +60,43 @@ impl RecordingStorage for S3RecordingStorage {}async fn delete_recording(&self, recording_key: &str) -> anyhow::Result<()> {- let full_key = format!("calls/{recording_key}");self.client.delete_object().bucket(&self.bucket)- .key(&full_key)+ .key(recording_object_key(recording_key)).send().await?;Ok(())}++ async fn delete_recording_preview(&self, preview_key: &str) -> anyhow::Result<()> {+ self.client+ .delete_object()+ .bucket(&self.bucket)+ .key(preview_object_key(preview_key))+ .send()+ .await?;+ Ok(())+ }+}++#[cfg(test)]+mod test {+ use super::*;++ #[test]+ fn recording_object_key_adds_calls_prefix() {+ assert_eq!(+ recording_object_key("room/recording.mp4"),+ "calls/room/recording.mp4"+ );+ }++ #[test]+ fn preview_object_key_uses_stored_key_path_without_prefix_changes() {+ assert_eq!(+ preview_object_key("calls/room/recording.mp4/PREVIEW.jpg"),+ "calls/room/recording.mp4/PREVIEW.jpg"+ );+ }}diff --git a/rust/cloud-storage/call_recording_preview_handler/Cargo.toml b/rust/cloud-storage/call_recording_preview_handler/Cargo.tomlnew file mode 100644index 0000000000..f450a68a7f--- /dev/null+++ b/rust/cloud-storage/call_recording_preview_handler/Cargo.toml@@ -0,0 +1,21 @@+[package]+edition = "2024"+name = "call_recording_preview_handler"+publish = false+version = "0.1.0"++[dependencies]+anyhow = { workspace = true }+aws-sdk-s3 = { workspace = true }+aws_lambda_events = { workspace = true, features = ["s3"] }+lambda_runtime = { workspace = true }+macro_aws_config = { path = "../macro_aws_config", features = ["s3"] }+macro_entrypoint = { path = "../macro_entrypoint" }+sqlx = { workspace = true }+tokio = { workspace = true, features = ["fs", "process", "time"] }+tracing = { workspace = true }+urlencoding = { workspace = true }+uuid = { workspace = true }++[dev-dependencies]+macro_db_migrator = { path = "../macro_db_migrator" }diff --git a/rust/cloud-storage/call_recording_preview_handler/event.json b/rust/cloud-storage/call_recording_preview_handler/event.jsonnew file mode 100644index 0000000000..5c96ea5ac5--- /dev/null+++ b/rust/cloud-storage/call_recording_preview_handler/event.json@@ -0,0 +1,38 @@+{+ "Records": [+ {+ "eventVersion": "2.1",+ "eventSource": "aws:s3",+ "awsRegion": "us-east-1",+ "eventTime": "2026-06-04T00:00:00.000Z",+ "eventName": "ObjectCreated:Put",+ "userIdentity": {+ "principalId": "EXAMPLE"+ },+ "requestParameters": {+ "sourceIPAddress": "127.0.0.1"+ },+ "responseElements": {+ "x-amz-request-id": "EXAMPLE123456789",+ "x-amz-id-2": "EXAMPLE"+ },+ "s3": {+ "s3SchemaVersion": "1.0",+ "configurationId": "call-recording-preview",+ "bucket": {+ "name": "macro-call-recording-local",+ "ownerIdentity": {+ "principalId": "EXAMPLE"+ },+ "arn": "arn:aws:s3:::macro-call-recording-local"+ },+ "object": {+ "key": "calls/example-room/2026-06-04T00%3A00%3A00Z.mp4",+ "size": 1048576,+ "eTag": "0123456789abcdef0123456789abcdef",+ "sequencer": "006655AA9911223344"+ }+ }+ }+ ]+}diff --git a/rust/cloud-storage/call_recording_preview_handler/justfile b/rust/cloud-storage/call_recording_preview_handler/justfilenew file mode 100644index 0000000000..123ea870af--- /dev/null+++ b/rust/cloud-storage/call_recording_preview_handler/justfile@@ -0,0 +1,16 @@+lambda_name := file_name(justfile_directory())++test:+ cargo test --all-features++# Build through cross by default so the zip contains a Lambda-compatible Linux binary.+build compiler="cross":+ SQLX_OFFLINE=true cargo lambda build {{ if compiler == "" { "" } else { "--compiler " + compiler } }} --release --bin {{lambda_name}} --output-format zip+ {{ justfile_directory() }}/scripts/package-ffmpeg.sh++watch:+ cargo lambda watch++# invoke the lambda locally after watch is running+invoke:+ cargo lambda invoke {{lambda_name}} --data-file event.jsondiff --git a/rust/cloud-storage/call_recording_preview_handler/scripts/package-ffmpeg.sh b/rust/cloud-storage/call_recording_preview_handler/scripts/package-ffmpeg.shnew file mode 100755index 0000000000..b6ef65d2ad--- /dev/null+++ b/rust/cloud-storage/call_recording_preview_handler/scripts/package-ffmpeg.sh@@ -0,0 +1,52 @@+#!/usr/bin/env bash+set -euo pipefail++lambda_name="call_recording_preview_handler"+ffmpeg_version="7.0.2"+archive_name="ffmpeg-${ffmpeg_version}-amd64-static.tar.xz"+archive_dir="ffmpeg-${ffmpeg_version}-amd64-static"+archive_url="https://johnvansickle.com/ffmpeg/releases/${archive_name}"+archive_sha256="abda8d77ce8309141f83ab8edf0596834087c52467f6badf376a6a2a4c87cf67"++script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+crate_dir="$(cd "${script_dir}/.." && pwd)"+workspace_dir="$(cd "${crate_dir}/.." && pwd)"+zip_path="${workspace_dir}/target/lambda/${lambda_name}/bootstrap.zip"++if [[ ! -f "${zip_path}" ]]; then+ echo "Lambda zip not found: ${zip_path}" >&2+ echo "Run cargo lambda build before packaging ffmpeg." >&2+ exit 1+fi++tmp_dir="$(mktemp -d)"+trap 'rm -rf "${tmp_dir}"' EXIT++archive_path="${tmp_dir}/${archive_name}"+extract_dir="${tmp_dir}/extract"+package_dir="${tmp_dir}/package"++mkdir -p "${extract_dir}" "${package_dir}/bin"++echo "Downloading ${archive_url}"+curl --fail --location --show-error --retry 3 --output "${archive_path}" "${archive_url}"++echo "Verifying ${archive_name}"+printf '%s %s\n' "${archive_sha256}" "${archive_path}" | sha256sum --check --status++tar -xJf "${archive_path}" -C "${extract_dir}" \+ "${archive_dir}/ffmpeg" \+ "${archive_dir}/ffprobe"++install -m 0755 "${extract_dir}/${archive_dir}/ffmpeg" "${package_dir}/bin/ffmpeg"+install -m 0755 "${extract_dir}/${archive_dir}/ffprobe" "${package_dir}/bin/ffprobe"++echo "Adding ffmpeg and ffprobe to ${zip_path}"+(+ cd "${package_dir}"+ zip -9 -q "${zip_path}" bin/ffmpeg bin/ffprobe+)++unzip -tqq "${zip_path}" >/dev/null++echo "Packaged ffmpeg ${ffmpeg_version} into ${zip_path}"diff --git a/rust/cloud-storage/call_recording_preview_handler/src/db.rs b/rust/cloud-storage/call_recording_preview_handler/src/db.rsnew file mode 100644index 0000000000..bfb1f67e9f--- /dev/null+++ b/rust/cloud-storage/call_recording_preview_handler/src/db.rs@@ -0,0 +1,234 @@+use sqlx::{Pool, Postgres};++/// Persist the generated preview image object key/path for a recording.+///+/// `recording_key` is the MP4 key without the `calls/` prefix. `preview_key`+/// is the stable S3 object key/path for the preview image, for example+/// `calls/{room}/{recording_file_name}/PREVIEW.jpg`. Returns the total number+/// of active and archived rows updated so callers can retry when no matching+/// recording row exists yet.+#[tracing::instrument(skip(db), err)]+pub async fn update_preview_key(+ db: &Pool<Postgres>,+ recording_key: &str,+ preview_key: &str,+) -> anyhow::Result<u64> {+ let mut tx = db.begin().await?;++ let active = sqlx::query!(+ r#"+ UPDATE calls+ SET preview_url = $2+ WHERE recording_key = $1+ "#,+ recording_key,+ preview_key,+ )+ .execute(tx.as_mut())+ .await?;++ let archived = sqlx::query!(+ r#"+ UPDATE call_records+ SET preview_url = $2+ WHERE recording_key = $1+ "#,+ recording_key,+ preview_key,+ )+ .execute(tx.as_mut())+ .await?;++ tx.commit().await?;++ Ok(active.rows_affected() + archived.rows_affected())+}++#[cfg(test)]+mod test {+ use super::*;+ use macro_db_migrator::MACRO_DB_MIGRATIONS;+ use sqlx::{Pool, Postgres};+ use uuid::Uuid;++ const CHANNEL_ID: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_00000000c411);+ const ACTIVE_CALL_ID: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_00000000ca11);+ const ARCHIVED_CALL_ID: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_00000000ca12);+ const MATCHING_RECORDING_KEY: &str = "room/recording.mp4";+ const OTHER_RECORDING_KEY: &str = "room/other.mp4";+ const PREVIEW_KEY: &str = "calls/room/recording.mp4/PREVIEW.jpg";++ async fn insert_channel(pool: &Pool<Postgres>) -> anyhow::Result<()> {+ sqlx::query(+ r#"+ INSERT INTO comms_channels (id, name, channel_type, owner_id, created_at, updated_at)+ VALUES ($1, 'preview-test-channel', 'public', 'macro|[email protected]', NOW(), NOW())+ "#,+ )+ .bind(CHANNEL_ID)+ .execute(pool)+ .await?;++ Ok(())+ }++ async fn insert_share_permission(pool: &Pool<Postgres>, id: &str) -> anyhow::Result<()> {+ sqlx::query(+ r#"+ INSERT INTO "SharePermission" (id, "isPublic", "publicAccessLevel", "createdAt", "updatedAt")+ VALUES ($1, FALSE, NULL, NOW(), NOW())+ "#,+ )+ .bind(id)+ .execute(pool)+ .await?;++ Ok(())+ }++ async fn insert_active_call(pool: &Pool<Postgres>, recording_key: &str) -> anyhow::Result<()> {+ insert_share_permission(pool, "preview-test-active-share").await?;+ sqlx::query(+ r#"+ INSERT INTO calls (id, channel_id, room_name, created_by, recording_key, share_permission_id)+ VALUES ($1, $2, 'preview-active-room', 'macro|[email protected]', $3, 'preview-test-active-share')+ "#,+ )+ .bind(ACTIVE_CALL_ID)+ .bind(CHANNEL_ID)+ .bind(recording_key)+ .execute(pool)+ .await?;++ Ok(())+ }++ async fn insert_archived_call(+ pool: &Pool<Postgres>,+ recording_key: &str,+ ) -> anyhow::Result<()> {+ insert_share_permission(pool, "preview-test-archived-share").await?;+ sqlx::query(+ r#"+ INSERT INTO call_records (+ id,+ channel_id,+ room_name,+ created_by,+ started_at,+ ended_at,+ duration_ms,+ recording_key,+ share_permission_id+ )+ VALUES (+ $1,+ $2,+ 'preview-archived-room',+ 'macro|[email protected]',+ NOW(),+ NOW(),+ 0,+ $3,+ 'preview-test-archived-share'+ )+ "#,+ )+ .bind(ARCHIVED_CALL_ID)+ .bind(CHANNEL_ID)+ .bind(recording_key)+ .execute(pool)+ .await?;++ Ok(())+ }++ async fn preview_url_for_active_call(pool: &Pool<Postgres>) -> anyhow::Result<Option<String>> {+ let preview_url = sqlx::query_scalar(+ r#"+ SELECT preview_url+ FROM calls+ WHERE id = $1+ "#,+ )+ .bind(ACTIVE_CALL_ID)+ .fetch_one(pool)+ .await?;++ Ok(preview_url)+ }++ async fn preview_url_for_archived_call(+ pool: &Pool<Postgres>,+ ) -> anyhow::Result<Option<String>> {+ let preview_url = sqlx::query_scalar(+ r#"+ SELECT preview_url+ FROM call_records+ WHERE id = $1+ "#,+ )+ .bind(ARCHIVED_CALL_ID)+ .fetch_one(pool)+ .await?;++ Ok(preview_url)+ }++ #[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+ async fn update_preview_key_updates_active_and_archived_rows(+ pool: Pool<Postgres>,+ ) -> anyhow::Result<()> {+ insert_channel(&pool).await?;+ insert_active_call(&pool, MATCHING_RECORDING_KEY).await?;+ insert_archived_call(&pool, MATCHING_RECORDING_KEY).await?;++ let rows = update_preview_key(&pool, MATCHING_RECORDING_KEY, PREVIEW_KEY).await?;++ assert_eq!(rows, 2);+ assert_eq!(+ preview_url_for_active_call(&pool).await?.as_deref(),+ Some(PREVIEW_KEY)+ );+ assert_eq!(+ preview_url_for_archived_call(&pool).await?.as_deref(),+ Some(PREVIEW_KEY)+ );+ Ok(())+ }++ #[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+ async fn update_preview_key_updates_only_matching_recording_key(+ pool: Pool<Postgres>,+ ) -> anyhow::Result<()> {+ insert_channel(&pool).await?;+ insert_active_call(&pool, MATCHING_RECORDING_KEY).await?;+ insert_archived_call(&pool, OTHER_RECORDING_KEY).await?;++ let rows = update_preview_key(&pool, MATCHING_RECORDING_KEY, PREVIEW_KEY).await?;++ assert_eq!(rows, 1);+ assert_eq!(+ preview_url_for_active_call(&pool).await?.as_deref(),+ Some(PREVIEW_KEY)+ );+ assert!(preview_url_for_archived_call(&pool).await?.is_none());+ Ok(())+ }++ #[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+ async fn update_preview_key_returns_zero_when_no_rows_match(+ pool: Pool<Postgres>,+ ) -> anyhow::Result<()> {+ insert_channel(&pool).await?;+ insert_active_call(&pool, OTHER_RECORDING_KEY).await?;+ insert_archived_call(&pool, OTHER_RECORDING_KEY).await?;++ let rows = update_preview_key(&pool, MATCHING_RECORDING_KEY, PREVIEW_KEY).await?;++ assert_eq!(rows, 0);+ assert!(preview_url_for_active_call(&pool).await?.is_none());+ assert!(preview_url_for_archived_call(&pool).await?.is_none());+ Ok(())+ }+}diff --git a/rust/cloud-storage/call_recording_preview_handler/src/event.rs b/rust/cloud-storage/call_recording_preview_handler/src/event.rsnew file mode 100644index 0000000000..c1088a2784--- /dev/null+++ b/rust/cloud-storage/call_recording_preview_handler/src/event.rs@@ -0,0 +1,265 @@+use std::{path::PathBuf, time::Duration};++use anyhow::{Context, bail};+use aws_lambda_events::event::s3::{S3Event, S3EventRecord};+use aws_sdk_s3::{Client as S3Client, primitives::ByteStream};+use lambda_runtime::{Error, LambdaEvent};+use sqlx::{PgPool, Postgres};+use tracing::Instrument;++use crate::{db, ffmpeg::FfmpegTools, key};++const DEFAULT_PRESIGNED_URL_SECONDS: u64 = 900;+const JPEG_CONTENT_TYPE: &str = "image/jpeg";++/// Runtime configuration for the call recording preview handler.+#[derive(Debug, Clone)]+pub struct HandlerConfig {+ ffmpeg_path: PathBuf,+ ffprobe_path: PathBuf,+ default_bucket_name: Option<String>,+ presigned_url_duration: Duration,+}++impl HandlerConfig {+ /// Builds handler configuration from environment variables.+ ///+ /// `FFMPEG_PATH` and `FFPROBE_PATH` override the default Lambda paths under+ /// `${LAMBDA_TASK_ROOT}/bin`. `CALL_RECORDING_BUCKET_NAME` is used only as a+ /// fallback when a malformed local S3 event does not include a bucket name.+ pub fn from_env() -> Self {+ let task_root = std::env::var_os("LAMBDA_TASK_ROOT")+ .map(PathBuf::from)+ .unwrap_or_else(|| PathBuf::from("/var/task"));+ let ffmpeg_path = std::env::var_os("FFMPEG_PATH")+ .map(PathBuf::from)+ .unwrap_or_else(|| task_root.join("bin/ffmpeg"));+ let ffprobe_path = std::env::var_os("FFPROBE_PATH")+ .map(PathBuf::from)+ .unwrap_or_else(|| task_root.join("bin/ffprobe"));+ let default_bucket_name = std::env::var("CALL_RECORDING_BUCKET_NAME")+ .ok()+ .filter(|bucket| !bucket.trim().is_empty());++ Self {+ ffmpeg_path,+ ffprobe_path,+ default_bucket_name,+ presigned_url_duration: Duration::from_secs(DEFAULT_PRESIGNED_URL_SECONDS),+ }+ }++ /// Builds handler configuration with explicit ffmpeg and ffprobe paths.+ pub fn with_tool_paths(+ ffmpeg_path: impl Into<PathBuf>,+ ffprobe_path: impl Into<PathBuf>,+ ) -> Self {+ Self {+ ffmpeg_path: ffmpeg_path.into(),+ ffprobe_path: ffprobe_path.into(),+ default_bucket_name: None,+ presigned_url_duration: Duration::from_secs(DEFAULT_PRESIGNED_URL_SECONDS),+ }+ }+}++/// Shared Lambda handler state.+#[derive(Clone)]+pub struct HandlerState {+ s3_client: S3Client,+ db: PgPool,+ tools: FfmpegTools,+ default_bucket_name: Option<String>,+ presigned_url_duration: Duration,+}++impl HandlerState {+ /// Creates handler state from AWS, database, and handler configuration.+ pub fn new(s3_client: S3Client, db: PgPool, config: HandlerConfig) -> Self {+ Self {+ s3_client,+ db,+ tools: FfmpegTools::new(config.ffmpeg_path, config.ffprobe_path),+ default_bucket_name: config.default_bucket_name,+ presigned_url_duration: config.presigned_url_duration,+ }+ }+}++/// Processes an S3 event and generates previews for eligible MP4 recordings.+#[tracing::instrument(skip(state, event), err)]+pub async fn handler(state: HandlerState, event: LambdaEvent<S3Event>) -> Result<(), Error> {+ tracing::info!(+ record_count = event.payload.records.len(),+ "processing call recording preview event"+ );++ for (index, record) in event.payload.records.into_iter().enumerate() {+ let span = tracing::info_span!(+ "process_s3_record",+ record_index = index,+ encoded_key = record.s3.object.key.as_deref().unwrap_or_default(),+ );++ process_record(&state, record, index)+ .instrument(span)+ .await?;+ }++ Ok(())+}++#[tracing::instrument(skip(state, record), err)]+async fn process_record(+ state: &HandlerState,+ record: S3EventRecord,+ record_index: usize,+) -> anyhow::Result<()> {+ let encoded_key = record+ .s3+ .object+ .key+ .as_deref()+ .context("S3 event record did not include an object key")?;++ let preview_keys = match key::preview_keys_from_encoded_s3_key(encoded_key)? {+ key::KeyDecision::Process(preview_keys) => preview_keys,+ key::KeyDecision::Skip(reason) => {+ tracing::info!(reason = reason.as_str(), "skipping S3 object");+ return Ok(());+ }+ };++ let bucket_name = bucket_name_from_record(&record, state)+ .context("S3 event record did not include a bucket name")?;+ tracing::info!(+ bucket = %bucket_name,+ source_key = %preview_keys.source_key,+ preview_key = %preview_keys.preview_key,+ "generating call recording preview"+ );++ let source_url = presign_source_object(+ &state.s3_client,+ bucket_name,+ &preview_keys.source_key,+ state.presigned_url_duration,+ )+ .await?;+ let output_path = temp_preview_path(record_index);++ state+ .tools+ .create_preview_jpeg(&source_url, &output_path)+ .await+ .with_context(|| {+ format!(+ "failed to create preview JPEG for {}",+ preview_keys.source_key+ )+ })?;++ upload_preview_jpeg(+ &state.s3_client,+ bucket_name,+ &preview_keys.preview_key,+ &output_path,+ )+ .await?;++ persist_preview_key(+ &state.db,+ &preview_keys.recording_key,+ &preview_keys.preview_key,+ )+ .await?;++ tokio::fs::remove_file(&output_path)+ .await+ .inspect_err(|error| tracing::warn!(error=?error, path=%output_path.display(), "failed to remove temporary preview image"))+ .ok();++ Ok(())+}++fn bucket_name_from_record<'a>(+ record: &'a S3EventRecord,+ state: &'a HandlerState,+) -> Option<&'a str> {+ record+ .s3+ .bucket+ .name+ .as_deref()+ .filter(|bucket| !bucket.trim().is_empty())+ .or(state.default_bucket_name.as_deref())+}++#[tracing::instrument(skip(client), err)]+async fn presign_source_object(+ client: &S3Client,+ bucket_name: &str,+ source_key: &str,+ duration: Duration,+) -> anyhow::Result<String> {+ let presigning_config = aws_sdk_s3::presigning::PresigningConfig::expires_in(duration)?;+ let presigned = client+ .get_object()+ .bucket(bucket_name)+ .key(source_key)+ .presigned(presigning_config)+ .await+ .with_context(|| format!("failed to presign s3://{bucket_name}/{source_key}"))?;++ Ok(macro_aws_config::transform_aws_url_for_internal_fetch(+ presigned.uri(),+ ))+}++#[tracing::instrument(skip(client, output_path), err)]+async fn upload_preview_jpeg(+ client: &S3Client,+ bucket_name: &str,+ preview_key: &str,+ output_path: &std::path::Path,+) -> anyhow::Result<()> {+ let body = tokio::fs::read(output_path)+ .await+ .with_context(|| format!("failed to read {}", output_path.display()))?;++ client+ .put_object()+ .bucket(bucket_name)+ .key(preview_key)+ .content_type(JPEG_CONTENT_TYPE)+ .body(ByteStream::from(body))+ .send()+ .await+ .with_context(|| format!("failed to upload s3://{bucket_name}/{preview_key}"))?;++ Ok(())+}++#[tracing::instrument(skip(db), err)]+async fn persist_preview_key(+ db: &sqlx::Pool<Postgres>,+ recording_key: &str,+ preview_key: &str,+) -> anyhow::Result<()> {+ let rows_updated = db::update_preview_key(db, recording_key, preview_key)+ .await+ .with_context(|| format!("failed to persist preview key for {recording_key}"))?;++ if rows_updated > 0 {+ return Ok(());+ }++ bail!("no call rows matched recording_key {recording_key}")+}++fn temp_preview_path(record_index: usize) -> PathBuf {+ PathBuf::from("/tmp").join(format!(+ "call-recording-preview-{}-{record_index}.jpg",+ std::process::id()+ ))+}diff --git a/rust/cloud-storage/call_recording_preview_handler/src/ffmpeg.rs b/rust/cloud-storage/call_recording_preview_handler/src/ffmpeg.rsnew file mode 100644index 0000000000..e40063da3f--- /dev/null+++ b/rust/cloud-storage/call_recording_preview_handler/src/ffmpeg.rs@@ -0,0 +1,181 @@+#[cfg(test)]+mod test;++use std::{path::Path, process::Output, time::Duration};++use anyhow::{Context, bail};+use tokio::process::Command;++const COMMAND_OUTPUT_TIMEOUT: Duration = Duration::from_secs(60);++#[derive(Debug, Clone)]+pub(crate) struct FfmpegTools {+ ffmpeg_path: std::path::PathBuf,+ ffprobe_path: std::path::PathBuf,+}++impl FfmpegTools {+ pub(crate) fn new(+ ffmpeg_path: impl Into<std::path::PathBuf>,+ ffprobe_path: impl Into<std::path::PathBuf>,+ ) -> Self {+ Self {+ ffmpeg_path: ffmpeg_path.into(),+ ffprobe_path: ffprobe_path.into(),+ }+ }++ #[tracing::instrument(skip(self, source_url), err)]+ pub(crate) async fn create_preview_jpeg(+ &self,+ source_url: &str,+ output_path: &Path,+ ) -> anyhow::Result<()> {+ let duration = probe_duration(&self.ffprobe_path, source_url).await?;+ let midpoint_seconds = duration / 2.0;++ extract_frame_with_fallback(&self.ffmpeg_path, source_url, midpoint_seconds, output_path)+ .await+ }+}++#[tracing::instrument(skip(source_url), err)]+pub(crate) async fn probe_duration(ffprobe_path: &Path, source_url: &str) -> anyhow::Result<f64> {+ let mut command = Command::new(ffprobe_path);+ command+ .arg("-v")+ .arg("error")+ .arg("-show_entries")+ .arg("format=duration")+ .arg("-of")+ .arg("default=noprint_wrappers=1:nokey=1")+ .arg(source_url);++ let output = command_output(&mut command, "ffprobe").await?;++ ensure_command_success(&output, "ffprobe")?;+ let stdout = std::str::from_utf8(&output.stdout).context("ffprobe output was not UTF-8")?;++ parse_duration(stdout)+}++pub(crate) fn parse_duration(output: &str) -> anyhow::Result<f64> {+ let duration_text = output+ .lines()+ .map(str::trim)+ .find(|line| !line.is_empty())+ .context("ffprobe did not return a duration")?;++ let duration = duration_text+ .parse::<f64>()+ .with_context(|| format!("failed to parse ffprobe duration {duration_text:?}"))?;++ if duration.is_finite() && duration >= 0.0 {+ return Ok(duration);+ }++ bail!("ffprobe returned invalid duration {duration}")+}++#[tracing::instrument(skip(source_url), err)]+async fn extract_frame_with_fallback(+ ffmpeg_path: &Path,+ source_url: &str,+ midpoint_seconds: f64,+ output_path: &Path,+) -> anyhow::Result<()> {+ remove_file_if_present(output_path).await?;++ let midpoint_result =+ extract_frame(ffmpeg_path, source_url, midpoint_seconds, output_path).await;+ if file_has_data(output_path).await? {+ return Ok(());+ }++ match midpoint_result {+ Ok(()) => tracing::warn!("midpoint ffmpeg extraction produced no frame; retrying at start"),+ Err(error) => {+ tracing::warn!(error=?error, "midpoint ffmpeg extraction failed without a frame; retrying at start");+ }+ }++ remove_file_if_present(output_path).await?;+ extract_frame(ffmpeg_path, source_url, 0.0, output_path)+ .await+ .context("failed to extract preview frame at start of recording")?;++ if file_has_data(output_path).await? {+ return Ok(());+ }++ bail!("ffmpeg completed but did not create a preview frame")+}++#[tracing::instrument(skip(source_url), err)]+async fn extract_frame(+ ffmpeg_path: &Path,+ source_url: &str,+ seek_seconds: f64,+ output_path: &Path,+) -> anyhow::Result<()> {+ let mut command = Command::new(ffmpeg_path);+ command+ .arg("-y")+ .arg("-ss")+ .arg(format_seek_seconds(seek_seconds))+ .arg("-i")+ .arg(source_url)+ .arg("-frames:v")+ .arg("1")+ .arg("-q:v")+ .arg("2")+ .arg(output_path);++ let output = command_output(&mut command, "ffmpeg").await?;++ ensure_command_success(&output, "ffmpeg")+}++async fn command_output(command: &mut Command, command_name: &str) -> anyhow::Result<Output> {+ command.kill_on_drop(true);+ let output = tokio::time::timeout(COMMAND_OUTPUT_TIMEOUT, command.output())+ .await+ .with_context(|| format!("timed out running {command_name}"))?;++ output.with_context(|| format!("failed to run {command_name}"))+}++fn ensure_command_success(output: &Output, command_name: &str) -> anyhow::Result<()> {+ if output.status.success() {+ return Ok(());+ }++ let stdout = String::from_utf8_lossy(&output.stdout);+ let stderr = String::from_utf8_lossy(&output.stderr);+ bail!(+ "{command_name} failed with status {}. stdout: {} stderr: {}",+ output.status,+ stdout.trim(),+ stderr.trim(),+ )+}++async fn file_has_data(path: &Path) -> anyhow::Result<bool> {+ match tokio::fs::metadata(path).await {+ Ok(metadata) => Ok(metadata.len() > 0),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),+ Err(error) => Err(error).with_context(|| format!("failed to inspect {}", path.display())),+ }+}++async fn remove_file_if_present(path: &Path) -> anyhow::Result<()> {+ match tokio::fs::remove_file(path).await {+ Ok(()) => Ok(()),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),+ Err(error) => Err(error).with_context(|| format!("failed to remove {}", path.display())),+ }+}++fn format_seek_seconds(seconds: f64) -> String {+ format!("{seconds:.3}")+}diff --git a/rust/cloud-storage/call_recording_preview_handler/src/ffmpeg/test.rs b/rust/cloud-storage/call_recording_preview_handler/src/ffmpeg/test.rsnew file mode 100644index 0000000000..b6a6118408--- /dev/null+++ b/rust/cloud-storage/call_recording_preview_handler/src/ffmpeg/test.rs@@ -0,0 +1,48 @@+use std::path::Path;++use super::*;++#[test]+fn parse_duration_reads_first_non_empty_line() -> anyhow::Result<()> {+ let duration = parse_duration("\n12.345678\n")?;++ assert_eq!(duration, 12.345678);+ Ok(())+}++#[test]+fn parse_duration_rejects_missing_duration() {+ let error = parse_duration("\n\t\n").expect_err("empty output should fail");++ assert!(+ error+ .to_string()+ .contains("ffprobe did not return a duration")+ );+}++#[test]+fn parse_duration_rejects_non_numeric_duration() {+ let error = parse_duration("N/A\n").expect_err("non-numeric output should fail");++ assert!(+ error+ .to_string()+ .contains("failed to parse ffprobe duration")+ );+}++#[tokio::test]+async fn probe_duration_reports_missing_ffprobe_executable() {+ let missing_ffprobe = Path::new("/tmp/macro-call-preview-missing-ffprobe");+ let error = probe_duration(missing_ffprobe, "https://example.invalid/recording.mp4")+ .await+ .expect_err("missing ffprobe executable should fail");++ assert!(error.to_string().contains("failed to run ffprobe"));+}++#[test]+fn format_seek_seconds_uses_millisecond_precision() {+ assert_eq!(format_seek_seconds(1.23456), "1.235");+}diff --git a/rust/cloud-storage/call_recording_preview_handler/src/key.rs b/rust/cloud-storage/call_recording_preview_handler/src/key.rsnew file mode 100644index 0000000000..4142ccba36--- /dev/null+++ b/rust/cloud-storage/call_recording_preview_handler/src/key.rs@@ -0,0 +1,81 @@+#[cfg(test)]+mod test;++use anyhow::Context;++const CALLS_PREFIX: &str = "calls/";+const MP4_SUFFIX: &str = ".mp4";+const PREVIEW_FILENAME: &str = "PREVIEW.jpg";++#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct PreviewKeys {+ pub source_key: String,+ pub recording_key: String,+ pub preview_key: String,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) enum KeyDecision {+ Process(PreviewKeys),+ Skip(SkipReason),+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum SkipReason {+ MissingCallsPrefix,+ MissingParent,+ PreviewImage,+ NonMp4,+}++impl SkipReason {+ pub(crate) fn as_str(self) -> &'static str {+ match self {+ Self::MissingCallsPrefix => "object key is outside calls/",+ Self::MissingParent => "object key has no call recording parent",+ Self::PreviewImage => "object key is the generated preview image",+ Self::NonMp4 => "object key is not an mp4 recording",+ }+ }+}++pub(crate) fn preview_keys_from_encoded_s3_key(encoded_key: &str) -> anyhow::Result<KeyDecision> {+ let decoded_key = decode_s3_object_key(encoded_key)?;+ Ok(preview_keys_from_decoded_s3_key(&decoded_key))+}++pub(crate) fn decode_s3_object_key(encoded_key: &str) -> anyhow::Result<String> {+ let form_encoded_key = encoded_key.replace('+', "%20");+ let decoded = urlencoding::decode(&form_encoded_key)+ .with_context(|| format!("failed to decode S3 object key {encoded_key}"))?;++ Ok(decoded.into_owned())+}++pub(crate) fn preview_keys_from_decoded_s3_key(decoded_key: &str) -> KeyDecision {+ let Some(recording_key) = decoded_key.strip_prefix(CALLS_PREFIX) else {+ return KeyDecision::Skip(SkipReason::MissingCallsPrefix);+ };++ let Some((parent, file_name)) = recording_key.rsplit_once('/') else {+ return KeyDecision::Skip(SkipReason::MissingParent);+ };++ if parent.is_empty() || file_name.is_empty() {+ return KeyDecision::Skip(SkipReason::MissingParent);+ }++ if file_name == PREVIEW_FILENAME {+ return KeyDecision::Skip(SkipReason::PreviewImage);+ }++ if !file_name.ends_with(MP4_SUFFIX) {+ return KeyDecision::Skip(SkipReason::NonMp4);+ }++ KeyDecision::Process(PreviewKeys {+ source_key: decoded_key.to_string(),+ recording_key: recording_key.to_string(),+ preview_key: format!("{CALLS_PREFIX}{parent}/{file_name}/{PREVIEW_FILENAME}"),+ })+}diff --git a/rust/cloud-storage/call_recording_preview_handler/src/key/test.rs b/rust/cloud-storage/call_recording_preview_handler/src/key/test.rsnew file mode 100644index 0000000000..4cee328c07--- /dev/null+++ b/rust/cloud-storage/call_recording_preview_handler/src/key/test.rs@@ -0,0 +1,59 @@+use super::*;++#[test]+fn decode_s3_object_key_decodes_percent_encoding_and_spaces() -> anyhow::Result<()> {+ let decoded = decode_s3_object_key("calls/room+name/file%20name%2Bplus.mp4")?;++ assert_eq!(decoded, "calls/room name/file name+plus.mp4");+ Ok(())+}++#[test]+fn preview_keys_from_decoded_s3_key_derives_preview_key() {+ let decision = preview_keys_from_decoded_s3_key("calls/example-room/1700000000.mp4");++ assert_eq!(+ decision,+ KeyDecision::Process(PreviewKeys {+ source_key: "calls/example-room/1700000000.mp4".to_string(),+ recording_key: "example-room/1700000000.mp4".to_string(),+ preview_key: "calls/example-room/1700000000.mp4/PREVIEW.jpg".to_string(),+ })+ );+}++#[test]+fn preview_keys_from_decoded_s3_key_preserves_nested_parent_path() {+ let decision = preview_keys_from_decoded_s3_key("calls/org/example-room/recording.mp4");++ assert_eq!(+ decision,+ KeyDecision::Process(PreviewKeys {+ source_key: "calls/org/example-room/recording.mp4".to_string(),+ recording_key: "org/example-room/recording.mp4".to_string(),+ preview_key: "calls/org/example-room/recording.mp4/PREVIEW.jpg".to_string(),+ })+ );+}++#[test]+fn preview_keys_from_decoded_s3_key_skips_non_mp4_keys() {+ let decision = preview_keys_from_decoded_s3_key("calls/example-room/recording.mov");++ assert_eq!(decision, KeyDecision::Skip(SkipReason::NonMp4));+}++#[test]+fn preview_keys_from_decoded_s3_key_skips_preview_images() {+ let decision =+ preview_keys_from_decoded_s3_key("calls/example-room/1700000000.mp4/PREVIEW.jpg");++ assert_eq!(decision, KeyDecision::Skip(SkipReason::PreviewImage));+}++#[test]+fn preview_keys_from_decoded_s3_key_skips_keys_outside_calls_prefix() {+ let decision = preview_keys_from_decoded_s3_key("other/example-room/recording.mp4");++ assert_eq!(decision, KeyDecision::Skip(SkipReason::MissingCallsPrefix));+}diff --git a/rust/cloud-storage/call_recording_preview_handler/src/lib.rs b/rust/cloud-storage/call_recording_preview_handler/src/lib.rsnew file mode 100644index 0000000000..1fdcbbedbe--- /dev/null+++ b/rust/cloud-storage/call_recording_preview_handler/src/lib.rs@@ -0,0 +1,10 @@+#![deny(missing_docs)]++//! Lambda handler for generating call recording preview thumbnails.++mod db;+mod event;+mod ffmpeg;+mod key;++pub use event::{HandlerConfig, HandlerState, handler};diff --git a/rust/cloud-storage/call_recording_preview_handler/src/main.rs b/rust/cloud-storage/call_recording_preview_handler/src/main.rsnew file mode 100644index 0000000000..0400884c90--- /dev/null+++ b/rust/cloud-storage/call_recording_preview_handler/src/main.rs@@ -0,0 +1,37 @@+#![recursion_limit = "256"]++use anyhow::Context;+use aws_lambda_events::event::s3::S3Event;+use call_recording_preview_handler::{HandlerConfig, HandlerState, handler};+use lambda_runtime::{Error, LambdaEvent, run, service_fn, tracing};+use macro_entrypoint::MacroEntrypoint;+use sqlx::postgres::PgPoolOptions;++#[tokio::main]+async fn main() -> Result<(), Error> {+ MacroEntrypoint::default().init();++ tracing::trace!("initiating call recording preview lambda");++ let config = HandlerConfig::from_env();+ let database_url = std::env::var("DATABASE_URL").context("DATABASE_URL must be provided")?;+ let db = PgPoolOptions::new()+ .min_connections(1)+ .max_connections(1)+ .connect(&database_url)+ .await+ .context("could not connect to db")?;++ tracing::trace!("initialized db connection");++ let s3_client = macro_aws_config::s3_client().await;+ tracing::trace!("initialized s3 client");++ let state = HandlerState::new(s3_client, db, config);+ let func = service_fn(move |event: LambdaEvent<S3Event>| {+ let state = state.clone();+ async move { handler(state, event).await }+ });++ run(func).await+}diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfileindex e8a5c33f0d..73f10654b1 100644--- a/rust/cloud-storage/justfile+++ b/rust/cloud-storage/justfile@@ -31,6 +31,7 @@ build_dev_service_images:# Build all lambda functionsbuild_lambdas compiler="":ulimit -n 10240 && just docx_unzip_handler/build {{compiler}}+ ulimit -n 10240 && just call_recording_preview_handler/build {{compiler}}ulimit -n 10240 && just delete_chat_handler/build {{compiler}}ulimit -n 10240 && just organization_retention_handler/build {{compiler}}ulimit -n 10240 && just organization_retention_trigger/build {{compiler}}@@ -102,6 +103,7 @@ setup_test_envs:echo "DATABASE_URL={{ DATABASE_URL }}" >> ./task_dedup/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./crm/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./bots/.env+ echo "DATABASE_URL={{ DATABASE_URL }}" >> ./call_recording_preview_handler/.envsetup_macrodb:just macro_db_client/create_dbdiff --git a/rust/cloud-storage/macro_db_client/migrations/20260604160449_call_record_preview_url.sql b/rust/cloud-storage/macro_db_client/migrations/20260604160449_call_record_preview_url.sqlnew file mode 100644index 0000000000..38558016b7--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260604160449_call_record_preview_url.sql@@ -0,0 +1,2 @@+ALTER TABLE calls ADD COLUMN preview_url TEXT;+ALTER TABLE call_records ADD COLUMN preview_url TEXT;diff --git a/rust/cloud-storage/models_soup/src/call_record/test.rs b/rust/cloud-storage/models_soup/src/call_record/test.rsindex 4efbcf3749..b76af0db4f 100644--- a/rust/cloud-storage/models_soup/src/call_record/test.rs+++ b/rust/cloud-storage/models_soup/src/call_record/test.rs@@ -16,7 +16,9 @@ fn record_with_participants(user_ids: &[&str]) -> CallRecord {egress_id: None,recording_started_at: None,recording_key: None,+ preview_key: None,recording_url: None,+ recording_preview_url: None,channel_name: None,custom_name: None,summary: None,