Bree

Laravel Go

breelaravel (github.com/breeso/bree-go/laravel) installs Bree in a Laravel Go application: it opens the engine at startup, refuses to start if the rules fail their checks, and turns rejected input into Laravel validation errors.

It requires Laravel Go (go.laravel.com) v0.1.1 or later and Go 1.27, as Laravel Go does, plus the engine library.

Run the example

examples/laravel-go is a Laravel Go application with one route, POST /api/shipments/eligibility, that asks the shipment_eligibility rule whether a parcel can ship. With CGO_LDFLAGS set as in Build the engine:

cd examples/laravel-go
cp .env.example .env
go run . key:generate
go run . serve

In another terminal:

$ curl -s -X POST http://127.0.0.1:8000/api/shipments/eligibility \
    -H 'Content-Type: application/json' -H 'Accept: application/json' \
    -d '{"origin_postal_prefix":"M5V","destination_postal_prefix":"H2X","weight_grams":22000,"service":"express","service_limits":[{"service":"express","max_weight_grams":30000,"origin_prefixes":["M"],"destination_prefixes":["H","M"]}]}'
{"eligible":false,"reason":"overweight","digest":"sha256:101d5f62411af7044de482d4ad188fdc991faf6c3d1d4d7881527e6d2859b9ee"}

Express parcels are capped at 20 kg by the rule. Input that does not match the rule's types, or that the rule rejects with invalid, is a 422 with the messages by field, as a failed r.Validate would give:

{"message":"must be one of \"standard\", \"express\", \"overnight\" (and 1 more error)","errors":{"service":["must be one of \"standard\", \"express\", \"overnight\""],"weight":["is not a field of this type"]}}
{"message":"must be 1 to 5 upper-case letters or digits, such as M5V","errors":{"origin_postal_prefix":["must be 1 to 5 upper-case letters or digits, such as M5V"]}}

The example's .env.example sets BREE_RULES=rules, so the running application watches rules/. Raise EXPRESS_MAX_GRAMS to 25000 in rules/shipment_eligibility.luau and the log says why the answer did not change:

level=WARN msg="bree: kept the previous rules because the rules have 1 problem:\n  rules/shipment_eligibility.test.luau:42: test \"express is capped at 20 kg, below the carrier's 30 kg\" failed\n    expected { eligible = false, reason = \"overweight\" }\n         got { eligible = true, reason = \"eligible\" }"

Update that test (a 26 kg parcel, "capped at 25 kg") and the change is used within a second, without a restart:

level=INFO msg="bree: loaded shipment_eligibility" rule=shipment_eligibility digest=sha256:e2cbe0d589f37319dd989b3e012dd23f238cd2349850cb665cdb4c8c14392fad

Run go generate ./... to compile the change into the next build, and git checkout rules to put the example back.

Its tests send requests through the whole application: go test ./... in examples/laravel-go.

Add Bree to your application

1. Dependencies

go get github.com/breeso/bree-go@main github.com/breeso/bree-go/laravel@main

2. Rules

Put the rules in a rules package, with a rules.go that runs bree-gen, and generate, as in Getting started:

// Package rules is the application's business rules.
package rules

//go:generate go run github.com/breeso/bree-go/cmd/bree-gen

3. Register the package

In bootstrap/app.go:

import (
	laravel "go.laravel.com"

	breelaravel "github.com/breeso/bree-go/laravel"

	"app/rules"
)

func Options() laravel.Options {
	return laravel.Options{
		// ...
		Packages: []laravel.Package{breelaravel.New(rules.Rules)},
	}
}

The package opens the engine when the application starts. If a rule does not type check, fails a test, or no longer has the types bree-gen generated, the application does not start, and the error names each problem.

4. Decide in a handler

breelaravel.From(r) is the engine. Pass the request body to DecideJSON, so the rule's Input type decides what a valid request is, and hand errors to breelaravel.Fail:

package shipments

import (
	"encoding/json"

	"go.laravel.com/web"

	breelaravel "github.com/breeso/bree-go/laravel"

	"app/rules"
)

// Eligibility is the answer to POST /api/shipments/eligibility.
type Eligibility struct {
	Eligible bool                            `json:"eligible"`
	Reason   rules.ShipmentEligibilityReason `json:"reason"`
	// Which version of the rule decided: a digest of its source.
	Digest string `json:"digest"`
}

func Check(r *web.Request) *web.Response {
	body, err := r.JSON[json.RawMessage]()
	if err != nil {
		return web.Fail(err)
	}
	d, err := rules.ShipmentEligibility.DecideJSON(breelaravel.From(r), body)
	if err != nil {
		return breelaravel.Fail(err)
	}
	return web.JSON(Eligibility{
		Eligible: d.Output.Eligible,
		Reason:   d.Output.Reason,
		Digest:   d.Digest,
	})
}

When your code builds the input itself, use Decide with the generated struct instead. From takes any context of the application, so jobs and commands can decide too.

Fail answers the way Laravel answers any other failure:

Error Response
invalid_input a validation error on each field: a 422 with the messages for JSON requests, the messages beside each field for forms and Inertia pages
invalid_request 400
anything else a server error that Laravel logs and reports, because it means a rule failed or the deploy is out of step

A body that is not JSON never reaches Bree: r.JSON fails first, and Laravel answers with its own 400.

Configuration

Variable Default
BREE_RULES (empty) A rules directory to load and watch. Empty uses the rules embedded in the binary.
BREE_RELOAD_INTERVAL_MS 1000 How often to look for changes in BREE_RULES. 0 loads once.

Reloads and refused changes are logged through the application's logger, as above.

To change the settings in code, or set limits, pass a function to New:

breelaravel.New(rules.Rules, func(cfg *breelaravel.Config) {
	cfg.Limits = bree.Limits{Timeout: 200 * time.Millisecond}
})

Testing

laraveltest boots the whole application, rules included. Set BREE_RULES to empty so tests use the rules embedded in the binary, as the example does in tests/tests.go:

laraveltest.Env(map[string]string{
	"APP_ENV":    "testing",
	"BREE_RULES": "",
})
func TestARejectedValueNamesTheField(t *testing.T) {
	tests.New(t).PostJSON("/api/shipments/eligibility", parcel(0)).
		AssertStatus(422).
		AssertJSONPath("errors.weight_grams.0", "must be at least 1 gram")
}

Edit this page on GitHub