Documentation
¶
Overview ¶
Package api wires together the HTTP router, middleware, and handlers.
Index ¶
- Constants
- func SearchConcurrency(maxConns int32, configured int) (k int, clamped bool)
- type ActionLister
- type ActionStateSetter
- type AskConversationStore
- type AskRequest
- type AskSourceItem
- type CollectionStatusProvider
- type CreateNoteResponse
- type DocumentFreshnessProvider
- type DocumentStore
- type EvalExporter
- type EvalMetricsLister
- type EvidenceFeedbackRequest
- type EvidenceFeedbackResponse
- type EvidenceVoter
- type FeedbackRecorder
- type FeedbackRequest
- type FeedbackResponse
- type FreshnessChecker
- type GoldenSet
- type GraphReader
- type IngestFileChunkWriter
- type IngestFileEmbedder
- type IngestFileResponse
- type IngestFileUpserter
- type IngestMessagesRequest
- type IngestMessagesResponse
- type IngestMessagesUpserter
- type IngestRecordingResponse
- type IngestRecordingUpserter
- type NotesUpserter
- type RecentItemsQuerier
- type ReindexRecommender
- type ReindexStateRecorder
- type RetrievalResult
- type Server
- func (s *Server) Handler() http.Handler
- func (s *Server) WithActions(lister ActionLister, setter ActionStateSetter) *Server
- func (s *Server) WithAskConfig(timeout time.Duration, topK, insightM int) *Server
- func (s *Server) WithAskRerankDefault(enabled bool) *Server
- func (s *Server) WithAskSessions(sessions AskConversationStore) *Server
- func (s *Server) WithBriefing(cache *briefing.Cache, maxActions int) *Server
- func (s *Server) WithClock(now func() time.Time) *Server
- func (s *Server) WithCollectStatus(cs CollectionStatusProvider) *Server
- func (s *Server) WithEvalMetrics(em EvalMetricsLister) *Server
- func (s *Server) WithEvidenceFeedback(v EvidenceVoter) *Server
- func (s *Server) WithGolden(g GoldenSet) *Server
- func (s *Server) WithGraph(g GraphReader) *Server
- func (s *Server) WithIngestFile(upserter IngestFileUpserter, chunks IngestFileChunkWriter, ...) *Server
- func (s *Server) WithIngestMessages(upserter IngestMessagesUpserter, chunks IngestFileChunkWriter, ...) *Server
- func (s *Server) WithIngestRecording(upserter IngestRecordingUpserter, recordingDir string, maxFileBytes int64, ...) *Server
- func (s *Server) WithNotes(upserter NotesUpserter, chunks IngestFileChunkWriter, embed IngestFileEmbedder) *Server
- func (s *Server) WithPIINameRedaction(enabled bool) *Server
- func (s *Server) WithPIINumberHashing(enabled bool) *Server
- func (s *Server) WithReindexAlertWebhook(url string) *Server
- func (s *Server) WithReindexCheck(rc ReindexRecommender) *Server
- func (s *Server) WithReindexState(rs ReindexStateRecorder) *Server
- func (s *Server) WithSearchConcurrency(k int) *Server
- func (s *Server) WithSearchTimeout(timeout time.Duration) *Server
Constants ¶
const SearchGateWait = searchGateWait
SearchGateWait 는 REST·golden 검색이 슬롯을 기다리는 상한(searchGateWait)을 밖에 알린다. cmd/server 가 "슬롯 대기 + 검색 타임아웃" 이 HTTP WriteTimeout 안에 드는지 시작 시 점검하는 데 쓴다.
Variables ¶
This section is empty.
Functions ¶
func SearchConcurrency ¶ added in v0.25.2
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
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 ¶
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 ¶
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
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
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 ¶
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
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
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
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
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
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, 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) 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
WithPIINameRedaction opts into forward-only protection of known contacts.
func (*Server) WithPIINumberHashing ¶ added in v0.23.0
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
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
WithSearchConcurrency 는 동시 검색 상한을 k 로 건다. k <= 0 이면 게이트를 두지 않는다(기존 테스트 호환). 운영 배선(cmd/server)은 SearchConcurrency 로 구한 1 이상의 값을 넣는다. Handler() 전에 불러야 한다.
Source Files
¶
- actions.go
- ask.go
- ask_citation.go
- ask_context.go
- ask_conversations.go
- ask_eval_hooks.go
- ask_evidence.go
- ask_history.go
- ask_retrieval.go
- ask_rewrite.go
- briefing.go
- collect_status.go
- document.go
- documents_recent.go
- eval.go
- eval_metrics.go
- feedback.go
- feedback_evidence.go
- feedback_input.go
- golden.go
- golden_generation.go
- graph.go
- graphql.go
- graphql_limits.go
- ingest_file.go
- ingest_messages.go
- ingest_recording.go
- middleware.go
- notes.go
- reindex.go
- reindex_check.go
- router.go
- search.go
- search_gate.go
- search_input.go
- source.go
- stats.go