Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

32.5 KB
Raw Blame
//! Kafka consumer for entity events that change realtime Soup items.
//!
//! Delivery is best effort with bounded retries: offsets are committed after
//! successful domain processing or a logged terminal failure. Exhausted publication
//! retries discard the rest of that event so it cannot wedge a partition. Failed
//! linked-session lookups still allow direct PR record updates. Malformed and
//! recognized-but-irrelevant events are also committed. Cancellation leaves the
//! in-flight event uncommitted; partial delivery and replay can produce duplicates.

#[cfg(test)]
mod test;

use std::{future::Future, time::Duration};

use crate::domain::{
    models::{Patch, SoupRealtimePatch},
    ports::{PullRequestSessions, SoupRealtimeService},
    service::SoupRealtimeServiceImpl,
};
use call::domain::events::{CallMacroEvent, CallTopicEvent};
use channels::domain::{
    broker_events::{ChannelMacroEvent, ChannelTopicEvent},
    models::ReferencedShareItemType,
};
use chat::domain::events::{ChatMacroEvent, ChatTopicEvent};
use documents::domain::events::{DocumentMacroEvent, DocumentTopicEvent, InteractionReason};
use email::domain::events::{EmailMacroEvent, EmailTopicEvent};
use github_pull_requests::broker::{GithubPullRequestMacroEvent, GithubPullRequestTopicEvent};
use initiative::domain::events::{InitiativeMacroEvent, InitiativeTopicEvent};
use kafka_util::{GroupName, InitialOffset, KafkaEventConsumer};
use macro_event_broker::{
    KafkaConsumerAdapter, MacroEvent as _, MacroEventCollection as _, MacroEventConsumerService,
};
use messages::domain::models::MessageParent;
use messages::outbound::broker::{MessageMacroEvent, MessageTopicEvent};
use model_entity::{Entity, EntityType};
use models_properties::EntityType as PropertyEntityType;
use models_properties::service::property_value::PropertyValue;
use projects::domain::events::{ProjectMacroEvent, ProjectTopicEvent};
use properties::domain::events::{PropertyMacroEvent, PropertyTopicEvent};
use rdkafka::consumer::CommitMode;
use rdkafka::message::{BorrowedMessage, Message as _};
use rootcause::prelude::{Report, ResultExt as _};
use system_properties::SystemPropertyKey;
use tokio_retry::{Retry, strategy::ExponentialBackoff};
use tracing::Instrument as _;

/// Consumer group used for Soup-affecting entity event offsets.
struct SoupRealtimeConsumerGroup;

impl GroupName for SoupRealtimeConsumerGroup {
    const GROUP_NAME: &'static str = "soup-realtime";
    // `macro.messages` joined this group's subscription with no committed
    // offset; starting at its head avoids replaying the topic's retention.
    const INITIAL_OFFSET: InitialOffset = InitialOffset::Latest;
}

type SoupRealtimeKafkaAdapter = KafkaConsumerAdapter<SoupRealtimeConsumerGroup, DeclaredMacroEvent>;
type SoupRealtimeKafkaConsumer =
    MacroEventConsumerService<DeclaredMacroEvent, SoupRealtimeKafkaAdapter>;

macro_event_broker::declare_topics!(
    DeclaredMacroEvent:
        GithubPullRequestMacroEvent,
        DocumentMacroEvent,
        ProjectMacroEvent,
        ChatMacroEvent,
        EmailMacroEvent,
        ChannelMacroEvent,
        MessageMacroEvent,
        PropertyMacroEvent,
        InitiativeMacroEvent,
        CallMacroEvent,
);

fn entity(entity_type: EntityType, entity_id: impl ToString) -> Entity<'static> {
    entity_type.with_entity_string(entity_id.to_string())
}

fn update(entity_type: EntityType, entity_id: impl ToString) -> SoupRealtimePatch {
    SoupRealtimePatch::for_entity(Patch::Updated(entity(entity_type, entity_id)))
}

fn delete(entity_type: EntityType, entity_id: impl ToString) -> SoupRealtimePatch {
    SoupRealtimePatch::for_entity(Patch::Deleted(entity(entity_type, entity_id)))
}

fn push_unique_patch_with_access_source(
    patches: &mut Vec<SoupRealtimePatch>,
    patch: Patch<Entity<'static>>,
    access_source: Entity<'static>,
) {
    if patch.value().entity_id.is_empty()
        || patches.iter().any(|candidate| candidate.patch == patch)
    {
        return;
    }
    patches.push(SoupRealtimePatch::new(patch, access_source));
}

fn push_unique_patch(patches: &mut Vec<SoupRealtimePatch>, patch: Patch<Entity<'static>>) {
    let access_source = patch.value().clone();
    push_unique_patch_with_access_source(patches, patch, access_source);
}

fn push_unique_update(
    patches: &mut Vec<SoupRealtimePatch>,
    entity_type: EntityType,
    entity_id: &str,
) {
    push_unique_patch(patches, Patch::Updated(entity(entity_type, entity_id)));
}

fn push_unique_delete(
    patches: &mut Vec<SoupRealtimePatch>,
    entity_type: EntityType,
    entity_id: &str,
) {
    push_unique_patch(patches, Patch::Deleted(entity(entity_type, entity_id)));
}

fn patches_from_document_event(event: &DocumentTopicEvent) -> Vec<SoupRealtimePatch> {
    let mut updates = Vec::new();
    match event {
        DocumentTopicEvent::Created(metadata) => {
            push_unique_update(&mut updates, EntityType::Document, &metadata.document_id);
            if let Some(project_id) = metadata.project_id.as_deref() {
                push_unique_update(&mut updates, EntityType::Project, project_id);
            }
        }
        DocumentTopicEvent::Updated(metadata) => {
            push_unique_update(&mut updates, EntityType::Document, &metadata.document_id);
            if let Some(project_id) = metadata.project_id.as_deref() {
                push_unique_update(&mut updates, EntityType::Project, project_id);
            }
            if metadata.previous_project_id.as_deref() != metadata.project_id.as_deref()
                && let Some(previous_project_id) = metadata.previous_project_id.as_deref()
            {
                push_unique_update(&mut updates, EntityType::Project, previous_project_id);
            }
        }
        DocumentTopicEvent::Deleted(metadata) => {
            push_unique_delete(&mut updates, EntityType::Document, &metadata.document_id);
            if let Some(project_id) = metadata.project_id.as_deref() {
                push_unique_update(&mut updates, EntityType::Project, project_id);
            }
        }
        DocumentTopicEvent::Copied(metadata) => {
            push_unique_update(&mut updates, EntityType::Document, &metadata.document_id);
        }
        DocumentTopicEvent::Interaction(metadata)
            if metadata.reason == InteractionReason::Edited =>
        {
            push_unique_update(&mut updates, EntityType::Document, &metadata.document_id);
        }
        DocumentTopicEvent::Interaction(_)
        | DocumentTopicEvent::ContentUploaded(_)
        | DocumentTopicEvent::SyncContentUpdated(_)
        | DocumentTopicEvent::Purged(_) => {}
    }
    updates
}

fn patches_from_initiative_event(event: &InitiativeTopicEvent) -> Vec<SoupRealtimePatch> {
    match event {
        InitiativeTopicEvent::Created(change) | InitiativeTopicEvent::Updated(change) => {
            vec![update(EntityType::Initiative, change.initiative_id)]
        }
        InitiativeTopicEvent::Purged { initiative_id } => {
            vec![delete(EntityType::Initiative, initiative_id)]
        }
    }
}

fn patches_from_project_event(event: &ProjectTopicEvent) -> Vec<SoupRealtimePatch> {
    let mut updates = Vec::new();
    match event {
        ProjectTopicEvent::Created(metadata) => {
            push_unique_update(&mut updates, EntityType::Project, &metadata.project_id);
            if let Some(parent_id) = metadata.parent_project_id.as_deref() {
                push_unique_update(&mut updates, EntityType::Project, parent_id);
            }
        }
        ProjectTopicEvent::Updated(metadata) => {
            push_unique_update(&mut updates, EntityType::Project, &metadata.project_id);
            if let Some(previous_parent_id) = metadata.previous_parent_id.as_deref() {
                push_unique_update(&mut updates, EntityType::Project, previous_parent_id);
            }
            if let Some(parent_id) = metadata.parent_id.as_deref() {
                push_unique_update(&mut updates, EntityType::Project, parent_id);
            }
        }
        ProjectTopicEvent::Deleted(metadata) => {
            push_unique_delete(&mut updates, EntityType::Project, &metadata.project_id);
            for project_id in &metadata.deleted_project_ids {
                push_unique_delete(&mut updates, EntityType::Project, project_id);
            }
            for document_id in &metadata.deleted_document_ids {
                push_unique_delete(&mut updates, EntityType::Document, document_id);
            }
            for chat_id in &metadata.deleted_chat_ids {
                push_unique_delete(&mut updates, EntityType::Chat, chat_id);
            }
            if let Some(parent_id) = metadata.parent_project_id.as_deref() {
                push_unique_update(&mut updates, EntityType::Project, parent_id);
            }
        }
        ProjectTopicEvent::Restored(metadata) => {
            push_unique_update(&mut updates, EntityType::Project, &metadata.project_id);
            for project_id in &metadata.restored_project_ids {
                push_unique_update(&mut updates, EntityType::Project, project_id);
            }
        }
        ProjectTopicEvent::PermanentlyDeleted(_) => {}
        ProjectTopicEvent::Uploaded(metadata) => {
            for project_id in &metadata.project_ids {
                push_unique_update(&mut updates, EntityType::Project, project_id);
            }
        }
    }
    updates
}

fn patches_from_chat_event(event: &ChatTopicEvent) -> Vec<SoupRealtimePatch> {
    let mut updates = Vec::new();
    match event {
        ChatTopicEvent::Created(metadata) => {
            push_unique_update(&mut updates, EntityType::Chat, &metadata.chat_id);
            if let Some(project_id) = metadata.project_id.as_deref() {
                push_unique_update(&mut updates, EntityType::Project, project_id);
            }
        }
        ChatTopicEvent::Updated(metadata) => {
            push_unique_update(&mut updates, EntityType::Chat, &metadata.chat_id);
            if let Some(project_id) = metadata.project_id.as_deref() {
                push_unique_update(&mut updates, EntityType::Project, project_id);
            }
            if metadata.previous_project_id.as_deref() != metadata.project_id.as_deref()
                && let Some(previous_project_id) = metadata.previous_project_id.as_deref()
            {
                push_unique_update(&mut updates, EntityType::Project, previous_project_id);
            }
        }
        ChatTopicEvent::Deleted(metadata) => {
            push_unique_delete(&mut updates, EntityType::Chat, &metadata.chat_id);
            if let Some(project_id) = metadata.project_id.as_deref() {
                push_unique_update(&mut updates, EntityType::Project, project_id);
            }
        }
        ChatTopicEvent::PermanentlyDeleted(metadata) => {
            if let Some(project_id) = metadata.project_id.as_deref() {
                push_unique_update(&mut updates, EntityType::Project, project_id);
            }
        }
        ChatTopicEvent::Restored(metadata) => {
            push_unique_update(&mut updates, EntityType::Chat, &metadata.chat_id);
            if let Some(project_id) = metadata.project_id.as_deref() {
                push_unique_update(&mut updates, EntityType::Project, project_id);
            }
        }
        ChatTopicEvent::Copied(metadata) => {
            push_unique_update(&mut updates, EntityType::Chat, &metadata.chat_id);
        }
        ChatTopicEvent::MessageSent(metadata) => {
            push_unique_update(&mut updates, EntityType::Chat, &metadata.chat_id);
        }
        ChatTopicEvent::MessageDeleted(_) => {}
    }
    updates
}

fn patches_from_email_event(event: &EmailTopicEvent) -> Vec<SoupRealtimePatch> {
    let updated_thread = |thread_id| vec![update(EntityType::EmailThread, thread_id)];
    let deleted_thread = |thread_id| vec![delete(EntityType::EmailThread, thread_id)];

    match event {
        EmailTopicEvent::MessageReceived(metadata) => {
            if metadata.is_spam_or_trash {
                Vec::new()
            } else {
                updated_thread(metadata.thread_id)
            }
        }
        EmailTopicEvent::MessageDraftSynced(metadata) => {
            if metadata.is_spam_or_trash {
                Vec::new()
            } else {
                updated_thread(metadata.thread_id)
            }
        }
        EmailTopicEvent::MessageSent(metadata) => updated_thread(metadata.thread_id),
        EmailTopicEvent::MessageDeleted(metadata) => updated_thread(metadata.thread_id),
        EmailTopicEvent::MessageSendQueued(metadata) => updated_thread(metadata.thread_id),
        EmailTopicEvent::MessageSendCancelled(metadata) => updated_thread(metadata.thread_id),
        EmailTopicEvent::ThreadArchived(metadata) => updated_thread(metadata.thread_id),
        EmailTopicEvent::ThreadTrashed(metadata) => {
            if metadata.trashed {
                deleted_thread(metadata.thread_id)
            } else {
                updated_thread(metadata.thread_id)
            }
        }
        EmailTopicEvent::ThreadRead(metadata) => updated_thread(metadata.thread_id),
        EmailTopicEvent::ThreadStarred(metadata) => updated_thread(metadata.thread_id),
        EmailTopicEvent::ThreadSpamChanged(metadata) => {
            if metadata.spam {
                deleted_thread(metadata.thread_id)
            } else {
                updated_thread(metadata.thread_id)
            }
        }
        EmailTopicEvent::ThreadProjectChanged(metadata) => updated_thread(metadata.thread_id),
        EmailTopicEvent::ThreadLabelsUpdated(metadata) => updated_thread(metadata.thread_id),
        EmailTopicEvent::ThreadBackfilled(metadata) => updated_thread(metadata.thread_id),
        EmailTopicEvent::ThreadsReindexRequested(metadata) => metadata
            .thread_ids
            .iter()
            .map(|thread_id| update(EntityType::EmailThread, thread_id))
            .collect(),
        EmailTopicEvent::LinkConnected(_)
        | EmailTopicEvent::LinkDisconnected(_)
        | EmailTopicEvent::LinkReauthRequired(_) => Vec::new(),
    }
}

fn channel_and_thread_entities(
    channel_id: impl ToString,
    message_id: impl ToString,
    thread_id: Option<impl ToString>,
) -> Vec<SoupRealtimePatch> {
    let channel = entity(EntityType::Channel, channel_id);
    let thread = entity(
        EntityType::ChannelMessage,
        thread_id
            .map(|id| id.to_string())
            .unwrap_or_else(|| message_id.to_string()),
    );
    vec![
        SoupRealtimePatch::for_entity(Patch::Updated(channel.clone())),
        SoupRealtimePatch::new(Patch::Updated(thread), channel),
    ]
}

fn soup_entity_type_from_channel_reference(entity_type: &str) -> Option<EntityType> {
    match ReferencedShareItemType::from_raw(entity_type)? {
        ReferencedShareItemType::AgentSession => Some(EntityType::AgentSession),
        // Databases use their own list and table-change gateway events.
        ReferencedShareItemType::Database => None,
        ReferencedShareItemType::Document => Some(EntityType::Document),
        ReferencedShareItemType::Chat => Some(EntityType::Chat),
        ReferencedShareItemType::Project => Some(EntityType::Project),
        ReferencedShareItemType::EmailThread => Some(EntityType::EmailThread),
        ReferencedShareItemType::Call => Some(EntityType::Call),
        // A shared event is previewed in place, never listed in the soup.
        ReferencedShareItemType::CalendarEvent => None,
        // Forms are not soup entities; a posted form renders as its card.
        ReferencedShareItemType::Form => None,
        // External chats are not soup entities; External lists them.
        ReferencedShareItemType::ExternalChat => None,
    }
}

fn push_channel_reference_update(
    patches: &mut Vec<SoupRealtimePatch>,
    channel: &Entity<'static>,
    entity_type: &str,
    entity_id: &str,
) {
    let Some(entity_type) = soup_entity_type_from_channel_reference(entity_type) else {
        return;
    };
    push_unique_patch_with_access_source(
        patches,
        Patch::Updated(entity(entity_type, entity_id)),
        channel.clone(),
    );
}

fn patches_from_channel_event(event: &ChannelTopicEvent) -> Vec<SoupRealtimePatch> {
    match event {
        ChannelTopicEvent::PictureChanged(metadata) => {
            vec![update(EntityType::Channel, metadata.channel_id)]
        }
        ChannelTopicEvent::Updated(metadata) => {
            vec![update(EntityType::Channel, metadata.channel_id)]
        }
        ChannelTopicEvent::ParticipantAdded(metadata) => {
            vec![update(EntityType::Channel, metadata.channel_id)]
        }
        ChannelTopicEvent::ParticipantRemoved(metadata) => {
            vec![update(EntityType::Channel, metadata.channel_id)]
        }
        ChannelTopicEvent::Created(metadata) => {
            vec![update(EntityType::Channel, metadata.channel_id)]
        }
        ChannelTopicEvent::Deleted(metadata) => {
            vec![delete(EntityType::Channel, metadata.channel_id)]
        }
        // A request to join changes neither the channel nor its membership.
        ChannelTopicEvent::AccessRequested(_) => Vec::new(),
    }
}

/// Imported records reach Soup as soon as they are stored. Native call
/// lifecycle events don't patch Soup yet.
fn patches_from_call_event(event: &CallTopicEvent) -> Vec<SoupRealtimePatch> {
    match event {
        CallTopicEvent::RecordImported(metadata) => {
            vec![update(EntityType::Call, metadata.call_id)]
        }
        CallTopicEvent::Started(_)
        | CallTopicEvent::RecordArchived(_)
        | CallTopicEvent::RecordUpdated(_)
        | CallTopicEvent::RecordDeleted(_)
        | CallTopicEvent::RecordSummarized(_)
        | CallTopicEvent::RecordingReady(_) => Vec::new(),
    }
}

/// Message facts carry their parent. Channel messages are Soup items, so a
/// channel post, edit, deletion, or attachment change patches the channel
/// and its thread; document discussions are not Soup items and patch nothing.
fn patches_from_message_event(event: &MessageTopicEvent) -> Vec<SoupRealtimePatch> {
    let channel = |parent: &MessageParent| match parent {
        MessageParent::Channel(channel_id) => Some(*channel_id),
        _ => None,
    };
    match event {
        MessageTopicEvent::Posted(metadata) => {
            let Some(channel_id) = channel(&metadata.parent) else {
                return Vec::new();
            };
            let mut patches =
                channel_and_thread_entities(channel_id, metadata.message_id, metadata.thread_id);
            let channel = entity(EntityType::Channel, channel_id);
            for mention in &metadata.mentions {
                push_channel_reference_update(
                    &mut patches,
                    &channel,
                    &mention.entity_type,
                    &mention.entity_id,
                );
            }
            patches
        }
        MessageTopicEvent::Patched(metadata) => match channel(&metadata.parent) {
            Some(channel_id) => {
                channel_and_thread_entities(channel_id, metadata.message_id, metadata.thread_id)
            }
            None => Vec::new(),
        },
        MessageTopicEvent::Deleted(metadata) => {
            let Some(channel_id) = channel(&metadata.parent) else {
                return Vec::new();
            };
            let channel = entity(EntityType::Channel, channel_id);
            let thread_patch = match metadata.thread_id {
                Some(thread_id) => Patch::Updated(entity(EntityType::ChannelMessage, thread_id)),
                None => Patch::Deleted(entity(EntityType::ChannelMessage, metadata.message_id)),
            };
            vec![
                SoupRealtimePatch::for_entity(Patch::Updated(channel.clone())),
                SoupRealtimePatch::new(thread_patch, channel),
            ]
        }
        MessageTopicEvent::AttachmentCreated(metadata) => {
            let Some(channel_id) = channel(&metadata.parent) else {
                return Vec::new();
            };
            let channel = entity(EntityType::Channel, channel_id);
            let mut patches = vec![SoupRealtimePatch::for_entity(Patch::Updated(
                channel.clone(),
            ))];
            for attachment in &metadata.attachments {
                push_channel_reference_update(
                    &mut patches,
                    &channel,
                    &attachment.entity_type,
                    &attachment.entity_id,
                );
            }
            patches
        }
        MessageTopicEvent::AttachmentRemoved(metadata) => channel(&metadata.parent)
            .map(|channel_id| vec![update(EntityType::Channel, channel_id)])
            .unwrap_or_default(),
        // Mentions carry no entity change beyond the posted fact emitted
        // alongside them.
        MessageTopicEvent::Mentioned(_) => Vec::new(),
    }
}

fn soup_entity_type_from_property(entity_type: PropertyEntityType) -> Option<EntityType> {
    match entity_type {
        PropertyEntityType::CalendarEvent => Some(EntityType::CalendarEvent),
        PropertyEntityType::CallRecord => Some(EntityType::Call),
        PropertyEntityType::Chat => Some(EntityType::Chat),
        PropertyEntityType::Company => Some(EntityType::CrmCompany),
        PropertyEntityType::Document | PropertyEntityType::Task => Some(EntityType::Document),
        PropertyEntityType::Project => Some(EntityType::Project),
        PropertyEntityType::Thread => Some(EntityType::EmailThread),
        PropertyEntityType::Initiative => Some(EntityType::Initiative),
        PropertyEntityType::DatabaseRow => Some(EntityType::DatabaseRow),
        // Soup channels do not expose properties; users and CRM contacts are
        // not Soup items.
        PropertyEntityType::Channel | PropertyEntityType::User | PropertyEntityType::Contact => {
            None
        }
    }
}

fn property_update(entity_type: PropertyEntityType, entity_id: &str) -> Vec<SoupRealtimePatch> {
    soup_entity_type_from_property(entity_type)
        .map(|entity_type| update(entity_type, entity_id))
        .into_iter()
        .collect()
}

fn patches_from_property_event(event: &PropertyTopicEvent) -> Vec<SoupRealtimePatch> {
    match event {
        PropertyTopicEvent::EntityPropertyUpdated(metadata) => {
            let mut patches = property_update(metadata.entity_type, &metadata.entity_id);
            // Deleting a project clears its tasks with internal, unattributed writes
            // after publishing Purged; refreshing that project here could replace the
            // deletion with a stale replica row.
            let attributed = metadata.actor_user_id.is_some()
                || metadata.actor.is_some()
                || metadata.on_behalf_of.is_some();
            if metadata.entity_type == PropertyEntityType::Task
                && metadata.property_definition_id == SystemPropertyKey::PROJECT_UUID
                && attributed
            {
                // The projects the task left and joined change their task lists.
                for value in [&metadata.previous_value, &metadata.value]
                    .into_iter()
                    .flatten()
                {
                    let PropertyValue::EntityRef(references) = value else {
                        continue;
                    };
                    for reference in references {
                        push_unique_update(
                            &mut patches,
                            EntityType::Initiative,
                            &reference.entity_id,
                        );
                    }
                }
            }
            patches
        }
        PropertyTopicEvent::EntityPropertyDeleted(metadata) => {
            property_update(metadata.entity_type, &metadata.entity_id)
        }
        PropertyTopicEvent::EntityPropertiesCleared(metadata)
            if metadata.entity_type == PropertyEntityType::Initiative
                && metadata.actor_user_id.is_none()
                && metadata.actor.is_none()
                && metadata.on_behalf_of.is_none() =>
        {
            // Initiative deletion clears properties with an internal receipt after
            // publishing Purged. The topics have no shared ordering; refreshing here
            // could replace the deletion with a stale replica row. User/bot clears
            // remain ordinary property updates below.
            Vec::new()
        }
        PropertyTopicEvent::EntityPropertiesCleared(metadata) => {
            property_update(metadata.entity_type, &metadata.entity_id)
        }
        PropertyTopicEvent::Created(_)
        | PropertyTopicEvent::Deleted(_)
        | PropertyTopicEvent::OptionCreated(_)
        | PropertyTopicEvent::OptionUpdated(_)
        | PropertyTopicEvent::OptionDeleted(_) => Vec::new(),
    }
}

fn patches_from_event(event: &DeclaredMacroEvent) -> Vec<SoupRealtimePatch> {
    match event {
        DeclaredMacroEvent::GithubPullRequestMacroEvent(event) => {
            let GithubPullRequestTopicEvent::Updated(change) = &event.event().event;
            change
                .foreign_entity_ids
                .iter()
                .map(|id| update(EntityType::ForeignEntity, id))
                .collect()
        }
        DeclaredMacroEvent::DocumentMacroEvent(event) => {
            patches_from_document_event(&event.event().event)
        }
        DeclaredMacroEvent::ProjectMacroEvent(event) => {
            patches_from_project_event(&event.event().event)
        }
        DeclaredMacroEvent::ChatMacroEvent(event) => patches_from_chat_event(&event.event().event),
        DeclaredMacroEvent::EmailMacroEvent(event) => {
            patches_from_email_event(&event.event().event)
        }
        DeclaredMacroEvent::ChannelMacroEvent(event) => {
            patches_from_channel_event(&event.event().event)
        }
        DeclaredMacroEvent::InitiativeMacroEvent(event) => {
            patches_from_initiative_event(&event.event().event)
        }
        DeclaredMacroEvent::MessageMacroEvent(event) => {
            patches_from_message_event(&event.event().event)
        }
        DeclaredMacroEvent::PropertyMacroEvent(event) => {
            patches_from_property_event(&event.event().event)
        }
        DeclaredMacroEvent::CallMacroEvent(event) => patches_from_call_event(&event.event().event),
    }
}

/// Total publication attempts per patch before discarding its source event.
const MAX_NOTIFY_ATTEMPTS: usize = 5;

/// Retries after one, two, four, and eight seconds.
fn notify_retry_strategy() -> impl Iterator<Item = Duration> {
    ExponentialBackoff::from_millis(2)
        .factor(500)
        .take(MAX_NOTIFY_ATTEMPTS - 1)
}

/// Commit-safe outcome after processing one entity event.
enum EventOutcome {
    /// Every affected item was successfully published through the domain service.
    Notified,
    /// A recognized event does not change a Soup-visible entity.
    Ignored,
    /// A patch exhausted its retries; the remaining event was logged and discarded.
    Dropped,
}

#[tracing::instrument(skip(service, sessions, event, commit))]
async fn process_event<S: SoupRealtimeService, L: PullRequestSessions>(
    service: &S,
    sessions: &L,
    event: &DeclaredMacroEvent,
    commit: impl FnOnce(),
) -> EventOutcome {
    let mut patches = patches_from_event(event);
    if let DeclaredMacroEvent::GithubPullRequestMacroEvent(event) = event {
        let GithubPullRequestTopicEvent::Updated(update) = &event.event().event;
        match Retry::start(notify_retry_strategy(), || {
            crate::domain::service::pull_request_patches(
                sessions,
                &update.github_key,
                update
                    .foreign_entity_ids
                    .iter()
                    .map(|id| entity(EntityType::ForeignEntity, id)),
            )
        })
        .await
        {
            Ok(expanded) => patches = expanded,
            Err(error) => {
                tracing::error!(
                    error=?error,
                    github_key=%update.github_key,
                    attempts=MAX_NOTIFY_ATTEMPTS,
                    "skipping linked session updates after lookup retries; publishing PR records"
                );
            }
        }
    }
    let mut outcome = if patches.is_empty() {
        tracing::trace!("ignoring event without a Soup patch");
        EventOutcome::Ignored
    } else {
        EventOutcome::Notified
    };

    let patch_count = patches.len();
    for (index, patch) in patches.into_iter().enumerate() {
        let result = Retry::start(notify_retry_strategy(), || {
            service.notify_users(patch.clone())
        })
        .await
        .inspect_err(|error| {
            tracing::error!(
                error = ?error,
                patch = ?patch,
                attempts = MAX_NOTIFY_ATTEMPTS,
                skipped_patch_count = patch_count - index - 1,
                "discarding realtime Soup source event after exhausting notification retries"
            );
        });
        if result.is_err() {
            outcome = EventOutcome::Dropped;
            break;
        }
    }

    commit();
    outcome
}

fn commit_logged(consumer: &SoupRealtimeKafkaConsumer, message: &BorrowedMessage<'_>) {
    let _ = consumer
        .inner()
        .commit_message(message, CommitMode::Async)
        .inspect_err(|error| {
            tracing::error!(
                error = ?error,
                topic = message.topic(),
                partition = message.partition(),
                offset = message.offset(),
                "failed to commit realtime Soup source offset"
            );
        });
}

impl SoupRealtimeServiceImpl {
    /// Runs the Soup-affecting entity event consumer until `shutdown` resolves.
    ///
    /// The consumer subscribes to every existing entity topic with events that
    /// can change a Soup item under the `soup-realtime` group. It commits malformed
    /// and recognized-but-ignored events immediately. Affecting events are committed
    /// after every patch succeeds or a patch exhausts its five publication attempts.
    /// Exhaustion logs an error and discards the remaining event before committing,
    /// intentionally preferring consumer progress over delivery during persistent
    /// failures. Shutdown during processing or retry backoff leaves the event
    /// uncommitted for replay.
    #[tracing::instrument(skip(self, sessions, shutdown), fields(brokers), err)]
    pub async fn run_entity_update_consumer(
        &self,
        brokers: &str,
        sessions: &impl PullRequestSessions,
        shutdown: impl Future<Output = ()> + Send,
    ) -> Result<(), Report> {
        let consumer = KafkaEventConsumer::<SoupRealtimeConsumerGroup>::from_env(brokers)?;
        let consumer = KafkaConsumerAdapter::<SoupRealtimeConsumerGroup, ()>::new(consumer)
            .subscribe::<DeclaredMacroEvent>()
            .context("failed to subscribe to Soup-affecting entity topics")?;
        let consumer = SoupRealtimeKafkaConsumer::new(consumer);
        tracing::info!(
            topics = ?DeclaredMacroEvent::topics(),
            group = SoupRealtimeConsumerGroup::GROUP_NAME,
            "realtime Soup entity consumer listening"
        );

        let mut shutdown = std::pin::pin!(shutdown);
        loop {
            tokio::select! {
                _ = &mut shutdown => {
                    tracing::info!("realtime Soup entity consumer shutting down");
                    break;
                }
                result = consumer.recv() => {
                    let Ok(message) = result else { continue; };
                    let kafka_message = message.inner();
                    let span = tracing::info_span!(
                        "realtime_soup_source_event",
                        topic = kafka_message.topic(),
                        partition = kafka_message.partition(),
                        offset = kafka_message.offset(),
                    );
                    let decoded = {
                        let _guard = span.enter();
                        message.decode_payload()
                    };
                    let event = match decoded {
                        Ok(event) => event,
                        Err(_) => {
                            commit_logged(&consumer, kafka_message);
                            continue;
                        }
                    };

                    // Do not advance until delivery succeeds or the event reaches
                    // the logged terminal-drop outcome after bounded retries.
                    tokio::select! {
                        biased;
                        _ = &mut shutdown => break,
                        _ = process_event(self, sessions, &event, || {
                            commit_logged(&consumer, kafka_message);
                        }).instrument(span) => {}
                    }
                }
            }
        }

        Ok(())
    }
}