providerfw

package
v0.0.18 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2025 License: MIT, Apache-2.0 Imports: 34 Imported by: 0

README

pulumi-go-provider

This is a fork of pulumi-go-provider because mid needs to access internals of the library that aren't exposed. Don't use this in your own projects unless you know what you're doing.

Documentation

Overview

Package provider works as a shared high-level interface for rpc.ResourceProviderServer.

It is the lowest level that the rest of this repo should target, and servers as an interoperability layer between middle-wares.

Index

Constants

View Source
const (
	// FrameworkStateKeyName is the key name used to store the framework version in
	// a program's state.
	FrameworkStateKeyName = "pulumi-go-provider-version"
)

Variables

View Source
var ErrNoHost = errors.New("no provider host found in context")
View Source
var FrameworkVersion semver.Version

Version is the framework's release version. Be aware that if the framework is installed from a git commit, this will refer to the next proposed release, not a format like "1.2.3-$COMMIT".

View Source
var VersionStr = strings.TrimPrefix(version.Version, "v")

Functions

func ConfigMissingKeys

func ConfigMissingKeys(missing map[string]string) error

ConfigMissingKeys creates a structured error for missing provider keys.

func Errorf

func Errorf(msg string, a ...any) error

Errorf creates a new Error by delegating to fmt.Errorf.

func GetSchema

func GetSchema(ctx context.Context, name, version string, provider Provider) (schema.PackageSpec, error)

GetSchema retrieves the schema from the provider by invoking GetSchema on the provider.

This is a helper method to retrieve the schema from a provider without running the provider in a separate process. It should not be necessary for most providers.

To retrieve the schema from a provider binary, use

pulumi package get-schema ./pulumi-resource-MYPROVIDER

func GetTypeToken

func GetTypeToken[Ctx interface{ Value(any) any }](ctx Ctx) string

GetTypeToken returns the type associated with the current call.

ctx can either be the context.Context associated with currently gRPC method being served or a [*pulumi.Context] within github.com/sapslaj/mid/pkg/providerfw/infer's component resources.

If no type token is available, then the empty string will be returned.

func InternalErrorf

func InternalErrorf(msg string, a ...any) error

InternalErrorf indicates that the provider encountered an internal error.

This will tell the user that the provider had a bug, and the bug should be reported to the provider author.

This is different then [internal.Error], which indicates that pulumi-go-provider has a bug.

func RawServer

func RawServer(
	name, version string,
	provider Provider,
) func(*pprovider.HostClient) (rpc.ResourceProviderServer, error)

RawServer converts the Provider into a factory for gRPC servers.

If you are trying to set up a standard main function, see RunProvider.

func RunProvider

func RunProvider(ctx context.Context, name, version string, provider Provider) error

RunProvider runs a provider with the given name and version.

func RunProviderF

func RunProviderF(
	ctx context.Context,
	name string,
	version string,
	providerF func(*pprovider.HostClient) (Provider, error),
) error

RunProviderF allows running a provider that has not yet been bound to a HostClient.

Types

type CallRequest

type CallRequest struct {
	// the function token to invoke.
	Tok tokens.ModuleMember
	// the arguments for the function invocation.
	Args property.Map
	// the project name.
	Project string
	// the name of the stack being deployed into.
	Stack string
	// the configuration variables to apply before running.
	Config map[pconfig.Key]string
	// the configuration keys that have secret values.
	ConfigSecretKeys []pconfig.Key
	// true if we're only doing a dryrun (preview).
	DryRun bool
	// the degree of parallelism for resource operations (<=1 for serial).
	Parallel int32
	// the address for communicating back to the resource monitor.
	MonitorEndpoint string
	// the organization of the stack being deployed into.
	Organization string
}

CallRequest represents a requested resource method invocation.

It corresponds to rpc.CallRequest on the wire.

type CallResponse

type CallResponse struct {
	// The returned values, if the call was successful.
	Return property.Map
	// The failures if any arguments didn't pass verification.
	Failures []CheckFailure
}

CallResponse represents a completed resource method invocation.

It corresponds to rpc.CallResponse on the wire.

func ProgramCall

func ProgramCall(ctx context.Context, req CallRequest, callF comProvider.CallFunc,
) (CallResponse, error)

ProgramCall is a convenience function for a Provider to implement [Provider.Call] using the Pulumi Go SDK.

Call this method from within your [Provider.Call] method to transition into a Go SDK program context.

type CheckFailure

type CheckFailure struct {
	Property string
	Reason   string
}

type CheckRequest

type CheckRequest struct {
	Urn        presource.URN
	State      property.Map
	Inputs     property.Map
	RandomSeed []byte
}

type CheckResponse

type CheckResponse struct {
	Inputs   property.Map
	Failures []CheckFailure
}

type ConfigureRequest

type ConfigureRequest struct {
	Variables map[string]string
	Args      property.Map
}

type ConstructRequest

type ConstructRequest struct {
	// URN is the Pulumi URN for this resource.
	Urn presource.URN

	// Configuration for the specified project and stack.
	Config map[pconfig.Key]string

	// A set of configuration keys whose values are secrets.
	ConfigSecretKeys []pconfig.Key

	// True if and only if the request is being made as part of a preview/dry run, in which case the provider should not
	// actually construct the component.
	DryRun bool

	// The degree of parallelism that may be used for resource operations. A value less than or equal to 1 indicates
	// that operations should be performed serially.
	Parallel int32

	// The address of the [](pulumirpc.ResourceMonitor) that the provider should connect to in order to send [resource
	// registrations](resource-registration) for its nested resources.
	MonitorEndpoint string // the RPC address to the host resource monitor.

	// Parent is the URN of the parent resource.
	Parent presource.URN

	// Inputs is the set of inputs for the component.
	Inputs property.Map

	// Aliases is the set of aliases for the component.
	Aliases []presource.URN

	// Dependencies is the list of resources this component depends on, i.e. the DependsOn resource option.
	Dependencies []presource.URN

	// Protect is true if the component is protected.
	Protect *bool

	// Providers is a map from package name to provider reference.
	Providers map[tokens.Package]ProviderReference

	// AdditionalSecretOutputs lists extra output properties
	// that should be treated as secrets.
	AdditionalSecretOutputs []string

	// CustomTimeouts overrides default timeouts for resource operations.
	CustomTimeouts *presource.CustomTimeouts

	// DeletedWith specifies that if the given resource is deleted,
	// it will also delete this resource.
	DeletedWith presource.URN

	// DeleteBeforeReplace specifies that replacements of this resource
	// should delete the old resource before creating the new resource.
	DeleteBeforeReplace *bool

	// IgnoreChanges lists properties that should be ignored
	// when determining whether the resource should has changed.
	IgnoreChanges []string

	// ReplaceOnChanges lists properties changing which should cause
	// the resource to be replaced.
	ReplaceOnChanges []string

	// RetainOnDelete is true if deletion of the resource should not
	// delete the resource in the provider.
	RetainOnDelete *bool
}

ConstructRequest captures enough data to be able to register nested components against the caller's resource monitor.

type ConstructResponse

type ConstructResponse struct {
	// the Pulumi URN for this resource.
	Urn presource.URN
	// the state of this resource.
	State property.Map
}

func ProgramConstruct

func ProgramConstruct(ctx context.Context, req ConstructRequest, constructF comProvider.ConstructFunc,
) (ConstructResponse, error)

ProgramConstruct is a convenience function for a Provider to implement [Provider.Construct] using the Pulumi Go SDK.

Call this method from within your [Provider.Construct] method to transition into a Go SDK program context.

type CreateRequest

type CreateRequest struct {
	Urn        presource.URN // the Pulumi URN for this resource.
	Properties property.Map  // the provider inputs to set during creation.
	Timeout    float64       // the create request timeout represented in seconds.
	DryRun     bool          // true if this is a preview and the provider should not actually create the resource.
}

type CreateResponse

type CreateResponse struct {
	ID         string       // the ID of the created resource.
	Properties property.Map // any properties that were computed during creation.

	// non-nil to indicate that the create failed and left the resource in a partial
	// state.
	//
	// If PartialState is non-nil, then an error will be returned, annotated with
	// [pulumirpc.ErrorResourceInitFailed].
	PartialState *InitializationFailed
}

type DeleteRequest

type DeleteRequest struct {
	ID         string        // the ID of the resource to delete.
	Urn        presource.URN // the Pulumi URN for this resource.
	Properties property.Map  // the current properties on the resource.
	Timeout    float64       // the delete request timeout represented in seconds.
}

type DiffKind

type DiffKind string
const (
	Add           DiffKind = "add"            // this property was added
	AddReplace    DiffKind = "add&replace"    // this property was added, and this change requires a replace
	Delete        DiffKind = "delete"         // this property was removed
	DeleteReplace DiffKind = "delete&replace" // this property was removed, and this change requires a replace
	Update        DiffKind = "update"         // this property's value was changed
	UpdateReplace DiffKind = "update&replace" // this property's value was changed, and this change requires a replace
	Stable        DiffKind = "stable"         // this property's value will not change
)

type DiffRequest

type DiffRequest struct {
	ID            string
	Urn           presource.URN
	State         property.Map
	Inputs        property.Map
	IgnoreChanges []string
}

type DiffResponse

type DiffResponse struct {
	DeleteBeforeReplace bool // if true, this resource must be deleted before replacing it.
	HasChanges          bool // if true, this diff represents an actual difference and thus requires an update.
	// detailedDiff is an optional field that contains map from each changed property to the type of the change.
	//
	// The keys of this map are property paths. These paths are essentially Javascript property access expressions
	// in which all elements are literals, and obey the following EBNF-ish grammar:
	//
	//   propertyName := [a-zA-Z_$] { [a-zA-Z0-9_$] }
	//   quotedPropertyName := '"' ( '\' '"' | [^"] ) { ( '\' '"' | [^"] ) } '"'
	//   arrayIndex := { [0-9] }
	//
	//   propertyIndex := '[' ( quotedPropertyName | arrayIndex ) ']'
	//   rootProperty := ( propertyName | propertyIndex )
	//   propertyAccessor := ( ( '.' propertyName ) |  propertyIndex )
	//   path := rootProperty { propertyAccessor }
	//
	// Examples of valid keys:
	// - root
	// - root.nested
	// - root["nested"]
	// - root.double.nest
	// - root["double"].nest
	// - root["double"]["nest"]
	// - root.array[0]
	// - root.array[100]
	// - root.array[0].nested
	// - root.array[0][1].nested
	// - root.nested.array[0].double[1]
	// - root["key with \"escaped\" quotes"]
	// - root["key with a ."]
	// - ["root key with \"escaped\" quotes"].nested
	// - ["root key with a ."][100]
	DetailedDiff map[string]PropertyDiff
}

type Error

type Error struct {
	Inner error
}

Error indicates a bug in the pulumi-go-provider framework.

func (Error) Error

func (err Error) Error() string

type GetSchemaRequest

type GetSchemaRequest struct {
	Version int
}

type GetSchemaResponse

type GetSchemaResponse struct {
	Schema string
}

type Host

type Host interface {
	// Construct constructs a new resource using the provided [comProvider.ConstructFunc].
	Construct(context.Context, ConstructRequest, comProvider.ConstructFunc) (ConstructResponse, error)

	// Call calls a method using the provided [comProvider.CallFunc].
	Call(context.Context, CallRequest, comProvider.CallFunc) (CallResponse, error)
}

func GetHost

func GetHost(ctx context.Context) Host

GetHost retrieves the provider's Host from the context.

type InitializationFailed

type InitializationFailed struct {
	// Reasons why the resource did not fully initialize.
	Reasons []string
}

InitializationFailed indicates that a resource exists but failed to initialize, and is thus in a partial state.

type InvokeRequest

type InvokeRequest struct {
	Token tokens.Type  // the function token to invoke.
	Args  property.Map // the arguments for the function invocation.
}

type InvokeResponse

type InvokeResponse struct {
	Return   property.Map   // the returned values, if invoke was successful.
	Failures []CheckFailure // the failures if any arguments didn't pass verification.
}

type Logger

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

Logger provides methods for user visible logging.

Log info will be associated with the URN passed if any.

func GetLogger

func GetLogger(ctx context.Context) Logger

func (Logger) Debug

func (l Logger) Debug(msg string)

Debug logs a debug message visible to the user.

func (Logger) DebugStatus

func (l Logger) DebugStatus(msg string)

DebugStatus logs a debug message visible to the user.

The message will only be displayed while it is the latest message.

func (Logger) DebugStatusf

func (l Logger) DebugStatusf(msg string, a ...any)

DebugStatusf logs a debug message visible to the user, formatting it with fmt.Sprintf.

The message will only be displayed while it is the latest message.

func (Logger) Debugf

func (l Logger) Debugf(msg string, a ...any)

Debugf logs a debug message visible to the user, formatting it with fmt.Sprintf.

func (Logger) Error

func (l Logger) Error(msg string)

func (Logger) ErrorStatus

func (l Logger) ErrorStatus(msg string)

func (Logger) ErrorStatusf

func (l Logger) ErrorStatusf(msg string, a ...any)

func (Logger) Errorf

func (l Logger) Errorf(msg string, a ...any)

func (Logger) Info

func (l Logger) Info(msg string)

func (Logger) InfoStatus

func (l Logger) InfoStatus(msg string)

func (Logger) InfoStatusf

func (l Logger) InfoStatusf(msg string, a ...any)

func (Logger) Infof

func (l Logger) Infof(msg string, a ...any)

func (Logger) Warning

func (l Logger) Warning(msg string)

func (Logger) WarningStatus

func (l Logger) WarningStatus(msg string)

func (Logger) WarningStatusf

func (l Logger) WarningStatusf(msg string, a ...any)

func (Logger) Warningf

func (l Logger) Warningf(msg string, a ...any)

type ParameterizeRequest

type ParameterizeRequest struct {
	// Args indicates that the provider has been configured from the CLI.
	Args *ParameterizeRequestArgs
	// Value re-parameterizes an existing provider.
	Value *ParameterizeRequestValue
}

ParameterizeRequest configures the provider as parameterized.

Parameterize can be called in 2 configurations: with Args non-nil or with Value non-nil. Exactly one of Args or Value will be non-nil. Parameterize should leave the provider in the same state regardless of which variant was used.

type ParameterizeRequestArgs

type ParameterizeRequestArgs struct {
	// Args is the un-processed CLI args for the parameterization.
	//
	// For example:
	//
	//	pulumi package add my-provider arg1 arg2
	//	                               ^^^^ ^^^^
	//
	// Then ParameterizeRequestArgs{Args:[]string{"arg1", "arg2"}} will be sent.
	Args []string
}

type ParameterizeRequestValue

type ParameterizeRequestValue struct {
	Name    string
	Version semver.Version
	Value   []byte
}

ParameterizeRequestValue represents a re-parameterization from an already generated parameterized SDK.

Name and Version will match what was in the ParameterizeResponse that generated the SDK. Value will match what was in the schema returned during SDK generation.

type ParameterizeResponse

type ParameterizeResponse struct {
	Name    string
	Version semver.Version
}

type PropertyDiff

type PropertyDiff struct {
	Kind      DiffKind // The kind of diff asdsociated with this property.
	InputDiff bool     // The difference is between old and new inputs, not old and new state.
}

type Provider

type Provider struct {

	// GetSchema fetches the schema for this resource provider.
	GetSchema func(context.Context, GetSchemaRequest) (GetSchemaResponse, error)

	// Parameterize sets up the provider as a replacement parameterized provider.
	//
	// If a SDK was generated with parameters, then Parameterize should be called once before
	// [Provider.CheckConfig], [Provider.DiffConfig] or [Provider.Configure].
	//
	// Parameterize can be called in 2 configurations: with [ParameterizeRequest.Args] specified or with
	// [ParameterizeRequest.Value] specified. Parameterize should leave the provider in the same state
	// regardless of which variant was used.
	//
	// For more through documentation on Parameterize, see
	// https://pulumi-developer-docs.readthedocs.io/latest/docs/architecture/providers.html#parameterized-providers.
	Parameterize func(context.Context, ParameterizeRequest) (ParameterizeResponse, error)

	// Cancel signals the provider to gracefully shut down and abort any ongoing resource operations.
	// Operations aborted in this way will return an error (e.g., `Update` and `Create` will either return a
	// creation error or an initialization error). Since Cancel is advisory and non-blocking, it is up
	// to the host to decide how long to wait after Cancel is called before (e.g.)
	// hard-closing any gRPC connection.
	Cancel func(context.Context) error

	// Provider Config
	CheckConfig func(context.Context, CheckRequest) (CheckResponse, error)
	DiffConfig  func(context.Context, DiffRequest) (DiffResponse, error)
	// NOTE: We opt into all options.
	Configure func(context.Context, ConfigureRequest) error

	// Invokes
	Invoke func(context.Context, InvokeRequest) (InvokeResponse, error)

	// Check validates that the given property bag is valid for a resource of the given type and returns the inputs
	// that should be passed to successive calls to Diff, Create, or Update for this resource. As a rule, the provider
	// inputs returned by a call to Check should preserve the original representation of the properties as present in
	// the program inputs. Though this rule is not required for correctness, violations thereof can negatively impact
	// the end-user experience, as the provider inputs are using for detecting and rendering diffs.
	Check  func(context.Context, CheckRequest) (CheckResponse, error)
	Diff   func(context.Context, DiffRequest) (DiffResponse, error)
	Create func(context.Context, CreateRequest) (CreateResponse, error)
	Read   func(context.Context, ReadRequest) (ReadResponse, error)
	Update func(context.Context, UpdateRequest) (UpdateResponse, error)
	Delete func(context.Context, DeleteRequest) error

	// Call allows methods to be attached to resources.
	//
	// Right now, Call is restricted to methods on component resources.[^1][^2]
	//
	// [^1]: On the provider resource: https://github.com/pulumi/pulumi/issues/17025
	// [^2]: On custom resources: https://github.com/pulumi/pulumi/issues/16257
	Call func(context.Context, CallRequest) (CallResponse, error)

	// Components Resources
	Construct func(context.Context, ConstructRequest) (ConstructResponse, error)
}

func (Provider) Run

func (d Provider) Run(ctx context.Context, name string, version string) error

Run starts the provider.

func (Provider) WithDefaults

func (d Provider) WithDefaults() Provider

WithDefaults returns a provider with sensible defaults. It does not mutate its receiver.

Most default values return a NotYetImplemented error, which the engine knows to ignore. Other defaults are no-op functions.

You should not need to call this function manually. It will be automatically invoked before a provider is run.

type ProviderReference

type ProviderReference struct {
	Urn presource.URN
	ID  presource.ID
}

ProviderReference is a (URN, ID) tuple that refers to a particular provider instance.

type ReadRequest

type ReadRequest struct {
	ID         string        // the ID of the resource to read.
	Urn        presource.URN // the Pulumi URN for this resource.
	Properties property.Map  // the current state (sufficiently complete to identify the resource).
	Inputs     property.Map  // the current inputs, if any (only populated during refresh).
}

type ReadResponse

type ReadResponse struct {
	ID         string       // the ID of the resource read back (or empty if missing).
	Properties property.Map // the state of the resource read from the live environment.
	Inputs     property.Map // the inputs for this resource that would be returned from Check.

	// non-nil to indicate that the read failed and left the resource in a partial
	// state.
	//
	// If PartialState is non-nil, then an error will be returned, annotated with
	// [pulumirpc.ErrorResourceInitFailed].
	PartialState *InitializationFailed
}

type RunInfo

type RunInfo struct {
	PackageName string
	Version     string
}

func GetRunInfo

func GetRunInfo(ctx context.Context) RunInfo

type UpdateRequest

type UpdateRequest struct {
	ID            string        // the ID of the resource to update.
	Urn           presource.URN // the Pulumi URN for this resource.
	State         property.Map  // the old state of the resource to update.
	Inputs        property.Map  // the new values of provider inputs for the resource to update.
	Timeout       float64       // the update request timeout represented in seconds.
	IgnoreChanges []string      // a set of property paths that should be treated as unchanged.
	DryRun        bool          // true if the provider should not actually create the resource.
}

type UpdateResponse

type UpdateResponse struct {
	// any properties that were computed during updating.
	Properties property.Map
	// non-nil to indicate that the update failed and left the resource in a partial
	// state.
	//
	// If PartialState is non-nil, then an error will be returned, annotated with
	// [pulumirpc.ErrorResourceInitFailed].
	PartialState *InitializationFailed
}

Directories

Path Synopsis
Package ende - ENcoding and DEcoding resource.Property* values
Package ende - ENcoding and DEcoding resource.Property* values
Package infer is a framework to define Pulumi resources and functions derived from go types.
Package infer is a framework to define Pulumi resources and functions derived from go types.
tests
Package tests is a generated GoMock package.
Package tests is a generated GoMock package.
types
Package types provides ancillary types for use with github.com/sapslaj/mid/pkg/providerfw/infer.
Package types provides ancillary types for use with github.com/sapslaj/mid/pkg/providerfw/infer.
Package integration is a test library for validating in-memory providers behave correctly.
Package integration is a test library for validating in-memory providers behave correctly.
fake
Package fake implements a fake pulumirpc.EngineServer and pulumirpc.ResourceMonitorServer for integration test purposes.
Package fake implements a fake pulumirpc.EngineServer and pulumirpc.ResourceMonitorServer for integration test purposes.
Package introspect has shared utilities for reflecting.
Package introspect has shared utilities for reflecting.
Package key provides an internal set of keys for use with context.WithValue and context.Context.Value that can be shared across packages source.
Package key provides an internal set of keys for use with context.WithValue and context.Context.Value that can be shared across packages source.
Package middleware defines common interfaces multiple middleware components use.
Package middleware defines common interfaces multiple middleware components use.
cancel
Package cancel provides a middle-ware that ties the Cancel gRPC call from Pulumi to Go's context.Context cancellation system.
Package cancel provides a middle-ware that ties the Cancel gRPC call from Pulumi to Go's context.Context cancellation system.
cancel/evict
Package evict is a helper package for github.com/sapslaj/mid/pkg/providerfw/middleware/cancel.
Package evict is a helper package for github.com/sapslaj/mid/pkg/providerfw/middleware/cancel.
complexconfig
Package complexconfig adds middleware for schema informed complex configuration encoding/decoding as a work-around for https://github.com/pulumi/pulumi/pull/15032.
Package complexconfig adds middleware for schema informed complex configuration encoding/decoding as a work-around for https://github.com/pulumi/pulumi/pull/15032.
context
Package context allows systemic wrapping of provider.Context before invoking a subsidiary provider.
Package context allows systemic wrapping of provider.Context before invoking a subsidiary provider.
dispatch
Package dispatch provides a provider that dispatches calls by URN such as `Create` to resource level invocations.
Package dispatch provides a provider that dispatches calls by URN such as `Create` to resource level invocations.
rpc
Package rpc allows projecting a rpc.ResourceProviderServer into a p.Provider.
Package rpc allows projecting a rpc.ResourceProviderServer into a p.Provider.
schema
Package schema provides a middleware to respond to GetSchema.
Package schema provides a middleware to respond to GetSchema.
Package putil contains utility functions for working with [resource.PropertyValue]s and related types.
Package putil contains utility functions for working with [resource.PropertyValue]s and related types.
rapid
reflect
Package reflect provides [rapid.Generator]s for reflect types.
Package reflect provides [rapid.Generator]s for reflect types.
resource
Package resource provides [rapid.Generator]s for [resource.PropertyValue]s.
Package resource provides [rapid.Generator]s for [resource.PropertyValue]s.
Package rpc provides utilities for marshaling and unmarshaling of resource properties.
Package rpc provides utilities for marshaling and unmarshaling of resource properties.

Jump to

Keyboard shortcuts

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