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 ¶
- type Check
- type Rule
- func (r Rule[T]) And(rules ...Rule[T]) Rule[T]
- func (r Rule[T]) Else(err error) Check[T]
- func (r Rule[T]) Filter(seq iter.Seq[T]) iter.Seq[T]
- func (r Rule[T]) Not() Rule[T]
- func (r Rule[T]) Or(rules ...Rule[T]) Rule[T]
- func (r Rule[T]) Requires(then Rule[T]) Rule[T]
- func (r Rule[T]) Xor(other Rule[T]) Rule[T]
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Check ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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]) Or ¶
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 ¶
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