Documentation
¶
Overview ¶
Package registry loads the realm/database/collection tree from CONFIG_DIR into an immutable, validated registry used by routing, validation and provisioning.
Index ¶
- Constants
- Variables
- func EnvelopeProblem(id string) string
- func NormalizeEmail(v string) (string, error)
- func ParamsFingerprint(p imaging.Params) string
- func ParseDuration(v string) (time.Duration, error)
- func ParseSize(v string) (int64, error)
- func ProviderCallbackPath(realm, provider string) string
- func SourceHash(dir string) (string, error)
- func ValidName(name string) bool
- func ValidSecretName(name string) bool
- func ValidateVersionParams(p imaging.Params) []string
- type AccountSettings
- type AdminAccess
- type AdminRights
- type AppConfig
- type CachePolicy
- type Collection
- type ComplianceSettings
- type ConfigPath
- type Consent
- type ConsentRef
- type ConsentText
- type ConsentVersion
- type CookieSettings
- type CustomID
- type Database
- type EmailLimits
- type EmailSettings
- type ErasurePolicy
- type Field
- type FileField
- type Function
- type FunctionPush
- type Functions
- type Index
- type IndexKey
- type LoginThrottle
- type MFASettings
- type MagicLinkSettings
- type Manifest
- type ManifestBundle
- type Networks
- type OnComplete
- type PersonalData
- type Provider
- type PushDelivery
- type PushLimits
- type PushPlatform
- type PushSettings
- type RateLimit
- type ReadAccess
- type Realm
- type RealmSettings
- func (s RealmSettings) AdminAccess(roles []string) AdminAccess
- func (s RealmSettings) AdminRights(roles []string) AdminRights
- func (s RealmSettings) AdminRoles() []string
- func (s RealmSettings) AppConfigTTL() time.Duration
- func (s RealmSettings) BestLocale(tags ...string) string
- func (s RealmSettings) ConsentNames() []string
- func (s RealmSettings) ConsentsPastDeadline(held map[string]string, now time.Time) []ConsentRef
- func (s RealmSettings) ConsentsToAccept(held map[string]string) []ConsentRef
- func (s RealmSettings) FullAdminRoles() []string
- func (s RealmSettings) IsAdmin(roles []string) bool
- func (s RealmSettings) Languages() (def string, list []string)
- func (s RealmSettings) ListedLocale(tag string) string
- func (s RealmSettings) ReauthLifetime() time.Duration
- func (s RealmSettings) SignInRedirectAllowed(raw string) bool
- func (s RealmSettings) Throttle() LoginThrottle
- type Registry
- func (r *Registry) AuthRealms() []string
- func (r *Registry) CheckBundles() error
- func (r *Registry) CheckImageLimits(instance int64) error
- func (r *Registry) Collection(realm, database, collection string) (*Collection, bool)
- func (r *Registry) Databases() []*Database
- func (r *Registry) Fingerprint() (string, error)
- func (r *Registry) FunctionRealms(authEnabled bool) []string
- func (r *Registry) RealmNames() []string
- func (r *Registry) SortedRealms() []*Realm
- type Retry
- type Role
- type ScopeEntry
- type SecretRef
- type SoftDelete
- type StorageSettings
- type UserNetworks
- type Version
Constants ¶
const ( ProofIP = "ip" ProofUserAgent = "user_agent" )
ConsentProof names what a consent record stores besides time, method and text hash.
const ( // MaxIDLength is the longest id any collection accepts. MaxIDLength = 128 // DefaultDuplicateLimit is how many duplicate creates a caller may attempt per minute when // the collection doesn't say. DefaultDuplicateLimit = 20 // MaxDuplicateLimit is the largest duplicate_limit. MaxDuplicateLimit = 1000 )
const ( ErasureDelete = "delete" ErasureAnonymize = "anonymize" )
Erasure actions on the documents a user owns.
const ( MatchEmail = "email" MatchID = "id" )
What a `pull` or `unset` field holds: the user's email or their id.
const ( UploadProxy = "proxy" // streamed through backd UploadDirect = "direct" // a signed PUT straight to the bucket )
Upload modes.
const ( FunctionsDir = "_functions" // one Deno project per database BuildDir = ".build" // bundles and their manifest, written by `backd functions build` // TypesFile is the generated registry of the project's types (`backd types --functions`): it // shapes no bundle, so it is not part of the source hash or the config fingerprint. TypesFile = "backd.d.ts" // RuntimeDir holds what `defineFunction` runs on (a hidden folder, never part of the config). RuntimeDir = ".backd" ManifestFile = "manifest.json" FunctionFile = "function.yaml" InputSchemaFile = "input.schema.json" OutputSchemaFile = "output.schema.json" )
Function layout inside a database directory.
const ( ModeSync = "sync" ModeAsync = "async" ModeWebhook = "webhook" )
Function modes.
const ( DefaultSyncTimeout = 10 * time.Second DefaultAsyncTimeout = 15 * time.Minute MaxSyncTimeout = 60 * time.Second MaxAsyncTimeout = 24 * time.Hour DefaultMemory = 128 << 20 DefaultMaxOutput = 1 << 20 MaxSyncOutput = 64 << 20 // MaxAsyncOutput keeps an async job's result within one MongoDB // document (16 MiB, minus room for the job's other fields). MaxAsyncOutput = 15 << 20 DefaultConcurrency = 10 )
Defaults and bounds of function.yaml values.
const ( CompleteOK = "ok" // the function returned CompleteFailed = "failed" // any other result: an error, a timeout, a crash CompleteCancelled = "cancelled" // an administrator cancelled the job )
The endings a job's on_complete notification can be limited to (`on`).
const ( OverlapAllow = "allow" OverlapSkip = "skip" )
What a scheduled time does while the function's previous run hasn't finished.
const ( StoreKeyword = "x-backd-store" StoreDate = "date" )
StoreKeyword is the schema.json keyword, on a property, that picks how its value is stored. The only choice is StoreDate: a `format: date-time` string is stored as a BSON Date, so queries and sorting compare dates.
const ( DefaultAccountThreshold = 5 DefaultIPThreshold = 50 DefaultThrottleWindow = 15 * time.Minute DefaultMaxDelay = 15 * time.Minute )
Defaults of login_throttle in realm.yaml: failures are counted per account and per client address in a sliding window, and past a threshold each new attempt waits twice as long as the one before, up to MaxDelay.
const ( ExportInclude = "include" ExportExclude = "exclude" )
What a collection contributes to a user's personal data export.
const ( ProviderGoogle = "google" ProviderMicrosoft = "microsoft" ProviderApple = "apple" )
The built-in providers, which are reserved names.
const ( PlatformAndroid = "android" PlatformIOS = "ios" PlatformWeb = "web" )
The platforms a device can be registered for.
const ( PushProviderFCM = "fcm" PushProviderAPNs = "apns" PushProviderWebPush = "webpush" PushProviderCapture = "capture" )
The built-in push providers.
const ( DefaultMaxDevicesPerUser = 10 DefaultDeviceStaleAfter = 60 * 24 * time.Hour )
Defaults of push.devices.
const ( DefaultPushTimeout = 60 * time.Second DefaultPushAttempts = 5 DefaultPushBackoff = 30 * time.Second DefaultPushParallelism = 20 DefaultPushPerMinute = 5 DefaultPushPerDay = 24 DefaultPushSendRetention = 30 * 24 * time.Hour )
Defaults of push.delivery, push.limits and push.send_retention.
const ( SignupOpen = "open" SignupInvite = "invite" SignupClosed = "closed" )
Signup modes.
const ( DefaultIdleTimeout = 30 * 24 * time.Hour DefaultMaxLifetime = 90 * 24 * time.Hour DefaultAuditRetention = 365 * 24 * time.Hour // DefaultAppConfigCacheTTL is how long a client may use the app configuration without asking. DefaultAppConfigCacheTTL = 5 * time.Minute // DefaultLogRetention is functions.log_retention's default: a short // debugging window, not a log archive (see the docs). DefaultLogRetention = 7 * 24 * time.Hour // DefaultJobRetention is functions.job_retention's default: how long // an async job's result is kept once done (roadmap F11). DefaultJobRetention = 24 * time.Hour DefaultPasswordMinLength = 12 )
Defaults for realm settings left out of realm.yaml.
const ( DefaultEmailPerKindPerHour = 3 DefaultEmailPerDay = 10 DefaultEmailPerIPPerHour = 20 // The caps of custom emails from functions. DefaultEmailPerFunctionPerHour = 200 DefaultEmailPerInvocation = 50 DefaultEmailRecipientsPerMessage = 10 // DefaultLocale is the realm's default_locale when it sets none. DefaultLocale = "en" )
Defaults of email.limits.
const ( MetaDeletedAt = "_meta.deleted_at" MetaDeletedBy = "_meta.deleted_by" MetaPurgeAt = "_meta.purge_at" )
The _meta fields of a soft-deleted document: when it was deleted, by whom, and when it goes for good (only with a retention).
const ( DefaultPresignedTTL = 5 * time.Minute DefaultPendingTTL = time.Hour // Download modes. DownloadPresigned = "presigned" DownloadProxy = "proxy" )
Storage defaults and bounds (storage in realm.yaml).
const AppConfigDir = "app-config"
AppConfigDir is the folder of a realm that declares its app configuration: <realm>/app-config/schema.json and rules.yaml. It is never read as a database.
const AppConfigMaxBytes = 64 << 10
AppConfigMaxBytes is the most the whole configuration, defaults included, may take once encoded.
const CollectionFile = "collection.yaml"
CollectionFile is the optional file next to a collection's schema.json holding its data policy for an erased user.
const ConsentPseudonymSecret = "BACKD_CONSENT_PSEUDONYM_KEY"
ConsentPseudonymSecret is the realm secret that keys the pseudonym consent records keep of an erased person (design/compliance.md §8).
const ConsentsDir = "consents"
ConsentsDir is the folder of a realm that holds the consent texts: <realm>/consents/<name>/<version>/<locale>.md. It is never read as a database.
const DefaultConsentRetention = 3 * 365 * 24 * time.Hour
DefaultConsentRetention is how long consent records are kept after their user was erased, when the realm doesn't say (compliance.consent_retention).
const DefaultReauthTTL = 5 * time.Minute
DefaultReauthTTL is how long a re-authentication token works when the realm doesn't say.
const DefaultRedirectDelay = 3 * time.Second
DefaultRedirectDelay is email.redirect_delay when not set.
const DefaultResetPasswordTTL = time.Hour
DefaultResetPasswordTTL is account.tokens.reset_password when not set.
const DefaultVerifyEmailTTL = 48 * time.Hour
DefaultVerifyEmailTTL is account.tokens.verify_email when not set.
const DenoVersion = "2.9.7"
DenoVersion is the Deno version functions are bundled and run with. `backd functions build` requires exactly this version, and the executor image is built from it.
const FilesLinkKeySecret = "BACKD_FILES_LINK_KEY"
FilesLinkKeySecret is the realm secret that signs backd's own links to files.
const MaxCacheAge = 3600
MaxCacheAge is the longest `cache.max_age` a collection may declare, in seconds.
const MaxCallChain = 4
MaxCallChain is the longest chain of functions calling each other, the entry function included.
const ( // MaxMultipartFileSize is the largest direct upload where the provider takes a multipart one: // 1000 parts of at most about 4.2 GiB (a part may be 5 GiB). MaxMultipartFileSize = 4 << 40 )
const RealmFile = "realm.yaml"
RealmFile is the name of the required realm settings file.
const (
// SchemaFile is the name of a collection's schema file.
SchemaFile = schemaFile
)
const SystemDatabaseSuffix = "___system"
SystemDatabaseSuffix is appended to a realm name to form the MongoDB database holding the realm's users, sessions and keys.
Variables ¶
var BuiltinProviders = []string{ProviderApple, ProviderGoogle, ProviderMicrosoft}
BuiltinProviders are the providers backd knows, sorted.
var DefaultWebEndpointHosts = []string{
"fcm.googleapis.com",
"updates.push.services.mozilla.com",
"web.push.apple.com",
"*.notify.windows.com",
}
DefaultWebEndpointHosts are the push services of the major browsers.
var Platforms = []string{PlatformAndroid, PlatformIOS, PlatformWeb}
Platforms lists the platforms in the order they are shown.
var ReservedDirs = []string{email.DirName, email.PagesDirName, push.DirName, ConsentsDir, AppConfigDir}
ReservedDirs are folders of a realm that hold something other than a database: they are never read as databases.
var ReservedProviderNames = []string{"password", "email"}
ReservedProviderNames are the names of backd's own sign-in methods (an identity's provider is `password`, and magic links will record `email`): no provider may take them.
var SystemFields = []string{"id", "_meta.created_at", "_meta.updated_at", "_meta.version", "_meta.owner", "_meta.created_by", "_meta.updated_by", MetaDeletedAt, MetaDeletedBy, MetaPurgeAt}
SystemFields are the server-owned fields that can be queried, sorted and indexed in addition to the schema's fields.
Functions ¶
func EnvelopeProblem ¶ added in v0.8.2
EnvelopeProblem checks what every custom id must satisfy whatever the collection's pattern: 1 to 128 characters, only letters, digits and - . _ ~ : @, not starting with _ or . and without "..". It returns "" when id is inside the envelope.
func NormalizeEmail ¶
NormalizeEmail trims and lowercases an email address and checks its basic shape (one "@" with text on both sides, no spaces). The reserved ".invalid" top-level domain (RFC 2606) is refused: it never receives mail, and erased users' placeholder addresses live there, so nobody may take one. Characters that delimit addresses or break a header (commas, angle brackets, quotes, control characters...) are refused as well: a delivery function that joins recipients with commas must never see one address that is really two.
func ParamsFingerprint ¶ added in v0.8.1
ParamsFingerprint is Fingerprint for parameters that aren't a declared version's, such as the ones a function generates with.
func ParseDuration ¶
ParseDuration parses a Go duration ("12h", "90m") or a whole number of days ("30d").
func ProviderCallbackPath ¶ added in v0.8.2
ProviderCallbackPath is where a provider sends the user back to, relative to backd's public address: the URL to register in the provider's console.
func SourceHash ¶
SourceHash hashes every file of a functions project, except hidden entries (such as .build), so any change to code, shared lib/, deno.json, deno.lock or schemas changes it.
func ValidSecretName ¶
ValidSecretName reports whether name is a valid secret NAME (upper-case letters, digits and _, starting with a letter) — the same rule function.yaml's secrets list is checked against, without the leading "realm." a reference may carry.
func ValidateVersionParams ¶ added in v0.8.1
ValidateVersionParams reports what is wrong with parameters given at run time (by a function), with the same rules `versions:` is parsed with.
Types ¶
type AccountSettings ¶ added in v0.4.0
type AccountSettings struct {
// RequireVerifiedEmail: no session until the address is verified.
RequireVerifiedEmail bool
// WelcomeEmail sends the welcome email once the address is verified.
WelcomeEmail bool
// VerifyEmailTTL is how long a verification link works (account.tokens.verify_email).
VerifyEmailTTL time.Duration
// AllowEmailChange lets users change their own address (`POST /_auth/email`).
AllowEmailChange bool
// ChangeEmailTTL and RevertEmailChangeTTL are how long the confirmation
// and the undo link of an email change work.
ChangeEmailTTL, RevertEmailChangeTTL time.Duration
// ResetPasswordTTL is how long a reset link works (account.tokens.reset_password).
ResetPasswordTTL time.Duration
// PurgeUnverifiedAfter deletes accounts that never verified; 0 is off.
PurgeUnverifiedAfter time.Duration
// OnSignup is the internal, async function (<database>/<function>) called for every
// new user (account.on_signup), to create the app's profile document; OnSignupTimeout
// is its timeout.
OnSignup string
OnSignupTimeout time.Duration
}
AccountSettings are the account lifecycle settings of a realm.
func (AccountSettings) OnSignupDatabaseAndName ¶ added in v0.8.2
func (a AccountSettings) OnSignupDatabaseAndName() (string, string)
OnSignupDatabaseAndName splits OnSignup.
func (AccountSettings) TokenLifetime ¶ added in v0.4.0
func (a AccountSettings) TokenLifetime(p email.Purpose) time.Duration
TokenLifetime is how long a token of this purpose works in the realm.
type AdminAccess ¶ added in v0.7.0
type AdminAccess struct {
Write AdminRights
ReadAll bool
}
AdminAccess is what a user's admin roles let them do in the admin API: change some areas, and/or read every area (a read-only level, `admin: read`). Roles add up.
func (AdminAccess) Any ¶ added in v0.7.0
func (a AdminAccess) Any() bool
Any reports whether the access makes someone an administrator at all.
func (AdminAccess) CanRead ¶ added in v0.7.0
func (a AdminAccess) CanRead(s RealmSettings, want AdminRights) bool
CanRead reports whether the areas in want may be read: what the access changes it reads too; a read-only level reads every area except users and data, which realm.yaml's admin.read_access has to grant.
func (AdminAccess) CanWrite ¶ added in v0.7.0
func (a AdminAccess) CanWrite(want AdminRights) bool
CanWrite reports whether the areas in want may be changed.
func (AdminAccess) Covers ¶ added in v0.7.0
func (a AdminAccess) Covers(b AdminAccess) bool
Covers reports whether a can do everything b can: nobody hands out, or changes someone who holds, more than they have.
func (AdminAccess) Full ¶ added in v0.7.0
func (a AdminAccess) Full() bool
Full reports whether it is `admin: true`: every area, to change.
func (AdminAccess) String ¶ added in v0.7.0
func (a AdminAccess) String() string
String describes the access, for messages.
type AdminRights ¶ added in v0.6.0
type AdminRights uint8
AdminRights is the part of the admin API a role opens: a set of areas. `admin: true` in realm.yaml is every area (and any area added later); `admin: [users, invitations]` is just those. The zero value is none.
const ( RightUsers AdminRights = 1 << iota // users, their roles, passwords, addresses, networks, erasure RightInvitations // invitations RightAPIKeys // API keys RightSecrets // secrets RightAudit // the audit trail RightFunctions // running functions by hand, their invocations and every job RightData // the admin data route: documents, past their collections' rules RightConfig // the read-only view of the realm's configuration // AllRights is `admin: true`. AllRights = RightUsers | RightInvitations | RightAPIKeys | RightSecrets | RightAudit | RightFunctions | RightData | RightConfig )
func RightNamed ¶ added in v0.6.0
func RightNamed(name string) (AdminRights, bool)
RightNamed is the right of a name used in realm.yaml and the docs.
func (AdminRights) Any ¶ added in v0.6.0
func (r AdminRights) Any() bool
Any reports whether r opens anything: whether holding it makes someone an administrator.
func (AdminRights) Has ¶ added in v0.6.0
func (r AdminRights) Has(want AdminRights) bool
Has reports whether r includes every right in want.
func (AdminRights) Names ¶ added in v0.6.0
func (r AdminRights) Names() []string
Names lists the rights by name, in the documented order; "all" for every right.
func (AdminRights) String ¶ added in v0.6.0
func (r AdminRights) String() string
String is the names, comma separated ("none" for no right).
type AppConfig ¶ added in v0.8.2
type AppConfig struct {
SchemaPath string
RulesPath string // rules.yaml, whether or not the file exists
RawSchema map[string]any
Schema *jsonschema.Schema
// Paths holds every declared path (dot notation, `features.reports.enabled`);
// a path is a branch (an object) or a leaf (a value).
Paths map[string]ConfigPath
// Defaults is the whole configuration with every leaf at its default.
Defaults map[string]any
// Rules are the read rules by path, as written; use Effective for what applies.
Rules map[string]*rules.Rule
}
AppConfig is a realm's declared app configuration (<realm>/app-config/): the keys, their types and defaults, and who may read which path.
func (*AppConfig) Effective ¶ added in v0.8.2
Effective returns the rules that apply to a path: its own rule and those of every ancestor, all of which must allow the read. It reports false when nothing in the chain has a rule, which means clients can't read the path.
func (*AppConfig) HasPath ¶ added in v0.8.2
HasPath reports whether the path is declared, as a branch or as a leaf.
func (*AppConfig) SortedPaths ¶ added in v0.8.2
SortedPaths lists the declared paths in order.
type CachePolicy ¶ added in v0.8.2
CachePolicy is collection.yaml's cache: the collection's anonymous reads may be stored by shared caches (CDNs) for MaxAge seconds. Everything else stays private, no-cache.
type Collection ¶
type Collection struct {
Realm string
Database string
MongoDatabase string // <realm>__<database>
Name string
SchemaPath string // path of schema.json, for error messages
RawSchema map[string]any // decoded schema.json (numbers as json.Number)
Schema *jsonschema.Schema // compiled draft 2020-12 schema
Fields map[string]Field // dot path → field info, for query checks
Indexes []Index // declared in indexes.json
IndexPath string // path of indexes.json, when present
Rules *rules.Set // from collection.yaml's rules:; nil allows nothing
Erasure *ErasurePolicy // from collection.yaml; nil: an erase leaves the collection alone
ErasurePath string // path of collection.yaml, for error messages
SoftDelete *SoftDelete // from collection.yaml; nil: DELETE removes the document
PersonalData *PersonalData // from collection.yaml's personal_data:; nil: owned documents, whole
Cache *CachePolicy // from collection.yaml's cache:; nil: responses are private, no-cache
CustomID *CustomID // from collection.yaml's custom_id:; nil: the server generates the ids
Files map[string]*FileField // file fields from collection.yaml's files:; their schema is already in Schema and RawSchema
// contains filtered or unexported fields
}
Collection is a set of documents validated by one JSON Schema.
func (*Collection) ArrayField ¶
func (c *Collection) ArrayField(path string) bool
ArrayField reports whether path is declared as an array (only), with no array on the way to it.
func (*Collection) DateField ¶ added in v0.5.0
func (c *Collection) DateField(path string) bool
DateField reports whether path is stored as a BSON Date.
func (*Collection) DatesToStorage ¶ added in v0.5.0
func (c *Collection) DatesToStorage(doc map[string]any) map[string]any
DatesToStorage returns doc with the date fields converted to time.Time. doc itself is left alone (a request may be retried with the same body). A field that is absent or null stays so.
func (*Collection) IsKnownField ¶
func (c *Collection) IsKnownField(path string) bool
IsKnownField reports whether path is a system field or declared in the schema.
func (*Collection) ScalarField ¶
func (c *Collection) ScalarField(path string) bool
ScalarField reports whether path holds a single value: a system field, or a declared field whose types exclude "array", with no array on the way to it.
type ComplianceSettings ¶ added in v0.8.2
type ComplianceSettings struct {
// ConsentProof lists what each consent record stores besides time, method and
// text hash: ProofIP and ProofUserAgent. Both by default.
ConsentProof []string
// ConsentRetention is how long records are kept after erasure; 0 deletes them at erasure.
ConsentRetention time.Duration
// ConsentRetentionSet says whether realm.yaml chose a retention (0 is a choice).
ConsentRetentionSet bool
}
ComplianceSettings are the realm's compliance settings (compliance in realm.yaml).
func (ComplianceSettings) Proof ¶ added in v0.8.2
func (c ComplianceSettings) Proof(what string) bool
Proof reports whether records store the given proof ("ip" or "user_agent").
func (ComplianceSettings) Retention ¶ added in v0.8.2
func (c ComplianceSettings) Retention() time.Duration
Retention is how long consent records outlive their user: the realm's choice, or the default.
type ConfigPath ¶ added in v0.8.2
ConfigPath is one declared path of the configuration.
type Consent ¶ added in v0.8.2
type Consent struct {
Name string
// Required consents must be accepted to have an account; optional ones can be
// given and withdrawn at will.
Required bool
// Current is the version new accounts accept.
Current string
// Versions are the versions realm.yaml says something about, plus the current one.
Versions map[string]*ConsentVersion
// Texts holds the loaded texts by version and locale.
Texts map[string]map[string]ConsentText
}
Consent is one consent a realm asks for (consents in realm.yaml): a name, the version in force, and the texts of every version, per language.
type ConsentRef ¶ added in v0.8.2
type ConsentRef struct{ Name, Version string }
ConsentRef names a consent and a version of it.
type ConsentText ¶ added in v0.8.2
ConsentText is the exact text of a version in one language, with its SHA-256.
type ConsentVersion ¶ added in v0.8.2
type ConsentVersion struct {
// Reaccept asks users who accepted an earlier version to accept this one.
Reaccept bool
// ReacceptBy is the date after which open sessions of users who haven't accepted are
// refused; the zero time means sessions continue until the user signs in again.
ReacceptBy time.Time
}
ConsentVersion is what realm.yaml says about one version of a consent.
type CookieSettings ¶ added in v0.5.0
type CookieSettings struct {
Enabled bool
// SameSite is lax (default), strict or none. none is for apps on another
// site than the API (another registrable domain); lax and strict also work
// for an app on a sibling subdomain.
SameSite string
}
CookieSettings are the realm's session cookies.
type CustomID ¶ added in v0.8.2
type CustomID struct {
// User means the id must equal the id of the user creating the document.
User bool
// Pattern is the declared pattern as written; empty with User.
Pattern string
// DuplicateLimit is how many creates of an id that exists a caller may attempt per minute.
DuplicateLimit int
// contains filtered or unexported fields
}
CustomID is collection.yaml's custom_id: the collection takes the id of a new document from the client, which must match Pattern (or be the creating user's id) and the safety envelope.
type Database ¶
type Database struct {
Realm string
Name string
MongoName string // <realm>__<database>
Collections map[string]*Collection
Functions *Functions // from _functions/; nil when the database has none
// contains filtered or unexported fields
}
Database is one application's data, stored in one MongoDB database.
func (*Database) SortedCollections ¶
func (d *Database) SortedCollections() []*Collection
SortedCollections returns the database's collections sorted by name.
type EmailLimits ¶ added in v0.4.0
type EmailLimits struct {
PerKindPerHour int // emails of one kind to one recipient, per hour
PerDay int // emails to one recipient, per day
PerIPPerHour int // email-sending requests from one client address, per hour
// The caps of custom emails from functions (ctx.email.send), whoever the
// recipients are.
PerFunctionPerHour int // messages one function sends, per hour
PerInvocation int // messages one invocation sends
RecipientsPerMessage int // to, cc and bcc of one message
}
EmailLimits bound how many emails one address, and one client address, can cause.
type EmailSettings ¶ added in v0.4.0
type EmailSettings struct {
Function string // <database>/<function>: internal and async
From string // "Name <address>" or an address
ReplyTo string // optional
PublicURL string // overrides BACKD_URL for this realm's links; no trailing slash
Limits EmailLimits
// RedirectDelay is how long a hosted result page waits before it sends the
// user on (email.redirect_delay).
RedirectDelay time.Duration
// Redirects are where the hosted pages send users afterwards, by flow
// (verify_email, reset_password, change_email, invitation), when the
// request that caused the email named no other place.
Redirects map[string]string
// AllowedRedirects are the origins (https://app.example.com) and app
// schemes (acme://) that redirect_to, redirects and links may point at.
AllowedRedirects []string
// Links replace the hosted page of a flow with a page of the app: the
// link in the email is this URL, with {token} replaced.
Links map[string]string
// Timeout is the delivery function's own timeout, set when the config is
// loaded; email jobs lease for it.
Timeout time.Duration
}
EmailSettings are the email settings of a realm: which function delivers its messages and who they come from. backd renders the messages and never sends one itself.
func (EmailSettings) AllowedRedirect ¶ added in v0.4.0
func (e EmailSettings) AllowedRedirect(raw string) bool
AllowedRedirect reports whether raw is an absolute URL on one of the allowed origins or app schemes: where a page may send a user.
func (EmailSettings) DatabaseAndName ¶ added in v0.4.0
func (e EmailSettings) DatabaseAndName() (string, string)
DatabaseAndName splits Function into the database and the function name.
type ErasurePolicy ¶ added in v0.4.0
type ErasurePolicy struct {
// Action applies to the documents whose _meta.owner is the user: "" leaves
// them, ErasureDelete removes them, ErasureAnonymize applies Remove and
// Replace and clears the owner.
Action string
Remove []string // fields removed (anonymize)
Replace map[string]any // fields set to a fixed value (anonymize)
// Pull and Unset act on every document of the collection, whoever owns it:
// the user is removed from the array field / cleared from the field. The
// value says what the field holds: MatchEmail or MatchID.
Pull map[string]string
Unset map[string]string
}
ErasurePolicy is what an erase does to a collection (collection.yaml's on_owner_delete). A collection without the file is left alone.
func (*ErasurePolicy) Fields ¶ added in v0.4.0
func (p *ErasurePolicy) Fields() []string
Fields lists every field the policy touches, for the indexes it needs.
func (*ErasurePolicy) IndexedFields ¶ added in v0.4.0
func (p *ErasurePolicy) IndexedFields() []string
IndexedFields are the fields an erase searches by: the arrays and fields that hold the user (pull and unset), which need an index to be found without scanning the collection.
type Field ¶
type Field struct {
Types []string // JSON Schema types; empty when the schema doesn't constrain it
ItemTypes []string // for arrays: the types of the items, when declared
// Date marks a field stored as a BSON Date (x-backd-store: date in
// schema.json): clients send and read RFC 3339 strings, queries compare
// dates.
Date bool
}
Field describes one property path declared in a collection schema.
type FileField ¶ added in v0.8.0
type FileField struct {
Name string
Multiple bool // an array of files; otherwise at most one
MaxFiles int // for a multiple field
MaxSize int64 // bytes, per file
// Types are the allowed content types, detected from the bytes (never the
// client's claim): "image/png", or "image/*" for a family. Empty allows any.
Types []string
// Upload is UploadProxy or UploadDirect.
Upload string
// Download is DownloadPresigned or DownloadProxy; "" follows the realm's.
Download string
// PresignedTTL is how long this field's links last; 0 follows the realm's.
PresignedTTL time.Duration
// Cache is the Cache-Control max-age of proxied downloads of anonymously
// readable documents; 0 means no caching.
Cache time.Duration
// Versions are the resized copies of an image the field declares, by name order.
Versions []Version
// MaxPixels lowers the instance's image pixel limit for this field; 0 follows it.
MaxPixels int64
// KeepMetadata stores the JPEG and PNG pictures of the field as they were sent. By default
// their metadata (EXIF with the GPS position, XMP, comments, text chunks) is removed.
KeepMetadata bool
}
FileField is one file field of a collection, from collection.yaml.
type Function ¶
type Function struct {
Realm, Database, Name string
Dir string // the function's folder
Entry string // index.js or index.ts, relative to the project (slash-separated)
Mode string
Timeout time.Duration
Memory int64 // bytes
MaxOutput int64 // bytes
Concurrency int
RateLimit *RateLimit // nil: none
Retry *Retry // nil: a single attempt
Idempotency string // optional or required
Invoke *rules.Rule // nil: only API keys may invoke
Admin bool // ctx.admin.db with full access
ConfigWrite bool // ctx.admin.config: may change the realm's app configuration
Internal bool // no HTTP route: only backd, scheduled runs and other functions call it
Email bool // ctx.email.send: may send custom emails through the realm's templates and delivery function
// Push is set by `push:` in function.yaml: the function may send pushes (ctx.push.send).
Push *FunctionPush
DevOnly bool // backd refuses to start with it unless BACKD_DEV=true (development helpers)
Calls []string // functions of the same database this one may ctx.call
Schedule *cron.Schedule // nil: not scheduled
ScheduleExpr string
OnComplete *OnComplete // nil: nothing is told when a job ends
Timezone string // IANA name the schedule is read in; "UTC" unless set. Empty when not scheduled
Overlap string // allow (default) or skip: what a scheduled time does while the previous run hasn't finished
Secrets []SecretRef
Network []string // hosts (host or host:port) the function may reach
InputSchema *jsonschema.Schema
OutputSchema *jsonschema.Schema
}
Function is one function, from its folder in _functions/.
type FunctionPush ¶ added in v0.8.2
type FunctionPush struct {
// Kinds are the template kinds the function declares; Restricted says `kinds:` was given.
Kinds []string
Restricted bool
Audience bool
}
FunctionPush is what a function's `push:` declares: that it may send pushes, which template kinds it sends (empty: any, and raw title and body), and whether it may address an audience rather than named users.
func (*FunctionPush) AllowsKind ¶ added in v0.8.2
func (f *FunctionPush) AllowsKind(kind string) bool
AllowsKind says whether the function may send the kind.
type Functions ¶
type Functions struct {
Dir string // the _functions directory
Functions map[string]*Function // by name
}
Functions is a database's Deno project of functions (`_functions/`).
type Index ¶
type Index struct {
Keys []IndexKey
Unique bool
// TTL makes MongoDB delete a document when the date its single key holds
// has passed (soft_delete.retention's purge_at).
TTL bool
}
Index is one index declared in indexes.json.
type LoginThrottle ¶ added in v0.6.0
type LoginThrottle struct {
// AccountThreshold is how many failed attempts an account gets before
// each new attempt must wait; IPThreshold is the same per client address
// (IPv6 per /64), higher because a network can hide many people.
AccountThreshold int
IPThreshold int
// Window is how long a failure counts: the counter of an account or an
// address expires this long after its last failure.
Window time.Duration
// MaxDelay is the longest anyone waits. It never exceeds Window.
MaxDelay time.Duration
}
LoginThrottle is how a realm slows down guessing of passwords (login_throttle). The zero value means the defaults.
type MFASettings ¶ added in v0.8.2
type MFASettings struct {
// Off says users may not turn TOTP on (mfa.enabled: false). Users that already have
// it are still asked for it: switching the feature off never weakens an account.
Off bool
// Issuer is the name authenticator apps show; the realm's name when empty.
Issuer string
// RequiredRoles are the roles whose holders must use MFA; RequiredAll means everyone.
RequiredRoles []string
RequiredAll bool
}
MFASettings are the realm's multi-factor settings (mfa in realm.yaml).
func (MFASettings) Required ¶ added in v0.8.2
func (m MFASettings) Required(roles []string) bool
Required says whether a user with these roles must use MFA.
type MagicLinkSettings ¶ added in v0.8.2
type MagicLinkSettings struct {
// Enabled turns the endpoints on; it needs the realm's email.
Enabled bool
// Signup lets an address that has no account make one (verified, by redeeming the link
// or code), when the realm's own sign-up is open.
Signup bool
}
MagicLinkSettings are the realm's magic-link settings.
type Manifest ¶
type Manifest struct {
Deno string `json:"deno"`
Source string `json:"source"` // SourceHash of the project when built
Functions map[string]ManifestBundle `json:"functions"`
}
Manifest describes the bundles `backd functions build` wrote for one functions project.
func ReadManifest ¶
ReadManifest reads a project's .build/manifest.json.
type ManifestBundle ¶
type ManifestBundle struct {
Bundle string `json:"bundle"` // file name in .build
SHA256 string `json:"sha256"`
}
ManifestBundle is one function's bundle.
type Networks ¶
Networks is a list of IP networks. An empty list restricts nothing.
func ParseNetworks ¶
ParseNetworks parses IP addresses and CIDR networks, IPv4 or IPv6.
func (Networks) Allows ¶
Allows reports whether addr is in one of the networks; an empty list allows every address. addr is an IP address such as the one the HTTP layer resolves with TRUSTED_PROXIES; an unparsable one is refused by a non-empty list.
type OnComplete ¶ added in v0.8.0
type OnComplete struct {
Function string // a function of the same database
On []string // the endings that notify; every one when empty
}
OnComplete says which async function is queued, as a job of its own, when a job of this function ends.
func (*OnComplete) Notifies ¶ added in v0.8.0
func (o *OnComplete) Notifies(ending string) bool
Notifies reports whether an ending (CompleteOK, CompleteFailed or CompleteCancelled) is told.
type PersonalData ¶ added in v0.8.2
type PersonalData struct {
Export string // ExportInclude (default) or ExportExclude
Fields []string // only these fields (plus id and _meta); nil: whole documents
Reason string // why: required to exclude, and to leave fields out
}
PersonalData is collection.yaml's personal_data: it overrides what the export of a user's data takes from the collection. Without it the export follows the erasure model: the documents the user owns, whole.
type Provider ¶ added in v0.8.2
type Provider struct {
Name string // google, microsoft or apple
// ClientID is the application's id with the provider (Apple: the Services ID);
// ClientSecret names the secret that holds its secret (Apple has none: it
// signs one from PrivateKey).
ClientID string
ClientSecret string
// NativeClientIDs (Apple: BundleIDs) are the extra audiences the ID-token
// endpoint accepts, the ids of the mobile apps.
NativeClientIDs []string
// Tenant is Microsoft's: common, organizations, consumers or a tenant id.
Tenant string
// Apple only: the team and key that sign the client secret, the secret that
// holds the private key, and whether a user's tokens are revoked when the
// account goes away.
TeamID, KeyID, PrivateKey string
RevokeOnDelete bool
}
Provider is an external identity provider a realm lets its users sign in with.
func (*Provider) Audiences ¶ added in v0.8.2
Audiences are the client ids an ID token may be issued to: the web client and, for the ID-token endpoint, the native ones.
func (*Provider) SecretNames ¶ added in v0.8.2
SecretNames are the realm secrets the provider needs.
func (*Provider) TrustsEmail ¶ added in v0.8.2
TrustsEmail says whether an address the provider asserts as verified may link an existing account on its own (Google and Apple; not Microsoft, whose address claim a tenant administrator controls).
type PushDelivery ¶ added in v0.8.2
type PushDelivery struct {
Timeout time.Duration
RetryAttempts int
RetryBackoff time.Duration
Parallelism int
}
PushDelivery is push.delivery: a delivery unit's time limit, the attempts a unit gets and the provider requests a worker keeps in flight.
type PushLimits ¶ added in v0.8.2
type PushLimits struct {
PerMinute, PerDay int
}
PushLimits are push.limits.per_user: the pushes a user gets in a minute and a day.
type PushPlatform ¶ added in v0.8.2
type PushPlatform struct {
Provider string
// FCM: the service-account JSON.
Credentials string
// APNs: the .p8 signing key, its id, the team and the app's bundle id; Sandbox targets
// api.sandbox.push.apple.com.
Key string
KeyID, TeamID string
Topic string
Sandbox bool
// Web Push: the VAPID private key and the contact URI (mailto: or https:).
PrivateKey string
Subject string
}
PushPlatform is one enabled platform: its provider and that provider's credentials. The secrets are named, never held: Credentials, Key, PrivateKey and Subject are names of realm secrets (written secret:NAME in realm.yaml).
func (PushPlatform) SecretNames ¶ added in v0.8.2
func (p PushPlatform) SecretNames() []string
SecretNames are the realm secrets the platform's provider needs.
type PushSettings ¶ added in v0.8.2
type PushSettings struct {
// Platforms holds the enabled platforms and their provider.
Platforms map[string]PushPlatform
// WebPublicKey is the VAPID public key (base64url, uncompressed P-256 point) browsers
// subscribe with; WebEndpointHosts the hosts a subscription may point at: an exact host,
// or `*.example.com` for any subdomain.
WebPublicKey string
WebEndpointHosts []string
// MaxDevicesPerUser caps a user's devices; StaleAfter removes devices not seen for that long.
MaxDevicesPerUser int
StaleAfter time.Duration
// Delivery tunes the built-in senders; Limits are the per-user limits; SendRetention is how
// long the record of a send is kept.
Delivery PushDelivery
Limits PushLimits
SendRetention time.Duration
}
PushSettings are the push settings of a realm.
func (*PushSettings) Enabled ¶ added in v0.8.2
func (p *PushSettings) Enabled(platform string) bool
Enabled says whether a device may be registered for the platform.
func (*PushSettings) SecretNames ¶ added in v0.8.2
func (p *PushSettings) SecretNames() []string
SecretNames are the realm secrets push needs, sorted and without repeats.
func (*PushSettings) WebHostAllowed ¶ added in v0.8.2
func (p *PushSettings) WebHostAllowed(host string) bool
WebHostAllowed says whether a web subscription may point at the host.
type ReadAccess ¶ added in v0.7.0
ReadAccess is realm.yaml's admin.read_access: what read-only administrators may see beyond operations. Users and data hold personal data, so a realm opts in.
type Realm ¶
type Realm struct {
Name string
Settings RealmSettings // from realm.yaml
Databases map[string]*Database
// Email holds the parsed email templates of <realm>/email/; nil when the
// realm doesn't configure email.
Email *email.Templates
// Pages are the hosted pages the links in emails open (<realm>/pages/);
// nil when the realm doesn't configure email.
Pages *email.Pages
// Push holds the parsed push templates of <realm>/push/; nil when the realm has no push: section.
Push *push.Templates
// AppConfig is the realm's declared app configuration (<realm>/app-config/); nil when it has none.
AppConfig *AppConfig
}
Realm groups databases and owns a user pool.
func (*Realm) PersonalScope ¶ added in v0.8.2
func (r *Realm) PersonalScope() []ScopeEntry
PersonalScope lists, collection by collection, what the export of a user's data takes: the documents they own, those where they appear in a `pull` field, and the files those hold, minus what personal_data excludes.
type RealmSettings ¶
type RealmSettings struct {
AuthEnabled bool
Signup string
IdleTimeout time.Duration
MaxLifetime time.Duration
// AdminIdleTimeout and AdminMaxLifetime are the limits of the sessions of
// users who hold an admin role (sessions.admin_idle_timeout and
// sessions.admin_max_lifetime). 0 means the regular limit; set, they never
// exceed it.
AdminIdleTimeout time.Duration
AdminMaxLifetime time.Duration
// Cookie lets browser apps keep a session in an HttpOnly cookie, when
// their login asks for it (sessions.cookie).
Cookie CookieSettings
PasswordMinLength int
// LoginThrottle is login_throttle; read it through Throttle(), which
// fills in the defaults.
LoginThrottle LoginThrottle
CORSOrigins []string
Roles map[string]Role
// AdminNetworks restricts every admin API request (admin.allowed_networks);
// empty means unrestricted.
AdminNetworks Networks
// ReadAccess is what read-only administrators (`admin: read`) may see
// beyond operations (admin.read_access).
ReadAccess ReadAccess
// UserNetworks are the network restrictions realm.yaml sets per user
// email (in a role's user entries).
UserNetworks map[string]UserNetworks
// OpenAPIPublic makes the realm's OpenAPI document readable without credentials
// (openapi.public: true); otherwise only the realm's administrators read it.
OpenAPIPublic bool
// AppConfigCacheTTL is how long clients treat the app configuration as fresh
// (app_config.cache_ttl); zero when not set: use AppConfigTTL.
AppConfigCacheTTL time.Duration
// AuditRetention is how long audit records are kept (audit.retention);
// DefaultAuditRetention when not set.
AuditRetention time.Duration
// FunctionsMaxConcurrency caps how many function calls may run at once
// on this backd instance (functions.max_concurrency); 0 means
// unlimited. Applies whether or not auth is enabled.
FunctionsMaxConcurrency int
// FunctionsLogRetention is how long invocation records (roadmap F10)
// are kept (functions.log_retention); DefaultLogRetention when not
// set. Needs auth enabled, like the rest of functions.* except
// max_concurrency: there's no system database to store them in
// otherwise.
FunctionsLogRetention time.Duration
// FunctionsJobRetention is how long an async job's result (roadmap
// F11) is kept once done (functions.job_retention); DefaultJobRetention
// when not set. Needs auth enabled, like FunctionsLogRetention.
FunctionsJobRetention time.Duration
// Email is how the realm sends email (email in realm.yaml); nil when it
// doesn't, and then no email is ever sent.
Email *EmailSettings
// Storage is where the realm's files live (storage in realm.yaml); nil
// when it has none, and then it can't declare file fields.
Storage *StorageSettings
// Account is how the realm's accounts behave (account in realm.yaml).
Account AccountSettings
// Providers are the external identity providers (providers in realm.yaml),
// by name; SignInRedirects are where a sign-in may send the user back to
// (sign_in.allowed_redirects, normalized like email.allowed_redirects).
Providers map[string]*Provider
SignInRedirects []string
// SignInAppURL (sign_in.app_url) is where a sign-in goes back to when its
// redirect_to is absent: the app's own address, within the allowed redirects.
SignInAppURL string
// MFA are the multi-factor settings (mfa in realm.yaml).
MFA MFASettings
// ReauthTTL is how long a re-authentication token works (reauth.ttl).
ReauthTTL time.Duration
// DefaultLocale and Locales are the languages of the realm (default_locale and locales in
// realm.yaml): users' languages are mapped to them, and email and push templates exist for
// each. Read them with Languages.
DefaultLocale string
Locales []string
// Push holds the push notification settings: nil without a push: section.
Push *PushSettings
// MagicLink are the settings of sign-in by emailed link and code (magic_link in realm.yaml).
MagicLink MagicLinkSettings
// Consents are the consents the realm asks for (consents in realm.yaml), with the texts
// of every version once loaded; Compliance holds what their records keep and for how long.
Consents map[string]*Consent
Compliance ComplianceSettings
}
RealmSettings are the realm-level settings from realm.yaml, with defaults applied.
func (RealmSettings) AdminAccess ¶ added in v0.7.0
func (s RealmSettings) AdminAccess(roles []string) AdminAccess
AdminAccess is what the roles let a user do in the admin API, added up.
func (RealmSettings) AdminRights ¶ added in v0.6.0
func (s RealmSettings) AdminRights(roles []string) AdminRights
AdminRights is what the roles let a user change together: the union of the areas each role opens.
func (RealmSettings) AdminRoles ¶
func (s RealmSettings) AdminRoles() []string
AdminRoles returns the names of the roles that open any part of the admin API (admin: true, or a list of areas), sorted.
func (RealmSettings) AppConfigTTL ¶ added in v0.8.2
func (s RealmSettings) AppConfigTTL() time.Duration
AppConfigTTL is how long clients may use the app configuration without asking again.
func (RealmSettings) BestLocale ¶ added in v0.4.0
func (s RealmSettings) BestLocale(tags ...string) string
BestLocale maps the languages a person asked for, most wanted first, to the best language the realm lists, without ever failing: an exact match (es-MX), then the same language with its region dropped (es), then the default. The first tag that matches either way wins, so ["fr-CA", "es"] on a realm that lists es and en gives es.
func (RealmSettings) ConsentNames ¶ added in v0.8.2
func (s RealmSettings) ConsentNames() []string
ConsentNames returns the declared consents' names, sorted.
func (RealmSettings) ConsentsPastDeadline ¶ added in v0.8.2
func (s RealmSettings) ConsentsPastDeadline(held map[string]string, now time.Time) []ConsentRef
ConsentsPastDeadline is ConsentsToAccept restricted to the consents whose current version has a reaccept_by date that has passed: from then on a user who hasn't accepted them is refused until they do.
func (RealmSettings) ConsentsToAccept ¶ added in v0.8.2
func (s RealmSettings) ConsentsToAccept(held map[string]string) []ConsentRef
ConsentsToAccept lists the required consents a user must accept (again) to be let in: the ones they hold no version of, and the ones they hold an older version of when the current version asks for re-acceptance. held maps a consent to the version the user accepted; the list is sorted by name.
func (RealmSettings) FullAdminRoles ¶ added in v0.6.0
func (s RealmSettings) FullAdminRoles() []string
FullAdminRoles returns the names of the roles that open every area (`admin: true`), sorted: the ones that can recover a realm whatever else is lost.
func (RealmSettings) IsAdmin ¶
func (s RealmSettings) IsAdmin(roles []string) bool
IsAdmin reports whether roles include an admin role of the realm.
func (RealmSettings) Languages ¶ added in v0.4.0
func (s RealmSettings) Languages() (def string, list []string)
Languages returns a realm's default language and the languages it supports: the top-level default_locale and locales of realm.yaml, or just English when it sets none.
func (RealmSettings) ListedLocale ¶ added in v0.4.0
func (s RealmSettings) ListedLocale(tag string) string
ListedLocale returns the listed language equal to tag, ignoring case (es-mx finds es-MX), or "" when the realm doesn't list it.
func (RealmSettings) ReauthLifetime ¶ added in v0.8.2
func (s RealmSettings) ReauthLifetime() time.Duration
ReauthLifetime is the lifetime of a re-authentication token: the realm's, or the default.
func (RealmSettings) SignInRedirectAllowed ¶ added in v0.8.2
func (s RealmSettings) SignInRedirectAllowed(raw string) bool
SignInRedirectAllowed says whether a sign-in may send the user to raw: it is on sign_in.allowed_redirects, or, when the realm has none, on email.allowed_redirects.
func (RealmSettings) Throttle ¶ added in v0.6.0
func (s RealmSettings) Throttle() LoginThrottle
Throttle is the realm's login throttling, with the defaults filled in for what is left out.
type Registry ¶
Registry is the loaded configuration. It is read-only after Load.
func Load ¶
Load walks root and builds the registry. Every problem found is reported, each naming the offending path.
func (*Registry) AuthRealms ¶ added in v0.4.0
AuthRealms returns the realms with auth enabled (the ones with users, and so with jobs), sorted.
func (*Registry) CheckBundles ¶
CheckBundles reports functions projects whose bundles are missing, were built by another Deno version, don't match the sources, or were changed since the build. Startup refuses to run with any of them.
func (*Registry) CheckImageLimits ¶ added in v0.8.1
CheckImageLimits reports the fields whose `max_pixels` is above the instance's limit (BACKD_IMAGE_MAX_PIXELS): a field may only lower it.
func (*Registry) Collection ¶
func (r *Registry) Collection(realm, database, collection string) (*Collection, bool)
Collection returns the collection at realm/database/collection, if configured.
func (*Registry) Fingerprint ¶
Fingerprint identifies the config: a SHA-256 over every file backd reads from CONFIG_DIR — realm.yaml, each collection's schema.json, indexes.json and collection.yaml, and each functions project with its bundles — by relative path, length and content. Files backd ignores (hidden entries such as .git, stray files) don't change it, so the same checkout always has the same fingerprint, on any machine.
func (*Registry) FunctionRealms ¶
FunctionRealms returns the realms with at least one function, sorted.
func (*Registry) RealmNames ¶
RealmNames returns every configured realm's name, sorted.
func (*Registry) SortedRealms ¶
SortedRealms returns every realm, sorted by name.
type Retry ¶ added in v0.4.0
type Retry struct {
Attempts int // total attempts, the first included
Backoff time.Duration // the wait after the first failure; doubles after each one
MaxBackoff time.Duration // the longest single wait
}
Retry is an async function's retry policy: how often a failed attempt is repeated and how long to wait between attempts.
type Role ¶
type Role struct {
Description string
// Admin is what the sessions of users holding the role may do in the
// admin API: AllRights for `admin: true`, some areas for a list, none.
Admin AdminRights
// AdminRead is `admin: read` (alone or in a list): every area may be read.
AdminRead bool
// Users are seed assignments: normalized (trimmed, lowercased) emails.
Users []string
}
Role is a role declared in realm.yaml.
type ScopeEntry ¶ added in v0.8.2
type ScopeEntry struct {
Database string
Collection string
// Export is ExportInclude or ExportExclude.
Export string
// Owned: documents whose _meta.owner is the user. Always true when included.
Owned bool
// Fields lists the exported fields when the export is partial; nil means whole documents.
Fields []string
// Pull lists the arrays that hold the user, whose documents are included whoever owns them.
Pull []string
// Files lists the file fields whose files are part of the export.
Files []string
Reason string
// Declared: personal_data is in the collection's collection.yaml.
Declared bool
}
ScopeEntry says what the export of a user's data takes from one collection.
type SecretRef ¶
SecretRef names a secret a function may read: its own database's (`NAME`) or the realm's (`realm.NAME`).
type SoftDelete ¶ added in v0.6.0
type SoftDelete struct {
// Retention is how long a deleted document is kept before MongoDB's TTL
// index removes it; 0 keeps it until it is purged by hand.
Retention time.Duration
}
SoftDelete is collection.yaml's soft_delete: DELETE hides a document instead of removing it, so it can be restored.
type StorageSettings ¶ added in v0.8.0
type StorageSettings struct {
Provider string // storage.Provider's Name; LookupProvider gives its capabilities
// Endpoint and Region are what backd connects to, as the provider's rules
// resolve them; PublicEndpoint (providers that allow it) is only signed into
// links for browsers and never connected to.
Endpoint string
PublicEndpoint string
Region string
Bucket string
// Prefix starts every object key of this instance (<prefix>/<realm>/…): each
// backd instance sharing a bucket needs its own.
Prefix string
// AccessKey and SecretKey are the names of secrets of the realm's encrypted
// store (storage.access_key: secret:NAME), never values.
AccessKey, SecretKey string
Download string // DownloadPresigned or DownloadProxy: the default of the realm's fields
PresignedTTL time.Duration
PendingTTL time.Duration
// QuotaRealm and QuotaUser are the most bytes the files of all documents of the realm, and
// of the documents one user owns, may add up to; 0 is no limit. An upload that would pass
// either answers 413 quota_exceeded.
QuotaRealm, QuotaUser int64
// HTTP is true when Endpoint or PublicEndpoint is plain http, which startup
// allows only in development.
HTTP bool
}
StorageSettings is where a realm keeps its files: its own S3-compatible bucket on one of the supported providers. backd has no storage of its own.
func (*StorageSettings) ProviderEntry ¶ added in v0.8.0
func (s *StorageSettings) ProviderEntry() storage.Provider
ProviderEntry returns the provider's capabilities.
func (*StorageSettings) SecretNames ¶ added in v0.8.0
func (s *StorageSettings) SecretNames() []string
SecretNames are the realm secrets the storage needs.
type UserNetworks ¶
type UserNetworks struct {
Admin Networks // the user's admin API requests; within AdminNetworks
Login Networks // login and every request with the user's session
}
UserNetworks restricts where one user may act from.
type Version ¶ added in v0.8.1
type Version struct {
Name string
// Params are what workers make it with; zero (no max_width or max_height) for a
// version only functions make.
Params imaging.Params
// Writable lets functions make the version (with other parameters, too).
Writable bool
}
Version is one declared version of an image field (image versions, milestone 11).
func (Version) Fingerprint ¶ added in v0.8.1
Fingerprint identifies what a version is made with, so that a changed declaration can be told from the copies made before it. Defaults are written out, so spelling a default doesn't change it.