api

package
v0.0.0-...-50c8bf6 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2025 License: 0BSD Imports: 15 Imported by: 1

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"

	"runtime.link/api"
	"runtime.link/api/cmdl"
	"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)
}
Output:

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.

func ListenAndServe

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

Types

type ArgumentScanner

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

ArgumentScanner can scan arguments via a formatting pattern. Either %v, %[n]v or FieldName

func NewArgumentScanner

func NewArgumentScanner(args []reflect.Value) ArgumentScanner

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

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 or a FieldName.

type Auth

type Auth[Conn any] interface {
	// AssertHeader 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(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

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

func (Documentation) Example

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

func (Documentation) Examples

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

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
	// 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

	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 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.

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) In

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

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.

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.

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) 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.

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[I any, V 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 Scenario

type Scenario struct {
	Name string
	Kind string
	Text string
	Tags reflect.StructTag
	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 struct{}

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

	Error error
	Depth uint
	Setup bool
}

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 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).

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.

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.

type TestingFramework

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

func (*TestingFramework) Guide

func (tdd *TestingFramework) Guide(description literal)

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 WithExamples

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

type WithSpecification

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

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/cgo
Code generated by gen/gen.go.
Code generated by gen/gen.go.
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 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.
internal
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.1.0
Package oas provides a representation of the OpenAPI Specification (OAS) Version 3.1.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 pair can represent 1:1 mappings between two different APIs, such that validation errors are transformed.
Package pair can represent 1:1 mappings between two different APIs, such that validation errors are transformed.
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 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