functions

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 13, 2026 License: MIT Imports: 32 Imported by: 0

Documentation

Overview

Package functions builds and runs Go Cloud Functions as child processes.

There is no Docker and no buildpack: cloudrig generates a main that imports the function's package, compiles it with the toolchain already present, and serves it. Go only, for now.

Index

Constants

View Source
const (
	DefaultProject  = "cloudrig-local"
	DefaultLocation = "us-central1"
)

DefaultProject and DefaultLocation stand in when a caller does not say. Real gcloud always sends both in the resource path, so these only matter for the short URL form and for a CLI invocation without --project.

View Source
const (
	// MaxDeliveryAttempts includes the first try.
	MaxDeliveryAttempts = 5

	// RetryBackoff is the first wait; it doubles each attempt.
	RetryBackoff = 200 * time.Millisecond
)

Retry bounds a failed delivery. GCF retries a background function, so a function that is briefly unwell should not silently lose an event.

View Source
const AdminPath = "/_emu/functions"

AdminPath is where the registry's admin API is mounted.

View Source
const WatchInterval = 300 * time.Millisecond

WatchInterval is how often a watched source tree is rescanned.

Variables

This section is empty.

Functions

func DetectEntryPoint

func DetectEntryPoint(dir string) (string, error)

DetectEntryPoint picks the only exported handler in dir, so the common case needs no --entry-point at all.

func EntryPoints

func EntryPoints(dir string) ([]string, error)

EntryPoints lists the exported func(http.ResponseWriter, *http.Request) in dir, sorted, so a caller can detect or report the candidates.

func KnownRuntimes

func KnownRuntimes() []string

KnownRuntimes lists the accepted --runtime values, sorted.

func ResourceName

func ResourceName(project, location, name string) string

ResourceName builds a function resource name, filling in defaults.

Types

type DeployRequest

type DeployRequest struct {
	Project    string       `json:"project,omitempty"`
	Location   string       `json:"location,omitempty"`
	Name       string       `json:"name"`
	Source     string       `json:"source"`
	Runtime    Runtime      `json:"runtime,omitempty"`
	EntryPoint string       `json:"entryPoint,omitempty"`
	Watch      bool         `json:"watch,omitempty"`
	Trigger    EventTrigger `json:"trigger,omitempty"`
}

DeployRequest is the body of a deploy. Source is a path on the machine running the emulator, not an uploaded archive: the emulator and the CLI share a filesystem, and pretending otherwise would buy nothing.

type Descriptor

type Descriptor struct {
	Project    string       `json:"project"`
	Location   string       `json:"location"`
	Name       string       `json:"name"`
	Source     string       `json:"source"`
	Runtime    Runtime      `json:"runtime"`
	EntryPoint string       `json:"entryPoint"`
	Watch      bool         `json:"watch,omitempty"`
	Trigger    EventTrigger `json:"trigger,omitempty"`
	State      string       `json:"state"`
	UpdateTime time.Time    `json:"updateTime"`
}

Descriptor is a deployed function.

It is deliberately neutral: neither the v1 nor the v2 wire shape, but the facts both are projections of. Storing a wire shape would make the second API a translation of the first rather than a second view of the truth.

func (Descriptor) ResourceName

func (d Descriptor) ResourceName() string

ResourceName is projects/P/locations/L/functions/F.

type EventTrigger

type EventTrigger struct {
	// EventType is the CloudEvents type to listen for, e.g.
	// google.cloud.storage.object.v1.finalized.
	EventType string

	// Resource narrows the trigger, e.g. a bucket name. Empty listens to every
	// source of that type.
	Resource string
}

EventTrigger makes a function run when something happens rather than when it is called.

func (EventTrigger) IsSet

func (t EventTrigger) IsSet() bool

IsSet reports whether a trigger was configured.

type Function

type Function struct {
	// Project and Location complete the identity. Empty means the defaults.
	Project  string
	Location string

	// Name is the function id, the last segment of its resource name.
	Name string

	// Source is the directory holding the function's code.
	Source string

	// Runtime is a gcloud runtime identifier. Empty means detect from Source.
	Runtime Runtime

	// EntryPoint is the exported handler to serve.
	EntryPoint string

	// Watch redeploys the function when its source changes.
	Watch bool

	// Trigger runs the function on an event instead of an HTTP request.
	Trigger EventTrigger
}

Function names a deployable HTTP function.

func (Function) ResourceName

func (f Function) ResourceName() string

ResourceName is projects/P/locations/L/functions/F, the identity both API versions address a function by.

type Instance

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

Instance is a running function: a child process plus the proxy to it.

func Start

func Start(ctx context.Context, f Function, o Options) (*Instance, error)

Start builds f and launches it, returning once the child is listening.

Readiness is not polled: the generated shim binds its own port and prints the address, so the parent learns it is up by reading one line.

func (*Instance) EntryPoint

func (i *Instance) EntryPoint() string

EntryPoint is the resolved handler being served.

func (*Instance) FollowLogs

func (i *Instance) FollowLogs() (<-chan string, func())

FollowLogs streams lines written from now on, and returns a stop function.

func (*Instance) Location

func (i *Instance) Location() string

func (*Instance) LogSnapshot

func (i *Instance) LogSnapshot() []string

LogSnapshot returns the function's recent output.

func (*Instance) Name

func (i *Instance) Name() string

Name is the URL segment the function is served under.

func (*Instance) Project

func (i *Instance) Project() string

Project and Location are the resolved identity of the function.

func (*Instance) Runtime

func (i *Instance) Runtime() Runtime

Runtime is the resolved runtime the function is running on.

func (*Instance) ServeHTTP

func (i *Instance) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP proxies to the child process.

func (*Instance) Stop

func (i *Instance) Stop() error

Stop kills the child and removes its binary.

func (*Instance) URL

func (i *Instance) URL() string

URL is the child's own address, bypassing the emulator.

type Options

type Options struct {
	// Stderr receives the function's own output. Nil discards it, which is the
	// daemon's default: fn logs is where that output belongs.
	Stderr io.Writer

	// EventLog receives the registry's own messages — a watch redeploying, or
	// failing to. Distinct from Stderr so a daemon can report what it did
	// without echoing every line the function writes.
	EventLog io.Writer

	// Env is extra environment for the child, as KEY=VALUE.
	Env []string
}

Options configures Start.

type Registry

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

Registry holds the functions a running emulator is serving. Deploying a name that already exists replaces it, which is also how redeploy and hot reload work.

func NewRegistry

func NewRegistry(clk clock.Clock, bus *events.Bus, opts Options) *Registry

NewRegistry returns an empty registry. opts apply to every function it runs. A nil bus means event triggers never fire.

func (*Registry) Admin

func (r *Registry) Admin() http.Handler

Admin serves deploy, list, describe and delete.

func (*Registry) Delete

func (r *Registry) Delete(project, location, name string) error

Delete stops and removes a function.

func (*Registry) Deploy

func (r *Registry) Deploy(ctx context.Context, f Function) (Descriptor, error)

Deploy builds and starts f, replacing any function of the same name.

The replacement is started before the old one is stopped, so a failed deploy leaves the previous version serving rather than taking the name down.

func (*Registry) Get

func (r *Registry) Get(project, location, name string) (Descriptor, bool)

Get returns one descriptor by project, location and name. Empty project or location mean the defaults.

func (*Registry) GetByResource

func (r *Registry) GetByResource(resource string) (Descriptor, bool)

GetByResource returns one descriptor by full resource name.

func (*Registry) Handler

func (r *Registry) Handler(project, location, name string) (http.Handler, bool)

Handler returns the handler serving a function, for callers that invoke it directly rather than through a URL.

func (*Registry) Instance

func (r *Registry) Instance(project, location, name string) (*Instance, bool)

Instance returns the running function, for callers that need more than its handler — its logs, say.

func (*Registry) List

func (r *Registry) List(project, location string) []Descriptor

List returns every descriptor, by resource name. An empty project or location matches everything.

func (*Registry) Route

func (r *Registry) Route(escapedPath string) (http.Handler, string, bool)

Route resolves a request path to a deployed function and the path that function should see.

Two forms are accepted:

/{name}                          the default project and location
/{location}-{project}/{name}     the form the GCF emulator uses

A function is the root of its own URL space, so /hello/a/b reaches it as /a/b, matching how Cloud Functions presents it.

func (*Registry) SetEnv

func (r *Registry) SetEnv(env []string)

SetEnv sets environment variables injected into every function deployed after this call. Used to point functions at the emulator's own endpoints.

func (*Registry) StopAll

func (r *Registry) StopAll()

StopAll shuts every function down. It is safe to call twice.

type Runtime

type Runtime string

Runtime names the language stack a function runs on, using the same identifiers as gcloud functions deploy --runtime.

const (
	RuntimeGo     Runtime = "go"
	RuntimeNode20 Runtime = "nodejs20"
	RuntimeNode22 Runtime = "nodejs22"
)

func DetectRuntime

func DetectRuntime(source string) (Runtime, error)

DetectRuntime infers the runtime from what is in the source directory, so --runtime is optional for the obvious cases.

Jump to

Keyboard shortcuts

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