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(calls): calls backend (#2332)
Will Hutchinsond29f468e9cfa
diff --git a/.env-local.enc b/.env-local.encindex bc21d987d4..c379321408 100644--- a/.env-local.enc+++ b/.env-local.enc@@ -121,6 +121,9 @@ GITHUB_SYNC_APP_CLIENT_ID=ENC[AES256_GCM,data:qohjsgb/qeu5cj8o3mRhwuPF2eclIQ==,iSTRIPE_PRICE_ID_HAIKU=ENC[AES256_GCM,data:Ct+Z0bCbHZhEn6xk0y6Xz0j8IOxDsvoVt+nrQnjO788=,iv:fdbHkHe3ib5vaw3W6X/DAjlE67SOlCOkWg9J0OaCzSU=,tag:MRl5soTJFLmvLlpmQfeSLA==,type:str]STRIPE_PRICE_ID_SONNET=ENC[AES256_GCM,data:7gVVpmgmlObXMrNoMXik4vXzwzlMiYtHuQNUkoI6L10=,iv:F0ghJOngMJURVGqbQEcrNUEARTo3uGKr2Ia6E9eXr/Y=,tag:HNoZAEbAtxfpur7wtKnxCg==,type:str]STRIPE_PRICE_ID_OPUS=ENC[AES256_GCM,data:EWmSRm5ncUnZSfPX+TB6Q+Er9wfMpQFJTLtpwzcmH24=,iv:ySoEAspKd79+M88H9Fhcg4iVRqpebX6j+K/+YLZHMS0=,tag:BA/1DscWnUGbNC7lgU/qTg==,type:str]+LIVEKIT_SERVER_URL=ENC[AES256_GCM,data:w4SAApcyzwRtST6WGnzJTfFdX0Dp8pthvtH6Mymz2t/nhLZbLGrIIA==,iv:HHvLpOjtoC1Iw5DgXYidN+PAgzvdVY1PACgUPKrJUzE=,tag:p2YAF/sxxfFbpCJ4xtSGSw==,type:str]+LIVEKIT_API_KEY=ENC[AES256_GCM,data:qhLZaV4ww9UxE03tj91qx2Y=,iv:QJVCtekxlAe0fZLHIflnodnOmv45wpLzSBcNj5CtCOo=,tag:LlZ6f5STiC8ArQPLRMEsWw==,type:str]+LIVEKIT_API_SECRET=ENC[AES256_GCM,data:GLdp8wpK4kpbGPmR5aaWzZ4ns8jzTkRuFfroG8PUeG8ChFJONtoCFx1VjlxUfQ==,iv:YcaFnOZG8lA9kMxM8C4WD+DXqHRhprburLqIzDWI7Zc=,tag:Ro55kVfVytCWdfCT/GERCA==,type:str]sops_age__list_0__map_enc=-----BEGIN AGE ENCRYPTED FILE-----\nYWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IHBpdi1wMjU2IEUzMVUyZyBBM1lmcDc3\nUENpRVorSGVGa3R2NFlrdkx1Mm43aEcyR1ZtbEswL2RnWHlqMwpVMnY4ck5makNC\nZzVZc3JrZ3NKV2x3RTY0TFovRXJtVzEyeFZOZWRheHBNCi0tLSBobjhCbHpJa25s\nZDhyQjhCaEYrOWNiWHZkRWpnRlkwTnNEbjMwYzdxcTUwCqxxxmXy3mFUAbAy29y8\n2DFYDATdVvmplHpDTvgrNyY+lAL/3Jp9vtIs5DGXW/r73Nv3AhISmuCid18qhpAY\nUqE=\n-----END AGE ENCRYPTED FILE-----\nsops_age__list_0__map_recipient=age1yubikey1qw64ag5lzvn9ekrflu5ruj4a6ucycscl6ctk39fjzf76jptsay39z442pxvsops_kms__list_0__map_arn=arn:aws:kms:us-east-1:569036502058:key/mrk-cab29bf948044eb79005a81f48d40e93@@ -131,7 +134,7 @@ sops_kms__list_1__map_arn=arn:aws:kms:us-west-1:569036502058:key/mrk-cab29bf9480sops_kms__list_1__map_aws_profile=sops_kms__list_1__map_created_at=2026-03-03T19:32:07Zsops_kms__list_1__map_enc=AQICAHjuYcSMsjB0lKJtZ3DIAvxF8N3RNRn5KZaAN74Et6122wFUqf7u/HEfCUGv7j69Mb6YAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMpcJQR1XeIAFFE7ebAgEQgDvYRYIWelwN8TuwA+6fZVaB34yKo9EQ5xPLr/3BU+ro1Mn2eBPCg3q8ie2LuE/3voim1X35P/cdtDqTZg==-sops_lastmodified=2026-03-30T20:22:37Z-sops_mac=ENC[AES256_GCM,data:swAKJFY60tRpNkoad2dSqVFVLdV5eu//JT4Yrp1Nv36t/CkxTBRxYxUa5aEgKv2GeiCVjdd+zTX/LANMJRMj5s6stsFH7qNd+5UldvM4qjPeBppLnjyMT5xZaWmovOXsEDCr4TkddDXCFR0L+lZZSmBtpweOAaVZGGX0EBS64x4=,iv:f/znoImRo/tNkpmCTXimuVq6Z9OhnH+zJAy5XviNdEo=,tag:3CeUiXE8Q1lBAZlHuqXUTw==,type:str]+sops_lastmodified=2026-04-01T17:58:53Z+sops_mac=ENC[AES256_GCM,data:bmKaEjJ+Aq8XQ7mdNqk0W6AbLOvALLHgOd/RU06GEooAoH3EHJzGW1qPsVywXkQ6+PaaZyuKMIM40HkDPf9ZcW8kbp/s7SkYH1+RDd97sevxu/JpG+fDDmWOHf/khGq7rjEUHCkD/hOXiWUdNQsStcMApafxRA/Xk6EDES/O/fA=,iv:AG+HFzzQv5Ex1TsdjQMCJ1CzZSypSmHHdnOgPKNZK2U=,tag:4B8ogEduTaJvkWaghtogWA==,type:str]sops_unencrypted_suffix=_unencryptedsops_version=3.12.1diff --git a/.env-localdev.enc b/.env-localdev.encindex e4b698a456..45ec06a917 100644--- a/.env-localdev.enc+++ b/.env-localdev.enc@@ -127,6 +127,9 @@ GITHUB_SYNC_APP_CLIENT_ID=ENC[AES256_GCM,data:b2qkbli7aE9odK8Q8THou2iayneW/w==,iSTRIPE_PRICE_ID_HAIKU=ENC[AES256_GCM,data:8lDkvr4V/G6bvIGYxv/s/cXLcPuaikYDREmbx6R/HPo=,iv:wj5dtSDj6+OYjbdrYKl2R0f1WPuJEFbdK8xZ+kGNjNI=,tag:yzvROLM01p0Jl1YtdHjyxQ==,type:str]STRIPE_PRICE_ID_SONNET=ENC[AES256_GCM,data:anbLDuVNiR+N/XAlfbJl3Nx+Iy6ohhnAlsZtMM5w/xA=,iv:YYnl3fNSFnHdV2dchqdw5/1E8W/ga5Pnyf9WqN6bUco=,tag:jYTxEyeBlKBIwv18mZWPBg==,type:str]STRIPE_PRICE_ID_OPUS=ENC[AES256_GCM,data:fgVL97kmyo7kTrG6UjvFr/2gbgAFSpV+hnpy3jkKhos=,iv:C7vXETcHpbUW2iUi+m2WR/xu7ANbGAI+8z74GKBY0FA=,tag:SQP2Go5fPmxZg6GeGMdl9A==,type:str]+LIVEKIT_SERVER_URL=ENC[AES256_GCM,data:aBbXYtf18XRTfQX500l5Mej8FPxqDmH+Lp9W6LdGzI7NgX1kzfZSoA==,iv:IIpmcZ6BXUVl4w51XqpTa7BLvNeEooR16UPxrKW0My8=,tag:JQvnwl+ccDbQxTC1ghJ+Jw==,type:str]+LIVEKIT_API_KEY=ENC[AES256_GCM,data:aKkhucWrN/FNaYmbloWdxm0=,iv:RmykULpzwZ9lftkF2wrcAzekMIk9+YWc9AZsZhKiYx0=,tag:f245xdM6FmWDioEV/Lv9Nw==,type:str]+LIVEKIT_API_SECRET=ENC[AES256_GCM,data:VrLzVGpQG7ML+TZcopCsEkyj/mXiTm+9BsqWE3nGdIozRf6PIyUwHlyErGoFCQ==,iv:na9JIyCdt94SFnPLh9l+33c8lZRW+uR8WYw+Ju8zdYw=,tag:cLL0wJz4jzpAIRysbt4tSQ==,type:str]sops_age__list_0__map_enc=-----BEGIN AGE ENCRYPTED FILE-----\nYWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IHBpdi1wMjU2IEUzMVUyZyBBNDlKWUVt\nbUpscDEzSE9IZTNvdkd6VUFpWWhQM1ZWcndzL0srVXE4SW5GUQpHR2xNR3lIUnBV\nY3BqbmRadVVPMUdkeUluR0RycDJsWWt1V2Z0T1hqbG1JCi0tLSA5cVZQSGtNNmgr\nVXdyWGZsLzg2N0lyakxuVDZuNEFDUlUrNXJIMHE3UmRRClCd0JD9Q51ZLVKv73Px\nebG4SM/4o73tU3IHJu4tyQUrFM+we+JEDvsYKHBuUgTGC+2yQRPmHV+HObTqqRnu\nzGg=\n-----END AGE ENCRYPTED FILE-----\nsops_age__list_0__map_recipient=age1yubikey1qw64ag5lzvn9ekrflu5ruj4a6ucycscl6ctk39fjzf76jptsay39z442pxvsops_kms__list_0__map_arn=arn:aws:kms:us-east-1:569036502058:key/mrk-cab29bf948044eb79005a81f48d40e93@@ -137,7 +140,7 @@ sops_kms__list_1__map_arn=arn:aws:kms:us-west-1:569036502058:key/mrk-cab29bf9480sops_kms__list_1__map_aws_profile=sops_kms__list_1__map_created_at=2026-03-03T19:32:17Zsops_kms__list_1__map_enc=AQICAHjuYcSMsjB0lKJtZ3DIAvxF8N3RNRn5KZaAN74Et6122wHtcTS4UVhM79Eansn1/OmrAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMRrFwSp99ZM2mPtJzAgEQgDvsIaiNifNz0/18C9OH77AG/LQLpmDiXiJYV46yLDv9vdyPL3PaLMvkAqgL3Xb2F4RcZOIUxkTS3u92xQ==-sops_lastmodified=2026-03-30T20:23:00Z-sops_mac=ENC[AES256_GCM,data:NQibyHoAMTk42FBQ0brnqcL4KpYZxobK01ooju7gYLN7LY3NT0CjQCSidAqP6QN//QBrjf7Q4SjzOLhwU+EklfwDwLD+dEiRFdPmLYWEesYpvt9/HY+bfdKf4M2Az6TWkzRPnXs+ELbz0Xr6fjC/FBhUzi9LKk4LClBELLmAplc=,iv:pfoH6wTtff6NPcIr7b8Y+w92sFNGEnMTP9HFas+wZIE=,tag:aPrOmqcztN0MxzxhuaAdvA==,type:str]+sops_lastmodified=2026-04-01T17:58:57Z+sops_mac=ENC[AES256_GCM,data:1dqNviaaNLsw6pTZx/yCBqBKVobf5/tjkTang8lp3HyycvKxwh3cHyGVIIap/+N9QLhDfF5TzfKjlZLqGq/Qt87pD6lWbSnhxLXGTiDrIRpD8gPxmhmMkV6PdQK/PxdPnVaQgxKK7Q+DuX6UE+k4SXeuVxpg/18c1Pw+oAKyFJ8=,iv:+iz30VKRImCveqKlV7QHqJ32vsRW9UPtPr1B69+d4ZE=,tag:AqSEj7atSbCfs1cbiD47vA==,type:str]sops_unencrypted_suffix=_unencryptedsops_version=3.12.1diff --git a/infra/stacks/cloud-storage-service/Pulumi.dev.yaml b/infra/stacks/cloud-storage-service/Pulumi.dev.yamlindex 17d5a90d14..f7223b5600 100644--- a/infra/stacks/cloud-storage-service/Pulumi.dev.yaml+++ b/infra/stacks/cloud-storage-service/Pulumi.dev.yaml@@ -18,3 +18,6 @@ config:cloud-storage-service:github_sync_app_url: https://github.com/apps/dev-macro-appcloud-storage-service:github_sync_app_pem: github-sync-app-pem-devcloud-storage-service:github_sync_app_client_id: Iv23lipL80fCypV6UZa1+ cloud-storage-service:livekit_server_url: livekit-server-url-dev+ cloud-storage-service:livekit_api_key: livekit-api-key-dev+ cloud-storage-service:livekit_api_secret: livekit-api-secret-devdiff --git a/infra/stacks/cloud-storage-service/Pulumi.prod.yaml b/infra/stacks/cloud-storage-service/Pulumi.prod.yamlindex 54cb122d6e..6103de82f9 100644--- a/infra/stacks/cloud-storage-service/Pulumi.prod.yaml+++ b/infra/stacks/cloud-storage-service/Pulumi.prod.yaml@@ -18,3 +18,6 @@ config:cloud-storage-service:github_sync_app_url: https://github.com/apps/macro-applicationcloud-storage-service:github_sync_app_pem: github-sync-app-pem-prodcloud-storage-service:github_sync_app_client_id: Iv23ct0BBwvcPqFORaCI+ cloud-storage-service:livekit_server_url: livekit-server-url-prod+ cloud-storage-service:livekit_api_key: livekit-api-key-prod+ cloud-storage-service:livekit_api_secret: livekit-api-secret-proddiff --git a/infra/stacks/cloud-storage-service/index.ts b/infra/stacks/cloud-storage-service/index.tsindex 6cf51cec66..f055e2bb7f 100644--- a/infra/stacks/cloud-storage-service/index.ts+++ b/infra/stacks/cloud-storage-service/index.ts@@ -265,6 +265,18 @@ const githubSyncAppPemArn: pulumi.Output<string> = aws.secretsmanagerconst GITHUB_SYNC_APP_CLIENT_ID = config.require('github_sync_app_client_id');+const LIVEKIT_SERVER_URL = aws.secretsmanager+ .getSecretVersionOutput({ secretId: config.require('livekit_server_url') })+ .apply((secret) => secret.secretString);++const LIVEKIT_API_KEY = aws.secretsmanager+ .getSecretVersionOutput({ secretId: config.require('livekit_api_key') })+ .apply((secret) => secret.secretString);++const LIVEKIT_API_SECRET = aws.secretsmanager+ .getSecretVersionOutput({ secretId: config.require('livekit_api_secret') })+ .apply((secret) => secret.secretString);+const cloudStorageService = new CloudStorageService(`cloud-storage-service-${stack}`,{@@ -298,6 +310,19 @@ const cloudStorageService = new CloudStorageService(githubSyncAppPemArn,],containerEnvVars: [+ {+ name: 'LIVEKIT_SERVER_URL',+ value: pulumi.interpolate`${LIVEKIT_SERVER_URL}`,+ },+ {+ name: 'LIVEKIT_API_KEY',+ value: pulumi.interpolate`${LIVEKIT_API_KEY}`,+ },+ {+ name: 'LIVEKIT_API_SECRET',+ value: pulumi.interpolate`${LIVEKIT_API_SECRET}`,+ },+{name: 'OPENSEARCH_URL',value: OPENSEARCH_URL,diff --git a/js/app/bun.lock b/js/app/bun.lockindex d6dfc7b990..c5fdbf9391 100644--- a/js/app/bun.lock+++ b/js/app/bun.lock@@ -77,6 +77,7 @@"lexical": "^0.32.1","libheif-js": "^1.19.8","linkify-it": "^5.0.0",+ "livekit-client": "^2.18.0","loro-crdt": "^1.5.9","nanoid": "^3.3.7","neverthrow": "^8.2.0",@@ -454,6 +455,8 @@"@biomejs/cli-win32-x64": ["@biomejs/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-qEpGjSkPC3qX4ycbMUthXvi9CkRq7kZpkqMY1OyhmYlYLnANnooDQ7hDerM8+0NJ+DZKVnsIc07h30XOpt7LtQ=="],+ "@bufbuild/protobuf": ["@bufbuild/[email protected]", "", {}, "sha512-wJ8ReQbHxsAfXhrf9ixl0aYbZorRuOWpBNzm8pL8ftmSxQx/wnJD5Eg861NwJU/czy2VXFIebCeZnZrI9rktIQ=="],+"@codemirror/autocomplete": ["@codemirror/[email protected]", "", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.17.0", "@lezer/common": "^1.0.0" } }, "sha512-PHHBXFomUs5DF+9tCOM/UoW6XQ4R44lLNNhRaW9PKPTU0D7lIjRg3ElxaJnTwsl/oHiR93WSXDBrekhoUGCPtg=="],"@codemirror/commands": ["@codemirror/[email protected]", "", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.4.0", "@codemirror/view": "^6.27.0", "@lezer/common": "^1.1.0" } }, "sha512-KlGVYufHMQzxbdQONiLyGQDUW0itrLZwq3CcY7xpv9ZLRHqzkBSoteocBHtMCoY7/Ci4xhzSrToIeLg7FxHuaw=="],@@ -740,6 +743,10 @@"@lezer/rust": ["@lezer/[email protected]", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-Lz5sIPBdF2FUXcWeCu1//ojFAZqzTQNRga0aYv6dYXqJqPfMdCAI0NzajWUd4Xijj1IKJLtjoXRPMvTKWBcqKg=="],+ "@livekit/mutex": ["@livekit/[email protected]", "", {}, "sha512-EsshAucklmpuUAfkABPxJNhzj9v2sG7JuzFDL4ML1oJQSV14sqrpTYnsaOudMAw9yOaW53NU3QQTlUQoRs4czw=="],++ "@livekit/protocol": ["@livekit/[email protected]", "", { "dependencies": { "@bufbuild/protobuf": "^1.10.0" } }, "sha512-/vfhDUGcUKO8Q43r6i+5FrDhl5oZjm/X3U4x2Iciqvgn5C8qbj+57YPcWSJ1kyIZm5Cm6AV2nAPjMm3ETD/iyg=="],+"@lukemorales/query-key-factory": ["@lukemorales/[email protected]", "", { "peerDependencies": { "@tanstack/query-core": ">= 4.0.0", "@tanstack/react-query": ">= 4.0.0" } }, "sha512-A3frRDdkmaNNQi6mxIshsDk4chRXWoXa05US8fBo4kci/H+lVmujS6QrwQLLGIkNIRFGjMqp2uKjC4XsLdydRw=="],"@macro-inc/lexical-core": ["@macro-inc/lexical-core@workspace:packages/lexical-core"],@@ -1254,6 +1261,8 @@"@types/deep-eql": ["@types/[email protected]", "", {}, "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw=="],+ "@types/dom-mediacapture-record": ["@types/[email protected]", "", {}, "sha512-mUMZLK3NvwRLcAAT9qmcK+9p7tpU2FHdDsntR3YI4+GY88XrgG4XiE7u1Q2LAN2/FZOz/tdMDC3GQCR4T8nFuw=="],+"@types/es-aggregate-error": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-qJ7LIFp06h1QE1aVxbVd+zJP2wdaugYXYfd6JxsyRMrYHaxb6itXPogW2tz+ylUJ1n1b+JF1PHyYCfYHm0dvUg=="],"@types/estree": ["@types/[email protected]", "", {}, "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw=="],@@ -1730,6 +1739,8 @@"eventid": ["[email protected]", "", { "dependencies": { "uuid": "^8.0.0" } }, "sha512-sPNTqiMokAvV048P2c9+foqVJzk49o6d4e0D/sq5jog3pw+4kBgyR0gaM1FM7Mx6Kzd9dztesh9oYz1LWWOpzw=="],+ "events": ["[email protected]", "", {}, "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q=="],+"execa": ["[email protected]", "", { "dependencies": { "cross-spawn": "^7.0.3", "get-stream": "^6.0.0", "human-signals": "^2.1.0", "is-stream": "^2.0.0", "merge-stream": "^2.0.0", "npm-run-path": "^4.0.1", "onetime": "^5.1.2", "signal-exit": "^3.0.3", "strip-final-newline": "^2.0.0" } }, "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg=="],"exit-hook": ["[email protected]", "", {}, "sha512-MsG3prOVw1WtLXAZbM3KiYtooKR1LvxHh3VHsVtIy0uiUu8usxgB/94DP2HxtD/661lLdB6yzQ09lGJSQr6nkg=="],@@ -2004,6 +2015,8 @@"jiti": ["[email protected]", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ=="],+ "jose": ["[email protected]", "", {}, "sha512-d7kPDd34KO/YnzaDOlikGpOurfF0ByC2sEV4cANCtdqLlTfBlw2p14O/5d/zv40gJPbIQxfES3nSx1/oYNyuZQ=="],+"js-tokens": ["[email protected]", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="],"js-yaml": ["[email protected]", "", { "dependencies": { "argparse": "^1.0.7", "esprima": "^4.0.0" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g=="],@@ -2100,6 +2113,8 @@"linkify-it": ["[email protected]", "", { "dependencies": { "uc.micro": "^2.0.0" } }, "sha512-5aHCbzQRADcdP+ATqnDuhhJ/MRIqDkZX5pyjFHRRysS8vZ5AbqGEoFIb6pYHPZ+L/OC2Lc+xT8uHVVR5CAK/wQ=="],+ "livekit-client": ["[email protected]", "", { "dependencies": { "@livekit/mutex": "1.1.1", "@livekit/protocol": "1.44.0", "events": "^3.3.0", "jose": "^6.1.0", "loglevel": "^1.9.2", "sdp-transform": "^2.15.0", "tslib": "2.8.1", "typed-emitter": "^2.1.0", "webrtc-adapter": "^9.0.1" }, "peerDependencies": { "@types/dom-mediacapture-record": "^1" } }, "sha512-wjH4y0rw5fnkPmmaxutPhD4XcAq6goQszS8lw9PEpGXVwiRE6sI/ZH+mOT/s8AHJnEC3tjmfiMZ4MQt8BlaWew=="],+"locate-path": ["[email protected]", "", { "dependencies": { "p-locate": "^5.0.0" } }, "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw=="],"lodash": ["[email protected]", "", {}, "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg=="],@@ -2460,6 +2475,10 @@"scheduler": ["[email protected]", "", { "dependencies": { "loose-envify": "^1.1.0" } }, "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ=="],+ "sdp": ["[email protected]", "", {}, "sha512-lwsAIzOPlH8/7IIjjz3K0zYBk7aBVVcvjMwt3M4fLxpjMYyy7i3I97SLHebgn4YBjirkzfp3RvRDWSKsh/+WFw=="],++ "sdp-transform": ["[email protected]", "", { "bin": { "sdp-verify": "checker.js" } }, "sha512-KrOH82c/W+GYQ0LHqtr3caRpM3ITglq3ljGUIb8LTki7ByacJZ9z+piSGiwZDsRyhQbYBOBJgr2k6X4BZXi3Kw=="],+"semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A=="],"seroval": ["[email protected]", "", {}, "sha512-RbcPH1n5cfwKrru7v7+zrZvjLurgHhGyso3HTyGtRivGWgYjbOmGuivCQaORNELjNONoK35nj28EoWul9sb1zQ=="],@@ -2704,6 +2723,8 @@"typed-array-length": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.7", "for-each": "^0.3.3", "gopd": "^1.0.1", "has-proto": "^1.0.3", "is-typed-array": "^1.1.13", "possible-typed-array-names": "^1.0.0" } }, "sha512-/OxDN6OtAk5KBpGb28T+HZc2M+ADtvRxXrKKbUwtsLgdoxgX13hyy7ek6bFRl5+aBs2yZzB0c4CnQfAtVypW/g=="],+ "typed-emitter": ["[email protected]", "", { "optionalDependencies": { "rxjs": "*" } }, "sha512-g/KzbYKbH5C2vPkaXGu8DJlHrGKHLsM25Zg9WuC9pMGfuvT+X25tZQWo5fK1BjBm8+UrVE9LDCvaY0CQk+fXDA=="],+"typedarray-to-buffer": ["[email protected]", "", {}, "sha512-6dOYeZfS3O9RtRD1caom0sMxgK59b27+IwoNy8RDPsmslSGOyU+mpTamlaIW7aNKi90ZQZ9DFaZL3YRoiSCULQ=="],"typedoc": ["[email protected]", "", { "dependencies": { "glob": "^8.0.3", "lunr": "^2.3.9", "marked": "^4.0.16", "minimatch": "^5.1.0", "shiki": "^0.10.1" }, "peerDependencies": { "typescript": "4.0.x || 4.1.x || 4.2.x || 4.3.x || 4.4.x || 4.5.x || 4.6.x || 4.7.x" }, "bin": { "typedoc": "bin/typedoc" } }, "sha512-NK9RlLhRUGMvc6Rw5USEYgT4DVAUFk7IF7Q6MYfpJ88KnTZP7EneEa4RcP+tX1auAcz7QT1Iy0bUSZBYYHdoyA=="],@@ -2788,6 +2809,8 @@"webidl-conversions": ["[email protected]", "", {}, "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g=="],+ "webrtc-adapter": ["[email protected]", "", { "dependencies": { "sdp": "^3.2.0" } }, "sha512-5ZZY1+lGq8LEKuDlg9M2RPJHlH3R7OVwyHqMcUsLKCgd9Wvf+QrFTCItkXXYPmrJn8H6gRLXbSgxLLdexiqHxw=="],+"websocket": ["websocket@workspace:packages/websocket"],"whatwg-encoding": ["[email protected]", "", { "dependencies": { "iconv-lite": "0.6.3" } }, "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ=="],@@ -3596,6 +3619,8 @@"knip/zod": ["[email protected]", "", {}, "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg=="],+ "livekit-client/tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],+"log-symbols/chalk": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="],"loro-mirror-monorepo/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~5.26.4" } }, "sha512-ZsbGerYg72WMXUIE9fYxtvfzLEuq6q8mKERdWFnqTmOvudMxnz+CBNRoOwJ2kNpFOncrKjT1hZwxjlFgQ9qvQA=="],diff --git a/js/app/package.json b/js/app/package.jsonindex 17abdb4126..eac02493a9 100644--- a/js/app/package.json+++ b/js/app/package.json@@ -94,6 +94,7 @@"lexical": "^0.32.1","libheif-js": "^1.19.8","linkify-it": "^5.0.0",+ "livekit-client": "^2.18.0","loro-crdt": "^1.5.9","nanoid": "^3.3.7","neverthrow": "^8.2.0",diff --git a/js/app/packages/service-clients/service-call/client.ts b/js/app/packages/service-clients/service-call/client.tsnew file mode 100644index 0000000000..7690501745--- /dev/null+++ b/js/app/packages/service-clients/service-call/client.ts@@ -0,0 +1,56 @@+import { SERVER_HOSTS } from '@core/constant/servers';+import { fetchWithToken } from '@core/util/fetchWithToken';+import { mapOk } from '@core/util/maybeResult';++const host: string = SERVER_HOSTS['document-storage-service'];++export type CallTokenResponse = {+ callId: string;+ channelId: string;+ token: string;+ roomName: string;+ serverUrl: string;+};++export type LeaveCallResponse = {+ callEnded: boolean;+};++export type TranscriptSegmentPayload = {+ segmentId: string;+ speakerId: string;+ content: string;+ startedAt: string;+ endedAt: string | null;+ isFinal: boolean;+};++export const callServiceClient = {+ async getOrCreateCall(channelId: string) {+ return mapOk(+ await fetchWithToken<CallTokenResponse>(`${host}/call/${channelId}`, {+ method: 'GET',+ }),+ (result) => result+ );+ },++ async leaveCall(channelId: string) {+ return mapOk(+ await fetchWithToken<LeaveCallResponse>(`${host}/call/${channelId}`, {+ method: 'DELETE',+ }),+ (result) => result+ );+ },++ async sendTranscriptSegment(+ channelId: string,+ segment: TranscriptSegmentPayload+ ) {+ return fetchWithToken(`${host}/call/${channelId}/transcript`, {+ method: 'POST',+ body: JSON.stringify(segment),+ });+ },+};diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/callTokenResponse.ts b/js/app/packages/service-clients/service-storage/generated/schemas/callTokenResponse.tsnew file mode 100644index 0000000000..3c9971c312--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/callTokenResponse.ts@@ -0,0 +1,22 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Response returned when creating or joining a call.+ */+export interface CallTokenResponse {+ /** The call identifier. */+ callId: string;+ /** The channel this call is associated with. */+ channelId: string;+ /** The RTC room name. */+ roomName: string;+ /** The RTC server URL for the frontend SDK to connect to. */+ serverUrl: string;+ /** The RTC token for connecting to the room. */+ token: string;+}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 e4e5b69923..e12327f24a 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@@ -76,6 +76,7 @@ export * from './basicDocumentSubTypeProperty';export * from './basicDocumentType';export * from './basicDocumentUpdatedAt';export * from './bomPart';+export * from './callTokenResponse';export * from './channel';export * from './channelFilters';export * from './channelFiltersImportance';@@ -362,6 +363,7 @@ export * from './itemWithUserAccessLevel';export * from './latestMessage';export * from './latestMessageLatestMessage';export * from './latestMessageLatestNonThreadMessage';+export * from './leaveCallResponse';export * from './locationResponseData';export * from './locationResponseDataOneOf';export * from './locationResponseDataOneOfTwo';@@ -591,6 +593,8 @@ export * from './threadCreatedAt';export * from './threadDeletedAt';export * from './threadResponse';export * from './threadUpdatedAt';+export * from './transcriptSegmentRequest';+export * from './transcriptSegmentRequestEndedAt';export * from './typedSuccessResponse';export * from './typedSuccessResponseDataOneOf';export * from './unthreadedPdfUuidRequest';diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/leaveCallResponse.ts b/js/app/packages/service-clients/service-storage/generated/schemas/leaveCallResponse.tsnew file mode 100644index 0000000000..26d29c9ba5--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/leaveCallResponse.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Response for the leave/end call operation.+ */+export interface LeaveCallResponse {+ /** Whether the entire call was ended (room deleted). */+ callEnded: boolean;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/transcriptSegmentRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/transcriptSegmentRequest.tsnew file mode 100644index 0000000000..54d2461983--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/transcriptSegmentRequest.ts@@ -0,0 +1,25 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { TranscriptSegmentRequestEndedAt } from './transcriptSegmentRequestEndedAt';++/**+ * A transcript segment from LiveKit Inference STT.+ */+export interface TranscriptSegmentRequest {+ /** The transcribed text content. */+ content: string;+ /** When the speaker stopped talking for this segment. */+ endedAt?: TranscriptSegmentRequestEndedAt;+ /** Whether this is a final transcription (not interim). */+ isFinal: boolean;+ /** LiveKit segment ID (used for deduplication across multiple submitters). */+ segmentId: string;+ /** The speaker's user ID (from `lk.transcribed_track_id`). */+ speakerId: string;+ /** When the speaker started talking for this segment. */+ startedAt: string;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/transcriptSegmentRequestEndedAt.ts b/js/app/packages/service-clients/service-storage/generated/schemas/transcriptSegmentRequestEndedAt.tsnew file mode 100644index 0000000000..e108b5c4dc--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/transcriptSegmentRequestEndedAt.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * When the speaker stopped talking for this segment.+ */+export type TranscriptSegmentRequestEndedAt = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex 11d6d46903..fbc04df47c 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -810,6 +810,80 @@ export const createCommentResponse = zod}));+/**+ * Gets or creates a call for the channel. If a call already exists, joins it;+otherwise creates a new one. Always returns a join token.+ * @summary Handler for `GET /call/{channel_id}`.+ */+export const getOrCreateCallParams = zod.object({+ channel_id: zod.string().uuid().describe('Channel ID'),+});++export const getOrCreateCallResponse = zod+ .object({+ callId: zod.string().uuid().describe('The call identifier.'),+ channelId: zod+ .string()+ .uuid()+ .describe('The channel this call is associated with.'),+ roomName: zod.string().describe('The RTC room name.'),+ serverUrl: zod+ .string()+ .describe('The RTC server URL for the frontend SDK to connect to.'),+ token: zod.string().describe('The RTC token for connecting to the room.'),+ })+ .describe('Response returned when creating or joining a call.');++/**+ * @summary Handler for `DELETE /call/{channel_id}`.+ */+export const leaveOrEndCallParams = zod.object({+ channel_id: zod.string().uuid().describe('Channel ID'),+});++export const leaveOrEndCallResponse = zod+ .object({+ callEnded: zod+ .boolean()+ .describe('Whether the entire call was ended (room deleted).'),+ })+ .describe('Response for the leave/end call operation.');++/**+ * Receives transcript segments from the frontend.+Requires channel membership. Duplicate segments (same `segment_id`) are ignored.+ * @summary Handler for `POST /call/{channel_id}/transcript`.+ */+export const ingestTranscriptParams = zod.object({+ channel_id: zod.string().uuid().describe('Channel ID'),+});++export const ingestTranscriptBody = zod+ .object({+ content: zod.string().describe('The transcribed text content.'),+ endedAt: zod+ .string()+ .datetime({})+ .nullish()+ .describe('When the speaker stopped talking for this segment.'),+ isFinal: zod+ .boolean()+ .describe('Whether this is a final transcription (not interim).'),+ segmentId: zod+ .string()+ .describe(+ 'LiveKit segment ID (used for deduplication across multiple submitters).'+ ),+ speakerId: zod+ .string()+ .describe("The speaker's user ID (from `lk.transcribed_track_id`)."),+ startedAt: zod+ .string()+ .datetime({})+ .describe('When the speaker started talking for this segment.'),+ })+ .describe('A transcript segment from LiveKit Inference STT.');+/*** @summary Handler for `GET /channels/{channel_id}/attachments`.*/diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex 36cfa6e90b..572cfc6af0 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -594,6 +594,208 @@}}},+ "/call/webhook": {+ "post": {+ "tags": ["call::inbound::axum_router"],+ "summary": "Handler for `POST /call/webhook`.",+ "description": "Receives webhook events from the RTC provider (e.g. LiveKit).\nThe `Authorization` header contains the webhook auth token\nand the body contains the raw event payload.",+ "operationId": "call_webhook",+ "responses": {+ "200": {+ "description": "Event processed"+ },+ "401": {+ "description": "Invalid webhook signature"+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/call/{channel_id}": {+ "get": {+ "tags": ["call::inbound::axum_router"],+ "summary": "Handler for `GET /call/{channel_id}`.",+ "description": "Gets or creates a call for the channel. If a call already exists, joins it;\notherwise creates a new one. Always returns a join token.",+ "operationId": "get_or_create_call",+ "parameters": [+ {+ "name": "channel_id",+ "in": "path",+ "description": "Channel ID",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CallTokenResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ },+ "delete": {+ "tags": ["call::inbound::axum_router"],+ "summary": "Handler for `DELETE /call/{channel_id}`.",+ "operationId": "leave_or_end_call",+ "parameters": [+ {+ "name": "channel_id",+ "in": "path",+ "description": "Channel ID",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/LeaveCallResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "No active call",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/call/{channel_id}/transcript": {+ "post": {+ "tags": ["call::inbound::axum_router"],+ "summary": "Handler for `POST /call/{channel_id}/transcript`.",+ "description": "Receives transcript segments from the frontend.\nRequires channel membership. Duplicate segments (same `segment_id`) are ignored.",+ "operationId": "ingest_transcript",+ "parameters": [+ {+ "name": "channel_id",+ "in": "path",+ "description": "Channel ID",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/TranscriptSegmentRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "Segment ingested"+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "No active call",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/channels/{channel_id}/attachments": {"get": {"tags": ["channels::inbound::axum_router"],@@ -5499,6 +5701,35 @@}}},+ "CallTokenResponse": {+ "type": "object",+ "description": "Response returned when creating or joining a call.",+ "required": ["callId", "channelId", "token", "roomName", "serverUrl"],+ "properties": {+ "callId": {+ "type": "string",+ "format": "uuid",+ "description": "The call identifier."+ },+ "channelId": {+ "type": "string",+ "format": "uuid",+ "description": "The channel this call is associated with."+ },+ "roomName": {+ "type": "string",+ "description": "The RTC room name."+ },+ "serverUrl": {+ "type": "string",+ "description": "The RTC server URL for the frontend SDK to connect to."+ },+ "token": {+ "type": "string",+ "description": "The RTC token for connecting to the room."+ }+ }+ },"Channel": {"type": "object","required": [@@ -8277,6 +8508,17 @@}}},+ "LeaveCallResponse": {+ "type": "object",+ "description": "Response for the leave/end call operation.",+ "required": ["callEnded"],+ "properties": {+ "callEnded": {+ "type": "boolean",+ "description": "Whether the entire call was ended (room deleted)."+ }+ }+ },"LocationResponseData": {"oneOf": [{@@ -10475,6 +10717,45 @@}}},+ "TranscriptSegmentRequest": {+ "type": "object",+ "description": "A transcript segment from LiveKit Inference STT.",+ "required": [+ "segmentId",+ "speakerId",+ "content",+ "startedAt",+ "isFinal"+ ],+ "properties": {+ "content": {+ "type": "string",+ "description": "The transcribed text content."+ },+ "endedAt": {+ "type": ["string", "null"],+ "format": "date-time",+ "description": "When the speaker stopped talking for this segment."+ },+ "isFinal": {+ "type": "boolean",+ "description": "Whether this is a final transcription (not interim)."+ },+ "segmentId": {+ "type": "string",+ "description": "LiveKit segment ID (used for deduplication across multiple submitters)."+ },+ "speakerId": {+ "type": "string",+ "description": "The speaker's user ID (from `lk.transcribed_track_id`)."+ },+ "startedAt": {+ "type": "string",+ "format": "date-time",+ "description": "When the speaker started talking for this segment."+ }+ }+ },"TypedSuccessResponse": {"type": "object","required": ["error", "data"],diff --git a/js/app/tsconfig.json b/js/app/tsconfig.jsonindex 23843277d2..4bf0b7e52a 100644--- a/js/app/tsconfig.json+++ b/js/app/tsconfig.json@@ -90,6 +90,9 @@"@service-static-files/*": ["./packages/service-clients/service-static-files/*"],+ "@service-call/*": [+ "./packages/service-clients/service-call/*"+ ],"@service-cognition/*": ["./packages/service-clients/service-cognition/*"],diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex f66ba9bacc..51bac8b385 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -594,7 +594,7 @@ dependencies = ["futures","github","http-body-util",- "jsonwebtoken",+ "jsonwebtoken 10.3.0 (git+https://github.com/whutchinson98/jsonwebtoken)","last_online_tracker","macro_auth","macro_aws_config",@@ -1582,6 +1582,15 @@ dependencies = ["generic-array",]+[[package]]+name = "block2"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"+dependencies = [+ "objc2",+]+[[package]]name = "borsh"version = "1.5.7"@@ -1707,6 +1716,30 @@ version = "0.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ade8366b8bd5ba243f0a58f036cc0ca8a2f069cff1a2351ef1cac6b083e16fc0"+[[package]]+name = "call"+version = "0.1.0"+dependencies = [+ "anyhow",+ "axum",+ "chrono",+ "entity_access",+ "livekit-api",+ "livekit-protocol",+ "macro_db_migrator",+ "macro_user_id",+ "mockall",+ "model-error-response",+ "model_user",+ "serde",+ "sqlx",+ "thiserror 2.0.17",+ "tokio",+ "tracing",+ "utoipa",+ "uuid",+]+[[package]]name = "cc"version = "1.2.51"@@ -1890,7 +1923,7 @@ version = "4.5.32"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "09176aae279615badda0765c0c0b3f6ed53f4709118af73cf4655d85d1530cd7"dependencies = [- "heck",+ "heck 0.5.0","proc-macro2","quote","syn 2.0.98",@@ -2022,7 +2055,7 @@ dependencies = ["frecency","futures","http-body-util",- "jsonwebtoken",+ "jsonwebtoken 10.3.0 (git+https://github.com/whutchinson98/jsonwebtoken)","last_online_tracker","macro_auth","macro_aws_config",@@ -2292,7 +2325,7 @@ dependencies = ["macro_middleware","macro_uuid","model",- "nix",+ "nix 0.29.0","remote_env_var","rs-libreoffice-bindings","s3_client",@@ -2854,6 +2887,16 @@ dependencies = ["subtle",]+[[package]]+name = "dispatch2"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"+dependencies = [+ "bitflags 2.8.0",+ "objc2",+]+[[package]]name = "displaydoc"version = "0.2.5"@@ -2993,6 +3036,7 @@ dependencies = ["base64 0.22.1","bytes","bzip2",+ "call","channels","chrono","clap",@@ -3014,7 +3058,7 @@ dependencies = ["github","hex","http-body-util",- "jsonwebtoken",+ "jsonwebtoken 10.3.0 (git+https://github.com/whutchinson98/jsonwebtoken)","last_online_tracker","lazy_static","macro_auth",@@ -3772,7 +3816,7 @@ version = "0.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a1e6a265c649f3f5979b601d26f1d05ada116434c87741c9493cb56218f76cbc"dependencies = [- "heck",+ "heck 0.5.0","proc-macro2","quote","syn 2.0.98",@@ -3962,6 +4006,12 @@ version = "0.1.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "645cbb3a84e60b7531617d5ae4e57f7e27308f6445f5abf653209ea76dec8dff"+[[package]]+name = "fixedbitset"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"+[[package]]name = "flate2"version = "1.1.9"@@ -4341,7 +4391,7 @@ dependencies = ["hex","hmac","http-body-util",- "jsonwebtoken",+ "jsonwebtoken 10.3.0 (git+https://github.com/whutchinson98/jsonwebtoken)","macro_db_migrator","macro_env","macro_user_id",@@ -4381,7 +4431,7 @@ dependencies = ["base64 0.22.1","chrono","futures",- "jsonwebtoken",+ "jsonwebtoken 10.3.0 (git+https://github.com/whutchinson98/jsonwebtoken)","mail-builder","mockall","models_email",@@ -4511,6 +4561,12 @@ dependencies = ["hashbrown 0.15.2",]+[[package]]+name = "heck"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"+[[package]]name = "heck"version = "0.5.0"@@ -5340,6 +5396,15 @@ dependencies = ["either",]+[[package]]+name = "itertools"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57"+dependencies = [+ "either",+]+[[package]]name = "itertools"version = "0.12.1"@@ -5383,6 +5448,27 @@ dependencies = ["wasm-bindgen",]+[[package]]+name = "jsonwebtoken"+version = "10.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0529410abe238729a60b108898784df8984c87f6054c9c4fcacc47e4803c1ce1"+dependencies = [+ "base64 0.22.1",+ "ed25519-dalek",+ "getrandom 0.2.15",+ "hmac",+ "js-sys",+ "p256 0.13.2",+ "p384",+ "rand 0.8.5",+ "rsa",+ "serde",+ "serde_json",+ "sha2",+ "signature 2.2.0",+]+[[package]]name = "jsonwebtoken"version = "10.3.0"@@ -5588,6 +5674,58 @@ version = "0.7.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4ee93343901ab17bd981295f2cf0026d4ad018c7c31ba84549a4ddbb47a45104"+[[package]]+name = "livekit-api"+version = "0.4.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "020c7eaab7cec16b69a058659f9acff32067e0e2d4f81e80639f3ffa29464b09"+dependencies = [+ "base64 0.21.7",+ "http 1.3.1",+ "jsonwebtoken 10.3.0 (registry+https://github.com/rust-lang/crates.io-index)",+ "livekit-protocol",+ "log",+ "os_info",+ "parking_lot",+ "pbjson-types",+ "prost 0.12.6",+ "rand 0.9.0",+ "reqwest",+ "scopeguard",+ "serde",+ "serde_json",+ "sha2",+ "thiserror 1.0.69",+ "url",+]++[[package]]+name = "livekit-protocol"+version = "0.7.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c21d56b4dc2598b1296ca891abb225bf1c05ea007d6f43bc4fd48c31be64bf59"+dependencies = [+ "futures-util",+ "livekit-runtime",+ "parking_lot",+ "pbjson",+ "pbjson-types",+ "prost 0.12.6",+ "serde",+ "thiserror 1.0.69",+ "tokio",+]++[[package]]+name = "livekit-runtime"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "532e84c6cdc5fe774f2b5d9912597b5f3bea561927a48296d03e24549d21c3f6"+dependencies = [+ "tokio",+ "tokio-stream",+]+[[package]]name = "lock_api"version = "0.4.12"@@ -5695,7 +5833,7 @@ dependencies = ["anyhow","axum","cookie",- "jsonwebtoken",+ "jsonwebtoken 10.3.0 (git+https://github.com/whutchinson98/jsonwebtoken)","macro_env","macro_env_var","macro_user_id",@@ -6581,6 +6719,12 @@ dependencies = ["version_check",]+[[package]]+name = "multimap"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084"+[[package]]name = "mutants"version = "0.0.3"@@ -6670,6 +6814,18 @@ dependencies = ["libc",]+[[package]]+name = "nix"+version = "0.30.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "74523f3a35e05aba87a1d978330aef40f67b0304ac79c1c00b294c9830543db6"+dependencies = [+ "bitflags 2.8.0",+ "cfg-if",+ "cfg_aliases",+ "libc",+]+[[package]]name = "nom"version = "7.1.3"@@ -6941,6 +7097,165 @@ dependencies = ["libm",]+[[package]]+name = "objc2"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f"+dependencies = [+ "objc2-encode",+]++[[package]]+name = "objc2-cloud-kit"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c"+dependencies = [+ "bitflags 2.8.0",+ "objc2",+ "objc2-foundation",+]++[[package]]+name = "objc2-core-data"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa"+dependencies = [+ "objc2",+ "objc2-foundation",+]++[[package]]+name = "objc2-core-foundation"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"+dependencies = [+ "bitflags 2.8.0",+ "dispatch2",+ "objc2",+]++[[package]]+name = "objc2-core-graphics"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807"+dependencies = [+ "bitflags 2.8.0",+ "dispatch2",+ "objc2",+ "objc2-core-foundation",+ "objc2-io-surface",+]++[[package]]+name = "objc2-core-image"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006"+dependencies = [+ "objc2",+ "objc2-foundation",+]++[[package]]+name = "objc2-core-location"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ca347214e24bc973fc025fd0d36ebb179ff30536ed1f80252706db19ee452009"+dependencies = [+ "objc2",+ "objc2-foundation",+]++[[package]]+name = "objc2-core-text"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d"+dependencies = [+ "bitflags 2.8.0",+ "objc2",+ "objc2-core-foundation",+ "objc2-core-graphics",+]++[[package]]+name = "objc2-encode"+version = "4.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"++[[package]]+name = "objc2-foundation"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"+dependencies = [+ "bitflags 2.8.0",+ "block2",+ "libc",+ "objc2",+ "objc2-core-foundation",+]++[[package]]+name = "objc2-io-surface"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d"+dependencies = [+ "bitflags 2.8.0",+ "objc2",+ "objc2-core-foundation",+]++[[package]]+name = "objc2-quartz-core"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f"+dependencies = [+ "bitflags 2.8.0",+ "objc2",+ "objc2-core-foundation",+ "objc2-foundation",+]++[[package]]+name = "objc2-ui-kit"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22"+dependencies = [+ "bitflags 2.8.0",+ "block2",+ "objc2",+ "objc2-cloud-kit",+ "objc2-core-data",+ "objc2-core-foundation",+ "objc2-core-graphics",+ "objc2-core-image",+ "objc2-core-location",+ "objc2-core-text",+ "objc2-foundation",+ "objc2-quartz-core",+ "objc2-user-notifications",+]++[[package]]+name = "objc2-user-notifications"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9df9128cbbfef73cda168416ccf7f837b62737d748333bfe9ab71c245d76613e"+dependencies = [+ "objc2",+ "objc2-foundation",+]+[[package]]name = "once_cell"version = "1.21.3"@@ -7088,7 +7403,7 @@ dependencies = ["opentelemetry-http","opentelemetry-proto","opentelemetry_sdk",- "prost",+ "prost 0.14.3","reqwest","thiserror 2.0.17","tokio",@@ -7104,7 +7419,7 @@ checksum = "a7175df06de5eaee9909d4805a3d07e28bb752c34cab57fa9cff549da596b30f"dependencies = ["opentelemetry","opentelemetry_sdk",- "prost",+ "prost 0.14.3","tonic","tonic-prost",]@@ -7170,6 +7485,22 @@ dependencies = ["tracing",]+[[package]]+name = "os_info"+version = "3.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e4022a17595a00d6a369236fdae483f0de7f0a339960a53118b818238e132224"+dependencies = [+ "android_system_properties",+ "log",+ "nix 0.30.1",+ "objc2",+ "objc2-foundation",+ "objc2-ui-kit",+ "serde",+ "windows-sys 0.61.2",+]+[[package]]name = "outref"version = "0.5.2"@@ -7258,6 +7589,43 @@ version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b867cad97c0791bbd3aaa6472142568c6c9e8f71937e98379f584cfb0cf35bec"+[[package]]+name = "pbjson"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1030c719b0ec2a2d25a5df729d6cff1acf3cc230bf766f4f97833591f7577b90"+dependencies = [+ "base64 0.21.7",+ "serde",+]++[[package]]+name = "pbjson-build"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2580e33f2292d34be285c5bc3dba5259542b083cfad6037b6d70345f24dcb735"+dependencies = [+ "heck 0.4.1",+ "itertools 0.11.0",+ "prost 0.12.6",+ "prost-types",+]++[[package]]+name = "pbjson-types"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "18f596653ba4ac51bdecbb4ef6773bc7f56042dc13927910de1684ad3d32aa12"+dependencies = [+ "bytes",+ "chrono",+ "pbjson",+ "pbjson-build",+ "prost 0.12.6",+ "prost-build",+ "serde",+]+[[package]]name = "pbkdf2"version = "0.12.2"@@ -7328,6 +7696,16 @@ dependencies = ["tracing",]+[[package]]+name = "petgraph"+version = "0.6.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db"+dependencies = [+ "fixedbitset",+ "indexmap 2.12.1",+]+[[package]]name = "phf"version = "0.10.1"@@ -7728,6 +8106,16 @@ dependencies = ["uuid",]+[[package]]+name = "prost"+version = "0.12.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "deb1435c188b76130da55f17a466d252ff7b1418b2ad3e037d127b94e3411f29"+dependencies = [+ "bytes",+ "prost-derive 0.12.6",+]+[[package]]name = "prost"version = "0.14.3"@@ -7735,7 +8123,41 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d2ea70524a2f82d518bce41317d0fae74151505651af45faf1ffbd6fd33f0568"dependencies = ["bytes",- "prost-derive",+ "prost-derive 0.14.3",+]++[[package]]+name = "prost-build"+version = "0.12.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "22505a5c94da8e3b7c2996394d1c933236c4d743e81a410bcca4e6989fc066a4"+dependencies = [+ "bytes",+ "heck 0.5.0",+ "itertools 0.12.1",+ "log",+ "multimap",+ "once_cell",+ "petgraph",+ "prettyplease",+ "prost 0.12.6",+ "prost-types",+ "regex",+ "syn 2.0.98",+ "tempfile",+]++[[package]]+name = "prost-derive"+version = "0.12.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "81bddcdb20abf9501610992b6759a4c888aef7d1a7247ef75e2404275ac24af1"+dependencies = [+ "anyhow",+ "itertools 0.12.1",+ "proc-macro2",+ "quote",+ "syn 2.0.98",][[package]]@@ -7751,6 +8173,15 @@ dependencies = ["syn 2.0.98",]+[[package]]+name = "prost-types"+version = "0.12.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9091c90b0a32608e984ff2fa4091273cbdd755d54935c51d520887f4a1dbd5b0"+dependencies = [+ "prost 0.12.6",+]+[[package]]name = "pxfm"version = "0.1.25"@@ -9662,7 +10093,7 @@ checksum = "19a9c1841124ac5a61741f96e1d9e2ec77424bf323962dd894bdb93f37d5219b"dependencies = ["dotenvy","either",- "heck",+ "heck 0.5.0","hex","once_cell","proc-macro2",@@ -9966,7 +10397,7 @@ version = "0.27.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c77a8c5abcaf0f9ce05d62342b7d298c346515365c36b673df4ebe3ced01fde8"dependencies = [- "heck",+ "heck 0.5.0","proc-macro2","quote","rustversion",@@ -10431,7 +10862,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d6c55a2d6a14174563de34409c9f92ff981d006f56da9c6ecd40d9d4a31500b0"dependencies = ["bytes",- "prost",+ "prost 0.14.3","tonic",]@@ -11633,7 +12064,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc"dependencies = ["anyhow",- "heck",+ "heck 0.5.0","wit-parser",]@@ -11653,7 +12084,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21"dependencies = ["anyhow",- "heck",+ "heck 0.5.0","indexmap 2.12.1","prettyplease","syn 2.0.98",diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex 9b9582d08e..76d2aeba2b 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -10,6 +10,7 @@ members = ["anthropic","authentication_service","authentication_service_client",+ "call","channels","chat","comms_db_client",@@ -173,6 +174,8 @@ jsonwebtoken = { git = "https://github.com/whutchinson98/jsonwebtoken", features"rust_crypto",] }lambda_runtime = "0.13.0"+livekit-api = "0.4.16"+livekit-protocol = "0.7.2"lazy_static = "1.5.0"log = "0.4.26"mockall = "0.13"diff --git a/rust/cloud-storage/call/.sqlx/query-1e45a7245820860fa347be763bb94e3aa7d6e5d9a2660ed6668eaec3d0b39745.json b/rust/cloud-storage/call/.sqlx/query-1e45a7245820860fa347be763bb94e3aa7d6e5d9a2660ed6668eaec3d0b39745.jsonnew file mode 100644index 0000000000..8612481418--- /dev/null+++ b/rust/cloud-storage/call/.sqlx/query-1e45a7245820860fa347be763bb94e3aa7d6e5d9a2660ed6668eaec3d0b39745.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE calls SET egress_id = $2 WHERE id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "1e45a7245820860fa347be763bb94e3aa7d6e5d9a2660ed6668eaec3d0b39745"+}diff --git a/rust/cloud-storage/call/.sqlx/query-20a6a1d55831d2f428a4439ff09cd0f680dab8845b5789b83eee8966bbb85937.json b/rust/cloud-storage/call/.sqlx/query-20a6a1d55831d2f428a4439ff09cd0f680dab8845b5789b83eee8966bbb85937.jsonnew file mode 100644index 0000000000..53e84b1e8f--- /dev/null+++ b/rust/cloud-storage/call/.sqlx/query-20a6a1d55831d2f428a4439ff09cd0f680dab8845b5789b83eee8966bbb85937.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM calls WHERE id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "20a6a1d55831d2f428a4439ff09cd0f680dab8845b5789b83eee8966bbb85937"+}diff --git a/rust/cloud-storage/call/.sqlx/query-2995844320b8b71c3e61d00a6b91c0b083f404ee8a8541538709acc18f6679ad.json b/rust/cloud-storage/call/.sqlx/query-2995844320b8b71c3e61d00a6b91c0b083f404ee8a8541538709acc18f6679ad.jsonnew file mode 100644index 0000000000..2134794b8b--- /dev/null+++ b/rust/cloud-storage/call/.sqlx/query-2995844320b8b71c3e61d00a6b91c0b083f404ee8a8541538709acc18f6679ad.json@@ -0,0 +1,55 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO calls (id, channel_id, room_name, created_by)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (channel_id) DO NOTHING\n RETURNING id, channel_id, room_name, created_by, created_at, egress_id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "channel_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "room_name",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "created_by",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 5,+ "name": "egress_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Text",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ true+ ]+ },+ "hash": "2995844320b8b71c3e61d00a6b91c0b083f404ee8a8541538709acc18f6679ad"+}diff --git a/rust/cloud-storage/call/.sqlx/query-2a43904e78a134b93cef3613fa69ed67bdd5fe2f059e97d3e74a11d478647c86.json b/rust/cloud-storage/call/.sqlx/query-2a43904e78a134b93cef3613fa69ed67bdd5fe2f059e97d3e74a11d478647c86.jsonnew file mode 100644index 0000000000..301e5dce85--- /dev/null+++ b/rust/cloud-storage/call/.sqlx/query-2a43904e78a134b93cef3613fa69ed67bdd5fe2f059e97d3e74a11d478647c86.json@@ -0,0 +1,19 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO call_transcripts (call_id, segment_id, speaker_id, content, started_at, ended_at, sequence_num)\n VALUES ($1, $2, $3, $4, $5, $6, (\n SELECT COALESCE(MAX(sequence_num), 0) + 1\n FROM call_transcripts\n WHERE call_id = $1\n ))\n ON CONFLICT (call_id, segment_id) DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text",+ "Text",+ "Timestamptz",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "2a43904e78a134b93cef3613fa69ed67bdd5fe2f059e97d3e74a11d478647c86"+}diff --git a/rust/cloud-storage/call/.sqlx/query-2a75819c2697a91f55f1161c1dd79d065235f02119bbb2cc2b881f6fa8f82274.json b/rust/cloud-storage/call/.sqlx/query-2a75819c2697a91f55f1161c1dd79d065235f02119bbb2cc2b881f6fa8f82274.jsonnew file mode 100644index 0000000000..01133fef47--- /dev/null+++ b/rust/cloud-storage/call/.sqlx/query-2a75819c2697a91f55f1161c1dd79d065235f02119bbb2cc2b881f6fa8f82274.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT call_id, user_id, joined_at\n FROM call_participants\n WHERE call_id = $1 AND left_at IS NULL\n ORDER BY joined_at ASC\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "call_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "joined_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false+ ]+ },+ "hash": "2a75819c2697a91f55f1161c1dd79d065235f02119bbb2cc2b881f6fa8f82274"+}diff --git a/rust/cloud-storage/call/.sqlx/query-39fb4a71810075749c01ca721695f3f5743a32053277017489892c8253bd6f99.json b/rust/cloud-storage/call/.sqlx/query-39fb4a71810075749c01ca721695f3f5743a32053277017489892c8253bd6f99.jsonnew file mode 100644index 0000000000..9e6af2373c--- /dev/null+++ b/rust/cloud-storage/call/.sqlx/query-39fb4a71810075749c01ca721695f3f5743a32053277017489892c8253bd6f99.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE calls SET recording_url = $2 WHERE egress_id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "39fb4a71810075749c01ca721695f3f5743a32053277017489892c8253bd6f99"+}diff --git a/rust/cloud-storage/call/.sqlx/query-414c3ac70d95caaaf4c7fdb0556c287e3755f19187f07ec05d4ce0c60a5df751.json b/rust/cloud-storage/call/.sqlx/query-414c3ac70d95caaaf4c7fdb0556c287e3755f19187f07ec05d4ce0c60a5df751.jsonnew file mode 100644index 0000000000..12cc6e12d0--- /dev/null+++ b/rust/cloud-storage/call/.sqlx/query-414c3ac70d95caaaf4c7fdb0556c287e3755f19187f07ec05d4ce0c60a5df751.json@@ -0,0 +1,52 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, channel_id, room_name, created_by, created_at, egress_id\n FROM calls\n WHERE channel_id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "channel_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "room_name",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "created_by",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 5,+ "name": "egress_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ true+ ]+ },+ "hash": "414c3ac70d95caaaf4c7fdb0556c287e3755f19187f07ec05d4ce0c60a5df751"+}diff --git a/rust/cloud-storage/call/.sqlx/query-444840cacdf181727100b5ee338de844abb56d9cb3a88034db7b285fcff7e9b7.json b/rust/cloud-storage/call/.sqlx/query-444840cacdf181727100b5ee338de844abb56d9cb3a88034db7b285fcff7e9b7.jsonnew file mode 100644index 0000000000..0f87a4867d--- /dev/null+++ b/rust/cloud-storage/call/.sqlx/query-444840cacdf181727100b5ee338de844abb56d9cb3a88034db7b285fcff7e9b7.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id FROM call_records WHERE egress_id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "444840cacdf181727100b5ee338de844abb56d9cb3a88034db7b285fcff7e9b7"+}diff --git a/rust/cloud-storage/call/.sqlx/query-5d7c176f88f6883ffdd41a43969a101f26817ebd80c68dbeffe7c3226ab67a41.json b/rust/cloud-storage/call/.sqlx/query-5d7c176f88f6883ffdd41a43969a101f26817ebd80c68dbeffe7c3226ab67a41.jsonnew file mode 100644index 0000000000..0010b2933a--- /dev/null+++ b/rust/cloud-storage/call/.sqlx/query-5d7c176f88f6883ffdd41a43969a101f26817ebd80c68dbeffe7c3226ab67a41.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO call_record_participants (call_record_id, user_id, joined_at, left_at)\n SELECT $1, user_id, joined_at, left_at\n FROM call_participants\n WHERE call_id = $2\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "5d7c176f88f6883ffdd41a43969a101f26817ebd80c68dbeffe7c3226ab67a41"+}diff --git a/rust/cloud-storage/call/.sqlx/query-77a3b4ac298457a9c06b145d60a00127619bcfe56c969e69c03c98e7b2d975f9.json b/rust/cloud-storage/call/.sqlx/query-77a3b4ac298457a9c06b145d60a00127619bcfe56c969e69c03c98e7b2d975f9.jsonnew file mode 100644index 0000000000..c07a0bcdf7--- /dev/null+++ b/rust/cloud-storage/call/.sqlx/query-77a3b4ac298457a9c06b145d60a00127619bcfe56c969e69c03c98e7b2d975f9.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT EXISTS(\n SELECT 1 FROM call_participants\n WHERE call_id = $1 AND user_id = $2 AND left_at IS NULL\n ) as \"exists!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "exists!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "77a3b4ac298457a9c06b145d60a00127619bcfe56c969e69c03c98e7b2d975f9"+}diff --git a/rust/cloud-storage/call/.sqlx/query-78d6d53824fefc526411d2a0ff9d70f665ebe35943b7246ff5e6e3f801183cef.json b/rust/cloud-storage/call/.sqlx/query-78d6d53824fefc526411d2a0ff9d70f665ebe35943b7246ff5e6e3f801183cef.jsonnew file mode 100644index 0000000000..b5606178ca--- /dev/null+++ b/rust/cloud-storage/call/.sqlx/query-78d6d53824fefc526411d2a0ff9d70f665ebe35943b7246ff5e6e3f801183cef.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE call_participants\n SET left_at = now()\n WHERE call_id = $1 AND user_id = $2 AND left_at IS NULL\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "78d6d53824fefc526411d2a0ff9d70f665ebe35943b7246ff5e6e3f801183cef"+}diff --git a/rust/cloud-storage/call/.sqlx/query-828f0574782433d07de91f85db16dd61ef2d91b2073d68dcf116135bdbca3851.json b/rust/cloud-storage/call/.sqlx/query-828f0574782433d07de91f85db16dd61ef2d91b2073d68dcf116135bdbca3851.jsonnew file mode 100644index 0000000000..3f01c0deb5--- /dev/null+++ b/rust/cloud-storage/call/.sqlx/query-828f0574782433d07de91f85db16dd61ef2d91b2073d68dcf116135bdbca3851.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE call_records SET recording_url = $2 WHERE id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "828f0574782433d07de91f85db16dd61ef2d91b2073d68dcf116135bdbca3851"+}diff --git a/rust/cloud-storage/call/.sqlx/query-b564cb72641ccbd1fede2f0fac3167e192665f8dda8043f7a27c22a2eec49662.json b/rust/cloud-storage/call/.sqlx/query-b564cb72641ccbd1fede2f0fac3167e192665f8dda8043f7a27c22a2eec49662.jsonnew file mode 100644index 0000000000..e7ba0e104f--- /dev/null+++ b/rust/cloud-storage/call/.sqlx/query-b564cb72641ccbd1fede2f0fac3167e192665f8dda8043f7a27c22a2eec49662.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO call_record_transcripts (call_record_id, segment_id, speaker_id, content, started_at, ended_at, sequence_num)\n SELECT $1, segment_id, speaker_id, content, started_at, ended_at, sequence_num\n FROM call_transcripts\n WHERE call_id = $2\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "b564cb72641ccbd1fede2f0fac3167e192665f8dda8043f7a27c22a2eec49662"+}diff --git a/rust/cloud-storage/call/.sqlx/query-d0c976b53ed5c8b754013dc219219ae33bff5dc510075ca8f0f24db8a9e1ead6.json b/rust/cloud-storage/call/.sqlx/query-d0c976b53ed5c8b754013dc219219ae33bff5dc510075ca8f0f24db8a9e1ead6.jsonnew file mode 100644index 0000000000..32a1192c57--- /dev/null+++ b/rust/cloud-storage/call/.sqlx/query-d0c976b53ed5c8b754013dc219219ae33bff5dc510075ca8f0f24db8a9e1ead6.json@@ -0,0 +1,35 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO call_participants (call_id, user_id)\n VALUES ($1, $2)\n ON CONFLICT (call_id, user_id) DO UPDATE SET left_at = NULL, joined_at = now()\n RETURNING call_id, user_id, joined_at\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "call_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "joined_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false+ ]+ },+ "hash": "d0c976b53ed5c8b754013dc219219ae33bff5dc510075ca8f0f24db8a9e1ead6"+}diff --git a/rust/cloud-storage/call/.sqlx/query-dd6e7bbdb4ee903f6769bf2259bbca5c630c1f2bb969d26ca5b3e00530deaa02.json b/rust/cloud-storage/call/.sqlx/query-dd6e7bbdb4ee903f6769bf2259bbca5c630c1f2bb969d26ca5b3e00530deaa02.jsonnew file mode 100644index 0000000000..a4936971aa--- /dev/null+++ b/rust/cloud-storage/call/.sqlx/query-dd6e7bbdb4ee903f6769bf2259bbca5c630c1f2bb969d26ca5b3e00530deaa02.json@@ -0,0 +1,22 @@+{+ "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_url)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Text",+ "Text",+ "Timestamptz",+ "Timestamptz",+ "Int8",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "dd6e7bbdb4ee903f6769bf2259bbca5c630c1f2bb969d26ca5b3e00530deaa02"+}diff --git a/rust/cloud-storage/call/.sqlx/query-f2b90d413f8882f0d1da810aeca51a503118d0dddd8759495f607c65158605d7.json b/rust/cloud-storage/call/.sqlx/query-f2b90d413f8882f0d1da810aeca51a503118d0dddd8759495f607c65158605d7.jsonnew file mode 100644index 0000000000..13b75b74c6--- /dev/null+++ b/rust/cloud-storage/call/.sqlx/query-f2b90d413f8882f0d1da810aeca51a503118d0dddd8759495f607c65158605d7.json@@ -0,0 +1,52 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, channel_id, room_name, created_by, created_at, egress_id\n FROM calls\n WHERE room_name = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "channel_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "room_name",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "created_by",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 5,+ "name": "egress_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ true+ ]+ },+ "hash": "f2b90d413f8882f0d1da810aeca51a503118d0dddd8759495f607c65158605d7"+}diff --git a/rust/cloud-storage/call/.sqlx/query-f38943ee03436d2c57f710d4592b242fe240c11788d50a36d7b7bac85610114b.json b/rust/cloud-storage/call/.sqlx/query-f38943ee03436d2c57f710d4592b242fe240c11788d50a36d7b7bac85610114b.jsonnew file mode 100644index 0000000000..69eb93fd48--- /dev/null+++ b/rust/cloud-storage/call/.sqlx/query-f38943ee03436d2c57f710d4592b242fe240c11788d50a36d7b7bac85610114b.json@@ -0,0 +1,58 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, channel_id, room_name, created_by, created_at, egress_id, recording_url\n FROM calls\n WHERE id = $1\n FOR UPDATE\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "channel_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "room_name",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "created_by",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 5,+ "name": "egress_id",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "recording_url",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ true,+ true+ ]+ },+ "hash": "f38943ee03436d2c57f710d4592b242fe240c11788d50a36d7b7bac85610114b"+}diff --git a/rust/cloud-storage/call/.sqlx/query-f6226ec842f894cdf49b4a8d0d1f363e31040405915cffa7da18a3ed337e298a.json b/rust/cloud-storage/call/.sqlx/query-f6226ec842f894cdf49b4a8d0d1f363e31040405915cffa7da18a3ed337e298a.jsonnew file mode 100644index 0000000000..c69a93a03c--- /dev/null+++ b/rust/cloud-storage/call/.sqlx/query-f6226ec842f894cdf49b4a8d0d1f363e31040405915cffa7da18a3ed337e298a.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT COUNT(*) as \"count!\"\n FROM call_participants\n WHERE call_id = $1 AND left_at IS NULL\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "count!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "f6226ec842f894cdf49b4a8d0d1f363e31040405915cffa7da18a3ed337e298a"+}diff --git a/rust/cloud-storage/call/Cargo.toml b/rust/cloud-storage/call/Cargo.tomlnew file mode 100644index 0000000000..eb2b3617ce--- /dev/null+++ b/rust/cloud-storage/call/Cargo.toml@@ -0,0 +1,42 @@+[package]+edition = "2024"+name = "call"+publish = false+version = "0.1.0"++[features]+default = ["inbound", "outbound", "ports"]+inbound = [+ "dep:axum",+ "dep:entity_access",+ "dep:model-error-response",+ "dep:model_user",+ "dep:utoipa",+ "ports",+]+outbound = ["dep:livekit-api", "dep:livekit-protocol", "dep:sqlx", "ports"]+ports = ["dep:tokio"]++[dependencies]+anyhow = { workspace = true }+axum = { workspace = true, optional = true }+chrono = { workspace = true }+entity_access = { path = "../entity_access", optional = true, default-features = false, features = ["inbound"] }+livekit-api = { workspace = true, optional = true }+livekit-protocol = { workspace = true, optional = true }+macro_user_id = { path = "../macro_user_id" }+model-error-response = { path = "../model-error-response", optional = true }+model_user = { path = "../model_user", optional = true, features = ["axum"] }+serde = { workspace = true }+sqlx = { workspace = true, optional = true }+thiserror = { workspace = true }+tokio = { workspace = true, features = ["macros"], optional = true }+tracing = { workspace = true }+utoipa = { workspace = true, optional = true }+uuid = { workspace = true }++[dev-dependencies]+macro_db_migrator = { path = "../macro_db_migrator" }+mockall = { workspace = true }+sqlx = { workspace = true }+tokio = { workspace = true }diff --git a/rust/cloud-storage/call/fixtures/call_repo.sql b/rust/cloud-storage/call/fixtures/call_repo.sqlnew file mode 100644index 0000000000..eca10fbe9b--- /dev/null+++ b/rust/cloud-storage/call/fixtures/call_repo.sql@@ -0,0 +1,25 @@+-- Fixture for call repo integration tests.+--+-- Channel: ch1 (public)+-- Active call: call1 in ch1, created by user-a+-- Participants: user-a (creator), user-b+--+-- Channel: ch2 (public, no active call)++-- channels+INSERT INTO comms_channels (id, name, channel_type, org_id, owner_id, created_at, updated_at) VALUES+ ('00000000-0000-0000-0000-000000000c01', 'call-test-channel', 'public', NULL, 'macro|[email protected]',+ '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00'),+ ('00000000-0000-0000-0000-000000000c02', 'empty-channel', 'public', NULL, 'macro|[email protected]',+ '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00');++-- active call in ch1+INSERT INTO calls (id, channel_id, room_name, created_by, created_at) VALUES+ ('00000000-0000-0000-0000-0000000ca110', '00000000-0000-0000-0000-000000000c01',+ '00000000-0000-0000-0000-000000000c01', 'macro|[email protected]',+ '2024-01-01 12:00:00+00');++-- participants in call1+INSERT INTO call_participants (call_id, user_id, joined_at) VALUES+ ('00000000-0000-0000-0000-0000000ca110', 'macro|[email protected]', '2024-01-01 12:00:00+00'),+ ('00000000-0000-0000-0000-0000000ca110', 'macro|[email protected]', '2024-01-01 12:01:00+00');diff --git a/rust/cloud-storage/call/justfile b/rust/cloud-storage/call/justfilenew file mode 100644index 0000000000..d7f13030d3--- /dev/null+++ b/rust/cloud-storage/call/justfile@@ -0,0 +1,9 @@+DATABASE_URL := "postgres://user:password@localhost:5432/macrodb"++mod sqlx '../sqlx.just'++prepare_db:+ just sqlx::prepare_db {{ DATABASE_URL }}++check:+ cargo check --all-featuresdiff --git a/rust/cloud-storage/call/src/domain/mod.rs b/rust/cloud-storage/call/src/domain/mod.rsnew file mode 100644index 0000000000..f080d971b1--- /dev/null+++ b/rust/cloud-storage/call/src/domain/mod.rs@@ -0,0 +1,10 @@+/// Domain models for calls.+pub mod models;++/// Port traits for calls.+#[cfg(feature = "ports")]+pub mod ports;++/// Service orchestration for calls.+#[cfg(feature = "ports")]+pub mod service;diff --git a/rust/cloud-storage/call/src/domain/models.rs b/rust/cloud-storage/call/src/domain/models.rsnew file mode 100644index 0000000000..7510259f47--- /dev/null+++ b/rust/cloud-storage/call/src/domain/models.rs@@ -0,0 +1,139 @@+//! Domain models for the call crate.++use std::fmt;++use chrono::{DateTime, Utc};+use uuid::Uuid;++/// Represents an active call in a channel.+#[derive(Debug, Clone)]+pub struct Call {+ /// Unique call identifier.+ pub id: Uuid,+ /// The channel this call belongs to.+ pub channel_id: Uuid,+ /// Name of the RTC room (typically the channel_id as a string).+ pub room_name: String,+ /// User who created the call.+ pub created_by: String,+ /// When the call was created.+ pub created_at: DateTime<Utc>,+ /// Egress (recording) ID, if recording is active.+ pub egress_id: Option<String>,+}++/// A participant in an active call.+#[derive(Debug, Clone)]+pub struct CallParticipant {+ /// The call this participant is in.+ pub call_id: Uuid,+ /// The user id.+ pub user_id: String,+ /// When the user joined the call.+ pub joined_at: DateTime<Utc>,+}++/// Response returned when creating or joining a call.+#[derive(Debug, serde::Serialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct CallTokenResponse {+ /// The call identifier.+ pub call_id: Uuid,+ /// The channel this call is associated with.+ pub channel_id: Uuid,+ /// The RTC token for connecting to the room.+ pub token: String,+ /// The RTC room name.+ pub room_name: String,+ /// The RTC server URL for the frontend SDK to connect to.+ pub server_url: String,+}++/// Response for the leave/end call operation.+#[derive(Debug, serde::Serialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct LeaveCallResponse {+ /// Whether the entire call was ended (room deleted).+ pub call_ended: bool,+}++/// Configuration for S3 egress output.+#[derive(Clone)]+pub struct EgressS3Config {+ /// S3 bucket name.+ pub bucket: String,+ /// AWS region.+ pub region: String,+ /// AWS access key ID.+ pub access_key: String,+ /// AWS secret access key.+ pub secret: String,+}++impl fmt::Debug for EgressS3Config {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.debug_struct("EgressS3Config")+ .field("bucket", &self.bucket)+ .field("region", &self.region)+ .field("access_key", &"<redacted>")+ .field("secret", &"<redacted>")+ .finish()+ }+}++/// A validated webhook event from the RTC provider.+#[derive(Debug, Clone)]+pub struct CallWebhookEvent {+ /// The event type (e.g. `room_started`, `room_finished`, `participant_joined`).+ pub event: String,+ /// Unique event identifier.+ pub id: String,+ /// Room name associated with the event, if any.+ pub room_name: Option<String>,+ /// Participant identity associated with the event, if any.+ pub participant_identity: Option<String>,+ /// Egress ID associated with the event, if any.+ pub egress_id: Option<String>,+ /// File download URL from a completed egress, if any.+ pub file_url: Option<String>,+ /// Unix timestamp (seconds) when the event was created.+ pub created_at: i64,+}++/// A transcript segment from LiveKit Inference STT.+#[derive(Debug, Clone, serde::Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct TranscriptSegmentRequest {+ /// LiveKit segment ID (used for deduplication across multiple submitters).+ pub segment_id: String,+ /// The speaker's user ID (from `lk.transcribed_track_id`).+ pub speaker_id: String,+ /// The transcribed text content.+ pub content: String,+ /// When the speaker started talking for this segment.+ pub started_at: DateTime<Utc>,+ /// When the speaker stopped talking for this segment.+ pub ended_at: Option<DateTime<Utc>>,+ /// Whether this is a final transcription (not interim).+ pub is_final: bool,+}++/// Errors that can occur during call operations.+#[derive(Debug, thiserror::Error)]+pub enum CallError {+ /// No active call found for this channel.+ #[error("no active call found for channel {0}")]+ NotFound(String),+ /// User is not in the call.+ #[error("user not in call")]+ NotInCall,+ /// Authentication or signature validation failed.+ #[error("authentication failed")]+ Auth,+ /// An internal error occurred.+ #[error(transparent)]+ Internal(#[from] anyhow::Error),+}diff --git a/rust/cloud-storage/call/src/domain/ports.rs b/rust/cloud-storage/call/src/domain/ports.rsnew file mode 100644index 0000000000..e6463f5091--- /dev/null+++ b/rust/cloud-storage/call/src/domain/ports.rs@@ -0,0 +1,189 @@+//! Port definitions for the call domain.+//!+//! These traits define the contracts that adapters must implement.++use std::fmt::Debug;+use std::future::Future;++use uuid::Uuid;++use super::models::{+ Call, CallError, CallParticipant, CallTokenResponse, CallWebhookEvent, EgressS3Config,+ LeaveCallResponse, TranscriptSegmentRequest,+};++/// Repository port for persisting call state to the database.+#[cfg_attr(test, mockall::automock(type Err = anyhow::Error;))]+pub trait CallRepository: Send + Sync + 'static {+ /// The error type returned by repository operations.+ type Err: Into<anyhow::Error> + Send + Debug;++ /// Create a new call record, or return `None` if one already exists for+ /// this channel (unique-constraint conflict).+ fn create_call(+ &self,+ call_id: &Uuid,+ channel_id: &Uuid,+ room_name: &str,+ created_by: &str,+ ) -> impl Future<Output = Result<Option<Call>, Self::Err>> + Send;++ /// Get an active call by channel ID.+ fn get_call_by_channel_id(+ &self,+ channel_id: &Uuid,+ ) -> impl Future<Output = Result<Option<Call>, Self::Err>> + Send;++ /// Get an active call by its RTC room name.+ fn get_call_by_room_name(+ &self,+ room_name: &str,+ ) -> impl Future<Output = Result<Option<Call>, Self::Err>> + Send;++ /// Add a participant to a call.+ fn add_participant(+ &self,+ call_id: &Uuid,+ user_id: &str,+ ) -> impl Future<Output = Result<CallParticipant, Self::Err>> + Send;++ /// Remove a participant from a call.+ fn remove_participant(+ &self,+ call_id: &Uuid,+ user_id: &str,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;++ /// Get all active participants for a call.+ fn get_participants(+ &self,+ call_id: &Uuid,+ ) -> impl Future<Output = Result<Vec<CallParticipant>, Self::Err>> + Send;++ /// Get the count of active participants in a call.+ fn get_participant_count(+ &self,+ call_id: &Uuid,+ ) -> impl Future<Output = Result<i64, Self::Err>> + Send;++ /// Check if a user is already a participant in a call.+ fn is_participant(+ &self,+ call_id: &Uuid,+ user_id: &str,+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;++ /// Delete a call record (when the call ends).+ fn delete_call(&self, call_id: &Uuid) -> impl Future<Output = Result<(), Self::Err>> + Send;++ /// Set the egress (recording) ID on an active call.+ fn set_egress_id(+ &self,+ call_id: &Uuid,+ egress_id: &str,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;++ /// Archive an active call to the permanent `call_records` and+ /// `call_record_participants` tables, then delete the ephemeral rows.+ /// Returns the new `call_records` id.+ fn archive_call(&self, call_id: &Uuid) -> impl Future<Output = Result<Uuid, Self::Err>> + Send;++ /// Set the recording URL on an archived call record.+ fn set_recording_url(+ &self,+ call_record_id: &Uuid,+ recording_url: &str,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;++ /// Find a call record by its egress ID (for webhook handling).+ fn get_call_record_by_egress_id(+ &self,+ egress_id: &str,+ ) -> impl Future<Output = Result<Option<Uuid>, Self::Err>> + Send;++ /// Set the recording URL on an active call (by egress ID).+ ///+ /// Used when `egress_ended` arrives before the call is archived.+ /// Returns `true` if a matching active call was found and updated.+ fn set_active_call_recording_url(+ &self,+ egress_id: &str,+ recording_url: &str,+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;++ /// Insert a transcript segment for an active call.+ fn create_transcript_segment(+ &self,+ call_id: &Uuid,+ segment: &TranscriptSegmentRequest,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;+}++/// RTC client port for interacting with the real-time communication service (e.g., LiveKit).+#[cfg_attr(test, mockall::automock)]+pub trait CallRtcClient: Send + Sync + 'static {+ /// Create a new RTC room with the given name.+ fn create_room(&self, room_name: &str) -> impl Future<Output = anyhow::Result<()>> + Send;++ /// Delete an RTC room.+ fn delete_room(&self, room_name: &str) -> impl Future<Output = anyhow::Result<()>> + Send;++ /// Generate an access token for a participant to join a room.+ fn generate_token(+ &self,+ room_name: &str,+ participant_identity: &str,+ ) -> impl Future<Output = anyhow::Result<String>> + Send;++ /// Remove a participant from a room.+ fn remove_participant(+ &self,+ room_name: &str,+ participant_identity: &str,+ ) -> impl Future<Output = anyhow::Result<()>> + Send;++ /// Start a room composite egress (recording). Returns the egress ID.+ fn start_room_composite_egress(+ &self,+ room_name: &str,+ s3_config: &EgressS3Config,+ ) -> impl Future<Output = anyhow::Result<String>> + Send;++ /// Stop an active egress by ID.+ fn stop_egress(&self, egress_id: &str) -> impl Future<Output = anyhow::Result<()>> + Send;++ /// Validate a webhook signature and parse the event from the raw body.+ fn receive_webhook(&self, body: &str, auth_token: &str) -> Result<CallWebhookEvent, CallError>;+}++/// Service interface for call operations.+pub trait CallService: Send + Sync + 'static {+ /// Get or create a call in a channel. If a call already exists, joins it;+ /// otherwise creates a new one. Always returns a join token.+ fn get_or_create_call(+ &self,+ channel_id: &Uuid,+ user_id: &str,+ ) -> impl Future<Output = Result<CallTokenResponse, CallError>> + Send;++ /// Leave or end a call. Removes the user; if last participant, also deletes the room and call.+ fn leave_or_end_call(+ &self,+ channel_id: &Uuid,+ user_id: &str,+ ) -> impl Future<Output = Result<LeaveCallResponse, CallError>> + Send;++ /// Validate and process a raw webhook event from the RTC provider.+ fn process_webhook_event(+ &self,+ body: &str,+ auth_token: &str,+ ) -> impl Future<Output = Result<(), CallError>> + Send;++ /// Ingest a transcript segment from the LiveKit Agent STT pipeline.+ fn ingest_transcript_segment(+ &self,+ channel_id: &Uuid,+ segment: TranscriptSegmentRequest,+ ) -> impl Future<Output = Result<(), CallError>> + Send;+}diff --git a/rust/cloud-storage/call/src/domain/service.rs b/rust/cloud-storage/call/src/domain/service.rsnew file mode 100644index 0000000000..8790641e3b--- /dev/null+++ b/rust/cloud-storage/call/src/domain/service.rs@@ -0,0 +1,368 @@+//! Call service implementation.++use uuid::Uuid;++use super::models::{+ CallError, CallTokenResponse, EgressS3Config, LeaveCallResponse, TranscriptSegmentRequest,+};+use super::ports::{CallRepository, CallRtcClient, CallService};++/// The concrete call service implementation.+pub struct CallServiceImpl<R: CallRepository, C: CallRtcClient> {+ repo: R,+ rtc_client: C,+ server_url: String,+ egress_s3_config: Option<EgressS3Config>,+}++impl<R: CallRepository, C: CallRtcClient> CallServiceImpl<R, C> {+ /// Create a new call service.+ pub fn new(repo: R, rtc_client: C, server_url: impl Into<String>) -> Self {+ Self {+ repo,+ rtc_client,+ server_url: server_url.into(),+ egress_s3_config: None,+ }+ }++ /// Enable auto-recording with the given S3 configuration.+ pub fn with_egress(mut self, s3_config: EgressS3Config) -> Self {+ self.egress_s3_config = Some(s3_config);+ self+ }+}++impl<R: CallRepository, C: CallRtcClient> CallService for CallServiceImpl<R, C> {+ #[tracing::instrument(err, skip(self))]+ async fn get_or_create_call(+ &self,+ channel_id: &Uuid,+ user_id: &str,+ ) -> Result<CallTokenResponse, CallError> {+ let call = match self+ .repo+ .get_call_by_channel_id(channel_id)+ .await+ .map_err(|e| CallError::Internal(e.into()))?+ {+ Some(existing) => existing,+ None => {+ let call_id = Uuid::now_v7();+ let room_name = channel_id.to_string();++ // Create RTC room (idempotent in LiveKit).+ self.rtc_client+ .create_room(&room_name)+ .await+ .map_err(CallError::Internal)?;++ // Try to create call record; if another request won the race+ // the ON CONFLICT returns None — re-read the existing call.+ match self+ .repo+ .create_call(&call_id, channel_id, &room_name, user_id)+ .await+ .map_err(|e| CallError::Internal(e.into()))?+ {+ Some(call) => {+ // We are the creator — start recording if configured.+ if let Some(s3_config) = &self.egress_s3_config {+ match self+ .rtc_client+ .start_room_composite_egress(&room_name, s3_config)+ .await+ {+ Ok(egress_id) => {+ self.repo+ .set_egress_id(&call.id, &egress_id)+ .await+ .map_err(|e| CallError::Internal(e.into()))?;+ }+ Err(e) => {+ tracing::error!(error=?e, "failed to start egress recording");+ }+ }+ }++ call+ }+ None => {+ // Another request created the call — read the existing one.+ self.repo+ .get_call_by_channel_id(channel_id)+ .await+ .map_err(|e| CallError::Internal(e.into()))?+ .ok_or_else(|| CallError::NotFound(channel_id.to_string()))?+ }+ }+ }+ };++ // Idempotent upsert — handles concurrent joins and rejoin after leave.+ self.repo+ .add_participant(&call.id, user_id)+ .await+ .map_err(|e| CallError::Internal(e.into()))?;++ // Always generate a fresh token (supports reconnection from different devices).+ let token = self+ .rtc_client+ .generate_token(&call.room_name, user_id)+ .await+ .map_err(CallError::Internal)?;++ Ok(CallTokenResponse {+ call_id: call.id,+ channel_id: *channel_id,+ token,+ room_name: call.room_name,+ server_url: self.server_url.clone(),+ })+ }++ #[tracing::instrument(err, skip(self))]+ async fn leave_or_end_call(+ &self,+ channel_id: &Uuid,+ user_id: &str,+ ) -> Result<LeaveCallResponse, CallError> {+ let call = self+ .repo+ .get_call_by_channel_id(channel_id)+ .await+ .map_err(|e| CallError::Internal(e.into()))?+ .ok_or_else(|| CallError::NotFound(channel_id.to_string()))?;++ // Verify user is in the call.+ let is_in_call = self+ .repo+ .is_participant(&call.id, user_id)+ .await+ .map_err(|e| CallError::Internal(e.into()))?;++ if !is_in_call {+ return Err(CallError::NotInCall);+ }++ // Remove participant from DB.+ self.repo+ .remove_participant(&call.id, user_id)+ .await+ .map_err(|e| CallError::Internal(e.into()))?;++ // Remove from RTC (best-effort).+ // LiveKit will fire participant_left and eventually room_finished webhooks,+ // which handle call record archival and cleanup of the ephemeral tables.+ self.rtc_client+ .remove_participant(&call.room_name, user_id)+ .await+ .inspect_err(+ |e| tracing::error!(error=?e, "failed to remove participant from RTC room"),+ )+ .ok();++ // Check if this was the last participant.+ let remaining = self+ .repo+ .get_participant_count(&call.id)+ .await+ .map_err(|e| CallError::Internal(e.into()))?;++ Ok(LeaveCallResponse {+ call_ended: remaining == 0,+ })+ }++ #[tracing::instrument(err, skip(self, body, auth_token))]+ async fn process_webhook_event(&self, body: &str, auth_token: &str) -> Result<(), CallError> {+ let event = self.rtc_client.receive_webhook(body, auth_token)?;++ tracing::info!(+ event_type = %event.event,+ event_id = %event.id,+ room_name = ?event.room_name,+ participant = ?event.participant_identity,+ "processing call webhook event"+ );++ match event.event.as_str() {+ "room_started" => {+ tracing::info!(room_name = ?event.room_name, "room started");+ }+ "room_finished" => {+ // Safety net: archive if not already handled by participant_left.+ if let Some(room_name) = &event.room_name+ && let Some(call) = self+ .repo+ .get_call_by_room_name(room_name)+ .await+ .map_err(|e| CallError::Internal(e.into()))?+ {+ tracing::info!(call_id = %call.id, room_name, "archiving call on room_finished");+ self.repo+ .archive_call(&call.id)+ .await+ .map_err(|e| CallError::Internal(e.into()))?;+ }+ }+ "participant_joined" => {+ let (Some(room_name), Some(participant_identity)) =+ (&event.room_name, &event.participant_identity)+ else {+ tracing::warn!(+ "participant_joined webhook missing room_name or participant_identity"+ );+ return Ok(());+ };++ let Some(call) = self+ .repo+ .get_call_by_room_name(room_name)+ .await+ .map_err(|e| CallError::Internal(e.into()))?+ else {+ return Ok(());+ };++ // Reconcile: idempotent upsert (handles reconnect/race conditions).+ self.repo+ .add_participant(&call.id, participant_identity)+ .await+ .map_err(|e| CallError::Internal(e.into()))?;+ tracing::info!(+ call_id = %call.id,+ participant = participant_identity,+ "reconciled participant_joined via webhook"+ );+ }+ "participant_left" => {+ let (Some(room_name), Some(participant_identity)) =+ (&event.room_name, &event.participant_identity)+ else {+ tracing::warn!(+ "participant_left webhook missing room_name or participant_identity"+ );+ return Ok(());+ };++ let Some(call) = self+ .repo+ .get_call_by_room_name(room_name)+ .await+ .map_err(|e| CallError::Internal(e.into()))?+ else {+ // Call already archived, nothing to do.+ return Ok(());+ };++ // Reconcile: remove participant from DB if still present (handles crash/disconnect).+ if self+ .repo+ .is_participant(&call.id, participant_identity)+ .await+ .map_err(|e| CallError::Internal(e.into()))?+ {+ self.repo+ .remove_participant(&call.id, participant_identity)+ .await+ .map_err(|e| CallError::Internal(e.into()))?;+ }++ // If no participants remain, archive the call and delete the room.+ let remaining = self+ .repo+ .get_participant_count(&call.id)+ .await+ .map_err(|e| CallError::Internal(e.into()))?;++ if remaining == 0 {+ tracing::info!(call_id = %call.id, room_name, "last participant left, archiving call");+ self.repo+ .archive_call(&call.id)+ .await+ .map_err(|e| CallError::Internal(e.into()))?;++ self.rtc_client+ .delete_room(room_name)+ .await+ .inspect_err(|e| tracing::error!(error=?e, "failed to delete RTC room"))+ .ok();+ }+ }+ "egress_started" | "egress_updated" => {+ tracing::info!(+ event_type = %event.event,+ egress_id = ?event.egress_id,+ room_name = ?event.room_name,+ "egress event"+ );+ }+ "egress_ended" => {+ let (Some(egress_id), Some(file_url)) = (&event.egress_id, &event.file_url) else {+ tracing::warn!("egress_ended webhook missing egress_id or file_url");+ return Ok(());+ };++ tracing::info!(egress_id, file_url, "egress recording completed");++ // Find the archived call record by egress_id and update the recording URL.+ if let Some(call_record_id) = self+ .repo+ .get_call_record_by_egress_id(egress_id)+ .await+ .map_err(|e| CallError::Internal(e.into()))?+ {+ self.repo+ .set_recording_url(&call_record_id, file_url)+ .await+ .map_err(|e| CallError::Internal(e.into()))?;+ } else {+ // Call not yet archived — store on the active call so+ // archive_call can carry it forward.+ let updated = self+ .repo+ .set_active_call_recording_url(egress_id, file_url)+ .await+ .map_err(|e| CallError::Internal(e.into()))?;+ if !updated {+ tracing::warn!(+ egress_id,+ "no active call or call record found for egress_id"+ );+ }+ }+ }+ _ => {+ tracing::debug!(event_type = %event.event, "unhandled webhook event type");+ }+ }++ Ok(())+ }++ #[tracing::instrument(err, skip(self, segment))]+ async fn ingest_transcript_segment(+ &self,+ channel_id: &Uuid,+ segment: TranscriptSegmentRequest,+ ) -> Result<(), CallError> {+ if !segment.is_final {+ return Ok(());+ }++ let call = self+ .repo+ .get_call_by_channel_id(channel_id)+ .await+ .map_err(|e| CallError::Internal(e.into()))?+ .ok_or_else(|| CallError::NotFound(channel_id.to_string()))?;++ self.repo+ .create_transcript_segment(&call.id, &segment)+ .await+ .map_err(|e| CallError::Internal(e.into()))?;++ Ok(())+ }+}diff --git a/rust/cloud-storage/call/src/inbound/axum_router.rs b/rust/cloud-storage/call/src/inbound/axum_router.rsnew file mode 100644index 0000000000..15865fb663--- /dev/null+++ b/rust/cloud-storage/call/src/inbound/axum_router.rs@@ -0,0 +1,312 @@+//! Axum routers for call endpoints.+//!+//! Two routers are exposed so the consumer can attach different middleware:+//!+//! - [`call_router`] — authenticated call operations (get/create, leave/end).+//! Requires auth middleware.+//! - [`webhook_router`] — RTC provider webhook ingestion.+//! Does **not** require auth middleware (LiveKit signs requests itself).++use std::sync::Arc;++use axum::{+ Json, Router,+ extract::{FromRef, State},+ http::StatusCode,+ response::IntoResponse,+ routing::{get, post},+};+use entity_access::{+ domain::{+ models::{EntityAccessReceipt, MemberParticipantRole, RequiredPermission},+ ports::EntityAccessService,+ },+ inbound::axum_extractors::ChannelAccessLevelExtractor,+};+use model_error_response::ErrorResponse;+use model_user::axum_extractor::MacroUserExtractor;+use uuid::Uuid;++use crate::domain::models::{+ CallError, CallTokenResponse, LeaveCallResponse, TranscriptSegmentRequest,+};+use crate::domain::ports::CallService;++// ---------------------------------------------------------------------------+// Call router (authenticated)+// ---------------------------------------------------------------------------++/// Router state for authenticated call operations.+pub struct CallRouterState<S, Svc> {+ service: Arc<S>,+ access_service: Arc<Svc>,+}++impl<S, Svc> Clone for CallRouterState<S, Svc> {+ fn clone(&self) -> Self {+ Self {+ service: self.service.clone(),+ access_service: self.access_service.clone(),+ }+ }+}++impl<S: CallService, Svc: EntityAccessService> CallRouterState<S, Svc> {+ /// Create a new router state from shared service references.+ pub fn new(service: Arc<S>, access_service: Arc<Svc>) -> Self {+ Self {+ service,+ access_service,+ }+ }+}++impl<S, Svc> FromRef<CallRouterState<S, Svc>> for Arc<Svc> {+ fn from_ref(state: &CallRouterState<S, Svc>) -> Self {+ state.access_service.clone()+ }+}++fn channel_id_from_receipt<T: RequiredPermission>(+ receipt: &EntityAccessReceipt<T>,+) -> Result<Uuid, CallError> {+ Uuid::parse_str(&receipt.entity().entity_id)+ .map_err(|_| CallError::Internal(anyhow::anyhow!("invalid channel_id")))+}++/// Authenticated call router.+///+/// Routes:+/// - `GET /{channel_id}` — get or create a call (join existing or start new)+/// - `DELETE /{channel_id}` — leave or end a call+/// - `POST /{channel_id}/transcript` — ingest a transcript segment (from authenticated frontend)+pub fn call_router<S, Svc, T>(state: CallRouterState<S, Svc>) -> Router<T>+where+ S: CallService,+ Svc: EntityAccessService,+ T: Send + Sync,+{+ Router::new()+ .route(+ "/{channel_id}",+ get(get_or_create_call_handler::<S, Svc>).delete(leave_or_end_call_handler::<S, Svc>),+ )+ .route(+ "/{channel_id}/transcript",+ post(transcript_handler::<S, Svc>),+ )+ .with_state(state)+}++// ---------------------------------------------------------------------------+// Webhook router (unauthenticated — LiveKit validates via its own JWT)+// ---------------------------------------------------------------------------++/// Router state for the webhook endpoint.+pub struct WebhookRouterState<S> {+ service: Arc<S>,+}++impl<S> Clone for WebhookRouterState<S> {+ fn clone(&self) -> Self {+ Self {+ service: self.service.clone(),+ }+ }+}++impl<S: CallService> WebhookRouterState<S> {+ /// Create a new webhook router state wrapping the call service.+ pub fn new(service: Arc<S>) -> Self {+ Self { service }+ }+}++/// Webhook router for RTC provider event ingestion.+///+/// Routes:+/// - `POST /webhook` — ingest a webhook event from LiveKit+pub fn webhook_router<S, T>(state: WebhookRouterState<S>) -> Router<T>+where+ S: CallService,+ T: Send + Sync,+{+ Router::new()+ .route("/webhook", post(webhook_handler::<S>))+ .with_state(state)+}++// ---------------------------------------------------------------------------+// Handlers+// ---------------------------------------------------------------------------++/// Handler for `GET /call/{channel_id}`.+///+/// Gets or creates a call for the channel. If a call already exists, joins it;+/// otherwise creates a new one. Always returns a join token.+#[utoipa::path(+ get,+ operation_id = "get_or_create_call",+ path = "/call/{channel_id}",+ params(+ ("channel_id" = Uuid, Path, description = "Channel ID"),+ ),+ responses(+ (status = 200, body = CallTokenResponse),+ (status = 401, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(err, skip_all)]+pub async fn get_or_create_call_handler<S: CallService, Svc: EntityAccessService>(+ State(state): State<CallRouterState<S, Svc>>,+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,+ user: MacroUserExtractor,+) -> Result<Json<CallTokenResponse>, CallError> {+ let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;+ let user_id = user.macro_user_id.as_ref();++ let response = state+ .service+ .get_or_create_call(&channel_id, user_id)+ .await?;++ Ok(Json(response))+}++/// Handler for `DELETE /call/{channel_id}`.+#[utoipa::path(+ delete,+ operation_id = "leave_or_end_call",+ path = "/call/{channel_id}",+ params(+ ("channel_id" = Uuid, Path, description = "Channel ID"),+ ),+ responses(+ (status = 200, body = LeaveCallResponse),+ (status = 401, body = ErrorResponse),+ (status = 404, body = ErrorResponse, description = "No active call"),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(err, skip_all)]+pub async fn leave_or_end_call_handler<S: CallService, Svc: EntityAccessService>(+ State(state): State<CallRouterState<S, Svc>>,+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,+ user: MacroUserExtractor,+) -> Result<Json<LeaveCallResponse>, CallError> {+ let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;+ let user_id = user.macro_user_id.as_ref();++ let response = state+ .service+ .leave_or_end_call(&channel_id, user_id)+ .await?;++ Ok(Json(response))+}++/// Handler for `POST /call/webhook`.+///+/// Receives webhook events from the RTC provider (e.g. LiveKit).+/// The `Authorization` header contains the webhook auth token+/// and the body contains the raw event payload.+#[utoipa::path(+ post,+ operation_id = "call_webhook",+ path = "/call/webhook",+ responses(+ (status = 200, description = "Event processed"),+ (status = 401, description = "Invalid webhook signature"),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(err, skip_all)]+pub async fn webhook_handler<S: CallService>(+ State(state): State<WebhookRouterState<S>>,+ headers: axum::http::HeaderMap,+ body: String,+) -> Result<StatusCode, CallError> {+ let auth_token = headers+ .get(axum::http::header::AUTHORIZATION)+ .and_then(|v| v.to_str().ok())+ .ok_or(CallError::Auth)?;++ state+ .service+ .process_webhook_event(&body, auth_token)+ .await?;++ Ok(StatusCode::OK)+}++/// Handler for `POST /call/{channel_id}/transcript`.+///+/// Receives transcript segments from the frontend.+/// Requires channel membership. Duplicate segments (same `segment_id`) are ignored.+#[utoipa::path(+ post,+ operation_id = "ingest_transcript",+ path = "/call/{channel_id}/transcript",+ params(+ ("channel_id" = Uuid, Path, description = "Channel ID"),+ ),+ request_body = TranscriptSegmentRequest,+ responses(+ (status = 200, description = "Segment ingested"),+ (status = 401, body = ErrorResponse),+ (status = 404, body = ErrorResponse, description = "No active call"),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(err, skip_all)]+pub async fn transcript_handler<S: CallService, Svc: EntityAccessService>(+ State(state): State<CallRouterState<S, Svc>>,+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,+ user: MacroUserExtractor,+ Json(segment): Json<TranscriptSegmentRequest>,+) -> Result<StatusCode, CallError> {+ let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;+ let user_id = user.macro_user_id.as_ref();++ if segment.speaker_id != user_id {+ return Err(CallError::Auth);+ }++ state+ .service+ .ingest_transcript_segment(&channel_id, segment)+ .await?;++ Ok(StatusCode::OK)+}++// ---------------------------------------------------------------------------+// Error mapping+// ---------------------------------------------------------------------------++impl IntoResponse for CallError {+ fn into_response(self) -> axum::response::Response {+ let status_code = match &self {+ CallError::NotFound(_) => StatusCode::NOT_FOUND,+ CallError::NotInCall => StatusCode::BAD_REQUEST,+ CallError::Auth => StatusCode::UNAUTHORIZED,+ CallError::Internal(_) => {+ tracing::error!(error=?self, "internal server error");+ StatusCode::INTERNAL_SERVER_ERROR+ }+ };++ let message = match &self {+ CallError::Internal(_) => "internal server error".to_string(),+ other => other.to_string(),+ };+ (+ status_code,+ Json(ErrorResponse {+ message: message.into(),+ }),+ )+ .into_response()+ }+}diff --git a/rust/cloud-storage/call/src/inbound/mod.rs b/rust/cloud-storage/call/src/inbound/mod.rsnew file mode 100644index 0000000000..13187bdc15--- /dev/null+++ b/rust/cloud-storage/call/src/inbound/mod.rs@@ -0,0 +1,2 @@+/// Axum handler and router for calls.+pub mod axum_router;diff --git a/rust/cloud-storage/call/src/lib.rs b/rust/cloud-storage/call/src/lib.rsnew file mode 100644index 0000000000..c83c4cf165--- /dev/null+++ b/rust/cloud-storage/call/src/lib.rs@@ -0,0 +1,14 @@+#![deny(missing_docs)]+//! Call management with hexagonal architecture.+//!+//! Manages video/audio calls in channels using a ports-and-adapters pattern+//! with LiveKit as the RTC backend.++/// Domain layer: models, ports, and service.+pub mod domain;+/// Inbound layer: axum handler and router.+#[cfg(feature = "inbound")]+pub mod inbound;+/// Outbound layer: LiveKit RTC client adapter.+#[cfg(feature = "outbound")]+pub mod outbound;diff --git a/rust/cloud-storage/call/src/outbound/livekit_rtc_client.rs b/rust/cloud-storage/call/src/outbound/livekit_rtc_client.rsnew file mode 100644index 0000000000..52a16cf871--- /dev/null+++ b/rust/cloud-storage/call/src/outbound/livekit_rtc_client.rs@@ -0,0 +1,170 @@+//! LiveKit adapter for the [`CallRtcClient`] port.+//!+//! Wraps the `livekit-api` crate to provide room management, token generation,+//! egress recording, and webhook validation.++use livekit_api::access_token::{AccessToken, TokenVerifier, VideoGrants};+use livekit_api::services::egress::{EgressClient, EgressOutput, RoomCompositeOptions};+use livekit_api::services::room::{CreateRoomOptions, RoomClient};+use livekit_api::webhooks::WebhookReceiver;+use livekit_protocol::{EncodedFileOutput, S3Upload, encoded_file_output};++use crate::domain::models::{CallError, CallWebhookEvent, EgressS3Config};+use crate::domain::ports::CallRtcClient;++/// LiveKit implementation of [`CallRtcClient`].+pub struct LivekitRtcClient {+ room_client: RoomClient,+ egress_client: EgressClient,+ webhook_receiver: WebhookReceiver,+ api_key: String,+ api_secret: String,+}++impl LivekitRtcClient {+ /// Create a new LiveKit RTC client.+ ///+ /// # Arguments+ /// * `server_url` - LiveKit server URL (e.g. `https://my-livekit.example.com`)+ /// * `api_key` - LiveKit API key+ /// * `api_secret` - LiveKit API secret+ pub fn new(+ server_url: &str,+ api_key: impl Into<String>,+ api_secret: impl Into<String>,+ ) -> Self {+ let api_key = api_key.into();+ let api_secret = api_secret.into();+ // Twirp RPC requires HTTP(S), not WebSocket. Convert wss:// → https://+ // and ws:// → http:// so the same env var works for both client SDK and+ // server-side API calls.+ let http_url = server_url+ .replace("wss://", "https://")+ .replace("ws://", "http://");+ let room_client = RoomClient::with_api_key(&http_url, &api_key, &api_secret);+ let egress_client = EgressClient::with_api_key(&http_url, &api_key, &api_secret);+ let verifier = TokenVerifier::with_api_key(&api_key, &api_secret);+ let webhook_receiver = WebhookReceiver::new(verifier);+ Self {+ room_client,+ egress_client,+ webhook_receiver,+ api_key,+ api_secret,+ }+ }+}++impl CallRtcClient for LivekitRtcClient {+ #[tracing::instrument(err, skip(self))]+ async fn create_room(&self, room_name: &str) -> anyhow::Result<()> {+ self.room_client+ .create_room(room_name, CreateRoomOptions::default())+ .await?;+ Ok(())+ }++ #[tracing::instrument(err, skip(self))]+ async fn delete_room(&self, room_name: &str) -> anyhow::Result<()> {+ self.room_client.delete_room(room_name).await?;+ Ok(())+ }++ #[tracing::instrument(err, skip(self))]+ async fn generate_token(+ &self,+ room_name: &str,+ participant_identity: &str,+ ) -> anyhow::Result<String> {+ let token = AccessToken::with_api_key(&self.api_key, &self.api_secret)+ .with_identity(participant_identity)+ .with_grants(VideoGrants {+ room_join: true,+ room: room_name.to_string(),+ can_publish: true,+ can_subscribe: true,+ can_publish_data: true,+ ..Default::default()+ })+ .to_jwt()?;+ Ok(token)+ }++ #[tracing::instrument(err, skip(self))]+ async fn remove_participant(+ &self,+ room_name: &str,+ participant_identity: &str,+ ) -> anyhow::Result<()> {+ self.room_client+ .remove_participant(room_name, participant_identity)+ .await?;+ Ok(())+ }++ #[tracing::instrument(err, skip(self, s3_config))]+ async fn start_room_composite_egress(+ &self,+ room_name: &str,+ s3_config: &EgressS3Config,+ ) -> anyhow::Result<String> {+ let output = EgressOutput::File(EncodedFileOutput {+ filepath: format!("calls/{room_name}/{{time}}"),+ output: Some(encoded_file_output::Output::S3(S3Upload {+ bucket: s3_config.bucket.clone(),+ region: s3_config.region.clone(),+ access_key: s3_config.access_key.clone(),+ secret: s3_config.secret.clone(),+ ..Default::default()+ })),+ ..Default::default()+ });++ let info = self+ .egress_client+ .start_room_composite_egress(room_name, vec![output], RoomCompositeOptions::default())+ .await?;++ Ok(info.egress_id)+ }++ #[tracing::instrument(err, skip(self))]+ async fn stop_egress(&self, egress_id: &str) -> anyhow::Result<()> {+ self.egress_client.stop_egress(egress_id).await?;+ Ok(())+ }++ fn receive_webhook(&self, body: &str, auth_token: &str) -> Result<CallWebhookEvent, CallError> {+ let event = self+ .webhook_receiver+ .receive(body, auth_token)+ .map_err(|e| {+ tracing::warn!(error=?e, "webhook signature validation failed");+ CallError::Auth+ })?;++ // Extract file URL from egress info if available.+ let (egress_id, file_url) = match &event.egress_info {+ Some(info) => {+ let url = info.file_results.first().map(|f| f.location.clone());+ let id = if info.egress_id.is_empty() {+ None+ } else {+ Some(info.egress_id.clone())+ };+ (id, url)+ }+ None => (None, None),+ };++ Ok(CallWebhookEvent {+ event: event.event,+ id: event.id,+ room_name: event.room.map(|r| r.name),+ participant_identity: event.participant.map(|p| p.identity),+ egress_id,+ file_url,+ created_at: event.created_at,+ })+ }+}diff --git a/rust/cloud-storage/call/src/outbound/mod.rs b/rust/cloud-storage/call/src/outbound/mod.rsnew file mode 100644index 0000000000..ff5139d096--- /dev/null+++ b/rust/cloud-storage/call/src/outbound/mod.rs@@ -0,0 +1,4 @@+/// LiveKit RTC client adapter implementing [`CallRtcClient`](crate::domain::ports::CallRtcClient).+pub mod livekit_rtc_client;+/// Postgres-backed repository implementing [`CallRepository`](crate::domain::ports::CallRepository).+pub mod pg_call_repo;diff --git a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs b/rust/cloud-storage/call/src/outbound/pg_call_repo.rsnew file mode 100644index 0000000000..e73e96b8c7--- /dev/null+++ b/rust/cloud-storage/call/src/outbound/pg_call_repo.rs@@ -0,0 +1,396 @@+//! Postgres-backed repository for call state.++#[cfg(test)]+mod test;++use chrono::Utc;+use sqlx::PgPool;+use uuid::Uuid;++use crate::domain::models::{Call, CallParticipant, TranscriptSegmentRequest};+use crate::domain::ports::CallRepository;++/// Postgres implementation of [`CallRepository`].+pub struct PgCallRepo {+ pool: PgPool,+}++impl PgCallRepo {+ /// Create a new repo with the given connection pool.+ pub fn new(pool: PgPool) -> Self {+ Self { pool }+ }+}++impl CallRepository for PgCallRepo {+ type Err = sqlx::Error;++ #[tracing::instrument(err, skip(self))]+ async fn create_call(+ &self,+ call_id: &Uuid,+ channel_id: &Uuid,+ room_name: &str,+ created_by: &str,+ ) -> Result<Option<Call>, Self::Err> {+ let row = sqlx::query!(+ r#"+ INSERT INTO calls (id, channel_id, room_name, created_by)+ VALUES ($1, $2, $3, $4)+ ON CONFLICT (channel_id) DO NOTHING+ RETURNING id, channel_id, room_name, created_by, created_at, egress_id+ "#,+ call_id,+ channel_id,+ room_name,+ created_by,+ )+ .fetch_optional(&self.pool)+ .await?;++ Ok(row.map(|r| Call {+ id: r.id,+ channel_id: r.channel_id,+ room_name: r.room_name,+ created_by: r.created_by,+ created_at: r.created_at,+ egress_id: r.egress_id,+ }))+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_call_by_channel_id(&self, channel_id: &Uuid) -> Result<Option<Call>, Self::Err> {+ sqlx::query!(+ r#"+ SELECT id, channel_id, room_name, created_by, created_at, egress_id+ FROM calls+ WHERE channel_id = $1+ "#,+ channel_id,+ )+ .fetch_optional(&self.pool)+ .await+ .map(|opt| {+ opt.map(|row| Call {+ id: row.id,+ channel_id: row.channel_id,+ room_name: row.room_name,+ created_by: row.created_by,+ created_at: row.created_at,+ egress_id: row.egress_id,+ })+ })+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_call_by_room_name(&self, room_name: &str) -> Result<Option<Call>, Self::Err> {+ sqlx::query!(+ r#"+ SELECT id, channel_id, room_name, created_by, created_at, egress_id+ FROM calls+ WHERE room_name = $1+ "#,+ room_name,+ )+ .fetch_optional(&self.pool)+ .await+ .map(|opt| {+ opt.map(|row| Call {+ id: row.id,+ channel_id: row.channel_id,+ room_name: row.room_name,+ created_by: row.created_by,+ created_at: row.created_at,+ egress_id: row.egress_id,+ })+ })+ }++ #[tracing::instrument(err, skip(self))]+ async fn add_participant(+ &self,+ call_id: &Uuid,+ user_id: &str,+ ) -> Result<CallParticipant, Self::Err> {+ let row = sqlx::query!(+ r#"+ INSERT INTO call_participants (call_id, user_id)+ VALUES ($1, $2)+ ON CONFLICT (call_id, user_id) DO UPDATE SET left_at = NULL, joined_at = now()+ RETURNING call_id, user_id, joined_at+ "#,+ call_id,+ user_id,+ )+ .fetch_one(&self.pool)+ .await?;++ Ok(CallParticipant {+ call_id: row.call_id,+ user_id: row.user_id,+ joined_at: row.joined_at,+ })+ }++ #[tracing::instrument(err, skip(self))]+ async fn remove_participant(&self, call_id: &Uuid, user_id: &str) -> Result<(), Self::Err> {+ sqlx::query!(+ r#"+ UPDATE call_participants+ SET left_at = now()+ WHERE call_id = $1 AND user_id = $2 AND left_at IS NULL+ "#,+ call_id,+ user_id,+ )+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_participants(&self, call_id: &Uuid) -> Result<Vec<CallParticipant>, Self::Err> {+ sqlx::query!(+ r#"+ SELECT call_id, user_id, joined_at+ FROM call_participants+ WHERE call_id = $1 AND left_at IS NULL+ ORDER BY joined_at ASC+ "#,+ call_id,+ )+ .fetch_all(&self.pool)+ .await+ .map(|rows| {+ rows.into_iter()+ .map(|row| CallParticipant {+ call_id: row.call_id,+ user_id: row.user_id,+ joined_at: row.joined_at,+ })+ .collect()+ })+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_participant_count(&self, call_id: &Uuid) -> Result<i64, Self::Err> {+ sqlx::query_scalar!(+ r#"+ SELECT COUNT(*) as "count!"+ FROM call_participants+ WHERE call_id = $1 AND left_at IS NULL+ "#,+ call_id,+ )+ .fetch_one(&self.pool)+ .await+ }++ #[tracing::instrument(err, skip(self))]+ async fn is_participant(&self, call_id: &Uuid, user_id: &str) -> Result<bool, Self::Err> {+ sqlx::query_scalar!(+ r#"+ SELECT EXISTS(+ SELECT 1 FROM call_participants+ WHERE call_id = $1 AND user_id = $2 AND left_at IS NULL+ ) as "exists!"+ "#,+ call_id,+ user_id,+ )+ .fetch_one(&self.pool)+ .await+ }++ #[tracing::instrument(err, skip(self))]+ async fn delete_call(&self, call_id: &Uuid) -> Result<(), Self::Err> {+ sqlx::query!(+ r#"+ DELETE FROM calls WHERE id = $1+ "#,+ call_id,+ )+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ #[tracing::instrument(err, skip(self))]+ async fn set_egress_id(&self, call_id: &Uuid, egress_id: &str) -> Result<(), Self::Err> {+ sqlx::query!(+ r#"+ UPDATE calls SET egress_id = $2 WHERE id = $1+ "#,+ call_id,+ egress_id,+ )+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ #[tracing::instrument(err, skip(self))]+ async fn archive_call(&self, call_id: &Uuid) -> Result<Uuid, Self::Err> {+ let mut tx = self.pool.begin().await?;++ // 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_url+ FROM calls+ WHERE id = $1+ FOR UPDATE+ "#,+ call_id,+ )+ .fetch_optional(tx.as_mut())+ .await?+ .ok_or(sqlx::Error::RowNotFound)?;++ let now = Utc::now();+ let duration_ms = now+ .signed_duration_since(call.created_at)+ .num_milliseconds()+ .max(0);+ let record_id = Uuid::now_v7();++ // Insert into call_records (including egress_id and any early recording_url).+ sqlx::query!(+ r#"+ INSERT INTO call_records (id, channel_id, room_name, created_by, started_at, ended_at, duration_ms, egress_id, recording_url)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)+ "#,+ record_id,+ call.channel_id,+ call.room_name,+ call.created_by,+ call.created_at,+ now,+ duration_ms,+ call.egress_id,+ call.recording_url,+ )+ .execute(tx.as_mut())+ .await?;++ // Copy all participants (including soft-deleted) to call_record_participants.+ sqlx::query!(+ r#"+ INSERT INTO call_record_participants (call_record_id, user_id, joined_at, left_at)+ SELECT $1, user_id, joined_at, left_at+ FROM call_participants+ WHERE call_id = $2+ "#,+ record_id,+ call_id,+ )+ .execute(tx.as_mut())+ .await?;++ // Copy transcripts to call_record_transcripts.+ sqlx::query!(+ r#"+ INSERT INTO call_record_transcripts (call_record_id, segment_id, speaker_id, content, started_at, ended_at, sequence_num)+ SELECT $1, segment_id, speaker_id, content, started_at, ended_at, sequence_num+ FROM call_transcripts+ WHERE call_id = $2+ "#,+ record_id,+ call_id,+ )+ .execute(tx.as_mut())+ .await?;++ // Delete the ephemeral call (cascades to call_participants and call_transcripts).+ sqlx::query!(+ r#"+ DELETE FROM calls WHERE id = $1+ "#,+ call_id,+ )+ .execute(tx.as_mut())+ .await?;++ tx.commit().await?;+ Ok(record_id)+ }++ #[tracing::instrument(err, skip(self))]+ async fn set_recording_url(+ &self,+ call_record_id: &Uuid,+ recording_url: &str,+ ) -> Result<(), Self::Err> {+ sqlx::query!(+ r#"+ UPDATE call_records SET recording_url = $2 WHERE id = $1+ "#,+ call_record_id,+ recording_url,+ )+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_call_record_by_egress_id(+ &self,+ egress_id: &str,+ ) -> Result<Option<Uuid>, Self::Err> {+ sqlx::query_scalar!(+ r#"+ SELECT id FROM call_records WHERE egress_id = $1+ "#,+ egress_id,+ )+ .fetch_optional(&self.pool)+ .await+ }++ #[tracing::instrument(err, skip(self))]+ async fn set_active_call_recording_url(+ &self,+ egress_id: &str,+ recording_url: &str,+ ) -> Result<bool, Self::Err> {+ let result = sqlx::query!(+ r#"+ UPDATE calls SET recording_url = $2 WHERE egress_id = $1+ "#,+ egress_id,+ recording_url,+ )+ .execute(&self.pool)+ .await?;+ Ok(result.rows_affected() > 0)+ }++ #[tracing::instrument(err, skip(self, segment))]+ async fn create_transcript_segment(+ &self,+ call_id: &Uuid,+ segment: &TranscriptSegmentRequest,+ ) -> Result<(), Self::Err> {+ sqlx::query!(+ r#"+ INSERT INTO call_transcripts (call_id, segment_id, speaker_id, content, started_at, ended_at, sequence_num)+ VALUES ($1, $2, $3, $4, $5, $6, (+ SELECT COALESCE(MAX(sequence_num), 0) + 1+ FROM call_transcripts+ WHERE call_id = $1+ ))+ ON CONFLICT (call_id, segment_id) DO NOTHING+ "#,+ call_id,+ segment.segment_id,+ segment.speaker_id,+ segment.content,+ segment.started_at,+ segment.ended_at,+ )+ .execute(&self.pool)+ .await?;+ Ok(())+ }+}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.rsnew file mode 100644index 0000000000..cb341198b1--- /dev/null+++ b/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rs@@ -0,0 +1,453 @@+use crate::domain::models::TranscriptSegmentRequest;+use crate::domain::ports::CallRepository;+use crate::outbound::pg_call_repo::PgCallRepo;+use chrono::Utc;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::{Pool, Postgres};+use uuid::Uuid;++const CH1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000c01);+const CH2: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000c02);+const CALL1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_0000000ca110);+const USER_A: &str = "macro|[email protected]";+const USER_B: &str = "macro|[email protected]";+const USER_C: &str = "macro|[email protected]";++fn repo(pool: Pool<Postgres>) -> PgCallRepo {+ PgCallRepo::new(pool)+}++// -- create_call --------------------------------------------------------------++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn create_call_returns_call(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ let id = Uuid::now_v7();+ let call = repo+ .create_call(&id, &CH2, "room-ch2", USER_B)+ .await?+ .expect("should create new call");++ assert_eq!(call.id, id);+ assert_eq!(call.channel_id, CH2);+ assert_eq!(call.room_name, "room-ch2");+ assert_eq!(call.created_by, USER_B);+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn create_call_returns_none_on_duplicate_channel(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ // CH1 already has an active call from the fixture.+ let result = repo+ .create_call(&Uuid::now_v7(), &CH1, "room-dup", USER_A)+ .await?;++ assert!(result.is_none(), "should return None on conflict");+ Ok(())+}++// -- get_call_by_channel_id ---------------------------------------------------++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn get_call_by_channel_id_found(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ let call = repo.get_call_by_channel_id(&CH1).await?;++ let call = call.expect("call should exist for ch1");+ assert_eq!(call.id, CALL1);+ assert_eq!(call.channel_id, CH1);+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn get_call_by_channel_id_not_found(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ let call = repo.get_call_by_channel_id(&CH2).await?;++ assert!(call.is_none(), "ch2 has no active call");+ Ok(())+}++// -- get_call_by_room_name ----------------------------------------------------++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn get_call_by_room_name_found(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ let call = repo+ .get_call_by_room_name("00000000-0000-0000-0000-000000000c01")+ .await?;++ let call = call.expect("call should exist for room name");+ assert_eq!(call.id, CALL1);+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn get_call_by_room_name_not_found(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ let call = repo.get_call_by_room_name("nonexistent-room").await?;++ assert!(call.is_none());+ Ok(())+}++// -- add_participant / remove_participant / is_participant ---------------------++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn add_and_check_participant(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);++ // user-c is not in the call yet.+ assert!(!repo.is_participant(&CALL1, USER_C).await?);++ let participant = repo.add_participant(&CALL1, USER_C).await?;+ assert_eq!(participant.call_id, CALL1);+ assert_eq!(participant.user_id, USER_C);++ assert!(repo.is_participant(&CALL1, USER_C).await?);+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn remove_participant_removes_from_db(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);++ assert!(repo.is_participant(&CALL1, USER_B).await?);+ repo.remove_participant(&CALL1, USER_B).await?;+ assert!(!repo.is_participant(&CALL1, USER_B).await?);+ Ok(())+}++// -- get_participants ---------------------------------------------------------++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn get_participants_returns_all(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ let participants = repo.get_participants(&CALL1).await?;++ assert_eq!(participants.len(), 2);+ let user_ids: Vec<&str> = participants.iter().map(|p| p.user_id.as_str()).collect();+ assert!(user_ids.contains(&USER_A));+ assert!(user_ids.contains(&USER_B));+ Ok(())+}++// -- get_participant_count ----------------------------------------------------++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn get_participant_count_correct(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);++ assert_eq!(repo.get_participant_count(&CALL1).await?, 2);++ repo.remove_participant(&CALL1, USER_B).await?;+ assert_eq!(repo.get_participant_count(&CALL1).await?, 1);+ Ok(())+}++// -- delete_call --------------------------------------------------------------++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn delete_call_cascades_to_participants(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);++ repo.delete_call(&CALL1).await?;++ assert!(repo.get_call_by_channel_id(&CH1).await?.is_none());+ // Participants should be cascade-deleted.+ assert_eq!(repo.get_participant_count(&CALL1).await?, 0);+ Ok(())+}++// -- archive_call -------------------------------------------------------------++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn archive_call_creates_record_and_deletes_ephemeral(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool.clone());++ let record_id = repo.archive_call(&CALL1).await?;++ // Ephemeral call should be gone.+ assert!(repo.get_call_by_channel_id(&CH1).await?.is_none());+ assert_eq!(repo.get_participant_count(&CALL1).await?, 0);++ // call_records should have the archived call.+ let record = sqlx::query!(+ r#"+ SELECT id, channel_id, room_name, created_by, started_at, ended_at, duration_ms+ FROM call_records+ WHERE id = $1+ "#,+ record_id,+ )+ .fetch_one(&pool)+ .await?;++ assert_eq!(record.channel_id, CH1);+ assert_eq!(record.created_by, USER_A);+ assert!(record.duration_ms >= 0);+ assert!(record.ended_at >= record.started_at);++ // call_record_participants should have both participants.+ let participants = sqlx::query_scalar!(+ r#"+ SELECT user_id+ FROM call_record_participants+ WHERE call_record_id = $1+ ORDER BY joined_at ASC+ "#,+ record_id,+ )+ .fetch_all(&pool)+ .await?;++ assert_eq!(participants.len(), 2);+ assert!(participants.contains(&USER_A.to_string()));+ assert!(participants.contains(&USER_B.to_string()));+ Ok(())+}++// -- archive preserves soft-deleted participants ------------------------------++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn archive_call_preserves_soft_deleted_participants(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool.clone());++ // Soft-delete both participants (simulates leave_or_end_call flow).+ repo.remove_participant(&CALL1, USER_A).await?;+ repo.remove_participant(&CALL1, USER_B).await?;++ // Active count should be 0 but rows still exist.+ assert_eq!(repo.get_participant_count(&CALL1).await?, 0);++ // Archive the call.+ let record_id = repo.archive_call(&CALL1).await?;++ // call_record_participants should have both participants with left_at set.+ let rows = sqlx::query!(+ r#"+ SELECT user_id, left_at+ FROM call_record_participants+ WHERE call_record_id = $1+ ORDER BY joined_at ASC+ "#,+ record_id,+ )+ .fetch_all(&pool)+ .await?;++ assert_eq!(rows.len(), 2);+ let user_ids: Vec<&str> = rows.iter().map(|r| r.user_id.as_str()).collect();+ assert!(user_ids.contains(&USER_A));+ assert!(user_ids.contains(&USER_B));+ // Both should have left_at set since they were soft-deleted.+ assert!(rows.iter().all(|r| r.left_at.is_some()));++ Ok(())+}++// -- set_active_call_recording_url --------------------------------------------++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn set_active_call_recording_url_updates_matching_call(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool.clone());++ // Set egress_id on the fixture call first.+ repo.set_egress_id(&CALL1, "egress-123").await?;++ // Should update and return true.+ let updated = repo+ .set_active_call_recording_url("egress-123", "s3://bucket/recording.mp4")+ .await?;+ assert!(updated);++ // Verify the URL 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_url carries forward.+ let record_id = repo.archive_call(&CALL1).await?;+ let url = sqlx::query_scalar!(+ r#"SELECT recording_url FROM call_records WHERE id = $1"#,+ record_id,+ )+ .fetch_one(&pool)+ .await?;+ assert_eq!(url.as_deref(), Some("s3://bucket/recording.mp4"));++ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn set_active_call_recording_url_returns_false_when_no_match(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool);++ let updated = repo+ .set_active_call_recording_url("nonexistent-egress", "s3://bucket/recording.mp4")+ .await?;+ assert!(!updated);++ Ok(())+}++// -- create_transcript_segment ------------------------------------------------++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn create_transcript_segment_stores_and_increments_sequence(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool.clone());+ let now = Utc::now();++ let seg1 = TranscriptSegmentRequest {+ segment_id: "seg-001".to_string(),+ speaker_id: USER_A.to_string(),+ content: "hello world".to_string(),+ started_at: now,+ ended_at: Some(now),+ is_final: true,+ };+ let seg2 = TranscriptSegmentRequest {+ segment_id: "seg-002".to_string(),+ speaker_id: USER_B.to_string(),+ content: "hi there".to_string(),+ started_at: now,+ ended_at: Some(now),+ is_final: true,+ };++ repo.create_transcript_segment(&CALL1, &seg1).await?;+ repo.create_transcript_segment(&CALL1, &seg2).await?;++ // Duplicate segment_id should be ignored.+ repo.create_transcript_segment(&CALL1, &seg1).await?;++ let rows = sqlx::query!(+ r#"+ SELECT speaker_id, content, sequence_num+ FROM call_transcripts+ WHERE call_id = $1+ ORDER BY sequence_num ASC+ "#,+ CALL1,+ )+ .fetch_all(&pool)+ .await?;++ assert_eq!(rows.len(), 2);+ assert_eq!(rows[0].content, "hello world");+ assert_eq!(rows[0].sequence_num, 1);+ assert_eq!(rows[1].content, "hi there");+ assert_eq!(rows[1].sequence_num, 2);+ Ok(())+}++// -- archive_call copies transcripts ------------------------------------------++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn archive_call_copies_transcripts(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool.clone());+ let now = Utc::now();++ // Add a transcript segment to the active call.+ let seg = TranscriptSegmentRequest {+ segment_id: "seg-archive-001".to_string(),+ speaker_id: USER_A.to_string(),+ content: "test transcript".to_string(),+ started_at: now,+ ended_at: Some(now),+ is_final: true,+ };+ repo.create_transcript_segment(&CALL1, &seg).await?;++ // Archive the call.+ let record_id = repo.archive_call(&CALL1).await?;++ // Transcripts should be in call_record_transcripts.+ let transcripts = sqlx::query!(+ r#"+ SELECT speaker_id, content, sequence_num+ FROM call_record_transcripts+ WHERE call_record_id = $1+ "#,+ record_id,+ )+ .fetch_all(&pool)+ .await?;++ assert_eq!(transcripts.len(), 1);+ assert_eq!(transcripts[0].content, "test transcript");+ assert_eq!(transcripts[0].speaker_id, USER_A);+ assert_eq!(transcripts[0].sequence_num, 1);++ // Ephemeral transcripts should be gone (cascaded).+ let ephemeral = sqlx::query_scalar!(+ r#"SELECT COUNT(*) as "count!" FROM call_transcripts WHERE call_id = $1"#,+ CALL1,+ )+ .fetch_one(&pool)+ .await?;+ assert_eq!(ephemeral, 0);++ Ok(())+}diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.tomlindex cd3e5fbdcf..51eb719b82 100644--- a/rust/cloud-storage/document_storage_service/Cargo.toml+++ b/rust/cloud-storage/document_storage_service/Cargo.toml@@ -41,6 +41,7 @@ bytes = { workspace = true }bzip2 = { workspace = true, default-features = false, features = ["libbz2-rs-sys",] }+call = { path = "../call" }channels = { path = "../channels", features = ["inbound", "outbound"] }chrono = { workspace = true }clap = { workspace = true }diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex b4283d08f9..fb6affa7c8 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -1,5 +1,10 @@use crate::{config::Config, service::s3::S3};use axum::extract::FromRef;+use call::{+ domain::service::CallServiceImpl,+ inbound::axum_router::{CallRouterState, WebhookRouterState},+ outbound::{livekit_rtc_client::LivekitRtcClient, pg_call_repo::PgCallRepo},+};use channels::{domain::service::ChannelMessagesServiceImpl, inbound::axum_router::ChannelsRouterState,outbound::pg_channels_repo::PgChannelMessagesRepo,@@ -154,6 +159,15 @@ pub(crate) type CommsState = CommsRouterState<CommsChannelService>;pub(crate) type DssChannelsState =ChannelsRouterState<ChannelMessagesServiceImpl<PgChannelMessagesRepo>, EntityAccessService>;+/// Type alias for the call service.+pub(crate) type DssCallService = CallServiceImpl<PgCallRepo, LivekitRtcClient>;++/// Type alias for the call router state.+pub(crate) type DssCallState = CallRouterState<DssCallService, EntityAccessService>;++/// Type alias for the call webhook router state.+pub(crate) type DssCallWebhookState = WebhookRouterState<DssCallService>;+/// Type alias for the github sync service.pub(crate) type GithubSyncServiceType =GithubSyncServiceImpl<DocumentService, PgGithubSyncRepo, GithubSyncClientImpl>;@@ -185,6 +199,8 @@ pub(crate) struct ApiContext {pub entity_access_service: Arc<EntityAccessService>,pub documents_state: DocumentsState,pub channels_state: DssChannelsState,+ pub call_state: DssCallState,+ pub call_webhook_state: DssCallWebhookState,}env_var! {diff --git a/rust/cloud-storage/document_storage_service/src/api/mod.rs b/rust/cloud-storage/document_storage_service/src/api/mod.rsindex ec5a1c91fe..1065eb5f1a 100644--- a/rust/cloud-storage/document_storage_service/src/api/mod.rs+++ b/rust/cloud-storage/document_storage_service/src/api/mod.rs@@ -93,6 +93,12 @@ fn api_router(state: ApiContext) -> Router {service: state.github_sync_service.clone(),};+ // Webhook router is outside auth — LiveKit validates via its own JWT.+ let webhook_router = Router::new().nest(+ "/call",+ call::inbound::axum_router::webhook_router(state.call_webhook_state.clone()),+ );+let internal_router = Router::new().nest("/github",@@ -186,6 +192,10 @@ fn api_router(state: ApiContext) -> Router {"/channels",channels::inbound::axum_router::channels_router(state.channels_state.clone()),)+ .nest(+ "/call",+ call::inbound::axum_router::call_router(state.call_state.clone()),+ ).layer(ServiceBuilder::new().layer(axum::middleware::from_fn(@@ -243,4 +253,5 @@ fn api_router(state: ApiContext) -> Router {Router::new().nest("/{version}", internal_router.clone()).merge(internal_router)+ .merge(webhook_router)}diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rsindex eb2515c9da..ea4f5ed5d0 100644--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs@@ -191,6 +191,12 @@ use utoipa::OpenApi;channels::inbound::axum_router::get_channel_attachments_handler,channels::inbound::axum_router::get_channel_participants_handler,+ // calls+ call::inbound::axum_router::get_or_create_call_handler,+ call::inbound::axum_router::leave_or_end_call_handler,+ call::inbound::axum_router::webhook_handler,+ call::inbound::axum_router::transcript_handler,+// pinspins::add_pin::add_pin_handler,pins::remove_pin::remove_pin_handler,@@ -327,6 +333,11 @@ use utoipa::OpenApi;ApiChannelParticipant,ApiParticipantRole,+ // Calls+ call::domain::models::CallTokenResponse,+ call::domain::models::LeaveCallResponse,+ call::domain::models::TranscriptSegmentRequest,+DocumentSubType,diff --git a/rust/cloud-storage/document_storage_service/src/config.rs b/rust/cloud-storage/document_storage_service/src/config.rsindex f74e49809f..52c3004659 100644--- a/rust/cloud-storage/document_storage_service/src/config.rs+++ b/rust/cloud-storage/document_storage_service/src/config.rs@@ -61,6 +61,9 @@ env_var! {pub ContactsQueue,pub GithubSyncAppUrl,pub GithubSyncAppClientId,+ pub LivekitServerUrl,+ pub LivekitApiKey,+ pub LivekitApiSecret,}}diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex b18f85ff71..3e27646d2d 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -8,6 +8,11 @@ use crate::{service::s3::S3,};use anyhow::Context;+use call::{+ domain::service::CallServiceImpl,+ inbound::axum_router::{CallRouterState, WebhookRouterState},+ outbound::{livekit_rtc_client::LivekitRtcClient, pg_call_repo::PgCallRepo},+};use channels::{domain::service::ChannelMessagesServiceImpl, inbound::axum_router::ChannelsRouterState,outbound::pg_channels_repo::PgChannelMessagesRepo,@@ -347,6 +352,21 @@ async fn main() -> anyhow::Result<()> {GithubSyncClientImpl::default(),);+ // Call service (LiveKit)+ let livekit_rtc_client = LivekitRtcClient::new(+ config.vars.livekit_server_url.as_ref(),+ config.vars.livekit_api_key.as_ref(),+ config.vars.livekit_api_secret.as_ref(),+ );+ let call_repo = PgCallRepo::new(db.clone());+ let call_service = Arc::new(CallServiceImpl::new(+ call_repo,+ livekit_rtc_client,+ config.vars.livekit_server_url.as_ref(),+ ));+ let call_state = CallRouterState::new(call_service.clone(), entity_access_service.clone());+ let call_webhook_state = WebhookRouterState::new(call_service.clone());+// Create the SQS worker for delete document processing before config is movedlet delete_document_worker = sqs_worker::SQSWorker::new(aws_sdk_sqs::Client::new(&aws_config),@@ -395,6 +415,8 @@ async fn main() -> anyhow::Result<()> {ChannelMessagesServiceImpl::new(PgChannelMessagesRepo::new(db.clone())),(*entity_access_service).clone(),),+ call_state,+ call_webhook_state,};// Spawn the delete document workerdiff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfileindex 888cb7a271..bc95127508 100644--- a/rust/cloud-storage/justfile+++ b/rust/cloud-storage/justfile@@ -88,6 +88,7 @@ setup_test_envs:echo "DATABASE_URL={{ MACRODB }}" >> ./referral/.envecho "DATABASE_URL={{ MACRODB }}" >> ./chat/.envecho "DATABASE_URL={{ MACRODB }}" >> ./memory/.env+ echo "DATABASE_URL={{ MACRODB }}" >> ./call/.envsetup_macrodb:just macro_db_client/create_dbdiff --git a/rust/cloud-storage/macro_db_client/migrations/20260331170640_add_call_tables.sql b/rust/cloud-storage/macro_db_client/migrations/20260331170640_add_call_tables.sqlnew file mode 100644index 0000000000..5c282b4c21--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260331170640_add_call_tables.sql@@ -0,0 +1,74 @@+-- Ephemeral tables for active calls (rows deleted when call ends via webhook)++CREATE TABLE IF NOT EXISTS calls (+ id UUID PRIMARY KEY,+ channel_id UUID NOT NULL REFERENCES comms_channels(id) ON DELETE CASCADE,+ room_name TEXT NOT NULL,+ created_by TEXT NOT NULL,+ egress_id TEXT,+ recording_url TEXT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ CONSTRAINT calls_one_per_channel UNIQUE (channel_id)+);++CREATE TABLE IF NOT EXISTS call_participants (+ call_id UUID NOT NULL REFERENCES calls(id) ON DELETE CASCADE,+ user_id TEXT NOT NULL,+ joined_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ left_at TIMESTAMPTZ,+ PRIMARY KEY (call_id, user_id)+);++-- Ephemeral transcript segments for active calls (copied to call_record_transcripts on archive)++CREATE TABLE IF NOT EXISTS call_transcripts (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ call_id UUID NOT NULL REFERENCES calls(id) ON DELETE CASCADE,+ segment_id TEXT NOT NULL,+ speaker_id TEXT NOT NULL,+ content TEXT NOT NULL,+ started_at TIMESTAMPTZ NOT NULL,+ ended_at TIMESTAMPTZ,+ sequence_num INT NOT NULL,+ CONSTRAINT call_transcripts_segment_unique UNIQUE (call_id, segment_id)+);++-- Permanent tables for call history (written on room_finished webhook)++CREATE TABLE IF NOT EXISTS call_records (+ id UUID PRIMARY KEY,+ channel_id UUID NOT NULL REFERENCES comms_channels(id) ON DELETE CASCADE,+ room_name TEXT NOT NULL,+ created_by TEXT NOT NULL,+ started_at TIMESTAMPTZ NOT NULL,+ ended_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ duration_ms BIGINT NOT NULL,+ recording_url TEXT,+ egress_id TEXT+);++CREATE TABLE IF NOT EXISTS call_record_participants (+ call_record_id UUID NOT NULL REFERENCES call_records(id) ON DELETE CASCADE,+ user_id TEXT NOT NULL,+ joined_at TIMESTAMPTZ NOT NULL,+ left_at TIMESTAMPTZ,+ PRIMARY KEY (call_record_id, user_id)+);++CREATE TABLE IF NOT EXISTS call_record_transcripts (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ call_record_id UUID NOT NULL REFERENCES call_records(id) ON DELETE CASCADE,+ segment_id TEXT,+ speaker_id TEXT NOT NULL,+ content TEXT NOT NULL,+ started_at TIMESTAMPTZ NOT NULL,+ ended_at TIMESTAMPTZ,+ sequence_num INT NOT NULL+);++CREATE INDEX IF NOT EXISTS idx_calls_channel_id ON calls(channel_id);+CREATE INDEX IF NOT EXISTS idx_calls_room_name ON calls(room_name);+CREATE INDEX IF NOT EXISTS idx_call_transcripts_call_id ON call_transcripts(call_id);+CREATE INDEX IF NOT EXISTS idx_call_records_channel_id ON call_records(channel_id);+CREATE INDEX IF NOT EXISTS idx_call_records_egress_id ON call_records(egress_id);+CREATE INDEX IF NOT EXISTS idx_call_record_transcripts_call_record_id ON call_record_transcripts(call_record_id);