mapping

package
v0.268.0 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: MIT Imports: 26 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.

Documentation

Overview

Package mapping builds, renders and previews openfga/mapper mapping documents. It owns the authoring model the `ofga mappings` workspace edits and the deterministic YAML it emits, and holds no terminal UI so the validate, test and apply subcommands can reuse it.

Index

Constants

View Source
const (
	EvalTimeout      = time.Second
	MaxTuples        = 40
	MaxRules         = 100
	MaxIteratorItems = 1000
)

Evaluation limits. The caps match mapper's own defaults, so the workspace fails the same way `ofga mappings apply` does rather than being permissive. EvalTimeout is the workspace's alone: it previews the document after every keystroke-sized change, so it is short enough that a runaway expression cannot lock up the UI. validate, test and apply use mapper's DefaultTimeout, as `fga` does.

View Source
const DefaultFile = "mapping.yaml"

DefaultFile is the mapping file name used when the user names none.

View Source
const Version = "1"

Version is the mapping language version this package emits. The language has exactly one version today; mapper rejects anything else.

Variables

View Source
var ErrChangedOnDisk = errors.New("changed on disk since it was loaded; reload it before saving")

ErrChangedOnDisk is why Save refuses to write: the file on disk is no longer what was loaded or last saved, and writing would discard someone's edit.

View Source
var ErrLayout = errors.New("the saved file would differ from the edit")

ErrLayout is why Render cannot keep a file's layout: what the merge wrote would not mean what the edit means. SaveReformatted writes it anyway.

View Source
var ErrNoEvent = errors.New("no event")

ErrNoEvent is DecodeEvent's error for empty or blank input.

Functions

func AppliedSoFar

func AppliedSoFar(p *Plan, applied int) string

AppliedSoFar is "no events applied", "applied event 1" or "applied events 1-2" for the events before p.Events[applied], numbered as in the file. It needs 0 <= applied < len(p.Events). The count Execute returns with an error keeps to that: p.Events[applied] is then the event that did not finish.

func ApplyQuestion

func ApplyQuestion(writes, deletes int, name, id string) string

ApplyQuestion is "Apply 2 writes and 1 delete to store acme (01ARZ…)?"; a zero half is dropped, and with no name only the id is shown.

func ChangeLine

func ChangeLine(t language.Tuple, field func(string) string) string

ChangeLine is one planned change as the CLI prints it: "+ user:1 member org:acme" or "- …", then " (cond: k=json, k2=json)" with sorted context keys. field sanitizes each part (output.SanitizeField in the CLI, style.SanitizeTerminal in the TUI).

func CheckTuple

func CheckTuple(t language.Tuple) error

CheckTuple reports what is wrong with the shape of an evaluated tuple: an object that is not type:id, or a user that is not type:id, type:* or type:id#relation, with every part non-empty. mapper renders a template that resolves to "" or leaves out the type without complaint; FGA refuses the write.

func Compile

func Compile(d *Document) ([]byte, *mapper.Mapping, mapper.Diagnostics, error)

Compile renders d and compiles it, returning the rendered bytes even when compilation fails — the preview pane shows the YAML the diagnostics point at. Evaluation is capped at EvalTimeout, since the workspace previews every edit.

func CompileSource

func CompileSource(src []byte) (*mapper.Mapping, mapper.Diagnostics, error)

CompileSource compiles a mapping file's bytes with the limits and tracing every ofga surface uses, so `validate`, `test` and `apply` agree on what a file means. Evaluation gets mapper's default timeout, as in `fga`.

func DecodeEvent

func DecodeEvent(data []byte) (map[string]any, error)

DecodeEvent reads one event: a single JSON object. Numbers are exact (an integer that fits in 64 bits is an int, anything else a float64), and one too large for a float64 is refused. Errors name the position: "line 3, column 7: …", or say what the value was instead of an object ("an event must be a JSON object, not an array"). Columns are 1-based and count bytes, not runes.

func EvalExpr

func EvalExpr(ctx context.Context, vars []Variable, expr string, event map[string]any) (any, error)

EvalExpr evaluates expr against event the way mapper evaluates an iterator source or a variable: input is the event, and variables are vars, each one seeing the ones declared before it.

mapper exports no single-expression evaluator, so this builds a one-rule document that declares expr as one more variable after vars, walks a one-element list holding that variable and renders the element with toJSON, compiles and evaluates it through mapper's public API, and decodes the JSON back. expr is never spliced into other expression text, so it compiles on its own, in the same scope, and whatever mapper evaluates — json_path, ??, functions, variables, comments — evaluates here the same way, because it is mapper doing it.

func Execute

func Execute(ctx context.Context, p *Plan, w TupleWriter, progress func(done, total int)) (int, error)

Execute applies a plan event by event, stopping at the first error or cancellation. An atomic event goes out as one Write request. A non-atomic event (a tuple is both deleted and written) sends its deletes, then its writes, each in chunks of maxChangesPerWrite. It returns how many events were fully applied. Cancellation is checked before each request, so one that lands after the last change still returns success: the plan is fully applied, and a resume would have nothing left to send.

func FieldInRule

func FieldInRule(field string) string

FieldInRule is field without its `rules[N]` / `rules["name"]` prefix, the part that names a place inside the rule; a field with no such prefix comes back as it is.

func IteratorItem

func IteratorItem(ctx context.Context, r Rule, event map[string]any) (any, bool)

IteratorItem is the first element r's iterator walks in event: the value its alias names inside the iterator's tuples. It is false when r has no iterator, or its source does not evaluate to a non-empty list.

func Lookup

func Lookup(event map[string]any, expr string) (any, bool)

Lookup resolves a path produced by Paths back to its value in event. The leading "input." segment addresses the event root; anything else misses because an iterator-scoped path has no event-level meaning.

func Marshal

func Marshal(d *Document) ([]byte, error)

Marshal renders d as a mapping file.

The node tree is built by hand rather than by tagging structs because two things must be stable: key order (the language documents one, and Go struct tags cannot express "omit this whole section"), and map ordering — `variables` and a tuple's `context` are YAML mappings whose order is the user's, and ranging a Go map would reshuffle them on every save. Templates are forced to double-quoted style so a literal relation and an interpolated object read alike; expressions are left to the emitter, which quotes them only when a plain scalar would not round-trip.

func MissingTypes

func MissingTypes(d *Document, ix *ModelIndex) []string

MissingTypes is every type a literal tuple user or object names that ix does not define, sorted. Templated values are skipped, and so is an empty index, which defines nothing to compare against.

func ParseEvents

func ParseEvents(r io.Reader, source string) ([]map[string]any, error)

ParseEvents reads events as one JSON object, a JSON array of objects, or a stream of them (JSONL) — a json.Decoder walks all three alike. Numbers are exact (see exactNumbers), and one too large for a float64 is refused. Errors read "<source>:<line>:<column>: …"; the column is 1-based and counts bytes, not runes.

func PlanSummary

func PlanSummary(p *Plan) string

PlanSummary is "3 events: 2 writes, 1 delete, 1 matched no rule".

func PlanText

func PlanText(p *Plan, field func(string) string) []string

PlanText is every line `ofga mappings apply` prints for p, uncapped: for each event with changes, "event N", " · <type>" when set, and " (split into N requests)" when not atomic; then its changes indented two spaces. The CLI caps it at maxPlanLines and adds its own "… N more" hint.

func Plural

func Plural(n int, noun string) string

Plural is "1 write" / "2 writes". Moved from tui.Plural; tui callers use this.

func SampleKey

func SampleKey(event map[string]any) (string, error)

SampleKey identifies an event by content. json.Marshal sorts map keys, so two rules pointing at equal events produce the same key.

func SamplesFromTests

func SamplesFromTests(ctx context.Context, d *Document)

SamplesFromTests gives each rule without a sample the input of the first test, in file order, whose evaluation matches that rule, labelled with the test's name. Rules are matched by position in mapper's trace (one entry per rule, in order, until an error), never by name, which may repeat or be empty. A document that does not compile gets none. It sets Sample directly: picking an event through the workspace would also rename the rule.

func SentLine

func SentLine(p *Plan, label string) string

SentLine is "sent 2 writes and 1 delete across 3 events to store acme".

func TupleText

func TupleText(t language.Tuple, field func(string) string) string

TupleText is a test's tuple, expected or actual, on one line: user relation object, then its condition and context, the context sorted by key with each value as JSON (so 2 and "2" differ), then a delete marked as one. A test may expect context without a condition, so context shows even then. mapper's runner tells two tuples apart by every one of these, so a failure that left one out could print a missing and an unexpected line that read the same. field escapes each value taken from the tuple, for a caller writing straight to a terminal; nil leaves them as they are.

func UniqueTestName

func UniqueTestName(tests []TestCase, name string) string

UniqueTestName is name, or name with " 2", " 3"… appended when tests already has a test of that name.

Types

type ContextEntry

type ContextEntry struct {
	Key      string
	Template string
}

ContextEntry is one condition-context parameter. A slice, not a map, so the emitted order is the order the user entered.

type Document

type Document struct {
	Rules []Rule
	Tests []TestCase
}

Document is a mapping file under construction. It mirrors the language's shape rather than mapper's parsed form because the workspace edits partial, not-yet-valid states — a rule with no tuples yet, a tuple with an empty object — that mapper's own types cannot represent.

type Event

type Event struct {
	Label   string // "test <name>" or "rule <name> sample"
	Payload map[string]any
}

Event is one event to apply, named for where it came from.

func Events

func Events(d *Document) []Event

Events lists d's test inputs, then its rules' samples that are not already among them, deduplicated by content. An unnamed rule is named by its position. A test or sample without an event is left out, but {} is kept: a rule that matches every event maps it.

type EventPlan

type EventPlan struct {
	Index   int    // 1-based
	Type    string // event["type"] when it is a string
	Matched bool   // some rule's `when` matched
	// Changes are the event's deletes followed by its writes, each group in
	// mapper's order. Action is write or delete.
	Changes []language.Tuple
	// Atomic means the event goes out as one Write request: it fits in one
	// request and no tuple is both deleted and written (OpenFGA rejects that).
	Atomic bool
}

EventPlan is what one event changes.

func (EventPlan) Requests

func (e EventPlan) Requests() int

Requests is how many Write requests Execute sends for the event: one when it is atomic, otherwise its deletes and then its writes, each in chunks of maxChangesPerWrite. An event that changes nothing sends none.

type File

type File struct {
	Path string
	// Src is what was read with the BOM stripped and CRLF kept, so positions
	// mapper reports line up with Doc and with root.
	Src []byte
	Doc *Document
	// Editable is whether Doc represents the whole file, which is what makes
	// Save safe. Reason says why not.
	Editable bool
	Reason   string
	// Invalid is mapper's verdict on a draft: a file whose YAML parses into a
	// mapping but that mapper rejects. Only the draft loaders return such a
	// file; it is nil otherwise.
	Invalid mapper.Diagnostics
	// contains filtered or unexported fields
}

File is a mapping file read from disk: its bytes, the editor's Document, and the yaml.v3 tree Save merges into so comments and key order survive.

func Create

func Create(path string, doc *Document) (*File, error)

Create writes doc to path, which must not exist, and returns it loaded as a draft. A path that exists fails with an error wrapping fs.ErrExist and writes nothing. The commit links the file into place, so something created between the Lstat and the commit is not replaced; only on a filesystem that cannot hard link does that race remain, and Save's own check covers every later write.

func Load

func Load(path string) (*File, error)

Load reads and parses the mapping file at path.

func LoadBytes

func LoadBytes(path string, data []byte) (*File, error)

LoadBytes parses data as a mapping file; path is only used to name it.

func LoadDraft

func LoadDraft(path string) (*File, error)

LoadDraft is Load for the editor: a file mapper rejects still loads, with mapper's verdict in Invalid, so it can be fixed in place. Load stays strict for validate, test and apply.

func LoadDraftBytes

func LoadDraftBytes(path string, data []byte) (*File, error)

LoadDraftBytes is LoadBytes with LoadDraft's leniency. YAML that does not parse is still a *LoadError.

func (*File) ChangedOnDisk

func (f *File) ChangedOnDisk() (bool, error)

ChangedOnDisk reports whether the file on disk is no longer what f loaded or last saved. A file that is gone counts as changed.

func (*File) Overwrite

func (f *File) Overwrite(doc *Document) (bool, error)

Overwrite is Save without the changed-on-disk check, for "save over it". It writes even when the file is missing or the edit changes nothing, and reports whether it wrote.

func (*File) ProblemPos

func (f *File) ProblemPos(p Problem) (line, col int)

ProblemPos is the 1-based position of what p is about: the field of the tuple or filter it names, or as much of that as the file has, down to its rule. It is 0, 0 for a problem about no rule.

func (*File) Render

func (f *File) Render(doc *Document) ([]byte, bool, error)

Render returns the bytes Save would write for doc, and whether they differ from the file in meaning (not just formatting).

func (*File) RuleLine

func (f *File) RuleLine(i int) (line, col int)

RuleLine is the 1-based position of rules[i] in Src, or 0, 0 if there is none.

func (*File) Save

func (f *File) Save(doc *Document) (bool, error)

Save writes Render's output atomically when it changed the file's meaning, and reports whether it wrote anything. It writes documents mapper would reject too, so work in progress can be saved. It refuses, writing nothing, when the file on disk is no longer what f loaded or last saved. After a write f describes the file now on disk and f.Doc is a new value: keep editing f.Doc, not doc.

func (*File) SaveReformatted

func (f *File) SaveReformatted(doc *Document) (bool, error)

SaveReformatted is Save writing Marshal(doc) instead of Render's layout-keeping bytes, for a document Render cannot lay out: comments and key order are lost, while CRLF line endings and a BOM are kept. It keeps Save's changed-on-disk check.

func (*File) TestLine

func (f *File) TestLine(i int) (line, col int)

TestLine is the 1-based position of tests[i] in Src, or 0, 0 if there is none.

type Finding

type Finding struct {
	Line    int    `json:"line,omitempty"`
	Column  int    `json:"column,omitempty"`
	Field   string `json:"field,omitempty"`
	Message string `json:"message"`

	// Rule and Section place the finding for an editor that jumps to it; they are
	// not part of validate's JSON. Rule is the index of the rule it belongs to,
	// -1 for the document. Section is trigger, action, variables, iterator,
	// filters or tuple, and "" when unknown.
	Rule    int    `json:"-"`
	Section string `json:"-"`
}

Finding is one reason a mapping file is not valid. Line and Column are 1-based and zero when the problem has no position in the file.

func Check

func Check(f *File, ix *ModelIndex) []Finding

Check returns every reason the file is not valid. ix may be nil (no model check). A file that does not compile returns only the compile findings: the filter and model checks need a file mapper accepts.

func FindingsFrom

func FindingsFrom(diags mapper.Diagnostics) []Finding

FindingsFrom converts mapper diagnostics to findings, keeping each message's first line. mapper's YAML syntax errors begin with a "[line:col] " echo of the position; it is trimmed because callers print the position themselves.

type Iterator

type Iterator struct {
	Source string
	As     string
	Tuples []Tuple
}

Iterator fans a rule out over an array in the event. Source is an expression yielding the array; As names the element inside the iterator's tuples.

type LoadError

type LoadError struct {
	Path        string
	Diagnostics mapper.Diagnostics
}

LoadError means the file is not a mapping: the YAML did not parse, or mapper rejected it. Diagnostics carry mapper's positions.

func (*LoadError) Error

func (e *LoadError) Error() string

type ModelIndex

type ModelIndex struct {
	Types          map[string][]string
	UserTypes      map[string][]string
	UserConditions map[string][]string // keyed by userConditionKey
	Conditions     map[string][]string
}

ModelIndex is the authorization model reduced to what the tuple editor needs: which types exist, which relations each has, which user types a relation accepts, and which conditions can be attached.

UserConditions keeps what UserTypes drops: for each relation and user type, the conditions a tuple may carry, "" meaning none. The model may list one user type more than once, as in [user, user with c].

Every accessor tolerates a nil receiver, because "skip the model" is a first class choice in the workspace and the editors should not each re-check.

func IndexModel

func IndexModel(m *openfga.AuthorizationModel) *ModelIndex

IndexModel builds an index from a fetched or loaded model. A nil model indexes to an empty, still-usable index.

func (*ModelIndex) AllRelations

func (ix *ModelIndex) AllRelations() []string

AllRelations returns every relation of every type, deduplicated and sorted: what a relation picker can offer before the object's type is known.

func (*ModelIndex) ConditionNames

func (ix *ModelIndex) ConditionNames() []string

ConditionNames returns every condition in the model, sorted.

func (*ModelIndex) ConditionParams

func (ix *ModelIndex) ConditionParams(name string) []string

ConditionParams returns a condition's parameter names, sorted.

func (*ModelIndex) Empty

func (ix *ModelIndex) Empty() bool

Empty reports whether the index carries no types at all.

func (*ModelIndex) RelationsFor

func (ix *ModelIndex) RelationsFor(typ string) []string

RelationsFor returns typ's relations, sorted.

func (*ModelIndex) TypeNames

func (ix *ModelIndex) TypeNames() []string

TypeNames returns every type, sorted.

func (*ModelIndex) UserConditionsFor

func (ix *ModelIndex) UserConditionsFor(typ, relation, userType string) []string

UserConditionsFor returns the conditions a tuple from userType to typ#relation may carry, "" meaning none.

func (*ModelIndex) UserTypesFor

func (ix *ModelIndex) UserTypesFor(typ, relation string) []string

UserTypesFor returns the user strings typ#relation directly accepts.

func (*ModelIndex) UserTypesForRelation

func (ix *ModelIndex) UserTypesForRelation(relation string) []string

UserTypesForRelation returns the user strings any type's relation of that name directly accepts, deduplicated and sorted. An empty relation means every relation of every type: what a user picker can offer before the object's type is known.

type Path

type Path struct {
	Expr    string
	Kind    string
	Example string
	IsArray bool
}

Path is one addressable field of a sample event, ready to drop into an expression or a template.

func Paths

func Paths(root string, v any) []Path

Paths flattens v into every expression that addresses a field inside it, prefixed with root ("input" at rule scope, the alias inside an iterator). Arrays are both reported themselves — an iterator needs the array, not its elements — and descended through element 0, so a field the user can see in the sample is always pickable.

type Plan

type Plan struct {
	Events          []EventPlan
	Writes, Deletes int
	Unmatched       int
}

Plan is the ordered changes a list of events makes to a store.

func PlanEvents

func PlanEvents(ctx context.Context, m *mapper.Mapping, events []map[string]any, from int, store TupleReader, progress func(done, total int)) (*Plan, error)

PlanEvents evaluates events in order with mapper and runs each result through mapper's own reconciler against a recording client. Reads see the store plus the changes planned for earlier events; writes are recorded, never sent. m must be compiled with tracing (CompileSource does), since Matched comes from the trace. Any event that fails fails the whole plan.

from is the 1-based number of the first event to plan: the ones before it are skipped entirely (a resumed apply), and every event keeps its number in events.

type Preview

type Preview struct {
	YAML        []byte
	Diagnostics mapper.Diagnostics
	Tuples      []language.Tuple
	Filters     []mapper.TupleFilterOperation
	Rules       []mapper.RuleTrace

	// Evaluated reports whether the sample was actually run through the mapping.
	// It is false when there was no sample, and false when the document did not
	// compile — and the two are indistinguishable from the fields above, because
	// both leave Tuples empty. A caller that counts tuples needs the difference:
	// zero tuples measured is a fact about the mapping, zero tuples because
	// nothing ran is a fact about nothing.
	Evaluated bool

	// EvalErr holds a failure that produced no diagnostics to show instead — a
	// Marshal rendering failure, say, where there is no mapper error to derive
	// diagnostics from. An evaluation error from mapper itself is total over
	// DiagnosticsFrom, so it lands in Diagnostics, not here.
	EvalErr error

	// OverBudget reports that mapper stopped the sample for producing more than
	// MaxTuples tuples. mapper checks the budget before it appends each rule's
	// batch, so Tuples then holds only what the earlier rules produced, and
	// TupleCount says nothing about the overrun.
	OverBudget bool
}

Preview is everything the workspace shows about a document at one moment: the bytes it would save, whether they compile, and what the current sample event turns into.

func Evaluate

func Evaluate(ctx context.Context, d *Document, event map[string]any) Preview

Evaluate compiles d and runs event through it. A nil event yields the compile half only, which is what the pane shows before a sample has been chosen.

func (Preview) OK

func (p Preview) OK() bool

OK reports whether the document both compiled and evaluated cleanly.

func (Preview) Problems

func (p Preview) Problems() []Problem

Problems renders the diagnostics as document-level problems, so a caller can list mapper's verdict alongside Lint's. Only the first line of a diagnostic is kept: the rest is the caret art the preview pane already draws.

EvalErr is deliberately not included. A diagnostic means the document itself is wrong; EvalErr is the residue mapper produced no diagnostic for, and one sample event that fails to evaluate does not make the mapping invalid.

func (Preview) TupleCount

func (p Preview) TupleCount() int

TupleCount is how many tuples the sample produced, counted the way mapper counts them against MaxTuples: a rule's own tuples plus the tuples every filter reconciled against. Both halves count, so a rule that writes twenty tuples and patches twenty more has already spent the whole budget.

type Problem

type Problem struct {
	Rule    int
	Section string
	// Item is the 1-based tuple or filter in Section the problem is about,
	// counting the iterator's tuples after the rule's own; 0 when it is about
	// the rule or the section as a whole.
	Item    int
	Field   string
	Message string
	Warning bool
}

Problem is one thing wrong with a document. Blocking problems stop a save; warnings are advisory — the model is a snapshot and a mapping may legitimately target types a newer model will add.

func Blocking

func Blocking(ps []Problem) []Problem

Blocking filters ps down to the problems that must be fixed before saving.

func CheckSamples

func CheckSamples(ctx context.Context, d *Document) []Problem

CheckSamples evaluates every rule's sample through the whole document, the way BuildTests does, and reports what keeps each one from becoming a test: an evaluation error, or a tuple CheckTuple rejects, each blocking; or a warning that the sample evaluates cleanly to nothing at all. A problem is filed under the first rule carrying that sample. Rules without a sample are skipped, and a document that does not compile yields nothing here: its diagnostics are the compile's, not any sample's.

It evaluates every sample, so a caller asks when it needs the answer — at save time — rather than after every keystroke.

func Lint

func Lint(d *Document, ix *ModelIndex) []Problem

Lint checks d for the mistakes mapper cannot catch: structurally incomplete rules the workspace allows mid-edit, and identifiers that compile but do not exist in ix. A nil ix disables the model checks entirely.

func Warnings

func Warnings(ps []Problem) []Problem

Warnings filters ps down to the advisory ones — every check that compared the document against a model, and CheckSamples' sample that makes no test. They are the complement of Blocking.

type Requirement

type Requirement struct {
	Type      string   // "organization"
	Relation  string   // "member"; empty means the type alone is required
	UserTypes []string // {"user"} — the directly-related user types
	DSL       string   // the fragment rendered in the gap panel
}

Requirement is one type-and-relation pair a recipe depends on, with the DSL fragment shown when the loaded model lacks it.

type RequirementStatus

type RequirementStatus struct {
	Requirement Requirement
	TypeOK      bool
	RelationOK  bool
	UserTypesOK bool
	Checked     bool
}

RequirementStatus is what the loaded model has to say about one Requirement.

Checked is false when there is no model to ask, which is a different answer from "missing": the workspace renders an unchecked status as a plain expectation rather than as a failure, since the user who skipped loading a model has not told us anything is wrong.

func CheckRequirements

func CheckRequirements(ix *ModelIndex, reqs []Requirement) []RequirementStatus

CheckRequirements asks the index whether each requirement holds. It reads exactly what lintAgainstModel reads, asked forwards ("will this work?") instead of backwards ("is this broken?").

The checks cascade: a missing type makes the relation unanswerable, and a missing relation makes the user types unanswerable. Reporting those as separate failures would tell the user three things are wrong when one is.

func (RequirementStatus) Satisfied

func (s RequirementStatus) Satisfied() bool

Satisfied reports whether the model covers this requirement. An unchecked status is never satisfied — absence of evidence is not evidence.

type Rule

type Rule struct {
	Name   string
	When   string
	Action string

	Variables []Variable
	Iterator  *Iterator
	Filters   []TupleFilter
	Tuples    []Tuple

	// Sample is the event this rule is previewed against. It is workspace state,
	// not part of the file: BuildTests turns it into a `tests:` entry at save
	// time, and Marshal never writes it.
	Sample *Sample

	// AutoName and AutoWhen record what picking an event last auto-filled, so a
	// later event pick can replace an untouched value but never a hand-edited
	// one. Workspace state; never marshalled.
	AutoName string
	AutoWhen string

	// New marks a rule added in this session that its editor has not been left
	// yet, so it shows guidance rather than errors. Workspace state; never
	// marshalled.
	New bool
}

Rule is one entry under `rules:`. Action is the rule-level action ("write" or "delete", or empty to leave it per-tuple); the language forbids setting it alongside any tuple-level action.

func (Rule) WritesTuples

func (r Rule) WritesTuples() bool

WritesTuples reports whether the rule produces any tuples at all, from its own list or one per item from its iterator.

type Sample

type Sample struct {
	Label string
	Event map[string]any
}

Sample is the event a rule is previewed against: an Auth0 catalog entry, a pasted payload, or one loaded from a file. Label is for display only.

type TestCase

type TestCase struct {
	Name               string
	Input              map[string]any
	ExpectTuples       []language.Tuple
	ExpectTupleFilters []language.TupleFilter

	AssertWritesCoveredByFilter bool
}

TestCase is one entry under `tests:`, generated from a rule's sample at save time so the file carries a regression test for what the workspace showed.

func BuildTests

func BuildTests(ctx context.Context, d *Document) []TestCase

BuildTests turns each rule's preview sample into a `tests:` entry, so a saved file carries a regression test for exactly what the workspace showed.

Each sample is evaluated through the whole document, not through its own rule alone: the `tests:` entry asserts everything the mapping emits for that input, so if the sample also trips a neighbouring rule, the expected tuples include that rule's tuples too, and the generated test fails the moment that stops being true. Samples shared by multiple rules collapse into one entry for the same reason.

Rules without a sample, samples that emit nothing or a tuple CheckTuple rejects, and documents that do not compile all yield no tests: BuildTests never ships a test that asserts nothing, one that cannot run, or one that asserts a tuple FGA would refuse. judgeSample decides, for CheckSamples too.

func NewTest

func NewTest(ctx context.Context, d *Document, name string, event map[string]any) (TestCase, error)

NewTest is a test of event asserting what the whole document produces for it now: the direct tuples, every filter operation's tuples and filters, and filter coverage when it holds — the test a save would generate from a sample of that event. An event no rule matches makes a test expecting nothing.

When the document does not compile, the event fails to evaluate, or it produces a tuple CheckTuple rejects, the error says why and the test comes back expecting nothing, so a caller can still keep it and let it fail with that reason. The last two are judgeSample's faults, through the same sampleFaults, so an own test never asserts a tuple no save would generate a test for.

func SavedTests

func SavedTests(ctx context.Context, d *Document) []TestCase

SavedTests is the `tests:` a save writes: the user's own tests (d.Tests) first, then the ones BuildTests generates from the rules' samples.

A generated test whose input is already an own test's is dropped, so the user's expectations win; that is how a generated test becomes the user's own — copied into d.Tests, then edited. A generated test whose name is taken is renamed with UniqueTestName, since mapper reports results by name.

func SavedTestsAndOrigins

func SavedTestsAndOrigins(ctx context.Context, d *Document) ([]TestCase, map[string]int)

SavedTestsAndOrigins is SavedTests, beside a map from the name of each generated test in it to the index of the rule whose sample it came from; a test the map does not name is one of the user's own. Every generated test costs an evaluation of its sample, so a caller that needs both asks once.

type TestOutcome

type TestOutcome struct {
	Name   string
	Line   int
	Passed bool
	// Missing and Unexpected are multiset differences between expected and
	// actual tuples.
	Missing, Unexpected []language.Tuple
	// MissingFilters and UnexpectedFilters are only set when the test declares
	// expect_tuple_filters, the only case in which mapper compares filters.
	MissingFilters, UnexpectedFilters []language.TupleFilter
	// Uncovered holds the write tuples no filter covers, for tests that set
	// assert_writes_covered_by_filter.
	Uncovered []language.Tuple
	// Expected and Actual are the full sets the test compared; the filter
	// pair is set only when the test declares expect_tuple_filters.
	Expected, Actual               []language.Tuple
	ExpectedFilters, ActualFilters []language.TupleFilter
	Fired                          []string // rules whose `when` matched
	Err                            error
	Duration                       time.Duration
}

TestOutcome is one embedded test's result, with enough detail to say why it failed. The diffs mirror mapper's own pass logic so a failing test always shows a reason and a passing one never shows noise.

type TestRun

type TestRun struct {
	Tests             []TestOutcome
	Filtered, Skipped int
}

TestRun is the outcome of running a file's tests.

func RunTests

func RunTests(ctx context.Context, f *File, filter string, failFast bool) (*TestRun, error)

RunTests compiles f and runs its tests whose name contains filter, each evaluation capped at mapper's DefaultTimeout as CompileSource caps it. A compile failure returns a *LoadError with mapper's diagnostics.

func RunTestsWithTimeout

func RunTestsWithTimeout(ctx context.Context, f *File, filter string, failFast bool, timeout time.Duration) (*TestRun, error)

RunTestsWithTimeout is RunTests with each evaluation capped at timeout. The workspace passes EvalTimeout: it runs every test on each edit, synchronously, so a runaway expression must cost it a second a test, not mapper's three. A test that takes between the two then fails there and passes in `ofga mappings test`, which is the CLI's verdict to keep.

func (TestRun) Failed

func (r TestRun) Failed() int

Failed counts the tests that did not pass.

type Tuple

type Tuple struct {
	User      string
	Relation  string
	Object    string
	When      string
	Action    string
	Condition string
	Context   []ContextEntry
}

Tuple is one entry under `tuples:`. User, Relation and Object are templates with `{{ expr }}` interpolation; When gates this tuple alone; Action is "write" (default) or "delete"; Condition names an FGA condition and Context supplies its parameters.

type TupleFilter

type TupleFilter struct {
	User     string
	Relation string
	Object   string
	Action   string
}

TupleFilter is one entry under `tuple_filters:`, describing the slice of existing tuples a rule owns. Action is "patch" (default) or "delete".

type TupleReader

type TupleReader interface {
	ReadTuples(ctx context.Context, filter language.TupleFilter) ([]language.Tuple, error)
}

TupleReader reads tuples from a store.

type TupleWriter

type TupleWriter interface {
	Write(ctx context.Context, writes, deletes []language.Tuple) error
}

TupleWriter writes tuples to a store in one request.

type Variable

type Variable struct {
	Name string
	Expr string
}

Variable is one entry under `variables:`. Order matters: each expression sees input plus the variables declared before it, and forward references are a compile error.

Directories

Path Synopsis
Package auth0 carries a catalog of Auth0 Events event types and an example payload for each, embedded so the `ofga mappings` workspace can preview a rule without network access.
Package auth0 carries a catalog of Auth0 Events event types and an example payload for each, embedded so the `ofga mappings` workspace can preview a rule without network access.

Jump to

Keyboard shortcuts

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