service

package
v1.1.3 Latest Latest
Warning

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

Go to latest
Published: Mar 6, 2026 License: Apache-2.0 Imports: 26 Imported by: 0

Documentation

Overview

Package service provides application layer services that orchestrate domain operations.

Index

Constants

This section is empty.

Variables

View Source
var ErrClientClosed = errors.New("kodit: client is closed")

ErrClientClosed indicates the client has been closed.

Functions

This section is empty.

Types

type Blob

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

Blob resolves blob references (commit SHA, tag, branch) and retrieves file content.

func NewBlob

func NewBlob(
	repositories repository.RepositoryStore,
	commits repository.CommitStore,
	tags repository.TagStore,
	branches repository.BranchStore,
	gitAdapter git.Adapter,
) *Blob

NewBlob creates a new Blob service.

func (*Blob) Content

func (b *Blob) Content(ctx context.Context, repoID int64, blobName, filePath string) (BlobContent, error)

Content resolves the blob reference and returns the file content at the given path.

func (*Blob) ListFiles

func (b *Blob) ListFiles(ctx context.Context, repoID int64, pattern string) ([]FileEntry, error)

ListFiles walks the repository working copy on disk and returns files matching the pattern.

func (*Blob) ListFilesForCommit

func (b *Blob) ListFilesForCommit(ctx context.Context, repoID int64, commitSHA, pattern string) ([]FileEntry, error)

ListFilesForCommit returns files in a specific commit from the git tree, filtered by glob pattern.

func (*Blob) Resolve

func (b *Blob) Resolve(ctx context.Context, repoID int64, blobName string) (string, error)

Resolve resolves a blob name to a commit SHA. It tries commit SHA, then tag name, then branch name.

type BlobContent

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

BlobContent holds the resolved content and metadata for a file at a given blob reference.

func NewBlobContent

func NewBlobContent(content []byte, commitSHA string) BlobContent

NewBlobContent creates a BlobContent from raw bytes and a commit SHA.

func (BlobContent) CommitSHA

func (b BlobContent) CommitSHA() string

CommitSHA returns the resolved commit SHA.

func (BlobContent) Content

func (b BlobContent) Content() []byte

Content returns the raw file bytes.

type Commit

type Commit struct {
	repository.Collection[repository.Commit]
}

Commit provides read access to commits, extensible with bespoke methods later.

func NewCommit

func NewCommit(store repository.CommitStore) *Commit

NewCommit creates a new Commit service wrapping the given store.

type Enrichment

type Enrichment struct {
	repository.Collection[enrichment.Enrichment]
	// contains filtered or unexported fields
}

Enrichment provides queries for enrichments and their associations. Embeds Collection for Find/Get/Count; bespoke methods handle complex queries.

func NewEnrichment

func NewEnrichment(
	enrichmentStore enrichment.EnrichmentStore,
	associationStore enrichment.AssociationStore,
	bm25Store search.BM25Store,
	codeEmbeddingStore search.EmbeddingStore,
	textEmbeddingStore search.EmbeddingStore,
	lineRangeStore chunk.LineRangeStore,
) *Enrichment

NewEnrichment creates a new Enrichment service.

func (*Enrichment) Count

func (s *Enrichment) Count(ctx context.Context, params *EnrichmentListParams) (int64, error)

Count returns the total count of enrichments matching the given params (without pagination).

func (*Enrichment) DeleteBy

func (s *Enrichment) DeleteBy(ctx context.Context, opts ...repository.Option) error

DeleteBy removes enrichments matching the given options. Also cleans up associated search indexes (BM25, code embeddings, text embeddings). Associations cascade-delete via the GORM OnDelete:CASCADE constraint on EnrichmentAssociationModel.

func (*Enrichment) LineRanges

func (s *Enrichment) LineRanges(ctx context.Context, enrichmentIDs []int64) (map[string]chunk.LineRange, error)

LineRanges returns chunk line ranges keyed by enrichment ID string.

func (*Enrichment) List

List returns enrichments matching the given params. Commit SHA filtering is handled via enrichment.WithCommitSHA / WithCommitSHAs options, which the store resolves to association JOINs transparently.

func (*Enrichment) RelatedEnrichments

func (s *Enrichment) RelatedEnrichments(ctx context.Context, enrichmentIDs []int64) (map[string][]enrichment.Enrichment, error)

RelatedEnrichments returns enrichments that reference the given enrichment IDs through the association store (e.g., snippet_summary enrichments pointing to snippet enrichments). Returns a map of parent enrichment ID (as string) to its related enrichments.

func (*Enrichment) RepositoryIDs

func (s *Enrichment) RepositoryIDs(ctx context.Context, enrichmentIDs []int64) (map[string]int64, error)

RepositoryIDs returns repository IDs keyed by enrichment ID string. It queries associations where enrichment_id IN (ids) and entity_type = "git_repos".

func (*Enrichment) Save

Save persists an enrichment (create or update). Associations cascade-delete via GORM constraints when an enrichment is removed.

func (*Enrichment) SourceFiles

func (s *Enrichment) SourceFiles(ctx context.Context, enrichmentIDs []int64) (map[string][]int64, error)

SourceFiles returns file IDs grouped by enrichment ID string. It queries associations where enrichment_id IN (ids) and entity_type = "git_commit_files".

type EnrichmentListParams

type EnrichmentListParams struct {
	Type       *enrichment.Type
	Subtype    *enrichment.Subtype
	CommitSHA  string
	CommitSHAs []string
	Limit      int
	Offset     int
}

EnrichmentListParams configures enrichment listing.

type File

type File struct {
	repository.Collection[repository.File]
}

File provides read access to files, extensible with bespoke methods later.

func NewFile

func NewFile(store repository.FileStore) *File

NewFile creates a new File service wrapping the given store.

type FileEntry

type FileEntry struct {
	Path    string
	Size    int64
	BlobSHA string
}

FileEntry holds metadata for a file found by ListFiles.

type Grep

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

Grep searches repository file contents using git grep.

func NewGrep

func NewGrep(
	repositories repository.RepositoryStore,
	commits repository.CommitStore,
	gitAdapter git.Adapter,
) *Grep

NewGrep creates a new Grep service.

func (*Grep) Search

func (g *Grep) Search(ctx context.Context, repoID int64, pattern string, pathspec string, maxFiles int) ([]GrepResult, error)

Search runs git grep against a repository and returns results grouped by file.

type GrepResult

type GrepResult struct {
	Path      string
	Language  string
	Matches   []git.GrepMatch
	CommitSHA string
	RepoID    int64
}

GrepResult holds grouped grep matches for a single file.

type Handler

type Handler interface {
	Execute(ctx context.Context, payload map[string]any) error
}

Handler executes a specific task operation.

type LineFilter

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

LineFilter extracts specific line ranges from file content. Supports formats like "L17-L26,L45,L55-L90".

func NewLineFilter

func NewLineFilter(param string) (LineFilter, error)

NewLineFilter parses a line filter parameter. An empty param returns a pass-through filter.

func (LineFilter) Apply

func (f LineFilter) Apply(content []byte) []byte

Apply extracts matching lines from content. If no ranges are set (pass-through), returns the original content. Non-contiguous ranges are separated by an ellipsis line.

func (LineFilter) ApplyWithLineNumbers

func (f LineFilter) ApplyWithLineNumbers(content []byte) []byte

ApplyWithLineNumbers extracts matching lines and prefixes each with its original 1-based line number and a tab character. If no ranges are set (pass-through), all lines are numbered. Non-contiguous ranges are separated by an ellipsis line.

func (LineFilter) Empty

func (f LineFilter) Empty() bool

Empty returns true if this is a pass-through filter.

type MultiSearchResult

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

MultiSearchResult represents the result of a multi-modal search.

func NewMultiSearchResult

func NewMultiSearchResult(
	enrichments []enrichment.Enrichment,
	fusedScores map[string]float64,
	originalScores map[string][]float64,
) MultiSearchResult

NewMultiSearchResult creates a new MultiSearchResult.

func (MultiSearchResult) Count

func (r MultiSearchResult) Count() int

Count returns the number of enrichments in the result.

func (MultiSearchResult) Enrichments

func (r MultiSearchResult) Enrichments() []enrichment.Enrichment

Enrichments returns the matched enrichments.

func (MultiSearchResult) FusedScores

func (r MultiSearchResult) FusedScores() map[string]float64

FusedScores returns a map of enrichment ID string to fused score.

func (MultiSearchResult) OriginalScores

func (r MultiSearchResult) OriginalScores() map[string][]float64

OriginalScores returns a map of enrichment ID string to raw scores from each search method.

type PeriodicSync

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

PeriodicSync enqueues SyncRepository tasks for all repositories on a timer.

func NewPeriodicSync

func NewPeriodicSync(
	cfg config.PeriodicSyncConfig,
	repositories repository.RepositoryStore,
	queue *Queue,
	prescribedOps task.PrescribedOperations,
	logger zerolog.Logger,
) *PeriodicSync

NewPeriodicSync creates a new PeriodicSync from config and dependencies.

func (*PeriodicSync) Start

func (p *PeriodicSync) Start(ctx context.Context)

Start begins periodic sync in a background goroutine. If disabled, this is a no-op.

func (*PeriodicSync) Stop

func (p *PeriodicSync) Stop()

Stop cancels the background goroutine and waits for it to finish.

type Queue

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

Queue provides the main interface for enqueuing and managing tasks.

func NewQueue

func NewQueue(store task.TaskStore, logger zerolog.Logger) *Queue

NewQueue creates a new queue service.

func (*Queue) Count

func (s *Queue) Count(ctx context.Context) (int64, error)

Count returns the total number of pending tasks.

func (*Queue) DrainForRepository

func (s *Queue) DrainForRepository(ctx context.Context, repoID int64) (int, error)

DrainForRepository removes all pending tasks whose payload contains the given repository_id. This prevents stale enrichment/indexing tasks from blocking a repository deletion.

func (*Queue) Enqueue

func (s *Queue) Enqueue(ctx context.Context, t task.Task) error

Enqueue adds a task to the queue. If a task with the same dedup_key exists, it updates the priority instead.

func (*Queue) EnqueueOperations

func (s *Queue) EnqueueOperations(
	ctx context.Context,
	operations []task.Operation,
	basePriority task.Priority,
	payload map[string]any,
) error

EnqueueOperations queues multiple operations with decreasing priority. The first operation in the list has the highest priority, ensuring operations are processed in order.

func (*Queue) Get

func (s *Queue) Get(ctx context.Context, id int64) (task.Task, error)

Get retrieves a task by ID.

func (*Queue) List

func (s *Queue) List(ctx context.Context, params *TaskListParams) ([]task.Task, error)

List returns tasks matching the given params. Tasks are sorted by priority (highest first) then by created_at (oldest first).

type Registry

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

Registry manages task handlers for different operations.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates a new handler registry.

func (*Registry) Handler

func (r *Registry) Handler(operation task.Operation) (Handler, bool)

Handler returns the handler for an operation.

func (*Registry) HasHandler

func (r *Registry) HasHandler(operation task.Operation) bool

HasHandler reports whether a handler is registered for the operation.

func (*Registry) Operations

func (r *Registry) Operations() []task.Operation

Operations returns all registered operations.

func (*Registry) Register

func (r *Registry) Register(operation task.Operation, handler Handler)

Register registers a handler for an operation.

type Repository

type Repository struct {
	repository.Collection[repository.Repository]
	// contains filtered or unexported fields
}

Repository provides repository management and query operations. Embeds Collection for Find/Get; bespoke methods handle writes and lifecycle.

func NewRepository

func NewRepository(
	repoStore repository.RepositoryStore,
	commitStore repository.CommitStore,
	branchStore repository.BranchStore,
	tagStore repository.TagStore,
	queue *Queue,
	prescribedOps task.PrescribedOperations,
	logger zerolog.Logger,
) *Repository

NewRepository creates a new Repository service.

func (*Repository) Add

Add creates a new repository and queues it for indexing. Returns the source, whether it was newly created, and any error. If the repository already exists, it returns the existing one with created=false.

func (*Repository) BranchesForRepository

func (s *Repository) BranchesForRepository(ctx context.Context, repoID int64) ([]repository.Branch, error)

BranchesForRepository returns all branches for a repository.

func (*Repository) Delete

func (s *Repository) Delete(ctx context.Context, id int64) error

Delete removes a repository and all associated data.

func (*Repository) Rescan

func (s *Repository) Rescan(ctx context.Context, params *RescanParams) error

Rescan triggers a rescan of a specific commit.

func (*Repository) RescanAll

func (s *Repository) RescanAll(ctx context.Context) error

func (*Repository) SummaryByID

func (s *Repository) SummaryByID(ctx context.Context, id int64) (repository.RepositorySummary, error)

SummaryByID returns a detailed summary for a repository.

func (*Repository) Sync

func (s *Repository) Sync(ctx context.Context, id int64) error

Sync triggers a sync (git fetch + branch scan + commit indexing) for a repository.

func (*Repository) UpdateTrackingConfig

func (s *Repository) UpdateTrackingConfig(ctx context.Context, id int64, params *TrackingConfigParams) (repository.Source, error)

UpdateTrackingConfig updates a repository's tracking configuration.

type RepositoryAddParams

type RepositoryAddParams struct {
	URL    string
	Branch string
	Tag    string
	Commit string
}

RepositoryAddParams configures adding a new repository.

type RescanParams

type RescanParams struct {
	RepositoryID int64
	CommitSHA    string
}

RescanParams configures a commit rescan operation.

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

Search orchestrates hybrid code search across text and code vector indexes.

func NewSearch

func NewSearch(
	embedder search.Embedder,
	textVectorStore search.EmbeddingStore,
	codeVectorStore search.EmbeddingStore,
	bm25Store search.BM25Store,
	enrichmentStore enrichment.EnrichmentStore,
	closed *atomic.Bool,
	logger zerolog.Logger,
) *Search

NewSearch creates a new Search service.

func (Search) Available

func (s Search) Available() bool

Available reports whether code search is configured.

func (Search) Query

func (s Search) Query(ctx context.Context, query string, opts ...SearchOption) (SearchResult, error)

Query performs a simple hybrid code search with options.

func (Search) Search

func (s Search) Search(ctx context.Context, request search.MultiRequest) (MultiSearchResult, error)

Search performs a hybrid search combining text and code vector search results.

func (Search) SearchCode

func (s Search) SearchCode(ctx context.Context, query string, topK int) ([]enrichment.Enrichment, error)

SearchCode performs code vector search against code snippet embeddings.

func (Search) SearchCodeWithScores

func (s Search) SearchCodeWithScores(ctx context.Context, query string, topK int, filters search.Filters) ([]enrichment.Enrichment, map[string]float64, error)

SearchCodeWithScores performs code vector search and returns enrichments together with their similarity scores (keyed by enrichment ID string).

func (Search) SearchKeywordsWithScores

func (s Search) SearchKeywordsWithScores(ctx context.Context, query string, limit int, filters search.Filters) ([]enrichment.Enrichment, map[string]float64, error)

SearchKeywordsWithScores performs BM25 keyword search and returns enrichments together with their BM25 scores (keyed by enrichment ID string).

func (Search) SearchText

func (s Search) SearchText(ctx context.Context, query string, topK int) ([]enrichment.Enrichment, error)

SearchText performs text vector search against enrichment summaries.

type SearchOption

type SearchOption func(*searchConfig)

SearchOption configures a search request.

func WithDocuments

func WithDocuments(include bool) SearchOption

WithDocuments includes enrichment documents in search results.

func WithEnrichmentTypes

func WithEnrichmentTypes(types ...string) SearchOption

WithEnrichmentTypes includes specific enrichment types in results.

func WithLanguages

func WithLanguages(langs ...string) SearchOption

WithLanguages filters results by programming languages.

func WithLimit

func WithLimit(n int) SearchOption

WithLimit sets the maximum number of results.

func WithMinScore

func WithMinScore(score float64) SearchOption

WithMinScore filters results below a minimum score threshold.

func WithOffset

func WithOffset(n int) SearchOption

WithOffset sets the offset for pagination.

func WithRepositories

func WithRepositories(ids ...int64) SearchOption

WithRepositories filters results by repository IDs.

func WithSemanticWeight

func WithSemanticWeight(w float64) SearchOption

WithSemanticWeight sets the weight for semantic (vector) search (0-1).

func WithSnippets

func WithSnippets(include bool) SearchOption

WithSnippets includes code snippets in search results.

type SearchResult

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

SearchResult represents the result of a hybrid search.

func (SearchResult) Count

func (r SearchResult) Count() int

Count returns the number of enrichments in the result.

func (SearchResult) Enrichments

func (r SearchResult) Enrichments() []enrichment.Enrichment

Enrichments returns the matched enrichments.

func (SearchResult) Scores

func (r SearchResult) Scores() map[string]float64

Scores returns a map of enrichment ID string to fused search score.

type Tag

type Tag struct {
	repository.Collection[repository.Tag]
}

Tag provides read access to tags, extensible with bespoke methods later.

func NewTag

func NewTag(store repository.TagStore) *Tag

NewTag creates a new Tag service wrapping the given store.

type TaskListParams

type TaskListParams struct {
	Operation *task.Operation
	Limit     int
	Offset    int
}

TaskListParams configures task listing.

type Tracking

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

Tracking provides read-only access to task status information.

func NewTracking

func NewTracking(
	statusStore task.StatusStore,
	taskStore task.TaskStore,
) *Tracking

NewTracking creates a new Tracking service.

func (*Tracking) Statuses

func (s *Tracking) Statuses(ctx context.Context, repositoryID int64) ([]task.Status, error)

Statuses returns all task statuses for a repository.

func (*Tracking) Summary

func (s *Tracking) Summary(ctx context.Context, repositoryID int64) (tracking.RepositoryStatusSummary, error)

Summary returns an aggregated status summary for a repository.

type TrackingConfigParams

type TrackingConfigParams struct {
	Branch string
	Tag    string
	Commit string
}

TrackingConfigParams configures a tracking config update.

type Worker

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

Worker processes tasks from the queue.

func NewWorker

func NewWorker(store task.TaskStore, registry *Registry, trackerFactory WorkerTrackerFactory, logger zerolog.Logger) *Worker

NewWorker creates a new queue worker.

func (*Worker) Busy

func (w *Worker) Busy() bool

Busy reports whether the worker is currently processing a task.

func (*Worker) ProcessOne

func (w *Worker) ProcessOne(ctx context.Context) (bool, error)

ProcessOne processes a single task synchronously (for testing).

func (*Worker) Start

func (w *Worker) Start(ctx context.Context)

Start begins processing tasks from the queue. The worker runs in a goroutine and can be stopped with Stop().

func (*Worker) Stop

func (w *Worker) Stop()

Stop gracefully shuts down the worker. It waits for the current task to complete before returning.

func (*Worker) WithPollPeriod

func (w *Worker) WithPollPeriod(d time.Duration) *Worker

WithPollPeriod sets the poll period for checking new tasks.

type WorkerTracker

type WorkerTracker interface {
	Fail(ctx context.Context, message string)
	Complete(ctx context.Context)
}

WorkerTracker marks a task status as failed or complete.

type WorkerTrackerFactory

type WorkerTrackerFactory interface {
	ForOperation(operation task.Operation, payload map[string]any) WorkerTracker
}

WorkerTrackerFactory creates trackers for task status updates.

Jump to

Keyboard shortcuts

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