api

package
v0.25.4 Latest Latest
Warning

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

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

Index

Constants

View Source
const (
	// DefaultIngestMessagesMaxBodyBytes 는 요청 본문 상한의 기본값(32 MiB)이다.
	// 정상 최대치는 300건(앱 BATCH_SIZE) × (본문 64 KiB + 필드·JSON 약 0.3 KiB)
	// ≈ 19.8 MB 이고, 그 1.6배다. 운영 실측(2026-09-25, 활성 SMS 3,395건)은
	// 본문 최대 7,454 B·p99 2,018 B 라 실제 요청은 수십~수백 KB 다.
	// INGEST_MESSAGES_MAX_BODY_BYTES 로 바꾼다.
	DefaultIngestMessagesMaxBodyBytes int64 = 32 << 20

	// IngestMessagesBudget 은 요청 하나의 처리 예산이다. 게이트웨이·클라이언트
	// 타임아웃(HTTP WriteTimeout 90초 < Cloudflare 100초 < OkHttp read 120초)보다
	// 확실히 짧아야 "서버는 아직 처리 중인데 게이트웨이는 이미 502" 인 상태
	// (2026-06-21 사고)가 생기지 않는다. 임베딩을 요청 경로에서 뺐으므로 정상
	// 300건은 몇 초 안에 끝난다. 예산이 끝나면 다음 DB 호출이 곧바로 실패하고
	// 503 으로 끝난다(풀 연결을 무기한 기다리지 않는다).
	IngestMessagesBudget = 45 * time.Second

	// IngestMessagesGateWait 는 ingest 게이트(동시 1건)를 기다리는 상한이다.
	// 앞 요청이 막 끝나는 순간의 겹침만 흡수하고, 그보다 길게 겹치면 503 이다.
	IngestMessagesGateWait = 2 * time.Second
)

ingest/messages 의 크기·시간 상한(#290, #288 1항).

View Source
const RecordingPartialMaxAge = time.Hour

RecordingPartialMaxAge 는 시작 시 청소하는 임시 파일(.partial)의 최소 나이다. 요청 하나의 최대 수명(recordingWriteDeadline, 230초)보다 넉넉히 길다.

View Source
const SearchGateWait = searchGateWait

SearchGateWait 는 REST·golden 검색이 슬롯을 기다리는 상한(searchGateWait)을 밖에 알린다. cmd/server 가 "슬롯 대기 + 검색 타임아웃" 이 HTTP WriteTimeout 안에 드는지 시작 시 점검하는 데 쓴다.

Variables

This section is empty.

Functions

func CleanupStaleRecordingPartials added in v0.25.3

func CleanupStaleRecordingPartials(dir string, olderThan time.Duration, now time.Time) (removed int, err error)

CleanupStaleRecordingPartials 는 dir 에서 writeFileAtomic 이 남긴 오래된 임시 파일("." 로 시작하고 ".partial" 로 끝나는 일반 파일, now-olderThan 보다 오래됨)을 지운다. 정상 경로는 실패하면 스스로 지우므로, 남는 것은 쓰는 도중 프로세스가 죽은 경우뿐이다. 서버 시작 시 한 번 부른다. 지운 개수와 첫 오류를 돌려준다 — 오류 문구에는 경로(번호가 든 파일 이름)가 있으므로 호출자는 로그에 문구를 남기지 말 것. dir 이 없으면 (0, nil).

func SearchConcurrency added in v0.25.2

func SearchConcurrency(maxConns int32, configured int) (k int, clamped bool)

SearchConcurrency 는 풀 크기 maxConns 와 SEARCH_MAX_CONCURRENCY 설정값 configured(0 = 자동)로 동시 검색 상한 K 를 정한다. clamped 는 설정값이 상한을 넘어 잘렸는지다(시작 로그 경고용).

  • 자동(configured <= 0): max(1, maxConns/2). 이슈 제안값. 풀의 절반을 검색에, 나머지 절반을 ingest·feedback·notes·/ask 대화 저장 같은 비검색 경로에 남긴다. pgx 기본 MaxConns 는 max(4, CPU 수)라 최소 2 가 된다.
  • 설정값: 그대로 쓰되 maxConns−1 로 자른다. 비검색 경로에 연결 1개는 반드시 남겨야 게이트의 존재 이유(ingest 보호)가 성립한다.
  • maxConns 가 1 이하면 둘 다 1 이다. 이때는 비검색 경로 몫을 보장할 수 없으므로 호출자가 경고를 남긴다.

Types

type ActionLister added in v0.23.0

type ActionLister interface {
	ListOpenActions(ctx context.Context, f store.ActionFilter) ([]store.ActionListItem, error)
}

ActionLister is the read side of the actions feature.

type ActionStateSetter added in v0.23.0

type ActionStateSetter interface {
	SetActionState(ctx context.Context, identityKey string, state model.ActionState, note string) (bool, error)
}

ActionStateSetter is the user-driven state transition. It returns found=false (with a nil error) when identityKey does not exist, so the handler can answer 404 instead of leaking a foreign-key violation as a 500.

type AskConversationStore added in v0.23.0

type AskConversationStore interface {
	Insert(ctx context.Context, session store.AskSession) (store.AskSession, error)
	ListConversationTurns(ctx context.Context, conversationID uuid.UUID) ([]store.AskSession, error)
	ListRecentConversations(ctx context.Context, limit int) ([]store.AskSession, error)
}

AskConversationStore is the subset of *store.AskSessionStore used by the multi-turn ask pipeline: persisting each turn (askHandler via saveAskTurn, ask_history.go) and serving the two read-only conversation-browsing routes below. Kept narrow — mirroring DocumentStore/FeedbackRecorder's existing interface-per-need convention in this package — so tests can inject an in-memory fake instead of a real Postgres-backed *store.AskSessionStore.

type AskRequest added in v0.23.0

type AskRequest struct {
	Question       string `json:"question"`
	ConversationID string `json:"conversation_id,omitempty"`
}

AskRequest is the JSON body accepted by POST /api/v1/ask. ConversationID is optional: omitted (or an unparsable value) starts a brand-new conversation with a server-generated id — see resolveConversation.

type AskSourceItem added in v0.23.0

type AskSourceItem struct {
	ID         string     `json:"id"`
	Title      string     `json:"title"`
	SourceType string     `json:"source_type"`
	Score      float64    `json:"score"`
	OccurredAt *time.Time `json:"occurred_at"`
}

AskSourceItem mirrors web/src/lib/types.ts:132-138 EXACTLY — field names and JSON types are a wire contract with the already-shipped frontend, not free to rename. id is mandatory: it is the only future path to (query, document_id, thumbs) feedback labels (see feedback.go's FeedbackRequest.DocumentID). The line range is a hint for humans, not an enforced contract — it drifts whenever either file is edited independently (it already has once); TestAskHandler_SSEFieldNames is what actually pins the JSON keys.

OccurredAt deliberately has NO omitempty. This field exists to let a client verify #215's recency-sort direction against real traffic — a document without a known event time still needs the key present with a JSON null so "no event time" (null) is distinguishable from "the server has not shipped this field yet" (missing key). Before this field existed, a deployment check that expected occurred_at could not tell those two cases apart and misread an absent field as a sort bug (issue #218). Every call site that fills this struct (mapAskSources, toAskSourceItems) must pass through whatever *time.Time it has, nil included, rather than skipping the field.

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 CreateNoteResponse added in v0.23.0

type CreateNoteResponse struct {
	ID     string `json:"id"`
	Status string `json:"status"`
}

CreateNoteResponse is the JSON body returned by POST /api/v1/notes.

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)
	// CountPendingTranscription returns the number of active call documents
	// (source_type='call') still awaiting a whisper transcript merge
	// (metadata.transcription="pending"). Surfaced on GET /api/v1/stats.
	CountPendingTranscription(ctx context.Context) (int, 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 EvidenceFeedbackRequest added in v0.23.0

type EvidenceFeedbackRequest struct {
	ConversationID string `json:"conversation_id"`
	Query          string `json:"query"`
	DocumentID     string `json:"document_id"`
	Thumbs         *int16 `json:"thumbs"`
	Rank           int    `json:"rank"`
	Layer          string `json:"layer"`
}

EvidenceFeedbackRequest is the JSON body of POST /api/v1/feedback/evidence.

Thumbs is a *int16 so that a missing field is distinguishable from an explicit 0: 0 is a meaningful value here ("clear my vote"), and treating an absent field as 0 would let a malformed client silently erase labels.

type EvidenceFeedbackResponse added in v0.23.0

type EvidenceFeedbackResponse struct {
	Thumbs int16 `json:"thumbs"`
}

EvidenceFeedbackResponse carries the vote state the server decided on. The client renders this rather than its own optimistic guess, so that the toggle rule lives in exactly one place.

type EvidenceVoter added in v0.23.0

type EvidenceVoter interface {
	UpsertEvidence(ctx context.Context, v store.EvidenceVote) (int64, int16, error)
}

EvidenceVoter is the subset of store.FeedbackStore used by this handler. It returns the row ID and the thumbs value the database settled on.

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 GoldenSet added in v0.23.0

type GoldenSet interface {
	GenerateQueries(ctx context.Context) (created int, totalOpen int, err error)
	NextQuery(ctx context.Context, judge string) (*store.GoldenQuery, error)
	JudgedDocumentIDs(ctx context.Context, queryID uuid.UUID, judge string) (map[uuid.UUID]struct{}, error)
	Progress(ctx context.Context) (store.GoldenProgress, error)
	UpsertJudgments(ctx context.Context, queryID uuid.UUID, judgments []store.GoldenJudgmentInput, finishQuery bool) (saved int, feedbackApplied int, err error)
	SkipQuery(ctx context.Context, queryID uuid.UUID) (bool, error)
	ExportEvalPairs(ctx context.Context, judge string) ([]store.EvalPair, error)
	FindQueryByText(ctx context.Context, text string) (uuid.UUID, bool, error)
}

GoldenSet is the subset of store.GoldenStore used by the golden-set handlers. Defined as an interface so tests can inject a stub without a real database.

type GraphReader added in v0.23.0

type GraphReader interface {
	EntryPoints(ctx context.Context, f graph.EntryFilter) ([]graph.EntryNode, error)
	Expand(ctx context.Context, f graph.ExpandFilter) ([]graph.Neighbor, error)
	Evidence(ctx context.Context, fromPgID, toPgID int64, relType string, limit int) ([]graph.EvidenceRef, error)
	SearchEntities(ctx context.Context, prefix string, limit int) ([]graph.EntityHit, error)
}

GraphReader is the read side of the projection. *graph.Reader satisfies it; declared here so handler tests can substitute a fake.

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 는 POST /api/v1/ingest/messages 가 받는 JSON 본문 형식이다(문서용 — 핸들러는 원소를 하나씩 따로 푼다, ingestMessagesEnvelope 참고).

type IngestMessagesResponse added in v0.18.0

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

IngestMessagesResponse 는 201 Created 와 함께 돌려주는 본문이다.

Sanitized 는 NUL(U+0000)을 지우고 저장한 레코드 수다(결정 D1: 실제 메시지를 버리지 않는다). PostgreSQL text·jsonb 는 NUL 을 받지 않는다. 앱은 ignoreUnknownKeys=true 라 새 필드가 호환에 문제없다.

type IngestMessagesUpserter added in v0.18.0

type IngestMessagesUpserter interface {
	UpsertTrackedWithChunks(ctx context.Context, doc *model.Document, buildChunks func(*model.Document) []store.Chunk) (contentChanged bool, err error)
}

IngestMessagesUpserter 는 ingest/messages 핸들러가 쓰는 문서 저장 인터페이스다. *store.DocumentStore 가 만족시킨다.

UpsertTrackedWithChunks 는 doc 을 upsert 하고, 내용이 바뀐 경우에만 같은 트랜잭션 안에서 청크를 buildChunks(doc) 로 교체한다(#290). 청크 단계가 실패하면 문서 행도 되돌아가므로, 503 뒤 재전송은 "내용 변경 없음" 빠른 경로로 빠져 청크 없는 문서를 남기지 않고 두 단계를 모두 다시 한다.

contentChanged=false 는 저장된 내용이 들어온 문서와 바이트 단위로 같아 청크 작업을 건너뛰었다는 뜻이다 — 재전송 배치를 싸게 유지하는 빠른 경로다 (2026-06-21, 224건 재전송 사고). store.ErrDuplicateTranscript 는 그대로 또는 %w 로 감싸 돌려줘야 한다(핸들러가 errors.Is 로 가른다). 구현은 멱등이어야 한다: 같은 문서를 다시 보내도 저장 상태가 망가지면 안 된다.

type IngestRecordingResponse added in v0.18.0

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

IngestRecordingResponse is the JSON body returned on a successful request.

Reason 은 Skipped 일 때 그 사유 코드다(recordingSkipReason*). 앱 (ApiModels.kt RecordingResponse)은 모르는 키를 무시하므로 더해도 안전하다.

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 NotesUpserter added in v0.23.0

type NotesUpserter interface {
	note.DocumentUpserter
	GetByID(ctx context.Context, id uuid.UUID) (*model.Document, error)
	ResetNoteEnrichment(ctx context.Context, documentID uuid.UUID) (bool, error)
	SoftDeleteByID(ctx context.Context, id uuid.UUID) error
	SoftDeleteInsightsByNoteID(ctx context.Context, noteID uuid.UUID) (int, error)
}

NotesUpserter is the document persistence interface required by the notes handlers. *store.DocumentStore satisfies this interface (Task 5).

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 RetrievalResult added in v0.23.0

type RetrievalResult struct {
	// Observed holds results from the 본검색 (main search): every source type
	// except model.SourceInsight.
	Observed []*model.SearchResult
	// Inferred holds results from the 인사이트검색 (insight search):
	// model.SourceInsight documents only.
	Inferred []*model.SearchResult
}

RetrievalResult keeps the 원문/정리 (Observed) and 추론 (Inferred) layers physically separate (spec §5.3) — Stage 3 renders them into different prompt sections and must never see them pre-merged.

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) WithActions added in v0.23.0

func (s *Server) WithActions(lister ActionLister, setter ActionStateSetter) *Server

WithActions wires the actions read and write dependencies. Both routes are registered only when the corresponding dependency is non-nil, so leaving the feature flag off means the routes do not exist (404) rather than existing and erroring (500).

func (*Server) WithAskConfig added in v0.23.0

func (s *Server) WithAskConfig(timeout time.Duration, topK, insightM int) *Server

WithAskConfig sets the ask-pipeline tuning knobs: the overall request timeout and the Stage 2 result-count caps (본검색/인사이트검색 limits). Optional — a Server that never calls this still has a working /api/v1/ask route using the package defaults (60s / 8 / 3). Values <= 0 are ignored (defaults are kept) so a misconfigured env var cannot zero out the pipeline.

func (*Server) WithAskRerankDefault added in v0.23.0

func (s *Server) WithAskRerankDefault(enabled bool) *Server

WithAskRerankDefault sets whether /api/v1/ask opts into cross-encoder reranking (model.SearchQuery.UseRerank) by default, mirroring cfg.RerankDefault (SEARCH_RERANK_DEFAULT). Optional — a Server that never calls this keeps /api/v1/ask opted OUT (the zero value), same as /api/v1/search and GraphQL. Kept as its own builder rather than folded into WithAskConfig because it toggles a search behaviour, not a pipeline-timing knob.

func (*Server) WithAskSessions added in v0.23.0

func (s *Server) WithAskSessions(sessions AskConversationStore) *Server

WithAskSessions enables conversation persistence for POST /api/v1/ask (turn history + query rewrite, ask_history.go) and registers GET /api/v1/ask/conversations and GET /api/v1/ask/conversations/{id}. Optional — a Server that never calls this still serves /api/v1/ask, just without cross-request memory: every request behaves like the first turn of a brand-new conversation (see resolveConversation), and the two GET routes are not registered at all (mirrors how WithNotes/WithIngestFile gate their own optional routes in router.go).

func (*Server) WithBriefing added in v0.23.0

func (s *Server) WithBriefing(cache *briefing.Cache, maxActions int) *Server

WithBriefing enables GET /api/v1/briefing. The route is registered only when an action lister and an LLM client are also present, so the feature flag being off means the route does not exist (404).

maxActions bounds how many open actions feed one briefing; <= 0 falls back to the package default.

func (*Server) WithClock added in v0.23.0

func (s *Server) WithClock(now func() time.Time) *Server

WithClock injects a deterministic clock into s AND, when the currently wired intentClassifier/queryPlanner are the concrete LLM-backed types this package constructs by default (NewServer, s.planner's fallback), into those too.

This exists for internal/askeval (issue #266): an offline evaluation run needs EVERY "current time" a fixture's as_of value touches — the Stage 3 system prompt (s.now, buildAskSystemPrompt), the deterministic window regexes (intent.LLMPlanner.deterministicPlan), and the LLM date-phrase-detection fallback (intent.LLMClassifier) — to agree on the SAME instant, or a fixture asserting "어제" resolves to one window in the prompt and a different one in retrieval would fail for a reason that has nothing to do with the code under test. Three separate unexported `now` fields exist (deep-plan #268 finding F8) precisely so each package's tests can pin its own clock independently; this builder is the one place that pins all three at once from OUTSIDE package api, which no existing same-package `srv.now = ...` test helper needed to do.

A type assertion, not a stronger requirement on the Server/Classifier/ Planner fields, is used for the classifier/planner half: both fields are interfaces (intent.Classifier, intent.Planner) precisely so a caller can substitute a test fake that has no clock at all (ask_test.go's fakeIntentClassifier). Silently skipping a fake that doesn't implement the WithNow-returning shape is the correct behavior here, not an error — see intent.LLMClassifier.WithNow / intent.LLMPlanner.WithNow for the exported setters this asserts against.

주의: WithClock은 고루틴 안전하지 않다 — s.now와 두 필드를 잠금 없이 그대로 대입한다. 서버가 이미 요청을 처리하기 시작한 뒤 호출하면 데이터 레이스가 된다. eval/test 전용 빌더이므로, 서버 시작 전(요청 처리 이전)에만 호출할 것.

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) WithEvidenceFeedback added in v0.23.0

func (s *Server) WithEvidenceFeedback(v EvidenceVoter) *Server

WithEvidenceFeedback wires the per-evidence feedback store. The POST /api/v1/feedback/evidence route is registered only when this is called, which is the rollback story: not calling it removes the endpoint entirely.

func (*Server) WithGolden added in v0.23.0

func (s *Server) WithGolden(g GoldenSet) *Server

WithGolden wires the golden-set store and registers the six /api/v1/golden/* routes. Must be called before the first call to Handler(). Search candidates are drawn from the same *search.Service every other read route uses (s.search), so no separate search dependency is needed here.

func (*Server) WithGraph added in v0.23.0

func (s *Server) WithGraph(g GraphReader) *Server

WithGraph enables the /api/v1/graph/* routes. Must be called before Handler(); leaving it out is the rollback path — the routes then do not exist at all.

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,
	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.

임베딩은 요청 경로에서 하지 않는다(결정 D2). 새 청크는 embedding IS NULL 로 저장되고, collector 의 청크 백필(scheduler.backfillChunkEmbeddings)과 문서 백필(backfillEmbeddings)이 다음 수집 주기에 채운다. FTS·bigm 검색은 즉시, 벡터 검색은 최대 수집 주기만큼 늦게 반영된다.

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

func (*Server) WithIngestMessagesMaxBody added in v0.25.3

func (s *Server) WithIngestMessagesMaxBody(maxBytes int64) *Server

WithIngestMessagesMaxBody 는 ingest/messages 요청 본문 상한 (INGEST_MESSAGES_MAX_BODY_BYTES)을 건다. 0 이하 값은 무시하고 기본값 (32 MiB)을 쓴다 — 상한을 끄는 설정은 두지 않는다. WithIngestMessages 앞뒤 어느 쪽에서 불러도 된다. 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) WithNotes added in v0.23.0

func (s *Server) WithNotes(upserter NotesUpserter, chunks IngestFileChunkWriter, embed IngestFileEmbedder) *Server

WithNotes attaches the dependencies required by POST /api/v1/notes, POST /api/v1/notes/{id}/retry-enrichment, and DELETE /api/v1/notes/{id}, and enables all three routes. Must be called before the first call to Handler().

func (*Server) WithPIINameRedaction added in v0.23.0

func (s *Server) WithPIINameRedaction(enabled bool) *Server

WithPIINameRedaction opts into forward-only protection of known contacts.

func (*Server) WithPIINumberHashing added in v0.23.0

func (s *Server) WithPIINumberHashing(enabled bool) *Server

WithPIINumberHashing sets the phone-number hashing policy (issue #164; cfg.PIINumberHashingEnabled) shared by the ingest-messages and ingest-recording handlers. Default false (zero value): the raw number is used instead of smsmap.ShortHash / a hashed label, and is additionally written into the document Metadata under "number" so it is searchable/visible. Pass true to restore the original #164 behaviour byte-for-byte. Must be called before the first call to Handler() (though the value is read per-request, not at wiring time, so ordering relative to the other With* builders does not matter).

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.

func (*Server) WithSearchConcurrency added in v0.25.2

func (s *Server) WithSearchConcurrency(k int) *Server

WithSearchConcurrency 는 동시 검색 상한을 k 로 건다. k <= 0 이면 게이트를 두지 않는다(기존 테스트 호환). 운영 배선(cmd/server)은 SearchConcurrency 로 구한 1 이상의 값을 넣는다. Handler() 전에 불러야 한다.

func (*Server) WithSearchTimeout added in v0.25.1

func (s *Server) WithSearchTimeout(timeout time.Duration) *Server

WithSearchTimeout 은 검색 요청 타임아웃(SEARCH_REQUEST_TIMEOUT_SECONDS)을 설정한다. 0 이하 값은 무시하고 기본값을 유지한다 — 0 은 "즉시 만료"라 설정 실수 하나로 모든 검색이 504 가 되기 때문이다.

Jump to

Keyboard shortcuts

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