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

cosmosdb

package
v1.9.0 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: MIT Imports: 45 Imported by: 0

README

Azure Cosmos DB

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

Coverage

Metric Value
PARITY entries audited 32 (32 ok)
Feature families 23 (19 ok, 4 partial)
Known gaps 9
Deferred items 0
Resource leaks clean
Known gaps
  • Throughput: physical partitions are modelled from RU only, ceil(RU/10000) of the offer (autoscale uses its maximum); the documented 50 GB storage term is not modelled, a lowered throughput shrinks the ranges at once (the service never merges partitions), range ids are always 0..N-1 (no split parents or ids), partition keys map to ranges by an even split of a SHA-256 hash space with 64-bit EPK bounds (the service uses MurmurHash3 over the encoded key), a cross-partition request charges its RU evenly across all partitions rather than by work done, and a shared database offer is partitioned by its total RU; burst capacity is a model of the documented 300 s idle bank spent at up to 3000 RU/s total per partition (applicability conditions unverified, not enforced for partitions already at 3000 RU/s or more); autoscale reports only its minimum, x-ms-cosmos-current-throughput is not exposed by azcosmos and is not emitted; serverless accounts are a single process-wide mode (--cosmosdb-serverless) with the 5000 RU/s container cap but no 50 GB storage limit; the replace between manual and autoscale is accepted on the data plane; minimum throughput is a flat 400 RU/s (not storage- or container-count-derived); Table API and metadata operations are not metered; the throughput error texts (min 400 manual / 1000 autoscale, steps of 100 / 1000, max 1,000,000) are from documented limits and the 429 text follows the task wording, not captured service responses
  • IndexingPolicy: multi-key ORDER BY composite-index, excluded-path/scan and vector/full-text index enforcement exist (families.indexing, families.search); still open are spatial index validation and enforcement inside stored-procedure queries (the docs state neither); a single-key ORDER BY on a path the policy does not index is 400 (text from the Mongo-API troubleshooting page and Microsoft Q&A, same engine; the scan header does not bypass it), id and _ts are always indexed in consistent mode, and lazy mode is rejected with 400 because the index-policy page says new containers cannot select it (error text paraphrased, exemptions not modelled). Filter plus ORDER BY needs no composite index (the index-policy page: the query still succeeds, only RU cost differs) and the current page no longer requires vector paths in excludedPaths, so neither is enforced
  • MultiRegion: regions, failoverPriority, multi-write and manual failover (ARM failoverPriorityChange) are modelled as account metadata over ONE physical store, so there is no replication lag, no regional endpoint, no automatic failover, no preferred-region routing and no write conflicts or conflicts feed; the data plane is one account, so the last ARM account written decides the topology; consistency levels other than a static session token are not modeled
  • RequestCharge: an approximation of documented costs, not a metering of index and storage work
  • SQL: ORDER BY combined with GROUP BY is accepted although the real service may reject it (the ORDER BY and GROUP BY reference pages, checked 2026-10-24, state neither a restriction nor an error text, so behaviour stays permissive); spatial functions are planar/haversine approximations with no Multi* geometry operations and no Geometry-mode (planar metre) semantics; ST_ISVALIDDETAILED reasons beyond the unclosed-ring text are paraphrased; VectorDistance is exact (no approximate index, no quantization error, dataType only validated) and FullTextScore tokenization has no stemming (families.search); unsupported functions are a 400 parse error
  • ItemOperations: the all-versions-and-deletes feed keeps only the newest 10000 versions per container and ignores the continuous-backup retention window; pre/post triggers fire for create, upsert, replace and delete only (the triggers REST page: "creation, deletion, and replacement of a document"; the patch REST page has no trigger header and azcosmos transactional batch has no trigger option), so PATCH and batch run none; stored procedure callbacks run synchronously, and a stored procedure runs on a private copy of its container without the backend lock, committing only if the container was not written meanwhile (up to 4 tries, then under the write lock), so a long script no longer stalls other containers but a busy container can fall back to the lock; there is no server-side bulk operation (the SDKs implement bulk client-side over batches and point operations)
  • Containers: geospatialConfig is stored and echoed only (no planar Geometry behaviour); vectorEmbeddingPolicy and fullTextPolicy are validated and enforced (families.search); computed properties are not used for index selection; the replace-time error text for a changed unique key policy is unverified
  • TableAPI: a $batch answers a single bare query (point retrieve or entity-collection query with $filter/$top/$select, 200 feed in the part; the docs show only the point retrieve, and a query part carries no continuation headers because the Table API here pages nothing), but several changesets (the service processes the first and rejects the rest with 400; here the whole request is 400 because the rejection response shape is undocumented), is 400; the 4 MiB payload limit is enforced as 400 InvalidInput with no documented service error code; Table API responses carry no per-operation request charge or continuation beyond what pkgs/odatatable provides
  • ResourceTokens: a document permission matches by document id across all partition keys (ids repeat across keys; the permission docs define no partition scoping for a document resource, while container permissions with resourcePartitionKey are already restricted to that key); permissions on stored procedures, triggers, UDFs and attachments are rejected rather than modelled; a permission left pointing at a deleted container simply grants nothing; the minimum x-ms-documentdb-expiry-seconds is unverified (docs give only the 3600 default and the 18000 maximum)

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 (

	// 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")
	// ErrChangeFeedStart is returned when an all-versions-and-deletes read names no start.
	ErrChangeFeedStart = errors.New("cosmosdb: all versions and deletes change feed cannot start from the beginning")
)

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 1..18000.
	ErrInvalidTokenExpiry = errors.New("cosmosdb: x-ms-documentdb-expiry-seconds must be between 1 and 18000")
)
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 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.

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 AccountRegion

type AccountRegion struct {
	Name             string `json:"name"`
	FailoverPriority int    `json:"failoverPriority"`
}

AccountRegion is one geo-replica of the account; the lowest failover priority is the write region.

type AccountRegions

type AccountRegions struct {
	Regions    []AccountRegion `json:"regions,omitempty"`
	MultiWrite bool            `json:"multiWrite,omitempty"`
}

AccountRegions is the account's regional topology. Every region serves the same single in-memory store.

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 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
	Port          int
	SweepInterval time.Duration
	ValidateAuth  bool
	TLS           bool
	// EnforceThroughput rejects requests with 429 once a container's provisioned RU/s budget is overdrawn.
	EnforceThroughput bool
	// BurstCapacity lets a partition spend up to 300 s of idle RU/s, at up to 3000 RU/s, before throttling.
	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) 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) 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) 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) 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) 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) SetAccountRegions

func (b *InMemoryBackend) SetAccountRegions(r AccountRegions)

SetAccountRegions replaces the regional topology reported by the account root.

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) ThroughputBudget

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

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

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
	Scanned int
}

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

type RUBudget

type RUBudget struct {
	Key        string
	Rate       float64
	Epoch      int64
	Partitions int
}

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.

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 */
}

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
}

ThroughputBackend is implemented by backends that provision throughput offers.

type ThroughputInfo

type ThroughputInfo struct {
	Modified     time.Time
	OfferRID     string
	ResourceRID  string
	ResourceLink string
	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