state

package
v2.8.2 Latest Latest
Warning

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

Go to latest
Published: Aug 7, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package state owns the Canary app's private durable state, including paired devices, push subscriptions, redacted inbox records, attention cursors, and app-local delivery evidence. It serializes mutations to state.json; daemon runtime and policy state remain separate authorities.

Index

Constants

View Source
const (
	AlertDeliveryVersion = "alert-delivery-v4"

	AlertDeliveryAttemptReserved       = "reserved"
	AlertDeliveryAttemptConfirmed      = "confirmed_pending_outcome"
	AlertDeliveryAttemptAccepted       = "push_service_accepted"
	AlertDeliveryAttemptRetry          = "retryable_failure"
	AlertDeliveryAttemptRejected       = "rejected"
	AlertDeliveryAttemptInterrupted    = "interrupted_uncertain"
	AlertDeliveryAttemptRetired        = "target_retired"
	AlertDeliveryAttemptInactive       = "occurrence_inactive"
	AlertDeliveryAttemptExhausted      = "retry_exhausted"
	AlertDeliveryAttemptModeSuppressed = "mode_suppressed"

	AlertDeliveryHealthHealthy     = "healthy"
	AlertDeliveryHealthDegraded    = "degraded"
	AlertDeliveryHealthUnavailable = "unavailable"
	AlertDeliveryHealthOverflow    = "overflow"

	AlertDeliveryHealthClassRetry          = "retry_pending"
	AlertDeliveryHealthClassRejected       = "transport_rejected"
	AlertDeliveryHealthClassObservation    = "producer_observation_rejected"
	AlertDeliveryHealthClassInterrupted    = "interrupted_uncertain"
	AlertDeliveryHealthClassStateWrite     = "state_write_failure"
	AlertDeliveryHealthClassOverflow       = "capacity_overflow"
	AlertDeliveryHealthClassNoSubscription = "no_active_subscription"
	AlertDeliveryHealthClassSigningKeys    = "signing_keys_unavailable"
	AlertDeliveryHealthClassSender         = "sender_unavailable"

	AlertDeliveryEndRecovered  = "recovered"
	AlertDeliveryEndOmitted    = "authoritative_omission"
	AlertDeliveryEndSuperseded = "qualified_escalation"
	// AlertDeliveryEndAuthorityScopeChanged labels an immutable public boundary
	// projection when the daemon moves to another opaque account/mode authority.
	// The private producer occurrence stays active and resumable: a context
	// switch is neither evidence of recovery nor a trustworthy clear.
	AlertDeliveryEndAuthorityScopeChanged = "authority_scope_changed"

	AlertDeliveryCompletionAccepted  AlertDeliveryCompletion = "accepted"
	AlertDeliveryCompletionRetryable AlertDeliveryCompletion = "retryable_failure"
	AlertDeliveryCompletionRejected  AlertDeliveryCompletion = "rejected"

	AlertDeliveryCompletionApplied         AlertDeliveryCompletionDisposition = "applied"
	AlertDeliveryCompletionAlreadyComplete AlertDeliveryCompletionDisposition = "already_complete"
	AlertDeliveryCompletionInactive        AlertDeliveryCompletionDisposition = "occurrence_inactive"
	AlertDeliveryCompletionRetired         AlertDeliveryCompletionDisposition = "target_retired"

	// AlertDispositionEligible and the related occurrence dispositions are
	// sampled when a producer occurrence is first persisted. An eligible
	// occurrence may only move to terminal suppression at the final mode gate;
	// no later mode upgrade can arm it again.
	AlertDispositionEligible        = "eligible"
	AlertDispositionModeSuppressed  = "mode_suppressed"
	AlertDispositionObserveOnly     = "observe_inbox_only"
	AlertDispositionCutoverExisting = "cutover_existing"
)

Alert-delivery constants version the app-local ledger and classify durable attempt transitions, aggregate health, occurrence endings, and completion dispositions. They do not grant transport eligibility.

View Source
const (
	AlertModeNone        = "none"
	AlertModeActOnly     = "act_only"
	AlertModeWatchAndAct = "watch_and_act"
)

Alert delivery modes control app-side notification eligibility without changing daemon policy or the durable occurrence record.

View Source
const (
	GovernanceTransportAccepted       = "push_service_accepted"
	GovernanceTransportPartial        = "partial_acceptance"
	GovernanceTransportAllFailed      = "all_failed"
	GovernanceTransportNoSubscription = "no_subscription"
	GovernanceTransportMissingKeys    = "missing_keys"
	GovernanceTransportSenderMissing  = "sender_unavailable"
	GovernanceTransportReserved       = "attempt_reserved"
	GovernanceTransportInterrupted    = "interrupted_uncertain"
	GovernanceTransportTargetRetired  = "target_retired"
	GovernanceTransportDeadlineRetry  = "deadline_retry"
	GovernanceTransportCanceledRetry  = "canceled_retry"
	GovernanceTransportNetworkRetry   = "transport_retry"
	GovernanceTransportHTTPRetry      = "http_retry"
	GovernanceTransportHTTPRejected   = "http_rejected"
	// GovernanceTransportTimeoutRetry and the following legacy classes remain
	// readable for state written by the first app implementation; new transport
	// code uses the specific classes above.
	GovernanceTransportTimeoutRetry = "timeout_retry"
	GovernanceTransportRejected     = "rejected"
	GovernanceTransportDead         = "dead_subscription"
	GovernanceTransportStateWrite   = "state_write_failure"
	GovernanceTransportRecovery     = "recovery"
	GovernanceTransportSuppressed   = "suppressed"
	GovernanceTransportOverflow     = "overflow"

	GovernanceDeliveryHealthy     = "healthy"
	GovernanceDeliverySuppressed  = "suppressed"
	GovernanceDeliveryDegraded    = "degraded"
	GovernanceDeliveryUnavailable = "unavailable"
	GovernanceDeliveryOverflow    = "overflow"
)

Governance transport and delivery constants classify app-local Web Push attempts and aggregate delivery health.

View Source
const (
	// AlertDeliveryHealthClassInvalidPersistedState is the public, redacted
	// fail-closed posture for an isolated alert_delivery decode or semantic
	// validation failure. The raw state and its artifact identity stay private.
	AlertDeliveryHealthClassInvalidPersistedState = "invalid_persisted_state"
)
View Source
const AttentionKindStress = "stress"

AttentionKindStress identifies the single legacy inbox record family sharing the app's durable read cursor.

Variables

View Source
var (
	ErrAlertDeliveryOverflow          = errors.New("alert delivery evidence overflow")
	ErrAlertDeliveryOldSnapshot       = errors.New("alert delivery snapshot is older than source authority")
	ErrAlertDeliveryUnknownOccurrence = errors.New("alert delivery occurrence not found")
	ErrAlertDeliveryInvalidTransition = errors.New("invalid alert delivery lifecycle transition")
	ErrAlertDeliveryAttentionRead     = errors.New("alert delivery attention read cursor is invalid")
	ErrAlertDeliveryUnavailable       = errors.New("alert delivery state is unavailable")
)

Alert-delivery errors expose bounded, redacted failure classes while occurrence, target, attempt, and persisted artifact identities stay private.

View Source
var (
	ErrAlertHistoryOverflow          = errors.New("alert history overflow: unread retention limit reached")
	ErrAttentionReadRegression       = errors.New("attention read cursor cannot regress")
	ErrAttentionReadBeyondHighWater  = errors.New("attention read cursor exceeds high-water sequence")
	ErrAttentionReferencesIncomplete = errors.New("attention references are incomplete through requested sequence")
	ErrAttentionSequenceExhausted    = errors.New("attention sequence exhausted")
	ErrInvalidPersistedState         = errors.New("invalid persisted app state")
)

App-state errors describe fail-closed capacity, cursor, and persisted-state validation failures without exposing private record identity.

Functions

func AlertDeliveryTargetRef

func AlertDeliveryTargetRef(deviceID, subscriptionID string) string

AlertDeliveryTargetRef hides device/subscription identities before they enter delivery state. A retired subscription must receive a new target ref.

Types

type AlertDeliveryAttemptTotals

type AlertDeliveryAttemptTotals struct {
	Attempts       int `json:"attempts"`
	Confirmed      int `json:"confirmed_pending_outcome"`
	Accepted       int `json:"push_service_accepted"`
	RetryPending   int `json:"retry_pending"`
	Rejected       int `json:"rejected"`
	Interrupted    int `json:"interrupted_uncertain"`
	TargetRetired  int `json:"target_retired"`
	Inactive       int `json:"occurrence_inactive"`
	RetryExhausted int `json:"retry_exhausted"`
	ModeSuppressed int `json:"mode_suppressed"`
}

AlertDeliveryAttemptTotals is a redacted projection of durable attempt dispositions; RetryPending is derived from current retained evidence.

type AlertDeliveryAttention

type AlertDeliveryAttention struct {
	UnreadCount    int                         `json:"unread_count"`
	HighWaterSeq   uint64                      `json:"high_water_seq"`
	ReadThroughSeq uint64                      `json:"read_through_seq"`
	UnreadRefs     []AlertDeliveryAttentionRef `json:"unread_refs"`
}

AlertDeliveryAttention is the source-neutral ledger's durable unread cursor. UnreadCount counts references above ReadThroughSeq through HighWaterSeq.

type AlertDeliveryAttentionRef

type AlertDeliveryAttentionRef struct {
	DisplayID string          `json:"display_id"`
	Source    rpc.AlertSource `json:"source"`
	Kind      rpc.AlertKind   `json:"kind"`
}

AlertDeliveryAttentionRef identifies one redacted unread occurrence without exposing its private producer key or evidence fingerprint.

type AlertDeliveryCompletion

type AlertDeliveryCompletion string

AlertDeliveryCompletion classifies the transport result supplied when a confirmed reservation is completed.

type AlertDeliveryCompletionDisposition

type AlertDeliveryCompletionDisposition string

AlertDeliveryCompletionDisposition reports whether completion was applied, already known, inactive, or reconciled after target retirement.

type AlertDeliveryCompletionOutcome

type AlertDeliveryCompletionOutcome struct {
	Disposition AlertDeliveryCompletionDisposition `json:"disposition"`
	Class       string                             `json:"class"`
	RetryAt     time.Time                          `json:"retry_at,omitzero"`
}

AlertDeliveryCompletionOutcome reports the durable disposition and retry state produced by completing one reservation.

type AlertDeliveryDueWork

type AlertDeliveryDueWork struct {
	OccurrenceKey string             `json:"-"`
	Candidate     rpc.AlertCandidate `json:"-"`
	DisplayID     string             `json:"display_id"`
}

AlertDeliveryDueWork is an app-internal dispatch record. The private producer occurrence and validated candidate are available to Go callers but are excluded from JSON; DisplayID is the only public identity.

type AlertDeliveryHealth

type AlertDeliveryHealth struct {
	State          string    `json:"state"`
	Class          string    `json:"class,omitempty"`
	UpdatedAt      time.Time `json:"updated_at"`
	LastAcceptedAt time.Time `json:"last_push_service_acceptance_at,omitzero"`
}

AlertDeliveryHealth summarizes app-local delivery readiness and outcomes. LastAcceptedAt records push-service acceptance, not device display or read.

type AlertDeliveryOccurrenceView

type AlertDeliveryOccurrenceView struct {
	DisplayID        string                    `json:"display_id"`
	Source           rpc.AlertSource           `json:"source"`
	Kind             rpc.AlertKind             `json:"kind"`
	PresentationCode rpc.AlertPresentationCode `json:"presentation_code"`
	State            rpc.AlertEpisodeState     `json:"state"`
	Severity         rpc.AlertSeverity         `json:"severity"`
	EvidenceHealth   rpc.AlertEvidenceHealth   `json:"evidence_health"`
	Destination      rpc.AlertDestination      `json:"destination"`
	EvidenceAsOf     time.Time                 `json:"evidence_as_of"`
	StateChangedAt   time.Time                 `json:"state_changed_at"`
	FirstSeenAt      time.Time                 `json:"first_seen_at"`
	LastSeenAt       time.Time                 `json:"last_seen_at"`
	EndedAt          time.Time                 `json:"ended_at,omitzero"`
	EndReason        string                    `json:"end_reason,omitempty"`
	AttentionSeq     uint64                    `json:"attention_seq"`
	Disposition      string                    `json:"disposition"`
}

AlertDeliveryOccurrenceView is safe for HTTP/SSE projection. Producer keys, evidence fingerprints, target identities, attempt IDs, and receipt keys are deliberately absent.

type AlertDeliveryReservation

type AlertDeliveryReservation struct {
	AttemptID     string    `json:"-"`
	DisplayID     string    `json:"display_id"`
	AttemptNumber int       `json:"attempt_number"`
	ReservedAt    time.Time `json:"reserved_at"`
	RetryAt       time.Time `json:"retry_at,omitzero"`
	// Candidate is populated only by a successful ConfirmAlertTransport.
	// It is the exact current candidate checked under the same store lock as
	// the persisted confirmed-pending-outcome transition. Dispatchers must
	// build transport copy from this value, never from a prior due-work scan.
	Candidate rpc.AlertCandidate `json:"-"`
}

AlertDeliveryReservation is the durable-before-send handoff for one occurrence-target attempt. Candidate is populated only after confirmation rechecks current eligibility under the store lock.

type AlertDeliveryView

type AlertDeliveryView struct {
	Initialized      bool                          `json:"initialized"`
	Version          string                        `json:"version,omitempty"`
	Generation       uint64                        `json:"generation"`
	AsOf             time.Time                     `json:"as_of,omitzero"`
	CurrentState     rpc.AlertSnapshotState        `json:"current_state,omitempty"`
	Coverage         rpc.AlertCoverage             `json:"coverage,omitzero"`
	Sources          []rpc.AlertSourceCoverage     `json:"sources,omitzero"`
	SourceWatermarks map[rpc.AlertSource]time.Time `json:"-"`
	Occurrences      []AlertDeliveryOccurrenceView `json:"occurrences"`
	Attention        AlertDeliveryAttention        `json:"attention"`
	AttemptTotals    AlertDeliveryAttemptTotals    `json:"-"`
	DeliveryHealth   AlertDeliveryHealth           `json:"delivery_health"`
	// AuthorityScope is private app coordination state. HTTP/SSE DTOs map the
	// view explicitly and JSON must never expose this opaque broker context.
	AuthorityScope string `json:"-"`
}

AlertDeliveryView is the redacted app projection of the source-neutral delivery ledger. Private authority scope, producer keys, target identities, attempts, and receipts are excluded from JSON.

type AlertRecord

type AlertRecord struct {
	ID          string    `json:"id"`
	Fingerprint string    `json:"fingerprint"`
	Action      string    `json:"action,omitempty"`
	Severity    string    `json:"severity,omitempty"`
	Account     string    `json:"account,omitempty"`
	Mode        string    `json:"mode,omitempty"`
	Title       string    `json:"title"`
	Body        string    `json:"body"`
	CreatedAt   time.Time `json:"created_at"`
	// LastMatchedAt is refreshed while an observed stress result still matches this
	// record's context (fingerprint for stress-source records, account/mode
	// for all). Previous-context expiry keys on it; records from before the
	// stamp existed fall back to CreatedAt.
	LastMatchedAt time.Time `json:"last_matched_at,omitzero"`
	AttentionSeq  uint64    `json:"attention_seq"`
}

AlertRecord is a redacted durable inbox row. AttentionSeq zero identifies a legacy row outside the shared unread cursor.

type AlertSettings

type AlertSettings struct {
	Mode string `json:"mode"`
}

AlertSettings holds the operator-selected app notification mode.

type Attention

type Attention struct {
	UnreadCount    int            `json:"unread_count"`
	HighWaterSeq   uint64         `json:"high_water_seq"`
	ReadThroughSeq uint64         `json:"read_through_seq"`
	UnreadRefs     []AttentionRef `json:"unread_refs"`
}

Attention is the shared durable unread cursor for the legacy Alerts inbox. Rows with sequence zero are intentionally excluded from UnreadCount.

type AttentionRef

type AttentionRef struct {
	Kind string `json:"kind"`
	ID   string `json:"id"`
}

AttentionRef identifies one redacted legacy inbox row without exposing its private fingerprint or transport identity.

type Data

type Data struct {
	Devices           []DeviceGrant       `json:"devices,omitempty"`
	AlertSettings     AlertSettings       `json:"alert_settings"`
	PushSubscriptions []PushSubscription  `json:"push_subscriptions,omitempty"`
	AlertHistory      []AlertRecord       `json:"alert_history,omitempty"`
	VAPID             *VAPIDKeys          `json:"vapid,omitempty"`
	LastPush          *PushAttempt        `json:"last_push,omitempty"`
	ProposalAudit     []ProposalAuditItem `json:"proposal_audit,omitempty"`
	RelayRoute        *RelayRoute         `json:"relay_route,omitempty"`
	// LegacyGovernanceOccurrences decodes the retired governance ledger's
	// occurrence rows for exactly one purpose: compacting their attention
	// sequences out of the shared cursor space at load. It is nilled by that
	// migration and never persisted again.
	LegacyGovernanceOccurrences []legacyGovernanceOccurrence `json:"governance_occurrences,omitempty"`
	DiagnosticStatus            GovernanceDiagnosticStatus   `json:"diagnostic_status"`
	AttentionHighWaterSeq       uint64                       `json:"attention_high_water_seq"`
	AttentionReadThroughSeq     uint64                       `json:"attention_read_through_seq"`
	AlertDelivery               *alertDeliveryData           `json:"alert_delivery,omitempty"`
}

Data is the persisted app-state envelope. AlertDelivery remains an internal independently versioned section even though the surrounding legacy fields are exported for JSON persistence and tests.

type DeviceGrant

type DeviceGrant struct {
	ID           string `json:"id"`
	Name         string `json:"name,omitempty"`
	PublicKeyJWK string `json:"public_key_jwk,omitempty"`
	// DeviceCookieHashes authenticate the long-lived HttpOnly device
	// cookie. Cookies are the only client storage that provably survives
	// the iOS home-screen web-app container split (localStorage/IndexedDB
	// written by Safari never reach the installed app), so session
	// continuity must not depend on script-visible storage. A capped list,
	// not a single value: Safari and the installed app hold twin copies of
	// the cookie jar, so issuing a fresh cookie to one twin must never
	// invalidate the other.
	DeviceCookieHashes []string  `json:"device_cookie_hashes,omitempty"`
	CreatedAt          time.Time `json:"created_at"`
	LastSeenAt         time.Time `json:"last_seen_at,omitzero"`
	RevokedAt          time.Time `json:"revoked_at,omitzero"`
}

DeviceGrant is an app-owned paired-device identity. RevokedAt is terminal: re-pairing creates a new identity instead of reviving this one.

type GovernanceDiagnosticStatus

type GovernanceDiagnosticStatus struct {
	State string    `json:"state,omitempty"`
	At    time.Time `json:"at,omitzero"`
}

GovernanceDiagnosticStatus stores the latest safe notification-test result.

type ProposalAuditItem

type ProposalAuditItem struct {
	ID        string          `json:"id"`
	DeviceID  string          `json:"device_id,omitempty"`
	Action    string          `json:"action,omitempty"`
	Payload   json.RawMessage `json:"payload,omitempty"`
	CreatedAt time.Time       `json:"created_at"`
}

ProposalAuditItem is a durable app-side audit row for paired-device proposal actions; Payload may contain private request data and is not a public DTO.

type PushAttempt

type PushAttempt struct {
	At             time.Time `json:"at"`
	SubscriptionID string    `json:"subscription_id,omitempty"`
	AlertID        string    `json:"alert_id,omitempty"`
	OK             bool      `json:"ok"`
	Status         string    `json:"status,omitempty"`
	Error          string    `json:"error,omitempty"`
	Class          string    `json:"class,omitempty"`
}

PushAttempt records one classified Web Push transport result. OK means the push service accepted the request, not that a device displayed it.

type PushSubscription

type PushSubscription struct {
	ID         string    `json:"id"`
	DeviceID   string    `json:"device_id"`
	Endpoint   string    `json:"endpoint"`
	P256DH     string    `json:"p256dh"`
	Auth       string    `json:"auth"`
	CreatedAt  time.Time `json:"created_at"`
	LastSeenAt time.Time `json:"last_seen_at,omitzero"`
}

PushSubscription is an app-owned Web Push target bound to one paired device. Its endpoint and keys are private transport material.

type RelayRoute

type RelayRoute struct {
	RemoteURL      string    `json:"remote_url"`
	RouteID        string    `json:"route_id"`
	ConnectorToken string    `json:"connector_token"`
	PublicURL      string    `json:"public_url,omitempty"`
	ConnectorURL   string    `json:"connector_url,omitempty"`
	CreatedAt      time.Time `json:"created_at"`
	UpdatedAt      time.Time `json:"updated_at"`
	ExpiresAt      time.Time `json:"expires_at"`
}

RelayRoute stores the app connector's resumable remote-relay registration. ExpiresAt is informational because a token-matched reconnect may revive it.

type Store

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

Store serializes access to the app's private state.json and returns copies or redacted projections at its public read boundaries. Its zero value is not usable; callers open a store with Open.

func Open

func Open(dir string) (*Store, error)

Open loads or initializes the private app store under dir, validates its persisted invariants, and recovers interrupted delivery reservations. It quarantines an invalid optional alert-delivery ledger without fabricating a replacement authority.

func (*Store) ActivePushSubscriptions

func (s *Store) ActivePushSubscriptions() []PushSubscription

ActivePushSubscriptions returns subscriptions only for current, non-revoked paired devices. Governance delivery deliberately does not inherit the legacy stress inbox's looser historical subscription iteration.

func (*Store) ActivePushSubscriptionsForDevice

func (s *Store) ActivePushSubscriptionsForDevice(deviceID string) []PushSubscription

ActivePushSubscriptionsForDevice returns subscriptions only when deviceID is a current, non-revoked paired device; otherwise it returns nil.

func (*Store) AddDevice

func (s *Store) AddDevice(d DeviceGrant) error

AddDevice durably inserts or updates a paired device. Revocation atomically retires that device's targets in both delivery ledgers and cannot be undone by updating the same identity.

func (*Store) AddDeviceCookieHash

func (s *Store) AddDeviceCookieHash(id, hash string) error

AddDeviceCookieHash retains a bounded set of cookie generations for one paired device so Safari and installed-app cookie jars can coexist.

func (*Store) AddPushSubscription

func (s *Store) AddPushSubscription(sub PushSubscription) error

AddPushSubscription durably inserts or refreshes an app-owned push target. Moving an endpoint between devices requires a fresh, never-retired target identity and atomically retires the prior target's delivery evidence.

func (*Store) AlertDeliveriesDue

func (s *Store) AlertDeliveriesDue(now time.Time) []AlertDeliveryDueWork

AlertDeliveriesDue reconstructs active transport-eligible work from durable state, including after restart without a fresh daemon snapshot. Per-target receipt/retry dedupe remains authoritative in BeginAlertDelivery.

func (*Store) AlertDelivery

func (s *Store) AlertDelivery(now time.Time) AlertDeliveryView

AlertDelivery returns one atomic generation of coverage, current state, source authority, redacted occurrence history, attention, and delivery totals. It contains no producer, target, attempt, or receipt identity.

func (*Store) AlertHistory

func (s *Store) AlertHistory(limit int) []AlertRecord

AlertHistory returns a copy of the newest legacy inbox rows. A non-positive limit returns all retained rows.

func (*Store) AlertSettings

func (s *Store) AlertSettings() AlertSettings

AlertSettings returns the current app notification mode.

func (*Store) Attention

func (s *Store) Attention() Attention

Attention returns a snapshot of the legacy inbox's shared durable unread cursor and redacted unread references.

func (*Store) BeginAlertDelivery

func (s *Store) BeginAlertDelivery(occurrenceKey, targetRef string, now time.Time) (AlertDeliveryReservation, bool, error)

BeginAlertDelivery durably reserves one private occurrence+target attempt before a transport caller is allowed to send. DisplayID is never accepted as authority and receipt identity is constructed internally.

func (*Store) ClearAlertHistory

func (s *Store) ClearAlertHistory() (int, error)

ClearAlertHistory removes only rows already covered by the durable read cursor and returns the number removed; unread rows are always retained.

func (*Store) CompactAlertDelivery

func (s *Store) CompactAlertDelivery(now time.Time) error

CompactAlertDelivery removes read, ended evidence older than the retention window and retired targets no longer referenced by active subscriptions or retained attempts. Unread occurrences are never compacted.

func (*Store) CompactAlertHistory

func (s *Store) CompactAlertHistory(stressFingerprint, account, mode string, now time.Time) error

CompactAlertHistory refreshes the last-matched stamp on records that still match the observed context and drops read records whose context died more than the retention window ago. Matching mirrors the SPA's staleness rule: only a positive mismatch (a different live stress fingerprint for a stress-source record, or a different stated account/mode) marks a record previous-context; unknown context never expires anything. Unread records never expire — the operator sees evidence before the store forgets it.

func (*Store) CompleteAlertDelivery

func (s *Store) CompleteAlertDelivery(attemptID string, completion AlertDeliveryCompletion, now time.Time) (AlertDeliveryCompletionOutcome, error)

CompleteAlertDelivery completes only a persisted reservation. It rechecks occurrence and target authority under the store lock before recording a receipt. The caller supplies neither occurrence, target, receipt key nor DisplayID, so it cannot redirect acceptance evidence.

func (*Store) ConfirmAlertTransport

func (s *Store) ConfirmAlertTransport(attemptID string, now time.Time) (AlertDeliveryReservation, bool, error)

ConfirmAlertTransport is the last durable-authority check immediately before an external Sender.Send call. Reservation alone never grants transport: a recovery or target retirement between Begin and Confirm finalizes the attempt without sending. The store cannot hold its lock across Sender.Send; a transition after Confirm is consequently recorded as interrupted uncertainty rather than proof that transport did or did not occur.

func (*Store) Device

func (s *Store) Device(id string) (DeviceGrant, bool)

Device returns the active paired device with id. Revoked and unknown devices both return false.

func (*Store) Devices

func (s *Store) Devices() []DeviceGrant

Devices returns a shallow copy of all paired-device records, including revoked devices retained as audit state.

func (*Store) EnsureVAPID

func (s *Store) EnsureVAPID(now time.Time, gen func() (privateKey, publicKey string, err error)) (VAPIDKeys, error)

EnsureVAPID returns the retained app signing keys or generates and durably stores one pair. gen is called while the store is locked and only when a complete retained pair is unavailable.

func (*Store) GovernanceDiagnostic added in v2.5.4

func (s *Store) GovernanceDiagnostic() GovernanceDiagnosticStatus

GovernanceDiagnostic returns the latest safe notification-test result.

func (*Store) HasAlertFingerprint

func (s *Store) HasAlertFingerprint(fp string) bool

HasAlertFingerprint reports whether the legacy inbox retains a record with the private semantic fingerprint fp.

func (*Store) LastPush

func (s *Store) LastPush() *PushAttempt

LastPush returns a copy of the legacy last-attempt diagnostic, or nil when no attempt has been recorded.

func (*Store) MarkAlertDeliveryAttentionRead

func (s *Store) MarkAlertDeliveryAttentionRead(throughSeq uint64) (AlertDeliveryAttention, error)

MarkAlertDeliveryAttentionRead durably advances the source-neutral inbox cursor only across a complete contiguous set of retained references. It is evidence of rendered app state, not human attention or physical delivery.

func (*Store) MarkAttentionRead

func (s *Store) MarkAttentionRead(throughSeq uint64) (Attention, error)

MarkAttentionRead durably advances the shared read cursor to application render state reported by a client. It is not proof of human attention or physical delivery.

func (*Store) ObserveAlertSnapshot

func (s *Store) ObserveAlertSnapshot(snapshot rpc.AlertCandidateSnapshot) (AlertDeliveryView, error)

ObserveAlertSnapshot validates and commits one complete producer contract. All lifecycle, authority-watermark, attention, and snapshot-view changes are written by the same atomic state-file replacement. Valid observations are persisted even when they only advance generation/coverage.

func (*Store) PruneDevices

func (s *Store) PruneDevices(cutoff time.Time) (int, error)

PruneDevices removes device grants whose last activity predates cutoff, along with their push subscriptions. Activity is the later of creation and last-seen, so a freshly paired but not-yet-used device survives.

func (*Store) PushSubscriptions

func (s *Store) PushSubscriptions() []PushSubscription

PushSubscriptions returns a shallow copy of all retained subscriptions, including targets whose device activity is not checked by this legacy read.

func (*Store) RecordAlert

func (s *Store) RecordAlert(rec AlertRecord) error

RecordAlert appends one redacted legacy inbox record and assigns its durable attention sequence. It rejects duplicate IDs and refuses to evict unread history when the bounded store is full.

func (*Store) RecordAlertIfNew

func (s *Store) RecordAlertIfNew(rec AlertRecord) (bool, error)

RecordAlertIfNew atomically deduplicates a semantic portfolio-stress occurrence and records its durable inbox row under the same store transaction.

func (*Store) RecordDiagnosticStatus

func (s *Store) RecordDiagnosticStatus(status GovernanceDiagnosticStatus) error

RecordDiagnosticStatus validates and persists the latest safe notification test result.

func (*Store) RecordPush

func (s *Store) RecordPush(attempt PushAttempt) error

RecordPush replaces the legacy last-attempt diagnostic with attempt.

func (*Store) RecoverAlertDeliveries

func (s *Store) RecoverAlertDeliveries(now time.Time) error

RecoverAlertDeliveries converts unowned reserve-before-send records into definite no-send retries. Only confirmed-pending-outcome records become interrupted uncertainty because Sender is unreachable before Confirm has durably committed that class. Both paths use the same bounded retry sequence. It is safe both after restart (the ownership map is empty) and in-process after Confirm or Complete persistence failures release their reservation. Genuinely owned work is never rewritten under an active dispatcher.

func (*Store) RelayRoute

func (s *Store) RelayRoute(remoteURL string) (RelayRoute, bool)

RelayRoute returns the resumable route only when remoteURL and its required credentials match. An expired route is still returned for token-matched revival.

func (*Store) RemovePushSubscription

func (s *Store) RemovePushSubscription(id string) error

RemovePushSubscription retires a subscription at the current UTC time.

func (*Store) RemovePushSubscriptionAt

func (s *Store) RemovePushSubscriptionAt(id string, retiredAt time.Time) error

RemovePushSubscriptionAt atomically removes a subscription selected by ID or endpoint and retires its targets in both delivery ledgers. A zero retiredAt uses the current UTC time.

func (*Store) RetireAlertDeliveryTarget

func (s *Store) RetireAlertDeliveryTarget(targetRef string, at time.Time) error

RetireAlertDeliveryTarget permanently closes delivery evidence for one private target ref. A re-paired/re-subscribed endpoint must use a new ref.

func (*Store) SetAlertDeliveryPrerequisiteHealth

func (s *Store) SetAlertDeliveryPrerequisiteHealth(class string, now time.Time) error

SetAlertDeliveryPrerequisiteHealth persists the current dispatcher's allowlisted prerequisite posture. An empty class clears only a prior prerequisite outage and recomputes health from durable attempts; it cannot clear overflow, a state-write failure, or interrupted transport evidence.

func (*Store) SetAlertMode

func (s *Store) SetAlertMode(mode string) error

SetAlertMode validates and durably replaces the app notification mode. It does not change daemon policy or retroactively alter stored occurrences.

func (*Store) SetDeviceSeen

func (s *Store) SetDeviceSeen(id string, at time.Time) error

SetDeviceSeen durably records the supplied last-seen time for a known device.

func (*Store) SetRelayRoute

func (s *Store) SetRelayRoute(route RelayRoute) error

SetRelayRoute validates and durably stores a relay registration, preserving CreatedAt when the same route identity is refreshed.

func (*Store) VAPID

func (s *Store) VAPID() (VAPIDKeys, bool)

VAPID returns a copy of the app's retained signing keys. False means no key record exists; callers must also validate non-empty key material as needed.

type VAPIDKeys

type VAPIDKeys struct {
	PublicKey  string    `json:"public_key"`
	PrivateKey string    `json:"private_key"`
	CreatedAt  time.Time `json:"created_at"`
}

VAPIDKeys stores the app-owned signing key pair. PrivateKey must never cross an authenticated app response or logging boundary.

Jump to

Keyboard shortcuts

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