The go-runtime API#
gitlab.com/terryp/model/go-runtime holds the support types generated Go
imports. This page is its public surface: the identifiers generated code names
in your package, and which you are therefore expected to name too.
Nothing under …/go-runtime/gen appears here. Those packages are generator
internals, exported only because generated code sits in your package and
cannot reach unexported identifiers. They carry no compatibility promise.
Every declaration below is read out of the module’s own source by
go:autopackage, so the prose is the package’s doc comments and a signature
here cannot drift from the one you compile against. conf.py points it at
go-runtime/ through go_autodoc_modules.
go-runtime#
Imported as mdl. It needs github.com/shopspring/decimal, which
Map’s decimal keys use.
Three of its types have a guide page behind them: Time input behavior states in
full how ParseClock reads an ambiguous entry against Bias and Window,
Stored rows that fail validation is why a write that adds no
new violation is accepted rather than rejected, which is what
ValidationRegressionError reports, and PostgreSQL is why a Path
column stores an array and so why Compare orders the way it does.
FromError and StatusCoder are consulted in the order
Error responses and status sets out.
- package gitlab.com/terryp/model/go-runtime#
Package model is the runtime support library for Go code generated by omniblack.model. Generated files import it rather than carrying their own copy of these types, so several generated packages in one program share one Optional[T], one ValidationError, and one Path.
The identifiers here are part of the generated code’s public contract: a model type’s optional fields are Optional[T], its Validate method reports *ValidationError, and route handlers implement FromError and StatusCoder.
- const DefaultUploadLimit int64 = 32 << 20#
DefaultUploadLimit is the largest body, in bytes, a generated REST endpoint accepts as an uploaded file unless SetUploadLimit or WithUploadLimit says otherwise: 32 MiB.
- const FormatJSON FileFormat = iota + 1#
- const FormatYAML#
- const FormatTOML#
- const FormatXML#
- var ErrNoFile = errors.New("the file field is not set")#
- var ErrFileTooLarge = errors.New("the file is too large")#
- var ErrContentType = errors.New("the file's content is not of an allowed type")#
- var DefaultWindow = Window{From: NewTimeOfDay(9, 0, 0), To: NewTimeOfDay(21, 0, 0)}#
DefaultWindow is the window used for a time field whose model declares none: a working day of 09:00 through 21:00. Under it a bare “7” reads as 7:00 PM and a bare “10” as 10:00 AM. Assign to it to retune every such field at once; a field that declares a window in the model is unaffected.
- var ErrNoBase = errors.New("the path is relative and its base is not set")#
ErrNoBase is returned when a relative path is resolved against an optional base field that is not set. The path is refused rather than resolved against the root instead.
- var ErrNoValue = errors.New("the path field is not set")#
ErrNoValue is returned when an optional path field that is not set is opened: there is no path to resolve.
- func AbsoluteURL(ctx context.Context, path string) string#
AbsoluteURL returns the URL of path, an escaped path from the server’s root such as “/api/t/%2Fd”, under the public URL of ctx. The public URL’s own path is a prefix: “/api/t/x” under https://example.com/app is https://example.com/app/api/t/x. With no public URL, path is returned as it is.
- func Allowed(ctx context.Context, p Perm) bool#
Allowed reports whether ctx’s user may do what p guards. An open perm is always allowed, a Never one never is, and an Authenticated one is whenever the request has a user. A context with no Authorizer allows everything: perms guard what a request does, and code that reads the database for itself is not a request.
- func AllowedInGroup(ctx context.Context, p Perm, group string) bool#
AllowedInGroup reports whether ctx’s user may do what p guards in the group called group, through what their membership of it grants. It does not check that they are a member. As with Allowed, an open perm is always allowed, a Never one never is, an Authenticated one is whenever the request has a user, and a context with no Authorizer allows everything; an Authorizer that is not an Owner holds no perm in a group.
- func AllowedRow(ctx context.Context, p RowPerm, owner, group string) bool#
AllowedRow reports whether ctx’s user may do what p guards to a row that owner owns and that is in group; either is “” when the row has none. A context with no Authorizer allows everything, as Allowed does.
- func DenyStatus(ctx context.Context) int#
DenyStatus returns the status a request denied a perm is answered with: 404 Not Found when it has no user, so a stranger cannot tell what exists, and 403 Forbidden when it has one.
- func KeyText[K KeyType](k K) (string, error)#
KeyText returns the text form of k, which JSON, YAML and TOML write as the key of k’s entry and a validation error names it by.
- func LoadZone(name string) (*time.Location, error)#
LoadZone returns the time zone name names, as ZoneName writes it: time.UTC for “UTC”, a time.FixedZone for an offset such as “-04:00”, and otherwise the IANA zone time.LoadLocation finds. It is how a zone stored apart from its instant, such as in a PostgreSQL column, is read back.
- func MayAllow(ctx context.Context, p RowPerm) bool#
MayAllow reports whether ctx’s user may do what p guards to some row: to every row, or to those it owns or whose group it is in. A request it is false for is denied before any row is read.
- func MustParseURL(s string) *url.URL#
MustParseURL is ParseURL for a URL known to be absolute, such as a literal base in generated code. It panics if s is not one.
- func ParseURL(ref string, base *url.URL) (url.URL, error)#
ParseURL reads ref, the wire form of a url field, as an absolute URL.
With a base, ref may be any URI reference, and is resolved against base as RFC 3986 describes: “guide” against “https://example.com/docs/” is “https://example.com/docs/guide”. With a nil base, ref must itself be absolute, with a scheme.
- func ParseZonedTime(s string) (time.Time, error)#
ParseZonedTime parses RFC 9557 or RFC 3339 text, as UnmarshalText does, into a time.Time in the zone it names.
- func PathSegments(r *http.Request, name string) []string#
PathSegments returns the segments the wildcard name matched in the request a Router serves, each unescaped on its own, so a segment that holds an escaped “/” stays one segment. r.PathValue(name) unescapes the value as a whole, which cannot tell “a%2Fb” from “a/b”. It returns nil when no Router served r, or when its pattern has no wildcard name.
- func PublicURL(ctx context.Context) *url.URL#
PublicURL returns the public URL of ctx: the one WithPublicURL gave it, or else the one SetPublicURL set. It is nil when there is neither.
- func RelativeURL(u url.URL, base *url.URL) string#
RelativeURL returns the wire form of u, an absolute URL, for a url field whose relative references resolve against base.
When u has base’s scheme, user, host and port, it is written relative to base: as a path relative to base’s directory if u is under it, and otherwise as a path from the root. Any other u, and every u when base is nil, is written in full. ParseURL(RelativeURL(u, base), base) is u.
- func ResolveBeside(file string, p Path) string#
ResolveBeside resolves p against the directory holding file, an fs.ValidPath name in fsys, as ResolveIn resolves against a base that is a file. file is not looked up, so it need not exist yet: generated code resolves against a source field with it, which always names a file, and whose file a new row only stages.
- func ResolveIn(fsys fs.FS, base string, p Path) (string, error)#
ResolveIn resolves p against base, in fsys, and returns the fs.ValidPath name it resolves to. base is an fs.ValidPath name too, “.” for the top of fsys.
An absolute p ignores base and resolves from the top of fsys. Otherwise base is looked up with fs.Stat: a directory is what p resolves against, and anything else resolves p against the directory holding it. The stat error, if any, is returned as is.
p’s segments are then joined on one by one: “.” is dropped, and “..” removes the segment before it, stopping at the top of fsys, the way chroot does. Symbolic links are left to fsys: an os.Root’s FS refuses one that leads outside the root.
- func SetPublicURL(u *url.URL)#
SetPublicURL sets the public URL the server is reached at, such as https://example.com or https://example.com/app, for every context that WithPublicURL has not given its own. A nil u clears it. It panics if u is not absolute, or has a query or fragment.
The value is the application’s to find: read it from an environment variable or a flag at startup, say.
- func SetUploadLimit(n int64)#
SetUploadLimit sets the largest body, in bytes, a generated REST endpoint accepts as an uploaded file, for every context that WithUploadLimit has not given its own. A larger body is answered with 413 Content Too Large. A negative n means no limit.
- func UploadLimit(ctx context.Context) int64#
UploadLimit returns the upload limit of ctx: the one WithUploadLimit gave it, or else the one SetUploadLimit set, which is DefaultUploadLimit until it is called. It is negative when there is no limit.
- func UserIDOf(ctx context.Context) (string, bool)#
UserIDOf returns the ID of ctx’s user, when its Authorizer is an Owner and the request has a user.
- func WithAuthorizer(ctx context.Context, a Authorizer) context.Context#
WithAuthorizer returns a context whose perms a asks about. The generated endpoints give each request’s context the Authorizer they were registered with, so a handler’s own calls see the same perms.
- func WithFS(fsys fs.FS, use func(fs.FS) error) error#
WithFS calls use with fsys, then closes fsys if it is an io.Closer, joining the two errors. Generated With methods use it to close the filesystem an opener returns, so an opener returns a new filesystem it wants closed, or a shared one that is not an io.Closer.
- func WithPublicURL(ctx context.Context, u *url.URL) context.Context#
WithPublicURL returns a context whose PublicURL is u, overriding the one SetPublicURL set, for a server reached under several names. A nil u gives the context no public URL, so AbsoluteURL leaves paths root-relative. It panics as SetPublicURL does.
- func WithUploadLimit(ctx context.Context, n int64) context.Context#
WithUploadLimit returns a context whose UploadLimit is n, overriding the one SetUploadLimit set, for a limit of some endpoints’ own. A negative n means no limit.
- func ZoneName(t time.Time) string#
ZoneName returns the name of t’s zone, as it is written in brackets: “UTC” for time.UTC, and the zone’s IANA name, such as “America/New_York”, when time.LoadLocation knows it and it has t’s offset at t. Any other zone, time.Local or a time.FixedZone among them, is named by its offset at t, such as “-04:00”.
- func AuthorizerOf(ctx context.Context) Authorizer#
AuthorizerOf returns the Authorizer WithAuthorizer gave ctx, or nil.
- func DateFromString(s string) (Date, error)#
DateFromString parses a “YYYY-MM-DD” string into a Date. It rejects days that do not exist, such as “2023-02-29”.
- func NewDate(year int, month time.Month, day int) Date#
NewDate builds a Date from a year, month, and day. Out-of-range components normalize the way time.Date does, so NewDate(2024, 2, 30) is March 1; callers taking user input should use DateFromString instead.
- func RootFS(root *os.Root) DirFS#
RootFS returns root’s filesystem as a DirFS, whose Dir is root’s name. Paths resolve in it as in root.FS(), so a symbolic link leading outside the root is refused.
- func NewFile(content []byte) File#
NewFile returns the File of content: its type as http.DetectContentType sniffs it, its length and its SHA-256. A client’s own Content-Type is never asked, so a file is only ever what its bytes say it is.
- func FormatOf(name string) (FileFormat, error)#
FormatOf returns the format of the file called name, found through the media type of its extension, the way Python’s mimetypes module finds one.
The type is looked up with mime.TypeByExtension, which reads Go’s built-in table and, on unix, the shared MIME-info database, which this package loads from the XDG data directories when it starts. An extension neither knows falls back to a small table of the formats Go does not build in: .yaml, .yml and .toml. The common aliases of each type are accepted, such as application/x-yaml and text/yaml, and so is any +json or +xml suffix type.
A name whose type is not one of the formats returns an error wrapping errors.ErrUnsupported.
- func ParseISBN(s string) (ISBN, error)#
ParseISBN reads an ISBN-10 or ISBN-13, with or without hyphens and spaces between its digits. Unlike UnmarshalText, it rejects “”.
- func Collect[K KeyType, V any](seq iter.Seq2[K, V]) Map[K, V]#
Collect returns a Map holding the pairs of seq, in its order. A later pair replaces the value of an earlier one with an equal key.
- func FromMap[K interface { KeyType comparable }, V any](m map[K]V) Map[K, V]#
FromMap returns a Map holding the entries of m, a Go map literal’s usual source. A Go map has no order, so the keys are set in the order of their KeyText forms, which is their order for string keys.
- func ChrootPath(name string) Path#
ChrootPath returns the absolute path that name, an fs.ValidPath name such as ResolveIn returns, has inside its filesystem: the path it would have after a chroot into that filesystem. “.” is “/”, and “a/b” is “/a/b”.
The generated PostgreSQL code stores this form beside a rooted path field’s value, so two values that name the same file store the same resolved path.
- func NewPath(absolute bool, segments ...string) (Path, error)#
NewPath builds a path from its segments. A segment may hold any text but “/”, and may not be empty.
- func ParsePath(s string) (Path, error)#
ParsePath parses a path’s text form. A leading “/” makes the path absolute; “/” alone is the empty absolute path and “” the empty relative one. Repeated and trailing separators are errors, not something to normalize away, so one path has exactly one text form.
- func PathFromStorage(elements []string) (Path, error)#
PathFromStorage reads back what Storage wrote.
- func OtherPerm(p Perm) RowPerm#
OtherPerm returns the RowPerm of a struct whose perms are not given by class: p, whoever owns the row.
- func NewTimeOfDay(hour, min, sec int) TimeOfDay#
NewTimeOfDay builds a TimeOfDay from a wall-clock hour, minute, and second. Out-of-range components wrap the way time.Duration arithmetic does, so NewTimeOfDay(25, 0, 0) is an hour past midnight; callers taking user input should use ParseClock instead.
- func ParseClock(s string, bias Bias, window Window) (TimeOfDay, error)#
ParseClock parses a loosely-typed clock entry into a TimeOfDay.
Accepted input is a bare hour (“7”), an hour:minute (“7:30”), or an hour:minute:second (“7:30:15”), with “.” accepted in place of “:”, optionally suffixed with a meridiem marker (a, am, p, pm – case-insensitive, spacing optional). A marker is definitive, as is an explicit 24-hour value (hour 0 or 13-23); combining the two is an error.
A zero-padded two-digit hour (“07”, “08”) is a definitive 24-hour value and skips the meridiem inference below. That is the form String() emits, so a stored value round-trips through an editor unchanged instead of being re-read as PM.
Otherwise a bare 1-12 hour is ambiguous, and its AM and PM readings are resolved against two layers of preference:
Readings ruled out by bias are dropped.
Of what remains, a reading inside window wins; if both or neither are inside it, the earlier one wins.
If bias ruled out everything, the best-effort reading is used: the later one when After is set, the earlier one when only Before is, so a typed entry still lands somewhere sensible rather than failing.
- func TimeOfDayFromDuration(d time.Duration) TimeOfDay#
TimeOfDayFromDuration builds a TimeOfDay from a duration measured since midnight. It is the inverse of Duration, and is how storage layers outside this package rebuild a value they wrote out as an offset.
- func TimeOfDayFromString(s string) (TimeOfDay, error)#
TimeOfDayFromString parses an “HH:MM” or “HH:MM:SS” string into a TimeOfDay.
- func ParseUUID(s string) (UUID, error)#
ParseUUID reads a UUID in its hyphenated hex form. Unlike UnmarshalText, it rejects “”.
- func UUIDOf(b [16]byte) UUID#
UUIDOf returns the UUID holding b, its sixteen bytes in network order.
- func ValidationErrorsOf(err error) []*ValidationError#
ValidationErrorsOf returns every ValidationError joined or wrapped into err, in order.
- type Authorizer interface#
Authorizer answers, for a request, who is asking and what they hold. The generated endpoints of a model with the auth feature are given one, and ask it each time a perm guards what a request does. Each method is given the request’s context, so an Authorizer keeps whatever it learns of the user there, from a middleware run before the endpoints.
- func Authenticated(ctx context.Context) bool#
Authenticated reports whether the request has a user. A request denied a perm is told the row does not exist (404) when it has none, and that it is forbidden (403) when it has one.
- func Has(ctx context.Context, name string) bool#
Has reports whether the request’s user holds the perm called name.
- type Bias struct#
Bias steers how an ambiguous clock entry is read, from what the rest of a form already says. A field holding the end of a span sets After to the span’s start, so typing “7” then “9” reads as 7:00 PM then 9:00 PM rather than 9:00 AM. Both bounds are exclusive, and a nil bound is no constraint.
- type Date struct#
Date holds a calendar date: a year, month, and day with no time of day and no time zone. It serializes to and from “YYYY-MM-DD” (e.g. “2024-02-29”) in JSON, YAML, and XML via MarshalText/UnmarshalText, and is a TOML local date (d = 2024-02-29) via MarshalTOML/UnmarshalTOML.
The zero Date is January 1 of year 1, the same day as the zero time.Time. Dates compare with ==.
- func (d Date) AddDays(n int) Date#
AddDays returns the date n days after d; a negative n moves back.
- func (d Date) MarshalTOML() ([]byte, error)#
MarshalTOML implements go-toml’s unstable.Marshaler, which the generated TOML codecs switch on, writing a TOML local date (2024-02-29). Without it go-toml would write MarshalText’s text as a string.
- func (d Date) MarshalText() ([]byte, error)#
MarshalText implements encoding.TextMarshaler, rendering “YYYY-MM-DD”.
- func (d Date) Month() time.Month#
Month returns the date’s month.
- func (d Date) Time(loc *time.Location) time.Time#
Time returns midnight at the start of the date in loc.
- func (d *Date) UnmarshalTOML(data []byte) error#
UnmarshalTOML implements go-toml’s unstable.Unmarshaler, which the generated TOML codecs switch on. It reads a TOML local date, or a string holding “YYYY-MM-DD”, the form a Date was written in before MarshalTOML.
- type DirEntry struct#
DirEntry is one entry of a directory a generated root endpoint lists. A request for a directory that does not ask for HTML, or that has no index.html, is answered with the directory’s entries, sorted by name, as a JSON or YAML list of these.
- type DirFS interface#
DirFS is a filesystem that is a directory on disk. A root’s opener returns one to make the root writable: a REST upload resolves its path in the filesystem, as a read does, and writes the file at that name under Dir.
Embeds: fs.FS
- type ExtMiddleware[T any] func(route Route, config T, next http.Handler) http.Handler#
ExtMiddleware wraps the handler of each route that sets an extension’s key, given the route’s value for that key as config. An extension’s Go package declares one for its config type, and the generated RouteExtensions has a field of that type for each extension the model enables.
- type File struct#
File is the value of a model’s file field: what the server recorded of the bytes its row owns when they were uploaded. The bytes themselves are stored beside the row and served from its file URL, <row url>/file/<field>, and never appear in its JSON, YAML or TOML, which hold this:
{"content_type": "image/png", "size": 1234, "sha256": "<hex>"}
The server sets it, from the bytes, with NewFile. Build one any other way and it describes no stored content.
- ContentType string#
ContentType is the media type sniffed from the content, with any parameters, as “text/plain; charset=utf-8”.
- type FileFormat int#
FileFormat is a wire format a generated struct is read from or written to a file in.
- func (f FileFormat) String() string#
String returns the format’s name.
- type FromError interface#
FromError populates an error response from an error. Implement it on the route’s error response type (a method on a generated struct may live in any file of the same package) so the generated wrapper can convert a handler’s error return into the model-defined error body.
- type ISBN struct#
ISBN holds an International Standard Book Number as its compact ISBN-13: thirteen digits and no separators, such as “9780306406157”. It serializes to and from that form in JSON, YAML, and XML via MarshalText/UnmarshalText.
It reads either kind of ISBN. An ISBN-10 such as “0-306-40615-2” becomes the ISBN-13 of the same book, “9780306406157”: 978 in front, and the check digit recomputed. Hyphens and spaces may separate the digits and are dropped. The check digit must be right, an ISBN-10’s last character may be an upper-case X, and an ISBN-13 must start with 978 or 979. So one book has one ISBN, whichever way it was written, and ISBNs compare with ==.
The zero ISBN holds no number: it is what an unset field holds. IsZero reports it, and MarshalText refuses it rather than write something that is not an ISBN. Build values with ParseISBN.
- func (i ISBN) ISBN10() (isbn10 string, ok bool)#
ISBN10 returns the ISBN-10 of the same book, without separators. Only an ISBN-13 starting with 978 has one; for any other, including the zero ISBN, ok is false.
- type Integer struct#
Integer is the wire form of a model integer field on a generated Raw struct. It is a big.Int that reads any integer-valued number, so 30, 30.0, and 1e2 are all accepted and 1.5 is rejected, and writes its exact digits in every format: a bare JSON number, and a YAML or TOML integer. Beyond 64 bits it is a YAML or TOML string of its digits: YAML readers would round a larger integer, and TOML’s native integer is limited to 64 bits.
- func (i Integer) MarshalJSON() ([]byte, error)#
MarshalJSON implements json.Marshaler, writing a bare JSON number.
- func (i Integer) MarshalTOML() ([]byte, error)#
MarshalTOML implements go-toml’s unstable.Marshaler, which the generated TOML codecs switch on. A value that fits in 64 bits is written as a TOML integer; a larger one as a string of its digits, as TOML readers reject an integer beyond 64 bits, and UnmarshalText reads it back exactly. Without it go-toml would write MarshalText’s digits as a string at every size.
- func (i Integer) MarshalText() ([]byte, error)#
MarshalText implements encoding.TextMarshaler, writing the decimal digits.
- func (i Integer) MarshalYAML() (any, error)#
MarshalYAML implements yaml.v3’s Marshaler. A value that fits in 64 bits is written as a YAML integer; a larger one as a string of its digits, which UnmarshalText reads back exactly. Returning the int64 rather than a yaml.Node keeps this package free of the YAML dependency.
- type KeyType interface#
KeyType is every type a model map can be keyed by. The approximated kinds admit plain strings, bools and floats and the int-backed generated enums without a conversion; the next are the runtime and library types a model field of that type becomes, a url’s url.URL and a Nerd Font glyph’s nerdfont.Glyph included. The approximated structs admit a generated reference type, whose underlying type is struct{ Key K } for its target’s key type K; a reference key is equal to another, and written as, its Key.
Type set: ~string | ~int | ~bool | ~float64 | big.Int | Integer | decimal.Decimal | time.Time | ZonedTime | Date | TimeOfDay | Path | ISBN | UUID | url.URL | nerdfont.Glyph | ~struct{ Key string } | ~struct{ Key int } | ~struct{ Key bool } | ~struct{ Key float64 } | ~struct{ Key big.Int } | ~struct{ Key Integer } | ~struct{ Key decimal.Decimal } | ~struct{ Key time.Time } | ~struct{ Key Date } | ~struct{ Key TimeOfDay } | ~struct{ Key Path } | ~struct{ Key ISBN } | ~struct{ Key UUID } | ~struct{ Key url.URL } | ~struct{ Key nerdfont.Glyph }
- type Map[K KeyType, V any] struct#
Map is a mapping from K to V that compares keys by their value, not by ==: two big.Int, decimal.Decimal, time.Time, ZonedTime, url.URL, Integer or Path keys are the same key when they hold the same value, and so are two references whose Keys are. A NaN key is never equal to itself, as in a Go map, so it cannot be found again.
A Map remembers the order its keys were first set in, and iterates and encodes in that order. Setting an existing key keeps its position; deleting it and setting it again moves it to the end.
Like a Go map, a Map is a handle: copies share their contents. The zero Map is empty and ready to use; its first Set allocates, so set a Map through a pointer, not a copy. Deleting keys while ranging over All, Keys or Values is safe; setting new ones may or may not reach the iteration.
- func (m Map[K, V]) All() iter.Seq2[K, V]#
All returns an iterator over the keys and values of m, in order.
- func (m Map[K, V]) Get(k K) Optional[V]#
Get returns the value of k, or None when m does not hold k.
- func (m Map[K, V]) IsZero() bool#
IsZero reports whether m is empty, so encoders’ omitzero and omitempty leave out an empty Map.
- func (m Map[K, V]) MarshalJSON() ([]byte, error)#
MarshalJSON implements json.Marshaler, writing an object whose keys are KeyText’s, in m’s order.
- func (m *Map[K, V]) Pop(k K) Optional[V]#
Pop removes k and returns the value it had, or None when m did not hold k.
- func (m *Map[K, V]) SetDefault(k K, v V) V#
SetDefault returns the value of k, first setting it to v when m does not hold k.
- type Middleware func(route Route, next http.Handler) http.Handler#
Middleware wraps one route’s handler. The generated RegisterAllEndpoints calls each Middleware it is given once per route, when the route is registered, so a Middleware decides per route and not per request: one that has nothing to do for a route returns next unchanged, at no cost to its requests.
- type Optional[T any] struct#
Optional wraps a value that may be absent, keeping “not set” distinct from the zero value of T.
- type Owner interface#
Owner is implemented by an Authorizer that knows who a request’s user is and which groups they belong to, which a struct whose perms are given by class needs: its user class is the request whose user owns the row, and its group class the one whose user is in the row’s group. An Authorizer that is not an Owner is only ever in the other class.
- func UserID(ctx context.Context) (string, bool)#
UserID returns the ID of the request’s user, as a row’s owner field holds it, and false when the request has no user.
- func Groups(ctx context.Context) []string#
Groups returns the names of the groups the request’s user belongs to.
- func HasInGroup(ctx context.Context, group, name string) bool#
HasInGroup reports whether the request’s user holds the perm called name in the group called group: through what their membership of it grants, not what Has answers. The group class is checked with it alone, so a perm held for every group belongs in the other class.
- type Path struct#
Path is a slash-separated filesystem path: a sequence of segments, plus whether the path is absolute. It serializes to and from its text form (“/a/b/c” or “a/b/c”) in JSON, YAML, and XML via MarshalText/UnmarshalText, and persists as a PostgreSQL text[] of its segments via Value/Scan.
A leading “/” is part of the value: “/a/b” and “a/b” are different paths and never compare equal. A segment may hold any text except “/” – spaces, dots, and non-ASCII all round-trip – which is exactly the rule a real path segment already follows.
Full is the authoritative field. MarshalText, String, and Value all read it, and Segments is the split form kept alongside. Assigning to either field directly leaves the other stale; call Normalize to re-derive Segments from Full, or build values with ParsePath and NewPath, which set both.
- func (p Path) Compare(other Path) int#
Compare orders two paths the way PostgreSQL orders the stored arrays, so a sort in Go and an ORDER BY agree: segment by segment, with an absolute path before a relative one and a directory immediately before its own contents.
It compares the stored form rather than Segments so the two orderings cannot drift apart. The leading empty element of an absolute path’s stored form is what puts absolute first.
- func (p Path) DescendantRange() (lower, upper []string)#
DescendantRange returns the bounds of the paths under p, for a query against an ordered index on the stored array:
lower, upper := dir.DescendantRange() rows, err := tx.Query(ctx, "SELECT ... WHERE tree_path > $1 AND tree_path < $2 ORDER BY tree_path", lower, upper)
lower is p’s own stored form, so “> lower” is everything strictly under p and “>= lower” includes p itself. upper is the least value sorting after every descendant: p’s last element with the lowest byte a PostgreSQL text value can hold appended to it. Every descendant repeats that element exactly and so falls below the bound, while a sibling whose name merely starts with it (“a-1” next to “a”) sorts above and is left out.
“/” is the exception: it is stored as {“”,””}, and its children do not repeat that last empty element. Every absolute path starts with the empty element instead, so its upper bound is {“\x01”}, which sorts after every absolute path and before every relative one.
The bound is byte-wise, which is why a path column pins the C collation.
- func (p Path) MarshalText() ([]byte, error)#
MarshalText implements encoding.TextMarshaler, rendering the text form.
- func (p *Path) Normalize() error#
Normalize re-derives Segments from Full, for a value whose Full was assigned directly. It returns an error when Full is not a valid path, leaving the value untouched.
- func (p *Path) Scan(src any) error#
Scan implements sql.Scanner, reading the path back from a text[].
- func (p Path) Storage() []string#
Storage returns the path as PostgreSQL stores it: strings.Split of the text form, whose leading empty element is exactly what records that the path is absolute. Join reverses it, so the round trip needs no marker and no escaping.
This and PathFromStorage are the only two places that know the stored shape.
- func (p *Path) UnmarshalText(b []byte) error#
UnmarshalText implements encoding.TextUnmarshaler, parsing the text form.
- func (p Path) Value() (driver.Value, error)#
Value implements driver.Valuer, storing the path as a PostgreSQL text[] array literal. driver.Value cannot hold a Go slice, so the array is rendered in its text form; every element is quoted, which is also what makes the empty leading element of an absolute path survive.
The generated pgx code does not go through this – it hands pgx the segments directly – so this is for callers using database/sql.
- type Perm struct#
Perm is what an action on a model requires, as a struct’s perms, a field’s, or a route’s perm declares it. The zero Perm requires nothing, which the model spells “anonymous”. Never is a perm no user holds, which the model spells false. Authenticated is one every request with a user holds, which the model spells “authenticated”. Otherwise Name, when set, is the perm the user must hold.
- type QueryError struct#
QueryError is the error of a user-written query, the text Find<Name> takes, that cannot run. Syntax says the text does not parse, as opposed to naming a field it may not, using an operator the field’s type does not allow, giving a value that type cannot read, or going over a limit. Position is where the problem is, in characters from the start of the text.
- func (e *QueryError) Error() string#
Error returns the message and the position.
- type Relation string#
Relation is how a row a generated Related method found is related to the row it was called on.
- type RequestError struct#
RequestError is the client’s fault: a request the generated wrapper could not decode, or a path parameter it could not parse, before any handler ran. The wrapper hands it to FromError, which can tell it from a server fault with errors.As, through either *RequestError or StatusCoder.
- func (e *RequestError) Error() string#
- func (e *RequestError) HttpStatus() int#
HttpStatus returns Status, so RequestError satisfies StatusCoder.
- func (e *RequestError) Unwrap() error#
- type Router struct#
Router is the http.Handler the generated RegisterAllEndpoints and RegisterRestEndpoints register their endpoints on. Use it as the server’s handler, or mount it on a ServeMux with mux.Handle(“/”, router).
A pattern’s path is written like a ServeMux pattern’s, with these differences:
{name} matches one non-empty segment.
{name…} matches one or more non-empty segments, in any position. A path may hold several, with a literal segment between each two. {name…} is greedy: it takes as many segments as the rest of the pattern allows. {name…?} is lazy and takes as few.
A path may not end in “/”: there is no subtree pattern. Write {name…} for one, or end the path in {$} to match exactly the trailing slash. {name…}/{$} matches one or more segments followed by a trailing slash, which {name…} alone never does.
Precedence follows ServeMux’s: the most specific matching pattern wins. Patterns are compared position by position from the left, and the first difference decides: a literal beats {name}, which beats {name…}. When both have {name…} in the same position and neither has another after it, the segments after it are compared from the right in the same way, and the pattern with more of them wins. When either has another, the pattern with more literal segments after the shared one wins, then the one with fewer {name…} after it; when they tie on both, the segments up to the next {name…} are compared from the left again. Laziness plays no part.
A GET pattern also serves HEAD. A path that only other methods match is answered with 405 and an Allow header, and one that no pattern matches with 404, each as an RFC 9457 application/problem+json body, the shape the generated REST endpoints answer errors in. Like ServeMux, the router redirects a request whose path holds a “//”, “.” or “..” segment to the cleaned path, and sets the request’s Pattern and path values for the handler.
The zero Router serves nothing; NewRouter returns one ready for use. It is safe to register patterns while it serves requests.
- func (rt *Router) Handle(method, path string, h http.Handler)#
Handle registers h for requests with the method whose path matches the pattern path. It panics on a malformed pattern, and on one with the same method and shape as a pattern already registered, since the two would match the same requests.
- func (rt *Router) HandleFunc(method, path string, h func(http.ResponseWriter, *http.Request))#
HandleFunc registers h as Handle does.
- func (rt *Router) ServeHTTP(w http.ResponseWriter, r *http.Request)#
ServeHTTP serves the request with its most specific matching pattern.
- type RowPerm struct#
RowPerm is what an action on a row requires of each class of request, for a struct whose perms are given by class. A request may take the action when any class it is in allows it: User when its user owns the row, Group when its user is in the row’s group, and Other always. Group’s perm is held in the row’s group, as Owner.HasInGroup answers; User’s and Other’s as Authorizer.Has does. The zero RowPerm requires nothing, as its Other does not; a struct whose perms are not by class has only Other, and its User and Group are Never.
- type StatusCoder interface#
StatusCoder supplies the HTTP status code for a model value or error. The generated wrapper consults it for the error response type, the error return value, and the success response type. Like FromError, it is implemented on the model’s generated types in the user’s own files.
- type TimeOfDay struct#
TimeOfDay holds a time of day with whole-second precision, stored as the number of nanoseconds since midnight. It serializes to and from “HH:MM:SS” (e.g. “12:34:56”) in both JSON and YAML via MarshalText/UnmarshalText, and is a TOML local time (t = 12:34:56) via MarshalTOML/UnmarshalTOML. Both “HH:MM” and “HH:MM:SS” are accepted on input; output is always the whole-second “HH:MM:SS” form.
- func (t TimeOfDay) Display() string#
Display renders the time of day on a 12-hour clock, e.g. “7:30 PM”. The seconds are shown only when they are set (“7:30:15 PM”). The result parses back to the same value through ParseClock.
- func (t TimeOfDay) Duration() time.Duration#
Duration returns the time of day as the number of nanoseconds since midnight.
- func (t TimeOfDay) MarshalTOML() ([]byte, error)#
MarshalTOML implements go-toml’s unstable.Marshaler, which the generated TOML codecs switch on, writing a TOML local time (12:34:56). Without it go-toml would write MarshalText’s text as a string.
- func (t TimeOfDay) MarshalText() ([]byte, error)#
MarshalText implements encoding.TextMarshaler, rendering “HH:MM:SS”.
- func (t *TimeOfDay) UnmarshalTOML(data []byte) error#
UnmarshalTOML implements go-toml’s unstable.Unmarshaler, which the generated TOML codecs switch on. It reads a TOML local time, dropping any fraction of a second, or a string holding “HH:MM” or “HH:MM:SS”, the form a TimeOfDay was written in before MarshalTOML.
- type UUID struct#
UUID holds an RFC 9562 universally unique identifier. It serializes to and from its lower-case hyphenated hex form, such as “0190f5c6-7d8e-7a3b-9c4d-5e6f7a8b9c0d”, in JSON, YAML, and XML via MarshalText/UnmarshalText.
It reads the hyphenated form, 8-4-4-4-12 hex digits, in either case, and nothing else: no braces, urn:uuid: prefix, or bare hex. UUIDs compare with ==.
The zero UUID holds no identifier: it is what an unset field holds, and is not the nil UUID, “00000000-0000-0000-0000-000000000000”, which is a UUID like any other. IsZero reports it, and MarshalText refuses it rather than write something that is not a UUID. Build values with ParseUUID or UUIDOf.
- func (u UUID) Bytes() [16]byte#
Bytes returns u’s sixteen bytes in network order, all zero for the zero UUID.
- func (u UUID) MarshalText() ([]byte, error)#
MarshalText implements encoding.TextMarshaler, writing the lower-case hyphenated hex form. It fails for the zero UUID.
- func (u UUID) String() string#
String returns u’s lower-case hyphenated hex form, or “” for the zero UUID.
- type ValidationError struct#
ValidationError describes a single constraint violation found by a generated Validate or FromRaw method. Kind is “required”, “length”, “range”, “content_type”, “version” or “constant”; DataPath locates the offending field within the value, as dot-joined segments where a string map key is quoted (‘key’), and FilePath is set when the value came from a known file.
- func (e *ValidationError) Error() string#
- type ValidationRegressionError struct#
ValidationRegressionError is returned when a write would replace a stored value with one that fails constraints the stored value does not. Added holds only those new violations; Existing holds every violation of the stored value. Unwrap yields Added, so errors.As finds a *ValidationError.
- Added []*ValidationError#
- Existing []*ValidationError#
- func (e *ValidationRegressionError) Error() string#
- func (e *ValidationRegressionError) Unwrap() []error#
- type Window struct#
Window is the span of hours a time field’s values typically fall in, used to pick between the AM and PM readings of an ambiguous clock entry. To is exclusive, and a window whose To is at or before its From wraps midnight (an evening shift, say 18:00 to 02:00).
- type ZonedTime time.Time#
ZonedTime is the wire form of a model datetime: a time.Time whose Location is the time zone it was written in. Generated code converts it to and from the time.Time a struct holds; a program rarely names it.
It serializes to and from RFC 9557 text, the RFC 3339 timestamp followed by the zone’s name in brackets, in JSON, YAML, TOML, and as a map key’s text:
2026-10-06T21:00:00-04:00[America/New_York]
A zone is named by its IANA name, which time.LoadLocation reads from the system’s zone files. A program that may run without them, in a scratch container or on Windows, embeds a copy by importing time/tzdata in its main package or building with -tags timetzdata.
Decoding also accepts a plain RFC 3339 timestamp: “Z” is the zone UTC, and a numeric offset is a fixed zone named by that offset, “-04:00”. So is a native TOML offset datetime, or a YAML timestamp. It rejects a timestamp with no offset, an unknown zone name, an offset the named zone does not have at that instant, and a critical (“!”) bracket other than the zone. Other brackets, such as [u-ca=iso8601], are ignored.
Encoding always writes the bracket: a fixed zone as 2026-10-06T21:00:00-04:00[-04:00], and UTC as 2026-10-06T21:00:00+00:00[UTC], the forms Temporal.ZonedDateTime writes. A zone with no IANA name, such as time.Local, is written as its offset at that instant; see ZoneName.
Two ZonedTimes are equal as map keys when they are the same instant.
- func (z ZonedTime) MarshalText() ([]byte, error)#
MarshalText implements encoding.TextMarshaler, rendering RFC 9557 text.
- func (z *ZonedTime) UnmarshalTOML(data []byte) error#
UnmarshalTOML implements go-toml’s unstable.Unmarshaler, which the generated TOML codecs switch on. It reads a string holding RFC 9557 or RFC 3339 text, or a TOML offset datetime. go-toml would refuse the datetime when only UnmarshalText is there.
go-runtime/pg#
Imported as mdlpg. Needs github.com/jackc/pgx/v5. This is the transaction
plumbing the postgres feature’s generated CRUD runs in; Go and PostgreSQL is
the guide, and this is the reference.
One transaction per request, begun lazily by the first query, so a request that never touches the database never holds a connection.
- package gitlab.com/terryp/model/go-runtime/pg#
Package pg is the PostgreSQL half of the omniblack.model Go runtime: the transaction plumbing the generated CRUD code and REST handlers run in.
The identifiers here are part of the generated code’s public contract. Install a database with DBMiddleware for HTTP work or WithTx for anything else; generated queries then find it through the context.
- var ErrNoDB = errors.New("no database in context; use DBMiddleware or WithTx")#
ErrNoDB is returned by generated CRUD code when the context carries no database. Install one with DBMiddleware or WithTx.
- var ErrQueryTimeout = errors.New("the query took too long")#
ErrQueryTimeout is the error of a statement that Limited stopped for running past QueryTimeout.
- var QueryTimeout = 5 * time.Second#
QueryTimeout is how long one statement of a query an end user wrote, such as a Find<Name>, may run. A server may set it at startup. It is rounded up to a millisecond, since PostgreSQL reads 0 as no limit.
- func DBMiddleware(db DB) func(http.Handler) http.Handler#
DBMiddleware gives every request one lazily begun transaction on db.
Generated endpoint wrappers finish the transaction themselves, from the handler’s error return, before they write the response. For any other handler the middleware finishes it afterwards: it rolls back on a panic or a response status of 400 or more and commits otherwise. The response has already been sent by then, so a failed commit can only be logged.
Each request also carries a unit of work (see package txn), finished right after the transaction on either path. So the same holds for what enlists in it: generated endpoints report a failed commit, and other handlers only log one.
- func ErrorStatus(err error) int#
ErrorStatus returns the HTTP status an integrity constraint error is reported as, or a statement timeout, or 0 when err is neither.
- func FinishRequestTx(ctx context.Context, failed bool) error#
FinishRequestTx ends the context’s request transaction and its unit of work. Generated endpoint wrappers call it before writing the response, so a failed commit is still reported to the client. With no request transaction it still finishes a unit of work installed by txn.Middleware.
- func Limited(ctx context.Context) context.Context#
Limited returns a ctx whose UseTx runs each statement under QueryTimeout, and in a savepoint, so that one stopped for running too long does not abort the request transaction. It is for a query the request’s user wrote, whose cost nothing else bounds. A stopped statement’s error is ErrQueryTimeout.
- func NewPool(ctx context.Context, connString string, afterConnect func(context.Context, *pgx.Conn) error) (*pgxpool.Pool, error)#
NewPool opens a pool whose connections know the model’s PostgreSQL types. The generated package wraps it as its own NewPool, passing the generated RegisterTypes as afterConnect.
- func UseTx(ctx context.Context, fn func(tx pgx.Tx) error) error#
UseTx runs fn with the context’s request transaction, beginning it on first use. The transaction is held exclusively while fn runs, because a pgx.Tx is not safe for concurrent use; fn must finish reading any rows it opens.
- func WithTx(ctx context.Context, db DB, fn func(ctx context.Context) error) (err error)#
WithTx runs fn in one transaction on db, committing when fn returns nil and rolling back otherwise (including on panic). When ctx already carries a transaction, fn joins it and the outer owner decides its outcome.
fn’s context also carries a unit of work (see package txn), finished with the transaction, so a resource fn enlists commits or rolls back with it.
go-runtime/client#
Imported as mdlclient. Depends on nothing outside the standard library.
The Go client calls its server through it, and its errors are
the client’s: RouteError, Problem, and HTTPError.
- package gitlab.com/terryp/model/go-runtime/client#
Package client is what a model’s generated Go client calls its server through: the model’s routes, and the REST resources the server serves.
A generated client package wraps a Client in its own Client type, whose methods build each request’s URL and body and hand them to the functions here, which send it and decode the response. The types here are the generated methods’ results and errors: a RouteError carries a route’s error body, a Problem a REST request’s, and an HTTPError a response the client could not read.
- var ErrMissingPathParam = errors.New("fills the path, so it is required")#
ErrMissingPathParam is the error of a request leaving out a field its route’s path needs.
- var ErrNoClient = errors.New("no client in the context to resolve the reference through")#
ErrNoClient is what a generated reference’s Resolve returns when its context carries no client to read the row through. The generated package’s WithClient gives a context one.
- func AppendQuery(query url.Values, name string, value any) error#
AppendQuery adds value to query under name. A value whose text is empty is left out, which the server reads as the field absent.
- func CallEmptyRoute[E any](ctx context.Context, c *Client, method, path string, query url.Values, body []byte, failure Decoder[E]) error#
CallEmptyRoute calls a route without a success body, as CallRoute does: a success status is a nil error, whatever its body.
- func CallRoute[S, E any](ctx context.Context, c *Client, method, path string, query url.Values, body []byte, success Decoder[S], failure Decoder[E]) (S, error)#
CallRoute sends method to path, with query as its query string and body, unless it is nil, as its JSON body, and reads the response as a route’s.
A success status is decoded by success, and any other by failure, into a *RouteError. A body neither reads is an *HTTPError.
- func DecodeJSON[T any, P interface { *T json.Unmarshaler }](body []byte) (T, error)#
DecodeJSON decodes body with *T’s UnmarshalJSON, as a generated struct’s.
- func FileURL(item, field string, steps ...string) string#
FileURL returns the path of a file a row’s rooted path names: item, the row’s path, then field, then steps, the list indexes, map keys (an enum’s by member name), and field names leading from the field to the path, each one segment.
- func MissingPathParam(name string) error#
MissingPathParam returns the error of a request leaving out the field name, which fills a path placeholder.
- func PathSegments(value any, name string) (string, error)#
PathSegments returns value, a path filling the wildcard {name…}, as the escaped segments it fills, keeping their “/” separators. An absolute path’s leading “/” is escaped as %2F, which is how the server tells it apart. The empty path fills no segment, so it is an error.
- func RestEmpty(ctx context.Context, c *Client, method, path string, options WriteOptions) error#
RestEmpty sends a REST request answered without a body.
- func RestRowOrPage[T any](ctx context.Context, c *Client, path string, options PageOptions, decode Decoder[T]) (Row[T], *Page, error)#
RestRowOrPage reads a row keyed by a path: the row, decoded by decode, or, when no row has the path, the page listing the rows under it, which is then non-nil.
- func Segment(value any, name string) (string, error)#
Segment returns value, filling the path placeholder name, as one escaped path segment. The server reads an empty one as no value, so it is an error.
- func Text(value any) (string, error)#
Text returns value as a URL carries it: a string as it is, and anything else by its MarshalText, as an enum spells its member’s name and a big.Int its digits, or else as fmt prints it.
- func UploadQuery(path string) url.Values#
UploadQuery is the query string of an upload of the file at path.
- func MergePatchBody(patch []byte) *Body#
MergePatchBody is patch, an RFC 7386 JSON merge patch, as a body.
- func QueryBody(name string, params json.Marshaler) (*Body, error)#
QueryBody is a QUERY body running the query a resource’s struct declares as name, with params, which is nil for a query that takes none.
- func New(base string, httpClient *http.Client) (*Client, error)#
New returns a Client of the server at base, an absolute URL whose path, if any, prefixes every endpoint’s. It sends requests with httpClient, or with http.DefaultClient when that is nil.
- func RestItem(ctx context.Context, c *Client, path string) (ListItem, error)#
RestItem reads one row’s listing item, its summary, at path.
- func RestPage(ctx context.Context, c *Client, method, path string, body *Body, options PageOptions) (Page, error)#
RestPage sends a REST request answered with a page of a listing.
- func RestRow[T any](ctx context.Context, c *Client, method, path string, query url.Values, body *Body, options WriteOptions, decode Decoder[T]) (Row[T], error)#
RestRow sends a REST request answered with a row, decoded by decode. A refusal is a *Problem, and a body that does not decode an *HTTPError.
- type Client struct#
Client sends requests to the server at a base URL. Its methods return copies, so one Client can be shared by every goroutine, and a copy made per incoming request carries that request’s cookies.
- func (c *Client) URL(path string, query url.Values) string#
URL returns the absolute URL of path, an escaped path from the server’s root, with query as its query string when it has any.
- func (c *Client) WithCookies(cookies ...*http.Cookie) *Client#
WithCookies returns a copy of c that sends cookies with every request, after any c already sends.
- func (c *Client) WithCookiesFrom(r *http.Request) *Client#
WithCookiesFrom returns a copy of c that sends r’s cookies with every request, so a server handling r calls the API as r’s user. It is a copy, so concurrent requests never see each other’s cookies.
- type Decoder[T any] func(body []byte) (T, error)#
Decoder decodes a response body, the model’s JSON wire form, as a T.
- type HTTPError struct#
HTTPError is a response the client could not read as the endpoint’s: an error status whose body is not the error type the endpoint declares, such as a 404 from the router, or a success whose body does not decode.
- type ListItem struct#
ListItem is one row in a listing.
- Fields json.RawMessage#
Fields is the wire form of the row’s summary fields, or of its primary key without a summary.
- type Page struct#
Page is one page of a listing, with the tokens naming the pages beside it. A token is passed back as PageOptions.Page. Prev is “” for the first page, which needs none.
- Next model.Optional[string]#
- Prev model.Optional[string]#
- type Problem struct#
Problem is an RFC 9457 problem details body: the error a REST request is refused with.
- Errors []FieldError#
- ExistingErrors []FieldError#
ExistingErrors lists the stored row’s violations when an update is refused for adding violations the row does not have.
- type RouteError[E any] struct#
RouteError is a route’s error response: an error status, whose body is the error type the route declares. errors.As finds it in a generated route method’s error.
- Body E#
Body is the decoded error response.
- func (e *RouteError[E]) Error() string#
go-runtime/summary#
Imported as mdlsummary. Depends on nothing outside the standard library.
Generated summary methods render through it, and return its Markdown;
Summaries is the guide.
- package gitlab.com/terryp/model/go-runtime/summary#
Package summary renders a struct’s summary: a title, and an optional subtitle under it.
A model struct declares each line of its summary as a text/template over the fields it names. The generated RenderTitle and RenderSubtitle methods fill the templates’ data and call
Template.Render; a program rarely uses this package directly, except to render theMarkdownthey return, whichMarkdown.HTMLdoes for a web page.Each line is inline CommonMark: one paragraph, with no headings, lists, code blocks, or other blocks, so a consumer renders it to HTML or to a terminal’s ANSI styles as it would any Markdown. The template’s own text is Markdown, written by the model’s author; the data it reads is escaped, so a name such as a*b* stays literal.
- func Escape(s string) Markdown#
Escape returns s as Markdown that renders as exactly s, on one line.
It backslash-escapes the characters that start inline markup, and a leading marker that would otherwise begin a heading, list item, or thematic break. Line breaks become spaces, since a summary is one paragraph, and leading spaces and tabs are dropped, as a paragraph drops them, so that an indent cannot start a code block.
- func Float(f float64) Markdown#
Float returns f as Markdown, in the shortest form that reads back as f.
- func List(conj string, items []Markdown) (Markdown, error)#
List joins items as an English list, with conj (“and” or “or”) before the last: “a”, “a and b”, “a, b, and c”. It adds no markup, and returns “” for no items. A summary template calls it as list:
{{list "and" .tags}}
It is not named and or or because text/template’s own and and or are its boolean operators.
- func MustParse(name, text string) *Template#
MustParse is
Parsefor a template known to be valid, panicking if it is not. Generated code parses each summary with it as the package initializes, so a template that does not parse fails the first test that loads it.
- func Parse(name, text string) (*Template, error)#
Parse parses text, one of a struct’s summary templates, named name in errors.
- type Markdown string#
Markdown is inline CommonMark text. A summary’s data and its result are both Markdown: a field’s text is escaped into it with
Escape, and an embedded or referenced struct’s summary already is it.
- type Ref[R, S any] struct#
Ref is a reference in a summary: the reference itself, and the summary of the row it names when that row was read. A generated summary renders a Ref whose Summary is nil by the reference’s key.
- Ref R#
- Summary *S#
go-runtime/txn#
Depends on nothing outside the standard library, so pg depends on it
without pulling anything in. It is the extension point for resources that
must commit with a request’s database transaction: a participant enlists
itself on first use, and pg finishes it right after the database is
decided.
- package gitlab.com/terryp/model/go-runtime/txn#
Package txn is the unit of work a request’s non-database resources enlist in, so that they commit or roll back with its database transaction.
The database is decided first. pg’s request transaction finishes the registry right after its own commit or rollback, and a participant is told which way it went: Commit when the database committed, Rollback when it rolled back or its commit failed. A participant therefore never publishes state the database refused.
Enlistment is lazy. A participant joins on its first use in a unit of work, so an extension needs no lifecycle hook to attach, and a request that never calls it pays nothing. pg.DBMiddleware and pg.WithTx install a registry wherever they install a transaction; Middleware installs one for a server with no database.
The package depends on nothing outside the standard library.
- var ErrFinished = errors.New("unit of work already finished")#
ErrFinished is returned by Join and Enlist once the unit of work has been committed or rolled back. A caller that staged durable state before joining must discard it itself before returning this error.
- var ErrNoRegistry = errors.New("no unit of work in context; use pg.DBMiddleware, pg.WithTx or txn.Middleware")#
ErrNoRegistry is returned by Join and Enlist when the context carries no unit of work. Install one with pg.DBMiddleware, pg.WithTx or Middleware.
- func Enlist[P Participant](ctx context.Context, key any, create func() (P, error)) (P, error)#
Enlist returns the participant enlisted under key in the context’s unit of work, creating and joining it with create on the first call. It is how a resource enlists lazily: every call in one unit of work gets the same participant, and a unit of work that never calls it has none.
create runs with the registry locked, so it must not call Join or Enlist. When it fails nothing is enlisted and its error is returned. Key is compared with ==, as a context key is; use a private type for it.
- func Finish(ctx context.Context, failed bool) error#
Finish ends the context’s unit of work: it commits every participant when failed is false and rolls every one back otherwise. It runs all of them even when some fail, and returns their errors joined. Only the first call has any effect, and a context with no unit of work is a no-op.
- func Join(ctx context.Context, p Participant) error#
Join enlists p in the context’s unit of work. Participants are committed in the order they joined and rolled back in the reverse order.
- func Middleware(next http.Handler) http.Handler#
Middleware gives every request a unit of work, for a server with no database; pg.DBMiddleware already installs one. When the request’s context already carries one, Middleware leaves it to its owner.
Generated endpoint wrappers finish the unit of work themselves, before they write the response. For any other handler the middleware finishes it afterwards: it rolls back on a panic or a response status of 400 or more and commits otherwise. The response has already been sent by then, so a failed commit can only be logged.
- func With(ctx context.Context) context.Context#
With returns a context carrying a new, empty unit of work. Whoever calls With owns it and must call Finish exactly once it knows the outcome.
- type Participant interface#
Participant is a non-database resource enlisted in a unit of work. Commit publishes its staged state; Rollback discards it. Exactly one of them is called, once, after the database transaction has been decided.
The context they receive is not canceled with the request: by the time they run the outcome is already decided, and abandoning a commit half-way would leave more behind than finishing it.
- func Commit(ctx context.Context) error#
- func Rollback(ctx context.Context) error#
go-runtime/fsedit#
Needs golang.org/x/sys/unix, and depends on txn and nothing else in the
runtime. Transactional file edits is the guide: the protocol, the two recovery rules, the
names a scanner must skip, and the locking rules.
- package gitlab.com/terryp/model/go-runtime/fsedit#
Package fsedit makes an edit to several files atomic and crash-recoverable, and commits it with the request’s database transaction.
An edit is staged beside its target as .<base>.<txnid>.next, a delete as a .<base>.<txnid>.del tombstone, and nothing real is touched until commit. A write’s content is first received into the root’s .txn directory, under an id of its own, before the directory is locked, and renamed to its staged name under the lock. Commit writes one manifest, .txn/<txnid>.json under the root, listing every target: that rename is the point of no return. It then renames each staged file over its target, and finally removes the manifest.
Recovery needs no guessing. A manifest means its transaction committed, and replaying it is idempotent: a staged file or tombstone that is still there is applied, and one that is gone was applied already. A staged file whose transaction has no manifest was never committed, and is removed. Call Recover at start, before serving.
In a request, Write, WriteFrom and Remove enlist a transaction in the context’s unit of work (see package txn) on first use, and it commits only after the database has: data the database rejects never reaches the files. Install the root with Middleware outside pg.DBMiddleware, or with With. Begin runs a transaction without a request, for a scanner, importer or command.
What a consumer must skip
Anything scanning the tree must skip the .txn directory at the root, and the hidden files matching .*.<txnid>.next and .*.<txnid>.del, where txnid is 16 lower-case hex digits.
Locking
Several processes may edit one tree. A transaction holds an exclusive flock on each directory it edits, from its first edit there until it finishes, so edits in one directory are serialized. Locks are taken in ascending path order, and never by a blocking wait: an edit gives up with ErrLocked after its LockTimeout, since the database commit runs while the locks are held and PostgreSQL cannot see a flock to break a deadlock through one. Taking a directory’s lock first finishes any committed edit there that a dead process left unapplied.
When a commit fails after the commit point
Publishing can fail after the manifest is in place: the disk is full, the filesystem reports an error, another process changed a directory. The transaction is committed all the same, and Commit returns the error to be logged. Its manifest stays, and each later lock on an affected directory, and Recover, tries again. Until one succeeds the directory takes no new edits, since a replay would overwrite them, and each attempt fails with an error naming the transaction and the directory. It clears by itself once the cause is gone.
The package builds on Linux and the BSDs, including macOS. MustCreate needs Linux’s RENAME_NOREPLACE, and fails with errors.ErrUnsupported anywhere else.
- const DefaultLockTimeout = 5 * time.Second#
DefaultLockTimeout is how long an edit waits for a directory’s lock when no LockTimeout option is given.
- var ErrConflict = errors.New("fsedit: target does not match the edit's precondition")#
- var ErrLocked = errors.New("fsedit: directory is locked by another transaction")#
- var ErrNoRoot = errors.New("fsedit: no root in context; use fsedit.Middleware or fsedit.With")#
- var ErrDone = errors.New("fsedit: transaction already finished")#
- func Middleware(root string) func(http.Handler) http.Handler#
Middleware gives every request root, as With does. It only configures: the transaction joins the request’s unit of work, so install it outside pg.DBMiddleware (or txn.Middleware), which own that.
- func Remove(ctx context.Context, path string, opts ...Option) error#
Remove stages the removal of path in the context’s transaction, as Write stages a write. Removing a path that does not exist is not an error.
- func With(ctx context.Context, root string) context.Context#
With returns a context whose Write, WriteFrom and Remove edit files under root.
- func Write(ctx context.Context, path string, data []byte, opts ...Option) error#
Write stages data as the new content of path in the context’s transaction. The transaction is begun on the first edit and joins the context’s unit of work, so it commits after, and only if, the database does. Later edits in the same unit of work join the same transaction; two edits to one path coalesce, and the last wins.
path is an ordinary path, relative to the working directory or absolute, and must lie under the root. Its directory must exist.
- func WriteFrom(ctx context.Context, path string, r io.Reader, opts ...Option) error#
WriteFrom stages what r reads, up to its end, as the new content of path, as Write stages data. It is Receive and then WriteReceived: the content is copied in before path’s directory is locked, so a slow reader holds no lock and keeps no other transaction waiting. A copy that fails, or whose context is canceled, leaves nothing staged, and an earlier edit of path in the transaction as it was.
- func WriteReceived(ctx context.Context, path string, in *Incoming, opts ...Option) error#
WriteReceived stages in, which Receive copied in, as the new content of path in the context’s transaction, as Write stages data. It takes path’s directory’s lock and checks the edit’s preconditions, and then moves in into place without copying it again, unless path is on another filesystem than the root’s .txn directory.
- func Receive(ctx context.Context, r io.Reader) (*Incoming, error)#
Receive copies what r reads, up to its end, into a file of the context’s transaction, for WriteReceived to stage as some path’s content once the caller knows which. Nothing is locked while it copies, so the copy can run before whatever decides the path, such as locking the database row that names it. Close the result when done with it.
- func IfUnmodified(tok Token) Option#
IfUnmodified fails the edit with ErrConflict when the target is no longer the version tok was taken from, including when it is gone. The check is made under the directory’s lock, which is then held until the transaction finishes, so no other fsedit transaction can change the target in between.
- func LockTimeout(d time.Duration) Option#
LockTimeout sets how long the edit waits for its directory’s lock before failing with ErrLocked. The default is DefaultLockTimeout.
- func MustCreate() Option#
MustCreate fails the edit with ErrConflict when the target exists. The commit then renames with RENAME_NOREPLACE, so a file created outside fsedit in the meantime is not replaced either.
That needs Linux 3.15 or later and a filesystem that supports the flag, such as ext4, btrfs, xfs or tmpfs. Off Linux the edit itself fails with an error wrapping errors.ErrUnsupported. On a Linux filesystem without the flag, the commit fails with that error after the commit point, as it would for any other error there: the create stays pending, and its directory accepts no edits until a filesystem that supports the flag lets it finish.
- func Recover(ctx context.Context, root string) (Recovered, error)#
Recover finishes every transaction under root that a dead process left behind. A transaction with a manifest committed, and its edits are published; one without never did, and its staged files are removed. Both are idempotent, so running Recover again, or after a crash part-way through, is safe.
Call it at start, before serving. Transactions still running in another process are left alone, so it is safe while sibling processes serve from the same tree.
- func Stat(path string) (Token, error)#
Stat returns the Token of the file at path as it is now. A file replaced by any fsedit edit gets a new inode, and so a new Token, even when its size and modification time come out the same.
- func Begin(root string) (*Tx, error)#
Begin starts a transaction over the files under root, creating root’s .txn directory if need be. Nothing is locked or staged until the first edit.
- type Incoming struct#
Incoming is content Receive copied into the root’s .txn directory, to be staged by WriteReceived. Close it once it is written, or will not be: content still there is removed. An Incoming is not safe for concurrent use.
It has an id of its own, whose liveness file it holds until it is closed, so Recover leaves it alone meanwhile, and removes it should its process die first.
- type Recovered struct#
Recovered is what Recover did, as target paths.
- type Token struct#
Token identifies one version of a file, for IfUnmodified. Take it with Stat when the file is read; the zero Token matches nothing.
- type Tx struct#
Tx is one transaction over the files under a root. The request-scoped Write and Remove manage one for you; Begin starts one directly, for code with no request. It is safe for concurrent use.
- func (t *Tx) Commit(ctx context.Context) error#
Commit publishes every staged edit. It fsyncs the staged directories, writes the manifest (the commit point), renames each staged file over its target, and removes the manifest.
An error before the manifest is in place means nothing was published, and the transaction has been rolled back. An error after it means the transaction is committed anyway: what could not be applied now is applied by the next transaction to lock the directory, or by Recover. Log that error; do not treat it as a rollback.
- func (t *Tx) Receive(r io.Reader) (*Incoming, error)#
Receive copies what r reads into a file of the transaction. See the package-level Receive.
- func (t *Tx) Remove(path string, opts ...Option) error#
Remove stages the removal of path. See the package-level Remove.
- func (t *Tx) Rollback(ctx context.Context) error#
Rollback discards every staged edit. The targets were never touched.
- func (t *Tx) Write(path string, data []byte, opts ...Option) error#
Write stages data as the new content of path. See the package-level Write.
go-runtime/secret#
Needs go-secret and
golang.org/x/crypto, and compiles only with GOEXPERIMENT=runtimesecret.
A model with a password or secret field imports it under its own name, and
no other model does. Passwords and secrets is the
guide, and Passwords and secrets sets out how a secret is
stored.
- package gitlab.com/terryp/model/go-runtime/secret#
Package secret holds the Go types of a model’s password and secret fields, built on
gitlab.com/terryp/go-secret.A
Passwordis what a password field holds: a plaintext decoded from JSON, YAML, TOML or XML, kept in guarded memfd_secret memory, or the Argon2id hash a database row stores, or both. It writes itself as that hash, in the PHC string format, and never as its plaintext. Text is always read as a plaintext, so a hash sent in its place is hashed again.A
Secretis what a secret field holds: a value the program reads back, such as an API token, kept in a guarded buffer. It writes itself as its plaintext, so a secret field is usually declared with read: false perms, which keep it out of every response. In PostgreSQL it is stored as its plaintext, so it can be indexed and compared; encrypt the database’s storage to keep it from the disk.Requirements
go-secret needs Linux with memfd_secret and GOEXPERIMENT=runtimesecret, and so does this package: it compiles only with the experiment on. Code generated from a model imports it only when the model has a password or secret field.
- func NewPassword(p gosecret.Password) Password#
NewPassword returns a Password holding the plaintext p, which it takes ownership of.
- func ParsePassword(s string) (Password, error)#
ParsePassword returns a Password holding the plaintext s, as UnmarshalText reads it. Unlike UnmarshalText, it rejects “”.
- func PasswordFromHash(h gosecret.PasswordHash) Password#
PasswordFromHash returns a Password holding only the hash h.
- func NewSecret(b *gosecret.Buffer) Secret#
NewSecret returns a Secret holding b, which it takes ownership of.
- func ParseSecret(s string) (Secret, error)#
ParseSecret returns a Secret holding a copy of s, which cannot be “”.
- type Password struct#
Password is the value of a password field: a plaintext password, the Argon2id hash of one, or both.
Where a Password comes from decides which it holds. Text, in every format a struct decodes from, is always a plaintext; only a database row holds a hash, which the generated PostgreSQL code reads with PasswordFromHash. A Password holding only a plaintext hashes it the first time its hash is asked for; copies of a Password share that hash, and the plaintext.
The zero Password holds neither: it is what an unset field holds. IsZero reports it, and MarshalText refuses it.
- func (p Password) Check(pw *gosecret.Buffer) bool#
Check reports whether pw is the password p holds. It is false for the zero Password, and for one destroyed before it was hashed.
- func (p Password) Destroy()#
Destroy wipes and releases p’s plaintext, if it holds one, for p and every copy of it. A hash already made is kept, but none is made: a Password destroyed before it was hashed holds nothing, and its Hash reports !ok. Hash it first to keep it usable.
- func (p Password) Equals(o Password) bool#
Equals reports whether p and o hold the same password, as far as that can be told without hashing either. Two plaintexts are compared in constant time inside guarded memory, and two hashes by their PHC strings, also in constant time. A plaintext never equals a hash, even its own: checking it against the hash would cost an Argon2id and tell whoever sent it whether it was the stored password. Copies of a Password are equal, as are two zero Passwords; one destroyed before it was hashed equals only its copies.
- func (p Password) Hash() (h gosecret.PasswordHash, ok bool)#
Hash returns p’s Argon2id hash, hashing its plaintext the first time it is called on a Password that holds only that. ok is false for the zero Password, and for one destroyed before it was hashed.
- func (p Password) IsZero() bool#
IsZero reports whether p is the zero Password, which holds nothing.
- func (p Password) MarshalText() ([]byte, error)#
MarshalText implements encoding.TextMarshaler, writing p’s hash in the PHC string format. It never writes the plaintext. It refuses the zero Password and one destroyed before it was hashed.
- func (p Password) Plain() (gosecret.Password, bool)#
Plain returns p’s plaintext, which only a Password decoded from a plaintext or made by NewPassword holds. It is the Password to check the quality of, before p is stored.
- func (p *Password) UnmarshalText(b []byte) error#
UnmarshalText implements encoding.TextUnmarshaler, reading b as a plaintext password and copying it into guarded memory.
It never reads b as a hash, even one MarshalText wrote: a hash sent in its place is a plaintext like any other and is hashed in turn, so nobody can set a hash directly. Decoding what MarshalText wrote therefore gives a Password whose plaintext is that hash, not the original password.
It reads “” as the zero Password, a missing value, which a generated struct’s FromRaw reports as required.
- type Secret struct#
Secret is the value of a secret field: bytes the program reads back, such as an API token, kept in a guarded buffer.
It writes itself as its plaintext, which has to leave guarded memory to do so. A secret field nobody should read over the wire is declared with read: false perms.
The zero Secret holds nothing: it is what an unset field holds. IsZero reports it, and MarshalText refuses it.
- func (s Secret) Buffer() *gosecret.Buffer#
Buffer returns the buffer s holds, or nil for the zero Secret.
- func (s Secret) Equals(o Secret) bool#
Equals reports whether s and o hold the same bytes, compared in constant time inside guarded memory, so neither plaintext is copied out. Two zero Secrets are equal; a zero Secret equals no other.
- func (s Secret) MarshalText() ([]byte, error)#
MarshalText implements encoding.TextMarshaler, writing s’s plaintext into ordinary memory.
- func (s Secret) Sum256() (sum [32]byte)#
Sum256 returns the SHA-256 of s’s bytes, or all zeroes for the zero Secret. It hashes inside View, so only the digest leaves guarded memory: it is what a secret field contributes to its row’s entity tag.
- func (s *Secret) UnmarshalText(b []byte) error#
UnmarshalText implements encoding.TextUnmarshaler, copying b into guarded memory. It reads “” as the zero Secret, a missing value, which a generated struct’s FromRaw reports as required.
- func (s Secret) View(f func([]byte))#
View calls f with read-only access to s’s bytes, as
gosecret.Buffer.Viewdoes. It panics on the zero Secret.
go-runtime/fyne#
Imported as mdlfyne. Needs fyne.io/fyne/v2. Only the fyne feature’s
generated code reaches for it, and normally you construct nothing here
yourself: a generated New<Field>Entry() returns a *TimeEntry with the
field’s window already compiled in, and a New<Field>Help() returns a
*HelpButton carrying the field’s desc from the model.
- package gitlab.com/terryp/model/go-runtime/fyne#
Package fyne holds the Fyne widgets omniblack.model generates constructors for, plus the binding adapter callers reach for when a widget’s representation is not the model value verbatim.
The identifiers here are part of the generated code’s public contract: a time field’s generated New<Field>Entry returns a *TimeEntry, and a field’s New<Field>Help returns a *HelpButton.
- func ChainTimeEntries(entries ...*TimeEntry)#
ChainTimeEntries biases a run of time entries to read in order, each one after every filled entry before it. It is what makes a start/end pair read naturally: with entries chained, typing “7” then “9” gives 7:00 PM and 9:00 PM rather than 9:00 AM.
The reference is the running maximum of the earlier readings, so an explicit earlier value (“9am” for the first end of a window) cannot drag a later entry back before the start. A blank or unparseable entry does not advance it.
Chaining only ever sets biases; it never revises an entry’s value. Each edit re-runs the pass so the entries after it read the new state, but the entries themselves keep whatever they were already read as. Editing one field of a chained run therefore leaves the other fields’ values exactly as they were.
Chaining wires each entry’s OnResolved, so set OnResolved before calling this – an existing callback is kept and still runs.
- func TransformBind[S, T any](src binding.Item[S], forward func(S) (T, error), reverse func(T) (S, error)) binding.Item[T]#
TransformBind adapts an existing binding into one carrying a different representation of the same underlying value. Use it when a widget’s text is not the model value verbatim – for example a clock-time entry showing “7pm” backed by a “19:00” string field – where the generated <Field>Item bindings cannot map one-to-one.
Pass the field’s generated <Field>Item as src. forward converts the source value to the widget representation (S -> T); reverse converts it back (T -> S). A reverse error leaves the underlying value unchanged so a widget can hold an unparseable draft while its Validator surfaces the problem, matching the permissive behaviour of the generated <Field>Item setters.
Because binding.String, binding.Bool, binding.Int and binding.Float are aliases for binding.Item[string|bool|int|float64], the result binds directly to the matching widget: TransformBind[string, string](world.ClockItem(), …) yields a binding.String for widget.Entry.Bind.
- func NewHelpButton(help string) *HelpButton#
NewHelpButton returns a help button showing help when tapped. The generated New<Field>Help constructors call it with the field’s description.
- func NewTimeEntry() *TimeEntry#
NewTimeEntry returns a time entry using model.DefaultWindow, for a caller wiring a time input by hand. Prefer the generated New<Field>Entry constructors, which compile in the field’s own window and bind it to the model.
- func NewTimeEntryWithWindow(window model.Window) *TimeEntry#
NewTimeEntryWithWindow returns a time entry resolving ambiguous bare hours against window. The generated New<Field>Entry constructors call it with the window the field declares in the model.
- type HelpButton struct#
HelpButton is a question-mark button that reveals a field’s description in a popup. Tapping it toggles the popup open or closed; tapping anywhere else closes it.
ponytail: click only, no hover. The popup sits on the canvas overlay stack, and that overlay covers the whole canvas and takes hover over from the button, so a hover-opened popup would flicker as soon as the pointer moved: open, mouse-out, close, mouse-in, open. Opening on hover needs a tooltip layer inside the window content, the way fyne-tooltip does it; add that if hover matters.
- Button widget.Button#
- Help string#
Help is the text shown in the popup, compiled in from the field’s desc by the generated New<Field>Help constructors. An empty Help opens nothing.
- func (b *HelpButton) Close()#
Close hides the popup if it is open.
- func (b *HelpButton) Open()#
Open shows the description in a popup directly below the button. It does nothing for an empty Help, for an already-open popup, or for a button that is not on a canvas yet.
- func (b *HelpButton) Shown() bool#
Shown reports whether the popup is currently open. It reads the popup’s own visibility rather than trusting a nil check: tapping outside a non-modal popup has its overlay hide it behind our back, and a stale non-nil popup would make the next tap a no-op.
- func (b *HelpButton) Toggle()#
Toggle opens the popup if it is closed and closes it if it is open. It is the button’s OnTapped.
- type TimeEntry struct#
TimeEntry is a text entry for a time-of-day field. It accepts the loose clock forms ParseClock does (“7”, “7:30”, “7pm”, “7.30p”) and resolves an ambiguous bare hour against two layers of preference: the field’s time Window, compiled in from the model by the generated New<Field>Entry constructors, and a Bias set at runtime from whatever else the form already says.
Both layers decide how an edit is read as it is made. Neither reaches back: a bias arriving after the fact does not re-read text already resolved, so the entry’s value only ever moves in response to its own field being typed in.
Every keystroke is accepted, including text that is not a time at all. While the entry has focus its text is exactly what the user typed, and the reading is shown beside it: whenever the two differ the entry states its reading at its trailing edge, so typing “9” into an evening field shows “9:00 PM” there before anything is saved. The Validator reports anything that does not parse. Only when focus leaves does the entry rewrite its text, in the canonical form of whatever it read – at which point the text says it and the hint clears; text that does not parse is left as typed and stays flagged.
The same reading is available through Resolved, Display, Hint, and the OnResolved callback, for a caller that wants to echo it somewhere else too.
TimeEntry owns the embedded Entry’s OnChanged. Use OnResolved instead; assigning OnChanged replaces the widget’s own handler and stops it working.
- Entry widget.Entry#
- AllowEmpty bool#
AllowEmpty makes a blank entry valid, meaning “unset”. Set automatically by the generated constructor for an optional field.
- OnResolved func(value model.TimeOfDay, filled bool, err error)#
OnResolved is called whenever the entry’s reading changes, with the resolved value, whether the entry was non-blank, and any parse error.
- func (e *TimeEntry) Bind(item binding.Item[model.TimeOfDay])#
Bind two-way binds the entry to a required time field’s item, seeding the text from the item’s current value.
- func (e *TimeEntry) BindOptional(item binding.Item[model.Optional[model.TimeOfDay]])#
BindOptional two-way binds the entry to an optional time field’s item. A blank entry is the unset value and vice versa, so AllowEmpty is implied.
- func (e *TimeEntry) Display() string#
Display renders the entry’s reading on a 12-hour clock (“7:00 PM”), or “” if the entry is blank or does not parse.
- func (e *TimeEntry) FocusGained()#
FocusGained starts an edit: from here until focus is lost the text is the user’s, and neither the model nor the entry’s own reading rewrites it.
- func (e *TimeEntry) FocusLost()#
FocusLost ends the edit and settles the entry: a reading that parses is rewritten in canonical form (“7pm” becomes “7:00 PM”), and text that does not parse is kept as typed with the Validator’s error still showing.
- func (e *TimeEntry) Hint() string#
Hint returns the reading shown at the trailing edge of the entry: the entry’s Display, or “” when the text is blank, does not parse, or already says the reading itself.
- func (e *TimeEntry) Refresh()#
Refresh restates the hint before redrawing, so every path that repaints the entry – a keystroke, a settle, a theme change – shows the current reading.
- func (e *TimeEntry) Resolved() (model.TimeOfDay, bool, error)#
Resolved returns the entry’s current reading: the parsed value, whether the entry was non-blank, and any parse error. A blank entry yields the zero TimeOfDay with filled false. The reading is the one the text was given when it was last edited, so it always agrees with what was written to the bound value, whatever the bias has since become.
- func (e *TimeEntry) SetBias(b model.Bias)#
SetBias steers how an ambiguous entry is read, from what the rest of the form says: a field holding the end of a span passes Bias{After: &start}, which is what makes a bare “9” typed there land in the evening when the span starts at 7:00 PM.
It applies to the next edit only. Text already read keeps the reading it was given – the entry’s value is not revised, and its text is not rewritten – because a field the user is not typing in should not change under them. So a start time moved to the evening after the end was already filled in leaves that end time alone; only what is typed from then on is read the new way.