gate

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 3 Imported by: ? 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

gate

Small, typed rules you can combine, plus checks that tell you which rule failed.

A rule is a func(T) bool over any type. gate combines rules with And, Or, Not, and friends, and turns them into checks that return errors. It only uses the standard library.

Install

go get github.com/brian-nunez/bkit/gate
import "github.com/brian-nunez/bkit/gate"

Rules

Any func(T) bool is a rule, and you call a rule like a function. A type alias keeps the definitions short.

When a rule needs two things, like a user and the document they want to touch, put them in a struct:

type Access struct {
	User User
	Doc  Doc
}

type rule = gate.Rule[Access]

func hasRole(role string) rule {
	return func(a Access) bool { return slices.Contains(a.User.Roles, role) }
}

var (
	isOwner  rule = func(a Access) bool { return a.User.ID == a.Doc.OwnerID }
	isEditor rule = func(a Access) bool { return slices.Contains(a.Doc.Editors, a.User.ID) }
	isDraft  rule = func(a Access) bool { return a.Doc.Draft }
	isBanned rule = func(a Access) bool { return a.User.Banned }

	canDelete = hasRole("admin").Or(hasRole("user").And(isOwner))
	canView   = hasRole("admin").Or(gate.All(
		isDraft.Requires(isOwner.Or(isEditor)),
		gate.None(isBanned),
	))
)

if !canDelete(Access{User: user, Doc: doc}) {
	return ErrForbidden
}

The same pattern works for orders:

type orderRule = gate.Rule[Order]

var (
	inStock   orderRule = func(o Order) bool { return o.Stock > 0 }
	notOnHold orderRule = func(o Order) bool { return !o.Hold }
	canShip             = inStock.And(notOnHold)
)
Function Passes when
r.And(rules...) r and all the other rules pass
r.Or(rules...) r or any of the other rules pass
r.Not() r fails
r.Xor(other) exactly one of r and other passes
r.Requires(then) r fails, or both pass
gate.All(rules...) every rule passes (true when empty)
gate.Any(rules...) at least one rule passes (false when empty)
gate.None(rules...) no rule passes (true when empty)
gate.AtLeast(n, rules...) at least n rules pass (true when n <= 0)

Rules run left to right and stop once the answer is known. Xor always runs both sides.

r.Filter(seq) gives back only the values from an iter.Seq[T] that pass:

for o := range canShip.Filter(slices.Values(orders)) {
	ship(o)
}

Checks

A check is a func(T) error. r.Else(err) returns err when r fails.

Use gate.Join to get every failure at once, which works well for config and forms. Use gate.First to stop at the first failure.

var (
	ErrBadPort    = errors.New("port must be 1-65535")
	ErrAuthMethod = errors.New("set exactly one of password or cert file")
)

validate := gate.Join(
	hasPort.Else(ErrBadPort),
	hasPassword.Xor(hasCertFile).Else(ErrAuthMethod),
)

err := validate(cfg)
if errors.Is(err, ErrAuthMethod) {
	// ...
}

You can also write a check by hand when you want a custom message:

validPost := gate.First(
	hasBody.Else(ErrEmptyBody),
	func(p Post) error {
		if len(p.Body) > 5000 {
			return fmt.Errorf("%w: %d characters", ErrTooLong, len(p.Body))
		}
		return nil
	},
)

Good to know

  • Rules and checks copy the slices you pass in. Changing the slice later won't change the rule.
  • Don't pass a nil rule or check. Calling one panics, the same as any nil func.
  • Else(nil) never fails.
  • Rules and checks never change after they are built. They are safe to use from many goroutines when the functions inside them are.
  • Running a rule doesn't allocate.

Errors

Checks return the errors passed to Else, or the ones a hand-written check returns. Join combines them with errors.Join. errors.Is and errors.As work on the result.

Development

From the repository root:

make -C gate check

This runs the format check, lint, vet, tests with the race detector, and a coverage check that requires 100%.

Releases

Each release gets a tag like gate/vX.Y.Z:

go get github.com/brian-nunez/bkit/gate@vX.Y.Z

Documentation

Overview

Package gate provides typed, composable boolean rules and the checks that explain why a rule failed.

A Rule is a plain func(T) bool over any value the caller chooses: a request, a configuration, an order, or a small struct that pairs a subject with the thing it acts on. Rules combine with Rule.And, Rule.Or, Rule.Not, Rule.Xor, and Rule.Requires, or with All, Any, None, and AtLeast. Because a rule is a function, any func(T) bool literal is a rule and a rule is called directly:

type rule = gate.Rule[Access]

var (
	isAdmin rule = func(a Access) bool { return a.User.Admin }
	isOwner rule = func(a Access) bool { return a.User.ID == a.Doc.OwnerID }
	canEdit      = isAdmin.Or(isOwner)
)

if canEdit(Access{User: user, Doc: doc}) { ... }

A Check is a func(T) error. Rule.Else turns a rule into a check that reports a caller-supplied error when the rule fails; Join reports every failing check and First reports only the first.

The package owns composition and evaluation order. Callers own the value type, every leaf rule, and every error a check reports; gate defines no errors of its own.

Combinators that can decide early stop evaluating as soon as the result is known. Combinators copy their rule and check arguments when they are built, so later changes to a caller's slice do not affect them. Calling a nil Rule or Check panics like any nil function call; callers must not pass nil.

Rules and checks are immutable after construction and safe for concurrent use when the leaf functions they wrap are. Evaluating a composed rule does not allocate.

Example
package main

import (
	"fmt"
	"slices"

	"github.com/brian-nunez/bkit/gate"
)

type User struct {
	ID     string
	Roles  []string
	Banned bool
}

type Doc struct {
	OwnerID string
	Editors []string
	Draft   bool
}

// Access pairs a user with the document they act on.
type Access struct {
	User User
	Doc  Doc
}

type rule = gate.Rule[Access]

func hasRole(role string) rule {
	return func(a Access) bool { return slices.Contains(a.User.Roles, role) }
}

var (
	isOwner  rule = func(a Access) bool { return a.User.ID == a.Doc.OwnerID }
	isEditor rule = func(a Access) bool { return slices.Contains(a.Doc.Editors, a.User.ID) }
	isDraft  rule = func(a Access) bool { return a.Doc.Draft }
	isBanned rule = func(a Access) bool { return a.User.Banned }
)

func main() {
	canDelete := hasRole("admin").Or(hasRole("user").And(isOwner))
	canView := hasRole("admin").Or(gate.All(
		isDraft.Requires(isOwner.Or(isEditor)),
		gate.None(isBanned),
	))

	doc := Doc{OwnerID: "u1", Editors: []string{"u2"}, Draft: true}
	owner := User{ID: "u1", Roles: []string{"user"}}
	editor := User{ID: "u2", Roles: []string{"user"}}
	admin := User{ID: "u9", Roles: []string{"admin"}}

	fmt.Println(canDelete(Access{User: owner, Doc: doc}))
	fmt.Println(canDelete(Access{User: editor, Doc: doc}))
	fmt.Println(canDelete(Access{User: admin, Doc: doc}))
	fmt.Println(canView(Access{User: editor, Doc: doc}))
	fmt.Println(canView(Access{User: User{ID: "u3"}, Doc: doc}))
}
Output:
true
false
true
true
false

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Check

type Check[T any] func(T) error

Check reports why a value fails a condition, or nil when it satisfies it.

Any func(T) error is a Check; Rule.Else builds one from a rule. The errors a check reports belong to the caller and are matched with errors.Is and errors.As.

func First

func First[T any](checks ...Check[T]) Check[T]

First returns a check that runs checks left to right and reports the first error, without running the rest, or nil when every check passes. First with no checks always reports nil.

Example
package main

import (
	"errors"
	"fmt"
	"slices"

	"github.com/brian-nunez/bkit/gate"
)

type User struct {
	ID     string
	Roles  []string
	Banned bool
}

type Doc struct {
	OwnerID string
	Editors []string
	Draft   bool
}

// Access pairs a user with the document they act on.
type Access struct {
	User User
	Doc  Doc
}

type rule = gate.Rule[Access]

func hasRole(role string) rule {
	return func(a Access) bool { return slices.Contains(a.User.Roles, role) }
}

var (
	isOwner rule = func(a Access) bool { return a.User.ID == a.Doc.OwnerID }

	isBanned rule = func(a Access) bool { return a.User.Banned }
)

var (
	ErrBanned   = errors.New("account is banned")
	ErrNotOwner = errors.New("only the owner can delete this")
)

func main() {
	checkDelete := gate.First(
		isBanned.Not().Else(ErrBanned),
		hasRole("admin").Or(isOwner).Else(ErrNotOwner),
	)

	doc := Doc{OwnerID: "u1"}

	fmt.Println(checkDelete(Access{User: User{ID: "u1"}, Doc: doc}))
	fmt.Println(checkDelete(Access{User: User{ID: "u2"}, Doc: doc}))
	fmt.Println(checkDelete(Access{User: User{ID: "u2", Banned: true}, Doc: doc}))
}
Output:
<nil>
only the owner can delete this
account is banned

func Join

func Join[T any](checks ...Check[T]) Check[T]

Join returns a check that runs every check and reports all of their errors combined with errors.Join, or nil when every check passes. Each reported error remains matchable with errors.Is and errors.As. Join with no checks always reports nil.

Example
package main

import (
	"errors"
	"fmt"

	"github.com/brian-nunez/bkit/gate"
)

type Config struct {
	Port     int
	Password string
	CertFile string
	TLS      bool
}

var (
	ErrBadPort      = errors.New("port must be 1-65535")
	ErrAuthMethod   = errors.New("set exactly one of password or cert file")
	ErrCertNeedsTLS = errors.New("cert file requires tls")
)

func main() {
	type cfgRule = gate.Rule[Config]

	var (
		hasPort     cfgRule = func(c Config) bool { return c.Port > 0 && c.Port < 65536 }
		hasPassword cfgRule = func(c Config) bool { return c.Password != "" }
		hasCertFile cfgRule = func(c Config) bool { return c.CertFile != "" }
		usesTLS     cfgRule = func(c Config) bool { return c.TLS }
	)

	validate := gate.Join(
		hasPort.Else(ErrBadPort),
		hasPassword.Xor(hasCertFile).Else(ErrAuthMethod),
		hasCertFile.Requires(usesTLS).Else(ErrCertNeedsTLS),
	)

	err := validate(Config{Port: 0, Password: "x", CertFile: "cert.pem"})
	fmt.Println(err)
	fmt.Println(errors.Is(err, ErrAuthMethod))
	fmt.Println(validate(Config{Port: 8443, CertFile: "cert.pem", TLS: true}))
}
Output:
port must be 1-65535
set exactly one of password or cert file
cert file requires tls
true
<nil>

type Rule

type Rule[T any] func(T) bool

Rule reports whether a value satisfies a condition.

Any func(T) bool is a Rule, and a Rule is called directly to evaluate it.

func All

func All[T any](rules ...Rule[T]) Rule[T]

All returns a rule that passes when every rule passes. It evaluates left to right and stops at the first failure. All with no rules always passes.

func Any

func Any[T any](rules ...Rule[T]) Rule[T]

Any returns a rule that passes when at least one rule passes. It evaluates left to right and stops at the first pass. Any with no rules always fails.

func AtLeast

func AtLeast[T any](n int, rules ...Rule[T]) Rule[T]

AtLeast returns a rule that passes when at least n rules pass. It evaluates left to right and stops as soon as n rules have passed or too few rules remain to reach n. AtLeast always passes when n <= 0 and always fails when n exceeds the number of rules.

Example
package main

import (
	"fmt"

	"github.com/brian-nunez/bkit/gate"
)

type SignIn struct {
	KnownDevice bool
	UsualRegion bool
	RecentLogin bool
	PassedMFA   bool
}

func main() {
	type signInRule = gate.Rule[SignIn]

	var (
		knownDevice signInRule = func(s SignIn) bool { return s.KnownDevice }
		usualRegion signInRule = func(s SignIn) bool { return s.UsualRegion }
		recentLogin signInRule = func(s SignIn) bool { return s.RecentLogin }
		passedMFA   signInRule = func(s SignIn) bool { return s.PassedMFA }
	)

	canSignIn := gate.AtLeast(2, knownDevice, usualRegion, recentLogin).Or(passedMFA)

	fmt.Println(canSignIn(SignIn{KnownDevice: true, RecentLogin: true}))
	fmt.Println(canSignIn(SignIn{KnownDevice: true}))
	fmt.Println(canSignIn(SignIn{KnownDevice: true, PassedMFA: true}))
}
Output:
true
false
true

func None

func None[T any](rules ...Rule[T]) Rule[T]

None returns a rule that passes when no rule passes. It evaluates left to right and stops at the first pass. None with no rules always passes.

func (Rule[T]) And

func (r Rule[T]) And(rules ...Rule[T]) Rule[T]

And returns a rule that passes when r and every rule in rules pass. It evaluates left to right and stops at the first failure.

func (Rule[T]) Else

func (r Rule[T]) Else(err error) Check[T]

Else returns a check that reports nil when r passes and err when r fails. err should be non-nil; with a nil err the check never reports a failure.

func (Rule[T]) Filter

func (r Rule[T]) Filter(seq iter.Seq[T]) iter.Seq[T]

Filter returns a sequence of the values from seq that pass r. It is lazy: values are read from seq and tested only as the result is iterated.

Example
package main

import (
	"fmt"
	"slices"

	"github.com/brian-nunez/bkit/gate"
)

type User struct {
	ID     string
	Roles  []string
	Banned bool
}

type Doc struct {
	OwnerID string
	Editors []string
	Draft   bool
}

// Access pairs a user with the document they act on.
type Access struct {
	User User
	Doc  Doc
}

type rule = gate.Rule[Access]

var (
	isOwner rule = func(a Access) bool { return a.User.ID == a.Doc.OwnerID }

	isDraft rule = func(a Access) bool { return a.Doc.Draft }
)

func main() {
	docs := []Doc{
		{OwnerID: "u1", Draft: true},
		{OwnerID: "u2", Draft: true},
		{OwnerID: "u2", Draft: false},
	}
	user := User{ID: "u1"}

	canView := isDraft.Requires(isOwner)

	accesses := func(yield func(Access) bool) {
		for _, d := range docs {
			if !yield(Access{User: user, Doc: d}) {
				return
			}
		}
	}
	for a := range canView.Filter(accesses) {
		fmt.Println(a.Doc.OwnerID, a.Doc.Draft)
	}
}
Output:
u1 true
u2 false

func (Rule[T]) Not

func (r Rule[T]) Not() Rule[T]

Not returns a rule that passes when r fails.

func (Rule[T]) Or

func (r Rule[T]) Or(rules ...Rule[T]) Rule[T]

Or returns a rule that passes when r or any rule in rules passes. It evaluates left to right and stops at the first pass.

func (Rule[T]) Requires

func (r Rule[T]) Requires(then Rule[T]) Rule[T]

Requires returns a rule that passes when r fails, or when both r and then pass: whenever r holds, then must hold too. then is evaluated only when r passes.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/brian-nunez/bkit/gate"
)

type Post struct {
	Body       string
	Reputation int
}

func main() {
	type postRule = gate.Rule[Post]

	var (
		hasLinks postRule = func(p Post) bool { return strings.Contains(p.Body, "http") }
		trusted  postRule = func(p Post) bool { return p.Reputation >= 100 }
	)

	// Only trusted authors may post links.
	canPublish := hasLinks.Requires(trusted)

	fmt.Println(canPublish(Post{Body: "hello", Reputation: 1}))
	fmt.Println(canPublish(Post{Body: "see http://example.com", Reputation: 1}))
	fmt.Println(canPublish(Post{Body: "see http://example.com", Reputation: 500}))
}
Output:
true
false
true

func (Rule[T]) Xor

func (r Rule[T]) Xor(other Rule[T]) Rule[T]

Xor returns a rule that passes when exactly one of r and other passes. It always evaluates both.

Jump to

Keyboard shortcuts

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