Documentation
¶
Overview ¶
Package api defines the standard runtime reflection representation for an iqlink API structure. The functions in this package are typically only used to implement iqlink 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/iqlink/api"
"github.com/iqhive/iqlink/api/cmdl"
"github.com/iqhive/iqlink/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 iqlink 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 an iqlink API structure.` // this section of the tag contains documentation.
// HelloWorld includes iqlink 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)
}
Output:
Index ¶
- Variables
- func DocumentationOf(field reflect.StructField) string
- func Export[API, H, Options any](exporter Exporter[H, Options], impl API, options Options) (H, error)
- func Import[API, Host, Conn any](T Linker[Host, Conn], host Host, conn Conn) API
- func ListenAndServe(addr string, auth Auth[*http.Request], implementation any) error
- func RegisterSampler(s Sampler)
- func RegisterSource[T any](files fs.FS)
- func Test(t *testing.T, impl Documentation)
- type ArgumentScanner
- type Auth
- type Document
- type Documentation
- func (fn Documentation) Environments(ctx context.Context) []string
- func (fn Documentation) Example(ctx context.Context, name string) (Example, bool)
- func (fn Documentation) Examples(ctx context.Context) (map[string][]string, error)
- func (fn Documentation) History(ctx context.Context) test.History
- func (fn Documentation) Test(ctx context.Context, name string) (test.Execution, bool)
- func (fn Documentation) Tests(ctx context.Context) (map[string][]string, error)
- type Environments
- type Error
- type Example
- type Examples
- type Exporter
- type Function
- func (fn Function) Call(ctx context.Context, args []reflect.Value) ([]reflect.Value, error)
- func (fn Function) Copy() Function
- func (fn Function) Format(f fmt.State, verb rune)
- func (fn Function) In(i int) reflect.Type
- func (fn Function) InName(i int) string
- func (fn Function) Is(ptr any) bool
- func (fn Function) Make(impl any)
- func (fn Function) MakeError(err error)
- func (fn Function) Named() bool
- func (fn Function) NumIn() int
- func (fn Function) NumOut() int
- func (fn Function) OutName(i int) string
- func (fn Function) Return(results []reflect.Value, err error) []reflect.Value
- func (fn Function) String() string
- type Host
- type Linker
- type Register
- type Sampler
- type Scenario
- type Specification
- type Step
- type Structure
- type TestingFramework
- func (tdd *TestingFramework) Guide(description literal)
- func (tdd *TestingFramework) Ready()
- func (tdd *TestingFramework) Setup(ctx context.Context, fn func(ctx context.Context) error) error
- func (tdd *TestingFramework) Story(description literal)
- func (tdd *TestingFramework) Tests(description literal)
- type TransportError
- type WithExamples
- type WithHistory
- type WithSource
- type WithSpecification
- type WithTests
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrNotImplemented = api_http.ErrNotImplemented ErrAccessDenied = accessDenied{} )
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 iqlink API structure using the given exporter and configuration.
func Import ¶
Import the given iqlink 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.
func ListenAndServe ¶
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 ¶
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.
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 Documentation ¶
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) Examples ¶
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 ¶
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 ¶
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 ¶
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; 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) 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 Exporter ¶
Exporter that can export an iqlink 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 Structure // root structure this function belongs to.
Path []string // namespace path from root to reach this function.
Impl reflect.Value
}
Function is a runtime reflection representation of an iqlink function.
func (Function) Call ¶
Call the function, automatically handling the presence of the first context.Context argument or the last [error] return value.
func (Function) Copy ¶
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 ¶
Format implements fmt.Formatter so that every verb, including %#v, uses Function.String instead of dumping fields.
func (Function) InName ¶
InName returns the Go name of the i'th argument (see Function.In) or "".
func (Function) Is ¶
Is returns true if the given pointer is the same as the underlying function implementation.
func (Function) Make ¶
Make the function use the given implementation, an error is returned if the implementation is not of the same type as the function.
func (Function) MakeError ¶
MakeError makes the function use the given error as its implementation. Either returning it (if possible) otherwise panicking with it.
func (Function) NumIn ¶
NumIn returns the number of arguments to the function except for the first argument if it is a context.Context.
func (Function) NumOut ¶
NumOut returns the number of return values for the function excluding the [error] value.
func (Function) Return ¶
Return returns the given results, if err is not nil, then results can be nil and vice versa.
func (Function) 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 ¶
Linker that can link an iqlink API structure up to a 'Host' implementation using the specified 'Connection' configuration.
type Register ¶
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 iqlink API structures.
type Structure ¶
type Structure struct {
Name string
Docs string
Tags reflect.StructTag
Host reflect.StructTag // host tag determined by GOOS.
// 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 an iqlink API structure. In Go source, these are represented using Go structs with at least one function field. These iqlink 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 ¶
StructureOf returns a reflected iqlink 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 ¶
Format implements fmt.Formatter so that every verb, including %#v, uses Structure.String instead of dumping fields.
func (Structure) MakeError ¶
MakeError calls Function.MakeError on each function within the structure.
func (Structure) 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 ¶
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) 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 github.com/iqhive/iqlink/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 iqlink recognises) what a valid value looks like. The underlying failure is written for a Go developer, may quote internal type names or the 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 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 ¶
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 iqlink (WORK-IN-PROGRESS).
|
Package call provides shared library linker for iqlink (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/cgo/gen
command
|
|
|
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 alternative to reflect.MakeFunc with support for transparent optimisation.
|
Package jit provides a safe alternative to reflect.MakeFunc with support for transparent optimisation. |
|
Package cmdl provides a command-line interface linker for iqlink.
|
Package cmdl provides a command-line interface linker for iqlink. |
|
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
|
|
|
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. |
|
gl
Code generated by generate.go; DO NOT EDIT.
|
Code generated by generate.go; DO NOT EDIT. |
|
gl/internal/example
command
|
|
|
gl/internal/generate
command
|
|
|
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. |
|
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]. |