worker

package
v0.18.2 Latest Latest
Warning

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

Go to latest
Published: Jun 9, 2026 License: MIT Imports: 18 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 worker provides background goroutine workers for the second-brain service. Workers are long-running and must be started via [Run] with a context that controls their lifetime.

Index

Constants

This section is empty.

Variables

View Source
var ErrRefetchNotSupported = errors.New("refetch not supported for this source")

ErrRefetchNotSupported is returned by a Refetcher when it cannot handle the given failure record. The worker treats this as a permanent skip (same behaviour as the pre-Refetcher debug-log skip) so that sources without a re-fetch capability do not regress.

Functions

func ExtractEntities

func ExtractEntities(ctx context.Context, client llm.Completer, doc *model.Document) ([]model.Entity, error)

ExtractEntities calls the LLM to extract named entities from doc and returns a slice of model.Entity values (Name + Type populated; ID and CreatedAt are zero-values — they are assigned by the store on upsert).

The call is BEST-EFFORT: when the LLM is disabled, the response cannot be parsed, or any other error occurs, an empty slice and a non-nil error are returned. Callers MUST treat this as a warning and proceed without entities.

Types

type Config

type Config struct {
	// FailureStore is required: the persistence layer for extraction failures.
	FailureStore FailureStore
	// DocStore is required: used to persist successfully re-extracted content.
	DocStore DocStore
	// Extractor is required: performs the actual text extraction from a file path.
	Extractor Extractor
	// Refetcher is optional: when non-nil it is used to re-download remote
	// binaries (e.g. Discord/Slack attachments) before extraction.
	// When nil (or when the Refetcher returns ErrRefetchNotSupported), remote
	// paths are skipped with a debug log — identical to the pre-Refetcher
	// behaviour.
	Refetcher Refetcher
	// Interval controls how often the worker polls for due failures.
	// Defaults to 1 minute when zero or negative.
	Interval time.Duration
	// BatchSize limits the number of failures processed per tick.
	// Defaults to 20 when zero or negative.
	BatchSize int
}

Config holds all configuration for ExtractionRetryWorker. Zero values for Interval and BatchSize are replaced with safe defaults.

type DocStore

type DocStore interface {
	Upsert(ctx context.Context, doc *model.Document) error
}

DocStore persists documents produced by successful re-extractions.

type Embedder

type Embedder interface {
	Enabled() bool
	Embed(ctx context.Context, text string) ([]float32, error)
}

Embedder generates embedding vectors for text. It is satisfied by *search.EmbedClient.

type EntityDocumentLister

type EntityDocumentLister interface {
	// ListWithoutEntities returns up to limit active documents whose
	// entities_processed_at column is NULL. Documents are ordered by
	// collected_at ASC so backfill progresses forward in time.
	ListWithoutEntities(ctx context.Context, limit int) ([]*model.Document, error)

	// MarkEntitiesProcessed sets entities_processed_at to now() for the
	// given document so it is not re-queued by ListWithoutEntities on the
	// next tick (issue #86).
	MarkEntitiesProcessed(ctx context.Context, documentID uuid.UUID) error
}

EntityDocumentLister is the read/write side of the document store required by EntityWorker.

type EntityLinker

type EntityLinker interface {
	// UpsertAndLinkEntities persists entities and links them to the document.
	UpsertAndLinkEntities(ctx context.Context, documentID uuid.UUID, entities []model.Entity) error
}

EntityLinker is the write side of the entity store required by EntityWorker.

type EntityWorker

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

EntityWorker is a background worker that extracts named entities from documents that have not yet been processed and persists them via EntityStore.

Extraction is BEST-EFFORT: LLM failures are logged as warnings and the document is left eligible for retry on the next tick. For documents where extraction succeeds (even with zero entities) or where entity linking fails, MarkEntitiesProcessed is called so the document is not re-queued indefinitely (issue #86).

func NewEntityWorker

func NewEntityWorker(cfg EntityWorkerConfig) *EntityWorker

NewEntityWorker constructs an EntityWorker from cfg. Panics when required fields are nil (programming error).

func (*EntityWorker) Run

func (w *EntityWorker) Run(ctx context.Context)

Run starts the entity extraction loop. It blocks until ctx is cancelled. When the LLM is not configured a single diagnostic log is emitted and the loop idles without processing any documents.

type EntityWorkerConfig

type EntityWorkerConfig struct {
	// Store provides both document listing and marking-processed.
	// Typically *store.DocumentStore satisfies this interface.
	Store EntityDocumentLister
	// Entities is the entity store (write side).
	Entities EntityLinker
	// LLM is the completion client used for extraction.
	LLM llm.Completer
	// Interval controls how often the worker polls. Defaults to 10 minutes.
	Interval time.Duration
	// BatchSize is the number of documents processed per tick. Defaults to 5.
	BatchSize int
}

EntityWorkerConfig holds configuration for EntityWorker.

type ExtractionRetryWorker

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

ExtractionRetryWorker periodically reads due failures from the extraction_failures table and re-runs extraction for each entry.

On success the failure record is deleted (via FailureStore.Resolve) and the extracted content is upserted into the document store.

On failure the failure record's attempt counter is incremented (via FailureStore.Record), backing off exponentially until the row is dead-lettered at 10 attempts.

Remote-source files (Slack attachments, Discord attachments, etc.) are handled as follows:

  • When Config.Refetcher is nil or returns ErrRefetchNotSupported, the record is skipped with a debug log (same as pre-Refetcher behaviour).
  • When Config.Refetcher successfully downloads the binary, extraction runs on the temp file; success resolves the record, failure increments attempts.

func New

func New(cfg Config) *ExtractionRetryWorker

New returns a configured ExtractionRetryWorker. It panics if any required dependency (FailureStore, DocStore, Extractor) is nil.

func (*ExtractionRetryWorker) Run

Run blocks until ctx is cancelled, processing retry batches at each tick. An initial batch is processed immediately on entry so that short-lived test contexts see at least one attempt.

type Extractor

type Extractor interface {
	ExtractFromPath(ctx context.Context, path string) (string, error)
}

Extractor re-extracts plain text from a file at the given absolute path. Implementations must not panic and must respect context cancellation.

The concrete adapter ([registryExtractor]) bridges this interface to the extractor.Registry type in internal/collector/extractor.

func NewRegistryExtractor

func NewRegistryExtractor(reg *extractor.Registry, timeout time.Duration) Extractor

NewRegistryExtractor returns an Extractor backed by the given extractor.Registry. Each extraction call is bounded by timeout; when timeout is zero, extractor.ExtractTimeout seconds are used.

type FailureStore

type FailureStore interface {
	DueForRetry(ctx context.Context, limit int) ([]store.ExtractionFailure, error)
	Record(ctx context.Context, f store.ExtractionFailure) error
	Resolve(ctx context.Context, sourceType, sourceID string) error
}

FailureStore manages extraction_failures rows.

type RefetchResult

type RefetchResult struct {
	// LocalPath is the absolute path to the downloaded temp file.
	LocalPath string
	// Cleanup removes the temp file. It is always non-nil. Callers must call
	// Cleanup exactly once (typically via defer) after extraction.
	Cleanup func()
}

RefetchResult is returned by a successful Refetcher.Refetch call. The caller is responsible for invoking Cleanup after the temp file is no longer needed.

type Refetcher

type Refetcher interface {
	Refetch(ctx context.Context, f store.ExtractionFailure) (*RefetchResult, error)
}

Refetcher can re-download a remote binary given an ExtractionFailure record and return a temporary local file path for the extractor to process.

Implementations must:

  • Return ErrRefetchNotSupported when they cannot handle the given record.
  • Return a non-nil RefetchResult.Cleanup function on success.
  • Respect ctx cancellation.
  • Not panic.

type SummarizerConfig

type SummarizerConfig struct {
	// Store is required: provides document read/write access.
	Store SummaryStore
	// LLM is required: the chat completion client.
	LLM llm.Completer
	// Embedder is optional: when non-nil and Enabled, summary embeddings are generated.
	Embedder Embedder
	// Interval controls how often the worker polls for unsummarized documents.
	// Defaults to 5 minutes when zero or negative.
	Interval time.Duration
	// BatchSize is the number of documents processed per tick.
	// Defaults to 10 when zero or negative.
	BatchSize int
	// MaxTickDuration is the hard ceiling for a single tick (LLM + embed + write).
	// It must be shorter than the drain timeout in cmd/collector/main.go (10 s).
	// Defaults to defaultMaxTickDuration (8 s) when zero or negative.
	MaxTickDuration time.Duration
	// BackfillEnabled controls whether the worker scans for pre-existing
	// unsummarized documents (WHERE title_summary IS NULL).
	// When false, ListUnsummarized is not called and only documents summarized
	// via an explicit call path are processed (future use).
	// Defaults to true when not set, preserving existing behaviour.
	// Set to false when running a slow local LLM (e.g. gemma3:4b on CPU) to
	// avoid a flood of LLM calls for the pre-existing backlog (SUMMARIZER_BACKFILL_ENABLED=false).
	BackfillEnabled *bool
}

SummarizerConfig holds configuration for SummarizerWorker.

type SummarizerWorker

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

SummarizerWorker periodically fetches documents without LLM summaries, generates title_summary and bullet_summary via an LLM, optionally embeds the summary text, and persists the result via UpdateSummary.

The worker respects the context lifetime: cancel the context to stop it. An in-progress tick is bounded by maxTickDuration (8 s by default) so that it always completes before the drain timeout in cmd/collector/main.go (#65).

Concurrent instance safety relies on two mechanisms:

  1. UpdateSummary's idempotency guard (WHERE title_summary IS NULL) prevents two instances from overwriting the same summary (#64).
  2. SUMMARIZER_ENABLED=false allows operators to run a single dedicated summariser pod so that concurrent writes do not occur in the first place.

func NewSummarizerWorker

func NewSummarizerWorker(cfg SummarizerConfig) *SummarizerWorker

NewSummarizerWorker constructs a SummarizerWorker from cfg. Panics when cfg.Store or cfg.LLM is nil (programming error).

func (*SummarizerWorker) Run

func (w *SummarizerWorker) Run(ctx context.Context)

Run starts the summarizer loop. It blocks until ctx is cancelled. An initial tick runs immediately on entry so that pending documents are processed without waiting a full interval on first start.

When the LLM is not configured, a single startup log is emitted and the loop runs without processing any documents (#67).

Each tick receives a child context with a maxTickDuration deadline derived from context.WithoutCancel(ctx) so that:

  • The tick is not interrupted by the parent SIGTERM (#65 — UpdateSummary must not be cut mid-write), AND
  • The tick is still bounded to maxTickDuration so it finishes well before the drain window in cmd/collector/main.go (#65).

type SummaryStore

type SummaryStore interface {
	// ListUnsummarized returns up to limit unsummarized active documents.
	// No transaction or row locks are acquired; callers must tolerate racing
	// concurrent instances. Duplicate work is prevented by UpdateSummary's
	// idempotency guard.
	ListUnsummarized(ctx context.Context, limit int) ([]*model.Document, error)

	// UpdateSummary persists the LLM summary for a single document.
	// Idempotent: a no-op when title_summary is already set.
	UpdateSummary(ctx context.Context, id uuid.UUID, titleSummary, bulletSummary string, summaryEmbedding []float32) error
}

SummaryStore is the persistence interface required by SummarizerWorker.

ListUnsummarized returns up to limit active documents whose title_summary is NULL (plain SELECT, no row locks). Concurrent instances may read the same row, but UpdateSummary's idempotency guard (WHERE title_summary IS NULL) ensures only the first writer persists a summary (#64).

type URLRefetcher

type URLRefetcher struct {
	// SlackBotToken is the Slack OAuth token used to authenticate file
	// downloads. Optional: when empty, Slack records are skipped.
	SlackBotToken string
	// contains filtered or unexported fields
}

URLRefetcher re-downloads remote attachments whose FilePath is an HTTP(S) URL. It handles two source types:

  • "discord": Discord CDN URLs (no authentication required; URLs are pre-signed and time-limited by Discord). On expiry the download will return an HTTP error and the worker will increment the attempt counter.

  • "slack": Slack file URLs that require a Bearer token. Provide the token via SlackBotToken; when empty, Slack records fall back to ErrRefetchNotSupported (no regression).

Any failure record whose FilePath does not start with "http://" or "https://" returns ErrRefetchNotSupported (preserving the existing skip behaviour for non-URL paths).

func NewURLRefetcher

func NewURLRefetcher(slackBotToken string) *URLRefetcher

NewURLRefetcher returns a URLRefetcher. slackBotToken may be empty — Slack records will return ErrRefetchNotSupported when it is.

func (*URLRefetcher) Refetch

Refetch downloads the file at f.FilePath (which must be an HTTP/HTTPS URL) to a temporary local file and returns the path + a cleanup func.

Returns ErrRefetchNotSupported when:

  • f.FilePath is not an HTTP/HTTPS URL
  • f.SourceType is "slack" and SlackBotToken is empty
  • f.FilePath hostname is not in the allowlist for f.SourceType (SSRF guard)

Jump to

Keyboard shortcuts

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