Documentation
¶
Index ¶
- Constants
- func ApplyEvent(tx *sql.Tx, event Event, validator EntityValidator) (bool, error)
- func BackfillOrphanEntities(tx *sql.Tx, sessionID string) (int, error)
- func BackfillStaleIssues(tx *sql.Tx, sessionID string) (int, error)
- func InitServerEventLog(db *sql.DB) error
- func IsPermanentApplyError(err error) bool
- func MarkEventsSynced(tx *sql.Tx, acks []Ack) error
- type Ack
- type ApplyResult
- type ConflictRecord
- type EntityValidator
- type Event
- type FailedEvent
- type OrphanedParentError
- type PullOutcome
- type PullResult
- type PushResult
- type Rejection
- type SkippedEvent
Constants ¶
const ( // SkipReasonOrphanedParent — a create whose ON DELETE CASCADE parent no // longer exists. Dropping it is the outcome that agrees with every other // peer; see OrphanedParentError. SkipReasonOrphanedParent = "orphaned_parent" // SkipReasonQuarantined — the event failed to apply with an error that // cannot succeed on retry. Advancing past it keeps the stream moving; see // IsPermanentApplyError. SkipReasonQuarantined = "quarantined" )
Reasons an event lands in sync_skipped_events.
Variables ¶
This section is empty.
Functions ¶
func ApplyEvent ¶
ApplyEvent applies a single sync event to the database within the given transaction. The validator is called to check that the entity type is allowed before any SQL is executed. Returns true if an existing row was overwritten (create/update only).
func BackfillOrphanEntities ¶
BackfillOrphanEntities scans all syncable tables for rows that have no corresponding action_log entry and inserts synthetic "create" events so they get picked up by the normal push pipeline.
Only runs when the client has never pulled from the server (last_pulled_server_seq == 0). After the first pull, entities in the DB may have come from the server, and backfilling those would create duplicate events.
Returns the total number of entities backfilled.
func BackfillStaleIssues ¶
BackfillStaleIssues inserts synthetic update events for issues whose updated_at timestamp is newer than the latest action_log entry. This helps sync older data where status changes weren't logged.
Only runs when the client has never pulled from the server.
func InitServerEventLog ¶
InitServerEventLog creates the events table and index if they don't exist.
func IsPermanentApplyError ¶ added in v0.60.0
IsPermanentApplyError reports whether a per-event apply failure is guaranteed to recur on every retry, and so must be quarantined rather than retried.
The rule ¶
An apply failure is PERMANENT when it is a pure function of the event itself and of local state that no later pull can change:
- the payload cannot be decoded, or carries no usable fields;
- the entity type or action type is one this client does not implement;
- the entity ID is empty;
- the statement violated a schema constraint (FOREIGN KEY, UNIQUE, NOT NULL, CHECK).
Replaying such an event reproduces the identical failure forever, because events are delivered in server_seq order: nothing that has not already arrived can arrive earlier and make the event valid.
An apply failure is TRANSIENT — and therefore retried with the cursor preserved, exactly as before — when it comes from the environment rather than the event: SQLITE_BUSY / database is locked, I/O errors, disk full, a closed or cancelled connection, timeouts. Those succeed on a later attempt and must never be quarantined, because quarantining one would skip an event that was perfectly valid.
The default is TRANSIENT. An error this function does not recognise is retried, which preserves the old behaviour: a peer stalls loudly rather than silently dropping an event whose nature we could not establish. Quarantine is opt-in per error class, never a catch-all.
Matching is on error text rather than driver error types on purpose: td links two SQLite drivers (mattn/go-sqlite3 and modernc.org/sqlite) with different error types, and the store interface is meant to stay driver-agnostic.
Types ¶
type ApplyResult ¶
type ApplyResult struct {
LastAppliedSeq int64
Applied int
Overwrites int
Conflicts []ConflictRecord
Failed []FailedEvent
// Skipped holds events deliberately not applied because applying them
// would be incorrect, not because something went wrong — today, a create
// whose FOREIGN KEY parent has been deleted (see OrphanedParentError).
// These are recorded in sync_skipped_events and must not block the stream.
Skipped []SkippedEvent
}
ApplyResult summarises the outcome of applying a batch of events.
func ApplyRemoteEvents ¶
func ApplyRemoteEvents(tx *sql.Tx, events []Event, myDeviceID string, validator EntityValidator, lastSyncAt *time.Time) (ApplyResult, error)
ApplyRemoteEvents applies a batch of remote events to the local database. Events with invalid entity types are logged and added to the Failed list. lastSyncAt gates conflict detection: overwrites are only flagged as conflicts when the local row was modified after lastSyncAt. Pass nil to skip conflict recording.
type ConflictRecord ¶
type ConflictRecord struct {
EntityType string
EntityID string
ServerSeq int64
LocalData json.RawMessage
RemoteData json.RawMessage
OverwrittenAt time.Time
}
ConflictRecord captures the details of a local row overwritten by a remote event.
type EntityValidator ¶
EntityValidator returns true if the given entity type is allowed.
type Event ¶
type Event struct {
ClientActionID int64
DeviceID string
SessionID string
ActionType string
EntityType string
EntityID string
Payload []byte // JSON
ClientTimestamp time.Time
ServerSeq int64
}
Event represents a single sync action from a device.
func GetPendingEvents ¶
GetPendingEvents reads unsynced, non-undone action_log rows and returns them as Events. It uses rowid for ordering and as ClientActionID. Before querying, it backfills synthetic "create" entries for any entities that exist in syncable tables but have no action_log row (e.g. pre-existing data).
func GetPendingEventsPreserveSession ¶ added in v0.45.0
GetPendingEventsPreserveSession reads unsynced, non-undone action_log rows and returns them as Events whose SessionID is the value stored on each row (NOT a caller-supplied session). Use this from the td-sync post-commit promotion path so per-actor session_ids stamped by the REST middleware (`twu_*` / `twa_*_as_*`) propagate end-to-end into events.db.
Behavioural differences vs GetPendingEvents:
- Per-row session_id is taken from action_log.session_id rather than overwritten with the caller's session.
- DeviceID is the constant supplied by the caller (typically api.TdWatchServerDeviceID = "td_watch_server" — see plan §10 Q2).
- No backfill (BackfillOrphanEntities / BackfillStaleIssues): promotion is for fresh writes from the REST handler that just committed. The backfill helpers exist to repair pre-existing data on the local CLI before the first push and would race / duplicate when run repeatedly on the server side.
Other field semantics (action_type mapping, entity_type normalization, {schema_version, new_data, previous_data} payload envelope, timestamp parsing, ClientActionID = rowid) match GetPendingEvents exactly so downstream consumers (InsertServerEvents, ApplyRemoteEvents) can't tell the two paths apart.
type FailedEvent ¶
type FailedEvent struct {
ServerSeq int64
DeviceID string
ActionType string
EntityType string
EntityID string
Payload []byte
Error error
}
FailedEvent records a single event that could not be applied.
type OrphanedParentError ¶ added in v0.60.0
type OrphanedParentError struct {
EntityType string
EntityID string
Column string
ParentTable string
ParentID string
}
OrphanedParentError reports that a remote row cannot be inserted because a row it references via a FOREIGN KEY does not exist locally.
Why this is a deliberate drop rather than a failure ¶
Every FK in the local schema that guards a synced child row is declared ON DELETE CASCADE (see internal/db/migration_fk_enforcement.go). A child of a cascade FK is not merely invalid without its parent — it is a row the schema says must not survive the parent. So when the parent is absent, there is no state in which applying the child is correct: had the parent still existed and been deleted a moment later, the cascade would have removed the child again.
The absence is also terminal, not a matter of timing. Events are applied in server_seq order, and a parent's create always carries a lower server_seq than any child referencing it: the author cannot position an issue on a board it does not have, and its own action_log preserves that order on push. A missing parent therefore means the parent was deleted, not that its create is still in flight. (Confirmed empirically for td-8fe2bc: enabling PRAGMA defer_foreign_keys, which would let a parent land later in the same batch, did not help — the parent was genuinely gone.)
Dropping the child converges peers rather than diverging them. The canonical case is a peer replaying its OWN events from a cursor suffix: it created a board, positioned an issue on it, then deleted the board. Its local state is already the end state (both rows gone). Replaying the position create would try to resurrect a row whose parent it has already deleted; every other peer, applying the same stream in order, also ends with both rows gone. Skipping is the only outcome that agrees with them.
The event is recorded in sync_skipped_events, never silently discarded.
func (*OrphanedParentError) Error ¶ added in v0.60.0
func (e *OrphanedParentError) Error() string
type PullOutcome ¶ added in v0.60.0
type PullOutcome struct {
// Abort is non-nil when the batch must be rolled back with the cursor
// preserved, so a later pull can retry it. Only transient failures abort.
Abort error
// Record lists events that will not be applied and must be durably
// recorded before the cursor advances past them.
Record []SkippedEvent
}
PullOutcome is the decision about what to do with a batch of applied events.
It lives here, not in cmd/, so every pull path reaches the same verdict: the batch pull (cmd/sync.go runPull), autosync (cmd/autosync.go), and the sync test harness. td-8fe2bc was a wedge in exactly this decision, and a wedge that only one of three call sites is protected against is not fixed.
func ResolvePullOutcome ¶ added in v0.60.0
func ResolvePullOutcome(result ApplyResult) PullOutcome
ResolvePullOutcome decides whether a batch aborts and what it leaves behind.
A TRANSIENT failure aborts the batch: the event was fine and the environment was not, so preserving the cursor and retrying is correct.
A PERMANENT failure does not abort. Retrying one reproduces it exactly, so aborting on it wedges the peer forever: every later pull replays the same batch, fails on the same event, rolls back, and no event behind it ever applies again. Those are quarantined instead — recorded with their error and server_seq, and stepped over. See IsPermanentApplyError for the rule that separates the two.
Deliberate skips (an orphaned create, see OrphanedParentError) are never failures and never abort; they are recorded for the same reason: nothing is dropped without a trace.
type PullResult ¶
PullResult is the server response to a pull request.
func GetEventsSince ¶
func GetEventsSince(tx *sql.Tx, afterSeq int64, limit int, excludeDevice string) (PullResult, error)
GetEventsSince retrieves events after the given sequence number. If excludeDevice is non-empty, events from that device are filtered out.
type PushResult ¶
PushResult is the server response to a push request.
func InsertServerEvents ¶
func InsertServerEvents(tx *sql.Tx, events []Event) (PushResult, error)
InsertServerEvents inserts events into the server event log within the given transaction. Duplicates (by device_id, session_id, client_action_id) are rejected, not errored.
func InsertServerEventsAttached ¶ added in v0.45.0
InsertServerEventsAttached behaves like InsertServerEvents but targets the `events` table in the named schema. Pass "main" for the conventional single-DB case; pass an attached schema name (e.g. "events_db") to write into a database that was opened with `ATTACH DATABASE … AS events_db`.
This is the path used by the td-watch post-commit promotion: project.db is the main schema (action_log lives there) and events.db is attached so the promotion + synced_at flip commit atomically.