plugin

package
v3.0.0-...-a5432f4 Latest Latest
Warning

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

Go to latest
Published: Jan 13, 2025 License: Apache-2.0 Imports: 52 Imported by: 29

Documentation

Index

Constants

View Source
const (
	// Propose: The provider may use the proposed name as a suggestion but is free to modify it.
	AutonamingModePropose AutonamingMode = iota
	// Enforce: The provider must use exactly the proposed name or return an error.
	AutonamingModeEnforce = 1
	// Disabled: The provider should disable automatic naming and return an error if no explicit name is provided
	// by user's program.
	AutonamingModeDisabled = 2
)
View Source
const (
	// UnknownBoolValue is a sentinel indicating that a bool property's value is not known, because it depends on
	// a computation with values whose values themselves are not yet known (e.g., dependent upon an output property).
	UnknownBoolValue = "1c4a061d-8072-4f0a-a4cb-0ff528b18fe7"
	// UnknownNumberValue is a sentinel indicating that a number property's value is not known, because it depends on
	// a computation with values whose values themselves are not yet known (e.g., dependent upon an output property).
	UnknownNumberValue = "3eeb2bf0-c639-47a8-9e75-3b44932eb421"
	// UnknownStringValue is a sentinel indicating that a string property's value is not known, because it depends on
	// a computation with values whose values themselves are not yet known (e.g., dependent upon an output property).
	UnknownStringValue = "04da6b54-80e4-46f7-96ec-b56ff0331ba9"
	// UnknownArrayValue is a sentinel indicating that an array property's value is not known, because it depends on
	// a computation with values whose values themselves are not yet known (e.g., dependent upon an output property).
	UnknownArrayValue = "6a19a0b0-7e62-4c92-b797-7f8e31da9cc2"
	// UnknownAssetValue is a sentinel indicating that an asset property's value is not known, because it depends on
	// a computation with values whose values themselves are not yet known (e.g., dependent upon an output property).
	UnknownAssetValue = "030794c1-ac77-496b-92df-f27374a8bd58"
	// UnknownArchiveValue is a sentinel indicating that an archive property's value is not known, because it depends
	// on a computation with values whose values themselves are not yet known (e.g., dependent upon an output property).
	UnknownArchiveValue = "e48ece36-62e2-4504-bad9-02848725956a"
	// UnknownObjectValue is a sentinel indicating that an archive property's value is not known, because it depends
	// on a computation with values whose values themselves are not yet known (e.g., dependent upon an output property).
	UnknownObjectValue = "dd056dcd-154b-4c76-9bd3-c8f88648b5ff"
)

Variables

View Source
var ErrNotYetImplemented = errors.New("NYI")

ErrNotYetImplemented may be returned from a provider for optional methods that are not yet implemented.

Functions

func GetLanguageAttachPort

func GetLanguageAttachPort(runtime string) (*int, error)

Checks CODEINFRA_DEBUG_LANGUAGES environment variable for any overrides for the language identified by name. If the user has requested to attach to a live language plugin, returns the port number from the env var.

For example, `CODEINFRA_DEBUG_LANGUAGES=go:12345,dotnet:678` will result in 12345 for go and 678 for dotnet.

func GetProviderAttachPort

func GetProviderAttachPort(pkg tokens.Package) (*int, error)

Checks CODEINFRA_DEBUG_PROVIDERS environment variable for any overrides for the provider identified by pkg. If the user has requested to attach to a live provider, returns the port number from the env var. For example, `CODEINFRA_DEBUG_PROVIDERS=aws:12345,gcp:678` will result in 12345 for aws.

func HclDiagnosticToRPCDiagnostic

func HclDiagnosticToRPCDiagnostic(diag *hcl.Diagnostic) *codegenrpc.Diagnostic

func HclDiagnosticsToRPCDiagnostics

func HclDiagnosticsToRPCDiagnostics(diags []*hcl.Diagnostic) []*codegenrpc.Diagnostic

func MakeExecutablePromptChoices

func MakeExecutablePromptChoices(executables ...string) []*codeinfrarpc.RuntimeOptionPrompt_RuntimeOptionValue

MakeRuntimeOptionPromptChoices creates a list of runtime option values from a list of executable names. If an executable is not found, it will be listed with a `[not found]` suffix at the end of the list.

func MarshalArchive

func MarshalArchive(v *archive.Archive, opts MarshalOptions) (*structpb.Value, error)

MarshalArchive marshals an archive into its wire form for resource provider plugins.

func MarshalAsset

func MarshalAsset(v *asset.Asset, opts MarshalOptions) (*structpb.Value, error)

MarshalAsset marshals an asset into its wire form for resource provider plugins.

func MarshalNull

func MarshalNull(opts MarshalOptions) *structpb.Value

MarshalNull marshals a nil to its protobuf form.

func MarshalProperties

func MarshalProperties(props resource.PropertyMap, opts MarshalOptions) (*structpb.Struct, error)

MarshalProperties marshals a resource's property map as a "JSON-like" protobuf structure.

func MarshalPropertyValue

func MarshalPropertyValue(key resource.PropertyKey, v resource.PropertyValue,
	opts MarshalOptions,
) (*structpb.Value, error)

MarshalPropertyValue marshals a single resource property value into its "JSON-like" value representation.

func MarshalString

func MarshalString(s string, opts MarshalOptions) *structpb.Value

MarshalString marshals a string to its protobuf form.

func MarshalStruct

func MarshalStruct(obj *structpb.Struct, opts MarshalOptions) *structpb.Value

MarshalStruct marshals a struct for use in a protobuf field where a value is expected.

func NewCheckResponse

func NewCheckResponse(err error) *codeinfrarpc.CheckResponse

NewCheckResponse produces a response with property validation failures from the given array of mapper failures.

func NewConverterServer

func NewConverterServer(converter Converter) codeinfrarpc.ConverterServer

func NewDetailedDiffFromObjectDiff

func NewDetailedDiffFromObjectDiff(diff *resource.ObjectDiff, inputDiff bool) map[string]PropertyDiff

NewDetailedDiffFromObjectDiff computes the detailed diff of Updated, Added and Deleted keys.

func NewProviderServer

func NewProviderServer(provider Provider) codeinfrarpc.ResourceProviderServer

func RPCDiagnosticToHclDiagnostic

func RPCDiagnosticToHclDiagnostic(diag *codegenrpc.Diagnostic) *hcl.Diagnostic

func UnmarshalProperties

func UnmarshalProperties(props *structpb.Struct, opts MarshalOptions) (resource.PropertyMap, error)

UnmarshalProperties unmarshals a "JSON-like" protobuf structure into a new resource property map.

func UnmarshalPropertyValue

func UnmarshalPropertyValue(key resource.PropertyKey, v *structpb.Value,
	opts MarshalOptions,
) (*resource.PropertyValue, error)

UnmarshalPropertyValue unmarshals a single "JSON-like" value into a new property value.

Types

type AboutInfo

type AboutInfo struct {
	Executable string
	Version    string
	Metadata   map[string]string
}

type AnalyzeDiagnostic

type AnalyzeDiagnostic struct {
	PolicyName        string
	PolicyPackName    string
	PolicyPackVersion string
	Description       string
	Message           string
	Tags              []string
	EnforcementLevel  apitype.EnforcementLevel
	URN               resource.URN
}

AnalyzeDiagnostic indicates that resource analysis failed; it contains the property and reason for the failure.

type Analyzer

type Analyzer interface {
	// Closer closes any underlying OS resources associated with this provider (like processes, RPC channels, etc).
	io.Closer
	// Name fetches an analyzer's qualified name.
	Name() tokens.QName
	// Analyze analyzes a single resource object, and returns any errors that it finds.
	// Is called before the resource is modified.
	Analyze(r AnalyzerResource) ([]AnalyzeDiagnostic, error)
	// AnalyzeStack analyzes all resources after a successful preview or update.
	// Is called after all resources have been processed, and all changes applied.
	AnalyzeStack(resources []AnalyzerStackResource) ([]AnalyzeDiagnostic, error)
	// Remediate is given the opportunity to optionally transform a single resource's properties.
	Remediate(r AnalyzerResource) ([]Remediation, error)
	// GetAnalyzerInfo returns metadata about the analyzer (e.g., list of policies contained).
	GetAnalyzerInfo() (AnalyzerInfo, error)
	// GetPluginInfo returns this plugin's information.
	GetPluginInfo() (workspace.PluginInfo, error)
	// Configure configures the analyzer, passing configuration properties for each policy.
	Configure(policyConfig map[string]AnalyzerPolicyConfig) error
}

Analyzer provides a pluggable interface for performing arbitrary analysis of entire projects/stacks/snapshots, and/or individual resources, for arbitrary issues. These might be style, policy, correctness, security, or performance related. This interface hides the messiness of the underlying machinery, since providers are behind an RPC boundary.

func NewAnalyzer

func NewAnalyzer(host Host, ctx *Context, name tokens.QName) (Analyzer, error)

NewAnalyzer binds to a given analyzer's plugin by name and creates a gRPC connection to it. If the associated plugin could not be found by name on the PATH, or an error occurs while creating the child process, an error is returned.

func NewPolicyAnalyzer

func NewPolicyAnalyzer(
	host Host, ctx *Context, name tokens.QName, policyPackPath string, opts *PolicyAnalyzerOptions,
) (Analyzer, error)

NewPolicyAnalyzer boots the nodejs analyzer plugin located at `policyPackpath`

type AnalyzerInfo

type AnalyzerInfo struct {
	Name           string
	DisplayName    string
	Version        string
	SupportsConfig bool
	Policies       []AnalyzerPolicyInfo
	InitialConfig  map[string]AnalyzerPolicyConfig
}

AnalyzerInfo provides metadata about a PolicyPack inside an analyzer.

type AnalyzerPolicyConfig

type AnalyzerPolicyConfig struct {
	// Configured enforcement level for the policy.
	EnforcementLevel apitype.EnforcementLevel
	// Configured properties of the policy.
	Properties map[string]interface{}
}

AnalyzerPolicyConfig is the configuration for a policy.

type AnalyzerPolicyConfigSchema

type AnalyzerPolicyConfigSchema struct {
	// Map of config property names to JSON schema.
	Properties map[string]JSONSchema

	// Required config properties
	Required []string
}

AnalyzerPolicyConfigSchema provides metadata about a policy's configuration.

type AnalyzerPolicyInfo

type AnalyzerPolicyInfo struct {
	// Unique URL-safe name for the policy.  This is unique to a specific version
	// of a Policy Pack.
	Name        string
	DisplayName string

	// Description is used to provide more context about the purpose of the policy.
	Description      string
	EnforcementLevel apitype.EnforcementLevel

	// Message is the message that will be displayed to end users when they violate
	// this policy.
	Message string

	// ConfigSchema is optional config schema for the policy.
	ConfigSchema *AnalyzerPolicyConfigSchema
}

AnalyzerPolicyInfo defines the metadata for an individual Policy within a Policy Pack.

type AnalyzerProviderResource

type AnalyzerProviderResource struct {
	URN        resource.URN
	Type       tokens.Type
	Name       string
	Properties resource.PropertyMap
}

AnalyzerProviderResource mirrors a resource's provider sent to the analyzer.

type AnalyzerResource

type AnalyzerResource struct {
	URN        resource.URN
	Type       tokens.Type
	Name       string
	Properties resource.PropertyMap
	Options    AnalyzerResourceOptions
	Provider   *AnalyzerProviderResource
}

AnalyzerResource mirrors a resource that is passed to `Analyze`.

type AnalyzerResourceOptions

type AnalyzerResourceOptions struct {
	Protect                 bool                    // true to protect this resource from deletion.
	IgnoreChanges           []string                // a list of property names to ignore during changes.
	DeleteBeforeReplace     *bool                   // true if this resource should be deleted prior to replacement.
	AdditionalSecretOutputs []resource.PropertyKey  // outputs that should always be treated as secrets.
	AliasURNs               []resource.URN          // additional URNs that should be aliased to this resource.
	Aliases                 []resource.Alias        // additional URNs that should be aliased to this resource.
	CustomTimeouts          resource.CustomTimeouts // an optional config object for resource options
}

AnalyzerResourceOptions mirrors resource options sent to the analyzer.

type AnalyzerStackResource

type AnalyzerStackResource struct {
	AnalyzerResource
	Parent               resource.URN                            // an optional parent URN for this resource.
	Dependencies         []resource.URN                          // dependencies of this resource object.
	PropertyDependencies map[resource.PropertyKey][]resource.URN // the set of dependencies that affect each property.
}

AnalyzerStackResource mirrors a resource that is passed to `AnalyzeStack`.

type AutonamingMode

type AutonamingMode int32

The mode that controls how the provider handles the proposed name. If not specified, defaults to `Propose`.

type AutonamingOptions

type AutonamingOptions struct {
	// ProposedName is the name that the provider should use for the resource.
	ProposedName string
	// Mode is the mode that controls how the provider handles the proposed name.
	Mode AutonamingMode
	// WarnIfNoSupport indicates whether the provider plugin should log a warning if the provider does not support
	// autonaming configuration.
	WarnIfNoSupport bool
}

Configuration for automatic resource naming behavior. This structure contains fields that control how the provider handles resource names, including proposed names and naming modes.

type CallInfo

type CallInfo struct {
	Project        string                // the project name housing the program being run.
	Stack          string                // the stack name being evaluated.
	Config         map[config.Key]string // the configuration variables to apply before running.
	DryRun         bool                  // true if we are performing a dry-run (preview).
	Parallel       int32                 // the degree of parallelism for resource operations (<=1 for serial).
	MonitorAddress string                // the RPC address to the host resource monitor.
}

CallInfo contains all of the information required to register resources as part of a call to Construct.

type CallOptions

type CallOptions struct {
	// ArgDependencies is a map from argument keys to a list of resources that the argument depends on.
	ArgDependencies map[resource.PropertyKey][]resource.URN
}

CallOptions captures options for a call to Call.

type CallRequest

type CallRequest struct {
	Tok     tokens.ModuleMember
	Args    resource.PropertyMap
	Info    CallInfo
	Options CallOptions
}

type CallResponse

type CallResponse = CallResult

type CallResult

type CallResult struct {
	// The returned values, if the call was successful.
	Return resource.PropertyMap
	// A map from return value keys to the dependencies of the return value.
	ReturnDependencies map[resource.PropertyKey][]resource.URN
	// The failures if any arguments didn't pass verification.
	Failures []CheckFailure
}

CallResult is the result of a call to Call.

type CheckConfigRequest

type CheckConfigRequest struct {
	URN           resource.URN
	Name          string
	Type          tokens.Type
	Olds, News    resource.PropertyMap
	AllowUnknowns bool
}

type CheckConfigResponse

type CheckConfigResponse struct {
	Properties resource.PropertyMap
	Failures   []CheckFailure
}

type CheckFailure

type CheckFailure struct {
	Property resource.PropertyKey // the property that failed checking.
	Reason   string               // the reason the property failed to check.
}

CheckFailure indicates that a call to check failed; it contains the property and reason for the failure.

type CheckRequest

type CheckRequest struct {
	URN  resource.URN
	Name string
	Type tokens.Type
	// TODO Change to (State, Input)
	Olds, News    resource.PropertyMap
	AllowUnknowns bool
	RandomSeed    []byte
	Autonaming    *AutonamingOptions
}

type CheckResponse

type CheckResponse struct {
	Properties resource.PropertyMap
	Failures   []CheckFailure
}

type CodeinfraParameterizationJSON

type CodeinfraParameterizationJSON struct {
	// The name of the parameterized package.
	Name string `json:"name"`
	// The version of the parameterized package.
	Version string `json:"version"`
	// The parameter value of the parameterized package.
	Value []byte `json:"value"`
}

type CodeinfraPluginJSON

type CodeinfraPluginJSON struct {
	// Indicates whether the package has an associated resource plugin. Set to false to indicate no plugin.
	Resource bool `json:"resource"`
	// Optional plugin name. If not set, the plugin name is derived from the package name.
	Name string `json:"name,omitempty"`
	// Optional plugin version. If not set, the version is derived from the package version (if possible).
	Version string `json:"version,omitempty"`
	// Optional plugin server. If not set, the default server is used when installing the plugin.
	Server string `json:"server,omitempty"`
	// Parameterization information for the package.
	Parameterization *CodeinfraParameterizationJSON `json:"parameterization,omitempty"`
}

CodeinfraPluginJSON represents additional information about a package's associated Codeinfra plugin. For Python, the content is inside a codeinfra-plugin.json file inside the package. For Node.js, the content is within the package.json file, under the "codeinfra" node. For .NET, the content is inside a codeinfra-plugin.json file inside the NuGet package. For Go, the content is inside a codeinfra-plugin.json file inside the module.

func LoadCodeinfraPluginJSON

func LoadCodeinfraPluginJSON(path string) (*CodeinfraPluginJSON, error)

func (*CodeinfraPluginJSON) JSON

func (plugin *CodeinfraPluginJSON) JSON() ([]byte, error)

type ConfigSource

type ConfigSource interface {
	// GetPackageConfig returns the set of configuration parameters for the indicated package, if any.
	GetPackageConfig(pkg tokens.Package) (resource.PropertyMap, error)
}

ConfigSource is an interface that allows a plugin context to fetch configuration data for a plugin named by package.

type ConfigureRequest

type ConfigureRequest struct {
	Inputs resource.PropertyMap
}

type ConfigureResponse

type ConfigureResponse struct{}

type ConstructInfo

type ConstructInfo struct {
	Project          string                // the project name housing the program being run.
	Stack            string                // the stack name being evaluated.
	Config           map[config.Key]string // the configuration variables to apply before running.
	ConfigSecretKeys []config.Key          // the configuration keys that have secret values.
	DryRun           bool                  // true if we are performing a dry-run (preview).
	Parallel         int32                 // the degree of parallelism for resource operations (<=1 for serial).
	MonitorAddress   string                // the RPC address to the host resource monitor.
}

ConstructInfo contains all of the information required to register resources as part of a call to Construct.

type ConstructOptions

type ConstructOptions struct {
	// Aliases is the set of aliases for the component.
	Aliases []resource.Alias

	// Dependencies is the list of resources this component depends on.
	Dependencies []resource.URN

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

	// Providers is a map from package name to provider reference.
	Providers map[string]string

	// PropertyDependencies is a map from property name to a list of resources that property depends on.
	PropertyDependencies map[resource.PropertyKey][]resource.URN

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

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

	// DeletedWith specifies that if the given resource is deleted,
	// it will also delete this resource.
	DeletedWith resource.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
}

ConstructOptions captures options for a call to Construct.

type ConstructRequest

type ConstructRequest struct {
	Info    ConstructInfo
	Type    tokens.Type
	Name    string
	Parent  resource.URN
	Inputs  resource.PropertyMap
	Options ConstructOptions
}

type ConstructResponse

type ConstructResponse = ConstructResult

type ConstructResult

type ConstructResult struct {
	// The URN of the constructed component resource.
	URN resource.URN
	// The output properties of the component resource.
	Outputs resource.PropertyMap
	// The resources that each output property depends on.
	OutputDependencies map[resource.PropertyKey][]resource.URN
}

ConstructResult is the result of a call to Construct.

type Context

type Context struct {
	Diag       diag.Sink // the diagnostics sink to use for messages.
	StatusDiag diag.Sink // the diagnostics sink to use for status messages.
	Host       Host      // the host that can be used to fetch providers.
	Pwd        string    // the working directory to spawn all plugins in.
	Root       string    // the root directory of the context.

	// If non-nil, configures custom gRPC client options. Receives pluginInfo which is a JSON-serializable bit of
	// metadata describing the plugin.
	DialOptions func(pluginInfo interface{}) []grpc.DialOption

	DebugTraceMutex *sync.Mutex // used internally to syncronize debug tracing
	// contains filtered or unexported fields
}

Context is used to group related operations together so that associated OS resources can be cached, shared, and reclaimed as appropriate. It also carries shared plugin configuration.

func NewContext

func NewContext(d, statusD diag.Sink, host Host, _ ConfigSource,
	pwd string, runtimeOptions map[string]interface{}, disableProviderPreview bool,
	parentSpan opentracing.Span,
) (*Context, error)

NewContext allocates a new context with a given sink and host. Note that the host is "owned" by this context from here forwards, such that when the context's resources are reclaimed, so too are the host's.

func NewContextWithContext

func NewContextWithContext(
	ctx context.Context,
	d, statusD diag.Sink, host Host,
	pwd, root string, runtimeOptions map[string]interface{}, disableProviderPreview bool,
	parentSpan opentracing.Span, plugins *workspace.Plugins, config map[config.Key]string,
	debugging DebugEventEmitter,
) (*Context, error)

NewContextWithContext is a variation of NewContextWithRoot that also sets the base context.

func NewContextWithRoot

func NewContextWithRoot(d, statusD diag.Sink, host Host,
	pwd, root string, runtimeOptions map[string]interface{}, disableProviderPreview bool,
	parentSpan opentracing.Span, plugins *workspace.Plugins, config map[config.Key]string,
	debugging DebugEventEmitter,
) (*Context, error)

NewContextWithRoot is a variation of NewContext that also sets known project Root. Additionally accepts Plugins

func (*Context) Base

func (ctx *Context) Base() context.Context

Base returns this plugin context's base context; this is useful for things like cancellation.

func (*Context) Close

func (ctx *Context) Close() error

Close reclaims all resources associated with this context.

func (*Context) Request

func (ctx *Context) Request() context.Context

Request allocates a request sub-context.

func (*Context) WithCancelChannel

func (ctx *Context) WithCancelChannel(c <-chan struct{}) *Context

WithCancelChannel registers a close channel which will close the returned Context when the channel is closed.

WARNING: Calling this function without ever closing `c` will leak go routines.

type ConvertProgramRequest

type ConvertProgramRequest struct {
	SourceDirectory string
	TargetDirectory string
	MapperTarget    string
	LoaderTarget    string
	Args            []string
}

type ConvertProgramResponse

type ConvertProgramResponse struct {
	Diagnostics hcl.Diagnostics
}

type ConvertStateRequest

type ConvertStateRequest struct {
	MapperTarget string
	Args         []string
}

type ConvertStateResponse

type ConvertStateResponse struct {
	Resources   []ResourceImport
	Diagnostics hcl.Diagnostics
}

type Converter

type Converter interface {
	io.Closer

	ConvertState(ctx context.Context, req *ConvertStateRequest) (*ConvertStateResponse, error)

	ConvertProgram(ctx context.Context, req *ConvertProgramRequest) (*ConvertProgramResponse, error)
}

func NewConverter

func NewConverter(ctx *Context, name string, version *semver.Version) (Converter, error)

type CreateRequest

type CreateRequest struct {
	URN        resource.URN
	Name       string
	Type       tokens.Type
	Properties resource.PropertyMap
	Timeout    float64
	Preview    bool
}

type CreateResponse

type CreateResponse struct {
	ID         resource.ID
	Properties resource.PropertyMap
	Status     resource.Status
}

type CustomTimeouts

type CustomTimeouts struct {
	Create string
	Update string
	Delete string
}

CustomTimeouts overrides default timeouts for resource operations. Timeout values are strings in the format accepted by time.ParseDuration.

type DebugEventEmitter

type DebugEventEmitter interface {
	// StartDebugging asks the host to start a debug session for the given configuration.
	StartDebugging(info DebuggingInfo) error
}

type DebuggingInfo

type DebuggingInfo struct {
	// Config is the debug configuration (language-specific, see Debug Adapter Protocol)
	Config map[string]interface{}
}

type DeleteRequest

type DeleteRequest struct {
	URN             resource.URN
	Name            string
	Type            tokens.Type
	ID              resource.ID
	Inputs, Outputs resource.PropertyMap
	Timeout         float64
}

type DeleteResponse

type DeleteResponse struct {
	Status resource.Status
}

type DependencyInfo

type DependencyInfo struct {
	// The name of the dependency.
	Name string
	// The version of the dependency. Unlike most versions in the system this is not guaranteed to be a semantic
	// version.
	Version string
}

DependencyInfo contains information about a dependency reported by a language runtime. These are the languages dependencies, they are not necessarily Codeinfra packages.

type DiffChanges

type DiffChanges int

DiffChanges represents the kind of changes detected by a diff operation.

const (
	// DiffUnknown indicates the provider didn't offer information about the changes (legacy behavior).
	DiffUnknown DiffChanges = 0
	// DiffNone indicates the provider performed a diff and concluded that no update is needed.
	DiffNone DiffChanges = 1
	// DiffSome indicates the provider performed a diff and concluded that an update or replacement is needed.
	DiffSome DiffChanges = 2
)

type DiffConfigRequest

type DiffConfigRequest struct {
	URN                              resource.URN
	Name                             string
	Type                             tokens.Type
	OldInputs, OldOutputs, NewInputs resource.PropertyMap
	AllowUnknowns                    bool
	IgnoreChanges                    []string
}

type DiffConfigResponse

type DiffConfigResponse = DiffResult

type DiffKind

type DiffKind int

DiffKind represents the kind of diff that applies to a particular property.

const (
	// DiffAdd indicates that the property was added.
	DiffAdd DiffKind = 0
	// DiffAddReplace indicates that the property was added and requires that the resource be replaced.
	DiffAddReplace DiffKind = 1
	// DiffDelete indicates that the property was deleted.
	DiffDelete DiffKind = 2
	// DiffDeleteReplace indicates that the property was added and requires that the resource be replaced.
	DiffDeleteReplace DiffKind = 3
	// DiffUpdate indicates that the property was updated.
	DiffUpdate DiffKind = 4
	// DiffUpdateReplace indicates that the property was updated and requires that the resource be replaced.
	DiffUpdateReplace DiffKind = 5
)

func (DiffKind) AsReplace

func (d DiffKind) AsReplace() DiffKind

AsReplace converts a DiffKind into the equivalent replacement if it not already a replacement.

func (DiffKind) Invert

func (d DiffKind) Invert() DiffKind

Invert returns the opposite diff kind to the receiver. That is:

  • Add -> Delete
  • AddReplace -> DeleteReplace
  • Delete -> Add
  • DeleteReplace -> AddReplace
  • Update -> Update
  • UpdateReplace -> UpdateReplace

func (DiffKind) IsReplace

func (d DiffKind) IsReplace() bool

func (DiffKind) String

func (d DiffKind) String() string

type DiffRequest

type DiffRequest struct {
	URN  resource.URN
	Name string
	Type tokens.Type
	ID   resource.ID
	// TODO Change to (OldInputs, OldState, NewInputs)
	OldInputs, OldOutputs, NewInputs resource.PropertyMap
	AllowUnknowns                    bool
	IgnoreChanges                    []string
}

type DiffResponse

type DiffResponse = DiffResult

type DiffResult

type DiffResult struct {
	Changes             DiffChanges             // true if this diff represents a changed resource.
	ReplaceKeys         []resource.PropertyKey  // an optional list of replacement keys.
	StableKeys          []resource.PropertyKey  // an optional list of property keys that are stable.
	ChangedKeys         []resource.PropertyKey  // an optional list of keys that changed.
	DetailedDiff        map[string]PropertyDiff // an optional structured diff
	DeleteBeforeReplace bool                    // if true, this resource must be deleted before recreating it.
}

DiffResult indicates whether an operation should replace or update an existing resource.

func (DiffResult) Invert

func (r DiffResult) Invert() DiffResult

Invert computes the inverse diff of the receiver -- the diff that would be required to "undo" this one.

func (DiffResult) Replace

func (r DiffResult) Replace() bool

Replace returns true if this diff represents a replacement.

type DiffUnavailableError

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

DiffUnavailableError may be returned by a provider if the provider is unable to diff a resource.

func DiffUnavailable

func DiffUnavailable(reason string) DiffUnavailableError

DiffUnavailable creates a new DiffUnavailableError with the given message.

func (DiffUnavailableError) Error

func (e DiffUnavailableError) Error() string

Error returns the error message for this DiffUnavailableError.

type Flags

type Flags int

Flags can be used to filter out plugins during loading that aren't necessary.

const (
	// AnalyzerPlugins is used to only load analyzers.
	AnalyzerPlugins Flags = 1 << iota
	// LanguagePlugins is used to only load language plugins.
	LanguagePlugins
	// ResourcePlugins is used to only load resource provider plugins.
	ResourcePlugins
)

type GetMappingRequest

type GetMappingRequest struct {
	Key, Provider string
}

type GetMappingResponse

type GetMappingResponse struct {
	Data     []byte
	Provider string
}

type GetMappingsRequest

type GetMappingsRequest struct {
	Key string
}

type GetMappingsResponse

type GetMappingsResponse struct {
	Keys []string
}

type GetSchemaRequest

type GetSchemaRequest struct {
	// Version is the version of the schema to return. If omitted, the latest version of the schema should be returned.
	Version int32
	// Subpackage name to get the schema for.
	SubpackageName string
	// Subpackage version to get the schema for.
	SubpackageVersion *semver.Version
}

type GetSchemaResponse

type GetSchemaResponse struct {
	Schema []byte
}

type GrpcProvider

type GrpcProvider interface {
	Provider

	// Attach triggers an attach for a currently running provider to the engine
	// TODO It would be nice if this was a HostClient rather than the string address but due to dependency
	// ordering we don't have access to declare that here.
	Attach(address string) error
}

type GrpcServer

type GrpcServer struct {
	io.Closer
	// contains filtered or unexported fields
}

GrpcServer is a standard Codeinfra style gRPC server that can be used to serve gRPC services.

func NewServer

func NewServer(ctx *Context, registrations ...func(server *grpc.Server)) (*GrpcServer, error)

NewServer creates a new GrpcServer wired up to the given services and context.

func (*GrpcServer) Addr

func (s *GrpcServer) Addr() string

func (*GrpcServer) Close

func (s *GrpcServer) Close() error

type Host

type Host interface {
	// ServerAddr returns the address at which the host's RPC interface may be found.
	ServerAddr() string

	// Log logs a message, including errors and warnings.  Messages can have a resource URN
	// associated with them.  If no urn is provided, the message is global.
	Log(sev diag.Severity, urn resource.URN, msg string, streamID int32)

	// LogStatus logs a status message message, including errors and warnings. Status messages show
	// up in the `Info` column of the progress display, but not in the final output. Messages can
	// have a resource URN associated with them.  If no urn is provided, the message is global.
	LogStatus(sev diag.Severity, urn resource.URN, msg string, streamID int32)

	// Analyzer fetches the analyzer with a given name, possibly lazily allocating the plugins for
	// it.  If an analyzer could not be found, or an error occurred while creating it, a non-nil
	// error is returned.
	Analyzer(nm tokens.QName) (Analyzer, error)

	// PolicyAnalyzer boots the nodejs analyzer plugin located at a given path. This is useful
	// because policy analyzers generally do not need to be "discovered" -- the engine is given a
	// set of policies that are required to be run during an update, so they tend to be in a
	// well-known place.
	PolicyAnalyzer(name tokens.QName, path string, opts *PolicyAnalyzerOptions) (Analyzer, error)

	// ListAnalyzers returns a list of all analyzer plugins known to the plugin host.
	ListAnalyzers() []Analyzer

	// Provider loads a new copy of the provider for a given package.  If a provider for this package could not be
	// found, or an error occurs while creating it, a non-nil error is returned.
	Provider(descriptor workspace.PackageDescriptor) (Provider, error)
	// CloseProvider closes the given provider plugin and deregisters it from this host.
	CloseProvider(provider Provider) error
	// LanguageRuntime fetches the language runtime plugin for a given language, lazily allocating if necessary.  If
	// an implementation of this language runtime wasn't found, on an error occurs, a non-nil error is returned.
	LanguageRuntime(runtime string, info ProgramInfo) (LanguageRuntime, error)

	// EnsurePlugins ensures all plugins in the given array are loaded and ready to use.  If any plugins are missing,
	// and/or there are errors loading one or more plugins, a non-nil error is returned.
	EnsurePlugins(plugins []workspace.PluginSpec, kinds Flags) error

	// ResolvePlugin resolves a plugin kind, name, and optional semver to a candidate plugin to load.
	ResolvePlugin(kind apitype.PluginKind, name string, version *semver.Version) (*workspace.PluginInfo, error)

	GetProjectPlugins() []workspace.ProjectPlugin

	// SignalCancellation asks all resource providers to gracefully shut down and abort any ongoing
	// operations. Operation aborted in this way will return an error (e.g., `Update` and `Create`
	// will either a creation error or an initialization error. SignalCancellation is advisory and
	// non-blocking; it is up to the host to decide how long to wait after SignalCancellation is
	// called before (e.g.) hard-closing any gRPC connection.
	SignalCancellation() error

	// StartDebugging asks the host to start a debugging session with the given configuration.
	StartDebugging(DebuggingInfo) error

	// Close reclaims any resources associated with the host.
	Close() error
}

A Host hosts provider plugins and makes them easily accessible by package name.

func NewDefaultHost

func NewDefaultHost(ctx *Context, runtimeOptions map[string]interface{},
	disableProviderPreview bool, plugins *workspace.Plugins, config map[config.Key]string,
	debugging DebugEventEmitter, projectName tokens.PackageName,
) (Host, error)

NewDefaultHost implements the standard plugin logic, using the standard installation root to find them.

type InitError

type InitError struct {
	Reasons []string
}

InitError represents a failure to initialize a resource, i.e., the resource has been successfully created, but it has failed to initialize.

func (*InitError) Error

func (ie *InitError) Error() string

type InstallDependenciesRequest

type InstallDependenciesRequest struct {
	Info                    ProgramInfo
	UseLanguageVersionTools bool
}

func (InstallDependenciesRequest) String

func (options InstallDependenciesRequest) String() string

type InvokeRequest

type InvokeRequest struct {
	Tok  tokens.ModuleMember
	Args resource.PropertyMap
}

type InvokeResponse

type InvokeResponse struct {
	Properties resource.PropertyMap
	Failures   []CheckFailure
}

type JSONSchema

type JSONSchema map[string]interface{}

JSONSchema represents a JSON schema.

type LanguageRuntime

type LanguageRuntime interface {
	// Closer closes any underlying OS resources associated with this plugin (like processes, RPC channels, etc).
	io.Closer
	// GetRequiredPackages computes the complete set of anticipated packages required by a program.
	GetRequiredPackages(info ProgramInfo) ([]workspace.PackageDescriptor, error)
	// Run executes a program in the language runtime for planning or deployment purposes.  If
	// info.DryRun is true, the code must not assume that side-effects or final values resulting
	// from resource deployments are actually available.  If it is false, on the other hand, a real
	// deployment is occurring and it may safely depend on these.
	//
	// Returns a triple of "error message", "bail", or real "error".  If "bail", the caller should
	// return result.Bail immediately and not print any further messages to the user.
	Run(info RunInfo) (string, bool, error)
	// GetPluginInfo returns this plugin's information.
	GetPluginInfo() (workspace.PluginInfo, error)

	// InstallDependencies will install dependencies for the project, e.g. by running `npm install` for nodejs projects.
	InstallDependencies(request InstallDependenciesRequest) error

	// RuntimeOptions returns additional options that can be set for the runtime.
	RuntimeOptionsPrompts(info ProgramInfo) ([]RuntimeOptionPrompt, error)

	// About returns information about the language runtime.
	About(info ProgramInfo) (AboutInfo, error)

	// GetProgramDependencies returns information about the dependencies for the given program.
	GetProgramDependencies(info ProgramInfo, transitiveDependencies bool) ([]DependencyInfo, error)

	// RunPlugin executes a plugin program and returns its result asynchronously.
	RunPlugin(info RunPluginInfo) (io.Reader, io.Reader, context.CancelFunc, error)

	// GenerateProject generates a program project in the given directory. This will include metadata files such
	// as Codeinfra.yaml and package.json.
	GenerateProject(sourceDirectory, targetDirectory, project string,
		strict bool, loaderTarget string, localDependencies map[string]string) (hcl.Diagnostics, error)

	// GeneratePlugin generates an SDK package.
	GeneratePackage(
		directory string, schema string, extraFiles map[string][]byte,
		loaderTarget string, localDependencies map[string]string,
		local bool,
	) (hcl.Diagnostics, error)

	// GenerateProgram is similar to GenerateProject but doesn't include any metadata files, just the program
	// source code.
	GenerateProgram(program map[string]string, loaderTarget string,
		strict bool) (map[string][]byte, hcl.Diagnostics, error)

	// Pack packs a library package into a language specific artifact in the given destination directory.
	Pack(packageDirectory string, destinationDirectory string) (string, error)
}

LanguageRuntime is a convenient interface for interacting with language runtime plugins. These tend to be dynamically loaded as plugins, although this interface hides this fact from the calling code.

func NewLanguageRuntime

func NewLanguageRuntime(host Host, ctx *Context, runtime, workingDirectory string, info ProgramInfo,
) (LanguageRuntime, error)

NewLanguageRuntime binds to a language's runtime plugin and then creates a gRPC connection to it. If the plugin could not be found, or an error occurs while creating the child process, an error is returned.

func NewLanguageRuntimeClient

func NewLanguageRuntimeClient(ctx *Context, runtime string, client codeinfrarpc.LanguageRuntimeClient) LanguageRuntime

type MarshalOptions

type MarshalOptions struct {
	Label                 string // an optional label for debugging.
	SkipNulls             bool   // true to skip nulls altogether in the resulting map.
	KeepUnknowns          bool   // true if we are keeping unknown values (otherwise we skip them).
	RejectUnknowns        bool   // true if we should return errors on unknown values. Takes precedence over KeepUnknowns.
	ElideAssetContents    bool   // true if we are eliding the contents of assets.
	ComputeAssetHashes    bool   // true if we are computing missing asset hashes on the fly.
	KeepSecrets           bool   // true if we are keeping secrets (otherwise we replace them with their underlying value).
	RejectAssets          bool   // true if we should return errors on Asset and Archive values.
	KeepResources         bool   // true if we are keeping resoures (otherwise we return raw urn).
	SkipInternalKeys      bool   // true to skip internal property keys (keys that start with "__") in the resulting map.
	KeepOutputValues      bool   // true if we are keeping output values.
	UpgradeToOutputValues bool   // true if secrets and unknowns should be upgraded to output values.
	WorkingDirectory      string // the optional working directory to use when serializing assets & archives.
}

MarshalOptions controls the marshaling of RPC structures.

type MockHost

type MockHost struct {
	ServerAddrF         func() string
	LogF                func(sev diag.Severity, urn resource.URN, msg string, streamID int32)
	LogStatusF          func(sev diag.Severity, urn resource.URN, msg string, streamID int32)
	AnalyzerF           func(nm tokens.QName) (Analyzer, error)
	PolicyAnalyzerF     func(name tokens.QName, path string, opts *PolicyAnalyzerOptions) (Analyzer, error)
	ListAnalyzersF      func() []Analyzer
	ProviderF           func(descriptor workspace.PackageDescriptor) (Provider, error)
	CloseProviderF      func(provider Provider) error
	LanguageRuntimeF    func(runtime string, info ProgramInfo) (LanguageRuntime, error)
	EnsurePluginsF      func(plugins []workspace.PluginSpec, kinds Flags) error
	ResolvePluginF      func(kind apitype.PluginKind, name string, version *semver.Version) (*workspace.PluginInfo, error)
	GetProjectPluginsF  func() []workspace.ProjectPlugin
	SignalCancellationF func() error
	CloseF              func() error
	StartDebuggingF     func(DebuggingInfo) error
}

func (*MockHost) Analyzer

func (m *MockHost) Analyzer(nm tokens.QName) (Analyzer, error)

func (*MockHost) Close

func (m *MockHost) Close() error

func (*MockHost) CloseProvider

func (m *MockHost) CloseProvider(provider Provider) error

func (*MockHost) EnsurePlugins

func (m *MockHost) EnsurePlugins(plugins []workspace.PluginSpec, kinds Flags) error

func (*MockHost) GetProjectPlugins

func (m *MockHost) GetProjectPlugins() []workspace.ProjectPlugin

func (*MockHost) LanguageRuntime

func (m *MockHost) LanguageRuntime(runtime string, info ProgramInfo) (LanguageRuntime, error)

func (*MockHost) ListAnalyzers

func (m *MockHost) ListAnalyzers() []Analyzer

func (*MockHost) Log

func (m *MockHost) Log(sev diag.Severity, urn resource.URN, msg string, streamID int32)

func (*MockHost) LogStatus

func (m *MockHost) LogStatus(sev diag.Severity, urn resource.URN, msg string, streamID int32)

func (*MockHost) PolicyAnalyzer

func (m *MockHost) PolicyAnalyzer(name tokens.QName, path string, opts *PolicyAnalyzerOptions) (Analyzer, error)

func (*MockHost) Provider

func (m *MockHost) Provider(descriptor workspace.PackageDescriptor) (Provider, error)

func (*MockHost) ResolvePlugin

func (m *MockHost) ResolvePlugin(
	kind apitype.PluginKind, name string, version *semver.Version,
) (*workspace.PluginInfo, error)

func (*MockHost) ServerAddr

func (m *MockHost) ServerAddr() string

func (*MockHost) SignalCancellation

func (m *MockHost) SignalCancellation() error

func (*MockHost) StartDebugging

func (m *MockHost) StartDebugging(info DebuggingInfo) error

type MockProvider

type MockProvider struct {
	NotForwardCompatibleProvider

	CloseF              func() error
	PkgF                func() tokens.Package
	HandshakeF          func(context.Context, ProviderHandshakeRequest) (*ProviderHandshakeResponse, error)
	ParameterizeF       func(context.Context, ParameterizeRequest) (ParameterizeResponse, error)
	GetSchemaF          func(context.Context, GetSchemaRequest) (GetSchemaResponse, error)
	CheckConfigF        func(context.Context, CheckConfigRequest) (CheckConfigResponse, error)
	DiffConfigF         func(context.Context, DiffConfigRequest) (DiffConfigResponse, error)
	ConfigureF          func(context.Context, ConfigureRequest) (ConfigureResponse, error)
	CheckF              func(context.Context, CheckRequest) (CheckResponse, error)
	DiffF               func(context.Context, DiffRequest) (DiffResponse, error)
	CreateF             func(context.Context, CreateRequest) (CreateResponse, error)
	ReadF               func(context.Context, ReadRequest) (ReadResponse, error)
	UpdateF             func(context.Context, UpdateRequest) (UpdateResponse, error)
	DeleteF             func(context.Context, DeleteRequest) (DeleteResponse, error)
	ConstructF          func(context.Context, ConstructRequest) (ConstructResponse, error)
	InvokeF             func(context.Context, InvokeRequest) (InvokeResponse, error)
	StreamInvokeF       func(context.Context, StreamInvokeRequest) (StreamInvokeResponse, error)
	CallF               func(context.Context, CallRequest) (CallResponse, error)
	GetPluginInfoF      func(context.Context) (workspace.PluginInfo, error)
	SignalCancellationF func(context.Context) error
	GetMappingF         func(context.Context, GetMappingRequest) (GetMappingResponse, error)
	GetMappingsF        func(context.Context, GetMappingsRequest) (GetMappingsResponse, error)
}

func (*MockProvider) Call

func (*MockProvider) Check

func (*MockProvider) CheckConfig

func (*MockProvider) Close

func (m *MockProvider) Close() error

func (*MockProvider) Configure

func (*MockProvider) Construct

func (*MockProvider) Create

func (*MockProvider) Delete

func (*MockProvider) Diff

func (*MockProvider) DiffConfig

func (*MockProvider) GetMapping

func (*MockProvider) GetMappings

func (*MockProvider) GetPluginInfo

func (m *MockProvider) GetPluginInfo(ctx context.Context) (workspace.PluginInfo, error)

func (*MockProvider) GetSchema

func (*MockProvider) Handshake

func (*MockProvider) Invoke

func (*MockProvider) Parameterize

func (*MockProvider) Pkg

func (m *MockProvider) Pkg() tokens.Package

func (*MockProvider) Read

func (*MockProvider) SignalCancellation

func (m *MockProvider) SignalCancellation(ctx context.Context) error

func (*MockProvider) StreamInvoke

func (*MockProvider) Update

type NotForwardCompatibleProvider

type NotForwardCompatibleProvider struct{}

NotForwardCompatible can be embedded to explicitly opt out of forward compatibility.

Either NotForwardCompatibleProvider or UnimplementedProvider must be embedded to implement Provider.

type ParameterizeArgs

type ParameterizeArgs struct {
	Args []string
}

type ParameterizeParameters

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

type ParameterizeRequest

type ParameterizeRequest struct {
	Parameters ParameterizeParameters
}

type ParameterizeResponse

type ParameterizeResponse struct {
	Name    string
	Version semver.Version
}

type ParameterizeValue

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

type PolicyAnalyzerOptions

type PolicyAnalyzerOptions struct {
	Organization string
	Project      string
	Stack        string
	Config       map[config.Key]string
	DryRun       bool
}

PolicyAnalyzerOptions includes a bag of options to pass along to a policy analyzer.

type ProgramInfo

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

ProgramInfo contains minimal information about the program to be run.

func NewProgramInfo

func NewProgramInfo(rootDirectory, programDirectory, entryPoint string, options map[string]any) ProgramInfo

func (ProgramInfo) EntryPoint

func (info ProgramInfo) EntryPoint() string

The programs main entrypoint, either a file path relative to the program directory or "." for the program directory.

func (ProgramInfo) Marshal

func (info ProgramInfo) Marshal() (*codeinfrarpc.ProgramInfo, error)

func (ProgramInfo) Options

func (info ProgramInfo) Options() map[string]any

Runtime plugin options for the program

func (ProgramInfo) ProgramDirectory

func (info ProgramInfo) ProgramDirectory() string

The programs directory, generally the same as or a subdirectory of the root directory.

func (ProgramInfo) RootDirectory

func (info ProgramInfo) RootDirectory() string

The programs root directory, i.e. where the Codeinfra.yaml file is.

func (ProgramInfo) String

func (info ProgramInfo) String() string

type PropertyDiff

type PropertyDiff struct {
	Kind      DiffKind // The kind of diff.
	InputDiff bool     // True if this is a diff between old and new inputs rather than old state and new inputs.
}

PropertyDiff records the difference between a single property's old and new values.

func (PropertyDiff) ToReplace

func (p PropertyDiff) ToReplace() PropertyDiff

ToReplace converts the kind of a PropertyDiff into the equivalent replacement if it not already a replacement.

type Provider

type Provider interface {

	// Closer closes any underlying OS resources associated with this provider (like processes, RPC channels, etc).
	io.Closer

	// Pkg fetches this provider's package.
	Pkg() tokens.Package

	// Handshake is the first call made by the engine to a provider. It is used to pass the engine's address to the
	// provider so that it may establish its own connections back, and to establish protocol configuration that will be
	// used to communicate between the two parties. Providers that support Handshake implicitly support the set of
	// feature flags previously handled by Configure prior to Handshake's introduction, such as secrets and resource
	// references.
	Handshake(context.Context, ProviderHandshakeRequest) (*ProviderHandshakeResponse, error)

	// Parameterize adds a sub-package to this provider instance.
	Parameterize(context.Context, ParameterizeRequest) (ParameterizeResponse, error)

	// GetSchema returns the schema for the provider.
	GetSchema(context.Context, GetSchemaRequest) (GetSchemaResponse, error)

	// CheckConfig validates the configuration for this resource provider.
	CheckConfig(context.Context, CheckConfigRequest) (CheckConfigResponse, error)
	// DiffConfig checks what impacts a hypothetical change to this provider's configuration will have on the provider.
	DiffConfig(context.Context, DiffConfigRequest) (DiffConfigResponse, error)
	// Configure configures the resource provider with "globals" that control its behavior.
	Configure(context.Context, ConfigureRequest) (ConfigureResponse, 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.
	Check(context.Context, CheckRequest) (CheckResponse, error)
	// Diff checks what impacts a hypothetical update will have on the resource's properties.
	Diff(context.Context, DiffRequest) (DiffResponse, error)
	// Create allocates a new instance of the provided resource and returns its unique resource.ID.
	Create(context.Context, CreateRequest) (CreateResponse, error)
	// Read the current live state associated with a resource.  Enough state must be include in the inputs to uniquely
	// identify the resource; this is typically just the resource ID, but may also include some properties.  If the
	// resource is missing (for instance, because it has been deleted), the resulting property map will be nil.
	Read(context.Context, ReadRequest) (ReadResponse, error)
	// Update updates an existing resource with new values.
	Update(context.Context, UpdateRequest) (UpdateResponse, error)
	// Delete tears down an existing resource. The inputs and outputs are the last recorded ones from state.
	Delete(context.Context, DeleteRequest) (DeleteResponse, error)

	// Construct creates a new component resource.
	Construct(context.Context, ConstructRequest) (ConstructResponse, error)

	// Invoke dynamically executes a built-in function in the provider.
	Invoke(context.Context, InvokeRequest) (InvokeResponse, error)
	// StreamInvoke dynamically executes a built-in function in the provider, which returns a stream
	// of responses.
	StreamInvoke(context.Context, StreamInvokeRequest) (StreamInvokeResponse, error)
	// Call dynamically executes a method in the provider associated with a component resource.
	Call(context.Context, CallRequest) (CallResponse, error)

	// GetPluginInfo returns this plugin's information.
	GetPluginInfo(context.Context) (workspace.PluginInfo, error)

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

	// GetMapping returns the mapping (if any) for the provider. A provider should return an empty response
	// (not an error) if it doesn't have a mapping for the given key.
	GetMapping(context.Context, GetMappingRequest) (GetMappingResponse, error)

	// GetMappings returns the mappings (if any) for the providers. A provider should return an empty list (not an
	// error) if it doesn't have any mappings for the given key.
	// If a provider implements this method GetMapping will be called using the results from this method.
	GetMappings(context.Context, GetMappingsRequest) (GetMappingsResponse, error)
	// contains filtered or unexported methods
}

Provider presents a simple interface for orchestrating resource create, read, update, and delete operations. Each provider understands how to handle all of the resource types within a single package.

This interface hides some of the messiness of the underlying machinery, since providers are behind an RPC boundary.

It is important to note that provider operations are not transactional. (Some providers might decide to offer transactional semantics, but such a provider is a rare treat.) As a result, failures in the operations below can range from benign to catastrophic (possibly leaving behind a corrupt resource). It is up to the provider to make a best effort to ensure catastrophes do not occur. The errors returned from mutating operations indicate both the underlying error condition in addition to a bit indicating whether the operation was successfully rolled back.

func NewProvider

func NewProvider(host Host, ctx *Context, pkg tokens.Package, version *semver.Version,
	options map[string]interface{}, disableProviderPreview bool, jsonConfig string,
	projectName tokens.PackageName,
) (Provider, error)

NewProvider attempts to bind to a given package's resource plugin and then creates a gRPC connection to it. If the plugin could not be found, or an error occurs while creating the child process, an error is returned.

func NewProviderFromPath

func NewProviderFromPath(host Host, ctx *Context, path string) (Provider, error)

NewProviderFromPath creates a new provider by loading the plugin binary located at `path`.

func NewProviderWithClient

func NewProviderWithClient(ctx *Context, pkg tokens.Package, client codeinfrarpc.ResourceProviderClient,
	disableProviderPreview bool,
) Provider

type ProviderHandshakeRequest

type ProviderHandshakeRequest struct {
	// The gRPC address of the engine handshaking with the provider. At a minimum, this address will expose an instance of
	// the Engine service.
	EngineAddress string

	// A *root directory* where the provider's binary, `CodeinfraPlugin.yaml`, or other identifying source code is located.
	// In the event that the provider is *not* being booted by the engine (e.g. in the case that the engine has been asked
	// to attach to an existing running provider instance via a host/port number), this field will be empty.
	RootDirectory *string

	// A *program directory* in which the provider should execute. This is generally a subdirectory of the root directory,
	// though this is not required. In the event that the provider is *not* being booted by the engine (e.g. in the case
	// that the engine has been asked to attach to an existing running provider instance via a host/port number), this
	// field will be empty.
	ProgramDirectory *string
}

The type of requests sent as part of a Handshake call.

type ProviderHandshakeResponse

type ProviderHandshakeResponse struct{}

The type of responses sent as part of a Handshake call.

type ReadRequest

type ReadRequest struct {
	URN           resource.URN
	Name          string
	Type          tokens.Type
	ID            resource.ID
	Inputs, State resource.PropertyMap
}

type ReadResponse

type ReadResponse struct {
	ReadResult
	Status resource.Status
}

type ReadResult

type ReadResult struct {
	// This is the ID for the resource. This ID will always be populated and will ensure we get the most up-to-date
	// resource ID.
	ID resource.ID
	// Inputs contains the new inputs for the resource, if any. If this field is nil, the provider does not support
	// returning inputs from a call to Read and the old inputs (if any) should be preserved.
	Inputs resource.PropertyMap
	// Outputs contains the new outputs/state for the resource, if any. If this field is nil, the resource does not
	// exist.
	Outputs resource.PropertyMap
}

ReadResult is the result of a call to Read.

type Remediation

type Remediation struct {
	PolicyName        string
	Description       string
	PolicyPackName    string
	PolicyPackVersion string
	URN               resource.URN
	Properties        resource.PropertyMap
	Diagnostic        string
}

Remediation indicates that a resource remediation took place, and contains the resulting transformed properties and associated metadata.

type ResourceImport

type ResourceImport struct {
	Type        string
	Name        string
	ID          string
	LogicalName string
	IsComponent bool
	IsRemote    bool

	Version           string
	PluginDownloadURL string
}

type RunInfo

type RunInfo struct {
	Info              ProgramInfo           // the information about the program to run.
	MonitorAddress    string                // the RPC address to the host resource monitor.
	Project           string                // the project name housing the program being run.
	Stack             string                // the stack name being evaluated.
	Pwd               string                // the program's working directory.
	Args              []string              // any arguments to pass to the program.
	Config            map[config.Key]string // the configuration variables to apply before running.
	ConfigSecretKeys  []config.Key          // the configuration keys that have secret values.
	ConfigPropertyMap resource.PropertyMap  // the configuration as a property map.
	DryRun            bool                  // true if we are performing a dry-run (preview).
	QueryMode         bool                  // true if we're only doing a query.
	Parallel          int32                 // the degree of parallelism for resource operations (<=1 for serial).
	Organization      string                // the organization name housing the program being run (might be empty).
	LoaderAddress     string                // the RPC address of the host's schema loader.
	AttachDebugger    bool                  // true if we are starting the program under a debugger.
}

RunInfo contains all of the information required to perform a plan or deployment operation.

type RunPluginInfo

type RunPluginInfo struct {
	Info             ProgramInfo
	WorkingDirectory string
	Args             []string
	Env              []string
}

type RuntimeOptionPrompt

type RuntimeOptionPrompt struct {
	Key         string
	Description string
	Choices     []RuntimeOptionValue
	Default     *RuntimeOptionValue
	PromptType  RuntimeOptionType
}

RuntimeOptionPrompt is a prompt for a runtime option. The prompt can have multiple choices or be free-form if Choices is empty. Key is the key as used in runtime.options.<Key> in the Codeinfra.yaml file.

type RuntimeOptionType

type RuntimeOptionType int
const (
	PromptTypeString RuntimeOptionType = iota
	PromptTypeInt32
)

type RuntimeOptionValue

type RuntimeOptionValue struct {
	PromptType  RuntimeOptionType
	StringValue string
	Int32Value  int32
	DisplayName string
}

RuntimeOptionValue represents a single value that can be selected for a runtime option. The value can be either a string or an int32.

func RuntimeOptionValueFromString

func RuntimeOptionValueFromString(promptType RuntimeOptionType, value string) (RuntimeOptionValue, error)

func (RuntimeOptionValue) String

func (v RuntimeOptionValue) String() string

func (RuntimeOptionValue) Value

func (v RuntimeOptionValue) Value() interface{}

type StreamInvokeRequest

type StreamInvokeRequest struct {
	Tok    tokens.ModuleMember
	Args   resource.PropertyMap
	OnNext func(resource.PropertyMap) error
}

type StreamInvokeResponse

type StreamInvokeResponse struct {
	Failures []CheckFailure
}

type UnimplementedProvider

type UnimplementedProvider struct{ NotForwardCompatibleProvider }

UnimplementedProvider can be embedded to have a forward compatible implementation of Provider.

Either NotForwardCompatibleProvider or UnimplementedProvider must be embedded to implement Provider.

func (*UnimplementedProvider) Call

func (*UnimplementedProvider) Check

func (*UnimplementedProvider) CheckConfig

func (*UnimplementedProvider) Close

func (p *UnimplementedProvider) Close() error

func (*UnimplementedProvider) Configure

func (*UnimplementedProvider) Construct

func (*UnimplementedProvider) Create

func (*UnimplementedProvider) Delete

func (*UnimplementedProvider) Diff

func (*UnimplementedProvider) DiffConfig

func (*UnimplementedProvider) GetMapping

func (*UnimplementedProvider) GetMappings

func (*UnimplementedProvider) GetPluginInfo

func (*UnimplementedProvider) GetSchema

func (*UnimplementedProvider) Handshake

func (*UnimplementedProvider) Invoke

func (*UnimplementedProvider) Parameterize

func (*UnimplementedProvider) Pkg

func (*UnimplementedProvider) Read

func (*UnimplementedProvider) SignalCancellation

func (p *UnimplementedProvider) SignalCancellation(context.Context) error

func (*UnimplementedProvider) StreamInvoke

func (*UnimplementedProvider) Update

type UpdateRequest

type UpdateRequest struct {
	URN                              resource.URN
	Name                             string
	Type                             tokens.Type
	ID                               resource.ID
	OldInputs, OldOutputs, NewInputs resource.PropertyMap
	Timeout                          float64
	IgnoreChanges                    []string
	Preview                          bool
}

type UpdateResponse

type UpdateResponse struct {
	Properties resource.PropertyMap
	Status     resource.Status
}

Jump to

Keyboard shortcuts

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