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
fix(calendar): show a new join request in an open request list (#9267)
gbirman426b009f6f16
diff --git a/Cargo.lock b/Cargo.lockindex e73d46e177..48b96ae220 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -6583,6 +6583,7 @@ dependencies = ["macro_config","macro_cors","macro_db_client",+ "macro_db_migrator","macro_entrypoint","macro_env","macro_env_var",@@ -6669,6 +6670,7 @@ dependencies = ["uuid","webhook","whatsapp_linked",+ "wiremock","work_feed","workspace-hack","zip 9.0.5",diff --git a/crates/calendar_events/AGENTS.md b/crates/calendar_events/AGENTS.mdindex b454f14634..bb48684224 100644--- a/crates/calendar_events/AGENTS.md+++ b/crates/calendar_events/AGENTS.md@@ -218,6 +218,18 @@ reminder dispatch, team availability, and provider/Postgres persistence.unchanged and stays quiet; the client reads a status other than its decisionas already answered. Only an acceptance whose invitation is being writtenoverrules a decline (`resolve_join_request`), and it returns `accepted`.+ A new request reaches open lists the same way: `request_to_join` sends+ `calendar_changed` for the inbox of the sharer's copy once the row is stored,+ and only when this ask created it, so a repeat or a refused ask stays quiet.+ Each inbox holds its own entity, so however many of its calendars hold the+ event there is one list and one nudge, and another inbox's copy has its own+ list. The signal names that inbox, so it goes only to the list's readers;+ the requester is never one, since a reader's own view of the event is+ `OwnCopy`, which refuses the ask. The web also refetches the list when the+ sharer's notification lands, but that is not the signal: it reaches no+ delegate, a muted category never sends it, and the notifier only queues.+ `document_storage_service` hosts the ask, so it has its own+ `CalendarRefreshNotifier` (`src/outbound/calendar_refresh.rs`).- Calendar mentions reach the agent as document mentions (`blockName``calendar`), but `ReadContent` and `ReadMetadata` need document access, whicha channel-shared event never grants. The agent reads a mentioned event withdiff --git a/crates/calendar_events/src/domain/join_requests.rs b/crates/calendar_events/src/domain/join_requests.rsindex 886689acd9..018eb9c2f8 100644--- a/crates/calendar_events/src/domain/join_requests.rs+++ b/crates/calendar_events/src/domain/join_requests.rs@@ -18,7 +18,7 @@ use super::{mutations::invite::copy_capabilities,ports::{CalendarJoinRequestError, CalendarJoinRequestNotifier, CalendarJoinRequestService,- CalendarRepository,+ CalendarRefreshNotifier, CalendarRepository,},};@@ -91,6 +91,10 @@ pub enum JoinEligibility {Eligible {/// Owner of the shared event, who answers the request.sharer_id: String,+ /// Inbox of the sharer's copy. Each inbox holds its own copy of a+ /// meeting, so this one inbox's owner and delegates read the+ /// requests, however many of its calendars hold the event.+ sharer_link_id: Uuid,/// Event title, for the sharer's notification.title: String,},@@ -123,6 +127,7 @@ pub async fn join_eligibility<R: CalendarRepository>(}Ok(JoinEligibility::Eligible {sharer_id: shared.owner_id,+ sharer_link_id: target.email_link_id,title: shared.title,})}@@ -162,21 +167,24 @@ pub async fn annotate_join_state<R: CalendarRepository>(}/// Join-request use cases with persistence and delivery behind ports.-pub struct CalendarJoinRequestServiceImpl<R, N> {+pub struct CalendarJoinRequestServiceImpl<R, N, F> {repository: R,notifier: N,+ refresh: F,}-impl<R, N> CalendarJoinRequestServiceImpl<R, N>+impl<R, N, F> CalendarJoinRequestServiceImpl<R, N, F>whereR: CalendarRepository,N: CalendarJoinRequestNotifier,+ F: CalendarRefreshNotifier,{/// Construct the service from its ports.- pub fn new(repository: R, notifier: N) -> Self {+ pub fn new(repository: R, notifier: N, refresh: F) -> Self {Self {repository,notifier,+ refresh,}}@@ -185,10 +193,10 @@ whererequester_id: &str,event_id: Uuid,) -> Result<(CalendarJoinRequest, bool), CalendarJoinRequestError> {- let (sharer_id, title) = match join_eligibility(&self.repository, requester_id, event_id)+ let eligibility = join_eligibility(&self.repository, requester_id, event_id).await- .map_err(CalendarJoinRequestError::Internal)?- {+ .map_err(CalendarJoinRequestError::Internal)?;+ let (sharer_id, sharer_link_id, title) = match eligibility {JoinEligibility::NotVisible => return Err(CalendarJoinRequestError::NotFound),JoinEligibility::OwnCopy => {return Err(CalendarJoinRequestError::AlreadyOnCalendar);@@ -196,7 +204,11 @@ whereJoinEligibility::SharerCannotInvite => {return Err(CalendarJoinRequestError::SharerCannotInvite);}- JoinEligibility::Eligible { sharer_id, title } => (sharer_id, title),+ JoinEligibility::Eligible {+ sharer_id,+ sharer_link_id,+ title,+ } => (sharer_id, sharer_link_id, title),};// Invite the inbox whose calendar Macro syncs, the one an added copy// would land on, so the mention resolves to the invitation.@@ -218,6 +230,12 @@ wherereturn Err(CalendarJoinRequestError::Declined);}if opened {+ // The request is stored, so a refetch finds it. The signal names+ // the sharer's inbox, so it goes to that inbox's viewers and+ // never to the requester, who reads no list.+ self.refresh+ .calendar_changed(&sharer_id, sharer_link_id, false)+ .await;self.notifier.notify_join_request(&sharer_id, &request, &title).await;@@ -232,10 +250,11 @@ fn account_email(requester_id: &str) -> &str {requester_id.strip_prefix("macro|").unwrap_or(requester_id)}-impl<R, N> CalendarJoinRequestService for CalendarJoinRequestServiceImpl<R, N>+impl<R, N, F> CalendarJoinRequestService for CalendarJoinRequestServiceImpl<R, N, F>whereR: CalendarRepository,N: CalendarJoinRequestNotifier,+ F: CalendarRefreshNotifier,{#[tracing::instrument(name = "calendar.request_to_join",diff --git a/crates/calendar_events/src/domain/mutations/test/join.rs b/crates/calendar_events/src/domain/mutations/test/join.rsindex b8d5a2ec9b..c61c1e2308 100644--- a/crates/calendar_events/src/domain/mutations/test/join.rs+++ b/crates/calendar_events/src/domain/mutations/test/join.rs@@ -83,16 +83,31 @@ fn sharer_organizes() -> FakeRepo {}}-fn asking(+type TestJoinRequestService =+ CalendarJoinRequestServiceImpl<FakeRepo, RecordingNotifier, RecordingRefreshNotifier>;++fn asking(repo: FakeRepo) -> (TestJoinRequestService, RecordingNotifier) {+ let (service, notifier, _) = asking_with_refresh(repo);+ (service, notifier)+}++/// The service with a refresh notifier that watches `repo`'s stored requests.+fn asking_with_refresh(repo: FakeRepo,) -> (- CalendarJoinRequestServiceImpl<FakeRepo, RecordingNotifier>,+ TestJoinRequestService,RecordingNotifier,+ RecordingRefreshNotifier,) {let notifier = RecordingNotifier::default();+ let refresh = RecordingRefreshNotifier {+ join_requests: repo.join_requests.clone(),+ ..RecordingRefreshNotifier::default()+ };(- CalendarJoinRequestServiceImpl::new(repo, notifier.clone()),+ CalendarJoinRequestServiceImpl::new(repo, notifier.clone(), refresh.clone()),notifier,+ refresh,)}@@ -143,6 +158,87 @@ async fn a_channel_member_asks_the_sharer_only_once() {);}+#[tokio::test]+async fn a_new_request_refreshes_the_lists_readers_once_it_is_stored() {+ let (service, _, refresh) = asking_with_refresh(sharer_organizes());++ service+ .request_to_join(MEMBER, Uuid::now_v7())+ .await+ .unwrap();++ assert_eq!(+ refresh.notified.lock().unwrap().as_slice(),+ [(SHARER.to_string(), SELF_LINK, false)]+ );+ // The nudge saw the stored request, so a refetch finds it.+ assert_eq!(+ refresh.seen_statuses.lock().unwrap().as_slice(),+ [CalendarJoinRequestStatus::Pending]+ );+ // The requester reads no list and is told nothing about the sharer's inbox.+ assert!(refresh.answered_requesters.lock().unwrap().is_empty());+}++#[tokio::test]+async fn only_the_first_ask_refreshes_the_list() {+ for status in [+ CalendarJoinRequestStatus::Pending,+ CalendarJoinRequestStatus::Accepted,+ CalendarJoinRequestStatus::Declined,+ ] {+ let repo = sharer_organizes();+ let request = pending_request(&repo, status);+ let (service, _, refresh) = asking_with_refresh(repo);++ let result = service.request_to_join(MEMBER, request.event_id).await;++ assert_eq!(+ result.is_err(),+ status == CalendarJoinRequestStatus::Declined,+ "{status:?}"+ );+ assert!(refresh.notified.lock().unwrap().is_empty(), "{status:?}");+ }+}++#[tokio::test]+async fn a_refused_ask_refreshes_nothing() {+ let not_shared = FakeRepo {+ export: None,+ ..sharer_organizes()+ };+ let own_copy = FakeRepo {+ export: Some(shared_export(CalendarEventExportAccess::OwnCopy)),+ ..sharer_organizes()+ };+ let cannot_invite = sharer_as_guest(GuestPolicy {+ can_invite_others: false,+ ..GuestPolicy::default()+ });+ let read_only = FakeRepo {+ mutation_target: Some(mutation_target(true)),+ ..sharer_organizes()+ };+ for (repo, case) in [+ (not_shared, "not shared with the requester"),+ (own_copy, "already on the requester's calendar"),+ (cannot_invite, "the sharer may not add guests"),+ (read_only, "the sharer's calendar is read-only"),+ ] {+ let (service, _, refresh) = asking_with_refresh(repo);++ assert!(+ service+ .request_to_join(MEMBER, Uuid::now_v7())+ .await+ .is_err(),+ "{case}"+ );+ assert!(refresh.notified.lock().unwrap().is_empty(), "{case}");+ }+}+#[tokio::test]async fn a_member_without_a_calendar_is_invited_at_their_account_address() {let (service, _) = asking(FakeRepo {diff --git a/crates/calendar_events/src/domain/ports.rs b/crates/calendar_events/src/domain/ports.rsindex 7d91f4fbe9..e3b615aad9 100644--- a/crates/calendar_events/src/domain/ports.rs+++ b/crates/calendar_events/src/domain/ports.rs@@ -942,10 +942,10 @@ pub enum CalendarJoinRequestError {/// and for sharers reading the requests on their events.pub trait CalendarJoinRequestService: Send + Sync + 'static {/// Ask the person who shared an event with one of the requester's- /// channels to add them as a guest, notifying them when the request- /// becomes pending. Asking again while pending changes nothing; asking- /// after a decline is refused with `Declined`, so the sharer is asked- /// only once.+ /// channels to add them as a guest. When the request becomes pending this+ /// notifies them and refreshes the open request lists of their inbox's+ /// viewers. Asking again while pending changes nothing; asking after a+ /// decline is refused with `Declined`, so the sharer is asked only once.fn request_to_join(&self,requester_id: &str,diff --git a/crates/calendar_events/src/outbound/pg/test/join_requests.rs b/crates/calendar_events/src/outbound/pg/test/join_requests.rsindex 4e97f48100..f4a0d6574d 100644--- a/crates/calendar_events/src/outbound/pg/test/join_requests.rs+++ b/crates/calendar_events/src/outbound/pg/test/join_requests.rs@@ -1,6 +1,155 @@use super::*;-use crate::domain::join_requests::{CalendarJoinRequest, CalendarJoinRequestStatus};+use crate::domain::join_requests::{+ CalendarJoinRequest, CalendarJoinRequestServiceImpl, CalendarJoinRequestStatus,+};+use crate::domain::ports::{+ CalendarJoinRequestError, CalendarJoinRequestNotifier, CalendarJoinRequestService,+ CalendarRefreshNotifier,+};use sqlx::postgres::PgListener;+use std::sync::{Arc, Mutex};++struct NoNotification;++impl CalendarJoinRequestNotifier for NoNotification {+ async fn notify_join_request(&self, _: &str, _: &CalendarJoinRequest, _: &str) {}+}++/// Records each nudge with the requests its readers would refetch right then.+#[derive(Clone)]+struct ListReadingRefresh {+ repo: PgCalendarRepository,+ event_id: Uuid,+ nudges: Arc<Mutex<Vec<(String, Uuid, usize)>>>,+}++impl CalendarRefreshNotifier for ListReadingRefresh {+ async fn calendar_changed(&self, owner_id: &str, email_link_id: Uuid, _: bool) {+ let listed = self+ .repo+ .list_pending_join_requests(self.event_id)+ .await+ .unwrap()+ .len();+ self.nudges+ .lock()+ .unwrap()+ .push((owner_id.to_string(), email_link_id, listed));+ }++ async fn join_request_answered(&self, _: &str, _: Uuid) {+ unreachable!("asking answers nothing");+ }+}++/// The sharer's copy of the meeting on `provider`'s calendar: no guests, so+/// they may add one.+fn sharer_copy(link_id: Uuid, provider: (Uuid, Uuid)) -> CalendarEventUpsert {+ let mut copy = timed_upsert(+ "macro|[email protected]",+ link_id,+ provider,+ "[email protected]",+ "Offsite",+ 1,+ );+ copy.event.is_read_only = false;+ copy.event.attendees.clear();+ copy+}++async fn delegate(pool: &PgPool, primary: &str, child: &str, link_id: Uuid) {+ sqlx::query!(+ "INSERT INTO macro_user_links (primary_macro_id, child_macro_id, link_id) VALUES ($1, $2, $3)",+ primary,+ child,+ link_id,+ )+ .execute(pool)+ .await+ .unwrap();+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_new_request_reaches_the_inbox_holding_the_shared_copy_once(pool: PgPool) {+ let sharer_id = "macro|[email protected]";+ let member_id = "macro|[email protected]";+ let delegate_id = "macro|[email protected]";+ let mailbox_id = "macro|[email protected]";+ let other_delegate_id = "macro|[email protected]";+ for user in [+ sharer_id,+ member_id,+ delegate_id,+ mailbox_id,+ other_delegate_id,+ ] {+ insert_user(&pool, user).await;+ }+ let repo = PgCalendarRepository::new(pool.clone());++ // Two calendars of one inbox hold the meeting: one entity, one inbox.+ let shared_link = insert_link(&pool, sharer_id).await;+ let primary = provider_ids(&repo, shared_link).await;+ let secondary = insert_shared_calendar(&repo, primary.0, "owner", &[]).await;+ let event_id = repo+ .upsert_event_fixture(sharer_copy(shared_link, primary))+ .await+ .unwrap();+ let on_secondary = repo+ .upsert_event_fixture(sharer_copy(shared_link, (primary.0, secondary)))+ .await+ .unwrap();+ assert_eq!(on_secondary, event_id);+ delegate(&pool, delegate_id, mailbox_id, shared_link).await;++ // Their other inbox holds the same meeting as its own entity and list.+ let other_link = insert_link(&pool, sharer_id).await;+ let other_provider = provider_ids(&repo, other_link).await;+ let other_copy = repo+ .upsert_event_fixture(sharer_copy(other_link, other_provider))+ .await+ .unwrap();+ assert_ne!(other_copy, event_id);+ delegate(&pool, other_delegate_id, mailbox_id, other_link).await;++ let channel_id = insert_channel(&pool, sharer_id, &[sharer_id, member_id]).await;+ share_with_channel(&pool, event_id, channel_id).await;++ let refresh = ListReadingRefresh {+ repo: repo.clone(),+ event_id,+ nudges: Arc::default(),+ };+ let service = CalendarJoinRequestServiceImpl::new(repo, NoNotification, refresh.clone());++ let request = service.request_to_join(member_id, event_id).await.unwrap();++ assert_eq!(+ refresh.nudges.lock().unwrap().as_slice(),+ [(sharer_id.to_string(), shared_link, 1)]+ );+ for reader in [sharer_id, delegate_id] {+ assert_eq!(+ service.list_join_requests(reader, event_id).await.unwrap(),+ std::slice::from_ref(&request),+ "{reader}"+ );+ }+ // Those two are the list's only readers.+ for outsider in [other_delegate_id, member_id] {+ assert!(+ matches!(+ service.list_join_requests(outsider, event_id).await,+ Err(CalendarJoinRequestError::NotFound)+ ),+ "{outsider}"+ );+ }++ service.request_to_join(member_id, event_id).await.unwrap();+ assert_eq!(refresh.nudges.lock().unwrap().len(), 1);+}#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn join_requests_open_once_and_resolve_once(pool: PgPool) {diff --git a/docs/agent-guide/calendar.md b/docs/agent-guide/calendar.mdindex 6126f2cb0a..5707ba83f4 100644--- a/docs/agent-guide/calendar.md+++ b/docs/agent-guide/calendar.md@@ -882,7 +882,8 @@ says `You've asked to join this event` and refreshes to `Requested` or `Invited`notification (Settings → Notifications → Calendar → Requests to join), which Home lists as`<requester> asked to join <event>` with a person-plus glyph, like a comment row. It opens the event,whose details list each request with `Add as guest` and `Decline` on desktop and in the phone-drawer. Adding writes the guest through the same invite path as `Add guests`, so Google or+drawer. A new request appears in details already open, for the owner and delegates of the sharer's+inbox, without a reload; a repeated or refused ask changes nothing there. Adding writes the guest through the same invite path as `Add guests`, so Google orOutlook sends the invitation and the mention then opens the viewer's own copy. Declining sendsthe requester nothing, but their card then reads `Declined` and `The person who shared this eventdeclined your request to join.` with no `Ask to join`, and offers `Add to calendar` again. Adiff --git a/services/document_storage_service/AGENTS.md b/services/document_storage_service/AGENTS.mdindex 8e19eb9758..ce96edae22 100644--- a/services/document_storage_service/AGENTS.md+++ b/services/document_storage_service/AGENTS.md@@ -42,6 +42,13 @@ threads, pins, recents, notifications, folders, activity.objects keyed by part paths/hashes. The export route maps the documents domain'spending result to 409 with `Retry-After`; never reuse document-id-only archives.Location and export URLs share signing helpers in `src/service/cloudfront.rs`.+- `src/outbound/calendar_refresh.rs`: the `refresh_calendar` nudge for a new+ request to join a calendar event, which this service hosts while answers+ belong to `calendar_service`. It finds delegates by `link_id` alone, as the+ request list admits them; `get_primaries_for_link` also filters on the child,+ which a promoted shared mailbox's older events do not carry as their owner.+ Nudges follow a committed write, so they share `event_broker_tracker`'s+ bounded shutdown drain with event broker publishes.- `src/service/delete_document_worker.rs`: background worker handling documentdeletion side effects (feature-gated: `delete_document_worker`).- `src/service/conn_gateway.rs`: pushes realtime updates throughdiff --git a/services/document_storage_service/Cargo.toml b/services/document_storage_service/Cargo.tomlindex b26e474e45..f116770534 100644--- a/services/document_storage_service/Cargo.toml+++ b/services/document_storage_service/Cargo.toml@@ -310,11 +310,13 @@ cool_asserts = "2"flate2 = "1"frecency = { path = "../../crates/frecency", features = ["mock"] }macro_auth = { path = "../../crates/macro_auth", features = ["testing"] }+macro_db_migrator = { path = "../../crates/macro_db_migrator" }opentelemetry = { workspace = true, features = ["trace"] }opentelemetry_sdk = { workspace = true, features = ["testing", "trace"] }ordered-float = { workspace = true }tracing-opentelemetry = { workspace = true }tracing-subscriber = { workspace = true }+wiremock = { workspace = true }[package.metadata.cargo-machete]ignored = ["connection_gateway_client"]diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rsindex d192df0594..c1190368d0 100644--- a/services/document_storage_service/src/api/context.rs+++ b/services/document_storage_service/src/api/context.rs@@ -310,6 +310,7 @@ pub(crate) type DssCalendarJoinRequestService =calendar_events::outbound::notification_notifier::NotificationCalendarJoinRequestNotifier<NotificationIngressType,>,+ crate::outbound::calendar_refresh::ConnectionGatewayCalendarRefresh,>;/// Calendar join-request router state.diff --git a/services/document_storage_service/src/outbound/calendar_refresh.rs b/services/document_storage_service/src/outbound/calendar_refresh.rsnew file mode 100644index 0000000000..c80bd315a8--- /dev/null+++ b/services/document_storage_service/src/outbound/calendar_refresh.rs@@ -0,0 +1,149 @@+//! Connection-gateway adapter that nudges calendar viewers from this service,+//! which hosts asking to join a shared event.++use calendar_events::domain::{models::RefreshCalendarEvent, ports::CalendarRefreshNotifier};+use connection_gateway_client::client::ConnectionGatewayClient;+use sqlx::PgPool;+use tokio_util::task::TaskTracker;+use tracing::Instrument;+use uuid::Uuid;++#[cfg(test)]+mod test;++const REFRESHED: &str = "refreshed";++/// [`CalendarRefreshNotifier`] backed by the connection gateway: fans one+/// nudge out to the link owner and its delegates, as `calendar_service` and+/// `email_service` do. Nothing written here changes a team's view, so unlike+/// `calendar_service` it sends teammates no team refresh.+#[derive(Clone)]+pub struct ConnectionGatewayCalendarRefresh {+ client: ConnectionGatewayClient,+ db: PgPool,+ tasks: TaskTracker,+}++impl ConnectionGatewayCalendarRefresh {+ /// Construct the adapter. `tasks` is drained at shutdown, so a nudge for a+ /// committed write still goes out when the service stops right after it.+ pub fn new(client: ConnectionGatewayClient, db: PgPool, tasks: TaskTracker) -> Self {+ Self { client, db, tasks }+ }++ /// Signal the viewers of `link_id`. Delegates are found by the link+ /// alone, as `get_event_mutation_target` admits them to the request list:+ /// a promoted shared mailbox's edges name the mailbox as their child, not+ /// the owner its older events carry. Best effort: a viewer it misses only+ /// misses a refresh.+ #[tracing::instrument(+ name = "calendar.refresh_inbox_viewers",+ skip_all,+ fields(+ link_id = %link_id,+ recipients = tracing::field::Empty,+ failed_sends = tracing::field::Empty,+ outcome = tracing::field::Empty,+ )+ )]+ async fn refresh_inbox_viewers(&self, owner_id: &str, link_id: Uuid, team_ooo_changed: bool) {+ if !cfg!(feature = "connection_gateway") {+ return;+ }+ let payload = serde_json::to_value(RefreshCalendarEvent::Synced {+ link_id,+ team_ooo_changed,+ })+ .unwrap_or_default();+ let mut recipients = vec![owner_id.to_string()];+ let mut delegates_resolved = true;+ match sqlx::query_scalar!(+ "SELECT primary_macro_id FROM macro_user_links WHERE link_id = $1",+ link_id,+ )+ .fetch_all(&self.db)+ .await+ {+ Ok(delegates) => recipients.extend(delegates),+ Err(error) => {+ delegates_resolved = false;+ tracing::warn!(error=?error, %link_id, "failed to resolve calendar refresh delegates");+ }+ }+ recipients.sort();+ recipients.dedup();+ let span = tracing::Span::current();+ span.record("recipients", recipients.len());+ let mut failed_sends = 0_usize;+ for macro_id in recipients {+ let sent = self+ .client+ .refresh_calendar(¯o_id, payload.clone())+ .await+ .inspect_err(+ |error| tracing::error!(error=?error, %link_id, "failed to refresh calendar"),+ );+ failed_sends += usize::from(sent.is_err());+ }+ span.record("failed_sends", failed_sends);+ span.record(+ "outcome",+ if delegates_resolved && failed_sends == 0 {+ REFRESHED+ } else {+ "partial"+ },+ );+ }++ /// Tell one requester their request to join `event_id` was answered. It+ /// names the event, whose id they hold, and not the sharer's inbox.+ #[tracing::instrument(+ name = "calendar.refresh_join_requester",+ skip_all,+ fields(event_id = %event_id, outcome = tracing::field::Empty)+ )]+ async fn refresh_requester(&self, requester_id: &str, event_id: Uuid) {+ if !cfg!(feature = "connection_gateway") {+ return;+ }+ let payload = serde_json::to_value(RefreshCalendarEvent::JoinRequestAnswered { event_id })+ .unwrap_or_default();+ let sent = self+ .client+ .refresh_calendar(requester_id, payload)+ .await+ .inspect_err(|error| {+ tracing::error!(error=?error, %event_id, "failed to refresh the requester's calendar");+ });+ tracing::Span::current().record("outcome", if sent.is_ok() { REFRESHED } else { "failed" });+ }+}++impl CalendarRefreshNotifier for ConnectionGatewayCalendarRefresh {+ async fn calendar_changed(&self, owner_id: &str, email_link_id: Uuid, team_ooo_changed: bool) {+ // Spawned so the response never waits on the gateway, which is posted+ // to serially per recipient, while the write is already committed.+ let refresh = self.clone();+ let owner_id = owner_id.to_string();+ self.tasks.spawn(+ async move {+ refresh+ .refresh_inbox_viewers(&owner_id, email_link_id, team_ooo_changed)+ .await;+ }+ .in_current_span(),+ );+ }++ async fn join_request_answered(&self, requester_id: &str, event_id: Uuid) {+ let refresh = self.clone();+ let requester_id = requester_id.to_string();+ self.tasks.spawn(+ async move {+ refresh.refresh_requester(&requester_id, event_id).await;+ }+ .in_current_span(),+ );+ }+}diff --git a/services/document_storage_service/src/outbound/calendar_refresh/test.rs b/services/document_storage_service/src/outbound/calendar_refresh/test.rsnew file mode 100644index 0000000000..ed1dabd860--- /dev/null+++ b/services/document_storage_service/src/outbound/calendar_refresh/test.rs@@ -0,0 +1,279 @@+use std::future::Future;++use macro_db_migrator::MACRO_DB_MIGRATIONS;+use opentelemetry::trace::TracerProvider as _;+use opentelemetry_sdk::trace::{InMemorySpanExporter, SdkTracerProvider, SpanData};+use serde_json::{Value, json};+use sqlx::PgPool;+use tracing_subscriber::{Registry, layer::SubscriberExt as _};+use uuid::Uuid;+use wiremock::{+ Mock, MockServer, ResponseTemplate,+ matchers::{method, path_regex},+};++use super::*;++const OWNER: &str = "macro|[email protected]";+const DELEGATE: &str = "macro|[email protected]";+const MAILBOX: &str = "macro|[email protected]";+const OTHER_DELEGATE: &str = "macro|[email protected]";+const REQUESTER: &str = "macro|[email protected]";++async fn insert_user(pool: &PgPool, id: &str) {+ let macro_user_id = Uuid::now_v7();+ sqlx::query!(+ "INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1, $2, $3, $4)",+ macro_user_id,+ id,+ id,+ format!("cus_{macro_user_id}"),+ )+ .execute(pool)+ .await+ .unwrap();+ sqlx::query!(+ r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1, $2, $3)"#,+ id,+ id,+ macro_user_id,+ )+ .execute(pool)+ .await+ .unwrap();+}++async fn insert_link(pool: &PgPool, owner_id: &str) -> Uuid {+ let id = Uuid::now_v7();+ sqlx::query!(+ r#"+ INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider)+ VALUES ($1, $2, $2, $3, 'GMAIL')+ "#,+ id,+ owner_id,+ format!("calendar-{id}@example.com"),+ )+ .execute(pool)+ .await+ .unwrap();+ id+}++async fn gateway() -> (MockServer, ConnectionGatewayClient) {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "receipts": [] })))+ .mount(&server)+ .await;+ let client = ConnectionGatewayClient::new("test".to_string(), server.uri());+ (server, client)+}++/// The adapter with its tracker, as the service composes them.+fn adapter(+ client: ConnectionGatewayClient,+ pool: PgPool,+) -> (ConnectionGatewayCalendarRefresh, TaskTracker) {+ let tasks = TaskTracker::new();+ (+ ConnectionGatewayCalendarRefresh::new(client, pool, tasks.clone()),+ tasks,+ )+}++/// The gateway drops every message for `recipient`, whose id the pattern matches.+async fn refuse(server: &MockServer, recipient: &str) {+ Mock::given(method("POST"))+ .and(path_regex(recipient))+ .respond_with(ResponseTemplate::new(500))+ .with_priority(1)+ .mount(server)+ .await;+}++/// The span named `name` that `work` finishes under a recording subscriber.+async fn recorded_span(name: &str, work: impl Future<Output = ()>) -> SpanData {+ let exporter = InMemorySpanExporter::default();+ let provider = SdkTracerProvider::builder()+ .with_simple_exporter(exporter.clone())+ .build();+ let subscriber = Registry::default()+ .with(tracing_opentelemetry::layer().with_tracer(provider.tracer("test")));+ let guard = tracing::subscriber::set_default(subscriber);+ work.await;+ drop(guard);+ exporter+ .get_finished_spans()+ .unwrap()+ .into_iter()+ .find(|span| span.name == name)+ .unwrap()+}++fn attribute(span: &SpanData, key: &str) -> String {+ span.attributes+ .iter()+ .find(|attribute| attribute.key.as_str() == key)+ .map(|attribute| attribute.value.to_string())+ .unwrap()+}++/// `(recipient, message)` of every `refresh_calendar` the gateway received.+async fn refreshes(server: &MockServer) -> Vec<(String, Value)> {+ let mut sent: Vec<(String, Value)> = server+ .received_requests()+ .await+ .unwrap()+ .iter()+ .map(|request| {+ let body: Value = request.body_json().unwrap();+ assert_eq!(body["message_type"], "refresh_calendar");+ let recipient = request.url.path().replace("%7C", "|");+ let recipient = recipient.strip_prefix("/message/send/user/").unwrap();+ (recipient.to_string(), body["message"].clone())+ })+ .collect();+ sent.sort_by(|a, b| a.0.cmp(&b.0));+ sent+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn an_inbox_refresh_reaches_its_owner_and_each_delegate_once(pool: PgPool) {+ for user in [OWNER, DELEGATE, MAILBOX, OTHER_DELEGATE] {+ insert_user(&pool, user).await;+ }+ let link = insert_link(&pool, MAILBOX).await;+ let other_link = insert_link(&pool, MAILBOX).await;+ // A promoted shared mailbox: the edges name the mailbox as their child+ // while its older events still carry the owner, who is a delegate too.+ for primary in [OWNER, DELEGATE] {+ macro_db_client::macro_user_links::insert_edge(&pool, primary, MAILBOX, link)+ .await+ .unwrap();+ }+ macro_db_client::macro_user_links::insert_edge(&pool, OTHER_DELEGATE, MAILBOX, other_link)+ .await+ .unwrap();+ let (server, client) = gateway().await;+ let (refresh, tasks) = adapter(client, pool);++ refresh.calendar_changed(OWNER, link, false).await;+ // Shutdown's drain: it waits for the nudge the response did not.+ tasks.close();+ tasks.wait().await;++ let message = json!({ "event": "synced", "link_id": link, "team_ooo_changed": false });+ assert_eq!(+ refreshes(&server).await,+ [+ (DELEGATE.to_string(), message.clone()),+ (OWNER.to_string(), message),+ ]+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn the_owner_still_hears_when_delegates_cannot_be_resolved(pool: PgPool) {+ let link = Uuid::now_v7();+ let (server, client) = gateway().await;+ let (refresh, _) = adapter(client, pool.clone());+ pool.close().await;++ let span = recorded_span(+ "calendar.refresh_inbox_viewers",+ refresh.refresh_inbox_viewers(OWNER, link, false),+ )+ .await;++ assert_eq!(+ refreshes(&server).await,+ [(+ OWNER.to_string(),+ json!({ "event": "synced", "link_id": link, "team_ooo_changed": false }),+ )]+ );+ assert_eq!(attribute(&span, "failed_sends"), "0");+ assert_eq!(attribute(&span, "outcome"), "partial");+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_failed_send_shows_on_the_span_and_the_rest_still_go_out(pool: PgPool) {+ for user in [OWNER, DELEGATE, MAILBOX] {+ insert_user(&pool, user).await;+ }+ let link = insert_link(&pool, MAILBOX).await;+ for primary in [OWNER, DELEGATE] {+ macro_db_client::macro_user_links::insert_edge(&pool, primary, MAILBOX, link)+ .await+ .unwrap();+ }+ let (server, client) = gateway().await;+ refuse(&server, "refresh-delegate").await;+ let (refresh, _) = adapter(client, pool);++ let span = recorded_span(+ "calendar.refresh_inbox_viewers",+ refresh.refresh_inbox_viewers(OWNER, link, false),+ )+ .await;++ // Both were tried, in order, so the refused one did not stop the other.+ assert_eq!(server.received_requests().await.unwrap().len(), 2);+ assert_eq!(attribute(&span, "recipients"), "2");+ assert_eq!(attribute(&span, "failed_sends"), "1");+ assert_eq!(attribute(&span, "outcome"), "partial");+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_clean_refresh_shows_on_the_span(pool: PgPool) {+ let (server, client) = gateway().await;+ let (refresh, _) = adapter(client, pool);+ let link = Uuid::now_v7();++ let span = recorded_span(+ "calendar.refresh_inbox_viewers",+ refresh.refresh_inbox_viewers(OWNER, link, false),+ )+ .await;++ assert_eq!(server.received_requests().await.unwrap().len(), 1);+ assert_eq!(attribute(&span, "recipients"), "1");+ assert_eq!(attribute(&span, "failed_sends"), "0");+ assert_eq!(attribute(&span, "outcome"), "refreshed");+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn an_answer_names_the_event_and_never_the_inbox(pool: PgPool) {+ let event_id = Uuid::now_v7();+ let (server, client) = gateway().await;+ let (refresh, tasks) = adapter(client, pool);++ refresh.join_request_answered(REQUESTER, event_id).await;+ tasks.close();+ tasks.wait().await;++ assert_eq!(+ refreshes(&server).await,+ [(+ REQUESTER.to_string(),+ json!({ "event": "join_request_answered", "event_id": event_id }),+ )]+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_failed_answer_refresh_shows_on_the_span(pool: PgPool) {+ let event_id = Uuid::now_v7();+ let (server, client) = gateway().await;+ refuse(&server, "refresh-requester").await;+ let (refresh, _) = adapter(client, pool);++ let span = recorded_span(+ "calendar.refresh_join_requester",+ refresh.refresh_requester(REQUESTER, event_id),+ )+ .await;++ assert_eq!(attribute(&span, "outcome"), "failed");+}diff --git a/services/document_storage_service/src/outbound/mod.rs b/services/document_storage_service/src/outbound/mod.rsindex 29e28a65f4..7a301d20c0 100644--- a/services/document_storage_service/src/outbound/mod.rs+++ b/services/document_storage_service/src/outbound/mod.rs@@ -2,5 +2,6 @@pub mod access_requests;pub mod agent_dm_authorizer;+pub mod calendar_refresh;pub mod docx_export;pub mod entity_mutation;diff --git a/services/document_storage_service/src/server.rs b/services/document_storage_service/src/server.rsindex 1c0cfad704..1c6145afb5 100644--- a/services/document_storage_service/src/server.rs+++ b/services/document_storage_service/src/server.rs@@ -1956,6 +1956,11 @@ pub async fn run() -> anyhow::Result<()> {calendar_events::outbound::notification_notifier::NotificationCalendarJoinRequestNotifier::new((*notification_ingress_service).clone(),),+ crate::outbound::calendar_refresh::ConnectionGatewayCalendarRefresh::new(+ (*conn_gateway_client).clone(),+ db.clone(),+ event_broker_tracker.clone(),+ ),),),authorization_state.clone(),