Documentation ¶
Overview ¶
Package weaver provides the interface for building single-image distributed programs.
A program is composed of a set of Go interfaces called components. Components are recognized by "weaver generate" (typically invoked via "go generate"). "weaver generate" generates code that allows a component to be invoked over the network. This flexibility allows Service Weaver to decompose the program execution across many processes and machines.
Index ¶
- Constants
- Variables
- func CreateRabbitMQ(rabbit_host string, rabbit_port string, rabbit_user string, ...) antipode.RabbitMQ
- func CreateRedis(redis_host string, redis_port string, redis_password string) antipode.Redis
- func InitCtx(ctx context.Context) context.Context
- func InstrumentHandler(label string, handler http.Handler) http.Handler
- func InstrumentHandlerFunc(label string, f func(http.ResponseWriter, *http.Request)) http.Handler
- func Run[T any, P PointerToMain[T]](ctx context.Context, app func(context.Context, *T) error) error
- func Transfer(ctx context.Context, lineage Lineage) (context.Context, error)
- type Antipode
- type AutoMarshal
- type Implements
- type InstanceOf
- type Lineage
- type Listener
- type Main
- type NotRetriable
- type PointerToMain
- type Ref
- type RoutedBy
- type Unrouted
- type WeaverInfo
- type WithConfig
- type WithRouter
Examples ¶
Constants ¶
const HealthzURL = "/debug/weaver/healthz"
HealthzURL is the URL path on which Service Weaver performs health checks. Every application HTTP server must register a handler for this URL path, e.g.:
mux := http.NewServeMux() mux.HandleFunc(weaver.HealthzURL, func(http.ResponseWriter, *http.Request) { // ... })
As a convenience, Service Weaver registers HealthzHandler under this URL path in the default ServerMux, i.e.:
http.HandleFunc(weaver.HealthzURL, weaver.HealthzHandler)
Variables ¶
var HealthzHandler = func(w http.ResponseWriter, _ *http.Request) { fmt.Fprintf(w, "OK") }
HealthzHandler is a health-check handler that returns an OK status for all incoming HTTP requests.
var RemoteCallError = errors.New("Service Weaver remote call error")
RemoteCallError indicates that a remote component method call failed to execute properly. This can happen, for example, because of a failed machine or a network partition. Here's an illustrative example:
// Call the foo.Foo method. err := foo.Foo(ctx) if errors.Is(err, weaver.RemoteCallError) { // foo.Foo did not execute properly. } else if err != nil { // foo.Foo executed properly, but returned an error. } else { // foo.Foo executed properly and did not return an error. }
Note that if a method call returns an error with an embedded RemoteCallError, it does NOT mean that the method never executed. The method may have executed partially or fully. Thus, you must be careful retrying method calls that result in a RemoteCallError. Ensuring that all methods are either read-only or idempotent is one way to ensure safe retries, for example.
Functions ¶
func CreateRabbitMQ ¶
func CreateRedis ¶
func InstrumentHandler ¶
InstrumentHandler instruments the provided HTTP handler to collect sampled traces and metrics of HTTP request executions. Each trace and metric is labelled with the supplied label. The following metrics are collected:
- serviceweaver_http_request_count: Total number of requests.
- serviceweaver_http_error_count: Total number of 4XX and 5XX replies.
- serviceweaver_http_request_latency_micros: Execution latency in microseconds.
- serviceweaver_http_request_bytes_received: Total number of request bytes.
- serviceweaver_http_request_bytes_returned: Total number of response bytes
Example ¶
var mux http.ServeMux mux.Handle("/foo", InstrumentHandler("foo", http.HandlerFunc(func(http.ResponseWriter, *http.Request) { /*...*/ }))) mux.Handle("/bar", InstrumentHandler("bar", http.HandlerFunc(func(http.ResponseWriter, *http.Request) { /*...*/ }))) http.ListenAndServe(":9000", &mux)
Output:
func InstrumentHandlerFunc ¶
InstrumentHandlerFunc is identical to InstrumentHandler but takes a function instead of an http.Handler.
func Run ¶
Run runs app as a Service Weaver application.
The application is composed of a set of components that include weaver.Main as well as any components transitively needed by weaver.Main. An instance that implement weaver.Main is automatically created by weaver.Run and passed to app. Note: other replicas in which weaver.Run is called may also create instances of weaver.Main.
The type T must be a struct type that contains an embedded `weaver.Implements[weaver.Main]` field. A value of type T is created, initialized (by calling its Init method if any), and a pointer to the value is passed to app. app contains the main body of the application; it will typically run HTTP servers, etc.
If this process is hosting the `weaver.Main` component, Run will call app and will return when app returns. If this process is hosting other components, Run will start those components and never return. Most callers of Run will not do anything (other than possibly logging any returned error) after Run returns.
func main() { if err := weaver.Run(context.Background(), app); err != nil { log.Fatal(err) } }
Types ¶
type Antipode ¶
type Antipode struct { Datastore_type antipode.Datastore_type Datastore_ID string }
type AutoMarshal ¶
type AutoMarshal struct{}
AutoMarshal is a type that can be embedded within a struct to indicate that "weaver generate" should generate serialization methods for the struct.
Named struct types are not serializable by default. However, they can trivially be made serializable by embedding AutoMarshal. For example:
type Pair struct { weaver.AutoMarshal x, y int }
The AutoMarshal embedding instructs "weaver generate" to generate serialization methods for the struct, Pair in this example.
Note, however, that AutoMarshal cannot magically make any type serializable. For example, "weaver generate" will raise an error for the following code because the NotSerializable struct is fundamentally not serializable.
// ERROR: NotSerializable cannot be made serializable. type NotSerializable struct { weaver.AutoMarshal f func() // functions are not serializable c chan int // chans are not serializable }
func (AutoMarshal) WeaverMarshal ¶
func (AutoMarshal) WeaverMarshal(*codegen.Encoder)
func (AutoMarshal) WeaverUnmarshal ¶
func (AutoMarshal) WeaverUnmarshal(*codegen.Decoder)
type Implements ¶
type Implements[T any] struct { // contains filtered or unexported fields }
Implements[T] is a type that is be embedded inside a component implementation struct to indicate that the struct implements a component of type T. For example, consider a Cache component.
type Cache interface { Get(ctx context.Context, key string) (string, error) Put(ctx context.Context, key, value string) error }
A concrete type that implements the Cache component is written as follows:
type lruCache struct { weaver.Implements[Cache] ... }
Because Implements is embedded inside the component implementation, methods of Implements are available as methods of the component implementation type and can be invoked directly. For example, given an instance c of type lruCache, we can call c.Logger().
func (Implements[T]) Logger ¶
func (i Implements[T]) Logger(ctx context.Context) *slog.Logger
Logger returns a logger that associates its log entries with this component. Log entries are labeled with any OpenTelemetry trace id and span id in the provided context.
func (Implements[T]) Weaver ¶
func (i Implements[T]) Weaver() WeaverInfo
Weaver returns runtime information about the deployed application.
type InstanceOf ¶
type InstanceOf[T any] interface { // contains filtered or unexported methods }
InstanceOf[T] is the interface implemented by a struct that embeds weaver.Implements[T].
type Listener ¶
type Listener struct { net.Listener // underlying listener // contains filtered or unexported fields }
Listener is a network listener that can be placed as a field inside a component implementation struct. Once placed, Service Weaver automatically initializes the Listener and makes it suitable for receiving network traffic. For example:
type myComponentImpl struct { weaver.Implements[MyComponent] myListener weaver.Listener myOtherListener weaver.Listener }
By default, all listeners listen on address ":0". This behavior can be modified by passing options for individual listeners in the application config. For example, to specify local addresses for the above two listeners, the user can add the following lines to the application config file:
[listeners] myListener = {local_address = "localhost:9000"} myOtherListener = {local_address = "localhost:9001"}
Listeners are identified by their field names in the component implementation structs (e.g., myListener and myOtherListener). If the user wishes to assign different names to their listeners, they may do so by adding a `weaver:"name"` struct tag to their listener fields, e.g.:
type myComponentImpl struct { weaver.Implements[MyComponent] myListener weaver.Listener myOtherListener weaver.Listener `weaver:"mylistener2"` }
Listener names must be valid Go identifier names. Listener names must be unique inside a given application binary, regardless of which components they are specified in. For example, it is illegal to declare a Listener field "foo" in two different component implementation structs, unless one is renamed using the `weaver:"name"` struct tag.
HTTP servers constructed using this listener are expected to perform health checks on the reserved HealthzURL path. (Note that this URL path is configured to never receive any user traffic.)
type Main ¶
type Main interface{}
Main is the interface implemented by an application's main component.
type NotRetriable ¶
type NotRetriable interface{}
type PointerToMain ¶
type PointerToMain[T any] interface { *T InstanceOf[Main] }
PointerToMain is a type constraint that asserts *T is an instance of Main (i.e. T is a struct that embeds weaver.Implements[weaver.Main]).
type Ref ¶
type Ref[T any] struct { // contains filtered or unexported fields }
Ref[T] is a field that can be placed inside a component implementation struct. T must be a component type. Service Weaver will automatically fill such a field with a handle to the corresponding component.
type RoutedBy ¶
type RoutedBy[T any] interface { // contains filtered or unexported methods }
RoutedBy[T] is the interface implemented by a struct that embeds weaver.RoutedBy[T].
type Unrouted ¶
type Unrouted interface {
// contains filtered or unexported methods
}
Unrouted is the interface implemented by instances that don't embed weaver.WithRouter[T].
type WeaverInfo ¶
type WeaverInfo struct { // Unique identifier for the application deployment. DeploymentID string }
WeaverInfo holds runtime information about a deployed application.
type WithConfig ¶
type WithConfig[T any] struct { // contains filtered or unexported fields }
WithConfig[T] is a type that can be embedded inside a component implementation. The Service Weaver runtime will take per-component configuration information found in the application config file and use it to initialize the contents of T.
Example ¶
Consider a cache component where the cache size should be configurable. Define a struct that includes the size, associate it with the component implementation, and use it inside the component methods.
type cacheConfig struct Size int } type cache struct { weaver.Implements[Cache] weaver.WithConfig[cacheConfig] // ... } func (c *cache) Init(context.Context) error { // Use c.Config().Size... return nil }
The application config file can specify these values as keys under the full component path.
["example.com/mypkg/Cache"] Size = 1000
Field Names ¶
You can use `toml` struct tags to specify the name that should be used for a field in a config file. For example, we can change the cacheConfig struct to the following:
type cacheConfig struct Size int `toml:"my_custom_name"` }
And change the config file accordingly:
["example.com/mypkg/Cache"] my_custom_name = 1000
func (*WithConfig[T]) Config ¶
func (wc *WithConfig[T]) Config() *T
Config returns the configuration information for the component that embeds this weaver.WithConfig.
Any fields in T that were not present in the application config file will have their default values.
Any fields in the application config file that are not present in T will be flagged as an error at application startup.
type WithRouter ¶
type WithRouter[T any] struct{}
WithRouter[T] is a type that can be embedded inside a component implementation struct to indicate that calls to a method M on the component must be routed according to the the value returned by T.M().
Example ¶
For example, consider a Cache component that maintains an in-memory cache.
type Cache interface { Get(ctx context.Context, key string) (string, error) Put(ctx context.Context, key, value string) error }
We can create a router for the Cache component like this.
type cacheRouter struct{} func (cacheRouter) Get(_ context.Context, key string) string { return key } func (cacheRouter) Put(_ context.Context, key, value string) string { return key }
To associate a router with its component, embed weaver.WithRouter in the component implementation.
type lruCache struct { weaver.Implements[Cache] weaver.WithRouter[cacheRouter] }
For every component method that needs to be routed (e.g., Get and Put), the associated router should implement an equivalent method (i.e., same name and argument types) whose return type is the routing key. When a component's routed method is invoked, its corresponding router method is invoked to produce a routing key. Method invocations that produce the same key are routed to the same replica.
Routing Keys ¶
A routing key can be any integer (e.g., int, int32), float (i.e. float32, float64), or string; or a struct where all fields are integers, floats, or strings. A struct may also embed AutoMarshal. For example, the following are valid routing keys.
int int32 float32 float63 string struct{} struct{x int} struct{x int; y string} struct{weaver.AutoMarshal; x int; y string}
Every router method must return the same routing key type. The following, for example, is invalid:
// ERROR: Get returns a string, but Put returns an int. func (cacheRouter) Get(_ context.Context, key string) string { return key } func (cacheRouter) Put(_ context.Context, key, value string) int { return 42 }
Semantics ¶
NOTE that routing is done on a best-effort basis. Service Weaver will try to route method invocations with the same key to the same replica, but this is not guaranteed. As a corollary, you should never depend on routing for correctness. Only use routing to increase performance in the common case.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
cmd
|
|
weaver
Weaver deploys and manages Weaver applications.
|
Weaver deploys and manages Weaver applications. |
dev
|
|
docgen
docgen generates a static web site from markdown and other files.
|
docgen generates a static web site from markdown and other files. |
internal
|
|
cond
Package cond implements a context-aware condition variable.
|
Package cond implements a context-aware condition variable. |
config
Package config contains config related utilities.
|
Package config contains config related utilities. |
env
Package env implements helper functions for dealing with environment variables.
|
Package env implements helper functions for dealing with environment variables. |
files
Package files contains file-related utilities.
|
Package files contains file-related utilities. |
heap
Package heap provide a min-heap implementation called Heap.
|
Package heap provide a min-heap implementation called Heap. |
must
Package must provides a generic Must function.
|
Package must provides a generic Must function. |
net/call
Package call implements an RPC mechanism.
|
Package call implements an RPC mechanism. |
pipe
Package pipe extends os.exec, making it easier to create pipes to subcommands.
|
Package pipe extends os.exec, making it easier to create pipes to subcommands. |
reflection
Package reflection implements helpers for reflection code.
|
Package reflection implements helpers for reflection code. |
register
Package register implements a write-once register.
|
Package register implements a write-once register. |
routing
Package routing includes utilities for routing and assignments.
|
Package routing includes utilities for routing and assignments. |
status
Package status contains code for implementing status related commands like "weaver multi status" and "weaver single dashboard".
|
Package status contains code for implementing status related commands like "weaver multi status" and "weaver single dashboard". |
tool/callgraph
Package callgraph contains code to create visualizations of component call graphs stored inside a Service Weaver binary.
|
Package callgraph contains code to create visualizations of component call graphs stored inside a Service Weaver binary. |
Package metrics provides an API for counters, gauges, and histograms.
|
Package metrics provides an API for counters, gauges, and histograms. |
Package runtime contains code suitable for deployer implementers but not Service Weaver application developers.
|
Package runtime contains code suitable for deployer implementers but not Service Weaver application developers. |
bin
Package bin contains code to extract data from a Service Weaver binary.
|
Package bin contains code to extract data from a Service Weaver binary. |
codegen
Package codegen contains functions and types used by the weaver_gen.go files generated by "weaver generate".
|
Package codegen contains functions and types used by the weaver_gen.go files generated by "weaver generate". |
colors
Package colors contains color-related utilities.
|
Package colors contains color-related utilities. |
deployers
Deployers provides useful utilities for implementing Service Weaver deployers.
|
Deployers provides useful utilities for implementing Service Weaver deployers. |
envelope
Package envelope implements a sidecar-like process that connects a weavelet to its environment.
|
Package envelope implements a sidecar-like process that connects a weavelet to its environment. |
logging
Package logging contains logging related utilities.
|
Package logging contains logging related utilities. |
metrics
Package metrics implements Service Weaver metrics.
|
Package metrics implements Service Weaver metrics. |
perfetto
Package perfetto provides utilities for encoding trace spans in a format that can be read by the Perfetto UI.
|
Package perfetto provides utilities for encoding trace spans in a format that can be read by the Perfetto UI. |
protomsg
Package protomsg contains protobuf-related utilities.
|
Package protomsg contains protobuf-related utilities. |
retry
Package retry contains code to perform retries with exponential backoff.
|
Package retry contains code to perform retries with exponential backoff. |
tool
Package tool contains utilities for creating Service Weaver tools similar to weaver-multi, weaver-gke, and weaver-gke-local.
|
Package tool contains utilities for creating Service Weaver tools similar to weaver-multi, weaver-gke, and weaver-gke-local. |
traces
Package perfetto contains libraries for displaying trace information in the Perfetto UI.
|
Package perfetto contains libraries for displaying trace information in the Perfetto UI. |
version
Package version contains the version of the weaver module and its constituent APIs (e.g., the pipe API, the codegen API).
|
Package version contains the version of the weaver module and its constituent APIs (e.g., the pipe API, the codegen API). |