tempest_fastapi_sdk.chat¶
Blocos de mensageria: conversas, mensagens, mídia e confirmações de leitura.
chat
¶
Messenger building blocks — conversations, messages, media, receipts.
Reusable pieces over the SDK primitives (BaseModel /
BaseRepository / pagination / SSE): abstract tables + make_*
factories, a :class:ChatService, and an opt-in
:func:make_chat_router. Import the pieces you need and mount the
router, or drive the service directly.
What the module owns is the set of decisions that go wrong the same way
in every product that takes them alone: read state as a watermark on
the participant rather than a receipt row per reader, one reaction
per person (replaced, not stacked), a client-generated client_id that
makes a retried send idempotent, a revoke that clears the body while
keeping the row so replies still have something to quote, and a direct
conversation that cannot be created twice for the same pair.
MEMBERSHIP_RECHECK_SECONDS
module-attribute
¶
Default interval between membership re-checks on an open stream.
The removal event closes a stream the moment the SDK's own leave or
remove_participant runs; the re-check is what catches a membership
ended by any other path — a script, an admin panel, a direct UPDATE.
FORWARD_TARGETS_MAX
module-attribute
¶
Most conversations one forward may fan out to.
A forward writes one message, its attachment rows and one SSE publish per target, so an unbounded list turned a single request into an arbitrary number of writes.
MESSAGE_ATTACHMENTS_MAX
module-attribute
¶
Most attachment ids a single message may claim.
Each id costs a lookup and an UPDATE on the post path.
MESSAGE_BODY_MAX_LENGTH
module-attribute
¶
Longest body, in characters, a posted or edited message may carry.
The column is TEXT, so without a bound the only ceiling was the
request size the server happened to accept — and every reader of the
thread then downloads that body on every history page.
MESSAGES_PAGE_SIZE_MAX
module-attribute
¶
Largest page_size the chat router accepts for the history page.
PARTICIPANT_IDS_MAX
module-attribute
¶
Most user ids one request may add to a conversation.
Bounds the start and add-participants paths per request; a larger group is built across several requests.
REPLY_EXCERPT_LENGTH
module-attribute
¶
How much of a quoted message the reply stub carries.
The quote has to render without a second round-trip, and re-sending the whole parent — attachments and reactions included — under every reply multiplies the payload of a history page by the number of replies in it.
PARTICIPANT_REMOVED_EVENT
module-attribute
¶
SSE event published when a member leaves or is removed.
Its data is the :class:ParticipantResponseSchema of the row that
just got its left_at. The chat router's stream reads it to close the
connections of the user it names: their membership ended, so the
conversation's channel must stop reaching them.
ConversationKindEnum
¶
Bases: BaseStrEnum
Whether a conversation is a private pair or a named group.
The split is a column rather than "a group is one with a title", because a direct thread has no title by design — it is labelled by the other person, which is a per-reader answer and never a stored one.
Attributes:
| Name | Type | Description |
|---|---|---|
DIRECT |
str
|
Exactly two people, created once per pair. |
GROUP |
str
|
Any number of people, with a title and roles. |
MessageKindEnum
¶
Bases: BaseStrEnum
What a message carries.
body holds the text of a :attr:TEXT message and the caption of
every media kind, so a caption never needs a second column and an
empty caption is an empty string.
Attributes:
| Name | Type | Description |
|---|---|---|
TEXT |
str
|
Plain text. |
IMAGE |
str
|
One or more images, in the attachment table. |
VIDEO |
str
|
A video. |
AUDIO |
str
|
An audio file. |
VOICE |
str
|
A recorded voice note (drawn with a waveform). |
DOCUMENT |
str
|
An arbitrary file. |
LOCATION |
str
|
Coordinates, in |
CONTACT |
str
|
A contact card, in |
SYSTEM |
str
|
A notice the server wrote ("Ana criou o grupo"),
with its structured event in |
ParticipantRoleEnum
¶
Bases: BaseStrEnum
What a participant may do inside a conversation.
Attributes:
| Name | Type | Description |
|---|---|---|
MEMBER |
str
|
Can read and post. |
ADMIN |
str
|
Can also add/remove members and edit group data. |
OWNER |
str
|
The creator; cannot be removed by an admin. |
SystemEventEnum
¶
Bases: BaseStrEnum
The structured event behind a :attr:MessageKindEnum.SYSTEM message.
The client renders from this plus payload's ids, so the notice
is localized and the names are links. The rendered body the
server writes is the fallback for push notifications and search,
never the primary representation.
Attributes:
| Name | Type | Description |
|---|---|---|
CONVERSATION_CREATED |
str
|
The group was created. |
PARTICIPANTS_ADDED |
str
|
Someone added members. |
PARTICIPANT_REMOVED |
str
|
Someone was removed. |
PARTICIPANT_LEFT |
str
|
Someone left on their own. |
TITLE_CHANGED |
str
|
The group title changed. |
DESCRIPTION_CHANGED |
str
|
The group description changed. |
ROLE_CHANGED |
str
|
A participant's role changed. |
BaseConversationModel
¶
Bases: BaseModel
Abstract conversation/thread row.
title stays NULL for a direct thread on purpose: a direct
conversation is labelled by the other person, which is a per-reader
answer and therefore never a stored column.
last_message_at is denormalized from the newest message so the
conversation list orders and paginates without touching the messages
table. Write it in the same transaction as the message that moves it.
Attributes:
| Name | Type | Description |
|---|---|---|
kind |
ConversationKindEnum
|
Direct thread or group. |
title |
str | None
|
Human label for a group. |
description |
str | None
|
The group's subject text. |
avatar_path |
str | None
|
Storage key of the group picture — a key, never a URL, because a URL is a capability with a TTL and storing one freezes an access into the row. |
created_by |
UUID | None
|
The user who opened the conversation. |
last_message_at |
datetime | None
|
Timestamp of the newest
message, or |
last_message_id |
UUID | None
|
Id of that newest message. Not an FK, so deleting a message never has to update it first. |
BaseConversationParticipantModel
¶
Bases: BaseModel
Abstract join row: one user's membership in one conversation.
Read state is a watermark, not a row per message per reader. A
message counts as read by this participant when
last_read_at >= message.created_at, so a group of 200 people
costs 200 rows in total rather than 200 rows per message, and marking
a thread read is one UPDATE instead of a bulk insert. The cost is
that "read" is per-instant rather than per-message — which is exactly
the granularity a messenger UI shows.
The row survives leaving (left_at set, not deleted), because old
messages still have to resolve a sender name.
Preferences live here and not on the conversation: pinning, archiving and muting are decisions about your inbox. Written on the conversation they would silence the thread for everyone.
Attributes:
| Name | Type | Description |
|---|---|---|
conversation_id |
UUID
|
FK to the conversation (set by subclass). |
user_id |
UUID
|
FK to the participant user (set by subclass). |
role |
ParticipantRoleEnum
|
Member, admin or owner. |
joined_at |
datetime | None
|
When the membership started. |
left_at |
datetime | None
|
When it ended, or |
history_from |
datetime | None
|
Earliest message this participant
may read. |
muted_until |
datetime | None
|
Notifications suppressed until
this instant. |
is_pinned |
bool
|
Pinned to the top of this user's list. |
is_archived |
bool
|
Archived for this user. |
last_read_at |
datetime | None
|
Read watermark. |
last_read_message_id |
UUID | None
|
The message that moved the watermark, kept for the "unread from here" divider. |
last_delivered_at |
datetime | None
|
Delivery watermark, moved when a live connection acknowledges a message. |
BaseMessageAttachmentModel
¶
Bases: BaseModel
Abstract row for one file carried by a message.
A separate table rather than columns on the message, because an album posts several images under one message and because dimensions, duration and waveform mean nothing for text.
message_id is nullable, and that is the whole point of the
two-step upload: the row is written when the bytes land, and the
message that claims it may not exist for another minute — or ever, if
the sender gives up. Declaring it NOT NULL makes every upload
fail with an integrity error.
storage_key is a storage key, never a URL: a URL is minted per
read with a short TTL, so storing one freezes a capability into the
row.
uploader_id is what stops the two-step upload from being a
capability: between the upload and the post, the attachment id is the
only thing tying the file to anyone, and an id leaks (a log line, a
shared URL). With the uploader recorded, ChatService claims the row
only for a message whose sender is that uploader. The column is
nullable for rows written before it existed: a NULL uploader
keeps the old rule — claimable by whoever names the id — so upgrading
does not strand files already uploaded and not yet posted. It is not an
FK, like created_by on a conversation, so deleting a user never has
to decide whether their unposted uploads survive.
Attributes:
| Name | Type | Description |
|---|---|---|
message_id |
UUID | None
|
FK to the owning message, or |
uploader_id |
UUID | None
|
The user who uploaded the file, or
|
position |
int
|
Order within the message, 0-based. |
storage_key |
str
|
Storage key of the stored file. |
thumbnail_key |
str | None
|
Key of the generated preview. |
filename |
str
|
Original filename, shown for documents. |
mime_type |
str
|
Type sniffed from the bytes, not the client's claim. |
size_bytes |
int
|
Size of the stored object. |
width |
int | None
|
Pixel width, for image and video. |
height |
int | None
|
Pixel height, for image and video. |
duration_ms |
int | None
|
Duration, for audio, voice and video. |
waveform |
list[int] | None
|
Normalized amplitude buckets (0-100) for a voice note. Supplied by the recorder, because the reader has to draw the bar before fetching the audio. |
BaseMessageModel
¶
Bases: BaseModel
Abstract message row posted to a conversation.
body holds the text of a TEXT message and the caption of
every media kind, so a caption never needs a second column.
Deleting is two-valued on purpose. revoked_at is delete for
everyone: the row survives so the thread keeps its shape and replies
still have something to quote, while body is cleared — actually
cleared, not hidden behind a flag the next query forgets to filter —
and the attachments leave storage.
client_id is what makes a retried send idempotent. A POST
whose 201 is lost leaves the client unable to tell whether the
message landed: resending blindly posts twice, not resending loses
it. With an id the client generates before the request, unique per
sender, the retry returns the row that was already written. It is the
same problem the SDK's IdempotencyMiddleware solves for HTTP in
general, but the key here is a domain value — it outlives the request
and belongs to the message.
Attributes:
| Name | Type | Description |
|---|---|---|
conversation_id |
UUID
|
FK to the owning conversation (set by subclass). |
sender_id |
UUID
|
FK to the sending user (set by subclass).
Non-null even for a |
kind |
MessageKindEnum
|
What the message carries. |
body |
str
|
Text, or the caption of a media message. |
client_id |
str | None
|
Sender-generated id; unique per sender. |
reply_to_id |
UUID | None
|
The message being replied to. |
forwarded_from_id |
UUID | None
|
The original of a forward. |
forward_score |
int
|
How many hops this content has travelled. |
edited_at |
datetime | None
|
When the body was last edited. |
revoked_at |
datetime | None
|
When it was deleted for everyone. |
payload |
dict[str, Any] | None
|
Kind-specific structured data —
a |
BaseMessageReactionModel
¶
Bases: BaseModel
Abstract row for one person's reaction to one message.
The uniqueness that matters is (message_id, user_id), not
(message_id, user_id, emoji): one reaction per person, and
reacting again replaces it. The wider constraint is exactly what
turns a double-tap into two reactions.
Attributes:
| Name | Type | Description |
|---|---|---|
message_id |
UUID
|
FK to the reacted message (set by subclass). |
user_id |
UUID
|
FK to the reacting user (set by subclass). |
emoji |
str
|
The emoji itself, stored as text. |
AttachmentResponseSchema
¶
Bases: BaseSchema
One file carried by a message.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
UUID
|
The attachment row id. |
position |
int
|
Order within the message, 0-based. |
storage_key |
str
|
Storage key — mint a URL per read; never store one. |
thumbnail_key |
str | None
|
Key of the generated preview. |
filename |
str
|
Original filename. |
mime_type |
str
|
Type sniffed from the bytes. |
size_bytes |
int
|
Size of the stored object. |
width |
int | None
|
Pixel width. |
height |
int | None
|
Pixel height. |
duration_ms |
int | None
|
Duration in milliseconds. |
waveform |
list[int]
|
Amplitude buckets for a voice note. |
ConversationCreateSchema
¶
Bases: BaseSchema
Payload to start a conversation.
Attributes:
| Name | Type | Description |
|---|---|---|
participant_ids |
list[UUID]
|
The users to add. The authenticated creator is added automatically, so this lists only the other members. |
kind |
ConversationKindEnum | None
|
Direct thread or group. |
title |
str | None
|
Group title. |
description |
str | None
|
Group subject text. |
ConversationResponseSchema
¶
Bases: BaseSchema
A conversation as returned to clients.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
UUID
|
The conversation id. |
kind |
ConversationKindEnum
|
Direct thread or group. |
title |
str | None
|
The title, if any. |
description |
str | None
|
The subject text, if any. |
avatar_path |
str | None
|
Storage key of the picture. |
created_by |
UUID | None
|
Who opened it. |
created_at |
datetime
|
When it was created. |
last_message_at |
datetime | None
|
When the newest message landed. |
participants |
list[ParticipantResponseSchema]
|
The membership rows, when the caller asked for them. |
unread_count |
int | None
|
Messages after this caller's read watermark, when the caller asked for it. |
ConversationUpdateSchema
¶
Bases: BaseSchema
Payload to edit a group's data.
Attributes:
| Name | Type | Description |
|---|---|---|
title |
str | None
|
New title, when given. |
description |
str | None
|
New description, when given. |
ForwardSchema
¶
Bases: BaseSchema
Payload to forward a message into other conversations.
Attributes:
| Name | Type | Description |
|---|---|---|
conversation_ids |
list[UUID]
|
Where to forward it. |
MarkReadSchema
¶
Bases: BaseSchema
Payload to move a participant's read watermark.
Attributes:
| Name | Type | Description |
|---|---|---|
message_id |
UUID | None
|
Read up to and including this message.
|
MessageCreateSchema
¶
Bases: BaseSchema
Payload to post a message.
Attributes:
| Name | Type | Description |
|---|---|---|
body |
str
|
The text, or the caption of a media message. Empty
is valid for media; a |
kind |
MessageKindEnum
|
What the message carries. |
client_id |
str | None
|
An id the client generates before sending. Retrying with the same one returns the message that was already stored instead of posting a second copy. |
reply_to_id |
UUID | None
|
The message being replied to. |
attachment_ids |
list[UUID]
|
Files already uploaded and not yet claimed by a message, in render order. |
payload |
dict[str, Any] | None
|
Structured data for a
|
MessageEditSchema
¶
Bases: BaseSchema
Payload to edit a message's body.
Attributes:
| Name | Type | Description |
|---|---|---|
body |
str
|
The new text. |
MessageResponseSchema
¶
Bases: BaseSchema
A message as returned to clients.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
UUID
|
The message id. |
conversation_id |
UUID
|
The owning conversation. |
sender_id |
UUID
|
Who sent it, or the actor of a system notice. |
kind |
MessageKindEnum
|
What it carries. |
body |
str
|
Text or caption; empty once revoked. |
client_id |
str | None
|
The sender's idempotency id, echoed so a client can match it against its optimistic row. |
reply_to |
ReplyPreviewSchema | None
|
The quoted parent. |
forwarded_from_id |
UUID | None
|
The original of a forward. |
forward_score |
int
|
How many hops the content has travelled. |
edited_at |
datetime | None
|
When the body was last edited. |
revoked_at |
datetime | None
|
When it was deleted for everyone. |
payload |
dict[str, Any] | None
|
Kind-specific structured data. |
attachments |
list[AttachmentResponseSchema]
|
Files it carries. |
reactions |
list[ReactionSummarySchema]
|
Reactions, grouped by emoji. |
receipts |
ReceiptCountsSchema | None
|
Delivery/read counts, when the caller asked for them. |
created_at |
datetime
|
When it was posted. |
ParticipantPreferencesSchema
¶
Bases: BaseSchema
Payload to change your own view of a conversation.
Pinning, archiving and muting are decisions about your inbox, not about the thread — written on the conversation they would apply to everyone in it.
Attributes:
| Name | Type | Description |
|---|---|---|
is_pinned |
bool | None
|
Pin or unpin, when given. |
is_archived |
bool | None
|
Archive or unarchive, when given. |
muted_until |
datetime | None
|
Mute until this instant. |
ParticipantResponseSchema
¶
Bases: BaseSchema
One membership row as returned to clients.
Attributes:
| Name | Type | Description |
|---|---|---|
user_id |
UUID
|
The participant. |
role |
ParticipantRoleEnum
|
What they may do. |
joined_at |
datetime | None
|
When they joined. |
left_at |
datetime | None
|
When they left, or |
is_pinned |
bool
|
Whether this user pinned the thread. |
is_archived |
bool
|
Whether they archived it. |
muted_until |
datetime | None
|
Mute expiry, or |
last_read_at |
datetime | None
|
Their read watermark. |
ReactionCreateSchema
¶
Bases: BaseSchema
Payload to react to a message.
Attributes:
| Name | Type | Description |
|---|---|---|
emoji |
str
|
The emoji. Reacting again with a different one replaces the previous reaction rather than adding to it. |
ReactionSummarySchema
¶
Bases: BaseSchema
One emoji and who reacted with it.
Attributes:
| Name | Type | Description |
|---|---|---|
emoji |
str
|
The emoji. |
count |
int
|
How many people chose it. |
user_ids |
list[UUID]
|
Who they are, so a client can render "you and 3 others" without another request. |
ReceiptCountsSchema
¶
Bases: BaseSchema
How far a message has travelled, derived from the watermarks.
Counts come from comparing each participant's last_read_at /
last_delivered_at against the message's created_at — there is
no row per message per reader to count.
Attributes:
| Name | Type | Description |
|---|---|---|
delivered |
int
|
Participants whose delivery watermark has passed the message. |
read |
int
|
Participants whose read watermark has passed it. |
total |
int
|
Participants other than the sender. |
ReplyPreviewSchema
¶
Bases: BaseSchema
The quoted parent, small enough to inline under every reply.
revoked is the field an obvious implementation forgets: deleting
the quoted message has to delete the quote too, or the text leaks
back through whoever replied to it.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
UUID
|
The quoted message's id. |
sender_id |
UUID
|
Who wrote it. |
kind |
MessageKindEnum
|
What it carried, so the stub can show "Photo" instead of an empty line. |
excerpt |
str
|
The first :data: |
revoked |
bool
|
Whether the quoted message was deleted for everyone. Render the tombstone, never the excerpt. |
created_at |
datetime | None
|
When the quoted message was posted.
The excerpt is empty for a reader whose |
ChatMessageLike
¶
Bases: Protocol
The three attributes :meth:ChatService.receipt_counts reads.
Declared as read-only properties so concrete subclasses of
:class:~tempest_fastapi_sdk.chat.BaseMessageModel,
:class:~tempest_fastapi_sdk.chat.MessageResponseSchema, and
lightweight test doubles are all accepted.
ChatService
¶
ChatService(
*,
conversations: BaseRepository[Any],
participants: BaseRepository[Any],
messages: BaseRepository[Any],
attachments: BaseRepository[Any] | None = None,
reactions: BaseRepository[Any] | None = None,
broker: SSEBroker | None = None,
)
Create conversations, post messages, and keep read state.
Attributes:
| Name | Type | Description |
|---|---|---|
conversations |
BaseRepository[Any]
|
Conversation table. |
participants |
BaseRepository[Any]
|
Participant join table. |
messages |
BaseRepository[Any]
|
Message table. |
attachments |
BaseRepository[Any] | None
|
Attachment table.
|
reactions |
BaseRepository[Any] | None
|
Reaction table. |
broker |
SSEBroker | None
|
Optional SSE fan-out; when set, every
change is published to channel |
Initialize the service.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conversations
|
BaseRepository[Any]
|
Conversation repository. |
required |
participants
|
BaseRepository[Any]
|
Participant repository. |
required |
messages
|
BaseRepository[Any]
|
Message repository. |
required |
attachments
|
BaseRepository[Any] | None
|
Attachment repository, when the product carries media. |
None
|
reactions
|
BaseRepository[Any] | None
|
Reaction repository, when the product has reactions. |
None
|
broker
|
SSEBroker | None
|
Optional real-time fan-out broker. |
None
|
start_conversation
async
¶
start_conversation(
creator_id: UUID,
participant_ids: list[UUID],
*,
kind: ConversationKindEnum | str | None = None,
title: str | None = None,
description: str | None = None,
) -> ConversationResponseSchema
Create a conversation, or return the pair's existing one.
The creator is always a participant — their id is merged into
participant_ids — and takes the OWNER role in a group.
A DIRECT conversation is idempotent per pair: asking
twice for the same two people returns the conversation that
already exists. Two threads between the same two people is a
state the user cannot repair from the UI, and it is what happens
whenever two clients open the same chat at once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
creator_id
|
UUID
|
The user starting the conversation. |
required |
participant_ids
|
list[UUID]
|
The other users to add. |
required |
kind
|
ConversationKindEnum | str | None
|
Direct thread or
group. |
None
|
title
|
str | None
|
Group title. |
None
|
description
|
str | None
|
Group subject text. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
ConversationResponseSchema |
ConversationResponseSchema
|
The created — or existing — |
ConversationResponseSchema
|
conversation. |
Raises:
| Type | Description |
|---|---|
ValidationException
|
When a direct conversation is asked for with anything other than exactly two distinct people. |
get_conversation
async
¶
get_conversation(conversation_id: UUID) -> ConversationResponseSchema
Return a single conversation by id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conversation_id
|
UUID
|
The conversation id. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ConversationResponseSchema |
ConversationResponseSchema
|
The conversation, with its |
ConversationResponseSchema
|
participants. |
Raises:
| Type | Description |
|---|---|
AppException
|
The repository's not-found exception when no conversation matches. |
is_participant
async
¶
Return whether user_id is an active member.
Someone who left keeps their row — old messages still have to
resolve a sender name — so membership is left_at IS NULL,
not mere existence of the row.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conversation_id
|
UUID
|
The conversation to check. |
required |
user_id
|
UUID
|
The user to check. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
list_conversations
async
¶
list_conversations(
user_id: UUID, *, include_archived: bool = False
) -> list[ConversationResponseSchema]
Return the conversations user_id is in, newest first.
Pinned threads come first, then by newest message. Returns []
when the user is in none, per the SDK collection convention.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
UUID
|
The user whose conversations to list. |
required |
include_archived
|
bool
|
Whether archived threads are included. |
False
|
Returns:
| Type | Description |
|---|---|
list[ConversationResponseSchema]
|
list[ConversationResponseSchema]: The user's conversations, |
list[ConversationResponseSchema]
|
each carrying that user's |
add_attachment
async
¶
add_attachment(
uploader_id: UUID,
*,
storage_key: str,
filename: str = "",
mime_type: str = "application/octet-stream",
size_bytes: int = 0,
thumbnail_key: str | None = None,
width: int | None = None,
height: int | None = None,
duration_ms: int | None = None,
waveform: list[int] | None = None,
) -> AttachmentResponseSchema
Record an uploaded file as an unclaimed attachment of its uploader.
The first half of the two-step upload: call it once the bytes are
stored, hand the returned id back to the uploader, and let the
uploader name it in MessageCreateSchema.attachment_ids. The row
is written with uploader_id set, so :meth:post_message claims
it only for a message sent by that same user — anyone else who
learns the id gets the same 404 as for an id that does not
exist.
Writing the row yourself works too, as long as it carries
uploader_id; a row without one is claimable by any sender.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uploader_id
|
UUID
|
The user who uploaded the file. |
required |
storage_key
|
str
|
Storage key of the stored file — a key, never a URL. |
required |
filename
|
str
|
Original filename, shown for documents. |
''
|
mime_type
|
str
|
Type sniffed from the bytes, not the client's claim. |
'application/octet-stream'
|
size_bytes
|
int
|
Size of the stored object. |
0
|
thumbnail_key
|
str | None
|
Key of the generated preview. |
None
|
width
|
int | None
|
Pixel width, for image and video. |
None
|
height
|
int | None
|
Pixel height, for image and video. |
None
|
duration_ms
|
int | None
|
Duration, for audio, voice and video. |
None
|
waveform
|
list[int] | None
|
Normalized amplitude buckets (0-100) for a voice note. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
AttachmentResponseSchema |
AttachmentResponseSchema
|
The stored row; its |
AttachmentResponseSchema
|
the uploader posts. |
Raises:
| Type | Description |
|---|---|
ValidationException
|
When the service was built without an attachment repository. |
post_message
async
¶
post_message(
conversation_id: UUID, sender_id: UUID, data: MessageCreateSchema | str
) -> MessageResponseSchema
Persist a message and publish it, idempotently.
A retry carrying the client_id of a message that was already
stored returns that message — the same row, not a second copy.
That is the whole reason the id exists: a POST whose 201
is lost leaves the client unable to tell whether the message
landed.
The id is unique per sender, not per conversation, because
that is the uniqueness the table can enforce. So reusing one in a
different conversation is refused rather than answered: returning
the stored message would hand back a row belonging to another
thread, with a 201, while the message the caller actually
sent was never written.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conversation_id
|
UUID
|
The target conversation. |
required |
sender_id
|
UUID
|
The sending user. |
required |
data
|
MessageCreateSchema | str
|
The payload. A bare string is accepted as the body of a text message, which is what the previous signature took. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
MessageResponseSchema |
MessageResponseSchema
|
The persisted message. |
Raises:
| Type | Description |
|---|---|
ValidationException
|
When the message would carry nothing — no body and no attachments — or names attachments while the service has no attachment repository. |
NotFoundException
|
When |
edit_message
async
¶
edit_message(message_id: UUID, editor_id: UUID, body: str) -> MessageResponseSchema
Replace a message's body and stamp edited_at.
The editor must still be able to see the message — an active
participant, within their history_from — so a sender who left
the conversation can no longer rewrite what they said in it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message_id
|
UUID
|
The message to edit. |
required |
editor_id
|
UUID
|
Who is editing; must be the sender. |
required |
body
|
str
|
The new text. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
MessageResponseSchema |
MessageResponseSchema
|
The edited message. |
Raises:
| Type | Description |
|---|---|
AppException
|
The message repository's not-found exception when the message is missing or not visible to the editor. |
ForbiddenException
|
When the editor is not the sender. |
ValidationException
|
When the message was already revoked. |
revoke_message
async
¶
revoke_message(
message_id: UUID, actor_id: UUID
) -> tuple[MessageResponseSchema, list[str]]
Delete a message for everyone, keeping it as a tombstone.
The row survives so the thread keeps its shape and replies still have something to quote — but the body is cleared, not hidden behind a flag the next query forgets to filter, and the attachment rows go with it.
A key is reported only when no other attachment row still
references it. A forward points its copy at the same
storage_key — it copies the row, never the bytes — so
revoking the original must not hand the caller a key the
forwarded copy still renders; the key is reported by whichever
revoke removes its last reference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message_id
|
UUID
|
The message to revoke. |
required |
actor_id
|
UUID
|
Who is revoking; must be the sender, and still an active participant who can see the message. |
required |
Returns:
| Type | Description |
|---|---|
MessageResponseSchema
|
tuple[MessageResponseSchema, list[str]]: The tombstone, and |
list[str]
|
the storage keys the caller must now delete from storage — |
tuple[MessageResponseSchema, list[str]]
|
the SDK does not own the bucket, and a key left behind is a |
tuple[MessageResponseSchema, list[str]]
|
file that outlives the message that justified it. |
Raises:
| Type | Description |
|---|---|
AppException
|
The message repository's not-found exception when the message is missing or not visible to the actor. |
ForbiddenException
|
When the actor is not the sender. |
react
async
¶
react(message_id: UUID, user_id: UUID, emoji: str) -> MessageResponseSchema
Set this user's reaction, replacing any previous one.
One reaction per person: reacting again replaces. That is
the (message_id, user_id) uniqueness — widening it to
include the emoji is what turns a double-tap into two reactions.
The reactor must be able to see the message: an active
participant of its conversation, within their history_from.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message_id
|
UUID
|
The message reacted to. |
required |
user_id
|
UUID
|
Who is reacting. |
required |
emoji
|
str
|
The emoji. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
MessageResponseSchema |
MessageResponseSchema
|
The message, with reactions rebuilt. |
Raises:
| Type | Description |
|---|---|
AppException
|
The message repository's not-found exception when the message is missing or not visible to the user. |
ValidationException
|
When the service has no reaction repository. |
unreact
async
¶
unreact(message_id: UUID, user_id: UUID) -> MessageResponseSchema
Remove this user's reaction, if any.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message_id
|
UUID
|
The message. |
required |
user_id
|
UUID
|
Who is un-reacting. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
MessageResponseSchema |
MessageResponseSchema
|
The message, with reactions rebuilt. |
Raises:
| Type | Description |
|---|---|
AppException
|
The message repository's not-found exception when the message is missing or not visible to the user. |
ValidationException
|
When the service has no reaction repository. |
forward
async
¶
forward(
message_id: UUID, sender_id: UUID, conversation_ids: list[UUID]
) -> list[MessageResponseSchema]
Copy a message into other conversations.
The copy carries forwarded_from_id and a forward_score
one higher than the original's, which is what lets a client
label content that has travelled far.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message_id
|
UUID
|
The message to forward. |
required |
sender_id
|
UUID
|
Who is forwarding. |
required |
conversation_ids
|
list[UUID]
|
Where to forward it. |
required |
Returns:
| Type | Description |
|---|---|
list[MessageResponseSchema]
|
list[MessageResponseSchema]: One message per target, in the |
list[MessageResponseSchema]
|
order given. |
Raises:
| Type | Description |
|---|---|
AppException
|
The message repository's not-found exception when the original is missing or not visible to the sender — forwarding copies the body and the attachment rows, so it is a read of the original. |
ForbiddenException
|
When the sender is not a participant of a target conversation. |
mark_read
async
¶
mark_read(
conversation_id: UUID, user_id: UUID, *, message_id: UUID | None = None
) -> ParticipantResponseSchema
Move this participant's read watermark.
One UPDATE on one row, not a receipt row per message per
reader: in a group of 200 that would be 200 inserts per message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conversation_id
|
UUID
|
The conversation being read. |
required |
user_id
|
UUID
|
The reader. |
required |
message_id
|
UUID | None
|
Read up to and including this
message; |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
ParticipantResponseSchema |
ParticipantResponseSchema
|
The updated membership row. |
Raises:
| Type | Description |
|---|---|
ForbiddenException
|
When the user is not an active member. |
NotFoundException
|
When |
mark_delivered
async
¶
mark_delivered(conversation_id: UUID, user_id: UUID) -> ParticipantResponseSchema
Move this participant's delivery watermark to now.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conversation_id
|
UUID
|
The conversation. |
required |
user_id
|
UUID
|
The recipient whose client just connected. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ParticipantResponseSchema |
ParticipantResponseSchema
|
The updated membership row. |
Raises:
| Type | Description |
|---|---|
ForbiddenException
|
When the user is not an active member. |
receipt_counts
async
¶
receipt_counts(message: ChatMessageLike) -> ReceiptCountsSchema
Count who has received and read one message.
Derived from the watermarks — a participant has read the message
when last_read_at >= message.created_at — so there is no
per-message, per-reader row to count.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
ChatMessageLike
|
The message row or response carrying
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
ReceiptCountsSchema |
ReceiptCountsSchema
|
Delivered / read / total counts, |
ReceiptCountsSchema
|
excluding the sender. |
list_messages
async
¶
list_messages(
conversation_id: UUID,
*,
user_id: UUID | None = None,
page: int = 1,
page_size: int = 20,
ascending: bool = True,
with_receipts: bool = False,
) -> dict[str, Any]
Return an offset page of a conversation's messages.
When user_id is given, the page respects that participant's
history_from — someone added to a group later does not
inherit the backlog unless the product says so. That covers the
derived copies too: a reply on the page that quotes a message
older than history_from carries an empty excerpt.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conversation_id
|
UUID
|
The conversation to page. |
required |
user_id
|
UUID | None
|
The reader, for |
None
|
page
|
int
|
1-indexed page number. |
1
|
page_size
|
int
|
Messages per page. |
20
|
ascending
|
bool
|
Oldest-first when |
True
|
with_receipts
|
bool
|
Attach delivery/read counts to each message. |
False
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: |
dict[str, Any]
|
class: |
dict[str, Any]
|
|
Raises:
| Type | Description |
|---|---|
ValidationException
|
When |
add_participants
async
¶
add_participants(
conversation_id: UUID,
actor_id: UUID,
user_ids: list[UUID],
*,
share_history: bool = False,
) -> ConversationResponseSchema
Add members to a group and post the system notice.
A member who joins does not inherit the backlog by default:
history_from is stamped at the moment they join, so the group
decides what a newcomer can read rather than the absence of a
column deciding it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conversation_id
|
UUID
|
The group. |
required |
actor_id
|
UUID
|
Who is adding; must be admin or owner. |
required |
user_ids
|
list[UUID]
|
Who to add. |
required |
share_history
|
bool
|
Hand over the whole backlog instead. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
ConversationResponseSchema |
ConversationResponseSchema
|
The updated conversation. |
Raises:
| Type | Description |
|---|---|
ForbiddenException
|
When the actor may not add members. |
ValidationException
|
When the conversation is a direct thread. |
remove_participant
async
¶
remove_participant(
conversation_id: UUID, actor_id: UUID, user_id: UUID
) -> ConversationResponseSchema
Remove a member, keeping their row as a tombstone.
After the system notice, a participant.removed event carrying
the membership row is published on the conversation's channel;
:func:~tempest_fastapi_sdk.chat.make_chat_router closes the
removed user's open streams when it sees one naming them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conversation_id
|
UUID
|
The group. |
required |
actor_id
|
UUID
|
Who is removing; must be admin or owner. |
required |
user_id
|
UUID
|
Who to remove. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ConversationResponseSchema |
ConversationResponseSchema
|
The updated conversation. |
Raises:
| Type | Description |
|---|---|
ForbiddenException
|
When the actor may not remove members, or the target is the owner. |
leave
async
¶
leave(conversation_id: UUID, user_id: UUID) -> ConversationResponseSchema
Leave a conversation on your own.
Publishes the same participant.removed event as
:meth:remove_participant, so the leaver's open streams close
too.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conversation_id
|
UUID
|
The conversation to leave. |
required |
user_id
|
UUID
|
Who is leaving. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ConversationResponseSchema |
ConversationResponseSchema
|
The updated conversation. |
Raises:
| Type | Description |
|---|---|
ForbiddenException
|
When the user is not an active member. |
set_role
async
¶
set_role(
conversation_id: UUID,
actor_id: UUID,
user_id: UUID,
role: ParticipantRoleEnum | str,
) -> ParticipantResponseSchema
Promote or demote a participant.
Roles form a hierarchy. An admin may promote a member to admin;
only the owner may grant OWNER, change an owner's role or
change another admin's role. Without that rule an admin could
demote the owner, take OWNER for themselves and then remove
the creator, which :meth:remove_participant alone refuses.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conversation_id
|
UUID
|
The group. |
required |
actor_id
|
UUID
|
Who is changing it; must be admin or owner. |
required |
user_id
|
UUID
|
Whose role changes. |
required |
role
|
ParticipantRoleEnum | str
|
The new role. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ParticipantResponseSchema |
ParticipantResponseSchema
|
The updated membership. |
Raises:
| Type | Description |
|---|---|
ForbiddenException
|
When the actor may not change roles, or
is an admin trying to grant |
update_conversation
async
¶
update_conversation(
conversation_id: UUID,
actor_id: UUID,
*,
title: str | None = None,
description: str | None = None,
) -> ConversationResponseSchema
Edit a group's title or description.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conversation_id
|
UUID
|
The group. |
required |
actor_id
|
UUID
|
Who is editing; must be admin or owner. |
required |
title
|
str | None
|
New title, when given. |
None
|
description
|
str | None
|
New description, when given. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
ConversationResponseSchema |
ConversationResponseSchema
|
The updated conversation. |
Raises:
| Type | Description |
|---|---|
ForbiddenException
|
When the actor may not edit the group. |
set_preferences
async
¶
set_preferences(
conversation_id: UUID,
user_id: UUID,
*,
is_pinned: bool | None = None,
is_archived: bool | None = None,
muted_until: datetime | None = None,
) -> ParticipantResponseSchema
Change this user's own view of a conversation.
Pin, archive and mute live on the membership row, so they apply to one inbox. Written on the conversation they would mute the thread for everyone in it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conversation_id
|
UUID
|
The conversation. |
required |
user_id
|
UUID
|
Whose preferences change. |
required |
is_pinned
|
bool | None
|
Pin or unpin. |
None
|
is_archived
|
bool | None
|
Archive or unarchive. |
None
|
muted_until
|
datetime | None
|
Mute until this instant. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
ParticipantResponseSchema |
ParticipantResponseSchema
|
The updated membership row. |
Raises:
| Type | Description |
|---|---|
ForbiddenException
|
When the user is not an active member. |
make_conversation_model
¶
make_conversation_model(
*,
user_table: str | None = None,
tablename: str = "conversations",
class_name: str = "ConversationModel",
) -> type[BaseConversationModel]
Build a concrete ConversationModel subclass at runtime.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_table
|
str | None
|
Table the |
None
|
tablename
|
str
|
|
'conversations'
|
class_name
|
str
|
Python class name (affects repr / Alembic ids). |
'ConversationModel'
|
Returns:
| Type | Description |
|---|---|
type[BaseConversationModel]
|
type[BaseConversationModel]: A concrete mapped class. |
make_conversation_participant_model
¶
make_conversation_participant_model(
*,
conversation_table: str = "conversations",
user_table: str = "users",
tablename: str = "conversation_participants",
class_name: str = "ConversationParticipantModel",
) -> type[BaseConversationParticipantModel]
Build a concrete participant join model at runtime.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conversation_table
|
str
|
Table name of the concrete conversation model the FK references. |
'conversations'
|
user_table
|
str
|
Table name of the concrete user model the FK references. |
'users'
|
tablename
|
str
|
|
'conversation_participants'
|
class_name
|
str
|
Python class name. |
'ConversationParticipantModel'
|
Returns:
| Type | Description |
|---|---|
type[BaseConversationParticipantModel]
|
type[BaseConversationParticipantModel]: A concrete mapped class |
type[BaseConversationParticipantModel]
|
with a unique |
make_message_attachment_model
¶
make_message_attachment_model(
*,
message_table: str = "messages",
tablename: str = "message_attachments",
class_name: str = "MessageAttachmentModel",
) -> type[BaseMessageAttachmentModel]
Build a concrete attachment model at runtime.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message_table
|
str
|
Table name of the concrete message model. |
'messages'
|
tablename
|
str
|
|
'message_attachments'
|
class_name
|
str
|
Python class name. |
'MessageAttachmentModel'
|
Returns:
| Type | Description |
|---|---|
type[BaseMessageAttachmentModel]
|
type[BaseMessageAttachmentModel]: A concrete mapped class with a |
type[BaseMessageAttachmentModel]
|
unique |
make_message_model
¶
make_message_model(
*,
conversation_table: str = "conversations",
user_table: str = "users",
tablename: str = "messages",
class_name: str = "MessageModel",
) -> type[BaseMessageModel]
Build a concrete MessageModel subclass at runtime.
The generated class carries the two constraints the behaviour
depends on: (sender_id, client_id) unique, which is what makes a
retried send return the existing row instead of posting twice, and a
(conversation_id, created_at) index, which is the ordering every
history page reads.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conversation_table
|
str
|
Table name of the concrete conversation model the FK references. |
'conversations'
|
user_table
|
str
|
Table name of the concrete user model the sender FK references. |
'users'
|
tablename
|
str
|
|
'messages'
|
class_name
|
str
|
Python class name. |
'MessageModel'
|
Returns:
| Type | Description |
|---|---|
type[BaseMessageModel]
|
type[BaseMessageModel]: A concrete mapped class. |
make_message_reaction_model
¶
make_message_reaction_model(
*,
message_table: str = "messages",
user_table: str = "users",
tablename: str = "message_reactions",
class_name: str = "MessageReactionModel",
) -> type[BaseMessageReactionModel]
Build a concrete reaction model at runtime.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message_table
|
str
|
Table name of the concrete message model. |
'messages'
|
user_table
|
str
|
Table name of the concrete user model. |
'users'
|
tablename
|
str
|
|
'message_reactions'
|
class_name
|
str
|
Python class name. |
'MessageReactionModel'
|
Returns:
| Type | Description |
|---|---|
type[BaseMessageReactionModel]
|
type[BaseMessageReactionModel]: A concrete mapped class with a |
type[BaseMessageReactionModel]
|
unique |
type[BaseMessageReactionModel]
|
person, replaced rather than stacked. |
make_chat_router
¶
make_chat_router(
*,
service_factory: Callable[[AsyncSession], ChatService],
session_factory: Callable[..., AsyncIterator[AsyncSession]],
current_user_id: Callable[..., Any],
prefix: str = "/api/chat",
tags: list[str] | None = None,
max_page_size: int = MESSAGES_PAGE_SIZE_MAX,
membership_recheck_seconds: float | None = MEMBERSHIP_RECHECK_SECONDS,
stream_session_factory: Callable[[], AsyncIterator[AsyncSession]] | None = None,
docs_locale: str | None = None,
) -> APIRouter
Build the chat router.
Endpoints (all require authentication via current_user_id):
POST {prefix}/conversations-> start a conversation (creator is auto-added as a participant).GET {prefix}/conversations-> list the caller's conversations, pinned first then newest.GET {prefix}/conversations/{id}-> one conversation with its participants.PATCH {prefix}/conversations/{id}-> edit a group's title or description.PUT {prefix}/conversations/{id}/preferences-> pin, archive or mute for the caller only.POST {prefix}/conversations/{id}/participants-> add members to a group.DELETE {prefix}/conversations/{id}/participants/{participant_id}-> remove a member from a group.POST {prefix}/conversations/{id}/leave-> leave a conversation.POST {prefix}/conversations/{id}/read-> move the caller's read watermark.POST {prefix}/conversations/{id}/messages-> post a message (caller must be a participant).GET {prefix}/conversations/{id}/messages-> page the history (participant only).PATCH {prefix}/messages/{message_id}-> edit a message you sent.DELETE {prefix}/messages/{message_id}-> delete a message for everyone, leaving a tombstone.PUT {prefix}/messages/{message_id}/reaction-> react, replacing your previous reaction (needs a service built withreactions=).DELETE {prefix}/messages/{message_id}/reaction-> remove your reaction.POST {prefix}/messages/{message_id}/forward-> forward a message into other conversations.GET {prefix}/conversations/{id}/stream-> SSE stream of new messages (participant only; requires the service to carry anSSEBroker).
The stream does not hold a database session while it is open.
The participant check takes its session as
Depends(session_factory, scope="function"), which FastAPI closes
when the endpoint returns, before the first byte is streamed; a
session with the default scope would stay open — connection checked
out, transaction begun — for as long as the client stays connected,
so a few hundred idle tabs would drain the pool. A dependency the
caller wires into current_user_id that itself takes a session is
outside this guarantee.
The stream also ends when the membership does: a
participant.removed event naming the subscriber is delivered and
then the stream closes, and every membership_recheck_seconds —
measured on the frames the stream yields, heartbeats included — the
membership is read again on a short-lived session, which catches a
removal made outside :class:ChatService. That re-check runs while
the response is streaming, outside FastAPI's dependency resolution,
so it opens its session by calling stream_session_factory() —
which defaults to session_factory when that one takes no
parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
service_factory
|
Callable[[AsyncSession], ChatService]
|
Builds a
request-scoped :class: |
required |
session_factory
|
Callable[..., AsyncIterator[AsyncSession]]
|
FastAPI dependency yielding a request-scoped DB session — the
project's |
required |
current_user_id
|
Callable[..., Any]
|
FastAPI dependency resolving
the authenticated user's :class: |
required |
prefix
|
str
|
URL prefix. Defaults to |
'/api/chat'
|
tags
|
list[str] | None
|
OpenAPI tags. Defaults to |
None
|
max_page_size
|
int
|
Largest |
MESSAGES_PAGE_SIZE_MAX
|
membership_recheck_seconds
|
float | None
|
How often an open
stream re-reads the subscriber's membership. |
MEMBERSHIP_RECHECK_SECONDS
|
stream_session_factory
|
Callable[[], AsyncIterator[AsyncSession]] | None
|
Zero-argument factory the open stream calls for the
short-lived session of each membership re-check (for example
|
None
|
docs_locale
|
str | None
|
Language of the OpenAPI |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
APIRouter |
APIRouter
|
Ready to mount with |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |