api

package
v0.0.0-...-164d735 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: 0BSD Imports: 32 Imported by: 2 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 api defines the standard runtime reflection representation for a runtime.link API structure. The functions in this package are typically only used to implement runtime.link layers (ie. drivers) so that the layer can either host, or link functions specified within the structure.

Example
package main

import (
	"log"
	"os"

	"github.com/iqhive/runtime.link/api"
	"github.com/iqhive/runtime.link/api/cmdl"
	"github.com/iqhive/runtime.link/api/rest"
)

// API specification structure, typically named API for general structures, may
// be more suitably named Functions, Library or Command when the API is
// restricted to a specific runtime.link layer. Any Go comments in the source
// are intended to document design notes and ideas. This leaves Go struct tags
// for recording developer-facing documentation.
type API struct {
	api.Specification `api:"Example" lib:"libexample" cmd:"example"
        is an example of a runtime.link API structure.` // this section of the tag contains documentation.

	// HelloWorld includes runtime.link tags that specify how the function is called
	// across different link-layers. Typically, a context.Context argument and error
	// return value should be included here, they are omitted here for brevity.
	HelloWorld func() string `args:"hello_world" link:"example_helloworld func()$char" rest:"GET /hello_world"
        returns the string "Hello World"` // documentation for the function.
}

// New returns an implementation of the API. This doesn't have to be defined in the
// same package and may not even be implemented in Go. This will often be the case when
// representing an external API controlled by a third-party.
func New() API {
	return API{
		HelloWorld: func() string {
			return "Hello World"
		},
	}
}

func main() {
	example := New()
	if port := os.Getenv("PORT"); port != "" {
		if err := rest.ListenAndServe(port, nil, example); err != nil {
			log.Fatal(err)
		}
		return
	}
	cmdl.Main(example)
}

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrNotImplemented = api_http.ErrNotImplemented
	ErrAccessDenied   = accessDenied{}
)
View Source
var AccessDenied error = accessDenied{}

Deprecated

Functions

func DocumentationOf

func DocumentationOf(field reflect.StructField) string

DocumentationOf returns the doc string associated with a reflect.StructField. The doc string begins after the first newline of the tag and ignores any tab characters inside it.

func Export

func Export[API, H, Options any](exporter Exporter[H, Options], impl API, options Options) (H, error)

Export the given runtime.link API structure using the given exporter and configuration.

func Import

func Import[API, Host, Conn any](T Linker[Host, Conn], host Host, conn Conn) API

Import the given runtime.link API structure using the given transport, host and transport-specific configuration. If an error is returned by the linker all functions will be stubbed with an error implementation that returns the error returned by the linker.

API may be a pointer to an API structure, the structure it points to is then allocated here.

func ListenAndServe

func ListenAndServe(addr string, auth Auth[*http.Request], implementation any) error

func RegisterSampler

func RegisterSampler(s Sampler)

RegisterSampler installs the Sampler used by Documentation.Test to attach the sampled request/response of each downstream call to the recorded test.Event. It is called once, from the rest link-layer's init.

func RegisterSource

func RegisterSource[T any](files fs.FS)

RegisterSource associates Go source with the package of T, so that any API structure declared in that package gains parameter names.

func Test

func Test(t *testing.T, impl Documentation)

Types

type ArgumentScanner

type ArgumentScanner struct {
	// contains filtered or unexported fields
}

ArgumentScanner can scan arguments via a formatting pattern. Either %v, %[n]v, a Go parameter name (when constructed with NewNamedArgumentScanner), or a struct FieldName.

Parameter names shadow struct fields of the same name; %[n]v remains the unambiguous escape.

func NewArgumentScanner

func NewArgumentScanner(args []reflect.Value) ArgumentScanner

NewArgumentScanner returns a new argument scanner where format parameters are referring to the given arguments.

func NewNamedArgumentScanner

func NewNamedArgumentScanner(args []reflect.Value, names []string) ArgumentScanner

NewNamedArgumentScanner is NewArgumentScanner with Go parameter names aligned to args, so that ArgumentScanner.Scan can look up an argument by name. Empty names are ignored.

func (*ArgumentScanner) Scan

func (scanner *ArgumentScanner) Scan(format string) (reflect.Value, error)

Scan returns the argument specified by the given format string. The format string can be either %v, %[n]v, a Go parameter name, or a FieldName.

type Auth

type Auth[Conn any] interface {
	// Authenticate is called before the request is processed it
	// should confirm the identify of the caller. The context
	// returned will be passed to the function being called. If
	// the identity shouldn't know about the Function, return
	// an error here.
	//
	// Authenticate may be called multiple times for the same
	// [Conn] but any number of different [Function] parameters,
	// the context returned by the first call, may be fed into
	// any subsequent calls, so cache any expensive lookups and
	// reuse them where possible.
	Authenticate(context.Context, Conn, Function) (context.Context, error)

	// AssertAccess is called after arguments have been passed
	// and before the function is called. It should assert that
	// the identified caller is allowed to access the function.
	Authorize(context.Context, Conn, Function, []reflect.Value) error

	// Redact is called on any errors raised by the function, it
	// can be used to log and/or report this error, or to redact
	// any sensitive information from the error before it is
	// returned to the caller.
	Redact(context.Context, error) error
}

Auth returns an error if the given Conn is not allowed to access the given function. Used to implement authentication and authorisation for API calls.

type Document

type Document[Interface any, Implementation any] = Register[Interface, Implementation]

type Documentation

type Documentation func(context.Context) (Examples, error)

func (Documentation) Environments

func (fn Documentation) Environments(ctx context.Context) []string

Environments returns the sorted environment keys when the underlying suite is an Environments map, or nil otherwise (a single implicit "" environment). The rest host renders these as the /testruns environment selector.

func (Documentation) Example

func (fn Documentation) Example(ctx context.Context, name string) (Example, bool)

func (Documentation) Examples

func (fn Documentation) Examples(ctx context.Context) (map[string][]string, error)

Examples enumerates the example methods, grouped by the file they are declared in. Test methods (those prefixed with "Test") are excluded; use Documentation.Tests to enumerate those.

func (Documentation) History

func (fn Documentation) History(ctx context.Context) test.History

History returns the test.History assigned to the underlying test implementation, or nil if the implementation does not embed a TestingFramework with an assigned History. The rest host uses this to decide whether the builtin /testrun/* endpoints should be served.

func (Documentation) Test

func (fn Documentation) Test(ctx context.Context, name string) (test.Execution, bool)

Test runs the named test method and returns a test.Execution describing what happened: the story, the wall-clock duration, the ordered trace of calls (with their arguments and return values) and any error or panic. The boolean is false if no method with the given name exists.

func (Documentation) Tests

func (fn Documentation) Tests(ctx context.Context) (map[string][]string, error)

Tests enumerates the runnable methods, grouped by the file they are declared in. Every method is runnable: both examples (rendered as documentation) and dedicated test methods (prefixed with "Test"). The difference from Documentation.Examples is that Tests additionally includes the Test-prefixed methods, so the /testruns pages exercise the full suite.

type Environments

type Environments map[string]Examples

Environments groups one Examples suite per named environment (for example "st", "dev", "sit-a"). It is itself an Examples, so a Documentation may return it wherever a single suite is expected: the builtin /testruns UI then offers the environment as a selector and dispatches runs as "env:TestName".

The "" key is the default environment, without it the default is the first key in sorted order; a suite returned directly (not via an Environments map) is treated as if it were Environments{"": suite}, so existing single-environment callers are unaffected.

type Error

type Error[T any] struct {
	// contains filtered or unexported fields
}

Error can be used to specify an enumerated set of error values that can be returned by an API endpoint. It behaves like a xyz.Tagged that implements [error].

func (Error) Error

func (e Error) Error() string

func (Error) StatusHTTP

func (e Error) StatusHTTP() int

type Example

type Example struct {
	Title string
	Tests string
	Story string
	Steps []Step
	Error error
	Panic bool

	// Ready reports whether the example called [TestingFramework.Ready],
	// marking it as promoted to the regression suite. Runners such as [Test]
	// only fail the build for examples that are Ready; a failure in an example
	// that has not been marked Ready is reported as skipped instead.
	Ready bool
	// contains filtered or unexported fields
}

type Examples

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

type Exporter

type Exporter[Host any, Options any] interface {
	Export(Structure, Options) (Host, error)
}

Exporter that can export a runtime.link API structure using the specified 'Options' configuration.

type Function

type Function struct {
	Name string
	Docs string
	Tags reflect.StructTag
	Type reflect.Type

	// Args holds the Go parameter names of the function's arguments,
	// aligned with [Function.In] (so a leading context.Context is
	// excluded). Empty, or containing "" entries, when unknown.
	Args []string
	// Outs holds the Go result names, aligned with [Function.NumOut]
	// (so a trailing error is excluded). Empty when unknown.
	Outs []string

	// Root is the outermost structure this function belongs to, whatever its
	// depth. Its Scenarios and Instances include those of every namespace.
	Root Structure
	Path []string // namespace path from root to reach this function.

	Impl reflect.Value
}

Function is a runtime reflection representation of a runtime.link function.

func (Function) Call

func (fn Function) Call(ctx context.Context, args []reflect.Value) ([]reflect.Value, error)

Call the function, automatically handling the presence of the first context.Context argument or the last [error] return value. An error result that is an interface reports a failure unless it is nil, as err != nil would, so a nil pointer returned as an [error] is one. An error result of a concrete type reports a failure unless it is the zero value.

func (Function) Copy

func (fn Function) Copy() Function

Copy returns a copy of the function, the copy can be safely used inside of Function.Make in order to wrap the existing implementation.

func (Function) Format

func (fn Function) Format(f fmt.State, verb rune)

Format implements fmt.Formatter so that every verb, including %#v, uses Function.String instead of dumping fields.

func (Function) In

func (fn Function) In(i int) reflect.Type

func (Function) InName

func (fn Function) InName(i int) string

InName returns the Go name of the i'th argument (see Function.In) or "".

func (Function) Is

func (fn Function) Is(ptr any) bool

Is returns true if the given pointer is the same as the underlying function implementation.

func (Function) Make

func (fn Function) Make(impl any)

Make the function use the given implementation, an error is returned if the implementation is not of the same type as the function. An implementation that returns a list of results may leave out the last of them, with or without an error, and the function returns their zero values.

func (Function) MakeError

func (fn Function) MakeError(err error)

MakeError makes the function use the given error as its implementation. Either returning it (if possible) otherwise panicking with it. A function declaring a named error interface is given err as described by Function.Return, and any panic that follows from that is left to each call, as one function that cannot report the error must not stop the rest of its API from linking.

func (Function) Named

func (fn Function) Named() bool

Named reports whether every argument has a known name.

func (Function) NumIn

func (fn Function) NumIn() int

NumIn returns the number of arguments to the function except for the first argument if it is a context.Context.

func (Function) NumOut

func (fn Function) NumOut() int

NumOut returns the number of return values for the function excluding the [error] value.

func (Function) OutName

func (fn Function) OutName(i int) string

OutName returns the Go name of the i'th result or "".

func (Function) Return

func (fn Function) Return(results []reflect.Value, err error) []reflect.Value

Return returns the given results, if err is not nil, then results can be nil and vice versa.

A function can declare a narrower error result than [error], such as a named interface, which err might not implement. The result is then the first error in err's chain of that type. Failing that, it is an instance registered for that type with Register, wrapping err in a case that takes an [error] and has an "http" tag of 500 or above. No other case is used, as a failure that the API never saw must not read as one of the outcomes that it documents.

Return panics when nothing can hold err, naming what to register. A failed call must not read as a success, which is all that a zero result could do.

func (Function) String

func (fn Function) String() string

String returns the dotted path to the function within its API structure, such as "Math.Add". Without Function.String or Function.Format, printing a function follows Function.Root in a cycle and overflows the stack.

type Host

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

Host used to document host tags that identify the location of the link layer's target.

type Linker

type Linker[Host any, Conn any] interface {
	Link(Structure, Host, Conn) error
}

Linker that can link a runtime.link API structure up to a 'Host' implementation using the specified 'Connection' configuration.

type Register

type Register[Interface any, Implementation any] struct{}

Register an implementation of an interface, if I is an [error] and V is an Error-type then each nested error value will be registered as a scenario, else V will be documented as a possible instance of I.

type Sampler

type Sampler func(fn Function, args, vals []reflect.Value) (url string, req, resp []byte, err error)

Sampler reconstructs the downstream HTTP exchange for a function call from its arguments and return values: the "METHOD /path" line, the request body and the response body. It returns an empty url when the function does not correspond to an HTTP endpoint.

type Scenario

type Scenario struct {
	Name string
	Kind string
	Text string
	Tags reflect.StructTag

	// Instance is the error interface this scenario was registered against
	// via [Register]. For API-wide registrations this is the bare [error]
	// interface; for per-endpoint error interfaces (such as ErrorForLogin)
	// it is that named interface, allowing scenarios to be scoped to the
	// endpoints that declare it as their error return type.
	Instance reflect.Type

	Test func(error) bool
}

Scenario documents an out-of-band signal supported by the API that requires actioning by the client, this could be an error, a redirection or a status.

type Specification

type Specification = WithSpecification

Specification should be embedded in all runtime.link API structures.

type Step

type Step struct {
	Note string
	Call *Function
	Args []reflect.Value
	Vals []reflect.Value
	Time time.Time
	Seq  uint64

	Error  error
	Depth  uint
	Setup  bool
	Prefix string
}

type Structure

type Structure struct {
	Name string
	Docs string
	Tags reflect.StructTag

	// Host is the tag of the last host declared, by the [Specification] or
	// by a field that implements [Host]. When that is a field named for
	// another GOOS, and it has a tag, the field named for this GOOS is used
	// instead, or failing that the last host not named for any GOOS.
	Host reflect.StructTag

	// Functions or endpoints of the API, that can be called.
	Functions []Function

	// Scenarios documents out-of-band signals that can be returned
	// by the API, these are typically errors, redirections or
	// status codes.
	Scenarios []Scenario

	// Namespace enables structures to be nested.
	Namespace map[string]Structure

	// Instances map interface types, to a list of types that
	// have been registered as implementations of that interface.
	Instances map[reflect.Type][]reflect.Type
}

Structure is the runtime reflection representation for a runtime.link API structure. In Go source, these are represented using Go structs with at least one function field. These runtime.link API structures can be be nested in order to organise functions into sensible namespaces.

For example:

type Example struct {
	HelloWorld func() string `tag:"value"
		returns "Hello World"`

	Math struct {
		Add func(a, b int) int `tag:"value"
			returns a + b`
	}
}

Each function field can have struct tags that specify how a particular link layer should link to, or host the function. The tags can contain any number of newlines, each subsequent line after the first will be treated as documentation for the function (tabs are stripped from each line).

Parameter and result names are available on Function.Args and Function.Outs when the API structure implements WithSource (or RegisterSource has been called for its package). Names are never required; empty strings mean "unknown".

func StructureOf

func StructureOf(val any) Structure

StructureOf returns a reflected runtime.link API structure for the given value, if it is not a struct (or a pointer to a struct), only the name will be available.

When val (or a pointer to it) implements WithSource, Go parameter and result names are attached to each Function.

func (Structure) Format

func (s Structure) Format(f fmt.State, verb rune)

Format implements fmt.Formatter so that every verb, including %#v, uses Structure.String instead of dumping fields.

func (Structure) Iter

func (s Structure) Iter() iter.Seq[Function]

func (Structure) MakeError

func (s Structure) MakeError(err error)

MakeError calls Function.MakeError on each function within the structure.

func (Structure) String

func (s Structure) String() string

String returns the structure's name. Without Structure.String or Structure.Format, printing a structure follows Function.Root in a cycle and overflows the stack.

type TestingFramework

type TestingFramework struct {
	History test.History
	// contains filtered or unexported fields
}

func (*TestingFramework) Guide

func (tdd *TestingFramework) Guide(description literal)

func (*TestingFramework) Ready

func (tdd *TestingFramework) Ready()

Ready marks the example as ready for regression testing. It should be called early in a test, before any API calls. Examples that call Ready are treated as part of the regression suite: runners such as Test fail on an error. Examples that do not call Ready are still executed but a failure is reported as skipped rather than failing the build, so work-in-progress examples can be committed without breaking `go test`.

func (*TestingFramework) Setup

func (tdd *TestingFramework) Setup(ctx context.Context, fn func(ctx context.Context) error) error

func (*TestingFramework) Story

func (tdd *TestingFramework) Story(description literal)

func (*TestingFramework) Tests

func (tdd *TestingFramework) Tests(description literal)

type TransportError

type TransportError struct {
	// Name is the parameter as the caller addresses it (the path, query or body
	// field name), or empty when the request body as a whole was rejected.
	Name string
	Err  error
}

TransportError reports an argument sent by the caller that the transport (such as runtime.link/api/rest) could not decode into the parameter of the function being called, so the call was rejected before it was made. It is always the caller's to fix, so it maps to a 400.

Its Error is safe to show the caller: it is written only from the API's own description, being the parameter's name and (where the underlying failure is one runtime.link recognises) what a valid value looks like. The one thing it repeats from the request is a JSON number that its field cannot hold, which is named as what was sent, as in "age cannot be a JSON number 300". The underlying failure is written for a Go developer, may quote internal type names or any other value sent, and is only reachable via Unwrap, for logs.

func (*TransportError) Error

func (e *TransportError) Error() string

func (*TransportError) StatusHTTP

func (e *TransportError) StatusHTTP() int

func (*TransportError) Unwrap

func (e *TransportError) Unwrap() error

type WithExamples

type WithExamples interface {
	Example(context.Context, string) (Example, bool)
	Examples(context.Context) (map[string][]string, error)
}

type WithHistory

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

WithHistory is implemented by test Examples implementations that carry an assigned test.History. The rest host uses it to discover whether the builtin /testrun/* endpoints should be served for a given implementation.

type WithSource

type WithSource interface {
	Source() fs.FS
}

WithSource is implemented by API structures that ship the Go source of their package, enabling Function.Args and Function.Outs. Typically:

//go:embed *.go
var source embed.FS

func (API) Source() fs.FS { return source }

type WithSpecification

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

type WithTests

type WithTests interface {
	Test(context.Context, string) (test.Execution, bool)
	Tests(context.Context) (map[string][]string, error)
	History(context.Context) test.History
	// Environments lists the selectable environments a test may be run
	// against, or nil when the suite is not an [Environments] map (in which
	// case there is a single implicit "" environment). The builtin /testruns
	// UI renders these as a selector and dispatches "env:TestName".
	Environments(context.Context) []string
}

Directories

Path Synopsis
Package call provides shared library linker for runtime.link (WORK-IN-PROGRESS).
Package call provides shared library linker for runtime.link (WORK-IN-PROGRESS).
internal/abi
Package abi provides an interface to the platform-standard ABI calling conventions and type system (typically C).
Package abi provides an interface to the platform-standard ABI calling conventions and type system (typically C).
internal/bin
Package bin enables you to represent binary formats.
Package bin enables you to represent binary formats.
internal/bin/std/cpu/amd64
Package amd64 provides an instruction set specification for the AMD64 architecture.
Package amd64 provides an instruction set specification for the AMD64 architecture.
internal/bin/std/cpu/arm64
Package arm64 provides an instruction set specification for the ARM64 architecture.
Package arm64 provides an instruction set specification for the ARM64 architecture.
internal/dll
Package dll provides methods for dynamically loading shared libraries and symbol lookup.
Package dll provides methods for dynamically loading shared libraries and symbol lookup.
internal/ffi
Package ffi provides information about the platform-native C ABI types.
Package ffi provides information about the platform-native C ABI types.
internal/jit
Package jit provides a safe way to describe what a function does with each argument and return value, at a level above the code that carries it out: moves, conversions, pins and NUL-terminations, for [api.Linker] implementations to share.
Package jit provides a safe way to describe what a function does with each argument and return value, at a level above the code that carries it out: moves, conversions, pins and NUL-terminations, for [api.Linker] implementations to share.
Package cmdl provides a command-line interface linker for runtime.link.
Package cmdl provides a command-line interface linker for runtime.link.
Package data provides ways to declare validation constraints on values, these constraints can be reflected upon at runtime.
Package data provides ways to declare validation constraints on values, these constraints can be reflected upon at runtime.
petstore
Package petstore serves as an example for how to represent a REST API specification.
Package petstore serves as an example for how to represent a REST API specification.
Package fmts provides a format specification API linker.
Package fmts provides a format specification API linker.
Package grpc implements Protocol Buffer codecs.
Package grpc implements Protocol Buffer codecs.
internal
bit
has
http
Package http provides an extendable shell API based on http.
Package http provides an extendable shell API based on http.
oas
Package oas provides a representation of the OpenAPI Specification (OAS) Version 3.2.0
Package oas provides a representation of the OpenAPI Specification (OAS) Version 3.2.0
rtags
Package rtags provides methods for reading a rest.Tag, do not make this public, instead extend the rest.Tag with methods if required.
Package rtags provides methods for reading a rest.Tag, do not make this public, instead extend the rest.Tag with methods if required.
Package jrpc implements JSON-RPC codecs.
Package jrpc implements JSON-RPC codecs.
ai
gl
Code generated by generate.go; DO NOT EDIT.
Code generated by generate.go; DO NOT EDIT.
Package rest provides a REST API transport.
Package rest provides a REST API transport.
Package stub provides a stub api.Linker that returns empty values and specific errors.
Package stub provides a stub api.Linker that returns empty values and specific errors.
Package test provides the data structures for testrun execution and analysis.
Package test provides the data structures for testrun execution and analysis.
wasm module
Package xray provides standard means for introspecting the internal operational state of an [api.Linker].
Package xray provides standard means for introspecting the internal operational state of an [api.Linker].

Jump to

Keyboard shortcuts

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