Message processing
Message processing moves an outbound SMS, data message, or MMS from an API or gateway request to a tracked Android send. It preserves the request in local storage, waits for its scheduling rules, sends each recipient through the device, records the result, and exposes the same progress in cloud state and user-visible history. The detailed device-send rules are covered in Outbound message delivery; inbound SMS and MMS follow the separate Inbound SMS and MMS capture flow.
Lifecycle overview
The application treats a message as durable work rather than as a single immediate Android call. This lets a request survive app backgrounding, serve several recipients, and show progress after the radio operation has finished.
This diagram shows the main outbound path and the two places where the result becomes visible.
flowchart LR
A[Local API request] --> C[Common send request]
B[Cloud gateway request] --> C
C --> D[Durable message and recipients]
D --> E[Scheduled send work]
E --> F[Android telephony service]
F --> G[Recipient results]
G --> H[Aggregate message state]
H --> I[Cloud state update]
H --> J[Local API and app history]
Processing stages
The lifecycle has one shared queue after request intake. A local request enters it directly, while a cloud request is first fetched by the gateway and then converted to the same local send form. State changes pass through one state service that validates the transition, updates storage, and emits the result only after the stored view is current.
- An API or gateway supplies message content, recipients, and delivery controls.
- The application stores one message record and one pending record for each recipient.
- Queue rules decide when the message is eligible and which pending message runs next.
- Android accepts or rejects the send and may later report network delivery.
- The state service validates the recipient result, derives the message state, and records the change.
- Cloud-originated work sends the new state to the gateway. Local history reads the same stored result.
References: app/…/MessagesService.kt• L101-145 app/…/MessageStateService.kt• L57-80 app/…/MessageStateService.kt• L170-187
Request entry points
Both supported outbound sources use the same message service after intake. This keeps queue order, scheduling, recipient tracking, and Android delivery behavior consistent across local and cloud use.
Local API requests
The local HTTP API accepts text, data, or MMS content with one or more phone numbers. It validates the request, assigns an ID when needed, marks the source as local, and returns 202 Accepted after the message is stored and send work is scheduled. The Local HTTP API page describes this interface.
The API also reads message history, reads one message in detail, and cancels a message while it is still pending. These operations expose the queue without making the API responsible for the Android send itself.
References: app/…/MessagesRoutes.kt• L53-70 app/…/MessagesRoutes.kt• L137-209 app/…/MessagesRoutes.kt• L211-260
Cloud gateway requests
The gateway polls the connected cloud service for pending messages. It converts each cloud message into the common send request and stores it locally, so cloud work follows the same device queue as local work. The Cloud gateway integration page describes the cloud boundary.
The gateway also handles cloud cancellation and already-known messages. A message that is already stored causes a state sync instead of a duplicate local record, while a cancellation for a message not found locally is reported as cancelled upstream.
References: app/…/PullMessagesWorker.kt• L21-66 app/…/GatewayService.kt• L240-307 app/…/EventsReceiver.kt• L28-51
Durable message records
Persistence gives each outbound request a stable identity and keeps its overall data separate from the state of each recipient. The record includes the content form, source, creation time, scheduling and expiry limits, priority, delivery-report choice, and selected or chosen SIM. The Persistent storage page explains the wider storage model.
Message and recipient records
The application creates one message record with a pending recipient record for every destination. A multi-recipient request therefore has one shared content record but can show different results for different phone numbers. Supported content includes text, binary data, and MMS with optional subject, text, and attachments.
State timestamps are kept with the record so the application can report when a message reached each known state. The stored form can later be rebuilt into a send request with only recipients that remain pending. Queue reads reconcile a stale stored message state through the state service before they return work.
References: app/…/MessagesRepository.kt• L19-64 app/…/MessagesRepository.kt• L67-85 app/…/MessagesRepository.kt• L87-126 app/…/Message.kt• L25-52 app/…/MessageRecipient.kt• L6-16
Queue scheduling
Queue scheduling separates acceptance from delivery. The application can accept work now and send it later without losing the request or blocking the API response.
Eligibility rules
Only pending messages whose schedule time has arrived enter the send loop. Priority is considered first. The configured FIFO or LIFO order then chooses the oldest or newest eligible message at that priority.
Normal work can wait for work hours, a message-count limit, or a configured interval between sends. Expedited work receives faster treatment and can bypass the work-hour wait. If expedited work becomes due while normal work is outside work hours, the normal work yields so the expedited work can run. An expiry time still applies immediately before sending, so stale work becomes failed instead of being sent late.
References: app/…/MessagesDao.kt• L47-62 app/…/MessagesService.kt• L277-377 app/…/MessagesSettings.kt• L33-69
Background work
Background work keeps the queue active when the application is not in the foreground. A new local message starts send work at the next useful time. When an immediate message arrives while a future run is scheduled, the service starts the queue immediately and keeps the scheduling decision coordinated with worker rescheduling. Enqueue and worker-start decisions are serialized with the queue snapshot, so a concurrent request does not install a delayed run between those decisions. The worker continues until no eligible message remains, then schedules itself for the next future message when one exists.
The gateway uses a separate network-backed pull cycle to bring cloud work into the local queue. This boundary keeps cloud polling and device sending independent while allowing both sources to share the same delivery rules.
References: app/…/MessagesService.kt• L46-61 app/…/MessagesService.kt• L106-145 app/…/MessagesService.kt• L318-328 app/…/SendMessagesWorker.kt• L23-57 app/…/SendMessagesWorker.kt• L77-112 app/…/PullMessagesWorker.kt• L21-66
Android delivery
Android is the final device boundary for outbound delivery. The application prepares text, data, or MMS content, chooses the active subscription when needed, and asks Android's messaging services to send to each pending recipient.
Send and delivery results
The send operation reports two different milestones. Android first reports whether it accepted the send operation. If delivery reports are requested, Android can later report whether the network confirmed delivery.
For SMS and data messages, each Android request is tied to the original message ID and recipient. For MMS, the application marks recipients as processed after it submits the device operation, then changes them to sent or failed when Android returns the MMS result. This prevents the queue from submitting the same MMS again while the device operation is still in progress. A callback that wins a race with the submit path keeps its terminal result because state changes are validated before they are written. The full send behavior belongs to Outbound message delivery.
References: app/…/MessagesService.kt• L174-269 app/…/MessagesService.kt• L382-475 app/…/MessagesService.kt• L495-627 app/…/MessageStateService.kt• L91-143 app/…/EventsReceiver.kt• L18-41
Recipient state model
Recipient state records the result for each destination, while the message state summarizes the whole request. This distinction prevents one failed number from hiding a successful result for another number.
State meanings
The state path describes queue progress, Android acceptance, network delivery, cancellation, and failure. Cancelled is not final in the local state model because a late Android result can replace it with the actual send outcome. Failed is the only terminal state.
| State | Meaning |
|---|---|
Pending | Waiting for an eligible send attempt. |
Cancelled | The request was cancelled before a confirmed send outcome. |
Processed | Android accepted the send request. |
Sent | Android reported a successful send operation. |
Delivered | A delivery report confirmed delivery. |
Failed | Sending or delivery ended with an error. |
References: app/…/ProcessingState.kt• L3-11 app/…/MessageStateTransitions.kt• L26-50 app/…/MessagesService.kt• L201-269
State transition control
The message state service is the single path for local state changes. It reads the current message, checks the allowed transition, writes the recipient result, synchronizes the aggregate message state, and emits a state event only after a valid write. Invalid transitions and repeated states produce no write and no event.
The service serializes this full cycle per message ID. Different messages can progress in parallel, but a send callback, cancellation, queue reconciliation, and another state update for the same message cannot observe and overwrite each other out of order.
References: app/…/MessageStateService.kt• L11-43 app/…/MessageStateService.kt• L57-80 app/…/MessageStateService.kt• L146-168 app/…/PerMessageLock.kt• L7-29
Aggregate state
The message state is derived from its recipients. Pending, cancelled, and processed remain visible when any recipient still has that state. A message is failed only when all recipients fail. It is delivered only when all recipients are delivered; other mixed post-send results appear as sent.
Every update writes the recipient result and a state-history entry. The state service emits a state-change event after the stored view is refreshed, so downstream consumers use the same aggregate and recipient results that the history views show. The Event routing page describes how those events reach other systems.
References: app/…/MessageWithRecipients.kt• L7-32 app/…/MessagesDao.kt• L147-226 app/…/MessageStateService.kt• L91-143 app/…/MessageStateService.kt• L170-187
State propagation
State propagation carries the local result to systems that need it without coupling those systems to the Android callback. The message service emits one internal state-change event with the message ID, source, affected recipients, state, SIM, part count, and error.
Cloud state synchronization
Cloud-originated and gateway-originated messages send state changes back to the cloud. A network worker reads the current local record and sends the aggregate state, each recipient state, errors, and known state times. Local-only messages stop at local persistence and history.
References: app/…/EventsReceiver.kt• L41-51 app/…/SendStateWorker.kt• L23-80 app/…/GatewayApi.kt• L161-166
Cancellation propagation
Cancellation is accepted only when every recipient can still move from its current state to Cancelled. A fully cancelled message is an idempotent no-op. A message with a recipient that has already advanced is rejected instead of being reported as successfully cancelled.
If cancellation races with Android submission, the state table allows a later Sent, Delivered, or Failed result to replace Cancelled. This records the actual device outcome and prevents a cancel response from hiding a send that already crossed the Android boundary.
References: app/…/MessageStateService.kt• L91-143 app/…/MessageStateTransitions.kt• L34-49 app/…/MessagesService.kt• L100-103 app/…/EventsReceiver.kt• L99-113 app/…/GatewayService.kt• L240-274
User-visible history
Message history is a read view over the durable message and recipient state. It lets an operator see queue totals, inspect the overall result, and open a message to compare each recipient's progress. The User interface and operations page places these views in the wider operator workflow.
Local history views
The application list shows recent outbound messages and totals for pending, sent, delivered, and failed work. It loads more history as the user scrolls and can filter the list by processing state. The detail view shows the message content, aggregate state, and each recipient's state and error.
The local API provides the same history for external clients. Clients can filter by source, state, and creation range, choose sort order and pagination, then read a single message with its recipient results and state timestamps.
References: app/…/MessagesListViewModel.kt• L14-59 app/…/MessagesListFragment.kt• L36-62 app/…/MessageDetailsFragment.kt• L33-48 app/…/MessagesRoutes.kt• L53-134 app/…/MessagesRoutes.kt• L287-326
History retention
History is local operational data, not an endless archive. The configured message log lifetime removes old completed records while pending or cancelling work remains available for processing. This keeps the user view aligned with the retention policy without deleting active queue work.
References: app/…/MessagesDao.kt• L237-238 app/…/MessagesService.kt• L271-275
Change checklist
When these files or sections are changed, remember to consider these:
- Keep local API fields, cloud message fields, and the common send request aligned. A field lost at either boundary can change queue timing or device behavior without changing the API shape.
- Preserve the message ID and original recipient through Android callbacks. State updates depend on that identity link.
- Keep all supported content forms aligned across request parsing, stored content, queue reconstruction, and the Android send boundary. MMS attachments and their part count must remain part of the same message result.
- Keep recipient-state precedence and aggregate-state rules aligned with API responses, cloud patches, totals, and user history.
- When a state or transition changes, update the transition table, state history, event consumers, cloud synchronization, and user-facing state summaries together.
- Keep the state read, validation, write, aggregate sync, and event emission under the per-message coordination boundary. Do not add a same-key nested lock.
- Keep schedule, priority, work-hour, rate-limit, and expiry rules consistent between request intake, queue selection, and worker start times. A new immediate request must not leave an older delayed worker as the only scheduled run.
- Preserve the difference between local and cloud sources. Only cloud and gateway sources need cloud state synchronization.
- Keep queue snapshot reads and worker enqueue or reschedule actions under the same coordination boundary. Otherwise a concurrent request can leave due work waiting behind a later scheduled run.
- Keep the MMS submit-to-callback boundary idempotent. A callback must not overwrite a later or terminal recipient result when the shared MMS result is handled.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Duplicate message ID | The request is rejected and no second send record is created. | Generate a new ID for each logical send. |
| Message expires while waiting | Pending recipients become failed with an expiry error. | Set the expiry time beyond the expected queue delay. |
| Cancellation finds an advanced recipient | The cancellation is rejected and state remains unchanged. | Cancel before the send worker or Android callback advances the recipient. |
| Cancellation races with Android submission | A later device result can replace Cancelled with Sent, Delivered, or Failed. | Treat the device result as authoritative after submission. |
| Invalid or repeated state update | No database write or state event is produced. | Use the state service for every local state change. |
| Android send result fails | The affected recipient becomes failed while other recipients keep their own states. | Inspect the recipient error before deciding whether to submit a new request. |
| MMS service returns an error | MMS recipients become failed after the device reports the send result. | Check the recorded error and carrier or data-network status before retrying. |
| Delivery report is unavailable or negative | The message can remain sent or become failed instead of delivered. | Request delivery reports when the caller needs network confirmation. |
| Cloud state update loses network access | Local history is current but the cloud remains stale until a later successful update. | Restore network access and allow the state worker to retry. |
| History retention removes an old completed record | The message is no longer available in the local history view. | Set the message log lifetime to cover the required audit period. |
Key files
| File | Why to read it |
|---|---|
| app/…/MessagesService.kt | Main coordinator for intake, scheduling, Android results, cancellation, and queue execution. |
| app/…/MessageStateService.kt | Defines the guarded state-update cycle and the event boundary for message results. |
| app/…/MessageStateTransitions.kt | Defines which message and recipient state changes are valid. |
| app/…/PerMessageLock.kt | Shows how concurrent updates for one message are serialized without blocking unrelated messages. |
| app/…/MessagesRepository.kt | Shows how a request becomes durable work and how pending recipients are resumed. |
| app/…/MessageContent.kt | Defines the supported outbound content forms, including MMS content and attachments. |
| app/…/MessagesDao.kt | Defines queue eligibility, state persistence, state history, and retention. |
| app/…/MessagesRoutes.kt | Defines local API intake and history boundaries. |
| app/…/GatewayService.kt | Defines cloud message import, cancellation, and state-sync boundaries. |
| app/…/SendMessagesWorker.kt | Defines background execution for the outbound queue. |
| app/…/SendStateWorker.kt | Defines the path from local state to cloud state. |
| app/…/MessagesListViewModel.kt | Defines list filtering, totals, and incremental history loading for the user view. |
| app/…/MessageWithRecipients.kt | Defines how recipient results form the user-visible aggregate state. |
| app/…/MessagesListFragment.kt | Shows the recent message and state-total history view. |
| app/…/MessageDetailsFragment.kt | Shows the per-message and per-recipient history view. |