accounts

package
v1.3.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 14, 2026 License: AGPL-3.0 Imports: 15 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package accounts is the account registry and supervisor: which accounts exist, their state, one gm.Backend and one ingest goroutine each, and start/stop on pair, sign-out and remove (spec section 2.2).

Accounts are independent. One account's phone being asleep, its cookies expiring or its backfill running does not block another's.

Index

Constants

View Source
const (
	// BackfillComplete: accounts.backfill_complete_at_ms is set, so an empty
	// result means there is nothing rather than not yet.
	BackfillComplete = "complete"
	// BackfillRunning: a worker is walking this account now.
	BackfillRunning = "running"
	// BackfillPaused: THIS account's phone reported a database sync, so its
	// walk is waiting (section 5.2). Another account's phone does not cause
	// it.
	BackfillPaused = "paused"
	// BackfillPending: scheduled, not started yet.
	BackfillPending = "pending"
	// BackfillNotStarted: this account will NOT be scheduled -- parked,
	// signed out, error or account_changed -- so no worker exists for it.
	BackfillNotStarted = "not_started"
)

The closed `backfill.state` vocabulary of spec section 7.5.

View Source
const (
	// StatePairing: a pair is in flight and there is no session yet. It is
	// NEVER a resting state -- see Resting.
	StatePairing = store.StatePairing
	// StateConnected: session valid, long poll up. Reads and writes.
	StateConnected = store.StateConnected
	// StateDegraded: a transient listen error is being retried. Reads, and
	// writes that are likely to fail.
	StateDegraded = store.StateDegraded
	// StateError: the supervisor is retrying Reconnect with backoff. Reads;
	// writes refused.
	StateError = store.StateError
	// StateSignedOut: the owner signed this account out, or its cookies
	// died. Reads still work; writes refused with not_signed_in.
	StateSignedOut = store.StateSignedOut
	// StateParked: accounts.max_concurrent is reached, so this account holds
	// no client and no goroutine. Not an error and not transient.
	StateParked = store.StateParked
	// StateAccountChanged: the phone switched Google accounts underneath us.
	StateAccountChanged = store.StateAccountChanged
)
View Source
const (
	// AuditStateChanged carries from, to and state_reason. EVERY transition
	// writes one.
	AuditStateChanged = "account.state_changed"
	// AuditPaired is a brand-new account.
	AuditPaired = "account.paired"
	// AuditResumed is a re-pair onto an existing acct_ row.
	AuditResumed = "account.resumed"
	// AuditSignedOut is the owner signing an account out (spec section 4.7).
	AuditSignedOut = "account.signed_out"
	// AuditPairFailed is a pairing that never completed.
	AuditPairFailed = "account.pair_failed"
)

The audit kinds this package writes (spec section 12.4). Every one of them carries account_id, which is how "what happened to this account" stays answerable after the account is removed.

View Source
const DefaultMaxConcurrent = 8

DefaultMaxConcurrent is settings.accounts.max_concurrent (spec section 15.1, OQ-6). Accounts beyond it are `parked`.

View Source
const DefaultPairingTimeout = 5 * time.Minute

DefaultPairingTimeout is AGENT_GM_PAIRING_TIMEOUT (spec section 15.1): how long a started pairing may sit unconfirmed before the half-built AuthData is discarded and the `pairing` row deleted. It is measured against the injected clock, so no test waits it out.

View Source
const DefaultSweepInterval = 15 * time.Minute

DefaultSweepInterval is settings.ingest.sweep_interval (spec section 15.1), per account. It is also how often the cached `google` block of GET /v1/health is refreshed, so that route never blocks on a phone.

View Source
const SessionPersistInterval = 5 * time.Minute

SessionPersistInterval is the 5-minute timer of spec section 3.3. Cookies mutate in place with no event, so the timer is the only thing that captures a rotation.

View Source
const SubscriberBuffer = 64

SubscriberBuffer is how many state changes a subscriber may fall behind by before it starts dropping them. A slow subscriber must never block the supervisor, so publication is a non-blocking send and the overflow is counted rather than waited on.

Variables

View Source
var ErrUnknownAccount = errors.New("no such account")

ErrUnknownAccount is returned for an acct_ ID the supervisor does not hold.

Functions

func BackfillStates

func BackfillStates() []string

BackfillStates is the closed vocabulary, for the test that keeps it closed.

func PairingTimeoutFromEnv

func PairingTimeoutFromEnv() time.Duration

PairingTimeoutFromEnv reads AGENT_GM_PAIRING_TIMEOUT, falling back to DefaultPairingTimeout. An unparseable value is the default: a malformed timeout must not silently mean "never expire".

func Resting

func Resting(s State) bool

Resting reports whether a state is one an account may sit in indefinitely. `pairing` is the only one that is not: a pairing either completes or its row is deleted (spec sections 3.2, 4.7).

func Schedulable

func Schedulable(s State) bool

Schedulable reports whether the supervisor will give this account a backfill worker and a sweep timer.

`pairing` is included because a pairing in flight is about to become `connected`, and reporting `not_started` for it would be true for a second and misleading thereafter. Everything that reads but does not write -- parked, signed out, error, account_changed -- is not schedulable: it holds no client, so there is nothing for a worker to walk (spec section 4.7).

func Writable

func Writable(s State) bool

Writable reports whether a write naming an account in this state is accepted. Everything else is refused with unsupported_capability / not_signed_in, which is a PER-ACCOUNT condition and deliberately not the service-level not_paired (spec sections 4.7, 7.8).

A `parked` account is fully readable and is not writable: it holds no client to write through.

Types

type Account

type Account struct {
	ID      string
	Address string
	Backend gm.Backend
	// contains filtered or unexported fields
}

Account is one supervised Google account: one backend, one ingest goroutine, one session file.

func (*Account) Apply

func (a *Account) Apply(ctx context.Context, ev gm.Event)

Apply handles one event. It is exported so a test can drive it deterministically without a goroutine.

func (*Account) HasClient

func (a *Account) HasClient() bool

HasClient reports whether this account's backend is connected.

func (*Account) Ingester

func (a *Account) Ingester() *core.Ingester

Ingester exposes this account's ingester, for tests and for the spike.

func (*Account) PersistSession

func (a *Account) PersistSession(ctx context.Context) error

PersistSession writes this account's session file. It is called on PairSuccessful, on AuthTokenRefreshed, on every successful Connect, on graceful shutdown, and on the 5-minute dirty timer (spec section 3.3).

func (*Account) Running

func (a *Account) Running() bool

Running reports whether this account holds a client and a goroutine. A `parked` account holds neither, which is the part of spec section 4.7 worth asserting rather than the state string alone.

type AccountHealth

type AccountHealth struct {
	AccountID     string `json:"account_id"`
	GoogleAccount string `json:"google_account"`
	// Label and StateReason are POINTERS so that "no label" and "no reason"
	// encode as null, exactly as GET /v1/accounts encodes them. Section 7.5
	// says the health block is "the same per-account object", and serving ""
	// here against null there made the same account two shapes depending on
	// which route a client asked.
	Label           *string        `json:"label"`
	State           State          `json:"state"`
	StateReason     *string        `json:"state_reason"`
	PhoneResponding bool           `json:"phone_responding"`
	LastEventAt     *string        `json:"last_event_at"`
	Google          *GoogleHealth  `json:"google"`
	Backfill        BackfillHealth `json:"backfill"`
	Sweep           SweepHealth    `json:"sweep"`
	Counters        Counters       `json:"counters"`
}

AccountHealth is the per-account object GET /v1/health embeds and GET /v1/accounts/{id} returns (spec section 7.5).

type Auditor

type Auditor interface {
	Append(ctx context.Context, kind string, fields map[string]any) error
}

Auditor is the slice of internal/audit this package needs. It is an interface here rather than an import so the supervisor can be tested, and reasoned about, without the audit store -- and so that a nil Auditor is a supervisor that simply does not audit rather than one that panics.

type BackfillHealth

type BackfillHealth struct {
	State              string `json:"state"`
	ConversationsDone  int    `json:"conversations_done"`
	ConversationsTotal int    `json:"conversations_total"`
	// A rendered string, not a *time.Time. These three blocks are served
	// STRAIGHT out of this package by GET /v1/health and
	// GET /v1/accounts/{id} -- they never pass through internal/api's DTO
	// layer -- so Go's default encoder rendered them as RFC3339Nano, which
	// strips trailing zeros: the same account's last_event_at came back
	// ".120Z" on GET /v1/accounts (a DTO route) and ".12Z" on GET /v1/health.
	// Section 4.4's width is fixed, and section 7.5 promises those two routes
	// serve the same object. The type is a string so a *time.Time cannot come
	// back by accident: reverting this does not compile.
	CompletedAt *string `json:"completed_at"`
}

BackfillHealth is the per-account `backfill` block.

type Backfiller

type Backfiller interface {
	Start(ctx context.Context, accountID string) error
	Stop(accountID string)
	Pause(accountID string)
	Resume(accountID string)
	Progress(accountID string) BackfillHealth
}

Backfiller is one backfill worker per connected account (spec section 5.2). Pause and Resume are driven by THAT account's MOBILE_DATABASE_SYNC_STARTED / MOBILE_DATABASE_SYNC_COMPLETE alerts, so one sleepy phone never stalls another account.

type Counters

type Counters struct {
	DroppedEvents     uint64 `json:"dropped_events"`
	UnknownEvents     uint64 `json:"unknown_events"`
	PendingOperations int    `json:"pending_operations"`
}

Counters is the per-account `counters` block.

type GoogleHealth

type GoogleHealth struct {
	ConfigVersionLive string `json:"config_version_live"`
	// ConfigVersionStale is informational and is not a fault (D32).
	ConfigVersionStale bool `json:"config_version_stale"`
	IsDefaultSMSApp    bool `json:"is_default_sms_app"`
}

GoogleHealth is the per-account `google` block. It is served from a cache refreshed on connect and every sweep interval, so GET /v1/health never blocks on a phone, and it is nil -- null on the wire -- for an account that is not `connected`.

type MaxConcurrentSource

type MaxConcurrentSource interface {
	AccountsMaxConcurrent() int
}

MaxConcurrentSource is the one runtime setting this package reads: settings.accounts.max_concurrent (spec sections 4.7, 15.1). It is a one-method interface rather than an import of internal/settings so that the supervisor depends on the value and not on the registry.

type Reason

type Reason string

Reason is the short machine-readable string every account DTO carries beside its state, so `degraded` and `error` are diagnosable without reading logs (spec section 4.7).

It is its own type rather than a bare string so that an invented reason is a compile error: the vocabulary is closed by the compiler, not by a review.

const (
	// ReasonNone is the empty reason, which serialises as null.
	ReasonNone Reason = ""
	// ReasonCapacity: accounts.max_concurrent is reached. Pairs with
	// `parked`, never with `degraded` -- "waiting for a slot" and "retrying a
	// listen error" are different things.
	ReasonCapacity Reason = "capacity"
	// ReasonListenError: the long poll failed. Pairs with `degraded` while it
	// is being retried, and with `error` once it is fatal.
	ReasonListenError Reason = "listen_error"
	// ReasonCredentials: the credentials are dead, or the owner signed this
	// account out.
	ReasonCredentials Reason = "credentials"
	// ReasonRevokedByPhone: the phone revoked this pairing.
	ReasonRevokedByPhone Reason = "revoked_by_phone"
	// ReasonCookiesExpired: GaiaLoggedOut. The fix is a cookie refresh, not a
	// re-pair.
	ReasonCookiesExpired Reason = "cookies_expired"
	// ReasonAccountSwitched: the phone's active Google account changed.
	ReasonAccountSwitched Reason = "account_switched"
	// ReasonCrashRecovered: the state was reconstructed after a crash.
	ReasonCrashRecovered Reason = "crash_recovered"
)

func Reasons

func Reasons() []Reason

Reasons returns spec section 4.7's vocabulary, in the spec's order. The empty reason is not in it: it is the absence of one.

func (Reason) String

func (r Reason) String() string

func (Reason) Valid

func (r Reason) Valid() bool

Valid reports whether r is the empty reason or one of section 4.7's.

type State

type State = store.AccountState

State is the account-state vocabulary of spec section 4.7. It is an alias of store.AccountState so a state read out of a row and a state written into one are the same type -- there is exactly one vocabulary and no conversion layer to disagree with itself.

There is no bad_credentials state and no unpaired state; the seven below are the whole list.

func States

func States() []State

States returns spec section 4.7's whole vocabulary, in the spec's order.

type StateChange

type StateChange struct {
	AccountID string
	From      State
	To        State
	Reason    Reason
	// At is truncated to milliseconds. Section 4.4 says every JSON surface
	// renders timestamps as RFC 3339 UTC with millisecond precision, and a
	// stream is a JSON surface: a nanosecond timestamp here made the SSE
	// feed the one place a client saw a different shape.
	At time.Time
}

StateChange is one account state transition, and the whole payload of GET /v1/accounts/{id}/events. It carries no message data, which is why that route needs no replay ring and no cursor (spec section 7.5). The fields carry NO json tags: this type does not marshal itself field by field. MarshalJSON below is the whole rendering, and a tag here would be a second, inert statement of the shape for a reader to trust and a linter to check -- which is precisely how the timestamp came to be rendered twice, differently.

func (StateChange) MarshalJSON

func (c StateChange) MarshalJSON() ([]byte, error)

MarshalJSON renders an absent `from` and an absent `state_reason` as JSON null, and `at` at section 4.4's fixed millisecond width.

The SSE feed is the one JSON surface that does not go through internal/api's DTO layer -- this object is marshalled here and written straight to the socket -- so every rendering rule has to be applied again, by hand, right here. Two have now had to be: null-not-empty-string, and the timestamp.

Section 4.7 says state_reason is "a short machine-readable string ... or null", and /v1/accounts already honours that. The SSE feed did not: a transition with no reason served `"state_reason": ""`, and the opening snapshot -- where `from` genuinely has no value, because the client held no prior state -- served `"from": ""` as well. An empty string and "there is none" are different, and a client branching on truthiness gets the same answer for both only by accident.

type Subscription

type Subscription struct {
	// contains filtered or unexported fields
}

Subscription is one reader of the feed. Close it exactly once; a closed subscription's channel is closed too, so a range over it terminates.

func (*Subscription) AccountID

func (s *Subscription) AccountID() string

AccountID is the account this subscription follows, or "" for all of them.

func (*Subscription) Close

func (s *Subscription) Close()

Close unsubscribes. It is safe to call more than once.

func (*Subscription) Dropped

func (s *Subscription) Dropped() uint64

Dropped is how many changes this subscriber was too slow to take. It is a fact about the subscriber, never a reason to stall the supervisor.

func (*Subscription) Events

func (s *Subscription) Events() <-chan StateChange

Events is the channel state changes arrive on.

type Supervisor

type Supervisor struct {
	PrepareBackend func(string, gm.Backend) error

	// MaxConcurrent bounds how many accounts run at once. Accounts are
	// connected in last_event_at_ms order, newest first; the rest are parked
	// -- a state of its own, not degraded, because "waiting for a slot" and
	// "retrying a listen error" are different things.
	MaxConcurrent int

	// Settings is the one runtime setting this package reads. A nil Settings
	// means MaxConcurrent is whatever was set on this struct.
	Settings MaxConcurrentSource

	// Audit receives account.state_changed on EVERY transition, plus
	// account.paired, account.resumed, account.signed_out and
	// account.pair_failed. A nil Auditor simply does not audit.
	Audit Auditor

	// Sweep runs the reconciliation sweep for one connected account, on
	// connect -- including after a re-pair, with since = last_event_at_ms --
	// and on that account's own timer.
	Sweep Sweeper

	// Backfill is one backfill worker per connected account.
	Backfill Backfiller

	// PairingTimeout is AGENT_GM_PAIRING_TIMEOUT, measured against the
	// injected clock.
	PairingTimeout time.Duration

	// SweepInterval is settings.ingest.sweep_interval, per account.
	SweepInterval time.Duration

	// ManualIngest stops Start from launching the per-account event
	// goroutine and the per-account sweep timer, so a test can drive Apply
	// itself and never race the loop. Production leaves it false.
	ManualIngest bool
	// contains filtered or unexported fields
}

Supervisor holds every account.

func New

func New(st *store.Store, sessions *store.SessionStore, clk clock.Clock, log core.Logger) *Supervisor

New builds a supervisor.

func (*Supervisor) Adopt

func (s *Supervisor) Adopt(ctx context.Context, id, address string, backend gm.Backend) *Account

Adopt registers an already-paired backend, for a restart where the session file reloaded. It does not pair.

func (*Supervisor) CheckWritable

func (s *Supervisor) CheckWritable(ctx context.Context, accountID string) error

CheckWritable refuses a write naming an account that cannot make one. The refusal is unsupported_capability with details.reason = "not_signed_in": a per-account condition, never the service-level not_paired (spec sections 4.7, 7.8).

func (*Supervisor) ChooseWriteAccount

func (s *Supervisor) ChooseWriteAccount(ctx context.Context, requested string) (store.Account, error)

ChooseWriteAccount applies spec section 7.3 to a write. The rule itself lives in core.ResolveAccount, which is the single implementation of it; this supplies the candidate list from the store and hands back the chosen row.

Only accounts in a usable or recoverable state are candidates. That is what keeps an abandoned `pairing` row from making a single-account deployment ambiguous (spec section 16 Slice 2 test 38); a `signed_out` or `parked` account IS a candidate, because refusing its write for the right reason tells the caller more than pretending it does not exist.

func (*Supervisor) Get

func (s *Supervisor) Get(id string) (*Account, error)

Get returns one supervised account.

func (*Supervisor) Goroutines

func (s *Supervisor) Goroutines() int64

Goroutines is how many per-account goroutines the supervisor is running. A `parked` account contributes none, and a test asserts that rather than trusting the state string.

func (*Supervisor) Health

func (s *Supervisor) Health(ctx context.Context) ([]AccountHealth, error)

Health is every account's health block, newest event first. It reads cached Google values and never calls the phone.

func (*Supervisor) HealthFor

func (s *Supervisor) HealthFor(ctx context.Context, accountID string) (AccountHealth, error)

HealthFor is one account's health block.

func (*Supervisor) List

func (s *Supervisor) List() []*Account

List returns every supervised account, ordered by acct_ ID.

func (*Supervisor) MarkUnresumable

func (s *Supervisor) MarkUnresumable(ctx context.Context, accountID string, reason Reason) error

MarkUnresumable records on the row that an account could not be brought up at startup, so the state and state_reason say so instead of the row sitting at whatever it held when the process last stopped.

It exists because the only two ways an account's state changed were "the supervisor is driving it" and "the owner acted", and there is a third: a session file the process cannot open. That account has no client, so every write naming it is refused -- and until this existed the refusal came with a state and a reason describing the LAST run, which is the one thing an operator reads to find out what is wrong now.

`signed_out` is the state, not `error`: `error` means the supervisor is retrying with backoff, and nothing is retrying here. Section 15.4's runbook row already says an undecryptable data key leaves "every account `signed_out` with its history intact", which is exactly what this writes.

func (*Supervisor) Pair

func (s *Supervisor) Pair(ctx context.Context, backend gm.Backend, cookies map[string]string, deviceIndex int, emoji func(string)) (*Account, error)

Pair adds an account, or resumes one. It is always explicit; Agent GM never pairs implicitly (spec section 3.2).

backend is a fresh gm.Backend for this pairing. cookies are the seven captured cookies, which go from the capture into this call and nowhere else. emoji is handed the one emoji character to show the owner.

func (*Supervisor) PairAs

func (s *Supervisor) PairAs(ctx context.Context, expectedID string, backend gm.Backend, cookies map[string]string, deviceIndex int, emoji func(string)) (*Account, error)

PairAs is Pair with the account the caller expects. `agm pair --account <id>` and POST /v1/pairing/start's account_id make the intent explicit: a signed-in address that hashes to a different acct_ ID is refused with pairing_wrong_account and changes nothing (spec sections 3.2, 4.7).

An empty expectedID accepts whichever account signs in, which is how a first pairing and an ordinary re-pair work.

func (*Supervisor) Reconnect added in v1.3.2

func (s *Supervisor) Reconnect(ctx context.Context, a *Account) error

Reconnect restarts one account's backend and workers in this process. It is the account-scoped equivalent of a process restart: no session or indexed data is removed, and Start performs the normal config refresh, reconciliation sweep and state transition after the connection is ready.

func (*Supervisor) ReloadMaxConcurrent

func (s *Supervisor) ReloadMaxConcurrent(ctx context.Context)

ReloadMaxConcurrent re-reads the setting from its source and re-evaluates parking. It is what a settings change calls.

func (*Supervisor) SetMaxConcurrent

func (s *Supervisor) SetMaxConcurrent(ctx context.Context, n int)

SetMaxConcurrent changes accounts.max_concurrent and re-evaluates parking immediately, so raising the setting connects a parked account WITHOUT a restart (spec section 4.7, section 16 Slice 2 test 37).

func (*Supervisor) SignOut

func (s *Supervisor) SignOut(ctx context.Context, a *Account) error

SignOut disconnects the account, stops its ingest goroutine, shreds its session file, zeroes the in-memory AuthData, sets state='signed_out' and session_present=0.

It deletes no conversation, message, attachment, reaction, contact or operation. Everything stays readable and searchable (spec section 4.7, D30).

func (*Supervisor) Start

func (s *Supervisor) Start(ctx context.Context, a *Account) error

Start connects one account and begins draining its events. It is a no-op if the account is already running.

Every connect issues one ListConversations for this account's client: the first call on a Client sends BUGLE_ANNOTATION and later calls BUGLE_MESSAGE, and the flag lives on the Client, of which there is one per account. Satisfying the rule for one account leaves another account's conversation events untrustworthy (spec section 3.7).

func (*Supervisor) Stop

func (s *Supervisor) Stop(a *Account)

Stop disconnects one account and stops its ingest goroutine. It deletes nothing.

func (*Supervisor) StopAll

func (s *Supervisor) StopAll(ctx context.Context)

StopAll persists every session and stops every account, which is what graceful shutdown does.

func (*Supervisor) Subscribe

func (s *Supervisor) Subscribe(accountID string) *Subscription

Subscribe delivers one event per state change, for one account or -- with an empty accountID -- for every account, each tagged. It backs GET /v1/accounts/{account_id}/events and `agm session --watch` (spec section 7.5).

func (*Supervisor) SweepPairings

func (s *Supervisor) SweepPairings(ctx context.Context) ([]string, error)

SweepPairings deletes every `pairing` row with no live pairing behind it, and every live one older than the pairing timeout. It runs at startup -- where the live set is empty, so a process killed mid-pairing leaves nothing behind -- and on a timer.

It returns the IDs it deleted. A `pairing` row does not count toward the section 7.3 ambiguity rule even before this runs (store.CountsTowardAmbiguity), so an abandoned pairing can never start demanding account_id on writes.

type SweepHealth

type SweepHealth struct {
	// LastSweepAt is accounts.last_sweep_at_ms, so it survives a restart:
	// "when did this account last sweep?" is exactly the question an operator
	// asks after one.
	LastSweepAt *string `json:"last_sweep_at"`
	// SweepsTotal is a PROCESS-LIFETIME counter, not a stored total. A small
	// number right after a restart means the process is young, not that the
	// sweeper has stalled -- read LastSweepAt for that.
	SweepsTotal int `json:"sweeps_total"`
}

SweepHealth is the per-account `sweep` block.

type Sweeper

type Sweeper interface {
	Sweep(ctx context.Context, accountID string, since time.Time) error
}

Sweeper runs the reconciliation sweep of spec section 5.4 for one account, with `since` taken from that account's last_event_at_ms. One timer per connected account; a sweep for one account never touches another's rows.

type Workers

type Workers struct {
	// Engine builds the per-account engine. It is a function rather than a
	// map because an account's backend is only known once the supervisor has
	// connected it.
	Engine func(accountID string) (*core.Account, error)
	// Store is read directly by Progress.
	//
	// Progress used to build an engine just to reach the store, which meant
	// asking about an account that has no backend -- a parked one, a
	// signed-out one, one that has not connected yet -- did work and could
	// fail for a reason that has nothing to do with the question. The
	// backfill counts are rows in `backfill_state`; reading them needs a
	// database and nothing else.
	Store *store.Store
	// Log is optional.
	Log core.Logger
	// contains filtered or unexported fields
}

Workers is the real backfill and the real reconciliation sweep, in the shape `internal/accounts` supervises them.

**Why this type exists at all.** `internal/accounts` declares `Backfiller` and `Sweeper` so that the supervisor can start, stop, pause and resume the per-account work without importing `internal/core` and creating an import cycle. Before this type there was no implementation of either outside a test double, and `agent-gm serve` passed neither -- so §5.2's backfill and §5.4's sweep, the sweep D26 calls mandatory *because the event stream loses messages*, never ran in the shipped binary while both were "tested" against injected fakes.

The lesson is in the wiring test that goes with this file, not here: a worker interface with exactly one implementation, and that implementation only in tests, is a worker nothing runs.

func NewWorkers

func NewWorkers(st *store.Store, engine func(string) (*core.Account, error), log core.Logger) *Workers

NewWorkers builds the adapter.

func (*Workers) Pause

func (w *Workers) Pause(accountID string)

Pause holds THIS account's backfill while its phone reports a database sync. Results during a phone-side sync are unstable (spec section 5.2).

It records the pause even when no backfill is running yet, and that is not defensive coding: a MOBILE_DATABASE_SYNC_STARTED alert can arrive BEFORE ClientReady, so an account can legitimately be told to pause before it has anything to pause. Ignoring that -- which is what "only pause a running worker" does -- means the first page the walk reads is the unstable one, which is the exact failure section 5.2 pauses to avoid.

func (*Workers) Progress

func (w *Workers) Progress(accountID string) BackfillHealth

Progress reports what GET /v1/health's per-account `backfill` block says.

`conversations_done` and `conversations_total` come from `backfill_state` rather than from this process's memory, so they survive a restart and a resumed backfill reports where it really is rather than starting from zero.

func (*Workers) ProgressFor

func (w *Workers) ProgressFor(accountID string, accountState State) BackfillHealth

ProgressFor is Progress with the account's own state, which decides between the two "not finished" words.

`pending` means scheduled and not started yet; `not_started` means this account will not be scheduled at all -- it is parked, signed out, in error or account_changed, so no worker exists for it. They are different facts, for exactly the reason section 4.7 split `parked` from `degraded`: "waiting its turn" and "not in the queue at all" are not the same thing and an agent reading the block must be able to tell them apart. Reporting `pending` for a parked account would have it wait for a backfill that is never coming.

`complete` wins over both whenever backfill_complete_at_ms is set, because a signed-out account that finished before it was signed out still has its history indexed -- which is the whole point of section 4.7's "signing out keeps everything".

func (*Workers) Resume

func (w *Workers) Resume(accountID string)

Resume releases it on that phone's MOBILE_DATABASE_SYNC_COMPLETE.

func (*Workers) Start

func (w *Workers) Start(ctx context.Context, accountID string) error

Start begins this account's backfill, once. Calling it again while one is running is a no-op rather than a second walk of the same history.

func (*Workers) StartWith

func (w *Workers) StartWith(ctx context.Context, accountID string, ready []gm.Conversation) error

Ready is the conversation list ClientReady carried, for a caller that has one. It exists so a supervisor that does hold them can pass them rather than making the walk re-fetch (spec section 5.2 step 1).

func (*Workers) Stop

func (w *Workers) Stop(accountID string)

Stop ends this account's backfill. It is called when an account disconnects, is signed out, is parked or is removed.

func (*Workers) Sweep

func (w *Workers) Sweep(ctx context.Context, accountID string, since time.Time) error

Sweep runs the reconciliation sweep for one account.

It is synchronous: the supervisor calls it on connect and on that account's timer, and a sweep that ran in the background would make "the sweep ran" unobservable to the thing that asked for it.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL