quicksearch4datatug

package
v0.71.0 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 31 Imported by: ? 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 quicksearch4datatug implements consent-controlled project metadata search.

Index

Constants

View Source
const ConsentVersion = "project-quick-search/1"
View Source
const GitHubBudgetPerHour = 2000

GitHubBudgetPerHour keeps headroom in the server-owned OAuth app quota (5,000/hour).

View Source
const MaxDocuments = 1000
View Source
const MaxKnownScopes = 256

A repository catalogue bounds only this repository/folder; other customers cannot exhaust its capacity. Entries remain until physical deletion is known.

View Source
const MaxTrackedCollections = 128

Bound failed cleanup resources before creating another provider collection.

View Source
const ReadConcurrency = 8

ReadConcurrency bounds independent source reads within one request.

View Source
const SearchSchemaVersion = 2

SearchSchemaVersion is the collection schema that supports provider-side matching. An absent persisted version means version 1 (export-based, no longer served).

Variables

View Source
var (
	ErrInvalid         = errors.New("invalid_request")
	ErrDenied          = errors.New("project_denied")
	ErrUnavailable     = errors.New("search_unavailable")
	ErrConflict        = errors.New("operation_in_progress")
	ErrCapacity        = errors.New("index_capacity_reached")
	ErrConsent         = errors.New("consent_required")
	ErrProvider        = errors.New("provider_unavailable")
	ErrProviderUnknown = errors.New("provider_completion_unknown")
	// ErrReindexRequired: the active generation predates provider-side search.
	// ErrRateLimited: per-instance abuse limits were exceeded before any upstream call.
	ErrRateLimited     = errors.New("quick_search_rate_limited")
	ErrReindexRequired = errors.New("quick_search_reindex_required")
	// ErrUnsupportedStorage: provider-backed search does not serve hosted projects yet.
	ErrUnsupportedStorage = errors.New("quick_search_unsupported_storage")
)

Functions

func CanonicalProjectKey

func CanonicalProjectKey(project string) string

CanonicalProjectKey lowercases only the owner and repository of a "repo@owner@folder" project key: GitHub names are case-insensitive, repository paths are not.

func EqualMetadata

func EqualMetadata(uploaded, canonical Document) bool

EqualMetadata compares the entire uploaded projection, including navigation. No provider-controlled name/tag/source label survives an existence-only check.

func Fold

func Fold(s string) string

func IsSchemaMetadataPath

func IsSchemaMetadataPath(file string) bool

IsSchemaMetadataPath selects exactly supported model descriptors and split columns wrappers, excluding DDL and unrelated model files.

func IsSearchPath

func IsSearchPath(ctx context.Context) bool

IsSearchPath reports whether the authority is being resolved for a search request, which needs repository visibility and the actor's read access but not the manifest or management rights.

func MetadataTags

func MetadataTags(tags []string) []string

func RawTags

func RawTags(value any) []string

func ReadBatch

func ReadBatch(ctx context.Context, count int, read func(int) error) []error

ReadBatch joins all workers before returning input-ordered outcomes. Readers must be concurrency safe; cancellation prevents further source calls.

func StateKey added in v0.60.7

func StateKey(key string) *record.Key

StateKey is where a scope's state lives: ext/datatug/projectQuickSearch/{key}, the same document FirestoreStore reads and writes.

func TagKey

func TagKey(tag string) string

TagKey is the filterable form of a tag: hex(sha256(Fold(tag))).

Types

type Access

type Access struct {
	Scope                   Scope
	CanManage, Eligible     bool
	Audience                string
	GitHubOwner, GitHubName string
	// OwnerID is the immutable GitHub owner ID of a public repository (0 otherwise).
	OwnerID int64
	// DefaultBranch is the repository's current default branch when known.
	DefaultBranch string
	// RegisteredSpaceID and SharedProjectID bind a private GitHub scope to the
	// registration that authorized it; both are empty for public repositories.
	RegisteredSpaceID, SharedProjectID string
}

Access is always server-derived, including the immutable canonical scope.

type Authority

type Authority interface {
	Resolve(context.Context, string, Scope) (Access, error)
	Admit(context.Context, string, Access, Document) error
}

type BatchAuthority

type BatchAuthority interface {
	AdmitBatch(context.Context, string, Access, []Document) []error
}

BatchAuthority optionally supports safe bounded source admission. Authorities without this port retain their sequential admission contract.

type CleanupAuthority

type CleanupAuthority interface {
	ResolveCleanup(context.Context, string, Scope) (Scope, error)
}

CleanupAuthority grants only deletion of retained metadata, independently of source read access.

type Coverage

type Coverage struct {
	Kind   string `json:"kind"`
	Status string `json:"status"`
	Count  int    `json:"count"`
	Error  string `json:"error,omitempty"`
}

type DALStore

type DALStore struct{ DB dal.DB }

DALStore reuses the host's server-owned database and transaction lifecycle.

func (DALStore) Read

func (s DALStore) Read(ctx context.Context, key string) (State, error)

func (DALStore) Update

func (s DALStore) Update(ctx context.Context, key string, fn func(*State) error) error

func (DALStore) UpdateMany

func (s DALStore) UpdateMany(ctx context.Context, keys []string, fn func(map[string]*State) error) error

UpdateMany reads every record before writing, preserving Firestore transaction ordering.

type Document

type Document struct {
	Kind          string    `json:"kind"`
	ID            string    `json:"id"`
	Name          string    `json:"name"`
	QualifiedName string    `json:"qualifiedName,omitempty"`
	SourceName    string    `json:"sourceName,omitempty"`
	ParentID      string    `json:"parentId,omitempty"`
	ParentName    string    `json:"parentName,omitempty"`
	Tags          []string  `json:"tags"`
	Reference     Reference `json:"reference"`
}

func InlineSchemaDocument

func InlineSchemaDocument(body []byte, d Document) (Document, error)

func NamedDocument

func NamedDocument(kind, id, title string, tags []string, ref Reference) Document

func NamedDocumentJSON

func NamedDocumentJSON(kind, id string, body []byte, ref Reference) (Document, error)

func SchemaDocument

func SchemaDocument(modelID, modelTitle, schema, table, column, parentKind string, tags []string) Document

func SchemaDocumentFromSource

func SchemaDocumentFromSource(read func(string) ([]byte, error), d Document) (Document, error)

SchemaDocumentFromSource is shared by current-source per-item admission.

func SchemaInventory

func SchemaInventory(paths []string, read func(string) ([]byte, error)) ([]Document, error)

SchemaInventory consumes an already complete, pinned project file inventory.

func SplitSchemaDocuments

func SplitSchemaDocuments(model, schema, table, kind string, body []byte) ([]Document, error)

func (Document) Validate

func (d Document) Validate() error

type FirestoreStore

type FirestoreStore struct{ Client *firestore.Client }

FirestoreStore keeps lifecycle authority server-side; it stores no indexed metadata.

func (FirestoreStore) Read

func (s FirestoreStore) Read(ctx context.Context, key string) (State, error)

func (FirestoreStore) Update

func (s FirestoreStore) Update(ctx context.Context, key string, fn func(*State) error) error

func (FirestoreStore) UpdateMany

func (s FirestoreStore) UpdateMany(ctx context.Context, keys []string, fn func(map[string]*State) error) error

type MetadataAuthority

type MetadataAuthority interface {
	ReadMetadata(context.Context, string, Access, string) (MetadataSnapshot, error)
}

MetadataAuthority reads current canonical metadata without changing index state.

type MetadataSnapshot

type MetadataSnapshot struct {
	Documents      []Document `json:"documents"`
	SourceCoverage []Coverage `json:"sourceCoverage"`
}

type PreviewRequest

type PreviewRequest struct {
	EnvironmentID string `json:"environmentId,omitempty"`
}

type Provider

type Provider interface {
	Replace(context.Context, string, []ProviderDocument) error
	// Search performs matching in the engine over a bounded collection.
	Search(context.Context, string, ProviderSearchRequest) ([]ProviderDocument, error)
	// Read exports the whole collection; maintenance and migration only, never on the search path.
	Read(context.Context, string) ([]ProviderDocument, error)
	Delete(context.Context, string) error
}

type ProviderDocument

type ProviderDocument struct {
	Document
	Partition  string `json:"partition"`
	Generation uint64 `json:"generation"`
	Key        string `json:"key"`
	// Score is the engine text-match score of a search hit; it is never stored.
	Score int64 `json:"-"`
}

type ProviderSearchRequest

type ProviderSearchRequest struct {
	Partition  string
	Query      string
	Generation uint64
	TagKeys    []string
}

ProviderSearchRequest is engine-agnostic: Query is already folded, TagKeys are TagKey values (never raw tag text) and Generation selects the published documents. The adapter owns paging and must return the complete matched set.

type PublicGitHubVerifier

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

func NewPublicGitHubVerifier

func NewPublicGitHubVerifier(client *http.Client) *PublicGitHubVerifier

func (*PublicGitHubVerifier) ReadFile

func (v *PublicGitHubVerifier) ReadFile(ctx context.Context, repo PublicRepository, branch, file string) ([]byte, error)

func (*PublicGitHubVerifier) Resolve

func (v *PublicGitHubVerifier) Resolve(ctx context.Context, owner, name, folder, branch string) (PublicRepository, error)

Resolve verifies live public visibility and that the folder holds a DataTug project manifest.

func (*PublicGitHubVerifier) ResolveRepository

func (v *PublicGitHubVerifier) ResolveRepository(ctx context.Context, owner, name, folder, branch string) (PublicRepository, error)

ResolveRepository is the one-call search-path check: live repository identity and public visibility (404 denies; 401/403/429/5xx and transport errors are unavailable). It does not read the project manifest.

type PublicRepository

type PublicRepository struct {
	RepositoryID  int64
	OwnerID       int64
	DefaultBranch string
	Owner, Name   string
	Branch        string
}

type Query

type Query struct {
	Q     string   `json:"q"`
	Kinds []string `json:"kinds,omitempty"`
	Tags  []string `json:"tags,omitempty"`
}

type Reference

type Reference struct {
	EnvironmentID string `json:"environmentId,omitempty"`
	SourceID      string `json:"sourceId,omitempty"`
	DBModelID     string `json:"dbModelId,omitempty"`
	Schema        string `json:"schema,omitempty"`
	Table         string `json:"table,omitempty"`
	Column        string `json:"column,omitempty"`
	ObjectID      string `json:"objectId,omitempty"`
	Folder        string `json:"folder,omitempty"`
}

type Results

type Results struct {
	Items     []Document `json:"items"`
	ItemCount int        `json:"itemCount"`
	Tags      []string   `json:"tags"`
}

type Scope

type Scope struct {
	Audience     string `json:"audience,omitempty"`
	Storage      string `json:"storage"`
	SpaceID      string `json:"spaceID,omitempty"`
	Project      string `json:"project"`
	Branch       string `json:"branch,omitempty"`
	RepositoryID int64  `json:"repositoryId,omitempty"`
}

func (Scope) Key

func (s Scope) Key() string

type Service

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

func NewService

func NewService(store Store, provider Provider, authority Authority) (*Service, error)

func (*Service) CurrentOperation

func (s *Service) CurrentOperation(ctx context.Context, canonical Scope) (WriterOperation, error)

func (*Service) CurrentWriter

func (s *Service) CurrentWriter(ctx context.Context, canonical Scope) (string, time.Time, error)

CurrentWriter is trusted host recovery information, never a browser API.

func (*Service) Disable

func (s *Service) Disable(ctx context.Context, actor string, scope Scope) (Status, error)

func (*Service) Index

func (s *Service) Index(ctx context.Context, actor string, scope Scope, snapshot Snapshot, enable bool) (Status, error)

func (*Service) Preview

func (s *Service) Preview(ctx context.Context, actor string, scope Scope, request PreviewRequest) (MetadataSnapshot, error)

func (*Service) RecoverWriter

func (s *Service) RecoverWriter(ctx context.Context, scope Scope, operation string, barrier WriterRecoveryBarrier) error

func (*Service) Search

func (s *Service) Search(ctx context.Context, actor string, scope Scope, q Query) (Results, error)

func (*Service) Status

func (s *Service) Status(ctx context.Context, actor string, scope Scope) (Status, error)

type Snapshot

type Snapshot struct {
	Consent        bool       `json:"consent"`
	ConsentVersion string     `json:"consentVersion"`
	Documents      []Document `json:"documents"`
	SourceCoverage []Coverage `json:"sourceCoverage"`
}

func (Snapshot) Validate

func (s Snapshot) Validate() error

type State

type State struct {
	CatalogueInitialized bool
	KnownScopes          []Scope
	CleanupEpoch         uint64
	CredentialGeneration string
	Scope                Scope
	Generation           uint64
	ConsentActor         string
	ConsentAt            time.Time
	ConsentVersion       string
	Phase                string
	Active               string
	ActiveGeneration     uint64
	Collections          []string
	CleanupOwners        map[string]string
	Lease                string
	LeaseUntil           time.Time
	LastIndexedAt        *time.Time
	Count                int
	Coverage             []Coverage
	Error                string
	// SchemaVersion is the provider collection schema of the active generation (absent = 1).
	SchemaVersion int `json:",omitempty"`
	// RegisteredSpaceID and SharedProjectID are the private registration persisted at publication.
	RegisteredSpaceID string `json:",omitempty"`
	SharedProjectID   string `json:",omitempty"`
	// OwnerID is the public repository owner ID observed at publication.
	OwnerID int64 `json:",omitempty"`
	// NameKeys lists the anonymous name-index entries written for this scope at publication.
	NameKeys []string `json:",omitempty"`
}

type Status

type Status struct {
	SupportsMetadataPreview bool       `json:"supportsMetadataPreview,omitempty"`
	State                   string     `json:"state"`
	CanManage               bool       `json:"canManage"`
	Eligible                bool       `json:"eligible"`
	Audience                string     `json:"audience"`
	Provider                string     `json:"provider"`
	ConsentVersion          string     `json:"consentVersion,omitempty"`
	LastIndexedAt           *time.Time `json:"lastIndexedAt,omitempty"`
	DocumentCount           int        `json:"documentCount"`
	Error                   string     `json:"error,omitempty"`
	SourceCoverage          []Coverage `json:"sourceCoverage"`
	Revision                uint64     `json:"revision"`
	SchemaVersion           int        `json:"schemaVersion,omitempty"`
	// CountsUnavailable explains why documentCount and coverage counts are omitted
	// ("not_eligible", "unsupported_storage"); zero is never reported as truth.
	CountsUnavailable string `json:"countsUnavailable,omitempty"`
	// Warning is "default_branch_changed" for a manager when no consented scope covers the
	// repository's current default branch.
	Warning string `json:"warning,omitempty"`
}

func (Status) MarshalJSON

func (s Status) MarshalJSON() ([]byte, error)

MarshalJSON omits every count when CountsUnavailable is set.

type Store

type Store interface {
	Update(context.Context, string, func(*State) error) error
	Read(context.Context, string) (State, error)
}

Store serializes mutations durably across processes. A missing scope is a zero State.

type Timings

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

Timings records stage durations only: no query text, scope, metadata or tokens.

func WithTimings

func WithTimings(ctx context.Context) (context.Context, *Timings)

WithTimings returns a context whose Service calls record stage durations into the recorder.

func (*Timings) Add

func (t *Timings) Add(stage string, d time.Duration)

Add accumulates a stage duration.

func (*Timings) Stage

func (t *Timings) Stage(stage string) time.Duration

Stage returns the accumulated duration of a stage (zero when it never ran).

type TransactionalStore

type TransactionalStore interface {
	UpdateMany(context.Context, []string, func(map[string]*State) error) error
}

TransactionalStore atomically validates the repository catalogue and claims lifecycle state.

type Typesense

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

func NewTypesense

func NewTypesense(o TypesenseOptions) (*Typesense, error)

func (*Typesense) CredentialGeneration

func (t *Typesense) CredentialGeneration() string

func (*Typesense) Delete

func (t *Typesense) Delete(ctx context.Context, collection string) error

func (*Typesense) Read

func (t *Typesense) Read(ctx context.Context, collection string) ([]ProviderDocument, error)

Read exports the bounded collection. Maintenance and migration only: Search and Status never call it.

func (*Typesense) Replace

func (t *Typesense) Replace(ctx context.Context, collection string, docs []ProviderDocument) error

func (*Typesense) Search

func (t *Typesense) Search(ctx context.Context, collection string, req ProviderSearchRequest) ([]ProviderDocument, error)

Search pages sequentially so a same-name group is never split, failing closed when the total exceeds the document cap or changes between pages.

type TypesenseOptions

type TypesenseOptions struct {
	Origin, APIKey, CollectionPrefix string
	SearchAPIKey                     string
	CredentialGeneration             string
	HTTPClient                       *http.Client
}

TypesenseOptions: APIKey is the scoped lifecycle credential (create, import, export, delete). SearchAPIKey is a separate search-only credential; without it Search is unavailable while lifecycle operations keep working.

type WriterOperation

type WriterOperation struct {
	ID                   string
	CredentialGeneration string
	LeaseUntil           time.Time
	Scope                Scope
}

WriterOperation is trusted maintenance information, never exposed by routes.

type WriterRecoveryBarrier

type WriterRecoveryBarrier interface {
	FenceWriter(context.Context, Scope, string) error
}

WriterRecoveryBarrier must prove the old process/operation cannot issue any further provider requests (for example after an authoritative instance kill). Lease expiry or a caller assertion alone is not a recovery barrier.

Jump to

Keyboard shortcuts

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