api

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Jun 17, 2026 License: MIT Imports: 44 Imported by: 0

Documentation

Overview

Package api serves graphdb's graph store over HTTP — the REST surface plus the GraphQL endpoint.

The entry type is Server, constructed with NewServer or NewServerWithDataDir. It wires per-tenant isolation middleware, JWT and API-key authentication, and handlers for node/edge CRUD, traversal and graph algorithms, vector and full-text/hybrid search, GraphQL, OpenAI-compatible embeddings, graph-augmented retrieval, and compliance audit logging. Per-tenant GraphQL schemas are built lazily and cached (concurrent cold starts deduped via singleflight).

The full HTTP contract is described by docs/internals/openapi.yaml. Auth is fail-closed: JWT_SECRET must be set, and an admin user is bootstrapped on first start (see ADMIN_PASSWORD).

Index

Constants

View Source
const (
	// Traversal limits
	MinTraversalDepth     = 0
	MaxTraversalDepth     = 100
	DefaultTraversalDepth = 10

	// PageRank limits
	MinPageRankIterations     = 1
	MaxPageRankIterations     = 1000
	DefaultPageRankIterations = 20
	MinDampingFactor          = 0.0
	MaxDampingFactor          = 1.0
	DefaultDampingFactor      = 0.85

	// Cycle detection limits
	MinCycleLength = 1
	MaxCycleLength = 100

	// Algorithm timeout
	DefaultAlgorithmTimeout = 60 * time.Second
	MaxAlgorithmTimeout     = 5 * time.Minute
)

Algorithm parameter limits to prevent resource exhaustion

View Source
const CursorHeader = "X-Next-Cursor"

CursorHeader is the response header name for the next-page cursor. Absent from the response when the current page is the last one.

View Source
const DefaultPageLimit = 100

DefaultPageLimit is the page size when ?limit= is absent.

View Source
const (

	// Response header signalling hybrid degradation. Value matches Degraded in body.
	HeaderHybridDegraded = "X-GraphDB-Hybrid-Degraded"
)
View Source
const (

	// HeaderRetrieveDegraded matches the hybrid-search degradation
	// header pattern (X-GraphDB-Hybrid-Degraded) so callers can
	// inspect the response without parsing the body.
	HeaderRetrieveDegraded = "X-GraphDB-Retrieve-Degraded"
)
View Source
const MaxPageLimit = 1000

MaxPageLimit caps any caller-supplied ?limit= value to prevent memory pressure from "give me everything in one request" DOS shapes. 1000 matches the GraphQL MaxLimit default in pkg/graphql.

View Source
const (
	// TenantIDHeader is the header admins can use to override tenant context
	TenantIDHeader = "X-Tenant-ID"
)

Variables

View Source
var (
	DefaultCORSConfig      = middleware.DefaultCORSConfig
	DefaultRateLimitConfig = middleware.DefaultRateLimitConfig
	NewRateLimiter         = middleware.NewRateLimiter
	GetRequestID           = middleware.GetRequestID
	GetClientIP            = middleware.GetClientIP
	IsTrustedProxy         = middleware.IsTrustedProxy
)

Re-export functions from middleware package

View Source
var MaxTraversalNodes = 10000

MaxTraversalNodes caps how many nodes a single /traverse may return. Depth and the algorithm timeout alone don't bound output: a dense tenant graph materializes every reachable node into one slice + one JSON array, pinning memory for the request window (security audit H-8). On hitting the cap the traversal stops and the response carries X-Truncated: true. It is a var, not a const, only so tests can lower it to exercise the cap without building a 10k-node fixture.

Functions

This section is empty.

Types

type APIKeyResponse

type APIKeyResponse struct {
	ID          string     `json:"id"`
	Name        string     `json:"name"`
	Prefix      string     `json:"prefix"`
	Permissions []string   `json:"permissions"`
	Created     time.Time  `json:"created"`
	Expires     *time.Time `json:"expires,omitempty"`
	LastUsed    *time.Time `json:"last_used,omitempty"`
	Revoked     bool       `json:"revoked"`
}

APIKeyResponse represents an API key in list responses (without the actual key)

type AlgorithmRequest

type AlgorithmRequest struct {
	Algorithm  string         `json:"algorithm"` // "pagerank", "betweenness", "louvain"
	Parameters map[string]any `json:"parameters,omitempty"`
}

AlgorithmRequest represents a graph algorithm execution request

type AlgorithmResponse

type AlgorithmResponse struct {
	Algorithm string         `json:"algorithm"`
	Results   map[string]any `json:"results"`
	Time      string         `json:"time"`
}

AlgorithmResponse represents algorithm execution results

type BatchEdgeRequest

type BatchEdgeRequest struct {
	Edges []EdgeRequest `json:"edges"`
}

BatchEdgeRequest represents a batch edge creation request

type BatchEdgeResponse

type BatchEdgeResponse struct {
	Edges   []*EdgeResponse `json:"edges"`
	Created int             `json:"created"`
	Time    string          `json:"time"`
}

BatchEdgeResponse represents batch edge creation response

type BatchNodeRequest

type BatchNodeRequest struct {
	Nodes []NodeRequest `json:"nodes"`
}

BatchNodeRequest represents a batch node creation request

type BatchNodeResponse

type BatchNodeResponse struct {
	Nodes   []*NodeResponse `json:"nodes"`
	Created int             `json:"created"`
	Time    string          `json:"time"`
}

BatchNodeResponse represents batch node creation response

type CORSConfig

type CORSConfig = middleware.CORSConfig

Re-export types from middleware package for backward compatibility

type CreateAPIKeyRequest

type CreateAPIKeyRequest struct {
	Name        string   `json:"name"`
	Permissions []string `json:"permissions,omitempty"`
	ExpiresIn   int64    `json:"expires_in,omitempty"`  // seconds, 0 = never expires
	Environment string   `json:"environment,omitempty"` // "live" or "test" - defaults to server's GRAPHDB_ENV
}

CreateAPIKeyRequest represents a request to create an API key

type CreateAPIKeyResponse

type CreateAPIKeyResponse struct {
	Key     string     `json:"key"` // Only returned once!
	ID      string     `json:"id"`
	Name    string     `json:"name"`
	Prefix  string     `json:"prefix"`
	Expires *time.Time `json:"expires,omitempty"`
	Created time.Time  `json:"created"`
}

CreateAPIKeyResponse represents the response when creating an API key

type EdgeRequest

type EdgeRequest struct {
	FromNodeID uint64         `json:"from_node_id"`
	ToNodeID   uint64         `json:"to_node_id"`
	Type       string         `json:"type"`
	Properties map[string]any `json:"properties,omitempty"`
	Weight     float64        `json:"weight"`
}

EdgeRequest represents an edge creation request

type EdgeResponse

type EdgeResponse struct {
	ID         uint64         `json:"id"`
	FromNodeID uint64         `json:"from_node_id"`
	ToNodeID   uint64         `json:"to_node_id"`
	Type       string         `json:"type"`
	Properties map[string]any `json:"properties"`
	Weight     float64        `json:"weight"`
}

EdgeResponse represents an edge in API responses

type EdgeUpdateRequest

type EdgeUpdateRequest struct {
	Properties map[string]any `json:"properties,omitempty"`
	Weight     *float64       `json:"weight,omitempty"`
}

EdgeUpdateRequest is the body for PUT /edges/{id}. Weight is a *pointer* so an omitted weight means "leave it unchanged" — a bare float64 would decode a missing weight as 0.0 and silently zero the edge's weight on a properties-only update. Maps to storage.UpdateEdgeForTenant(weight *float64).

type EmbeddingData

type EmbeddingData struct {
	Object    string    `json:"object"` // always "embedding"
	Embedding []float32 `json:"embedding"`
	Index     int       `json:"index"` // matches the position in the request's input array
}

EmbeddingData is one embedding result.

type EmbeddingsRequest

type EmbeddingsRequest struct {
	Input          embeddingsInput `json:"input"`
	Model          string          `json:"model,omitempty"`
	EncodingFormat string          `json:"encoding_format,omitempty"`
	Dimensions     int             `json:"dimensions,omitempty"`
	User           string          `json:"user,omitempty"` // ignored; tenant from context
}

EmbeddingsRequest mirrors the OpenAI /v1/embeddings request shape so that clients which already speak OpenAI (LangChain, Vercel AI SDK, llamaindex, etc.) can drop in by setting api_base. The OpenAI fields not listed below (e.g. `user`) are accepted and silently ignored.

Input accepts either a single string OR an array of strings — both shapes are valid per the OpenAI spec, decoded by the embeddingsInput type.

The Model field is recorded but not validated. The only available backend is the per-tenant LSA index; pass any string. The model returned in the response is always lsaModelName regardless of the request's Model.

EncodingFormat must be "float" or empty (base64 is not supported in v1).

Dimensions, if non-zero, must match the LSA index's actual dimension or the request is rejected. This catches client misconfigurations that would otherwise produce silently-wrong-shape vectors.

type EmbeddingsResponse

type EmbeddingsResponse struct {
	Object string          `json:"object"` // always "list"
	Data   []EmbeddingData `json:"data"`
	Model  string          `json:"model"`
	Usage  EmbeddingsUsage `json:"usage"`
}

EmbeddingsResponse mirrors the OpenAI /v1/embeddings response shape.

type EmbeddingsUsage

type EmbeddingsUsage struct {
	PromptTokens int `json:"prompt_tokens"`
	TotalTokens  int `json:"total_tokens"`
}

EmbeddingsUsage approximates OpenAI's token-usage accounting. Since LSA doesn't have an OpenAI-equivalent tokenizer, prompt_tokens is the count of LSA tokens after stemming/stop-word removal; both fields are equal because there are no completion tokens for an embeddings request.

type ErrorResponse

type ErrorResponse struct {
	Error   string `json:"error"`
	Message string `json:"message"`
	Code    int    `json:"code"`
}

ErrorResponse represents an error response

type HealthResponse

type HealthResponse struct {
	Status    string         `json:"status"`
	Timestamp time.Time      `json:"timestamp"`
	Version   string         `json:"version"`
	Edition   string         `json:"edition"`
	Features  []string       `json:"features"`
	Uptime    string         `json:"uptime"`
	Checks    map[string]any `json:"checks,omitempty"`
}

HealthResponse represents health check response

type HybridSearchRequest

type HybridSearchRequest struct {
	Query          string   `json:"query"`
	Limit          int      `json:"limit,omitempty"`
	Offset         int      `json:"offset,omitempty"`
	Labels         []string `json:"labels,omitempty"`
	Alpha          *float64 `json:"alpha,omitempty"` // pointer so {"alpha":0} is distinguishable from unset
	IncludeContent bool     `json:"include_content,omitempty"`
	IncludeNodes   bool     `json:"include_nodes,omitempty"`
}

HybridSearchRequest is the JSON body for POST /hybrid-search.

type HybridSearchResponse

type HybridSearchResponse struct {
	Results  []HybridSearchResultItem `json:"results"`
	Count    int                      `json:"count"`
	TookMs   int64                    `json:"took_ms"`
	Degraded string                   `json:"degraded,omitempty"`
}

HybridSearchResponse is the JSON response for POST /hybrid-search. Degraded is non-empty when the hybrid path fell back to a single stage; values: "no-lsa-index", "query-out-of-vocabulary", "no-fts-match".

type HybridSearchResultItem

type HybridSearchResultItem struct {
	NodeID  uint64        `json:"node_id"`
	Score   float64       `json:"score"`
	FTSRank int           `json:"fts_rank"`
	LSARank int           `json:"lsa_rank"`
	Snippet string        `json:"snippet,omitempty"`
	Node    *NodeResponse `json:"node,omitempty"`
}

HybridSearchResultItem is one ranked hybrid result. FTSRank and LSARank expose the per-stage rank so callers can see why a doc scored where it did; -1 indicates the stage did not return this doc.

type LSAIndexRequest

type LSAIndexRequest struct {
	Labels         []string `json:"labels"`
	TitleProperty  string   `json:"title_property,omitempty"`
	BodyProperties []string `json:"body_properties"`

	// Optional tuning — omit to use DefaultLSAConfig values.
	Dims       int   `json:"dims,omitempty"`
	MinDocFreq int   `json:"min_doc_freq,omitempty"`
	MaxVocab   int   `json:"max_vocab,omitempty"`
	TitleBoost int   `json:"title_boost,omitempty"`
	Seed       int64 `json:"seed,omitempty"`
}

LSAIndexRequest configures an LSA build for the caller's tenant.

type LSAIndexResponse

type LSAIndexResponse struct {
	IndexedDocs int   `json:"indexed_docs"`
	Dimensions  int   `json:"dimensions"`
	TookMs      int64 `json:"took_ms"`
}

LSAIndexResponse reports build stats.

type MetricsResponse

type MetricsResponse struct {
	// Database stats
	NodeCount    uint64  `json:"node_count"`
	EdgeCount    uint64  `json:"edge_count"`
	TotalQueries uint64  `json:"total_queries"`
	AvgQueryTime float64 `json:"avg_query_time_ms"`

	// System stats
	MemoryUsedMB  uint64 `json:"memory_used_mb"`
	MemoryTotalMB uint64 `json:"memory_total_mb"`
	NumGoroutines int    `json:"num_goroutines"`
	NumCPU        int    `json:"num_cpu"`

	// Server stats
	Uptime        string `json:"uptime"`
	UptimeSeconds int64  `json:"uptime_seconds"`
}

MetricsResponse represents database metrics

type NodeRequest

type NodeRequest struct {
	Labels     []string       `json:"labels"`
	Properties map[string]any `json:"properties"`
}

NodeRequest represents a node creation/update request

type NodeResponse

type NodeResponse struct {
	ID         uint64         `json:"id"`
	Labels     []string       `json:"labels"`
	Properties map[string]any `json:"properties"`
}

NodeResponse represents a node in API responses

type QueryRequest

type QueryRequest struct {
	Query          string         `json:"query"`
	Parameters     map[string]any `json:"parameters,omitempty"`
	TimeoutSeconds *int           `json:"timeout_seconds,omitempty"` // Optional per-query timeout (1-300 seconds)
}

QueryRequest represents a query execution request

type QueryResponse

type QueryResponse struct {
	Columns []string         `json:"columns"`
	Rows    []map[string]any `json:"rows"`
	Count   int              `json:"count"`
	Time    string           `json:"time"`
}

QueryResponse represents a query execution response

type RateLimitConfig

type RateLimitConfig = middleware.RateLimitConfig

Re-export types from middleware package for backward compatibility

type RateLimiter

type RateLimiter = middleware.RateLimiter

Re-export types from middleware package for backward compatibility

type RetrieveDocument

type RetrieveDocument struct {
	PageContent string                   `json:"page_content"`
	Metadata    RetrieveDocumentMetadata `json:"metadata"`
}

RetrieveDocument is one ranked result, shaped for LangChain. PageContent is the chunk text; Metadata carries the graph signal (NodeID, Score, Source.Path).

type RetrieveDocumentMetadata

type RetrieveDocumentMetadata struct {
	NodeID uint64         `json:"node_id"`
	Score  float64        `json:"score"`
	Source RetrieveSource `json:"source"`
	Node   *NodeResponse  `json:"node,omitempty"` // populated when IncludeNode=true
}

RetrieveDocumentMetadata is the metadata block on each document. LangChain treats metadata as opaque; we use it to surface the graph-specific signals.

type RetrieveRequest

type RetrieveRequest struct {
	Query       string   `json:"query"`
	K           int      `json:"k,omitempty"`
	MaxTokens   int      `json:"max_tokens,omitempty"`
	MaxHops     int      `json:"max_hops,omitempty"`
	Alpha       *float64 `json:"alpha,omitempty"`
	Beta        *float64 `json:"beta,omitempty"`
	Tau         *float64 `json:"tau,omitempty"`
	Labels      []string `json:"labels,omitempty"`
	IncludeNode bool     `json:"include_node,omitempty"`
}

RetrieveRequest is the JSON body for POST /v1/retrieve. Shape matches LangChain's BaseRetriever pattern (per F2 spike #28 §2 Q1):

{ "query": "...", "k": 10, "max_tokens": 4096, "max_hops": 2,
  "alpha": 0.7, "beta": 0.3, "tau": 2.0,
  "labels": ["Doc"], "include_node": false }

Pointer-typed coefficients (Alpha, Beta, Tau) distinguish "set to zero" from "unset" — caller can pin alpha=0.0 (LSA-only seeds) without having that read as "use the default."

type RetrieveResponse

type RetrieveResponse struct {
	Documents []RetrieveDocument `json:"documents"`
	Degraded  string             `json:"degraded,omitempty"`
	TookMs    int64              `json:"took_ms"`
}

RetrieveResponse is the JSON response for POST /v1/retrieve. Degraded forwards the hybrid-search degraded flag ("no-lsa-index", "query-out-of-vocabulary").

type RetrieveSource

type RetrieveSource struct {
	NodeID uint64   `json:"node_id"`
	Label  string   `json:"label,omitempty"`
	Path   []uint64 `json:"path"` // [seed, ..., node_id]; length 1 for seeds
}

RetrieveSource captures the citation: which seed contributed the chunk, the node's primary label, and the BFS path. The path is the load-bearing graph signal — without it, /v1/retrieve is a fancy vector retriever (F2 spike §2 Q6).

type SearchIndexRequest

type SearchIndexRequest struct {
	Labels     []string `json:"labels"`
	Properties []string `json:"properties"`
}

SearchIndexRequest configures the FTS index build for the caller's tenant.

type SearchIndexResponse

type SearchIndexResponse struct {
	IndexedNodes int   `json:"indexed_nodes"`
	TookMs       int64 `json:"took_ms"`
}

SearchIndexResponse reports build stats.

type SearchRequest

type SearchRequest struct {
	Query          string   `json:"query"`
	Limit          int      `json:"limit,omitempty"`
	Offset         int      `json:"offset,omitempty"`
	Labels         []string `json:"labels,omitempty"`          // optional post-filter
	IncludeContent bool     `json:"include_content,omitempty"` // include a snippet of matched content
	IncludeNodes   bool     `json:"include_nodes,omitempty"`   // include full node data
}

SearchRequest is the JSON body shape for POST /search.

type SearchResponse

type SearchResponse struct {
	Results []SearchResultItem `json:"results"`
	Count   int                `json:"count"`
	TookMs  int64              `json:"took_ms"`
}

SearchResponse is the JSON response for POST /search.

type SearchResultItem

type SearchResultItem struct {
	NodeID  uint64        `json:"node_id"`
	Score   float64       `json:"score"`
	Snippet string        `json:"snippet,omitempty"`
	Node    *NodeResponse `json:"node,omitempty"`
}

SearchResultItem is a single ranked full-text result.

type Server

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

Server represents the HTTP API server

func NewServer

func NewServer(graph *storage.GraphStorage, port int) (*Server, error)

NewServer creates a new API server dataDir is used for persisting auth data (users, API keys)

func NewServerWithDataDir

func NewServerWithDataDir(graph *storage.GraphStorage, port int, dataDir string) (*Server, error)

NewServerWithDataDir creates a new API server with explicit data directory

func (*Server) GetDataDir

func (s *Server) GetDataDir() string

GetDataDir returns the server's data directory

func (*Server) InitCORSFromEnv

func (s *Server) InitCORSFromEnv()

InitCORSFromEnv initializes CORS configuration from environment variables CORS_ALLOWED_ORIGINS: comma-separated list of allowed origins (e.g., "https://app.example.com,https://admin.example.com") Use "*" to allow all origins (NOT recommended for production)

func (*Server) InitRateLimiterFromEnv

func (s *Server) InitRateLimiterFromEnv()

InitRateLimiterFromEnv initializes rate limiter from environment variables

func (*Server) NewMethodRouter

func (s *Server) NewMethodRouter(w http.ResponseWriter, r *http.Request) *methodRouter

NewMethodRouter creates a new method router.

func (*Server) NewPathExtractor

func (s *Server) NewPathExtractor(w http.ResponseWriter, r *http.Request) *pathIDExtractor

NewPathExtractor creates a new path extractor.

func (*Server) NewRequestDecoder

func (s *Server) NewRequestDecoder(w http.ResponseWriter, r *http.Request) *requestDecoder

NewRequestDecoder creates a new request decoder for the given request.

func (*Server) SaveAuthData

func (s *Server) SaveAuthData() error

SaveAuthData persists users and API keys to disk

func (*Server) SetCORSConfig

func (s *Server) SetCORSConfig(cfg *CORSConfig)

SetCORSConfig sets the CORS configuration for the server

func (*Server) SetEncryption

func (s *Server) SetEncryption(engine encryption.EncryptDecrypter, keyManager encryption.KeyProvider)

SetEncryption sets the encryption engine and key manager for the server. Uses typed interfaces for compile-time safety.

func (*Server) SetTLSConfig

func (s *Server) SetTLSConfig(cfg *tlspkg.Config)

SetTLSConfig sets the TLS configuration for the server

func (*Server) Start

func (s *Server) Start() error

func (*Server) StopMetrics

func (s *Server) StopMetrics()

StopMetrics stops the background metrics updater goroutine

type ShortestPathRequest

type ShortestPathRequest struct {
	StartNodeID uint64 `json:"start_node_id"`
	EndNodeID   uint64 `json:"end_node_id"`
	MaxDepth    int    `json:"max_depth"`
}

ShortestPathRequest represents a shortest path query

type ShortestPathResponse

type ShortestPathResponse struct {
	Path   []uint64 `json:"path"`
	Length int      `json:"length"`
	Found  bool     `json:"found"`
	Time   string   `json:"time"`
}

ShortestPathResponse represents the shortest path result

type TenantCreateRequest

type TenantCreateRequest struct {
	ID          string              `json:"id"`
	Name        string              `json:"name"`
	Description string              `json:"description,omitempty"`
	Quota       *tenant.TenantQuota `json:"quota,omitempty"`
	Metadata    map[string]string   `json:"metadata,omitempty"`
}

TenantCreateRequest represents a request to create a tenant

type TenantListResponse

type TenantListResponse struct {
	Tenants []TenantResponse `json:"tenants"`
	Count   int              `json:"count"`
}

TenantListResponse represents the response for listing tenants

type TenantResponse

type TenantResponse struct {
	ID          string              `json:"id"`
	Name        string              `json:"name"`
	Description string              `json:"description,omitempty"`
	Status      tenant.TenantStatus `json:"status"`
	Quota       *tenant.TenantQuota `json:"quota,omitempty"`
	Metadata    map[string]string   `json:"metadata,omitempty"`
	CreatedAt   int64               `json:"created_at"`
	UpdatedAt   int64               `json:"updated_at"`
}

TenantResponse represents a tenant in API responses

type TenantUpdateRequest

type TenantUpdateRequest struct {
	Name        string              `json:"name,omitempty"`
	Description string              `json:"description,omitempty"`
	Quota       *tenant.TenantQuota `json:"quota,omitempty"`
	Metadata    map[string]string   `json:"metadata,omitempty"`
}

TenantUpdateRequest represents a request to update a tenant

type TenantUsageResponse

type TenantUsageResponse struct {
	TenantID     string             `json:"tenant_id"`
	NodeCount    int64              `json:"node_count"`
	EdgeCount    int64              `json:"edge_count"`
	StorageBytes int64              `json:"storage_bytes"`
	QuotaUsage   *tenant.QuotaUsage `json:"quota_usage,omitempty"`
	LastUpdated  int64              `json:"last_updated"`
}

TenantUsageResponse represents tenant usage statistics

type TraversalRequest

type TraversalRequest struct {
	StartNodeID uint64   `json:"start_node_id"`
	MaxDepth    int      `json:"max_depth"`
	EdgeTypes   []string `json:"edge_types,omitempty"`
	Direction   string   `json:"direction"` // "outgoing", "incoming", "both"
}

TraversalRequest represents a graph traversal request

type TraversalResponse

type TraversalResponse struct {
	Nodes []*NodeResponse `json:"nodes"`
	Count int             `json:"count"`
	Time  string          `json:"time"`
	// Truncated is true when the traversal stopped at MaxTraversalNodes
	// before exhausting the reachable set (security audit H-8). The same
	// signal is mirrored in the X-Truncated response header.
	Truncated bool `json:"truncated,omitempty"`
}

TraversalResponse represents traversal results

type UpdateApplyResponse

type UpdateApplyResponse struct {
	JobID         string `json:"job_id"`         //nolint:tagliatelle
	TargetVersion string `json:"target_version"` //nolint:tagliatelle
	Message       string `json:"message"`
}

UpdateApplyResponse is the response body for POST /admin/update/apply.

type UpdateCheckResponse

type UpdateCheckResponse struct {
	CurrentVersion  string           `json:"current_version"`          //nolint:tagliatelle
	LatestVersion   string           `json:"latest_version"`           //nolint:tagliatelle
	UpdateAvailable bool             `json:"update_available"`         //nolint:tagliatelle
	LatestRelease   *updater.Release `json:"latest_release,omitempty"` //nolint:tagliatelle
}

UpdateCheckResponse is the response body for GET /admin/update/check.

type UpdateJob

type UpdateJob struct {
	ID            string          `json:"id"`
	Status        UpdateJobStatus `json:"status"`
	TargetVersion string          `json:"target_version"`         //nolint:tagliatelle // external API schema
	StartedAt     time.Time       `json:"started_at"`             //nolint:tagliatelle
	CompletedAt   *time.Time      `json:"completed_at,omitempty"` //nolint:tagliatelle
	Error         string          `json:"error,omitempty"`
}

UpdateJob is the externally-visible state of an in-flight or completed update.

type UpdateJobStatus

type UpdateJobStatus string

UpdateJobStatus is the lifecycle state of an update job.

const (
	UpdateJobRunning   UpdateJobStatus = "running"
	UpdateJobSucceeded UpdateJobStatus = "succeeded"
	UpdateJobFailed    UpdateJobStatus = "failed"
)

Update job lifecycle states. UpdateJobRunning means the goroutine is active; the two terminal states (Succeeded / Failed) have CompletedAt set and (for Failed) an Error message.

type VectorIndexListResponse

type VectorIndexListResponse struct {
	Indexes []VectorIndexResponse `json:"indexes"`
	Count   int                   `json:"count"`
}

VectorIndexListResponse represents list of vector indexes

type VectorIndexRequest

type VectorIndexRequest struct {
	PropertyName   string `json:"property_name"`
	Dimensions     int    `json:"dimensions"`
	M              int    `json:"m,omitempty"`               // HNSW parameter (default: 16)
	EfConstruction int    `json:"ef_construction,omitempty"` // HNSW parameter (default: 200)
	Metric         string `json:"metric,omitempty"`          // "cosine", "euclidean", "dot_product" (default: "cosine")
}

VectorIndexRequest represents a request to create a vector index

type VectorIndexResponse

type VectorIndexResponse struct {
	PropertyName string `json:"property_name"`
	Dimensions   int    `json:"dimensions,omitempty"`
	Metric       string `json:"metric,omitempty"`
}

VectorIndexResponse represents a vector index in API responses

type VectorSearchRequest

type VectorSearchRequest struct {
	PropertyName string    `json:"property_name"`
	QueryVector  []float32 `json:"query_vector"`
	K            int       `json:"k"`             // Number of results
	Ef           int       `json:"ef,omitempty"`  // Search parameter (default: k * 2)
	IncludeNodes bool      `json:"include_nodes"` // Include full node data in results
	FilterLabels []string  `json:"filter_labels"` // Optional: filter results by labels

	// PropertyFilter applies an exact-match predicate inside the HNSW
	// post-filter loop, alongside the tenant + label filters. Values
	// must be string, JSON number, or bool; non-primitives are rejected
	// with 400. Like FilterLabels, this is a post-filter on HNSW
	// candidates, so selective predicates may yield fewer than K
	// results even when many matching nodes exist deeper in the index.
	PropertyFilter map[string]any `json:"property_filter,omitempty"`
}

VectorSearchRequest represents a vector similarity search request

type VectorSearchResponse

type VectorSearchResponse struct {
	Results []VectorSearchResult `json:"results"`
	Count   int                  `json:"count"`
	TookMs  int64                `json:"took_ms"`
}

VectorSearchResponse represents vector search results

type VectorSearchResult

type VectorSearchResult struct {
	NodeID   uint64        `json:"node_id"`
	Distance float32       `json:"distance"`
	Score    float32       `json:"score"` // Similarity score (1 - distance for cosine)
	Node     *NodeResponse `json:"node,omitempty"`
}

VectorSearchResult represents a single search result

Directories

Path Synopsis
Package middleware provides HTTP middleware components for the GraphDB API server.
Package middleware provides HTTP middleware components for the GraphDB API server.

Jump to

Keyboard shortcuts

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