cruflags

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: BSD-3-Clause Imports: 15 Imported by: 0 modules, 0 packages

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

README

cru-flags

Clients for Cru's pipeline feature-flag service, one per language, in one repository. Each one reads CRU_FLAGS_URL, polls that one JSON document with ETag revalidation, keeps the last good copy through any outage, and answers "is this flag on?" from memory without ever raising:

Language Package Install Read a flag
Go github.com/CruGlobal/cru-flags go get github.com/CruGlobal/cru-flags cruflags.Enabled("checkout_v2")
TypeScript @cruglobal/flags npm install @cruglobal/flags flags.enabled("checkout_v2")
Python cru-flags pip install cru-flags flags.enabled("checkout_v2")
Ruby cru-flags gem "cru-flags" Flipper.enabled?(:checkout_v2) (Rails)

All four have zero runtime dependencies (the gem's one exception is flipper, for its read-only Flipper adapter), share one version number, and release together.

How flags are created and flipped (cru app flags), and how they fit the merge-dark / demo-on-stage / launch-in-production workflow, is in the pipeline guide.

Status: AI-generated, maintained on a best-effort basis. These libraries were authored primarily by an AI assistant against the design documents linked below. Dependabot keeps tooling current; feature work and fixes happen as needed. Issues and pull requests are welcome.

The contract every client keeps

  • CRU_FLAGS_URL unset means every flag is off, silently. Local development, CI, preview and lab environments have no flag document, and that is a normal state, not a configuration error.
  • Unknown flags read off. Only a literal "Enabled": true turns a flag on.
  • A flag read never fetches, never blocks and never raises. It is a memory lookup.
  • Poll every 30 seconds, plus or minus 20% jitter, sending If-None-Match so an unchanged document costs a 304.
  • Keep last-known-good. A failed poll (timeout, 5xx, a malformed body) changes nothing, forever. Flags never fall back to off on error. A 404 means "this app has no flags yet" and is not an error.
  • Fetch once at startup (Ready) so the first requests after a deploy see real flags.
  • Log health transitions only: once when polling starts failing, once when it recovers.

The conformance suite encodes these rules as cases, and every client's test suite runs them against the same test server.

Quick start

Go
import cruflags "github.com/CruGlobal/cru-flags"

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	cruflags.Ready(ctx) // optional: wait for the first fetch before serving
	cancel()

	if cruflags.Enabled("checkout_v2") {
		// ...
	}
}

Details: docs/go/README.md.

TypeScript / Node.js
import { flags } from "@cruglobal/flags";

await flags.ready(); // optional warmup
if (flags.enabled("checkout_v2")) {
  // ...
}

Details: docs/node/README.md.

Python
from cru_flags import flags

flags.ready(timeout=3.0)  # optional warmup
if flags.enabled("checkout_v2"):
    ...

Details: docs/python/README.md.

Ruby
# Gemfile
gem "cru-flags"

# In Rails the Railtie wires Flipper for you:
Flipper.enabled?(:checkout_v2)

# Anywhere else:
CruFlags.enabled?("checkout_v2")

Details: docs/ruby/README.md.

Lambda and Cloud Run

On runtimes that freeze the process between requests, a background poll timer does not tick. Set CRU_FLAGS_REFRESH_MODE=on-demand and every client drops the timer and refreshes from the read path instead, at most once per poll interval. Call Ready during init so the first invocation sees real flags.

Repository layout

Path What
*.go, go.mod Go package cruflags
src/, test/*.ts, package.json TypeScript package @cruglobal/flags
cru_flags/, tests/, pyproject.toml Python package cru-flags
lib/, test/*.rb, cru-flags.gemspec Ruby gem cru-flags
conformance/ Shared cases and the test server every client runs against
docs/<language>/ Each client's README, design document and old changelog

Each language's design document (docs/<language>/design.md) is the authoritative specification for that client. See CONTRIBUTING.md to work on them.

Releasing

release-please keeps a release pull request open on main, built from Conventional Commit subjects. Merging it bumps every version file, writes CHANGELOG.md, tags vX.Y.Z and publishes a GitHub Release. The release workflow then publishes to npm, PyPI and RubyGems through trusted publishing (no registry tokens live in this repository). The Go module needs no publish step: the tag is the release.

License

BSD-3-Clause.

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

View Source
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
)
View Source
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

func Enabled(name string) bool

Enabled reports whether a flag is on, using the default client. See Client.Enabled.

func Ready

func Ready(ctx context.Context) bool

Ready waits for the default client's first fetch to settle. See Client.Ready.

func Refresh

func Refresh(ctx context.Context) bool

Refresh refreshes the default client's document if it is stale. See Client.Refresh.

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

func New(opts Options) *Client

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

func (c *Client) Enabled(name string) (on bool)

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

func (c *Client) ForceRefresh(ctx context.Context) bool

ForceRefresh is Refresh without the PollInterval check.

func (*Client) Ready

func (c *Client) Ready(ctx context.Context) bool

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

func (c *Client) Refresh(ctx context.Context) bool

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
}

func (*Client) Snapshot

func (c *Client) Snapshot() (doc *Document)

Snapshot returns a copy of the document in effect, or nil before the first document and after a 404. Changing the copy changes nothing in the client.

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()
}

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"
)

Jump to

Keyboard shortcuts

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