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

cosmosdb

package
v1.9.1 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 52 Imported by: 0

README

Azure Cosmos DB

Parity grade: A · SDK azure-sdk-for-go/sdk/data/azcosmos@v1.5.0 · last audited 2026-10-20 (658ecc434)

Coverage

Metric Value
PARITY entries audited 35 (35 ok)
Feature families 24 (24 ok)
Known gaps none
Deferred items 0
Resource leaks clean

More

Documentation

Overview

Package cosmosdb emulates Azure Cosmos DB over its REST+JSON gateway protocol: the Core (SQL) API (databases, containers with hierarchical partition keys and TTL, documents, a SQL query engine with joins, subqueries, aggregates and built-ins, continuation tokens, request-unit accounting) and the Table API. Master-key auth and TLS are opt-in. See PARITY.md for scope and known gaps.

Index

Constants

View Source
const (
	ConsistencyStrong           = "Strong"
	ConsistencyBoundedStaleness = "BoundedStaleness"
	ConsistencySession          = "Session"
	ConsistencyConsistentPrefix = "ConsistentPrefix"
	ConsistencyEventual         = "Eventual"
)

Consistency levels, strongest first (Learn, "Consistency levels in Azure Cosmos DB").

View Source
const (

	// MinResourceTokenMaxSeconds and MaxResourceTokenMaxSeconds bound Settings.ResourceTokenMaxSeconds.
	MinResourceTokenMaxSeconds = minTokenExpirySeconds
	MaxResourceTokenMaxSeconds = maxTokenExpirySeconds
)
View Source
const (

	// PermissionModeAll and PermissionModeRead are the permissionMode values.
	PermissionModeAll  = "All"
	PermissionModeRead = "Read"
)
View Source
const DefaultMasterKey = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="

DefaultMasterKey is the real Cosmos DB Local Emulator's well-known, publicly documented fixed master key. Accepting it by default (like services/azureblob's/azurequeue's/azuretable's fixed devstoreaccount1 key) means unmodified SDK configuration pointed at the real emulator's documented connection string works out of the box against gopherstack too. See masterkey.go and AZURE.md section 5.

View Source
const DefaultPort = 8081

DefaultPort is the real Cosmos DB Local Emulator's own fixed, protocol-conventional TCP port (8081). Unlike services/azureblob's 10000, services/azurequeue's 10001, and services/azuretable's 10002 -- all of which mirror Azurite's own port convention -- 8081 mirrors the real Cosmos DB Emulator's own published default instead, since Cosmos's emulator (unlike Azurite) is a single-service, single-port tool with no analogous three-port split to imitate. This deliberately sits OUTSIDE --port-range-start/--port-range-end's own default range (10000-10100), exactly like services/iot's MQTT broker default (1883) -- see AZURE.md section 4 and handler.go's StartWorker for the synchronous-bind, no-fallback-pool rationale this follows.

Variables

View Source
var (
	// ErrMissingAuthorization is returned when validation is on and a request carries no Authorization header.
	ErrMissingAuthorization = errors.New("cosmosdb: missing Authorization header")
	// ErrMissingDate is returned when neither x-ms-date nor Date is present.
	ErrMissingDate = errors.New("cosmosdb: missing x-ms-date header")
	// ErrDateSkew is returned when the request date is outside maxAuthClockSkew of server time.
	ErrDateSkew = errors.New("cosmosdb: x-ms-date outside the allowed clock skew")
	// ErrBadSignature is returned when the signature does not match.
	ErrBadSignature = errors.New("cosmosdb: signature mismatch")
)
View Source
var (
	ErrDatabaseNotFound       = errors.New("cosmosdb: database not found")
	ErrDatabaseAlreadyExists  = errors.New("cosmosdb: database already exists")
	ErrContainerNotFound      = errors.New("cosmosdb: container not found")
	ErrContainerAlreadyExists = errors.New("cosmosdb: container already exists")
	ErrDocumentNotFound       = errors.New("cosmosdb: document not found")
	ErrDocumentAlreadyExists  = errors.New("cosmosdb: document already exists")
	ErrETagMismatch           = errors.New("cosmosdb: etag mismatch")

	// ErrInvalidDocument is returned when a document body is not a JSON
	// object, or its "id" field is present but not a non-empty string.
	ErrInvalidDocument = errors.New("cosmosdb: invalid document body")

	// ErrInvalidPartitionKeyPath is returned for a container partition key definition that is empty, unprefixed,
	// duplicated, or has more than three (hierarchical) paths.
	ErrInvalidPartitionKeyPath = errors.New(
		"cosmosdb: partitionKey.paths must contain between one and three distinct \"/\"-prefixed paths",
	)

	// ErrInvalidDefaultTTL is returned for a container defaultTtl that is neither -1 nor a positive integer.
	ErrInvalidDefaultTTL = errors.New("cosmosdb: defaultTtl must be -1 or a positive integer")

	// ErrPartitionKeyImmutable is returned when a container replace tries to change the partition key.
	ErrPartitionKeyImmutable = errors.New("cosmosdb: the partition key of an existing container cannot be changed")

	// ErrInvalidContainerPolicy is returned for a malformed unique-key, geospatial, vector or computed-property setting.
	ErrInvalidContainerPolicy = errors.New("cosmosdb: invalid container policy")

	// ErrUniqueKeyPolicyImmutable is returned when a container replace tries to change the unique key policy.
	ErrUniqueKeyPolicyImmutable = errors.New(
		"cosmosdb: the unique key policy of an existing container cannot be changed",
	)

	// ErrUniqueKeyViolation is returned when a write would duplicate a unique key value within a logical partition.
	ErrUniqueKeyViolation = errors.New("cosmosdb: unique index constraint violation")

	// ErrInvalidContinuation is returned for a malformed x-ms-continuation token.
	ErrInvalidContinuation = errors.New("cosmosdb: invalid continuation token")

	// ErrQueryParse and ErrQueryTooDeep are returned by ParseQuery. A parse
	// error always surfaces as 400 BadRequest, never a panic -- see
	// document_ops.go's handleQuery.
	ErrQueryParse   = errors.New("cosmosdb: query parse error")
	ErrQueryTooDeep = errors.New("cosmosdb: query expression nested too deeply")

	// ErrSnapshotNull* are returned by Restore when a snapshot's nested map
	// holds a JSON null entry, which decodes to a nil pointer that would
	// panic on first dereference if stored as-is. See persistence.go.
	ErrSnapshotDatabaseNull  = errors.New("cosmosdb: restore snapshot: database is null")
	ErrSnapshotContainerNull = errors.New("cosmosdb: restore snapshot: container is null")
	ErrSnapshotDocumentNull  = errors.New("cosmosdb: restore snapshot: document is null")

	ErrSnapshotUserNull       = errors.New("cosmosdb: restore snapshot: user is null")
	ErrSnapshotPermissionNull = errors.New("cosmosdb: restore snapshot: permission is null")

	// ErrPartitionKeyMismatch is returned by ReplaceDocument when the
	// replacement body's own partition-key-path field is present but
	// disagrees with the caller-supplied partition key (the
	// x-ms-documentdb-partitionkey header value, canonicalized). Without
	// this check, a document keyed under partition "a" could be silently
	// rewritten to claim partition "b" in its own body while remaining
	// stored (and only ever findable) under "a" -- an internally
	// inconsistent document real Cosmos DB never allows to exist.
	ErrPartitionKeyMismatch = errors.New(
		"cosmosdb: replacement body's partition key does not match the request's partition key",
	)

	// ErrSnapshotDocumentNullBody is returned by storedDocument.UnmarshalJSON
	// when a persisted document's "Body" field is itself JSON null.
	// encoding/json decodes a null-into-map with no error (it just sets the
	// map to nil), so without this explicit check a document with a null
	// Body would silently restore as an empty document, discarding every
	// field it used to have -- not a decode failure, so nothing would ever
	// surface the data loss.
	ErrSnapshotDocumentNullBody = errors.New("cosmosdb: restore snapshot: document body is null")

	// ErrUnexpectedTrailingJSON is returned by rejectTrailingJSON when a
	// second decode off the same stream succeeds instead of hitting EOF,
	// meaning the input carried more than the one JSON value callers
	// require.
	ErrUnexpectedTrailingJSON = errors.New("cosmosdb: unexpected additional JSON value")

	ErrInvalidPatch         = errors.New("cosmosdb: invalid patch request")
	ErrPatchConditionFailed = errors.New("cosmosdb: patch condition not satisfied")
	ErrBatchTooLarge        = errors.New("cosmosdb: batch has more operations than the 100 allowed")
	ErrScriptNotFound       = errors.New("cosmosdb: script not found")
	ErrScriptAlreadyExists  = errors.New("cosmosdb: script already exists")
	ErrInvalidScript        = errors.New("cosmosdb: invalid script definition")
	ErrScriptFailed         = errors.New("cosmosdb: script execution failed")
	ErrScriptTimeout        = errors.New("cosmosdb: script execution timed out")
	ErrInvalidTrigger       = errors.New("cosmosdb: trigger not usable for this operation")
	ErrInvalidPKRange       = errors.New("cosmosdb: unknown partition key range")
	ErrPKRangeGone          = errors.New("cosmosdb: partition key range was split")
	// ErrChangeFeedStart is returned when an all-versions-and-deletes read names no start.
	ErrChangeFeedStart = errors.New(
		"cosmosdb: all versions and deletes change feed starts from now or from a continuation, not from the beginning " +
			"or a point in time",
	)
	// ErrChangeFeedBackup is returned for an all-versions-and-deletes read on an account without continuous backup.
	ErrChangeFeedBackup = errors.New(
		"cosmosdb: all versions and deletes change feed requires continuous backup on the account",
	)
	// ErrChangeFeedRetention is returned when the start position is older than the continuous backup window.
	ErrChangeFeedRetention = errors.New(
		"cosmosdb: the change feed position is outside the continuous backup retention window",
	)
)

Sentinel errors for Azure Cosmos DB (Core/SQL API) operations.

View Source
var (
	ErrThroughputNotFound = errors.New("cosmosdb: no throughput is provisioned on the resource")
	ErrInvalidThroughput  = errors.New("cosmosdb: invalid throughput")
	ErrServerless         = errors.New("cosmosdb: throughput is not supported on serverless accounts")
)

Throughput errors.

View Source
var (
	// ErrInsufficientPermissions is returned when a valid resource token does not cover the request.
	ErrInsufficientPermissions = errors.New("cosmosdb: resource token does not grant this operation")
	// ErrTokenExpired is returned when a resource token is used outside its validity window.
	ErrTokenExpired = errors.New("cosmosdb: resource token is not valid at the current time")
	// ErrInvalidTokenExpiry is returned for an x-ms-documentdb-expiry-seconds outside 600..the configured maximum.
	ErrInvalidTokenExpiry = errors.New("cosmosdb: invalid x-ms-documentdb-expiry-seconds")
)
View Source
var (
	// ErrUserNotFound is returned for a user id absent from its database.
	ErrUserNotFound = errors.New("cosmosdb: user not found")
	// ErrUserAlreadyExists is returned when a user id is already taken in the database.
	ErrUserAlreadyExists = errors.New("cosmosdb: user already exists")
	// ErrPermissionNotFound is returned for a permission id absent from its user.
	ErrPermissionNotFound = errors.New("cosmosdb: permission not found")
	// ErrPermissionAlreadyExists is returned when a permission id is already taken for the user.
	ErrPermissionAlreadyExists = errors.New("cosmosdb: permission already exists")
	// ErrInvalidPermission is returned for a permission with a bad mode, resource link or partition key.
	ErrInvalidPermission = errors.New("cosmosdb: invalid permission")
)
View Source
var ErrConflictNotFound = errors.New("cosmosdb: conflict not found")

ErrConflictNotFound is returned for an unknown conflicts-feed entry.

View Source
var ErrInvalidConsistency = errors.New("cosmosdb: invalid consistency level")

ErrInvalidConsistency is returned for an x-ms-consistency-level the account cannot honour.

View Source
var ErrInvalidResourceTokenMax = errors.New("cosmosdb: resource-token-max-seconds must be between 600 and 86400")

ErrInvalidResourceTokenMax is returned when --cosmosdb-resource-token-max-seconds is outside 600..86400.

View Source
var ErrMalformedAuthorization = errors.New("cosmosdb: malformed Authorization header")

ErrMalformedAuthorization is returned by VerifyMasterKey when the request's Authorization header cannot be parsed.

View Source
var ErrNilAppContext = errors.New("cosmosdb: nil app context")

ErrNilAppContext is returned when Init is called with a nil AppContext.

View Source
var ErrReadSessionNotAvailable = errors.New("cosmosdb: read session is not available for the input session token")

ErrReadSessionNotAvailable is returned when a read names a session token the region has not caught up with (HTTP 404, substatus 1002).

View Source
var ErrUnknownRegion = errors.New("cosmosdb: unknown region")

ErrUnknownRegion is returned for an operation naming a region the account does not have.

Functions

func ExecuteQuery

func ExecuteQuery(query string, params []QueryParameter, docs []DocumentInfo) ([]any, error)

ExecuteQuery parses and runs query against docs. It never panics.

func VerifyMasterKey

func VerifyMasterKey(masterKey string, r *http.Request) (bool, error)

VerifyMasterKey recomputes the master-key signature for r using masterKey, and reports whether it matches the signature the client sent. This is an explicit, opt-in check: nothing in this package calls it implicitly -- see auth.go's authorize, which only calls this when Settings.ValidateAuth is true, mirroring pkgs/azureauth.VerifySharedKey's identical opt-in stance.

Types

type AccountPolicies

type AccountPolicies struct {
	Consistency        string
	Backup             string
	MaxStalenessPrefix int64
	MaxIntervalSeconds int
	AutomaticFailover  bool
}

AccountPolicies are the account settings an ARM account carries into the data plane.

type AccountRegion

type AccountRegion struct {
	Name             string `json:"name"`
	FailoverPriority int    `json:"failoverPriority"`
	ReplicationLagMs int    `json:"replicationLagMs,omitempty"`
	Offline          bool   `json:"offline,omitempty"`
}

AccountRegion is one geo-replica of the account. The lowest failover priority among online regions is the write region; ReplicationLagMs is how long a write elsewhere takes to arrive here.

type AccountRegions

type AccountRegions struct {
	Consistency    *ConsistencyPolicy `json:"consistency,omitempty"`
	Write          string             `json:"write,omitempty"`
	Backup         string             `json:"backup,omitempty"`
	Regions        []AccountRegion    `json:"regions,omitempty"`
	MultiWrite     bool               `json:"multiWrite,omitempty"`
	NoAutoFailover bool               `json:"noAutoFailover,omitempty"`
}

AccountRegions is the account's regional topology.

type BatchResult

type BatchResult struct {
	Body          map[string]any `json:"resourceBody,omitempty"`
	ETag          string         `json:"eTag,omitempty"`
	StatusCode    int            `json:"statusCode"`
	RequestCharge float64        `json:"requestCharge"`
}

BatchResult is one operation's outcome in the batch response array.

type ChangeVersion

type ChangeVersion struct {
	Current      *DocumentInfo
	Previous     *DocumentInfo
	PartitionKey map[string]any
	Op           string
	ID           string
	LSN          int64
	PreviousLSN  int64
	CRTS         int64
	TTLExpired   bool
}

ChangeVersion is one entry of the all-versions-and-deletes change feed.

type ConfigProvider

type ConfigProvider interface {
	GetCosmosDBSettings() Settings
}

ConfigProvider is a private interface to extract CosmosDB configuration from the abstract AppContext Config, mirroring services/azuretable.ConfigProvider.

type ConflictInfo

type ConflictInfo struct {
	Time             time.Time
	Content          *DocumentInfo
	ID               string
	RID              string
	Self             string
	Op               string
	DocID            string
	DocRID           string
	PartitionKeyJSON string
	LSN              int64
}

ConflictInfo is a read-only conflicts-feed entry.

type ConsistencyPolicy

type ConsistencyPolicy struct {
	Level                string `json:"defaultConsistencyLevel"`
	MaxStalenessPrefix   int64  `json:"maxStalenessPrefix,omitempty"`
	MaxIntervalInSeconds int    `json:"maxIntervalInSeconds,omitempty"`
}

ConsistencyPolicy is the account default consistency (userConsistencyPolicy on the account root).

type ContainerInfo

type ContainerInfo struct {
	DefaultTTL        *int
	ID                string
	RID               string
	PartitionKeyPath  string
	PartitionKeyPaths []string
	IndexingPolicy    json.RawMessage
	Modified          time.Time

	ConflictResolutionPolicy json.RawMessage
	ContainerPolicies
}

ContainerInfo is a read-only snapshot of a container, returned by the StorageBackend container accessors.

type ContainerPolicies

type ContainerPolicies struct {
	UniqueKeyPolicy       json.RawMessage `json:"uniqueKeyPolicy"`
	GeospatialConfig      json.RawMessage `json:"geospatialConfig"`
	VectorEmbeddingPolicy json.RawMessage `json:"vectorEmbeddingPolicy"`
	FullTextPolicy        json.RawMessage `json:"fullTextPolicy"`
	ComputedProperties    json.RawMessage `json:"computedProperties"`
}

ContainerPolicies are the optional container settings that are stored and echoed verbatim; the unique-key policy is enforced on writes and computed properties are evaluated by queries.

type ContainerSpec

type ContainerSpec struct {
	DefaultTTL        *int
	ID                string
	PartitionKeyPath  string
	PartitionKeyPaths []string
	IndexingPolicy    json.RawMessage

	ConflictResolutionPolicy json.RawMessage
	ContainerPolicies
}

ContainerSpec is the caller-supplied shape for creating or replacing a container. PartitionKeyPaths (up to three, hierarchical) takes precedence over the single PartitionKeyPath. DefaultTTL nil leaves TTL disabled.

type DatabaseInfo

type DatabaseInfo struct {
	Modified time.Time
	ID       string
	RID      string
}

DatabaseInfo is a read-only snapshot of a database, returned by the StorageBackend database accessors.

type DocumentInfo

type DocumentInfo struct {
	Timestamp        time.Time
	Body             map[string]any
	ID               string
	RID              string
	Self             string
	ETag             string
	PartitionKeyJSON string
	Seq              int64
}

DocumentInfo is a read-only snapshot of a document, returned by the StorageBackend document accessors. Body holds the document's user-defined fields only (never the system properties, which callers -- handler.go's encodeDocument -- overlay from the other fields at response-encode time, mirroring services/azuretable's EntityInfo/encodeEntity split).

type Handler

type Handler struct {
	Backend StorageBackend

	TableBackend *odatatable.InMemoryBackend

	MasterKey string

	TLSHosts                []string
	RegionPortBase          int
	Port                    int
	ResourceTokenMaxSeconds int
	SweepInterval           time.Duration
	ValidateAuth            bool
	TLS                     bool
	EnforceThroughput       bool
	BurstCapacity           bool
	// contains filtered or unexported fields
}

Handler is the Echo HTTP handler for Azure Cosmos DB (Core/SQL API) operations.

func NewHandler

func NewHandler(backend StorageBackend) *Handler

NewHandler creates a new Cosmos DB Handler. Port/MasterKey default to DefaultPort/DefaultMasterKey; callers (typically provider.go) override them from Settings.

func (*Handler) AcceptKey

func (h *Handler) AcceptKey(key string)

AcceptKey makes key a valid master key in addition to MasterKey, for keys the ARM control plane hands out.

func (*Handler) ExtractOperation

func (h *Handler) ExtractOperation(c *echo.Context) string

ExtractOperation extracts the Cosmos DB operation name from the request, for metrics labeling.

func (*Handler) ExtractResource

func (h *Handler) ExtractResource(c *echo.Context) string

ExtractResource extracts the resource path, for metrics labeling.

func (*Handler) GetSupportedOperations

func (h *Handler) GetSupportedOperations() []string

GetSupportedOperations returns the list of supported Cosmos DB operations, Core/SQL and Table API combined.

func (*Handler) Handler

func (h *Handler) Handler() echo.HandlerFunc

Handler returns the Echo handler function for Cosmos DB operations.

func (*Handler) MatchPriority

func (h *Handler) MatchPriority() int

MatchPriority returns the routing priority for the CosmosDB handler. Irrelevant in practice since RouteMatcher never matches; 0 (lowest) is the safe default.

func (*Handler) Name

func (h *Handler) Name() string

Name returns the service name.

func (*Handler) Reset

func (h *Handler) Reset()

Reset clears all in-memory state, Core/SQL and Table API alike.

func (*Handler) Restore

func (h *Handler) Restore(ctx context.Context, data []byte) error

Restore implements persistence.Persistable by delegating to the backend.

func (*Handler) RevokeKey

func (h *Handler) RevokeKey(key string)

RevokeKey stops accepting a key added by AcceptKey; the configured MasterKey is never revoked.

func (*Handler) RouteMatcher

func (h *Handler) RouteMatcher() service.Matcher

RouteMatcher exists only to satisfy service.Registerable's interface contract -- see provider.go's Provider doc comment. CosmosDB never matches on the shared AWS single-port Router; it runs on its own dedicated listener started by StartWorker.

func (*Handler) Shutdown

func (h *Handler) Shutdown(ctx context.Context)

Shutdown stops the dedicated Cosmos DB listener.

func (*Handler) SignRequest

func (h *Handler) SignRequest(r *http.Request) error

SignRequest adds x-ms-date and a master-key Authorization header to r using the handler's key. It lets in-process callers (the dashboard proxy) satisfy ValidateAuth.

func (*Handler) Snapshot

func (h *Handler) Snapshot(ctx context.Context) []byte

Snapshot implements persistence.Persistable by delegating to the backend.

func (*Handler) StartWorker

func (h *Handler) StartWorker(ctx context.Context) error

StartWorker binds the dedicated Cosmos DB listener (optionally TLS) and starts the TTL janitor. The bind is synchronous so a port conflict is returned to the caller.

func (*Handler) TLSCertPEM

func (h *Handler) TLSCertPEM() []byte

TLSCertPEM returns the self-signed certificate (PEM) the TLS listener serves, for clients to trust; nil unless TLS is enabled and the worker started.

type InMemoryBackend

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

InMemoryBackend implements StorageBackend using an in-memory map guarded by a single RWMutex. Shaped after services/azuretable's InMemoryBackend.

func NewInMemoryBackend

func NewInMemoryBackend() *InMemoryBackend

NewInMemoryBackend creates a new empty InMemoryBackend.

func (*InMemoryBackend) AccountRegions

func (b *InMemoryBackend) AccountRegions() AccountRegions

AccountRegions returns the topology, the default single region when none was set.

func (*InMemoryBackend) AttachTableAPI

func (b *InMemoryBackend) AttachTableAPI(t tableSnapshotter)

AttachTableAPI includes t in this backend's Snapshot/Restore/Reset.

func (*InMemoryBackend) CheckThroughput

func (b *InMemoryBackend) CheckThroughput(spec ThroughputSpec, containerLevel bool) error

CheckThroughput validates spec for provisioning on a database or container.

func (*InMemoryBackend) ConfigureAccountRegions

func (b *InMemoryBackend) ConfigureAccountRegions(r AccountRegions)

ConfigureAccountRegions replaces the whole topology including lag, offline state and consistency (the admin API).

func (*InMemoryBackend) CreateContainer

func (b *InMemoryBackend) CreateContainer(dbID string, spec ContainerSpec) (ContainerInfo, error)

CreateContainer creates a new, empty container within dbID. Returns ErrDatabaseNotFound if dbID doesn't exist, or ErrContainerAlreadyExists if a container with the same ID already exists in it.

func (*InMemoryBackend) CreateDatabase

func (b *InMemoryBackend) CreateDatabase(id string) (DatabaseInfo, error)

CreateDatabase creates a new, empty database. Returns ErrDatabaseAlreadyExists if a database with the same ID already exists.

func (*InMemoryBackend) CreateDocument

func (b *InMemoryBackend) CreateDocument(
	dbID, containerID string, body map[string]any, upsert bool,
) (DocumentInfo, error)

CreateDocument creates (or, if upsert, inserts-or-replaces) a document. See StorageBackend's doc comment.

func (*InMemoryBackend) CreatePermission

func (b *InMemoryBackend) CreatePermission(dbID, userID string, spec PermissionSpec) (PermissionInfo, error)

CreatePermission adds a permission to a user after resolving its resource link.

func (*InMemoryBackend) CreateScript

func (b *InMemoryBackend) CreateScript(dbID, collID string, kind scriptKind, spec ScriptSpec) (ScriptInfo, error)

CreateScript stores a new script; ErrScriptAlreadyExists if the id is taken.

func (*InMemoryBackend) CreateUser

func (b *InMemoryBackend) CreateUser(dbID, id string) (UserInfo, error)

CreateUser creates a user in dbID.

func (*InMemoryBackend) DeleteConflict

func (b *InMemoryBackend) DeleteConflict(dbID, collID, region, id string) error

DeleteConflict removes a conflicts-feed entry once the application has merged it.

func (*InMemoryBackend) DeleteContainer

func (b *InMemoryBackend) DeleteContainer(dbID, containerID string) error

DeleteContainer removes a container and all of its documents.

func (*InMemoryBackend) DeleteDatabase

func (b *InMemoryBackend) DeleteDatabase(id string) error

DeleteDatabase removes a database and all of its containers/documents. Returns ErrDatabaseNotFound if absent.

func (*InMemoryBackend) DeleteDocument

func (b *InMemoryBackend) DeleteDocument(dbID, containerID, partitionKey, id, ifMatch string) error

DeleteDocument removes a document after verifying ifMatch.

func (*InMemoryBackend) DeletePermission

func (b *InMemoryBackend) DeletePermission(dbID, userID, id string) error

DeletePermission removes a permission.

func (*InMemoryBackend) DeleteScript

func (b *InMemoryBackend) DeleteScript(dbID, collID string, kind scriptKind, id string) error

DeleteScript removes a script.

func (*InMemoryBackend) DeleteUser

func (b *InMemoryBackend) DeleteUser(dbID, id string) error

DeleteUser removes a user and its permissions.

func (*InMemoryBackend) ExecuteBatch

func (b *InMemoryBackend) ExecuteBatch(dbID, collID, partitionKey string, ops []batchOp) ([]BatchResult, bool, error)

ExecuteBatch runs ops atomically in one partition. When an operation fails the batch is rolled back, the failing result carries its status and every other result is 424. The bool reports whether it committed.

func (*InMemoryBackend) ExecuteSproc

func (b *InMemoryBackend) ExecuteSproc(dbID, collID, id, partitionKey string, args []any) (ScriptOutput, error)

ExecuteSproc runs a stored procedure against one partition. Everything it writes commits together or, on any failure, not at all. The script runs on a private copy of the container without holding the backend lock and is committed only if the container was not written meanwhile; after repeated conflicts it runs under the lock.

func (*InMemoryBackend) GetConflict

func (b *InMemoryBackend) GetConflict(dbID, collID, region, id string) (ConflictInfo, error)

GetConflict returns one conflicts-feed entry.

func (*InMemoryBackend) GetContainer

func (b *InMemoryBackend) GetContainer(dbID, containerID string) (ContainerInfo, error)

GetContainer retrieves a single container.

func (*InMemoryBackend) GetDatabase

func (b *InMemoryBackend) GetDatabase(id string) (DatabaseInfo, error)

GetDatabase retrieves a single database. Returns ErrDatabaseNotFound if absent.

func (*InMemoryBackend) GetDocument

func (b *InMemoryBackend) GetDocument(dbID, containerID, partitionKey, id string) (DocumentInfo, error)

GetDocument retrieves a single document by partition key and ID.

func (*InMemoryBackend) GetPermission

func (b *InMemoryBackend) GetPermission(dbID, userID, id string) (PermissionInfo, error)

GetPermission returns one permission.

func (*InMemoryBackend) GetScript

func (b *InMemoryBackend) GetScript(dbID, collID string, kind scriptKind, id string) (ScriptInfo, error)

GetScript returns one script.

func (*InMemoryBackend) GetThroughput

func (b *InMemoryBackend) GetThroughput(db, container string) (ThroughputInfo, error)

GetThroughput returns the offer of a database (container == "") or container.

func (*InMemoryBackend) GetThroughputByRID

func (b *InMemoryBackend) GetThroughputByRID(offerRID string) (ThroughputInfo, error)

GetThroughputByRID returns the offer with the given offer rid.

func (*InMemoryBackend) GetUser

func (b *InMemoryBackend) GetUser(dbID, id string) (UserInfo, error)

GetUser returns one user.

func (*InMemoryBackend) ListConflicts

func (b *InMemoryBackend) ListConflicts(dbID, collID, region string) ([]ConflictInfo, error)

ListConflicts returns the region's conflicts feed, oldest first. An empty region means the write region.

func (*InMemoryBackend) ListContainers

func (b *InMemoryBackend) ListContainers(dbID string) ([]ContainerInfo, error)

ListContainers returns a snapshot of all containers in dbID, sorted by ID.

func (*InMemoryBackend) ListDatabases

func (b *InMemoryBackend) ListDatabases() []DatabaseInfo

ListDatabases returns a snapshot of all databases, sorted by ID.

func (*InMemoryBackend) ListDocuments

func (b *InMemoryBackend) ListDocuments(dbID, containerID string) ([]DocumentInfo, error)

ListDocuments returns every live document in containerID, ordered by ID.

func (*InMemoryBackend) ListDocumentsPaged

func (b *InMemoryBackend) ListDocumentsPaged(
	dbID, containerID, token string, limit int,
) (page.Page[DocumentInfo], error)

ListDocumentsPaged returns one page of live documents; token and limit follow pkgs/page (limit <= 0 is unbounded).

func (*InMemoryBackend) ListPermissions

func (b *InMemoryBackend) ListPermissions(dbID, userID string) ([]PermissionInfo, error)

ListPermissions returns a user's permissions sorted by id.

func (*InMemoryBackend) ListScripts

func (b *InMemoryBackend) ListScripts(dbID, collID string, kind scriptKind) ([]ScriptInfo, error)

ListScripts returns every script of kind, sorted by id.

func (*InMemoryBackend) ListThroughputs

func (b *InMemoryBackend) ListThroughputs() []ThroughputInfo

ListThroughputs returns every provisioned offer.

func (*InMemoryBackend) ListUsers

func (b *InMemoryBackend) ListUsers(dbID string) ([]UserInfo, error)

ListUsers returns the users of dbID sorted by id.

func (*InMemoryBackend) PatchDocument

func (b *InMemoryBackend) PatchDocument(
	dbID, containerID, partitionKey, id string, req patchRequest, ifMatch string,
) (DocumentInfo, error)

PatchDocument applies a partial update to an existing document.

func (*InMemoryBackend) QueryDocuments

func (b *InMemoryBackend) QueryDocuments(
	dbID, containerID, query string, params []QueryParameter,
) ([]any, error)

QueryDocuments runs a Cosmos SQL query against containerID. Result values share nested data with stored documents and must be treated as read-only.

func (*InMemoryBackend) RangeShares

func (b *InMemoryBackend) RangeShares(dbID, collID string) []float64

RangeShares reports each partition's share of the container's documents, in layout order; an empty container shares evenly.

func (*InMemoryBackend) ReplaceContainer

func (b *InMemoryBackend) ReplaceContainer(dbID string, spec ContainerSpec) (ContainerInfo, error)

ReplaceContainer updates a container's defaultTtl and indexing policy. The partition key is immutable.

func (*InMemoryBackend) ReplaceDocument

func (b *InMemoryBackend) ReplaceDocument(
	dbID, containerID, partitionKey, id string, body map[string]any, ifMatch string,
) (DocumentInfo, error)

ReplaceDocument fully replaces an existing document's body; id and partition key are fixed by the request.

func (*InMemoryBackend) ReplacePermission

func (b *InMemoryBackend) ReplacePermission(dbID, userID, id string, spec PermissionSpec) (PermissionInfo, error)

ReplacePermission replaces permission id with spec; spec.ID may rename it.

func (*InMemoryBackend) ReplaceScript

func (b *InMemoryBackend) ReplaceScript(dbID, collID string, kind scriptKind, spec ScriptSpec) (ScriptInfo, error)

ReplaceScript overwrites an existing script's definition.

func (*InMemoryBackend) ReplaceThroughputByRID

func (b *InMemoryBackend) ReplaceThroughputByRID(offerRID string, spec ThroughputSpec) (ThroughputInfo, error)

ReplaceThroughputByRID replaces the offer with the given offer rid.

func (*InMemoryBackend) ReplaceUser

func (b *InMemoryBackend) ReplaceUser(dbID, id, newID string) (UserInfo, error)

ReplaceUser renames user id to newID, keeping its permissions.

func (*InMemoryBackend) Reset

func (b *InMemoryBackend) Reset()

Reset clears all in-memory state.

func (*InMemoryBackend) Restore

func (b *InMemoryBackend) Restore(ctx context.Context, data []byte) error

Restore loads backend state from a JSON snapshot. It implements persistence.Persistable. A snapshot's "databases" map, or any database's "Containers" map, or any container's "Documents" map, may legally be JSON null (a nil Go map after decode) rather than absent -- this is tolerated by initializing each to an empty map rather than leaving it nil, since a nil map is safe to range/read but panics on insertion (this was a real M2 bug in services/azuretable's Restore -- see AZURE.md's process rules).

func (*InMemoryBackend) RunQuery

func (b *InMemoryBackend) RunQuery(
	dbID, containerID, query string, params []QueryParameter, partitionKey string,
) (QueryResult, error)

RunQuery is QueryDocuments scoped to partitionKey (canonical JSON; empty means cross-partition), also reporting how many rows were scanned.

func (*InMemoryBackend) RunQueryOpts

func (b *InMemoryBackend) RunQueryOpts(
	dbID, containerID, query string, params []QueryParameter, partitionKey string, opts QueryOptions,
) (QueryResult, error)

RunQueryOpts is RunQuery with the indexing policy enforced: opts carries the request's scan switch.

func (*InMemoryBackend) SetAccountPolicies

func (b *InMemoryBackend) SetAccountPolicies(p AccountPolicies)

SetAccountPolicies applies the default consistency level, service-managed failover and backup mode.

func (*InMemoryBackend) SetAccountRegions

func (b *InMemoryBackend) SetAccountRegions(r AccountRegions)

SetAccountRegions replaces the regional topology reported by the account root. Lag, offline state and the consistency policy of regions that stay are kept.

func (*InMemoryBackend) SetPartitionLimits

func (b *InMemoryBackend) SetPartitionLimits(maxBytes int64, splitDelay time.Duration)

SetPartitionLimits overrides the physical partition storage limit (default 50 GB) and sets how long an asynchronous throughput scale-up takes (default 0: instant; the service takes "typically 4-6 hours").

func (*InMemoryBackend) SetRegionOffline

func (b *InMemoryBackend) SetRegionOffline(name string, offline bool) error

SetRegionOffline marks a region offline or online. The write region going offline fails over to the next online region by failover priority unless the account has automatic failover disabled.

func (*InMemoryBackend) SetServerless

func (b *InMemoryBackend) SetServerless(v bool)

SetServerless marks the account serverless: throughput cannot be provisioned and every container is capped.

func (*InMemoryBackend) SetThroughput

func (b *InMemoryBackend) SetThroughput(db, container string, spec ThroughputSpec) (ThroughputInfo, error)

SetThroughput creates or replaces the offer of a database (container == "") or container.

func (*InMemoryBackend) Snapshot

func (b *InMemoryBackend) Snapshot(ctx context.Context) []byte

Snapshot serialises the backend state to JSON. It implements persistence.Persistable.

func (*InMemoryBackend) SweepExpired

func (b *InMemoryBackend) SweepExpired() int

SweepExpired physically removes expired documents and returns how many were removed.

func (*InMemoryBackend) SweepPartitions

func (b *InMemoryBackend) SweepPartitions() int

SweepPartitions completes due scale-ups and splits partitions over the storage limit; it returns the splits.

func (*InMemoryBackend) SweepReplication

func (b *InMemoryBackend) SweepReplication() int

SweepReplication delivers due replicated writes; the janitor calls it so regions converge without traffic.

func (*InMemoryBackend) ThroughputBudget

func (b *InMemoryBackend) ThroughputBudget(db, coll string) RUBudget

ThroughputBudget reports the RU/s budget governing container coll of db.

type PartitionKeyRanges

type PartitionKeyRanges struct {
	Layout  *pkLayout
	RID     string
	Pending bool
}

PartitionKeyRanges is the container's partition key range feed.

type PermissionInfo

type PermissionInfo struct {
	Modified         time.Time
	ID               string
	RID              string
	DBID             string
	UserID           string
	Mode             string
	Resource         string
	Link             string
	PartitionKeyJSON string
	PartitionKey     json.RawMessage
}

PermissionInfo is a read-only snapshot of a permission. Link is the canonical id-based resource path.

type PermissionSpec

type PermissionSpec struct {
	ID           string
	Mode         string
	Resource     string
	PartitionKey json.RawMessage
}

PermissionSpec is the caller-supplied shape for creating or replacing a permission.

type Provider

type Provider struct{}

Provider implements service.Provider for the Azure Cosmos DB service. It registers no RouteMatcher on the shared single-port Router: the returned Handler is a service.BackgroundWorker serving its own listener on the fixed Cosmos emulator port (8081), and also runs the TTL sweeper.

func (*Provider) Init

Init initializes the CosmosDB service backend and handler. The configured port (Settings.Port, default DefaultPort) is only recorded here; the actual TCP bind happens synchronously in Handler.StartWorker, so a port-in-use failure is returned to the caller directly instead of being discovered later from a background goroutine.

func (*Provider) Name

func (p *Provider) Name() string

Name returns the service provider name.

type QueryOptions

type QueryOptions struct {
	// AllowScan permits queries the indexing policy cannot serve (x-ms-documentdb-query-enable-scan).
	AllowScan bool
}

QueryOptions are the request-level switches of a query.

type QueryParameter

type QueryParameter struct {
	Value any    `json:"value"`
	Name  string `json:"name"`
}

QueryParameter is one "@name"/value binding from a query request body.

type QueryResult

type QueryResult struct {
	Rows    []any
	Visited []*storedDocument
	Matched []*storedDocument
	Scanned int
	Loaded  float64
}

QueryResult is the output of one query execution; Scanned counts container rows examined.

type RUBudget

type RUBudget struct {
	Key    string
	Ranges []pkSpan
	Rate   float64
	Epoch  int64
}

RUBudget is the RU/s budget governing a container: a bucket key shared by every container drawing on the same offer, the total rate (0 = unlimited), the physical partition count and an epoch that changes whenever an offer is set, so callers can reset their meters.

func (RUBudget) Partitions

func (r RUBudget) Partitions() int

Partitions is the number of physical partitions.

type ScriptInfo

type ScriptInfo struct {
	Timestamp        time.Time
	ID               string
	Body             string
	TriggerType      string
	TriggerOperation string
	RID              string
	Self             string
	ETag             string
}

ScriptInfo is a read-only snapshot of a stored script.

type ScriptOutput

type ScriptOutput struct {
	Body    any
	Logs    []string
	Writes  int
	HasBody bool
}

ScriptOutput is the outcome of a stored procedure run.

type ScriptSpec

type ScriptSpec struct {
	ID               string
	Body             string
	TriggerType      string
	TriggerOperation string
}

ScriptSpec is the client-supplied definition of a script.

type Settings

type Settings struct {
	// MasterKey is the base64-encoded master key authorize verifies request
	// signatures against when ValidateAuth is true. Defaults to the real
	// emulator's own well-known key (DefaultMasterKey).
	MasterKey string `` //nolint:lll // config struct tags are intentionally verbose
	/* 248-byte string literal not displayed */
	// Port is the fixed TCP port for the dedicated Cosmos DB listener. See
	// handler.go's StartWorker for what happens when it's unavailable
	// (fails fast; no fallback pool, matching services/azureblob,
	// services/azurequeue, and services/azuretable).
	Port int `` //nolint:lll // config struct tags are intentionally verbose
	/* 172-byte string literal not displayed */
	// ValidateAuth opts into cryptographic master-key signature
	// verification of the Authorization header (opt-in, off by default --
	// mirrors services/s3's WithPresignValidation and pkgs/azureauth's
	// VerifySharedKey opt-in pattern). See masterkey.go.
	ValidateAuth bool `` //nolint:lll // config struct tags are intentionally verbose
	/* 169-byte string literal not displayed */
	// EnforceThroughput opts into 429 throttling against each container's (or shared database's) provisioned RU/s.
	EnforceThroughput bool `` //nolint:lll // config struct tags are intentionally verbose
	/* 199-byte string literal not displayed */
	// BurstCapacity lets throttled partitions spend banked idle RU/s (opt-in; needs enforce-throughput).
	BurstCapacity bool `` //nolint:lll // config struct tags are intentionally verbose
	/* 226-byte string literal not displayed */
	// Serverless models a serverless account: throughput cannot be provisioned and containers burst to 5000 RU/s.
	Serverless bool `` //nolint:lll // config struct tags are intentionally verbose
	/* 236-byte string literal not displayed */
	// ResourceTokenMaxSeconds is the longest accepted resource-token lifetime (600..86400).
	ResourceTokenMaxSeconds int `` //nolint:lll // config struct tags are intentionally verbose
	/* 253-byte string literal not displayed */
}

Settings holds service-level configuration for the Cosmos DB backend. Fields are picked up by the Kong CLI parser when this struct is embedded in the root CLI command (see cli.go's CLI.CosmosDB field), mirroring services/azuretable's Settings pattern.

func DefaultSettings

func DefaultSettings() Settings

DefaultSettings returns the default Settings. Used when no ConfigProvider is available at init time (e.g. tests constructing a Provider directly).

type StorageBackend

type StorageBackend interface {
	CreateDatabase(id string) (DatabaseInfo, error)
	GetDatabase(id string) (DatabaseInfo, error)
	ListDatabases() []DatabaseInfo
	DeleteDatabase(id string) error

	CreateUser(dbID, id string) (UserInfo, error)
	GetUser(dbID, id string) (UserInfo, error)
	ListUsers(dbID string) ([]UserInfo, error)
	ReplaceUser(dbID, id, newID string) (UserInfo, error)
	DeleteUser(dbID, id string) error

	CreatePermission(dbID, userID string, spec PermissionSpec) (PermissionInfo, error)
	GetPermission(dbID, userID, id string) (PermissionInfo, error)
	ListPermissions(dbID, userID string) ([]PermissionInfo, error)
	ReplacePermission(dbID, userID, id string, spec PermissionSpec) (PermissionInfo, error)
	DeletePermission(dbID, userID, id string) error

	CreateContainer(dbID string, spec ContainerSpec) (ContainerInfo, error)
	GetContainer(dbID, containerID string) (ContainerInfo, error)
	ListContainers(dbID string) ([]ContainerInfo, error)
	DeleteContainer(dbID, containerID string) error

	// CreateDocument creates (or, if upsert, inserts-or-replaces) a document
	// in containerID. The document's partition key value is derived from
	// body per the container's declared partition key path; body's "id"
	// field is used verbatim if present (a non-string "id" is rejected), or
	// generated if absent.
	CreateDocument(dbID, containerID string, body map[string]any, upsert bool) (DocumentInfo, error)
	GetDocument(dbID, containerID, partitionKey, id string) (DocumentInfo, error)
	ReplaceDocument(
		dbID, containerID, partitionKey, id string, body map[string]any, ifMatch string,
	) (DocumentInfo, error)
	DeleteDocument(dbID, containerID, partitionKey, id, ifMatch string) error
	// ListDocuments returns every document in containerID, ordered by ID,
	// for both the read-feed (GET .../docs) and the SQL query engine's FROM
	// clause. Cross-partition: it is not filtered by partition key.
	ListDocuments(dbID, containerID string) ([]DocumentInfo, error)

	// Reset clears all in-memory state. Used by the
	// POST /_gopherstack/reset endpoint for CI pipelines and rapid local development.
	Reset()
}

StorageBackend defines the interface for an Azure Cosmos DB (Core/SQL API) backend. Shaped after services/azuretable's StorageBackend: a narrow, testable seam between the wire handler and storage, so handler tests can substitute a fake.

ifMatch on ReplaceDocument/DeleteDocument threads through the same If-Match states services/azuretable's StorageBackend documents:

  • "" (no If-Match header): unconditional mutation.
  • any other string: the document must exist AND its current ETag must equal this value, else ErrETagMismatch.

partitionKey parameters are the caller-supplied partition key value's canonical JSON encoding (see canonicalPartitionKeyJSON), extracted from the mandatory x-ms-documentdb-partitionkey header on every point operation.

type ThroughputBackend

type ThroughputBackend interface {
	CheckThroughput(spec ThroughputSpec, containerLevel bool) error
	GetThroughput(db, container string) (ThroughputInfo, error)
	SetThroughput(db, container string, spec ThroughputSpec) (ThroughputInfo, error)
	ListThroughputs() []ThroughputInfo
	GetThroughputByRID(offerRID string) (ThroughputInfo, error)
	ReplaceThroughputByRID(offerRID string, spec ThroughputSpec) (ThroughputInfo, error)
	ThroughputBudget(db, coll string) RUBudget
	RangeShares(db, coll string) []float64
}

ThroughputBackend is implemented by backends that provision throughput offers.

type ThroughputInfo

type ThroughputInfo struct {
	Modified     time.Time
	OfferRID     string
	ResourceRID  string
	ResourceLink string
	Pending      bool
	Minimum      int
	ThroughputSpec
}

ThroughputInfo is a read-only snapshot of an offer.

type ThroughputSpec

type ThroughputSpec struct {
	Manual           int `json:"Throughput,omitempty"`
	AutoscaleMax     int `json:"AutoscaleMax,omitempty"`
	IncrementPercent int `json:"IncrementPercent,omitempty"`
}

ThroughputSpec is a provisioned-throughput setting: Manual RU/s, or an autoscale ceiling (with an optional auto-upgrade increment percentage). Exactly one of Manual and AutoscaleMax is non-zero.

func (ThroughputSpec) MinimumThroughput

func (s ThroughputSpec) MinimumThroughput() int

MinimumThroughput is the lowest value the offer can be lowered to.

func (ThroughputSpec) Validate

func (s ThroughputSpec) Validate() error

Validate checks the spec against the documented limits.

type UserInfo

type UserInfo struct {
	Modified time.Time
	ID       string
	RID      string
}

UserInfo is a read-only snapshot of a database user.

Jump to

Keyboard shortcuts

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