sqlite

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: Apache-2.0 Imports: 57 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 sqlite is the loop's one store: a SQLite database with one versioned schema that every repository shares.

Index

Constants

View Source
const (
	SessionEventsKey = "session_events"
	ViewEventsKey    = "view_events"
)

The Retained keys of the events SessionEvents and ViewEvents drop.

View Source
const (
	WorkflowEventsKey   = "workflow_events"
	UnitlessLoopRowsKey = "unitless_loop_rows"
)

The Retained keys of WorkflowEvents and UnitlessLoopRows; WorkflowRuns and PlanItems count under their tables.

View Source
const (
	KindPaused  = "paused"
	KindResumed = "resumed"
)

The kinds of the event a pause or a resume leaves.

View Source
const (
	SlackThread = "thread"
	SlackDM     = "dm"
)

Object kinds of slack_objects.

View Source
const (
	SlackNew      = "new"
	SlackEdited   = "edited"
	SlackDeleted  = "deleted"
	SlackReaction = "reaction"
)

Change kinds of slack_changes.

View Source
const DefaultKeep = 3

DefaultKeep is how many pre-migration backups stay.

View Source
const DefaultWarmFor = 72 * time.Hour

DefaultWarmFor is items.heat.warm_for when unset.

View Source
const PreRestoreDays = 30

PreRestoreDays is how long the copies Restore keeps of a replaced store stay.

View Source
const ReadConns = 4

ReadConns is the size of the read pool.

View Source
const SchemaVersion = 4

SchemaVersion is the PRAGMA user_version of a store this release creates and migrates to.

View Source
const SlackDiscoverCursor = "discover"

SlackDiscoverCursor is the source's discovery cursor.

View Source
const TimeLayout = time.RFC3339Nano

Variables

View Source
var DefaultRetention = Retention{
	SessionEvents:    retentionWindow,
	ViewEvents:       retentionWindow,
	ClosedSessions:   retentionWindow,
	Stops:            turns.StopsKept,
	Instructions:     retentionWindow,
	BriefBodies:      7 * 24 * time.Hour,
	EndedPRs:         400 * 24 * time.Hour,
	WorkflowRuns:     retentionWindow,
	PlanItems:        7 * 24 * time.Hour,
	WorkflowEvents:   retentionWindow,
	UnitlessLoopRows: retentionWindow,
	Classifications:  retentionWindow,
	Fetches:          retentionWindow,
	SubjectMarks:     true,
	VacuumPages:      4096,
}

DefaultRetention is what the daemon's retain job applies. ViewRows stays zero: the views re-plan a unit whose applied rows are gone, and every ended unit with a turn book is still planned.

View Source
var ErrDamaged = errors.New("the store is damaged")

ErrDamaged is a store that fails SQLite's integrity checks.

View Source
var ErrNoSpace = errors.New("not enough free space for the store's backup")

ErrNoSpace is too little free space for the backup a migration takes.

View Source
var ErrSchema = errors.New("the store is not at this release's schema version")
View Source
var ErrStoreBusy = errors.New("another process has the store open")

ErrStoreBusy is a store whose lock another process holds.

View Source
var ErrUnknownSegment = errors.New("unknown segment")

SessionEventKinds are the bookkeeping kinds SessionEvents drops. Pause events and every event of a pull request are kept.

Functions

func AdoptJobDrafts added in v0.2.0

func AdoptJobDrafts(ctx context.Context, tx *sql.Tx) error

AdoptJobDrafts rewrites every draft the proposals job proposed under its rules, in any state, to the identity of the default workflow that replaced the rule: rule and workflow stalled-nudge to slack-stalled-nudge, closure to slack-closure, ask-owner to slack-ask-owner, rule_key unchanged, so the workflow's hold and withdrawal see them; a draft not sent gets the workflow's effects.

func Check

func Check(path string) error

Check refuses a store at path that this release cannot open as it is, reading its file without opening it for writing. An absent or empty file passes: Open creates it.

func LockStore added in v0.2.0

func LockStore(path string) (unlock func(), err error)

LockStore takes, without waiting, the lock of the store at path that its writer holds: the daemon while it serves, and a command that migrates or restores the store. A held lock is ErrStoreBusy.

func Megabytes added in v0.2.0

func Megabytes(n int64) string

Megabytes is n bytes as whole megabytes, rounded up.

func ParseKey

func ParseKey(key string) (pr.Ref, error)

ParseKey reads the owner/repo#n key of the round state.

func Refuse added in v0.2.0

func Refuse(path string, s Status) error

Refuse is the SchemaError of a store in s at path, nil when this release opens it.

func StoredUnit

func StoredUnit(u unit.Unit, kind, key string) unit.Unit

StoredUnit is the unit an event of u, kind and key is stored under: u, or the session unit of the key's handle for a handle-keyed kind with no unit. Every writer of events applies it.

Types

type AgentSession

type AgentSession struct {
	ID, Kind, Handle, Home, Worktree, Transcript string
	FirstSeen, LastSeen                          time.Time
}

AgentSession is what the hooks told of one agent session; a resume keeps the handle and starts another.

type AgentWorktree

type AgentWorktree struct{ Home, Worktree string }

AgentWorktree is a worktree an agent session of the loop ran in, with the agent's home.

type Backup added in v0.2.0

type Backup struct {
	Path    string
	Version uint32
	Taken   time.Time
	// PreRestore is the store as it was before a restore replaced it.
	PreRestore bool
	Size       int64
	// contains filtered or unexported fields
}

Backup is a copy of the store in the backups directory.

func Backups added in v0.2.0

func Backups(dir string) ([]Backup, error)

Backups lists the backups in dir, newest first; an absent dir has none.

func Restorable added in v0.2.0

func Restorable(all []Backup) (Backup, bool)

Restorable is the newest backup in all, newest first as Backups lists them, that this release opens or migrates; pre-restore copies are left for an explicit choice.

type ChangeRow

type ChangeRow struct {
	Seq                        int64
	Conversation, TS, ThreadTS string
	Kind, EditedTS             string
	At                         time.Time
}

type Classifications

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

Classifications caches classify outputs by unit, workflow and the unit's fingerprint, and counts the calls of each local day for the daily cap. Its writes note nothing.

func (*Classifications) Output

func (c *Classifications) Output(ctx context.Context, u unit.Unit, workflow, fingerprint string) (json.RawMessage, bool, error)

Output is the stored output of workflow for u at fingerprint.

func (*Classifications) Save

func (c *Classifications) Save(ctx context.Context, u unit.Unit, workflow, fingerprint string, output json.RawMessage, at time.Time) error

Save stores output, a JSON value, replacing the one stored for the same unit, workflow and fingerprint.

func (*Classifications) Spend

func (c *Classifications) Spend(ctx context.Context, at time.Time, limit int) (bool, error)

Spend counts one classify call on the day of at in at's location when fewer than limit are counted there, and says whether it did.

func (*Classifications) Spent

func (c *Classifications) Spent(ctx context.Context, at time.Time) (int, error)

Spent is how many calls Spend counted on the day of at in at's location.

type ConversationRow

type ConversationRow struct {
	ID, Team, Name, Kind string
	IsMember, Archived   bool
	DMUser               string
	HWM                  string
	Admitted             bool
	UpdatedAt            time.Time
}

type DB

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

DB is the store: one writer connection, reached only through Write, and a read-only pool of ReadConns connections.

func Open

func Open(path string, log Noter) (*DB, error)

Open opens the store at path, creating it at SchemaVersion when it holds no table, and refuses with a SchemaError a store it cannot open as it is: an older one, which Migrate takes first, or a newer one that is not compatible. Both handles open through connector. A nil log gets a private change log.

func OpenReadOnly

func OpenReadOnly(path string) (*DB, error)

OpenReadOnly opens the store at path for reads only, for a process that is not the store's writer; it creates nothing and refuses a store at another version.

func (*DB) Activities added in v0.2.0

func (db *DB) Activities(ctx context.Context, provider unit.ProviderID) (map[unit.Unit]turn.Activity, error)

Activities reads the activity of every unit of provider that has any, in one statement: one aggregated part per table.

func (*DB) AgentTranscript

func (db *DB) AgentTranscript(ctx context.Context, agentSession string) (path, kind string, err error)

AgentTranscript is the transcript file and agent the hooks stored for the agent session, "" for each when none is stored.

func (*DB) AgentWorktrees

func (db *DB) AgentWorktrees(ctx context.Context) ([]AgentWorktree, error)

AgentWorktrees lists the distinct worktrees the loop's sessions ran in.

func (*DB) AutomatedTurns added in v0.2.0

func (db *DB) AutomatedTurns(ctx context.Context, from time.Time, except []unit.ProviderID) (int, error)

AutomatedTurns counts the automated turns sent since from on units of providers other than except's, withdrawn ones included: a turn a workflow started spends the day's budget whatever became of it.

func (*DB) Cards

func (db *DB) Cards() card.Store

Cards is the store of the units' card snapshots.

func (*DB) Classifications

func (db *DB) Classifications() *Classifications

func (*DB) Close

func (db *DB) Close() error

Close closes both handles and waits, up to closeWait, for the statements in flight to release their connections, so the store's files stop changing once it returns. Connections still open then are an error.

func (*DB) DossierSpent

func (db *DB) DossierSpent(ctx context.Context, from, to time.Time) (float64, error)

DossierSpent is the cost of the dossier calls recorded in [from, to).

func (*DB) Dossiers

func (db *DB) Dossiers() dossiers.Store

Dossiers is the dossiers table, and whether a dossier's unit still has open work.

func (*DB) DraftEffects added in v0.2.0

func (db *DB) DraftEffects() outbox.AppliedStore

DraftEffects keeps when the effects of a sent draft were applied.

func (*DB) Drafts

func (db *DB) Drafts() outbox.Store

Drafts is the Outbox's store.

func (*DB) Entries

func (db *DB) Entries() coregtd.Store

func (*DB) Events

func (db *DB) Events() automation.Events

Events reads the events table by id for event workflows, and keeps each workflow's cursor and last firing. Advancing a cursor notes nothing.

func (*DB) Extraction

func (db *DB) Extraction() *ExtractionStore

func (*DB) Fetches

func (db *DB) Fetches() *Fetches

func (*DB) HeadlessSpent

func (db *DB) HeadlessSpent(ctx context.Context, from, to time.Time) (float64, error)

HeadlessSpent is the cost in turn_usage of the headless turns started in [from, to).

func (*DB) Intakes

func (db *DB) Intakes() intake.Store

func (*DB) Items

func (db *DB) Items() coreitems.Store

Items is the items ledger's store: items, their op log and proposals.

func (*DB) Ledger

func (db *DB) Ledger() automation.Ledger

Ledger is the workflows' plan and runs. A write stores its rows and its events in one transaction, noting TopicLoopEvents for the events and TopicGate only when the pending set changes.

func (*DB) LinkTargets

func (db *DB) LinkTargets(ctx context.Context) ([]unit.Unit, error)

LinkTargets are the units some link that can resolve an item points to, sorted by provider and key.

func (db *DB) Links() port.LinkStore

Links is the store of cross-source links.

func (*DB) Marks added in v0.2.0

func (db *DB) Marks(ctx context.Context, u unit.Unit) (map[string]string, error)

Marks are u's handled marks by name.

func (*DB) Projects

func (db *DB) Projects() coregtd.ProjectStore

Projects are the projects' slugs and the Review's runs; a project's own fields are read and written with its entry.

func (*DB) R

func (db *DB) R() Reader

R is the read pool, for a read of one statement. Under a Snapshot's ctx it reads in that snapshot's transaction.

func (*DB) Read

func (db *DB) Read(ctx context.Context, fn func(tx *sql.Tx) error) error

Read runs fn in one deferred read transaction on the pool, so every statement sees one snapshot; under a Snapshot's ctx it runs in that snapshot's transaction. fn must not write.

func (*DB) Retain

func (db *DB) Retain(ctx context.Context, now time.Time, p Retention) (Retained, error)

Retain applies p as of now in one write transaction, noting Change.All with the topics of the tables it changed, then runs incremental_vacuum and PRAGMA optimize outside it. EndedPRs runs first, so the rules after it see the sessions and runs only an ended pull request's turns held, and a second pass at the same now changes nothing and notes nothing.

func (*DB) SaveAgentSession

func (db *DB) SaveAgentSession(ctx context.Context, a AgentSession) error

SaveAgentSession upserts a; an empty field never clears a stored one, and the seen times only widen.

func (*DB) Segments

func (db *DB) Segments() *SegmentStore

func (*DB) Slack

func (db *DB) Slack() *SlackStore

func (*DB) Snapshot

func (db *DB) Snapshot(ctx context.Context, fn func(ctx context.Context) error) error

Snapshot pins one deferred read transaction to the returned ctx: every store read made with it inside fn, in sqlite and inventory, uses that transaction, so a multi-method load sees one commit.

func (*DB) UnitEventKeys

func (db *DB) UnitEventKeys(ctx context.Context, u unit.Unit, kind string) (map[string]time.Time, error)

UnitEventKeys maps the keys of u's events of kind to when each was recorded.

func (*DB) Usage

func (db *DB) Usage() usage.Store

func (*DB) WorkflowActivity

func (db *DB) WorkflowActivity(ctx context.Context, since time.Time) (map[string]WorkflowActivity, error)

WorkflowActivity is each workflow's newest done run and its step refusals since since, by workflow name.

func (*DB) Worktrees

func (db *DB) Worktrees() Worktrees

func (*DB) Write

func (db *DB) Write(ctx context.Context, fn func(tx *Tx) error) (port.Change, error)

Write runs fn in one write transaction under db.mu. After COMMIT, when fn touched anything, it notes the log (still under db.mu, so log order is commit order) and returns that Change; otherwise the zero Change. An error from fn rolls back and notes nothing. A nested Write panics.

type ExtractionHint

type ExtractionHint struct{ Mode, Context, Why string }

type ExtractionRun

type ExtractionRun struct {
	Unit    unit.Unit
	At      time.Time
	Model   string
	CostUSD *float64
	Outcome string
	Error   string
}

type ExtractionSave

type ExtractionSave struct {
	States map[unit.Unit]ExtractionState
	// Hints replace the hints of the items they name.
	Hints map[unit.Unit]map[string]ExtractionHint
}

ExtractionSave is one run's result, written in one transaction.

type ExtractionState

type ExtractionState struct {
	LastTS                                        string
	LastSeq                                       int64
	Brief, Verdict, VerdictWhy, ViewerRole, Topic string
	StartedByViewer, ClosurePosted, Watched       bool
	ClosureMarked                                 bool
	At                                            time.Time
}

ExtractionState is one unit's row. Watched is written only by SetWatched; ClosureMarked, a sent draft's unit.closed, never by Save.

Brief is the JSON of the unit's brief in use. Save writes a non-empty one as the unit's extraction brief run of the day, the UTC date of the run's started_at: a second pass that day updates that run, a pass on a later day starts a new one. An empty Brief keeps the brief in use, whichever day wrote it.

type ExtractionStore

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

ExtractionStore holds what the Slack extraction job keeps per unit: its cursor and last answer, the hints of each item, the day's spend and a log of its calls.

func (*ExtractionStore) Day

func (s *ExtractionStore) Day(ctx context.Context, day string) (calls int, costUSD float64, err error)

Day is the spend of day ("2006-01-02"): calls made and their summed cost.

func (*ExtractionStore) Hints

Hints are u's item hints by item id.

func (*ExtractionStore) MarkClosed added in v0.2.0

func (s *ExtractionStore) MarkClosed(ctx context.Context, u unit.Unit, at time.Time) error

MarkClosed records a sent draft's unit.closed on u, which no extraction pass clears.

func (*ExtractionStore) Record

func (*ExtractionStore) Save

func (*ExtractionStore) SetWatched

func (s *ExtractionStore) SetWatched(ctx context.Context, u unit.Unit, watched bool, at time.Time) error

func (*ExtractionStore) Spend

func (s *ExtractionStore) Spend(ctx context.Context, day string, costUSD float64) error

Spend counts one call of costUSD toward day.

func (*ExtractionStore) States

func (s *ExtractionStore) States(ctx context.Context, units []unit.Unit) (map[unit.Unit]ExtractionState, error)

States are the rows of units; a unit without one is missing from the map.

func (*ExtractionStore) Watched

func (s *ExtractionStore) Watched(ctx context.Context, provider unit.ProviderID) (map[unit.Unit]ExtractionState, error)

Watched are the rows of provider that SetWatched marked.

type FactsRows

type FactsRows struct {
	Team          string
	Conversations []ConversationRow
	Objects       []ObjectFacts
	Users         []UserRow
	Cursor        string // "" keeps the stored one
}

type Fetches

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

Fetches is when each workspace was last fetched. Its writes note nothing.

func (*Fetches) Last

func (f *Fetches) Last(ctx context.Context, id string) (time.Time, error)

Last is the last fetch of workspace id, zero when it was never fetched.

func (*Fetches) Mark

func (f *Fetches) Mark(ctx context.Context, id string, at time.Time) error

type FileRow

type FileRow struct {
	ID       string `json:"id"`
	Title    string `json:"title,omitempty"`
	Mimetype string `json:"mimetype,omitempty"`
}

type HeatReader

type HeatReader struct {
	DB      *DB
	WarmFor func() time.Duration // nil or zero: DefaultWarmFor
	Clock   port.Clock
}

HeatReader reads port.Heat from the items ledger: active while a unit has an open item, warm for WarmFor after its last item resolved, cold otherwise.

func (HeatReader) Heat

func (h HeatReader) Heat(ctx context.Context, units []unit.Unit) (map[unit.Unit]port.Heat, error)

type MessageQuery

type MessageQuery struct {
	Thread   string
	From, To string
	After    string
	Limit    int
	// Before keeps the messages anchored before it; Newest takes the Limit of the newest anchors, returned in ts order.
	Before string
	Newest bool
}

MessageQuery selects a conversation's messages by anchor: Thread names one thread, From and To an inclusive range (To "" open). After and Limit page.

type MessageRow

type MessageRow struct {
	Conversation, TS, ThreadTS, ParentUser string
	User, BotID, AppID, Username           string
	Subtype, Text, EditedTS                string
	Deleted                                bool
	Files                                  []FileRow
	Links, Mentions                        []string
	// Reactions nil was not read and leaves the stored set; non-nil, even
	// empty, is the full set and replaces it.
	Reactions  []ReactionRow
	Permalink  string
	Via        string
	ReceivedAt time.Time
	// Units are what a change of this message notes; not stored.
	Units []unit.Unit
}

func (MessageRow) Anchor

func (m MessageRow) Anchor() string

Anchor is the ts that places the message: its thread's parent, or its own.

type MigrateOptions added in v0.2.0

type MigrateOptions struct {
	Backups string
	Now     func() time.Time
	// Keep is how many backups taken before a migration stay; 0 keeps
	// DefaultKeep.
	Keep int
	// Backup, when set, is the backup's path, as a Plan named it.
	Backup string
	// Step, when set, hears of each migration as it commits.
	Step func(label string, took time.Duration)
	// Warn, when set, hears of what failed after the migrations committed
	// without undoing them, such as removing an old backup.
	Warn func(error)
}

MigrateOptions are where Migrate keeps backups and what it reports.

type MigrationError added in v0.2.0

type MigrationError struct {
	From, Reached uint32
	Step          string
	Backup        string
	Err           error
}

MigrationError is a migration that failed; the store stays at Reached.

func (*MigrationError) Error added in v0.2.0

func (e *MigrationError) Error() string

func (*MigrationError) Unwrap added in v0.2.0

func (e *MigrationError) Unwrap() error

type Noter

type Noter interface {
	Note(t port.Topic, units ...unit.Unit) port.Change
	NoteAll(t port.Topic) port.Change
}

Noter is what Write notes into; *change.Log satisfies it.

type ObjectFacts

type ObjectFacts struct {
	Object   ObjectRow
	Messages []MessageRow
}

type ObjectRow

type ObjectRow struct {
	Object, Conversation, TS string
	Kind                     string // SlackThread or SlackDM
	Version, LatestReply     string
	ReplyCount               int
	Watched                  bool
	Reasons                  []string
	LastActivityAt           time.Time
	NextCheckAt              time.Time // zero: due now
	SeenAt, AdmittedAt       time.Time
}

type Plan added in v0.2.0

type Plan struct {
	From, To uint32
	// Steps are the migrations it runs, as 0002_name.
	Steps []string
	// Backup is the file it copies the store to first.
	Backup string
	// Size is the store's size with its WAL, and Free the bytes free where
	// the backup goes, -1 when unknown.
	Size, Free int64
}

Plan is what Migrate does to a store.

func Migrate added in v0.2.0

func Migrate(ctx context.Context, path string, o MigrateOptions) (Plan, error)

Migrate takes the store at path to SchemaVersion: it checks the store, copies it into o.Backups, runs each pending migration in its own transaction, checks the result and prunes old backups. The caller holds the store's lock (LockStore). A store with nothing pending is left alone.

func PlanMigration added in v0.2.0

func PlanMigration(path, backups string, now time.Time) (Plan, error)

PlanMigration is what Migrate would do to the store at path, with its backup in the directory backups; it changes nothing. A store this release cannot migrate is a SchemaError.

func (Plan) Pending added in v0.2.0

func (p Plan) Pending() bool

Pending says the plan migrates anything.

func (Plan) Short added in v0.2.0

func (p Plan) Short() bool

Short says the free space cannot hold the backup with room to spare.

type ReactionRow

type ReactionRow struct {
	Name  string
	Users []string
}

type Reader

type Reader interface {
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}

Reader is what a single read statement needs. An Exec through the pool fails with SQLITE_READONLY.

type Restored added in v0.2.0

type Restored struct {
	From Status
	// Kept is the copy of the store Restore replaced; empty when there was
	// none.
	Kept string
}

Restored is what Restore did.

func Restore added in v0.2.0

func Restore(ctx context.Context, path, from, backups string, now time.Time) (Restored, error)

Restore replaces the store at path with the backup at from, after copying the store into the backups directory as a pre-restore copy. The caller holds the store's lock. A backup older than SchemaVersion stays older: Migrate takes it forward.

type Retained

type Retained map[string]int

Retained counts the rows a pass deleted or compacted, per table; the events SessionEvents and ViewEvents drop count under their own keys, and "events" counts those of ended pull requests.

func (Retained) String

func (r Retained) String() string

String lists the tables a pass changed, in name order: "events 3, sessions 1", or "nothing".

type Retention

type Retention struct {
	SessionEvents time.Duration // events of no unit or a session unit, of the kinds in SessionEventKinds
	ViewEvents    time.Duration // view_applied, view_override and view_sink_failed events
	// ClosedSessions drops the sessions closed that long ago that no open
	// turn names, and the agent sessions last seen that long ago whose turns
	// all have their usage read.
	// It also drops the workflow runs of session units that old whose
	// session row is gone.
	ClosedSessions time.Duration
	Stops          time.Duration // turn_stops
	Instructions   time.Duration // turn_instructions, then the parts no row lists
	// BriefBodies empties brief and input of the runs started that long ago
	// that no unit_briefs row or turn references.
	BriefBodies time.Duration
	ViewRows    time.Duration // view_applied rows of pull requests merged or closed that long ago
	EndedPRs    time.Duration // a pull request merged or closed that long ago, with every row of it
	// WorkflowRuns drops the done workflow runs that old. A dismissed run
	// keeps its key terminal, so it goes only with its unit's rows.
	WorkflowRuns   time.Duration
	PlanItems      time.Duration // plan items not pending, last saved that long ago
	WorkflowEvents time.Duration // the engine's events, workflow.EngineKinds
	// UnitlessLoopRows drops the turns, records, answers, intakes, events,
	// workflow runs and plan items of a github unit with no pull_requests
	// row, no overrides row and nothing newer.
	UnitlessLoopRows time.Duration
	Classifications  time.Duration // classifications and classify_days
	Fetches          time.Duration
	// SubjectMarks drops the marks of entries done, in the trash or gone,
	// and of Slack units with no extraction cursor, no item and no entry.
	SubjectMarks bool
	VacuumPages  int // PRAGMA incremental_vacuum(VacuumPages) after each pass; 0 runs none
}

Retention says how long each kind of row is kept. Zero keeps forever.

type Rounds

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

Rounds is the round state's repository.

func NewRounds

func NewRounds(db *DB) *Rounds

func (*Rounds) AgentHome

func (r *Rounds) AgentHome(ctx context.Context, ref pr.Ref) (string, error)

AgentHome is the agent home remembered for the pull request's rounds, empty when none is.

func (*Rounds) Load

func (r *Rounds) Load(ctx context.Context) (*round.Store, error)

func (*Rounds) Pause

func (r *Rounds) Pause(ctx context.Context) (round.Pause, error)

func (*Rounds) Save

func (r *Rounds) Save(ctx context.Context, st *round.Store) error

Save writes only the fields st's setters changed, adds its rounds to the day's counters and drops the days before the newest one it counts.

func (*Rounds) SetPause

func (r *Rounds) SetPause(ctx context.Context, p round.Pause) error

SetPause writes the row and a paused or resumed event in one transaction.

type SaveResult

type SaveResult struct {
	Units    []unit.Unit
	Unitless bool
	Changes  int // change rows written
}

SaveResult is what a Save changed: the units its notes named, and whether a changed message had no unit (a DM range not segmented yet).

type SchemaError added in v0.2.0

type SchemaError struct {
	Path   string
	Status Status
	// contains filtered or unexported fields
}

SchemaError is a store at a version this release cannot open as it is.

func (SchemaError) Error added in v0.2.0

func (e SchemaError) Error() string

func (SchemaError) Is added in v0.2.0

func (e SchemaError) Is(target error) bool

func (SchemaError) State added in v0.2.0

func (e SchemaError) State() State

type SegmentRow

type SegmentRow struct {
	Team, Conversation, ID, FromTS, ToTS string
	Closed                               bool
}

type SegmentSpan

type SegmentSpan struct{ ID, FromTS, ToTS string }

SegmentSpan is a range Apply writes; ID "" asks for a new segment.

type SegmentStore

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

SegmentStore is the DM segment map: a conversation's ts ranges, each under an id that is never renamed or reused. Ranges are inclusive at both ends; ToTS "" is open.

func (*SegmentStore) Apply

func (s *SegmentStore) Apply(ctx context.Context, provider unit.ProviderID, team, conv string, spans []SegmentSpan, unitOf SegmentUnit, now time.Time) ([]SegmentRow, error)

Apply replaces conv's segments from spans[0].FromTS on: a named id moves to its span, a span without an id adopts the open segment that starts at its FromTS or gets a new id, and an open segment of the replaced range that no span names is closed with its last range. Spans are ascending and disjoint; only the last may be open. A segment that starts before the replaced range and reaches into it must be named. It notes port.TopicSourceEvents on every segment whose range moved, that was minted or that was closed, and returns the rows of spans in order.

func (*SegmentStore) Covering

func (s *SegmentStore) Covering(ctx context.Context, provider unit.ProviderID, conv, ts string) ([]SegmentRow, error)

Covering returns the open segments of conv whose range holds ts.

func (*SegmentStore) Of

func (s *SegmentStore) Of(ctx context.Context, provider unit.ProviderID, conv string) ([]SegmentRow, error)

Of are conv's open segments, ascending.

func (*SegmentStore) Segment

func (s *SegmentStore) Segment(ctx context.Context, provider unit.ProviderID, conv, id string) (SegmentRow, error)

Segment returns one segment, closed or not; ErrUnknownSegment when conv has no such id.

type SegmentUnit

type SegmentUnit func(team, conv, id string) unit.Unit

SegmentUnit names the unit of a segment, for the notes of Apply.

type SlackStore

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

SlackStore is the Slack source's tables. Only admitted objects have messages; a message outside them moves its conversation's hwm only.

func (*SlackStore) AdmittedConversations

func (s *SlackStore) AdmittedConversations(ctx context.Context) ([]ConversationRow, error)

AdmittedConversations are the conversations with an admitted object, with their hwm, for the catch-up.

func (*SlackStore) Changes

func (s *SlackStore) Changes(ctx context.Context, afterSeq int64, limit int) ([]ChangeRow, error)

Changes are the change rows after afterSeq, ascending, at most limit (0: all).

func (*SlackStore) Conversations

func (s *SlackStore) Conversations(ctx context.Context, ids []string) ([]ConversationRow, error)

func (*SlackStore) Cursor

func (s *SlackStore) Cursor(ctx context.Context, name string) (string, error)

Cursor is the named cursor's value, "" when unset.

func (*SlackStore) MarkSeen

func (s *SlackStore) MarkSeen(ctx context.Context, conv, ts string) error

MarkSeen moves conv's high-water mark to ts when it is later; it stores nothing of the message.

func (*SlackStore) Messages

func (s *SlackStore) Messages(ctx context.Context, conv string, q MessageQuery) ([]MessageRow, error)

Messages are conv's messages q selects, ascending ts, with their reactions. Slack timestamps compare as text: every ts has ten digits before the dot.

func (*SlackStore) Object

func (s *SlackStore) Object(ctx context.Context, object string) (ObjectRow, bool, error)

Object is an admitted or watched object.

func (s *SlackStore) Permalink(ctx context.Context) (string, error)

Permalink is a stored message permalink, "" when none is stored: what names the workspace's web host.

func (*SlackStore) PutConversations

func (s *SlackStore) PutConversations(ctx context.Context, cs []ConversationRow) error

PutConversations stores the conversations' metadata; hwm and admitted stay.

func (*SlackStore) PutUsers

func (s *SlackStore) PutUsers(ctx context.Context, us []UserRow) error

func (*SlackStore) RowObjects

func (s *SlackStore) RowObjects(ctx context.Context, since time.Time) ([]ObjectRow, error)

RowObjects are the objects watched or active at or after since.

func (*SlackStore) Save

func (s *SlackStore) Save(ctx context.Context, f FactsRows, now time.Time) (SaveResult, error)

Save writes the facts in one transaction and notes TopicSourceEvents with the units of every message that changed: new, edited, deleted or with other reactions. A message stored again unchanged writes and notes nothing.

func (*SlackStore) Schedule

func (s *SlackStore) Schedule(ctx context.Context, object string, at time.Time) error

Schedule sets the object's next check.

func (*SlackStore) See

func (s *SlackStore) See(ctx context.Context, objects []string, next map[string]time.Time, now time.Time) error

See stamps every object a pass returned as seen at now, and moves each to its next check in next.

func (*SlackStore) SetCursor

func (s *SlackStore) SetCursor(ctx context.Context, name, value string) error

func (*SlackStore) SetWatched

func (s *SlackStore) SetWatched(ctx context.Context, object string, watched bool, reason string) error

SetWatched flips watched and adds reason to the object's reasons; an object the store lacks is created due now with no version, so the next pass reads it. Its messages stay either way.

func (*SlackStore) UserByEmail

func (s *SlackStore) UserByEmail(ctx context.Context, email string) (UserRow, bool, error)

UserByEmail matches the email without case; a live user wins over a deleted one.

func (*SlackStore) Users

func (s *SlackStore) Users(ctx context.Context, ids []string) ([]UserRow, error)

func (*SlackStore) Versions

func (s *SlackStore) Versions(ctx context.Context, objects []string) (map[string]string, error)

Versions are the stored versions of the objects the store knows.

func (*SlackStore) Watched

func (s *SlackStore) Watched(ctx context.Context, now time.Time) ([]ObjectRow, error)

Watched are the watched objects whose next check is at or before now.

type State added in v0.2.0

type State int

State is how a store's version stands against this release.

const (
	// StateCurrent is a store at SchemaVersion, or no store yet.
	StateCurrent State = iota
	// StateOlder is a store Migrate takes to SchemaVersion.
	StateOlder
	// StateReadable is a newer store whose changes this release can still use.
	StateReadable
	// StateNewer is a newer store this release must not open.
	StateNewer
	// StateUnknown is a store at no version a release writes.
	StateUnknown
)

type Status added in v0.2.0

type Status struct {
	Version uint32
	// Compatible is the lowest version a release must read to use the store.
	Compatible uint32
	// Empty is an absent store, or one with no table yet.
	Empty bool
}

Status is a store's schema version as read from its file.

func Inspect added in v0.2.0

func Inspect(path string) (Status, error)

Inspect reads the schema version of the store at path from its header; for a store newer than this release it also reads the compatible version, opening the store for reads.

func (Status) Opens added in v0.2.0

func (s Status) Opens() bool

Opens says this release opens a store in s without migrating it.

func (Status) State added in v0.2.0

func (s Status) State() State

State places s against this release.

type Store

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

Store is the repository of the turns, the sessions and what the views applied. Every save writes its events in its own transaction.

func New

func New(db *DB) *Store

func (*Store) Applied

func (s *Store) Applied(ctx context.Context, sink string) (map[view.Key]view.Applied, error)

func (*Store) BindHandle

func (s *Store) BindHandle(ctx context.Context, id, manager, handle, runtime string, at time.Time) error

BindHandle makes handle the session's open handle from at, ending the one before; binding the open handle again changes nothing.

func (*Store) BookOf

func (s *Store) BookOf(ctx context.Context, k turns.Key) (turn.Book, bool, error)

func (*Store) Books

func (s *Store) Books(ctx context.Context, units ...unit.Unit) (map[unit.Unit]turn.Book, error)

func (*Store) EndHandle

func (s *Store) EndHandle(ctx context.Context, id string, at time.Time) error

EndHandle ends the session's open handle at at: the session is dormant.

func (*Store) LastStops

func (s *Store) LastStops(ctx context.Context, sessions []string) (map[string]turn.Stop, error)

LastStops returns the newest stop of each session that logged one.

func (*Store) LogStop

func (s *Store) LogStop(ctx context.Context, st turn.Stop, evs ...port.Event) error

func (*Store) Open

func (s *Store) Open(ctx context.Context) ([]unit.Unit, error)

func (*Store) RecordEvents

func (s *Store) RecordEvents(ctx context.Context, evs ...port.Event) error

RecordEvents writes evs on their units in one transaction.

func (*Store) Save

func (s *Store) Save(ctx context.Context, b turn.Book, evs ...port.Event) (turn.Book, error)

func (*Store) SaveApplied

func (s *Store) SaveApplied(ctx context.Context, sink string, a view.Applied, evs ...port.Event) error

func (*Store) SaveFailure

func (s *Store) SaveFailure(ctx context.Context, evs ...port.Event) error

func (*Store) SaveSession

func (s *Store) SaveSession(ctx context.Context, ses turn.Session, evs ...port.Event) error

SaveSession writes the session's row; its handles move only through BindHandle and EndHandle, so a save of a session read before its handle ended never opens it again.

func (*Store) Session

func (s *Store) Session(ctx context.Context, id string) (turn.Session, bool, error)

func (*Store) SessionOf

func (s *Store) SessionOf(ctx context.Context, manager, handle string) (string, bool, error)

SessionOf is the session whose process the manager addressed by handle, the newest one when the manager gave the handle out twice.

func (*Store) SessionOfHandle

func (s *Store) SessionOfHandle(ctx context.Context, handle string) (id, manager string, ok bool, err error)

SessionOfHandle is SessionOf over every manager, for a caller that knows the handle alone; ok is false when no manager or more than one gave it out.

func (*Store) Sessions

func (s *Store) Sessions(ctx context.Context) ([]turn.Session, error)

func (*Store) UnitsOf

func (s *Store) UnitsOf(ctx context.Context, handles []string) (map[string]unit.Unit, error)

func (*Store) WithTurns

func (s *Store) WithTurns(ctx context.Context, i turn.Intent) ([]unit.Unit, error)

type Tx

type Tx struct {
	*sql.Tx
	// contains filtered or unexported fields
}

Tx is a write transaction that records what it changed.

func (*Tx) Touch

func (tx *Tx) Touch(t port.Topic, units ...unit.Unit)

Touch records that the transaction changed rows of topic t for units; a store method calls it only for rows a statement changed. No units: a unit-less change.

func (*Tx) TouchAll

func (tx *Tx) TouchAll(t port.Topic)

TouchAll records a change to rows of topic t it does not enumerate.

type UserRow

type UserRow struct {
	ID, Name, DisplayName, Email string
	IsBot, Deleted               bool
	FetchedAt                    time.Time
}

type WorkflowActivity

type WorkflowActivity struct {
	LastRun  time.Time // the newest done run; zero when none is stored
	Refusals int       // the step refusals since the time asked
}

WorkflowActivity is what one workflow did, as doctor reports it.

type Worktrees

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

Worktrees is the store of worktree custody.

func (Worktrees) Drop

func (w Worktrees) Drop(ctx context.Context, path string) error

Drop forgets the worktree at path and its units.

func (Worktrees) Keep

func (w Worktrees) Keep(ctx context.Context, c wsdomain.Custody) error

Keep records c's owner; a worktree already in custody keeps its creator and takes c's owner, workspace id and repository when set.

func (Worktrees) LinkUnit

func (w Worktrees) LinkUnit(ctx context.Context, path string, u unit.Unit) error

LinkUnit records that the worktree at path stands for u.

func (Worktrees) Worktree

func (w Worktrees) Worktree(ctx context.Context, path string) (wsdomain.Custody, bool, error)

Worktree is the custody of the worktree at path.

func (Worktrees) Worktrees

func (w Worktrees) Worktrees(ctx context.Context) ([]wsdomain.Custody, error)

Worktrees is every worktree in custody, by path.

Directories

Path Synopsis
Package sqlitetest seeds a store with raw SQL in tests.
Package sqlitetest seeds a store with raw SQL in tests.

Jump to

Keyboard shortcuts

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