multidb

package
v1.5.3 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: MIT Imports: 37 Imported by: 1 module, 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 multidb provides composite database support for multi-database functionality.

Composite databases are virtual databases that span multiple physical databases, allowing queries to transparently access data from multiple constituent databases.

Package multidb provides configuration helpers for multi-database support.

Package multidb provides limit enforcement for multi-database support.

This package implements resource limit checking and enforcement for NornicDB's multi-database feature. Limits are enforced at runtime to prevent any single database from consuming excessive resources.

Key Features:

  • Storage limits: MaxNodes, MaxEdges, MaxBytes (enforced with exact size calculation)
  • Query limits: MaxQueryTime, MaxResults, MaxConcurrentQueries
  • Connection limits: MaxConnections
  • Rate limits: MaxQueriesPerSecond, MaxWritesPerSecond

Example - Checking limits before creating a node:

checker, err := manager.GetLimitChecker("tenant_a")
if err != nil {
	return err
}

node := &storage.Node{
	ID:     storage.NodeID("user-123"),
	Labels: []string{"User"},
	Properties: map[string]any{"name": "Alice"},
}

// Check if creating this node would exceed limits
if err := checker.CheckStorageLimits(ctx, "create_node", node, nil); err != nil {
	return fmt.Errorf("cannot create node: %w", err)
}

// Safe to create - limits checked
storage.CreateNode(node)

MaxBytes Enforcement:

MaxBytes enforcement charges the MessagePack size of a canonical logical entity. This is a consistent quota measure, not the physical Badger size. The current total is tracked incrementally in DatabaseInfo, and the check verifies that currentSize + newEntitySize <= MaxBytes.

Storage size is tracked incrementally:

  • Initialized lazily on first access (calculated from all existing nodes/edges)
  • Updated incrementally after successful creates/deletes
  • No recalculation needed - O(1) limit checks

Package multidb provides multi-database support for NornicDB.

This package implements Neo4j 4.x-style multi-database support, allowing multiple logical databases (tenants) to share a single physical storage backend while maintaining complete data isolation.

Package multidb provides resource limits for multi-database support.

Package multidb provides multi-database support for NornicDB.

This package implements Neo4j 4.x-style multi-database support, allowing multiple logical databases (tenants) to share a single physical storage backend while maintaining complete data isolation.

Package multidb provides metadata persistence for multi-database support.

Package multidb provides automatic migration of existing unprefixed data.

When upgrading from a pre-multi-database version of NornicDB, existing data without namespace prefixes is automatically migrated to the default database namespace. This ensures backwards compatibility and zero-downtime upgrades.

Migration Process:

  1. Detects unprefixed data (nodes/edges without "namespace:" prefix)
  2. Migrates all unprefixed data to default database namespace
  3. Updates all indexes automatically (via CreateNode/CreateEdge)
  4. Marks migration as complete in metadata (prevents re-running)

The migration runs automatically in NewDatabaseManager() and is completely transparent to users. No manual steps are required.

Example:

// Before upgrade: data stored as "node-123"
// After upgrade: automatically becomes "nornic:node-123"
// User access remains the same - no changes needed!

Package multidb provides routing strategies for composite databases.

Routing determines which constituent databases should be queried for a given operation. This enables efficient query execution by only accessing relevant constituents.

Index

Constants

View Source
const (
	QuotaCapacityStatus = "Neo.ClientError.General.ResourceLimit"
	QuotaRateStatus     = "Neo.TransientError.General.ResourceExhaustion"
)

QuotaCapacityStatus and QuotaRateStatus are NornicDB resource-quota statuses. Capacity needs an operator/data change; rate exhaustion admits a later retry.

View Source
const (
	OptionStorageLayout  = "storage"
	StorageShared        = "shared"
	StorageIsolated      = "isolated"
	OptionPhysicalLayout = "layout"
	LayoutStandard       = "standard"
	LayoutExperimental   = "experimental"
	// OptionProjected selects the opt-in physical projection format for a new
	// isolated store. An absent option means false.
	OptionProjected = "projected"
)

Storage layout is chosen at catalog creation; it cannot be altered in place.

View Source
const OptionTxLogEnrichment = "txLogEnrichment"

OptionTxLogEnrichment is Neo4j's change data capture option: OFF (the default), DIFF or FULL (#937).

Variables

View Source
var (
	ErrDatabaseNotFound              = errors.New("database not found")
	ErrDatabaseExists                = errors.New("database already exists")
	ErrInvalidDatabaseName           = errors.New("invalid database name")
	ErrMaxDatabasesReached           = errors.New("maximum number of databases reached")
	ErrCannotDropSystemDB            = errors.New("cannot drop system database")
	ErrCannotDropDefaultDB           = errors.New("cannot drop default database")
	ErrDatabaseOffline               = errors.New("database is offline")
	ErrAliasExists                   = errors.New("alias already exists")
	ErrAliasNotFound                 = errors.New("alias not found")
	ErrInvalidAliasName              = errors.New("invalid alias name")
	ErrAliasConflict                 = errors.New("alias conflicts with existing database name")
	ErrDatabaseHasAliases            = errors.New("database has aliases - drop aliases first")
	ErrStorageLimitExceeded    error = &quotaError{"storage limit exceeded", QuotaCapacityStatus}
	ErrQueryLimitExceeded            = errors.New("query limit exceeded")
	ErrConnectionLimitExceeded       = errors.New("connection limit exceeded")
	ErrRateLimitExceeded       error = &quotaError{"rate limit exceeded", QuotaRateStatus}
	ErrNotCompositeDatabase          = errors.New("database is not a composite database")
	ErrConstituentNotFound           = errors.New("constituent not found")
	ErrDuplicateConstituent          = errors.New("duplicate constituent alias")
)

Multi-database error types

View Source
var ErrPreparedImportDisabled = errors.New("publishing prepared databases is disabled")

Functions

func LoadChangeCaptureModes

func LoadChangeCaptureModes(ctx context.Context, engine storage.Engine, systemDatabase string) error

LoadChangeCaptureModes sets every persisted database's change capture mode (its txLogEnrichment option) on engine before journal recovery. A journaled commit that start-up applies publishes the change events its database captures, and it is applied before the database manager exists: the manager, created by the server after nornicdb.Open returns, loads this same catalog record and settles the same modes again. A store that holds no catalog metadata yet has no persisted option and sets none.

It reads only the catalog record; it neither writes nor validates metadata, so a store whose manager will be created later is unchanged.

func NewCatalogUpgradeV4

func NewCatalogUpgradeV4(systemDatabase, key string) (*storage.CatalogUpgradeV4, error)

NewCatalogUpgradeV4 prepares the one configured catalog's pure credential transformer. Native storage owns admission, atomic writes and the V4 marker. An absent key is permitted only when no connection requires encryption. For example, bootstrap passes this plan before opening an authorized upgrade. Durable custom engines must explicitly apply this transform through their authoritative upgrade owner before manager construction. For native storage, supply the plan to an authorized startup open: a live manager retains a catalog snapshot, so a manual migration cannot safely replace that snapshot. Existing nonempty native stores require an explicit plan even when its exact configured catalog record is absent; storage does not guess arbitrary catalog namespaces. Manager load/save never performs a credential migration. Use the same stable key at runtime; the plan certifies only this configured catalog, not arbitrary metadata nodes.

func ReadIsolatedStoreID

func ReadIsolatedStoreID(ctx context.Context, engine storage.Engine, name string) (string, error)

ReadIsolatedStoreID resolves a database's physical location for offline tools. An empty ID means its data is in the root store.

func ReadIsolatedStoreIDs

func ReadIsolatedStoreIDs(ctx context.Context, engine storage.Engine) (map[string]string, error)

ReadIsolatedStoreIDs returns the committed dedicated stores for offline maintenance. Pending DROP stores are owned by catalog recovery.

func RemoteUserForDisplay

func RemoteUserForDisplay(user, authMode string) string

RemoteUserForDisplay distinguishes an explicit public USER identity from credential material extracted from URL userinfo, including legacy records.

func RestoreDatabaseBackup

func RestoreDatabaseBackup(ctx context.Context, source, destination string) error

RestoreDatabaseBackup restores a native single-store file or a full archive into a new data directory. All stores are verified before the directory is made available. A restore never replaces an existing installation.

func RestoreDatabaseBackupWithKey

func RestoreDatabaseBackupWithKey(ctx context.Context, source, destination string, initializeKey func(string) ([]byte, error)) (result error)

RestoreDatabaseBackupWithKey provisions the destination's key inside the temporary data root. Every restored native store opens with that key.

func WithDropDatabaseIdentity

func WithDropDatabaseIdentity(ctx context.Context, databaseID string) context.Context

WithDropDatabaseIdentity ties a subsequent DROP to an authorized database incarnation. The DROP owner compares the identity under its catalog gate.

Types

type BackupCatalog

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

BackupCatalog is a stable physical inventory for a full backup. It is valid only during the callback passed to WithBackupCatalog.

func (BackupCatalog) HasDedicatedStores

func (b BackupCatalog) HasDedicatedStores() bool

HasDedicatedStores reports whether the catalog includes multiple stores.

func (BackupCatalog) Write

func (b BackupCatalog) Write(ctx context.Context, path string, shared func() error) error

Write preserves the native single-store format or writes all stores together in one archive. The shared writer preserves each caller's legacy fallback.

type CompositeRouting

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

CompositeRouting combines multiple routing strategies. Tries each strategy in order until one returns a result.

func NewCompositeRouting

func NewCompositeRouting() *CompositeRouting

NewCompositeRouting creates a new composite routing strategy.

func (*CompositeRouting) AddStrategy

func (c *CompositeRouting) AddStrategy(strategy RoutingStrategy)

AddStrategy adds a routing strategy to try in order.

func (*CompositeRouting) RouteQuery

func (c *CompositeRouting) RouteQuery(queryInfo *QueryInfo) []string

RouteQuery tries each strategy until one returns a result.

func (*CompositeRouting) RouteWrite

func (c *CompositeRouting) RouteWrite(operation string, labels []string, properties map[string]interface{}) string

RouteWrite tries each strategy until one returns a result.

type Config

type Config struct {
	IsolatedStores *IsolatedStoreConfig
	// DefaultDatabase is the database used when none is specified (default: "nornic")
	// This matches Neo4j's behavior where "neo4j" is the default, but NornicDB uses "nornic"
	DefaultDatabase string

	// SystemDatabase stores metadata (default: "system")
	SystemDatabase string

	// MaxDatabases limits total databases (0 = unlimited)
	MaxDatabases int

	// AllowDropDefault allows dropping the default database
	AllowDropDefault bool

	// RemoteEngineFactory creates a storage engine for a remote constituent.
	// If nil, remote constituents are not executable (metadata may still be stored).
	RemoteEngineFactory RemoteEngineFactory

	// RemoteCredentialEncryptionKey encrypts remote constituent user/password values
	// before metadata persistence. If empty, user_password auth mode is rejected.
	RemoteCredentialEncryptionKey string
}

Config holds DatabaseManager configuration.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns default configuration. The default database name is "nornic" (NornicDB's equivalent of Neo4j's "neo4j").

func NewConfigFromDefaultDatabase

func NewConfigFromDefaultDatabase(defaultDatabase string) *Config

NewConfigFromDefaultDatabase creates a DatabaseManager Config from a default database name. This allows the DatabaseManager to use the same default database name as configured in the main NornicDB configuration.

Example:

// Use default database name from main config
mainConfig := config.LoadDefaults()
dbConfig := multidb.NewConfigFromDefaultDatabase(mainConfig.Database.DefaultDatabase)
// ctx belongs to the application startup operation.
manager, err := multidb.NewDatabaseManager(ctx, inner, dbConfig)

type ConnectionLimits

type ConnectionLimits struct {
	// MaxConnections is the maximum concurrent connections (0 = unlimited).
	MaxConnections int `json:"max_connections,omitempty"`
}

ConnectionLimits controls connection count per database.

type ConnectionTracker

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

ConnectionTracker tracks active connections per database.

func NewConnectionTracker

func NewConnectionTracker() *ConnectionTracker

NewConnectionTracker creates a new connection tracker.

func (*ConnectionTracker) CheckConnectionLimit

func (t *ConnectionTracker) CheckConnectionLimit(manager *DatabaseManager, databaseName string) error

CheckConnectionLimit checks if a new connection is allowed.

func (*ConnectionTracker) DecrementConnection

func (t *ConnectionTracker) DecrementConnection(databaseName string)

DecrementConnection decrements the connection count for a database.

func (*ConnectionTracker) GetConnectionCount

func (t *ConnectionTracker) GetConnectionCount(databaseName string) int

GetConnectionCount returns the current connection count for a database.

func (*ConnectionTracker) IncrementConnection

func (t *ConnectionTracker) IncrementConnection(databaseName string)

IncrementConnection increments the connection count for a database.

func (*ConnectionTracker) TryIncrementConnection

func (t *ConnectionTracker) TryIncrementConnection(manager *DatabaseManager, databaseName string) error

TryIncrementConnection checks the connection limit and increments atomically.

This avoids the race window of a "check-then-increment" pattern under concurrent connection attempts.

type ConstituentRef

type ConstituentRef struct {
	// ConnectionV1 is the sole stored connection authority for the tagged V1
	// format. Its ciphertext contains the original URI, credentials and origin;
	// legacy URI/User/Password/AuthMode fields are absent in this representation.
	ConnectionV1 string `json:"connection_v1,omitempty"`

	// Alias is the name used within the composite database to reference this constituent.
	Alias string `json:"alias"`

	// DatabaseName is the actual database name (or alias) that this constituent points to.
	DatabaseName string `json:"database_name"`

	// Type is the type of constituent: "local" (same instance) or "remote" (another instance).
	Type string `json:"type"` // "local", "remote"

	// AccessMode controls what operations are allowed: "read", "write", "read_write".
	AccessMode string `json:"access_mode"` // "read", "write", "read_write"

	// URI points to the remote NornicDB endpoint when Type == "remote".
	URI string `json:"uri,omitempty"`

	// SecretRef identifies credentials/token material for remote access.
	// The actual secret is resolved outside of metadata persistence.
	SecretRef string `json:"secret_ref,omitempty"`

	// User and Password carry explicit authentication at admission/runtime.
	// Legacy catalogs store Password in its historical encrypted field. Tagged
	// catalogs store the original URI and these values only inside ConnectionV1;
	// URI-origin fallback credentials are derived at runtime, retaining token
	// precedence, rather than changing the meaning of persisted USER fields.
	User     string `json:"user,omitempty"`
	Password string `json:"password,omitempty"`

	// AuthMode defines remote auth behavior:
	// - "oidc_forwarding": forward caller Authorization header
	// - "user_password": use explicit User/Password for outbound Basic auth
	// Empty is treated as "oidc_forwarding" for remote constituents.
	AuthMode string `json:"auth_mode,omitempty"`
}

ConstituentRef represents a reference to a constituent database within a composite database.

func (*ConstituentRef) Validate

func (c *ConstituentRef) Validate() error

Validate validates a constituent reference.

type DatabaseCreateRequest

type DatabaseCreateRequest struct {
	// PrivateOwner is server-assigned, never accepted from a JSON request.
	PrivateOwner string `json:"-"`
	Name         string
	Options      map[string]string
}

DatabaseCreateRequest describes one atomic standard-database catalog creation. Options are initial metadata, published with the name through the same storage receipt. The manager validates and copies them; later caller changes do not modify the database. For example:

manager.CreateDatabase(ctx, DatabaseCreateRequest{Name: "tenant_a"})
manager.CreateDatabase(ctx, DatabaseCreateRequest{Name: "audit", Options: map[string]string{OptionTxLogEnrichment: "FULL"}})

Existing databases remain errors; query-level IF NOT EXISTS admission belongs to its caller. Request cancellation is governed by the catalog commit receipt.

type DatabaseInfo

type DatabaseInfo struct {
	ID              string           `json:"id"`
	IsolatedStoreID string           `json:"isolated_store_id,omitempty"`
	Name            string           `json:"name"`
	CreatedAt       time.Time        `json:"created_at"`
	PrivateOwner    string           `json:"private_owner,omitempty"`
	CreatedBy       string           `json:"created_by,omitempty"`
	Status          string           `json:"status"` // "online", "offline"
	Type            string           `json:"type"`   // "standard", "system"
	IsDefault       bool             `json:"is_default"`
	NodeCount       int64            `json:"node_count,omitempty"` // Cached, may be stale
	UpdatedAt       time.Time        `json:"updated_at"`
	Aliases         []string         `json:"aliases,omitempty"`      // Database aliases (Neo4j-compatible)
	Limits          *Limits          `json:"limits,omitempty"`       // Resource limits
	Constituents    []ConstituentRef `json:"constituents,omitempty"` // Constituent databases (for composite type)

	// Options are the database's options (CREATE DATABASE … OPTIONS, ALTER
	// DATABASE … SET OPTION), by Neo4j's option name.
	Options map[string]string `json:"options,omitempty"`
	// contains filtered or unexported fields
}

DatabaseInfo holds metadata about a database.

type DatabaseManager

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

DatabaseManager manages multiple logical databases within a single storage engine.

It provides:

  • Database creation and deletion
  • Database metadata tracking
  • Namespaced storage engine views
  • Neo4j 4.x multi-database compatibility

Reads use the published catalog. Mutations require their original operation context and serialize through physical receipt settlement. Canceling a waiter after acceptance never rolls back the accepted catalog proposal.

Example:

// Create manager with shared storage
ctx := context.Background()
inner, _ := storage.NewBadgerEngine("./data")
manager, _ := multidb.NewDatabaseManager(ctx, inner, nil)

// Create databases
manager.CreateDatabase(ctx, DatabaseCreateRequest{Name: "tenant_a"})
manager.CreateDatabase(ctx, DatabaseCreateRequest{Name: "tenant_b"})

// Get namespaced storage for a tenant
tenantStorage, _ := manager.GetStorage("tenant_a")

// Use storage (isolated to tenant_a)
tenantStorage.CreateNode(&storage.Node{ID: "123"})

func NewDatabaseManager

func NewDatabaseManager(ctx context.Context, inner storage.Engine, config *Config) (*DatabaseManager, error)

NewDatabaseManager creates a new database manager. ctx is the explicit startup/process lifetime, distinct from later request contexts. Writable catalog storage must expose native entity preparation and the authoritative EntityCommitSubmitter receipt capability through its wrapper route. Read-only startup does not admit catalog writes.

Parameters:

  • inner: The underlying storage engine (shared by all databases)
  • config: Configuration (nil for defaults)

On creation, initializes:

  • System database (for metadata)
  • Default database ("nornic" by default, configurable)

func (*DatabaseManager) ActiveDedicatedGraphStores

func (m *DatabaseManager) ActiveDedicatedGraphStores() []storage.Engine

ActiveDedicatedGraphStores snapshots online dedicated owners without keeping the catalog locked during storage reads or provider calls.

func (*DatabaseManager) AddConstituent

func (m *DatabaseManager) AddConstituent(ctx context.Context, compositeName string, constituent ConstituentRef) error

AddConstituent adds a constituent to an existing composite database.

func (*DatabaseManager) BackgroundGraphStore

func (m *DatabaseManager) BackgroundGraphStore(name string) (storage.Engine, error)

BackgroundGraphStore returns the physical owner of an already-qualified node. An unavailable dedicated database cannot fall back to the shared root.

func (*DatabaseManager) Close

func (m *DatabaseManager) Close() error

Close releases resources.

func (*DatabaseManager) CloseIsolatedStores

func (m *DatabaseManager) CloseIsolatedStores() error

CloseIsolatedStores releases only dedicated database engines. The serving DB's lifetime retains ownership of the shared engine.

func (*DatabaseManager) CreateAlias

func (m *DatabaseManager) CreateAlias(ctx context.Context, alias, databaseName string) error

CreateAlias creates an alias for a database (Neo4j-compatible).

func (*DatabaseManager) CreateCompositeDatabase

func (m *DatabaseManager) CreateCompositeDatabase(ctx context.Context, name string, constituents []ConstituentRef) error

CreateCompositeDatabase creates a new composite database.

func (*DatabaseManager) CreateDatabase

func (m *DatabaseManager) CreateDatabase(ctx context.Context, request DatabaseCreateRequest) error

CreateDatabase creates a new database.

Parameters:

  • request: Database name and initial options, copied into one catalog publication

Returns ErrDatabaseExists if database already exists. Returns ErrMaxDatabasesReached if limit exceeded.

func (*DatabaseManager) DatabaseIdentity

func (m *DatabaseManager) DatabaseIdentity(name string) (string, time.Time)

DatabaseIdentity returns a database's persisted UUID and creation time. Reloading a manager preserves these values; dropping and recreating the database creates a new UUID. An unknown database returns empty values. For example, SHOW DATABASES uses these values for databaseID and creationTime.

func (*DatabaseManager) DatabaseOptions

func (m *DatabaseManager) DatabaseOptions(databaseName string) (map[string]string, error)

DatabaseOptions returns a copy of a database's options.

func (*DatabaseManager) DatabaseStatementCaches

DatabaseStatementCaches atomically acquires an owner and selection generation. Aliases share their canonical database's owner; constituents keep the local target's owner (or the composite owner's for remote targets).

func (*DatabaseManager) DecrementStorageSize

func (m *DatabaseManager) DecrementStorageSize(databaseName string, nodeSize, edgeSize int64)

DecrementStorageSize decrements the tracked storage size for a database.

This should be called after successful node/edge deletion to maintain accurate size tracking for MaxBytes limit enforcement. The sizes should be the same values that were used when the entities were created.

Parameters:

  • databaseName: The database to update
  • nodeSize: Size in bytes of the node that was deleted (0 if no node deleted)
  • edgeSize: Size in bytes of the edge that was deleted (0 if no edge deleted)

Example:

// After successfully deleting a node (size known from creation)
manager.DecrementStorageSize("tenant_a", nodeSize, 0)

// After successfully deleting an edge (size known from creation)
manager.DecrementStorageSize("tenant_a", 0, edgeSize)

Thread-safe: This method is safe to call from multiple goroutines. Defensive: Size is prevented from going negative (resets to 0 if underflow).

func (*DatabaseManager) DefaultDatabaseName

func (m *DatabaseManager) DefaultDatabaseName() string

DefaultDatabaseName returns the default database name.

func (*DatabaseManager) DropAlias

func (m *DatabaseManager) DropAlias(ctx context.Context, alias string) error

DropAlias removes an alias (Neo4j-compatible).

func (*DatabaseManager) DropCompositeDatabase

func (m *DatabaseManager) DropCompositeDatabase(ctx context.Context, name string) error

DropCompositeDatabase removes a composite database.

This only removes the composite database metadata. The constituent databases remain unchanged.

func (*DatabaseManager) DropDatabase

func (m *DatabaseManager) DropDatabase(ctx context.Context, name string) error

DropDatabase removes a database and all its data.

Parameters:

  • name: Database name to drop

Returns ErrDatabaseNotFound if database doesn't exist. Returns ErrCannotDropSystemDB for system/default databases.

func (*DatabaseManager) Exists

func (m *DatabaseManager) Exists(name string) bool

Exists checks if a database exists.

func (*DatabaseManager) ExistsOrIsConstituent

func (m *DatabaseManager) ExistsOrIsConstituent(name string) bool

ExistsOrIsConstituent returns true if the name refers to an existing database or a valid composite constituent in dotted "composite.alias" form. This is used by protocol entry paths (Bolt/HTTP) to avoid premature DB-not-found rejection for constituent graph references.

func (*DatabaseManager) FinishPendingDrop

func (m *DatabaseManager) FinishPendingDrop(ctx context.Context, name string) error

FinishPendingDrop finishes a drop the DROP owner already accepted for name, and nothing else. Without a held fence it reports ErrDatabaseNotFound, so it can never reach a live or newer database of that name. Entry points that may only remove their own kind of live database (Qdrant collections) use it for a name that is no longer available to them.

func (*DatabaseManager) GetCompositeConstituents

func (m *DatabaseManager) GetCompositeConstituents(compositeName string) ([]ConstituentRef, error)

GetCompositeConstituents returns stored registration snapshots for the visible aliases. It never decrypts credentials. Resolve execution with GetStorage and project metadata with RemoteConstituentForDisplay; tagged URI/User/Password fields are absent because ConnectionV1 is their sole stored authority.

func (*DatabaseManager) GetDatabase

func (m *DatabaseManager) GetDatabase(name string) (*DatabaseInfo, error)

GetDatabase returns info for a specific database.

func (*DatabaseManager) GetDatabaseLimits

func (m *DatabaseManager) GetDatabaseLimits(databaseName string) (*Limits, error)

GetDatabaseLimits returns resource limits for a database.

func (*DatabaseManager) GetDefaultStorage

func (m *DatabaseManager) GetDefaultStorage() (storage.Engine, error)

GetDefaultStorage returns storage for the default database.

func (*DatabaseManager) GetStorage

func (m *DatabaseManager) GetStorage(name string) (storage.Engine, error)

GetStorage returns a namespaced storage engine for the specified database.

The returned engine is scoped to the database - all operations only affect data within that namespace.

func (*DatabaseManager) GetStorageSize

func (m *DatabaseManager) GetStorageSize(ctx context.Context, databaseName string) (int64, int64, int64)

GetStorageSize returns the current tracked storage size for a database.

Returns:

  • totalSize: Total storage size in bytes (sum of all nodes and edges)
  • nodeSize: Total size of all nodes in bytes
  • edgeSize: Total size of all edges in bytes

The size is tracked incrementally and initialized lazily on first access. This provides O(1) access for limit checking without recalculating from all entities.

Example:

totalSize, nodeSize, edgeSize := manager.GetStorageSize(ctx, "tenant_a")
fmt.Printf("Database uses %d bytes (%d from nodes, %d from edges)\n",
	totalSize, nodeSize, edgeSize)

Thread-safe: This method is safe to call from multiple goroutines.

func (*DatabaseManager) GetStorageWithAuth

func (m *DatabaseManager) GetStorageWithAuth(name string, authToken string) (storage.Engine, error)

GetStorageWithAuth returns a storage engine for the specified database and forwards authToken to remote constituent factories when composite databases include remotes.

Resolution and construction are separate owners so that a configured remote engine factory never runs under the metadata lock. The factory is foreign code: it may reenter this manager's public catalog (for example ListDatabaseNames), and holding m.mu across it blocks that reentry permanently (NOR-183).

func (*DatabaseManager) IncrementStorageSize

func (m *DatabaseManager) IncrementStorageSize(databaseName string, nodeSize, edgeSize int64)

IncrementStorageSize increments the tracked storage size for a database.

This should be called after successful node/edge creation to maintain accurate size tracking for MaxBytes limit enforcement. The sizes should be calculated using the same gob encoding used by the storage engine.

Parameters:

  • databaseName: The database to update
  • nodeSize: Size in bytes of the node that was created (0 if no node created)
  • edgeSize: Size in bytes of the edge that was created (0 if no edge created)

Example:

// After successfully creating a node
nodeSize, _ := calculateNodeSize(node)
manager.IncrementStorageSize("tenant_a", nodeSize, 0)

// After successfully creating an edge
edgeSize, _ := calculateEdgeSize(edge)
manager.IncrementStorageSize("tenant_a", 0, edgeSize)

Thread-safe: This method is safe to call from multiple goroutines.

func (*DatabaseManager) IsCompositeDatabase

func (m *DatabaseManager) IsCompositeDatabase(name string) bool

IsCompositeDatabase checks if a database is a composite database.

func (*DatabaseManager) ListAliases

func (m *DatabaseManager) ListAliases(databaseName string) map[string]string

ListAliases returns all aliases for a database, or all aliases if database is empty.

func (*DatabaseManager) ListCompositeDatabases

func (m *DatabaseManager) ListCompositeDatabases() []*DatabaseInfo

ListCompositeDatabases returns all composite databases.

func (*DatabaseManager) ListDatabaseNames

func (m *DatabaseManager) ListDatabaseNames() []string

ListDatabaseNames returns a snapshot of canonical catalog names, including empty, composite and system databases. Aliases remain selections of their targets, rather than additional databases. Name-only consumers avoid copying configuration, limits, aliases and constituent metadata they do not use.

func (*DatabaseManager) ListDatabases

func (m *DatabaseManager) ListDatabases() []*DatabaseInfo

ListDatabases returns all database info.

func (*DatabaseManager) PrivateDatabaseOwner

func (m *DatabaseManager) PrivateDatabaseOwner(name string) string

PrivateDatabaseOwner returns immutable ownership from the live catalog, resolving aliases before reading the physical database's metadata.

func (*DatabaseManager) PrivateWorkspace

func (m *DatabaseManager) PrivateWorkspace(owner string) *DatabaseInfo

PrivateWorkspace returns the catalog snapshot belonging to this principal.

func (*DatabaseManager) PublishPreparedDatabase

func (m *DatabaseManager) PublishPreparedDatabase(ctx context.Context, name, id string) error

PublishPreparedDatabase verifies a closed store before the existing catalog receipt makes its binding visible. Only that receipt can transfer ownership.

func (*DatabaseManager) RegisterStatementCacheIndex

func (m *DatabaseManager) RegisterStatementCacheIndex(invalidate func()) func()

RegisterStatementCacheIndex publishes invalidation only after releasing the metadata lock. A callback may hold its index lock and reenter the manager.

func (*DatabaseManager) ReloadAfterRestore

func (m *DatabaseManager) ReloadAfterRestore(ctx context.Context) error

ReloadAfterRestore publishes the restored catalog into the running manager. The caller must hold the catalog gate through WithBackupCatalog so another catalog transition cannot publish the pre-restore image afterwards.

func (*DatabaseManager) RemoteConstituentForDisplay

func (m *DatabaseManager) RemoteConstituentForDisplay(ref ConstituentRef) (ConstituentRef, error)

RemoteConstituentForDisplay projects a stored registration without exposing its connection authority. Execution and catalog/cache identity must continue to use the original stored registration. For example, SHOW CONSTITUENTS can display its URI/public explicit USER without receiving PASSWORD or ciphertext.

func (*DatabaseManager) RemoveConstituent

func (m *DatabaseManager) RemoveConstituent(ctx context.Context, compositeName string, alias string) error

RemoveConstituent removes a constituent from a composite database.

func (*DatabaseManager) ResolveConnectionLimitOwner added in v1.3.1

func (m *DatabaseManager) ResolveConnectionLimitOwner(selection string) (string, error)

ResolveConnectionLimitOwner resolves a Bolt database selection to the local database whose connection limit owns it. Local composite constituents are charged to their underlying database; remote constituents use the composite.

func (*DatabaseManager) ResolveDatabase

func (m *DatabaseManager) ResolveDatabase(nameOrAlias string) (string, error)

ResolveDatabase resolves an alias or database name to the actual database name.

func (*DatabaseManager) ServerIdentity

func (m *DatabaseManager) ServerIdentity() (string, time.Time)

ServerIdentity returns the persisted installation UUID and creation time. They survive manager reloads and are shared by all databases in the installation. A read-only legacy store may return an empty ID until upgraded by its writer. For example, administrative introspection can use these values for serverID and the DBMS creationDate instead of inventing an identity or timestamp.

func (*DatabaseManager) SetDatabaseLimits

func (m *DatabaseManager) SetDatabaseLimits(ctx context.Context, databaseName string, limits *Limits) error

SetDatabaseLimits sets resource limits for a database.

func (*DatabaseManager) SetDatabaseOption

func (m *DatabaseManager) SetDatabaseOption(ctx context.Context, databaseName, key, value string) error

SetDatabaseOption sets a database option, or removes it when value is empty, and persists the database metadata. The caller validates the option.

func (*DatabaseManager) SetDatabaseStatus

func (m *DatabaseManager) SetDatabaseStatus(ctx context.Context, name, status string) error

SetDatabaseStatus sets a database online/offline.

func (*DatabaseManager) StatementCacheScope

func (m *DatabaseManager) StatementCacheScope(name string) (*StatementCacheScope, error)

StatementCacheScope resolves a selection under the metadata lock. A retained executor keeps its old token; removing/recreating the selection never revives it.

func (*DatabaseManager) SystemDatabaseName

func (m *DatabaseManager) SystemDatabaseName() string

SystemDatabaseName returns the configured metadata database name. For example, dbms.info uses this name rather than assuming it is "system".

func (*DatabaseManager) WithBackupCatalog

func (m *DatabaseManager) WithBackupCatalog(ctx context.Context, operation func(BackupCatalog) error) error

WithBackupCatalog holds the catalog stable while the caller authorizes and captures a backup. It also waits for DROP's physical cleanup, which can run outside the catalog gate. Ordinary graph transactions keep serving.

type FullScanRouting

type FullScanRouting struct{}

FullScanRouting routes all queries to all constituents. This is the default strategy when no routing rules are configured.

func NewFullScanRouting

func NewFullScanRouting() *FullScanRouting

NewFullScanRouting creates a new full-scan routing strategy.

func (*FullScanRouting) RouteQuery

func (r *FullScanRouting) RouteQuery(queryInfo *QueryInfo) []string

RouteQuery returns nil, indicating all constituents should be queried.

func (*FullScanRouting) RouteWrite

func (r *FullScanRouting) RouteWrite(operation string, labels []string, properties map[string]interface{}) string

RouteWrite returns empty string, indicating write should go to first writable constituent.

type IsolatedStoreConfig

type IsolatedStoreConfig struct {
	Create func(context.Context, string, map[string]string) (string, storage.Engine, error)
	Open   func(context.Context, string, string, map[string]string, bool) (storage.Engine, error)
	Drop   func(string) error
}

IsolatedStoreConfig owns physically separate databases on a standalone server. Its presence makes isolated storage the default for new catalogs.

type LabelRouting

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

LabelRouting routes queries based on node labels. Each label is mapped to one or more constituent aliases.

func NewLabelRouting

func NewLabelRouting() *LabelRouting

NewLabelRouting creates a new label-based routing strategy.

func (*LabelRouting) RouteQuery

func (r *LabelRouting) RouteQuery(queryInfo *QueryInfo) []string

RouteQuery routes a query based on labels.

func (*LabelRouting) RouteWrite

func (r *LabelRouting) RouteWrite(operation string, labels []string, properties map[string]interface{}) string

RouteWrite routes a write operation based on labels.

func (*LabelRouting) SetLabelRouting

func (r *LabelRouting) SetLabelRouting(label string, constituents []string)

SetLabelRouting configures which constituents should be queried for a given label.

type LimitChecker

type LimitChecker interface {
	// CheckStorageLimits checks if storage operations are within limits.
	// Returns error if limit would be exceeded.
	// For create operations, pass the node/edge being created to calculate exact size.
	CheckStorageLimits(ctx context.Context, operation string, node *storage.Node, edge *storage.Edge) error

	// CheckQueryLimits checks if query execution is allowed.
	// Returns error if limit would be exceeded.
	CheckQueryLimits(ctx context.Context) (context.Context, context.CancelFunc, error)

	// GetQueryLimits returns the query limits for this database.
	GetQueryLimits() interface{}

	// GetRateLimits returns the rate limits for this database.
	GetRateLimits() *RateLimits

	// CheckQueryRate checks if query rate limit is allowed.
	CheckQueryRate() error

	// CheckWriteRate checks if write rate limit is allowed.
	CheckWriteRate() error
}

LimitChecker provides an interface for checking resource limits. This allows storage engines to check limits without depending on DatabaseManager. It implements both storage.LimitChecker and storage.QueryLimitChecker.

type Limits

type Limits struct {
	Storage    StorageLimits    `json:"storage,omitempty"`
	Query      QueryLimits      `json:"query,omitempty"`
	Connection ConnectionLimits `json:"connection,omitempty"`
	Rate       RateLimits       `json:"rate,omitempty"`
}

Limits holds resource limits for a database.

All limits are optional (0 = unlimited). Limits are enforced at runtime to prevent any single database from consuming excessive resources.

Example:

limits := &Limits{
	Storage: StorageLimits{
		MaxNodes: 1000000,
		MaxEdges: 5000000,
		MaxBytes: 10 * 1024 * 1024 * 1024, // 10GB
	},
	Query: QueryLimits{
		MaxQueryTime:        60 * time.Second,
		MaxResults:          10000,
		MaxConcurrentQueries: 10,
	},
	Connection: ConnectionLimits{
		MaxConnections: 50,
	},
	Rate: RateLimits{
		MaxQueriesPerSecond: 100,
		MaxWritesPerSecond:  50,
	},
}

func DefaultLimits

func DefaultLimits() *Limits

DefaultLimits returns default limits (all unlimited).

func (*Limits) GetMaxResults

func (l *Limits) GetMaxResults() int64

GetMaxResults returns the maximum number of results (for interface compatibility).

func (*Limits) IsUnlimited

func (l *Limits) IsUnlimited() bool

IsUnlimited returns true if all limits are unlimited (default state).

type PropertyRouting

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

PropertyRouting routes queries based on property values. Useful for database/shard-based routing (e.g., database_id property).

func NewPropertyRouting

func NewPropertyRouting(propertyName string) *PropertyRouting

NewPropertyRouting creates a new property-based routing strategy.

func (*PropertyRouting) RouteQuery

func (r *PropertyRouting) RouteQuery(queryInfo *QueryInfo) []string

RouteQuery routes a query based on property values.

func (*PropertyRouting) RouteWrite

func (r *PropertyRouting) RouteWrite(operation string, labels []string, properties map[string]interface{}) string

RouteWrite routes a write operation based on property values.

func (*PropertyRouting) SetDefaultConstituent

func (r *PropertyRouting) SetDefaultConstituent(constituent string)

SetDefaultConstituent sets the default constituent for values not in the map.

func (*PropertyRouting) SetPropertyRouting

func (r *PropertyRouting) SetPropertyRouting(value interface{}, constituent string)

SetPropertyRouting configures which constituent should be queried for a property value.

type QueryInfo

type QueryInfo struct {
	// Labels referenced in the query
	Labels []string

	// Properties used in WHERE clauses or CREATE/MERGE operations
	Properties map[string]interface{}

	// Property names that might be used for routing
	PropertyNames []string

	// Whether this is a write operation
	IsWrite bool

	// Whether this is a full scan (no specific labels/properties)
	IsFullScan bool
}

QueryInfo contains information extracted from a Cypher query for routing decisions.

type QueryLimits

type QueryLimits struct {
	// MaxQueryTime is the maximum query execution time (0 = unlimited).
	MaxQueryTime time.Duration `json:"max_query_time,omitempty"`

	// MaxResults is the maximum number of results returned (0 = unlimited).
	MaxResults int64 `json:"max_results,omitempty"`

	// MaxConcurrentQueries is the maximum concurrent queries (0 = unlimited).
	MaxConcurrentQueries int `json:"max_concurrent_queries,omitempty"`
}

QueryLimits controls query execution per database.

func (*QueryLimits) GetMaxResults

func (q *QueryLimits) GetMaxResults() int64

GetMaxResults returns the maximum number of results (for interface compatibility).

type RateLimits

type RateLimits struct {
	// MaxQueriesPerSecond is the maximum queries per second (0 = unlimited).
	MaxQueriesPerSecond int `json:"max_queries_per_second,omitempty"`

	// MaxWritesPerSecond is the maximum writes per second (0 = unlimited).
	MaxWritesPerSecond int `json:"max_writes_per_second,omitempty"`
}

RateLimits controls request rate per database.

type RemoteEngineFactory

type RemoteEngineFactory func(ref ConstituentRef, authToken string) (storage.Engine, error)

RemoteEngineFactory creates storage engines for remote composite constituents. authToken is the original caller's auth token/header value, forwarded to preserve authentication context across distributed constituent queries.

type RoutingStrategy

type RoutingStrategy interface {
	// RouteQuery determines which constituents should be queried for a given operation.
	// Returns list of constituent aliases to query.
	RouteQuery(queryInfo *QueryInfo) []string

	// RouteWrite determines which constituent should receive a write operation.
	// Returns constituent alias, or empty string if routing is ambiguous (full scan).
	RouteWrite(operation string, labels []string, properties map[string]interface{}) string
}

RoutingStrategy defines how queries are routed to constituent databases.

type StatementCacheIndex

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

StatementCacheIndex registers one retained-view index for its host lifetime. Bind and Close may race; Close never retires resources the index only borrows.

func (*StatementCacheIndex) Bind

func (i *StatementCacheIndex) Bind(manager *DatabaseManager, invalidate func())

func (*StatementCacheIndex) Close

func (i *StatementCacheIndex) Close()

type StatementCacheResource

type StatementCacheResource interface {
	Dispose()
	InvalidateScopes()
}

StatementCacheResource belongs to a canonical database. Selection removal invalidates dependent entries; only removal of that database retires the owner. Implementations must not call back into the manager while holding cache locks.

type StatementCacheScope

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

StatementCacheScope is one catalog selection generation. It contains names and lifetime state only, never storage, credentials or execution state.

func (*StatementCacheScope) Generation

func (s *StatementCacheScope) Generation() uint64

Generation identifies this selection's lifetime, including same-name recreation.

func (*StatementCacheScope) Valid

func (s *StatementCacheScope) Valid() bool

type StorageLimits

type StorageLimits struct {
	// MaxNodes is the maximum number of nodes allowed (0 = unlimited).
	// When exceeded, create operations fail with: "has reached max_nodes limit (N/M)"
	MaxNodes int64 `json:"max_nodes,omitempty"`

	// MaxEdges is the maximum number of edges allowed (0 = unlimited).
	// When exceeded, create operations fail with: "has reached max_edges limit (N/M)"
	MaxEdges int64 `json:"max_edges,omitempty"`

	// MaxBytes is the maximum storage size in bytes (0 = unlimited).
	// When exceeded, create operations fail with: "would exceed max_bytes limit
	// (current: X bytes, limit: Y bytes, new entity: Z bytes)"
	//
	// Size is the canonical logical entity's MessagePack length, which can differ
	// from the physical Badger or WAL size.
	MaxBytes int64 `json:"max_bytes,omitempty"`
}

StorageLimits controls storage capacity per database.

All limits are enforced at runtime. When a limit is exceeded, the operation fails with a clear error message explaining the quota limits.

MaxBytes Enforcement:

MaxBytes charges the MessagePack size of canonical logical entities. That quota measure is tracked incrementally; it is not the physical disk size.

Example:

limits := StorageLimits{
	MaxNodes: 1000000,                    // 1 million nodes
	MaxEdges: 5000000,                    // 5 million edges
	MaxBytes: 10 * 1024 * 1024 * 1024,   // 10GB
}

Jump to

Keyboard shortcuts

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