api

package
v0.22.0 Latest Latest
Warning

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

Go to latest
Published: Jul 13, 2026 License: MIT Imports: 34 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 api wires together the HTTP router, middleware, and handlers.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CollectionStatusProvider added in v0.20.0

type CollectionStatusProvider interface {
	CollectionStatus(ctx context.Context) ([]store.CollectionSourceStatus, error)
}

CollectionStatusProvider is the subset of store.DocumentStore used by the collect-status handler. Defined as an interface for testability.

type DocumentFreshnessProvider added in v0.21.0

type DocumentFreshnessProvider interface {
	DocumentFreshness(ctx context.Context) ([]store.SourceDocumentFreshness, error)
}

DocumentFreshnessProvider is the interface required for document-level freshness checks (issue #159). Implemented by store.DocumentStore. Kept separate from CollectionStatusProvider so each can be mocked independently.

type DocumentStore

type DocumentStore interface {
	GetByID(ctx context.Context, id uuid.UUID) (*model.Document, error)
	ListBySource(ctx context.Context, src model.SourceType, limit, offset int) ([]*model.Document, error)
	ListRecent(ctx context.Context, includeSrc model.SourceType, excludeSrcs []model.SourceType, limit, offset int) ([]*model.Document, error)
	CountBySource(ctx context.Context) (map[string]int, error)
	QueryBaselineStats(ctx context.Context) (*store.BaselineStats, error)
}

DocumentStore is the subset of store.DocumentStore used by the API.

type EvalExporter

type EvalExporter interface {
	ExportJSONL(ctx context.Context, w io.Writer) (int, error)
}

EvalExporter is the subset of store.EvalStore used by the eval export handler. Defined as an interface so tests can inject a stub without a real database.

type EvalMetricsLister

type EvalMetricsLister interface {
	List(ctx context.Context, limit int) ([]store.EvalMetricsRecord, error)
}

EvalMetricsLister is the subset of store.EvalMetricsStore used by the eval metrics handler. Defined as an interface so tests can inject a stub.

type FeedbackRecorder

type FeedbackRecorder interface {
	Record(ctx context.Context, f store.Feedback) (int64, error)
}

FeedbackRecorder is the subset of store.FeedbackStore used by the feedback handler. Defined as an interface so tests can inject a stub without a real database.

type FeedbackRequest

type FeedbackRequest struct {
	Query      *string        `json:"query,omitempty"`
	DocumentID *string        `json:"document_id,omitempty"`
	ChunkID    *int64         `json:"chunk_id,omitempty"`
	Source     string         `json:"source"`
	SessionID  *string        `json:"session_id,omitempty"`
	UserID     *string        `json:"user_id,omitempty"`
	Thumbs     int16          `json:"thumbs"`
	Comment    *string        `json:"comment,omitempty"`
	Metadata   map[string]any `json:"metadata,omitempty"`
}

FeedbackRequest is the JSON body accepted by POST /api/v1/feedback.

type FeedbackResponse

type FeedbackResponse struct {
	ID int64 `json:"id"`
}

FeedbackResponse is returned on successful feedback creation.

type FreshnessChecker added in v0.20.0

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

FreshnessChecker monitors collection_log for stale sources and fires an alert to webhookURL when a source exceeds its expected interval or has too many consecutive failures (#137).

It also optionally monitors document-level freshness for push-ingested sources (e.g. SMS via Android app) that do not write collection_log rows (#159). Use WithDocumentFreshness to register sources and their alert thresholds.

Retired sources (decommissioned collectors that still have historical rows in collection_log) can be excluded from freshness checks via WithRetiredSources (#161). This prevents permanent stale-alert noise from sources that are intentionally no longer active.

It follows the same alerting pattern as the eval regression webhook in cmd/eval/main.go: POST a Slack-compatible JSON payload to the configured ALERT_WEBHOOK_URL.

func NewFreshnessChecker added in v0.20.0

func NewFreshnessChecker(store CollectionStatusProvider, webhook string, maxAge time.Duration, maxConsecFail int) *FreshnessChecker

NewFreshnessChecker creates a FreshnessChecker.

  • store: provides CollectionStatus.
  • webhook: Slack-compatible incoming webhook URL (from ALERT_WEBHOOK_URL).
  • maxAge: alert threshold for time since last successful run (default 2h when zero).
  • maxConsecFail: alert threshold for consecutive failures (default 3 when zero).

func (*FreshnessChecker) Check added in v0.20.0

func (f *FreshnessChecker) Check(ctx context.Context) error

Check queries collection_log and sends a webhook alert for any stale or repeatedly-failing source. It is intended to be called on a regular tick (e.g. from a cron job or the scheduler).

When WithDocumentFreshness has been called, it also queries the documents table and alerts when a monitored source has no recent active documents.

Errors contacting the store are returned. Webhook errors are logged but not returned so that a transient network failure does not block the scheduler.

func (*FreshnessChecker) WithDocumentFreshness added in v0.21.0

func (f *FreshnessChecker) WithDocumentFreshness(provider DocumentFreshnessProvider, maxAgeBySource map[string]time.Duration) *FreshnessChecker

WithDocumentFreshness configures document-level freshness monitoring for push-ingested sources (e.g. SMS via Android push app) that bypass the collection_log path. Each entry in maxAgeBySource maps a source type string to its alert threshold: if the most recent active document for that source was created more than the threshold ago (or no active document exists), an alert fires.

This method returns the receiver to enable method chaining:

checker := api.NewFreshnessChecker(store, webhookURL, 2*time.Hour, 3).
    WithDocumentFreshness(map[string]time.Duration{"sms": 24*time.Hour})

func (*FreshnessChecker) WithRetiredSources added in v0.21.1

func (f *FreshnessChecker) WithRetiredSources(sources ...string) *FreshnessChecker

WithRetiredSources registers source type strings that are intentionally decommissioned (i.e. the collector has been removed but historical rows remain in collection_log). Retired sources are silently skipped in the collection_log freshness check — they will never produce stale-alert noise even though their last_success timestamp is frozen in the past (#161).

Document-level freshness checks (WithDocumentFreshness) are unaffected.

This method returns the receiver for method chaining:

checker := api.NewFreshnessChecker(store, webhookURL, 2*time.Hour, 3).
    WithRetiredSources("secretary").
    WithDocumentFreshness(...)

type IngestFileChunkWriter added in v0.17.0

type IngestFileChunkWriter interface {
	ReplaceDocument(ctx context.Context, documentID uuid.UUID, chunks []store.Chunk) error
	ListByDocument(ctx context.Context, documentID uuid.UUID) ([]store.Chunk, error)
	UpdateChunkEmbeddings(ctx context.Context, embeddings []store.ChunkEmbedding) error
}

IngestFileChunkWriter is the chunk persistence interface required by the ingest-file handler. *store.ChunkStore satisfies this interface.

type IngestFileEmbedder added in v0.17.0

type IngestFileEmbedder interface {
	Enabled() bool
	EmbedBatch(ctx context.Context, texts []string) ([][]float32, error)
}

IngestFileEmbedder is the embedding interface required by the ingest-file handler. The search.EmbeddingEngine satisfies this interface.

type IngestFileResponse added in v0.17.0

type IngestFileResponse struct {
	DocumentID string `json:"document_id"`
	Accepted   bool   `json:"accepted"`
}

IngestFileResponse is the JSON body returned on a successful upload.

type IngestFileUpserter added in v0.17.0

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

IngestFileUpserter is the document persistence interface required by the ingest-file handler. *store.DocumentStore satisfies this interface.

type IngestMessagesRequest added in v0.18.0

type IngestMessagesRequest struct {
	SMS   []ingestSMSRecord  `json:"sms"`
	Calls []ingestCallRecord `json:"calls"`
}

IngestMessagesRequest is the JSON body accepted by POST /api/v1/ingest/messages.

type IngestMessagesResponse added in v0.18.0

type IngestMessagesResponse struct {
	Accepted int      `json:"accepted"`
	Skipped  int      `json:"skipped"`
	Errors   []string `json:"errors"`
}

IngestMessagesResponse is the JSON body returned on a successful request.

type IngestMessagesUpserter added in v0.18.0

type IngestMessagesUpserter interface {
	// UpsertTracked upserts the document and reports (contentChanged, error).
	// contentChanged is true when the document was newly inserted OR when an
	// existing row's content was modified. false means the stored content is
	// byte-for-byte identical to the incoming doc: chunk/embed work can be
	// skipped safely.
	// Implementations must be idempotent: re-sending the same document must not
	// corrupt stored state.
	UpsertTracked(ctx context.Context, doc *model.Document) (contentChanged bool, err error)
}

IngestMessagesUpserter is the document persistence interface required by the ingest-messages handler. *store.DocumentStore satisfies this interface via UpsertTracked, which returns change-detection metadata alongside the normal upsert semantics.

The contentChanged return value allows the handler to skip chunk replacement and re-embedding when a record arrives unchanged — the dominant cost in the 224-record duplicate-batch scenario where 216 records were identical re-sends: each was triggering a full embed API call (~300 ms) for a total of ~70 s per request. With the skip, unchanged records complete in a single DB round-trip (~1 ms).

type IngestRecordingResponse added in v0.18.0

type IngestRecordingResponse struct {
	Accepted   bool   `json:"accepted"`
	Skipped    bool   `json:"skipped"`
	DocumentID string `json:"document_id,omitempty"`
}

IngestRecordingResponse is the JSON body returned on a successful request.

type IngestRecordingUpserter added in v0.18.0

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

IngestRecordingUpserter is the document persistence interface required by the ingest-recording handler. *store.DocumentStore satisfies this interface.

type RecentItemsQuerier added in v0.19.0

type RecentItemsQuerier interface {
	ListRecentByKind(ctx context.Context, kind store.RecentKind, limit int) ([]store.RecentItem, error)
	CountByKind(ctx context.Context, kind store.RecentKind) (int, error)
}

RecentItemsQuerier is the store interface required by recentDocumentsHandler. It combines the paginated list query and the total-count query so the handler can report both the current page size and the true DB total in one response.

type ReindexRecommender

type ReindexRecommender interface {
	Check(ctx context.Context) (search.ReindexRecommendation, error)
}

ReindexRecommender is the subset of search.ReindexChecker used by the reindex check handler. Defined as an interface so tests can inject a stub.

type ReindexStateRecorder

type ReindexStateRecorder interface {
	Save(ctx context.Context, state store.ReindexState) error
}

ReindexStateRecorder is the subset of store.ReindexStateStore used by the reindex handler. Defined as an interface so tests can inject a stub.

type Server

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

Server holds the dependencies needed by all handlers.

func NewServer

func NewServer(
	docs DocumentStore,
	svc *search.Service,
	feedback FeedbackRecorder,
	eval EvalExporter,
	llmClient llm.Completer,
	filesystemPath string,
	apiKey string,
) *Server

NewServer creates a Server with the provided dependencies.

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler returns the root http.Handler for the application. It is safe to call from multiple goroutines: the underlying router is built exactly once via sync.Once and the result is reused for every subsequent call.

func (*Server) WithCollectStatus added in v0.20.0

func (s *Server) WithCollectStatus(cs CollectionStatusProvider) *Server

WithCollectStatus attaches a CollectionStatusProvider to the server so that the GET /api/v1/collect/status route is registered. Must be called before the first call to Handler().

func (*Server) WithEvalMetrics

func (s *Server) WithEvalMetrics(em EvalMetricsLister) *Server

WithEvalMetrics attaches an EvalMetricsLister to the server so that the GET /api/v1/eval/metrics route is registered. Returns s for method chaining.

NOTE: WithEvalMetrics must be called before the first call to Handler(), because the chi router is built exactly once via sync.Once.

func (*Server) WithIngestFile added in v0.17.0

func (s *Server) WithIngestFile(
	upserter IngestFileUpserter,
	chunks IngestFileChunkWriter,
	embed IngestFileEmbedder,
	maxFileBytes int64,
) *Server

WithIngestFile attaches the dependencies required by POST /api/v1/ingest/file and enables the route.

maxFileBytes is the per-upload size cap in bytes; 0 uses the package default (100 MiB). Pass cfg.IngestMaxFileBytes here.

Must be called before the first call to Handler().

func (*Server) WithIngestMessages added in v0.18.0

func (s *Server) WithIngestMessages(
	upserter IngestMessagesUpserter,
	chunks IngestFileChunkWriter,
	embed IngestFileEmbedder,
	maxBatchMessages int,
	cutover time.Time,
) *Server

WithIngestMessages attaches the dependencies required by POST /api/v1/ingest/messages and enables the route.

maxBatchMessages caps the total number of SMS + call records accepted in a single request; 0 uses the package default (5000). Pass cfg.IngestMaxBatchMessages here.

cutover is the optional floor time inherited from cfg.CollectorCutover: records whose OccurredAt is before this time are silently skipped. Zero time.Time{} disables the floor.

Must be called before the first call to Handler().

func (*Server) WithIngestRecording added in v0.18.0

func (s *Server) WithIngestRecording(
	upserter IngestRecordingUpserter,
	recordingDir string,
	maxFileBytes int64,
	cutover time.Time,
) *Server

WithIngestRecording attaches the dependencies required by POST /api/v1/ingest/recording and enables the route.

recordingDir is the directory where uploaded audio files are written; it must be non-empty for the route to be active. Corresponds to cfg.IngestRecordingDir.

maxFileBytes is the per-upload size cap (bytes); 0 uses the package default (100 MiB). Pass cfg.IngestMaxFileBytes here.

cutover is the optional floor time from cfg.CollectorCutover: recordings whose parsed timestamp is before this value are silently skipped (accepted=false, skipped=true). Zero time.Time{} disables the floor.

Must be called before the first call to Handler().

func (*Server) WithReindexAlertWebhook added in v0.20.0

func (s *Server) WithReindexAlertWebhook(url string) *Server

WithReindexAlertWebhook sets the AlertWebhookURL used by the reindex check handler to send a notification when ShouldReindex=true (#142). Must be called before the first call to Handler().

func (*Server) WithReindexCheck

func (s *Server) WithReindexCheck(rc ReindexRecommender) *Server

WithReindexCheck attaches a ReindexRecommender to the server so that the GET /api/v1/reindex/check route is registered. Returns s for method chaining.

NOTE: WithReindexCheck must be called before the first call to Handler(), because the chi router is built exactly once via sync.Once.

func (*Server) WithReindexState

func (s *Server) WithReindexState(rs ReindexStateRecorder) *Server

WithReindexState attaches a ReindexStateRecorder to the server so that the /api/v1/reindex route is registered. Returns s for method chaining.

NOTE: WithReindexState must be called before the first call to Handler(), because the chi router is built exactly once via sync.Once.

Jump to

Keyboard shortcuts

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