Documentation
¶
Overview ¶
Package cruflags is the Go client for Cru's pipeline feature-flag service.
The service publishes one small JSON document per app per environment. The pipeline's app modules put its URL in CRU_FLAGS_URL in release-candidate and production; local development, CI, preview and lab have no flag document and no variable, and there every flag is off.
import cruflags "github.com/CruGlobal/cru-flags"
func main() {
// Optional: wait for the first fetch, so the first requests after a
// deploy see real flags instead of every flag off.
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
cruflags.Ready(ctx)
cancel()
// ...
if cruflags.Enabled("checkout_v2") {
// ...
}
}
Enabled is a memory lookup. It never blocks, never fails and never panics, and anything other than "Enabled": true in the document reads off, including a flag the document does not name. Flags are created and flipped with `cru app flags`; this package only reads them.
How the document stays current ¶
By default a goroutine polls every 30 seconds, plus or minus 20% jitter, sending If-None-Match so an unchanged document costs a 304. A failed poll changes nothing: the last good document is served for as long as the outage lasts, and flags never fall back to off. A 404 means the app has no flags yet; every flag is off and nothing is logged. Health is logged on transitions only, once when polling starts failing and once when it recovers, through slog.Default() unless Options.OnError says otherwise.
AWS Lambda and Cloud Run ¶
A runtime that freezes the process between requests stops the poller's clock too. Set CRU_FLAGS_REFRESH_MODE=on-demand (or Options.RefreshMode) and the client runs no goroutine: a read that finds the document 30 seconds old starts a refresh in the background, and Refresh fetches and waits, at most once per interval. On Lambda, call Ready during init and Refresh at the top of the handler:
func init() {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
cruflags.Ready(ctx)
}
func handler(ctx context.Context, event Event) (Response, error) {
cruflags.Refresh(ctx)
if cruflags.Enabled("checkout_v2") {
// ...
}
}
Tests ¶
Code under test can take a *Client and be handed one built with New and an Options.URL pointing at an httptest server. With CRU_FLAGS_URL unset, the package-level functions answer every flag off and make no requests.
The behavior shared with the TypeScript, Python and Ruby clients is specified by the conformance suite in this repository, and the reasoning behind each decision is in docs/go/design.md.
Example ¶
The usual setup: wait briefly for the first fetch at startup, then read flags anywhere. With CRU_FLAGS_URL unset, as in this example, every flag is off and nothing is fetched.
package main
import (
"context"
"fmt"
"time"
cruflags "github.com/CruGlobal/cru-flags"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
cruflags.Ready(ctx)
cancel()
if cruflags.Enabled("checkout_v2") {
fmt.Println("new checkout")
} else {
fmt.Println("old checkout")
}
}
Output: old checkout
Index ¶
Examples ¶
Constants ¶
const ( // URLEnvVar holds the flag document URL. The pipeline's app modules set it // in release-candidate and production; everywhere else it is unset. URLEnvVar = "CRU_FLAGS_URL" // RefreshModeEnvVar selects "background" or "on-demand" refresh for a // client whose Options.RefreshMode is empty. RefreshModeEnvVar = "CRU_FLAGS_REFRESH_MODE" // MaxBodyBytes caps a response body. A larger 200 is a failed fetch, so a // misbehaving endpoint cannot exhaust memory. Matches the other clients. MaxBodyBytes = 1 << 20 )
const Version = "0.3.0" // x-release-please-version
Version is this package's release, sent in the User-Agent header. Go resolves the module's version from its git tag; this constant only mirrors it, and release-please moves both together.
Variables ¶
This section is empty.
Functions ¶
func Enabled ¶
Enabled reports whether a flag is on, using the default client. See Client.Enabled.
func Ready ¶
Ready waits for the default client's first fetch to settle. See Client.Ready.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client reads one flag document. Build it with New, or use the package's default client through Enabled, Ready, Refresh and Snapshot.
A Client does nothing until its first Enabled, Ready, Refresh or Snapshot call: no environment read, no request, no goroutine. That first call reads the configuration, starts the first fetch and, in Background mode, the poller.
The zero value is ready to use and behaves like New(Options{}). Every method is safe for concurrent use, and safe on a nil *Client, which behaves as an inert client.
func Default ¶
func Default() *Client
Default returns the client behind the package-level functions, for code that takes a *Client.
func New ¶
New returns an inert Client. Nothing happens until it is first used.
Example ¶
A client of your own, for tests or for code that takes a *Client.
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
cruflags "github.com/CruGlobal/cru-flags"
)
func main() {
service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("ETag", `"3"`)
_, _ = w.Write([]byte(`{"Version": 3, "Flags": {"checkout_v2": {"Enabled": true}}}`))
}))
defer service.Close()
flags := cruflags.New(cruflags.Options{URL: service.URL})
defer flags.Close()
flags.Ready(context.Background())
fmt.Println(flags.Enabled("checkout_v2"), flags.Enabled("not_a_flag"))
}
Output: true false
func (*Client) Close ¶
func (c *Client) Close()
Close stops the client for good: the poller exits, a fetch in progress is abandoned, and Close waits for both. Reads keep answering from the last document. Closing is optional for a client that lives as long as the process, and safe to repeat: every call waits.
func (*Client) Enabled ¶
Enabled reports whether the flag called name is on.
It never blocks, never panics and never fails: an unknown flag, a document that has not arrived, a flag-service outage before the first success, and an inert client all read off. Only "Enabled": true in the document turns a flag on. After the first success, the last good document is served through any outage, for as long as it lasts.
In OnDemand mode, Enabled starts a refresh when the document is PollInterval old, and answers from the current document without waiting.
func (*Client) ForceRefresh ¶
ForceRefresh is Refresh without the PollInterval check.
func (*Client) Ready ¶
Ready waits for the first fetch to settle, successfully or not, so the first requests a process serves see real flags. Call it once during startup, with a deadline:
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() cruflags.Ready(ctx)
It reports whether the wait ended because that fetch settled (true) or because ctx did (false). It says nothing about whether the fetch succeeded. An inert client has nothing to wait for and returns true at once.
func (*Client) Refresh ¶
Refresh fetches the document unless the last attempt is younger than PollInterval, and waits for it or for ctx. A refresh already in progress is shared rather than repeated. It reports whether the document is fresh: an attempt has settled and the latest one succeeded.
In OnDemand mode this is how a request handler gets the current document before reading flags; it costs at most one conditional GET per PollInterval:
func middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cruflags.Refresh(r.Context())
next.ServeHTTP(w, r)
})
}
Example ¶
On a runtime that freezes between requests, refresh from the request path instead of a poller. Refresh fetches at most once per PollInterval.
package main
import (
"fmt"
"net/http"
cruflags "github.com/CruGlobal/cru-flags"
)
func main() {
flags := cruflags.New(cruflags.Options{RefreshMode: cruflags.OnDemand})
defer flags.Close()
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
flags.Refresh(r.Context())
if flags.Enabled("checkout_v2") {
_, _ = fmt.Fprintln(w, "new checkout")
return
}
_, _ = fmt.Fprintln(w, "old checkout")
})
_ = handler
}
Output:
type Document ¶
type Document struct {
Project string `json:"Project,omitempty"`
Environment string `json:"Environment,omitempty"`
Version int64 `json:"Version,omitempty"`
NotifySlack bool `json:"NotifySlack"`
Flags map[string]Flag `json:"Flags"`
}
Document is a flag document as the service publishes it. Only Flag.Enabled changes behavior; the rest is carried for display and debugging.
func Snapshot ¶
func Snapshot() *Document
Snapshot returns a copy of the default client's document. See Client.Snapshot.
type ErrorCode ¶
type ErrorCode string
ErrorCode says why a fetch failed.
const ( // CodeHTTP means the service answered with an unexpected status (5xx, 400, and // so on). FetchError.Status carries it. A 404 is not an error, and a 304 // is a success. CodeHTTP ErrorCode = "http" // CodeNetwork means the request never completed (DNS, connection refused or // reset, TLS, too many redirects, a malformed URL). CodeNetwork ErrorCode = "network" // CodeTimeout means the fetch outlived Options.FetchTimeout and was abandoned. CodeTimeout ErrorCode = "timeout" // CodeParse means a 2xx arrived whose body is not a usable flag document, // including a body over MaxBodyBytes. CodeParse ErrorCode = "parse" )
type FetchError ¶
type FetchError struct {
Code ErrorCode
// Status is the HTTP status, when Code is CodeHTTP.
Status int
// Message describes the failure.
Message string
// Err is the underlying error, when there is one.
Err error
}
FetchError is the error carried by a Failing HealthEvent. Nothing in the package returns it: Enabled, Ready and Refresh never return errors. It exists so an OnError handler can branch on Code and Status instead of matching message text.
func (*FetchError) Error ¶
func (e *FetchError) Error() string
func (*FetchError) Unwrap ¶
func (e *FetchError) Unwrap() error
type Flag ¶
type Flag struct {
Enabled bool `json:"Enabled"`
Description string `json:"Description,omitempty"`
CreatedAt time.Time `json:"CreatedAt,omitzero"`
UpdatedAt time.Time `json:"UpdatedAt,omitzero"`
UpdatedBy string `json:"UpdatedBy,omitempty"`
}
Flag is one entry in a Document.
type HealthEvent ¶
type HealthEvent struct {
Kind HealthKind
URL string
// Err is a *FetchError when Kind is Failing, and nil when it is Recovered.
Err error
}
HealthEvent is passed to Options.OnError on a health transition, never on every failed poll: at the default interval, per-poll reporting is 2,880 identical lines per day per instance, and they bury the one that matters.
type HealthKind ¶
type HealthKind string
HealthKind is a health transition.
const ( // Failing means a fetch failed after the client was healthy. Failing HealthKind = "failing" // Recovered means a fetch succeeded after the client was failing. Recovered HealthKind = "recovered" )
type Options ¶
type Options struct {
// URL of the flag document. Empty means os.Getenv(URLEnvVar), read when
// the client starts rather than when it is built. With neither, the client
// is inert: every flag is off, and it makes no requests and logs nothing.
URL string
// PollInterval is how often the document is refreshed. Default 30s.
PollInterval time.Duration
// FetchTimeout bounds one fetch, body included. Default 2s.
FetchTimeout time.Duration
// RefreshMode is Background or OnDemand. Empty means
// os.Getenv(RefreshModeEnvVar), and Background when that is unset.
RefreshMode RefreshMode
// OnError is called on health transitions only. It runs on the fetching
// goroutine before callers waiting on that fetch are released, so it must
// return quickly, and it must not call Close, Ready, Refresh or
// ForceRefresh on the same client (for the default client, the package's
// Ready and Refresh): those wait on the fetch that is running the
// handler, and deadlock. Enabled and Snapshot are safe. A panic in it is
// recovered. The default logs both transitions at Warn on slog.Default().
OnError func(HealthEvent)
}
Options configures a Client. The zero value is the usual configuration: the URL and refresh mode come from the environment.
Example (OnError) ¶
Route health transitions somewhere other than slog.Default().
package main
import (
"log/slog"
cruflags "github.com/CruGlobal/cru-flags"
)
func main() {
logger := slog.New(slog.DiscardHandler)
flags := cruflags.New(cruflags.Options{
OnError: func(event cruflags.HealthEvent) {
logger.Warn("feature flags "+string(event.Kind), "url", event.URL, "error", event.Err)
},
})
defer flags.Close()
}
Output:
type RefreshMode ¶
type RefreshMode string
RefreshMode is how a Client keeps its document current.
const ( // Background polls on a goroutine every PollInterval, plus or minus 20% // jitter. Reads never touch the network. The default. Background RefreshMode = "background" // OnDemand runs no poller. A read that finds the document PollInterval old // starts a refresh without waiting for it, and Refresh refreshes and waits. // For runtimes that freeze the process between requests: AWS Lambda, and // Cloud Run with CPU throttled outside requests. OnDemand RefreshMode = "on-demand" )