Documentation
¶
Overview ¶
Package rest serves Mongo collections with the HTTP contract of Python Eve, so the gateways that call the Eve APIs keep working unchanged: where/sort/projection/page/max_results, the _items/_links/_meta envelope, If-Match/ETag, Eve's error envelope and Cerberus validation messages.
The package has two layers:
- Service: the resource operations without HTTP (Eve's getitem, post_internal, patch_internal...). Custom endpoints and tests use it.
- API: the HTTP handlers that translate requests and responses.
Eve's event hooks are the Hooks of a Resource. Pre-write hooks run in the same Mongo transaction as the write, which is where an outbox event must be recorded.
Index ¶
- Constants
- Variables
- func IsNotFound(err error) bool
- func ParseSort(raw string) (bson.D, error)
- func ParseWhere(raw string, denylist []string) (bson.M, error)
- func Render(v any) any
- func RenderISO(v any) any
- func RenderISOOffset(v any) any
- func RequestArgs(ctx context.Context) url.Values
- func WriteError(w http.ResponseWriter, r *http.Request, err error)
- func WriteJSON(w http.ResponseWriter, status int, body any)
- type API
- func (a *API) Handle(pattern string, h http.Handler)
- func (a *API) Register(res *Resource) *Service
- func (a *API) RequireAuth(h http.Handler) http.Handler
- func (a *API) ResourceURLs() []string
- func (a *API) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (a *API) Service(name string) *Service
- type Adapter
- type AdditionalLookup
- type Datasource
- type Doc
- type ErrDeniedOperator
- type Error
- type ErrorClassifier
- type Field
- type FieldType
- type Hooks
- type IDCodec
- type IfMatch
- type InsertError
- type Issues
- type ListQuery
- type ListResult
- type Messages
- type NoTransaction
- type Options
- type Pagination
- type PreconditionFailedError
- type QueryAdapter
- type Resource
- type RetryOptions
- type Schema
- type Service
- func (s *Service) CheckEtag(original Doc, ifMatch string) error
- func (s *Service) Delete(ctx context.Context, lookup any, opts WriteOptions) error
- func (s *Service) Find(ctx context.Context, lookup any) (Doc, error)
- func (s *Service) Get(ctx context.Context, lookup any) (Doc, error)
- func (s *Service) Insert(ctx context.Context, docs []Doc, opts WriteOptions) ([]Doc, error)
- func (s *Service) ItemBody(doc Doc) map[string]any
- func (s *Service) List(ctx context.Context, q *ListQuery) (*ListResult, error)
- func (s *Service) Patch(ctx context.Context, lookup any, changes Doc, opts WriteOptions) (Doc, error)
- func (s *Service) Replace(ctx context.Context, lookup any, doc Doc, opts WriteOptions) (Doc, error)
- func (s *Service) Resource() *Resource
- func (s *Service) WithTransaction(ctx context.Context, fn func(ctx context.Context) error) error
- func (s *Service) WriteFound(w http.ResponseWriter, r *http.Request, lookup bson.M)
- func (s *Service) WriteItem(w http.ResponseWriter, r *http.Request, doc Doc)
- func (s *Service) WriteList(w http.ResponseWriter, r *http.Request, lookup bson.M)
- func (s *Service) WriteListFallback(w http.ResponseWriter, r *http.Request, lookup, fallback bson.M)
- func (s *Service) WriteResult(doc Doc) map[string]any
- type Store
- type Transactor
- type ValidationError
- type WriteOptions
Constants ¶
const DateFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
DateFormat is Eve's DATE_FORMAT, used in responses and accepted in where.
const HeaderDryRun = "X-Dry-Run"
HeaderDryRun is set to "true" on every response of an API in dry run.
Variables ¶
var ( ErrNotFound = Abort(http.StatusNotFound, "") ErrPreconditionRequired = Abort(http.StatusPreconditionRequired, msgIfMatchRequired) )
Errors returned by Service.
var ( // Werkzeug1 is the text of Werkzeug >= 1.0 (Eve 1.x and 2.x). Werkzeug1 = Messages{ http.StatusBadRequest: msgBadRequest, http.StatusNotFound: msgNotFound, http.StatusMethodNotAllowed: msgMethodNotAllowed, http.StatusConflict: msgConflict, http.StatusInternalServerError: msgInternal, } // Werkzeug0 is the text of Werkzeug 0.11 (Eve 0.7). Werkzeug0 = Messages{ http.StatusBadRequest: msgBadRequest, http.StatusNotFound: "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.", http.StatusMethodNotAllowed: msgMethodNotAllowed, http.StatusConflict: "A conflict happened while processing the request. The resource might have been modified while the request was being processed.", http.StatusInternalServerError: "The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.", } )
var DefaultQueryDenylist = []string{"$where", "$function", "$accumulator"}
DefaultQueryDenylist blocks the operators that run JavaScript on the server. Eve's default MONGO_QUERY_BLACKLIST also blocks $regex; resources that kept that default must add it to Resource.QueryDenylist.
var PublicGET = []string{http.MethodGet}
PublicGET is the PUBLIC_METHODS/PUBLIC_ITEM_METHODS of every Eve API.
Functions ¶
func IsNotFound ¶
IsNotFound reports whether err means the document does not exist.
func ParseSort ¶
ParseSort accepts both of Eve's syntaxes: [("field", -1), ("other", 1)] and "-field,other". The first is read by ast.literal_eval, so pairs may also be lists, as in JSON ([["field", -1]]), and it may be a dict ({"field": -1}), sorted in the order of its keys. An empty list or dict is no sort.
func ParseWhere ¶
ParseWhere decodes a JSON Mongo query and converts values the way Eve's _mongotize does: strings in DATE_FORMAT become dates and 24 hex strings become ObjectIDs. Eve also accepts Python expressions (slug=="x"); that syntax is not supported and returns an error.
func Render ¶
Render converts a stored document into Eve's JSON representation: ObjectIDs as hex strings and dates in DATE_FORMAT.
func RenderISO ¶
RenderISO converts a stored document into plain JSON with ISO 8601 dates without offset, as Eve-Elastic serializes datetimes.
func RenderISOOffset ¶
RenderISOOffset is RenderISO with the +00:00 offset, as the Python Elasticsearch client serializes the timezone aware datetimes of Eve (tags-api in HLG: "2026-10-26T18:24:29+00:00").
func RequestArgs ¶
RequestArgs returns the query string of the request being served, for hooks that read parameters Eve's parse_request exposed (e.g. a custom projection key).
func WriteError ¶
func WriteError(w http.ResponseWriter, r *http.Request, err error)
WriteError writes the Eve response for an error returned by Service or a hook; unknown errors become 500 and are logged.
Types ¶
type API ¶
type API struct {
// contains filtered or unexported fields
}
API serves a set of resources with Eve's HTTP contract.
func (*API) Handle ¶
Handle adds a custom route. More specific patterns win over the resource routes, e.g. "POST /articles/{id}/publish".
func (*API) RequireAuth ¶
RequireAuth protects a custom endpoint with the API authentication.
func (*API) ResourceURLs ¶
ResourceURLs lists the resource routes in registration order.
type Adapter ¶ added in v0.102.0
type Adapter interface {
QueryAdapter
IDCodec
ErrorClassifier
// Find lists documents; filter/sort/projection are whatever
// CombineFilter/CombineSort/CombineProjection returned. limit <= 0
// means no skip/limit is applied. Parameter order intentionally
// matches plan section 3's pseudocode, not Store.Find's (filter,
// skip, limit, sort, projection) -- mongoAdapter.Find is the one
// place that transposes between the two; a second implementation
// should double check it against this doc comment, not Store's.
Find(ctx context.Context, filter, sort, projection any, skip, limit int64) ([]Doc, error)
CountDocuments(ctx context.Context, filter any) (int64, error)
// FindOne reads one document; lookup is whatever CombineFilter (or
// WriteLookup, for a write's own re-read) returned.
FindOne(ctx context.Context, lookup, projection any) (Doc, error)
// InsertMany writes docs, computing and setting each one's _etag in
// place -- _id/_created/_updated are already set by Service.Insert,
// before the OnInsert hooks ran; _etag is adapter-specific (a
// content hash for Mongo, "1" for a fresh Postgres row) and is set
// here, after the hooks, immediately before the write.
InsertMany(ctx context.Context, docs []Doc) error
// UpdateOne writes updated's business fields changed (changes
// names which keys) at lookup, and sets updated's final _etag/
// _updated in place before returning -- a fresh value the
// implementation is itself responsible for, computed however its
// backend actually determines it: a content hash set right before
// the write for a backend with no way to read a value back (Mongo;
// mongoAdapter.setEtag), or the value a RETURNING clause confirmed
// the write actually produced, for a backend that has one
// (Postgres's version counter). Either way, the caller never
// computes or sets _etag/_updated itself. matched == 0 without an
// error is not a failure: the caller (Service's checkMatched)
// decides 404 vs 412 by re-reading.
UpdateOne(ctx context.Context, lookup any, updated, changes Doc) (matched int64, err error)
// ReplaceOne overwrites the whole document at lookup, setting
// replacement's final _etag/_updated in place, same contract as
// UpdateOne.
ReplaceOne(ctx context.Context, lookup any, replacement Doc) (matched int64, err error)
DeleteOne(ctx context.Context, lookup any) (deleted int64, err error)
// MergePatch applies changes to original's business fields only
// (original's meta fields pass through untouched) -- Eve's
// MERGE_NESTED_DOCUMENTS deep merge for Mongo, RFC 7396 JSON Merge
// Patch for Postgres (seção 10, deliberate divergence). The caller
// sets _updated/_etag on the result afterward.
MergePatch(original, changes Doc) (Doc, error)
// ValidatesMergedDocument reports whether patchOnce (section 9.4)
// must validate the whole post-merge document against the
// resource's Schema before writing it, in addition to the
// pre-merge validation of the client's own PATCH body that always
// runs. mongoAdapter returns false -- Mongo keeps today's exact
// behavior, validating only what the client sent. postgresAdapter
// returns true: RFC 7396's merge can delete a key the Schema marks
// Required (a Required+Nullable field's null never means "store
// null", it means "remove the key"), and only a check against the
// merged result catches that before the write.
ValidatesMergedDocument() bool
// EqualsFilter builds "field == value", optionally excluding one
// document by excludeID -- the friendly pre-check a Schema's
// unique validation runs before a write; the real uniqueness
// guarantee is the backend's own unique index.
EqualsFilter(field string, value any, excludeID any) (any, error)
}
Adapter is the full backend seam Service writes through -- the unified interface ADR-0002/this plan's section 3 describes. QueryAdapter/IDCodec/ErrorClassifier (above) were extracted first (Fase 0), as three separate, independently testable interfaces; Adapter embeds all three and adds the CRUD/merge/uniqueness methods a Resource needs to never touch Store directly. mongoAdapter (this package, Fase 4a) and restpostgres's postgresAdapter (Fase 2-4b) both implement it in full, each with its own `var _ Adapter = (*...)(nil)` assertion.
Fase 0/2's history, not repeated here to reopen it: Store stays bson.M/bson.D-typed (rest/store.go) -- Adapter does not replace it, it sits in front of it. A Resource with Adapter set never calls Store at all (Resource.setDefaults only builds a mongoAdapter wrapping Store when Adapter is nil); a Postgres Resource sets Adapter directly and leaves Store nil.
type AdditionalLookup ¶
type AdditionalLookup struct {
Field string
Pattern *regexp.Regexp
// Filter builds the lookup instead of {Field: value}, for a custom
// lookup route that matches several fields.
Filter func(value string) bson.M
// PathLinks builds the item links from the request path, as Eve's
// resource_link does for a custom Flask route that calls getitem
// (videos' find_by_slug): collection "videos/<slug>", self
// "videos/<slug>/<id>".
PathLinks bool
}
AdditionalLookup is Eve's additional_lookup. Eve registers it for reads only.
type Datasource ¶
type Datasource struct {
// Projection is the default projection (fields returned when the client
// does not send one).
Projection bson.M
// Filter is always applied to reads and writes.
Filter bson.M
// DefaultSort is used when the client does not send sort.
DefaultSort bson.D
}
Datasource mirrors Eve's datasource settings.
type Doc ¶
Doc is a stored document, from either backend. A business field's concrete Go type for a number read back from storage depends on which: Mongo's own driver decodes BSON straight into int64/float64; Postgres' decodeDoc (restpostgres/crud.go) decodes the stored jsonb with UseNumber() instead, into a json.Number, deliberately -- the whole reason restpostgres/crud.go exists is so a value beyond what float64 can hold exactly (Fase 0b of the Postgres portability plan) comes back exact too. A hook written against one backend that reads a numeric field with value.(float64) needs value.(json.Number) (or both) to work against the other.
func ReadBody ¶
ReadBody decodes a JSON object; custom endpoints use it. A JSON number in the result is a json.Number (Fase 0b of the Postgres portability plan, exact literal text, never a lossy float64) -- a caller written before this change that still does body["age"]. (float64) gets ok=false now, not the old value, since the type genuinely changed; switch to body["age"].(json.Number) and its Int64()/Float64() methods.
type ErrDeniedOperator ¶
type ErrDeniedOperator struct{ Operator string }
ErrDeniedOperator is returned when where uses a denied operator.
func (ErrDeniedOperator) Error ¶
func (e ErrDeniedOperator) Error() string
type Error ¶
type Error struct {
Status int
Message string
// RetryExhaustedReason names why patchOnce's retry loop gave up
// (section 9.7/9.8 of the Postgres portability plan): "max_attempts"
// or "max_duration". Empty for every error that isn't that -- an
// additive field, not a new status code.
RetryExhaustedReason string
}
Error is an error with the HTTP status Eve would answer. Hooks return it to abort a request, like flask.abort in the Python APIs.
type ErrorClassifier ¶ added in v0.102.0
type ErrorClassifier interface {
// IsNotFound reports whether err means a lookup found no document.
IsNotFound(err error) bool
// IsDuplicateKey reports whether err means a unique index was
// violated.
IsDuplicateKey(err error) bool
// IsClientError reports whether err was caused by the client's query
// itself (a bad filter value, an invalid regular expression...), not
// the server or the connection.
IsClientError(err error) bool
// IsTimeout reports whether err means the operation ran out of time.
IsTimeout(err error) bool
// ClassifiesWriteTimeouts reports whether Service's writeError
// (section 12 of the Postgres portability plan) may run a write's
// backend error through IsTimeout at all, turning a true result
// into a 503 before returning it from the Transactor.WithTransaction
// closure it ran inside of. mongoAdapter returns false:
// platform/mongodb's Transactor.WithTransaction hands that very
// closure's return value straight to the driver's own
// sess.WithTransaction, which inspects the *original* error for a
// TransientTransactionError label to decide whether to silently
// retry the whole transaction -- replacing it with Abort(503, "")
// here, even only for a write IsTimeout would also recognize,
// would erase that label and turn an error the driver already
// retries transparently into an immediate, un-retried 503.
// postgresAdapter returns true: platform/postgres's Transactor has
// no such label-based retry (a plain BeginTx/fn/Commit/Rollback,
// confirmed by reading it), so nothing is lost by classifying
// 57014/40P01/40001 as 503 from inside the closure.
ClassifiesWriteTimeouts() bool
}
ErrorClassifier tells Service what kind of failure a Store operation returned, so the HTTP status it picks does not depend on checking a backend-specific error value (mongo.ErrNoDocuments, mongo.IsTimeout...) at each call site.
Fase 0 of the Postgres portability work (see website/docs/reference/architecture-decisions.md, ADR-0002): extracted out of rest/service.go, with mongoAdapter implementing it exactly as that code already behaved — no behavior change for Mongo.
type Field ¶
type Field struct {
Type FieldType
Required bool
Nullable bool
Unique bool
Default any
// Allowed lists the accepted values; for lists, every element.
Allowed []any
// MinLength and MaxLength apply to strings and lists (0 = unchecked).
MinLength int
MaxLength int
// Min and Max apply to numbers.
Min, Max *float64
// NotEmpty is Cerberus' empty: False.
NotEmpty bool
// AllowEmpty is an explicit empty: True: an empty value skips the
// remaining rules (Cerberus 1.3 _validate_empty drops minlength, regex,
// allowed...). Without it, "" is still checked against Regex.
AllowEmpty bool
Regex *regexp.Regexp
// Schema validates the keys of a dict.
Schema Schema
// AllowUnknown accepts keys outside Schema in a dict.
AllowUnknown bool
// Items validates every element of a list.
Items *Field
// Check runs after the other rules (Cerberus' check_with or a custom
// type). doc is the document being validated (the changes on PATCH, as
// Cerberus' self.document). It returns nil or the issue: a message or
// nested Issues.
Check func(ctx context.Context, value any, doc map[string]any) any
}
Field is a Cerberus field definition. The messages follow Cerberus 1.3.
type FieldType ¶
type FieldType string
FieldType is the subset of Cerberus types used by the Eve APIs. An empty type accepts any value.
type Hooks ¶
type Hooks struct {
// OnPreGet may change the query before a GET (Eve's on_pre_GET).
OnPreGet []func(ctx context.Context, q *ListQuery) error
// OnFetchedResource and OnFetchedItem may change the documents before
// they are rendered (Eve's on_fetched_resource / on_fetched_item).
OnFetchedResource []func(ctx context.Context, docs []Doc) error
OnFetchedItem []func(ctx context.Context, doc Doc) error
// OnPrepare runs once per written document, after validation and before
// the transaction (original is nil on insert). It is the place for HTTP
// calls: the hooks below run inside the transaction, which they would
// hold open, and run again when the driver retries it.
OnPrepare []func(ctx context.Context, doc, original Doc) error
OnInsert []func(ctx context.Context, docs []Doc) error
OnInserted []func(ctx context.Context, docs []Doc) error
// updates holds only the changed fields, original the stored document.
OnUpdate []func(ctx context.Context, updates, original Doc) error
OnUpdated []func(ctx context.Context, updates, original Doc) error
OnReplace []func(ctx context.Context, replacement, original Doc) error
OnReplaced []func(ctx context.Context, replacement, original Doc) error
OnDelete []func(ctx context.Context, original Doc) error
OnDeleted []func(ctx context.Context, original Doc) error
}
Hooks mirror Eve's event hooks. Each list runs in order; behaviors that are shared between resources (audit, Elasticsearch sync, outbox) are Hooks values combined with Use.
Pre-write hooks (OnInsert, OnUpdate, OnReplace, OnDelete) run inside the write transaction: an error aborts the write, and an *Error sets the status. Post-write hooks run after the commit; their errors are logged and do not change the response.
type IDCodec ¶ added in v0.102.0
type IDCodec interface {
// NewID generates the id of a document being inserted.
NewID() any
// IDString renders id the way it appears in a URL or a response body.
IDString(id any) string
// LookupByID parses value, taken from a URL path segment, as an id;
// ok is false when value does not look like an id at all.
LookupByID(value string) (id any, ok bool)
// LookupID adapts an id already stored in a Doc for use inside a
// filter (e.g. excluding the current document from a uniqueness
// check).
LookupID(id any) any
}
IDCodec generates and parses the `_id` field's values.
type IfMatch ¶ added in v0.102.0
type IfMatch struct {
// Any is true for the wildcard "*".
Any bool
// contains filtered or unexported fields
}
IfMatch is a parsed If-Match precondition (RFC 7232 §3.1): either the wildcard "*" (any current representation satisfies it) or a list of entity-tags, compared with the strong comparison function the RFC requires for If-Match — a weak entity-tag in the list can never match.
WriteOptions.IfMatch carries this type (Fase 4b): http.go's update/ delete handlers build it from the request's If-Match header(s) via ParseIfMatch, and Service.checkEtag/patchOnce's retry loop (section 9 of the Postgres portability plan) consume it -- Any is what lets a PATCH under "If-Match: *" retry an optimistic-concurrency conflict instead of always answering the first one with 412.
func ParseIfMatch ¶ added in v0.102.0
ParseIfMatch parses the value(s) of one or more If-Match header lines, e.g. http.Header.Values("If-Match") — RFC 7230 §3.2.2 lets a field repeat, each repetition appending to the same comma-separated list. ok is false when no usable element (wildcard or entity-tag) was found.
func (IfMatch) IsZero ¶ added in v0.102.0
IsZero reports whether no If-Match condition was present at all — neither the wildcard nor any entity-tag — the same as the header being absent, or present but empty after RFC 7230 §7's tolerated empty list elements are discarded.
func (IfMatch) StrongMatches ¶ added in v0.102.0
StrongMatches reports whether current — an unquoted, unweak etag value such as a stored "_etag" — satisfies this condition: true for the wildcard, or when current equals one of the listed entity-tags that is not itself weak (If-Match never matches by weak comparison).
func (IfMatch) StrongMatchesAny ¶ added in v0.102.0
StrongMatchesAny is StrongMatches tried against several candidates in turn -- the stored etag plus, for a resource with CompatibleEtags, the older etags a write replaced -- true when any one of them satisfies m (or m is the wildcard, which never even looks at candidates).
type InsertError ¶
InsertError is returned by Service.Insert when some documents are invalid; Results has one entry per document, nil for the valid ones.
func (*InsertError) Error ¶
func (e *InsertError) Error() string
type Issues ¶
Issues maps a field to its error message (or nested Issues), as Eve's _issues.
func ValidateDict ¶
ValidateDict validates a nested document against schema; custom checks use it for schemas chosen at runtime (e.g. vars templates).
type ListQuery ¶
type ListQuery struct {
Filter any
Sort any
Projection any
Page int
MaxResults int
// ShowDeleted lists soft deleted documents too: Eve checks the presence
// of show_deleted, not its value.
ShowDeleted bool
// contains filtered or unexported fields
}
ListQuery is the parsed form of Eve's query string. Filter/Sort/ Projection are whatever the resource's own Adapter.ParseWhere/ ParseSort/ParseProjection produced -- bson.M/bson.D/bson.M for a Mongo resource (mongoAdapter delegates to the package-level parseWhere/ParseSort/parseProjection below, unchanged), a backend-specific type for any other one (e.g. restpostgres's postgres.Query/[]SortTerm/Projection).
func ParseListQuery ¶
ParseListQuery parses where, sort, projection, page and max_results with Eve's rules (eve.utils.parse_request): an invalid or non positive max_results falls back to the default, max_results is capped at the limit, page uses its absolute value and an invalid page is ignored. With pagination disabled the default is 0 (no limit), there is no cap and page is not read.
where/sort/projection are decoded with Mongo's own rules (parseWhere/ ParseSort/parseProjection below) regardless of the eventual resource's backend -- fine for this function's own callers (itemBody's link-building echo, and direct use in tests), which only ever read the raw query string back (queryString) or pagination, never Filter/Sort/Projection's parsed value. A resource's own collection GET goes through parseListQueryFor instead, which asks the resource's Adapter to parse them, so a Postgres resource's where= is decoded as a postgres.Query, never forced through Mongo's rules.
type ListResult ¶
ListResult is a page of documents. Total is -1 when the resource optimizes pagination for speed.
type Messages ¶
Messages are Werkzeug's default error descriptions, which Eve returns in _error.message. Werkzeug 0.x (Eve 0.7 APIs) used two spaces between sentences.
type NoTransaction ¶
type NoTransaction struct{}
NoTransaction runs fn without a transaction.
func (NoTransaction) WithTransaction ¶
WithTransaction implements Transactor.
type Options ¶
type Options struct {
// Auth validates tokens; nil disables authentication.
Auth *auth.Authenticator
// Transactor wraps the writes; nil means no transactions.
Transactor Transactor
// Messages are the default error texts; nil means Werkzeug1. Use
// Werkzeug0 for an API that really runs Werkzeug 0.11.
Messages Messages
// CacheControl and CacheExpires (seconds) are Eve's global
// CACHE_CONTROL and CACHE_EXPIRES, sent by the home endpoint.
CacheControl string
CacheExpires int
// HTMLForbidden answers a missing or invalid token with Werkzeug's HTML
// 403 page, as Eve 0.7 does when 403 is not in STANDARD_ERRORS
// (contents-api).
HTMLForbidden bool
// QueryTimeout limits each read (find and count); 0 means no limit.
// When it runs out the response is 503 (D-27).
QueryTimeout time.Duration
// DryRun marks every response with X-Dry-Run, logs the writes and skips
// the post-write hooks. The Transactor must roll back.
DryRun bool
// DryRunTimeout limits each request in dry run; 0 means no limit. The
// mirror of ingress-nginx holds the client's next request on the
// connection until the mirrored one ends, so a slow Go API would slow
// the Python one; it also bounds the locks of the aborted transaction
// and the driver's retries on write conflicts.
DryRunTimeout time.Duration
}
Options configure an API.
type Pagination ¶
Pagination holds Eve's PAGINATION_DEFAULT, PAGINATION_LIMIT, OPTIMIZE_PAGINATION_FOR_SPEED (no count, so no total and no last page) and PAGINATION = False (Disabled: every document, no _meta, no page links).
type PreconditionFailedError ¶
type PreconditionFailedError struct {
Current Doc
}
PreconditionFailedError is returned when If-Match does not match. It keeps the current document so the response can tell who changed it.
func (*PreconditionFailedError) Error ¶
func (e *PreconditionFailedError) Error() string
type QueryAdapter ¶ added in v0.102.0
type QueryAdapter interface {
// ParseWhere decodes the client's "where" query parameter into a
// filter, applying res's QueryDenylist/QueryObjectIDAsString.
ParseWhere(raw string, res *Resource) (any, error)
// ParseSort decodes the client's "sort" query parameter.
ParseSort(raw string) (any, error)
// ParseProjection decodes the client's "projection" query parameter.
ParseProjection(raw string) (any, error)
// CombineFilter combines clientFilter with res's datasource filter
// and, unless includeDeleted, the soft delete condition.
CombineFilter(res *Resource, clientFilter any, includeDeleted bool) (any, error)
// CombineSort falls back to res's Datasource.DefaultSort when
// clientSort is empty.
CombineSort(res *Resource, clientSort any) any
// CombineProjection narrows res's datasource projection by
// clientProjection, or applies clientProjection as sent when res has
// none (AllowUnknown).
CombineProjection(res *Resource, clientProjection any) (any, error)
// WriteLookup builds the CAS condition a write conditions on, from
// the document read before the write (original) -- always from
// original, never from a client's match/SkipConcurrency.
WriteLookup(original Doc) (any, error)
// IDFilter builds a filter selecting the single document whose _id
// equals id (an IDCodec.NewID/LookupByID value) -- combinable with
// CombineFilter exactly like a client's ParseWhere result, so an
// item route (GET/PATCH/PUT/DELETE /<url>/<id>) can reach the right
// document through the same CombineFilter/datasource-filter/soft-
// delete path a collection query already does, instead of a
// Mongo-only bson.M{"_id": id} literal hardcoded at the call site
// (http.go's itemLookup, service.go's checkMatched, before this
// method existed).
IDFilter(id any) (any, error)
// RetryPolicy returns the RetryOptions this adapter was configured
// with -- the budget Service's patchOnce retry loop uses for a PATCH
// whose If-Match is the wildcard "*" (section 9.7). mongoAdapter
// returns the zero RetryOptions: Mongo keeps today's behavior
// exactly, a single attempt, so a version conflict under
// If-Match: * is still a plain 412, never a 503.
RetryPolicy() RetryOptions
}
QueryAdapter parses the client's where/sort/projection query parameters and combines them with a Resource's own defaults (datasource filter, soft delete, default sort, datasource projection), and builds the CAS lookup a write conditions on. Same Fase 0 extraction as ErrorClassifier/ IDCodec: mongoAdapter implements it exactly as rest/query.go and rest/service.go already behaved.
type Resource ¶
type Resource struct {
// Name identifies the resource (the DOMAIN key).
Name string
// DisableSwagger hides this resource from OpenAPI; its routes remain active.
// The zero value includes the resource in the automatically served docs.
DisableSwagger bool
// URL is the route, Eve's "url". Defaults to Name.
URL string
// ResourceTitle is the title of the collection links. Defaults to URL.
ResourceTitle string
// ItemTitle is the title of the document links. Defaults to
// ResourceTitle without trailing "s", as Eve does.
ItemTitle string
// Store is the Mongo-shaped persistence seam. A resource that sets
// Adapter directly (a Postgres resource, via restpostgres) leaves
// this nil -- setDefaults only builds a mongoAdapter wrapping Store
// when Adapter is nil, never the reverse.
Store Store
// Adapter is the full backend seam (see Adapter's doc comment).
// Nil defaults to a mongoAdapter wrapping Store.
Adapter Adapter
Schema Schema
// AllowUnknown accepts fields outside Schema (Eve's allow_unknown).
AllowUnknown bool
Datasource Datasource
// AdditionalLookup enables GET /<url>/<value> by another field.
AdditionalLookup *AdditionalLookup
// Allowed methods, Eve's RESOURCE_METHODS and ITEM_METHODS.
ResourceMethods []string
ItemMethods []string
// Methods that do not require authentication, Eve's PUBLIC_METHODS and
// PUBLIC_ITEM_METHODS.
PublicMethods []string
PublicItemMethods []string
Pagination Pagination
// SoftDelete marks documents with _deleted instead of removing them.
SoftDelete bool
// QueryDenylist is the list of operators rejected in where, Eve's
// MONGO_QUERY_BLACKLIST. Nil means DefaultQueryDenylist.
QueryDenylist []string
// CacheControl and CacheExpires (seconds) set the Cache-Control and
// Expires headers of successful GETs (Eve's CACHE_CONTROL/CACHE_EXPIRES).
CacheControl string
CacheExpires int
// QueryObjectIDAsString keeps 24 hex strings of where as strings (Eve's
// query_objectid_as_string), for ids stored as strings.
QueryObjectIDAsString bool
// ItemNextLink adds {"next": "<item>?page=2"} to item responses, as Eve
// 0.7 does with OPTIMIZE_PAGINATION_FOR_SPEED.
ItemNextLink bool
// ItemNextFromCollection points that next link at the collection
// ("<url>?page=2"), as Eve 2.3 does.
ItemNextFromCollection bool
// Validate runs after the schema rules, as the rules of a custom Eve
// Validator. original is nil on POST; partial is true on PATCH. The
// returned issues are merged with the schema's.
Validate func(ctx context.Context, doc, original Doc, partial bool) (Issues, error)
// still accepts: the hooks put there the etags replaced by writes that
// did not touch what the client edits (Eve has no such field).
CompatibleEtags string
// RequireMergePatchContentType enforces RFC 7396 §A's requirement
// that a PATCH request use "application/merge-patch+json" -- an
// opt-in capability a resource whose Adapter.MergePatch is RFC 7396
// end to end (a Postgres resource) turns on. Eve/Mongo resources,
// whose MergePatch is a deep merge, not RFC 7396, leave it off and
// keep accepting any Content-Type, as Eve itself always did.
RequireMergePatchContentType bool
Hooks Hooks
}
Resource is an entry of Eve's DOMAIN.
type RetryOptions ¶ added in v0.102.0
type RetryOptions struct {
// MaxAttempts is retries BEYOND the initial attempt; 0 is valid
// ("disabled" -- a single attempt, a conflict there is a plain 412,
// never a 503); negative is an error.
MaxAttempts int
// BaseBackoff is the ceiling for the first retry's jitter; must be > 0.
BaseBackoff time.Duration
// MaxBackoff is the ceiling later retries saturate to; must be >= BaseBackoff.
MaxBackoff time.Duration
// MaxDuration bounds the retry loop's total wall-clock budget (only
// meaningful once MaxAttempts > 0); must be > 0.
MaxDuration time.Duration
}
RetryOptions bounds patchOnce's retry loop (the Postgres portability plan's section 9): how many times, and for how long, a PATCH whose If-Match is the wildcard "*" retries after an optimistic-concurrency conflict, instead of answering the first conflict with 412.
There is no usable zero value: RetryOptions{} fails Validate() because every duration field must be positive regardless of MaxAttempts -- start from DefaultRetryOptions() and override only what differs. An Adapter that never configures retrying (mongoAdapter today) exposes the zero value through RetryPolicy instead, which Service treats as "no retry capability" without ever calling Validate() on it -- Validate is for a caller that is about to use the loop, checked once at registration (e.g. restpostgres.NewAdapter), never on every request.
func DefaultRetryOptions ¶ added in v0.102.0
func DefaultRetryOptions() RetryOptions
DefaultRetryOptions is the only recognized starting point for a RetryOptions value -- disable retrying by overriding just MaxAttempts to 0 from this, rather than building a RetryOptions{} from scratch.
func (RetryOptions) Validate ¶ added in v0.102.0
func (r RetryOptions) Validate() error
Validate reports whether r is usable: every duration field positive, MaxBackoff at least BaseBackoff, MaxAttempts not negative.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service runs the operations of a resource with Eve's rules. It is the equivalent of Eve's getitem/post_internal/patch_internal/put_internal/ deleteitem_internal and has no HTTP concerns.
func NewService ¶
func NewService(res *Resource, tx Transactor) *Service
NewService builds a Service; tx may be nil for no transactions.
func (*Service) CheckEtag ¶
CheckEtag is Eve's If-Match check for custom endpoints: 428 without it, 412 when it differs from the stored etag. ifMatch is the raw header value (one line's worth; use ParseIfMatch directly for several repeated headers, or for the wildcard "*" to be recognized as matching any current etag).
func (*Service) Delete ¶
Delete removes the document, or marks it with _deleted when the resource uses soft delete (Eve's deleteitem).
func (*Service) Get ¶
Get returns one document with the default projection and the fetched hooks applied (Eve's getitem).
func (*Service) Insert ¶
Insert validates and stores documents (Eve's post_internal). When a document is invalid nothing is stored and an *InsertError is returned.
func (*Service) Patch ¶
func (s *Service) Patch(ctx context.Context, lookup any, changes Doc, opts WriteOptions) (Doc, error)
Patch updates some fields (Eve's patch). Nested documents are merged, as Eve's MERGE_NESTED_DOCUMENTS does. It returns the updated document.
A plain If-Match (one or more concrete entity-tags, or none at all) runs patchOnce exactly once, same as before this method gained a retry loop: a version conflict there is the usual 412, whether or not the resource's Adapter.RetryPolicy ever configures retrying. The loop only engages for the wildcard "If-Match: *" on a resource whose RetryPolicy has MaxAttempts > 0 (restpostgres's postgresAdapter, when its Options.Retry was given one; mongoAdapter never does) -- section 9.7 of the Postgres portability plan: retry an optimistic-concurrency conflict instead of answering the first one with 412, since the client already said it doesn't care which version it's patching.
func (*Service) Replace ¶
Replace stores a new version of the document keeping _id and _created (Eve's put). It returns the stored document.
func (*Service) WithTransaction ¶
WithTransaction runs fn in the transaction used by the writes of the resource, for custom endpoints that write directly and record outbox events.
func (*Service) WriteFound ¶
WriteFound answers a custom item route as Eve's getitem(resource, lookup) with send_response: 404 when nothing matches, the cache headers on GET and HEAD (render.py), ETag and Last-Modified, 304 on If-None-Match, and the links built from the request path, also when the route is a POST.
func (*Service) WriteItem ¶
WriteItem answers as GET /<url>/<id> (Eve's send_response of getitem): ETag and Last-Modified headers and the item body; the cache headers only for GET and HEAD, as Eve's _prepare_response.
func (*Service) WriteList ¶
WriteList answers a custom list route as Eve's get(resource, lookup) with send_response: the query string of the request (where, sort, page...) plus lookup, with the links built from the request path as Eve's resource_link does.
func (*Service) WriteListFallback ¶
func (s *Service) WriteListFallback(w http.ResponseWriter, r *http.Request, lookup, fallback bson.M)
WriteListFallback answers a custom list route with lookup when its page has items and with fallback otherwise: two get(resource, lookup) calls on the same request, as contents-api's get_content_by_url (the exact link, then the slow $regex).
type Store ¶
type Store interface {
// Find lists documents; limit <= 0 means no skip/limit is applied, and
// a nil sort or projection leaves Mongo's defaults.
Find(ctx context.Context, filter bson.M, skip, limit int64, sort bson.D, projection bson.M) ([]Doc, error)
CountDocuments(ctx context.Context, filter bson.M) (int64, error)
// FindOne reads one document; a nil projection leaves Mongo's default.
FindOne(ctx context.Context, filter bson.M, projection bson.M) (Doc, error)
InsertMany(ctx context.Context, docs []any) error
// UpdateOne applies a $set-shaped update document and returns the
// number of matched documents.
UpdateOne(ctx context.Context, filter, update bson.M) (matched int64, err error)
ReplaceOne(ctx context.Context, filter bson.M, replacement any) (matched int64, err error)
DeleteOne(ctx context.Context, filter bson.M) (deleted int64, err error)
}
Store is the persistence seam a Resource reads and writes through. It decouples the concrete storage client from rest — not the query language: filters, sorts and updates stay bson.M/bson.D, and the error values a Store returns (not found, duplicate key, timeout) are still Mongo-shaped (mongo.ErrNoDocuments, mongo.IsDuplicateKeyError...), because the callers in this package check for those directly. The only implementation today wraps a *mongo.Collection (platform/mongodb. Store); a non-Mongo backend needs either to return Mongo-compatible errors for the checks above, or this interface needs a second pass to carry its own error values instead.
Methods take plain bson/stdlib types, not rest-owned option structs: that keeps platform/mongodb (or any other Store implementation) from having to import rest for its method signatures to match, which would invert the services → behaviors → rest → platform layering.
https://gui-rondon.github.io/hyrule/docs/reference/architecture
type Transactor ¶
type Transactor interface {
WithTransaction(ctx context.Context, fn func(ctx context.Context) error) error
}
Transactor runs fn in a transaction. Use mongodb.Transactor with a replica set; NoTransaction runs fn directly (standalone Mongo, unit tests).
type ValidationError ¶
type ValidationError struct {
Issues Issues
}
ValidationError carries Cerberus-like issues of one document.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
type WriteOptions ¶
type WriteOptions struct {
// IfMatch is the client's parsed If-Match precondition. A zero
// IfMatch (IsZero true) is "no header sent" -- the same as an empty
// string before this field's type changed from string to IfMatch.
IfMatch IfMatch
// SkipConcurrency disables the If-Match check, as Eve's *_internal
// functions do by default.
SkipConcurrency bool
// SkipValidation disables the schema validation.
SkipValidation bool
}
WriteOptions control the concurrency and validation checks of a write.