client

package
v0.9.7 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 29 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package client is the Go client for backd: one entry point per realm, with the sign-in surface, collections that speak the query language, files, functions and their jobs, organizations, push devices, the app configuration and live views, the way backd-js and the Dart client do.

It uses the standard library only and never imports backd's internal packages, so it stays small to depend on. The admin API is not part of it: administration is a server-side concern and a shipped application must not be able to administer a realm. Tools that need it build on Client.Do.

c := client.New(client.Options{URL: "http://localhost:8080", Realm: "shelf", APIKey: key})
defer c.Close()

Every call that does I/O takes a context.Context first. Errors are *Error values: use errors.Is with the Err… sentinels (ErrNotFound, ErrConflict, …) and errors.As with *Error or the typed errors that carry more, such as *ConsentRequiredError.

The design is in design/go-client.md.

Example

A client talks to one realm: sign in once, and the token goes with every call.

package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/fernandezvara/backd/pkg/client"
)

// demo is a small stand-in for a backd server, so the examples run.
func demo() *httptest.Server {
	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch {
		case r.URL.Path == "/v1/shelf/_auth/login":
			fmt.Fprint(w, `{"token":"bds_demo","session_id":"s1","expires_at":"2030-01-01T00:00:00Z","user":{"id":"u1","email":"ada@example.com"}}`)
		case r.URL.Path == "/v1/shelf/main/assets" && r.URL.Query().Get("after") == "":
			fmt.Fprint(w, `{"items":[{"id":"a1","title":"Docs","_meta":{"version":1}},{"id":"a2","title":"Notes","_meta":{"version":1}}],"has_more":true,"next_cursor":"c1"}`)
		case r.URL.Path == "/v1/shelf/main/assets":
			fmt.Fprint(w, `{"items":[{"id":"a3","title":"Links","_meta":{"version":1}}],"has_more":false}`)
		default:
			w.WriteHeader(http.StatusNotFound)
			fmt.Fprint(w, `{"error":{"code":"not_found","message":"no such document","request_id":"rq1"}}`)
		}
	}))
}

func main() {
	srv := demo()
	defer srv.Close()
	ctx := context.Background()

	c, err := client.New(client.Options{URL: srv.URL, Realm: "shelf"})
	if err != nil {
		panic(err)
	}
	defer c.Close()

	session, err := c.Auth().Login(ctx, client.SignInInput{Email: "ada@example.com", Password: "dev-p4ssw0rd!"})
	if err != nil {
		panic(err)
	}
	fmt.Println("signed in as", session.User.Email)

	page, err := c.DB("main").Collection("assets").List(ctx, client.Query{Limit: 2})
	if err != nil {
		panic(err)
	}
	for _, doc := range page.Items {
		fmt.Println(doc.ID(), doc["title"])
	}
}
Output:
signed in as ada@example.com
a1 Docs
a2 Notes

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrBackd = &Error{kind: kBackd} // every error of this package

	ErrValidation      = &Error{kind: kValidation}     // 400
	ErrAuthentication  = &Error{kind: kAuthentication} // 401
	ErrForbidden       = &Error{kind: kForbidden}      // 403
	ErrNotFound        = &Error{kind: kNotFound}       // 404
	ErrConflict        = &Error{kind: kConflict}       // 409
	ErrVersionMismatch = &Error{kind: kVersion}        // 412: the If-Match version is not the current one
	ErrRetryable       = &Error{kind: kRetryable}      // 429 and 503
	ErrNetwork         = &Error{kind: kNetwork}        // no answer: the connection failed, or the context ended

	ErrRealtimeNotEnabled    = &Error{kind: kRealtimeNotEnabled}
	ErrTooManySubscriptions  = &Error{kind: kTooManySubs}
	ErrInvalidResumeToken    = &Error{kind: kInvalidResume}
	ErrInvalidID             = &Error{kind: kInvalidID}
	ErrTeam                  = &Error{kind: kTeam}
	ErrInvalidExpand         = &Error{kind: kInvalidExpand}
	ErrExpandTooLarge        = &Error{kind: kExpandTooLarge}
	ErrInvalidAggregate      = &Error{kind: kInvalidAggregate}
	ErrFieldEncrypted        = &Error{kind: kFieldEncrypted}
	ErrAggregateNotEnabled   = &Error{kind: kAggregateNotOn}
	ErrSearchNotEnabled      = &Error{kind: kSearchNotOn}
	ErrSsoRequired           = &Error{kind: kSsoRequired}
	ErrPasswordExpired       = &Error{kind: kPasswordExpired}
	ErrSessionEnded          = &Error{kind: kSessionEnded}
	ErrOrgRequiresMFA        = &Error{kind: kOrgRequiresMFA}
	ErrOrgRoleRequiresMFA    = &Error{kind: kOrgRoleRequiresMFA}
	ErrNotTeamMember         = &Error{kind: kNotTeamMember}
	ErrNotAllowed            = &Error{kind: kNotAllowed}
	ErrSsoSession            = &Error{kind: kSsoSession}
	ErrNotOrgMember          = &Error{kind: kNotOrgMember}
	ErrIDTaken               = &Error{kind: kIDTaken}
	ErrLastOrgManager        = &Error{kind: kLastOrgManager}
	ErrIndexBuilding         = &Error{kind: kIndexBuilding}
	ErrAggregateTooExpensive = &Error{kind: kAggregateCost}
	ErrSearchTooExpensive    = &Error{kind: kSearchCost}
	ErrVerificationRequired  = &Error{kind: kVerification}
	ErrSecondStepRequired    = &Error{kind: kSecondStep}
	ErrConsentRequired       = &Error{kind: kConsentRequired}
)

The sentinels match with errors.Is. A sentinel of a class matches its subclasses too: ErrValidation matches ErrInvalidID, ErrConflict matches ErrIDTaken, ErrForbidden matches ErrOrgRequiresMFA.

Functions

func Between

func Between(lo, hi any) map[string]any

Between matches values from lo to hi, both included.

func BucketKey

func BucketKey(t time.Time, unit BucketUnit) (string, error)

BucketKey is the bucket key of a date (in UTC), in the text form the server uses: "2026-03-07", "2026-W10" (ISO 8601 weeks, from Monday), "2026-03" or "2026".

func Contains

func Contains(s string) map[string]any

func DecodeDocs

func DecodeDocs[T any](docs []Doc) ([]T, error)

DecodeDocs decodes documents into structs, for the items of a view.

func EndsWith

func EndsWith(s string) map[string]any

func Eq

func Eq(v any) map[string]any

Eq, Ne, Gt, Gte, Lt, Lte, In, Nin, Between, IsNull, NotNull, Like, ILike, StartsWith, IStartsWith, EndsWith, IEndsWith, Contains and IContains build the operators of a field's condition.

func Expand

func Expand(parts ...ExpandPart) (string, error)

Expand builds the Expand of a Query and of a read: the references to return next to the result, in _expanded, with the fields of each: "author(name,avatar),tags". Nothing is expanded unless you pass this.

func Flatten

func Flatten(values map[string]any) map[string]any

Flatten turns nested values into dotted paths: {"limits": {"max": 5}} becomes {"limits.max": 5}.

func FormatSize

func FormatSize(n int64, family SizeFamily) string

FormatSize prints n for people: the largest unit whose value is at least 1, up to TB or TiB, with at most two decimals and no trailing zeros ("1.5 KiB", "5 MiB"). SizeBoth prints binary.

func Gt

func Gt(v any) map[string]any

func Gte

func Gte(v any) map[string]any

func IContains

func IContains(s string) map[string]any

func IEndsWith

func IEndsWith(s string) map[string]any

func ILike

func ILike(s string) map[string]any

func IStartsWith

func IStartsWith(s string) map[string]any

func IfMatchValue

func IfMatchValue(v any) (string, error)

IfMatchValue is the If-Match of a version: a number becomes the quoted ETag the server compares.

func In

func In(vs ...any) map[string]any

func IsNull

func IsNull() map[string]any

func Like

func Like(s string) map[string]any

func Lt

func Lt(v any) map[string]any

func Lte

func Lte(v any) map[string]any

func MustExpand

func MustExpand(parts ...ExpandPart) string

MustExpand is Expand for names written in the program: it panics on a bad one.

func Ne

func Ne(v any) map[string]any

func Nin

func Nin(vs ...any) map[string]any

func NormalizeOrg

func NormalizeOrg(ref string) string

NormalizeOrg is an organization as the server compares it: case and surrounding spaces do not matter.

func NotNull

func NotNull() map[string]any

func ParseSize

func ParseSize(v string, family SizeFamily, allowBytes bool) (int64, error)

ParseSize parses a size such as "128MB" (powers of 1000) or "1.5MiB" (powers of 1024). The unit is case-sensitive and follows the number directly. A decimal is fine when the result is a whole number of bytes. family limits the units; allowBytes also accepts a bare number of bytes ("1048576"). It follows the one size grammar of the server and the other clients.

Example

Sizes follow the one grammar of the server: a number and a case-sensitive unit.

package main

import (
	"fmt"
	"strings"

	"github.com/fernandezvara/backd/pkg/client"
)

func main() {
	n, err := client.ParseSize("1.5MiB", client.SizeBoth, false)
	fmt.Println(n, err)
	fmt.Println(client.FormatSize(n, client.SizeBinary))
	_, err = client.ParseSize("1.5mib", client.SizeBoth, false)
	fmt.Println(strings.HasPrefix(err.Error(), `invalid size "1.5mib"`))
}
Output:
1572864 <nil>
1.5 MiB
true

func PublicURL

func PublicURL(file *FileDetails, version string) string

PublicURL is a public file's permanent address, or of one of its versions once that is ready. It is "" for a file that isn't public, and for a version that isn't ready.

func StartsWith

func StartsWith(s string) map[string]any

Types

type Account

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

Account is the signed-in user's own data: ask for a copy of everything the realm holds about them, and download it. c.Account().

func (*Account) DownloadExport

func (a *Account) DownloadExport(ctx context.Context, id string, dst io.Writer, opts ...RequestOption) (int64, error)

DownloadExport copies the package of a ready export (a zip) to dst and returns how many bytes were written. The server answers with the bytes or with a link to the storage; both work.

func (*Account) Export

func (a *Account) Export(ctx context.Context, id string, opts ...RequestOption) (*DataExport, error)

Export returns one export.

func (*Account) Exports

func (a *Account) Exports(ctx context.Context, opts ...RequestOption) ([]DataExport, error)

Exports lists the user's exports.

func (*Account) RequestExport

func (a *Account) RequestExport(ctx context.Context, opts ...RequestOption) (*DataExport, error)

RequestExport asks for a copy of the user's data; it needs a recent proof (Auth.Reauth).

func (*Account) WaitForExport

func (a *Account) WaitForExport(ctx context.Context, id string, o ExportWaitOptions, opts ...RequestOption) (*DataExport, error)

WaitForExport polls until the export is ready. A failed or expired export is an error.

type AggregateGroup

type AggregateGroup struct {
	// Key maps each grouped field (with its bucket, "paid_at:month") to the group's value.
	Key map[string]any
	// Values maps each metric ("count", "sum_total", …) to its value.
	Values map[string]any
}

AggregateGroup is one group of an aggregation: its key and the values of the metrics.

func FillBuckets

func FillBuckets(groups []AggregateGroup, o FillBucketsOptions) ([]AggregateGroup, error)

FillBuckets fills the buckets an aggregation left out, so a chart has a point for every day, week, month or year between From and To. The server doesn't return empty buckets; this adds them to groups grouped by one date field and nothing else (GroupBy "paid_at:month"). The groups come back in key order; a group with a null key (documents with no date) stays at the front.

func (AggregateGroup) Count

func (g AggregateGroup) Count() (float64, bool)

Count returns the group's count metric.

func (AggregateGroup) MarshalJSON

func (g AggregateGroup) MarshalJSON() ([]byte, error)

func (*AggregateGroup) UnmarshalJSON

func (g *AggregateGroup) UnmarshalJSON(b []byte) error

type AggregateParams

type AggregateParams struct {
	// Where is the same filter as a list's, with $search; the read rules apply first.
	Where any
	// GroupBy lists up to 3 declared fields; a date takes a bucket: "paid_at:month".
	GroupBy []string
	// Metrics are "count" (the default), "count_distinct:<field>", "sum:<field>", "avg:<field>", …
	Metrics []string
	// TZ is the IANA zone of the date buckets ("Europe/Madrid"); UTC by default.
	TZ string
	// OrderBy lists group keys and result names, "-" for descending: "-count".
	OrderBy []string
	// Limit is the number of groups returned.
	Limit int
	// Language is the language of a $search in Where.
	Language string
}

AggregateParams are the parameters of an aggregation.

type AggregateResult

type AggregateResult struct {
	Groups []AggregateGroup `json:"groups"`
	// TotalGroups is how many groups there were before Limit.
	TotalGroups int `json:"total_groups"`
}

AggregateResult is the answer of an aggregation.

type Auth

type Auth struct {

	// MFA is the second factor of the signed-in user.
	MFA *MFA
	// MagicLink signs in with a link sent by email, and a code to type when the link opens elsewhere.
	MagicLink *MagicLink
	// contains filtered or unexported fields
}

Auth is the sign-up, sign-in and session side of a client: c.Auth().

func (*Auth) AcceptConsents

func (a *Auth) AcceptConsents(ctx context.Context, challenge string, consents map[string]string, opts ...RequestOption) (*Session, error)

AcceptConsents finishes a sign-in that had consents to accept first (name to version).

func (*Auth) AcceptInvitation

func (a *Auth) AcceptInvitation(ctx context.Context, token, password, locale string, opts ...RequestOption) error

AcceptInvitation accepts an invitation by its token; password sets one for a new account.

func (*Auth) ChangePassword

func (a *Auth) ChangePassword(ctx context.Context, newPassword string, opts ...RequestOption) error

ChangePassword sets a new password for the signed-in user (or the first one, for an account that signs in with a provider). It needs a recent proof (Reauth).

func (*Auth) CompleteSignIn

func (a *Auth) CompleteSignIn(ctx context.Context, address string, opts ...RequestOption) (*Step, error)

CompleteSignIn finishes a redirect sign-in (or a link, or a magic link) from the address the person came back to. It returns nil, nil when the address carries no sign-in. The result is the step the sign-in led to (StepLinked after a link). A sign-in through an organization's connection is kept by that organization's client when the storage allows it.

func (*Auth) ConfirmEmailChange

func (a *Auth) ConfirmEmailChange(ctx context.Context, token string, opts ...RequestOption) error

ConfirmEmailChange confirms the change with the token of the link sent to the new address.

func (*Auth) Current

func (a *Auth) Current() *Session

Current returns the session of the last sign-in made by this client, or nil.

func (*Auth) DeleteAccount

func (a *Auth) DeleteAccount(ctx context.Context, opts ...RequestOption) error

DeleteAccount deactivates the signed-in user's account (it can't sign in; its data is kept). It needs a recent proof (Reauth).

func (*Auth) FindOrgs

func (a *Auth) FindOrgs(ctx context.Context, email, locale string, opts ...RequestOption) error

FindOrgs asks the server to email the person the organizations their address belongs to. The answer is the same whether or not the address is known.

func (*Auth) HasFreshProof

func (a *Auth) HasFreshProof() bool

HasFreshProof reports whether a proof from Reauth is still good.

func (*Auth) HasSession

func (a *Auth) HasSession(ctx context.Context) (bool, error)

HasSession reports whether a session token is stored (it may have expired).

func (*Auth) LinkProvider

func (a *Auth) LinkProvider(ctx context.Context, provider string, o OAuthOptions, opts ...RequestOption) (string, error)

LinkProvider starts linking a provider to the signed-in user; it needs a recent proof (Reauth).

func (*Auth) LinkProviderWithIDToken

func (a *Auth) LinkProviderWithIDToken(ctx context.Context, provider string, in IDTokenInput, opts ...RequestOption) error

LinkProviderWithIDToken links a provider to the signed-in user with an identity token.

func (*Auth) Login

func (a *Auth) Login(ctx context.Context, in SignInInput, opts ...RequestOption) (*Session, error)

Login signs in with email and password and returns the session. A second step to take is a *SecondStepRequiredError carrying the challenge.

func (*Auth) Logout

func (a *Auth) Logout(ctx context.Context, opts ...RequestOption) error

Logout ends the current session. The local token is removed even when the server says it was already gone.

func (*Auth) LogoutAll

func (a *Auth) LogoutAll(ctx context.Context, opts ...RequestOption) error

LogoutAll ends every session of the user.

func (*Auth) Me

func (a *Auth) Me(ctx context.Context, opts ...RequestOption) (*Me, error)

Me returns the signed-in user with their sign-in methods.

func (*Auth) OnChange

func (a *Auth) OnChange(f func(AuthChange)) (stop func())

OnChange registers f to be called on every sign-in, sign-out and expiry, and returns the function that removes it. f runs on the goroutine that made the change; keep it short.

func (*Auth) Options

func (a *Auth) Options(ctx context.Context, org string, opts ...RequestOption) (*SignInOptions, error)

Options asks how people can sign in; org is an organization by id or slug (the client's own by default).

func (*Auth) Org

func (a *Auth) Org(ctx context.Context, opts ...RequestOption) (*MeOrg, error)

Org returns the organization the session is scoped to, or nil.

func (*Auth) PreviewInvitation

func (a *Auth) PreviewInvitation(ctx context.Context, token, org string, opts ...RequestOption) (*InvitationPreview, error)

PreviewInvitation says what an invitation offers before the person has signed in, so the app can ask "Join Acme as editor?". org is the organization the token is for, by id or slug (the client's own by default). Every token that does not work fails alike with invalid_invitation.

func (*Auth) Providers

func (a *Auth) Providers(ctx context.Context, org string, opts ...RequestOption) ([]string, error)

Providers lists the external providers that are enabled.

func (*Auth) Reauth

func (a *Auth) Reauth(ctx context.Context, in ReauthInput, opts ...RequestOption) (*ReauthProof, error)

Reauth gets a fresh proof of identity. The client keeps it and sends it with the sensitive calls (changing a password, an email address, the second factor, deleting the account) until it expires.

func (*Auth) RemovePassword

func (a *Auth) RemovePassword(ctx context.Context, opts ...RequestOption) error

RemovePassword removes the password, leaving the other ways of signing in. It needs a recent proof.

func (*Auth) RequestEmailChange

func (a *Auth) RequestEmailChange(ctx context.Context, newEmail, redirectTo string, opts ...RequestOption) error

RequestEmailChange asks to change the signed-in user's address; a confirmation goes to the new one. It needs a recent proof (Reauth).

func (*Auth) RequestPasswordReset

func (a *Auth) RequestPasswordReset(ctx context.Context, email, redirectTo, org string, opts ...RequestOption) error

RequestPasswordReset emails a reset link; the answer is the same whether or not the address is known.

func (*Auth) RequestReauthCode

func (a *Auth) RequestReauthCode(ctx context.Context, opts ...RequestOption) error

RequestReauthCode emails the user a code to prove who they are with Reauth (method "email_code").

func (*Auth) ResendVerification

func (a *Auth) ResendVerification(ctx context.Context, email, redirectTo string, opts ...RequestOption) error

ResendVerification asks for the verification email again; the answer is the same whether or not the address is known.

func (*Auth) ResetPassword

func (a *Auth) ResetPassword(ctx context.Context, token, password string, opts ...RequestOption) error

ResetPassword sets a new password with the token of the reset link.

func (*Auth) RevertEmailChange

func (a *Auth) RevertEmailChange(ctx context.Context, token string, opts ...RequestOption) error

RevertEmailChange undoes a change with the token of the link sent to the old address.

func (*Auth) RevokeSession

func (a *Auth) RevokeSession(ctx context.Context, id string, opts ...RequestOption) error

RevokeSession ends one of the user's sessions by id.

func (*Auth) Sessions

func (a *Auth) Sessions(ctx context.Context, opts ...RequestOption) ([]SessionInfo, error)

Sessions lists the signed-in user's sessions.

func (*Auth) SignIn

func (a *Auth) SignIn(ctx context.Context, in SignInInput, opts ...RequestOption) (*Step, error)

SignIn checks the first factor and returns the step it leads to: the session (stored), or the second step to take. Use Login when a second step should be an error.

func (*Auth) SignInWith

func (a *Auth) SignInWith(ctx context.Context, provider string, o OAuthOptions, opts ...RequestOption) (string, error)

SignInWith starts a sign-in with a provider ("google", "microsoft", "apple" or a configured one) and returns the address to send the person to. The PKCE verifier is kept in the OAuth storage until CompleteSignIn gets the address the person comes back to.

func (*Auth) SignInWithIDToken

func (a *Auth) SignInWithIDToken(ctx context.Context, provider string, in IDTokenInput, opts ...RequestOption) (*Step, error)

SignInWithIDToken signs in with an identity token from a provider's native flow.

func (*Auth) SignUpWithOrg

func (a *Auth) SignUpWithOrg(ctx context.Context, in SignUpWithOrgInput, opts ...RequestOption) (*OrgSession, error)

SignUpWithOrg creates an account and an organization together and signs in. The session is scoped to the new organization: with a storage that can keep a token per organization, it is kept in the client of that organization (c.Org(slug)) and returned from there.

func (*Auth) Signup

func (a *Auth) Signup(ctx context.Context, in SignUpInput, opts ...RequestOption) (*Session, error)

Signup creates an account and signs in. When the realm requires a verified address first it returns an error matching ErrVerificationRequired and nothing is stored; a person with a second step to take gets a *SecondStepRequiredError.

func (*Auth) Token

func (a *Auth) Token(ctx context.Context) (string, error)

Token returns the stored session token, or "" when signed out.

func (*Auth) UnlinkProvider

func (a *Auth) UnlinkProvider(ctx context.Context, provider, org string, opts ...RequestOption) error

UnlinkProvider removes a provider from the signed-in user; it needs a recent proof.

func (*Auth) UpdateMe

func (a *Auth) UpdateMe(ctx context.Context, changes map[string]any, opts ...RequestOption) (*User, error)

UpdateMe changes the signed-in user's own settings: today their language ("locale"), which must be one the realm lists.

func (*Auth) UpdatePassword

func (a *Auth) UpdatePassword(ctx context.Context, in UpdatePasswordInput, opts ...RequestOption) error

UpdatePassword replaces an expired password.

func (*Auth) VerifyEmail

func (a *Auth) VerifyEmail(ctx context.Context, token string, opts ...RequestOption) error

VerifyEmail confirms an address with the token of the link.

func (*Auth) VerifyMFA

func (a *Auth) VerifyMFA(ctx context.Context, challenge, method, code string, opts ...RequestOption) (*Session, error)

VerifyMFA finishes a sign-in with a code of the second factor (method "totp" or "recovery_code").

func (*Auth) WithProof

func (a *Auth) WithProof(ctx context.Context, ask func(ctx context.Context, methods []string) (ReauthInput, error), action func(ctx context.Context) error) error

WithProof runs action; when the server asks for a fresh proof (reauth_required) it asks the person with ask (given the methods they can use), reauthenticates and runs action again.

type AuthChange

type AuthChange struct {
	Event AuthEvent
	// Session is the new session for SignedIn, otherwise nil.
	Session *Session
}

AuthChange is what a listener receives.

type AuthEvent

type AuthEvent string

AuthEvent says what changed.

const (
	// SignedIn: a sign-in (signup or login).
	SignedIn AuthEvent = "SIGNED_IN"
	// SignedOut: a sign-out (logout, logout everywhere, account deleted).
	SignedOut AuthEvent = "SIGNED_OUT"
	// SessionExpired: the server refused the stored token.
	SessionExpired AuthEvent = "SESSION_EXPIRED"
)

type Base

type Base struct {
	ID       string         `json:"id"`
	Meta     Meta           `json:"_meta"`
	Expanded map[string]any `json:"_expanded,omitempty"`
}

Base is what every document has. Embed it in the struct of a document:

type Post struct {
    client.Base
    Title string `json:"title"`
}

type BatchOperation

type BatchOperation struct {
	Op         string         `json:"op"` // "create", "replace", "patch" or "delete"
	Collection string         `json:"collection"`
	ID         string         `json:"id,omitempty"`
	Document   map[string]any `json:"document,omitempty"`
	Patch      map[string]any `json:"patch,omitempty"`
	// IfMatch is the version the document must have: an int, or an ETag string.
	IfMatch any `json:"-"`
}

BatchOperation is one operation of a batch.

type BucketUnit

type BucketUnit string

BucketUnit is the size of a date bucket of an aggregation.

const (
	BucketDay   BucketUnit = "day"
	BucketWeek  BucketUnit = "week"
	BucketMonth BucketUnit = "month"
	BucketYear  BucketUnit = "year"
)

type CacheOptions

type CacheOptions struct {
	// Disable turns the cache off.
	Disable bool
	// MaxEntries bounds the number of reads kept; 200 when zero.
	MaxEntries int
	// MaxBytes bounds the size of the bodies kept; 5 MiB when zero.
	MaxBytes int
}

CacheOptions tune the revalidation cache. It is on by default.

type CacheStats

type CacheStats struct {
	// Hits are reads the server answered 304 to: the kept body was current.
	Hits int
	// Misses are cacheable reads that came back in full.
	Misses int
	// Entries and Bytes are what is kept.
	Entries int
	Bytes   int
}

CacheStats says how the revalidation cache is doing.

type Client

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

Client talks to one realm. It is safe for concurrent use.

func New

func New(opts Options) (*Client, error)

New creates a client for one realm.

func (*Client) Account

func (c *Client) Account() *Account

Account returns the signed-in user's own data.

func (*Client) Auth

func (c *Client) Auth() *Auth

Auth returns the sign-up, sign-in and session calls.

func (*Client) CacheStats

func (c *Client) CacheStats() CacheStats

CacheStats says how the client's revalidation cache is doing; zero when it is off.

func (*Client) ClearCache

func (c *Client) ClearCache()

ClearCache forgets everything the revalidation cache holds.

func (*Client) Close

func (c *Client) Close() error

Close ends what the client keeps running (live views) and releases idle connections. The client can't be used for live views afterwards. It is safe to call twice.

func (*Client) Config

func (c *Client) Config() *Config

Config returns the realm's app configuration: flags, switches and limits, cached per user.

func (*Client) Consents

func (c *Client) Consents() *Consents

Consents returns the realm's consents: their texts, and what the signed-in user holds.

func (*Client) DB

func (c *Client) DB(name string) *Database

DB returns a database of the realm.

func (*Client) Do

func (c *Client) Do(ctx context.Context, method string, path []string, body, out any, opts ...RequestOption) (*Response, error)

Do sends one call to /v1/{realm}/{path…} and returns the answer. It is the extension point other code builds on: it adds the credentials, applies retries and the revalidation cache, maps failures to *Error and reports stale types. path is the segments after the realm; each is encoded here. body, when not nil, is sent as JSON; a successful JSON answer is decoded into out when out is not nil.

Example

Do is the primitive every call is made with, for endpoints the client has no method for.

package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/fernandezvara/backd/pkg/client"
)

// demo is a small stand-in for a backd server, so the examples run.
func demo() *httptest.Server {
	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch {
		case r.URL.Path == "/v1/shelf/_auth/login":
			fmt.Fprint(w, `{"token":"bds_demo","session_id":"s1","expires_at":"2030-01-01T00:00:00Z","user":{"id":"u1","email":"ada@example.com"}}`)
		case r.URL.Path == "/v1/shelf/main/assets" && r.URL.Query().Get("after") == "":
			fmt.Fprint(w, `{"items":[{"id":"a1","title":"Docs","_meta":{"version":1}},{"id":"a2","title":"Notes","_meta":{"version":1}}],"has_more":true,"next_cursor":"c1"}`)
		case r.URL.Path == "/v1/shelf/main/assets":
			fmt.Fprint(w, `{"items":[{"id":"a3","title":"Links","_meta":{"version":1}}],"has_more":false}`)
		default:
			w.WriteHeader(http.StatusNotFound)
			fmt.Fprint(w, `{"error":{"code":"not_found","message":"no such document","request_id":"rq1"}}`)
		}
	}))
}

func main() {
	srv := demo()
	defer srv.Close()
	c, _ := client.New(client.Options{URL: srv.URL, Realm: "shelf"})
	defer c.Close()

	var page struct {
		Items []struct{ ID string }
	}
	_, err := c.Do(context.Background(), "GET", []string{"main", "assets"}, nil, &page)
	fmt.Println(len(page.Items), err)
}
Output:
2 <nil>

func (*Client) Functions

func (c *Client) Functions() *Functions

Functions returns the functions of the realm, addressed as "<database>/<name>".

func (*Client) HasAPIKey

func (c *Client) HasAPIKey() bool

HasAPIKey reports whether the client was created with an API key.

func (*Client) OnClose

func (c *Client) OnClose(f func())

OnClose registers f to run when the client is closed; realtime streams use it to end.

func (*Client) OnCredentialChange

func (c *Client) OnCredentialChange(f func())

OnCredentialChange registers f to run when the signed-in caller changes (a sign-in, a sign-out, an expired session): whatever was read as the previous caller is not the new one's. The caches use it.

func (*Client) Org

func (c *Client) Org(ref string) (*Client, error)

Org returns the client of one organization, for a program that is signed in to several at once: it has the same address, realm and settings and a token of its own, so its calls reach that organization and no other, and signing out of it leaves the others signed in. The organization is its id or its slug; asking again for the same gives the same client. It needs a storage that can keep a token per organization (MemoryStorage and FileStorage can).

func (*Client) OrgRef

func (c *Client) OrgRef() string

OrgRef returns the organization the client is bound to, as it was given, or "".

func (*Client) Orgs

func (c *Client) Orgs() *Orgs

Orgs returns the organizations of the signed-in user: members, teams, templates and invitations.

func (*Client) Push

func (c *Client) Push() *Push

Push returns the signed-in user's push devices.

func (*Client) Realm

func (c *Client) Realm() string

Realm returns the realm the client talks to.

func (*Client) Realtime

func (c *Client) Realtime() *Realtime

Realtime returns the live views of the client.

func (*Client) Storage

func (c *Client) Storage() TokenStorage

Storage returns where the client keeps its session token.

func (*Client) URL

func (c *Client) URL() string

URL returns the base URL of the server, without a trailing slash.

type Collection

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

Collection is a collection of a database. Its calls return documents as Doc; use Typed to get structs.

func (*Collection) Aggregate

func (c *Collection) Aggregate(ctx context.Context, p AggregateParams, opts ...RequestOption) (*AggregateResult, error)

Aggregate groups the documents and computes metrics over them, on the server.

func (*Collection) Client

func (c *Collection) Client() *Client

Client returns the client the collection reads through.

func (*Collection) Create

func (c *Collection) Create(ctx context.Context, doc any, opts ...RequestOption) (Doc, error)

Create writes a new document and returns it as stored.

func (*Collection) Delete

func (c *Collection) Delete(ctx context.Context, id string, opts ...RequestOption) error

Delete deletes a document.

func (*Collection) DeleteFile

func (c *Collection) DeleteFile(ctx context.Context, id, field, fileID string, opts ...RequestOption) (Doc, error)

DeleteFile removes one file from a field and returns the document.

func (*Collection) DownloadFile

func (c *Collection) DownloadFile(ctx context.Context, id, field, fileID string, dst io.Writer, o GetFileOptions, opts ...RequestOption) (int64, error)

DownloadFile copies a file's bytes to dst and returns how many were written.

func (*Collection) FileField

func (c *Collection) FileField(ctx context.Context, field string, opts ...RequestOption) (*FileField, error)

FileField returns how the collection declares a file field. The answer is kept by the client.

func (*Collection) FileURL

func (c *Collection) FileURL(ctx context.Context, id, field, fileID string, o FileURLOptions, opts ...RequestOption) (*FileLink, error)

FileURL returns a link to read a file: the permanent address of a public file (made without a request when File is given), or a signed link. It returns nil for a version that isn't ready.

func (*Collection) Files

func (c *Collection) Files(id, field string) *Files

Files returns the files held in a field of a document.

func (*Collection) Get

func (c *Collection) Get(ctx context.Context, id string, o ReadOptions, opts ...RequestOption) (Doc, error)

Get reads one document.

func (*Collection) InTeam

func (c *Collection) InTeam(team string) *Collection

InTeam returns the collection scoped to a team of the organization: lists and creates reach that team's documents.

func (*Collection) Iterate

func (c *Collection) Iterate(ctx context.Context, q Query, opts ...RequestOption) iter.Seq2[Doc, error]

Iterate reads every document the query matches, following the cursors.

func (*Collection) List

func (c *Collection) List(ctx context.Context, q Query, opts ...RequestOption) (*Page[Doc], error)

List reads a page of documents.

func (*Collection) Name

func (c *Collection) Name() string

Name returns the collection's name.

func (*Collection) Patch

func (c *Collection) Patch(ctx context.Context, id string, patch any, opts ...RequestOption) (Doc, error)

Patch merges changes into a document.

func (*Collection) Path

func (c *Collection) Path() []string

Path returns the database and collection names.

func (*Collection) PrepareUpload

func (c *Collection) PrepareUpload(ctx context.Context, field string, src *FileSource, o UploadOptions, opts ...RequestOption) (*PreparedUpload, error)

PrepareUpload stores a file before its document exists, so the document can be created with the file in one write: create the document with the returned Ref in the field.

func (*Collection) Replace

func (c *Collection) Replace(ctx context.Context, id string, doc any, opts ...RequestOption) (Doc, error)

Replace replaces a document.

func (*Collection) Restore

func (c *Collection) Restore(ctx context.Context, id string, opts ...RequestOption) (Doc, error)

Restore brings back a soft-deleted document.

func (*Collection) Search

func (c *Collection) Search(ctx context.Context, text string, q Query, opts ...RequestOption) (*Page[Doc], error)

Search lists the documents that match the text, best first.

func (*Collection) Subscribe

func (c *Collection) Subscribe(spec SubscriptionSpec, o SubscribeOptions) (*LiveView, error)

Subscribe follows this collection. The spec's DB and Collection are filled in; in a collection scoped to a team (Collection.InTeam) the filter is limited to the team.

func (*Collection) UploadFile

func (c *Collection) UploadFile(ctx context.Context, id, field string, src *FileSource, o UploadOptions, opts ...RequestOption) (Doc, error)

UploadFile uploads a file into a field of a document the way the field takes it (through backd, or straight to the storage, in parts when it is large) and returns the document.

type Config

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

Config is the realm's app configuration: flags, switches and limits the operator changes without a release, cached per user. It revalidates stale copies with If-None-Match and tells listeners which paths changed. c.Config().

func (*Config) Decode

func (cfg *Config) Decode(ctx context.Context, path string, out any, opts ...RequestOption) error

Decode reads the value at a path into out (a pointer), like json.Unmarshal.

func (*Config) Get

func (cfg *Config) Get(ctx context.Context, path string, opts ...RequestOption) (any, error)

Get returns the value at a dotted path ("limits.max"), nil when it isn't set. A held copy answers at once; a stale one is revalidated in the background. Unknown paths are fetched.

func (*Config) GetSync

func (cfg *Config) GetSync(path string, fallback any) any

GetSync returns the value at a path from what is held, or fallback when nothing held covers it. It never waits and never asks the server: call Load first.

func (*Config) Live

func (cfg *Config) Live(paths ...string) (stop func())

Live keeps the held copies of the configuration current: it follows the paths over the realtime stream (all the caller reads, with none), and re-reads what changed. Changes are reported to Config.OnChange; failures to Config.OnError. It returns the function that stops it.

func (*Config) Load

func (cfg *Config) Load(ctx context.Context, paths []string, opts ...RequestOption) (map[string]any, error)

Load returns the values under paths (all of them with none), from the held copy while it is fresh and from the server otherwise.

func (*Config) OnChange

func (cfg *Config) OnChange(f func(paths []string)) (stop func())

OnChange registers f to be called with the dotted paths whose values changed when a held copy is replaced by a different one. It returns the function that removes it.

func (*Config) OnError

func (cfg *Config) OnError(f func(error)) (stop func())

OnError registers f to be called with the errors of the background updates (revalidations and the live stream), which have nobody to return them to.

func (*Config) Refresh

func (cfg *Config) Refresh(ctx context.Context, paths []string, opts ...RequestOption) (map[string]any, error)

Refresh is Load that always asks the server (the copy held is revalidated, so an unchanged configuration costs a 304).

type ConfigStorage

type ConfigStorage interface {
	// Load returns the value saved under key, or "" when there is none.
	Load(key string) (string, error)
	Save(key, value string) error
	// Clear removes every key that starts with prefix.
	Clear(prefix string) error
}

ConfigStorage keeps the app configuration between runs, so a program starts with the last values it saw. It is optional: without it the configuration is kept in memory.

type ConnectionInput

type ConnectionInput struct {
	ClientID string
	// ClientSecret is required the first time; left out, the stored one is kept.
	ClientSecret string
	// Tenant: Microsoft, required, a tenant id (never common, organizations or consumers).
	Tenant string
	// HostedDomain: Google, required, the Workspace domain.
	HostedDomain    string
	EmailDomains    []string
	NativeClientIDs []string
	JoinRoles       []string
	// Enabled is true for a new connection; unchanged on a replace.
	Enabled *bool
}

ConnectionInput is the input of Set. Nil and empty fields are left out.

type ConsentEvent

type ConsentEvent struct {
	Consent string `json:"consent"`
	Version string `json:"version"`
	Action  string `json:"action"` // "accepted" or "withdrawn"
	Method  string `json:"method"` // "signup", "prompt", "api" or "admin"
	Locale  string `json:"locale"`
	At      string `json:"at"`
}

ConsentEvent is one entry of the history of a user's consents.

type ConsentHistory

type ConsentHistory struct {
	ConsentState
	History []ConsentEvent `json:"history"`
}

ConsentHistory is the state with the history.

type ConsentInfo

type ConsentInfo struct {
	Name     string `json:"name"`
	Required bool   `json:"required"`
	Current  struct {
		Version  string `json:"version"`
		Reaccept bool   `json:"reaccept"`
		// ReacceptBy is the date by which the new version has to be accepted again.
		ReacceptBy string `json:"reaccept_by,omitempty"`
	} `json:"current"`
	Locales []string `json:"locales"`
}

ConsentInfo is a consent the realm asks for.

type ConsentRef

type ConsentRef struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

ConsentRef names a consent and the version it asks for.

type ConsentRequiredError

type ConsentRequiredError struct {

	// Consents are the ones to accept, with the versions the server wants.
	Consents []ConsentRef
	// contains filtered or unexported fields
}

func (*ConsentRequiredError) Unwrap

func (e *ConsentRequiredError) Unwrap() error

type ConsentState

type ConsentState struct {
	// Consents maps each consent accepted to its version.
	Consents map[string]string `json:"consents"`
	// ToAccept are the required consents still to accept, at the version to show.
	ToAccept []ConsentRef `json:"to_accept"`
}

ConsentState is what the signed-in user holds.

type ConsentText

type ConsentText struct {
	Name    string `json:"name"`
	Version string `json:"version"`
	Locale  string `json:"locale"`
	// Text is Markdown.
	Text string `json:"text"`
	// Hash is the SHA-256 of the text, kept with each acceptance.
	Hash string `json:"hash"`
	// Current: the version in force.
	Current bool `json:"current"`
}

ConsentText is the text of a consent version in a language.

type Consents

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

Consents are the consents the realm asks for, and what the signed-in user holds: c.Consents().

func (*Consents) Accept

func (s *Consents) Accept(ctx context.Context, consents map[string]string, opts ...RequestOption) (*ConsentState, error)

Accept records the acceptance of consents (name to version) by the signed-in user.

func (*Consents) Current

func (s *Consents) Current(ctx context.Context, opts ...RequestOption) ([]ConsentInfo, error)

Current lists the consents the realm asks for, with the version in force. It needs no sign-in.

func (*Consents) State

func (s *Consents) State(ctx context.Context, opts ...RequestOption) (*ConsentHistory, error)

State returns what the signed-in user holds, with the history of acceptances and withdrawals.

func (*Consents) Text

func (s *Consents) Text(ctx context.Context, name, version, locale string, opts ...RequestOption) (*ConsentText, error)

Text returns the text of a consent version in a language (the realm's default when locale is empty).

func (*Consents) Withdraw

func (s *Consents) Withdraw(ctx context.Context, name string, opts ...RequestOption) (*ConsentState, error)

Withdraw records the withdrawal of a consent; a required one can't be withdrawn.

type CreateOrgInput

type CreateOrgInput struct {
	Name string `json:"name"`
	// Slug is the short name people know the organization by: lowercase letters, digits and hyphens.
	Slug string `json:"slug"`
}

CreateOrgInput is the input of Orgs.Create.

type DataExport

type DataExport struct {
	ID string `json:"id"`
	// Status is "queued", "running", "ready", "failed" or "expired". A ready export can be
	// downloaded until ExpiresAt; a failed one may be asked for again at once.
	Status     string `json:"status"`
	CreatedAt  string `json:"created_at"`
	FinishedAt string `json:"finished_at,omitempty"`
	// ExpiresAt is when the package is deleted (ready only).
	ExpiresAt string `json:"expires_at,omitempty"`
	// Size is the bytes of the zip (ready only).
	Size int64 `json:"size,omitempty"`
	// Counts is what the package holds (ready only): records per part, and "files".
	Counts map[string]int `json:"counts,omitempty"`
	// Step is what it is doing now (queued or running only).
	Step string `json:"step,omitempty"`
}

DataExport is a copy of a user's data, prepared in the background.

type Database

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

Database is a database of the realm: client.DB("main").Collection("posts").

func (*Database) Batch

func (d *Database) Batch(ctx context.Context, ops []BatchOperation, opts ...RequestOption) ([]Doc, error)

Batch runs operations on several collections of the database, all or none. The results come in the order of the operations: the written document for create, replace and patch, and just its id for delete.

func (*Database) Call

func (d *Database) Call(ctx context.Context, name string, input, out any, opts ...RequestOption) (*Job, error)

Call calls a function of the database with an input. A synchronous function answers with its output, which is decoded into out (when not nil) and the returned job is nil. An async function, or a call made with WithRespondAsync, answers with a job: it is returned, and out is untouched; Wait for the output. WithIdempotencyKey makes a repeat return the first answer.

func (*Database) Collection

func (d *Database) Collection(name string) *Collection

Collection returns a collection of the database.

func (*Database) Job

func (d *Database) Job(ctx context.Context, id string, opts ...RequestOption) (*Job, error)

Job returns the job with an id (saved from an earlier call), with its current data.

func (*Database) Name

func (d *Database) Name() string

Name returns the database's name.

func (*Database) Run

func (d *Database) Run(ctx context.Context, name string, input, out any, o WaitOptions, opts ...RequestOption) error

Run calls a function and, if it answers with a job, waits for it: the output ends in out either way. It is Call followed by Wait.

type Detail

type Detail struct {
	Path   string `json:"path"`
	Reason string `json:"reason"`
	// Code names the problem when it has a code of its own, such as field_encrypted.
	Code string `json:"code,omitempty"`
}

Detail points at one problem, such as a field that failed validation.

type Device

type Device struct {
	ID       string  `json:"id"`
	Platform string  `json:"platform"` // "android", "ios" or "web"
	Name     *string `json:"name"`
	// CreatedAt and LastSeen are RFC 3339.
	CreatedAt string `json:"created_at"`
	LastSeen  string `json:"last_seen"`
}

Device is a device registered to receive push notifications.

type DeviceInput

type DeviceInput struct {
	// Platform is "android", "ios" or "web".
	Platform string `json:"platform"`
	// Token is the push token the platform gave the device.
	Token string `json:"token"`
	Name  string `json:"name,omitempty"`
}

DeviceInput is what a device registers with.

type Doc

type Doc map[string]any

Doc is a document read without a type of its own.

func (Doc) ID

func (d Doc) ID() string

ID returns the document's id.

func (Doc) Meta

func (d Doc) Meta() Meta

Meta returns the document's _meta.

type Doer

type Doer interface {
	Do(*http.Request) (*http.Response, error)
}

Doer sends an HTTP request. *http.Client is one; tests and unusual deployments (a proxy, a signing layer) plug their own, the way backd-js takes a fetch.

type Error

type Error struct {
	// Status is the HTTP status; 0 when there was no answer.
	Status int
	// Code is the API's error code, such as "not_found" or "id_taken"; "network_error" or
	// "aborted" when there was no answer, and "http_<status>" when the answer was not the API's.
	Code    string
	Message string
	Details []Detail
	// RequestID is the id the server logged the request under, for support.
	RequestID string
	// RetryAfter is how long the server asked to wait, for retryable answers; 0 when it didn't say.
	RetryAfter time.Duration
	// Header holds the response headers of the failed call (nil when there was no answer).
	Header http.Header
	// Path is the path after /v1/{realm} of the call that failed, such as "_admin/jobs"; empty for
	// errors that were not the answer to a call.
	Path string
	// contains filtered or unexported fields
}

Error is what a failed call returns: the API's answer (or, for ErrNetwork, the lack of one).

Example

Failures are *client.Error values: test their class with errors.Is.

package main

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/fernandezvara/backd/pkg/client"
)

// demo is a small stand-in for a backd server, so the examples run.
func demo() *httptest.Server {
	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch {
		case r.URL.Path == "/v1/shelf/_auth/login":
			fmt.Fprint(w, `{"token":"bds_demo","session_id":"s1","expires_at":"2030-01-01T00:00:00Z","user":{"id":"u1","email":"ada@example.com"}}`)
		case r.URL.Path == "/v1/shelf/main/assets" && r.URL.Query().Get("after") == "":
			fmt.Fprint(w, `{"items":[{"id":"a1","title":"Docs","_meta":{"version":1}},{"id":"a2","title":"Notes","_meta":{"version":1}}],"has_more":true,"next_cursor":"c1"}`)
		case r.URL.Path == "/v1/shelf/main/assets":
			fmt.Fprint(w, `{"items":[{"id":"a3","title":"Links","_meta":{"version":1}}],"has_more":false}`)
		default:
			w.WriteHeader(http.StatusNotFound)
			fmt.Fprint(w, `{"error":{"code":"not_found","message":"no such document","request_id":"rq1"}}`)
		}
	}))
}

func main() {
	srv := demo()
	defer srv.Close()
	c, _ := client.New(client.Options{URL: srv.URL, Realm: "shelf"})
	defer c.Close()

	_, err := c.DB("main").Collection("assets").Get(context.Background(), "nope", client.ReadOptions{})
	var e *client.Error
	if errors.Is(err, client.ErrNotFound) && errors.As(err, &e) {
		fmt.Printf("%d %s: %s (request %s)\n", e.Status, e.Code, e.Message, e.RequestID)
	}
}
Output:
404 not_found: no such document (request rq1)

func (*Error) Error

func (e *Error) Error() string

func (*Error) Is

func (e *Error) Is(target error) bool

Is reports whether target is a sentinel of e's class.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying cause of a network error, such as context.Canceled.

type ExpandPart

type ExpandPart struct {
	Name   string
	Fields []string
}

ExpandPart is one reference of an expand, with the fields to return of it.

func Ref

func Ref(name string, fields ...string) ExpandPart

Ref names a reference to expand (or "name.nested" for a second level) and, optionally, the fields to return of it: Ref("author", "name", "avatar").

type ExportWaitOptions

type ExportWaitOptions struct {
	// PollInterval is the time between polls; 2s when zero.
	PollInterval time.Duration
	// Timeout gives up; 30 minutes when zero.
	Timeout    time.Duration
	OnProgress func(*DataExport)
}

ExportWaitOptions are the options of WaitForExport.

type FileConfigStorage

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

FileConfigStorage keeps each key in a file of a directory.

func NewFileConfigStorage

func NewFileConfigStorage(dir string) *FileConfigStorage

NewFileConfigStorage returns a storage that keeps its keys in dir.

func (*FileConfigStorage) Clear

func (f *FileConfigStorage) Clear(prefix string) error

func (*FileConfigStorage) Load

func (f *FileConfigStorage) Load(key string) (string, error)

func (*FileConfigStorage) Save

func (f *FileConfigStorage) Save(key, value string) error

type FileContent

type FileContent struct {
	// File is set when Get looked the file up (no file id given).
	File   *FileDetails
	Header http.Header
	Body   io.ReadCloser
}

FileContent is a file read: its bytes are Body, which the caller closes.

func (*FileContent) Bytes

func (c *FileContent) Bytes() ([]byte, error)

Bytes reads and closes the body.

func (*FileContent) Text

func (c *FileContent) Text() (string, error)

Text reads and closes the body as text.

type FileDetails

type FileDetails struct {
	ID         string `json:"id"` // fl_…
	Name       string `json:"name"`
	Size       int64  `json:"size"`
	Type       string `json:"type"` // detected from the content
	SHA256     string `json:"sha256"`
	UploadedAt string `json:"uploaded_at"`
	// Width and Height are the pixels of an image, as a viewer sees it.
	Width  int `json:"width,omitempty"`
	Height int `json:"height,omitempty"`
	// Versions is the state of each version the field declares (versions: in collection.yaml).
	Versions map[string]VersionState `json:"versions,omitempty"`
	// Public is true for a file of a public field (public: true): it is read at URL, with no signed link.
	Public bool `json:"public,omitempty"`
	// KeyName is a public file's name as its address ends with it.
	KeyName string `json:"key_name,omitempty"`
	// URL is a public file's permanent address, or the signed link of a read with FileLinks.
	URL string `json:"url,omitempty"`
	// ExpiresAt is when a signed URL stops working (never set on a public file's address).
	ExpiresAt string `json:"expires_at,omitempty"`
}

FileDetails describes a stored file, as the field of a document holds it.

type FileField

type FileField struct {
	Name string `json:"name"`
	// Upload is "proxy" (the bytes go through backd) or "direct" (to the storage with a signed request).
	Upload string `json:"upload"`
	// Download is "presigned" or "proxy".
	Download string `json:"download"`
	Multiple bool   `json:"multiple"`
	MaxFiles int    `json:"max_files"`
	MaxSize  int64  `json:"max_size"` // bytes per file
	// Types are the allowed content types; empty allows any.
	Types []string `json:"types"`
	// MultipartAbove: files above this many bytes are sent in parts (direct fields that can hold more).
	MultipartAbove int64 `json:"multipart_above,omitempty"`
}

FileField is how a collection declares one of its file fields.

type FileLink struct {
	URL string `json:"url"`
	// ExpiresAt is RFC 3339; nil for the address of a public file, which never expires.
	ExpiresAt *string `json:"expires_at"`
}

FileLink is a link to read a file.

type FileSource

type FileSource struct {
	R    io.ReaderAt
	Size int64
	// Name and Type default to the file's own: the base name of a path, a type from its extension.
	Name, Type string
	// contains filtered or unexported fields
}

FileSource is the data of a file to upload: something that can be read at any offset (it is hashed before it is sent, and sent in parts when it is large) and its size.

func FileFromBytes

func FileFromBytes(b []byte, name, contentType string) *FileSource

FileFromBytes is the source of data held in memory.

func FileFromReaderAt

func FileFromReaderAt(r io.ReaderAt, size int64, name, contentType string) *FileSource

FileFromReaderAt is the source of anything that reads at an offset, such as an *os.File.

func OpenFile

func OpenFile(path string) (*FileSource, error)

OpenFile opens a file on disk as a source; close it when the upload is done.

func (*FileSource) Close

func (s *FileSource) Close() error

Close releases the file of a source made by OpenFile.

type FileStorage

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

FileStorage keeps the token in a file (mode 0600), so a script or a tool stays signed in between runs. Slots are files next to it, named <path>.<organization>.

func NewFileStorage

func NewFileStorage(path string) *FileStorage

NewFileStorage returns a storage that keeps the token in path.

func (*FileStorage) Get

func (f *FileStorage) Get(context.Context) (string, error)

func (*FileStorage) Remove

func (f *FileStorage) Remove(context.Context) error

func (*FileStorage) Set

func (f *FileStorage) Set(_ context.Context, token string) error

func (*FileStorage) Slot

func (f *FileStorage) Slot(name string) TokenStorage

func (*FileStorage) Slots

func (f *FileStorage) Slots(context.Context) ([]string, error)

type FileURLOptions

type FileURLOptions struct {
	Version string
	// File, when you hold the file's details (from a read of the document), lets a public file's
	// address be made without a request.
	File *FileDetails
}

FileURLOptions are the options of FileURL.

type FileVersion

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

FileVersion acts on one version of a file.

func (*FileVersion) Delete

func (v *FileVersion) Delete(ctx context.Context, opts ...RequestOption) (*VersionState, error)

Delete drops the copy: the version is pending again (a worker makes it) or empty (only functions make it).

func (*FileVersion) Generate

func (v *FileVersion) Generate(ctx context.Context, p VersionParams, opts ...RequestOption) (*VersionState, error)

Generate makes the version with other parameters; only a writable version allows it.

func (*FileVersion) Regenerate

func (v *FileVersion) Regenerate(ctx context.Context, opts ...RequestOption) (*VersionState, error)

Regenerate makes the version again with the parameters collection.yaml declares.

type Files

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

Files are the files of one field of one document: coll.Files(id, "photos").

func (*Files) Delete

func (f *Files) Delete(ctx context.Context, fileID string, ifMatch any, opts ...RequestOption) (Doc, error)

Delete removes a file from the field and returns the document. With no fileID it clears the field.

func (*Files) Get

func (f *Files) Get(ctx context.Context, fileID string, o GetFileOptions, opts ...RequestOption) (*FileContent, error)

Get reads a file. With no fileID it is the only file the field holds.

func (f *Files) Link(ctx context.Context, fileID string, o GetFileOptions, opts ...RequestOption) (*FileLink, error)

Link returns a link to read a file (signed, or the permanent address of a public file).

func (*Files) List

func (f *Files) List(ctx context.Context, opts ...RequestOption) ([]FileDetails, error)

List returns the files the field holds.

func (*Files) Put

func (f *Files) Put(ctx context.Context, data io.Reader, o PutOptions, opts ...RequestOption) (Doc, error)

Put sends a file through backd (a field with proxy uploads) and attaches it to the document. It returns the document. Use UploadFile to let the client choose the way the field takes files.

func (*Files) Version

func (f *Files) Version(name, fileID string) *FileVersion

Version addresses the version name of a file (the only one of the field with no fileID).

type FillBucketsOptions

type FillBucketsOptions struct {
	// Field is the grouped date field, and Unit its bucket: the groups must be grouped by
	// "<Field>:<Unit>" and nothing else.
	Field string
	Unit  BucketUnit
	// From and To are bucket keys in the zone of the aggregation ("2026-01"), or time.Time values,
	// which name the bucket they fall in as seen in UTC; both are included.
	From, To any
	// Empty holds the values of an empty bucket's metrics (for sums, {"sum_total": "0"}); count is 0.
	Empty map[string]any
}

FillBucketsOptions say which buckets to fill.

type Functions

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

Functions calls functions by their full name: c.Functions().Call(ctx, "main/refund", input, &out).

func (*Functions) Call

func (f *Functions) Call(ctx context.Context, name string, input, out any, opts ...RequestOption) (*Job, error)

Call is Database.Call for "<database>/<name>".

func (*Functions) Run

func (f *Functions) Run(ctx context.Context, name string, input, out any, o WaitOptions, opts ...RequestOption) error

Run is Database.Run for "<database>/<name>".

type GetFileOptions

type GetFileOptions struct {
	// Version reads a version (a resized copy) of the file.
	Version string
}

GetFileOptions are the options of Files.Get and Files.Link.

type IDTokenInput

type IDTokenInput struct {
	IDToken           string
	Nonce             string
	AuthorizationCode string
	Invitation        string
	Locale            string
	Org               string
	Consents          map[string]string
}

IDTokenInput is the input of SignInWithIDToken and LinkProviderWithIDToken: the identity token a native sign-in (Sign in with Apple, Google) gave the program.

type Identity

type Identity struct {
	Provider      string  `json:"provider"`
	Email         string  `json:"email"`
	EmailVerified bool    `json:"email_verified"`
	CreatedAt     string  `json:"created_at"`
	LastUsedAt    *string `json:"last_used_at"`
}

Identity is one way the user signs in: a password or an external provider.

type InvitationPreview

type InvitationPreview struct {
	Org struct {
		ID   string `json:"id"`
		Name string `json:"name"`
	} `json:"org"`
	Roles []string `json:"roles"`
	Teams []struct {
		ID   string `json:"id"`
		Name string `json:"name"`
	} `json:"teams"`
	Binding   string `json:"binding"`
	ExpiresAt string `json:"expires_at"`
}

InvitationPreview is what an invitation to an organization offers.

type InviteInput

type InviteInput struct {
	Binding string   `json:"binding"`
	User    string   `json:"user,omitempty"`  // for "user"
	Email   string   `json:"email,omitempty"` // for "email"
	Roles   []string `json:"roles,omitempty"`
	Teams   []string `json:"teams,omitempty"` // team ids
	// Send also emails it (only "email").
	Send bool `json:"send,omitempty"`
	// ExpiresIn is a duration such as "2d" (default 7d, at most 30d).
	ExpiresIn string `json:"expires_in,omitempty"`
	// MaxUses is for "none"; 1 by default.
	MaxUses int `json:"max_uses,omitempty"`
}

InviteInput is the input of Create.

type Job

type Job struct {

	// ID and Function are fixed; Data is as of the last Status or Wait poll.
	ID       string
	Function string
	Data     JobData
	// contains filtered or unexported fields
}

Job is a handle to an async function's job: a call that the function answers with 202 returns one. Poll with Status, or Wait for the output the way a synchronous call returns it.

func (*Job) Status

func (j *Job) Status(ctx context.Context, opts ...RequestOption) (string, error)

Status polls the job's current status ("queued", "running" or "done").

func (*Job) Steps

func (j *Job) Steps() []JobStep

Steps returns the steps reported as of the last poll (the last is the current step).

func (*Job) Wait

func (j *Job) Wait(ctx context.Context, o WaitOptions, opts ...RequestOption) (json.RawMessage, error)

Wait polls until the job is done, then returns its output, the value a synchronous call would have returned, or an *Error matching what a synchronous call would have returned for the same outcome (with the function's own code, when it raised one).

func (*Job) WaitInto

func (j *Job) WaitInto(ctx context.Context, out any, o WaitOptions, opts ...RequestOption) error

WaitInto is Wait that decodes the output into out.

type JobData

type JobData struct {
	ID string `json:"id"`
	// Function is "<database>/<name>".
	Function string `json:"function"`
	// Status is "queued", "running" or "done".
	Status    string `json:"status"`
	CreatedAt string `json:"created_at"`
	// Attempts is how many times a worker has started it.
	Attempts int `json:"attempts,omitempty"`
	// NextAttemptAt is when a failed attempt will be retried (the function's retry policy); nil otherwise.
	NextAttemptAt *string    `json:"next_attempt_at,omitempty"`
	Result        *JobResult `json:"result"`
	// Steps are what the running (or last) attempt reported; at most 100.
	Steps []JobStep `json:"steps,omitempty"`
	// StepsOmitted is how many were left out of the middle when there were more than 100.
	StepsOmitted int `json:"steps_omitted,omitempty"`
}

JobData is a job as the API returns it.

type JobResult

type JobResult struct {
	// Status is "ok", "function_error", "timeout", "memory", "cpu", "crash", "output_too_large" or "bundle".
	Status string `json:"status"`
	// Output is the function's output, when Status is "ok".
	Output json.RawMessage `json:"output,omitempty"`
	// HTTPStatus is the status a synchronous call would have answered with; 0 when Status is "ok".
	HTTPStatus int `json:"http_status,omitempty"`
	// Code is the function's own code (function_error) or one of backd's own.
	Code       string   `json:"code,omitempty"`
	Message    string   `json:"message,omitempty"`
	Details    []Detail `json:"details,omitempty"`
	DurationMs int64    `json:"duration_ms"`
}

JobResult is how an async job ended, once its status is "done": the same shape a synchronous call's own answer would carry for the same outcome.

type JobStep

type JobStep struct {
	// N is 1 for the first step of the attempt (it counts steps left out too).
	N    int    `json:"n"`
	Name string `json:"name"`
	// Status is "running", "done", "failed", "timed_out" or "cancelled".
	Status     string  `json:"status"`
	StartedAt  string  `json:"started_at"`
	EndedAt    *string `json:"ended_at"`
	DurationMs *int64  `json:"duration_ms"`
	// Current is how far the step got; Total how much there is to do, when the function said.
	Current   int     `json:"current"`
	Total     *int    `json:"total"`
	Message   *string `json:"message"`
	UpdatedAt string  `json:"updated_at"`
}

JobStep is one step the function reported with ctx.step(), and how far it got with ctx.progress().

type JobTimeoutError

type JobTimeoutError struct{ JobID string }

JobTimeoutError means Wait gave up before the job finished. The job itself is unaffected and still running: wait again, or poll with Status.

func (*JobTimeoutError) Error

func (e *JobTimeoutError) Error() string

type LiveState

type LiveState struct {
	Status LiveStatus
	// Items are the first subscription's documents (the usual case: one).
	Items []Doc
	// Subscriptions are all of them, by id.
	Subscriptions map[string]LiveSubscriptionState
	// References are the referenced documents: by reference name, then by id.
	References map[string]map[string]Doc
}

LiveState is what a view holds.

type LiveStatus

type LiveStatus string

LiveStatus says where a live view stands.

const (
	// StatusConnecting: nothing has been loaded yet.
	StatusConnecting LiveStatus = "connecting"
	// StatusLive: loaded and the stream is open.
	StatusLive LiveStatus = "live"
	// StatusResyncing: the stream dropped or was reset; the items shown are the last known.
	StatusResyncing LiveStatus = "resyncing"
	// StatusClosed: closed by Close, or by an error (see [LiveView.Err]).
	StatusClosed LiveStatus = "closed"
)

type LiveSubscriptionState

type LiveSubscriptionState struct {
	Items  []Doc
	Status LiveStatus
}

LiveSubscriptionState is one subscription of a view.

type LiveView

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

LiveView is the documents of one or more subscriptions, kept current. Read it with LiveView.State or LiveView.Items; react to changes with OnChange or the Updates channel. It is safe for concurrent use; callbacks run one at a time, in order, on a goroutine of their own, never while the view is locked, so they can read the view.

func (*LiveView) Close

func (v *LiveView) Close()

Close stops following. It is safe to call twice.

func (*LiveView) Err

func (v *LiveView) Err() error

Err returns the error that closed the view, if any.

func (*LiveView) Items

func (v *LiveView) Items() []Doc

Items returns the first subscription's documents.

func (*LiveView) OnAccessLost

func (v *LiveView) OnAccessLost(f func(string)) (off func())

OnAccessLost registers f to be called, with the subscription's name, when the caller can no longer read what the subscription follows: its items are emptied.

func (*LiveView) OnChange

func (v *LiveView) OnChange(f func(LiveState)) (off func())

OnChange registers f to be called with the new state after the items, the status or the references change (several changes at once are one call). It returns the function that removes it.

func (*LiveView) OnError

func (v *LiveView) OnError(f func(error)) (off func())

OnError registers f to be called when the view fails for good (it is then closed).

func (*LiveView) OnReset

func (v *LiveView) OnReset(f func(ResetInfo)) (off func())

OnReset registers f to be called when the server asks a subscription to reload.

func (*LiveView) OnStatus

func (v *LiveView) OnStatus(f func(LiveStatus)) (off func())

OnStatus registers f to be called when the status changes.

func (*LiveView) Ready

func (v *LiveView) Ready(ctx context.Context) (LiveState, error)

Ready waits until the view is live and returns its state, or returns the error that closed it.

func (*LiveView) State

func (v *LiveView) State() LiveState

State returns what the view holds now.

func (*LiveView) Status

func (v *LiveView) Status() LiveStatus

Status returns where the view stands.

func (*LiveView) Updates

func (v *LiveView) Updates() <-chan LiveState

Updates returns a channel that receives the state after each change. It keeps only the latest state a slow reader hasn't taken, and is closed when the view is closed.

type LoadSpec

type LoadSpec struct {
	// Sort is the order, as an order_by ("-_meta.created_at"); by id when empty.
	Sort []string
	// Limit is the most documents kept (100 by default); the list keeps the first Limit in Sort order.
	Limit int
}

LoadSpec says how the initial list is read and how the live list is kept.

type MFA

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

MFA is the second factor (an authenticator app) of the signed-in user: c.Auth().MFA.

func (*MFA) Confirm

func (m *MFA) Confirm(ctx context.Context, in MFAConfirmInput, opts ...RequestOption) (*MFAConfirmResult, error)

Confirm checks the first code of the authenticator app and turns the second factor on.

func (*MFA) Disable

func (m *MFA) Disable(ctx context.Context, opts ...RequestOption) error

Disable turns the second factor off. It needs a recent proof (Reauth).

func (*MFA) RegenerateRecoveryCodes

func (m *MFA) RegenerateRecoveryCodes(ctx context.Context, opts ...RequestOption) ([]string, error)

RegenerateRecoveryCodes makes a new set of recovery codes, replacing the old. It needs a recent proof (Reauth).

func (*MFA) Setup

func (m *MFA) Setup(ctx context.Context, challenge string, opts ...RequestOption) (*MFASetup, error)

Setup starts setting up the authenticator app. A user who must set one up before they can sign in (StepEnrollment) passes the challenge; a signed-in user needs a recent proof (Reauth).

func (*MFA) Status

func (m *MFA) Status(ctx context.Context, opts ...RequestOption) (*MFAStatus, error)

Status says whether the second factor is available and enabled for the user.

type MFAConfirmInput

type MFAConfirmInput struct {
	SetupID, Code string
	// Challenge is the one of StepEnrollment; empty for a signed-in user.
	Challenge string
}

MFAConfirmInput is the input of MFA.Confirm.

type MFAConfirmResult

type MFAConfirmResult struct {
	// RecoveryCodes are shown once: the user keeps them for when they lose the app.
	RecoveryCodes []string
	// Session is set when the confirmation finished a sign-in.
	Session *Session
	// Consent is set when the sign-in still has consents to accept.
	Consent *Step
}

MFAConfirmResult is the answer to confirming the setup.

type MFASetup

type MFASetup struct {
	SetupID    string `json:"setup_id"`
	Secret     string `json:"secret"`
	OtpauthURI string `json:"otpauth_uri"`
	QR         string `json:"qr"`
	ExpiresAt  string `json:"expires_at"`
}

MFASetup is what an authenticator app needs to be set up: show the QR code or the secret.

type MFAStatus

type MFAStatus struct {
	Available         bool     `json:"available"`
	Enabled           bool     `json:"enabled"`
	Methods           []string `json:"methods"`
	RecoveryCodesLeft int      `json:"recovery_codes_left"`
	Required          bool     `json:"required"`
}

MFAStatus says where the user stands with the second factor.

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

MagicLink signs in with a link sent by email: c.Auth().MagicLink.

func (*MagicLink) Request

func (m *MagicLink) Request(ctx context.Context, email string, o MagicLinkOptions, opts ...RequestOption) (string, error)

Request emails the person a sign-in link and a code. The PKCE verifier is kept in the OAuth storage: finish with CompleteSignIn on the address the link opens, or VerifyCode with the code. It returns the request id.

func (*MagicLink) VerifyCode

func (m *MagicLink) VerifyCode(ctx context.Context, code string, opts ...RequestOption) (*Step, error)

VerifyCode finishes a magic-link sign-in with the code from the email, in the client that asked for the link.

type MagicLinkOptions

type MagicLinkOptions struct {
	// RedirectTo is where the link sends the person back to (within the realm's sign_in.allowed_redirects).
	RedirectTo string
	Locale     string
	Org        string
	Consents   map[string]string
}

MagicLinkOptions are the options of MagicLink.Request.

type Me

type Me struct {
	User
	Identities    []Identity `json:"identities"`
	ReauthMethods []string   `json:"reauth_methods"`
	SignInMethods []string   `json:"sign_in_methods"`
	// Consents maps each consent the user holds to its version (with consents declared in the realm).
	Consents map[string]string `json:"consents,omitempty"`
	// ToAccept are the required consents still to accept.
	ToAccept []ConsentRef `json:"to_accept,omitempty"`
	Org      *MeOrg       `json:"org,omitempty"`
}

Me is the signed-in user with their sign-in methods.

type MeOrg

type MeOrg struct {
	ID    string   `json:"id"`
	Name  string   `json:"name,omitempty"`
	Slug  *string  `json:"slug,omitempty"`
	Roles []string `json:"roles,omitempty"`
	Teams []string `json:"teams,omitempty"`
}

MeOrg is the organization a scoped session belongs to.

type MemberListParams

type MemberListParams struct {
	PageParams
	// WithoutSSO lists only the members with no identity on the organization's connection.
	WithoutSSO bool
}

MemberListParams page the members of an organization.

type MemoryOAuthStorage

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

MemoryOAuthStorage keeps the pending sign-in in memory. It is the default.

func (*MemoryOAuthStorage) Get

func (*MemoryOAuthStorage) Remove

func (*MemoryOAuthStorage) Set

type MemoryStorage

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

MemoryStorage keeps the token in memory. It is the default and is safe for concurrent use.

func NewMemoryStorage

func NewMemoryStorage() *MemoryStorage

NewMemoryStorage returns an empty in-memory storage.

func (*MemoryStorage) Get

func (*MemoryStorage) Remove

func (m *MemoryStorage) Remove(context.Context) error

func (*MemoryStorage) Set

func (m *MemoryStorage) Set(_ context.Context, token string) error

func (*MemoryStorage) Slot

func (m *MemoryStorage) Slot(name string) TokenStorage

func (*MemoryStorage) Slots

func (m *MemoryStorage) Slots(context.Context) ([]string, error)

type Meta

type Meta struct {
	CreatedAt string `json:"created_at"`
	UpdatedAt string `json:"updated_at"`
	// Version increases on every write; use it with [WithIfMatch].
	Version int64 `json:"version,omitempty"`
	// Owner is the id of the user who created it (realms with auth enabled).
	Owner     string `json:"owner,omitempty"`
	CreatedBy string `json:"created_by,omitempty"`
	UpdatedBy string `json:"updated_by,omitempty"`
	// Org is the organization the document belongs to (collections with organization).
	Org string `json:"org,omitempty"`
	// Team is the team of the organization the document belongs to (collections with team).
	Team string `json:"team,omitempty"`
	// Score is the relevance to a $search, in a list sorted by "_relevance".
	Score     *float64 `json:"score,omitempty"`
	DeletedAt string   `json:"deleted_at,omitempty"`
	DeletedBy string   `json:"deleted_by,omitempty"`
	// PurgeAt is when a soft-deleted document is removed for good.
	PurgeAt string `json:"purge_at,omitempty"`
	// Redacted lists the encrypted fields the caller may not see: they come back null, and a
	// null here is hidden, not empty.
	Redacted []string `json:"redacted,omitempty"`
}

Meta is what backd keeps next to every document, in its _meta.

type NewOrgInvitation

type NewOrgInvitation struct {
	OrgInvitation
	Token string  `json:"token"`
	Link  *string `json:"link"`
}

NewOrgInvitation is an invitation with its token and link, shown only when it is made or renewed.

type OAuthOptions

type OAuthOptions struct {
	// RedirectTo is where backd sends the browser back to (it must be within the realm's
	// sign_in.allowed_redirects); outside a browser the realm's sign_in.app_url when empty.
	RedirectTo string
	// Invitation is an invitation token, for realms with signup: invite.
	Invitation string
	Locale     string
	// Consents accepted for the account the sign-in may make (name to version).
	Consents map[string]string
	// Org signs in through the connection of this organization instead of the realm's own providers.
	Org string
}

OAuthOptions are the options of a redirect sign-in or link.

type OAuthReturn

type OAuthReturn struct {
	Code     string // the one-time code to exchange for a session
	Error    string // why the sign-in failed
	Linked   string // the provider that was linked, for a link made from a signed-in session
	Provider string
	Org      string
}

OAuthReturn is what backd put on the address it sent the person back to.

func ParseOAuthReturn

func ParseOAuthReturn(address string) *OAuthReturn

ParseOAuthReturn reads the backd_* parameters of the address a sign-in with a provider (or a magic link) returns to. It returns nil when the address carries none.

type OAuthStorage

type OAuthStorage interface {
	Get(ctx context.Context) (string, error)
	Set(ctx context.Context, value string) error
	Remove(ctx context.Context) error
}

OAuthStorage keeps what a redirect sign-in needs between its start and its end: the PKCE verifier and where the sign-in began. A program that starts a sign-in and finishes it in another process (a CLI that opens a browser and waits on a local address) keeps it in memory; one that is restarted in between keeps it somewhere durable.

type Options

type Options struct {
	// URL is the base URL of backd, such as "https://api.example.com".
	URL string
	// Realm is the realm to talk to.
	Realm string
	// APIKey is a server-side credential (bdk_…) with full access to the realm. Keep it out of anything
	// a user's device can read.
	APIKey string
	// Org binds the client to an organization, by id or by the slug people know ("acme"): sign-in
	// calls go to /_auth/orgs/{org}/…, so the session is scoped to it. See [Client.Org].
	Org string
	// Storage keeps the session token; memory by default.
	Storage TokenStorage
	// OAuthStorage keeps the pending redirect sign-in (its PKCE verifier) between its start and its end; memory by default.
	OAuthStorage OAuthStorage
	// Cache tunes the revalidation cache of document and list reads; on by default.
	Cache CacheOptions
	// ConfigStorage keeps the app configuration between runs ([Client.Config]); memory only by default.
	ConfigStorage ConfigStorage
	// Retry configures the retries for 429 and 503; off by default.
	Retry Retry
	// Headers are sent with every call.
	Headers map[string]string
	// Doer sends the requests; an *http.Client by default.
	Doer Doer
	// Types is the fingerprint of the generated types the program was written against (the
	// fingerprint field of realm.json, made by `backd types`). It is sent as X-Backd-Types; when
	// the server's config has moved on it answers X-Backd-Types-Stale and OnStaleTypes is called, once.
	// Leave it out in production: nothing is sent then.
	Types string
	// MapError, when set, is given every error [Client.Do] and the calls built on it return, and
	// returns what the caller sees: to add a hint, to turn it into the error type of a larger program.
	// What it returns should still wrap the original ([errors.Is] and [errors.As] keep working).
	MapError func(error) error
	// OnStaleTypes is called once when the server says the types are stale; a warning is logged by default.
	OnStaleTypes func()
}

Options configure a Client. URL and Realm are required.

type OrgConnection

type OrgConnection struct {
	Provider string `json:"provider"` // "google" or "microsoft"
	ClientID string `json:"client_id"`
	// Tenant is the Microsoft tenant id; HostedDomain the Google Workspace domain.
	Tenant       string `json:"tenant,omitempty"`
	HostedDomain string `json:"hosted_domain,omitempty"`
	// EmailDomains: when set, the verified address must also be in one of them.
	EmailDomains []string `json:"email_domains"`
	// NativeClientIDs are extra client ids the id-token sign-in accepts (mobile apps).
	NativeClientIDs []string `json:"native_client_ids"`
	// JoinRoles are the organization roles given to people who join through it.
	JoinRoles []string `json:"join_roles"`
	Enabled   bool     `json:"enabled"`
	// ClientSecretSet: without a secret the connection is unavailable.
	ClientSecretSet bool `json:"client_secret_set"`
	// RedirectURI is the address to register with the provider (when backd knows its public address).
	RedirectURI  string `json:"redirect_uri,omitempty"`
	RedirectPath string `json:"redirect_path"`
	CreatedAt    string `json:"created_at"`
	UpdatedAt    string `json:"updated_at"`
}

OrgConnection is an organization's sign-in provider.

type OrgConnections

type OrgConnections struct {
	Items []OrgConnection `json:"items"`
	// Providers are the providers the realm lets organizations connect.
	Providers      []string `json:"providers,omitempty"`
	MaxConnections int      `json:"max_connections,omitempty"`
}

OrgConnections are the connections of an organization.

type OrgInvitation

type OrgInvitation struct {
	ID string `json:"id"`
	// Binding says who may accept: "user" (one user), "email" (whoever holds a verified address) or
	// "none" (anyone signed in with the link).
	Binding string `json:"binding"`
	// Status is "pending", "used", "revoked" or "expired".
	Status    string   `json:"status"`
	User      string   `json:"user,omitempty"`
	Email     string   `json:"email,omitempty"`
	Roles     []string `json:"roles"`
	Teams     []string `json:"teams"`
	MaxUses   int      `json:"max_uses"`
	Uses      int      `json:"uses"`
	CreatedAt string   `json:"created_at"`
	ExpiresAt string   `json:"expires_at"`
}

OrgInvitation is an invitation to join an organization.

type OrgInvitations

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

OrgInvitations are the invitations of an organization.

func (*OrgInvitations) Create

Create makes an invitation.

func (*OrgInvitations) List

func (i *OrgInvitations) List(ctx context.Context, opts ...RequestOption) ([]OrgInvitation, error)

List returns the invitations.

func (i *OrgInvitations) NewLink(ctx context.Context, id string, opts ...RequestOption) (*NewOrgInvitation, error)

NewLink renews an invitation's token and link.

func (*OrgInvitations) Revoke

func (i *OrgInvitations) Revoke(ctx context.Context, id string, opts ...RequestOption) error

Revoke cancels an invitation.

func (*OrgInvitations) Send

func (i *OrgInvitations) Send(ctx context.Context, id string, opts ...RequestOption) error

Send emails an invitation to its address.

type OrgMember

type OrgMember struct {
	User string `json:"user"`
	// Email is present according to the realm's members_visible_to.
	Email string `json:"email,omitempty"`
	// Roles are the direct roles.
	Roles          []string        `json:"roles"`
	Teams          []string        `json:"teams"`
	TeamRoles      []TeamRoleGrant `json:"team_roles"`
	EffectiveRoles []RoleOrigin    `json:"effective_roles"`
	// Overlap lists roles held directly and also through a team or by default.
	Overlap []string `json:"overlap"`
	// MFA and MFARoles are only for members who manage the organization.
	MFA       *bool    `json:"mfa,omitempty"`
	MFARoles  []string `json:"mfa_roles,omitempty"`
	JoinedAt  string   `json:"joined_at"`
	InvitedBy string   `json:"invited_by,omitempty"`
}

OrgMember is a member of an organization.

type OrgMemberPage

type OrgMemberPage struct {
	Items   []OrgMember `json:"items"`
	HasMore bool        `json:"has_more"`
	// Next is the After of the next page.
	Next string `json:"next,omitempty"`
}

OrgMemberPage is a page of members.

type OrgMembers

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

OrgMembers are the members of an organization.

func (*OrgMembers) List

List returns a page of members.

func (*OrgMembers) Remove

func (m *OrgMembers) Remove(ctx context.Context, user string, opts ...RequestOption) error

Remove removes a member from the organization.

func (*OrgMembers) Update

func (m *OrgMembers) Update(ctx context.Context, user string, roles []string, opts ...RequestOption) (*OrgMember, error)

Update sets a member's direct roles.

type OrgPatch

type OrgPatch struct {
	Name        *string `json:"name,omitempty"`
	Slug        *string `json:"slug,omitempty"`
	RequireMFA  *bool   `json:"require_mfa,omitempty"`
	SSORequired *bool   `json:"sso_required,omitempty"`
	// SessionMaxAge is in seconds (at least 3600); 0 goes back to the realm's limit.
	SessionMaxAge *int `json:"session_max_age,omitempty"`
}

OrgPatch changes an organization; nil fields stay as they are. Turning on RequireMFA or SSORequired, or changing SessionMaxAge, needs a recent proof (Auth.Reauth).

type OrgSSO

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

OrgSSO are the sign-in connections of an organization (its own Google Workspace or Microsoft tenant).

func (*OrgSSO) Delete

func (s *OrgSSO) Delete(ctx context.Context, provider string, opts ...RequestOption) error

Delete removes a connection; it needs a recent proof.

func (*OrgSSO) Get

func (s *OrgSSO) Get(ctx context.Context, provider string, opts ...RequestOption) (*OrgConnection, error)

Get returns one connection.

func (*OrgSSO) List

func (s *OrgSSO) List(ctx context.Context, opts ...RequestOption) (*OrgConnections, error)

List returns the organization's connections.

func (*OrgSSO) Set

func (s *OrgSSO) Set(ctx context.Context, provider string, in ConnectionInput, opts ...RequestOption) (*OrgConnection, error)

Set creates or replaces a connection; it needs a recent proof.

type OrgSession

type OrgSession struct {
	*Session
	Organization json.RawMessage
}

OrgSession is the session of Auth.SignUpWithOrg with the organization that was made.

type OrgTeam

type OrgTeam struct {
	ID        string   `json:"id"`
	Name      string   `json:"name"`
	Roles     []string `json:"roles"` // organization roles every member of the team holds
	CreatedAt string   `json:"created_at"`
}

OrgTeam is a team of an organization.

type OrgTeamMember

type OrgTeamMember struct {
	OrgMember
	// InTeam: whether they belong to the team (a role holder needs not).
	InTeam      bool     `json:"in_team"`
	RolesInTeam []string `json:"roles_in_team"`
}

OrgTeamMember is a member seen from one team.

type OrgTeamMemberPage

type OrgTeamMemberPage struct {
	Items   []OrgTeamMember `json:"items"`
	HasMore bool            `json:"has_more"`
	Next    string          `json:"next,omitempty"`
}

OrgTeamMemberPage is a page of the members of a team.

type OrgTeams

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

OrgTeams are the teams of an organization.

func (*OrgTeams) AddMember

func (t *OrgTeams) AddMember(ctx context.Context, team, user string, opts ...RequestOption) (*OrgMember, error)

AddMember puts a member of the organization in a team.

func (*OrgTeams) Create

func (t *OrgTeams) Create(ctx context.Context, in TeamInput, opts ...RequestOption) (*OrgTeam, error)

Create makes a team.

func (*OrgTeams) Delete

func (t *OrgTeams) Delete(ctx context.Context, team string, opts ...RequestOption) error

Delete deletes a team.

func (*OrgTeams) GrantRole

func (t *OrgTeams) GrantRole(ctx context.Context, team string, in TeamRoleInput, opts ...RequestOption) (*OrgTeamMember, error)

GrantRole gives a member a team role, for a window of time if From and Until say so.

func (*OrgTeams) List

func (t *OrgTeams) List(ctx context.Context, opts ...RequestOption) ([]OrgTeam, error)

List returns the teams.

func (*OrgTeams) Members

func (t *OrgTeams) Members(ctx context.Context, team string, p TeamMembersParams, opts ...RequestOption) (*OrgTeamMemberPage, error)

Members returns a page of the members of a team, or of the holders of one of its roles.

func (*OrgTeams) RemoveMember

func (t *OrgTeams) RemoveMember(ctx context.Context, team, user string, opts ...RequestOption) (*OrgMember, error)

RemoveMember takes a member out of a team.

func (*OrgTeams) RevokeRole

func (t *OrgTeams) RevokeRole(ctx context.Context, team string, in TeamRoleInput, opts ...RequestOption) (*OrgTeamMember, error)

RevokeRole takes a team role away from a member.

func (*OrgTeams) SetRoleWindow

func (t *OrgTeams) SetRoleWindow(ctx context.Context, team string, in TeamRoleInput, opts ...RequestOption) (*OrgTeamMember, error)

SetRoleWindow changes the window of a granted team role.

func (*OrgTeams) Update

func (t *OrgTeams) Update(ctx context.Context, team string, patch TeamPatch, opts ...RequestOption) (*OrgTeam, error)

Update changes a team.

type OrgTemplate

type OrgTemplate struct {
	Kind      string `json:"kind"`
	Locale    string `json:"locale"`
	Version   int    `json:"version"`
	UpdatedAt string `json:"updated_at"`
	UpdatedBy string `json:"updated_by,omitempty"`
	// Subject, Text and HTML are only set when one template is read.
	Subject  string `json:"subject,omitempty"`
	Text     string `json:"text,omitempty"`
	HTML     string `json:"html,omitempty"`
	Versions []struct {
		TemplateText
		Version int    `json:"version"`
		At      string `json:"at"`
		By      string `json:"by,omitempty"`
	} `json:"versions"`
	// Removed is only in the answer to a save: what the HTML sanitizer drops from the sample.
	Removed []string `json:"removed,omitempty"`
}

OrgTemplate is a customized template, with its older versions (newest first, at most 20).

type OrgTemplateList

type OrgTemplateList struct {
	// Customizable maps the kinds an organization may customize to the placeholders each must print.
	Customizable map[string]struct {
		Required []string `json:"required"`
	} `json:"customizable"`
	Items []OrgTemplate `json:"items"`
}

OrgTemplateList is the answer to listing templates.

type OrgTemplates

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

OrgTemplates are the email templates an organization customizes.

func (*OrgTemplates) Delete

func (t *OrgTemplates) Delete(ctx context.Context, kind, locale string, opts ...RequestOption) error

Delete goes back to the default template.

func (*OrgTemplates) Get

func (t *OrgTemplates) Get(ctx context.Context, kind, locale string, opts ...RequestOption) (*OrgTemplate, error)

Get returns one template.

func (*OrgTemplates) List

func (t *OrgTemplates) List(ctx context.Context, opts ...RequestOption) (*OrgTemplateList, error)

List returns the templates the organization has customized, and the kinds it may.

func (*OrgTemplates) Preview

func (t *OrgTemplates) Preview(ctx context.Context, kind, locale string, in PreviewInput, opts ...RequestOption) (*TemplatePreview, error)

Preview renders a template with sample data.

func (*OrgTemplates) Put

func (t *OrgTemplates) Put(ctx context.Context, kind, locale string, text TemplateText, opts ...RequestOption) (*OrgTemplate, error)

Put saves a template.

func (*OrgTemplates) Test

func (t *OrgTemplates) Test(ctx context.Context, kind, locale string, draft *TemplateText, opts ...RequestOption) error

Test sends a draft (or the saved template) to the signed-in user's address.

type Organization

type Organization struct {
	ID     string  `json:"id"`
	Name   string  `json:"name"`
	Slug   *string `json:"slug"`
	Status string  `json:"status"` // "active", "orphaned" or "deleted"
	// RequireMFA: the organization requires a second factor of its members.
	RequireMFA bool `json:"require_mfa"`
	// SSORequired: its people can only sign in through its connection.
	SSORequired bool `json:"sso_required"`
	// MembersWithoutSSO and SessionsRevoked are only in the answer that turned SSORequired on.
	MembersWithoutSSO *int `json:"members_without_sso,omitempty"`
	SessionsRevoked   *int `json:"sessions_revoked,omitempty"`
	// SessionMaxAge is the seconds the sessions opened in the organization last at most; nil: the realm's limit.
	SessionMaxAge *int `json:"session_max_age"`
	// MFAMet is false when the organization requires a second factor and this session used none.
	MFAMet bool `json:"mfa_met"`
	// Claims are written by administrators and functions; read-only here.
	Claims    map[string]any `json:"claims"`
	CreatedAt string         `json:"created_at"`
	// Roles are the user's effective role names there; EffectiveRoles say where each came from.
	Roles          []string            `json:"roles"`
	EffectiveRoles []RoleOrigin        `json:"effective_roles"`
	Teams          []string            `json:"teams"`
	TeamRoles      map[string][]string `json:"team_roles"`
	// Session is only in the answer to creating the organization: a session scoped to it.
	Session *struct {
		Token     string `json:"token"`
		ExpiresAt string `json:"expires_at"`
		Org       string `json:"org"`
	} `json:"session,omitempty"`
}

Organization is an organization as a member sees it.

type Orgs

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

Orgs are the organizations of the signed-in user: c.Orgs().

func (*Orgs) Create

func (o *Orgs) Create(ctx context.Context, in CreateOrgInput, opts ...RequestOption) (*Organization, error)

Create makes an organization with the signed-in user as its manager. The session in the answer is scoped to it: with a storage that can keep a token per organization it is kept by the organization's client (c.Org(slug)).

func (*Orgs) Delete

func (o *Orgs) Delete(ctx context.Context, id string, opts ...RequestOption) error

Delete deletes an organization; it needs a recent proof.

func (*Orgs) Get

func (o *Orgs) Get(ctx context.Context, id string, opts ...RequestOption) (*Organization, error)

Get returns an organization by id or slug.

func (*Orgs) Invitations

func (o *Orgs) Invitations(org string) *OrgInvitations

Invitations returns the invitations of an organization.

func (*Orgs) Leave

func (o *Orgs) Leave(ctx context.Context, id string, opts ...RequestOption) error

Leave removes the signed-in user from an organization.

func (*Orgs) Members

func (o *Orgs) Members(org string) *OrgMembers

Members returns the members of an organization.

func (*Orgs) SSO

func (o *Orgs) SSO(org string) *OrgSSO

SSO returns the sign-in connections of an organization.

func (*Orgs) SignedIn

func (o *Orgs) SignedIn(ctx context.Context) ([]SignedInOrg, error)

SignedIn lists the organizations the storage holds a session for, to show a switcher. It needs a storage with slots; with another it returns nothing.

func (*Orgs) Teams

func (o *Orgs) Teams(org string) *OrgTeams

Teams returns the teams of an organization.

func (*Orgs) Templates

func (o *Orgs) Templates(org string) *OrgTemplates

Templates returns the email templates an organization customizes.

func (*Orgs) Update

func (o *Orgs) Update(ctx context.Context, id string, patch OrgPatch, opts ...RequestOption) (*Organization, error)

Update changes an organization.

type Page

type Page[T any] struct {
	Items   []T  `json:"items"`
	Limit   int  `json:"limit"`
	Skip    int  `json:"skip"`
	HasMore bool `json:"has_more"`
	// NextCursor, with HasMore, is the After of the next page.
	NextCursor string `json:"next_cursor,omitempty"`
	// Total is set when the query asked to Count; it counts the whole list, not what follows After.
	Total *int `json:"total,omitempty"`
}

Page is one page of a list.

type PageParams

type PageParams struct {
	Limit int
	// After is the Next of the previous page.
	After string
}

PageParams page the lists of members.

type PasswordExpiredError

type PasswordExpiredError struct {

	// ResetEmailQueued is true when the server has sent the person a link to choose a new one.
	ResetEmailQueued bool
	// contains filtered or unexported fields
}

PasswordExpiredError is the answer to a sign-in with a password that has expired.

func (*PasswordExpiredError) Unwrap

func (e *PasswordExpiredError) Unwrap() error

type PreparedUpload

type PreparedUpload struct {
	ID    string
	Token string
	// Ref is what goes in the document's field.
	Ref map[string]string
	// ExpiresAt is RFC 3339: an upload that is not used expires then.
	ExpiresAt string
	// File is what backd stored.
	File struct {
		Name   string `json:"name"`
		Size   int64  `json:"size"`
		Type   string `json:"type"`
		SHA256 string `json:"sha256"`
	}
}

PreparedUpload is a file stored but not yet attached to a document: put Ref in the document's field.

type PreviewInput

type PreviewInput struct {
	Draft *TemplateText
	Data  map[string]any
}

PreviewInput is the input of Preview: a draft to render (the saved template when nil) with sample data.

type Profile

type Profile struct {
	Name       string `json:"name,omitempty"`
	GivenName  string `json:"given_name,omitempty"`
	FamilyName string `json:"family_name,omitempty"`
	Picture    string `json:"picture,omitempty"`
}

Profile is what a provider says of a person who just signed up, handed over once. Treat it as a hint.

type Push

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

Push registers this device so that functions can reach the signed-in user: c.Push(). Web push subscriptions need a browser and are not part of the Go client.

func (*Push) DeviceID

func (p *Push) DeviceID() string

DeviceID is the id of the device this client registered, or "".

func (*Push) Devices

func (p *Push) Devices(ctx context.Context, opts ...RequestOption) ([]Device, error)

Devices lists the user's registered devices.

func (*Push) Register

func (p *Push) Register(ctx context.Context, in DeviceInput, opts ...RequestOption) (*Device, error)

Register tells backd the token of this device. Registering again with the same token updates it.

func (*Push) RegisterOnLaunch

func (p *Push) RegisterOnLaunch(getToken func(ctx context.Context) (*DeviceInput, error), onError func(error)) (stop func())

RegisterOnLaunch registers the device now (if signed in) and after every sign-in, with the token getToken returns; it returns nil when the platform has none yet. Errors go to onError (they have nobody to be returned to). The returned function stops it.

func (*Push) Unregister

func (p *Push) Unregister(ctx context.Context, id string, opts ...RequestOption) (bool, error)

Unregister removes a device (this client's, with no id). It returns false when there was none to remove.

type PutOptions

type PutOptions struct {
	// Name is the display name; Type the content type (application/octet-stream by default).
	Name, Type string
	// IfMatch makes the write conditional on the document's version.
	IfMatch    any
	OnProgress func(UploadProgress)
}

PutOptions are the options of Files.Put.

type Query

type Query struct {
	// Where is a [Where], any value that encodes to a JSON object, or the JSON text of one.
	Where any
	// OrderBy lists fields, with a "-" prefix for descending: "-_meta.created_at".
	OrderBy []string
	// Limit is the page size, 1 to 100; the server's default (20) when 0.
	Limit int
	Skip  int
	// After is the NextCursor of the previous page: it continues the list after it.
	After string
	// Count also returns the Total of the whole list.
	Count bool
	// Deleted is "only" or "include" in a collection with soft_delete.
	Deleted string
	// FileLinks adds url and expires_at to every file of every document.
	FileLinks bool
	// Expand names the references to return in _expanded; build it with [Expand].
	Expand string
	// Language is the language a $search is stemmed in (a locale code such as "es").
	Language string
}

Query is what a list reads: the filter, the order and the page. The zero value lists the first page.

type ReadOptions

type ReadOptions struct {
	// Deleted is "only" or "include" to read a soft-deleted document.
	Deleted   string
	FileLinks bool
	Expand    string
}

ReadOptions are the options of a read of one document.

type Realtime

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

Realtime follows collections live over one multiplexed stream: c.Realtime(). Subscribing is per view; the client opens one stream for all of them and keeps it open, resuming after drops.

func (*Realtime) Open

func (r *Realtime) Open() int

Open returns the number of live views that are open.

func (*Realtime) Subscribe

func (r *Realtime) Subscribe(specs []SubscriptionSpec, o SubscribeOptions) (*LiveView, error)

Subscribe follows one or more subscriptions as one view. The view is loaded from normal reads when the stream is open, and kept current from its events; Close it when done.

type ReauthInput

type ReauthInput struct {
	// Method is one of the user's reauth_methods: "totp", "recovery_code", "password" or "email_code".
	Method   string
	Code     string
	Password string
}

ReauthInput proves who the user is again before a sensitive action.

type ReauthProof

type ReauthProof struct {
	Token     string
	ExpiresAt string
}

ReauthProof is the fresh proof of identity; the client sends it with sensitive calls while it is good.

type ReferenceSpec

type ReferenceSpec struct {
	// Field is a field of the listed documents (a dot path) holding an id or a list of ids.
	Field string
	// DB is the referenced collection's database; the subscription's by default.
	DB         string
	Collection string
	// Fields keeps only these fields of each referenced document (and its id and _meta).
	Fields []string
}

ReferenceSpec names documents referenced by the listed ones, to keep beside the list.

type RequestOption

type RequestOption func(*request)

RequestOption changes one call made with Client.Do.

func WithContentType

func WithContentType(contentType string) RequestOption

WithContentType sets the content type of a JSON body, such as application/merge-patch+json.

func WithHeader

func WithHeader(key, value string) RequestOption

WithHeader sets a header for the call.

func WithIdempotencyKey

func WithIdempotencyKey(key string) RequestOption

WithIdempotencyKey makes a create safe to repeat: the same key returns the first answer. It applies to creates, batches and function calls.

func WithIfMatch

func WithIfMatch(version any) RequestOption

WithIfMatch makes a write conditional on the document's version (its _meta.version, or an ETag). A document that has moved on is an error matching ErrVersionMismatch. A conditional write is safe to retry, so the client's retry settings apply to it.

func WithOrg

func WithOrg(org string) RequestOption

WithOrg scopes a call to an organization (collections with organization), by id or slug.

func WithProgress

func WithProgress(f func(UploadProgress)) RequestOption

WithProgress reports how much of the body has been sent.

func WithPurge

func WithPurge() RequestOption

WithPurge makes a delete remove the document for good instead of soft-deleting it.

func WithQuery

func WithQuery(q url.Values) RequestOption

WithQuery adds query parameters.

func WithRaw

func WithRaw() RequestOption

WithRaw returns the answer unread in Response.Body, for a file's bytes. The caller closes it.

func WithRawBody

func WithRawBody(body io.Reader, contentType string) RequestOption

WithRawBody sends r as the body as it is (a file's bytes) instead of JSON. contentType defaults to application/octet-stream. Without a io.Seeker the call is not repeated on a retry.

func WithReauth

func WithReauth() RequestOption

WithReauth sends the fresh proof of identity that Auth.Reauth gave, while it is good.

func WithRespondAsync

func WithRespondAsync() RequestOption

WithRespondAsync asks for the call to be answered at once with a job (Prefer: respond-async) instead of waiting for the output, when the function allows it.

func WithRetry

func WithRetry(retry Retry) RequestOption

WithRetry overrides the client's retry settings for this call.

func WithTeam

func WithTeam(team string) RequestOption

WithTeam scopes a call to a team of the organization (collections with team).

func WithoutAuth

func WithoutAuth() RequestOption

WithoutAuth sends no credentials.

func WithoutCache

func WithoutCache() RequestOption

WithoutCache skips the revalidation cache for this read.

func WithoutExpire

func WithoutExpire() RequestOption

WithoutExpire keeps a refused session token from ending the session (sign-in calls use it).

type ResetInfo

type ResetInfo struct {
	Subscription string
	// Reason is "history_expired", "slow_consumer", "preimage_missing", "config_changed" or "access_changed".
	Reason string
}

ResetInfo is what a reset says.

type Response

type Response struct {
	Status int
	Header http.Header
	// Body is the unread answer of a call made with [WithRaw] (a file's bytes); the caller closes it.
	Body io.ReadCloser
	// Data is the answer's body of any other call.
	Data []byte
	// FromCache is true when the server answered 304 and Data is the body kept from an earlier read.
	FromCache bool
}

Response is the answer to a successful call.

type Retry

type Retry struct {
	// Attempts is the number of extra tries after the first; 0 turns retries off.
	Attempts int
	// MaxDelay is the longest wait between tries; 30s when zero.
	MaxDelay time.Duration
}

Retry says how many times a call is repeated when the server answers 429 or 503. Only safe calls are repeated: reads, and writes that carry If-Match or an Idempotency-Key.

type RevalidationCache

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

RevalidationCache keeps the last body and ETag of document and list reads and revalidates them with If-None-Match, so an unchanged read costs a 304. Entries read as one caller (a session or an API key) are never reused for another. It is safe for concurrent use.

func NewRevalidationCache

func NewRevalidationCache(o CacheOptions) *RevalidationCache

NewRevalidationCache returns an empty cache.

func (*RevalidationCache) Clear

func (c *RevalidationCache) Clear()

Clear forgets everything.

func (*RevalidationCache) Stats

func (c *RevalidationCache) Stats() CacheStats

Stats says how the cache is doing.

type RoleOrigin

type RoleOrigin struct {
	Role   string   `json:"role"`
	Origin []string `json:"origin"`
}

RoleOrigin says where a role of a member comes from: "direct", "default" (the realm's default_roles) or the names of the teams that carry it.

type SecondStepRequiredError

type SecondStepRequiredError struct {
	Challenge string
	Methods   []string
	Consents  []ConsentRef
	// contains filtered or unexported fields
}

SecondStepRequiredError is what Login, Signup and the methods that promise a session return when the sign-in needs a second step: use SignIn to get the step as a value instead.

func (*SecondStepRequiredError) Unwrap

func (e *SecondStepRequiredError) Unwrap() error

type Session

type Session struct {
	Token     string `json:"token"`
	TokenType string `json:"token_type,omitempty"`
	SessionID string `json:"session_id"`
	// ExpiresAt is RFC 3339; pushed forward as the session is used.
	ExpiresAt string `json:"expires_at"`
	User      *User  `json:"user,omitempty"`
	// Org is the organization the session is scoped to: its token reaches that organization and no other.
	Org string `json:"org,omitempty"`
	// NewUser and Profile are set by a sign-in with a provider.
	NewUser           *bool    `json:"new_user,omitempty"`
	Profile           *Profile `json:"profile,omitempty"`
	RecoveryCodesLeft *int     `json:"recovery_codes_left,omitempty"`
}

Session is a new session. The client has stored its token already.

type SessionInfo

type SessionInfo struct {
	ID         string `json:"id"`
	CreatedAt  string `json:"created_at"`
	LastUsedAt string `json:"last_used_at"`
	ExpiresAt  string `json:"expires_at"`
	// Current is the session making this request.
	Current bool `json:"current"`
	// Org is the id of the organization the session is scoped to (none for an operator's).
	Org string `json:"org,omitempty"`
	// Connection is the provider of the organization's connection that opened it.
	Connection string `json:"connection,omitempty"`
}

SessionInfo is one of the user's sessions.

type SignInInput

type SignInInput struct {
	Email, Password string
	// Org signs in through this organization's routes (the client's own by default).
	Org        string
	Invitation string
}

SignInInput is the input of SignIn and Login.

type SignInOptions

type SignInOptions struct {
	// Providers are the external providers that are enabled.
	Providers []string
	// Methods are the other ways: "password", "magic_link".
	Methods     []string
	SSORequired bool
}

SignInOptions says how people can sign in to the realm (or to an organization).

type SignUpInput

type SignUpInput struct {
	Email, Password string
	// Invitation is an invitation token, for realms with signup: invite.
	Invitation string
	Locale     string
	// RedirectTo is where the verification link sends the person back to.
	RedirectTo string
	// Org signs up through this organization's routes (the client's own by default).
	Org string
	// Consents accepted at sign-up (name to version).
	Consents map[string]string
}

SignUpInput is the input of Signup.

type SignUpWithOrgInput

type SignUpWithOrgInput struct {
	Email, Password string
	// Name is the organization's name; Slug the short name people know it by.
	Name, Slug string
	Invitation string
	Locale     string
	RedirectTo string
	Consents   map[string]string
}

SignUpWithOrgInput is the input of SignUpWithOrg.

type SignedInOrg

type SignedInOrg struct {
	Ref       string // the id or slug the client of the organization is made with
	ID        string
	Name      string
	ExpiresAt string
}

SignedInOrg is an organization this program holds a session for.

type SizeFamily

type SizeFamily int

SizeFamily says which units a size accepts (and, for output, which it prints).

const (
	// SizeBoth accepts decimal and binary units. It is the zero value and the default for input;
	// for output it prints binary.
	SizeBoth SizeFamily = iota
	// SizeDecimal accepts B, KB, MB, GB and TB: powers of 1000.
	SizeDecimal
	// SizeBinary accepts B, KiB, MiB, GiB and TiB: powers of 1024.
	SizeBinary
)

func (SizeFamily) Units

func (f SizeFamily) Units() string

Units lists the units the family accepts, as a message names them.

type SlotStorage

type SlotStorage interface {
	TokenStorage
	// Slot returns the storage of one organization.
	Slot(name string) TokenStorage
	// Slots lists the organizations that hold a token.
	Slots(ctx context.Context) ([]string, error)
}

SlotStorage is a storage that can keep a token per organization, which Client.Org needs.

type Step

type Step struct {
	Kind      StepKind
	Session   *Session
	Challenge string
	// Methods are the second factors the user can use with StepMFA ("totp", "recovery_code").
	Methods []string
	// Consents are the ones to accept with StepConsent.
	Consents []ConsentRef
	Linked   string
}

Step is what a first factor answered: the session, or the second step the user has to take.

type StepKind

type StepKind int

StepKind says what a first factor led to.

const (
	// StepSession: signed in; Step.Session has the session.
	StepSession StepKind = iota
	// StepMFA: a code of the user's second factor is needed; send it with VerifyMFA(Challenge, method, code).
	StepMFA
	// StepEnrollment: the user's role requires a second factor and they have none; set one up with
	// MFA().Setup and MFA().Confirm using the Challenge.
	StepEnrollment
	// StepConsent: the sign-in is done but consents must be accepted first; show their texts
	// (Consents().Text) and send the acceptance with AcceptConsents(Challenge, consents).
	StepConsent
	// StepLinked: a provider was linked to the signed-in user (CompleteSignIn of a link); Step.Linked names it.
	StepLinked
)

type SubscribeOptions

type SubscribeOptions struct {
	// Jitter: a reload after a reset waits a random time up to this (1s by default), so that
	// many clients reset at once don't all reload at once.
	Jitter time.Duration
	// Random is the source of randomness for the jitter, in [0, 1); math/rand by default.
	Random func() float64
	// MaxBackoff is the longest wait before reconnecting after a failure (30s by default).
	MaxBackoff time.Duration
}

SubscribeOptions tune a live view.

type SubscriptionSpec

type SubscriptionSpec struct {
	// ID names the subscription in LiveState.Subscriptions; its position by default.
	ID string
	// DB and Collection name a collection that declares realtime: true.
	DB, Collection string
	// Where is the filter, in the query language limited to comparisons, $in, $nin, $between,
	// $isNull and $and/$or (no $search or text operators).
	Where any
	// Doc follows one document by id instead of a filter.
	Doc  string
	Load LoadSpec
	// References are referenced documents to keep beside the list, by name.
	References map[string]ReferenceSpec
}

SubscriptionSpec says what a live view follows.

type TeamInput

type TeamInput struct {
	Name  string   `json:"name"`
	Roles []string `json:"roles,omitempty"`
}

TeamInput is the input of Create.

type TeamMembersParams

type TeamMembersParams struct {
	// Role keeps the holders of a team role.
	Role string
	PageParams
}

TeamMembersParams filter and page the members of a team.

type TeamPatch

type TeamPatch struct {
	Name  *string   `json:"name,omitempty"`
	Roles *[]string `json:"roles,omitempty"`
}

TeamPatch changes a team; nil fields stay as they are.

type TeamRoleGrant

type TeamRoleGrant struct {
	Team  string `json:"team"`
	Role  string `json:"role"`
	From  string `json:"from,omitempty"`  // counts from then; always when empty
	Until string `json:"until,omitempty"` // and until then; for ever when empty
	// GrantedBy is a user id; empty for administrators and functions.
	GrantedBy string `json:"granted_by,omitempty"`
	GrantedAt string `json:"granted_at"`
	// Active: whether it counts now.
	Active bool `json:"active"`
}

TeamRoleGrant is a team role a member holds, in force or not.

type TeamRoleInput

type TeamRoleInput struct {
	// User is a member of the organization (they need not belong to the team).
	User string `json:"user"`
	// Role is a team role the realm declares.
	Role  string `json:"role"`
	From  string `json:"from,omitempty"`
	Until string `json:"until,omitempty"`
}

TeamRoleInput names a team role to grant, change the window of, or revoke.

type TemplatePreview

type TemplatePreview struct {
	TemplateText
	// Removed is what the sanitizer dropped.
	Removed []string `json:"removed"`
}

TemplatePreview is a rendered template, already sanitized.

type TemplateText

type TemplateText struct {
	Subject string `json:"subject"`
	Text    string `json:"text"`
	HTML    string `json:"html"`
}

TemplateText is the text of a template.

type TokenStorage

type TokenStorage interface {
	Get(ctx context.Context) (string, error)
	Set(ctx context.Context, token string) error
	Remove(ctx context.Context) error
}

TokenStorage keeps the session token between calls (and, for a file, between runs). An empty token means signed out.

type Typed

type Typed[T any] struct {
	// contains filtered or unexported fields
}

Typed decodes the documents of a collection into T, a struct that embeds Base. The calls are those of Collection.

func As

func As[T any](c *Collection) *Typed[T]

As returns the collection reading and writing documents as T.

func (*Typed[T]) Collection

func (t *Typed[T]) Collection() *Collection

Collection returns the untyped collection.

func (*Typed[T]) Create

func (t *Typed[T]) Create(ctx context.Context, doc any, opts ...RequestOption) (*T, error)

Create writes a new document and returns it as stored. Use WithIdempotencyKey to make a repeat harmless, WithOrg to say the organization.

func (*Typed[T]) Delete

func (t *Typed[T]) Delete(ctx context.Context, id string, opts ...RequestOption) error

Delete deletes a document; in a collection with soft_delete it can be restored, unless WithPurge removes it for good.

func (*Typed[T]) Get

func (t *Typed[T]) Get(ctx context.Context, id string, o ReadOptions, opts ...RequestOption) (*T, error)

Get reads one document.

func (*Typed[T]) Iterate

func (t *Typed[T]) Iterate(ctx context.Context, q Query, opts ...RequestOption) iter.Seq2[T, error]

Iterate reads every document the query matches, page after page, following the cursors. The loop ends at the first error, which is the second value of the last iteration.

Example

Iterate reads everything a query matches, page after page, following the cursors.

package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/fernandezvara/backd/pkg/client"
)

// demo is a small stand-in for a backd server, so the examples run.
func demo() *httptest.Server {
	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch {
		case r.URL.Path == "/v1/shelf/_auth/login":
			fmt.Fprint(w, `{"token":"bds_demo","session_id":"s1","expires_at":"2030-01-01T00:00:00Z","user":{"id":"u1","email":"ada@example.com"}}`)
		case r.URL.Path == "/v1/shelf/main/assets" && r.URL.Query().Get("after") == "":
			fmt.Fprint(w, `{"items":[{"id":"a1","title":"Docs","_meta":{"version":1}},{"id":"a2","title":"Notes","_meta":{"version":1}}],"has_more":true,"next_cursor":"c1"}`)
		case r.URL.Path == "/v1/shelf/main/assets":
			fmt.Fprint(w, `{"items":[{"id":"a3","title":"Links","_meta":{"version":1}}],"has_more":false}`)
		default:
			w.WriteHeader(http.StatusNotFound)
			fmt.Fprint(w, `{"error":{"code":"not_found","message":"no such document","request_id":"rq1"}}`)
		}
	}))
}

func main() {
	srv := demo()
	defer srv.Close()
	c, _ := client.New(client.Options{URL: srv.URL, Realm: "shelf"})
	defer c.Close()

	assets := c.DB("main").Collection("assets")
	for doc, err := range assets.Iterate(context.Background(), client.Query{Limit: 2}) {
		if err != nil {
			panic(err)
		}
		fmt.Println(doc.ID())
	}
}
Output:
a1
a2
a3

func (*Typed[T]) List

func (t *Typed[T]) List(ctx context.Context, q Query, opts ...RequestOption) (*Page[T], error)

List reads a page of documents.

func (*Typed[T]) Patch

func (t *Typed[T]) Patch(ctx context.Context, id string, patch any, opts ...RequestOption) (*T, error)

Patch merges changes into a document (JSON Merge Patch: a null removes a field); use WithIfMatch to not overwrite a newer version.

func (*Typed[T]) Replace

func (t *Typed[T]) Replace(ctx context.Context, id string, doc any, opts ...RequestOption) (*T, error)

Replace replaces a document; use WithIfMatch to not overwrite a newer version.

func (*Typed[T]) Restore

func (t *Typed[T]) Restore(ctx context.Context, id string, opts ...RequestOption) (*T, error)

Restore brings back a soft-deleted document.

func (*Typed[T]) Search

func (t *Typed[T]) Search(ctx context.Context, text string, q Query, opts ...RequestOption) (*Page[T], error)

Search lists the documents that match the text, best first. The text is words, "quoted phrases" and -excluded words. q.Where is combined with the search; q.OrderBy and q.After are not used (relevance pages by Skip).

type UpdatePasswordInput

type UpdatePasswordInput struct {
	Email, Password, NewPassword string
	Code, Method                 string
}

UpdatePasswordInput is the input of UpdatePassword: the way a person whose password expired chooses a new one, proving the old one (and a second factor when they have one).

type UploadOptions

type UploadOptions struct {
	// Name and Type override the source's own.
	Name, Type string
	// IfMatch makes the upload conditional on the document's version (a number or an ETag).
	IfMatch any
	// OnProgress reports how much has been sent.
	OnProgress func(UploadProgress)
}

UploadOptions are the options of an upload.

type UploadProgress

type UploadProgress struct {
	Loaded int64 // bytes sent
	Total  int64 // bytes in all, when known (0 otherwise)
}

UploadProgress says how much of an upload has been sent.

type User

type User struct {
	ID            string   `json:"id"`
	Email         string   `json:"email"`
	EmailVerified bool     `json:"email_verified"`
	Roles         []string `json:"roles"`
	// Locale is the user's language, one the realm lists (used for their emails).
	Locale    string `json:"locale"`
	CreatedAt string `json:"created_at"`
}

User is a realm user as the user sees themselves.

type VersionInfo

type VersionInfo struct {
	// Status is "undeclared" when the field doesn't declare the version.
	Status string
	Ready  bool
	Reason string
	Width  int
	Height int
}

VersionInfo says where a version stands.

func VersionStatus

func VersionStatus(file *FileDetails, name string) VersionInfo

VersionStatus says where the version name of a file stands.

type VersionParams

type VersionParams struct {
	MaxWidth  int    `json:"max_width,omitempty"`
	MaxHeight int    `json:"max_height,omitempty"`
	Fit       string `json:"fit,omitempty"` // "contain", "cover" or "stretch"
	Quality   int    `json:"quality,omitempty"`
	Format    string `json:"format,omitempty"` // "jpeg" or "png"
	Upscale   bool   `json:"upscale,omitempty"`
}

VersionParams are the parameters of Generate.

type VersionState

type VersionState struct {
	// Status is "pending", "ready", "empty", "skipped" or "failed".
	Status      string         `json:"status"`
	Reason      string         `json:"reason,omitempty"`
	ID          string         `json:"id,omitempty"` // fv_…, once ready
	Size        int64          `json:"size,omitempty"`
	Type        string         `json:"type,omitempty"`
	Width       int            `json:"width,omitempty"`
	Height      int            `json:"height,omitempty"`
	Params      map[string]any `json:"params,omitempty"`
	Fingerprint string         `json:"fingerprint,omitempty"`
	// Custom is true for a copy made with parameters a function gave (Generate), not the declared ones.
	Custom      bool   `json:"custom,omitempty"`
	GeneratedAt string `json:"generated_at,omitempty"`
	// URL is the copy's permanent address, on a public file once it is ready.
	URL string `json:"url,omitempty"`
}

VersionState is the state of one version (a resized copy) of an image.

type WaitOptions

type WaitOptions struct {
	// PollInterval is the time between polls; 500ms when zero.
	PollInterval time.Duration
	// Timeout gives up with a *JobTimeoutError; without it Wait waits until the job is done or the context ends.
	Timeout time.Duration
	// OnProgress is called after every poll with the steps reported so far.
	OnProgress func(steps []JobStep, job *Job)
}

WaitOptions are the options of Wait.

type Where

type Where map[string]any

Where is a filter in backd's query language: field names to a value (equality) or to the operators built by Eq, Gt, In and the others; "$or" and "$and" take lists of filters. The client only serializes it; the server checks it against the collection.

client.Where{"status": "active", "price": client.Between(10, 20)}
Example

Where is a filter in the query language: field names to values, or to operators.

package main

import (
	"fmt"

	"github.com/fernandezvara/backd/pkg/client"
)

func main() {
	w := client.Or(
		client.Where{"status": "published", "views": client.Gte(100)},
		client.Where{"tags": client.In("go", "backd")},
	)
	q := client.Query{Where: w, OrderBy: []string{"-_meta.created_at"}, Limit: 20}
	fmt.Println(q.OrderBy, q.Limit)
}
Output:
[-_meta.created_at] 20

func And

func And(w ...Where) Where

And matches documents that match all of the filters.

func Or

func Or(w ...Where) Where

Or matches documents that match any of the filters.

Jump to

Keyboard shortcuts

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