Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
email_api_client
What it is
Part of the Email feature: provider-neutral contracts and models for email provider integrations (sync, send, tokens, rate limits), plus the Gmail and Outlook (Microsoft Graph) outbound adapters.
Start here
src/domain/service.rs:EmailApiClientServiceImpl<R, T, L>— the orchestration layer, generic over a repository, token source, and request gate port; submodulesattachments/blocklist/contacts/labels/messages/raw_message/send/subscription/synchold one capability each.src/domain/ports.rs:ProviderRequestGate(per-mailbox admission for the service above),ProviderRateLimiter(the OutlookMailboxApiService's),ProviderTokenSource, and the repository traits adapters implement.src/outbound/gmail.rs: the Gmail adapter (featureoutbound-gmail).src/outbound/outlook.rs: the Microsoft Graph adapter (featureoutbound-outlook); every Graph call goes throughoutlook/transport.rs, which owns request headers, provider error mapping, write-failure logs, and oneoutlook.graph_requestspan per attempt (with anoutlook.graph_admissionchild for the per-mailbox gate wait).src/outbound/microsoft_gate.rs: the Redis admission every Graph request passes (window, concurrency, cooldown), which also counts admitted requests per sync generation.
Scope
- Owns: the provider-neutral vocabulary (
Message,Contact,SyncCursor,SendRequest, token/rate-limit errors) and orchestration over it. - Not here: Macro's own email domain (threads, scheduling) →
crates/email; SQLx storage →email_db_client.
Boundaries
- Depends on:
email_utils,models_email,gmail_client(featureoutbound-gmail),calendar_events(featureoutbound-outlook). - Used by:
crates/email(ports only),services/email_service,services/calendar_service.
Recipes
- Add a provider capability: a trait method on
src/domain/ports.rs→ a submodule undersrc/domain/service.rs→ implement it insrc/outbound/gmail.rs→ tests alongside insrc/domain/service/test.rs/test_support.rs.
Checks
cargo test -p email_api_client --all-features. The Outlook calendar mutation tests insrc/outbound/outlook/calendar/test/mutations.rsdrive the calendar domain service against Postgres through#[sqlx::test], so they need the local test database from Database development.
Gotchas
Undated provider drafts use creation time for All Mail eligibility; spam/junk and trash remain excluded. Keep ingestion, recomputation, and cached projections aligned.
#![deny(missing_docs)].The service is generic over
<R, T, L>(repository, token source, request gate) — add a new dependency as a port + generic bound, not a concrete field.Every provider call holds a
ProviderRequestGatepermit (RequestPermit) for its duration and finishes it with the call's error, so a provider rate limit cools the mailbox down for every caller. A permit dropped unfinished, by a cancelled future or an undispatchedPreparedSendMessage, releases itself. New service methods go throughread_with_tokenorcall_with_token; a call made with a bare token is invisible to the in-flight cap. Their spans declaregate_in_flightandgate_capas empty fields, which admission fills with the mailbox's load so it sits next to the call's outcome. Paginated reads (history, contacts) are page-level ports that the service loops over, one permit per page, so every page is charged to the mailbox's window and checks its cooldown; a refused page fails the read, and the span keeps the last page's load. Keep new paginated provider calls page-level rather than looping in the adapter.Link-based reads go through
read_with_token, which retries once with a fresh token when the provider answersAuthRequired; a cached token can outlive a revoked grant, and only the fresh fetch lets the token source mark the link for reauthorization. Contact listings useretry_with_fresh_tokento keep their WARN-level logging. Writes usecall_with_tokenand do not retry.SendRequest::build_mime(Gmail sends) turns an inlinetext/calendarattachment with no Content-ID into the message's calendar body, the last alternative after the text and HTML, which is how an answerable invitation (RFC 6047) is sent; other files stay attachments. Outlook sends do not go through it.Graph answers a bodyless POST or PATCH without
Content-Length: 0with 411 Length Required.transport.rsadds the header, so new Graph calls must go throughrequest/conditional_requestrather than the raw client. Usegraph_requestonly when a caller must branch on the Graph status, error code, or request id; the others drop them.outlook.graph_requestis the Graph telemetry contract the Outlook sync monitors ininfra/stacks/monitoringread. Every attempt recordsoutlook.throttle_origin(gate,graphornone); a gate refusal (RateLimitOrigin::Gatewith itsGateLimit) sent nothing, so it is not a span error and logs at DEBUG. The span setsoperation.namebecause Datadog files a client span with an HTTP method ashttp.client.request, and itsurl.templatecomes fromoutlook/route.rs, which keeps only known Graph path words so ids and user-chosen names never reach it. Record numeric fields asi64; unsigned values reach the collector as strings.domain::request_count::countedcounts the Graph requests one unit of work sends (the transport callsrecord_sent); Outlook token failures surface asEmailApiError::CredentialsUnavailable, apart from Graph failures.The Outlook calendar normalizer (
outlook/calendar/normalize.rs,recurrence.rs) fails withRejected, which names the Graph property path (recurrence.range.endDate,instances.start.dateTime), built only from literals so its log carries no event content, so the sync can skip and log that one event. Give a new check aRejected, notinvalid(). Graph leavesoriginalStartout ofinstancesunless it is selected, so the request selectsINSTANCE_PROPERTIES(Graph's defaulteventproperties plusoriginalStart); a new read of an instance property must be added there, since a$selectreturns nothing else. An exception still without one is left out of its series and reported as aSkippedOccurrence(instances.originalStart.missing); one Macro cannot parse rejects the series atinstances.originalStart. RaiseREADER_REVISIONwith a change that lets Macro read events it skipped before, so delta calendars read them again. Graph names UTCtzone://Microsoft/Utcon meetings Exchange imported from another system's invitation, whichzones::zonemaps; a series end date in a legacy custom zone (tzone://Microsoft/Custom) is read in the zone the event's time is kept in. Calendar discovery reads the mailbox'smailboxSettings.timeZone(Windows or IANA) through the same table; a name it cannot map leaves the calendars without a zone and is reported asOutlookDiscovery::unmapped_time_zonerather than failing the account.zones.rsis CLDR'swindowsZones.xml(territory001, in file order) with itsLICENSEbeside it; regenerate both from a new CLDR release when Windows adds zones. Keep out a zone whose IANA rules the bundled chrono-tz lacks: Outlook writes send local times computed with them, so stale rules move an event. British Columbia, Alberta and Manitoba Standard Time are held out that way until current tz data ships.Same-mailbox Outlook replies use
createReply. When Graph refuses it with 400ErrorInvalidOperation,create_draftcreates a standalone draft that carries the same correlation and RFC reply headers.
Related
- Rules:
.agents/rules/rust/architecture.md