Documentation
¶
Index ¶
- Constants
- Variables
- func MarshalQuerySpecJSON(query QuerySpec) ([]byte, error)
- func MarshalWireDocument(document Document) ([]byte, error)
- func MarshalWireValue(value Value) ([]byte, error)
- func ValidateStrictJSON(data []byte, maxBytes int) error
- type BackupStats
- type BackupV2Result
- type Change
- type ChangeBatch
- type Collection
- func (c *Collection) CreateIndex(ctx context.Context, name string, fields []IndexField, options IndexOptions) error
- func (c *Collection) CreateIndexOnline(ctx context.Context, name string, fields []IndexField, options IndexOptions) (IndexBuildID, error)
- func (c *Collection) DeleteMany(ctx context.Context, filter Filter) (DeleteResult, error)
- func (c *Collection) DeleteManyQuery(ctx context.Context, query QuerySpec) (DeleteResult, error)
- func (c *Collection) DeleteManyQueryLimited(ctx context.Context, query QuerySpec, maxAffected int) (DeleteResult, error)
- func (c *Collection) DeleteOne(ctx context.Context, filter Filter) (DeleteResult, error)
- func (c *Collection) DeleteOneQuery(ctx context.Context, query QuerySpec) (DeleteResult, error)
- func (c *Collection) Explain(ctx context.Context, filter Filter) (ExplainResult, error)
- func (c *Collection) Find(ctx context.Context, filter Filter, options ...QueryOptions) (*Cursor, error)
- func (c *Collection) FindOne(ctx context.Context, filter Filter) (Document, error)
- func (c *Collection) FindQuery(ctx context.Context, query QuerySpec) (*Cursor, error)
- func (c *Collection) InsertMany(ctx context.Context, documents []Document) ([]DocumentID, error)
- func (c *Collection) InsertOne(ctx context.Context, document Document) (DocumentID, error)
- func (c *Collection) SnapshotQuery(ctx context.Context, query QuerySpec) (QuerySnapshot, error)
- func (c *Collection) StartIndexBuild(ctx context.Context, name string, fields []IndexField, options IndexOptions) (IndexBuildID, error)
- func (c *Collection) SubscribeQuery(ctx context.Context, query QuerySpec, buffer int) (*QuerySubscription, error)
- func (c *Collection) SubscribeQueryDeltas(ctx context.Context, query QuerySpec, buffer int) (*QueryDeltaSubscription, error)
- func (c *Collection) UpdateMany(ctx context.Context, filter Filter, update Update) (UpdateResult, error)
- func (c *Collection) UpdateManyQuery(ctx context.Context, query QuerySpec, mutation MutationSpec) (UpdateResult, error)
- func (c *Collection) UpdateManyQueryLimited(ctx context.Context, query QuerySpec, mutation MutationSpec, maxAffected int) (UpdateResult, error)
- func (c *Collection) UpdateOne(ctx context.Context, filter Filter, update Update) (UpdateResult, error)
- func (c *Collection) UpdateOneQuery(ctx context.Context, query QuerySpec, mutation MutationSpec) (UpdateResult, error)
- type CommitStats
- type CompactionStats
- type Cursor
- type DB
- func New() *DB
- func NewWithOptions(options DatabaseOptions) (*DB, error)
- func Open(path string) (*DB, error)
- func OpenV1(path string) (*DB, error)
- func OpenV1WithOptions(path string, options V1Options) (*DB, error)
- func OpenV2(path string) (*DB, error)
- func OpenV2WithOptions(path string, options V2Options) (*DB, error)
- func OpenWithOptions(path string, options OpenOptions) (*DB, error)
- func (db *DB) AbortIndexBuild(ctx context.Context, id IndexBuildID) error
- func (db *DB) BackupV2(ctx context.Context, destination string) (result BackupV2Result, resultErr error)
- func (db *DB) CanResumeFrom(token uint64) bool
- func (db *DB) Close() error
- func (db *DB) Collection(name string) *Collection
- func (db *DB) CompactToV2(ctx context.Context, destination string) (resultErr error)
- func (db *DB) CompactToV2WithOptions(ctx context.Context, destination string, options V2DestinationOptions) (resultErr error)
- func (db *DB) DatabaseIdentity() [16]byte
- func (db *DB) DiagnosticSnapshotAfter(after uint64, limit int) DiagnosticSnapshot
- func (db *DB) EnableDiagnostics(options DiagnosticsOptions) (*Diagnostics, error)
- func (db *DB) IndexBuild(id IndexBuildID) (IndexBuildStatus, error)
- func (db *DB) IndexBuilds() ([]IndexBuildStatus, error)
- func (db *DB) MeldbaseSystemRecordBackend() systemrecord.Backend
- func (db *DB) MeldbaseSystemWrite(ctx context.Context, systemMutation systemrecord.Mutation, ...) (systemrecord.Result, bool, error)
- func (db *DB) MigrateToV2(ctx context.Context, destination string) error
- func (db *DB) MigrateToV2WithOptions(ctx context.Context, destination string, options V2DestinationOptions) error
- func (db *DB) OpenQueryReplay(ctx context.Context, collection string, query QuerySpec, afterToken uint64, ...) (*QueryReplaySubscription, error)
- func (db *DB) OperationalState() OperationalState
- func (db *DB) ReclaimV2Pages(ctx context.Context) (result ReclaimV2Result, resultErr error)
- func (db *DB) ReclaimV2PagesWithOptions(ctx context.Context, options ReclaimV2Options) (result ReclaimV2Result, resultErr error)
- func (db *DB) RecoveryReport() RecoveryReport
- func (db *DB) ResourceLimits() ResourceLimits
- func (db *DB) ResumeIndexBuild(ctx context.Context, id IndexBuildID) error
- func (db *DB) RunWriteTransaction(ctx context.Context, build func(*WriteTransaction) error) error
- func (db *DB) StartIndexBuildScheduler(parent context.Context, options IndexBuildSchedulerOptions) (*IndexBuildScheduler, error)
- func (db *DB) StartV2Maintenance(parent context.Context, options V2MaintenanceOptions) (*V2Maintenance, error)
- func (db *DB) Stats() DBStats
- func (db *DB) Sync() error
- func (db *DB) WatchChanges(ctx context.Context, collection string, buffer int) (<-chan ChangeBatch, <-chan error, error)
- type DBStats
- type DatabaseOptions
- type DeleteResult
- type DiagnosticEvent
- type DiagnosticKind
- type DiagnosticOutcome
- type DiagnosticSnapshot
- type DiagnosticStats
- type Diagnostics
- func (d *Diagnostics) Close() error
- func (d *Diagnostics) DiagnosticSnapshotAfter(after uint64, limit int) DiagnosticSnapshot
- func (d *Diagnostics) Snapshot() DiagnosticSnapshot
- func (d *Diagnostics) SnapshotAfter(after uint64, limit int) DiagnosticSnapshot
- func (d *Diagnostics) Stats() DiagnosticStats
- type DiagnosticsOptions
- type Document
- type DocumentCacheStats
- type DocumentID
- type DurabilityStats
- type ExplainResult
- type Filter
- type IndexBuildFailure
- type IndexBuildID
- type IndexBuildPhase
- type IndexBuildScheduler
- type IndexBuildSchedulerOptions
- type IndexBuildSchedulerStats
- type IndexBuildStats
- type IndexBuildStatus
- type IndexDefinition
- type IndexField
- type IndexOptions
- type Kind
- type MutationSpec
- type OpenOptions
- type Operation
- type OperationalState
- type PageCacheStats
- type QueryDelta
- type QueryDeltaOperation
- type QueryDeltaOperationKind
- type QueryDeltaSubscription
- type QueryLimits
- type QueryOptions
- type QueryReplaySource
- type QueryReplaySubscription
- type QuerySnapshot
- type QuerySpec
- func (q QuerySpec) Capped(max int) QuerySpec
- func (q QuerySpec) Constrain(policy QuerySpec) QuerySpec
- func (q QuerySpec) Execute(documents []Document) []Document
- func (q QuerySpec) HasModifiers() bool
- func (q QuerySpec) Limit() (int, bool)
- func (q QuerySpec) Match(document Document) bool
- func (q QuerySpec) Paths() []string
- func (q QuerySpec) Skip() int
- func (q QuerySpec) Sort() []SortField
- type QueryStats
- type QuerySubscription
- type RealtimeStats
- type ReclaimV2Options
- type ReclaimV2Result
- type ReclamationStats
- type RecoveryMode
- type RecoveryReport
- type ResourceLimits
- type ResourceStats
- type SortField
- type StorageFormat
- type StorageFormatInfo
- type StorageStats
- type Update
- type UpdateResult
- type V1CheckpointPolicy
- type V1Options
- type V2CommitRetentionPolicy
- type V2DestinationOptions
- type V2Maintenance
- type V2MaintenanceOptions
- type V2MaintenanceStats
- type V2Options
- type V2StorageLimits
- type V2VerificationReport
- type Value
- func Array(v ...Value) Value
- func Binary(v []byte) Value
- func Bool(v bool) Value
- func Float(v float64) Value
- func ID(v DocumentID) Value
- func Int(v int64) Value
- func Null() Value
- func Object(v Document) Value
- func String(v string) Value
- func Time(v time.Time) Value
- func UnmarshalWireValue(data []byte, limits QueryLimits) (Value, error)
- func ValueOf(x any) (Value, error)
- func (v Value) ArrayValue() ([]Value, bool)
- func (v Value) BinaryValue() ([]byte, bool)
- func (v Value) Bool() (bool, bool)
- func (v Value) Clone() Value
- func (v Value) Equal(other Value) bool
- func (v Value) Float64() (float64, bool)
- func (v Value) IDValue() (DocumentID, bool)
- func (v Value) Int64() (int64, bool)
- func (v Value) Kind() Kind
- func (v Value) ObjectValue() (Document, bool)
- func (v Value) StringValue() (string, bool)
- func (v Value) TimeValue() (time.Time, bool)
- type WriteTransaction
- func (tx *WriteTransaction) DeleteOne(collection string, id DocumentID) error
- func (tx *WriteTransaction) GetOne(collection string, id DocumentID) (Document, error)
- func (tx *WriteTransaction) InsertOne(collection string, document Document) (DocumentID, error)
- func (tx *WriteTransaction) MeldbaseStageSystemMutation(mutation systemrecord.Mutation, onCommit func(uint64)) error
- func (tx *WriteTransaction) ReplaceOne(collection string, id DocumentID, document Document) error
- func (tx *WriteTransaction) UpdateOne(collection string, id DocumentID, mutation MutationSpec) error
- type WriteTransactionStats
Constants ¶
const ( IndexBuildPhaseScan IndexBuildPhase = "scan" IndexBuildPhaseCatchUp IndexBuildPhase = "catch_up" IndexBuildPhaseReady IndexBuildPhase = "ready" IndexBuildPhaseFailed IndexBuildPhase = "failed" IndexBuildFailureNone IndexBuildFailure = "" IndexBuildFailureUniqueConflict IndexBuildFailure = "unique_conflict" IndexBuildFailureResourceLimit IndexBuildFailure = "resource_limit" IndexBuildFailureHistoryLost IndexBuildFailure = "history_lost" IndexBuildFailureCanceled IndexBuildFailure = "canceled" IndexBuildFailureInvalidIndex IndexBuildFailure = "invalid_index" )
const ( V2PageSize uint64 = 16 << 10 DefaultV2MaxFileBytes uint64 = 8 << 30 )
const ( DefaultV2CommitRetentionMaxCommits uint64 = 10_000 DefaultV2CommitRetentionMaxBytes uint64 = 256 << 20 )
Variables ¶
var ( ErrClosed = errors.New("meldbase: database is closed") ErrInvalidDocument = errors.New("meldbase: invalid document") ErrInvalidFilter = errors.New("meldbase: invalid filter") ErrInvalidUpdate = errors.New("meldbase: invalid update") ErrMutationLimit = errors.New("meldbase: mutation affected-row limit exceeded") ErrWriteConflict = errors.New("meldbase: write transaction snapshot conflicted") ErrWriteTransactionUnsupported = errors.New("meldbase: write transactions require storage V2") ErrNotFound = errors.New("meldbase: document not found") ErrDuplicateID = errors.New("meldbase: duplicate document id") ErrInvalidCollection = errors.New("meldbase: invalid collection") ErrImmutableID = errors.New("meldbase: _id is immutable") ErrSlowConsumer = errors.New("meldbase: change consumer is too slow") ErrCorrupt = errors.New("meldbase: corrupt database") ErrUnsupportedFormat = errors.New("meldbase: unsupported storage format or required feature") ErrDuplicateKey = errors.New("meldbase: duplicate index key") ErrInvalidIndex = errors.New("meldbase: invalid index") ErrCompoundIndexUnsupported = errors.New("meldbase: compound or descending indexes require storage V2 or memory") ErrDurability = errors.New("meldbase: durability failure; writes are disabled") ErrInvalidDelta = errors.New("meldbase: invalid query delta") ErrHistoryLost = errors.New("meldbase: requested history is no longer retained") ErrMigrationUnsupported = errors.New("meldbase: migration requires an open V1 durable database") ErrMigrationDestinationExists = errors.New("meldbase: migration destination already exists") ErrCompactionUnsupported = errors.New("meldbase: compaction requires an open V2 database") ErrCompactionDestinationExists = errors.New("meldbase: compaction destination already exists") ErrReclamationUnsupported = errors.New("meldbase: page reclamation requires an open V2 database") ErrInvalidReclamationOptions = errors.New("meldbase: invalid reclamation options") ErrReclamationConflict = errors.New("meldbase: online reclamation conflicted with concurrent writes") ErrBackupUnsupported = errors.New("meldbase: physical backup requires an open V2 database") ErrBackupDestinationExists = errors.New("meldbase: backup destination already exists or is the source") ErrVerificationUnsupported = errors.New("meldbase: verification requires an existing V2 database") ErrDatabaseLocked = errors.New("meldbase: database is locked by another process") ErrRecoveryRequired = errors.New("meldbase: startup recovery required by the selected policy") ErrInvalidResourceLimits = errors.New("meldbase: invalid resource limits") ErrResourceLimit = errors.New("meldbase: resource limit exceeded") ErrIndexBuildUnsupported = errors.New("meldbase: resumable index builds require storage V2") ErrIndexBuildNotFound = errors.New("meldbase: index build not found") ErrIndexBuildExists = errors.New("meldbase: index build already exists") ErrIndexBuildFailed = errors.New("meldbase: index build is in a terminal failed state") ErrInvalidIndexBuildSchedulerOptions = errors.New("meldbase: invalid index build scheduler options") ErrIndexBuildSchedulerRunning = errors.New("meldbase: index build scheduler already running") )
var DefaultQueryLimits = QueryLimits{
MaxWireBytes: 1 << 20, MaxDepth: 16, MaxNodes: 128,
MaxArrayItems: 256, MaxValueBytes: 16_384, MaxSortFields: 4,
MaxLimit: 10_000,
}
var (
ErrDiagnosticsActive = errors.New("meldbase: diagnostics are already active")
)
Functions ¶
func MarshalQuerySpecJSON ¶
MarshalQuerySpecJSON emits the canonical, data-only wire representation used for transport fingerprints and cross-language conformance.
func MarshalWireDocument ¶
func MarshalWireValue ¶
func ValidateStrictJSON ¶
ValidateStrictJSON rejects oversized, trailing, deeply nested, and duplicate-key JSON before a transport decodes it into structs or maps.
Types ¶
type BackupStats ¶
type BackupV2Result ¶
type Change ¶
type Change struct {
Collection string
Operation Operation
DocumentID DocumentID
Before *Document
After *Document
Index *IndexDefinition
}
type ChangeBatch ¶
type Collection ¶
type Collection struct {
// contains filtered or unexported fields
}
func (*Collection) CreateIndex ¶
func (c *Collection) CreateIndex(ctx context.Context, name string, fields []IndexField, options IndexOptions) error
func (*Collection) CreateIndexOnline ¶
func (c *Collection) CreateIndexOnline(ctx context.Context, name string, fields []IndexField, options IndexOptions) (IndexBuildID, error)
CreateIndexOnline starts and runs one durable build to publication. A context cancellation leaves the returned build discoverable through IndexBuilds; use StartIndexBuild when the ID must be known before execution.
func (*Collection) DeleteMany ¶
func (c *Collection) DeleteMany(ctx context.Context, filter Filter) (DeleteResult, error)
func (*Collection) DeleteManyQuery ¶
func (c *Collection) DeleteManyQuery(ctx context.Context, query QuerySpec) (DeleteResult, error)
func (*Collection) DeleteManyQueryLimited ¶
func (c *Collection) DeleteManyQueryLimited(ctx context.Context, query QuerySpec, maxAffected int) (DeleteResult, error)
DeleteManyQueryLimited atomically rejects the whole mutation when more than maxAffected documents match.
func (*Collection) DeleteOne ¶
func (c *Collection) DeleteOne(ctx context.Context, filter Filter) (DeleteResult, error)
func (*Collection) DeleteOneQuery ¶
func (c *Collection) DeleteOneQuery(ctx context.Context, query QuerySpec) (DeleteResult, error)
func (*Collection) Explain ¶
func (c *Collection) Explain(ctx context.Context, filter Filter) (ExplainResult, error)
func (*Collection) Find ¶
func (c *Collection) Find(ctx context.Context, filter Filter, options ...QueryOptions) (*Cursor, error)
func (*Collection) InsertMany ¶
func (c *Collection) InsertMany(ctx context.Context, documents []Document) ([]DocumentID, error)
InsertMany validates IDs, documents, and all unique-index keys before writing one WAL record. Either the entire batch becomes visible or none of it does.
func (*Collection) InsertOne ¶
func (c *Collection) InsertOne(ctx context.Context, document Document) (DocumentID, error)
func (*Collection) SnapshotQuery ¶
func (c *Collection) SnapshotQuery(ctx context.Context, query QuerySpec) (QuerySnapshot, error)
func (*Collection) StartIndexBuild ¶
func (c *Collection) StartIndexBuild(ctx context.Context, name string, fields []IndexField, options IndexOptions) (IndexBuildID, error)
StartIndexBuild creates a durable private shadow index. It is Storage V2 only and does not scan documents or make the index query-visible.
func (*Collection) SubscribeQuery ¶
func (c *Collection) SubscribeQuery(ctx context.Context, query QuerySpec, buffer int) (*QuerySubscription, error)
func (*Collection) SubscribeQueryDeltas ¶
func (c *Collection) SubscribeQueryDeltas(ctx context.Context, query QuerySpec, buffer int) (*QueryDeltaSubscription, error)
func (*Collection) UpdateMany ¶
func (c *Collection) UpdateMany(ctx context.Context, filter Filter, update Update) (UpdateResult, error)
func (*Collection) UpdateManyQuery ¶
func (c *Collection) UpdateManyQuery(ctx context.Context, query QuerySpec, mutation MutationSpec) (UpdateResult, error)
func (*Collection) UpdateManyQueryLimited ¶
func (c *Collection) UpdateManyQueryLimited(ctx context.Context, query QuerySpec, mutation MutationSpec, maxAffected int) (UpdateResult, error)
UpdateManyQueryLimited atomically rejects the whole mutation when more than maxAffected documents match. A non-positive limit is invalid here so callers cannot accidentally disable a server-owned safety bound.
func (*Collection) UpdateOne ¶
func (c *Collection) UpdateOne(ctx context.Context, filter Filter, update Update) (UpdateResult, error)
func (*Collection) UpdateOneQuery ¶
func (c *Collection) UpdateOneQuery(ctx context.Context, query QuerySpec, mutation MutationSpec) (UpdateResult, error)
type CommitStats ¶
type CompactionStats ¶
type Cursor ¶
type Cursor struct {
// contains filtered or unexported fields
}
type DB ¶
type DB struct {
// contains filtered or unexported fields
}
func NewWithOptions ¶
func NewWithOptions(options DatabaseOptions) (*DB, error)
NewWithOptions creates an in-memory database with explicit resource limits.
func Open ¶
Open opens an existing V1 or V2 database after read-only format detection. A missing or zero-length path creates V2, the current default format. It never migrates or rewrites an existing V1 database implicitly.
func OpenV1 ¶
OpenV1 explicitly creates or opens the legacy page-checkpoint plus WAL format. Existing applications normally use Open, which still recognizes V1 without migrating it. New databases should use Open or OpenV2.
func OpenV1WithOptions ¶
OpenV1WithOptions explicitly opens the legacy page-checkpoint plus WAL format with a bounded automatic checkpoint policy.
func OpenV2 ¶
OpenV2 explicitly creates or opens Storage V2. It never interprets or migrates a V1 file. Open performs read-only format selection when callers want to support both generations.
func OpenWithOptions ¶
func OpenWithOptions(path string, options OpenOptions) (*DB, error)
func (*DB) AbortIndexBuild ¶
func (db *DB) AbortIndexBuild(ctx context.Context, id IndexBuildID) error
func (*DB) BackupV2 ¶
func (db *DB) BackupV2(ctx context.Context, destination string) (result BackupV2Result, resultErr error)
BackupV2 writes an exact, verified physical copy to a new path. It preserves database identity and Commit Log history, so the result is a restore artifact rather than an independent writable fork. The source writer is blocked for the copy duration; readers remain available.
func (*DB) CanResumeFrom ¶
func (*DB) Collection ¶
func (db *DB) Collection(name string) *Collection
func (*DB) CompactToV2 ¶
CompactToV2 writes the current logical V2 state into a new, atomically published V2 file. It never overwrites destination or mutates the source. The compacted database deliberately receives a new identity and commit-log history, so callers must treat every old resume token as invalid.
func (*DB) CompactToV2WithOptions ¶
func (db *DB) CompactToV2WithOptions(ctx context.Context, destination string, options V2DestinationOptions) (resultErr error)
CompactToV2WithOptions is CompactToV2 with an explicit destination quota.
func (*DB) DatabaseIdentity ¶
func (*DB) DiagnosticSnapshotAfter ¶
func (db *DB) DiagnosticSnapshotAfter(after uint64, limit int) DiagnosticSnapshot
DiagnosticSnapshotAfter reads the currently active diagnostic session. It allows long-lived admin handlers to follow a safely replaced session.
func (*DB) EnableDiagnostics ¶
func (db *DB) EnableDiagnostics(options DiagnosticsOptions) (*Diagnostics, error)
func (*DB) IndexBuild ¶
func (db *DB) IndexBuild(id IndexBuildID) (IndexBuildStatus, error)
func (*DB) IndexBuilds ¶
func (db *DB) IndexBuilds() ([]IndexBuildStatus, error)
IndexBuilds returns all durable unfinished builds. The result survives a clean close, process crash, and reopen.
func (*DB) MeldbaseSystemRecordBackend ¶
func (db *DB) MeldbaseSystemRecordBackend() systemrecord.Backend
MeldbaseSystemRecordBackend is internal plumbing for first-party packages such as server. Its return type lives under internal/, so it is deliberately unavailable as an application-facing generic key/value API.
func (*DB) MeldbaseSystemWrite ¶
func (db *DB) MeldbaseSystemWrite(ctx context.Context, systemMutation systemrecord.Mutation, build func(*WriteTransaction) ([]byte, error)) (systemrecord.Result, bool, error)
MeldbaseSystemWrite runs build against one immutable V2 snapshot without holding the database writer lock. If build succeeds and its point read set is still valid, its business changes and systemMutation commit in one V2 generation. The bool reports whether a composite commit was attempted; false means build produced no business change or lost optimistic validation.
This method is first-party plumbing: the systemrecord parameter is internal, preventing external applications from using the private keyspace.
func (*DB) MigrateToV2 ¶
MigrateToV2 writes a consistent logical snapshot of an open V1 durable DB to a new V2 file. The source remains open and unchanged. The destination must not exist and is published only after V2 reopen and semantic verification. A successful migration deliberately has a new database identity, invalidating every V1 resume token rather than mapping it onto unrelated V2 commit history.
func (*DB) MigrateToV2WithOptions ¶
func (db *DB) MigrateToV2WithOptions(ctx context.Context, destination string, options V2DestinationOptions) error
MigrateToV2WithOptions is MigrateToV2 with an explicit destination quota.
func (*DB) OpenQueryReplay ¶
func (*DB) OperationalState ¶
func (db *DB) OperationalState() OperationalState
func (*DB) ReclaimV2Pages ¶
func (db *DB) ReclaimV2Pages(ctx context.Context) (result ReclaimV2Result, resultErr error)
ReclaimV2Pages audits both valid Meta roots and every active snapshot/replay lease, then makes only unreachable pages available to future COW commits. The free pool is process-local and safely reconstructed by another call on reopen.
func (*DB) ReclaimV2PagesWithOptions ¶
func (db *DB) ReclaimV2PagesWithOptions(ctx context.Context, options ReclaimV2Options) (result ReclaimV2Result, resultErr error)
ReclaimV2PagesWithOptions runs explicit synchronous or low-pause optimistic reclamation. Online mode is opt-in and may return an error wrapping ErrReclamationConflict when every bounded attempt overlaps a commit.
func (*DB) RecoveryReport ¶
func (db *DB) RecoveryReport() RecoveryReport
RecoveryReport returns the receipt captured by the successful constructor. It performs no I/O and never changes after the DB is opened.
func (*DB) ResourceLimits ¶
func (db *DB) ResourceLimits() ResourceLimits
ResourceLimits returns the immutable normalized limits selected at open.
func (*DB) ResumeIndexBuild ¶
func (db *DB) ResumeIndexBuild(ctx context.Context, id IndexBuildID) error
ResumeIndexBuild scans bounded batches, catches up retained commits, and atomically publishes the index. Only one caller should resume a given build; stale concurrent callers receive ErrWriteConflict from durable CAS checks.
func (*DB) RunWriteTransaction ¶
RunWriteTransaction executes build against one immutable Storage V2 snapshot and atomically publishes all staged point mutations if every document read by the callback still matches. The callback runs without the database writer lock. A conflicting point write returns ErrWriteConflict; callbacks are never retried because they may contain application side effects.
A successful callback with no effective changes is a successful no-op and does not advance the commit sequence. The transaction is invalid as soon as the callback returns. Normal DB and Collection methods must not be called from inside build.
func (*DB) StartIndexBuildScheduler ¶
func (db *DB) StartIndexBuildScheduler(parent context.Context, options IndexBuildSchedulerOptions) (*IndexBuildScheduler, error)
func (*DB) StartV2Maintenance ¶
func (db *DB) StartV2Maintenance(parent context.Context, options V2MaintenanceOptions) (*V2Maintenance, error)
func (*DB) WatchChanges ¶
type DBStats ¶
type DBStats struct {
CapturedAt time.Time `json:"capturedAt"`
StartedAt time.Time `json:"startedAt"`
Uptime time.Duration `json:"uptimeNanos"`
Closed bool `json:"closed"`
WritesDisabled bool `json:"writesDisabled"`
Durable bool `json:"durable"`
CommitSequence uint64 `json:"commitSequence"`
Collections uint64 `json:"collections"`
Documents uint64 `json:"documents"`
Indexes uint64 `json:"indexes"`
ActiveChangeWatchers uint64 `json:"activeChangeWatchers"`
Commits CommitStats `json:"commits"`
Transactions WriteTransactionStats `json:"writeTransactions"`
Queries QueryStats `json:"queries"`
Realtime RealtimeStats `json:"realtime"`
Durability DurabilityStats `json:"durability"`
Storage StorageStats `json:"storage"`
Compaction CompactionStats `json:"compaction"`
Reclamation ReclamationStats `json:"reclamation"`
Backup BackupStats `json:"backup"`
Diagnostics DiagnosticStats `json:"diagnostics"`
Recovery RecoveryReport `json:"recovery"`
Resources ResourceStats `json:"resources"`
IndexBuilds IndexBuildStats `json:"indexBuilds"`
}
DBStats is a point-in-time, allocation-bounded view of database health. Counters are process-lifetime values and reset when the database is reopened. Persistent state such as CommitSequence is read from the database itself.
Stats deliberately exposes no user values, document IDs, query parameters, or callbacks. It is safe for an admin sampler to call periodically, but it is not intended to be called on every database operation.
type DatabaseOptions ¶
type DatabaseOptions struct{ ResourceLimits ResourceLimits }
DatabaseOptions configures an in-memory database.
type DeleteResult ¶
type DeleteResult struct{ DeletedCount int64 }
type DiagnosticEvent ¶
type DiagnosticEvent struct {
Sequence uint64 `json:"sequence"`
CapturedAt time.Time `json:"capturedAt"`
Kind DiagnosticKind `json:"kind"`
Outcome DiagnosticOutcome `json:"outcome"`
ErrorClass string `json:"errorClass,omitempty"`
Stage string `json:"stage,omitempty"`
Duration time.Duration `json:"durationNanos"`
DocumentsExamined uint64 `json:"documentsExamined,omitempty"`
DocumentsReturned uint64 `json:"documentsReturned,omitempty"`
Changes uint64 `json:"changes,omitempty"`
Slow bool `json:"slow"`
Sampled bool `json:"sampled"`
}
type DiagnosticKind ¶
type DiagnosticKind string
const ( DiagnosticQuery DiagnosticKind = "query" DiagnosticCommit DiagnosticKind = "commit" )
type DiagnosticOutcome ¶
type DiagnosticOutcome string
const ( DiagnosticSuccess DiagnosticOutcome = "success" DiagnosticFailure DiagnosticOutcome = "failure" DiagnosticCanceled DiagnosticOutcome = "canceled" )
type DiagnosticSnapshot ¶
type DiagnosticSnapshot struct {
Version uint32 `json:"version"`
Session uint64 `json:"session"`
StartedAt time.Time `json:"startedAt"`
CapturedAt time.Time `json:"capturedAt"`
Stats DiagnosticStats `json:"stats"`
Events []DiagnosticEvent `json:"events"`
Truncated bool `json:"truncated"`
HasMore bool `json:"hasMore"`
}
type DiagnosticStats ¶
type Diagnostics ¶
type Diagnostics struct {
// contains filtered or unexported fields
}
Diagnostics owns a fixed-capacity event ring. Close disables future timing and recording but keeps the retained snapshot readable by its owner.
func (*Diagnostics) Close ¶
func (d *Diagnostics) Close() error
func (*Diagnostics) DiagnosticSnapshotAfter ¶
func (d *Diagnostics) DiagnosticSnapshotAfter(after uint64, limit int) DiagnosticSnapshot
DiagnosticSnapshotAfter lets a fixed Diagnostics handle also satisfy admin diagnostic-source contracts.
func (*Diagnostics) Snapshot ¶
func (d *Diagnostics) Snapshot() DiagnosticSnapshot
func (*Diagnostics) SnapshotAfter ¶
func (d *Diagnostics) SnapshotAfter(after uint64, limit int) DiagnosticSnapshot
SnapshotAfter returns retained events with sequence greater than after in chronological order. A non-positive limit means the ring capacity. Truncated reports that after predates the oldest retained sequence; HasMore asks the caller to continue from the last returned sequence.
func (*Diagnostics) Stats ¶
func (d *Diagnostics) Stats() DiagnosticStats
type DiagnosticsOptions ¶
type DiagnosticsOptions struct {
Capacity int
SlowQueryThreshold time.Duration
SlowCommitThreshold time.Duration
SampleEvery uint64
RecordAll bool
ExcludeFailures bool
}
DiagnosticsOptions controls opt-in detailed events. Defaults retain 256 events and record failed, >=50ms queries and >=100ms durable commits. Setting RecordAll is intended only for short development sessions. SampleEvery adds a deterministic one-in-N sample of otherwise fast successful operations.
type Document ¶
func UnmarshalWireDocument ¶
func UnmarshalWireDocument(data []byte, limits QueryLimits) (Document, error)
func UnmarshalWireInputDocument ¶
func UnmarshalWireInputDocument(data []byte, limits QueryLimits) (Document, error)
func (Document) ID ¶
func (d Document) ID() (DocumentID, bool)
type DocumentCacheStats ¶
type DocumentID ¶
type DocumentID [16]byte
func NewDocumentID ¶
func NewDocumentID() (DocumentID, error)
func ParseDocumentID ¶
func ParseDocumentID(s string) (DocumentID, error)
func (DocumentID) IsZero ¶
func (id DocumentID) IsZero() bool
func (DocumentID) String ¶
func (id DocumentID) String() string
type DurabilityStats ¶
type DurabilityStats struct {
WALAppends uint64 `json:"walAppends"`
WALPayloadBytes uint64 `json:"walPayloadBytes"`
WALCurrentBytes uint64 `json:"walCurrentBytes"`
WALCurrentCommits uint64 `json:"walCurrentCommits"`
WALAppendFailures uint64 `json:"walAppendFailures"`
WALAppendNanos uint64 `json:"walAppendNanos"`
WALAppendMaxLatency time.Duration `json:"walAppendMaxLatencyNanos"`
CheckpointAttempts uint64 `json:"checkpointAttempts"`
CheckpointsCompleted uint64 `json:"checkpointsCompleted"`
CheckpointFailures uint64 `json:"checkpointFailures"`
AutomaticCheckpoints uint64 `json:"automaticCheckpoints"`
CheckpointNanos uint64 `json:"checkpointNanos"`
CheckpointMaxLatency time.Duration `json:"checkpointMaxLatencyNanos"`
}
type ExplainResult ¶
type IndexBuildFailure ¶
type IndexBuildFailure string
type IndexBuildID ¶
type IndexBuildID [16]byte
IndexBuildID identifies one durable, resumable Storage V2 index build.
func ParseIndexBuildID ¶
func ParseIndexBuildID(value string) (IndexBuildID, error)
func (IndexBuildID) IsZero ¶
func (id IndexBuildID) IsZero() bool
func (IndexBuildID) MarshalText ¶
func (id IndexBuildID) MarshalText() ([]byte, error)
func (IndexBuildID) String ¶
func (id IndexBuildID) String() string
func (*IndexBuildID) UnmarshalText ¶
func (id *IndexBuildID) UnmarshalText(value []byte) error
type IndexBuildPhase ¶
type IndexBuildPhase string
type IndexBuildScheduler ¶
type IndexBuildScheduler struct {
// contains filtered or unexported fields
}
func (*IndexBuildScheduler) Done ¶
func (scheduler *IndexBuildScheduler) Done() <-chan struct{}
func (*IndexBuildScheduler) Stats ¶
func (scheduler *IndexBuildScheduler) Stats() IndexBuildSchedulerStats
func (*IndexBuildScheduler) Stop ¶
func (scheduler *IndexBuildScheduler) Stop()
type IndexBuildSchedulerOptions ¶
type IndexBuildSchedulerOptions struct {
PollInterval time.Duration
RunTimeout time.Duration
MaxConcurrency int
RunImmediately bool
}
IndexBuildSchedulerOptions configures an explicit default-off runner. Each task receives a bounded time quantum, then yields durable progress so CRUD and other builds can proceed between quanta.
type IndexBuildSchedulerStats ¶
type IndexBuildSchedulerStats struct {
Polls uint64 `json:"polls"`
Runs uint64 `json:"runs"`
Completed uint64 `json:"completed"`
Yielded uint64 `json:"yielded"`
MarkedFailed uint64 `json:"markedFailed"`
Conflicts uint64 `json:"conflicts"`
Failed uint64 `json:"failed"`
Active uint64 `json:"active"`
LastDuration time.Duration `json:"lastDurationNanos"`
LastError string `json:"lastError,omitempty"`
}
type IndexBuildStats ¶
type IndexBuildStats struct {
Active uint64 `json:"active"`
Persistent uint64 `json:"persistent"`
Scanning uint64 `json:"scanning"`
CatchingUp uint64 `json:"catchingUp"`
Ready uint64 `json:"ready"`
PersistentFailed uint64 `json:"persistentFailed"`
RetentionLeaseActive bool `json:"retentionLeaseActive"`
RetentionPressure bool `json:"retentionPressure"`
PersistentEntries uint64 `json:"persistentEntries"`
PersistentBytes uint64 `json:"persistentBytes"`
SchedulerRuns uint64 `json:"schedulerRuns"`
SchedulerYields uint64 `json:"schedulerYields"`
SchedulerFailures uint64 `json:"schedulerFailures"`
Attempts uint64 `json:"attempts"`
Completed uint64 `json:"completed"`
Failed uint64 `json:"failed"`
Retries uint64 `json:"retries"`
Conflicts uint64 `json:"conflicts"`
LastEntries uint64 `json:"lastEntries"`
LastBytes uint64 `json:"lastBytes"`
LastDuration time.Duration `json:"lastDurationNanos"`
MaxDuration time.Duration `json:"maxDurationNanos"`
// contains filtered or unexported fields
}
type IndexBuildStatus ¶
type IndexBuildStatus struct {
ID IndexBuildID `json:"id"`
Collection string `json:"collection"`
Name string `json:"name"`
Field string `json:"field"`
Fields []IndexField `json:"fields"`
Unique bool `json:"unique"`
Phase IndexBuildPhase `json:"phase"`
Failure IndexBuildFailure `json:"failure,omitempty"`
SourceSequence uint64 `json:"sourceSequence"`
AppliedSequence uint64 `json:"appliedSequence"`
EntryCount uint64 `json:"entryCount"`
CanonicalBytes uint64 `json:"canonicalBytes"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
IndexBuildStatus is durable progress. EntryCount and CanonicalBytes describe the current private Secondary tree, not transient Go heap usage.
type IndexDefinition ¶
type IndexDefinition struct {
Name, Field string
Order int
Unique bool
// Fields is the ordered definition for compound/descending indexes. Field
// and Order remain the compatibility mirror of Fields[0] for V1 records and
// existing callers; new code must use indexDefinitionFields.
Fields []IndexField
}
type IndexField ¶
IndexField is one ordered component of an index definition. Order must be 1 (ascending) or -1 (descending); fields are evaluated left to right.
type IndexOptions ¶
type IndexOptions struct{ Unique bool }
IndexOptions controls complete-tuple uniqueness.
type MutationSpec ¶
type MutationSpec struct {
// contains filtered or unexported fields
}
func CompileUpdate ¶
func CompileUpdate(update Update) (MutationSpec, error)
func DecodeMutationSpecJSON ¶
func DecodeMutationSpecJSON(data []byte, limits QueryLimits) (MutationSpec, error)
func (MutationSpec) Paths ¶
func (m MutationSpec) Paths() []string
type OpenOptions ¶
type OpenOptions struct {
Recovery RecoveryMode
V1Checkpoint V1CheckpointPolicy
V2CommitRetention V2CommitRetentionPolicy
ResourceLimits ResourceLimits
V2StorageLimits V2StorageLimits
}
OpenOptions configures format-neutral Open. V1Checkpoint is ignored for V2; V2 retention/storage fields are ignored for V1.
type OperationalState ¶
OperationalState is a minimal, allocation-free serving-state snapshot. A fail-stop durability error preserves reads from the last committed state but disables writes; a closed database is neither readable nor writable.
type PageCacheStats ¶
type QueryDelta ¶
type QueryDelta struct {
FromToken uint64
Token uint64
Operations []QueryDeltaOperation
}
QueryDelta transforms exactly FromToken into Token. Operations are ordered: removals first, followed by reverse-order add/move anchors and document changes. Applying them in slice order is deterministic.
type QueryDeltaOperation ¶
type QueryDeltaOperation struct {
Kind QueryDeltaOperationKind
DocumentID DocumentID
BeforeID DocumentID
Document Document
}
QueryDeltaOperation mutates an ordered query result. A zero BeforeID means the end of the result; database document IDs are never zero.
type QueryDeltaOperationKind ¶
type QueryDeltaOperationKind string
const ( QueryDeltaRemove QueryDeltaOperationKind = "remove" QueryDeltaAdd QueryDeltaOperationKind = "add_before" QueryDeltaMove QueryDeltaOperationKind = "move_before" QueryDeltaChange QueryDeltaOperationKind = "change" )
type QueryDeltaSubscription ¶
type QueryDeltaSubscription struct {
Initial QuerySnapshot
Deltas <-chan QueryDelta
Errors <-chan error
// contains filtered or unexported fields
}
QueryDeltaSubscription returns one safe initial snapshot and then ordered deltas. It is the preferred core stream for transports and reactive clients; QuerySubscription remains the full-snapshot compatibility adapter.
func (*QueryDeltaSubscription) Close ¶
func (s *QueryDeltaSubscription) Close()
type QueryLimits ¶
type QueryOptions ¶
type QueryReplaySource ¶
type QueryReplaySource interface {
OpenQueryReplay(ctx context.Context, collection string, query QuerySpec, afterToken uint64, buffer int) (*QueryReplaySubscription, error)
}
QueryReplaySource atomically reconstructs a query at afterToken and tails later ordered revisions. Initial.Token must equal afterToken. Implementations return ErrHistoryLost when retention can no longer satisfy that contract.
type QueryReplaySubscription ¶
type QueryReplaySubscription struct {
Initial QuerySnapshot
Deltas <-chan QueryDelta
Errors <-chan error
// contains filtered or unexported fields
}
func (*QueryReplaySubscription) Close ¶
func (subscription *QueryReplaySubscription) Close()
type QuerySnapshot ¶
func ApplyQueryDelta ¶
func ApplyQueryDelta(snapshot QuerySnapshot, delta QueryDelta) (QuerySnapshot, error)
ApplyQueryDelta strictly validates and applies an ordered delta without mutating the input snapshot.
type QuerySpec ¶
type QuerySpec struct {
// contains filtered or unexported fields
}
func CompileQuery ¶
func CompileQuery(filter Filter, options QueryOptions) (QuerySpec, error)
func DecodeQuerySpecJSON ¶
func DecodeQuerySpecJSON(data []byte, limits QueryLimits) (QuerySpec, error)
func (QuerySpec) Constrain ¶
Constrain applies a server-owned row predicate before the caller's sort and pagination. This is the safe composition point for authorization policies.
func (QuerySpec) HasModifiers ¶
type QueryStats ¶
type QueryStats struct {
ActiveCursors uint64 `json:"activeCursors"`
Total uint64 `json:"total"`
Failed uint64 `json:"failed"`
CollectionScans uint64 `json:"collectionScans"`
IndexScans uint64 `json:"indexScans"`
IDLookups uint64 `json:"idLookups"`
DocumentsExamined uint64 `json:"documentsExamined"`
DocumentsReturned uint64 `json:"documentsReturned"`
}
type QuerySubscription ¶
type QuerySubscription struct {
Snapshots <-chan QuerySnapshot
Errors <-chan error
// contains filtered or unexported fields
}
func (*QuerySubscription) Close ¶
func (s *QuerySubscription) Close()
type RealtimeStats ¶
type RealtimeStats struct {
QuerySubscribers uint64 `json:"querySubscribers"`
IncrementalBatches uint64 `json:"incrementalBatches"`
IncrementalViewUpdates uint64 `json:"incrementalViewUpdates"`
FullViewRecomputes uint64 `json:"fullViewRecomputes"`
QueueOverflows uint64 `json:"queueOverflows"`
PendingBatches uint64 `json:"pendingBatches"`
PendingChanges uint64 `json:"pendingChanges"`
PendingBatchCapacity uint64 `json:"pendingBatchCapacity"`
PendingChangeCapacity uint64 `json:"pendingChangeCapacity"`
DeltaDeliveries uint64 `json:"deltaDeliveries"`
DeltaOperations uint64 `json:"deltaOperations"`
PublishedBatches uint64 `json:"publishedBatches"`
PublishedChanges uint64 `json:"publishedChanges"`
WatcherDeliveries uint64 `json:"watcherDeliveries"`
InitialSnapshots uint64 `json:"initialSnapshots"`
QueryRecomputes uint64 `json:"queryRecomputes"`
SnapshotsEmitted uint64 `json:"snapshotsEmitted"`
DocumentsEmitted uint64 `json:"documentsEmitted"`
SlowConsumers uint64 `json:"slowConsumers"`
}
type ReclaimV2Options ¶
type ReclaimV2Options struct {
Online bool
MaxAttempts int
// MemoryOnly skips the physical FreeSpace maintenance generation. It keeps
// the final installation pause O(1), but another audit is needed after reopen.
MemoryOnly bool
}
ReclaimV2Options controls explicit page reclamation. Online scans a duplicate read handle without holding the storage writer lock and installs its result only if the Meta generation is unchanged. MaxAttempts bounds complete graph rescans after concurrent commits; zero selects three attempts.
type ReclaimV2Result ¶
type ReclamationStats ¶
type ReclamationStats struct {
Active uint64 `json:"active"`
Attempts uint64 `json:"attempts"`
Scans uint64 `json:"scans"`
Conflicts uint64 `json:"conflicts"`
Completed uint64 `json:"completed"`
Failed uint64 `json:"failed"`
LastAttempts uint64 `json:"lastAttempts"`
LastOnline bool `json:"lastOnline"`
LastReachable uint64 `json:"lastReachable"`
LastReclaimable uint64 `json:"lastReclaimable"`
LastDuration time.Duration `json:"lastDurationNanos"`
}
type RecoveryMode ¶
type RecoveryMode uint8
RecoveryMode controls whether Open may perform only the bounded recovery actions described by RecoveryReport. Zero selects the normal automatic mode.
const ( RecoveryAutomatic RecoveryMode = iota RecoveryRequireClean )
type RecoveryReport ¶
type RecoveryReport struct {
SchemaVersion int `json:"schemaVersion"`
Engine string `json:"engine"`
Created bool `json:"created"`
Recovered bool `json:"recovered"`
CommitSequenceBefore uint64 `json:"commitSequenceBefore"`
CommitSequenceAfter uint64 `json:"commitSequenceAfter"`
SelectedMetaSlot uint8 `json:"selectedMetaSlot"`
ChecksumValidMetaSlots uint8 `json:"checksumValidMetaSlots"`
RootValidMetaSlots uint8 `json:"rootValidMetaSlots"`
MetaRedundancyDegraded bool `json:"metaRedundancyDegraded"`
FallbackToOlderRoot bool `json:"fallbackToOlderRoot"`
MainTailBytesRemoved uint64 `json:"mainTailBytesRemoved"`
WALRecordsReplayed uint64 `json:"walRecordsReplayed"`
WALTailBytesRemoved uint64 `json:"walTailBytesRemoved"`
AccelerationDegraded bool `json:"accelerationDegraded"`
}
RecoveryReport is an immutable, non-sensitive receipt for decisions made while opening a database. It reports only actions that were completed before Open returned successfully; corruption and unsupported formats still fail Open instead of being described as recovered.
type ResourceLimits ¶
type ResourceLimits struct {
MaxDocumentBytes uint64 `json:"maxDocumentBytes"`
MaxTransactionBytes uint64 `json:"maxTransactionBytes"`
MaxTransactionChanges uint64 `json:"maxTransactionChanges"`
MaxIndexBuildEntries uint64 `json:"maxIndexBuildEntries"`
MaxIndexBuildBytes uint64 `json:"maxIndexBuildBytes"`
}
ResourceLimits bounds work admitted by write and index-maintenance APIs. Zero values select production defaults; limits cannot be disabled accidentally. Byte limits use the canonical typed binary representation, independent of Go heap layout, JSON spelling, storage generation, or transport compression.
type ResourceStats ¶
type ResourceStats struct {
Limits ResourceLimits `json:"limits"`
Rejections uint64 `json:"rejections"`
}
type StorageFormat ¶
type StorageFormat string
StorageFormat identifies the on-disk engine family without opening or mutating the database. Unknown denotes a missing or zero-length path, not an unrecognized non-empty file.
const ( StorageFormatUnknown StorageFormat = "" StorageFormatV1 StorageFormat = "v1" StorageFormatV2 StorageFormat = "v2" )
func DetectStorageFormat ¶
func DetectStorageFormat(path string) (StorageFormat, error)
DetectStorageFormat reads only the two fixed meta-page magic fields. The selected engine remains responsible for checksums and complete validation. A non-empty unknown or mixed-family file fails closed as ErrCorrupt.
type StorageFormatInfo ¶
type StorageFormatInfo struct {
Format StorageFormat `json:"format"`
Revision uint16 `json:"revision"`
Generation uint64 `json:"generation"`
CommitSequence uint64 `json:"commitSequence"`
PhysicalPageCount uint64 `json:"physicalPageCount,omitempty"`
RequiredFeatures uint64 `json:"requiredFeatures"`
OptionalFeatures uint64 `json:"optionalFeatures"`
DatabaseIDHex string `json:"databaseIdHex,omitempty"`
ValidMetaSlots int `json:"validMetaSlots"`
ReaderCompatible bool `json:"readerCompatible"`
}
StorageFormatInfo is a read-only negotiation view, not a full graph audit. ReaderCompatible says this binary understands the reported revision and all required feature bits; callers must still Open the database before use.
func InspectStorageFormat ¶
func InspectStorageFormat(path string) (StorageFormatInfo, error)
InspectStorageFormat validates stable Meta checksums and reports the newest negotiation envelope without locking, opening, migrating, or mutating the database. For checksum-valid future V2 revisions it still reports revision and feature bits while ReaderCompatible is false.
type StorageStats ¶
type StorageStats struct {
Engine string `json:"engine"`
PageSize uint64 `json:"pageSize"`
PhysicalPages uint64 `json:"physicalPages"`
CommitSequence uint64 `json:"commitSequence"`
OldestRetainedSequence uint64 `json:"oldestRetainedSequence"`
RetainedCommits uint64 `json:"retainedCommits"`
CommitRetentionMax uint64 `json:"commitRetentionMax"`
CommitRetentionOverage uint64 `json:"commitRetentionOverage"`
RetainedCommitBytes uint64 `json:"retainedCommitBytes"`
CommitRetentionMaxBytes uint64 `json:"commitRetentionMaxBytes"`
CommitRetentionByteOverage uint64 `json:"commitRetentionByteOverage"`
RetentionPrunedCommits uint64 `json:"retentionPrunedCommits"`
RetentionPressureEvents uint64 `json:"retentionPressureEvents"`
RetentionPressure bool `json:"retentionPressure"`
StorageUsedBytes uint64 `json:"storageUsedBytes"`
StorageMaxBytes uint64 `json:"storageMaxBytes"`
StorageByteOverage uint64 `json:"storageByteOverage"`
StorageLimitRejections uint64 `json:"storageLimitRejections"`
StorageQuotaExhausted bool `json:"storageQuotaExhausted"`
ActiveReaders uint64 `json:"activeReaders"`
ActiveReplayLeases uint64 `json:"activeReplayLeases"`
Documents uint64 `json:"documents"`
Collections uint64 `json:"collections"`
ReusablePages uint64 `json:"reusablePages"`
TreeSplits uint64 `json:"treeSplits"`
TreeMerges uint64 `json:"treeMerges"`
PersistentFreeSpace bool `json:"persistentFreeSpace"`
FreeSpaceLoads uint64 `json:"freeSpaceLoads"`
FreeSpaceLoadFailures uint64 `json:"freeSpaceLoadFailures"`
FreeSpacePublishes uint64 `json:"freeSpacePublishes"`
FreeSpaceCandidateChecks uint64 `json:"freeSpaceCandidateChecks"`
PageCache PageCacheStats `json:"pageCache"`
DocumentCache DocumentCacheStats `json:"documentCache"`
CommitAttempts uint64 `json:"commitAttempts"`
CommittedTransactions uint64 `json:"committedTransactions"`
RejectedTransactions uint64 `json:"rejectedTransactions"`
CommitNanos uint64 `json:"commitNanos"`
CommitMaxLatency time.Duration `json:"commitMaxLatencyNanos"`
}
StorageStats describes the selected physical backend. Session counters reset on reopen; physical state and cache counters come from the backend itself.
type UpdateResult ¶
type UpdateResult struct{ MatchedCount, ModifiedCount int64 }
type V1CheckpointPolicy ¶
V1CheckpointPolicy bounds the legacy sidecar WAL. Either enabled threshold triggers a synchronous physical checkpoint after the triggering logical commit is already durable. Zero values select production defaults.
type V1Options ¶
type V1Options struct {
Checkpoint V1CheckpointPolicy
Recovery RecoveryMode
ResourceLimits ResourceLimits
}
V1Options configures the explicitly selected legacy V1 storage engine. Storage V2 does not use this policy because every V2 commit publishes a COW database root and inactive Meta page atomically.
type V2CommitRetentionPolicy ¶
V2CommitRetentionPolicy bounds logical Commit Log history by both commit count and canonical encoded bytes. Zero fields select production defaults. Active replay leases may temporarily exceed either budget rather than losing history under a reader.
type V2DestinationOptions ¶
type V2DestinationOptions struct {
StorageLimits V2StorageLimits
ResourceLimits ResourceLimits
}
V2DestinationOptions configures newly written migration or compaction files. ResourceLimits govern transient index construction as well as the reopened destination handle; zero fields select production defaults.
type V2Maintenance ¶
type V2Maintenance struct {
// contains filtered or unexported fields
}
V2Maintenance owns one background reclamation loop. Stop is idempotent and waits for an active scan to observe cancellation. Closing the DB also stops the loop through the DB lifecycle channel.
func (*V2Maintenance) Done ¶
func (maintenance *V2Maintenance) Done() <-chan struct{}
func (*V2Maintenance) Stats ¶
func (maintenance *V2Maintenance) Stats() V2MaintenanceStats
func (*V2Maintenance) Stop ¶
func (maintenance *V2Maintenance) Stop()
type V2MaintenanceOptions ¶
type V2MaintenanceOptions struct {
Interval time.Duration
Timeout time.Duration
MaxAttempts int
RunImmediately bool
// PersistFreeSpace opts into a physical maintenance generation after each
// successful scan. The default memory-only mode minimizes writer pauses.
PersistFreeSpace bool
}
V2MaintenanceOptions configures an explicit default-off maintenance loop. Every run uses online optimistic reclamation; runs never overlap.
type V2MaintenanceStats ¶
type V2Options ¶
type V2Options struct {
Recovery RecoveryMode
CommitRetention V2CommitRetentionPolicy
ResourceLimits ResourceLimits
StorageLimits V2StorageLimits
}
V2Options configures explicitly selected Storage V2 opening.
type V2StorageLimits ¶
type V2StorageLimits struct{ MaxFileBytes uint64 }
V2StorageLimits bounds the physical single-file high-water mark. Zero selects DefaultV2MaxFileBytes. The value must be a 16 KiB V2 page multiple.
type V2VerificationReport ¶
type V2VerificationReport struct {
SchemaVersion int `json:"schemaVersion"`
Verified bool `json:"verified"`
Format StorageFormat `json:"format"`
Revision uint16 `json:"revision"`
DatabaseIDHex string `json:"databaseIdHex"`
MetaGeneration uint64 `json:"metaGeneration"`
CommitSequence uint64 `json:"commitSequence"`
OldestRetainedSequence uint64 `json:"oldestRetainedSequence"`
RequiredFeatures uint64 `json:"requiredFeatures"`
OptionalFeatures uint64 `json:"optionalFeatures"`
ValidMetaSlots int `json:"validMetaSlots"`
FileBytes uint64 `json:"fileBytes"`
TrailingBytes uint64 `json:"trailingBytes"`
PhysicalPages uint64 `json:"physicalPages"`
CommittedPhysicalPages uint64 `json:"committedPhysicalPages"`
ReachablePages uint64 `json:"reachablePages"`
ReclaimablePages uint64 `json:"reclaimablePages"`
PersistentFreeSpace bool `json:"persistentFreeSpace"`
FreeSpaceValid bool `json:"freeSpaceValid"`
IndexContentsVerified bool `json:"indexContentsVerified"`
IndexBuildContentsVerified bool `json:"indexBuildContentsVerified"`
SHA256 string `json:"sha256"`
}
V2VerificationReport is a schema-versioned receipt for a full, read-only V2 protected-page graph and published-index semantic audit. ReclaimablePages is informational; verification never installs a free pool or publishes maintenance metadata.
func VerifyV2File ¶
func VerifyV2File(ctx context.Context, path string) (V2VerificationReport, error)
VerifyV2File performs an offline, non-mutating audit of an existing V2 file. It takes a non-blocking shared advisory lock, so an active writer fails with ErrDatabaseLocked. It never creates, truncates, repairs, reclaims, or advances the database. Meta inspection alone is cheaper; this method walks every page protected by both valid Meta roots, recomputes published and provable shadow Secondary keys from canonical Primary documents in both directions, and hashes the file. Legacy caught-up builds lacking an applied CatalogRoot remain readable but report IndexBuildContentsVerified=false.
type Value ¶
type Value struct {
// contains filtered or unexported fields
}
Value is a closed tagged value. Its representation is private so callers cannot construct a tag/payload mismatch.
func ID ¶
func ID(v DocumentID) Value
func Time ¶
Time stores millisecond precision, matching JavaScript Date and the wire contract. Precision is normalized at construction rather than silently lost during transport.
func UnmarshalWireValue ¶
func UnmarshalWireValue(data []byte, limits QueryLimits) (Value, error)
UnmarshalWireValue decodes one closed, typed wire value using the same depth/item/byte limits as query operands. It is suitable for data-only protocol arguments such as RPC; it never evaluates source or callbacks.
func (Value) ArrayValue ¶
func (Value) BinaryValue ¶
func (Value) IDValue ¶
func (v Value) IDValue() (DocumentID, bool)
func (Value) ObjectValue ¶
func (Value) StringValue ¶
type WriteTransaction ¶
type WriteTransaction struct {
// contains filtered or unexported fields
}
WriteTransaction is a short-lived snapshot write view. It provides point operations with optimistic serializable commit validation. Values returned from it are isolated clones.
A transaction is active only during its handler callback. Handlers must not retain it or call normal DB/Collection methods from inside the callback.
func (*WriteTransaction) DeleteOne ¶
func (tx *WriteTransaction) DeleteOne(collection string, id DocumentID) error
DeleteOne stages a point delete. Deleting a document inserted earlier in the same callback cancels that insert without producing a storage mutation.
func (*WriteTransaction) GetOne ¶
func (tx *WriteTransaction) GetOne(collection string, id DocumentID) (Document, error)
GetOne returns one document by intrinsic ID from the transaction's current view, including earlier point mutations in the same callback.
func (*WriteTransaction) InsertOne ¶
func (tx *WriteTransaction) InsertOne(collection string, document Document) (DocumentID, error)
InsertOne stages one insert and returns its generated or supplied ID.
func (*WriteTransaction) MeldbaseStageSystemMutation ¶
func (tx *WriteTransaction) MeldbaseStageSystemMutation(mutation systemrecord.Mutation, onCommit func(uint64)) error
MeldbaseStageSystemMutation is first-party composite-transaction plumbing. Its internal parameter type prevents external applications from accessing the private System tree. onCommit runs synchronously after the durable root is published and before the matching business ChangeBatch becomes visible; it must be bounded, non-blocking and must not call back into the database.
func (*WriteTransaction) ReplaceOne ¶
func (tx *WriteTransaction) ReplaceOne(collection string, id DocumentID, document Document) error
ReplaceOne stages a full replacement for an existing document. The supplied document may omit _id; if present it must equal id.
func (*WriteTransaction) UpdateOne ¶
func (tx *WriteTransaction) UpdateOne(collection string, id DocumentID, mutation MutationSpec) error
UpdateOne applies one already compiled, data-only mutation to the transaction's current document view. Earlier writes in the same transaction are visible and the intrinsic _id remains immutable.
type WriteTransactionStats ¶
type WriteTransactionStats struct {
Active uint64 `json:"active"`
Started uint64 `json:"started"`
Committed uint64 `json:"committed"`
Noops uint64 `json:"noops"`
Conflicts uint64 `json:"conflicts"`
Aborted uint64 `json:"aborted"`
}
WriteTransactionStats describes public optimistic point transactions. Every started callback reaches exactly one terminal counter. These aggregates do not contain collection, document, principal, or callback identifiers.
Source Files
¶
- availability.go
- backup_v2.go
- compaction_v2.go
- compound_index_key.go
- cursor_storage.go
- database.go
- diagnostics.go
- document.go
- errors.go
- filter.go
- index_build_scheduler.go
- index_builds.go
- index_definition.go
- index_key.go
- indexes.go
- indexes_v2.go
- maintenance_v2.go
- migration.go
- mutation_selection.go
- mutation_wire.go
- observability.go
- persistence.go
- persistence_codec.go
- persistence_v2.go
- persistence_v2_cache.go
- query.go
- query_backend.go
- query_delta.go
- query_replay.go
- query_wire.go
- reactive.go
- reactive_replay_v2.go
- reactive_shared.go
- reactive_tree.go
- reclamation_v2.go
- recovery.go
- resource_limits.go
- storage_document_codec.go
- storage_format.go
- system_records_v2.go
- update.go
- value.go
- verify_v2.go
- write_transaction.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package admin provides optional, bounded observability consumers for Meldbase.
|
Package admin provides optional, bounded observability consumers for Meldbase. |
|
cmd
|
|
|
meld
command
|
|
|
integrations
|
|
|
otel
Package meldotel exports Meldbase's bounded admin snapshots through the stable OpenTelemetry Metrics API.
|
Package meldotel exports Meldbase's bounded admin snapshots through the stable OpenTelemetry Metrics API. |
|
internal
|
|
|
policyrecord
Package policyrecord defines the durable private representation of server query-policy generations.
|
Package policyrecord defines the durable private representation of server query-policy generations. |
|
qualification
Package qualification contains operational release-evidence runners.
|
Package qualification contains operational release-evidence runners. |
|
storage/v2
Package v2 contains the experimental Meldbase Storage V2 page format.
|
Package v2 contains the experimental Meldbase Storage V2 page format. |
|
systemrecord
Package systemrecord defines the private bridge between the root database and higher-level built-in services.
|
Package systemrecord defines the private bridge between the root database and higher-level built-in services. |
|
Package server exposes Meldbase's authenticated HTTP, WebSocket realtime and data-only RPC transport.
|
Package server exposes Meldbase's authenticated HTTP, WebSocket realtime and data-only RPC transport. |