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
- Variables
- func ExecuteQuery(query string, params []QueryParameter, docs []DocumentInfo) ([]any, error)
- func VerifyMasterKey(masterKey string, r *http.Request) (bool, error)
- type AccountRegion
- type AccountRegions
- type BatchResult
- type ChangeVersion
- type ConfigProvider
- type ContainerInfo
- type ContainerPolicies
- type ContainerSpec
- type DatabaseInfo
- type DocumentInfo
- type Handler
- func (h *Handler) AcceptKey(key string)
- func (h *Handler) ExtractOperation(c *echo.Context) string
- func (h *Handler) ExtractResource(c *echo.Context) string
- func (h *Handler) GetSupportedOperations() []string
- func (h *Handler) Handler() echo.HandlerFunc
- func (h *Handler) MatchPriority() int
- func (h *Handler) Name() string
- func (h *Handler) Reset()
- func (h *Handler) Restore(ctx context.Context, data []byte) error
- func (h *Handler) RevokeKey(key string)
- func (h *Handler) RouteMatcher() service.Matcher
- func (h *Handler) Shutdown(ctx context.Context)
- func (h *Handler) SignRequest(r *http.Request) error
- func (h *Handler) Snapshot(ctx context.Context) []byte
- func (h *Handler) StartWorker(ctx context.Context) error
- func (h *Handler) TLSCertPEM() []byte
- type InMemoryBackend
- func (b *InMemoryBackend) AccountRegions() AccountRegions
- func (b *InMemoryBackend) AttachTableAPI(t tableSnapshotter)
- func (b *InMemoryBackend) CheckThroughput(spec ThroughputSpec, containerLevel bool) error
- func (b *InMemoryBackend) CreateContainer(dbID string, spec ContainerSpec) (ContainerInfo, error)
- func (b *InMemoryBackend) CreateDatabase(id string) (DatabaseInfo, error)
- func (b *InMemoryBackend) CreateDocument(dbID, containerID string, body map[string]any, upsert bool) (DocumentInfo, error)
- func (b *InMemoryBackend) CreatePermission(dbID, userID string, spec PermissionSpec) (PermissionInfo, error)
- func (b *InMemoryBackend) CreateScript(dbID, collID string, kind scriptKind, spec ScriptSpec) (ScriptInfo, error)
- func (b *InMemoryBackend) CreateUser(dbID, id string) (UserInfo, error)
- func (b *InMemoryBackend) DeleteContainer(dbID, containerID string) error
- func (b *InMemoryBackend) DeleteDatabase(id string) error
- func (b *InMemoryBackend) DeleteDocument(dbID, containerID, partitionKey, id, ifMatch string) error
- func (b *InMemoryBackend) DeletePermission(dbID, userID, id string) error
- func (b *InMemoryBackend) DeleteScript(dbID, collID string, kind scriptKind, id string) error
- func (b *InMemoryBackend) DeleteUser(dbID, id string) error
- func (b *InMemoryBackend) ExecuteBatch(dbID, collID, partitionKey string, ops []batchOp) ([]BatchResult, bool, error)
- func (b *InMemoryBackend) ExecuteSproc(dbID, collID, id, partitionKey string, args []any) (ScriptOutput, error)
- func (b *InMemoryBackend) GetContainer(dbID, containerID string) (ContainerInfo, error)
- func (b *InMemoryBackend) GetDatabase(id string) (DatabaseInfo, error)
- func (b *InMemoryBackend) GetDocument(dbID, containerID, partitionKey, id string) (DocumentInfo, error)
- func (b *InMemoryBackend) GetPermission(dbID, userID, id string) (PermissionInfo, error)
- func (b *InMemoryBackend) GetScript(dbID, collID string, kind scriptKind, id string) (ScriptInfo, error)
- func (b *InMemoryBackend) GetThroughput(db, container string) (ThroughputInfo, error)
- func (b *InMemoryBackend) GetThroughputByRID(offerRID string) (ThroughputInfo, error)
- func (b *InMemoryBackend) GetUser(dbID, id string) (UserInfo, error)
- func (b *InMemoryBackend) ListContainers(dbID string) ([]ContainerInfo, error)
- func (b *InMemoryBackend) ListDatabases() []DatabaseInfo
- func (b *InMemoryBackend) ListDocuments(dbID, containerID string) ([]DocumentInfo, error)
- func (b *InMemoryBackend) ListDocumentsPaged(dbID, containerID, token string, limit int) (page.Page[DocumentInfo], error)
- func (b *InMemoryBackend) ListPermissions(dbID, userID string) ([]PermissionInfo, error)
- func (b *InMemoryBackend) ListScripts(dbID, collID string, kind scriptKind) ([]ScriptInfo, error)
- func (b *InMemoryBackend) ListThroughputs() []ThroughputInfo
- func (b *InMemoryBackend) ListUsers(dbID string) ([]UserInfo, error)
- func (b *InMemoryBackend) PatchDocument(dbID, containerID, partitionKey, id string, req patchRequest, ifMatch string) (DocumentInfo, error)
- func (b *InMemoryBackend) QueryDocuments(dbID, containerID, query string, params []QueryParameter) ([]any, error)
- func (b *InMemoryBackend) ReplaceContainer(dbID string, spec ContainerSpec) (ContainerInfo, error)
- func (b *InMemoryBackend) ReplaceDocument(dbID, containerID, partitionKey, id string, body map[string]any, ...) (DocumentInfo, error)
- func (b *InMemoryBackend) ReplacePermission(dbID, userID, id string, spec PermissionSpec) (PermissionInfo, error)
- func (b *InMemoryBackend) ReplaceScript(dbID, collID string, kind scriptKind, spec ScriptSpec) (ScriptInfo, error)
- func (b *InMemoryBackend) ReplaceThroughputByRID(offerRID string, spec ThroughputSpec) (ThroughputInfo, error)
- func (b *InMemoryBackend) ReplaceUser(dbID, id, newID string) (UserInfo, error)
- func (b *InMemoryBackend) Reset()
- func (b *InMemoryBackend) Restore(ctx context.Context, data []byte) error
- func (b *InMemoryBackend) RunQuery(dbID, containerID, query string, params []QueryParameter, partitionKey string) (QueryResult, error)
- func (b *InMemoryBackend) RunQueryOpts(dbID, containerID, query string, params []QueryParameter, partitionKey string, ...) (QueryResult, error)
- func (b *InMemoryBackend) SetAccountRegions(r AccountRegions)
- func (b *InMemoryBackend) SetServerless(v bool)
- func (b *InMemoryBackend) SetThroughput(db, container string, spec ThroughputSpec) (ThroughputInfo, error)
- func (b *InMemoryBackend) Snapshot(ctx context.Context) []byte
- func (b *InMemoryBackend) SweepExpired() int
- func (b *InMemoryBackend) ThroughputBudget(db, coll string) RUBudget
- type PermissionInfo
- type PermissionSpec
- type Provider
- type QueryOptions
- type QueryParameter
- type QueryResult
- type RUBudget
- type ScriptInfo
- type ScriptOutput
- type ScriptSpec
- type Settings
- type StorageBackend
- type ThroughputBackend
- type ThroughputInfo
- type ThroughputSpec
- type UserInfo
Constants ¶
const ( // PermissionModeAll and PermissionModeRead are the permissionMode values. PermissionModeAll = "All" PermissionModeRead = "Read" )
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.
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 ¶
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") )
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.
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.
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") )
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") )
var ErrMalformedAuthorization = errors.New("cosmosdb: malformed Authorization header")
ErrMalformedAuthorization is returned by VerifyMasterKey when the request's Authorization header cannot be parsed.
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 ¶
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 ¶
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 ¶
AcceptKey makes key a valid master key in addition to MasterKey, for keys the ARM control plane hands out.
func (*Handler) ExtractOperation ¶
ExtractOperation extracts the Cosmos DB operation name from the request, for metrics labeling.
func (*Handler) ExtractResource ¶
ExtractResource extracts the resource path, for metrics labeling.
func (*Handler) GetSupportedOperations ¶
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 ¶
MatchPriority returns the routing priority for the CosmosDB handler. Irrelevant in practice since RouteMatcher never matches; 0 (lowest) is the safe default.
func (*Handler) Reset ¶
func (h *Handler) Reset()
Reset clears all in-memory state, Core/SQL and Table API alike.
func (*Handler) RevokeKey ¶
RevokeKey stops accepting a key added by AcceptKey; the configured MasterKey is never revoked.
func (*Handler) RouteMatcher ¶
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) SignRequest ¶
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 ¶
Snapshot implements persistence.Persistable by delegating to the backend.
func (*Handler) StartWorker ¶
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 ¶
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) 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 ¶
func (p *Provider) Init(ctx *service.AppContext) (service.Registerable, error)
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.
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 ¶
QueryParameter is one "@name"/value binding from a query request body.
type QueryResult ¶
QueryResult is the output of one query execution; Scanned counts container rows examined.
type RUBudget ¶
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 ¶
ScriptOutput is the outcome of a stored procedure run.
type ScriptSpec ¶
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.
Source Files
¶
- account_ops.go
- auth.go
- batch.go
- changefeed.go
- changelog.go
- container_ops.go
- container_policy.go
- database_ops.go
- document_ops.go
- errors.go
- fulltext.go
- handler.go
- indexing.go
- interfaces.go
- item_tx.go
- keyring.go
- masterkey.go
- models.go
- offer_ops.go
- paging.go
- partitionkey.go
- partitions.go
- patch.go
- permission_ops.go
- persistence.go
- provider.go
- query_resources.go
- query_rows.go
- regions.go
- ru.go
- script_engine.go
- script_env.go
- script_exec.go
- script_ops.go
- scripts.go
- search_coll.go
- settings.go
- sql_agg.go
- sql_ast.go
- sql_eval.go
- sql_exec.go
- sql_funcs.go
- sql_funcs_ext.go
- sql_parser.go
- sql_resolve.go
- sql_spatial.go
- sql_tokenizer.go
- store.go
- table_api.go
- table_api_ops.go
- table_batch.go
- throttle.go
- throughput.go
- token.go
- triggers.go
- ttl.go
- udf.go
- users.go
- users_ops.go
- vector.go