endpoint

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 29 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 endpoint is the DSL for the controller's own API: the operations that run on the controller, such as the agents, the jobs and the audit log, and not on a host. A group's definition is Go; its OpenAPI part, and later its routes, CLI commands and tests, come from it. A behavior is work on a host and has its own DSL, internal/behavior.

Index

Constants

View Source
const (
	KindDefinition = "definition"
	KindOption     = "option"
	KindMethod     = "method"
	KindRefine     = "refine"
	KindError      = "error"
	KindDeps       = "deps"
	KindTag        = "tag"
	KindCheck      = "check"
	KindGenerated  = "generated"
)

The kinds of term in Spec, in the order that a group is written.

View Source
const (
	RuleName    = "name"
	RuleArea    = "area"
	RuleMethods = "methods"
	RuleUnique  = "unique"
	RuleSegment = "segment"
	RuleAction  = "action"
	RuleKey     = "key"
	RuleID      = "id"
	RuleRoute   = "route"
	RuleSchema  = "schema"
	RuleHandler = "handler"
	RuleSubDoc  = "subdoc"
	// RuleValidate is the same check in the behavior DSL, from package rule.
	RuleValidate = "validate"
	// RuleFails is the same check in the behavior DSL, from package rule.
	RuleFails = "fails"
	// RuleOptional: an optional field of a request body is left out of the
	// JSON when it is empty, so a client does not send "" for it.
	RuleOptional = "optional"
	// RuleIn: each in tag of an input field is path, query, form or body.
	// Any other value falls into the request body with no error.
	RuleIn = "in"
	// RuleField: a field that Location or Example names is a json field of
	// its type. A misspelled name gave a Location of <nil>, or dropped the
	// example from the spec, with no error.
	RuleField = "field"
	// RuleReason: each error that a method maps has a valid types.Reason. Go
	// converts an untyped literal to types.Reason, so Because("not_manged")
	// compiles, and the caller would get a word the schema does not list.
	RuleReason = "reason"
	// RuleExample: each flag that an Example names is a flag of the
	// method's command. A misspelled flag showed a command on its docs page
	// that fails.
	RuleExample = "example"
	// RulePrints: the output that Prints gives an example is a value of the
	// method's output type, and Prints follows an Example. Prints takes any
	// value, so a sample of another type compiles.
	RulePrints = "prints"
	// RuleSecret: a secret.Value input field is not in the path or the
	// query, which logs keep with the URL, and is not recorded on a span.
	RuleSecret = "secret"
	// RuleStutter: a type of the group's package does not repeat the name
	// of its package, as agent.AgentInfo does. Go reads it as agent.Info.
	RuleStutter = "stutter"
)

The rules Validate checks, by the name a Problem reports.

View Source
const AreaExtension = "x-osapi-area"

AreaExtension is the extension of each operation and each tag of the spec that names its area, one of area.All, such as fleet. The full spec groups the tags by it in x-tagGroups.

View Source
const AreasExtension = "x-osapi-areas"

AreasExtension is the extension of the full spec that lists the areas, area.All, in their order, each with its name and its label. A generator that reads the spec, such as the SDK's pages, takes the areas from it.

View Source
const ExamplesExtension = "x-osapi-examples"

ExamplesExtension is the extension of an operation of the spec that has the examples of its method: for each, the doc and the input, by the name of each parameter and property of the body. The SDK's generator writes a program from them that calls the method with each input.

View Source
const GroupExtension = "x-osapi-group"

GroupExtension is the extension of each tag of the spec that names its group, such as dns or agent: the segment of its paths that the group's own operations start at. The SDK names its services from it, as the tag's x-displayName is a title for a person, such as Package updates.

View Source
const MethodExtension = "x-osapi-method"

MethodExtension is the extension of each operation of the spec that names the method in its group, such as get or drain.

View Source
const ProgramExtension = "x-osapi-program"

ProgramExtension marks an operation that a program calls, not a person, which NoCommand sets: it has no CLI command, and the SDK needs no example of it, since an example would run it against a controller.

View Source
const SecretExtension = "x-osapi-secret"

SecretExtension marks a field, or the value of a map, of type secret.Value: a reference, secret://<vault>/<key>, or the value.

View Source
const SettingsPrefix = "controller.endpoints"

SettingsPrefix is where each endpoint group's settings sit in osapi's config: controller.endpoints.<name>.<field>.

Variables

View Source
var Checks = guide.Checks{
	{
		Rule:     RuleStutter,
		Requires: "No type of the group's package that a method uses repeats the name of its package, such as agent.AgentInfo: Go code reads it as agent.Info. revive's exported rule refuses it too.",
		Fix:      "Drop the package's name from the type, and keep its API name with a schema tag on its blank field: type Info struct { _ struct{} `schema:\"AgentInfo\"` }. Never write //nolint:revive.",
	},
	{
		Rule:     RuleSecret,
		Requires: "No secret.Value input field is tagged in:\"path\" or in:\"query\", or telemetry:\"attr\": a URL goes in logs, and a span is no place for a secret.",
		Fix:      "Send the secret in the body: drop its in tag, or tag it in:\"body\" or in:\"form\". Remove telemetry:\"attr\" from it.",
	},
	{
		Rule:     RuleExample,
		Requires: "Each flag that an Example names is a flag of the method's command: a field of its input, a field of the struct that in:\"body\" names, or --json, --debug or --osapi-file.",
		Fix:      "Spell each flag of the example as the command has it: osapi dsl endpoint get --name <group> lists the methods, and the command's --help lists its flags.",
	},
	{
		Rule:     RulePrints,
		Requires: "The output that Prints gives an example is a value of the method's output type, and Prints follows an Example.",
		Fix:      "Give Prints a value of the method's output type, after the Example that it shows.",
	},
	{
		Rule:     RuleIn,
		Requires: "Each in tag of an input field is path, query, form or body.",
		Fix:      "Correct the value. A field with another value is read from the request body, not from where the tag says.",
	},
	{
		Rule:     RuleReason,
		Requires: "Each error that a method maps has a reason that types.Reason lists.",
		Fix:      "Use a types.Reason constant, such as endpoint.ReasonNotManaged, in Because.",
	},
	{
		Rule:     RuleField,
		Requires: "The field that Location names is a json field of the method's output, and the field that Example[T] names is a json field of T.",
		Fix:      "Correct the name to the json name of the field, such as job_id.",
	},
	{
		Rule:     RuleArea,
		Requires: "The group has an area, one of area.All, so the UI, the SDK's pages and the docs site can place its operations.",
		Fix:      "Add endpoint.Area(...) to the group's definition with a constant of package area, such as area.Fleet. Add a new area to area.All with its label first.",
	},
	{
		Rule:     RuleName,
		Requires: "The group and each method have a name of lowercase letters and digits, starting with a letter.",
		Fix:      "Name the group as its path segment, such as agent, and each method for what it does, such as list or drain.",
	},
	{
		Rule:     RuleMethods,
		Requires: "The group has at least one method.",
		Fix:      "Add a method with endpoint.Get, Post, Put or Delete.",
	},
	{
		Rule:     RuleUnique,
		Requires: "No two methods of a group have one name.",
		Fix:      "Give each method its own name.",
	},
	{
		Rule:     RuleSegment,
		Requires: "Each Sub and Action segment is lowercase letters and digits.",
		Fix:      "Use one word, such as pending or drain.",
	},
	{
		Rule:     RuleAction,
		Requires: "A method with an Action has a key: an input field tagged in:\"path\".",
		Fix:      "Tag the field the action is on in:\"path\", or use Sub for a fixed path.",
	},
	{
		Rule:     RuleKey,
		Requires: "An input has at most one field tagged in:\"path\" besides the fields of the Prefix, or .Key names each of them in the order of the path. Each field that .Key or the Prefix names is an in:\"path\" field of the input, is not a secret, and is named once.",
		Fix:      "Tag one field in:\"path\". For a key with more than one field, such as a key in a vault, name each in order with .Key(\"vault\", \"key\").",
	},
	{
		Rule:     RuleID,
		Requires: "Each operationId is used once, and starts with a capital letter, as each operationId of the API does.",
		Fix:      "Give the method its own ID with .ID, in Pascal case, such as GetAgents.",
	},
	{
		Rule:     RuleRoute,
		Requires: "No two methods have one verb and path.",
		Fix:      "Change the verb, the Sub or the Action.",
	},
	{
		Rule:     RuleHandler,
		Requires: "A group that Uses a type gives each method a handler, func(context.Context, D, In) (Out, error), with D that type and In and Out the method's types. A group with a handler Uses a type.",
		Fix:      "Add .Handle(fn) to each method, with the signature that the message names, and endpoint.Uses[Deps]() to Define.",
	},
	{
		Rule:     RuleSubDoc,
		Requires: "Each Sub segment that makes a command of its own, such as stale in osapi client file stale list, has a SubDoc: the one line of help of that command.",
		Fix:      "Add endpoint.SubDoc(\"segment\", \"...\") to Define, with what the segment's commands do, such as Read the deployments whose file changed since.",
	},
	{
		Rule:     RuleValidate,
		Requires: rule.Requires,
		Fix:      rule.Fix,
	},
	{
		Rule:     RuleFails,
		Requires: rule.FailsRequires,
		Fix:      rule.FailsFix,
	},
	{
		Rule:     RuleOptional,
		Requires: "An optional field of a write's request body, with omitempty in its validate tag, has omitempty in its json tag too, so a client leaves it out when it is empty instead of sending \"\" or 0, which its other rules can refuse.",
		Fix:      "Add ,omitempty to the field's json tag, such as json:\"reason,omitempty\".",
	},
	{
		Rule:     RuleSchema,
		Requires: "The spec builds: each input and output type is one that JSON can encode, and each validate rule has a schema.",
		Fix:      "Use structs, slices, maps, strings, numbers, bools and time.Time; not channels or functions. Register the schema of a custom validate rule with rule.Register, beside its validator in internal/validation.",
	},
}

Checks are the rules Validate applies. osapi dsl endpoint validate --help prints each one, and each problem carries the fix of its rule, so an author or an agent can read the rules before breaking one. The tests trigger each rule, and fail on a rule without a check.

View Source
var ReasonDocs = map[types.Reason]string{
	types.ReasonInvalidRequest: "the request breaks a rule, such as a missing field (400).",
	types.ReasonUnauthorized:   "no token, or a token that is not valid (401).",
	types.ReasonForbidden:      "the token does not have the permission (403).",
	types.ReasonNotFound:       "the host or osapi does not have what the request names (404).",
	types.ReasonNotManaged:     "the item is there, but osapi did not deploy it, so osapi does not change it (409).",
	types.ReasonNotInstalled:   "the host does not have a program that the request needs (409).",
	types.ReasonConflict:       "the state of the item blocks the request, such as a create of one that exists (409).",
	types.ReasonUnavailable:    "a part that osapi depends on is down, such as NATS (503).",
	types.ReasonServerError:    "the controller failed; its log has the cause (500).",
}

ReasonDocs say when each reason is the answer, with its status. The ErrorResponse schema of the spec has them.

View Source
var Spec = guide.Spec{
	Kinds: []guide.Kind{
		{Kind: KindDefinition, Title: "Definition"},
		{Kind: KindOption, Title: "Options of Define"},
		{Kind: KindMethod, Title: "Methods"},
		{Kind: KindRefine, Title: "Refinements of a method"},
		{Kind: KindError, Title: "Errors a method maps"},
		{Kind: KindDeps, Title: "What a Deps takes"},
		{Kind: KindTag, Title: "Tags on input and output fields"},
		{Kind: KindCheck, Title: "What holds a group to its spec"},
		{Kind: KindGenerated, Title: "Generated, never edited"},
	},
	Terms: []guide.Term{
		{
			Kind: KindDefinition,
			Name: `Register(Define(name, doc, options...))`,
			Does: "Declares the group and adds it to the registry. The commands and the tests read the registry. Each path of the group starts /api/<name>.",
			When: "One time, in <group>.go under internal/controller/endpoints/<group>: var Group = endpoint.Register(endpoint.Define(...)). Add its import to internal/controller/endpoints/all.",
		},

		{
			Kind: KindOption,
			Name: `Area(area.Name)`,
			Does: "Puts the group's operations in an area, one of area.All: the folder of the SDK's page and of the group's reference page, and its section of the docs site's SDK menu. The UI's Behaviors page shows the behaviors of an area, not the endpoints. The spec gives each operation its area as x-osapi-area. Use a constant of package area, such as area.Fleet. area.All has the label and the order of each area.",
			When: "In each group. endpoint validate refuses a group with none.",
		},
		{
			Kind: KindOption,
			Name: `Title("title")`,
			Does: "Sets the title of the group's spec. The full spec puts it in front of each tag, and the UI's client files get their names from the result.",
			When: "When a group moves from a hand-written spec: copy its info.title, so no client file is renamed.",
		},
		{
			Kind: KindOption,
			Name: "Uses[Deps]()",
			Does: "Names the struct of what the group's handlers use, such as the job client. The controller gives one at startup, and a test gives one with fakes. It is the place of the host in a behavior.",
			When: "In each group that is served. Keep it to interfaces, so a test can fake each one.",
		},
		{
			Kind: KindOption,
			Name: "Config(defaults)",
			Does: "Declares the group's own settings: defaults is a struct whose fields carry mapstructure, doc and validate tags, as osapi's config does, and whose values are the defaults. They join the config under controller.endpoints.<group>: osapi config list shows them, OSAPI_CONTROLLER_ENDPOINTS_<GROUP>_<FIELD> sets them, and config validate checks them. The group's .SettingsKey(), .SettingsType(), .SetSettings(v) and .CurrentSettings() are what the config loader calls.",
			When: "For a setting that only the group reads, such as a limit of its handlers, so the core config in internal/config does not change for it. A request's values are its input, never a setting.",
		},
		{
			Kind: KindCheck,
			Name: "Settings[T](g)",
			Does: "The group's settings as T, the struct that Config took: the config's values once the controller loaded it, else the defaults.",
			When: "In a handler, as endpoint.Settings[Limits](Group).",
		},
		{
			Kind: KindOption,
			Name: `Doc[T]("description")`,
			Does: "Describes T, a named type, in its schema. Go has no tag on a type, so a group says it here.",
			When: "For each type whose schema has a description, such as one that another group defines too: the full spec fails when two groups define one schema in different words.",
		},
		{
			Kind: KindOption,
			Name: `Example[T]("field", "example")`,
			Does: "Gives the field of T with that json name its example in the schema.",
			When: "For an example with a double quote, such as a JSON document. A struct tag cannot keep the backslash of a quote, because the formatters drop it.",
		},
		{
			Kind: KindOption,
			Name: `Tag("name", "display", "doc")`,
			Does: "Sets the tag of each operation, its name in the docs and its description.",
			When: "When a group moves: copy its tag. A new group can leave it; the tag is then the group's name.",
		},
		{
			Kind: KindOption,
			Name: `CommandLong("text")`,
			Does: "Is the rest of the help of the group's command, after its one line.",
			When: "When the group's command needs more than its one line, such as what most of its commands read.",
		},
		{
			Kind: KindOption,
			Name: `SubDoc("segment", "short")`,
			Does: "Is the one line of help of the command that a Sub segment makes, such as stale in osapi client file stale. Without it, the command says <Segment> commands.",
			When: "For each Sub segment of the group, so its command says what it holds.",
		},
		{
			Kind: KindOption,
			Name: `CommandNotes("text")`,
			Does: "Adds a Notes section to the page of the group's own command, such as a link to a page that tells more about the group.",
			When: "When the group's command has a page of its own to point at, as each behavior's does.",
		},
		{
			Kind: KindOption,
			Name: `Prefix("next/node/{hostname}")`,
			Does: "Puts each path of the group under a prefix, between /api/ and the group's name. Each {field} of the prefix is an in:\"path\" field of each method's input, which is not the method's key.",
			When: "For the groups that the behavior generator writes, whose paths start with the target host. A group of the controller has none. The fixed segments are the command's path too: next node sysctl.",
		},

		{
			Kind: KindMethod,
			Name: `Get[In, Out]("name")`,
			Does: "A GET that takes In and answers with Out. Its permission is <group>:read.",
			When: "For a read.",
		},
		{
			Kind: KindMethod,
			Name: `Post[In, Out]("name")`,
			Does: "A POST that takes In and answers with Out. Its permission is <group>:write.",
			When: "For a create, or an action such as drain.",
		},
		{
			Kind: KindMethod,
			Name: `Put[In, Out]("name")`,
			Does: "A PUT that takes In and answers with Out. Its permission is <group>:write.",
			When: "For an update of the thing the key names.",
		},
		{
			Kind: KindMethod,
			Name: `Delete[In, Out]("name")`,
			Does: "A DELETE that takes In and answers with Out. Its permission is <group>:write.",
			When: "For a removal.",
		},

		{
			Kind: KindRefine,
			Name: ".Handle(fn)",
			Does: "Sets the function that runs the method: func(ctx context.Context, d Deps, in In) (Out, error). The generated route decodes and validates In, calls it, and maps its error with Errors. Only the route calls it; other code that needs the work goes through the API.",
			When: "On each method of a group that Uses a type. Validate checks the signature.",
		},
		{
			Kind: KindRefine,
			Name: `.Sub("segment")`,
			Does: "Puts a fixed segment after the group's name, before the key: /api/<group>/<segment>[/{key}]. When the segment is not the method's name, the CLI command is under it too: osapi client <group> <segment> <method>.",
			When: "For a path beside the key, such as /api/agent/pending, or with no key, such as /api/file/stale.",
		},
		{
			Kind: KindRefine,
			Name: `.CommandSub("word")`,
			Does: "Puts the CLI command under a word that is not a segment of the path: osapi client <group> <word> <method>. The word needs a SubDoc, as a Sub does.",
			When: "When the command names a resource that the path does not, such as vault in osapi client secret vault list for GET /api/secret.",
		},
		{
			Kind: KindRefine,
			Name: `.Key("field", ...)`,
			Does: "Names the in:\"path\" fields of the key, in the order of the path: /api/<group>[/<segment>]/{field}/.../{key}. The last field names what the method acts on, as the CLI line of a method with no body says. Without it, the key is the one in:\"path\" field that the Prefix does not name. endpoint validate checks that each named field is a path field of the input, is not a secret, and is named once, and that no other path field is left out.",
			When: "For a key that is unique only in the thing that holds it, such as a key in a vault: .Key(\"vault\", \"key\") for /api/secret/{vault}/{key}. A list of the keys of one vault names only the holder: .Key(\"vault\").",
		},
		{
			Kind: KindRefine,
			Name: `.Action("segment")`,
			Does: "Puts a segment after the key: /api/<group>/{key}/<segment>.",
			When: "For an action on one thing, such as /api/agent/{hostname}/drain. Needs a key.",
		},
		{
			Kind: KindRefine,
			Name: `.ID("operationId")`,
			Does: "Sets the operationId. The Go SDK and the UI client get their names from it. Without it, the ID is the verb, the group, the Sub and the name.",
			When: "When a group moves: keep the ID of the hand-written spec, so no name that a program calls changes.",
		},
		{
			Kind: KindRefine,
			Name: `.Describe("summary")`,
			Does: "Sets the summary: what the method does, in one line.",
			When: "Always.",
		},
		{
			Kind: KindRefine,
			Name: `.Explain("text")`,
			Does: "Sets the description: the rest of what a caller needs to know.",
			When: "When the summary is not enough, such as what occurs when two agents share a hostname.",
		},
		{
			Kind: KindRefine,
			Name: `.Returns("doc")`,
			Does: "Describes the response of a success. Without it, the summary describes it.",
			When: "When the response needs its own words, such as \"List of active agents.\".",
		},
		{
			Kind: KindRefine,
			Name: `.Command("short", "long")`,
			Does: "Sets the CLI command's own help: its one line and the rest. Without it, the command has the summary and the description of the API. The one line, and the doc of each input field that becomes a flag's help, start with a capital letter and have no period at the end; the long help is sentences. A test of every command holds this.",
			When: "When the CLI needs words for a person at a shell, such as what the command reads and what to run next.",
		},
		{
			Kind: KindRefine,
			Name: `.Fails("doc", in)`,
			Does: "Declares an input that the API refuses with 400: the method's input, with the other fields valid and one rule broken. A test sends each one through the routes. " + rule.FailsRequires,
			When: rule.FailsWhen,
		},
		{
			Kind: KindRefine,
			Name: `.Example("--flag value", "doc")`,
			Does: "Adds an example of the CLI command: the flags after osapi client <group> <method>, and, when given, what it shows, as a # line above it. The help and the CLI page show each one.",
			When: "At least one for each method: the call a person makes most.",
		},
		{
			Kind: KindRefine,
			Name: ".Prints(out)",
			Does: "Gives the last Example its output: what the API answers, a value of the method's output type. The CLI page shows it as the CLI prints it, in its colors, and as the JSON that --json prints. endpoint validate refuses a value of another type, and Prints before an Example.",
			When: "After the first Example of each method that answers with a body. Times in the value are relative to 2026-01-15 10:00 UTC, the time that the docs generator fixes, so an age is the same on each run.",
		},
		{
			Kind: KindRefine,
			Name: `.Check("words", "flags", path, want, ...)`,
			Does: "Gives the last Example a read that shows its result: the command words after the binary, its flags, and pairs of a path in its --json output and the value that the path must have. A path is JSON names joined with a dot, and a segment [name=value] selects an element of a list. command.Absent is a field that must not be there, and command.OneOf a field that may have any of its values. {out.<path>} is a field of the example's own --json output. The integration suite runs the read after the example, again for up to 30 seconds until it matches.",
			When: "After each Example of a write: the integration gate fails a write example with no Check, CheckFails or NoCheck.",
		},
		{
			Kind: KindRefine,
			Name: `.CheckFails("words", "flags", "text")`,
			Does: "Gives the last Example a read that must fail with text in its error, such as not found: the example removed the thing that the read names.",
			When: "After each Example of a delete or a revoke.",
		},
		{
			Kind: KindRefine,
			Name: `.NoCheck("why")`,
			Does: "Says why no read shows the result of the method's examples. The integration gate takes it in place of a Check, and requires a reason of 40 characters or more.",
			When: "Only on a write whose result no osapi command reads back, such as the streams that nats setup makes.",
		},
		{
			Kind: KindRefine,
			Name: `.Use("name")`,
			Does: "Names the CLI command apart from the method. A method whose Sub differs from its command name goes under a command of the Sub.",
			When: "When the command's verb is a method name the group has already, such as list under pending beside the group's own list.",
		},
		{
			Kind: KindRefine,
			Name: `.Location("field")`,
			Does: "Gives a 201 the Location header: the group's path and the value of the output's field with that json name.",
			When: "For each method that creates a resource and answers 201, such as job retry with job_id.",
		},
		{
			Kind: KindRefine,
			Name: `.Answers(code, "doc")`,
			Does: "Adds a status that the method answers with its own output, not an ErrorResponse. The method returns its output with endpoint.Answer(code).",
			When: "For a probe whose failure has a body that says what failed, such as the 503 of health ready.",
		},
		{
			Kind: KindRefine,
			Name: `.Notes("text")`,
			Does: "Adds a Notes section to the CLI command's page.",
			When: "For what a person needs that the help does not say, such as what --json has that the table does not.",
		},
		{
			Kind: KindRefine,
			Name: `.Result("text")`,
			Does: "Adds a Result section to the CLI command's page.",
			When: "For what the command does in a case that needs words, such as when two agents share a hostname.",
		},
		{
			Kind: KindRefine,
			Name: `.Permission(types.PermGroupVerb)`,
			Does: "Names the permission the method needs, in place of <group>:read or <group>:write. " +
				"It takes a types.Permission: use a Perm constant of pkg/sdk/types, not a string. " +
				"The constant is Perm, then the resource and the verb, such as PermAgentRead; " +
				"osapi controller role get --name admin lists each permission. " +
				"It must be one that a group, a behavior or the hand-written domains declare: " +
				"a test fails on a name that nothing declares, because no role grants it.",
			When: "When a different permission covers it, such as agent:read for facts, or trace:read for telemetry.",
		},
		{
			Kind: KindRefine,
			Name: ".AdminOnly()",
			Does: "Makes the method's permission one that only the admin role grants. By the rule, " +
				"admin gets each permission; operator each read and each execute permission, and automation each read and each write permission, that is not admin only; read each read that is not admin only; auditor and observer get their lists; a shell permission is admin only with no mark. " +
				"Each method with the same permission must agree. osapi controller role get --name automation " +
				"shows what a role gets.",
			When: "For a trust decision or a record of who did what, such as admission:write, " +
				"agent:write or audit:read.",
		},
		{
			Kind: KindRefine,
			Name: ".Public()",
			Does: "Makes the method need no bearer token, so it has no 401, and no 403 for a permission.",
			When: "For the health probes that a load balancer calls, and for the agent's join, which its join token authorizes.",
		},
		{
			Kind: KindRefine,
			Name: ".NoCommand()",
			Does: "Gives the method no CLI command. Its route, its spec and its SDK method are as each other method's.",
			When: "For a method that a program calls, not a person, such as the agent's join, whose request the agent signs.",
		},
		{
			Kind: KindRefine,
			Name: ".Status(code)",
			Does: "Sets the status of a success. 204 has no body.",
			When: "For 201 after a create or a retry, or 204 after a delete with nothing to return.",
		},
		{
			Kind: KindRefine,
			Name: `.Says("state")`,
			Does: "Sets what the CLI prints for a method that answers with no body: the key of the input, then the text, such as web-01 draining. Without it, the CLI prints the past tense of the method, such as m-1 admitted for admit.",
			When: "On a method that answers 204 and whose result is a state, not the past tense of the method, such as drain.",
		},
		{
			Kind: KindRefine,
			Name: ".Errors(errors...)",
			Does: "Maps the errors a method returns to status codes. An error that is not in the list is a 500. Each method also gets 400 when it has an input, 401 and 403 when it is not public, and 500.",
			When: "For each answer a caller acts on, such as 404 or 409. Never map a failure of the controller to 409.",
		},

		{
			Kind: KindError,
			Name: `Errorf(sentinel, "format", args...)`,
			Does: "Is an error whose text is the message, and that errors.Is matches to sentinel. The answer has the status that Errors maps sentinel to, and the message as its error.",
			When: "In a handler, to answer 404 or 409 with a message that names what it was called with, such as no pending agent with hostname \"web-01\".",
		},
		{
			Kind: KindError,
			Name: `Internal("msg", cause)`,
			Does: "Is a failure of the controller whose cause stays out of the answer: the caller gets msg and a 500, and the log gets the cause.",
			When: "When the cause has what a caller must not see, such as the address or the error of a backend.",
		},
		{
			Kind: KindError,
			Name: `.Because(reason)`,
			Does: "Gives a mapped error a reason other than the reason of its status, such as Conflict(behavior.ErrNotManaged, doc).Because(types.ReasonNotManaged). Each error answer is {error, reason}: the status is the class of the problem, the reason is the cause that a program branches on, one of the values of types.Reason, and the message is for a person. Each helper sets the reason of its status: NotFound not_found, Conflict conflict, Invalid invalid_request, Forbidden forbidden, Unavailable unavailable.",
			When: "When two errors of one status are different causes, such as not_managed and not_installed beside conflict.",
		},
		{
			Kind: KindError,
			Name: "ReasonFor(status)",
			Does: "The reason of a status that no mapped error names, such as a route that does not exist, or a 500, which is server_error.",
			When: "In a writer of error answers outside the generated routes, such as the error handler of the API.",
		},
		{
			Kind: KindError,
			Name: `NotFound(err, "doc")`,
			Does: "Maps err to 404.",
			When: "When the thing the key names is not there.",
		},
		{
			Kind: KindError,
			Name: `Conflict(err, "doc")`,
			Does: "Maps err to 409.",
			When: "When the state of the thing does not allow the call, such as an agent that is already drained.",
		},
		{
			Kind: KindError,
			Name: `Answer(code)`,
			Does: "Returned with the method's output, sends that output with code: a status that .Answers added.",
			When: "When a probe fails and its body says what failed, such as health ready's 503.",
		},
		{
			Kind: KindError,
			Name: `Forbidden(err, "doc")`,
			Does: "Maps err to 403. Its doc is the 403's description, so say the permission failure too.",
			When: "When the token may make the request, but not on this thing, such as a write to a file that osapi owns.",
		},
		{
			Kind: KindError,
			Name: `Invalid(err, "doc")`,
			Does: "Maps err to 400. Its doc is the 400's description, so say the decode failures too.",
			When: "When the request is well formed but the method cannot do it, such as a retry of a job with no operation data.",
		},
		{
			Kind: KindError,
			Name: `Unavailable(err, "doc")`,
			Does: "Maps err to 503.",
			When: "When a backend the method needs is not set, such as the trace backend.",
		},

		{
			Kind: KindDeps,
			Name: "an interface of the group, in deps.go",
			Does: "Each field of Deps is an interface that the group declares in its deps.go, with only the methods that its handlers call. internal/controller/handlers.go gives the real service of the controller. The tests give the mockgen mock from the group's mocks/, so a handler test sets what each call returns and asserts each call it makes.",
			When: "For each service that a handler uses. Declare a narrow interface, not the concrete type, and never write a fake by hand. A group whose service the controller may not have, such as a store with no bucket, checks for nil.",
		},
		{
			Kind: KindDeps,
			Name: "Jobs",
			Does: "The job client of the controller: it lists and reads the agents and the jobs, sets the drain flag, writes the timeline of an agent, and deletes and retries jobs. handlers.go gives d.jobs.",
			When: "For a group that reads or changes the agents or the jobs, such as agent, job and admission. A request that runs on a host is a behavior, not a Jobs call of an endpoint.",
		},
		{
			Kind: KindDeps,
			Name: "Store",
			Does: "A store of the controller in its own KV bucket: the admission records of the agents, or the entries of the audit log.",
			When: "For the group that owns the records. A Store can be nil when the controller has no bucket for it; the group answers that the feature is off.",
		},
		{
			Kind: KindDeps,
			Name: "Objects, States",
			Does: "The Object Store, which holds the files that osapi client file upload stores, and the file-state KV, whose keys are the files that agents deployed. fileDeps in handlers.go opens both.",
			When: "For the file group. An agent reads an object through the object behavior, not through an endpoint.",
		},
		{
			Kind: KindDeps,
			Name: "Admissions",
			Does: "The admission records, which say the keys that the controller admitted for each machine.",
			When: "For the agent group's list and get, which show an agent whose keys are not the admitted keys as Refused, with the KeyMismatch condition.",
		},
		{
			Kind: KindDeps,
			Name: "Health",
			Does: "The health.Reporter of the controller: the state of NATS, the controller and its parts, for the health, controller, nats and agent groups.",
			When: "For a group that reports whether a part of osapi is up.",
		},
		{
			Kind: KindDeps,
			Name: "Joiner",
			Does: "The admission watcher, which admits the machine of a join request whose token admits, and gives the controller's public key.",
			When: "For the agent group's join. A controller with no watcher gives none, and join answers 503.",
		},
		{
			Kind: KindDeps,
			Name: "Traces",
			Does: "The TraceReader: it reads one trace from the tracing backend that the config names, for osapi client telemetry trace get.",
			When: "For the telemetry group.",
		},
		{
			Kind: KindDeps,
			Name: "Agents",
			Does: "Lists the agents, each with what its registration reports, such as its certificates. The job client is one; a test gives a mockgen mock.",
			When: "For the pki group, which lists each agent's certificates.",
		},
		{
			Kind: KindDeps,
			Name: "Local",
			Does: "The certificates of the controller's host, the controller's and the NATS server's, which handlers.go reads from the files of the host at each call. A test gives a func that returns fixed ones, or nil for none.",
			When: "For the pki group.",
		},
		{
			Kind: KindDeps,
			Name: "Hostname",
			Does: "The hostname of the controller's host, from os.Hostname, which names the host of the controller's own certificates. A test gives a fixed name.",
			When: "For the pki group, whose get takes a certificate of the controller's host when the hostname is empty.",
		},
		{
			Kind: KindDeps,
			Name: "Rotation",
			Does: "Starts and shows the rotation of the controller's key: the *keyrotation.Rotation that startEnrollment makes and runs. A test gives a mockgen mock.",
			When: "For the pki group, whose key rotation and key rotate methods use it.",
		},
		{
			Kind: KindDeps,
			Name: "CertRotation",
			Does: "Starts and shows the rotation of the NATS server's certificate: the *certrotation.Rotation that startEnrollment makes and runs. A test gives a mockgen mock.",
			When: "For the pki group, whose nats get and nats rotate methods use it.",
		},
		{
			Kind: KindDeps,
			Name: "Vaults",
			Does: "The vaults of controller.secrets.vaults, by name: each vault's spec, and the vault.Vault that gets, puts, deletes and lists its keys. handlers.go gives the vault.Set that the controller opens at startup.",
			When: "For the secret group. A handler reads the metadata of a key from List, so that no method reads a value that it does not give.",
		},
		{
			Kind: KindTag,
			Name: `param:"Name"`,
			Does: "Makes a path field a shared parameter: the spec has it once, under components.parameters.Name, and each operation refers to it.",
			When: "On a path field that each method of a group has, such as the hostname of a behavior's target.",
		},
		{
			Kind: KindTag,
			Name: `_ struct{} ` + "`schema:\"Name\"`",
			Does: "Names the schema of a type in the spec, as json names a field: on the type's blank field, because Go has no tag on a type. Without it, the schema is the type's Go name. It keeps an API name when the Go name is shorter: agent.Info has the schema AgentInfo, and the SDK and the UI keep their names. It sits beside title, which the CLI reads: _ struct{} `title:\"Agent\" schema:\"AgentInfo\"`. The spec refuses two types with one schema name.",
			When: "On each type of a group's package whose Go name would repeat its package: the stutter rule refuses agent.AgentInfo, and revive does too. Never write //nolint:revive.",
		},
		{
			Kind: KindCheck,
			Name: "SchemaName(t)",
			Does: "The schema name of t in the spec: its schema tag, or its Go name.",
			When: "Nothing to call: give a type the tag, and the spec reads it.",
		},
		{
			Kind: KindTag,
			Name: "secret.Value",
			Does: "Not a tag: the type of an input field that holds a secret, from internal/secret; map[string]secret.Value is a map of them. It is a reference, secret://<vault>/<key>, or the value. The spec makes it a string of format password, writeOnly and x-osapi-secret, and its description says what it takes. The audit redacts it by name, but keeps a reference. The CLI flag takes a reference, or - to read the value from standard input, and refuses a value. Its String, Format, MarshalJSON and LogValue give the reference or [redacted]; Reveal gives the value. The route resolves a reference from its vault, after the limits of use: secret:use, and the targets of the vault. The secret rule refuses one in:\"path\" or in:\"query\", or with telemetry:\"attr\".",
			When: "On each input that holds a password, a key or a token. Not a string: a string whose name is on the audit denylist fails TestSecretsAreTyped.",
		},
		{
			Kind: KindCheck,
			Name: "SecretFields()",
			Does: "The json names of each secret.Value input field of each registered group, a behavior's group too, at each depth. The audit summary redacts each, with its fixed denylist.",
			When: "Nothing to call: give a secret field the type, and the audit finds it.",
		},
		{
			Kind: KindTag,
			Name: `in:"path"`,
			Does: "Makes the input field the key: {name} in the path. It is required. A method has at most one, besides the fields that the group's Prefix names.",
			When: "For the field that names the thing, such as hostname or id.",
		},
		{
			Kind: KindTag,
			Name: `in:"query"`,
			Does: "Makes the input field a query parameter.",
			When: "For a filter, a page or an option, such as status, limit or force.",
		},
		{
			Kind: KindTag,
			Name: `in:"form"`,
			Does: "Makes the field a part of a multipart/form-data body. A []byte field is the file, a string of format binary.",
			When: "For an upload of a file, such as POST /api/file.",
		},
		{
			Kind: KindTag,
			Name: `in:"body"`,
			Does: "Makes the field's type the whole request body. Without it, the input's other fields are the body, as one object. The body is optional unless the field is validate:\"required\".",
			When: "When the body is a named schema, such as a retry request.",
		},
		{
			Kind: KindTag,
			Name: `flag:"name"`,
			Does: "Names the field's CLI flag. Without it, the flag is the json name with _ as -. A field of an in:\"body\" struct is a flag too.",
			When: "When the flag has a name that the CLI uses elsewhere, such as --target for target_hostname.",
		},
		{
			Kind: KindTag,
			Name: `short:"T"`,
			Does: "Gives the field's CLI flag a one-letter shorthand.",
			When: "When the CLI uses that shorthand elsewhere, such as -T for a target.",
		},
		{
			Kind: KindTag,
			Name: `json:"name"`,
			Does: "Names the field in JSON, the parameter and the schema property. In an output type, a field without ,omitempty or ,omitzero is required.",
			When: "On each field.",
		},
		{
			Kind: KindTag,
			Name: `doc:"..."`,
			Does: "Describes the field in the spec.",
			When: "On each field a caller reads or sets.",
		},
		{
			Kind: KindTag,
			Name: `example:"..."`,
			Does: "Gives the field an example in the spec and the API docs: a number for an integer or a number, true or false for a boolean, and the text for the rest.",
			When: "On each field a caller reads, so the docs show a value.",
		},
		{
			Kind: KindTag,
			Name: `default:"20"`,
			Does: "Gives a field its default in the spec, and its CLI flag the same value. The method still sees the zero value when the caller sends none, and applies the default itself.",
			When: "For an optional query parameter, such as limit.",
		},
		{
			Kind: KindTag,
			Name: `pattern:"^...$"`,
			Does: "Gives a string field a regular expression, in the spec, and the generated route answers 400 for a value that does not match.",
			When: "For an ID of a fixed form, such as a trace ID of 32 hexadecimal characters.",
		},
		{
			Kind: KindTag,
			Name: rule.TagName,
			Does: rule.TagDoes + " In an endpoint, the generated route checks them before the handler runs, and a handler runs only from its route: TestHandlersRunFromRoutes, in internal/controller/endpoints/all, fails a call of it from other code. The author writes no check.",
			When: rule.TagWhen,
		},
		{
			Kind: KindTag,
			Name: rule.RegisterName,
			Does: rule.RegisterDoes,
			When: rule.RegisterWhen,
		},
		{
			Kind: KindTag,
			Name: "time.Time",
			Does: "Is a string with the date-time format. An int64 is an integer of format int64 and the other integers have none; a float64 is a number of format double and a float32 has none; as oapi-codegen maps them back.",
			When: "For a timestamp. Tag an optional one ,omitzero: ,omitempty does not leave out a zero time.",
		},
		{
			Kind: KindTag,
			Name: "a named struct, or a struct with no name",
			Does: "A named struct is a schema in the components, with its name. A struct with no name, or an alias of one, is in place.",
			When: "Give a type the name its schema has. Use an alias of a struct with no name, such as Message, for a schema that the spec has in place.",
		},

		{
			Kind: KindCheck,
			Name: "TestEndpointParity",
			Does: "Compares the contract of a group's spec with its hand-written spec, line by line: tags, operations, parameters, auth, bodies, responses and schemas. Prose is not compared.",
			When: "Add a row to moving in internal/controller/endpoints/all/parity_public_test.go for a group that moves. A difference on purpose is accepted with its reason and an issue.",
		},
		{
			Kind: KindCheck,
			Name: "SentEmpty(fields)",
			Does: "The optional rule: each optional field of a request body, with omitempty in its validate tag and none in its json tag, which a client would send as \"\" or 0. dsl endpoint validate checks each write with it, and dsl behavior validate checks each behavior write's body with the same func.",
			When: "Add ,omitempty to the json tag of each field it names.",
		},
		{
			Kind: KindCheck,
			Name: "TestJoinedSpec",
			Does: "Holds the full spec to its contract, internal/apicontract/testdata/joined.golden.",
			When: "When you change the API on purpose, run it with -update and keep the diff.",
		},
		{
			Kind: KindCheck,
			Name: "osapi dsl endpoint openapi get --name <group>",
			Does: "Prints the group's spec, as the definition makes it.",
			When: "To read the prose beside the hand-written spec.",
		},

		{
			Kind: KindCheck,
			Name: "go generate ./internal/controller/endpoints/all",
			Does: "Writes, for each group that Uses a type, gen/api.yaml, the routes in gen/api.go, the decoders in gen/decode.go and the CLI commands in gen/cli.go, one for each method under osapi client <group>, and internal/controller/endpoints/all/gen, which registers every group's routes and commands. just generate then joins gen/api.yaml into the main spec.",
			When: "After each change to a group. go-generate-check fails when a gen/ file is stale. Never edit a gen/ file.",
		},
		{
			Kind: KindCheck,
			Name: "osapi dsl endpoint create --name <group> --description \"...\"",
			Does: "Writes a new group under internal/controller/endpoints/<group>: a list and a get, an empty Deps, its types and the tests of its methods, and adds its import to internal/controller/endpoints/all. It builds, validates and passes its tests; endpoint-scaffold-check in just test holds it to that.",
			When: "To start a new group. Then run go generate ./internal/controller/endpoints/all and just generate, and change it.",
		},
		{
			Kind: KindCheck,
			Name: "Deps in internal/controller/handlers.go",
			Does: "The controller gives each group its Deps, such as agentDeps. An empty Deps needs no wiring. A group whose Deps has a field and is not given stops the controller at startup.",
			When: "When a group's Deps gets its first field: add a line there, and a nil pointer must be a nil interface.",
		},
		{
			Kind: KindGenerated,
			Name: "internal/controller/endpoints/<group>/gen/",
			Does: "The routes, decoders, CLI commands and spec of the group, from go generate ./internal/controller/endpoints/all.",
			When: "Change the definition, then generate. A generated file that is wrong is fixed in the definition or in internal/controller/endpoint/gen.",
		},
		{
			Kind: KindGenerated,
			Name: "internal/controller/endpoints/<group>/mocks/",
			Does: "The doubles of the group's Deps, from go generate ./internal/controller/endpoints/<group>/mocks.",
			When: "Run it again after deps.go changes.",
		},
		{
			Kind: KindGenerated,
			Name: "internal/controller/endpoints/all/gen/",
			Does: "The import of each group's gen package, so the controller registers its routes and commands, from go generate ./internal/controller/endpoints/all.",
			When: "Change the definition, then generate. A generated file that is wrong is fixed in the definition or in internal/controller/endpoint/gen.",
		},
		{
			Kind: KindGenerated,
			Name: "docs/docs/sidebar/usage/cli/",
			Does: "The CLI pages, from just cli-docs-generate. The help of an endpoint command comes from .Command, .Example, .Notes, .Result and each input field's doc.",
			When: "Change the definition, then generate. A generated file that is wrong is fixed in the definition or in internal/controller/endpoint/gen.",
		},
		{
			Kind: KindGenerated,
			Name: "internal/controller/api/gen/, pkg/sdk/client/*.gen.go, ui/src/sdk/gen/, docs/docs/gen/",
			Does: "The full spec, the SDK, the UI client and the API pages, from just generate.",
			When: "Change the definition, then generate. A generated file that is wrong is fixed in the definition or in internal/controller/endpoint/gen.",
		},
	},
}

Spec is every term of the endpoint DSL. osapi dsl endpoint spec get prints it, so an author, or an agent, learns the DSL from the binary that it builds. A test fails on an exported option, method or refinement of this package without an entry.

Functions

func Answer

func Answer(
	code int,
) error

Answer is the error a method returns, with its output, to answer code with that output: a status that Answers added.

func ErrorSchema

func ErrorSchema() *openapi3.Schema

ErrorSchema is the schema of ErrorResponse, the body of each error answer: its message, and its reason, one of the values of types.Reason, with what each means.

func Errorf

func Errorf(
	sentinel error,
	format string,
	args ...any,
) error

Errorf is an error whose text is the message, and that errors.Is matches to sentinel. A handler returns it to answer with the status that Errors maps sentinel to, and with a message that names what it was called with, such as no pending agent with hostname "web-01".

func Internal

func Internal(
	msg string,
	cause error,
) error

Internal is a failure of the controller whose cause stays out of the answer: the caller gets msg, a 500, and the log gets the cause, such as the address of a backend that could not be read.

func OpenAPI

func OpenAPI(
	g *Group,
) (*openapi3.T, error)

OpenAPI is the group's part of the spec. It has the shared ErrorResponse schema, so the spec stands alone.

func ReasonFor

func ReasonFor(
	status int,
) types.Reason

ReasonFor is the reason of a status that no error names: the reason of a 404 that no route matches, or a 405.

func Scaffold

func Scaffold(
	root string,
	name string,
	doc string,
) ([]string, error)

Scaffold writes a new group's layout under internal/controller/endpoints/<name>/ in the osapi checkout at root, and registers it in internal/controller/endpoints/all. It returns the files written, relative to root, the registration last. Everything is rendered and checked before anything is written, so a taken name or a root that is not a checkout writes nothing.

func SchemaName

func SchemaName(
	t reflect.Type,
) string

SchemaName is the name of the schema of t in the spec: the schema tag of its blank field, or its Go name. The tag keeps an API name when the Go name is shorter, so agent.Info is the schema AgentInfo:

type Info struct {
	_ struct{} `schema:"AgentInfo"`
}

func SecretFields

func SecretFields() map[string]bool

SecretFields are the JSON names of every secret.Value input field, at each depth, across the methods of every registered group: a behavior's group too. The audit log redacts each by name.

func SentEmpty

func SentEmpty(
	fs []reflect.StructField,
) []string

SentEmpty is each field of a request body, fs, that is optional, with omitempty in its validate tag, but has no omitempty in its json tag: a client sends "" or 0 for it, which its other rules can refuse. The behavior DSL asks it of a write's body, so the two cannot disagree.

func Settings

func Settings[T any](
	g *Group,
) T

Settings returns g's decoded settings as T, the struct passed to Config. Before the config is loaded, or in a process that never loads it, it returns the declared defaults.

Types

type AnswerError

type AnswerError struct {
	// Code is the status.
	Code int
}

AnswerError is the error Answer makes: the status to send the output with.

func (*AnswerError) Error

func (e *AnswerError) Error() string

type Answered

type Answered struct {
	// Code is the status.
	Code int
	// Doc is its description in the spec.
	Doc string
}

Answered is a status a method answers with its own output, which Answers sets: such as a probe's 503, which says what is not ready.

type CommandExample

type CommandExample = command.Example

CommandExample is an example of a CLI command: its flags, and what it shows, which the help writes as a # line above it.

type Declared

type Declared struct {
	Permission types.Permission
	AdminOnly  bool
	Named      bool
	// Where is the group and method, such as agent drain, for an error.
	Where string
}

Declared is a permission that a method of a group needs: the permission, whether the method marks it admin only, and whether the method names it, with Permission, rather than takes its group's.

type Error

type Error struct {
	// Err is the error, matched with errors.Is.
	Err error
	// Code is the status code.
	Code int
	// Reason is the word of the answer's reason field, one of the values of types.Reason.
	Reason types.Reason
	// Doc says when it occurs, for the spec.
	Doc string
}

Error is an error a method can return, and the status code it maps to.

func Conflict

func Conflict(
	err error,
	doc string,
) Error

Conflict maps err to 409.

func Forbidden

func Forbidden(
	err error,
	doc string,
) Error

Forbidden maps err to 403: a request that the token may make, but not on this thing, such as a write to a file that osapi owns.

func Invalid

func Invalid(
	err error,
	doc string,
) Error

Invalid maps err to 400: a request that is well formed, but that the method cannot do, such as a retry of a job with nothing to run again.

func NotFound

func NotFound(
	err error,
	doc string,
) Error

NotFound maps err to 404.

func Unavailable

func Unavailable(
	err error,
	doc string,
) Error

Unavailable maps err to 503.

func (Error) Because

func (e Error) Because(
	reason types.Reason,
) Error

Because is e with reason instead of the reason of its status, such as not_managed for a 409 that osapi did not deploy.

type ErrorResponse

type ErrorResponse struct {
	Error string `json:"error"`
	// Reason is why, as one of the values of types.Reason.
	Reason types.Reason `json:"reason"`
}

ErrorResponse is the body of each answer that is not a success: the ErrorResponse schema of the spec.

type Group

type Group struct {
	// Name is the segment of each path after the prefix, and the CLI group.
	Name string
	// CommandNotes is the Notes section of the page of the group's command,
	// which CommandNotes sets.
	CommandNotes string
	// CommandLong is the rest of the help of the group's command, which
	// CommandLong sets.
	CommandLong string
	// SubDocs are the one line of help of each command that a Sub makes,
	// such as stale in osapi client file stale, which SubDoc sets.
	SubDocs map[string]string
	// Prefix is the part of each path between /api/ and the name, such as
	// next/node/{hostname}. Each {field} in it is a path field of each
	// method's input, besides the method's key.
	Prefix string
	// Doc says what the group is, in one line.
	Doc string
	// Area is the area of the group's operations, one of area.All, which
	// Area sets.
	Area area.Name
	// Title is the title of the group's spec. The full spec puts it in
	// front of each tag, and the UI's client files take their names from
	// the result, so a group that moves keeps the title it had.
	Title string
	// Tag is the tag of each operation, with its name in the docs and its
	// description.
	Tag, TagDisplay, TagDoc string
	// Deps is the type Uses names: what the group's handlers get from the
	// controller, such as the job client. Nil for a group that only has a
	// spec.
	Deps reflect.Type
	// Docs are the descriptions of the group's named types, which Doc sets:
	// Go has no tag on a type.
	Docs map[reflect.Type]string
	// Examples are the examples of fields of the group's named types, by
	// type and json name, which Example sets: for a value a tag cannot hold.
	Examples map[reflect.Type]map[string]string
	// Methods are the group's endpoints, in the order they were declared.
	Methods []*Method
	// Defaults are the group's own settings and their defaults, which
	// Config sets, or nil for a group with none.
	Defaults any
	// contains filtered or unexported fields
}

Group is a set of endpoints under one path, /api/<name>, such as agent.

func All

func All() []*Group

All is each registered group, by name.

func Define

func Define(
	name string,
	doc string,
	opts ...Option,
) *Group

Define builds a group from its options. Validate checks the result.

func Lookup

func Lookup(
	name string,
) *Group

Lookup is the registered group with the name, or nil.

func Register

func Register(
	g *Group,
) *Group

Register adds g to the groups the controller has, and returns it. Two groups with one name are a mistake in the code, so it panics.

func (*Group) CommandPath

func (g *Group) CommandPath() []string

CommandPath is the words of the group's command under osapi client: the fixed segments of its prefix, then its name. sysctl under the prefix next/node/{hostname} is next node sysctl.

func (*Group) CommandPermission

func (g *Group) CommandPermission(
	m command.Command,
) types.Permission

CommandPermission is the permission of method m, which is one of the group's methods, for the command layer.

func (*Group) Commands

func (g *Group) Commands() []command.Command

Commands are the group's methods, for the command layer, but a method that NoCommand marks.

func (*Group) CurrentSettings

func (g *Group) CurrentSettings() any

CurrentSettings is g's decoded settings, or its declared defaults before the config is read, or nil when it declares none.

func (*Group) Declared

func (g *Group) Declared() []Declared

Declared is the permission of each method of g that needs one.

func (*Group) GroupArea

func (g *Group) GroupArea() area.Name

GroupArea is the group's Area, for the command layer: the heading that its command is under in the help of its parent.

func (*Group) GroupDoc

func (g *Group) GroupDoc() string

GroupDoc is the group's Doc, for the command layer.

func (*Group) GroupLong

func (g *Group) GroupLong() string

GroupLong is the help CommandLong set, or "", for the command layer.

func (*Group) GroupName

func (g *Group) GroupName() string

GroupName is the group's Name, for the command layer.

func (*Group) GroupNotes

func (g *Group) GroupNotes() string

GroupNotes is the Notes section CommandNotes set, or "", for the command layer.

func (*Group) Method

func (g *Group) Method(
	name string,
) *Method

Method is the method of g with the name, or nil.

func (*Group) Path

func (g *Group) Path(
	m *Method,
) string

Path is the method's path: /api/, the group's prefix, its name, then its fixed sub-path, then its key, then its action, each only when it has one.

func (*Group) Permission

func (g *Group) Permission(
	m *Method,
) types.Permission

Permission is the permission a method needs: the one it names, or <group>:read for a GET and <group>:write for the other verbs. A public method needs none, and has "".

func (*Group) SetSettings

func (g *Group) SetSettings(
	v any,
)

SetSettings stores the decoded settings. The config loader calls it once the config is read.

func (*Group) SettingsKey

func (g *Group) SettingsKey() string

SettingsKey is the config key the group's settings sit under, such as controller.endpoints.job.

func (*Group) SettingsType

func (g *Group) SettingsType() reflect.Type

SettingsType is the type of the group's settings struct, or nil when it declares none.

func (*Group) SubDoc

func (g *Group) SubDoc(
	segment string,
) string

SubDoc is the help SubDoc set for the segment, or "", for the command layer.

type InternalError

type InternalError struct {
	// Msg is what the caller gets.
	Msg string
	// Cause is what the log gets.
	Cause error
}

InternalError is the error Internal makes.

func (*InternalError) Error

func (e *InternalError) Error() string

func (*InternalError) Unwrap

func (e *InternalError) Unwrap() error

type Method

type Method struct {
	// Name is the method's name in its group, such as list or drain.
	Name string

	// In is the input type: a field tagged in:"path" is the key, a field
	// tagged in:"query" is a query parameter, and the others are the JSON
	// body.
	In reflect.Type
	// Out is the response type.
	Out reflect.Type
	// contains filtered or unexported fields
}

Method is one endpoint of a group. Get, Post, Put and Delete make one; its methods set the rest and return it, so a definition chains them.

func Delete

func Delete[In, Out any](
	name string,
) *Method

Delete is a DELETE endpoint that takes In and answers with Out.

func Get

func Get[In, Out any](
	name string,
) *Method

Get is a GET endpoint that takes In and answers with Out.

func Post

func Post[In, Out any](
	name string,
) *Method

Post is a POST endpoint that takes In and answers with Out.

func Put

func Put[In, Out any](
	name string,
) *Method

Put is a PUT endpoint that takes In and answers with Out.

func (*Method) Action

func (m *Method) Action(
	segment string,
) *Method

Action puts a segment after the key, such as drain in /api/agent/{hostname}/drain.

func (*Method) AdminOnly

func (m *Method) AdminOnly() *Method

AdminOnly makes the method's permission one that only the admin role grants, such as admission:write: write and read do not get it. Each method with one permission must agree. An execute or shell permission is admin only with no mark.

func (*Method) Answering

func (m *Method) Answering() []Answered

Answering is the statuses Answers added.

func (*Method) Answers

func (m *Method) Answers(
	code int,
	doc string,
) *Method

Answers adds a status that the method answers with its output, not with an error: such as the 503 of a probe, whose body says what failed. The method returns its output with Answer(code).

func (*Method) Check

func (m *Method) Check(
	words string,
	flags string,
	pathsAndWants ...any,
) *Method

Check gives the last Example a read that shows its result: the command words after the binary, such as client agent config get, its flags, and the paths and wants of the fields of its --json output, as command.Fields pairs them. The integration suite runs it after the example. endpoint validate refuses a Check before an Example.

func (*Method) CheckFails

func (m *Method) CheckFails(
	words string,
	flags string,
	errorText string,
) *Method

CheckFails gives the last Example a read that fails with errorText, such as not found: the example removed the thing that the read names.

func (*Method) Command

func (m *Method) Command(
	short string,
	long string,
) *Method

Command sets the CLI command's own help: its one line, and the rest. The API's summary and description are for a caller of the API; the CLI's are for a person at a shell.

func (*Method) CommandLong

func (m *Method) CommandLong() string

CommandLong is the rest of the CLI command's help: the one Command set, or the description.

func (*Method) CommandName

func (m *Method) CommandName() string

CommandName is the CLI command's name: the one Use set, or the method's.

func (*Method) CommandShort

func (m *Method) CommandShort() string

CommandShort is the CLI command's one line: the one Command set, or the summary.

func (*Method) CommandSub

func (m *Method) CommandSub(
	word string,
) *Method

CommandSub puts the CLI command under a word that is not in the path, such as vault in osapi client secret vault list for GET /api/secret.

func (*Method) Describe

func (m *Method) Describe(
	summary string,
) *Method

Describe sets the summary: what the method does, in one line.

func (*Method) Errors

func (m *Method) Errors(
	errs ...Error,
) *Method

Errors are the errors the method can return, each with its status code. An error that is not in the list is a 500.

func (*Method) Example

func (m *Method) Example(
	flags string,
	doc ...string,
) *Method

Example adds an example of the CLI command: its flags, such as --hostname web-01, and, when doc is given, what it shows. The help shows each one after the command, under its doc as a # line.

func (*Method) Examples

func (m *Method) Examples() []CommandExample

Examples are the CLI command's examples, the flags and the doc of each.

func (*Method) Explain

func (m *Method) Explain(
	text string,
) *Method

Explain sets the description: the rest of what a caller needs to know.

func (*Method) Fails

func (m *Method) Fails(
	doc string,
	input any,
) *Method

Fails declares an input that the API refuses with 400: the method's input with the other fields valid and one rule broken. Validate requires one for each rule of each input field, and a test sends each one through the routes.

func (*Method) HTTPMethod

func (m *Method) HTTPMethod() string

HTTPMethod is the method's HTTP method, such as GET. Get, Post, Put and Delete set it, so an author cannot name one that is not.

func (*Method) Handle

func (m *Method) Handle(
	fn any,
) *Method

Handle sets the function that runs the method: func(ctx context.Context, d D, in In) (Out, error), with D the type the group Uses. Validate checks the signature; the generated route calls it.

func (*Method) Handler

func (m *Method) Handler() any

Handler is the function Handle set, or nil.

func (*Method) ID

func (m *Method) ID(
	id string,
) *Method

ID sets the operationId. The Go SDK and the UI client take their names from it, so a group that moves keeps the IDs it had.

func (*Method) Input

func (m *Method) Input() reflect.Type

Input is the method's In, for the command layer.

func (*Method) Key

func (m *Method) Key(
	fields ...string,
) *Method

Key names the path fields of the key, in the order of the path, such as Key("vault", "key") for /api/secret/{vault}/{key}: a key that is unique only in the thing that holds it. Without it, the key is the one input field tagged in:"path" that the prefix does not name.

func (*Method) KeyField

func (m *Method) KeyField() string

KeyField is the json name of the last field of the key, which names what the method acts on, such as key in /api/secret/{vault}/{key}, or "".

func (*Method) Keys

func (m *Method) Keys() []string

Keys are the json names of the path fields of the key, in the order of the path: the ones Key named, or the one input field tagged in:"path" that the prefix does not name. It is empty when the method has no key.

func (*Method) Location

func (m *Method) Location(
	field string,
) *Method

Location names the field of the output that holds the ID of the resource a 201 created, such as job_id: the answer's Location header is the group's path and that ID, such as /api/job/7c9e6679-....

func (*Method) LocationField

func (m *Method) LocationField() string

LocationField is the field Location named, or "".

func (*Method) Mapped

func (m *Method) Mapped() []Error

Mapped are the errors Errors set, each with its status code.

func (*Method) MethodName

func (m *Method) MethodName() string

MethodName is the method's Name, for the command layer.

func (*Method) NoCheck

func (m *Method) NoCheck(
	why string,
) *Method

NoCheck says why no read shows the result of the method's examples, for a write whose result no command reads back. The integration gate requires a Check of each example of a write, or this.

func (*Method) NoCommand

func (m *Method) NoCommand() *Method

NoCommand makes the method have no CLI command: a program calls it, not a person, such as the agent's join. Its route, its spec and its SDK method are as each other method's.

func (*Method) Notes

func (m *Method) Notes(
	text string,
) *Method

Notes adds a Notes section to the CLI command's page: what a person needs to know that the help does not say, such as what --json has that the table does not.

func (*Method) OperationID

func (m *Method) OperationID(
	g *Group,
) string

OperationID is the operationId: the one ID sets, or the verb and the path in Pascal case, as each operationId of the API is.

func (*Method) Output

func (m *Method) Output() reflect.Type

Output is the method's Out, which the command layer prints from.

func (*Method) PageNotes

func (m *Method) PageNotes() string

PageNotes is the Notes section Notes set, or "".

func (*Method) PageResult

func (m *Method) PageResult() string

PageResult is the Result section Result set, or "".

func (*Method) Permission

func (m *Method) Permission(
	permission types.Permission,
) *Method

Permission names the permission the method needs, in place of the group's read or write permission.

func (*Method) Prints

func (m *Method) Prints(
	out any,
) *Method

Prints gives the last Example its output: what the API answers, a value of the method's output type. The docs page of the command shows it as the CLI prints it, and as JSON for --json. endpoint validate refuses a value of another type, and Prints before an Example.

func (*Method) Public

func (m *Method) Public() *Method

Public makes the method need no auth: the health probes, and the agent's join, which the join token authorizes.

func (*Method) Refusals

func (m *Method) Refusals() []Refusal

Refusals are the inputs Fails declared.

func (*Method) Result

func (m *Method) Result(
	text string,
) *Method

Result adds a Result section to the CLI command's page: what the command does in a case that needs words, such as when two agents share a name.

func (*Method) Returns

func (m *Method) Returns(
	doc string,
) *Method

Returns describes the response of a success, such as "List of active agents."

func (*Method) Saying

func (m *Method) Saying() string

Saying is the text Says set, or "", for the command layer.

func (*Method) Says

func (m *Method) Says(
	text string,
) *Method

Says is what the CLI prints for a method that answers with no body, when it is a state and not the past tense of the method: the agent's key and draining, for drain.

func (*Method) Status

func (m *Method) Status(
	code int,
) *Method

Status sets the status code of a success, such as 201 or 204.

func (*Method) Sub

func (m *Method) Sub(
	segment string,
) *Method

Sub puts a fixed segment after the group's name, such as pending in /api/agent/pending, or facts in /api/agent/facts.

func (*Method) SubPath

func (m *Method) SubPath() string

SubPath is the word that the CLI command is under: the one CommandSub set, or the fixed segment Sub set, or "".

func (*Method) SuccessStatus

func (m *Method) SuccessStatus() int

SuccessStatus is the status of a success: the one Status set, or 200.

func (*Method) Unchecked

func (m *Method) Unchecked() string

Unchecked is why no read shows the result of the method's examples, as NoCheck says it, or "".

func (*Method) Use

func (m *Method) Use(
	name string,
) *Method

Use names the CLI command apart from the method, whose name must be unique in the group: such as list under pending, when the group has a list already.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option is a setting of a group, or one of its endpoints.

func Area

func Area(
	name area.Name,
) Option

Area puts the group's operations in an area, one of area.All: the folder of the SDK's page and its section of the docs site's SDK menu. endpoint validate refuses a group with none.

func CommandLong

func CommandLong(
	text string,
) Option

CommandLong is the rest of the help of the group's command, after its one line, such as what most of its commands read.

func CommandNotes

func CommandNotes(
	text string,
) Option

CommandNotes adds a Notes section to the page of the group's own command, such as a link to the page that tells more about the group.

func Config

func Config(
	defaults any,
) Option

Config declares a group's own settings, as behavior.Config does for a behavior. defaults is a struct whose fields carry mapstructure, doc and validate tags, the same as osapi's own config, and whose field values are the defaults. The settings join osapi's config under controller.endpoints.<name>: config list shows them, OSAPI_ environment variables set them, and config validate checks them. A handler reads them with Settings. Settings are standing configuration of the controller; a request's values are its input, never a setting.

func Doc

func Doc[T any](
	doc string,
) Option

Doc describes T, a named type of the group, in its schema.

func Example

func Example[T any](
	field string,
	example string,
) Option

Example gives the field of T with the json name field its example. A struct tag holds an example with no double quote, and Example holds the rest, such as a JSON document: gofumpt and golines drop the backslashes of a quote in a tag.

func Prefix

func Prefix(
	path string,
) Option

Prefix puts each path of the group under a prefix, between /api/ and the group's name, such as next/node/{hostname} for a behavior. Each {field} of the prefix is a path field of each method's input, which is not its key.

func SubDoc

func SubDoc(
	segment string,
	short string,
) Option

SubDoc is the one line of help of the command that the Sub segment makes, such as stale in osapi client file stale.

func Tag

func Tag(
	name string,
	display string,
	doc string,
) Option

Tag sets the tag of each operation of the group: its name, its name in the docs, and its description.

func Title

func Title(
	title string,
) Option

Title sets the title of the group's spec.

func Uses

func Uses[D any]() Option

Uses names D, the struct of what the group's handlers use, such as the job client. The controller gives one D at startup, and a test gives one with fakes. Each handler takes it as its second argument.

type Problem

type Problem struct {
	// Group is the group it is about.
	Group string `json:"group"`
	// Method is the method it is about, or "" for the group.
	Method string `json:"method,omitempty"`
	// Rule is the name of the rule, from Checks.
	Rule string `json:"rule"`
	// Message says what is wrong.
	Message string `json:"message"`
	// Fix is how to fix it, from the check of Rule.
	Fix string `json:"fix" table:"-"`
}

Problem is a rule a definition breaks, and how to fix it.

func Validate

func Validate(
	g *Group,
) []Problem

Validate is each rule g breaks. A group with no problems makes a spec that loads and routes that do not collide.

func (Problem) String

func (p Problem) String() string

type Refusal

type Refusal struct {
	// Doc says what is wrong with the input, such as "a name over 255
	// characters".
	Doc string
	// Input is the method's input, with one rule broken.
	Input any
}

Refusal is an input that the API refuses with 400, as Fails declares it.

type SpecExample

type SpecExample struct {
	// Doc says what the example shows.
	Doc string `json:"doc"`
	// Input is the value of each parameter and each property of the body
	// that the example's flags set, by its name in the spec.
	Input map[string]any `json:"input"`
}

SpecExample is one example of a method in the spec.

Directories

Path Synopsis
Package command is the endpoint layer's runner of the generated CLI commands of the endpoint groups.
Package command is the endpoint layer's runner of the generated CLI commands of the endpoint groups.
gen
Command gen writes the files that come from the endpoint groups: for each group that Uses a type, its gen/api.yaml, the routes in gen/api.go and the decoders in gen/decode.go, and internal/controller/endpoints/all/gen, which registers every group's routes.
Command gen writes the files that come from the endpoint groups: for each group that Uses a type, its gen/api.yaml, the routes in gen/api.go and the decoders in gen/decode.go, and internal/controller/endpoints/all/gen, which registers every group's routes.
genutil
Package genutil holds what the endpoint layer's writers share: the fields of an input as JSON reads them, and the house layout of a jen group.
Package genutil holds what the endpoint layer's writers share: the fields of an input as JSON reads them, and the house layout of a jen group.
routegen
Package routegen writes the route table and the decoders of an endpoint group, for the endpoint generator and the behavior generator alike, so a behavior's routes are the same code as an endpoint's.
Package routegen writes the route table and the decoders of an endpoint group, for the endpoint generator and the behavior generator alike, so a behavior's routes are the same code as an endpoint's.
specgen
Package specgen writes the specs as the repository keeps them, for the endpoint generator and the behavior generator alike: the spec of each group, and the full spec of the API, which joins them.
Package specgen writes the specs as the repository keeps them, for the endpoint generator and the behavior generator alike: the spec of each group, and the full spec of the API, which joins them.
Package server is the runtime the generated routes of an endpoint group call.
Package server is the runtime the generated routes of an endpoint group call.

Jump to

Keyboard shortcuts

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