Help us shape the future of Go! Take the 2026 Go Developer Survey

mongodb

package
v0.26.0 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: MIT Imports: 51 Imported by: 0

README

Ridu MongoDB adapter

github.com/riducms/ridu/adapters/mongodb requires a writable replica-set primary with logical sessions and transactions. Opening it does not create collections, indexes, or migration state.

Draft-enabled versioned content keeps a working document and a separate live-head document; the live head is independent of retained version history. MongoDB migration history uses the current planner 5.0.0; older planner artifacts and physical layouts are unsupported and must be handled outside Ridu before startup. Readiness rejects incomplete live-head coverage. Unique-index additions to versioned content use a maintenance-admitted, resumable reservation rebuild before the new indexes are built; typed field renames rebuild those reservations in their semantic transaction. A collection or global that starts keeping versions does so in a migration of its own that records what its stored documents become. Its maintenance-admitted semantic transaction gives every stored document, trashed ones included, a first version and, for published, a live head; require-empty stops the migration while any document is stored. Development schema sync enables versions only on a resource that stores none.

Document locks are fence writes, because MongoDB has no row locks. A reference takes a shared lock: it increments one of the target's fence records in z_ridu_reference_fences, one per open transaction of a Store, so saves that share a popular target do not conflict. An update or delete takes an exclusive lock: it increments the document's own fence and each of its fence records, which conflicts with every holder. The records stay for later saves, at most 32 per document, and are removed with the document, its collection's retirement or a collection rename. A transaction that meets a conflicting lock before its first content write restarts on a newer snapshot, locks again what it held and waits its turn instead of failing. Within one Store the turns are queued, as PostgreSQL queues lock requests: a waiting update or delete holds back the references of transactions that began after it, so a stream of saves cannot starve it, and a transaction waiting for another one of the Store resumes when that one ends or gives way. The queue is local to the process; replicas coordinate only through the fences and retry after a jittered backoff. Operation statements carry a server time limit of the caller's deadline, at most 60 seconds. Database-side shape guards for counts and selections check the authored root and each repeated field's row identity, so their size follows definitions rather than block placements. A filter through repeated fields nests one $elemMatch per level and guards the rows along its own path by their declared fields; see the concurrency and limits section of the guide.

New projects can select it during scaffolding:

ridu new

Choose MongoDB in the wizard and review the summary. For non-interactive setup, use the flags in the MongoDB guide.

Production support covers generated starter and blank projects using MongoDB Community 8.2.9, SCRAM-SHA-256, a writable three-member replica set, verified TLS, and Linux x86-64. It does not cover Atlas, DocumentDB, Cosmos DB, standalone servers, other versions, topologies, platforms, or generic Mongo-compatible services.

Read the complete MongoDB guide for existing-project ridu.toml and adapter-factory wiring, replica-set Compose setup, development/index verification, migrations, credentials, and the production profile. Ridu does not provide a cross-adapter live-data migration; write and verify a custom migration when moving existing PostgreSQL or SQLite data.

Documentation

Overview

Package mongodb provides Ridu's official MongoDB document store.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ProjectMigrations

func ProjectMigrations(transforms ...ridumigration.DataTransform) ridumigration.ProjectDriver

ProjectMigrations binds checksum-protected callbacks into the compiled project while MongoDB retains ownership of transactions, checkpoints, and the credential-bearing connection boundary.

func VerifyArtifacts

func VerifyArtifacts(ctx context.Context, config Config, directory string, transforms ...ridumigration.DataTransform) error

VerifyArtifacts replays immutable history in an isolated shadow database.

func VerifyArtifactsWithOptions

func VerifyArtifactsWithOptions(ctx context.Context, config Config, directory string, options RunnerOptions, transforms ...ridumigration.DataTransform) error

VerifyArtifactsWithOptions exercises the production runner, ledger, status, and readiness checks against an isolated database which is always dropped.

Types

type ArtifactOptions

type ArtifactOptions struct {
	AllowDestructive bool
	Renames          []ridumigration.Rename
	DataTransforms   []ridumigration.DataTransformDescriptor
	// ExistingDocuments says, for each resource that starts keeping versions,
	// what becomes of the documents it already stores.
	ExistingDocuments map[schema.StableID]ridumigration.ExistingDocuments
}

ArtifactOptions contains only reviewed semantic intent that can be frozen into an immutable MongoDB artifact. Callbacks themselves are never serialized; only their checksum-bound descriptors cross this boundary.

type Config

type Config struct {
	DatabaseURL string
	// AllowInsecureTransport permits plaintext or certificate verification
	// bypasses to a remote host for an explicitly selected development
	// fixture. Loopback and Unix-socket databases never need it.
	AllowInsecureTransport bool
	ApplicationName        string
	ConnectTimeout         time.Duration
	ServerSelectionTimeout time.Duration
	MaxConnectionIdleTime  time.Duration
	MaxPoolSize            uint64
	MinPoolSize            uint64
}

Config controls MongoDB connection behavior. DatabaseURL is runtime-only infrastructure and must never be copied into a schema manifest or artifact.

type CreatedArtifact

type CreatedArtifact struct {
	Path     string `json:"path"`
	Name     string `json:"name"`
	Checksum string `json:"checksum"`
	Version  uint32 `json:"version"`
}

CreatedArtifact is the stable filesystem identity of one newly published immutable MongoDB migration artifact.

func CreateArtifact

func CreateArtifact(ctx context.Context, directory, name string, after schema.Manifest, now time.Time, options ArtifactOptions) (CreatedArtifact, error)

CreateArtifact plans and atomically publishes one immutable MongoDB migration artifact with explicit semantic intent. Planning is offline: it reads only committed artifacts and the executable manifest; database URLs, secrets, and live MongoDB state are outside this boundary.

type MigrationPhaseStatus

type MigrationPhaseStatus struct {
	ID    string                  `json:"id"`
	Mode  ridumigration.PhaseMode `json:"mode"`
	State string                  `json:"state"`
	Steps []MigrationStepStatus   `json:"steps"`
}

MigrationPhaseStatus describes one immutable execution boundary.

type MigrationStatus

type MigrationStatus struct {
	Name     string                 `json:"name"`
	Checksum string                 `json:"checksum"`
	Version  uint32                 `json:"version"`
	Applied  bool                   `json:"applied"`
	Phases   []MigrationPhaseStatus `json:"phases,omitempty"`
}

MigrationStatus describes one immutable MongoDB artifact relative to the database ledger.

func InspectArtifacts

func InspectArtifacts(ctx context.Context, config Config, directory string, executableManifest schema.Manifest) ([]MigrationStatus, error)

InspectArtifacts binds status and plan inspection to the executable manifest, validates and precompiles that exact in-memory history before connecting, and uses the retained files for every database-backed check.

type MigrationStepStatus

type MigrationStepStatus struct {
	ID    string                 `json:"id"`
	Kind  ridumigration.StepKind `json:"kind"`
	State string                 `json:"state"`
}

MigrationStepStatus describes one durable MongoDB executor invocation.

type RunnerOptions

type RunnerOptions struct {
	AllowMaintenance bool
	AllowUnbounded   bool
	LeaseWait        time.Duration
	LeaseDuration    time.Duration
	OperationTimeout time.Duration
}

RunnerOptions bounds MongoDB migration coordination and index builds. AllowUnbounded permits a zero wait or operation timeout; lease expiry is always bounded so a crashed migrator cannot permanently block recovery.

type SafetyError

type SafetyError struct {
	Risks []ridumigration.Risk
}

SafetyError reports a valid MongoDB transition that still requires explicit destructive review before publication.

func (*SafetyError) Error

func (err *SafetyError) Error() string

type Store

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

Store is one replica-set-backed MongoDB database with immutable migration ledger readiness and transactional document storage.

func Open

func Open(ctx context.Context, databaseURL string) (*Store, error)

Open connects to a TLS-protected MongoDB replica set using safe defaults.

func OpenWithConfig

func OpenWithConfig(ctx context.Context, config Config) (*Store, error)

OpenWithConfig validates the credential-bearing URL without echoing it, connects, and proves transaction-capable replica-set topology. It does not create collections, indexes, or migration state.

func (*Store) AcquireDocumentLock

func (backend *Store) AcquireDocumentLock(ctx context.Context, candidate store.DocumentLock, now time.Time, takeover bool) (store.DocumentLock, bool, error)

func (*Store) AdoptArtifacts added in v0.9.0

func (backend *Store) AdoptArtifacts(ctx context.Context, directory string) ([]string, error)

AdoptArtifacts records pending migrations as applied, without running them, through the newest one whose schema the database already has, such as a database ridu dev synchronized. See ridu migrate baseline.

func (*Store) AllowAuthAttempt

func (backend *Store) AllowAuthAttempt(ctx context.Context, keyHash string, now time.Time, window time.Duration, maximum int) (bool, error)

func (*Store) ApplyArtifacts

func (backend *Store) ApplyArtifacts(ctx context.Context, directory string, transforms ...ridumigration.DataTransform) error

ApplyArtifacts applies the complete immutable MongoDB migration history.

func (*Store) ApplyArtifactsWithOptions

func (backend *Store) ApplyArtifactsWithOptions(ctx context.Context, directory string, options RunnerOptions, transforms ...ridumigration.DataTransform) error

ApplyArtifactsWithOptions applies planner-validated physical and semantic MongoDB steps, including registered transforms, and durably records each resumable boundary.

func (*Store) ArtifactPlan

func (backend *Store) ArtifactPlan(ctx context.Context, directory string) ([]MigrationStatus, error)

ArtifactPlan returns the same strict state with phase and step detail for deterministic CLI rendering.

func (*Store) ArtifactStatus

func (backend *Store) ArtifactStatus(ctx context.Context, directory string) ([]MigrationStatus, error)

ArtifactStatus validates immutable history and reports durable progress.

func (*Store) Begin

func (backend *Store) Begin(ctx context.Context) (store.Transaction, error)

Begin opens a majority-committed, snapshot-isolated write transaction. Until its first content write, a transient conflict restarts it on a newer snapshot (see lockDocument), so its reads are snapshot-isolated from that point, as a read-committed PostgreSQL transaction's statements are.

func (*Store) BeginSnapshot

func (backend *Store) BeginSnapshot(ctx context.Context) (store.Transaction, error)

BeginSnapshot opens the same stable snapshot in read-only adapter mode.

func (*Store) CancelTask

func (backend *Store) CancelTask(ctx context.Context, id string) error

func (*Store) ChangePasswordHash

func (backend *Store) ChangePasswordHash(ctx context.Context, collection schema.Collection, userID string, expectedPasswordHash, hash []byte) error

func (*Store) ClaimTasks

func (backend *Store) ClaimTasks(ctx context.Context, request store.TaskClaim) ([]store.Task, error)

func (*Store) ClearDevelopmentFieldKinds added in v0.12.0

func (backend *Store) ClearDevelopmentFieldKinds(ctx context.Context, before, after schema.Manifest, expected []fieldchange.Report) error

ClearDevelopmentFieldKinds clears only the reviewed field values from working documents, published heads, and retained snapshots, with references in one transaction. Immutable applied or incomplete migration history requires the reviewed runner.

func (*Store) Close

func (backend *Store) Close() error

Close releases the MongoDB client. It is idempotent and uses an internal bound so it satisfies the framework runtime's context-free close contract.

func (*Store) CompleteTask

func (backend *Store) CompleteTask(ctx context.Context, id, leaseToken string, output json.RawMessage) error

func (*Store) CreateAPIKey

func (backend *Store) CreateAPIKey(ctx context.Context, key store.AuthAPIKey, sessionTokenHash string, now time.Time) error

func (*Store) CreateAuthToken

func (backend *Store) CreateAuthToken(ctx context.Context, token store.AuthToken) error

func (*Store) CreateSession

func (backend *Store) CreateSession(ctx context.Context, session store.AuthSession, expectedPasswordHash []byte) error

func (*Store) DeleteAPIKey

func (backend *Store) DeleteAPIKey(ctx context.Context, collectionID schema.StableID, userID, id string) error

func (*Store) DeletePreference

func (backend *Store) DeletePreference(ctx context.Context, collectionID schema.StableID, userID, key string) error

func (*Store) DeletePreferences

func (backend *Store) DeletePreferences(ctx context.Context, collectionID schema.StableID, userID string) error

func (*Store) DeleteSession

func (backend *Store) DeleteSession(ctx context.Context, tokenHash string) error

func (*Store) DeleteUserSession

func (backend *Store) DeleteUserSession(ctx context.Context, collectionID schema.StableID, userID, sessionID string) error

func (*Store) DeleteUserSessions

func (backend *Store) DeleteUserSessions(ctx context.Context, collectionID schema.StableID, userID string) error

func (*Store) DevelopmentManifest added in v0.12.0

func (backend *Store) DevelopmentManifest(ctx context.Context) (schema.Manifest, bool, error)

DevelopmentManifest returns the database-owned last synchronized schema. Existing indexes or JSON documents do not prove the previous field kinds, so collections without a record are an error; a fresh database has none.

func (*Store) DismissTaskForTarget

func (backend *Store) DismissTaskForTarget(ctx context.Context, id, slug string, target store.DocumentReference) error

func (*Store) EnqueueTask

func (backend *Store) EnqueueTask(ctx context.Context, task store.Task) (store.Task, error)

func (*Store) FailTask

func (backend *Store) FailTask(ctx context.Context, failure store.TaskFailure) error

func (*Store) FindAPIKey

func (backend *Store) FindAPIKey(ctx context.Context, id string, now time.Time) (store.AuthAPIKey, error)

func (*Store) FindAuthCredential

func (backend *Store) FindAuthCredential(ctx context.Context, collection schema.Collection, identity string) (store.AuthCredential, error)

func (*Store) FindDocumentLock

func (backend *Store) FindDocumentLock(ctx context.Context, collectionID schema.StableID, documentID string, now time.Time) (store.DocumentLock, error)

func (*Store) FindSession

func (backend *Store) FindSession(ctx context.Context, tokenHash string, now time.Time) (store.AuthSession, error)

func (*Store) FindSessionByID added in v0.4.0

func (backend *Store) FindSessionByID(ctx context.Context, id string, now time.Time) (store.AuthSession, error)

func (*Store) FindTask

func (backend *Store) FindTask(ctx context.Context, id string) (store.Task, error)

func (*Store) ForceUnlock

func (backend *Store) ForceUnlock(ctx context.Context, collectionID schema.StableID, userID string) error

func (*Store) GetPreference

func (backend *Store) GetPreference(ctx context.Context, collectionID schema.StableID, userID, key string) (store.Preference, error)

func (*Store) HasMigrationHistory added in v0.12.0

func (backend *Store) HasMigrationHistory(ctx context.Context) (bool, error)

HasMigrationHistory includes partial semantic work, which development recovery must never mutate outside the immutable runner.

func (*Store) HeartbeatTask

func (backend *Store) HeartbeatTask(ctx context.Context, id, leaseToken string, leaseDuration time.Duration) error

func (*Store) ListAPIKeys

func (backend *Store) ListAPIKeys(ctx context.Context, collectionID schema.StableID, userID string, now time.Time) ([]store.AuthAPIKey, error)

func (*Store) ListSessions

func (backend *Store) ListSessions(ctx context.Context, collectionID schema.StableID, userID string, now time.Time) ([]store.AuthSession, error)

func (*Store) ListTasks

func (backend *Store) ListTasks(ctx context.Context, request store.TaskList) ([]store.Task, error)

func (*Store) LockUploadObjects

func (backend *Store) LockUploadObjects(ctx context.Context, objectKeys []string) (func(), error)

LockUploadObjects acquires one separately committed exact-owner lock set. Acquisition is all-or-none, and rows remain held until release. Graceful shutdown must drain callers before Store.Close; crash-abandoned rows require explicit operator recovery.

func (*Store) Ping

func (backend *Store) Ping(ctx context.Context) error

Ping proves that the connected replica set can serve a primary read.

func (*Store) PruneExpiredAuth

func (backend *Store) PruneExpiredAuth(ctx context.Context, limit int) (store.AuthPruneResult, error)

func (*Store) PruneTasks

func (backend *Store) PruneTasks(ctx context.Context, limit int) (int, error)

func (*Store) Ready

func (backend *Store) Ready(ctx context.Context, manifest schema.Manifest) error

Ready checks the manifest and physical schema for development and adapter diagnostics when no executable migration history digest is available.

func (*Store) ReadyWithMigrationHistory

func (backend *Store) ReadyWithMigrationHistory(ctx context.Context, manifest schema.Manifest, expectedHistoryDigest string) error

ReadyWithMigrationHistory verifies the complete ordered artifact history, recorded head and executable storage schema, then the physical index contract. Admin presentation may differ.

func (*Store) RecordFailedLogin

func (backend *Store) RecordFailedLogin(ctx context.Context, collectionID schema.StableID, userID string, now time.Time, maximum int, lockDuration time.Duration) (store.AuthCredential, error)

func (*Store) ReleaseDocumentLock

func (backend *Store) ReleaseDocumentLock(
	ctx context.Context,
	collectionID schema.StableID,
	documentID string,
	ownerCollectionID schema.StableID,
	ownerID string,
) error

func (*Store) ReleaseTask

func (backend *Store) ReleaseTask(
	ctx context.Context,
	id, leaseToken string,
	delay time.Duration,
	code, message string,
) error

func (*Store) ReplaceBaseline added in v0.12.0

func (backend *Store) ReplaceBaseline(ctx context.Context, directory string, options migration.BaselineReplacementOptions) ([]string, error)

ReplaceBaseline atomically replaces a verified development artifact/step ledger. Content, snapshots, namespaces, and indexes are never changed. Replacement artifacts from the first unrecorded semantic step onward stay pending for ApplyArtifacts.

func (*Store) ResetLoginAttempts

func (backend *Store) ResetLoginAttempts(ctx context.Context, collectionID schema.StableID, userID string, now time.Time) (bool, error)

func (*Store) ResetPasswordWithToken

func (backend *Store) ResetPasswordWithToken(ctx context.Context, collectionID schema.StableID, tokenHash string, hash []byte, now time.Time) (string, error)

func (*Store) ReviewDevelopmentFieldKinds added in v0.12.0

func (backend *Store) ReviewDevelopmentFieldKinds(ctx context.Context, before, after schema.Manifest) ([]fieldchange.Report, error)

ReviewDevelopmentFieldKinds reads both active heads and every snapshot under one stable database snapshot, counting each logical document once.

func (*Store) ReviewDevelopmentVersions added in v0.19.0

func (backend *Store) ReviewDevelopmentVersions(ctx context.Context, before, after schema.Manifest) ([]enableversions.Report, error)

ReviewDevelopmentVersions counts the documents, trashed ones included, that each resource starting to keep versions between before and after already stores in this database. It changes nothing.

func (*Store) RotateSession

func (backend *Store) RotateSession(ctx context.Context, currentHash string, replacement store.AuthSession, now time.Time) error

func (*Store) SetPasswordHash

func (backend *Store) SetPasswordHash(ctx context.Context, collection schema.Collection, userID string, hash []byte, initiallyVerified bool) error

func (*Store) SetPreference

func (backend *Store) SetPreference(ctx context.Context, preference store.Preference) (store.Preference, error)

func (*Store) SyncDevelopmentSchema added in v0.12.0

func (backend *Store) SyncDevelopmentSchema(ctx context.Context, manifest schema.Manifest) error

SyncDevelopmentSchema verifies additive index sync under the migration lease, then records its manifest in a fenced transaction. Failed builds never certify the candidate schema.

func (*Store) TouchAPIKey

func (backend *Store) TouchAPIKey(ctx context.Context, id string, now time.Time) error

func (*Store) UpgradePasswordHash

func (backend *Store) UpgradePasswordHash(ctx context.Context, collection schema.Collection, userID string, expectedPasswordHash, hash []byte) error

func (*Store) VerifyEmailWithToken

func (backend *Store) VerifyEmailWithToken(ctx context.Context, collectionID schema.StableID, tokenHash string, now time.Time) (string, error)

func (*Store) VerifyIndexes

func (backend *Store) VerifyIndexes(ctx context.Context, manifest schema.Manifest) error

VerifyIndexes is a non-mutating physical check for the complete current manifest plan. A successful verification authorizes this Store instance to serve every resource in that plan; Open itself remains free of schema mutations.

Jump to

Keyboard shortcuts

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