Documentation
¶
Overview ¶
Package core holds the operations the surfaces share: ingestion (backfill, the live stream and the reconciliation sweep), and the mutation pipeline.
The structural rule of spec section 5.1 is enforced here by construction: backfill, the live event stream and the sweep all write through Ingester.IngestMessage and Ingester.IngestConversation. There is no separate backfill writer whose behaviour could drift, so a bug in ordering or dedup is reproducible from either source -- which is exactly what section 16's acceptance test 2 asserts by running both orders.
Index ¶
- Constants
- Variables
- func CheckAccountWritable(a AccountRef) error
- func CheckConversationActionable(c store.Conversation, action string) error
- func CheckForceRCS(c store.Conversation, forceRCS bool) error
- func CheckMediaReady(att store.Attachment, action string) error
- func CheckMyMessage(m store.Message, action string) error
- func CheckMyReaction(r store.Reaction) error
- func CheckObjectAccount(param, objectID, objectAccountID, requestedAccountID string) error
- func CheckReplySupported(c store.Conversation, replyToMessageID string) error
- func ClassifyResolve(res gm.ResolveResult, compiled, live gm.ConfigVersion) (*gm.Conversation, error)
- func IsDM(c *gm.Conversation) bool
- func ReactionPathSegment(segment string) string
- func ReapPendingOperations(ctx context.Context, st *store.Store, aud *audit.Writer, timeout time.Duration, ...) ([]store.Operation, error)
- func Reconcile(ctx context.Context, a *Account, since time.Time) error
- func RecoverOperations(ctx context.Context, st *store.Store, aud *audit.Writer, source string) ([]store.Operation, error)
- func RunPendingReprocess(ctx context.Context, st *store.Store, sweep Sweeper, accountIDs []string) (task string, ran bool, err error)
- func SendWithRetry(ctx context.Context, clk clock.Clock, attempt SendAttempt) (gm.SendResult, error)
- func SweepIdempotencyKeys(ctx context.Context, st *store.Store, ttl time.Duration) (int64, error)
- func ValidateIdempotencyKey(key string) error
- type Account
- func (a *Account) AddReaction(ctx context.Context, in ReactionInput) (Result, error)
- func (a *Account) Backfill(ctx context.Context, ready []gm.Conversation) error
- func (a *Account) BackfillHorizonAt() time.Time
- func (a *Account) BackfillPaused() bool
- func (a *Account) DeleteConversation(ctx context.Context, in DeleteConversationInput) (Result, error)
- func (a *Account) DeleteMessage(ctx context.Context, in DeleteMessageInput) (Result, error)
- func (a *Account) HandleEvent(ctx context.Context, ev gm.Event) error
- func (a *Account) Ingest() *Ingester
- func (a *Account) KickBackfill(ctx context.Context, ready []gm.Conversation)
- func (a *Account) LastEventAt(ctx context.Context) (time.Time, error)
- func (a *Account) LastSessionID() string
- func (a *Account) MarkRead(ctx context.Context, in MarkReadInput) (Result, error)
- func (a *Account) PatchConversation(ctx context.Context, in ConversationPatch, req Request) (Result, error)
- func (a *Account) PauseBackfill()
- func (a *Account) Reconcile(ctx context.Context, since time.Time) error
- func (a *Account) RemoveReaction(ctx context.Context, in ReactionInput) (Result, error)
- func (a *Account) ResumeBackfill()
- func (a *Account) Row(ctx context.Context) (store.Account, error)
- func (a *Account) SendMedia(ctx context.Context, in SendMediaInput) (Result, error)
- func (a *Account) SendText(ctx context.Context, in SendTextInput) (Result, error)
- func (a *Account) SetCrashBefore(fn func(store.Operation) error)
- func (a *Account) StartConversation(ctx context.Context, in StartConversationInput) (Result, error)
- func (a *Account) SweepFromEpoch(ctx context.Context) error
- func (a *Account) SweepOnEvent(ctx context.Context) error
- func (a *Account) SweepOnTimer(ctx context.Context) error
- func (a *Account) SweepSince(ctx context.Context) (time.Time, error)
- func (a *Account) Sweeps() uint64
- func (a *Account) TouchEvent(ctx context.Context, at time.Time) error
- func (a *Account) WaitBackfill()
- type AccountRef
- type Call
- type Config
- type ConversationPatch
- type DeleteConversationInput
- type DeleteMessageInput
- type Ingester
- func (in *Ingester) Applied() uint64
- func (in *Ingester) CountUnknown()
- func (in *Ingester) Ignored() uint64
- func (in *Ingester) IngestConversation(ctx context.Context, c gm.Conversation) (string, error)
- func (in *Ingester) IngestMessage(ctx context.Context, m gm.Message, isDM, isOld bool) (store.UpsertMessageResult, error)
- func (in *Ingester) New() uint64
- func (in *Ingester) OutOfOrder() uint64
- func (in *Ingester) Unknown() uint64
- type Intent
- type Logger
- type MarkReadInput
- type Outcome
- type ReactionInput
- type Request
- type Resolution
- type Result
- type SendAttempt
- type SendMediaInput
- type SendTextInput
- type StartConversationInput
- type Sweeper
Constants ¶
const ( KindSendText = "send_text" KindSendMedia = "send_media" KindStartConversation = "start_conversation" KindMarkRead = "mark_read" KindAddReaction = "add_reaction" KindRemoveReaction = "remove_reaction" KindDeleteMessage = "delete_message" KindDeleteConv = "delete_conversation" KindArchive = "archive" KindUnarchive = "unarchive" )
The operation kinds of spec section 6.5.
const MaxIdempotencyKeyBytes = 200
MaxIdempotencyKeyBytes is spec section 6.3's ceiling on a key.
const PendingReprocessKey = "pending_reprocess"
PendingReprocessKey is the `server_meta` key of spec section 4.3.
"A migration needing derived data recomputed sets `server_meta.pending_reprocess = <task name>`; the process runs that task once after startup and clears the key."
const TaskReconcileParticipants = "reconcile_participants"
TaskReconcileParticipants is the task migration 0004 asks for.
0004 rewrites `messages.sender_participant` and `reactions.participant_id` to derived `part_` IDs by joining through `participants`, which already holds the mapping. What it cannot fix is a row whose participant Agent GM never ingested: there is nothing to join against. Those rows keep their raw value, and a raw value there makes every `sender` filter return an empty page -- silently, because an empty page is a valid answer.
So the migration hands them here, and this re-ingests them through the current path, which derives correctly.
Variables ¶
var ErrResolveNoConversation = errors.New("google answered SUCCESS with no conversation")
ErrResolveNoConversation means Google answered SUCCESS with no conversation in the body, which is a contract violation rather than a refusal.
var WritableStates = map[string]bool{ "connected": true, "degraded": true, }
WritableStates are the account states a write may proceed in (§4.7). Everything else reads but does not write.
Functions ¶
func CheckAccountWritable ¶
func CheckAccountWritable(a AccountRef) error
CheckAccountWritable is step 5 of §6.2, and it runs **before** any operation row exists, so a refused action never leaves a record that looks like an attempt (§7.8).
Every non-writable state answers `unsupported_capability` with `not_signed_in` — a per-account condition, distinct from the service-level `not_paired`, which means there are no accounts at all. `parked` is in that set because a parked account holds no client to write with; the account's own `state` and `state_reason` say which of the reasons it is, which is exactly why `state_reason` exists.
func CheckConversationActionable ¶
func CheckConversationActionable(c store.Conversation, action string) error
CheckConversationActionable refuses an action on a thread Google will not let anybody write to: `conversation_read_only` when Conversation.ReadOnly is set, and `conversation_deleted` when delete-for-me has been applied locally.
func CheckForceRCS ¶
func CheckForceRCS(c store.Conversation, forceRCS bool) error
CheckForceRCS refuses force_rcs where capabilities.force_rcs is false -- section 4.6 derives that as "RCS and SEND_MODE_AUTO", which is exactly the force_rcs_eligible column.
func CheckMediaReady ¶
func CheckMediaReady(att store.Attachment, action string) error
CheckMediaReady refuses an action on an attachment whose bytes are not downloaded yet.
func CheckMyMessage ¶
CheckMyMessage refuses deleting a message the owner did not send. Direction is the test: Google only permits an unsend of one's own message, and an incoming one is somebody else's.
func CheckMyReaction ¶
CheckMyReaction refuses removing somebody else's reaction. is_mine is decided at write time by the ingest path, so this reads a fact rather than re-deriving one.
func CheckObjectAccount ¶
CheckObjectAccount enforces the other half of §7.3: a `conv_` or `msg_` ID that belongs to a different account than the `account_id` given is `invalid_request` naming both — **never `not_found`**, which would suggest the thread is gone when in fact the caller merely named the wrong account.
`param` is the parameter the object ID arrived under, so the message names the thing the caller typed. The refusal itself is apierr's IDFromAnotherAccount, which is the one constructor for this shape.
objectAccountID is the account the object really belongs to; it is compared here and is not echoed into the error, which names the account_id the caller supplied.
func CheckReplySupported ¶
func CheckReplySupported(c store.Conversation, replyToMessageID string) error
CheckReplySupported refuses a reply on an SMS/MMS conversation: replies are RCS-only. An SMS thread that silently dropped the reply target would send the text anyway, to the right person, with the quoted context gone -- which is worse than a refusal, because the agent believes it replied.
func ClassifyResolve ¶
func ClassifyResolve(res gm.ResolveResult, compiled, live gm.ConfigVersion) (*gm.Conversation, error)
ClassifyResolve turns a GetOrCreateConversation answer into Agent GM's own vocabulary (spec sections 3.7, 7.2).
The CREATE_RCS retry itself lives in the gm adapter, which retries exactly once, so a CREATE_RCS arriving here is the *second* one and there is nothing further to try.
**Google's real status always survives.** This used to relabel ANY failure as `config_version_stale` whenever the compiled and live ConfigVersions differed, and the Slice 2 live gate showed what that costs: a named group start failed for an entirely unrelated reason -- the name was being sent on the first call -- while the versions happened to differ, as they normally do between pin bumps. The operator was told to bump the pin, which would not have helped, and the actual status was discarded. That is precisely the misdiagnosis D32 exists to prevent, committed by the very code that names it.
So the status decides the code, always:
- a second CREATE_RCS is `google_error`: a named status Agent GM has already done the one documented thing about;
- anything else is `google_undocumented_status` carrying the bare integer, claiming no meaning for it.
A version mismatch is added as CONTEXT on whichever of those it is -- both versions in `details`, and a sentence saying a pin bump may be the fix -- because it is genuinely useful when a create fails and genuinely not a diagnosis on its own. `config_version_stale` remains what D32 says it is: a fact reported by GET /v1/health, never an error code.
func IsDM ¶
func IsDM(c *gm.Conversation) bool
IsDM reports whether a conversation is a direct one, which is what shouldIgnoreStatus's isDM argument means.
func ReactionPathSegment ¶
ReactionPathSegment canonicalises the emoji in a URL path segment, so DELETE .../reactions/❤️ and DELETE .../reactions/❤ address the same row.
func ReapPendingOperations ¶
func ReapPendingOperations(ctx context.Context, st *store.Store, aud *audit.Writer, timeout time.Duration, source string) ([]store.Operation, error)
ReapPendingOperations settles every `pending` operation older than operations.pending_timeout to `unknown`, measured from created_at_ms and on the INJECTED clock -- so a test advances 24 hours rather than waiting them out. Like crash recovery it is process-wide.
func Reconcile ¶
Reconcile is the reconciliation sweep of spec section 5.4, for ONE account.
The live event stream is not a complete record. The library's dedup abandons every remaining part of a batch on a hit (section 3.4, event_handler.go:263-266,272-275), so messages can be LOST, not merely duplicated, and no amount of local dedup recovers what never arrived. This is the only thing that does.
- ListConversations(active) and, if backfill.include_archive, ListConversations(archived).
- For each conversation whose last_activity_ms is newer than `since`, or whose latest_message_id is not a row we hold: FetchMessages(convID, page_size, cursor=nil), walking back until a message older than `since` is reached.
- Upsert everything through the same path as section 5.3. Unchanged rows write nothing (content_hash).
- Record accounts.last_sweep_at_ms for this account.
It is idempotent by construction, because every write goes through the same upsert functions the live stream uses. Running it more often costs bandwidth and nothing else.
`since` is supplied by the trigger, from the column section 5.4's table names -- last_event_at_ms for every event-driven trigger, last_sweep_at_ms for the timer, the epoch for a whole-server re-backfill. It is not the current time: a sweep that walked back only as far as "now" would re-list the conversations and then decline to fetch the very messages it exists to recover.
func RecoverOperations ¶
func RecoverOperations(ctx context.Context, st *store.Store, aud *audit.Writer, source string) ([]store.Operation, error)
RecoverOperations is the startup sweep of spec section 6.6.
UPDATE operations SET status='unknown', terminal=1, terminal_at_ms=?,
error_code='crash_recovered'
WHERE status='running';
It runs BEFORE the listener binds and before any account connects, and it is process-wide rather than per-account deliberately: a crash is a property of the process, so every account's in-flight operations are settled at once. Accounts are independent in their NETWORK behaviour; recovery from a process death is not an account concern.
Each row is audited as operation.crash_recovered, with its account_id. **Nothing is retried.** If the send did reach Google, the remote echo will arrive on reconnect and correct the operation to `succeeded` with a message_id -- which is exactly why the correction transition out of `unknown` exists.
A `pending` operation is left alone here; ReapPendingOperations settles it at pending_timeout, measured from created_at_ms.
func RunPendingReprocess ¶
func RunPendingReprocess(ctx context.Context, st *store.Store, sweep Sweeper, accountIDs []string) (task string, ran bool, err error)
RunPendingReprocess runs the task `server_meta.pending_reprocess` names, if any, and clears the key.
**It is the missing half of section 4.3.** Migration 0004 was the first thing ever to write that key, and nothing read it: the clause says the process runs the task and clears the key, and without the second half the key stayed set for ever on every upgraded database while the rows it was set for kept their raw IDs. A migration that hands work to a task nothing runs has not deferred the work; it has dropped it.
**It runs AFTER the listener binds**, on the goroutine that resumes the accounts. That is a deliberate reversal: it used to run first, on the reasoning that a caller must not see a half-reconciled database and read a short `sender=me` page as an answer. On the owner's real deployment the resume and the reprocess together took four minutes, and for those four minutes `/healthz` did not answer at all -- so every watcher concluded the service was down, which is a worse and much more frequent lie than a brief partial page.
So the window is accepted and named: on the ONE start after an upgrade whose migration deferred work, a query filtered on a derived value -- the `sender=me` page is the one that matters -- can return fewer rows than it will a moment later, until this finishes and clears the key. `GET /v1/health` reports the task while it runs, so the state is visible rather than merely brief. What does NOT wait is anything that settles the database itself: migrations (section 4.3) and crash recovery (section 6.6) both complete before the socket is bound.
**The key is cleared only when every account ROW was reconciled**, not merely every account that resumed. `accountIDs` is the set with a live client; every account in the store is relinked regardless, because a relink is a join and needs no client, and `signed_out` is an ordinary resting state whose history stays readable (section 4.7). Passing only the resumed set once meant "resumed accounts=0" followed by "cleared the key", with nothing rebuilt and no second attempt ever.
A sweep that FAILS -- a phone asleep, an account that would not connect -- leaves the key set, so the next start tries again rather than declaring the work done because it was attempted.
func SendWithRetry ¶
func SendWithRetry(ctx context.Context, clk clock.Clock, attempt SendAttempt) (gm.SendResult, error)
SendWithRetry is the only retry Agent GM performs, and it is not Agent GM's own policy: it is the three upstream-derived retries for transient Google statuses, executed inside the same request (spec sections 6.1, 3.7).
There is no queue, no worker and no retry schedule Agent GM owns (D4). The backoffs are gm.SendRetryBackoff -- [3s, 8s, 20s] at the pin -- measured on the injected clock, so a test proves the schedule without waiting 31 seconds. Only FAILURE_2 and FAILURE_3 are transient; FAILURE_4 is not_default_sms_app and is returned at once, because retrying it sends nothing and delays an answer the owner has to act on.
**The caller mints one TmpID and reuses it across every attempt** (spec section 6.3). A fresh TmpID per attempt would let two attempts of one request correlate to two operations, which is exactly the duplicate-message hazard the whole idempotency design exists to prevent.
func SweepIdempotencyKeys ¶
SweepIdempotencyKeys deletes operation rows past operations.idempotency_ttl. It never deletes a row that is not terminal.
func ValidateIdempotencyKey ¶
ValidateIdempotencyKey is section 6.3's shape rule for a key that is PRESENT. An empty key is not an error any more (D38): it means the caller sent no `Idempotency-Key` header, which is the ordinary case, and the operation gets a server-minted ID instead. A key over 200 bytes, not valid UTF-8, or carrying control characters is still invalid_request naming Idempotency-Key in details.field, and writes nothing.
Types ¶
type Account ¶
type Account struct {
ID string
Store *store.Store
Backend gm.Backend
Clock clock.Clock
Config Config
Log Logger
// Audit is the section 12.4 writer. It may be nil in a narrow unit test;
// every call site tolerates that.
Audit *audit.Writer
// Source is the resolved client source of section 12.3, stamped on every
// audit row this engine writes. Ingestion's own source is "system".
Source string
// DataKey seals attachment decryption keys at rest. Nil means the
// attachment row is written without one, which is what a test that does
// not exercise media wants.
DataKey *store.DataKey
// contains filtered or unexported fields
}
Account is one account's ingestion and mutation engine: one store, one gm.Backend, one clock, one ingester (spec sections 2.4, 3.4, 5.2, 5.3).
Everything on it is scoped to this account. No method here ever reads or writes another account's rows, and no event on this account's stream changes another account's state -- which is why the two-account tests of section 13.2 can assert no cross-talk by construction rather than by inspection.
func (*Account) AddReaction ¶
AddReaction adds, or SWITCHes, this account's own reaction on a message.
When the owner already has exactly that reaction, there is nothing to do: the answer is `changed: false` with `operation: null`, and the backend is called zero times. That is not an optimisation, it is the honest answer -- creating an operation row for a no-op would make "did my reaction land" unanswerable from the operation alone.
func (*Account) Backfill ¶
Backfill is spec section 5.2, for THIS account, in the order the spec numbers.
- Upsert the conversations carried on ClientReady.
- ListConversations(INBOX, conversation_page_size) -- which is also what arms the library's BUGLE_MESSAGE mode (section 3.7).
- ListConversations(ARCHIVE) if backfill.include_archive.
- ListContacts() and ListTopContacts(); upsert contacts; link participants.
- For each conversation, oldest-activity first, page FetchMessages until the page is empty, max_messages_per_conversation is reached, or a message older than backfill.horizon is seen.
- Record per-conversation progress in backfill_state so a restart resumes rather than restarting.
- Set accounts.backfill_complete_at_ms for THIS account.
Every row written carries this account's account_id, and every call is on this account's client. Concurrency is backfill.concurrency conversations at a time per account.
The whole of it pauses while a MOBILE_DATABASE_SYNC_STARTED/SYNCING alert from THIS phone is outstanding and resumes on that phone's MOBILE_DATABASE_SYNC_COMPLETE; one sleepy phone never stalls another account, because the flag is on this Account.
func (*Account) BackfillHorizonAt ¶
BackfillHorizonAt is the cut-off a backfill would apply now, exposed so a caller can report it without recomputing the arithmetic.
func (*Account) BackfillPaused ¶
BackfillPaused reports whether this account's backfill is deferred.
func (*Account) DeleteConversation ¶
func (a *Account) DeleteConversation(ctx context.Context, in DeleteConversationInput) (Result, error)
DeleteConversation is the delete_conversation mutation.
It is Google's delete-for-me and nothing else (D14): it removes the owner's own copy of the thread, and the other people in it keep theirs. There is no delete option and no second kind of delete, which is why this takes no switch and why a request carrying one is refused at the route.
`libgm.DeleteConversation` wants a participant's number as well as the conversation ID, so the thread's first visible other participant is resolved here rather than at the route: which number that is, is a fact about the conversation, and the route's job is to name the conversation.
func (*Account) DeleteMessage ¶
DeleteMessage is the delete_message mutation. Deleting a message the owner did not send is `not_my_message`, and it is refused before any operation row exists.
func (*Account) HandleEvent ¶
HandleEvent applies one event from THIS account's stream (spec section 3.4). There is one handler per account, driven by one goroutine, and nothing here ever touches another account's rows or another account's state.
The order inside is deliberate. A trigger that runs a sweep reads `last_event_at_ms` BEFORE the event is allowed to move it: the whole value of `since` is that it precedes the data the sweep is going to recover, and stamping it first would hand the sweep a bound above the very messages the library's dedup lost.
func (*Account) KickBackfill ¶
func (a *Account) KickBackfill(ctx context.Context, ready []gm.Conversation)
KickBackfill runs Backfill on its own goroutine, so an account's event loop stays free to deliver the MOBILE_DATABASE_SYNC_STARTED alert that pauses it. A backfill that ran inline on the event loop could never be told to pause.
func (*Account) LastEventAt ¶
LastEventAt is `accounts.last_event_at_ms` for this account, which is the `since` every event-driven trigger in spec section 5.4's table hands the sweep. It is read from the row rather than guessed from the clock: the whole point of the value is that it is the moment data was last actually received, not the moment somebody noticed.
func (*Account) LastSessionID ¶
LastSessionID is the session ID this account last saw.
func (*Account) PatchConversation ¶
func (a *Account) PatchConversation(ctx context.Context, in ConversationPatch, req Request) (Result, error)
PatchConversation applies one conversation change.
Repeating a change that is already applied returns `changed: false` with `operation: null` and calls the backend ZERO times. An idempotent PATCH that re-sent the change anyway would be indistinguishable from one that had to, and would spend a mutation budget on nothing.
func (*Account) PauseBackfill ¶
func (a *Account) PauseBackfill()
PauseBackfill defers THIS account's backfill because its phone is resyncing its own database. Results during a phone-side sync are unstable.
func (*Account) RemoveReaction ¶
RemoveReaction removes this account's own reaction, addressed either by emoji or by react_ ID. Somebody else's is `not_my_reaction`, refused before any operation row exists.
func (*Account) ResumeBackfill ¶
func (a *Account) ResumeBackfill()
ResumeBackfill lifts the pause on MOBILE_DATABASE_SYNC_COMPLETE.
func (*Account) SetCrashBefore ¶
SetCrashBefore installs the step-8/step-9 fault seam. Passing nil removes it.
func (*Account) StartConversation ¶
StartConversation is the start_conversation mutation. The CREATE_RCS retry itself lives in the gm adapter, which retries exactly once with CreateRCSGroup=true exactly as upstream does; ClassifyResolve then turns whatever came back into Agent GM's own vocabulary.
func (*Account) SweepFromEpoch ¶
SweepFromEpoch is POST /v1/admin/backfill with no body: a full re-backfill of this account, `since` the epoch. It is the most expensive operation Agent GM offers, which is why the route requires {"confirm": true}.
func (*Account) SweepOnEvent ¶
SweepOnEvent is every event-driven trigger of section 5.4's table -- BROWSER_ACTIVE with a changed session ID, MOBILE_DATABASE_SYNC_COMPLETE, events.NoDataReceived, events.ListenRecovered and every successful Connect, and POST /v1/admin/backfill naming this account -- all of which hand it last_event_at_ms.
func (*Account) SweepOnTimer ¶
SweepOnTimer is the per-account timer trigger, every settings.ingest.sweep_interval, with that account's last_sweep_at_ms as `since`.
func (*Account) SweepSince ¶
SweepSince returns the `since` the timer trigger uses: THIS account's last_sweep_at_ms (spec section 5.4's table). Every other trigger uses last_event_at_ms, which is LastEventAt.
func (*Account) TouchEvent ¶
TouchEvent moves last_event_at_ms forward, monotonically. It is stamped with the datum's own timestamp rather than the wall clock, so a sweep triggered straight after a lossy batch still has a `since` that precedes the messages the batch lost.
func (*Account) WaitBackfill ¶
func (a *Account) WaitBackfill()
WaitBackfill blocks until every kicked backfill has finished.
type AccountRef ¶
type AccountRef struct {
ID string `json:"id"`
GoogleAccount string `json:"google_account"`
State string `json:"state"`
}
AccountRef is the little of an account that choosing one needs: exactly the three fields §7.3 says `details.accounts` carries, so the refusal can be built from the same value the decision was made on.
type Call ¶
Call is one account's library call, made at step 9 -- after the operation row is committed at step 8. The operation is passed in because a send needs its tmp_id.
type Config ¶
type Config struct {
// BackfillConcurrency is backfill.concurrency: conversations at a time,
// per account (default 2, bounds 1-8).
BackfillConcurrency int
// ConversationPageSize is backfill.conversation_page_size.
ConversationPageSize int
// MessagePageSize is backfill.message_page_size.
MessagePageSize int
// MaxMessagesPerConversation is backfill.max_messages_per_conversation.
MaxMessagesPerConversation int
// Horizon is backfill.horizon: backfill stops at a message older than
// this.
Horizon time.Duration
// IncludeArchive is backfill.include_archive.
IncludeArchive bool
// SweepInterval is ingest.sweep_interval, the per-account timer trigger
// of the reconciliation sweep.
SweepInterval time.Duration
// PendingTimeout is operations.pending_timeout.
PendingTimeout time.Duration
}
Config is the slice of spec section 15.1's settings table that ingestion and operations read. It is a plain struct rather than a live handle on internal/settings because core must be drivable from a test with one literal, and because a running backfill must not change page size underneath itself halfway through a conversation.
Every field here is ScopePerAccount in section 15.1: the value is applied to each account independently, so the cost multiplies by account count.
type ConversationPatch ¶
ConversationPatch is PATCH /v1/conversations/{id} (spec section 7.7): archive, unarchive, pin, unpin and mark-unread. Each field is a pointer, so "not mentioned" and "set to false" are different requests.
type DeleteConversationInput ¶
DeleteConversationInput is DELETE /v1/conversations/{id}.
type DeleteMessageInput ¶
DeleteMessageInput is DELETE /v1/messages/{id}.
type Ingester ¶
type Ingester struct {
Store *store.Store
AccountID string
Log Logger
// Account is the engine this ingester belongs to. It carries the audit
// writer, the clock and the operation correlation this path needs. It is
// nil in the narrowest unit tests, and every use of it is guarded.
Account *Account
// contains filtered or unexported fields
}
Ingester applies one account's events to the store. There is one per account, driven by one goroutine (spec section 5.3).
func (*Ingester) CountUnknown ¶
func (in *Ingester) CountUnknown()
CountUnknown records one unnamed event.
func (*Ingester) IngestConversation ¶
IngestConversation upserts one conversation and replaces its participants.
func (*Ingester) IngestMessage ¶
func (in *Ingester) IngestMessage(ctx context.Context, m gm.Message, isDM, isOld bool) (store.UpsertMessageResult, error)
IngestMessage is spec section 5.3 for one message, and it is the ONLY writer of message rows: backfill, the live stream and the sweep all arrive here.
isOld is used only to suppress side effects (spec section 5.4). An old message:
- never resolves an operation,
- never bumps last_activity_ms past a newer value,
- and is never counted as new.
It is not used to decide whether to store -- an old event may carry information the database lacks.
func (*Ingester) New ¶
New counts messages counted as new. An IsOld replay is never counted here: section 5.4 uses IsOld only to suppress side effects, and "how many new messages arrived" is one of them.
func (*Ingester) OutOfOrder ¶
OutOfOrder counts refused backward delivery-state moves.
type Intent ¶
type Intent int
Intent is whether the caller is about to read or to write. The two differ, and the difference is the whole of §7.3: a read that omits `account_id` covers every account, which is a useful default for "what came in today"; a write that omits it would have to guess which person to text, which is not a default anybody wants.
type Logger ¶
type Logger interface {
Debug(msg string, kv ...any)
Info(msg string, kv ...any)
Warn(msg string, kv ...any)
}
Logger is the small logging surface core needs. Logs carry the acct_ ID, never the Google account address, and never a message body (spec 12.2).
type MarkReadInput ¶
MarkReadInput is POST /v1/conversations/{id}/read.
type Outcome ¶
Outcome is what a library call produced. The caller of runOperation fills it in; the pipeline decides what it means for the operation row.
type ReactionInput ¶
type ReactionInput struct {
Request
MessageID string
// Emoji is whatever the caller sent, in whatever form. It is
// canonicalised here.
Emoji string
// ReactionID is the react_ ID form of the removal. Exactly one of Emoji
// and ReactionID is given on a remove.
ReactionID string
}
ReactionInput is POST /v1/messages/{id}/reactions and its DELETE.
type Request ¶
type Request struct {
// AuthorizationID scopes the idempotency tuple. Two clients may use the
// same key value.
AuthorizationID string
// Key is the Idempotency-Key header, and empty when the caller sent
// none -- which is the ordinary case (D38).
// It is REQUIRED on every mutation.
Key string
// Body is the request body exactly as it arrived. The fingerprint is a
// SHA-256 over its canonical serialisation, so reordered JSON keys are a
// replay and any changed value is not.
Body []byte
// ConversationID is the conv_ ID the operation is about, where there is
// one.
ConversationID string
// Source is the section 12.3 client source, for the audit row.
Source string
}
Request is the part of a mutation that every kind shares: who is asking, under which key, over which body.
type Resolution ¶
type Resolution struct {
// AccountID is the single account chosen, or "" for every account.
AccountID string
// AllAccounts is true when the query covers every account. It is never
// true for a Write.
AllAccounts bool
}
Resolution is the answer: either one account, or every account.
func ResolveAccount ¶
func ResolveAccount(requested string, accounts []AccountRef, intent Intent) (Resolution, error)
ResolveAccount implements §7.3.
- Exactly one account exists → the parameter may be omitted and defaults to it. A single-account deployment never has to think about accounts.
- More than one → a **write** must name one; omitting it is `invalid_request` with `details.field = "account_id"` and `details.accounts` listing the candidates, so the caller can retry without a second round trip. A **read** may still omit it and then covers every account.
- Zero accounts → any write is `not_paired`; a read returns an empty page, which is a resolution over no accounts rather than an error.
- An `acct_` ID that does not exist is `not_found`. A malformed one is `invalid_request` naming the parameter and the expected prefix, never `not_found` (§4.1).
`accounts` is every account the server holds, **whatever its state**. A `signed_out` or `parked` account is still a candidate here: it is a real account the caller may have meant, and refusing the write for the right reason (`unsupported_capability` / `not_signed_in`, at step 5 of §6.2) tells the caller far more than pretending it does not exist. Filtering by state here would also make the ambiguity rule depend on which accounts happened to be connected, so the same request would sometimes need `account_id` and sometimes not.
type Result ¶
type Result struct {
// Operation is the row as it stands after the outcome was recorded. It is
// the zero value only when the mutation was a no-op that creates no
// operation at all (an unchanged PATCH, or a reaction that is already
// exactly the one asked for).
Operation store.Operation
// HasOperation is false for those no-ops, which serve `operation: null`.
HasOperation bool
// Replayed is true when the idempotency key matched and nothing was sent.
Replayed bool
// Changed is section 7.7's `changed` field.
Changed bool
}
Result is a mutation's answer.
type SendAttempt ¶
type SendAttempt func(ctx context.Context) (gm.SendResult, error)
SendAttempt performs one library send. It is called once per attempt by SendWithRetry, always with the same TmpID.
type SendMediaInput ¶
type SendMediaInput struct {
Request
Media gm.MediaRef
Caption string
ReplyToMessageID string
ForceRCS bool
}
SendMediaInput is POST /v1/conversations/{id}/messages carrying an upload.
type SendTextInput ¶
SendTextInput is POST /v1/conversations/{id}/messages for a text.
type StartConversationInput ¶
type StartConversationInput struct {
Request
// Numbers is the addressee set. It is the one place a target is named by
// phone number rather than by ID, which is why account_id is required
// there and merely accepted elsewhere (section 7.3).
Numbers []string
GroupName string
}
StartConversationInput is POST /v1/conversations.