Documentation
¶
Overview ¶
Package htmlupdate serves HTML templates that can update themselves in place.
One URL answers two ways. Without the render header a request gets the ordinary complete document, so a browser without the runtime, a crawler, and curl are all unaffected. With it, the response carries only the boundaries whose markup actually changed.
The transport concerns live here rather than in htmlbind, because that package stays free of net/http so generated template code keeps working on TinyGo and WebAssembly targets.
Index ¶
- Constants
- Variables
- func DecodeManifest(encoded string) delta.Manifest
- func EncodeManifest(manifest delta.Manifest) string
- func QueryBool(values url.Values, name string, target *bool) error
- func QueryFloat(values url.Values, name string, target *float64) error
- func QueryInt(values url.Values, name string, target *int) error
- func QueryOptional[T any](values url.Values, name string, target **T) error
- func QueryString[T ~string](values url.Values, name string, target *T) error
- func QueryTime(values url.Values, name string, target *time.Time) error
- func QueryURL(values url.Values, name string, target *url.URL) error
- func RuntimeSource() []byte
- func RuntimeVersion() string
- func WriteFailure(w http.ResponseWriter, failure Failure)
- type Asset
- type DeltaStream
- func (s *DeltaStream) Children(instanceID, frame, childrenValidator string, boundaries ...string)
- func (s *DeltaStream) Close() error
- func (s *DeltaStream) ExpectLive()
- func (s *DeltaStream) Fail(message string)
- func (s *DeltaStream) Replace(instanceID, html, frame string, boundaries ...string)
- func (s *DeltaStream) ReplaceValues(instanceID, sequence string, values []string, frame string, ...)
- func (s *DeltaStream) Retry(after time.Duration) error
- func (s *DeltaStream) Sent(instanceID string) bool
- func (s *DeltaStream) Settled(boundaryID string, html []byte)
- func (s *DeltaStream) Unchanged(instanceID, frame, childrenValidator string)
- type Failure
- type FailureKind
- type Mode
- type Negotiated
- type Options
- func (o Options) CSRFToken(r *http.Request) string
- func (o Options) Mount(router Router)
- func (o Options) Negotiate(r *http.Request) Negotiated
- func (o Options) OpenLiveStream(w http.ResponseWriter, head []string) *DeltaStream
- func (o Options) OpenStream(w http.ResponseWriter, head []string) *DeltaStream
- func (o Options) Redraw(w http.ResponseWriter, r *http.Request, reg *Registry, ...) bool
- func (o Options) Render(w http.ResponseWriter, r *http.Request, wrappers []htmlbind.Wrapper, ...) error
- func (o Options) RenderLiveStream(ctx context.Context, w http.ResponseWriter, r *http.Request, ...) error
- func (o Options) RenderStream(w http.ResponseWriter, r *http.Request, wrappers []htmlbind.Wrapper, ...) error
- func (o Options) RenderStreamAsync(ctx context.Context, w http.ResponseWriter, r *http.Request, ...) error
- func (o Options) RuntimeAsset() Asset
- func (o Options) RuntimeConfig() RuntimeConfig
- func (o Options) RuntimeConfigFor(csrfToken string) RuntimeConfig
- func (o Options) RuntimeHandler() http.Handler
- func (o Options) RuntimePath() string
- func (o Options) ScriptTag() string
- func (o Options) ScriptTagFor(csrfToken string) string
- func (o Options) Sequence(w http.ResponseWriter, r *http.Request) bool
- func (o Options) Validate() error
- func (o Options) VerifyCSRF(r *http.Request, expected string) error
- func (o Options) WantsUpdate(r *http.Request) bool
- func (o Options) WriteNavigate(w http.ResponseWriter, url string) error
- func (o Options) WriteUpdate(w http.ResponseWriter, r *http.Request, updates []Update, ...) error
- func (o Options) WriteUpdateStatus(w http.ResponseWriter, r *http.Request, status int, updates []Update, ...) error
- type QueryError
- type Registry
- type Reloadable
- type Router
- type RuntimeConfig
- type Update
Constants ¶
const DefaultCSRFFieldName = "_csrf"
DefaultCSRFFieldName is the hidden field generated forms carry. It matches the generator's own default, because the two have to agree: one writes the field and the other reads it.
const DefaultCSRFHeaderName = "X-CSRF-Token"
DefaultCSRFHeaderName is where the runtime puts the token. Unlike the render and manifest headers it does not follow HeaderPrefix, because this one is a name middleware already looks for rather than a namespace this module owns.
const DefaultDataAttributePrefix = "tb"
DefaultDataAttributePrefix names the attributes the protocol puts in a document. It matches the generator's own default, because the two have to agree: one writes the attributes and the other reads them.
const DefaultGlobalName = "tinybind"
DefaultGlobalName is what the browser runtime is installed under.
const DefaultHeaderPrefix = "X-Tinybind"
DefaultHeaderPrefix names the request and response headers.
const DefaultMaxManifestBytes = 8 << 10
DefaultMaxManifestBytes bounds the validators a request may carry. Beyond it the hints are dropped, which costs bytes in the response instead of risking a proxy rejecting the request.
const DefaultMaxQueryBytes = 4 << 10
DefaultMaxQueryBytes bounds the arguments a redraw may carry, since a GET puts every one of them in the URL. Options.MaxQueryBytes overrides it, for a deployment behind a proxy with its own URL limit.
const DefaultPathPrefix = "/_tb"
DefaultPathPrefix is the URL namespace holding every framework-owned endpoint. Keeping them under one prefix means a deployment can route, cache, or protect the whole surface with one rule.
const DefaultRedrawCacheControl = "private, no-cache"
DefaultRedrawCacheControl keeps a redraw out of every shared cache and makes a private one revalidate.
It is private rather than public because a redraw usually renders per-user content, and no-cache rather than no-store because no-store would forbid the conditional request the ETag exists for: a browser that may not keep the bytes can never ask whether they changed.
const DefaultRuntimeFileName = "tinybind"
DefaultRuntimeFileName names the served runtime file.
const DefaultSequenceCacheControl = "public, max-age=31536000, immutable"
DefaultSequenceCacheControl keeps a sequence forever. It is addressed by a digest of its own content, so a deploy that changes a template produces a new address rather than a new body at the old one, and nothing needs invalidating.
const DefaultStreamContentType = "application/x-ndjson; charset=utf-8"
DefaultStreamContentType marks a delta delivered as a record stream. One JSON record per line, which is the framing the module already uses for streamed values. Options.StreamContentType overrides it.
Variables ¶
var BuildID = sync.OnceValue(func() string { if info, ok := debug.ReadBuildInfo(); ok { var revision string var modified bool for _, setting := range info.Settings { switch setting.Key { case "vcs.revision": revision = setting.Value case "vcs.modified": modified = setting.Value == "true" } } if revision != "" && !modified { return revision[:min(len(revision), 16)] } } return processID() })
BuildID identifies the running binary.
It is the third and last identity in this design, and it does the job the other two deliberately do not:
- the protocol version names the wire contract, and must stay stable across builds or every deploy would make an already-loaded page incompatible
- a component kind names a component, and must stay stable so an unrelated deploy does not invalidate its endpoint
- the build id names this binary, so anything that could change rendering invalidates client state: a template, a Go function a template calls, the render runtime itself, or a dependency
A component kind cannot do this job. It hashes one component's own compiled plan, so it misses a change in a component that one calls, in an external function, and in the framework's own rendering.
The value comes from the version control revision the binary was stamped with. A binary built from a dirty tree, or with no stamping at all, gets a value unique to the process instead: during development every restart should invalidate, and guessing otherwise would serve stale regions while editing.
var ErrCSRFMismatch = errors.New("htmlupdate: CSRF token does not match the session")
ErrCSRFMismatch reports a token that is not the session's.
var ErrCSRFMissing = errors.New("htmlupdate: request carries no CSRF token")
ErrCSRFMissing reports an unsafe request carrying no token at all.
Functions ¶
func DecodeManifest ¶
DecodeManifest reads the compact validator list a client sends back. The encoding is "id:frame" or "id:frame:children" separated by commas, which stays inside one header and needs no escaping because every part is an opaque token.
The third part is what lets a list say its rows moved without its parent being replaced. It is absent for a boundary containing no nested boundary, which is most of them, and a pair with only two parts still reads.
func EncodeManifest ¶
EncodeManifest renders the validator list a client sends back. It exists so a test, and any non-browser client, can produce exactly what the runtime does.
func QueryFloat ¶
QueryFloat decodes a float parameter.
func QueryOptional ¶
QueryOptional decodes a parameter the template declared optional. An absent name is the absent value; a present but undecodable one is still an error.
func QueryString ¶
QueryString decodes any string-kinded parameter, covering plain strings, decimals, and generated enums.
func QueryTime ¶
QueryTime decodes an instant, date, or time parameter in RFC 3339 form, which is the form CanonTime writes and the one a query string can carry unambiguously.
func RuntimeSource ¶ added in v0.3.1
func RuntimeSource() []byte
RuntimeSource is the browser runtime this package implements.
The bytes are the point. A framework that already ships a runtime cannot put two on one document — that would be two boundary id spaces, two build identities, and two script tags with nothing deciding which owns a region — so it merges ours into its own asset. Without readable bytes, merging means keeping a copy, and a copy is not a version-pinned dependency: it drifts on upgrade with nothing in the build failing, and a drifted browser runtime is a silently dead page rather than a compile error.
The bytes carry no naming choice. The runtime reads its attribute prefix, header namespace, endpoint prefix, and installed name from the configuration it is given, so one asset serves every deployment and merging it needs no build step. RuntimeConfig produces that configuration; the file installs createPartialUpdateRuntime for a caller constructing an instance directly.
func RuntimeVersion ¶
func RuntimeVersion() string
RuntimeVersion is the content identity of the browser runtime. It appears in the runtime path so a new build gets a new URL.
func WriteFailure ¶ added in v0.3.1
func WriteFailure(w http.ResponseWriter, failure Failure)
WriteFailure writes the response this package writes when no caller took over. It is exported so a caller that only wants to observe a failure can log it and delegate the response, rather than reimplementing five status codes.
The body is RFC 9457 problem details, which is this module's documented error format everywhere else; the update endpoints were the only paths writing plain text. The media type is what tells the two apart on the wire: application/json is an update to apply, including a non-2xx one, and application/problem+json is a request that produced no update at all.
The status still directs. A client's rule — any non-2xx falls back to an ordinary navigation — is unchanged, so a client that cannot read the body still lands correctly; the body adds diagnosis rather than direction.
Types ¶
type Asset ¶ added in v0.3.1
type Asset struct {
// Source is the file's content.
Source []byte
// Version is the content digest. Two builds with the same digest are the
// same file, and a changed digest is a changed URL.
Version string
// ContentType is the media type the file must be served as.
ContentType string
// FileName is the name this package would serve it under, which a caller
// serving it elsewhere may ignore.
FileName string
}
Asset is one static file this package requires a page to load.
The module decides what the bytes are and what identifies them; the caller decides where they are served, under what name, and with what cache policy.
type DeltaStream ¶
type DeltaStream struct {
// contains filtered or unexported fields
}
DeltaStream is an open record stream a producer writes boundary completions to as they settle.
It exists so the transport and the producer stay separate. A synchronous delta drives it today; an asynchronous render sequence drives it by calling Replace once per completion, which makes wiring one in a call rather than a redesign.
func (*DeltaStream) Children ¶ added in v0.4.5
func (s *DeltaStream) Children(instanceID, frame, childrenValidator string, boundaries ...string)
Children writes a boundary whose own markup is unchanged and whose nested boundaries are now these, in this order.
It carries no markup, which is the point: appending one row to a list costs the list of ids rather than the list of holes. A client keeps what the list keeps, moving what moved, drops what it omits, and fills what arrives as its own operation in the same response.
func (*DeltaStream) Close ¶
func (s *DeltaStream) Close() error
Close writes the terminator. Without it the client treats the stream as truncated and discards its manifest, so a producer must always reach here.
The terminator names which ending this is: a navigation says whether a live request should follow, and a live stream says whether the client should come back. A close with no reason would make a healthy lifetime rollover indistinguishable from a fault, so a client would back off on both and stall a working screen every time the server rotates a connection.
func (*DeltaStream) ExpectLive ¶ added in v0.3.3
func (s *DeltaStream) ExpectLive()
ExpectLive marks this stream's terminator as handing off to a live request, which a navigation does when the route it just described owns a live boundary.
Without it a client either opens a speculative live request on every navigation — one full page execution per screen that will never deliver anything — or the caller hardcodes which routes are live.
func (*DeltaStream) Fail ¶
func (s *DeltaStream) Fail(message string)
Fail reports a failure that happened after the response committed. The status is already sent, so this is the only way to say so.
func (*DeltaStream) Replace ¶
func (s *DeltaStream) Replace(instanceID, html, frame string, boundaries ...string)
Replace writes one settled boundary, the validator it produced, and the nested boundaries appearing as holes in its markup.
A hole whose id also arrives as an operation on this stream is filled from it; one that does not is a region the client already holds and moves in. The list is what separates the two, since nothing in the markup does.
func (*DeltaStream) ReplaceValues ¶ added in v0.4.4
func (s *DeltaStream) ReplaceValues(instanceID, sequence string, values []string, frame string, boundaries ...string)
ReplaceValues is Replace for a client that walks sequences: the fragment travels as the address of its static half and the values that fill it, so the statics cost one response per client rather than one per render.
func (*DeltaStream) Retry ¶ added in v0.3.3
func (s *DeltaStream) Retry(after time.Duration) error
Retry closes a healthy stream the server chose to end: a lifetime bound, a shutdown, a rebalance. The client reconnects promptly instead of backing off, because nothing failed.
after is the server's own hint for how long to wait. Zero leaves the delay to the client, which is the right answer for an ordinary rollover; a server shedding load or rolling a deploy is the only party that knows to spread the return, so it is the only one that can fill this in.
Calling it on a navigation stream is a mistake this package does not guard against, because a navigation has nothing to reconnect to; it is here for the live path, where a bare close cannot mean stop.
func (*DeltaStream) Sent ¶
func (s *DeltaStream) Sent(instanceID string) bool
Sent reports whether an instance already appeared, so a producer emitting completions out of order does not restate one it already wrote.
func (*DeltaStream) Settled ¶
func (s *DeltaStream) Settled(boundaryID string, html []byte)
Settled writes an await boundary that finished after the initial pass.
It addresses a placeholder inside a region the client already installed, which is a different namespace from an instance id, so it is its own record kind rather than an operation with a surprising target.
func (*DeltaStream) Unchanged ¶
func (s *DeltaStream) Unchanged(instanceID, frame, childrenValidator string)
Unchanged restates a boundary's validator without markup, so the client can rebuild its whole manifest from what it received.
type Failure ¶ added in v0.3.1
type Failure struct {
// Kind is why the request was refused.
Kind FailureKind
// Status is the response status this package would have written.
Status int
// Message is the plain-text body this package would have written. It never
// contains anything the request supplied, so it is safe to send as is.
Message string
// Err is the underlying cause, when there is one. A decoder rejection and a
// render failure carry theirs; a stale page has none, because nothing
// failed.
//
// It may name internal detail, so it belongs in a log rather than in a
// response body.
Err error
// KindID and InstanceID name what was asked for, when the path was
// well-formed enough to say. Both are attacker-supplied, so treat them as
// untrusted when they reach a log.
KindID string
InstanceID string
}
Failure is one request an update endpoint could not answer.
This package has to write a response, because it owns the endpoint. It does not have to decide what a failure looks like, which is why the whole value reaches the caller instead of a status and a line of plain text reaching the client. A caller with problem responses, its own error pages, a request-scoped logger, or a tracer sees every one of these.
type FailureKind ¶ added in v0.3.1
type FailureKind int
FailureKind names why an update endpoint could not answer.
The kind is what a caller branches on. The status and the message are defaults it may keep or replace, but the kind is the fact: a stale page and a failed render are the same 4xx-or-5xx to a proxy and completely different events to whoever is on call.
const ( // FailureMalformedRequest is a redraw that named no component: the mode said // redraw and the kind or instance header was missing or empty. FailureMalformedRequest FailureKind = iota // FailureUnknownComponent is a kind this deployment does not publish. // // It is the ordinary version-skew signal: a page loaded before a deploy // asks for a component whose markup has since changed, gets a 404, and // reloads. A sustained rate of it after a deploy has settled means // something else. FailureUnknownComponent // FailureArgumentsTooLarge is a query past the configured bound. FailureArgumentsTooLarge // FailureInvalidArguments is a query the generated decoder refused. FailureInvalidArguments // FailureRenderFailed is a component that could not render. FailureRenderFailed )
func (FailureKind) String ¶ added in v0.3.1
func (k FailureKind) String() string
String names the kind for a log line or a span attribute.
type Mode ¶
type Mode int
Mode is the rendering a request asked for.
const ( // ModeDocument is the complete HTML document. It is what a request without // a usable render header gets, including one from an incompatible client. ModeDocument Mode = iota ModeNavigation // ModeLive returns the deliveries of the same route's live boundaries, on a // response held open for as long as the subscriptions live. // // It is its own mode rather than a navigation held open because the two // differ in duration and in termination: a navigation ends when the route has // been described, a live response ends when every source finishes or when the // server reaches a lifetime bound. Sharing one name meant a deployment could // not route, time out, or bound them separately, and a served-mode log could // not tell an hours-long subscription from ordinary navigation traffic. ModeLive // ModeRedraw returns one registered component's subtree, addressed by the // kind and instance headers rather than by the URL path. // // It is a request mode so a caller can answer a redraw at any URL it likes. // Usually that is the page the component sits on, where the redraw inherits // the page's own authorization rather than needing a second path pattern kept // in step with the one protecting the page — two rules that must agree and // that nothing forces to agree. ModeRedraw // ModeSequence returns the static half of one fragment, addressed by a // digest of its own content. // // It is the one response in this package that is not per user: a sequence // derives from the template rather than from a request, so it is the only // one that can be public, immutable, and held by a shared cache. ModeSequence )
type Negotiated ¶
type Negotiated struct {
Mode Mode
// Version is whatever the client wrote after "v=" in the render header, or
// zero when it wrote none. This package neither defines it nor compares it:
// the browser client belongs to the caller, so the caller owns its wire
// version and what a mismatch means. It is carried so a caller that does
// version its wire can read it, and it is echoed back on the response.
//
// The compatibility axis this package still operates is the build identity,
// whose value Options.BuildID already makes the caller's.
Version int
// Known holds the validators the client already has. It is empty on a
// client's first update, which simply yields a larger delta.
Known delta.Manifest
}
Negotiated is what a request asked for, after validation.
type Options ¶
type Options struct {
// Key authenticates validators. Two renders that are to be compared must
// use the same key; rotating it forces complete documents, which is the
// intended effect of a rotation.
//
// An unkeyed digest of low entropy content lets anyone confirm a guess by
// comparing digests, so a deployment serving non-public pages must set it.
Key []byte
// HeaderPrefix overrides the header namespace. Empty uses
// DefaultHeaderPrefix. The runtime reads it from its configuration, so
// overriding it needs no rebuilt runtime.
HeaderPrefix string
// DataAttributePrefix overrides the attribute namespace. Empty uses
// DefaultDataAttributePrefix.
//
// It must match the generator's own DataAttributePrefix, because that is
// what wrote the instance attributes into the markup this runtime reads.
// It also names the preserve and ignore markers an application author
// writes by hand, which is why a framework needs to own it: those are the
// author's surface, not a wire detail.
DataAttributePrefix string
// GlobalName overrides the name the browser runtime is installed under.
// Empty uses DefaultGlobalName.
//
// A framework sets it so its users call the framework's own name rather
// than a dependency's.
GlobalName string
// RuntimeFileName overrides the base name of the served runtime asset.
// Empty uses DefaultRuntimeFileName. The content digest and the .js suffix
// are appended either way, so the URL stays immutably cacheable.
RuntimeFileName string
// CallerOwnsRuntime says the caller ships its own browser runtime, so this
// package serves and references none: Mount registers no asset route and
// ScriptTag returns nothing.
//
// Usually that runtime is this one, merged into a larger asset from
// RuntimeSource. Two runtimes on one document would mean two boundary id
// spaces and two build identities, so a framework that already has one takes
// this rather than adding a second.
CallerOwnsRuntime bool
// ServeRuntime asks this package to serve the reference browser runtime at a
// content-hashed URL and to write the script tag that loads it.
//
// It is off by default, which is the whole of the difference from earlier
// versions: the browser half belongs to the caller, so serving one is
// something a deployment asks for rather than something it inherits.
//
// Exactly one of this and CallerOwnsRuntime must be set, and Validate says so
// at startup. A build that set neither would compile and then serve pages
// that silently stop updating, which is the worst failure shape available
// here: nothing fails, the page is just quietly dead.
ServeRuntime bool
// CSRFFieldName is the hidden field generated forms carry. Empty uses
// DefaultCSRFFieldName.
//
// It must match the generator's own CSRFFieldName, because that is what
// wrote the field into the markup this reads back: one writes it and the
// other reads it, and nothing links the two at compile time.
CSRFFieldName string
// CSRFHeaderName overrides the header the browser runtime puts the CSRF
// token in. Empty uses DefaultCSRFHeaderName.
//
// It does not follow HeaderPrefix on purpose: the render, manifest, and
// build headers name this protocol, and this one names a convention every
// framework's middleware already looks for.
CSRFHeaderName string
// PathPrefix overrides the URL namespace of every framework endpoint.
// Empty uses DefaultPathPrefix. Unlike the header names, the runtime learns
// this one at load time, so overriding it needs no rebuilt runtime.
PathPrefix string
// BuildID overrides the identity of the running binary. Empty uses
// BuildID(), which is the version control revision the binary was stamped
// with, or a per-process value when the tree was dirty or unstamped.
//
// A page rendered by a different build has client state this binary cannot
// vouch for, so it is served a complete document instead of a delta.
BuildID string
// MaxManifestBytes caps the manifest header a request may carry. Zero uses
// DefaultMaxManifestBytes. An oversized manifest is ignored rather than
// rejected, so the response is a larger delta instead of an error.
MaxManifestBytes int
// MaxQueryBytes caps the arguments a redraw may carry. Zero uses
// DefaultMaxQueryBytes. Unlike an oversized manifest an oversized query is
// rejected, because the arguments are the request rather than a hint.
MaxQueryBytes int
// SequenceCacheControl overrides the cache policy of a sequence response.
// Empty uses DefaultSequenceCacheControl, which keeps it forever because the
// address is a digest of the body.
SequenceCacheControl string
// RedrawCacheControl overrides the cache policy of a redraw response. Empty
// uses DefaultRedrawCacheControl.
//
// A caller relaxing it takes responsibility for what a redraw renders: the
// arguments come from the browser, so the component authorizes its own
// inputs, and a cache keyed on the URL alone would serve one user's render
// to another.
RedrawCacheControl string
// StreamContentType overrides the media type of a streamed delta. Empty
// uses DefaultStreamContentType.
//
// This one names the wire format rather than a limit, so overriding it is a
// framing choice a client has to agree with, not a tuning knob.
StreamContentType string
// OnFailure receives every request an endpoint of this package could not
// answer, and writes the response for it. Nil writes the plain-text
// response WriteFailure writes.
//
// This package owns the endpoint, so it has to write something; it does
// not have to decide what a failure looks like. A caller with problem
// responses, its own error pages, a request-scoped logger, or a tracer
// takes the whole Failure and answers however it answers everything else.
//
// A hook must write a response, exactly as a handler must. Delegating to
// WriteFailure after logging is the cheapest way to keep the default body.
OnFailure func(w http.ResponseWriter, r *http.Request, failure Failure)
}
Options configure one set of update endpoints.
func (Options) CSRFToken ¶ added in v0.3.3
CSRFToken reads the token a request carries, header first and form body second.
The order is not arbitrary. The header is what the runtime sends and the only channel a non-form body has; the field is the fallback for a submission made without script. Reading the header first also means an ordinary fetch never pays for parsing a body it does not have.
Reading the field consumes the request body through ParseForm, as any handler reading a form does.
func (Options) Mount ¶
Mount registers every endpoint this package owns under the configured path prefix, which is now the runtime asset and nothing else.
It takes no registry, because a redraw is no longer an endpoint this package mounts: the caller answers one from its own handler with Options.Redraw, at whatever URL it chooses. That is the whole point of the change — an endpoint the caller routes, protects, and logs should have an address the caller picked.
The asset is registered only when this build serves it; see Options.ServeRuntime.
func (Options) Negotiate ¶
func (o Options) Negotiate(r *http.Request) Negotiated
Negotiate resolves how a request must be answered.
Anything unrecognized resolves to ModeDocument rather than to an error: a stale client, a truncated header, and a proxy that dropped a header must all still produce a working page. That is a total function on the mode name rather than a version comparison, so it holds with no version at all.
func (Options) OpenLiveStream ¶ added in v0.3.3
func (o Options) OpenLiveStream(w http.ResponseWriter, head []string) *DeltaStream
OpenLiveStream commits a delivery stream: the same records on the same framing, in the live mode rather than the navigation one.
The difference a caller sees is the ending. A navigation stream closes final, having described the route; a live stream closes done when every source finished, or retry when the server closed a healthy response at a lifetime bound. A client keys its retry policy on that rather than on the fact that the stream ended.
func (Options) OpenStream ¶
func (o Options) OpenStream(w http.ResponseWriter, head []string) *DeltaStream
OpenStream commits the response and writes the head record.
Everything that could change the status has to be decided before this call, because after it the status is fixed and a failure can only be reported in band through Fail.
func (Options) Redraw ¶ added in v0.3.5
func (o Options) Redraw(w http.ResponseWriter, r *http.Request, reg *Registry, options ...htmlbind.Option) bool
Redraw answers a redraw request at whatever URL the caller serves it from, and reports whether it did.
It is the entry a caller branches on inside its own page handler:
func page(w http.ResponseWriter, r *http.Request) {
if options.Redraw(w, r, registry) {
return
}
// ordinary page render
}
Addressing it at the page's own URL is the point. Path protection is configured by path pattern, so a redraw on a reserved path needs its own pattern maintained in parallel with the one protecting the page the component sits on — two rules that must agree and that nothing forces to agree. At the page URL the redraw inherits that protection automatically, and placed after the handler's own checks it inherits those too, not merely the middleware's.
A request that is not a redraw returns false with nothing written, including a request from a page another build rendered: at a page URL the right answer to a stale redraw is that page, which the caller is about to render anyway, and that costs a reload rather than a refusal and then a reload.
options reach the component's render, so a redraw sees the same cache store, URL scheme policy, and CSRF token the page render was given. Without them a component renders one way inside its page and another in the response that replaces it — and one containing an unsafe form does not render at all, since htmlbind.Builder.CSRFField needs a token. The boundary prefix and the build identity are supplied from these Options and do not need passing.
func (Options) Render ¶
func (o Options) Render(w http.ResponseWriter, r *http.Request, wrappers []htmlbind.Wrapper, leaf htmlbind.Fragment) error
Render answers one request with either a complete document or a delta.
It always sets Vary, because a cache that served a delta body to a document request would hand a browser a page of JSON. The caller keeps every other response concern, as elsewhere in this module.
func (Options) RenderLiveStream ¶
func (o Options) RenderLiveStream(ctx context.Context, w http.ResponseWriter, r *http.Request, wrappers []htmlbind.Wrapper, leaf htmlbind.Fragment, options ...htmlbind.Option) error
RenderLiveStream is RenderStreamAsync for a chain holding live sources: in the live mode it keeps every subscription open and writes each delivery as it arrives.
The mode is what decides. A navigation asks what this route looks like now, so a live boundary settles in place and the response ends; a live request asks for the deliveries, so the response stays open. Serving both from one entry is what keeps the reconnect path and the render path the same code — the reason a reconnect needs no cursor, no event log, and no replay.
Reconnecting after a dropped stream is the same request again. Nothing has to be resumed, because a live delivery carries the whole state of its region rather than an increment, so a missed one costs nothing and boundary ids are reproduced by position.
func (Options) RenderStream ¶
func (o Options) RenderStream(w http.ResponseWriter, r *http.Request, wrappers []htmlbind.Wrapper, leaf htmlbind.Fragment) error
RenderStream answers a navigation with a record stream instead of one buffered body, so each region applies as soon as it is written.
Everything that could change the status is decided before the first record, because writing it commits the response. After that a failure can only be reported in band.
func (Options) RenderStreamAsync ¶
func (o Options) RenderStreamAsync(ctx context.Context, w http.ResponseWriter, r *http.Request, wrappers []htmlbind.Wrapper, leaf htmlbind.Fragment, options ...htmlbind.Option) error
RenderStreamAsync answers a navigation with a record stream that also carries await boundaries as they settle.
Each region reaches the browser with its fallback in place and is replaced when its dependency finishes, so a slow one delays only itself. A chain with no await boundary produces exactly what RenderStream does.
This entry serves the document and navigation modes. A live request reaching it is answered as a navigation and terminated final, so a client that opened a live connection to a route this caller does not serve live learns so at once instead of holding a connection that will never deliver.
func (Options) RuntimeAsset ¶ added in v0.3.1
RuntimeAsset is the browser runtime as a static asset, for a caller that serves its own files.
func (Options) RuntimeConfig ¶ added in v0.3.1
func (o Options) RuntimeConfig() RuntimeConfig
RuntimeConfig is the configuration matching these options, so the server and the browser cannot disagree about a name.
It carries no CSRF token: a token belongs to a session and these options belong to the process. Use RuntimeConfigFor to add one.
func (Options) RuntimeConfigFor ¶ added in v0.3.3
func (o Options) RuntimeConfigFor(csrfToken string) RuntimeConfig
RuntimeConfigFor is RuntimeConfig carrying this session's CSRF token, so the runtime sends it on every request it issues.
The header is the channel for anything the runtime fetches; the hidden field generated into each form is the channel for a submission with no script. They carry the same value, which is what a header carrying exactly one value requires of the token: one per session.
func (Options) RuntimeHandler ¶
RuntimeHandler serves the browser runtime.
A caller owning the runtime serves its own asset and never calls this; see Options.CallerOwnsRuntime and RuntimeSource.
func (Options) RuntimePath ¶
RuntimePath is the URL the browser runtime is served from. The version segment makes the response immutable, which is why the handler may set a long max-age.
func (Options) ScriptTag ¶
ScriptTag is the element loading the runtime, ready to place at the end of a document body.
The caller injects it, because this milestone has no document shell bootstrap. The tag carries the whole runtime configuration, so one shared asset works for any set of names without being rebuilt.
A caller owning the runtime gets an empty string: a tag pointing at an asset this build does not serve is worse than no tag at all.
func (Options) ScriptTagFor ¶ added in v0.3.3
ScriptTagFor is ScriptTag carrying this session's CSRF token, which is what a handler that renders forms uses.
func (Options) Sequence ¶ added in v0.4.4
Sequence answers a request for one sequence tree, and reports whether it did.
It is the entry a caller branches on inside its own handler, exactly as Redraw is, so the address a client asks at is the caller's to choose and this package mounts nothing:
func page(w http.ResponseWriter, r *http.Request) {
if options.Sequence(w, r) {
return
}
// ordinary page render
}
An address this process has never rendered is answered 404, and a client falls back to asking for the assembled form it can always be sent instead. That is the whole recovery path: a sequence is an optimisation over markup that is still available, never a thing a screen depends on.
func (Options) Validate ¶ added in v0.3.1
Validate reports every option this package cannot use, so a caller running a startup validation pass hears about all of them at once rather than finding the first one in a browser.
Nothing calls it automatically: an Options value is a struct literal, so there is no constructor to fail in, and a handler is the wrong place to discover a configuration mistake.
func (Options) VerifyCSRF ¶ added in v0.3.3
VerifyCSRF compares what a request carries against the session's token.
expected is the caller's to produce, from wherever its session lives. An empty expected is refused rather than treated as "nothing to check": a session lookup that quietly returned nothing would otherwise disable the whole control for exactly the requests that most need it.
This is a token check and nothing else. Origin and Fetch Metadata validation belong to middleware that sees the request before any of this — Go's own http.CrossOriginProtection is what wraps a handler with them — and they are worth having: the two defenses fail for unrelated reasons, which is the point of running both.
func (Options) WantsUpdate ¶
WantsUpdate reports whether the caller can apply an update response.
An ordinary form submission cannot, so a handler branches on this and redirects instead, which is what keeps a page working without JavaScript.
func (Options) WriteNavigate ¶
func (o Options) WriteNavigate(w http.ResponseWriter, url string) error
WriteNavigate tells the browser to leave the page, which is how an action that changed where the user belongs stays correct without guessing which regions to rewrite.
func (Options) WriteUpdate ¶
func (o Options) WriteUpdate(w http.ResponseWriter, r *http.Request, updates []Update, options ...htmlbind.Option) error
WriteUpdate answers a mutating request with the regions it changed, so one round trip both performs the action and refreshes the page.
The body is the same shape a redraw returns, so the browser applies it with the same code. Unlike a redraw this request is not idempotent: it carries ambient credentials, so it needs CSRF protection, and its response is never cacheable.
options reach every region's render. The token one matters most here: a region holding an unsafe form emits a CSRF field, and without a token that render fails outright — which is this entry's own headline case, since rewriting a form with its validation errors is what it exists for.
func (Options) WriteUpdateStatus ¶
func (o Options) WriteUpdateStatus(w http.ResponseWriter, r *http.Request, status int, updates []Update, options ...htmlbind.Option) error
WriteUpdateStatus is WriteUpdate with an explicit status, so a failed validation can return 422 and still rewrite the form region with its errors.
The browser applies an update response whatever the status says, because rendering the failure is the point.
type QueryError ¶ added in v0.4.4
type QueryError struct {
// Parameter is the declared name the request got wrong.
Parameter string
// Reason completes the sentence "redraw parameter <name> …", so it reads
// the same in a log line and in a problem response.
Reason string
}
QueryError is a redraw parameter the decoder refused, naming which one.
The name is what makes a refusal answerable: a failure response reports the parameter as a field-level error rather than one line of prose a caller would have to parse. The reason never quotes the value, because the value is attacker-supplied and the response is not the place to reflect it.
func (*QueryError) Error ¶ added in v0.4.4
func (e *QueryError) Error() string
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry holds the components a deployment publishes for redraw.
Nothing is registered implicitly. Being exported, single-rooted, and renderable is not enough, because publishing an endpoint must be deliberate.
func (*Registry) MustRegister ¶ added in v0.3.1
func (reg *Registry) MustRegister(component Reloadable)
MustRegister is Register for a caller with nowhere to return an error, such as a package-level registry value.
func (*Registry) Register ¶
func (reg *Registry) Register(component Reloadable) error
Register adds a component to the redraw surface.
A repeated kind is refused rather than overwritten. The kind covers a component's name, parameters, and compiled markup but not its package, so two identical templates in different packages produce the same one; silently keeping the last registration would then serve a component that looks the same but calls its own package's external functions.
This must fail at startup, and failing at startup is not the same as panicking: a caller running its own startup validation pass collects what is wrong and reports all of it, rather than aborting the process on the first one. So the failure is returned, and a caller that wants the abort still has it one line away.
func (*Registry) RequiredAssets ¶ added in v0.3.3
RequiredAssets is every registered component's required files, deduplicated by identity and in registration order. It is RequiredHead read as identity rather than as markup, for a caller deciding where each file is served.
func (*Registry) RequiredHead ¶ added in v0.3.3
RequiredHead is every registered component's head contribution, deduplicated and in registration order.
It is what a caller puts in its document shell. A redraw addresses a region on a page this endpoint did not render, so it can only swap markup into a head somebody else already wrote; a component whose stylesheet is not there renders unstyled, and nothing about the swap can repair that afterwards.
Reading it needs no request and no render, so a document shell built once at startup covers every redraw the deployment will ever serve.
type Reloadable ¶
type Reloadable struct {
// KindID is the generated component identity, name plus a hash of its
// parameters and compiled plan. Editing the template changes it, so a page
// loaded before a deploy requests a kind that no longer exists.
KindID string
// Render decodes the query values and returns the bound component. It is
// generated code: the decoder is typed, and an unknown name or an
// undecodable value is an error rather than a zero value.
Render func(r *http.Request, instanceID string, values url.Values) (htmlbind.Fragment, error)
// Head is what this component contributes to a document head: the merged,
// ready-to-write tags of the component and everything it calls.
//
// A redraw rewrites a region of a page this endpoint never rendered, so
// unlike a navigation it cannot merge into a head it owns. Publishing the
// contribution is what lets a caller put it in the document shell before
// anything is swapped, which is the only way nothing is fetched mid-swap.
Head []string
// Assets names the static files this component requires. It is Head read as
// identity rather than as markup, which is what a caller needs to decide
// whether the page already carries them.
Assets []htmlbind.Asset
}
Reloadable is one component published as a redraw endpoint.
Registering a component publishes an HTTP endpoint whose parameters anyone can supply, so the component authorizes its own inputs exactly as an ordinary handler does. Registration is the review point: a component that only formats values handed to it is safe, while one that loads a record by identifier must check ownership itself.
type Router ¶ added in v0.3.1
Router is what Mount installs on.
It names the one method Mount uses, so a framework with its own router passes it directly instead of losing the call. *http.ServeMux satisfies it, which is what keeps every existing call site compiling: naming a concrete type here made the convenience uncallable from exactly the callers who most wanted the whole surface installed by one rule.
type RuntimeConfig ¶ added in v0.3.1
type RuntimeConfig struct {
// Build is the identity of the binary that rendered the page.
Build string `json:"build"`
// Attr is the data-attribute prefix, which names the instance attribute the
// runtime locates by and the preserve and ignore markers authors write.
Attr string `json:"attr"`
// Header is the header namespace the render, manifest, and build headers
// are derived from.
Header string `json:"header"`
// Global is the name the runtime instance is installed under. Empty
// installs nothing, which is what a caller using only the factory wants.
Global string `json:"global"`
// CSRFHeader is the header the runtime puts the token in. It is not derived
// from Header, because X-CSRF-Token is a name every framework already
// recognizes rather than one this module owns.
CSRFHeader string `json:"csrfHeader,omitempty"`
// CSRF is the session's token. It is empty for a deployment that turned the
// token off, and then the runtime sends no header, so a page without one is
// byte-identical to what it was before this existed.
//
// A token in a data attribute is readable by script, which is the same
// exposure the hidden field in every form already has. It is not what
// protects against XSS: script that runs in the page can act as the user
// whether or not it can read this.
CSRF string `json:"csrf,omitempty"`
}
RuntimeConfig is what the browser runtime reads to learn its own names.
It is exported because a framework merging the runtime into its own asset builds the same object and passes it to the factory directly, rather than reproducing the field names from the JavaScript.