Persistent storage and database evolution
The gateway uses one Room database to keep the state that must survive process restarts. It stores outbound work and its history, inbound message records, logs, webhook delivery work, subscriptions, inbox upload work, device keys, and token status so the rest of the application can resume work and report a consistent view of the gateway. The stored records support the event flow described in event routing and the settings managed through configuration management.
Database boundary
The database is the durable boundary between short-lived gateway work and the next application run. AppDatabase defines the tables and gives each area a focused data access object (DAO), while Room checks that the declared schema matches the on-device schema at version 25. See application lifecycle for how database startup fits into the wider application start sequence.
The database groups data by the product behavior it supports:
| Data group | Purpose |
|---|---|
| Outbound messages | Preserve message content, delivery options, current state, and recipient results. |
| State history | Record the states reached by a message and by each recipient. |
| Inbound messages | Keep a searchable record of received SMS, data SMS, and MMS events. |
| Logs | Keep recent operational records with optional structured context. |
| Webhooks | Store subscriptions and durable delivery attempts with retry state. |
| Inbox uploads | Keep encrypted inbound content until its upload work is complete. |
| Tokens | Track expiry, revocation, and the relationship between access and refresh tokens. |
| Device keys | Track public-key versions and their retirement state. |
Gateway state records
Outbound message records
The outbound message model is the durable work item for sending. A message can hold text, data, or MMS content. It can identify its source, target a SIM, carry expiry or schedule rules, and move through the shared processing states from pending to a final result. The message content is kept with a type marker so later reads can restore the correct content kind.
Each message has one or more recipient records. A recipient keeps its phone number, its own processing state, and an optional error. The parent message owns these records, so removing a message also removes its recipients and their state history. The DAO returns a message with its related recipients when the sender needs a complete work item. It also provides queue selection, message counts, filtered history, and retention cleanup.
When a message enters the database or changes state, the data layer also records the state transition. This separates the current state used for work selection from the history used to explain what happened. A message with several recipients can therefore have a different overall result from an individual recipient.
References: app/…/Message.kt• L12-53 app/…/Message.kt• L65-105 app/…/MessageRecipient.kt• L6-17 app/…/MessageWithRecipients.kt• L7-32 app/…/MessageState.kt• L6-21 app/…/RecipientState.kt• L6-22 app/…/MessagesDao.kt• L44-100 app/…/MessagesDao.kt• L126-238
Inbound message records
The inbound message record gives the gateway a durable, small view of received traffic. It identifies the event type, sender, optional recipient and SIM details, a content preview, and its creation time. The inbound DAO supports recent views, time and type filters, counts, lookup by ID, deletion, and age-based cleanup. Its views and counts treat downloaded MMS records as part of the MMS group, while exact type queries can still select one stored type.
This record is separate from the outbound message model because received traffic has a different life cycle and does not need outbound delivery state. A migration can clear these records without changing outbound work or its history. See inbound SMS and MMS capture for the capture flow that creates these records.
References: app/…/IncomingMessage.kt• L7-30 app/…/IncomingMessagesDao.kt• L9-27 app/…/IncomingMessagesDao.kt• L29-70 app/…/Migrations.kt• L88-96
Operational logs
The log table keeps records that help explain gateway behavior after the event has passed. Each entry has a priority, module name, message, time, and optional JSON context. The log DAO exposes recent entries and time-range reads, then removes entries older than the chosen retention point.
Logs support diagnosis but do not drive message delivery. Their retention path is independent from message and inbound-message retention. See operational logs for how the gateway presents these records.
References: app/…/LogEntry.kt• L8-24 app/…/LogEntriesDao.kt• L8-20
Webhook delivery records
Webhook storage has two roles. A subscription describes which URL receives which event for which source, while a queue record represents a delivery that can wait, retry, complete, or become permanently failed. The queue keeps the next attempt time, retry count, and last error so delivery can continue after a restart. Event selection is part of the wider event routing flow.
The queue also supports recovery of work that stayed in processing too long and cleanup of old terminal records. This makes webhook delivery a durable side effect rather than a best-effort action tied to one process run. See webhook delivery and webhook event payloads for the delivery contract.
References: app/…/WebHook.kt• L8-15 app/…/WebhookQueueEntity.kt• L12-44 app/…/WebHooksDao.kt• L12-43 app/…/WebhookQueueDao.kt• L24-49 app/…/WebhookQueueDao.kt• L65-159
Token records
The token table lets the gateway enforce token lifetime and revocation across requests. It stores each token ID, expiry, optional revocation time, token use, and optional parent refresh-token ID. The token DAO treats refresh rotation as one database action: it checks the current token, revokes it, and creates the replacement pair only when the current token is valid and active.
Expired tokens can be removed without changing active tokens. Revocation can also cover a token and its child token, which preserves the security link between refresh operations and issued access tokens. See local API authentication for how requests use this state.
References: app/…/Token.kt• L8-35 app/…/TokensDao.kt• L11-66
Inbox uploads and device keys
The database also preserves protected inbound content and the device keys that support its handling. Inbox upload records keep encrypted sender, recipient, content, and attachment data with the source message identity, while device-key records keep each public-key version and its creation or retirement time. These records let upload work and key changes remain durable across process restarts.
The upload identity is unique for a message and content type, so the same inbound item does not create duplicate upload work. Key versions are also unique, which keeps key history addressable as keys change.
References: app/…/AppDatabase.kt• L28-41 app/…/Module.kt• L5-14 app/…/25.json• L432-508 app/…/25.json• L724-785
Data access and consistency
DAO responsibilities
A DAO is the database-facing contract for one area of gateway behavior. It combines simple reads and writes with higher-level actions so callers can ask for a business result instead of rebuilding table relationships themselves.
The main access patterns are:
| DAO | Durable behavior |
|---|---|
MessagesDao | Selects due work, joins messages to recipients, updates current state, records state history, reports totals, and removes old completed work. |
IncomingMessagesDao | Stores received-message summaries and supports views, filters, counts, lookup, deletion, and retention. |
LogEntriesDao | Adds logs and reads or removes them by time. |
WebHooksDao | Reads and replaces subscriptions by event or source. |
WebhookQueueDao | Advances queued delivery through retry and terminal states. |
InboxUploadDao | Stores and retrieves durable encrypted inbound upload work. |
TokensDao | Issues, finds, revokes, rotates, and cleans up tokens. |
DeviceKeysDao | Reads and updates the device public-key lifecycle. |
Transactions matter where one logical action spans related rows. Message insertion keeps the message, recipients, and initial history together. Token rotation keeps revocation and replacement issuance together. Subscription replacement also removes and adds a source's subscriptions as one operation.
References: app/…/AppDatabase.kt• L71-80 app/…/Module.kt• L5-14 app/…/MessagesDao.kt• L103-145 app/…/MessagesDao.kt• L164-226 app/…/TokensDao.kt• L34-58 app/…/WebHooksDao.kt• L27-37
Durable state transitions
The gateway uses a shared processing state model for outbound messages and recipients. Current state controls work selection and summary counts, while the state tables retain the set of states reached with their update times. Recipient state contributes to the message result, which lets a multi-recipient send report a combined outcome without losing per-number errors.
The same principle appears in the webhook queue with its delivery states. Pending and failed work can be selected when due, processing work can be recovered after a timeout, and terminal work can be retained until cleanup. The message send flow consumes these durable states as part of message processing.
References: app/…/ProcessingState.kt• L3-11 app/…/MessageWithRecipients.kt• L22-32 app/…/MessagesDao.kt• L147-226 app/…/WebhookQueueDao.kt• L24-49
Stored value conversion
Room type conversion
Room stores a limited set of database types, so the database boundary converts richer Kotlin values to stable text or numeric values. The shared converters store lists and JSON values as JSON text, and write dates as UTC timestamp text with milliseconds. Nullable values remain nullable across the conversion boundary.
Date reads accept the canonical format and known older formats. An invalid date returns null instead of raising an error, so an old row does not break a reactive database read. New rows still use the canonical format.
Webhook queue status uses its own converter because the queue stores the status value used by its retry state machine. An unknown stored status falls back to pending, so changes to status names must be treated as a data contract change.
References: app/…/Converters.kt• L11-86 app/…/WebhookConverters.kt• L8-17 app/…/WebhookQueueEntity.kt• L19-34 app/…/ConvertersTest.kt• L10-67
Message content representation
Message content is kept as JSON text with a separate type value. This lets one durable message record support text, data, and MMS messages while keeping the stored shape stable for reads and migrations. The model restores the matching content form when a caller reads the record.
References: app/…/Message.kt• L12-15 app/…/Message.kt• L65-105 app/…/Migrations.kt• L18-85
Schema evolution
Versioned database history
Room identifies a database schema by version and upgrades an existing device through the registered path. The current schema is version 25. Most steps use Room auto-migrations, while steps that change data meaning use named manual migrations.
The checked-in schema snapshots from versions 1 through 25 are the record of how gateway state changed over time. They show both structural changes and the stored defaults needed when new fields are added. A new schema is not only a code change: it is a promise about how existing gateway data remains readable.
References: app/…/AppDatabase.kt• L28-68 app/…/1.json• L1-90 app/…/25.json• L1-794
Manual data changes
Three upgrades carry data meaning that Room cannot infer safely:
| Upgrade | Data effect |
|---|---|
| 7 to 8 | Fills missing validity times for pending messages from their creation time. |
| 13 to 14 | Rebuilds the message table and converts the old text field into typed JSON content. |
| 21 to 22 | Deletes all stored inbound-message records. |
These steps are part of the supported upgrade path. The 21-to-22 change is especially important because it intentionally removes user-visible inbound history during that upgrade, while leaving the other database areas in place.
References: app/…/Migrations.kt• L6-16 app/…/Migrations.kt• L18-85 app/…/Migrations.kt• L88-96 app/…/AppDatabase.kt• L44-67
Change checklist
When these files or sections are changed, remember to consider these:
- A Room entity field, table name, index, relation, or enum value change must have a matching schema version decision and an upgrade path for existing devices.
- A change to message content types or converter formats must preserve reads of old rows and update the 13-to-14 compatibility assumptions if the old shape is still supported. Date readers must continue to accept legacy timestamp forms while new writes keep the canonical form.
- A change to inbound type filters must keep the distinction between exact stored-type queries and the grouped MMS views and counts aligned.
- A change to
ProcessingStatemust keep current-state queries, state-history rows, summary counts, and recipient-to-message result rules aligned. - A change to webhook queue status values must update the queue queries and
WebhookConverterstogether. Stored rows use the serialized status values. - A change to token use or parent-token rules must preserve refresh rotation and revocation behavior across existing token rows.
- A retention policy change must check each independent cleanup path for messages, inbound messages, logs, tokens, and terminal webhook entries.
- A change to inbox upload identity or encrypted fields must preserve the unique message-and-type contract and the ability to resume protected upload work.
- A change to device-key versions or retirement rules must preserve unique key versions and the distinction between active and retired keys.
- A schema change must add or update the checked-in Room schema snapshot so the recorded history matches the runtime database.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| The database version or entity shape changes without a registered migration. | An existing installation cannot move to the new schema through the supported upgrade path. | Update AppDatabase, add the needed migration, and keep the schema snapshot in step with the declared version. |
| A stored enum value changes without a data migration. | Queries can miss rows or a converter can map old webhook work to the pending state. | Treat serialized enum values as stable data contracts. Migrate old values before changing them. |
| A legacy or invalid date value reaches a reader that expects only the current format. | A database-backed view can fail or lose the ability to expose an affected row. | Keep the tolerant date reader and preserve the canonical format for new writes. |
| An inbound type filter treats downloaded MMS as a separate user-facing group. | MMS views and totals can omit records that belong in the MMS result. | Keep grouped MMS filters and totals aligned with the stored type values. |
| A message is deleted while its history is still needed. | Cascading deletes remove its recipients and both levels of state history. | Apply message retention only after the required audit period. |
| Refresh rotation runs for a missing, wrong-use, or already revoked token. | No valid replacement pair is created and the caller must handle the reported rotation result. | Check the explicit RefreshRotationResult before treating rotation as successful. |
| Upgrade 21 to 22 runs on a database with inbound history. | All stored inbound-message records are cleared by design. | Treat this migration as data loss for inbound history and communicate it in any upgrade or support plan. |
| A queue item remains in processing past its timeout. | The webhook event can stop making progress until recovery returns it to pending work. | Keep the queue recovery step active and preserve the attempt-time contract. |
| Two inbox upload rows use the same message and type. | Duplicate upload work can be created or the insert can fail against the unique contract. | Preserve the (type, message_id) uniqueness rule when creating or migrating upload records. |
| A device key reuses an existing version or loses its retirement time. | Key selection or key history can become ambiguous across restarts. | Preserve unique key versions and the active-versus-retired key state. |
Key files
| File | Why to read it |
|---|---|
| app/…/AppDatabase.kt | Defines the database boundary, registered entities, DAOs, version, and upgrade path. |
| app/…/Module.kt | Exposes the database and each DAO to the rest of the application as shared services. |
| app/…/MessagesDao.kt | Shows how durable message work, recipient state, history, summaries, and retention fit together. |
| app/…/Message.kt | Defines the durable outbound message and its supported content kinds. |
| app/…/Migrations.kt | Explains the upgrades that transform or remove existing data. |
| app/…/Converters.kt | Defines the shared representation of dates, lists, and JSON values. |
| app/…/ConvertersTest.kt | Captures the date formats that must round-trip and the legacy values that must not break reads. |
| app/…/TokensDao.kt | Shows the durable rules for token revocation and refresh rotation. |
| app/…/WebhookQueueDao.kt | Shows how webhook delivery survives retries, restarts, and stuck workers. |
| app/…/IncomingMessagesDao.kt | Shows the read, grouped MMS filter, and retention boundary for inbound-message history. |
| app/…/25.json | Records the current on-device schema that version 25 must produce, including inbox uploads and device keys. |