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
//! Ports (trait contracts) for the collab-surface domain.
use entity_access::domain::models::{AnyEntityPermission, EntityAccessReceipt};
use macro_sync_service_jwt::DocumentPermissionToken;
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::Entity;
use uuid::Uuid;
#[cfg(doc)]
use crate::domain::models::SurfaceOwnership;
use crate::domain::models::{CollabSurface, CollabSurfaceError, SurfaceSnapshot, SurfaceUpdate};
/// Outbound persistence port for collab surfaces.
pub trait CollabSurfaceRepo: Send + Sync + 'static {
/// The error type returned by repository operations.
type Err: std::error::Error + Send + Sync + 'static;
/// Insert a surface in `pending` state. Returns `false` (without error)
/// when a row with this id already exists — live or soft-deleted — so
/// concurrent ensures race safely.
fn insert(
&self,
surface: &CollabSurface,
) -> impl Future<Output = Result<bool, Self::Err>> + Send;
/// Fetch a surface by id. Soft-deleted surfaces read as absent.
fn get(
&self,
id: Uuid,
) -> impl Future<Output = Result<Option<CollabSurface>, Self::Err>> + Send;
/// All live surfaces attached to a parent entity.
fn list_by_parent(
&self,
parent: &Entity<'_>,
) -> impl Future<Output = Result<Vec<CollabSurface>, Self::Err>> + Send;
/// Flip a surface to `ready` after its sync-service session initialized.
fn mark_ready(&self, id: Uuid) -> impl Future<Output = Result<(), Self::Err>> + Send;
/// Soft-delete a surface. Idempotent.
fn soft_delete(&self, id: Uuid) -> impl Future<Output = Result<(), Self::Err>> + Send;
/// Whether `id` belongs to a soft-deleted surface.
fn is_deleted(&self, id: Uuid) -> impl Future<Output = Result<bool, Self::Err>> + Send;
}
/// Outbound port onto the document id namespace, which surfaces share in
/// sync-service. `outbound::document_ids::PgDocumentIds` implements it over
/// macro_db_client's `does_document_exist` helper, which owns reads of the
/// documents table.
pub trait DocumentIds: Send + Sync + 'static {
/// Whether `id` names a document, live or soft-deleted.
fn is_document_id(
&self,
id: Uuid,
) -> impl Future<Output = Result<bool, rootcause::Report>> + Send;
}
/// Outbound port onto the forms domain's ids. A form's surface takes the
/// form's id, and a form exists before its surface (which it ensures on first
/// open) and never comes back once purged. Implemented by the forms domain
/// over its own repository; this crate never reads forms tables.
pub trait FormIds: Send + Sync + 'static {
/// Whether `id` names a form, live or trashed.
fn is_form_id(&self, id: Uuid) -> impl Future<Output = Result<bool, rootcause::Report>> + Send;
}
/// Outbound port for a surface's sync-service session: boots it from markdown
/// or a Loro snapshot, checks whether it exists, and reads and writes its Loro
/// state under a signed grant.
///
/// Implementations convert markdown to a Loro snapshot (an empty string maps
/// to the canonical blank-document snapshot) and store it as the session's
/// initial state. Initialization is one-shot per id on the sync-service side,
/// so both methods treat an already-initialized session as success.
#[cfg_attr(test, mockall::automock)]
pub trait SurfaceInitializer: Send + Sync + 'static {
/// Initialize the sync-service session for `surface_id` with `markdown`.
fn initialize(
&self,
surface_id: &str,
markdown: &str,
) -> impl Future<Output = Result<(), CollabSurfaceError>> + Send;
/// Initialize the sync-service session for `surface_id` with an opaque
/// Loro `snapshot`, stored as-is as the session's initial state.
fn initialize_from_snapshot(
&self,
surface_id: &str,
snapshot: &[u8],
) -> impl Future<Output = Result<(), CollabSurfaceError>> + Send;
/// Whether a session for `surface_id` exists. Only asked for a new id,
/// before its row is inserted. Sync-service answers yes as soon as a
/// session knows its id (a client connected, say), not only once it is
/// initialized: the conservative answer for an id nothing should use yet.
fn session_exists(
&self,
surface_id: &str,
) -> impl Future<Output = Result<bool, CollabSurfaceError>> + Send;
/// The session for `surface_id` rendered as GitHub-flavored markdown.
fn markdown(
&self,
surface_id: &str,
) -> impl Future<Output = Result<String, CollabSurfaceError>> + Send;
/// The session's full Loro state, read through sync-service's signed
/// `GET /document/{surface_id}/state` with `token` as the bearer grant.
fn snapshot(
&self,
surface_id: &str,
token: &DocumentPermissionToken,
) -> impl Future<Output = Result<SurfaceSnapshot, CollabSurfaceError>> + Send;
/// Apply a Loro `update` to the session through sync-service's signed
/// `POST /document/{surface_id}/update`, only while the state is still at
/// `expected_revision` (otherwise [`SurfaceUpdate::Conflict`]). `token`
/// must grant Edit.
fn update(
&self,
surface_id: &str,
token: &DocumentPermissionToken,
expected_revision: &[u8],
update: &[u8],
) -> impl Future<Output = Result<SurfaceUpdate, CollabSurfaceError>> + Send;
}
/// The collab-surface use-cases, generic over the outbound ports.
pub trait CollabSurfaceService: Send + Sync + 'static {
/// Idempotently ensure surface `id` exists, attached to the parent entity
/// the receipt proves access to, with its sync-service session
/// initialized. Returns only once the surface is `ready`:
///
/// - missing → created with the caller-supplied id, initialized, `ready`.
/// - exists (live) → parent must match the receipt's entity; a `pending`
/// row (an earlier ensure died or failed mid-init) has its
/// initialization retried.
/// - soft-deleted → [`CollabSurfaceError::Gone`]; ids are never reused.
/// - not a random (v4 or v7) UUID → [`CollabSurfaceError::BadRequest`].
/// - the id names a document, or a new id already has a sync-service
/// session → [`CollabSurfaceError::IdReserved`], before any row is
/// written: a new surface only ever creates its own session.
/// - the parent's domain owns its surfaces
/// ([`SurfaceOwnership::ParentDomain`]) → [`CollabSurfaceError::AccessDenied`].
/// - the id names a form, live or trashed → [`CollabSurfaceError::IdReserved`]:
/// it is that form's surface id, whether or not the form has opened it.
///
/// Concurrent ensures for the same id converge: the insert is
/// conflict-tolerant and the initializer treats an already-initialized
/// session as success.
fn ensure_surface(
&self,
user_id: &MacroUserIdStr<'_>,
parent_receipt: EntityAccessReceipt<AnyEntityPermission>,
id: Uuid,
initial_markdown: String,
) -> impl Future<Output = Result<CollabSurface, CollabSurfaceError>> + Send;
/// Fetch a surface. The caller must already hold a receipt for the
/// surface's parent (resolved by the inbound layer via
/// [`CollabSurfaceService::get_parent`]).
fn get_surface(
&self,
user_id: &MacroUserIdStr<'_>,
parent_receipt: EntityAccessReceipt<AnyEntityPermission>,
id: Uuid,
) -> impl Future<Output = Result<CollabSurface, CollabSurfaceError>> + Send;
/// The parent entity of a surface, for the inbound layer to mint a receipt
/// against before any surface operation. `NotFound` for missing/deleted.
/// A form's surface outlives its form when the form row is deleted
/// without the forms domain (a database, table or owner purge cascades
/// to it) or when retiring it failed after a purge; such a surface is
/// retired here, the first time it is asked for, and reads as `NotFound`.
fn get_parent(
&self,
id: Uuid,
) -> impl Future<Output = Result<Entity<'static>, CollabSurfaceError>> + Send;
/// Mint a sync-service connection token for a `ready` surface, at the
/// access level implied by the caller's permission on the parent entity.
/// A form's surface needs Edit on the form.
/// A surface whose id names a document is refused
/// ([`CollabSurfaceError::IdReserved`]), whenever it was bound.
fn mint_token(
&self,
user_id: &MacroUserIdStr<'_>,
parent_receipt: EntityAccessReceipt<AnyEntityPermission>,
id: Uuid,
) -> impl Future<Output = Result<DocumentPermissionToken, CollabSurfaceError>> + Send;
/// Soft-delete a surface. Requires an edit-capable permission on the
/// parent, and a parent whose domain does not own its surfaces
/// ([`SurfaceOwnership::ParentDomain`]): a deleted id never comes back, so
/// only the owning domain may retire one. The sync-service session is not
/// reclaimed (documented gap shared with documents); deletion makes the
/// surface unmintable, which cuts off all access.
fn delete_surface(
&self,
user_id: &MacroUserIdStr<'_>,
parent_receipt: EntityAccessReceipt<AnyEntityPermission>,
id: Uuid,
) -> impl Future<Output = Result<(), CollabSurfaceError>> + Send;
}
/// Surfaces a parent's domain owns ([`SurfaceOwnership::ParentDomain`]). That
/// domain has already authorized its caller, so these take no receipt; keep
/// them out of reach of caller-chosen ids.
pub trait OwnedSurfaceService: Send + Sync + 'static {
/// Idempotently ensure surface `id`, parented by `parent`, exists and is
/// `ready`, under the same rules as [`CollabSurfaceService::ensure_surface`].
/// A new surface starts from `initial_markdown`; an existing one keeps its
/// content.
fn ensure_owned_surface(
&self,
parent: Entity<'static>,
id: Uuid,
initial_markdown: String,
) -> impl Future<Output = Result<CollabSurface, CollabSurfaceError>> + Send;
/// [`OwnedSurfaceService::ensure_owned_surface`] for a surface whose
/// content is not markdown: a new surface starts from `snapshot`, opaque
/// Loro bytes the parent's domain built; an existing one keeps its content.
fn ensure_owned_surface_from_snapshot(
&self,
parent: Entity<'static>,
id: Uuid,
snapshot: Vec<u8>,
) -> impl Future<Output = Result<CollabSurface, CollabSurfaceError>> + Send;
/// A ready surface's content as GitHub-flavored markdown; `None` while the
/// surface does not exist or is not ready.
fn owned_surface_markdown(
&self,
id: Uuid,
) -> impl Future<Output = Result<Option<String>, CollabSurfaceError>> + Send;
/// A ready surface's full Loro state and revision. `parent` must be the
/// surface's parent and of a type whose domain owns its surfaces;
/// a missing, retired or pending surface, or one whose id names a
/// document, is refused and never seeded.
fn owned_surface_snapshot(
&self,
parent: Entity<'static>,
id: Uuid,
) -> impl Future<Output = Result<SurfaceSnapshot, CollabSurfaceError>> + Send;
/// Apply a Loro `update` to a ready surface's state if it is still at
/// `expected_revision`, under the same rules as
/// [`OwnedSurfaceService::owned_surface_snapshot`].
fn update_owned_surface(
&self,
parent: Entity<'static>,
id: Uuid,
expected_revision: Vec<u8>,
update: Vec<u8>,
) -> impl Future<Output = Result<SurfaceUpdate, CollabSurfaceError>> + Send;
/// Soft-delete a surface for the domain that owns it. Idempotent.
fn retire_surface(
&self,
id: Uuid,
) -> impl Future<Output = Result<(), CollabSurfaceError>> + Send;
}