From 0185d32adde7ca0867b7391776e1c88ee7bd7fff Mon Sep 17 00:00:00 2001 From: Erik Osterman Date: Sat, 31 Oct 2026 12:38:49 -0500 Subject: [PATCH 01/28] feat(plugin): deliver Terragrunt log events live through the Atmos API Add a Log service to the plugin callback channel so a plugin can push log entries while a call is still running. The Atmos side renders them through the existing masked stderr logger, scoped by plugin, component, stack, and unit, and drops them below the invocation's log level. No entry is dropped: when the terminal renders slower than the plugin logs, the plugin waits for room in a bounded queue, and a cancelled call stops waiting and reports how many events it could not show. If the log service is unavailable, undelivered entries return with the response instead. Discover, Prepare, and state resolution all use it, and it stops promptly on cancellation without leaking goroutines. Co-Authored-By: Claude Sonnet 5.5 --- pkg/plugin/adapter/component/invoke.go | 2 +- pkg/plugin/adapter/component/logs.go | 35 +- .../adapter/component/logs_live_test.go | 197 +++++ pkg/plugin/adapter/component/main_test.go | 60 +- .../adapter/configuration/preparation.go | 2 +- pkg/plugin/adapter/configuration/state.go | 2 +- pkg/plugin/bridge/invocations.go | 15 +- pkg/plugin/bridge/logs.go | 43 ++ pkg/plugin/bridge/logs_test.go | 66 ++ pkg/plugin/bridge/mock_logs_test.go | 54 ++ pkg/plugin/proto/atmos/plugin/v1/plugin.pb.go | 683 ++++++++++-------- .../proto/atmos/plugin/v1/plugin_grpc.pb.go | 126 ++++ plugins/terragrunt/fixtures/toolprobe/main.go | 31 +- plugins/terragrunt/internal/engine/logs.go | 61 +- .../terragrunt/internal/engine/logs_test.go | 53 ++ plugins/terragrunt/internal/engine/resolve.go | 5 +- .../terragrunt/internal/provider/discovery.go | 6 +- .../internal/provider/live_logs_test.go | 173 +++++ plugins/terragrunt/internal/provider/logs.go | 65 +- .../internal/provider/preparation.go | 12 +- .../terragrunt/internal/provider/provider.go | 24 +- plugins/terragrunt/main.go | 4 +- proto/atmos/plugin/v1/plugin.proto | 18 +- sdk/api/logs.go | 298 ++++++++ sdk/api/logs_test.go | 363 ++++++++++ sdk/proto/atmos/plugin/v1/plugin.pb.go | 683 ++++++++++-------- sdk/proto/atmos/plugin/v1/plugin_grpc.pb.go | 126 ++++ tests/terragrunt_streaming_test.go | 160 ++++ 28 files changed, 2679 insertions(+), 688 deletions(-) create mode 100644 pkg/plugin/adapter/component/logs_live_test.go create mode 100644 pkg/plugin/bridge/logs.go create mode 100644 pkg/plugin/bridge/logs_test.go create mode 100644 pkg/plugin/bridge/mock_logs_test.go create mode 100644 plugins/terragrunt/internal/provider/live_logs_test.go create mode 100644 sdk/api/logs.go create mode 100644 sdk/api/logs_test.go create mode 100644 tests/terragrunt_streaming_test.go diff --git a/pkg/plugin/adapter/component/invoke.go b/pkg/plugin/adapter/component/invoke.go index 4c21bd714f6..d687a7708eb 100644 --- a/pkg/plugin/adapter/component/invoke.go +++ b/pkg/plugin/adapter/component/invoke.go @@ -30,7 +30,7 @@ func (p *Provider) invoke(ctx context.Context, capability string, run func(conte defer handle.Close() // No ambient HTTP, browser, secret, or private-credential grants. Future host // adapters must provide explicit invocation-scoped grants for allowed effects. - scope := bridge.Invocation{Namespace: p.owner + ":component:" + p.name} + scope := bridge.Invocation{Namespace: p.owner + ":component:" + p.name, Logs: newLiveLogs(ctx, p.name)} err = handle.Invoke(ctx, scope, func(call context.Context, invocation *pluginv1.Invocation) error { return run(call, handle, invocation) }) diff --git a/pkg/plugin/adapter/component/logs.go b/pkg/plugin/adapter/component/logs.go index 82a2ae0a843..eefad2c011e 100644 --- a/pkg/plugin/adapter/component/logs.go +++ b/pkg/plugin/adapter/component/logs.go @@ -1,6 +1,7 @@ package component import ( + "context" "maps" "slices" "strings" @@ -21,6 +22,36 @@ type LogScope struct { Stack string } +type logScopeKey struct{} + +// WithLogScope names the component and stack that log events delivered during a call belong to. A plugin +// delivers its log events while the call runs, so the call must carry the scope; a call without one is scoped +// to the plugin alone. +func WithLogScope(ctx context.Context, scope LogScope) context.Context { + defer perf.Track(nil, "componentadapter.WithLogScope")() + + return context.WithValue(ctx, logScopeKey{}, scope) +} + +// liveLogs renders the entries a plugin delivers while a call runs, scoped to the call. +type liveLogs struct{ scope LogScope } + +// newLiveLogs returns the sink for the call made with ctx by the provider named name. +func newLiveLogs(ctx context.Context, name string) liveLogs { + scope, _ := ctx.Value(logScopeKey{}).(LogScope) + if scope.Provider == "" { + scope.Provider = name + } + return liveLogs{scope: scope} +} + +// WriteLogs renders the entries now, in order, through the same path as entries a response carries. +func (l liveLogs) WriteLogs(_ context.Context, entries []*pluginv1.LogEntry) { + defer perf.Track(nil, "componentadapter.liveLogs.WriteLogs")() + + RenderLogs(l.scope, entries) +} + // logOff is the level that tells a plugin to return no log events. const logOff = "off" @@ -77,7 +108,9 @@ func RenderLogs(scope LogScope, entries []*pluginv1.LogEntry) { for _, entry := range entries { level, ok := logLevel(entry.GetLevel()) - if !ok { + // The plugin drops events below the level it was given, and the host checks again here: a plugin may + // ignore the level, and masking and formatting an event nobody will see is wasted work. + if !ok || level < log.GetLevel() { continue } message := atmosio.MaskString(entry.GetMessage()) diff --git a/pkg/plugin/adapter/component/logs_live_test.go b/pkg/plugin/adapter/component/logs_live_test.go new file mode 100644 index 00000000000..675859c3ac8 --- /dev/null +++ b/pkg/plugin/adapter/component/logs_live_test.go @@ -0,0 +1,197 @@ +package component + +import ( + "context" + "os" + "path/filepath" + "runtime" + "strings" + "sync" + "testing" + "time" + + charm "github.com/charmbracelet/log" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/zclconf/go-cty/cty" + + atmosio "github.com/cloudposse/atmos/pkg/io" + log "github.com/cloudposse/atmos/pkg/logger" + pluginv1 "github.com/cloudposse/atmos/pkg/plugin/proto/atmos/plugin/v1" +) + +// syncBuffer is a log destination that the test reads while the logger writes from another goroutine. +type syncBuffer struct { + mu sync.Mutex + text strings.Builder +} + +func (b *syncBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.text.Write(p) +} + +func (b *syncBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.text.String() +} + +func captureLiveLogs(t *testing.T, level charm.Level) *syncBuffer { + t.Helper() + output := &syncBuffer{} + previousLevel := log.GetLevel() + log.SetOutput(output) + log.SetLevel(level) + ResetShownMessages() + t.Cleanup(func() { + log.SetOutput(os.Stderr) + log.SetLevel(previousLevel) + ResetShownMessages() + }) + return output +} + +func liveRequest(t *testing.T, root, command string) *pluginv1.ComponentRequest { + t.Helper() + return &pluginv1.ComponentRequest{ + RootDirectory: root, Address: fixtureAddress(), Invocation: &pluginv1.Invocation{LogLevel: "debug"}, + Operation: &pluginv1.ComponentOperation{Command: command, Mode: "native"}, + Configuration: wireValue(t, cty.ObjectVal(map[string]cty.Value{})), + ProviderConfiguration: wireValue(t, cty.ObjectVal(map[string]cty.Value{})), + } +} + +type prepared struct { + response *pluginv1.PrepareComponentResponse + err error +} + +// waitFor polls until the condition holds, failing the test when it does not within the limit. +func waitFor(t *testing.T, what string, condition func() bool) { + t.Helper() + require.Eventually(t, condition, 20*time.Second, 5*time.Millisecond, what) +} + +func TestLiveLogsReachTheLoggerWhileTheCallIsStillRunning(t *testing.T) { + output := captureLiveLogs(t, charm.DebugLevel) + atmosio.RegisterSecret("live-secret-value-91ab") + root := t.TempDir() + provider := fixtureProvider(t) + ctx := WithLogScope(t.Context(), LogScope{Component: "app", Stack: "live"}) + finished := make(chan prepared, 1) + go func() { + response, err := provider.Prepare(ctx, liveRequest(t, root, "live-logs")) + finished <- prepared{response, err} + }() + + // The plugin has delivered an entry and is blocked: the call has not returned, yet the entry is on screen. + waitFor(t, "first live entry reaches the Atmos logger", func() bool { return strings.Contains(output.String(), "first live entry") }) + select { + case result := <-finished: + t.Fatalf("the call returned before it was released: %+v", result) + default: + } + early := output.String() + assert.Contains(t, early, "component=app") + assert.Contains(t, early, "stack=live") + assert.Contains(t, early, "plugin=fixture/hcl") + assert.Contains(t, early, "unit=live/app") + assert.NotContains(t, early, "last live entry", "an entry the plugin has not produced yet cannot be on screen") + // Secrets in a live entry are masked like those in a response. + assert.NotContains(t, early, "live-secret-value-91ab") + + require.NoError(t, os.WriteFile(filepath.Join(root, "gate"), nil, 0o600)) + result := <-finished + require.NoError(t, result.err) + // The final entry is on screen once the call has returned, in the order the plugin produced them, and the + // response does not repeat what was delivered live. + final := output.String() + first, info, last := strings.Index(final, "first live entry"), strings.Index(final, "info live entry"), strings.Index(final, "last live entry") + assert.True(t, first >= 0 && first < info && info < last, "order: %d %d %d in %q", first, info, last, final) + assert.Empty(t, result.response.GetLogs()) + assert.Equal(t, 1, strings.Count(final, "first live entry")) +} + +func TestLiveLogsAreGatedByTheAtmosLevel(t *testing.T) { + output := captureLiveLogs(t, charm.InfoLevel) + root := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(root, "gate"), nil, 0o600)) + _, err := fixtureProvider(t).Prepare(t.Context(), liveRequest(t, root, "live-logs")) + require.NoError(t, err) + assert.Contains(t, output.String(), "info live entry") + assert.NotContains(t, output.String(), "first live entry") + assert.NotContains(t, output.String(), "last live entry") + + warn := captureLiveLogs(t, charm.WarnLevel) + _, err = fixtureProvider(t).Prepare(t.Context(), liveRequest(t, root, "live-logs")) + require.NoError(t, err) + assert.Empty(t, warn.String()) +} + +func TestLiveLogsDefaultToThePluginScopeAndNeverTouchTheResponse(t *testing.T) { + output := captureLiveLogs(t, charm.DebugLevel) + root := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(root, "gate"), nil, 0o600)) + response, err := fixtureProvider(t).Prepare(t.Context(), liveRequest(t, root, "live-logs")) + require.NoError(t, err) + assert.Contains(t, output.String(), "plugin=fixture/hcl") + assert.NotContains(t, output.String(), "component=") + assert.Empty(t, response.GetLogs()) +} + +func TestEntriesTheResponseCarriesStayInTheResponse(t *testing.T) { + output := captureLiveLogs(t, charm.DebugLevel) + response, err := fixtureProvider(t).Prepare(t.Context(), liveRequest(t, t.TempDir(), "return-logs")) + require.NoError(t, err) + // A plugin that did not deliver live returns its entries as before, and the adapter renders nothing itself. + require.Len(t, response.GetLogs(), 1) + assert.Equal(t, "returned in the response", response.GetLogs()[0].GetMessage()) + assert.Empty(t, output.String()) +} + +func TestCancellingTheCallStopsLiveDeliveryWithoutLeakingGoroutines(t *testing.T) { + output := captureLiveLogs(t, charm.DebugLevel) + provider := fixtureProvider(t) + // Warm up so the baseline includes the long-lived runtime goroutines. + warm := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(warm, "gate"), nil, 0o600)) + _, err := provider.Prepare(t.Context(), liveRequest(t, warm, "live-logs")) + require.NoError(t, err) + baseline := settledGoroutines() + + root := t.TempDir() + ctx, cancel := context.WithCancel(t.Context()) + finished := make(chan prepared, 1) + go func() { + response, err := provider.Prepare(ctx, liveRequest(t, root, "live-logs")) + finished <- prepared{response, err} + }() + waitFor(t, "first live entry of the second call", func() bool { return strings.Count(output.String(), "first live entry") == 2 }) + cancel() + select { + case result := <-finished: + require.Error(t, result.err) + case <-time.After(20 * time.Second): + t.Fatal("cancelling the command did not stop the call") + } + // Poll directly: a testify Eventually condition runs on a goroutine of its own and would count itself. + deadline := time.Now().Add(10 * time.Second) + for runtime.NumGoroutine() > baseline && time.Now().Before(deadline) { + time.Sleep(20 * time.Millisecond) + } + if runtime.NumGoroutine() > baseline { + buffer := make([]byte, 1<<18) + t.Fatalf("goroutines after cancel: %d, baseline %d\n%s", runtime.NumGoroutine(), baseline, buffer[:runtime.Stack(buffer, true)]) + } + // Only the warm-up call produced a last entry: the cancelled call never reached its end. + assert.Equal(t, 1, strings.Count(output.String(), "last live entry")) + assert.Equal(t, 2, strings.Count(output.String(), "first live entry")) +} + +func settledGoroutines() int { + runtime.GC() + time.Sleep(200 * time.Millisecond) + return runtime.NumGoroutine() +} diff --git a/pkg/plugin/adapter/component/main_test.go b/pkg/plugin/adapter/component/main_test.go index 349281f6b3a..5e7b5f2d83a 100644 --- a/pkg/plugin/adapter/component/main_test.go +++ b/pkg/plugin/adapter/component/main_test.go @@ -5,10 +5,12 @@ import ( "os" "path/filepath" "testing" + "time" "github.com/hashicorp/go-plugin" "google.golang.org/grpc" "google.golang.org/grpc/codes" + "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/emptypb" @@ -30,8 +32,8 @@ func TestMain(m *testing.M) { type fixtureProtocol struct{ plugin.NetRPCUnsupportedPlugin } -func (*fixtureProtocol) GRPCServer(_ *plugin.GRPCBroker, server *grpc.Server) error { - fixture := &componentFixture{} +func (*fixtureProtocol) GRPCServer(broker *plugin.GRPCBroker, server *grpc.Server) error { + fixture := &componentFixture{broker: broker} pluginv1.RegisterInfoServer(server, fixture) pluginv1.RegisterComponentDiscoveryServer(server, fixture) pluginv1.RegisterComponentValidationServer(server, fixture) @@ -45,6 +47,9 @@ func (*fixtureProtocol) GRPCClient(context.Context, *plugin.GRPCBroker, *grpc.Cl } type componentFixture struct { + broker *plugin.GRPCBroker + // api is the connection to the Atmos API, dialed when Atmos configures the plugin. + api *grpc.ClientConn pluginv1.UnimplementedInfoServer pluginv1.UnimplementedComponentDiscoveryServer pluginv1.UnimplementedComponentValidationServer @@ -61,7 +66,12 @@ func (*componentFixture) Describe(context.Context, *pluginv1.DescribeRequest) (* return result, proto.Unmarshal(raw, result) } -func (*componentFixture) Configure(context.Context, *pluginv1.ConfigureRequest) (*emptypb.Empty, error) { +func (f *componentFixture) Configure(_ context.Context, request *pluginv1.ConfigureRequest) (*emptypb.Empty, error) { + if id, ok := request.GetBrokerIds()["atmos.api.v1"]; ok && f.broker != nil { + if connection, err := f.broker.Dial(id); err == nil { + f.api = connection + } + } return &emptypb.Empty{}, nil } @@ -116,11 +126,20 @@ func (*componentFixture) Discover(_ context.Context, request *pluginv1.DiscoverC return &pluginv1.DiscoverComponentsResponse{Components: []*pluginv1.DiscoveredComponent{{Address: fixtureAddress(), Provider: request.Provider, Engine: "terraform", Source: "live/app/terragrunt.hcl"}}}, nil } -func (*componentFixture) Prepare(_ context.Context, request *pluginv1.ComponentRequest) (*pluginv1.PrepareComponentResponse, error) { +func (f *componentFixture) Prepare(ctx context.Context, request *pluginv1.ComponentRequest) (*pluginv1.PrepareComponentResponse, error) { if err := recordCall(request.RootDirectory, "preparation", request); err != nil { return nil, err } - return &pluginv1.PrepareComponentResponse{Engine: "terraform", WorkingDirectory: request.RootDirectory, ModuleSource: "./module", Inputs: request.Configuration, State: fixtureState(request.RootDirectory), Files: []*pluginv1.ComponentGeneratedFile{{Path: "backend.tf", Content: []byte("$${literal}\n%{ literal }\n"), IfExists: "error"}}}, nil + var returned []*pluginv1.LogEntry + switch request.GetOperation().GetCommand() { + case "live-logs": + if err := f.liveLogs(ctx, request); err != nil { + return nil, err + } + case "return-logs": + returned = []*pluginv1.LogEntry{{Level: pluginv1.LogLevel_LOG_LEVEL_DEBUG, Message: "returned in the response"}} + } + return &pluginv1.PrepareComponentResponse{Logs: returned, Engine: "terraform", WorkingDirectory: request.RootDirectory, ModuleSource: "./module", Inputs: request.Configuration, State: fixtureState(request.RootDirectory), Files: []*pluginv1.ComponentGeneratedFile{{Path: "backend.tf", Content: []byte("$${literal}\n%{ literal }\n"), IfExists: "error"}}}, nil } func (*componentFixture) Resolve(_ context.Context, request *pluginv1.ComponentRequest) (*pluginv1.ResolveComponentStateResponse, error) { @@ -137,3 +156,34 @@ func recordCall(root, method string, request proto.Message) error { } return os.WriteFile(filepath.Join(root, method+".pb"), raw, 0o600) } + +// liveLogs delivers one entry, waits for the gate file the test creates, then delivers another. The wait +// stands for a slow operation such as a run_cmd; the test reads the first entry while the call is blocked. +func (f *componentFixture) liveLogs(ctx context.Context, request *pluginv1.ComponentRequest) error { + if f.api == nil { + return status.Error(codes.FailedPrecondition, "no API connection") + } + client := pluginv1.NewLogClient(f.api) + ctx = metadata.AppendToOutgoingContext(ctx, "atmos-invocation-id", request.GetInvocation().GetId()) + send := func(level pluginv1.LogLevel, message string) error { + _, err := client.Write(ctx, &pluginv1.LogRequest{Entries: []*pluginv1.LogEntry{{Level: level, Message: message, Unit: "live/app", Fields: map[string]string{"auth": "Bearer live-secret-value-91ab"}}}}) + return err + } + if err := send(pluginv1.LogLevel_LOG_LEVEL_DEBUG, "first live entry"); err != nil { + return err + } + if err := send(pluginv1.LogLevel_LOG_LEVEL_INFO, "info live entry"); err != nil { + return err + } + for { + if _, err := os.Stat(filepath.Join(request.GetRootDirectory(), "gate")); err == nil { + break + } + select { + case <-ctx.Done(): + return status.FromContextError(ctx.Err()).Err() + case <-time.After(10 * time.Millisecond): + } + } + return send(pluginv1.LogLevel_LOG_LEVEL_DEBUG, "last live entry") +} diff --git a/pkg/plugin/adapter/configuration/preparation.go b/pkg/plugin/adapter/configuration/preparation.go index cf181c6da8f..de09b95795b 100644 --- a/pkg/plugin/adapter/configuration/preparation.go +++ b/pkg/plugin/adapter/configuration/preparation.go @@ -70,7 +70,7 @@ func runProviderPrepare(ctx context.Context, info *schema.ConfigAndStacksInfo, s return nil, err } selected.request.Effects = &pluginv1.ComponentEffects{Commands: true, Network: true, Secrets: true, Writes: true, StateReads: true} - result, err := selected.provider.Prepare(ctx, selected.request) + result, err := selected.provider.Prepare(adapter.WithLogScope(ctx, logScope(selected.request, info)), selected.request) if err != nil { return nil, err } diff --git a/pkg/plugin/adapter/configuration/state.go b/pkg/plugin/adapter/configuration/state.go index 863c01e51c8..568d8bb8865 100644 --- a/pkg/plugin/adapter/configuration/state.go +++ b/pkg/plugin/adapter/configuration/state.go @@ -30,7 +30,7 @@ func (s *Session) ResolveState(ctx context.Context, info *schema.ConfigAndStacks if !ok { return nil, errUtils.ErrPluginUnsupportedExtension } - result, err := resolver.ResolveState(ctx, selected.request) + result, err := resolver.ResolveState(adapter.WithLogScope(ctx, logScope(selected.request, info)), selected.request) if err != nil { return nil, err } diff --git a/pkg/plugin/bridge/invocations.go b/pkg/plugin/bridge/invocations.go index df120bb4347..c9efef7051a 100644 --- a/pkg/plugin/bridge/invocations.go +++ b/pkg/plugin/bridge/invocations.go @@ -16,6 +16,7 @@ import ( "github.com/cloudposse/atmos/pkg/keyring" "github.com/cloudposse/atmos/pkg/perf" apiv1 "github.com/cloudposse/atmos/pkg/plugin/proto/atmos/api/v1" + pluginv1 "github.com/cloudposse/atmos/pkg/plugin/proto/atmos/plugin/v1" ) // InvocationMetadata is set by Plugin SDK calls back into the Atmos API. @@ -24,11 +25,13 @@ const InvocationMetadata = "atmos-invocation-id" // Invocation scopes API services to a single active call. Namespace includes the // package, configured provider, realm, and configuration fingerprint. type Invocation struct { - Context context.Context - Browser api.Browser - HTTP api.HTTP - Secrets SecretReader - Keyring keyring.Keyring + Context context.Context + Browser api.Browser + HTTP api.HTTP + Secrets SecretReader + Keyring keyring.Keyring + // Logs shows the log entries the plugin delivers while the call runs. Nil grants no live delivery. + Logs LogSink Namespace string Interactive bool } @@ -39,6 +42,7 @@ type Server struct { apiv1.UnimplementedBrowserServer apiv1.UnimplementedCredentialsServer apiv1.UnimplementedSecretsServer + pluginv1.UnimplementedLogServer storageMu sync.Mutex mu sync.RWMutex calls map[string]*activeInvocation @@ -57,6 +61,7 @@ func (s *Server) Register(server *grpc.Server) { apiv1.RegisterBrowserServer(server, s) apiv1.RegisterCredentialsServer(server, s) apiv1.RegisterSecretsServer(server, s) + pluginv1.RegisterLogServer(server, s) } // Begin grants API access until the returned cleanup function is called. diff --git a/pkg/plugin/bridge/logs.go b/pkg/plugin/bridge/logs.go new file mode 100644 index 00000000000..5874fd666f9 --- /dev/null +++ b/pkg/plugin/bridge/logs.go @@ -0,0 +1,43 @@ +package bridge + +//go:generate go run go.uber.org/mock/mockgen@v0.6.0 -source=$GOFILE -destination=mock_logs_test.go -package=bridge + +import ( + "context" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/emptypb" + + "github.com/cloudposse/atmos/pkg/perf" + pluginv1 "github.com/cloudposse/atmos/pkg/plugin/proto/atmos/plugin/v1" +) + +// maxLogBatch bounds the entries one Write call may carry, so a plugin cannot hold the terminal with one call. +const maxLogBatch = 1024 + +// LogSink shows the log entries a plugin delivers during its invocation. Write returns after the entries are +// shown, which is what lets a plugin order its entries before its result. It must not fail the invocation. +type LogSink interface { + WriteLogs(context.Context, []*pluginv1.LogEntry) +} + +// Write shows entries delivered by the active invocation. An invocation without a sink, or an unknown or +// finished one, delivers nothing; the plugin then returns the entries in its response instead. +func (s *Server) Write(ctx context.Context, request *pluginv1.LogRequest) (*emptypb.Empty, error) { + defer perf.Track(nil, "bridge.Server.Write")() + + call, err := s.authorize(ctx) + if err != nil { + return nil, err + } + defer call.done() + if call.Logs == nil { + return nil, status.Error(codes.PermissionDenied, "log delivery not granted") + } + if len(request.GetEntries()) > maxLogBatch { + return nil, status.Error(codes.InvalidArgument, "too many log entries") + } + call.Logs.WriteLogs(call.Context, request.GetEntries()) + return &emptypb.Empty{}, nil +} diff --git a/pkg/plugin/bridge/logs_test.go b/pkg/plugin/bridge/logs_test.go new file mode 100644 index 00000000000..fe5054ce063 --- /dev/null +++ b/pkg/plugin/bridge/logs_test.go @@ -0,0 +1,66 @@ +package bridge + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/mock/gomock" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" + + pluginv1 "github.com/cloudposse/atmos/pkg/plugin/proto/atmos/plugin/v1" +) + +func logEntries(messages ...string) []*pluginv1.LogEntry { + entries := make([]*pluginv1.LogEntry, 0, len(messages)) + for _, message := range messages { + entries = append(entries, &pluginv1.LogEntry{Level: pluginv1.LogLevel_LOG_LEVEL_DEBUG, Message: message}) + } + return entries +} + +func TestLogDeliveryIsGrantedPerInvocation(t *testing.T) { + t.Parallel() + server := New() + sink := NewMockLogSink(gomock.NewController(t)) + granted, err := server.Begin("granted", Invocation{Context: t.Context(), Namespace: "plugin", Logs: sink}) + require.NoError(t, err) + t.Cleanup(granted) + withheld, err := server.Begin("withheld", Invocation{Context: t.Context(), Namespace: "plugin"}) + require.NoError(t, err) + t.Cleanup(withheld) + with := func(id string) context.Context { + return metadata.NewIncomingContext(t.Context(), metadata.Pairs(InvocationMetadata, id)) + } + + // Entries reach the sink of the invocation that made the call, in order, before the call returns. + var delivered []string + sink.EXPECT().WriteLogs(gomock.Any(), gomock.Any()).Do(func(_ any, entries []*pluginv1.LogEntry) { + for _, entry := range entries { + delivered = append(delivered, entry.GetMessage()) + } + }).Times(2) + _, err = server.Write(with("granted"), &pluginv1.LogRequest{Entries: logEntries("first", "second")}) + require.NoError(t, err) + _, err = server.Write(with("granted"), &pluginv1.LogRequest{Entries: logEntries("third")}) + require.NoError(t, err) + assert.Equal(t, []string{"first", "second", "third"}, delivered) + + // An invocation without a grant, an unknown one, and a missing one deliver nothing. + for _, id := range []string{"withheld", "unknown", ""} { + _, err := server.Write(with(id), &pluginv1.LogRequest{Entries: logEntries("hidden")}) + require.Equal(t, codes.PermissionDenied, status.Code(err), id) + } + + // A batch above the bound is refused so one call cannot hold the terminal. + _, err = server.Write(with("granted"), &pluginv1.LogRequest{Entries: logEntries(make([]string, maxLogBatch+1)...)}) + require.Equal(t, codes.InvalidArgument, status.Code(err)) + + // After the invocation ends nothing is accepted, so a late call cannot print after the result. + granted() + _, err = server.Write(with("granted"), &pluginv1.LogRequest{Entries: logEntries("late")}) + require.Equal(t, codes.PermissionDenied, status.Code(err)) +} diff --git a/pkg/plugin/bridge/mock_logs_test.go b/pkg/plugin/bridge/mock_logs_test.go new file mode 100644 index 00000000000..968e9bb1002 --- /dev/null +++ b/pkg/plugin/bridge/mock_logs_test.go @@ -0,0 +1,54 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: logs.go +// +// Generated by this command: +// +// mockgen -source=logs.go -destination=mock_logs_test.go -package=bridge +// + +// Package bridge is a generated GoMock package. +package bridge + +import ( + context "context" + reflect "reflect" + + pluginv1 "github.com/cloudposse/atmos/pkg/plugin/proto/atmos/plugin/v1" + gomock "go.uber.org/mock/gomock" +) + +// MockLogSink is a mock of LogSink interface. +type MockLogSink struct { + ctrl *gomock.Controller + recorder *MockLogSinkMockRecorder + isgomock struct{} +} + +// MockLogSinkMockRecorder is the mock recorder for MockLogSink. +type MockLogSinkMockRecorder struct { + mock *MockLogSink +} + +// NewMockLogSink creates a new mock instance. +func NewMockLogSink(ctrl *gomock.Controller) *MockLogSink { + mock := &MockLogSink{ctrl: ctrl} + mock.recorder = &MockLogSinkMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockLogSink) EXPECT() *MockLogSinkMockRecorder { + return m.recorder +} + +// WriteLogs mocks base method. +func (m *MockLogSink) WriteLogs(arg0 context.Context, arg1 []*pluginv1.LogEntry) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "WriteLogs", arg0, arg1) +} + +// WriteLogs indicates an expected call of WriteLogs. +func (mr *MockLogSinkMockRecorder) WriteLogs(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WriteLogs", reflect.TypeOf((*MockLogSink)(nil).WriteLogs), arg0, arg1) +} diff --git a/pkg/plugin/proto/atmos/plugin/v1/plugin.pb.go b/pkg/plugin/proto/atmos/plugin/v1/plugin.pb.go index 001d7def3a9..9258eb0ecda 100644 --- a/pkg/plugin/proto/atmos/plugin/v1/plugin.pb.go +++ b/pkg/plugin/proto/atmos/plugin/v1/plugin.pb.go @@ -185,7 +185,7 @@ func (x ComponentSource_Kind) Number() protoreflect.EnumNumber { // Deprecated: Use ComponentSource_Kind.Descriptor instead. func (ComponentSource_Kind) EnumDescriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{33, 0} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{34, 0} } type ComponentDependency_Kind int32 @@ -234,7 +234,7 @@ func (x ComponentDependency_Kind) Number() protoreflect.EnumNumber { // Deprecated: Use ComponentDependency_Kind.Descriptor instead. func (ComponentDependency_Kind) EnumDescriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{34, 0} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{35, 0} } // Invocation identifies the live call authorized to use the Atmos API broker. @@ -1168,7 +1168,9 @@ func (x *SourceLocation) GetColumn() uint32 { } // LogEntry is one structured log event from a plugin's engine, for example a Terragrunt logger event. -// A response carries the entries produced while it was computed, in order. The host renders them through +// A plugin delivers entries while the call runs through the Log service of the Atmos API, so a slow +// operation shows progress as it happens. A response carries only the entries that could not be delivered +// that way, in order, and never an entry that was delivered live. The host renders them through // the Atmos logger on the UI channel (stderr), scoped to the component and stack of the call, with secret // masking, at the level each entry carries. They are hidden at the Atmos default level and shown with // --logs-level=Debug or Trace. Entries never change the outcome of the call and are never written to the @@ -1252,6 +1254,50 @@ func (x *LogEntry) GetUnit() string { return "" } +type LogRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Entries []*LogEntry `protobuf:"bytes,1,rep,name=entries,proto3" json:"entries,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *LogRequest) Reset() { + *x = LogRequest{} + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[14] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *LogRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*LogRequest) ProtoMessage() {} + +func (x *LogRequest) ProtoReflect() protoreflect.Message { + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[14] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use LogRequest.ProtoReflect.Descriptor instead. +func (*LogRequest) Descriptor() ([]byte, []int) { + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{14} +} + +func (x *LogRequest) GetEntries() []*LogEntry { + if x != nil { + return x.Entries + } + return nil +} + // ErrorDetail is the structured, user-facing description of a plugin failure. // A plugin returns it as a gRPC status detail (google.rpc.Status.details) on a // failed call, or inside Diagnostic.detail for a per-item failure that must not @@ -1297,7 +1343,7 @@ type ErrorDetail struct { func (x *ErrorDetail) Reset() { *x = ErrorDetail{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[14] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[15] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1309,7 +1355,7 @@ func (x *ErrorDetail) String() string { func (*ErrorDetail) ProtoMessage() {} func (x *ErrorDetail) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[14] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[15] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1322,7 +1368,7 @@ func (x *ErrorDetail) ProtoReflect() protoreflect.Message { // Deprecated: Use ErrorDetail.ProtoReflect.Descriptor instead. func (*ErrorDetail) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{14} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{15} } func (x *ErrorDetail) GetCode() string { @@ -1422,7 +1468,7 @@ type Diagnostic struct { func (x *Diagnostic) Reset() { *x = Diagnostic{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[15] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[16] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1434,7 +1480,7 @@ func (x *Diagnostic) String() string { func (*Diagnostic) ProtoMessage() {} func (x *Diagnostic) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[15] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[16] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1447,7 +1493,7 @@ func (x *Diagnostic) ProtoReflect() protoreflect.Message { // Deprecated: Use Diagnostic.ProtoReflect.Descriptor instead. func (*Diagnostic) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{15} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{16} } func (x *Diagnostic) GetField() string { @@ -1480,7 +1526,7 @@ type ValidateResponse struct { func (x *ValidateResponse) Reset() { *x = ValidateResponse{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[16] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[17] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1492,7 +1538,7 @@ func (x *ValidateResponse) String() string { func (*ValidateResponse) ProtoMessage() {} func (x *ValidateResponse) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[16] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[17] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1505,7 +1551,7 @@ func (x *ValidateResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ValidateResponse.ProtoReflect.Descriptor instead. func (*ValidateResponse) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{16} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{17} } func (x *ValidateResponse) GetDiagnostics() []*Diagnostic { @@ -1525,7 +1571,7 @@ type Unsupported struct { func (x *Unsupported) Reset() { *x = Unsupported{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[17] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[18] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1537,7 +1583,7 @@ func (x *Unsupported) String() string { func (*Unsupported) ProtoMessage() {} func (x *Unsupported) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[17] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[18] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1550,7 +1596,7 @@ func (x *Unsupported) ProtoReflect() protoreflect.Message { // Deprecated: Use Unsupported.ProtoReflect.Descriptor instead. func (*Unsupported) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{17} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{18} } func (x *Unsupported) GetOperation() string { @@ -1577,7 +1623,7 @@ type RefreshRequest struct { func (x *RefreshRequest) Reset() { *x = RefreshRequest{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[18] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[19] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1589,7 +1635,7 @@ func (x *RefreshRequest) String() string { func (*RefreshRequest) ProtoMessage() {} func (x *RefreshRequest) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[18] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[19] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1602,7 +1648,7 @@ func (x *RefreshRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use RefreshRequest.ProtoReflect.Descriptor instead. func (*RefreshRequest) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{18} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{19} } func (x *RefreshRequest) GetProvider() *ProviderRequest { @@ -1632,7 +1678,7 @@ type RefreshResponse struct { func (x *RefreshResponse) Reset() { *x = RefreshResponse{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[19] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[20] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1644,7 +1690,7 @@ func (x *RefreshResponse) String() string { func (*RefreshResponse) ProtoMessage() {} func (x *RefreshResponse) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[19] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[20] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1657,7 +1703,7 @@ func (x *RefreshResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use RefreshResponse.ProtoReflect.Descriptor instead. func (*RefreshResponse) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{19} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{20} } func (x *RefreshResponse) GetResult() isRefreshResponse_Result { @@ -1710,7 +1756,7 @@ type EnvironmentResponse struct { func (x *EnvironmentResponse) Reset() { *x = EnvironmentResponse{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[20] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[21] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1722,7 +1768,7 @@ func (x *EnvironmentResponse) String() string { func (*EnvironmentResponse) ProtoMessage() {} func (x *EnvironmentResponse) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[20] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[21] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1735,7 +1781,7 @@ func (x *EnvironmentResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use EnvironmentResponse.ProtoReflect.Descriptor instead. func (*EnvironmentResponse) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{20} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{21} } func (x *EnvironmentResponse) GetEnvironment() map[string]string { @@ -1755,7 +1801,7 @@ type PrepareEnvironmentRequest struct { func (x *PrepareEnvironmentRequest) Reset() { *x = PrepareEnvironmentRequest{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[21] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[22] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1767,7 +1813,7 @@ func (x *PrepareEnvironmentRequest) String() string { func (*PrepareEnvironmentRequest) ProtoMessage() {} func (x *PrepareEnvironmentRequest) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[21] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[22] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1780,7 +1826,7 @@ func (x *PrepareEnvironmentRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use PrepareEnvironmentRequest.ProtoReflect.Descriptor instead. func (*PrepareEnvironmentRequest) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{21} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{22} } func (x *PrepareEnvironmentRequest) GetProvider() *ProviderRequest { @@ -1809,7 +1855,7 @@ type CredentialPath struct { func (x *CredentialPath) Reset() { *x = CredentialPath{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[22] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[23] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1821,7 +1867,7 @@ func (x *CredentialPath) String() string { func (*CredentialPath) ProtoMessage() {} func (x *CredentialPath) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[22] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[23] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1834,7 +1880,7 @@ func (x *CredentialPath) ProtoReflect() protoreflect.Message { // Deprecated: Use CredentialPath.ProtoReflect.Descriptor instead. func (*CredentialPath) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{22} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{23} } func (x *CredentialPath) GetLocation() string { @@ -1874,7 +1920,7 @@ type PathsResponse struct { func (x *PathsResponse) Reset() { *x = PathsResponse{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[23] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[24] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1886,7 +1932,7 @@ func (x *PathsResponse) String() string { func (*PathsResponse) ProtoMessage() {} func (x *PathsResponse) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[23] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[24] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1899,7 +1945,7 @@ func (x *PathsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use PathsResponse.ProtoReflect.Descriptor instead. func (*PathsResponse) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{23} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{24} } func (x *PathsResponse) GetPaths() []*CredentialPath { @@ -1919,7 +1965,7 @@ type IdentityAuthenticateRequest struct { func (x *IdentityAuthenticateRequest) Reset() { *x = IdentityAuthenticateRequest{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[24] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[25] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1931,7 +1977,7 @@ func (x *IdentityAuthenticateRequest) String() string { func (*IdentityAuthenticateRequest) ProtoMessage() {} func (x *IdentityAuthenticateRequest) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[24] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[25] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1944,7 +1990,7 @@ func (x *IdentityAuthenticateRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use IdentityAuthenticateRequest.ProtoReflect.Descriptor instead. func (*IdentityAuthenticateRequest) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{24} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{25} } func (x *IdentityAuthenticateRequest) GetIdentity() *IdentityRequest { @@ -1971,7 +2017,7 @@ type IdentityPrepareRequest struct { func (x *IdentityPrepareRequest) Reset() { *x = IdentityPrepareRequest{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[25] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[26] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1983,7 +2029,7 @@ func (x *IdentityPrepareRequest) String() string { func (*IdentityPrepareRequest) ProtoMessage() {} func (x *IdentityPrepareRequest) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[25] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[26] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1996,7 +2042,7 @@ func (x *IdentityPrepareRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use IdentityPrepareRequest.ProtoReflect.Descriptor instead. func (*IdentityPrepareRequest) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{25} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{26} } func (x *IdentityPrepareRequest) GetIdentity() *IdentityRequest { @@ -2026,7 +2072,7 @@ type CommandRequest struct { func (x *CommandRequest) Reset() { *x = CommandRequest{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[26] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[27] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2038,7 +2084,7 @@ func (x *CommandRequest) String() string { func (*CommandRequest) ProtoMessage() {} func (x *CommandRequest) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[26] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[27] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2051,7 +2097,7 @@ func (x *CommandRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use CommandRequest.ProtoReflect.Descriptor instead. func (*CommandRequest) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{26} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{27} } func (x *CommandRequest) GetInvocation() *Invocation { @@ -2091,7 +2137,7 @@ type CommandExit struct { func (x *CommandExit) Reset() { *x = CommandExit{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[27] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[28] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2103,7 +2149,7 @@ func (x *CommandExit) String() string { func (*CommandExit) ProtoMessage() {} func (x *CommandExit) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[27] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[28] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2116,7 +2162,7 @@ func (x *CommandExit) ProtoReflect() protoreflect.Message { // Deprecated: Use CommandExit.ProtoReflect.Descriptor instead. func (*CommandExit) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{27} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{28} } func (x *CommandExit) GetCode() uint32 { @@ -2140,7 +2186,7 @@ type CommandEvent struct { func (x *CommandEvent) Reset() { *x = CommandEvent{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[28] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[29] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2152,7 +2198,7 @@ func (x *CommandEvent) String() string { func (*CommandEvent) ProtoMessage() {} func (x *CommandEvent) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[28] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[29] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2165,7 +2211,7 @@ func (x *CommandEvent) ProtoReflect() protoreflect.Message { // Deprecated: Use CommandEvent.ProtoReflect.Descriptor instead. func (*CommandEvent) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{28} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{29} } func (x *CommandEvent) GetEvent() isCommandEvent_Event { @@ -2239,7 +2285,7 @@ type ComponentValue struct { func (x *ComponentValue) Reset() { *x = ComponentValue{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[29] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[30] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2251,7 +2297,7 @@ func (x *ComponentValue) String() string { func (*ComponentValue) ProtoMessage() {} func (x *ComponentValue) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[29] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[30] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2264,7 +2310,7 @@ func (x *ComponentValue) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentValue.ProtoReflect.Descriptor instead. func (*ComponentValue) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{29} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{30} } func (x *ComponentValue) GetTypeJson() []byte { @@ -2297,7 +2343,7 @@ type ComponentValuePath struct { func (x *ComponentValuePath) Reset() { *x = ComponentValuePath{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[30] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[31] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2309,7 +2355,7 @@ func (x *ComponentValuePath) String() string { func (*ComponentValuePath) ProtoMessage() {} func (x *ComponentValuePath) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[30] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[31] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2322,7 +2368,7 @@ func (x *ComponentValuePath) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentValuePath.ProtoReflect.Descriptor instead. func (*ComponentValuePath) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{30} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{31} } func (x *ComponentValuePath) GetSteps() []*ComponentValueStep { @@ -2345,7 +2391,7 @@ type ComponentValueStep struct { func (x *ComponentValueStep) Reset() { *x = ComponentValueStep{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[31] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[32] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2357,7 +2403,7 @@ func (x *ComponentValueStep) String() string { func (*ComponentValueStep) ProtoMessage() {} func (x *ComponentValueStep) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[31] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[32] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2370,7 +2416,7 @@ func (x *ComponentValueStep) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentValueStep.ProtoReflect.Descriptor instead. func (*ComponentValueStep) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{31} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{32} } func (x *ComponentValueStep) GetSelector() isComponentValueStep_Selector { @@ -2427,7 +2473,7 @@ type ComponentAddress struct { func (x *ComponentAddress) Reset() { *x = ComponentAddress{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[32] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[33] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2439,7 +2485,7 @@ func (x *ComponentAddress) String() string { func (*ComponentAddress) ProtoMessage() {} func (x *ComponentAddress) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[32] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[33] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2452,7 +2498,7 @@ func (x *ComponentAddress) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentAddress.ProtoReflect.Descriptor instead. func (*ComponentAddress) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{32} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{33} } func (x *ComponentAddress) GetStack() string { @@ -2489,7 +2535,7 @@ type ComponentSource struct { func (x *ComponentSource) Reset() { *x = ComponentSource{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[33] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[34] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2501,7 +2547,7 @@ func (x *ComponentSource) String() string { func (*ComponentSource) ProtoMessage() {} func (x *ComponentSource) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[33] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[34] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2514,7 +2560,7 @@ func (x *ComponentSource) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentSource.ProtoReflect.Descriptor instead. func (*ComponentSource) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{33} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{34} } func (x *ComponentSource) GetPath() string { @@ -2548,7 +2594,7 @@ type ComponentDependency struct { func (x *ComponentDependency) Reset() { *x = ComponentDependency{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[34] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[35] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2560,7 +2606,7 @@ func (x *ComponentDependency) String() string { func (*ComponentDependency) ProtoMessage() {} func (x *ComponentDependency) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[34] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[35] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2573,7 +2619,7 @@ func (x *ComponentDependency) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentDependency.ProtoReflect.Descriptor instead. func (*ComponentDependency) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{34} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{35} } func (x *ComponentDependency) GetTarget() *ComponentAddress { @@ -2605,7 +2651,7 @@ type DiscoveredComponent struct { func (x *DiscoveredComponent) Reset() { *x = DiscoveredComponent{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[35] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[36] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2617,7 +2663,7 @@ func (x *DiscoveredComponent) String() string { func (*DiscoveredComponent) ProtoMessage() {} func (x *DiscoveredComponent) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[35] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[36] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2630,7 +2676,7 @@ func (x *DiscoveredComponent) ProtoReflect() protoreflect.Message { // Deprecated: Use DiscoveredComponent.ProtoReflect.Descriptor instead. func (*DiscoveredComponent) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{35} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{36} } func (x *DiscoveredComponent) GetAddress() *ComponentAddress { @@ -2697,7 +2743,7 @@ type ComponentEffects struct { func (x *ComponentEffects) Reset() { *x = ComponentEffects{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[36] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[37] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2709,7 +2755,7 @@ func (x *ComponentEffects) String() string { func (*ComponentEffects) ProtoMessage() {} func (x *ComponentEffects) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[36] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[37] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2722,7 +2768,7 @@ func (x *ComponentEffects) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentEffects.ProtoReflect.Descriptor instead. func (*ComponentEffects) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{36} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{37} } func (x *ComponentEffects) GetCommands() bool { @@ -2777,7 +2823,7 @@ type ComponentOperation struct { func (x *ComponentOperation) Reset() { *x = ComponentOperation{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[37] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[38] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2789,7 +2835,7 @@ func (x *ComponentOperation) String() string { func (*ComponentOperation) ProtoMessage() {} func (x *ComponentOperation) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[37] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[38] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2802,7 +2848,7 @@ func (x *ComponentOperation) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentOperation.ProtoReflect.Descriptor instead. func (*ComponentOperation) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{37} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{38} } func (x *ComponentOperation) GetCommand() string { @@ -2853,7 +2899,7 @@ type DiscoverComponentsRequest struct { func (x *DiscoverComponentsRequest) Reset() { *x = DiscoverComponentsRequest{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[38] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[39] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2865,7 +2911,7 @@ func (x *DiscoverComponentsRequest) String() string { func (*DiscoverComponentsRequest) ProtoMessage() {} func (x *DiscoverComponentsRequest) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[38] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[39] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2878,7 +2924,7 @@ func (x *DiscoverComponentsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DiscoverComponentsRequest.ProtoReflect.Descriptor instead. func (*DiscoverComponentsRequest) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{38} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{39} } func (x *DiscoverComponentsRequest) GetInvocation() *Invocation { @@ -2967,7 +3013,7 @@ type DiscoverComponentsResponse struct { func (x *DiscoverComponentsResponse) Reset() { *x = DiscoverComponentsResponse{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[39] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[40] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2979,7 +3025,7 @@ func (x *DiscoverComponentsResponse) String() string { func (*DiscoverComponentsResponse) ProtoMessage() {} func (x *DiscoverComponentsResponse) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[39] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[40] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2992,7 +3038,7 @@ func (x *DiscoverComponentsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use DiscoverComponentsResponse.ProtoReflect.Descriptor instead. func (*DiscoverComponentsResponse) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{39} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{40} } func (x *DiscoverComponentsResponse) GetComponents() []*DiscoveredComponent { @@ -3033,7 +3079,7 @@ type ComponentRequest struct { func (x *ComponentRequest) Reset() { *x = ComponentRequest{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[40] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[41] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3045,7 +3091,7 @@ func (x *ComponentRequest) String() string { func (*ComponentRequest) ProtoMessage() {} func (x *ComponentRequest) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[40] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[41] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3058,7 +3104,7 @@ func (x *ComponentRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentRequest.ProtoReflect.Descriptor instead. func (*ComponentRequest) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{40} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{41} } func (x *ComponentRequest) GetInvocation() *Invocation { @@ -3138,7 +3184,7 @@ type ComponentStateIdentity struct { func (x *ComponentStateIdentity) Reset() { *x = ComponentStateIdentity{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[41] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[42] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3150,7 +3196,7 @@ func (x *ComponentStateIdentity) String() string { func (*ComponentStateIdentity) ProtoMessage() {} func (x *ComponentStateIdentity) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[41] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[42] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3163,7 +3209,7 @@ func (x *ComponentStateIdentity) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentStateIdentity.ProtoReflect.Descriptor instead. func (*ComponentStateIdentity) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{41} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{42} } func (x *ComponentStateIdentity) GetBackendType() string { @@ -3208,7 +3254,7 @@ type ComponentGeneratedFile struct { func (x *ComponentGeneratedFile) Reset() { *x = ComponentGeneratedFile{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[42] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[43] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3220,7 +3266,7 @@ func (x *ComponentGeneratedFile) String() string { func (*ComponentGeneratedFile) ProtoMessage() {} func (x *ComponentGeneratedFile) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[42] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[43] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3233,7 +3279,7 @@ func (x *ComponentGeneratedFile) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentGeneratedFile.ProtoReflect.Descriptor instead. func (*ComponentGeneratedFile) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{42} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{43} } func (x *ComponentGeneratedFile) GetPath() string { @@ -3278,7 +3324,7 @@ type ComponentExecutionConfiguration struct { func (x *ComponentExecutionConfiguration) Reset() { *x = ComponentExecutionConfiguration{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[43] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[44] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3290,7 +3336,7 @@ func (x *ComponentExecutionConfiguration) String() string { func (*ComponentExecutionConfiguration) ProtoMessage() {} func (x *ComponentExecutionConfiguration) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[43] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[44] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3303,7 +3349,7 @@ func (x *ComponentExecutionConfiguration) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentExecutionConfiguration.ProtoReflect.Descriptor instead. func (*ComponentExecutionConfiguration) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{43} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{44} } func (x *ComponentExecutionConfiguration) GetExtraArguments() []*ComponentExtraArguments { @@ -3347,7 +3393,7 @@ type ComponentExtraArguments struct { func (x *ComponentExtraArguments) Reset() { *x = ComponentExtraArguments{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[44] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[45] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3359,7 +3405,7 @@ func (x *ComponentExtraArguments) String() string { func (*ComponentExtraArguments) ProtoMessage() {} func (x *ComponentExtraArguments) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[44] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[45] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3372,7 +3418,7 @@ func (x *ComponentExtraArguments) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentExtraArguments.ProtoReflect.Descriptor instead. func (*ComponentExtraArguments) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{44} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{45} } func (x *ComponentExtraArguments) GetCommands() []string { @@ -3427,7 +3473,7 @@ type ComponentHook struct { func (x *ComponentHook) Reset() { *x = ComponentHook{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[45] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[46] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3439,7 +3485,7 @@ func (x *ComponentHook) String() string { func (*ComponentHook) ProtoMessage() {} func (x *ComponentHook) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[45] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[46] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3452,7 +3498,7 @@ func (x *ComponentHook) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentHook.ProtoReflect.Descriptor instead. func (*ComponentHook) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{45} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{46} } func (x *ComponentHook) GetName() string { @@ -3555,7 +3601,7 @@ type PrepareComponentResponse struct { func (x *PrepareComponentResponse) Reset() { *x = PrepareComponentResponse{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[46] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[47] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3567,7 +3613,7 @@ func (x *PrepareComponentResponse) String() string { func (*PrepareComponentResponse) ProtoMessage() {} func (x *PrepareComponentResponse) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[46] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[47] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3580,7 +3626,7 @@ func (x *PrepareComponentResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use PrepareComponentResponse.ProtoReflect.Descriptor instead. func (*PrepareComponentResponse) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{46} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{47} } func (x *PrepareComponentResponse) GetEngine() string { @@ -3728,7 +3774,7 @@ type ComponentErrorsConfiguration struct { func (x *ComponentErrorsConfiguration) Reset() { *x = ComponentErrorsConfiguration{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[47] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[48] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3740,7 +3786,7 @@ func (x *ComponentErrorsConfiguration) String() string { func (*ComponentErrorsConfiguration) ProtoMessage() {} func (x *ComponentErrorsConfiguration) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[47] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[48] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3753,7 +3799,7 @@ func (x *ComponentErrorsConfiguration) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentErrorsConfiguration.ProtoReflect.Descriptor instead. func (*ComponentErrorsConfiguration) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{47} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{48} } func (x *ComponentErrorsConfiguration) GetRetry() []*ComponentRetryPolicy { @@ -3783,7 +3829,7 @@ type ComponentRetryPolicy struct { func (x *ComponentRetryPolicy) Reset() { *x = ComponentRetryPolicy{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[48] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[49] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3795,7 +3841,7 @@ func (x *ComponentRetryPolicy) String() string { func (*ComponentRetryPolicy) ProtoMessage() {} func (x *ComponentRetryPolicy) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[48] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[49] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3808,7 +3854,7 @@ func (x *ComponentRetryPolicy) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentRetryPolicy.ProtoReflect.Descriptor instead. func (*ComponentRetryPolicy) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{48} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{49} } func (x *ComponentRetryPolicy) GetName() string { @@ -3853,7 +3899,7 @@ type ComponentIgnorePolicy struct { func (x *ComponentIgnorePolicy) Reset() { *x = ComponentIgnorePolicy{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[49] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[50] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3865,7 +3911,7 @@ func (x *ComponentIgnorePolicy) String() string { func (*ComponentIgnorePolicy) ProtoMessage() {} func (x *ComponentIgnorePolicy) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[49] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[50] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3878,7 +3924,7 @@ func (x *ComponentIgnorePolicy) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentIgnorePolicy.ProtoReflect.Descriptor instead. func (*ComponentIgnorePolicy) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{49} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{50} } func (x *ComponentIgnorePolicy) GetName() string { @@ -3926,7 +3972,7 @@ type ComponentExclude struct { func (x *ComponentExclude) Reset() { *x = ComponentExclude{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[50] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[51] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3938,7 +3984,7 @@ func (x *ComponentExclude) String() string { func (*ComponentExclude) ProtoMessage() {} func (x *ComponentExclude) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[50] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[51] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3951,7 +3997,7 @@ func (x *ComponentExclude) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentExclude.ProtoReflect.Descriptor instead. func (*ComponentExclude) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{50} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{51} } func (x *ComponentExclude) GetCondition() bool { @@ -3990,7 +4036,7 @@ type ComponentIam struct { func (x *ComponentIam) Reset() { *x = ComponentIam{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[51] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[52] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4002,7 +4048,7 @@ func (x *ComponentIam) String() string { func (*ComponentIam) ProtoMessage() {} func (x *ComponentIam) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[51] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[52] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4015,7 +4061,7 @@ func (x *ComponentIam) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentIam.ProtoReflect.Descriptor instead. func (*ComponentIam) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{51} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{52} } func (x *ComponentIam) GetRole() string { @@ -4059,7 +4105,7 @@ type ResolveComponentStateResponse struct { func (x *ResolveComponentStateResponse) Reset() { *x = ResolveComponentStateResponse{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[52] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[53] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4071,7 +4117,7 @@ func (x *ResolveComponentStateResponse) String() string { func (*ResolveComponentStateResponse) ProtoMessage() {} func (x *ResolveComponentStateResponse) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[52] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[53] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4084,7 +4130,7 @@ func (x *ResolveComponentStateResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ResolveComponentStateResponse.ProtoReflect.Descriptor instead. func (*ResolveComponentStateResponse) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{52} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{53} } func (x *ResolveComponentStateResponse) GetState() *ComponentStateIdentity { @@ -4213,7 +4259,10 @@ const file_atmos_plugin_v1_plugin_proto_rawDesc = "" + "\x04unit\x18\x05 \x01(\tR\x04unit\x1a9\n" + "\vFieldsEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + - "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\x90\x03\n" + + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"A\n" + + "\n" + + "LogRequest\x123\n" + + "\aentries\x18\x01 \x03(\v2\x19.atmos.plugin.v1.LogEntryR\aentries\"\x90\x03\n" + "\vErrorDetail\x12\x12\n" + "\x04code\x18\x01 \x01(\tR\x04code\x12\x18\n" + "\asummary\x18\x02 \x01(\tR\asummary\x12\x16\n" + @@ -4482,7 +4531,9 @@ const file_atmos_plugin_v1_plugin_proto_rawDesc = "" + "\x10SEVERITY_WARNING\x10\x022\x9f\x01\n" + "\x04Info\x12O\n" + "\bDescribe\x12 .atmos.plugin.v1.DescribeRequest\x1a!.atmos.plugin.v1.DescribeResponse\x12F\n" + - "\tConfigure\x12!.atmos.plugin.v1.ConfigureRequest\x1a\x16.google.protobuf.Empty2\xd3\x04\n" + + "\tConfigure\x12!.atmos.plugin.v1.ConfigureRequest\x1a\x16.google.protobuf.Empty2C\n" + + "\x03Log\x12<\n" + + "\x05Write\x12\x1b.atmos.plugin.v1.LogRequest\x1a\x16.google.protobuf.Empty2\xd3\x04\n" + "\fAuthProvider\x12O\n" + "\bValidate\x12 .atmos.plugin.v1.ProviderRequest\x1a!.atmos.plugin.v1.ValidateResponse\x12V\n" + "\fAuthenticate\x12 .atmos.plugin.v1.ProviderRequest\x1a\".atmos.plugin.v1.AuthenticateEvent0\x01\x12L\n" + @@ -4523,7 +4574,7 @@ func file_atmos_plugin_v1_plugin_proto_rawDescGZIP() []byte { var ( file_atmos_plugin_v1_plugin_proto_enumTypes = make([]protoimpl.EnumInfo, 4) - file_atmos_plugin_v1_plugin_proto_msgTypes = make([]protoimpl.MessageInfo, 65) + file_atmos_plugin_v1_plugin_proto_msgTypes = make([]protoimpl.MessageInfo, 66) file_atmos_plugin_v1_plugin_proto_goTypes = []any{ LogLevel(0), // 0: atmos.plugin.v1.LogLevel Severity(0), // 1: atmos.plugin.v1.Severity @@ -4543,205 +4594,209 @@ var ( (*AuthenticateEvent)(nil), // 15: atmos.plugin.v1.AuthenticateEvent (*SourceLocation)(nil), // 16: atmos.plugin.v1.SourceLocation (*LogEntry)(nil), // 17: atmos.plugin.v1.LogEntry - (*ErrorDetail)(nil), // 18: atmos.plugin.v1.ErrorDetail - (*Diagnostic)(nil), // 19: atmos.plugin.v1.Diagnostic - (*ValidateResponse)(nil), // 20: atmos.plugin.v1.ValidateResponse - (*Unsupported)(nil), // 21: atmos.plugin.v1.Unsupported - (*RefreshRequest)(nil), // 22: atmos.plugin.v1.RefreshRequest - (*RefreshResponse)(nil), // 23: atmos.plugin.v1.RefreshResponse - (*EnvironmentResponse)(nil), // 24: atmos.plugin.v1.EnvironmentResponse - (*PrepareEnvironmentRequest)(nil), // 25: atmos.plugin.v1.PrepareEnvironmentRequest - (*CredentialPath)(nil), // 26: atmos.plugin.v1.CredentialPath - (*PathsResponse)(nil), // 27: atmos.plugin.v1.PathsResponse - (*IdentityAuthenticateRequest)(nil), // 28: atmos.plugin.v1.IdentityAuthenticateRequest - (*IdentityPrepareRequest)(nil), // 29: atmos.plugin.v1.IdentityPrepareRequest - (*CommandRequest)(nil), // 30: atmos.plugin.v1.CommandRequest - (*CommandExit)(nil), // 31: atmos.plugin.v1.CommandExit - (*CommandEvent)(nil), // 32: atmos.plugin.v1.CommandEvent - (*ComponentValue)(nil), // 33: atmos.plugin.v1.ComponentValue - (*ComponentValuePath)(nil), // 34: atmos.plugin.v1.ComponentValuePath - (*ComponentValueStep)(nil), // 35: atmos.plugin.v1.ComponentValueStep - (*ComponentAddress)(nil), // 36: atmos.plugin.v1.ComponentAddress - (*ComponentSource)(nil), // 37: atmos.plugin.v1.ComponentSource - (*ComponentDependency)(nil), // 38: atmos.plugin.v1.ComponentDependency - (*DiscoveredComponent)(nil), // 39: atmos.plugin.v1.DiscoveredComponent - (*ComponentEffects)(nil), // 40: atmos.plugin.v1.ComponentEffects - (*ComponentOperation)(nil), // 41: atmos.plugin.v1.ComponentOperation - (*DiscoverComponentsRequest)(nil), // 42: atmos.plugin.v1.DiscoverComponentsRequest - (*DiscoverComponentsResponse)(nil), // 43: atmos.plugin.v1.DiscoverComponentsResponse - (*ComponentRequest)(nil), // 44: atmos.plugin.v1.ComponentRequest - (*ComponentStateIdentity)(nil), // 45: atmos.plugin.v1.ComponentStateIdentity - (*ComponentGeneratedFile)(nil), // 46: atmos.plugin.v1.ComponentGeneratedFile - (*ComponentExecutionConfiguration)(nil), // 47: atmos.plugin.v1.ComponentExecutionConfiguration - (*ComponentExtraArguments)(nil), // 48: atmos.plugin.v1.ComponentExtraArguments - (*ComponentHook)(nil), // 49: atmos.plugin.v1.ComponentHook - (*PrepareComponentResponse)(nil), // 50: atmos.plugin.v1.PrepareComponentResponse - (*ComponentErrorsConfiguration)(nil), // 51: atmos.plugin.v1.ComponentErrorsConfiguration - (*ComponentRetryPolicy)(nil), // 52: atmos.plugin.v1.ComponentRetryPolicy - (*ComponentIgnorePolicy)(nil), // 53: atmos.plugin.v1.ComponentIgnorePolicy - (*ComponentExclude)(nil), // 54: atmos.plugin.v1.ComponentExclude - (*ComponentIam)(nil), // 55: atmos.plugin.v1.ComponentIam - (*ResolveComponentStateResponse)(nil), // 56: atmos.plugin.v1.ResolveComponentStateResponse - nil, // 57: atmos.plugin.v1.Invocation.EnvironmentEntry - nil, // 58: atmos.plugin.v1.ConfigureRequest.BrokerIdsEntry - nil, // 59: atmos.plugin.v1.Interaction.FieldsEntry - nil, // 60: atmos.plugin.v1.LogEntry.FieldsEntry - nil, // 61: atmos.plugin.v1.EnvironmentResponse.EnvironmentEntry - nil, // 62: atmos.plugin.v1.PrepareEnvironmentRequest.EnvironmentEntry - nil, // 63: atmos.plugin.v1.IdentityPrepareRequest.EnvironmentEntry - nil, // 64: atmos.plugin.v1.ComponentOperation.OptionsEntry - nil, // 65: atmos.plugin.v1.ComponentExtraArguments.EnvironmentEntry - nil, // 66: atmos.plugin.v1.PrepareComponentResponse.InputOriginsEntry - nil, // 67: atmos.plugin.v1.PrepareComponentResponse.FeatureFlagsEntry - nil, // 68: atmos.plugin.v1.ComponentIgnorePolicy.SignalsEntry - (*timestamppb.Timestamp)(nil), // 69: google.protobuf.Timestamp - (*structpb.Struct)(nil), // 70: google.protobuf.Struct - (*emptypb.Empty)(nil), // 71: google.protobuf.Empty + (*LogRequest)(nil), // 18: atmos.plugin.v1.LogRequest + (*ErrorDetail)(nil), // 19: atmos.plugin.v1.ErrorDetail + (*Diagnostic)(nil), // 20: atmos.plugin.v1.Diagnostic + (*ValidateResponse)(nil), // 21: atmos.plugin.v1.ValidateResponse + (*Unsupported)(nil), // 22: atmos.plugin.v1.Unsupported + (*RefreshRequest)(nil), // 23: atmos.plugin.v1.RefreshRequest + (*RefreshResponse)(nil), // 24: atmos.plugin.v1.RefreshResponse + (*EnvironmentResponse)(nil), // 25: atmos.plugin.v1.EnvironmentResponse + (*PrepareEnvironmentRequest)(nil), // 26: atmos.plugin.v1.PrepareEnvironmentRequest + (*CredentialPath)(nil), // 27: atmos.plugin.v1.CredentialPath + (*PathsResponse)(nil), // 28: atmos.plugin.v1.PathsResponse + (*IdentityAuthenticateRequest)(nil), // 29: atmos.plugin.v1.IdentityAuthenticateRequest + (*IdentityPrepareRequest)(nil), // 30: atmos.plugin.v1.IdentityPrepareRequest + (*CommandRequest)(nil), // 31: atmos.plugin.v1.CommandRequest + (*CommandExit)(nil), // 32: atmos.plugin.v1.CommandExit + (*CommandEvent)(nil), // 33: atmos.plugin.v1.CommandEvent + (*ComponentValue)(nil), // 34: atmos.plugin.v1.ComponentValue + (*ComponentValuePath)(nil), // 35: atmos.plugin.v1.ComponentValuePath + (*ComponentValueStep)(nil), // 36: atmos.plugin.v1.ComponentValueStep + (*ComponentAddress)(nil), // 37: atmos.plugin.v1.ComponentAddress + (*ComponentSource)(nil), // 38: atmos.plugin.v1.ComponentSource + (*ComponentDependency)(nil), // 39: atmos.plugin.v1.ComponentDependency + (*DiscoveredComponent)(nil), // 40: atmos.plugin.v1.DiscoveredComponent + (*ComponentEffects)(nil), // 41: atmos.plugin.v1.ComponentEffects + (*ComponentOperation)(nil), // 42: atmos.plugin.v1.ComponentOperation + (*DiscoverComponentsRequest)(nil), // 43: atmos.plugin.v1.DiscoverComponentsRequest + (*DiscoverComponentsResponse)(nil), // 44: atmos.plugin.v1.DiscoverComponentsResponse + (*ComponentRequest)(nil), // 45: atmos.plugin.v1.ComponentRequest + (*ComponentStateIdentity)(nil), // 46: atmos.plugin.v1.ComponentStateIdentity + (*ComponentGeneratedFile)(nil), // 47: atmos.plugin.v1.ComponentGeneratedFile + (*ComponentExecutionConfiguration)(nil), // 48: atmos.plugin.v1.ComponentExecutionConfiguration + (*ComponentExtraArguments)(nil), // 49: atmos.plugin.v1.ComponentExtraArguments + (*ComponentHook)(nil), // 50: atmos.plugin.v1.ComponentHook + (*PrepareComponentResponse)(nil), // 51: atmos.plugin.v1.PrepareComponentResponse + (*ComponentErrorsConfiguration)(nil), // 52: atmos.plugin.v1.ComponentErrorsConfiguration + (*ComponentRetryPolicy)(nil), // 53: atmos.plugin.v1.ComponentRetryPolicy + (*ComponentIgnorePolicy)(nil), // 54: atmos.plugin.v1.ComponentIgnorePolicy + (*ComponentExclude)(nil), // 55: atmos.plugin.v1.ComponentExclude + (*ComponentIam)(nil), // 56: atmos.plugin.v1.ComponentIam + (*ResolveComponentStateResponse)(nil), // 57: atmos.plugin.v1.ResolveComponentStateResponse + nil, // 58: atmos.plugin.v1.Invocation.EnvironmentEntry + nil, // 59: atmos.plugin.v1.ConfigureRequest.BrokerIdsEntry + nil, // 60: atmos.plugin.v1.Interaction.FieldsEntry + nil, // 61: atmos.plugin.v1.LogEntry.FieldsEntry + nil, // 62: atmos.plugin.v1.EnvironmentResponse.EnvironmentEntry + nil, // 63: atmos.plugin.v1.PrepareEnvironmentRequest.EnvironmentEntry + nil, // 64: atmos.plugin.v1.IdentityPrepareRequest.EnvironmentEntry + nil, // 65: atmos.plugin.v1.ComponentOperation.OptionsEntry + nil, // 66: atmos.plugin.v1.ComponentExtraArguments.EnvironmentEntry + nil, // 67: atmos.plugin.v1.PrepareComponentResponse.InputOriginsEntry + nil, // 68: atmos.plugin.v1.PrepareComponentResponse.FeatureFlagsEntry + nil, // 69: atmos.plugin.v1.ComponentIgnorePolicy.SignalsEntry + (*timestamppb.Timestamp)(nil), // 70: google.protobuf.Timestamp + (*structpb.Struct)(nil), // 71: google.protobuf.Struct + (*emptypb.Empty)(nil), // 72: google.protobuf.Empty } ) var file_atmos_plugin_v1_plugin_proto_depIdxs = []int32{ - 69, // 0: atmos.plugin.v1.Invocation.deadline:type_name -> google.protobuf.Timestamp - 57, // 1: atmos.plugin.v1.Invocation.environment:type_name -> atmos.plugin.v1.Invocation.EnvironmentEntry - 69, // 2: atmos.plugin.v1.Credentials.expires_at:type_name -> google.protobuf.Timestamp - 70, // 3: atmos.plugin.v1.Credentials.data:type_name -> google.protobuf.Struct + 70, // 0: atmos.plugin.v1.Invocation.deadline:type_name -> google.protobuf.Timestamp + 58, // 1: atmos.plugin.v1.Invocation.environment:type_name -> atmos.plugin.v1.Invocation.EnvironmentEntry + 70, // 2: atmos.plugin.v1.Credentials.expires_at:type_name -> google.protobuf.Timestamp + 71, // 3: atmos.plugin.v1.Credentials.data:type_name -> google.protobuf.Struct 6, // 4: atmos.plugin.v1.DescribeRequest.host_supported:type_name -> atmos.plugin.v1.ServiceVersionRange 6, // 5: atmos.plugin.v1.DescribeResponse.services:type_name -> atmos.plugin.v1.ServiceVersionRange 7, // 6: atmos.plugin.v1.DescribeResponse.exports:type_name -> atmos.plugin.v1.Export - 58, // 7: atmos.plugin.v1.ConfigureRequest.broker_ids:type_name -> atmos.plugin.v1.ConfigureRequest.BrokerIdsEntry - 70, // 8: atmos.plugin.v1.ConfigureRequest.settings:type_name -> google.protobuf.Struct + 59, // 7: atmos.plugin.v1.ConfigureRequest.broker_ids:type_name -> atmos.plugin.v1.ConfigureRequest.BrokerIdsEntry + 71, // 8: atmos.plugin.v1.ConfigureRequest.settings:type_name -> google.protobuf.Struct 4, // 9: atmos.plugin.v1.ProviderRequest.invocation:type_name -> atmos.plugin.v1.Invocation - 70, // 10: atmos.plugin.v1.ProviderRequest.spec:type_name -> google.protobuf.Struct + 71, // 10: atmos.plugin.v1.ProviderRequest.spec:type_name -> google.protobuf.Struct 4, // 11: atmos.plugin.v1.IdentityRequest.invocation:type_name -> atmos.plugin.v1.Invocation - 70, // 12: atmos.plugin.v1.IdentityRequest.spec:type_name -> google.protobuf.Struct - 70, // 13: atmos.plugin.v1.IdentityRequest.principal:type_name -> google.protobuf.Struct - 59, // 14: atmos.plugin.v1.Interaction.fields:type_name -> atmos.plugin.v1.Interaction.FieldsEntry + 71, // 12: atmos.plugin.v1.IdentityRequest.spec:type_name -> google.protobuf.Struct + 71, // 13: atmos.plugin.v1.IdentityRequest.principal:type_name -> google.protobuf.Struct + 60, // 14: atmos.plugin.v1.Interaction.fields:type_name -> atmos.plugin.v1.Interaction.FieldsEntry 13, // 15: atmos.plugin.v1.AuthenticateEvent.progress:type_name -> atmos.plugin.v1.Progress 14, // 16: atmos.plugin.v1.AuthenticateEvent.interaction:type_name -> atmos.plugin.v1.Interaction 5, // 17: atmos.plugin.v1.AuthenticateEvent.result:type_name -> atmos.plugin.v1.Credentials 0, // 18: atmos.plugin.v1.LogEntry.level:type_name -> atmos.plugin.v1.LogLevel - 60, // 19: atmos.plugin.v1.LogEntry.fields:type_name -> atmos.plugin.v1.LogEntry.FieldsEntry - 69, // 20: atmos.plugin.v1.LogEntry.time:type_name -> google.protobuf.Timestamp - 16, // 21: atmos.plugin.v1.ErrorDetail.location:type_name -> atmos.plugin.v1.SourceLocation - 1, // 22: atmos.plugin.v1.ErrorDetail.severity:type_name -> atmos.plugin.v1.Severity - 17, // 23: atmos.plugin.v1.ErrorDetail.logs:type_name -> atmos.plugin.v1.LogEntry - 18, // 24: atmos.plugin.v1.Diagnostic.detail:type_name -> atmos.plugin.v1.ErrorDetail - 19, // 25: atmos.plugin.v1.ValidateResponse.diagnostics:type_name -> atmos.plugin.v1.Diagnostic - 11, // 26: atmos.plugin.v1.RefreshRequest.provider:type_name -> atmos.plugin.v1.ProviderRequest - 5, // 27: atmos.plugin.v1.RefreshRequest.current:type_name -> atmos.plugin.v1.Credentials - 5, // 28: atmos.plugin.v1.RefreshResponse.credentials:type_name -> atmos.plugin.v1.Credentials - 21, // 29: atmos.plugin.v1.RefreshResponse.unsupported:type_name -> atmos.plugin.v1.Unsupported - 61, // 30: atmos.plugin.v1.EnvironmentResponse.environment:type_name -> atmos.plugin.v1.EnvironmentResponse.EnvironmentEntry - 11, // 31: atmos.plugin.v1.PrepareEnvironmentRequest.provider:type_name -> atmos.plugin.v1.ProviderRequest - 62, // 32: atmos.plugin.v1.PrepareEnvironmentRequest.environment:type_name -> atmos.plugin.v1.PrepareEnvironmentRequest.EnvironmentEntry - 26, // 33: atmos.plugin.v1.PathsResponse.paths:type_name -> atmos.plugin.v1.CredentialPath - 12, // 34: atmos.plugin.v1.IdentityAuthenticateRequest.identity:type_name -> atmos.plugin.v1.IdentityRequest - 5, // 35: atmos.plugin.v1.IdentityAuthenticateRequest.upstream:type_name -> atmos.plugin.v1.Credentials - 12, // 36: atmos.plugin.v1.IdentityPrepareRequest.identity:type_name -> atmos.plugin.v1.IdentityRequest - 63, // 37: atmos.plugin.v1.IdentityPrepareRequest.environment:type_name -> atmos.plugin.v1.IdentityPrepareRequest.EnvironmentEntry - 4, // 38: atmos.plugin.v1.CommandRequest.invocation:type_name -> atmos.plugin.v1.Invocation - 70, // 39: atmos.plugin.v1.CommandRequest.settings:type_name -> google.protobuf.Struct - 31, // 40: atmos.plugin.v1.CommandEvent.exit:type_name -> atmos.plugin.v1.CommandExit - 34, // 41: atmos.plugin.v1.ComponentValue.sensitive_paths:type_name -> atmos.plugin.v1.ComponentValuePath - 35, // 42: atmos.plugin.v1.ComponentValuePath.steps:type_name -> atmos.plugin.v1.ComponentValueStep - 33, // 43: atmos.plugin.v1.ComponentValueStep.index:type_name -> atmos.plugin.v1.ComponentValue - 2, // 44: atmos.plugin.v1.ComponentSource.kind:type_name -> atmos.plugin.v1.ComponentSource.Kind - 36, // 45: atmos.plugin.v1.ComponentDependency.target:type_name -> atmos.plugin.v1.ComponentAddress - 3, // 46: atmos.plugin.v1.ComponentDependency.kind:type_name -> atmos.plugin.v1.ComponentDependency.Kind - 36, // 47: atmos.plugin.v1.DiscoveredComponent.address:type_name -> atmos.plugin.v1.ComponentAddress - 33, // 48: atmos.plugin.v1.DiscoveredComponent.configuration:type_name -> atmos.plugin.v1.ComponentValue - 37, // 49: atmos.plugin.v1.DiscoveredComponent.sources:type_name -> atmos.plugin.v1.ComponentSource - 38, // 50: atmos.plugin.v1.DiscoveredComponent.dependencies:type_name -> atmos.plugin.v1.ComponentDependency - 64, // 51: atmos.plugin.v1.ComponentOperation.options:type_name -> atmos.plugin.v1.ComponentOperation.OptionsEntry - 4, // 52: atmos.plugin.v1.DiscoverComponentsRequest.invocation:type_name -> atmos.plugin.v1.Invocation - 41, // 53: atmos.plugin.v1.DiscoverComponentsRequest.operation:type_name -> atmos.plugin.v1.ComponentOperation - 40, // 54: atmos.plugin.v1.DiscoverComponentsRequest.effects:type_name -> atmos.plugin.v1.ComponentEffects - 33, // 55: atmos.plugin.v1.DiscoverComponentsRequest.provider_configuration:type_name -> atmos.plugin.v1.ComponentValue - 39, // 56: atmos.plugin.v1.DiscoverComponentsResponse.components:type_name -> atmos.plugin.v1.DiscoveredComponent - 19, // 57: atmos.plugin.v1.DiscoverComponentsResponse.diagnostics:type_name -> atmos.plugin.v1.Diagnostic - 17, // 58: atmos.plugin.v1.DiscoverComponentsResponse.logs:type_name -> atmos.plugin.v1.LogEntry - 4, // 59: atmos.plugin.v1.ComponentRequest.invocation:type_name -> atmos.plugin.v1.Invocation - 36, // 60: atmos.plugin.v1.ComponentRequest.address:type_name -> atmos.plugin.v1.ComponentAddress - 41, // 61: atmos.plugin.v1.ComponentRequest.operation:type_name -> atmos.plugin.v1.ComponentOperation - 40, // 62: atmos.plugin.v1.ComponentRequest.effects:type_name -> atmos.plugin.v1.ComponentEffects - 33, // 63: atmos.plugin.v1.ComponentRequest.configuration:type_name -> atmos.plugin.v1.ComponentValue - 33, // 64: atmos.plugin.v1.ComponentRequest.provider_configuration:type_name -> atmos.plugin.v1.ComponentValue - 33, // 65: atmos.plugin.v1.ComponentStateIdentity.backend:type_name -> atmos.plugin.v1.ComponentValue - 48, // 66: atmos.plugin.v1.ComponentExecutionConfiguration.extra_arguments:type_name -> atmos.plugin.v1.ComponentExtraArguments - 49, // 67: atmos.plugin.v1.ComponentExecutionConfiguration.before_hooks:type_name -> atmos.plugin.v1.ComponentHook - 49, // 68: atmos.plugin.v1.ComponentExecutionConfiguration.after_hooks:type_name -> atmos.plugin.v1.ComponentHook - 49, // 69: atmos.plugin.v1.ComponentExecutionConfiguration.error_hooks:type_name -> atmos.plugin.v1.ComponentHook - 65, // 70: atmos.plugin.v1.ComponentExtraArguments.environment:type_name -> atmos.plugin.v1.ComponentExtraArguments.EnvironmentEntry - 33, // 71: atmos.plugin.v1.PrepareComponentResponse.inputs:type_name -> atmos.plugin.v1.ComponentValue - 45, // 72: atmos.plugin.v1.PrepareComponentResponse.state:type_name -> atmos.plugin.v1.ComponentStateIdentity - 46, // 73: atmos.plugin.v1.PrepareComponentResponse.files:type_name -> atmos.plugin.v1.ComponentGeneratedFile - 38, // 74: atmos.plugin.v1.PrepareComponentResponse.dependencies:type_name -> atmos.plugin.v1.ComponentDependency - 37, // 75: atmos.plugin.v1.PrepareComponentResponse.sources:type_name -> atmos.plugin.v1.ComponentSource - 19, // 76: atmos.plugin.v1.PrepareComponentResponse.diagnostics:type_name -> atmos.plugin.v1.Diagnostic - 47, // 77: atmos.plugin.v1.PrepareComponentResponse.execution:type_name -> atmos.plugin.v1.ComponentExecutionConfiguration - 66, // 78: atmos.plugin.v1.PrepareComponentResponse.input_origins:type_name -> atmos.plugin.v1.PrepareComponentResponse.InputOriginsEntry - 51, // 79: atmos.plugin.v1.PrepareComponentResponse.errors:type_name -> atmos.plugin.v1.ComponentErrorsConfiguration - 54, // 80: atmos.plugin.v1.PrepareComponentResponse.exclude:type_name -> atmos.plugin.v1.ComponentExclude - 55, // 81: atmos.plugin.v1.PrepareComponentResponse.iam:type_name -> atmos.plugin.v1.ComponentIam - 33, // 82: atmos.plugin.v1.PrepareComponentResponse.encryption:type_name -> atmos.plugin.v1.ComponentValue - 67, // 83: atmos.plugin.v1.PrepareComponentResponse.feature_flags:type_name -> atmos.plugin.v1.PrepareComponentResponse.FeatureFlagsEntry - 17, // 84: atmos.plugin.v1.PrepareComponentResponse.logs:type_name -> atmos.plugin.v1.LogEntry - 52, // 85: atmos.plugin.v1.ComponentErrorsConfiguration.retry:type_name -> atmos.plugin.v1.ComponentRetryPolicy - 53, // 86: atmos.plugin.v1.ComponentErrorsConfiguration.ignore:type_name -> atmos.plugin.v1.ComponentIgnorePolicy - 68, // 87: atmos.plugin.v1.ComponentIgnorePolicy.signals:type_name -> atmos.plugin.v1.ComponentIgnorePolicy.SignalsEntry - 33, // 88: atmos.plugin.v1.ComponentIam.web_identity_token:type_name -> atmos.plugin.v1.ComponentValue - 45, // 89: atmos.plugin.v1.ResolveComponentStateResponse.state:type_name -> atmos.plugin.v1.ComponentStateIdentity - 37, // 90: atmos.plugin.v1.ResolveComponentStateResponse.sources:type_name -> atmos.plugin.v1.ComponentSource - 19, // 91: atmos.plugin.v1.ResolveComponentStateResponse.diagnostics:type_name -> atmos.plugin.v1.Diagnostic - 17, // 92: atmos.plugin.v1.ResolveComponentStateResponse.logs:type_name -> atmos.plugin.v1.LogEntry - 33, // 93: atmos.plugin.v1.ComponentOperation.OptionsEntry.value:type_name -> atmos.plugin.v1.ComponentValue - 16, // 94: atmos.plugin.v1.PrepareComponentResponse.InputOriginsEntry.value:type_name -> atmos.plugin.v1.SourceLocation - 33, // 95: atmos.plugin.v1.ComponentIgnorePolicy.SignalsEntry.value:type_name -> atmos.plugin.v1.ComponentValue - 8, // 96: atmos.plugin.v1.Info.Describe:input_type -> atmos.plugin.v1.DescribeRequest - 10, // 97: atmos.plugin.v1.Info.Configure:input_type -> atmos.plugin.v1.ConfigureRequest - 11, // 98: atmos.plugin.v1.AuthProvider.Validate:input_type -> atmos.plugin.v1.ProviderRequest - 11, // 99: atmos.plugin.v1.AuthProvider.Authenticate:input_type -> atmos.plugin.v1.ProviderRequest - 22, // 100: atmos.plugin.v1.AuthProvider.Refresh:input_type -> atmos.plugin.v1.RefreshRequest - 11, // 101: atmos.plugin.v1.AuthProvider.Logout:input_type -> atmos.plugin.v1.ProviderRequest - 11, // 102: atmos.plugin.v1.AuthProvider.Environment:input_type -> atmos.plugin.v1.ProviderRequest - 11, // 103: atmos.plugin.v1.AuthProvider.Paths:input_type -> atmos.plugin.v1.ProviderRequest - 25, // 104: atmos.plugin.v1.AuthProvider.PrepareEnvironment:input_type -> atmos.plugin.v1.PrepareEnvironmentRequest - 12, // 105: atmos.plugin.v1.AuthIdentity.Validate:input_type -> atmos.plugin.v1.IdentityRequest - 28, // 106: atmos.plugin.v1.AuthIdentity.Authenticate:input_type -> atmos.plugin.v1.IdentityAuthenticateRequest - 12, // 107: atmos.plugin.v1.AuthIdentity.Logout:input_type -> atmos.plugin.v1.IdentityRequest - 12, // 108: atmos.plugin.v1.AuthIdentity.Environment:input_type -> atmos.plugin.v1.IdentityRequest - 12, // 109: atmos.plugin.v1.AuthIdentity.Paths:input_type -> atmos.plugin.v1.IdentityRequest - 29, // 110: atmos.plugin.v1.AuthIdentity.PrepareEnvironment:input_type -> atmos.plugin.v1.IdentityPrepareRequest - 30, // 111: atmos.plugin.v1.Commands.Run:input_type -> atmos.plugin.v1.CommandRequest - 42, // 112: atmos.plugin.v1.ComponentDiscovery.Discover:input_type -> atmos.plugin.v1.DiscoverComponentsRequest - 44, // 113: atmos.plugin.v1.ComponentValidation.Validate:input_type -> atmos.plugin.v1.ComponentRequest - 44, // 114: atmos.plugin.v1.ComponentPreparation.Prepare:input_type -> atmos.plugin.v1.ComponentRequest - 44, // 115: atmos.plugin.v1.ComponentState.Resolve:input_type -> atmos.plugin.v1.ComponentRequest - 9, // 116: atmos.plugin.v1.Info.Describe:output_type -> atmos.plugin.v1.DescribeResponse - 71, // 117: atmos.plugin.v1.Info.Configure:output_type -> google.protobuf.Empty - 20, // 118: atmos.plugin.v1.AuthProvider.Validate:output_type -> atmos.plugin.v1.ValidateResponse - 15, // 119: atmos.plugin.v1.AuthProvider.Authenticate:output_type -> atmos.plugin.v1.AuthenticateEvent - 23, // 120: atmos.plugin.v1.AuthProvider.Refresh:output_type -> atmos.plugin.v1.RefreshResponse - 71, // 121: atmos.plugin.v1.AuthProvider.Logout:output_type -> google.protobuf.Empty - 24, // 122: atmos.plugin.v1.AuthProvider.Environment:output_type -> atmos.plugin.v1.EnvironmentResponse - 27, // 123: atmos.plugin.v1.AuthProvider.Paths:output_type -> atmos.plugin.v1.PathsResponse - 24, // 124: atmos.plugin.v1.AuthProvider.PrepareEnvironment:output_type -> atmos.plugin.v1.EnvironmentResponse - 20, // 125: atmos.plugin.v1.AuthIdentity.Validate:output_type -> atmos.plugin.v1.ValidateResponse - 15, // 126: atmos.plugin.v1.AuthIdentity.Authenticate:output_type -> atmos.plugin.v1.AuthenticateEvent - 71, // 127: atmos.plugin.v1.AuthIdentity.Logout:output_type -> google.protobuf.Empty - 24, // 128: atmos.plugin.v1.AuthIdentity.Environment:output_type -> atmos.plugin.v1.EnvironmentResponse - 27, // 129: atmos.plugin.v1.AuthIdentity.Paths:output_type -> atmos.plugin.v1.PathsResponse - 24, // 130: atmos.plugin.v1.AuthIdentity.PrepareEnvironment:output_type -> atmos.plugin.v1.EnvironmentResponse - 32, // 131: atmos.plugin.v1.Commands.Run:output_type -> atmos.plugin.v1.CommandEvent - 43, // 132: atmos.plugin.v1.ComponentDiscovery.Discover:output_type -> atmos.plugin.v1.DiscoverComponentsResponse - 20, // 133: atmos.plugin.v1.ComponentValidation.Validate:output_type -> atmos.plugin.v1.ValidateResponse - 50, // 134: atmos.plugin.v1.ComponentPreparation.Prepare:output_type -> atmos.plugin.v1.PrepareComponentResponse - 56, // 135: atmos.plugin.v1.ComponentState.Resolve:output_type -> atmos.plugin.v1.ResolveComponentStateResponse - 116, // [116:136] is the sub-list for method output_type - 96, // [96:116] is the sub-list for method input_type - 96, // [96:96] is the sub-list for extension type_name - 96, // [96:96] is the sub-list for extension extendee - 0, // [0:96] is the sub-list for field type_name + 61, // 19: atmos.plugin.v1.LogEntry.fields:type_name -> atmos.plugin.v1.LogEntry.FieldsEntry + 70, // 20: atmos.plugin.v1.LogEntry.time:type_name -> google.protobuf.Timestamp + 17, // 21: atmos.plugin.v1.LogRequest.entries:type_name -> atmos.plugin.v1.LogEntry + 16, // 22: atmos.plugin.v1.ErrorDetail.location:type_name -> atmos.plugin.v1.SourceLocation + 1, // 23: atmos.plugin.v1.ErrorDetail.severity:type_name -> atmos.plugin.v1.Severity + 17, // 24: atmos.plugin.v1.ErrorDetail.logs:type_name -> atmos.plugin.v1.LogEntry + 19, // 25: atmos.plugin.v1.Diagnostic.detail:type_name -> atmos.plugin.v1.ErrorDetail + 20, // 26: atmos.plugin.v1.ValidateResponse.diagnostics:type_name -> atmos.plugin.v1.Diagnostic + 11, // 27: atmos.plugin.v1.RefreshRequest.provider:type_name -> atmos.plugin.v1.ProviderRequest + 5, // 28: atmos.plugin.v1.RefreshRequest.current:type_name -> atmos.plugin.v1.Credentials + 5, // 29: atmos.plugin.v1.RefreshResponse.credentials:type_name -> atmos.plugin.v1.Credentials + 22, // 30: atmos.plugin.v1.RefreshResponse.unsupported:type_name -> atmos.plugin.v1.Unsupported + 62, // 31: atmos.plugin.v1.EnvironmentResponse.environment:type_name -> atmos.plugin.v1.EnvironmentResponse.EnvironmentEntry + 11, // 32: atmos.plugin.v1.PrepareEnvironmentRequest.provider:type_name -> atmos.plugin.v1.ProviderRequest + 63, // 33: atmos.plugin.v1.PrepareEnvironmentRequest.environment:type_name -> atmos.plugin.v1.PrepareEnvironmentRequest.EnvironmentEntry + 27, // 34: atmos.plugin.v1.PathsResponse.paths:type_name -> atmos.plugin.v1.CredentialPath + 12, // 35: atmos.plugin.v1.IdentityAuthenticateRequest.identity:type_name -> atmos.plugin.v1.IdentityRequest + 5, // 36: atmos.plugin.v1.IdentityAuthenticateRequest.upstream:type_name -> atmos.plugin.v1.Credentials + 12, // 37: atmos.plugin.v1.IdentityPrepareRequest.identity:type_name -> atmos.plugin.v1.IdentityRequest + 64, // 38: atmos.plugin.v1.IdentityPrepareRequest.environment:type_name -> atmos.plugin.v1.IdentityPrepareRequest.EnvironmentEntry + 4, // 39: atmos.plugin.v1.CommandRequest.invocation:type_name -> atmos.plugin.v1.Invocation + 71, // 40: atmos.plugin.v1.CommandRequest.settings:type_name -> google.protobuf.Struct + 32, // 41: atmos.plugin.v1.CommandEvent.exit:type_name -> atmos.plugin.v1.CommandExit + 35, // 42: atmos.plugin.v1.ComponentValue.sensitive_paths:type_name -> atmos.plugin.v1.ComponentValuePath + 36, // 43: atmos.plugin.v1.ComponentValuePath.steps:type_name -> atmos.plugin.v1.ComponentValueStep + 34, // 44: atmos.plugin.v1.ComponentValueStep.index:type_name -> atmos.plugin.v1.ComponentValue + 2, // 45: atmos.plugin.v1.ComponentSource.kind:type_name -> atmos.plugin.v1.ComponentSource.Kind + 37, // 46: atmos.plugin.v1.ComponentDependency.target:type_name -> atmos.plugin.v1.ComponentAddress + 3, // 47: atmos.plugin.v1.ComponentDependency.kind:type_name -> atmos.plugin.v1.ComponentDependency.Kind + 37, // 48: atmos.plugin.v1.DiscoveredComponent.address:type_name -> atmos.plugin.v1.ComponentAddress + 34, // 49: atmos.plugin.v1.DiscoveredComponent.configuration:type_name -> atmos.plugin.v1.ComponentValue + 38, // 50: atmos.plugin.v1.DiscoveredComponent.sources:type_name -> atmos.plugin.v1.ComponentSource + 39, // 51: atmos.plugin.v1.DiscoveredComponent.dependencies:type_name -> atmos.plugin.v1.ComponentDependency + 65, // 52: atmos.plugin.v1.ComponentOperation.options:type_name -> atmos.plugin.v1.ComponentOperation.OptionsEntry + 4, // 53: atmos.plugin.v1.DiscoverComponentsRequest.invocation:type_name -> atmos.plugin.v1.Invocation + 42, // 54: atmos.plugin.v1.DiscoverComponentsRequest.operation:type_name -> atmos.plugin.v1.ComponentOperation + 41, // 55: atmos.plugin.v1.DiscoverComponentsRequest.effects:type_name -> atmos.plugin.v1.ComponentEffects + 34, // 56: atmos.plugin.v1.DiscoverComponentsRequest.provider_configuration:type_name -> atmos.plugin.v1.ComponentValue + 40, // 57: atmos.plugin.v1.DiscoverComponentsResponse.components:type_name -> atmos.plugin.v1.DiscoveredComponent + 20, // 58: atmos.plugin.v1.DiscoverComponentsResponse.diagnostics:type_name -> atmos.plugin.v1.Diagnostic + 17, // 59: atmos.plugin.v1.DiscoverComponentsResponse.logs:type_name -> atmos.plugin.v1.LogEntry + 4, // 60: atmos.plugin.v1.ComponentRequest.invocation:type_name -> atmos.plugin.v1.Invocation + 37, // 61: atmos.plugin.v1.ComponentRequest.address:type_name -> atmos.plugin.v1.ComponentAddress + 42, // 62: atmos.plugin.v1.ComponentRequest.operation:type_name -> atmos.plugin.v1.ComponentOperation + 41, // 63: atmos.plugin.v1.ComponentRequest.effects:type_name -> atmos.plugin.v1.ComponentEffects + 34, // 64: atmos.plugin.v1.ComponentRequest.configuration:type_name -> atmos.plugin.v1.ComponentValue + 34, // 65: atmos.plugin.v1.ComponentRequest.provider_configuration:type_name -> atmos.plugin.v1.ComponentValue + 34, // 66: atmos.plugin.v1.ComponentStateIdentity.backend:type_name -> atmos.plugin.v1.ComponentValue + 49, // 67: atmos.plugin.v1.ComponentExecutionConfiguration.extra_arguments:type_name -> atmos.plugin.v1.ComponentExtraArguments + 50, // 68: atmos.plugin.v1.ComponentExecutionConfiguration.before_hooks:type_name -> atmos.plugin.v1.ComponentHook + 50, // 69: atmos.plugin.v1.ComponentExecutionConfiguration.after_hooks:type_name -> atmos.plugin.v1.ComponentHook + 50, // 70: atmos.plugin.v1.ComponentExecutionConfiguration.error_hooks:type_name -> atmos.plugin.v1.ComponentHook + 66, // 71: atmos.plugin.v1.ComponentExtraArguments.environment:type_name -> atmos.plugin.v1.ComponentExtraArguments.EnvironmentEntry + 34, // 72: atmos.plugin.v1.PrepareComponentResponse.inputs:type_name -> atmos.plugin.v1.ComponentValue + 46, // 73: atmos.plugin.v1.PrepareComponentResponse.state:type_name -> atmos.plugin.v1.ComponentStateIdentity + 47, // 74: atmos.plugin.v1.PrepareComponentResponse.files:type_name -> atmos.plugin.v1.ComponentGeneratedFile + 39, // 75: atmos.plugin.v1.PrepareComponentResponse.dependencies:type_name -> atmos.plugin.v1.ComponentDependency + 38, // 76: atmos.plugin.v1.PrepareComponentResponse.sources:type_name -> atmos.plugin.v1.ComponentSource + 20, // 77: atmos.plugin.v1.PrepareComponentResponse.diagnostics:type_name -> atmos.plugin.v1.Diagnostic + 48, // 78: atmos.plugin.v1.PrepareComponentResponse.execution:type_name -> atmos.plugin.v1.ComponentExecutionConfiguration + 67, // 79: atmos.plugin.v1.PrepareComponentResponse.input_origins:type_name -> atmos.plugin.v1.PrepareComponentResponse.InputOriginsEntry + 52, // 80: atmos.plugin.v1.PrepareComponentResponse.errors:type_name -> atmos.plugin.v1.ComponentErrorsConfiguration + 55, // 81: atmos.plugin.v1.PrepareComponentResponse.exclude:type_name -> atmos.plugin.v1.ComponentExclude + 56, // 82: atmos.plugin.v1.PrepareComponentResponse.iam:type_name -> atmos.plugin.v1.ComponentIam + 34, // 83: atmos.plugin.v1.PrepareComponentResponse.encryption:type_name -> atmos.plugin.v1.ComponentValue + 68, // 84: atmos.plugin.v1.PrepareComponentResponse.feature_flags:type_name -> atmos.plugin.v1.PrepareComponentResponse.FeatureFlagsEntry + 17, // 85: atmos.plugin.v1.PrepareComponentResponse.logs:type_name -> atmos.plugin.v1.LogEntry + 53, // 86: atmos.plugin.v1.ComponentErrorsConfiguration.retry:type_name -> atmos.plugin.v1.ComponentRetryPolicy + 54, // 87: atmos.plugin.v1.ComponentErrorsConfiguration.ignore:type_name -> atmos.plugin.v1.ComponentIgnorePolicy + 69, // 88: atmos.plugin.v1.ComponentIgnorePolicy.signals:type_name -> atmos.plugin.v1.ComponentIgnorePolicy.SignalsEntry + 34, // 89: atmos.plugin.v1.ComponentIam.web_identity_token:type_name -> atmos.plugin.v1.ComponentValue + 46, // 90: atmos.plugin.v1.ResolveComponentStateResponse.state:type_name -> atmos.plugin.v1.ComponentStateIdentity + 38, // 91: atmos.plugin.v1.ResolveComponentStateResponse.sources:type_name -> atmos.plugin.v1.ComponentSource + 20, // 92: atmos.plugin.v1.ResolveComponentStateResponse.diagnostics:type_name -> atmos.plugin.v1.Diagnostic + 17, // 93: atmos.plugin.v1.ResolveComponentStateResponse.logs:type_name -> atmos.plugin.v1.LogEntry + 34, // 94: atmos.plugin.v1.ComponentOperation.OptionsEntry.value:type_name -> atmos.plugin.v1.ComponentValue + 16, // 95: atmos.plugin.v1.PrepareComponentResponse.InputOriginsEntry.value:type_name -> atmos.plugin.v1.SourceLocation + 34, // 96: atmos.plugin.v1.ComponentIgnorePolicy.SignalsEntry.value:type_name -> atmos.plugin.v1.ComponentValue + 8, // 97: atmos.plugin.v1.Info.Describe:input_type -> atmos.plugin.v1.DescribeRequest + 10, // 98: atmos.plugin.v1.Info.Configure:input_type -> atmos.plugin.v1.ConfigureRequest + 18, // 99: atmos.plugin.v1.Log.Write:input_type -> atmos.plugin.v1.LogRequest + 11, // 100: atmos.plugin.v1.AuthProvider.Validate:input_type -> atmos.plugin.v1.ProviderRequest + 11, // 101: atmos.plugin.v1.AuthProvider.Authenticate:input_type -> atmos.plugin.v1.ProviderRequest + 23, // 102: atmos.plugin.v1.AuthProvider.Refresh:input_type -> atmos.plugin.v1.RefreshRequest + 11, // 103: atmos.plugin.v1.AuthProvider.Logout:input_type -> atmos.plugin.v1.ProviderRequest + 11, // 104: atmos.plugin.v1.AuthProvider.Environment:input_type -> atmos.plugin.v1.ProviderRequest + 11, // 105: atmos.plugin.v1.AuthProvider.Paths:input_type -> atmos.plugin.v1.ProviderRequest + 26, // 106: atmos.plugin.v1.AuthProvider.PrepareEnvironment:input_type -> atmos.plugin.v1.PrepareEnvironmentRequest + 12, // 107: atmos.plugin.v1.AuthIdentity.Validate:input_type -> atmos.plugin.v1.IdentityRequest + 29, // 108: atmos.plugin.v1.AuthIdentity.Authenticate:input_type -> atmos.plugin.v1.IdentityAuthenticateRequest + 12, // 109: atmos.plugin.v1.AuthIdentity.Logout:input_type -> atmos.plugin.v1.IdentityRequest + 12, // 110: atmos.plugin.v1.AuthIdentity.Environment:input_type -> atmos.plugin.v1.IdentityRequest + 12, // 111: atmos.plugin.v1.AuthIdentity.Paths:input_type -> atmos.plugin.v1.IdentityRequest + 30, // 112: atmos.plugin.v1.AuthIdentity.PrepareEnvironment:input_type -> atmos.plugin.v1.IdentityPrepareRequest + 31, // 113: atmos.plugin.v1.Commands.Run:input_type -> atmos.plugin.v1.CommandRequest + 43, // 114: atmos.plugin.v1.ComponentDiscovery.Discover:input_type -> atmos.plugin.v1.DiscoverComponentsRequest + 45, // 115: atmos.plugin.v1.ComponentValidation.Validate:input_type -> atmos.plugin.v1.ComponentRequest + 45, // 116: atmos.plugin.v1.ComponentPreparation.Prepare:input_type -> atmos.plugin.v1.ComponentRequest + 45, // 117: atmos.plugin.v1.ComponentState.Resolve:input_type -> atmos.plugin.v1.ComponentRequest + 9, // 118: atmos.plugin.v1.Info.Describe:output_type -> atmos.plugin.v1.DescribeResponse + 72, // 119: atmos.plugin.v1.Info.Configure:output_type -> google.protobuf.Empty + 72, // 120: atmos.plugin.v1.Log.Write:output_type -> google.protobuf.Empty + 21, // 121: atmos.plugin.v1.AuthProvider.Validate:output_type -> atmos.plugin.v1.ValidateResponse + 15, // 122: atmos.plugin.v1.AuthProvider.Authenticate:output_type -> atmos.plugin.v1.AuthenticateEvent + 24, // 123: atmos.plugin.v1.AuthProvider.Refresh:output_type -> atmos.plugin.v1.RefreshResponse + 72, // 124: atmos.plugin.v1.AuthProvider.Logout:output_type -> google.protobuf.Empty + 25, // 125: atmos.plugin.v1.AuthProvider.Environment:output_type -> atmos.plugin.v1.EnvironmentResponse + 28, // 126: atmos.plugin.v1.AuthProvider.Paths:output_type -> atmos.plugin.v1.PathsResponse + 25, // 127: atmos.plugin.v1.AuthProvider.PrepareEnvironment:output_type -> atmos.plugin.v1.EnvironmentResponse + 21, // 128: atmos.plugin.v1.AuthIdentity.Validate:output_type -> atmos.plugin.v1.ValidateResponse + 15, // 129: atmos.plugin.v1.AuthIdentity.Authenticate:output_type -> atmos.plugin.v1.AuthenticateEvent + 72, // 130: atmos.plugin.v1.AuthIdentity.Logout:output_type -> google.protobuf.Empty + 25, // 131: atmos.plugin.v1.AuthIdentity.Environment:output_type -> atmos.plugin.v1.EnvironmentResponse + 28, // 132: atmos.plugin.v1.AuthIdentity.Paths:output_type -> atmos.plugin.v1.PathsResponse + 25, // 133: atmos.plugin.v1.AuthIdentity.PrepareEnvironment:output_type -> atmos.plugin.v1.EnvironmentResponse + 33, // 134: atmos.plugin.v1.Commands.Run:output_type -> atmos.plugin.v1.CommandEvent + 44, // 135: atmos.plugin.v1.ComponentDiscovery.Discover:output_type -> atmos.plugin.v1.DiscoverComponentsResponse + 21, // 136: atmos.plugin.v1.ComponentValidation.Validate:output_type -> atmos.plugin.v1.ValidateResponse + 51, // 137: atmos.plugin.v1.ComponentPreparation.Prepare:output_type -> atmos.plugin.v1.PrepareComponentResponse + 57, // 138: atmos.plugin.v1.ComponentState.Resolve:output_type -> atmos.plugin.v1.ResolveComponentStateResponse + 118, // [118:139] is the sub-list for method output_type + 97, // [97:118] is the sub-list for method input_type + 97, // [97:97] is the sub-list for extension type_name + 97, // [97:97] is the sub-list for extension extendee + 0, // [0:97] is the sub-list for field type_name } func init() { file_atmos_plugin_v1_plugin_proto_init() } @@ -4754,16 +4809,16 @@ func file_atmos_plugin_v1_plugin_proto_init() { (*AuthenticateEvent_Interaction)(nil), (*AuthenticateEvent_Result)(nil), } - file_atmos_plugin_v1_plugin_proto_msgTypes[19].OneofWrappers = []any{ + file_atmos_plugin_v1_plugin_proto_msgTypes[20].OneofWrappers = []any{ (*RefreshResponse_Credentials)(nil), (*RefreshResponse_Unsupported)(nil), } - file_atmos_plugin_v1_plugin_proto_msgTypes[28].OneofWrappers = []any{ + file_atmos_plugin_v1_plugin_proto_msgTypes[29].OneofWrappers = []any{ (*CommandEvent_Stdout)(nil), (*CommandEvent_Stderr)(nil), (*CommandEvent_Exit)(nil), } - file_atmos_plugin_v1_plugin_proto_msgTypes[31].OneofWrappers = []any{ + file_atmos_plugin_v1_plugin_proto_msgTypes[32].OneofWrappers = []any{ (*ComponentValueStep_Attribute)(nil), (*ComponentValueStep_Index)(nil), } @@ -4773,9 +4828,9 @@ func file_atmos_plugin_v1_plugin_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_atmos_plugin_v1_plugin_proto_rawDesc), len(file_atmos_plugin_v1_plugin_proto_rawDesc)), NumEnums: 4, - NumMessages: 65, + NumMessages: 66, NumExtensions: 0, - NumServices: 8, + NumServices: 9, }, GoTypes: file_atmos_plugin_v1_plugin_proto_goTypes, DependencyIndexes: file_atmos_plugin_v1_plugin_proto_depIdxs, diff --git a/pkg/plugin/proto/atmos/plugin/v1/plugin_grpc.pb.go b/pkg/plugin/proto/atmos/plugin/v1/plugin_grpc.pb.go index bd48e39bb7b..09a04a900a2 100644 --- a/pkg/plugin/proto/atmos/plugin/v1/plugin_grpc.pb.go +++ b/pkg/plugin/proto/atmos/plugin/v1/plugin_grpc.pb.go @@ -161,6 +161,132 @@ var Info_ServiceDesc = grpc.ServiceDesc{ Metadata: "atmos/plugin/v1/plugin.proto", } +const ( + Log_Write_FullMethodName = "/atmos.plugin.v1.Log/Write" +) + +// LogClient is the client API for Log service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +// +// Log is served by Atmos on the Atmos API broker connection, next to the API services, and called by the +// plugin. It delivers LogEntry messages while a call is still running, instead of in the response where they +// show only when the call ends. Atmos renders each entry through its logger on the UI channel (stderr), +// scoped to the component and stack of the call, with secret masking, and drops entries below the Atmos log +// level. Entries arrive in the order of the calls, and a call returns only after Atmos has rendered its +// entries, so a plugin that waits for its last call before it returns the result shows every entry before the +// result. Delivery never changes the outcome of the call and is never part of a result. A call that fails with +// UNAVAILABLE, PERMISSION_DENIED, UNIMPLEMENTED, or FAILED_PRECONDITION delivered nothing, and the plugin then +// returns those entries in the logs field of its response. Entries delivered here are never repeated there. +// Like the API services, Log accepts only calls that carry the active invocation ID in the +// atmos-invocation-id metadata. +type LogClient interface { + Write(ctx context.Context, in *LogRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) +} + +type logClient struct { + cc grpc.ClientConnInterface +} + +func NewLogClient(cc grpc.ClientConnInterface) LogClient { + return &logClient{cc} +} + +func (c *logClient) Write(ctx context.Context, in *LogRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(emptypb.Empty) + err := c.cc.Invoke(ctx, Log_Write_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// LogServer is the server API for Log service. +// All implementations must embed UnimplementedLogServer +// for forward compatibility. +// +// Log is served by Atmos on the Atmos API broker connection, next to the API services, and called by the +// plugin. It delivers LogEntry messages while a call is still running, instead of in the response where they +// show only when the call ends. Atmos renders each entry through its logger on the UI channel (stderr), +// scoped to the component and stack of the call, with secret masking, and drops entries below the Atmos log +// level. Entries arrive in the order of the calls, and a call returns only after Atmos has rendered its +// entries, so a plugin that waits for its last call before it returns the result shows every entry before the +// result. Delivery never changes the outcome of the call and is never part of a result. A call that fails with +// UNAVAILABLE, PERMISSION_DENIED, UNIMPLEMENTED, or FAILED_PRECONDITION delivered nothing, and the plugin then +// returns those entries in the logs field of its response. Entries delivered here are never repeated there. +// Like the API services, Log accepts only calls that carry the active invocation ID in the +// atmos-invocation-id metadata. +type LogServer interface { + Write(context.Context, *LogRequest) (*emptypb.Empty, error) + mustEmbedUnimplementedLogServer() +} + +// UnimplementedLogServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedLogServer struct{} + +func (UnimplementedLogServer) Write(context.Context, *LogRequest) (*emptypb.Empty, error) { + return nil, status.Error(codes.Unimplemented, "method Write not implemented") +} +func (UnimplementedLogServer) mustEmbedUnimplementedLogServer() {} +func (UnimplementedLogServer) testEmbeddedByValue() {} + +// UnsafeLogServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to LogServer will +// result in compilation errors. +type UnsafeLogServer interface { + mustEmbedUnimplementedLogServer() +} + +func RegisterLogServer(s grpc.ServiceRegistrar, srv LogServer) { + // If the following call panics, it indicates UnimplementedLogServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&Log_ServiceDesc, srv) +} + +func _Log_Write_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(LogRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(LogServer).Write(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Log_Write_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(LogServer).Write(ctx, req.(*LogRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// Log_ServiceDesc is the grpc.ServiceDesc for Log service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var Log_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "atmos.plugin.v1.Log", + HandlerType: (*LogServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Write", + Handler: _Log_Write_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "atmos/plugin/v1/plugin.proto", +} + const ( AuthProvider_Validate_FullMethodName = "/atmos.plugin.v1.AuthProvider/Validate" AuthProvider_Authenticate_FullMethodName = "/atmos.plugin.v1.AuthProvider/Authenticate" diff --git a/plugins/terragrunt/fixtures/toolprobe/main.go b/plugins/terragrunt/fixtures/toolprobe/main.go index 103461930dc..e9bbdbf2681 100644 --- a/plugins/terragrunt/fixtures/toolprobe/main.go +++ b/plugins/terragrunt/fixtures/toolprobe/main.go @@ -7,6 +7,9 @@ // command in terragrunt.log, and runs the engine command that follows `--` in the directory named by // --working-dir. No real Terragrunt runs, so a test proves how Atmos invokes the executable, not how // Terragrunt behaves. +// +// Run as `toolprobe --wait-for FILE` under any name it blocks until FILE exists and then prints +// "released", which lets a test hold a command such as a run_cmd open while it observes Atmos. package main import ( @@ -17,18 +20,29 @@ import ( "os/exec" "path/filepath" "strings" + "time" ) const ( - logMode = 0o600 - failureCode = 127 + logMode = 0o600 + failureCode = 127 + waitLimit = 2 * time.Minute + pollInterval = 20 * time.Millisecond ) +// errGateTimeout reports a wait that was never released. +var errGateTimeout = errors.New("gate file did not appear in time") + func main() { os.Exit(run()) } func run() int { + // `--wait-for FILE` blocks until FILE exists, so a test can hold a command open for exactly as long as it + // needs, on every platform and without a shell. + if len(os.Args) == 3 && os.Args[1] == "--wait-for" { + return waitFor(os.Args[2]) + } self, err := os.Executable() if err != nil { return fail(err) @@ -54,6 +68,19 @@ func answersAsTerragrunt(self string) bool { return strings.EqualFold(strings.TrimSuffix(strings.ToLower(filepath.Base(self)), ".exe"), "terragrunt") } +// waitFor polls for the file and fails, instead of hanging a test forever, when it never appears. +func waitFor(path string) int { + deadline := time.Now().Add(waitLimit) + for time.Now().Before(deadline) { + if _, err := os.Stat(path); err == nil { //nolint:gosec // The path comes from the test that launched this helper. + _, _ = os.Stdout.WriteString("released\n") + return 0 + } + time.Sleep(pollInterval) + } + return fail(fmt.Errorf("%w: %s", errGateTimeout, path)) +} + // execute runs the real tool with the process streams. func execute(tool, directory string, arguments []string) int { // The target is the path a test wrote beside this fixture, never external input. diff --git a/plugins/terragrunt/internal/engine/logs.go b/plugins/terragrunt/internal/engine/logs.go index 6338021484a..c8d3620c8f4 100644 --- a/plugins/terragrunt/internal/engine/logs.go +++ b/plugins/terragrunt/internal/engine/logs.go @@ -8,6 +8,7 @@ import ( "slices" "strings" "sync" + "time" "github.com/gruntwork-io/terragrunt/pkg/log" "github.com/sirupsen/logrus" @@ -38,6 +39,8 @@ type LogSink struct { size int mu sync.Mutex off bool + // forward receives each kept event as it happens instead of the sink collecting it. + forward func(*model.LogEntry) } // NewLogSink returns a sink for the events of a call at the host's log level. Terragrunt's logger reports @@ -59,6 +62,36 @@ func NewLogSink(level, root string) *LogSink { return sink } +// Enabled reports whether the sink keeps any event, which depends on the level the host asked for. +// +//nolint:lintroller // Plugin evaluator code cannot import the host performance tracker. +func (s *LogSink) Enabled() bool { return !s.off } + +// Forward hands every kept event to deliver as it happens, in order, instead of collecting it for Entries. +// Terragrunt may log from several goroutines, so deliver is called while the sink holds its lock to keep the +// order of events; it must be fast and must not call back into the sink. Events are no longer bounded by +// the sink: the deliverer owns that. +// +//nolint:lintroller // Plugin evaluator code cannot import the host performance tracker. +func (s *LogSink) Forward(deliver func(*model.LogEntry)) { + s.mu.Lock() + defer s.mu.Unlock() + s.forward = deliver +} + +// Event reports an event of the plugin itself, such as the start of an evaluation, the way the Terragrunt +// logger's events are reported: kept at the sink's level, collected or forwarded in order. +// +//nolint:lintroller // Plugin evaluator code cannot import the host performance tracker. +func (s *LogSink) Event(level log.Level, message, unit string) { + if s == nil || s.off || level > s.level { + return + } + s.mu.Lock() + defer s.mu.Unlock() + s.keep(&model.LogEntry{Time: time.Now(), Level: level.String(), Message: message, Unit: s.relative(unit)}) +} + // TerragruntLevel returns the Terragrunt logger level that produces every event the sink keeps. // //nolint:lintroller // Plugin evaluator code cannot import the host performance tracker. @@ -126,10 +159,6 @@ func (s *LogSink) add(level log.Level, entry *logrus.Entry) { } s.mu.Lock() defer s.mu.Unlock() - if len(s.entries) >= maxLogEntries || s.size >= maxLogBytes { - s.dropped++ - return - } fields := make(map[string]string, len(entry.Data)) unit := "" for _, key := range slices.Sorted(maps.Keys(entry.Data)) { @@ -140,12 +169,26 @@ func (s *LogSink) add(level log.Level, entry *logrus.Entry) { } fields[key] = value } - message := truncate(entry.Message) - s.size += len(message) + len(unit) - for key, value := range fields { - s.size += len(key) + len(value) + s.keep(&model.LogEntry{Time: entry.Time, Level: level.String(), Message: truncate(entry.Message), Fields: fields, Unit: unit}) +} + +// keep forwards the event when a deliverer is set, and otherwise collects it up to the bounds. The caller +// holds the lock. +func (s *LogSink) keep(entry *model.LogEntry) { + if s.forward != nil { + s.forward(entry) + return + } + size := len(entry.Message) + len(entry.Unit) + for key, value := range entry.Fields { + size += len(key) + len(value) + } + if len(s.entries) >= maxLogEntries || s.size >= maxLogBytes { + s.dropped++ + return } - s.entries = append(s.entries, model.LogEntry{Time: entry.Time, Level: level.String(), Message: message, Fields: fields, Unit: unit}) + s.size += size + s.entries = append(s.entries, *entry) } // relative makes a unit directory project relative, leaving a path outside the project unchanged. diff --git a/plugins/terragrunt/internal/engine/logs_test.go b/plugins/terragrunt/internal/engine/logs_test.go index 0c03bedd4c0..e5e99cb6483 100644 --- a/plugins/terragrunt/internal/engine/logs_test.go +++ b/plugins/terragrunt/internal/engine/logs_test.go @@ -11,6 +11,8 @@ import ( "github.com/gruntwork-io/terragrunt/pkg/log" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/cloudposse/atmos/plugins/terragrunt/internal/model" ) // logger returns a Terragrunt logger that reports to the sink, at the level the sink asks for. @@ -140,3 +142,54 @@ func TestResolveReportsLoggerEventsToTheContextSink(t *testing.T) { _, err = Resolve(t.Context(), request) require.NoError(t, err, "evaluation without a sink still works") } + +func TestLogSinkForwardsEventsInOrderInsteadOfCollectingThem(t *testing.T) { + sink := NewLogSink("debug", "") + var forwarded []string + sink.Forward(func(entry *model.LogEntry) { forwarded = append(forwarded, entry.Level+":"+entry.Message) }) + l := logger(t, sink) + + l.Trace("below the level") + l.Debug("first") + l.Warn("second") + sink.Event(log.InfoLevel, "third", "") + + assert.Equal(t, []string{"debug:first", "warn:second", "info:third"}, forwarded) + assert.Empty(t, sink.Entries(), "forwarded events are not also kept for the response") +} + +func TestLogSinkForwardingKeepsOrderAcrossConcurrentUnits(t *testing.T) { + sink := NewLogSink("debug", "") + var forwarded []int + sink.Forward(func(entry *model.LogEntry) { forwarded = append(forwarded, len(entry.Fields["unit"])) }) + l := logger(t, sink) + var wg sync.WaitGroup + for unit := range 8 { + wg.Go(func() { + for range 50 { + l.WithField("unit", strings.Repeat("u", unit+1)).Info("working") + } + }) + } + wg.Wait() + // The deliverer is never called concurrently, so it needs no lock of its own. + assert.Len(t, forwarded, 400) +} + +func TestLogSinkEventsFollowTheLevelAndAreRelativeToTheRoot(t *testing.T) { + root := t.TempDir() + for level, want := range map[string]int{"": 0, "warn": 0, "debug": 1, "trace": 2} { + sink := NewLogSink(level, root) + assert.Equal(t, want > 0, sink.Enabled(), level) + sink.Event(log.InfoLevel, "Evaluating unit", filepath.Join(root, "live", "app")) + sink.Event(log.TraceLevel, "too verbose", "") + entries := sink.Entries() + require.Len(t, entries, want, level) + if want > 0 { + assert.Equal(t, model.LogEntry{Time: entries[0].Time, Level: "info", Message: "Evaluating unit", Unit: "live/app"}, entries[0]) + assert.False(t, entries[0].Time.IsZero()) + } + } + var missing *LogSink + assert.NotPanics(t, func() { missing.Event(log.InfoLevel, "ignored", "") }) +} diff --git a/plugins/terragrunt/internal/engine/resolve.go b/plugins/terragrunt/internal/engine/resolve.go index 358fab2959f..6b1e8230c0c 100644 --- a/plugins/terragrunt/internal/engine/resolve.go +++ b/plugins/terragrunt/internal/engine/resolve.go @@ -61,9 +61,12 @@ func resolveUnit(ctx context.Context, request model.Request, filesystem afero.Fs loggerOptions := []log.Option{log.WithOutput(io.Discard), log.WithFormatter(formatter)} level := request.LogLevel // Terragrunt's own log events go to the host as structured entries, never to a stream. - if sink := logSinkFrom(ctx); sink != nil { + sink := logSinkFrom(ctx) + if sink != nil { loggerOptions, level = append(loggerOptions, log.WithHooks(sink.hook())), sink.TerragruntLevel() } + // A coarse phase event: a slow unit shows which one is being evaluated before anything else is logged. + sink.Event(log.InfoLevel, "Evaluating unit", filepath.Dir(path)) logger := log.New(loggerOptions...) if level != "" { if err := logger.SetLevel(level); err != nil { diff --git a/plugins/terragrunt/internal/provider/discovery.go b/plugins/terragrunt/internal/provider/discovery.go index 8ab4f4d8621..5ee944d2dc8 100644 --- a/plugins/terragrunt/internal/provider/discovery.go +++ b/plugins/terragrunt/internal/provider/discovery.go @@ -13,12 +13,12 @@ import ( // Discover expands local stacks in an isolated overlay without preparing units. func (p *Provider) Discover(ctx context.Context, request *pluginv1.DiscoverComponentsRequest) (*pluginv1.DiscoverComponentsResponse, error) { - ctx, sink := withLogs(ctx, request.GetInvocation(), request.GetRootDirectory()) + ctx, logs := p.withLogs(ctx, request.GetInvocation(), request.GetRootDirectory()) response, err := p.discover(ctx, request) if response != nil { - response.Logs = logEntries(sink) + response.Logs = logs.entries() } - return response, withFailureLogs(err, sink) + return response, withFailureLogs(err, logs) } // discoveryRequest validates a discovery request and turns it into an inventory evaluation. diff --git a/plugins/terragrunt/internal/provider/live_logs_test.go b/plugins/terragrunt/internal/provider/live_logs_test.go new file mode 100644 index 00000000000..2c7c88cebce --- /dev/null +++ b/plugins/terragrunt/internal/provider/live_logs_test.go @@ -0,0 +1,173 @@ +package provider + +import ( + "context" + "net" + "os" + "path/filepath" + "sync" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/test/bufconn" + "google.golang.org/protobuf/types/known/emptypb" + + "github.com/cloudposse/atmos/sdk/api" + "github.com/cloudposse/atmos/sdk/component" + pluginv1 "github.com/cloudposse/atmos/sdk/proto/atmos/plugin/v1" +) + +// logReceiver stands in for Atmos: it records what the plugin delivers while a call runs. +type logReceiver struct { + pluginv1.UnimplementedLogServer + mu sync.Mutex + entries []*pluginv1.LogEntry + invocation string + calls int +} + +func (r *logReceiver) Write(ctx context.Context, request *pluginv1.LogRequest) (*emptypb.Empty, error) { + r.mu.Lock() + defer r.mu.Unlock() + r.calls++ + if values := metadata.ValueFromIncomingContext(ctx, api.InvocationMetadata); len(values) == 1 { + r.invocation = values[0] + } + r.entries = append(r.entries, request.GetEntries()...) + return &emptypb.Empty{}, nil +} + +func (r *logReceiver) snapshot() ([]*pluginv1.LogEntry, int, string) { + r.mu.Lock() + defer r.mu.Unlock() + return append([]*pluginv1.LogEntry(nil), r.entries...), r.calls, r.invocation +} + +// apiClient binds an API client to a real in-process connection. A nil receiver serves no log service, +// like an Atmos that predates live delivery. +func apiClient(t *testing.T, receiver *logReceiver) *api.Client { + t.Helper() + listener := bufconn.Listen(1 << 20) + server := grpc.NewServer() + if receiver != nil { + pluginv1.RegisterLogServer(server, receiver) + } + go func() { _ = server.Serve(listener) }() + t.Cleanup(server.Stop) + connection, err := grpc.NewClient("passthrough:///log-test", grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithContextDialer(func(context.Context, string) (net.Conn, error) { return listener.Dial() })) + require.NoError(t, err) + t.Cleanup(func() { _ = connection.Close() }) + client := &api.Client{} + require.NoError(t, client.Bind(connection)) + return client +} + +func messagesOf(entries []*pluginv1.LogEntry) []string { + messages := make([]string, 0, len(entries)) + for _, entry := range entries { + messages = append(messages, entry.GetMessage()) + } + return messages +} + +func discoverAt(t *testing.T, provider *Provider, root, level, id string) *pluginv1.DiscoverComponentsResponse { + t.Helper() + opts, err := encode(map[string]any{"enabled": true, "mode": "native", "discovery": map[string]any{"enabled": true, "included_paths": []string{"live/**"}}}) + require.NoError(t, err) + response, err := provider.Discover(t.Context(), &pluginv1.DiscoverComponentsRequest{RootDirectory: root, Provider: "terragrunt", ProviderConfiguration: opts, IncludePaths: []string{"live/**"}, Operation: &pluginv1.ComponentOperation{Mode: "native", Command: "plan"}, Invocation: &pluginv1.Invocation{Id: id, LogLevel: level}}) + require.NoError(t, err) + return response +} + +func TestEngineLogsAreDeliveredLiveAndNotRepeatedInTheResponse(t *testing.T) { + receiver := &logReceiver{} + response := discoverAt(t, New(nil, WithAPI(apiClient(t, receiver))), fixture(t, "explicit-stack"), "debug", "call-42") + + delivered, calls, invocation := receiver.snapshot() + assert.Equal(t, "call-42", invocation, "the entries belong to the invocation that made the call") + require.NotEmpty(t, delivered) + assert.Positive(t, calls) + // Everything was delivered before the result, so the response repeats nothing. + assert.Empty(t, response.Logs) + // The phase event names the unit being evaluated, relative to the project, at info level. + var phases []string + for _, entry := range delivered { + assert.NotEqual(t, pluginv1.LogLevel_LOG_LEVEL_TRACE, entry.GetLevel(), "trace is below the requested level") + if entry.GetMessage() == "Evaluating unit" { + phases = append(phases, entry.GetUnit()) + assert.Equal(t, pluginv1.LogLevel_LOG_LEVEL_INFO, entry.GetLevel()) + } + } + assert.NotEmpty(t, phases) + for _, unit := range phases { + assert.False(t, filepath.IsAbs(unit), "unit %q is relative to the project root", unit) + } +} + +func TestEngineLogsFallBackToTheResponseWhenAtmosCannotTakeThem(t *testing.T) { + root := fixture(t, "explicit-stack") + baseline := discoverAt(t, New(nil), root, "debug", "call-1") + require.NotEmpty(t, baseline.Logs) + + for name, client := range map[string]*api.Client{ + "log service not served": apiClient(t, nil), + "no connection": {}, + } { + t.Run(name, func(t *testing.T) { + response := discoverAt(t, New(nil, WithAPI(client)), root, "debug", "call-1") + assert.ElementsMatch(t, messagesOf(baseline.Logs), messagesOf(response.Logs), "the same events return with the response") + }) + } + + t.Run("without an invocation to attribute them to", func(t *testing.T) { + receiver := &logReceiver{} + response := discoverAt(t, New(nil, WithAPI(apiClient(t, receiver))), root, "debug", "") + _, calls, _ := receiver.snapshot() + assert.Zero(t, calls) + assert.ElementsMatch(t, messagesOf(baseline.Logs), messagesOf(response.Logs)) + }) +} + +func TestNothingIsDeliveredBelowTheInvocationLevel(t *testing.T) { + for _, level := range []string{"", "warn", "error", "off", "info"} { + receiver := &logReceiver{} + response := discoverAt(t, New(nil, WithAPI(apiClient(t, receiver))), fixture(t, "explicit-stack"), level, "call-1") + _, calls, _ := receiver.snapshot() + assert.Zero(t, calls, "level %q", level) + assert.Empty(t, response.Logs, "level %q", level) + } +} + +func brokenUnit(t *testing.T) *pluginv1.ComponentRequest { + t.Helper() + root, err := filepath.EvalSymlinks(t.TempDir()) + require.NoError(t, err) + require.NoError(t, os.MkdirAll(filepath.Join(root, "module"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(root, "terragrunt.hcl"), []byte("terraform { source = \"./module\" }\ninputs = { broken = local.absent }\n"), 0o644)) + request := componentRequest(t) + request.RootDirectory, request.Source = root, "terragrunt.hcl" + request.Configuration, err = encode(map[string]any{}) + require.NoError(t, err) + request.Invocation.LogLevel, request.Invocation.Id = "trace", "call-9" + return request +} + +func TestAFailedCallStillShowsItsLogsAndNothingTwice(t *testing.T) { + receiver := &logReceiver{} + _, err := New(nil, WithAPI(apiClient(t, receiver))).Prepare(t.Context(), brokenUnit(t)) + require.Error(t, err) + detail, ok := component.FailureDetail(err) + require.True(t, ok) + delivered, _, _ := receiver.snapshot() + assert.NotEmpty(t, delivered, "the events before the failure were shown while the call ran") + assert.Empty(t, detail.Logs, "the failure does not repeat them") + + _, err = New(nil, WithAPI(apiClient(t, nil))).Prepare(t.Context(), brokenUnit(t)) + detail, ok = component.FailureDetail(err) + require.True(t, ok) + assert.NotEmpty(t, detail.Logs, "without live delivery the failure carries the events that explain it") +} diff --git a/plugins/terragrunt/internal/provider/logs.go b/plugins/terragrunt/internal/provider/logs.go index 97b1c77c29f..8d185a8aab7 100644 --- a/plugins/terragrunt/internal/provider/logs.go +++ b/plugins/terragrunt/internal/provider/logs.go @@ -8,35 +8,58 @@ import ( "google.golang.org/protobuf/types/known/timestamppb" "github.com/cloudposse/atmos/plugins/terragrunt/internal/engine" + "github.com/cloudposse/atmos/plugins/terragrunt/internal/model" + "github.com/cloudposse/atmos/sdk/api" pluginv1 "github.com/cloudposse/atmos/sdk/proto/atmos/plugin/v1" ) -// withLogs makes the evaluation of one call report the Terragrunt logger's events at the level the host asked -// for. The events return in the response, or in the failure when the call fails, so the host can show them -// through the Atmos logger. Nothing is written to a stream and no event changes the outcome of the call. -func withLogs(ctx context.Context, invocation *pluginv1.Invocation, root string) (context.Context, *engine.LogSink) { - sink := engine.NewLogSink(invocation.GetLogLevel(), root) - return engine.WithLogSink(ctx, sink), sink +// callLogs carries the Terragrunt logger's events of one call to Atmos at the level it asked for. With an +// API connection the events are delivered while the call runs, so a slow run_cmd or registry fetch shows +// progress. Events that could not be delivered, and all events when there is no connection, are collected +// and returned with the response, or with the failure, for Atmos to show when the call ends. Nothing is +// written to a stream of its own and no event changes the outcome of the call. +type callLogs struct { + sink *engine.LogSink + stream *api.LogStream } -// logEntries converts the collected events to their wire form. -func logEntries(sink *engine.LogSink) []*pluginv1.LogEntry { - collected := sink.Entries() - if len(collected) == 0 { - return nil +// withLogs makes the evaluation of one call report the Terragrunt logger's events. The caller must call +// entries before it returns, so the events delivered live are shown before the result. +func (p *Provider) withLogs(ctx context.Context, invocation *pluginv1.Invocation, root string) (context.Context, *callLogs) { + sink := engine.NewLogSink(invocation.GetLogLevel(), root) + logs := &callLogs{sink: sink} + if p.api != nil && sink.Enabled() { + logs.stream = p.api.OpenLogs(ctx, invocation.GetId()) + sink.Forward(func(entry *model.LogEntry) { logs.stream.Send(logEntry(entry)) }) } + return engine.WithLogSink(ctx, sink), logs +} + +// entries waits for the events delivered live to be shown, for a bounded time, stops delivery, and returns the +// events Atmos has not shown, in order, in their wire form. It is safe to call more than once. +func (l *callLogs) entries() []*pluginv1.LogEntry { + collected := l.sink.Entries() entries := make([]*pluginv1.LogEntry, 0, len(collected)) for i := range collected { - entry := &collected[i] - converted := &pluginv1.LogEntry{Level: logLevel(entry.Level), Message: entry.Message, Fields: entry.Fields, Unit: entry.Unit} - if !entry.Time.IsZero() { - converted.Time = timestamppb.New(entry.Time) - } - entries = append(entries, converted) + entries = append(entries, logEntry(&collected[i])) + } + // The stream is empty of anything already shown; what it returns could not be delivered. + entries = append(entries, l.stream.Close()...) + if len(entries) == 0 { + return nil } return entries } +// logEntry converts one event to its wire form. +func logEntry(entry *model.LogEntry) *pluginv1.LogEntry { + converted := &pluginv1.LogEntry{Level: logLevel(entry.Level), Message: entry.Message, Fields: entry.Fields, Unit: entry.Unit} + if !entry.Time.IsZero() { + converted.Time = timestamppb.New(entry.Time) + } + return converted +} + func logLevel(level string) pluginv1.LogLevel { switch strings.ToLower(level) { case "trace": @@ -53,13 +76,15 @@ func logLevel(level string) pluginv1.LogLevel { return pluginv1.LogLevel_LOG_LEVEL_UNSPECIFIED } -// withFailureLogs attaches the events collected before a failure to the failure the host renders. -func withFailureLogs(err error, sink *engine.LogSink) error { +// withFailureLogs attaches the events Atmos has not shown to the failure Atmos renders, and makes sure the +// events delivered live are shown before the failure. +func withFailureLogs(err error, logs *callLogs) error { + entries := logs.entries() var failure *rpcFailure if !errors.As(err, &failure) { return err } - if entries := logEntries(sink); len(entries) > 0 { + if len(entries) > 0 { failure.failure.Logs(entries) } return err diff --git a/plugins/terragrunt/internal/provider/preparation.go b/plugins/terragrunt/internal/provider/preparation.go index 23a4263373c..86c301c9a02 100644 --- a/plugins/terragrunt/internal/provider/preparation.go +++ b/plugins/terragrunt/internal/provider/preparation.go @@ -56,13 +56,13 @@ func (p *Provider) componentRequest(ctx context.Context, request *pluginv1.Compo // Prepare resolves current inputs after dependencies and returns literal files. // Terraform execution remains owned by Atmos. func (p *Provider) Prepare(ctx context.Context, request *pluginv1.ComponentRequest) (*pluginv1.PrepareComponentResponse, error) { - ctx, sink := withLogs(ctx, request.GetInvocation(), request.GetRootDirectory()) + ctx, logs := p.withLogs(ctx, request.GetInvocation(), request.GetRootDirectory()) response, err := p.prepare(ctx, request) err = scoped(err, "prepare", request.GetRootDirectory(), request.GetAddress()) if response != nil { - response.Logs = logEntries(sink) + response.Logs = logs.entries() } - return response, withFailureLogs(err, sink) + return response, withFailureLogs(err, logs) } func (p *Provider) prepare(ctx context.Context, request *pluginv1.ComponentRequest) (*pluginv1.PrepareComponentResponse, error) { @@ -148,13 +148,13 @@ func stateIdentity(req model.Request, result *model.Resolution) (*pluginv1.Compo // Resolve reads backend identity in an overlay, independently of dependency outputs. func (p *Provider) Resolve(ctx context.Context, request *pluginv1.ComponentRequest) (*pluginv1.ResolveComponentStateResponse, error) { - ctx, sink := withLogs(ctx, request.GetInvocation(), request.GetRootDirectory()) + ctx, logs := p.withLogs(ctx, request.GetInvocation(), request.GetRootDirectory()) response, err := p.resolveState(ctx, request) err = scoped(err, "resolve state", request.GetRootDirectory(), request.GetAddress()) if response != nil { - response.Logs = logEntries(sink) + response.Logs = logs.entries() } - return response, withFailureLogs(err, sink) + return response, withFailureLogs(err, logs) } func (p *Provider) resolveState(ctx context.Context, request *pluginv1.ComponentRequest) (*pluginv1.ResolveComponentStateResponse, error) { diff --git a/plugins/terragrunt/internal/provider/provider.go b/plugins/terragrunt/internal/provider/provider.go index d7aead60b70..204293f2789 100644 --- a/plugins/terragrunt/internal/provider/provider.go +++ b/plugins/terragrunt/internal/provider/provider.go @@ -16,6 +16,7 @@ import ( "github.com/cloudposse/atmos/plugins/terragrunt/internal/engine" "github.com/cloudposse/atmos/plugins/terragrunt/internal/model" + "github.com/cloudposse/atmos/sdk/api" "github.com/cloudposse/atmos/sdk/component" pluginv1 "github.com/cloudposse/atmos/sdk/proto/atmos/plugin/v1" ) @@ -32,14 +33,33 @@ type Provider struct { pluginv1.UnimplementedComponentPreparationServer pluginv1.UnimplementedComponentStateServer evaluate Evaluator + // api delivers log events to Atmos while a call runs. Nil keeps them for the response. + api *api.Client +} + +// Option configures a Provider. +type Option func(*Provider) + +// WithAPI lets the provider deliver its log events to Atmos while a call runs, so a slow operation shows +// progress instead of nothing until it ends. +// +//nolint:lintroller // Plugin code cannot import the host performance tracker. +func WithAPI(client *api.Client) Option { + return func(p *Provider) { p.api = client } } // New constructs a provider with the pinned evaluator when none is supplied. -func New(evaluate Evaluator) *Provider { +// +//nolint:lintroller // Plugin code cannot import the host performance tracker. +func New(evaluate Evaluator, options ...Option) *Provider { if evaluate == nil { evaluate = engine.Resolve } - return &Provider{evaluate: evaluate} + p := &Provider{evaluate: evaluate} + for _, apply := range options { + apply(p) + } + return p } func encode(value any) (*pluginv1.ComponentValue, error) { diff --git a/plugins/terragrunt/main.go b/plugins/terragrunt/main.go index e5e4356992d..dd6b792b0c1 100644 --- a/plugins/terragrunt/main.go +++ b/plugins/terragrunt/main.go @@ -36,8 +36,8 @@ func description() *pluginv1.DescribeResponse { } func main() { - plugin.Main(plugin.Config{Description: description(), Build: func(_ *api.Client) plugin.Services { - service := provider.New(nil) + plugin.Main(plugin.Config{Description: description(), Build: func(client *api.Client) plugin.Services { + service := provider.New(nil, provider.WithAPI(client)) return plugin.Services{Discovery: service, Validation: service, Preparation: service, State: service} }}) } diff --git a/proto/atmos/plugin/v1/plugin.proto b/proto/atmos/plugin/v1/plugin.proto index 7be981c484a..0c89cd48b5a 100644 --- a/proto/atmos/plugin/v1/plugin.proto +++ b/proto/atmos/plugin/v1/plugin.proto @@ -99,7 +99,9 @@ enum LogLevel { } // LogEntry is one structured log event from a plugin's engine, for example a Terragrunt logger event. -// A response carries the entries produced while it was computed, in order. The host renders them through +// A plugin delivers entries while the call runs through the Log service of the Atmos API, so a slow +// operation shows progress as it happens. A response carries only the entries that could not be delivered +// that way, in order, and never an entry that was delivered live. The host renders them through // the Atmos logger on the UI channel (stderr), scoped to the component and stack of the call, with secret // masking, at the level each entry carries. They are hidden at the Atmos default level and shown with // --logs-level=Debug or Trace. Entries never change the outcome of the call and are never written to the @@ -115,6 +117,20 @@ message LogEntry { string unit = 5; } +// Log is served by Atmos on the Atmos API broker connection, next to the API services, and called by the +// plugin. It delivers LogEntry messages while a call is still running, instead of in the response where they +// show only when the call ends. Atmos renders each entry through its logger on the UI channel (stderr), +// scoped to the component and stack of the call, with secret masking, and drops entries below the Atmos log +// level. Entries arrive in the order of the calls, and a call returns only after Atmos has rendered its +// entries, so a plugin that waits for its last call before it returns the result shows every entry before the +// result. Delivery never changes the outcome of the call and is never part of a result. A call that fails with +// UNAVAILABLE, PERMISSION_DENIED, UNIMPLEMENTED, or FAILED_PRECONDITION delivered nothing, and the plugin then +// returns those entries in the logs field of its response. Entries delivered here are never repeated there. +// Like the API services, Log accepts only calls that carry the active invocation ID in the +// atmos-invocation-id metadata. +service Log { rpc Write(LogRequest) returns (google.protobuf.Empty); } +message LogRequest { repeated LogEntry entries = 1; } + // ErrorDetail is the structured, user-facing description of a plugin failure. // A plugin returns it as a gRPC status detail (google.rpc.Status.details) on a // failed call, or inside Diagnostic.detail for a per-item failure that must not diff --git a/sdk/api/logs.go b/sdk/api/logs.go new file mode 100644 index 00000000000..ff25bc4a89a --- /dev/null +++ b/sdk/api/logs.go @@ -0,0 +1,298 @@ +package api + +import ( + "context" + "fmt" + "sync" + "time" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + pluginv1 "github.com/cloudposse/atmos/sdk/proto/atmos/plugin/v1" +) + +const ( + // DefaultLogQueue bounds the entries a LogStream holds while Atmos renders earlier ones. + DefaultLogQueue = 1024 + // DefaultLogBatch bounds the entries sent in one call, so a backlog drains in a few calls. + DefaultLogBatch = 64 + // DefaultLogFlush is how long Close waits for Atmos to render the entries still queued. Zero waits until + // every entry is delivered or the call is cancelled, so no entry is lost to a slow terminal. + DefaultLogFlush = time.Duration(0) +) + +// LogOption configures a LogStream. +type LogOption func(*LogStream) + +// WithLogQueue sets how many entries the stream holds before Send waits for Atmos to render some. Values below +// one are ignored. +// +//nolint:lintroller // Pure SDK helper; the standalone SDK cannot import host perf tracking. +func WithLogQueue(entries int) LogOption { + return func(s *LogStream) { + if entries > 0 { + s.capacity = entries + } + } +} + +// WithLogBatch sets how many entries one call to Atmos carries at most. Values below one are ignored. +// +//nolint:lintroller // Pure SDK helper; the standalone SDK cannot import host perf tracking. +func WithLogBatch(entries int) LogOption { + return func(s *LogStream) { + if entries > 0 { + s.batch = entries + } + } +} + +// WithLogFlush caps how long Close waits for queued entries to reach Atmos; entries cut off by the cap are +// counted as omitted. The default is no cap. Values below zero are ignored. +// +//nolint:lintroller // Pure SDK helper; the standalone SDK cannot import host perf tracking. +func WithLogFlush(wait time.Duration) LogOption { + return func(s *LogStream) { + if wait >= 0 { + s.flush = wait + } + } +} + +// LogStream delivers a plugin's log entries to Atmos while a call is still running, so that Atmos shows them +// as they happen instead of when the call ends. Entries are sent in order by one goroutine, and none is dropped: +// when Atmos renders more slowly than the plugin logs, Send waits for room in the queue, so the plugin slows to +// the speed of the terminal. Send never fails the call, and it stops waiting when the call is cancelled. +// +// Entries that Atmos did not take, because the log service is unavailable, come back from Close so the plugin +// can return them in its response, where Atmos renders them when the call ends. Entries delivered live are +// never returned, so nothing is shown twice. An entry whose delivery was cut off in flight, by cancellation or +// an optional flush cap, is counted as omitted rather than returned: it may already be on screen. +type LogStream struct { + sink pluginv1.LogClient + ctx context.Context + cancel context.CancelFunc + capacity int + batch int + flush time.Duration + wake chan struct{} + done chan struct{} + // space wakes senders waiting for room in the queue. + space *sync.Cond + + mu sync.Mutex + queue []*pluginv1.LogEntry + undelivered []*pluginv1.LogEntry + omitted int + unavailable bool + closing bool + result []*pluginv1.LogEntry + closed bool +} + +// OpenLogs starts delivering log entries for the invocation. It never fails: when the Atmos API is not +// configured or the invocation is unknown, every entry comes back from Close instead, which is how plugins +// returned entries before live delivery existed. The caller must call Close before it returns the result. +// +//nolint:lintroller // Pure SDK helper; the standalone SDK cannot import host perf tracking. +func (c *Client) OpenLogs(ctx context.Context, invocationID string, options ...LogOption) *LogStream { + stream := &LogStream{capacity: DefaultLogQueue, batch: DefaultLogBatch, flush: DefaultLogFlush, wake: make(chan struct{}, 1), done: make(chan struct{})} + for _, apply := range options { + apply(stream) + } + stream.space = sync.NewCond(&stream.mu) + stream.ctx, stream.cancel = context.WithCancel(WithInvocation(ctx, invocationID)) + // A cancelled call must not leave senders waiting for room. + context.AfterFunc(stream.ctx, stream.wakeSenders) + if c == nil || invocationID == "" { + stream.unavailable = true + close(stream.done) + return stream + } + conn, err := c.conn() + if err != nil { + stream.unavailable = true + close(stream.done) + return stream + } + stream.sink = pluginv1.NewLogClient(conn) + go stream.run() + return stream +} + +// Send queues an entry for delivery. It is safe for concurrent use. It waits while the queue is full, and does +// nothing after Close; when the call is cancelled while it waits, the entry is counted as omitted. +// +//nolint:lintroller // Pure SDK helper; the standalone SDK cannot import host perf tracking. +func (s *LogStream) Send(entry *pluginv1.LogEntry) { + if s == nil || entry == nil { + return + } + s.mu.Lock() + defer s.mu.Unlock() + for !s.closing && !s.unavailable && s.ctx.Err() == nil && len(s.queue) >= s.capacity { + s.space.Wait() + } + if s.closing { + return + } + if s.unavailable { + s.keepLocked(entry) + return + } + if s.ctx.Err() != nil { + s.omitted++ + return + } + s.queue = append(s.queue, entry) + select { + case s.wake <- struct{}{}: + default: + } +} + +// wakeSenders releases senders waiting for room, after the stream closes or its call is cancelled. +func (s *LogStream) wakeSenders() { + s.mu.Lock() + defer s.mu.Unlock() + s.space.Broadcast() +} + +// keepLocked remembers an undelivered entry for the response, up to the queue bound, which keeps the response +// within the transport's message size. The caller holds the lock. +func (s *LogStream) keepLocked(entry *pluginv1.LogEntry) { + if len(s.undelivered) >= s.capacity { + s.omitted++ + return + } + s.undelivered = append(s.undelivered, entry) +} + +// Close waits for queued entries to reach Atmos, for at most the flush cap when one is set, stops the stream, and returns +// the entries Atmos did not take, in order, followed by one entry that says how many were omitted when any +// were. It is safe to call more than once; later calls return the same entries. +// +//nolint:lintroller // Pure SDK helper; the standalone SDK cannot import host perf tracking. +func (s *LogStream) Close() []*pluginv1.LogEntry { + if s == nil { + return nil + } + s.mu.Lock() + if s.closed { + result := append([]*pluginv1.LogEntry(nil), s.result...) + s.mu.Unlock() + return result + } + s.closing = true + s.space.Broadcast() + s.mu.Unlock() + select { + case s.wake <- struct{}{}: + default: + } + s.awaitDrained() + s.cancel() + + s.mu.Lock() + defer s.mu.Unlock() + s.omitted += len(s.queue) + s.queue = nil + s.result = s.undelivered + if s.omitted > 0 { + s.result = append(s.result, &pluginv1.LogEntry{Level: pluginv1.LogLevel_LOG_LEVEL_WARN, Message: fmt.Sprintf("%d log events were not shown", s.omitted)}) + } + s.closed = true + return append([]*pluginv1.LogEntry(nil), s.result...) +} + +// awaitDrained waits until every queued entry is delivered or the call is cancelled, and gives up after the +// flush cap when one is set. +func (s *LogStream) awaitDrained() { + if s.flush <= 0 { + <-s.done + return + } + timer := time.NewTimer(s.flush) + defer timer.Stop() + select { + case <-s.done: + case <-timer.C: + // Abort the call in flight; the goroutine counts what it carried as omitted. + s.cancel() + <-s.done + } +} + +// run sends queued entries in order until the stream is closed and drained, or its context ends. +func (s *LogStream) run() { + defer close(s.done) + for { + batch, more := s.take() + if !more { + return + } + s.deliver(batch) + } +} + +// take removes the next batch from the queue, waiting for one. It reports false when no more will come. +func (s *LogStream) take() ([]*pluginv1.LogEntry, bool) { + for { + s.mu.Lock() + if len(s.queue) > 0 { + size := min(s.batch, len(s.queue)) + batch := append([]*pluginv1.LogEntry(nil), s.queue[:size]...) + s.queue = s.queue[size:] + s.space.Broadcast() + s.mu.Unlock() + return batch, true + } + closing := s.closing + s.mu.Unlock() + if closing || s.ctx.Err() != nil { + return nil, false + } + select { + case <-s.wake: + case <-s.ctx.Done(): + return nil, false + } + } +} + +// deliver sends one batch. Atmos acknowledges a call after it rendered the entries, so success means shown. +func (s *LogStream) deliver(batch []*pluginv1.LogEntry) { + _, err := s.sink.Write(s.ctx, &pluginv1.LogRequest{Entries: batch}) + if err == nil { + return + } + s.mu.Lock() + defer s.mu.Unlock() + if !notDelivered(err) { + // Cut off or failed in an unknown state: the entries may be on screen, so they are not repeated. + s.omitted += len(batch) + return + } + // Atmos took nothing. Stop calling it and hand everything back, in order, for the response. + s.unavailable = true + for _, entry := range batch { + s.keepLocked(entry) + } + for _, entry := range s.queue { + s.keepLocked(entry) + } + s.queue = nil + s.space.Broadcast() +} + +// notDelivered reports whether a failed call certainly delivered nothing, so its entries are safe to return in +// the response instead. +func notDelivered(err error) bool { + switch status.Code(err) { + case codes.Unavailable, codes.PermissionDenied, codes.Unimplemented, codes.FailedPrecondition, codes.InvalidArgument, codes.ResourceExhausted: + return true + default: + return false + } +} diff --git a/sdk/api/logs_test.go b/sdk/api/logs_test.go new file mode 100644 index 00000000000..076d9857e45 --- /dev/null +++ b/sdk/api/logs_test.go @@ -0,0 +1,363 @@ +package api + +import ( + "context" + "errors" + "fmt" + "runtime" + "strings" + "sync" + "testing" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/emptypb" + + pluginv1 "github.com/cloudposse/atmos/sdk/proto/atmos/plugin/v1" +) + +// logFixture implements the log service over the real wire protocol. A gate holds each call until released. +type logFixture struct { + pluginv1.UnimplementedLogServer + mu sync.Mutex + messages []string + invocation string + calls int + gate chan struct{} + received chan struct{} + failWith error +} + +func newLogFixture() *logFixture { return &logFixture{received: make(chan struct{}, 1024)} } + +func (f *logFixture) Write(ctx context.Context, request *pluginv1.LogRequest) (*emptypb.Empty, error) { + if f.gate != nil { + select { + case <-f.gate: + case <-ctx.Done(): + return nil, ctx.Err() + } + } + if f.failWith != nil { + return nil, f.failWith + } + f.mu.Lock() + f.calls++ + if values := metadata.ValueFromIncomingContext(ctx, InvocationMetadata); len(values) == 1 { + f.invocation = values[0] + } + for _, entry := range request.GetEntries() { + f.messages = append(f.messages, entry.GetMessage()) + } + f.mu.Unlock() + f.received <- struct{}{} + return &emptypb.Empty{}, nil +} + +func (f *logFixture) delivered() []string { + f.mu.Lock() + defer f.mu.Unlock() + return append([]string(nil), f.messages...) +} + +func logClient(t *testing.T, fixture *logFixture) *Client { + t.Helper() + client, _ := serviceClient(t, func(s *grpc.Server) { + if fixture != nil { + pluginv1.RegisterLogServer(s, fixture) + } + }) + return client +} + +func entry(message string) *pluginv1.LogEntry { + return &pluginv1.LogEntry{Level: pluginv1.LogLevel_LOG_LEVEL_DEBUG, Message: message} +} + +func messages(entries []*pluginv1.LogEntry) []string { + result := make([]string, 0, len(entries)) + for _, e := range entries { + result = append(result, e.GetMessage()) + } + return result +} + +func equal(a, b []string) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +func TestLogStreamDeliversBeforeCloseAndCarriesTheInvocation(t *testing.T) { + t.Parallel() + fixture := newLogFixture() + client := logClient(t, fixture) + stream := client.OpenLogs(t.Context(), "invocation-7") + stream.Send(entry("early")) + // The entry reaches Atmos while the stream is open, which is the point of live delivery: the call that + // produced it has not returned. + select { + case <-fixture.received: + case <-time.After(5 * time.Second): + t.Fatal("entry was not delivered while the stream was open") + } + if got := fixture.delivered(); !equal(got, []string{"early"}) { + t.Fatalf("delivered = %v", got) + } + if undelivered := stream.Close(); len(undelivered) != 0 { + t.Fatalf("a delivered entry came back: %v", messages(undelivered)) + } + if fixture.invocation != "invocation-7" { + t.Fatalf("invocation metadata = %q", fixture.invocation) + } +} + +func TestLogStreamPreservesOrderAcrossBatches(t *testing.T) { + t.Parallel() + fixture := newLogFixture() + stream := logClient(t, fixture).OpenLogs(t.Context(), "id", WithLogBatch(3)) + var want []string + for i := range 50 { + want = append(want, fmt.Sprintf("event-%02d", i)) + stream.Send(entry(want[i])) + } + if undelivered := stream.Close(); len(undelivered) != 0 { + t.Fatalf("undelivered: %v", messages(undelivered)) + } + // Close flushes: every entry is on screen before the call may return its result. + if got := fixture.delivered(); !equal(got, want) { + t.Fatalf("delivered order = %v", got) + } + if fixture.calls < 2 { + t.Fatalf("expected the backlog to use more than one call, got %d", fixture.calls) + } +} + +func TestLogStreamReturnsEntriesWhenTheServiceIsUnavailable(t *testing.T) { + t.Parallel() + denied := &logFixture{failWith: status.Error(codes.PermissionDenied, "denied"), received: make(chan struct{}, 8)} + for name, build := range map[string]func(*testing.T) *Client{ + "not served": func(t *testing.T) *Client { return logClient(t, nil) }, + "permission denied": func(t *testing.T) *Client { return logClient(t, denied) }, + "unbound client": func(*testing.T) *Client { return &Client{} }, + "nil client": func(*testing.T) *Client { return nil }, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + stream := build(t).OpenLogs(t.Context(), "id") + stream.Send(entry("one")) + stream.Send(entry("two")) + // Wait for the failed attempt so the later entry exercises the unavailable path directly. + time.Sleep(50 * time.Millisecond) + stream.Send(entry("three")) + got := messages(stream.Close()) + if !equal(got, []string{"one", "two", "three"}) { + t.Fatalf("returned = %v", got) + } + }) + } +} + +func TestLogStreamDoesNotRepeatEntriesCutOffInFlight(t *testing.T) { + t.Parallel() + for name, failure := range map[string]error{ + "internal": status.Error(codes.Internal, "boom"), + "unknown": errors.New("unknown"), + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + fixture := newLogFixture() + fixture.failWith = failure + stream := logClient(t, fixture).OpenLogs(t.Context(), "id") + stream.Send(entry("maybe shown")) + got := messages(stream.Close()) + if !equal(got, []string{"1 log events were not shown"}) { + t.Fatalf("an entry that may be on screen was returned or the omission was not reported: %v", got) + } + }) + } +} + +func TestLogStreamWaitsForRoomAndLosesNothing(t *testing.T) { + t.Parallel() + fixture := newLogFixture() + fixture.gate = make(chan struct{}) + stream := logClient(t, fixture).OpenLogs(t.Context(), "id", WithLogQueue(3), WithLogBatch(1)) + stream.Send(entry("inflight")) + // Wait until the sender holds the first entry in a blocked call, so the queue is empty and then full. + deadline := time.Now().Add(5 * time.Second) + for { + stream.mu.Lock() + empty := len(stream.queue) == 0 + stream.mu.Unlock() + if empty { + break + } + if time.Now().After(deadline) { + t.Fatal("sender never took the first entry") + } + time.Sleep(time.Millisecond) + } + for i := range 3 { + stream.Send(entry(fmt.Sprintf("queued-%d", i))) + } + // The queue is full and the receiver is stalled: the next Send waits instead of dropping anything. + finished := make(chan struct{}) + go func() { + stream.Send(entry("queued-3")) + close(finished) + }() + select { + case <-finished: + t.Fatal("Send returned while the queue was full and the receiver stalled") + case <-time.After(100 * time.Millisecond): + } + close(fixture.gate) + select { + case <-finished: + case <-time.After(5 * time.Second): + t.Fatal("Send did not resume after the receiver drained the queue") + } + if got := stream.Close(); len(got) != 0 { + t.Fatalf("nothing should be returned or omitted, got %v", messages(got)) + } + if got := fixture.delivered(); !equal(got, []string{"inflight", "queued-0", "queued-1", "queued-2", "queued-3"}) { + t.Fatalf("delivered = %v", got) + } +} + +func TestLogStreamCancellationReleasesWaitingSenders(t *testing.T) { + t.Parallel() + fixture := newLogFixture() + fixture.gate = make(chan struct{}) + ctx, cancel := context.WithCancel(t.Context()) + stream := logClient(t, fixture).OpenLogs(ctx, "id", WithLogQueue(1), WithLogBatch(1)) + stream.Send(entry("inflight")) + stream.Send(entry("queued")) + finished := make(chan struct{}) + go func() { + stream.Send(entry("waiting")) + close(finished) + }() + select { + case <-finished: + t.Fatal("Send returned while the queue was full") + case <-time.After(100 * time.Millisecond): + } + cancel() + select { + case <-finished: + case <-time.After(5 * time.Second): + t.Fatal("cancellation left a sender waiting") + } + got := messages(stream.Close()) + if len(got) != 1 || !strings.HasSuffix(got[0], "log events were not shown") { + t.Fatalf("a cancelled call must report what it could not show: %v", got) + } +} + +func TestLogStreamFlushCapStillBoundsClose(t *testing.T) { + t.Parallel() + fixture := newLogFixture() + fixture.gate = make(chan struct{}) + stream := logClient(t, fixture).OpenLogs(t.Context(), "id", WithLogFlush(100*time.Millisecond)) + stream.Send(entry("stuck")) + begin := time.Now() + got := messages(stream.Close()) + if elapsed := time.Since(begin); elapsed > 3*time.Second { + t.Fatalf("Close waited %s past its flush cap", elapsed) + } + if !equal(got, []string{"1 log events were not shown"}) { + t.Fatalf("returned = %v", got) + } +} + +func TestLogStreamStopsWithoutLeakingOnCancelAndIgnoresLateSends(t *testing.T) { + fixture := newLogFixture() + fixture.gate = make(chan struct{}) + client := logClient(t, fixture) + // Establish the connection and the server goroutines before counting. + warm := client.OpenLogs(t.Context(), "warm") + warm.Send(entry("warm")) + fixture.gate <- struct{}{} + <-fixture.received + warm.Close() + baseline := stabilised() + + ctx, cancel := context.WithCancel(t.Context()) + stream := client.OpenLogs(ctx, "id") + stream.Send(entry("held")) + time.Sleep(20 * time.Millisecond) + cancel() + begin := time.Now() + stream.Close() + if elapsed := time.Since(begin); elapsed > 2*time.Second { + t.Fatalf("Close after cancel took %s", elapsed) + } + // Late sends and repeated closes are harmless. + stream.Send(entry("late")) + stream.Close() + waitForGoroutines(t, baseline) +} + +func TestLogStreamCloseIsIdempotentAndNilSafe(t *testing.T) { + t.Parallel() + var missing *LogStream + missing.Send(entry("ignored")) + if missing.Close() != nil { + t.Fatal("nil stream returned entries") + } + stream := (*Client)(nil).OpenLogs(t.Context(), "id") + stream.Send(nil) + stream.Send(entry("kept")) + first, second := stream.Close(), stream.Close() + if !equal(messages(first), []string{"kept"}) || !equal(messages(second), []string{"kept"}) { + t.Fatalf("first = %v, second = %v", messages(first), messages(second)) + } + first[0] = nil + if second[0] == nil { + t.Fatal("results alias each other") + } +} + +func TestLogStreamOptionsIgnoreInvalidValues(t *testing.T) { + t.Parallel() + stream := (*Client)(nil).OpenLogs(t.Context(), "id", WithLogQueue(0), WithLogBatch(-1), WithLogFlush(-time.Second)) + defer stream.Close() + if stream.capacity != DefaultLogQueue || stream.batch != DefaultLogBatch || stream.flush != DefaultLogFlush { + t.Fatalf("invalid options changed defaults: %d %d %s", stream.capacity, stream.batch, stream.flush) + } + limited := (*Client)(nil).OpenLogs(t.Context(), "id", WithLogQueue(1)) + limited.Send(entry("a")) + limited.Send(entry("b")) + if got := messages(limited.Close()); !equal(got, []string{"a", "1 log events were not shown"}) { + t.Fatalf("unavailable stream is not bounded: %v", got) + } +} + +func stabilised() int { + runtime.GC() + time.Sleep(50 * time.Millisecond) + return runtime.NumGoroutine() +} + +func waitForGoroutines(t *testing.T, baseline int) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for runtime.NumGoroutine() > baseline { + if time.Now().After(deadline) { + buffer := make([]byte, 1<<16) + t.Fatalf("goroutines leaked: %d > %d\n%s", runtime.NumGoroutine(), baseline, buffer[:runtime.Stack(buffer, true)]) + } + time.Sleep(10 * time.Millisecond) + } +} diff --git a/sdk/proto/atmos/plugin/v1/plugin.pb.go b/sdk/proto/atmos/plugin/v1/plugin.pb.go index 001d7def3a9..9258eb0ecda 100644 --- a/sdk/proto/atmos/plugin/v1/plugin.pb.go +++ b/sdk/proto/atmos/plugin/v1/plugin.pb.go @@ -185,7 +185,7 @@ func (x ComponentSource_Kind) Number() protoreflect.EnumNumber { // Deprecated: Use ComponentSource_Kind.Descriptor instead. func (ComponentSource_Kind) EnumDescriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{33, 0} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{34, 0} } type ComponentDependency_Kind int32 @@ -234,7 +234,7 @@ func (x ComponentDependency_Kind) Number() protoreflect.EnumNumber { // Deprecated: Use ComponentDependency_Kind.Descriptor instead. func (ComponentDependency_Kind) EnumDescriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{34, 0} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{35, 0} } // Invocation identifies the live call authorized to use the Atmos API broker. @@ -1168,7 +1168,9 @@ func (x *SourceLocation) GetColumn() uint32 { } // LogEntry is one structured log event from a plugin's engine, for example a Terragrunt logger event. -// A response carries the entries produced while it was computed, in order. The host renders them through +// A plugin delivers entries while the call runs through the Log service of the Atmos API, so a slow +// operation shows progress as it happens. A response carries only the entries that could not be delivered +// that way, in order, and never an entry that was delivered live. The host renders them through // the Atmos logger on the UI channel (stderr), scoped to the component and stack of the call, with secret // masking, at the level each entry carries. They are hidden at the Atmos default level and shown with // --logs-level=Debug or Trace. Entries never change the outcome of the call and are never written to the @@ -1252,6 +1254,50 @@ func (x *LogEntry) GetUnit() string { return "" } +type LogRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Entries []*LogEntry `protobuf:"bytes,1,rep,name=entries,proto3" json:"entries,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *LogRequest) Reset() { + *x = LogRequest{} + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[14] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *LogRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*LogRequest) ProtoMessage() {} + +func (x *LogRequest) ProtoReflect() protoreflect.Message { + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[14] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use LogRequest.ProtoReflect.Descriptor instead. +func (*LogRequest) Descriptor() ([]byte, []int) { + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{14} +} + +func (x *LogRequest) GetEntries() []*LogEntry { + if x != nil { + return x.Entries + } + return nil +} + // ErrorDetail is the structured, user-facing description of a plugin failure. // A plugin returns it as a gRPC status detail (google.rpc.Status.details) on a // failed call, or inside Diagnostic.detail for a per-item failure that must not @@ -1297,7 +1343,7 @@ type ErrorDetail struct { func (x *ErrorDetail) Reset() { *x = ErrorDetail{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[14] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[15] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1309,7 +1355,7 @@ func (x *ErrorDetail) String() string { func (*ErrorDetail) ProtoMessage() {} func (x *ErrorDetail) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[14] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[15] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1322,7 +1368,7 @@ func (x *ErrorDetail) ProtoReflect() protoreflect.Message { // Deprecated: Use ErrorDetail.ProtoReflect.Descriptor instead. func (*ErrorDetail) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{14} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{15} } func (x *ErrorDetail) GetCode() string { @@ -1422,7 +1468,7 @@ type Diagnostic struct { func (x *Diagnostic) Reset() { *x = Diagnostic{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[15] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[16] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1434,7 +1480,7 @@ func (x *Diagnostic) String() string { func (*Diagnostic) ProtoMessage() {} func (x *Diagnostic) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[15] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[16] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1447,7 +1493,7 @@ func (x *Diagnostic) ProtoReflect() protoreflect.Message { // Deprecated: Use Diagnostic.ProtoReflect.Descriptor instead. func (*Diagnostic) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{15} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{16} } func (x *Diagnostic) GetField() string { @@ -1480,7 +1526,7 @@ type ValidateResponse struct { func (x *ValidateResponse) Reset() { *x = ValidateResponse{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[16] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[17] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1492,7 +1538,7 @@ func (x *ValidateResponse) String() string { func (*ValidateResponse) ProtoMessage() {} func (x *ValidateResponse) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[16] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[17] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1505,7 +1551,7 @@ func (x *ValidateResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ValidateResponse.ProtoReflect.Descriptor instead. func (*ValidateResponse) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{16} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{17} } func (x *ValidateResponse) GetDiagnostics() []*Diagnostic { @@ -1525,7 +1571,7 @@ type Unsupported struct { func (x *Unsupported) Reset() { *x = Unsupported{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[17] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[18] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1537,7 +1583,7 @@ func (x *Unsupported) String() string { func (*Unsupported) ProtoMessage() {} func (x *Unsupported) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[17] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[18] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1550,7 +1596,7 @@ func (x *Unsupported) ProtoReflect() protoreflect.Message { // Deprecated: Use Unsupported.ProtoReflect.Descriptor instead. func (*Unsupported) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{17} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{18} } func (x *Unsupported) GetOperation() string { @@ -1577,7 +1623,7 @@ type RefreshRequest struct { func (x *RefreshRequest) Reset() { *x = RefreshRequest{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[18] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[19] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1589,7 +1635,7 @@ func (x *RefreshRequest) String() string { func (*RefreshRequest) ProtoMessage() {} func (x *RefreshRequest) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[18] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[19] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1602,7 +1648,7 @@ func (x *RefreshRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use RefreshRequest.ProtoReflect.Descriptor instead. func (*RefreshRequest) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{18} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{19} } func (x *RefreshRequest) GetProvider() *ProviderRequest { @@ -1632,7 +1678,7 @@ type RefreshResponse struct { func (x *RefreshResponse) Reset() { *x = RefreshResponse{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[19] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[20] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1644,7 +1690,7 @@ func (x *RefreshResponse) String() string { func (*RefreshResponse) ProtoMessage() {} func (x *RefreshResponse) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[19] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[20] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1657,7 +1703,7 @@ func (x *RefreshResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use RefreshResponse.ProtoReflect.Descriptor instead. func (*RefreshResponse) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{19} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{20} } func (x *RefreshResponse) GetResult() isRefreshResponse_Result { @@ -1710,7 +1756,7 @@ type EnvironmentResponse struct { func (x *EnvironmentResponse) Reset() { *x = EnvironmentResponse{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[20] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[21] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1722,7 +1768,7 @@ func (x *EnvironmentResponse) String() string { func (*EnvironmentResponse) ProtoMessage() {} func (x *EnvironmentResponse) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[20] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[21] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1735,7 +1781,7 @@ func (x *EnvironmentResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use EnvironmentResponse.ProtoReflect.Descriptor instead. func (*EnvironmentResponse) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{20} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{21} } func (x *EnvironmentResponse) GetEnvironment() map[string]string { @@ -1755,7 +1801,7 @@ type PrepareEnvironmentRequest struct { func (x *PrepareEnvironmentRequest) Reset() { *x = PrepareEnvironmentRequest{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[21] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[22] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1767,7 +1813,7 @@ func (x *PrepareEnvironmentRequest) String() string { func (*PrepareEnvironmentRequest) ProtoMessage() {} func (x *PrepareEnvironmentRequest) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[21] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[22] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1780,7 +1826,7 @@ func (x *PrepareEnvironmentRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use PrepareEnvironmentRequest.ProtoReflect.Descriptor instead. func (*PrepareEnvironmentRequest) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{21} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{22} } func (x *PrepareEnvironmentRequest) GetProvider() *ProviderRequest { @@ -1809,7 +1855,7 @@ type CredentialPath struct { func (x *CredentialPath) Reset() { *x = CredentialPath{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[22] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[23] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1821,7 +1867,7 @@ func (x *CredentialPath) String() string { func (*CredentialPath) ProtoMessage() {} func (x *CredentialPath) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[22] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[23] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1834,7 +1880,7 @@ func (x *CredentialPath) ProtoReflect() protoreflect.Message { // Deprecated: Use CredentialPath.ProtoReflect.Descriptor instead. func (*CredentialPath) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{22} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{23} } func (x *CredentialPath) GetLocation() string { @@ -1874,7 +1920,7 @@ type PathsResponse struct { func (x *PathsResponse) Reset() { *x = PathsResponse{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[23] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[24] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1886,7 +1932,7 @@ func (x *PathsResponse) String() string { func (*PathsResponse) ProtoMessage() {} func (x *PathsResponse) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[23] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[24] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1899,7 +1945,7 @@ func (x *PathsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use PathsResponse.ProtoReflect.Descriptor instead. func (*PathsResponse) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{23} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{24} } func (x *PathsResponse) GetPaths() []*CredentialPath { @@ -1919,7 +1965,7 @@ type IdentityAuthenticateRequest struct { func (x *IdentityAuthenticateRequest) Reset() { *x = IdentityAuthenticateRequest{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[24] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[25] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1931,7 +1977,7 @@ func (x *IdentityAuthenticateRequest) String() string { func (*IdentityAuthenticateRequest) ProtoMessage() {} func (x *IdentityAuthenticateRequest) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[24] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[25] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1944,7 +1990,7 @@ func (x *IdentityAuthenticateRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use IdentityAuthenticateRequest.ProtoReflect.Descriptor instead. func (*IdentityAuthenticateRequest) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{24} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{25} } func (x *IdentityAuthenticateRequest) GetIdentity() *IdentityRequest { @@ -1971,7 +2017,7 @@ type IdentityPrepareRequest struct { func (x *IdentityPrepareRequest) Reset() { *x = IdentityPrepareRequest{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[25] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[26] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1983,7 +2029,7 @@ func (x *IdentityPrepareRequest) String() string { func (*IdentityPrepareRequest) ProtoMessage() {} func (x *IdentityPrepareRequest) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[25] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[26] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1996,7 +2042,7 @@ func (x *IdentityPrepareRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use IdentityPrepareRequest.ProtoReflect.Descriptor instead. func (*IdentityPrepareRequest) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{25} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{26} } func (x *IdentityPrepareRequest) GetIdentity() *IdentityRequest { @@ -2026,7 +2072,7 @@ type CommandRequest struct { func (x *CommandRequest) Reset() { *x = CommandRequest{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[26] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[27] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2038,7 +2084,7 @@ func (x *CommandRequest) String() string { func (*CommandRequest) ProtoMessage() {} func (x *CommandRequest) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[26] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[27] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2051,7 +2097,7 @@ func (x *CommandRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use CommandRequest.ProtoReflect.Descriptor instead. func (*CommandRequest) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{26} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{27} } func (x *CommandRequest) GetInvocation() *Invocation { @@ -2091,7 +2137,7 @@ type CommandExit struct { func (x *CommandExit) Reset() { *x = CommandExit{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[27] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[28] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2103,7 +2149,7 @@ func (x *CommandExit) String() string { func (*CommandExit) ProtoMessage() {} func (x *CommandExit) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[27] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[28] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2116,7 +2162,7 @@ func (x *CommandExit) ProtoReflect() protoreflect.Message { // Deprecated: Use CommandExit.ProtoReflect.Descriptor instead. func (*CommandExit) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{27} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{28} } func (x *CommandExit) GetCode() uint32 { @@ -2140,7 +2186,7 @@ type CommandEvent struct { func (x *CommandEvent) Reset() { *x = CommandEvent{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[28] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[29] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2152,7 +2198,7 @@ func (x *CommandEvent) String() string { func (*CommandEvent) ProtoMessage() {} func (x *CommandEvent) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[28] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[29] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2165,7 +2211,7 @@ func (x *CommandEvent) ProtoReflect() protoreflect.Message { // Deprecated: Use CommandEvent.ProtoReflect.Descriptor instead. func (*CommandEvent) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{28} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{29} } func (x *CommandEvent) GetEvent() isCommandEvent_Event { @@ -2239,7 +2285,7 @@ type ComponentValue struct { func (x *ComponentValue) Reset() { *x = ComponentValue{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[29] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[30] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2251,7 +2297,7 @@ func (x *ComponentValue) String() string { func (*ComponentValue) ProtoMessage() {} func (x *ComponentValue) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[29] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[30] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2264,7 +2310,7 @@ func (x *ComponentValue) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentValue.ProtoReflect.Descriptor instead. func (*ComponentValue) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{29} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{30} } func (x *ComponentValue) GetTypeJson() []byte { @@ -2297,7 +2343,7 @@ type ComponentValuePath struct { func (x *ComponentValuePath) Reset() { *x = ComponentValuePath{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[30] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[31] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2309,7 +2355,7 @@ func (x *ComponentValuePath) String() string { func (*ComponentValuePath) ProtoMessage() {} func (x *ComponentValuePath) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[30] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[31] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2322,7 +2368,7 @@ func (x *ComponentValuePath) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentValuePath.ProtoReflect.Descriptor instead. func (*ComponentValuePath) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{30} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{31} } func (x *ComponentValuePath) GetSteps() []*ComponentValueStep { @@ -2345,7 +2391,7 @@ type ComponentValueStep struct { func (x *ComponentValueStep) Reset() { *x = ComponentValueStep{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[31] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[32] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2357,7 +2403,7 @@ func (x *ComponentValueStep) String() string { func (*ComponentValueStep) ProtoMessage() {} func (x *ComponentValueStep) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[31] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[32] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2370,7 +2416,7 @@ func (x *ComponentValueStep) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentValueStep.ProtoReflect.Descriptor instead. func (*ComponentValueStep) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{31} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{32} } func (x *ComponentValueStep) GetSelector() isComponentValueStep_Selector { @@ -2427,7 +2473,7 @@ type ComponentAddress struct { func (x *ComponentAddress) Reset() { *x = ComponentAddress{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[32] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[33] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2439,7 +2485,7 @@ func (x *ComponentAddress) String() string { func (*ComponentAddress) ProtoMessage() {} func (x *ComponentAddress) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[32] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[33] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2452,7 +2498,7 @@ func (x *ComponentAddress) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentAddress.ProtoReflect.Descriptor instead. func (*ComponentAddress) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{32} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{33} } func (x *ComponentAddress) GetStack() string { @@ -2489,7 +2535,7 @@ type ComponentSource struct { func (x *ComponentSource) Reset() { *x = ComponentSource{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[33] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[34] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2501,7 +2547,7 @@ func (x *ComponentSource) String() string { func (*ComponentSource) ProtoMessage() {} func (x *ComponentSource) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[33] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[34] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2514,7 +2560,7 @@ func (x *ComponentSource) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentSource.ProtoReflect.Descriptor instead. func (*ComponentSource) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{33} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{34} } func (x *ComponentSource) GetPath() string { @@ -2548,7 +2594,7 @@ type ComponentDependency struct { func (x *ComponentDependency) Reset() { *x = ComponentDependency{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[34] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[35] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2560,7 +2606,7 @@ func (x *ComponentDependency) String() string { func (*ComponentDependency) ProtoMessage() {} func (x *ComponentDependency) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[34] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[35] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2573,7 +2619,7 @@ func (x *ComponentDependency) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentDependency.ProtoReflect.Descriptor instead. func (*ComponentDependency) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{34} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{35} } func (x *ComponentDependency) GetTarget() *ComponentAddress { @@ -2605,7 +2651,7 @@ type DiscoveredComponent struct { func (x *DiscoveredComponent) Reset() { *x = DiscoveredComponent{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[35] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[36] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2617,7 +2663,7 @@ func (x *DiscoveredComponent) String() string { func (*DiscoveredComponent) ProtoMessage() {} func (x *DiscoveredComponent) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[35] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[36] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2630,7 +2676,7 @@ func (x *DiscoveredComponent) ProtoReflect() protoreflect.Message { // Deprecated: Use DiscoveredComponent.ProtoReflect.Descriptor instead. func (*DiscoveredComponent) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{35} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{36} } func (x *DiscoveredComponent) GetAddress() *ComponentAddress { @@ -2697,7 +2743,7 @@ type ComponentEffects struct { func (x *ComponentEffects) Reset() { *x = ComponentEffects{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[36] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[37] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2709,7 +2755,7 @@ func (x *ComponentEffects) String() string { func (*ComponentEffects) ProtoMessage() {} func (x *ComponentEffects) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[36] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[37] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2722,7 +2768,7 @@ func (x *ComponentEffects) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentEffects.ProtoReflect.Descriptor instead. func (*ComponentEffects) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{36} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{37} } func (x *ComponentEffects) GetCommands() bool { @@ -2777,7 +2823,7 @@ type ComponentOperation struct { func (x *ComponentOperation) Reset() { *x = ComponentOperation{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[37] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[38] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2789,7 +2835,7 @@ func (x *ComponentOperation) String() string { func (*ComponentOperation) ProtoMessage() {} func (x *ComponentOperation) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[37] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[38] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2802,7 +2848,7 @@ func (x *ComponentOperation) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentOperation.ProtoReflect.Descriptor instead. func (*ComponentOperation) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{37} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{38} } func (x *ComponentOperation) GetCommand() string { @@ -2853,7 +2899,7 @@ type DiscoverComponentsRequest struct { func (x *DiscoverComponentsRequest) Reset() { *x = DiscoverComponentsRequest{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[38] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[39] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2865,7 +2911,7 @@ func (x *DiscoverComponentsRequest) String() string { func (*DiscoverComponentsRequest) ProtoMessage() {} func (x *DiscoverComponentsRequest) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[38] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[39] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2878,7 +2924,7 @@ func (x *DiscoverComponentsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DiscoverComponentsRequest.ProtoReflect.Descriptor instead. func (*DiscoverComponentsRequest) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{38} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{39} } func (x *DiscoverComponentsRequest) GetInvocation() *Invocation { @@ -2967,7 +3013,7 @@ type DiscoverComponentsResponse struct { func (x *DiscoverComponentsResponse) Reset() { *x = DiscoverComponentsResponse{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[39] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[40] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2979,7 +3025,7 @@ func (x *DiscoverComponentsResponse) String() string { func (*DiscoverComponentsResponse) ProtoMessage() {} func (x *DiscoverComponentsResponse) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[39] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[40] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2992,7 +3038,7 @@ func (x *DiscoverComponentsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use DiscoverComponentsResponse.ProtoReflect.Descriptor instead. func (*DiscoverComponentsResponse) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{39} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{40} } func (x *DiscoverComponentsResponse) GetComponents() []*DiscoveredComponent { @@ -3033,7 +3079,7 @@ type ComponentRequest struct { func (x *ComponentRequest) Reset() { *x = ComponentRequest{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[40] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[41] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3045,7 +3091,7 @@ func (x *ComponentRequest) String() string { func (*ComponentRequest) ProtoMessage() {} func (x *ComponentRequest) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[40] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[41] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3058,7 +3104,7 @@ func (x *ComponentRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentRequest.ProtoReflect.Descriptor instead. func (*ComponentRequest) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{40} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{41} } func (x *ComponentRequest) GetInvocation() *Invocation { @@ -3138,7 +3184,7 @@ type ComponentStateIdentity struct { func (x *ComponentStateIdentity) Reset() { *x = ComponentStateIdentity{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[41] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[42] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3150,7 +3196,7 @@ func (x *ComponentStateIdentity) String() string { func (*ComponentStateIdentity) ProtoMessage() {} func (x *ComponentStateIdentity) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[41] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[42] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3163,7 +3209,7 @@ func (x *ComponentStateIdentity) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentStateIdentity.ProtoReflect.Descriptor instead. func (*ComponentStateIdentity) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{41} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{42} } func (x *ComponentStateIdentity) GetBackendType() string { @@ -3208,7 +3254,7 @@ type ComponentGeneratedFile struct { func (x *ComponentGeneratedFile) Reset() { *x = ComponentGeneratedFile{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[42] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[43] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3220,7 +3266,7 @@ func (x *ComponentGeneratedFile) String() string { func (*ComponentGeneratedFile) ProtoMessage() {} func (x *ComponentGeneratedFile) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[42] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[43] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3233,7 +3279,7 @@ func (x *ComponentGeneratedFile) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentGeneratedFile.ProtoReflect.Descriptor instead. func (*ComponentGeneratedFile) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{42} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{43} } func (x *ComponentGeneratedFile) GetPath() string { @@ -3278,7 +3324,7 @@ type ComponentExecutionConfiguration struct { func (x *ComponentExecutionConfiguration) Reset() { *x = ComponentExecutionConfiguration{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[43] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[44] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3290,7 +3336,7 @@ func (x *ComponentExecutionConfiguration) String() string { func (*ComponentExecutionConfiguration) ProtoMessage() {} func (x *ComponentExecutionConfiguration) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[43] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[44] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3303,7 +3349,7 @@ func (x *ComponentExecutionConfiguration) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentExecutionConfiguration.ProtoReflect.Descriptor instead. func (*ComponentExecutionConfiguration) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{43} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{44} } func (x *ComponentExecutionConfiguration) GetExtraArguments() []*ComponentExtraArguments { @@ -3347,7 +3393,7 @@ type ComponentExtraArguments struct { func (x *ComponentExtraArguments) Reset() { *x = ComponentExtraArguments{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[44] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[45] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3359,7 +3405,7 @@ func (x *ComponentExtraArguments) String() string { func (*ComponentExtraArguments) ProtoMessage() {} func (x *ComponentExtraArguments) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[44] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[45] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3372,7 +3418,7 @@ func (x *ComponentExtraArguments) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentExtraArguments.ProtoReflect.Descriptor instead. func (*ComponentExtraArguments) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{44} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{45} } func (x *ComponentExtraArguments) GetCommands() []string { @@ -3427,7 +3473,7 @@ type ComponentHook struct { func (x *ComponentHook) Reset() { *x = ComponentHook{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[45] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[46] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3439,7 +3485,7 @@ func (x *ComponentHook) String() string { func (*ComponentHook) ProtoMessage() {} func (x *ComponentHook) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[45] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[46] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3452,7 +3498,7 @@ func (x *ComponentHook) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentHook.ProtoReflect.Descriptor instead. func (*ComponentHook) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{45} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{46} } func (x *ComponentHook) GetName() string { @@ -3555,7 +3601,7 @@ type PrepareComponentResponse struct { func (x *PrepareComponentResponse) Reset() { *x = PrepareComponentResponse{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[46] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[47] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3567,7 +3613,7 @@ func (x *PrepareComponentResponse) String() string { func (*PrepareComponentResponse) ProtoMessage() {} func (x *PrepareComponentResponse) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[46] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[47] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3580,7 +3626,7 @@ func (x *PrepareComponentResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use PrepareComponentResponse.ProtoReflect.Descriptor instead. func (*PrepareComponentResponse) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{46} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{47} } func (x *PrepareComponentResponse) GetEngine() string { @@ -3728,7 +3774,7 @@ type ComponentErrorsConfiguration struct { func (x *ComponentErrorsConfiguration) Reset() { *x = ComponentErrorsConfiguration{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[47] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[48] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3740,7 +3786,7 @@ func (x *ComponentErrorsConfiguration) String() string { func (*ComponentErrorsConfiguration) ProtoMessage() {} func (x *ComponentErrorsConfiguration) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[47] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[48] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3753,7 +3799,7 @@ func (x *ComponentErrorsConfiguration) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentErrorsConfiguration.ProtoReflect.Descriptor instead. func (*ComponentErrorsConfiguration) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{47} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{48} } func (x *ComponentErrorsConfiguration) GetRetry() []*ComponentRetryPolicy { @@ -3783,7 +3829,7 @@ type ComponentRetryPolicy struct { func (x *ComponentRetryPolicy) Reset() { *x = ComponentRetryPolicy{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[48] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[49] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3795,7 +3841,7 @@ func (x *ComponentRetryPolicy) String() string { func (*ComponentRetryPolicy) ProtoMessage() {} func (x *ComponentRetryPolicy) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[48] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[49] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3808,7 +3854,7 @@ func (x *ComponentRetryPolicy) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentRetryPolicy.ProtoReflect.Descriptor instead. func (*ComponentRetryPolicy) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{48} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{49} } func (x *ComponentRetryPolicy) GetName() string { @@ -3853,7 +3899,7 @@ type ComponentIgnorePolicy struct { func (x *ComponentIgnorePolicy) Reset() { *x = ComponentIgnorePolicy{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[49] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[50] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3865,7 +3911,7 @@ func (x *ComponentIgnorePolicy) String() string { func (*ComponentIgnorePolicy) ProtoMessage() {} func (x *ComponentIgnorePolicy) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[49] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[50] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3878,7 +3924,7 @@ func (x *ComponentIgnorePolicy) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentIgnorePolicy.ProtoReflect.Descriptor instead. func (*ComponentIgnorePolicy) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{49} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{50} } func (x *ComponentIgnorePolicy) GetName() string { @@ -3926,7 +3972,7 @@ type ComponentExclude struct { func (x *ComponentExclude) Reset() { *x = ComponentExclude{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[50] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[51] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3938,7 +3984,7 @@ func (x *ComponentExclude) String() string { func (*ComponentExclude) ProtoMessage() {} func (x *ComponentExclude) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[50] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[51] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3951,7 +3997,7 @@ func (x *ComponentExclude) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentExclude.ProtoReflect.Descriptor instead. func (*ComponentExclude) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{50} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{51} } func (x *ComponentExclude) GetCondition() bool { @@ -3990,7 +4036,7 @@ type ComponentIam struct { func (x *ComponentIam) Reset() { *x = ComponentIam{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[51] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[52] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4002,7 +4048,7 @@ func (x *ComponentIam) String() string { func (*ComponentIam) ProtoMessage() {} func (x *ComponentIam) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[51] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[52] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4015,7 +4061,7 @@ func (x *ComponentIam) ProtoReflect() protoreflect.Message { // Deprecated: Use ComponentIam.ProtoReflect.Descriptor instead. func (*ComponentIam) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{51} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{52} } func (x *ComponentIam) GetRole() string { @@ -4059,7 +4105,7 @@ type ResolveComponentStateResponse struct { func (x *ResolveComponentStateResponse) Reset() { *x = ResolveComponentStateResponse{} - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[52] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[53] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4071,7 +4117,7 @@ func (x *ResolveComponentStateResponse) String() string { func (*ResolveComponentStateResponse) ProtoMessage() {} func (x *ResolveComponentStateResponse) ProtoReflect() protoreflect.Message { - mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[52] + mi := &file_atmos_plugin_v1_plugin_proto_msgTypes[53] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4084,7 +4130,7 @@ func (x *ResolveComponentStateResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ResolveComponentStateResponse.ProtoReflect.Descriptor instead. func (*ResolveComponentStateResponse) Descriptor() ([]byte, []int) { - return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{52} + return file_atmos_plugin_v1_plugin_proto_rawDescGZIP(), []int{53} } func (x *ResolveComponentStateResponse) GetState() *ComponentStateIdentity { @@ -4213,7 +4259,10 @@ const file_atmos_plugin_v1_plugin_proto_rawDesc = "" + "\x04unit\x18\x05 \x01(\tR\x04unit\x1a9\n" + "\vFieldsEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + - "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\x90\x03\n" + + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"A\n" + + "\n" + + "LogRequest\x123\n" + + "\aentries\x18\x01 \x03(\v2\x19.atmos.plugin.v1.LogEntryR\aentries\"\x90\x03\n" + "\vErrorDetail\x12\x12\n" + "\x04code\x18\x01 \x01(\tR\x04code\x12\x18\n" + "\asummary\x18\x02 \x01(\tR\asummary\x12\x16\n" + @@ -4482,7 +4531,9 @@ const file_atmos_plugin_v1_plugin_proto_rawDesc = "" + "\x10SEVERITY_WARNING\x10\x022\x9f\x01\n" + "\x04Info\x12O\n" + "\bDescribe\x12 .atmos.plugin.v1.DescribeRequest\x1a!.atmos.plugin.v1.DescribeResponse\x12F\n" + - "\tConfigure\x12!.atmos.plugin.v1.ConfigureRequest\x1a\x16.google.protobuf.Empty2\xd3\x04\n" + + "\tConfigure\x12!.atmos.plugin.v1.ConfigureRequest\x1a\x16.google.protobuf.Empty2C\n" + + "\x03Log\x12<\n" + + "\x05Write\x12\x1b.atmos.plugin.v1.LogRequest\x1a\x16.google.protobuf.Empty2\xd3\x04\n" + "\fAuthProvider\x12O\n" + "\bValidate\x12 .atmos.plugin.v1.ProviderRequest\x1a!.atmos.plugin.v1.ValidateResponse\x12V\n" + "\fAuthenticate\x12 .atmos.plugin.v1.ProviderRequest\x1a\".atmos.plugin.v1.AuthenticateEvent0\x01\x12L\n" + @@ -4523,7 +4574,7 @@ func file_atmos_plugin_v1_plugin_proto_rawDescGZIP() []byte { var ( file_atmos_plugin_v1_plugin_proto_enumTypes = make([]protoimpl.EnumInfo, 4) - file_atmos_plugin_v1_plugin_proto_msgTypes = make([]protoimpl.MessageInfo, 65) + file_atmos_plugin_v1_plugin_proto_msgTypes = make([]protoimpl.MessageInfo, 66) file_atmos_plugin_v1_plugin_proto_goTypes = []any{ LogLevel(0), // 0: atmos.plugin.v1.LogLevel Severity(0), // 1: atmos.plugin.v1.Severity @@ -4543,205 +4594,209 @@ var ( (*AuthenticateEvent)(nil), // 15: atmos.plugin.v1.AuthenticateEvent (*SourceLocation)(nil), // 16: atmos.plugin.v1.SourceLocation (*LogEntry)(nil), // 17: atmos.plugin.v1.LogEntry - (*ErrorDetail)(nil), // 18: atmos.plugin.v1.ErrorDetail - (*Diagnostic)(nil), // 19: atmos.plugin.v1.Diagnostic - (*ValidateResponse)(nil), // 20: atmos.plugin.v1.ValidateResponse - (*Unsupported)(nil), // 21: atmos.plugin.v1.Unsupported - (*RefreshRequest)(nil), // 22: atmos.plugin.v1.RefreshRequest - (*RefreshResponse)(nil), // 23: atmos.plugin.v1.RefreshResponse - (*EnvironmentResponse)(nil), // 24: atmos.plugin.v1.EnvironmentResponse - (*PrepareEnvironmentRequest)(nil), // 25: atmos.plugin.v1.PrepareEnvironmentRequest - (*CredentialPath)(nil), // 26: atmos.plugin.v1.CredentialPath - (*PathsResponse)(nil), // 27: atmos.plugin.v1.PathsResponse - (*IdentityAuthenticateRequest)(nil), // 28: atmos.plugin.v1.IdentityAuthenticateRequest - (*IdentityPrepareRequest)(nil), // 29: atmos.plugin.v1.IdentityPrepareRequest - (*CommandRequest)(nil), // 30: atmos.plugin.v1.CommandRequest - (*CommandExit)(nil), // 31: atmos.plugin.v1.CommandExit - (*CommandEvent)(nil), // 32: atmos.plugin.v1.CommandEvent - (*ComponentValue)(nil), // 33: atmos.plugin.v1.ComponentValue - (*ComponentValuePath)(nil), // 34: atmos.plugin.v1.ComponentValuePath - (*ComponentValueStep)(nil), // 35: atmos.plugin.v1.ComponentValueStep - (*ComponentAddress)(nil), // 36: atmos.plugin.v1.ComponentAddress - (*ComponentSource)(nil), // 37: atmos.plugin.v1.ComponentSource - (*ComponentDependency)(nil), // 38: atmos.plugin.v1.ComponentDependency - (*DiscoveredComponent)(nil), // 39: atmos.plugin.v1.DiscoveredComponent - (*ComponentEffects)(nil), // 40: atmos.plugin.v1.ComponentEffects - (*ComponentOperation)(nil), // 41: atmos.plugin.v1.ComponentOperation - (*DiscoverComponentsRequest)(nil), // 42: atmos.plugin.v1.DiscoverComponentsRequest - (*DiscoverComponentsResponse)(nil), // 43: atmos.plugin.v1.DiscoverComponentsResponse - (*ComponentRequest)(nil), // 44: atmos.plugin.v1.ComponentRequest - (*ComponentStateIdentity)(nil), // 45: atmos.plugin.v1.ComponentStateIdentity - (*ComponentGeneratedFile)(nil), // 46: atmos.plugin.v1.ComponentGeneratedFile - (*ComponentExecutionConfiguration)(nil), // 47: atmos.plugin.v1.ComponentExecutionConfiguration - (*ComponentExtraArguments)(nil), // 48: atmos.plugin.v1.ComponentExtraArguments - (*ComponentHook)(nil), // 49: atmos.plugin.v1.ComponentHook - (*PrepareComponentResponse)(nil), // 50: atmos.plugin.v1.PrepareComponentResponse - (*ComponentErrorsConfiguration)(nil), // 51: atmos.plugin.v1.ComponentErrorsConfiguration - (*ComponentRetryPolicy)(nil), // 52: atmos.plugin.v1.ComponentRetryPolicy - (*ComponentIgnorePolicy)(nil), // 53: atmos.plugin.v1.ComponentIgnorePolicy - (*ComponentExclude)(nil), // 54: atmos.plugin.v1.ComponentExclude - (*ComponentIam)(nil), // 55: atmos.plugin.v1.ComponentIam - (*ResolveComponentStateResponse)(nil), // 56: atmos.plugin.v1.ResolveComponentStateResponse - nil, // 57: atmos.plugin.v1.Invocation.EnvironmentEntry - nil, // 58: atmos.plugin.v1.ConfigureRequest.BrokerIdsEntry - nil, // 59: atmos.plugin.v1.Interaction.FieldsEntry - nil, // 60: atmos.plugin.v1.LogEntry.FieldsEntry - nil, // 61: atmos.plugin.v1.EnvironmentResponse.EnvironmentEntry - nil, // 62: atmos.plugin.v1.PrepareEnvironmentRequest.EnvironmentEntry - nil, // 63: atmos.plugin.v1.IdentityPrepareRequest.EnvironmentEntry - nil, // 64: atmos.plugin.v1.ComponentOperation.OptionsEntry - nil, // 65: atmos.plugin.v1.ComponentExtraArguments.EnvironmentEntry - nil, // 66: atmos.plugin.v1.PrepareComponentResponse.InputOriginsEntry - nil, // 67: atmos.plugin.v1.PrepareComponentResponse.FeatureFlagsEntry - nil, // 68: atmos.plugin.v1.ComponentIgnorePolicy.SignalsEntry - (*timestamppb.Timestamp)(nil), // 69: google.protobuf.Timestamp - (*structpb.Struct)(nil), // 70: google.protobuf.Struct - (*emptypb.Empty)(nil), // 71: google.protobuf.Empty + (*LogRequest)(nil), // 18: atmos.plugin.v1.LogRequest + (*ErrorDetail)(nil), // 19: atmos.plugin.v1.ErrorDetail + (*Diagnostic)(nil), // 20: atmos.plugin.v1.Diagnostic + (*ValidateResponse)(nil), // 21: atmos.plugin.v1.ValidateResponse + (*Unsupported)(nil), // 22: atmos.plugin.v1.Unsupported + (*RefreshRequest)(nil), // 23: atmos.plugin.v1.RefreshRequest + (*RefreshResponse)(nil), // 24: atmos.plugin.v1.RefreshResponse + (*EnvironmentResponse)(nil), // 25: atmos.plugin.v1.EnvironmentResponse + (*PrepareEnvironmentRequest)(nil), // 26: atmos.plugin.v1.PrepareEnvironmentRequest + (*CredentialPath)(nil), // 27: atmos.plugin.v1.CredentialPath + (*PathsResponse)(nil), // 28: atmos.plugin.v1.PathsResponse + (*IdentityAuthenticateRequest)(nil), // 29: atmos.plugin.v1.IdentityAuthenticateRequest + (*IdentityPrepareRequest)(nil), // 30: atmos.plugin.v1.IdentityPrepareRequest + (*CommandRequest)(nil), // 31: atmos.plugin.v1.CommandRequest + (*CommandExit)(nil), // 32: atmos.plugin.v1.CommandExit + (*CommandEvent)(nil), // 33: atmos.plugin.v1.CommandEvent + (*ComponentValue)(nil), // 34: atmos.plugin.v1.ComponentValue + (*ComponentValuePath)(nil), // 35: atmos.plugin.v1.ComponentValuePath + (*ComponentValueStep)(nil), // 36: atmos.plugin.v1.ComponentValueStep + (*ComponentAddress)(nil), // 37: atmos.plugin.v1.ComponentAddress + (*ComponentSource)(nil), // 38: atmos.plugin.v1.ComponentSource + (*ComponentDependency)(nil), // 39: atmos.plugin.v1.ComponentDependency + (*DiscoveredComponent)(nil), // 40: atmos.plugin.v1.DiscoveredComponent + (*ComponentEffects)(nil), // 41: atmos.plugin.v1.ComponentEffects + (*ComponentOperation)(nil), // 42: atmos.plugin.v1.ComponentOperation + (*DiscoverComponentsRequest)(nil), // 43: atmos.plugin.v1.DiscoverComponentsRequest + (*DiscoverComponentsResponse)(nil), // 44: atmos.plugin.v1.DiscoverComponentsResponse + (*ComponentRequest)(nil), // 45: atmos.plugin.v1.ComponentRequest + (*ComponentStateIdentity)(nil), // 46: atmos.plugin.v1.ComponentStateIdentity + (*ComponentGeneratedFile)(nil), // 47: atmos.plugin.v1.ComponentGeneratedFile + (*ComponentExecutionConfiguration)(nil), // 48: atmos.plugin.v1.ComponentExecutionConfiguration + (*ComponentExtraArguments)(nil), // 49: atmos.plugin.v1.ComponentExtraArguments + (*ComponentHook)(nil), // 50: atmos.plugin.v1.ComponentHook + (*PrepareComponentResponse)(nil), // 51: atmos.plugin.v1.PrepareComponentResponse + (*ComponentErrorsConfiguration)(nil), // 52: atmos.plugin.v1.ComponentErrorsConfiguration + (*ComponentRetryPolicy)(nil), // 53: atmos.plugin.v1.ComponentRetryPolicy + (*ComponentIgnorePolicy)(nil), // 54: atmos.plugin.v1.ComponentIgnorePolicy + (*ComponentExclude)(nil), // 55: atmos.plugin.v1.ComponentExclude + (*ComponentIam)(nil), // 56: atmos.plugin.v1.ComponentIam + (*ResolveComponentStateResponse)(nil), // 57: atmos.plugin.v1.ResolveComponentStateResponse + nil, // 58: atmos.plugin.v1.Invocation.EnvironmentEntry + nil, // 59: atmos.plugin.v1.ConfigureRequest.BrokerIdsEntry + nil, // 60: atmos.plugin.v1.Interaction.FieldsEntry + nil, // 61: atmos.plugin.v1.LogEntry.FieldsEntry + nil, // 62: atmos.plugin.v1.EnvironmentResponse.EnvironmentEntry + nil, // 63: atmos.plugin.v1.PrepareEnvironmentRequest.EnvironmentEntry + nil, // 64: atmos.plugin.v1.IdentityPrepareRequest.EnvironmentEntry + nil, // 65: atmos.plugin.v1.ComponentOperation.OptionsEntry + nil, // 66: atmos.plugin.v1.ComponentExtraArguments.EnvironmentEntry + nil, // 67: atmos.plugin.v1.PrepareComponentResponse.InputOriginsEntry + nil, // 68: atmos.plugin.v1.PrepareComponentResponse.FeatureFlagsEntry + nil, // 69: atmos.plugin.v1.ComponentIgnorePolicy.SignalsEntry + (*timestamppb.Timestamp)(nil), // 70: google.protobuf.Timestamp + (*structpb.Struct)(nil), // 71: google.protobuf.Struct + (*emptypb.Empty)(nil), // 72: google.protobuf.Empty } ) var file_atmos_plugin_v1_plugin_proto_depIdxs = []int32{ - 69, // 0: atmos.plugin.v1.Invocation.deadline:type_name -> google.protobuf.Timestamp - 57, // 1: atmos.plugin.v1.Invocation.environment:type_name -> atmos.plugin.v1.Invocation.EnvironmentEntry - 69, // 2: atmos.plugin.v1.Credentials.expires_at:type_name -> google.protobuf.Timestamp - 70, // 3: atmos.plugin.v1.Credentials.data:type_name -> google.protobuf.Struct + 70, // 0: atmos.plugin.v1.Invocation.deadline:type_name -> google.protobuf.Timestamp + 58, // 1: atmos.plugin.v1.Invocation.environment:type_name -> atmos.plugin.v1.Invocation.EnvironmentEntry + 70, // 2: atmos.plugin.v1.Credentials.expires_at:type_name -> google.protobuf.Timestamp + 71, // 3: atmos.plugin.v1.Credentials.data:type_name -> google.protobuf.Struct 6, // 4: atmos.plugin.v1.DescribeRequest.host_supported:type_name -> atmos.plugin.v1.ServiceVersionRange 6, // 5: atmos.plugin.v1.DescribeResponse.services:type_name -> atmos.plugin.v1.ServiceVersionRange 7, // 6: atmos.plugin.v1.DescribeResponse.exports:type_name -> atmos.plugin.v1.Export - 58, // 7: atmos.plugin.v1.ConfigureRequest.broker_ids:type_name -> atmos.plugin.v1.ConfigureRequest.BrokerIdsEntry - 70, // 8: atmos.plugin.v1.ConfigureRequest.settings:type_name -> google.protobuf.Struct + 59, // 7: atmos.plugin.v1.ConfigureRequest.broker_ids:type_name -> atmos.plugin.v1.ConfigureRequest.BrokerIdsEntry + 71, // 8: atmos.plugin.v1.ConfigureRequest.settings:type_name -> google.protobuf.Struct 4, // 9: atmos.plugin.v1.ProviderRequest.invocation:type_name -> atmos.plugin.v1.Invocation - 70, // 10: atmos.plugin.v1.ProviderRequest.spec:type_name -> google.protobuf.Struct + 71, // 10: atmos.plugin.v1.ProviderRequest.spec:type_name -> google.protobuf.Struct 4, // 11: atmos.plugin.v1.IdentityRequest.invocation:type_name -> atmos.plugin.v1.Invocation - 70, // 12: atmos.plugin.v1.IdentityRequest.spec:type_name -> google.protobuf.Struct - 70, // 13: atmos.plugin.v1.IdentityRequest.principal:type_name -> google.protobuf.Struct - 59, // 14: atmos.plugin.v1.Interaction.fields:type_name -> atmos.plugin.v1.Interaction.FieldsEntry + 71, // 12: atmos.plugin.v1.IdentityRequest.spec:type_name -> google.protobuf.Struct + 71, // 13: atmos.plugin.v1.IdentityRequest.principal:type_name -> google.protobuf.Struct + 60, // 14: atmos.plugin.v1.Interaction.fields:type_name -> atmos.plugin.v1.Interaction.FieldsEntry 13, // 15: atmos.plugin.v1.AuthenticateEvent.progress:type_name -> atmos.plugin.v1.Progress 14, // 16: atmos.plugin.v1.AuthenticateEvent.interaction:type_name -> atmos.plugin.v1.Interaction 5, // 17: atmos.plugin.v1.AuthenticateEvent.result:type_name -> atmos.plugin.v1.Credentials 0, // 18: atmos.plugin.v1.LogEntry.level:type_name -> atmos.plugin.v1.LogLevel - 60, // 19: atmos.plugin.v1.LogEntry.fields:type_name -> atmos.plugin.v1.LogEntry.FieldsEntry - 69, // 20: atmos.plugin.v1.LogEntry.time:type_name -> google.protobuf.Timestamp - 16, // 21: atmos.plugin.v1.ErrorDetail.location:type_name -> atmos.plugin.v1.SourceLocation - 1, // 22: atmos.plugin.v1.ErrorDetail.severity:type_name -> atmos.plugin.v1.Severity - 17, // 23: atmos.plugin.v1.ErrorDetail.logs:type_name -> atmos.plugin.v1.LogEntry - 18, // 24: atmos.plugin.v1.Diagnostic.detail:type_name -> atmos.plugin.v1.ErrorDetail - 19, // 25: atmos.plugin.v1.ValidateResponse.diagnostics:type_name -> atmos.plugin.v1.Diagnostic - 11, // 26: atmos.plugin.v1.RefreshRequest.provider:type_name -> atmos.plugin.v1.ProviderRequest - 5, // 27: atmos.plugin.v1.RefreshRequest.current:type_name -> atmos.plugin.v1.Credentials - 5, // 28: atmos.plugin.v1.RefreshResponse.credentials:type_name -> atmos.plugin.v1.Credentials - 21, // 29: atmos.plugin.v1.RefreshResponse.unsupported:type_name -> atmos.plugin.v1.Unsupported - 61, // 30: atmos.plugin.v1.EnvironmentResponse.environment:type_name -> atmos.plugin.v1.EnvironmentResponse.EnvironmentEntry - 11, // 31: atmos.plugin.v1.PrepareEnvironmentRequest.provider:type_name -> atmos.plugin.v1.ProviderRequest - 62, // 32: atmos.plugin.v1.PrepareEnvironmentRequest.environment:type_name -> atmos.plugin.v1.PrepareEnvironmentRequest.EnvironmentEntry - 26, // 33: atmos.plugin.v1.PathsResponse.paths:type_name -> atmos.plugin.v1.CredentialPath - 12, // 34: atmos.plugin.v1.IdentityAuthenticateRequest.identity:type_name -> atmos.plugin.v1.IdentityRequest - 5, // 35: atmos.plugin.v1.IdentityAuthenticateRequest.upstream:type_name -> atmos.plugin.v1.Credentials - 12, // 36: atmos.plugin.v1.IdentityPrepareRequest.identity:type_name -> atmos.plugin.v1.IdentityRequest - 63, // 37: atmos.plugin.v1.IdentityPrepareRequest.environment:type_name -> atmos.plugin.v1.IdentityPrepareRequest.EnvironmentEntry - 4, // 38: atmos.plugin.v1.CommandRequest.invocation:type_name -> atmos.plugin.v1.Invocation - 70, // 39: atmos.plugin.v1.CommandRequest.settings:type_name -> google.protobuf.Struct - 31, // 40: atmos.plugin.v1.CommandEvent.exit:type_name -> atmos.plugin.v1.CommandExit - 34, // 41: atmos.plugin.v1.ComponentValue.sensitive_paths:type_name -> atmos.plugin.v1.ComponentValuePath - 35, // 42: atmos.plugin.v1.ComponentValuePath.steps:type_name -> atmos.plugin.v1.ComponentValueStep - 33, // 43: atmos.plugin.v1.ComponentValueStep.index:type_name -> atmos.plugin.v1.ComponentValue - 2, // 44: atmos.plugin.v1.ComponentSource.kind:type_name -> atmos.plugin.v1.ComponentSource.Kind - 36, // 45: atmos.plugin.v1.ComponentDependency.target:type_name -> atmos.plugin.v1.ComponentAddress - 3, // 46: atmos.plugin.v1.ComponentDependency.kind:type_name -> atmos.plugin.v1.ComponentDependency.Kind - 36, // 47: atmos.plugin.v1.DiscoveredComponent.address:type_name -> atmos.plugin.v1.ComponentAddress - 33, // 48: atmos.plugin.v1.DiscoveredComponent.configuration:type_name -> atmos.plugin.v1.ComponentValue - 37, // 49: atmos.plugin.v1.DiscoveredComponent.sources:type_name -> atmos.plugin.v1.ComponentSource - 38, // 50: atmos.plugin.v1.DiscoveredComponent.dependencies:type_name -> atmos.plugin.v1.ComponentDependency - 64, // 51: atmos.plugin.v1.ComponentOperation.options:type_name -> atmos.plugin.v1.ComponentOperation.OptionsEntry - 4, // 52: atmos.plugin.v1.DiscoverComponentsRequest.invocation:type_name -> atmos.plugin.v1.Invocation - 41, // 53: atmos.plugin.v1.DiscoverComponentsRequest.operation:type_name -> atmos.plugin.v1.ComponentOperation - 40, // 54: atmos.plugin.v1.DiscoverComponentsRequest.effects:type_name -> atmos.plugin.v1.ComponentEffects - 33, // 55: atmos.plugin.v1.DiscoverComponentsRequest.provider_configuration:type_name -> atmos.plugin.v1.ComponentValue - 39, // 56: atmos.plugin.v1.DiscoverComponentsResponse.components:type_name -> atmos.plugin.v1.DiscoveredComponent - 19, // 57: atmos.plugin.v1.DiscoverComponentsResponse.diagnostics:type_name -> atmos.plugin.v1.Diagnostic - 17, // 58: atmos.plugin.v1.DiscoverComponentsResponse.logs:type_name -> atmos.plugin.v1.LogEntry - 4, // 59: atmos.plugin.v1.ComponentRequest.invocation:type_name -> atmos.plugin.v1.Invocation - 36, // 60: atmos.plugin.v1.ComponentRequest.address:type_name -> atmos.plugin.v1.ComponentAddress - 41, // 61: atmos.plugin.v1.ComponentRequest.operation:type_name -> atmos.plugin.v1.ComponentOperation - 40, // 62: atmos.plugin.v1.ComponentRequest.effects:type_name -> atmos.plugin.v1.ComponentEffects - 33, // 63: atmos.plugin.v1.ComponentRequest.configuration:type_name -> atmos.plugin.v1.ComponentValue - 33, // 64: atmos.plugin.v1.ComponentRequest.provider_configuration:type_name -> atmos.plugin.v1.ComponentValue - 33, // 65: atmos.plugin.v1.ComponentStateIdentity.backend:type_name -> atmos.plugin.v1.ComponentValue - 48, // 66: atmos.plugin.v1.ComponentExecutionConfiguration.extra_arguments:type_name -> atmos.plugin.v1.ComponentExtraArguments - 49, // 67: atmos.plugin.v1.ComponentExecutionConfiguration.before_hooks:type_name -> atmos.plugin.v1.ComponentHook - 49, // 68: atmos.plugin.v1.ComponentExecutionConfiguration.after_hooks:type_name -> atmos.plugin.v1.ComponentHook - 49, // 69: atmos.plugin.v1.ComponentExecutionConfiguration.error_hooks:type_name -> atmos.plugin.v1.ComponentHook - 65, // 70: atmos.plugin.v1.ComponentExtraArguments.environment:type_name -> atmos.plugin.v1.ComponentExtraArguments.EnvironmentEntry - 33, // 71: atmos.plugin.v1.PrepareComponentResponse.inputs:type_name -> atmos.plugin.v1.ComponentValue - 45, // 72: atmos.plugin.v1.PrepareComponentResponse.state:type_name -> atmos.plugin.v1.ComponentStateIdentity - 46, // 73: atmos.plugin.v1.PrepareComponentResponse.files:type_name -> atmos.plugin.v1.ComponentGeneratedFile - 38, // 74: atmos.plugin.v1.PrepareComponentResponse.dependencies:type_name -> atmos.plugin.v1.ComponentDependency - 37, // 75: atmos.plugin.v1.PrepareComponentResponse.sources:type_name -> atmos.plugin.v1.ComponentSource - 19, // 76: atmos.plugin.v1.PrepareComponentResponse.diagnostics:type_name -> atmos.plugin.v1.Diagnostic - 47, // 77: atmos.plugin.v1.PrepareComponentResponse.execution:type_name -> atmos.plugin.v1.ComponentExecutionConfiguration - 66, // 78: atmos.plugin.v1.PrepareComponentResponse.input_origins:type_name -> atmos.plugin.v1.PrepareComponentResponse.InputOriginsEntry - 51, // 79: atmos.plugin.v1.PrepareComponentResponse.errors:type_name -> atmos.plugin.v1.ComponentErrorsConfiguration - 54, // 80: atmos.plugin.v1.PrepareComponentResponse.exclude:type_name -> atmos.plugin.v1.ComponentExclude - 55, // 81: atmos.plugin.v1.PrepareComponentResponse.iam:type_name -> atmos.plugin.v1.ComponentIam - 33, // 82: atmos.plugin.v1.PrepareComponentResponse.encryption:type_name -> atmos.plugin.v1.ComponentValue - 67, // 83: atmos.plugin.v1.PrepareComponentResponse.feature_flags:type_name -> atmos.plugin.v1.PrepareComponentResponse.FeatureFlagsEntry - 17, // 84: atmos.plugin.v1.PrepareComponentResponse.logs:type_name -> atmos.plugin.v1.LogEntry - 52, // 85: atmos.plugin.v1.ComponentErrorsConfiguration.retry:type_name -> atmos.plugin.v1.ComponentRetryPolicy - 53, // 86: atmos.plugin.v1.ComponentErrorsConfiguration.ignore:type_name -> atmos.plugin.v1.ComponentIgnorePolicy - 68, // 87: atmos.plugin.v1.ComponentIgnorePolicy.signals:type_name -> atmos.plugin.v1.ComponentIgnorePolicy.SignalsEntry - 33, // 88: atmos.plugin.v1.ComponentIam.web_identity_token:type_name -> atmos.plugin.v1.ComponentValue - 45, // 89: atmos.plugin.v1.ResolveComponentStateResponse.state:type_name -> atmos.plugin.v1.ComponentStateIdentity - 37, // 90: atmos.plugin.v1.ResolveComponentStateResponse.sources:type_name -> atmos.plugin.v1.ComponentSource - 19, // 91: atmos.plugin.v1.ResolveComponentStateResponse.diagnostics:type_name -> atmos.plugin.v1.Diagnostic - 17, // 92: atmos.plugin.v1.ResolveComponentStateResponse.logs:type_name -> atmos.plugin.v1.LogEntry - 33, // 93: atmos.plugin.v1.ComponentOperation.OptionsEntry.value:type_name -> atmos.plugin.v1.ComponentValue - 16, // 94: atmos.plugin.v1.PrepareComponentResponse.InputOriginsEntry.value:type_name -> atmos.plugin.v1.SourceLocation - 33, // 95: atmos.plugin.v1.ComponentIgnorePolicy.SignalsEntry.value:type_name -> atmos.plugin.v1.ComponentValue - 8, // 96: atmos.plugin.v1.Info.Describe:input_type -> atmos.plugin.v1.DescribeRequest - 10, // 97: atmos.plugin.v1.Info.Configure:input_type -> atmos.plugin.v1.ConfigureRequest - 11, // 98: atmos.plugin.v1.AuthProvider.Validate:input_type -> atmos.plugin.v1.ProviderRequest - 11, // 99: atmos.plugin.v1.AuthProvider.Authenticate:input_type -> atmos.plugin.v1.ProviderRequest - 22, // 100: atmos.plugin.v1.AuthProvider.Refresh:input_type -> atmos.plugin.v1.RefreshRequest - 11, // 101: atmos.plugin.v1.AuthProvider.Logout:input_type -> atmos.plugin.v1.ProviderRequest - 11, // 102: atmos.plugin.v1.AuthProvider.Environment:input_type -> atmos.plugin.v1.ProviderRequest - 11, // 103: atmos.plugin.v1.AuthProvider.Paths:input_type -> atmos.plugin.v1.ProviderRequest - 25, // 104: atmos.plugin.v1.AuthProvider.PrepareEnvironment:input_type -> atmos.plugin.v1.PrepareEnvironmentRequest - 12, // 105: atmos.plugin.v1.AuthIdentity.Validate:input_type -> atmos.plugin.v1.IdentityRequest - 28, // 106: atmos.plugin.v1.AuthIdentity.Authenticate:input_type -> atmos.plugin.v1.IdentityAuthenticateRequest - 12, // 107: atmos.plugin.v1.AuthIdentity.Logout:input_type -> atmos.plugin.v1.IdentityRequest - 12, // 108: atmos.plugin.v1.AuthIdentity.Environment:input_type -> atmos.plugin.v1.IdentityRequest - 12, // 109: atmos.plugin.v1.AuthIdentity.Paths:input_type -> atmos.plugin.v1.IdentityRequest - 29, // 110: atmos.plugin.v1.AuthIdentity.PrepareEnvironment:input_type -> atmos.plugin.v1.IdentityPrepareRequest - 30, // 111: atmos.plugin.v1.Commands.Run:input_type -> atmos.plugin.v1.CommandRequest - 42, // 112: atmos.plugin.v1.ComponentDiscovery.Discover:input_type -> atmos.plugin.v1.DiscoverComponentsRequest - 44, // 113: atmos.plugin.v1.ComponentValidation.Validate:input_type -> atmos.plugin.v1.ComponentRequest - 44, // 114: atmos.plugin.v1.ComponentPreparation.Prepare:input_type -> atmos.plugin.v1.ComponentRequest - 44, // 115: atmos.plugin.v1.ComponentState.Resolve:input_type -> atmos.plugin.v1.ComponentRequest - 9, // 116: atmos.plugin.v1.Info.Describe:output_type -> atmos.plugin.v1.DescribeResponse - 71, // 117: atmos.plugin.v1.Info.Configure:output_type -> google.protobuf.Empty - 20, // 118: atmos.plugin.v1.AuthProvider.Validate:output_type -> atmos.plugin.v1.ValidateResponse - 15, // 119: atmos.plugin.v1.AuthProvider.Authenticate:output_type -> atmos.plugin.v1.AuthenticateEvent - 23, // 120: atmos.plugin.v1.AuthProvider.Refresh:output_type -> atmos.plugin.v1.RefreshResponse - 71, // 121: atmos.plugin.v1.AuthProvider.Logout:output_type -> google.protobuf.Empty - 24, // 122: atmos.plugin.v1.AuthProvider.Environment:output_type -> atmos.plugin.v1.EnvironmentResponse - 27, // 123: atmos.plugin.v1.AuthProvider.Paths:output_type -> atmos.plugin.v1.PathsResponse - 24, // 124: atmos.plugin.v1.AuthProvider.PrepareEnvironment:output_type -> atmos.plugin.v1.EnvironmentResponse - 20, // 125: atmos.plugin.v1.AuthIdentity.Validate:output_type -> atmos.plugin.v1.ValidateResponse - 15, // 126: atmos.plugin.v1.AuthIdentity.Authenticate:output_type -> atmos.plugin.v1.AuthenticateEvent - 71, // 127: atmos.plugin.v1.AuthIdentity.Logout:output_type -> google.protobuf.Empty - 24, // 128: atmos.plugin.v1.AuthIdentity.Environment:output_type -> atmos.plugin.v1.EnvironmentResponse - 27, // 129: atmos.plugin.v1.AuthIdentity.Paths:output_type -> atmos.plugin.v1.PathsResponse - 24, // 130: atmos.plugin.v1.AuthIdentity.PrepareEnvironment:output_type -> atmos.plugin.v1.EnvironmentResponse - 32, // 131: atmos.plugin.v1.Commands.Run:output_type -> atmos.plugin.v1.CommandEvent - 43, // 132: atmos.plugin.v1.ComponentDiscovery.Discover:output_type -> atmos.plugin.v1.DiscoverComponentsResponse - 20, // 133: atmos.plugin.v1.ComponentValidation.Validate:output_type -> atmos.plugin.v1.ValidateResponse - 50, // 134: atmos.plugin.v1.ComponentPreparation.Prepare:output_type -> atmos.plugin.v1.PrepareComponentResponse - 56, // 135: atmos.plugin.v1.ComponentState.Resolve:output_type -> atmos.plugin.v1.ResolveComponentStateResponse - 116, // [116:136] is the sub-list for method output_type - 96, // [96:116] is the sub-list for method input_type - 96, // [96:96] is the sub-list for extension type_name - 96, // [96:96] is the sub-list for extension extendee - 0, // [0:96] is the sub-list for field type_name + 61, // 19: atmos.plugin.v1.LogEntry.fields:type_name -> atmos.plugin.v1.LogEntry.FieldsEntry + 70, // 20: atmos.plugin.v1.LogEntry.time:type_name -> google.protobuf.Timestamp + 17, // 21: atmos.plugin.v1.LogRequest.entries:type_name -> atmos.plugin.v1.LogEntry + 16, // 22: atmos.plugin.v1.ErrorDetail.location:type_name -> atmos.plugin.v1.SourceLocation + 1, // 23: atmos.plugin.v1.ErrorDetail.severity:type_name -> atmos.plugin.v1.Severity + 17, // 24: atmos.plugin.v1.ErrorDetail.logs:type_name -> atmos.plugin.v1.LogEntry + 19, // 25: atmos.plugin.v1.Diagnostic.detail:type_name -> atmos.plugin.v1.ErrorDetail + 20, // 26: atmos.plugin.v1.ValidateResponse.diagnostics:type_name -> atmos.plugin.v1.Diagnostic + 11, // 27: atmos.plugin.v1.RefreshRequest.provider:type_name -> atmos.plugin.v1.ProviderRequest + 5, // 28: atmos.plugin.v1.RefreshRequest.current:type_name -> atmos.plugin.v1.Credentials + 5, // 29: atmos.plugin.v1.RefreshResponse.credentials:type_name -> atmos.plugin.v1.Credentials + 22, // 30: atmos.plugin.v1.RefreshResponse.unsupported:type_name -> atmos.plugin.v1.Unsupported + 62, // 31: atmos.plugin.v1.EnvironmentResponse.environment:type_name -> atmos.plugin.v1.EnvironmentResponse.EnvironmentEntry + 11, // 32: atmos.plugin.v1.PrepareEnvironmentRequest.provider:type_name -> atmos.plugin.v1.ProviderRequest + 63, // 33: atmos.plugin.v1.PrepareEnvironmentRequest.environment:type_name -> atmos.plugin.v1.PrepareEnvironmentRequest.EnvironmentEntry + 27, // 34: atmos.plugin.v1.PathsResponse.paths:type_name -> atmos.plugin.v1.CredentialPath + 12, // 35: atmos.plugin.v1.IdentityAuthenticateRequest.identity:type_name -> atmos.plugin.v1.IdentityRequest + 5, // 36: atmos.plugin.v1.IdentityAuthenticateRequest.upstream:type_name -> atmos.plugin.v1.Credentials + 12, // 37: atmos.plugin.v1.IdentityPrepareRequest.identity:type_name -> atmos.plugin.v1.IdentityRequest + 64, // 38: atmos.plugin.v1.IdentityPrepareRequest.environment:type_name -> atmos.plugin.v1.IdentityPrepareRequest.EnvironmentEntry + 4, // 39: atmos.plugin.v1.CommandRequest.invocation:type_name -> atmos.plugin.v1.Invocation + 71, // 40: atmos.plugin.v1.CommandRequest.settings:type_name -> google.protobuf.Struct + 32, // 41: atmos.plugin.v1.CommandEvent.exit:type_name -> atmos.plugin.v1.CommandExit + 35, // 42: atmos.plugin.v1.ComponentValue.sensitive_paths:type_name -> atmos.plugin.v1.ComponentValuePath + 36, // 43: atmos.plugin.v1.ComponentValuePath.steps:type_name -> atmos.plugin.v1.ComponentValueStep + 34, // 44: atmos.plugin.v1.ComponentValueStep.index:type_name -> atmos.plugin.v1.ComponentValue + 2, // 45: atmos.plugin.v1.ComponentSource.kind:type_name -> atmos.plugin.v1.ComponentSource.Kind + 37, // 46: atmos.plugin.v1.ComponentDependency.target:type_name -> atmos.plugin.v1.ComponentAddress + 3, // 47: atmos.plugin.v1.ComponentDependency.kind:type_name -> atmos.plugin.v1.ComponentDependency.Kind + 37, // 48: atmos.plugin.v1.DiscoveredComponent.address:type_name -> atmos.plugin.v1.ComponentAddress + 34, // 49: atmos.plugin.v1.DiscoveredComponent.configuration:type_name -> atmos.plugin.v1.ComponentValue + 38, // 50: atmos.plugin.v1.DiscoveredComponent.sources:type_name -> atmos.plugin.v1.ComponentSource + 39, // 51: atmos.plugin.v1.DiscoveredComponent.dependencies:type_name -> atmos.plugin.v1.ComponentDependency + 65, // 52: atmos.plugin.v1.ComponentOperation.options:type_name -> atmos.plugin.v1.ComponentOperation.OptionsEntry + 4, // 53: atmos.plugin.v1.DiscoverComponentsRequest.invocation:type_name -> atmos.plugin.v1.Invocation + 42, // 54: atmos.plugin.v1.DiscoverComponentsRequest.operation:type_name -> atmos.plugin.v1.ComponentOperation + 41, // 55: atmos.plugin.v1.DiscoverComponentsRequest.effects:type_name -> atmos.plugin.v1.ComponentEffects + 34, // 56: atmos.plugin.v1.DiscoverComponentsRequest.provider_configuration:type_name -> atmos.plugin.v1.ComponentValue + 40, // 57: atmos.plugin.v1.DiscoverComponentsResponse.components:type_name -> atmos.plugin.v1.DiscoveredComponent + 20, // 58: atmos.plugin.v1.DiscoverComponentsResponse.diagnostics:type_name -> atmos.plugin.v1.Diagnostic + 17, // 59: atmos.plugin.v1.DiscoverComponentsResponse.logs:type_name -> atmos.plugin.v1.LogEntry + 4, // 60: atmos.plugin.v1.ComponentRequest.invocation:type_name -> atmos.plugin.v1.Invocation + 37, // 61: atmos.plugin.v1.ComponentRequest.address:type_name -> atmos.plugin.v1.ComponentAddress + 42, // 62: atmos.plugin.v1.ComponentRequest.operation:type_name -> atmos.plugin.v1.ComponentOperation + 41, // 63: atmos.plugin.v1.ComponentRequest.effects:type_name -> atmos.plugin.v1.ComponentEffects + 34, // 64: atmos.plugin.v1.ComponentRequest.configuration:type_name -> atmos.plugin.v1.ComponentValue + 34, // 65: atmos.plugin.v1.ComponentRequest.provider_configuration:type_name -> atmos.plugin.v1.ComponentValue + 34, // 66: atmos.plugin.v1.ComponentStateIdentity.backend:type_name -> atmos.plugin.v1.ComponentValue + 49, // 67: atmos.plugin.v1.ComponentExecutionConfiguration.extra_arguments:type_name -> atmos.plugin.v1.ComponentExtraArguments + 50, // 68: atmos.plugin.v1.ComponentExecutionConfiguration.before_hooks:type_name -> atmos.plugin.v1.ComponentHook + 50, // 69: atmos.plugin.v1.ComponentExecutionConfiguration.after_hooks:type_name -> atmos.plugin.v1.ComponentHook + 50, // 70: atmos.plugin.v1.ComponentExecutionConfiguration.error_hooks:type_name -> atmos.plugin.v1.ComponentHook + 66, // 71: atmos.plugin.v1.ComponentExtraArguments.environment:type_name -> atmos.plugin.v1.ComponentExtraArguments.EnvironmentEntry + 34, // 72: atmos.plugin.v1.PrepareComponentResponse.inputs:type_name -> atmos.plugin.v1.ComponentValue + 46, // 73: atmos.plugin.v1.PrepareComponentResponse.state:type_name -> atmos.plugin.v1.ComponentStateIdentity + 47, // 74: atmos.plugin.v1.PrepareComponentResponse.files:type_name -> atmos.plugin.v1.ComponentGeneratedFile + 39, // 75: atmos.plugin.v1.PrepareComponentResponse.dependencies:type_name -> atmos.plugin.v1.ComponentDependency + 38, // 76: atmos.plugin.v1.PrepareComponentResponse.sources:type_name -> atmos.plugin.v1.ComponentSource + 20, // 77: atmos.plugin.v1.PrepareComponentResponse.diagnostics:type_name -> atmos.plugin.v1.Diagnostic + 48, // 78: atmos.plugin.v1.PrepareComponentResponse.execution:type_name -> atmos.plugin.v1.ComponentExecutionConfiguration + 67, // 79: atmos.plugin.v1.PrepareComponentResponse.input_origins:type_name -> atmos.plugin.v1.PrepareComponentResponse.InputOriginsEntry + 52, // 80: atmos.plugin.v1.PrepareComponentResponse.errors:type_name -> atmos.plugin.v1.ComponentErrorsConfiguration + 55, // 81: atmos.plugin.v1.PrepareComponentResponse.exclude:type_name -> atmos.plugin.v1.ComponentExclude + 56, // 82: atmos.plugin.v1.PrepareComponentResponse.iam:type_name -> atmos.plugin.v1.ComponentIam + 34, // 83: atmos.plugin.v1.PrepareComponentResponse.encryption:type_name -> atmos.plugin.v1.ComponentValue + 68, // 84: atmos.plugin.v1.PrepareComponentResponse.feature_flags:type_name -> atmos.plugin.v1.PrepareComponentResponse.FeatureFlagsEntry + 17, // 85: atmos.plugin.v1.PrepareComponentResponse.logs:type_name -> atmos.plugin.v1.LogEntry + 53, // 86: atmos.plugin.v1.ComponentErrorsConfiguration.retry:type_name -> atmos.plugin.v1.ComponentRetryPolicy + 54, // 87: atmos.plugin.v1.ComponentErrorsConfiguration.ignore:type_name -> atmos.plugin.v1.ComponentIgnorePolicy + 69, // 88: atmos.plugin.v1.ComponentIgnorePolicy.signals:type_name -> atmos.plugin.v1.ComponentIgnorePolicy.SignalsEntry + 34, // 89: atmos.plugin.v1.ComponentIam.web_identity_token:type_name -> atmos.plugin.v1.ComponentValue + 46, // 90: atmos.plugin.v1.ResolveComponentStateResponse.state:type_name -> atmos.plugin.v1.ComponentStateIdentity + 38, // 91: atmos.plugin.v1.ResolveComponentStateResponse.sources:type_name -> atmos.plugin.v1.ComponentSource + 20, // 92: atmos.plugin.v1.ResolveComponentStateResponse.diagnostics:type_name -> atmos.plugin.v1.Diagnostic + 17, // 93: atmos.plugin.v1.ResolveComponentStateResponse.logs:type_name -> atmos.plugin.v1.LogEntry + 34, // 94: atmos.plugin.v1.ComponentOperation.OptionsEntry.value:type_name -> atmos.plugin.v1.ComponentValue + 16, // 95: atmos.plugin.v1.PrepareComponentResponse.InputOriginsEntry.value:type_name -> atmos.plugin.v1.SourceLocation + 34, // 96: atmos.plugin.v1.ComponentIgnorePolicy.SignalsEntry.value:type_name -> atmos.plugin.v1.ComponentValue + 8, // 97: atmos.plugin.v1.Info.Describe:input_type -> atmos.plugin.v1.DescribeRequest + 10, // 98: atmos.plugin.v1.Info.Configure:input_type -> atmos.plugin.v1.ConfigureRequest + 18, // 99: atmos.plugin.v1.Log.Write:input_type -> atmos.plugin.v1.LogRequest + 11, // 100: atmos.plugin.v1.AuthProvider.Validate:input_type -> atmos.plugin.v1.ProviderRequest + 11, // 101: atmos.plugin.v1.AuthProvider.Authenticate:input_type -> atmos.plugin.v1.ProviderRequest + 23, // 102: atmos.plugin.v1.AuthProvider.Refresh:input_type -> atmos.plugin.v1.RefreshRequest + 11, // 103: atmos.plugin.v1.AuthProvider.Logout:input_type -> atmos.plugin.v1.ProviderRequest + 11, // 104: atmos.plugin.v1.AuthProvider.Environment:input_type -> atmos.plugin.v1.ProviderRequest + 11, // 105: atmos.plugin.v1.AuthProvider.Paths:input_type -> atmos.plugin.v1.ProviderRequest + 26, // 106: atmos.plugin.v1.AuthProvider.PrepareEnvironment:input_type -> atmos.plugin.v1.PrepareEnvironmentRequest + 12, // 107: atmos.plugin.v1.AuthIdentity.Validate:input_type -> atmos.plugin.v1.IdentityRequest + 29, // 108: atmos.plugin.v1.AuthIdentity.Authenticate:input_type -> atmos.plugin.v1.IdentityAuthenticateRequest + 12, // 109: atmos.plugin.v1.AuthIdentity.Logout:input_type -> atmos.plugin.v1.IdentityRequest + 12, // 110: atmos.plugin.v1.AuthIdentity.Environment:input_type -> atmos.plugin.v1.IdentityRequest + 12, // 111: atmos.plugin.v1.AuthIdentity.Paths:input_type -> atmos.plugin.v1.IdentityRequest + 30, // 112: atmos.plugin.v1.AuthIdentity.PrepareEnvironment:input_type -> atmos.plugin.v1.IdentityPrepareRequest + 31, // 113: atmos.plugin.v1.Commands.Run:input_type -> atmos.plugin.v1.CommandRequest + 43, // 114: atmos.plugin.v1.ComponentDiscovery.Discover:input_type -> atmos.plugin.v1.DiscoverComponentsRequest + 45, // 115: atmos.plugin.v1.ComponentValidation.Validate:input_type -> atmos.plugin.v1.ComponentRequest + 45, // 116: atmos.plugin.v1.ComponentPreparation.Prepare:input_type -> atmos.plugin.v1.ComponentRequest + 45, // 117: atmos.plugin.v1.ComponentState.Resolve:input_type -> atmos.plugin.v1.ComponentRequest + 9, // 118: atmos.plugin.v1.Info.Describe:output_type -> atmos.plugin.v1.DescribeResponse + 72, // 119: atmos.plugin.v1.Info.Configure:output_type -> google.protobuf.Empty + 72, // 120: atmos.plugin.v1.Log.Write:output_type -> google.protobuf.Empty + 21, // 121: atmos.plugin.v1.AuthProvider.Validate:output_type -> atmos.plugin.v1.ValidateResponse + 15, // 122: atmos.plugin.v1.AuthProvider.Authenticate:output_type -> atmos.plugin.v1.AuthenticateEvent + 24, // 123: atmos.plugin.v1.AuthProvider.Refresh:output_type -> atmos.plugin.v1.RefreshResponse + 72, // 124: atmos.plugin.v1.AuthProvider.Logout:output_type -> google.protobuf.Empty + 25, // 125: atmos.plugin.v1.AuthProvider.Environment:output_type -> atmos.plugin.v1.EnvironmentResponse + 28, // 126: atmos.plugin.v1.AuthProvider.Paths:output_type -> atmos.plugin.v1.PathsResponse + 25, // 127: atmos.plugin.v1.AuthProvider.PrepareEnvironment:output_type -> atmos.plugin.v1.EnvironmentResponse + 21, // 128: atmos.plugin.v1.AuthIdentity.Validate:output_type -> atmos.plugin.v1.ValidateResponse + 15, // 129: atmos.plugin.v1.AuthIdentity.Authenticate:output_type -> atmos.plugin.v1.AuthenticateEvent + 72, // 130: atmos.plugin.v1.AuthIdentity.Logout:output_type -> google.protobuf.Empty + 25, // 131: atmos.plugin.v1.AuthIdentity.Environment:output_type -> atmos.plugin.v1.EnvironmentResponse + 28, // 132: atmos.plugin.v1.AuthIdentity.Paths:output_type -> atmos.plugin.v1.PathsResponse + 25, // 133: atmos.plugin.v1.AuthIdentity.PrepareEnvironment:output_type -> atmos.plugin.v1.EnvironmentResponse + 33, // 134: atmos.plugin.v1.Commands.Run:output_type -> atmos.plugin.v1.CommandEvent + 44, // 135: atmos.plugin.v1.ComponentDiscovery.Discover:output_type -> atmos.plugin.v1.DiscoverComponentsResponse + 21, // 136: atmos.plugin.v1.ComponentValidation.Validate:output_type -> atmos.plugin.v1.ValidateResponse + 51, // 137: atmos.plugin.v1.ComponentPreparation.Prepare:output_type -> atmos.plugin.v1.PrepareComponentResponse + 57, // 138: atmos.plugin.v1.ComponentState.Resolve:output_type -> atmos.plugin.v1.ResolveComponentStateResponse + 118, // [118:139] is the sub-list for method output_type + 97, // [97:118] is the sub-list for method input_type + 97, // [97:97] is the sub-list for extension type_name + 97, // [97:97] is the sub-list for extension extendee + 0, // [0:97] is the sub-list for field type_name } func init() { file_atmos_plugin_v1_plugin_proto_init() } @@ -4754,16 +4809,16 @@ func file_atmos_plugin_v1_plugin_proto_init() { (*AuthenticateEvent_Interaction)(nil), (*AuthenticateEvent_Result)(nil), } - file_atmos_plugin_v1_plugin_proto_msgTypes[19].OneofWrappers = []any{ + file_atmos_plugin_v1_plugin_proto_msgTypes[20].OneofWrappers = []any{ (*RefreshResponse_Credentials)(nil), (*RefreshResponse_Unsupported)(nil), } - file_atmos_plugin_v1_plugin_proto_msgTypes[28].OneofWrappers = []any{ + file_atmos_plugin_v1_plugin_proto_msgTypes[29].OneofWrappers = []any{ (*CommandEvent_Stdout)(nil), (*CommandEvent_Stderr)(nil), (*CommandEvent_Exit)(nil), } - file_atmos_plugin_v1_plugin_proto_msgTypes[31].OneofWrappers = []any{ + file_atmos_plugin_v1_plugin_proto_msgTypes[32].OneofWrappers = []any{ (*ComponentValueStep_Attribute)(nil), (*ComponentValueStep_Index)(nil), } @@ -4773,9 +4828,9 @@ func file_atmos_plugin_v1_plugin_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_atmos_plugin_v1_plugin_proto_rawDesc), len(file_atmos_plugin_v1_plugin_proto_rawDesc)), NumEnums: 4, - NumMessages: 65, + NumMessages: 66, NumExtensions: 0, - NumServices: 8, + NumServices: 9, }, GoTypes: file_atmos_plugin_v1_plugin_proto_goTypes, DependencyIndexes: file_atmos_plugin_v1_plugin_proto_depIdxs, diff --git a/sdk/proto/atmos/plugin/v1/plugin_grpc.pb.go b/sdk/proto/atmos/plugin/v1/plugin_grpc.pb.go index bd48e39bb7b..09a04a900a2 100644 --- a/sdk/proto/atmos/plugin/v1/plugin_grpc.pb.go +++ b/sdk/proto/atmos/plugin/v1/plugin_grpc.pb.go @@ -161,6 +161,132 @@ var Info_ServiceDesc = grpc.ServiceDesc{ Metadata: "atmos/plugin/v1/plugin.proto", } +const ( + Log_Write_FullMethodName = "/atmos.plugin.v1.Log/Write" +) + +// LogClient is the client API for Log service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +// +// Log is served by Atmos on the Atmos API broker connection, next to the API services, and called by the +// plugin. It delivers LogEntry messages while a call is still running, instead of in the response where they +// show only when the call ends. Atmos renders each entry through its logger on the UI channel (stderr), +// scoped to the component and stack of the call, with secret masking, and drops entries below the Atmos log +// level. Entries arrive in the order of the calls, and a call returns only after Atmos has rendered its +// entries, so a plugin that waits for its last call before it returns the result shows every entry before the +// result. Delivery never changes the outcome of the call and is never part of a result. A call that fails with +// UNAVAILABLE, PERMISSION_DENIED, UNIMPLEMENTED, or FAILED_PRECONDITION delivered nothing, and the plugin then +// returns those entries in the logs field of its response. Entries delivered here are never repeated there. +// Like the API services, Log accepts only calls that carry the active invocation ID in the +// atmos-invocation-id metadata. +type LogClient interface { + Write(ctx context.Context, in *LogRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) +} + +type logClient struct { + cc grpc.ClientConnInterface +} + +func NewLogClient(cc grpc.ClientConnInterface) LogClient { + return &logClient{cc} +} + +func (c *logClient) Write(ctx context.Context, in *LogRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(emptypb.Empty) + err := c.cc.Invoke(ctx, Log_Write_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// LogServer is the server API for Log service. +// All implementations must embed UnimplementedLogServer +// for forward compatibility. +// +// Log is served by Atmos on the Atmos API broker connection, next to the API services, and called by the +// plugin. It delivers LogEntry messages while a call is still running, instead of in the response where they +// show only when the call ends. Atmos renders each entry through its logger on the UI channel (stderr), +// scoped to the component and stack of the call, with secret masking, and drops entries below the Atmos log +// level. Entries arrive in the order of the calls, and a call returns only after Atmos has rendered its +// entries, so a plugin that waits for its last call before it returns the result shows every entry before the +// result. Delivery never changes the outcome of the call and is never part of a result. A call that fails with +// UNAVAILABLE, PERMISSION_DENIED, UNIMPLEMENTED, or FAILED_PRECONDITION delivered nothing, and the plugin then +// returns those entries in the logs field of its response. Entries delivered here are never repeated there. +// Like the API services, Log accepts only calls that carry the active invocation ID in the +// atmos-invocation-id metadata. +type LogServer interface { + Write(context.Context, *LogRequest) (*emptypb.Empty, error) + mustEmbedUnimplementedLogServer() +} + +// UnimplementedLogServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedLogServer struct{} + +func (UnimplementedLogServer) Write(context.Context, *LogRequest) (*emptypb.Empty, error) { + return nil, status.Error(codes.Unimplemented, "method Write not implemented") +} +func (UnimplementedLogServer) mustEmbedUnimplementedLogServer() {} +func (UnimplementedLogServer) testEmbeddedByValue() {} + +// UnsafeLogServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to LogServer will +// result in compilation errors. +type UnsafeLogServer interface { + mustEmbedUnimplementedLogServer() +} + +func RegisterLogServer(s grpc.ServiceRegistrar, srv LogServer) { + // If the following call panics, it indicates UnimplementedLogServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&Log_ServiceDesc, srv) +} + +func _Log_Write_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(LogRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(LogServer).Write(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Log_Write_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(LogServer).Write(ctx, req.(*LogRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// Log_ServiceDesc is the grpc.ServiceDesc for Log service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var Log_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "atmos.plugin.v1.Log", + HandlerType: (*LogServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Write", + Handler: _Log_Write_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "atmos/plugin/v1/plugin.proto", +} + const ( AuthProvider_Validate_FullMethodName = "/atmos.plugin.v1.AuthProvider/Validate" AuthProvider_Authenticate_FullMethodName = "/atmos.plugin.v1.AuthProvider/Authenticate" diff --git a/tests/terragrunt_streaming_test.go b/tests/terragrunt_streaming_test.go new file mode 100644 index 00000000000..9c2f6406a34 --- /dev/null +++ b/tests/terragrunt_streaming_test.go @@ -0,0 +1,160 @@ +package tests + +import ( + "fmt" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// stampedLine is one line a process wrote to a stream, with the moment this test read it. +type stampedLine struct { + At time.Time + Text string +} + +// stampedWriter records the lines a process writes, as it writes them, so a test can ask what was already +// visible at a given moment. It stands in for a terminal that is watched while the command runs. +type stampedWriter struct { + mutex sync.Mutex + partial string + lines []stampedLine +} + +func (w *stampedWriter) Write(p []byte) (int, error) { + w.mutex.Lock() + defer w.mutex.Unlock() + now := time.Now() + w.partial += string(p) + for { + line, rest, found := strings.Cut(w.partial, "\n") + if !found { + break + } + w.lines = append(w.lines, stampedLine{At: now, Text: line}) + w.partial = rest + } + return len(p), nil +} + +// find returns the first line that contains every text, or false. +func (w *stampedWriter) find(texts ...string) (stampedLine, bool) { + w.mutex.Lock() + defer w.mutex.Unlock() + for _, line := range w.lines { + matches := true + for _, text := range texts { + matches = matches && strings.Contains(line.Text, text) + } + if matches { + return line, true + } + } + return stampedLine{}, false +} + +func (w *stampedWriter) text() string { + w.mutex.Lock() + defer w.mutex.Unlock() + var all strings.Builder + for _, line := range w.lines { + all.WriteString(line.Text + "\n") + } + return all.String() +} + +// buildGateTool compiles the acceptance helper that blocks until a file exists. It is the same Go helper +// that stands in for tools elsewhere in the plugin's acceptance tests, so no shell is involved. +func buildGateTool(t *testing.T) string { + t.Helper() + name := "gate" + if runtime.GOOS == "windows" { + name += ".exe" + } + output := filepath.Join(t.TempDir(), name) + build := exec.Command("go", "build", "-o", output, "./fixtures/toolprobe") + build.Dir = filepath.Join(repoRoot, "plugins", "terragrunt") + if combined, err := build.CombinedOutput(); err != nil { + t.Skipf("cannot build the gate helper: %v\n%s", err, combined) + } + return output +} + +// A unit whose inputs run a command that stays open until the test releases it, like a slow run_cmd, a +// registry fetch, or an STS exchange does in real use. +const slowUnit = `terraform { source = "../../../modules/unit" } +inputs = { greeting = run_cmd("--terragrunt-quiet", "%s", "--wait-for", "%s") } +` + +// TestTerragruntLogsReachTheTerminalWhileAUnitIsStillEvaluating runs the real CLI, the real plugin, and +// real OpenTofu. A unit's evaluation is held open by a command; the test watches stderr as the process +// writes it and releases the command only after the earlier log line of that unit is visible. If the plugin +// returned its log events with the result, the line could not appear first, the command would never be +// released, and the unit would fail on the helper's own time limit. +func TestTerragruntLogsReachTheTerminalWhileAUnitIsStillEvaluating(t *testing.T) { + if testing.Short() { + t.Skip("builds the Terragrunt plugin and runs OpenTofu") + } + ensureAtmosRunner(t) + pluginPackage := buildTerragruntPluginPackage(t) + project := newTerragruntProject(t, pluginPackage, newFakeAtmosPro(t)) + gateTool := buildGateTool(t) + gate := filepath.Join(t.TempDir(), "released") + project.write("live/dev/slow/terragrunt.hcl", fmt.Sprintf(slowUnit, filepath.ToSlash(gateTool), filepath.ToSlash(gate))) + + run := func(args ...string) (*stampedWriter, *stampedWriter, chan error) { + cmd := atmosRunner.Command(args...) + cmd.Dir = project.root + cmd.Env = append(cmd.Env, "NO_COLOR=1", "ATMOS_TELEMETRY_ENABLED=false", "TF_IN_AUTOMATION=true") + stdout, stderr := &stampedWriter{}, &stampedWriter{} + cmd.Stdout, cmd.Stderr = stdout, stderr + require.NoError(t, cmd.Start()) + done := make(chan error, 1) + go func() { done <- cmd.Wait() }() + return stdout, stderr, done + } + + t.Run("an earlier log line is on screen before the command it precedes finishes", func(t *testing.T) { + stdout, stderr, done := run("terraform", "plan", "slow", "-s", "dev", "--logs-level=Debug") + defer func() { _ = os.WriteFile(gate, nil, 0o600) }() + + require.Eventually(t, func() bool { + _, seen := stderr.find("Evaluating unit", "component=slow", "stack=dev") + return seen + }, 2*time.Minute, 10*time.Millisecond, "the unit's log line never appeared while its command was open:\n%s", stderr.text()) + // Only preparing the unit scopes an event to its component and stack, and preparing is the call that + // runs the held command right after logging this line. + early, _ := stderr.find("Evaluating unit", "component=slow", "stack=dev") + select { + case err := <-done: + t.Fatalf("the command finished before it was released (%v), so the line was not delivered live:\n%s", err, stderr.text()) + default: + } + assert.Contains(t, early.Text, "unit=live/dev/slow") + assert.Contains(t, early.Text, "plugin=terragrunt") + + released := time.Now() + require.NoError(t, os.WriteFile(gate, nil, 0o600)) + err := <-done + finished := time.Now() + require.NoError(t, err, "stderr:\n%s", stderr.text()) + assert.True(t, early.At.Before(released), "line at %s, release at %s", early.At, released) + assert.True(t, released.Before(finished)) + assert.NotContains(t, stdout.text(), "Evaluating unit", "log events never reach the data channel") + }) + + t.Run("the default level shows no engine events", func(t *testing.T) { + stdout, stderr, done := run("terraform", "plan", "slow", "-s", "dev") + require.NoError(t, <-done, "stderr:\n%s", stderr.text()) + assert.NotContains(t, stderr.text(), "Evaluating unit") + assert.NotContains(t, stdout.text(), "Evaluating unit") + }) +} From 50488ae0d8f64a57793e4c13cf5b4d12a8dd0a26 Mon Sep 17 00:00:00 2001 From: Erik Osterman Date: Sun, 1 Nov 2026 09:23:57 -0600 Subject: [PATCH 02/28] test(plugin): count only Atmos goroutines in the live-log cancellation test Runtime and scheduler goroutines come and go, so a raw goroutine count made the leak check flaky. Co-Authored-By: Claude Sonnet 5.5 --- .../adapter/component/logs_live_test.go | 24 +++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/pkg/plugin/adapter/component/logs_live_test.go b/pkg/plugin/adapter/component/logs_live_test.go index 675859c3ac8..0cf37a7f10c 100644 --- a/pkg/plugin/adapter/component/logs_live_test.go +++ b/pkg/plugin/adapter/component/logs_live_test.go @@ -160,6 +160,7 @@ func TestCancellingTheCallStopsLiveDeliveryWithoutLeakingGoroutines(t *testing.T _, err := provider.Prepare(t.Context(), liveRequest(t, warm, "live-logs")) require.NoError(t, err) baseline := settledGoroutines() + require.Positive(t, baseline, "the counter must see at least this test goroutine") root := t.TempDir() ctx, cancel := context.WithCancel(t.Context()) @@ -177,13 +178,15 @@ func TestCancellingTheCallStopsLiveDeliveryWithoutLeakingGoroutines(t *testing.T t.Fatal("cancelling the command did not stop the call") } // Poll directly: a testify Eventually condition runs on a goroutine of its own and would count itself. + // Count only goroutines running Atmos code, so runtime and scheduler goroutines that come and go + // (garbage collection workers, timers, the race detector) cannot make the comparison flaky. deadline := time.Now().Add(10 * time.Second) - for runtime.NumGoroutine() > baseline && time.Now().Before(deadline) { + for atmosGoroutines() > baseline && time.Now().Before(deadline) { time.Sleep(20 * time.Millisecond) } - if runtime.NumGoroutine() > baseline { + if atmosGoroutines() > baseline { buffer := make([]byte, 1<<18) - t.Fatalf("goroutines after cancel: %d, baseline %d\n%s", runtime.NumGoroutine(), baseline, buffer[:runtime.Stack(buffer, true)]) + t.Fatalf("Atmos goroutines after cancel: %d, baseline %d\n%s", atmosGoroutines(), baseline, buffer[:runtime.Stack(buffer, true)]) } // Only the warm-up call produced a last entry: the cancelled call never reached its end. assert.Equal(t, 1, strings.Count(output.String(), "last live entry")) @@ -193,5 +196,18 @@ func TestCancellingTheCallStopsLiveDeliveryWithoutLeakingGoroutines(t *testing.T func settledGoroutines() int { runtime.GC() time.Sleep(200 * time.Millisecond) - return runtime.NumGoroutine() + return atmosGoroutines() +} + +// atmosGoroutines counts goroutines with a frame in Atmos code. +func atmosGoroutines() int { + buffer := make([]byte, 1<<20) + buffer = buffer[:runtime.Stack(buffer, true)] + count := 0 + for _, stack := range strings.Split(string(buffer), "\n\n") { + if strings.Contains(stack, "github.com/cloudposse/atmos/") { + count++ + } + } + return count } From 9e5c1a32c327c9afbeab1c13bb190e2cfefeef57 Mon Sep 17 00:00:00 2001 From: Erik Osterman Date: Wed, 11 Nov 2026 15:17:58 -0600 Subject: [PATCH 03/28] test(plugin): verify concurrent log order and document retention --- .../terragrunt/internal/engine/logs_test.go | 21 ++++++++++++++----- sdk/api/logs.go | 9 ++++---- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/plugins/terragrunt/internal/engine/logs_test.go b/plugins/terragrunt/internal/engine/logs_test.go index e5e99cb6483..62322e90a31 100644 --- a/plugins/terragrunt/internal/engine/logs_test.go +++ b/plugins/terragrunt/internal/engine/logs_test.go @@ -160,20 +160,31 @@ func TestLogSinkForwardsEventsInOrderInsteadOfCollectingThem(t *testing.T) { func TestLogSinkForwardingKeepsOrderAcrossConcurrentUnits(t *testing.T) { sink := NewLogSink("debug", "") - var forwarded []int - sink.Forward(func(entry *model.LogEntry) { forwarded = append(forwarded, len(entry.Fields["unit"])) }) + forwarded := make(map[string][]string) + var total int + sink.Forward(func(entry *model.LogEntry) { + forwarded[entry.Fields["unit"]] = append(forwarded[entry.Fields["unit"]], entry.Message) + total++ + }) l := logger(t, sink) var wg sync.WaitGroup for unit := range 8 { wg.Go(func() { - for range 50 { - l.WithField("unit", strings.Repeat("u", unit+1)).Info("working") + for sequence := range 50 { + l.WithField("unit", strings.Repeat("u", unit+1)).Info(fmt.Sprint(sequence)) } }) } wg.Wait() // The deliverer is never called concurrently, so it needs no lock of its own. - assert.Len(t, forwarded, 400) + assert.Equal(t, 400, total) + for unit := range 8 { + var want []string + for sequence := range 50 { + want = append(want, fmt.Sprint(sequence)) + } + assert.Equal(t, want, forwarded[strings.Repeat("u", unit+1)]) + } } func TestLogSinkEventsFollowTheLevelAndAreRelativeToTheRoot(t *testing.T) { diff --git a/sdk/api/logs.go b/sdk/api/logs.go index ff25bc4a89a..9612d4cebb5 100644 --- a/sdk/api/logs.go +++ b/sdk/api/logs.go @@ -65,8 +65,9 @@ func WithLogFlush(wait time.Duration) LogOption { // when Atmos renders more slowly than the plugin logs, Send waits for room in the queue, so the plugin slows to // the speed of the terminal. Send never fails the call, and it stops waiting when the call is cancelled. // -// Entries that Atmos did not take, because the log service is unavailable, come back from Close so the plugin -// can return them in its response, where Atmos renders them when the call ends. Entries delivered live are +// Entries that Atmos did not take, because the log service is unavailable, are retained up to the queue +// capacity for Close to return in the response; further entries are counted as omitted. The default capacity +// is 1,024 entries and WithLogQueue changes it. Entries delivered live are // never returned, so nothing is shown twice. An entry whose delivery was cut off in flight, by cancellation or // an optional flush cap, is counted as omitted rather than returned: it may already be on screen. type LogStream struct { @@ -92,8 +93,8 @@ type LogStream struct { } // OpenLogs starts delivering log entries for the invocation. It never fails: when the Atmos API is not -// configured or the invocation is unknown, every entry comes back from Close instead, which is how plugins -// returned entries before live delivery existed. The caller must call Close before it returns the result. +// configured or the invocation is unknown, Close returns up to the queue capacity (1,024 by default), +// followed by an omission warning if more entries were sent. The caller must call Close before returning. // //nolint:lintroller // Pure SDK helper; the standalone SDK cannot import host perf tracking. func (c *Client) OpenLogs(ctx context.Context, invocationID string, options ...LogOption) *LogStream { From 3419f183d42f4302fcd3d21b2d6f08feb1df850c Mon Sep 17 00:00:00 2001 From: Erik Osterman Date: Wed, 11 Nov 2026 15:18:41 -0600 Subject: [PATCH 04/28] fix(sdk): cap live log batches at bridge limit --- sdk/api/logs.go | 7 +++++-- sdk/api/logs_test.go | 21 +++++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/sdk/api/logs.go b/sdk/api/logs.go index 9612d4cebb5..685d4f1ece9 100644 --- a/sdk/api/logs.go +++ b/sdk/api/logs.go @@ -17,6 +17,8 @@ const ( DefaultLogQueue = 1024 // DefaultLogBatch bounds the entries sent in one call, so a backlog drains in a few calls. DefaultLogBatch = 64 + // MaxLogBatch matches the host bridge limit on entries per Write call. + MaxLogBatch = 1024 // DefaultLogFlush is how long Close waits for Atmos to render the entries still queued. Zero waits until // every entry is delivered or the call is cancelled, so no entry is lost to a slow terminal. DefaultLogFlush = time.Duration(0) @@ -37,13 +39,14 @@ func WithLogQueue(entries int) LogOption { } } -// WithLogBatch sets how many entries one call to Atmos carries at most. Values below one are ignored. +// WithLogBatch sets how many entries one call to Atmos carries at most, capped at MaxLogBatch. +// Values below one are ignored. // //nolint:lintroller // Pure SDK helper; the standalone SDK cannot import host perf tracking. func WithLogBatch(entries int) LogOption { return func(s *LogStream) { if entries > 0 { - s.batch = entries + s.batch = min(entries, MaxLogBatch) } } } diff --git a/sdk/api/logs_test.go b/sdk/api/logs_test.go index 076d9857e45..6ef2d28662c 100644 --- a/sdk/api/logs_test.go +++ b/sdk/api/logs_test.go @@ -29,11 +29,15 @@ type logFixture struct { gate chan struct{} received chan struct{} failWith error + maxBatch int } func newLogFixture() *logFixture { return &logFixture{received: make(chan struct{}, 1024)} } func (f *logFixture) Write(ctx context.Context, request *pluginv1.LogRequest) (*emptypb.Empty, error) { + if f.maxBatch > 0 && len(request.GetEntries()) > f.maxBatch { + return nil, status.Error(codes.InvalidArgument, "batch too large") + } if f.gate != nil { select { case <-f.gate: @@ -142,6 +146,23 @@ func TestLogStreamPreservesOrderAcrossBatches(t *testing.T) { } } +func TestLogStreamCapsOversizedBatches(t *testing.T) { + fixture := newLogFixture() + fixture.maxBatch = MaxLogBatch + fixture.gate = make(chan struct{}) + stream := logClient(t, fixture).OpenLogs(t.Context(), "id", WithLogQueue(2048), WithLogBatch(2048)) + for i := range 1500 { + stream.Send(entry(fmt.Sprint(i))) + } + close(fixture.gate) + if got := stream.Close(); len(got) != 0 { + t.Fatalf("undelivered: %v", messages(got)) + } + if got := fixture.delivered(); len(got) != 1500 { + t.Fatalf("delivered %d entries, want 1500", len(got)) + } +} + func TestLogStreamReturnsEntriesWhenTheServiceIsUnavailable(t *testing.T) { t.Parallel() denied := &logFixture{failWith: status.Error(codes.PermissionDenied, "denied"), received: make(chan struct{}, 8)} From c8c8494312b2347abd0ee5b4d07438e6031e46ae Mon Sep 17 00:00:00 2001 From: Erik Osterman Date: Wed, 11 Nov 2026 15:19:12 -0600 Subject: [PATCH 05/28] fix(sdk): avoid replay after ambiguous log delivery --- sdk/api/logs.go | 5 +++-- sdk/api/logs_test.go | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/sdk/api/logs.go b/sdk/api/logs.go index 685d4f1ece9..e951bb3e08a 100644 --- a/sdk/api/logs.go +++ b/sdk/api/logs.go @@ -72,7 +72,8 @@ func WithLogFlush(wait time.Duration) LogOption { // capacity for Close to return in the response; further entries are counted as omitted. The default capacity // is 1,024 entries and WithLogQueue changes it. Entries delivered live are // never returned, so nothing is shown twice. An entry whose delivery was cut off in flight, by cancellation or -// an optional flush cap, is counted as omitted rather than returned: it may already be on screen. +// an optional flush cap or an ambiguous transport failure, is counted as omitted rather than returned: it +// may already be on screen. type LogStream struct { sink pluginv1.LogClient ctx context.Context @@ -294,7 +295,7 @@ func (s *LogStream) deliver(batch []*pluginv1.LogEntry) { // the response instead. func notDelivered(err error) bool { switch status.Code(err) { - case codes.Unavailable, codes.PermissionDenied, codes.Unimplemented, codes.FailedPrecondition, codes.InvalidArgument, codes.ResourceExhausted: + case codes.PermissionDenied, codes.Unimplemented, codes.FailedPrecondition, codes.InvalidArgument, codes.ResourceExhausted: return true default: return false diff --git a/sdk/api/logs_test.go b/sdk/api/logs_test.go index 6ef2d28662c..c53eaabc47f 100644 --- a/sdk/api/logs_test.go +++ b/sdk/api/logs_test.go @@ -191,8 +191,9 @@ func TestLogStreamReturnsEntriesWhenTheServiceIsUnavailable(t *testing.T) { func TestLogStreamDoesNotRepeatEntriesCutOffInFlight(t *testing.T) { t.Parallel() for name, failure := range map[string]error{ - "internal": status.Error(codes.Internal, "boom"), - "unknown": errors.New("unknown"), + "internal": status.Error(codes.Internal, "boom"), + "unavailable": status.Error(codes.Unavailable, "connection lost"), + "unknown": errors.New("unknown"), } { t.Run(name, func(t *testing.T) { t.Parallel() From fb7536ecd77fae3788b76e22927ec9ff3a642246 Mon Sep 17 00:00:00 2001 From: Erik Osterman Date: Wed, 11 Nov 2026 15:19:44 -0600 Subject: [PATCH 06/28] test(sdk): assert exact cancellation omission count --- sdk/api/logs_test.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/sdk/api/logs_test.go b/sdk/api/logs_test.go index c53eaabc47f..ae1c766ee88 100644 --- a/sdk/api/logs_test.go +++ b/sdk/api/logs_test.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "runtime" - "strings" "sync" "testing" "time" @@ -282,7 +281,7 @@ func TestLogStreamCancellationReleasesWaitingSenders(t *testing.T) { t.Fatal("cancellation left a sender waiting") } got := messages(stream.Close()) - if len(got) != 1 || !strings.HasSuffix(got[0], "log events were not shown") { + if !equal(got, []string{"3 log events were not shown"}) { t.Fatalf("a cancelled call must report what it could not show: %v", got) } } From a0adb895ed0cc2b1ac3f81e6ed179c0e97e8062e Mon Sep 17 00:00:00 2001 From: Erik Osterman Date: Wed, 11 Nov 2026 15:20:30 -0600 Subject: [PATCH 07/28] fix(plugin): identify rejected log batches --- pkg/plugin/bridge/logs.go | 6 ++++-- pkg/plugin/bridge/logs_test.go | 5 +++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/pkg/plugin/bridge/logs.go b/pkg/plugin/bridge/logs.go index 5874fd666f9..6e08570bb11 100644 --- a/pkg/plugin/bridge/logs.go +++ b/pkg/plugin/bridge/logs.go @@ -4,11 +4,13 @@ package bridge import ( "context" + "fmt" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/types/known/emptypb" + errUtils "github.com/cloudposse/atmos/errors" "github.com/cloudposse/atmos/pkg/perf" pluginv1 "github.com/cloudposse/atmos/pkg/plugin/proto/atmos/plugin/v1" ) @@ -33,10 +35,10 @@ func (s *Server) Write(ctx context.Context, request *pluginv1.LogRequest) (*empt } defer call.done() if call.Logs == nil { - return nil, status.Error(codes.PermissionDenied, "log delivery not granted") + return nil, fmt.Errorf("%w: %w", errUtils.ErrPluginUnauthorized, status.Error(codes.PermissionDenied, "log delivery not granted")) } if len(request.GetEntries()) > maxLogBatch { - return nil, status.Error(codes.InvalidArgument, "too many log entries") + return nil, fmt.Errorf("%w: %w", errUtils.ErrPluginPayloadTooLarge, status.Error(codes.InvalidArgument, "too many log entries")) } call.Logs.WriteLogs(call.Context, request.GetEntries()) return &emptypb.Empty{}, nil diff --git a/pkg/plugin/bridge/logs_test.go b/pkg/plugin/bridge/logs_test.go index fe5054ce063..257b9b79c3d 100644 --- a/pkg/plugin/bridge/logs_test.go +++ b/pkg/plugin/bridge/logs_test.go @@ -11,6 +11,7 @@ import ( "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" + errUtils "github.com/cloudposse/atmos/errors" pluginv1 "github.com/cloudposse/atmos/pkg/plugin/proto/atmos/plugin/v1" ) @@ -55,9 +56,13 @@ func TestLogDeliveryIsGrantedPerInvocation(t *testing.T) { require.Equal(t, codes.PermissionDenied, status.Code(err), id) } + _, err = server.Write(with("withheld"), &pluginv1.LogRequest{Entries: logEntries("hidden")}) + require.ErrorIs(t, err, errUtils.ErrPluginUnauthorized) + // A batch above the bound is refused so one call cannot hold the terminal. _, err = server.Write(with("granted"), &pluginv1.LogRequest{Entries: logEntries(make([]string, maxLogBatch+1)...)}) require.Equal(t, codes.InvalidArgument, status.Code(err)) + require.ErrorIs(t, err, errUtils.ErrPluginPayloadTooLarge) // After the invocation ends nothing is accepted, so a late call cannot print after the result. granted() From da90b1b7a2bca0fcf08729a0ac74b2538a69d849 Mon Sep 17 00:00:00 2001 From: Erik Osterman Date: Wed, 11 Nov 2026 15:39:23 -0600 Subject: [PATCH 08/28] test(plugin): isolate cancelled call goroutines --- .../adapter/component/logs_live_test.go | 61 +++++++++++++------ 1 file changed, 41 insertions(+), 20 deletions(-) diff --git a/pkg/plugin/adapter/component/logs_live_test.go b/pkg/plugin/adapter/component/logs_live_test.go index 0cf37a7f10c..b8683fb41dc 100644 --- a/pkg/plugin/adapter/component/logs_live_test.go +++ b/pkg/plugin/adapter/component/logs_live_test.go @@ -2,6 +2,7 @@ package component import ( "context" + "fmt" "os" "path/filepath" "runtime" @@ -155,12 +156,23 @@ func TestCancellingTheCallStopsLiveDeliveryWithoutLeakingGoroutines(t *testing.T output := captureLiveLogs(t, charm.DebugLevel) provider := fixtureProvider(t) // Warm up so the baseline includes the long-lived runtime goroutines. + beforeWarm := atmosGoroutines() warm := t.TempDir() require.NoError(t, os.WriteFile(filepath.Join(warm, "gate"), nil, 0o600)) _, err := provider.Prepare(t.Context(), liveRequest(t, warm, "live-logs")) require.NoError(t, err) - baseline := settledGoroutines() - require.Positive(t, baseline, "the counter must see at least this test goroutine") + // The interrupt goroutine can outlive Prepare briefly. Wait for this specific + // warm-up goroutine to exit before taking the baseline. + waitFor(t, "warm-up interrupt goroutine exits", func() bool { + for id, stack := range atmosGoroutines() { + if _, existed := beforeWarm[id]; !existed && strings.Contains(stack, "runtime/native.newInterrupt.func1") { + return false + } + } + return true + }) + baseline := atmosGoroutines() + require.NotEmpty(t, baseline, "the snapshot must see at least this test goroutine") root := t.TempDir() ctx, cancel := context.WithCancel(t.Context()) @@ -177,37 +189,46 @@ func TestCancellingTheCallStopsLiveDeliveryWithoutLeakingGoroutines(t *testing.T case <-time.After(20 * time.Second): t.Fatal("cancelling the command did not stop the call") } - // Poll directly: a testify Eventually condition runs on a goroutine of its own and would count itself. - // Count only goroutines running Atmos code, so runtime and scheduler goroutines that come and go - // (garbage collection workers, timers, the race detector) cannot make the comparison flaky. + // Compare goroutine identities, not counts: an older goroutine exiting cannot + // conceal a goroutine leaked by the cancelled call. Poll directly so the + // assertion itself does not introduce a goroutine into the snapshot. deadline := time.Now().Add(10 * time.Second) - for atmosGoroutines() > baseline && time.Now().Before(deadline) { + var remaining map[string]string + for { + remaining = newAtmosGoroutines(baseline) + if len(remaining) == 0 || time.Now().After(deadline) { + break + } time.Sleep(20 * time.Millisecond) } - if atmosGoroutines() > baseline { - buffer := make([]byte, 1<<18) - t.Fatalf("Atmos goroutines after cancel: %d, baseline %d\n%s", atmosGoroutines(), baseline, buffer[:runtime.Stack(buffer, true)]) + if len(remaining) != 0 { + t.Fatalf("Atmos goroutines created after baseline remain after cancel: %v", remaining) } // Only the warm-up call produced a last entry: the cancelled call never reached its end. assert.Equal(t, 1, strings.Count(output.String(), "last live entry")) assert.Equal(t, 2, strings.Count(output.String(), "first live entry")) } -func settledGoroutines() int { - runtime.GC() - time.Sleep(200 * time.Millisecond) - return atmosGoroutines() -} - -// atmosGoroutines counts goroutines with a frame in Atmos code. -func atmosGoroutines() int { +// atmosGoroutines snapshots the identities and stacks of goroutines running Atmos code. +func atmosGoroutines() map[string]string { buffer := make([]byte, 1<<20) buffer = buffer[:runtime.Stack(buffer, true)] - count := 0 + stacks := make(map[string]string) for _, stack := range strings.Split(string(buffer), "\n\n") { if strings.Contains(stack, "github.com/cloudposse/atmos/") { - count++ + var id string + if _, err := fmt.Sscanf(stack, "goroutine %s", &id); err == nil { + stacks[id] = stack + } } } - return count + return stacks +} + +func newAtmosGoroutines(baseline map[string]string) map[string]string { + current := atmosGoroutines() + for id := range baseline { + delete(current, id) + } + return current } From 8274064b48c8a6391aef4831779f9900bb4ca98f Mon Sep 17 00:00:00 2001 From: Erik Osterman Date: Wed, 11 Nov 2026 17:47:30 -0600 Subject: [PATCH 09/28] test(terragrunt): fix streaming test gate setup Release the gate for the default-level subtest and fail when its helper cannot be built so test failures are not hidden. --- tests/terragrunt_streaming_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/terragrunt_streaming_test.go b/tests/terragrunt_streaming_test.go index 9c2f6406a34..fccd4f19735 100644 --- a/tests/terragrunt_streaming_test.go +++ b/tests/terragrunt_streaming_test.go @@ -83,7 +83,7 @@ func buildGateTool(t *testing.T) string { build := exec.Command("go", "build", "-o", output, "./fixtures/toolprobe") build.Dir = filepath.Join(repoRoot, "plugins", "terragrunt") if combined, err := build.CombinedOutput(); err != nil { - t.Skipf("cannot build the gate helper: %v\n%s", err, combined) + t.Fatalf("cannot build the gate helper: %v\n%s", err, combined) } return output } @@ -152,6 +152,7 @@ func TestTerragruntLogsReachTheTerminalWhileAUnitIsStillEvaluating(t *testing.T) }) t.Run("the default level shows no engine events", func(t *testing.T) { + require.NoError(t, os.WriteFile(gate, nil, 0o600)) stdout, stderr, done := run("terraform", "plan", "slow", "-s", "dev") require.NoError(t, <-done, "stderr:\n%s", stderr.text()) assert.NotContains(t, stderr.text(), "Evaluating unit") From 0004353540a5ff1ac4eaa23f64360183eebafa58 Mon Sep 17 00:00:00 2001 From: Erik Osterman Date: Thu, 12 Nov 2026 18:22:01 -0600 Subject: [PATCH 10/28] docs(terragrunt): combine native support announcement --- ...-10-29-native-terragrunt-compatibility.mdx | 29 +++++++++-- ...2026-10-29-native-terragrunt-discovery.mdx | 48 ------------------- website/src/data/roadmap.js | 2 +- 3 files changed, 27 insertions(+), 52 deletions(-) delete mode 100644 website/blog/2026-10-29-native-terragrunt-discovery.mdx diff --git a/website/blog/2026-10-29-native-terragrunt-compatibility.mdx b/website/blog/2026-10-29-native-terragrunt-compatibility.mdx index cb6c6b65dda..9ecad32d445 100644 --- a/website/blog/2026-10-29-native-terragrunt-compatibility.mdx +++ b/website/blog/2026-10-29-native-terragrunt-compatibility.mdx @@ -1,12 +1,12 @@ --- slug: native-terragrunt-compatibility -title: "Native Terragrunt Integration Beyond Discovery" +title: "Experimental Native Terragrunt Support" authors: [osterman] tags: [feature, experimental] cast: "/casts/demo/fixtures/terragrunt-native/plan.cast" castTitle: "Native Terragrunt discovery and planning" --- -Teams adopting Atmos alongside Terragrunt need more than a list of units. Existing HCL must retain its backend identity, generated-file ownership, and dependencies when Atmos prepares an operation. This experimental extension builds on native discovery with additional host adapters and compatibility checks. +Teams with working Terragrunt configurations should be able to use Atmos without first refactoring those configurations into Atmos conventions. Experimental native Terragrunt support lets you keep the HCL, units, and stacks you have, discover them as Atmos components, and run them with their backend identity, generated files, and dependencies intact. @@ -17,6 +17,18 @@ import TryExample from '@site/src/components/TryExample'; [View the full example](/examples/terragrunt-native) +## The problem + +You already use Terragrunt to manage Terraform. Now you want Atmos for toolchain management, vendoring, scaffolding, authentication, Kubernetes, Helm, and the rest of your infrastructure. You want to use what you have, without translating every Terragrunt unit into Atmos YAML first. + +Supporting existing Terragrunt configuration makes Atmos easier to adopt incrementally, without choosing between Atmos and Terragrunt. + +## How discovery works + +An explicitly enabled configuration plugin exposes discovered units as Terraform components. Atmos owns execution order, authentication setup, toolchain selection, and working directories. Native mode evaluates HCL without launching the Terragrunt executable. + +Discovery expands explicit stacks in memory. Planning and applying use isolated Atmos workdirs while preserving each unit's state location. Projects that do not enable discovery never scan for Terragrunt configuration. + ## Try it locally The example keeps a Terragrunt unit under `live/`, discovers it as an Atmos Terraform component, and plans a built-in `terraform_data` resource with OpenTofu. It requires no cloud credentials or Terragrunt executable. @@ -88,6 +100,17 @@ import: The units below `live/dev` become components of the importing stack, and no extra stack appears. Import the same unit from a shared mixin and every stack that uses the mixin gets it. If an imported unit has the same component name as a YAML component in that stack, Atmos names both and stops. Discovery paths, patterns, and symlink rules are described in the [migration guide](/migration/terragrunt#discovery-paths). +## Plan only what changed + +Affected selection discovers units at both Git revisions and compares them, together with their dependency relationships. A unit is affected when a file it reads changes: its `terragrunt.hcl` and includes, local module files, var files, generated and backend inputs, hook scripts, the lock file beside it, and files read by functions such as `file()` and `read_terragrunt_config()`. With `--include-dependents`, Atmos also follows the dependency graph: + +```shell +atmos describe affected --base origin/main +atmos terraform plan --affected --ref origin/main --include-dependents +``` + +When a path depends on the environment, dependency outputs, or another value Atmos cannot evaluate, the unit depends on everything in its scope, so the result errs toward planning more rather than less. + ## Inspect the executor The default instance table shows `Component`, `Stack`, `Type`, and `Engine`. A native Terragrunt unit remains a Terraform component. Its engine reflects the selected Terraform or OpenTofu executable. @@ -112,7 +135,7 @@ The same flow works across runners, which is how Atmos Pro plans on one runner a ## The settings Terragrunt users already rely on -`terraform_binary`, `errors` retry and ignore policies, `exclude`, feature flags, `iam_role` and web identity tokens, `remote_state` encryption, `tfr://` registry sources, and the `read-config` and `init-from-module` hook lifecycles all run natively. Atmos assumes IAM roles in process on top of the identity you already use, applies retry and ignore policies around each Terraform step, and names every unit an `exclude` block skips. Functions such as `get_aws_account_id()` use the same identity as the rest of the run. +Native mode also handles `terraform_binary`, `errors` retry and ignore policies, `exclude`, feature flags, `iam_role` and web identity tokens, `remote_state` encryption, `tfr://` registry sources, and the `read-config` and `init-from-module` hook lifecycles. Atmos assumes IAM roles in process on top of the identity you already use, applies retry and ignore policies around each Terraform step, and names every unit an `exclude` block skips. Functions such as `get_aws_account_id()` use the same identity as the rest of the run. ## Atmos Pro and executable mode diff --git a/website/blog/2026-10-29-native-terragrunt-discovery.mdx b/website/blog/2026-10-29-native-terragrunt-discovery.mdx deleted file mode 100644 index 79fb6fcedae..00000000000 --- a/website/blog/2026-10-29-native-terragrunt-discovery.mdx +++ /dev/null @@ -1,48 +0,0 @@ ---- -slug: native-terragrunt-discovery -title: "Experimental Native Terragrunt Discovery" -authors: [osterman] -tags: [feature, experimental] ---- -Teams with working Terragrunt configurations should be able to use Atmos without refactoring those configurations into Atmos conventions. Experimental native Terragrunt support is a step toward that: keep the HCL, units, and stacks you have, and adopt the Atmos capabilities you need alongside them. - - - -## The Problem - -You already use Terragrunt to manage Terraform. Now you want Atmos for toolchain management, vendoring, scaffolding, authentication, Kubernetes, Helm, and the rest of your infrastructure. You want to use what you have, without first translating every Terragrunt unit into Atmos YAML. - -Supporting existing Terragrunt configuration makes Atmos easier to get started with. Teams can adopt it incrementally, without choosing between Atmos and Terragrunt. - -## Use Atmos with Your Existing Terragrunt Configuration - -An explicitly enabled configuration plugin exposes discovered units as Terraform components. Atmos owns execution order, authentication setup, toolchain selection, and working directories. The native path evaluates HCL without launching the Terragrunt executable. - -Discovery uses an in-memory expansion for explicit stacks. Planning and applying use isolated Atmos workdirs while preserving the local backend's state path. Projects that do not enable discovery do not scan for Terragrunt configuration. - -## How to Use It - -This implementation requires a local development build; the Terragrunt plugin is not yet published. Follow the [package setup and fixture instructions](https://github.com/cloudposse/atmos/tree/feat/component-plugin-contracts/plugins/terragrunt#build-and-run) then enable discovery with [config set](/cli/commands/config/config-set): - -```shell -atmos config set plugins.packages.terragrunt.path /absolute/path/to/plugins/terragrunt -atmos config set components.terraform.terragrunt.enabled true -atmos config set components.terraform.terragrunt.mode native -atmos config set --type=yaml components.terraform.terragrunt.discovery.included_paths '["live/**"]' -atmos config set components.terraform.terragrunt.discovery.enabled true -``` - -Use [list instances](/cli/commands/list/list-instances) to inspect the discovered units and [Terraform plan](/cli/commands/terraform/plan) to plan them: - -```shell -atmos list instances -atmos terraform plan --all -``` - -Affected selection compares units and dependency relationships at both Git revisions. Shared includes, local module files, and explicit stack definitions can mark their consuming units affected; `--include-dependents` also follows the dependency graph. Reads inside unevaluated input expressions and arbitrary dynamic glob patterns still need additional source tracking. - -The current scope covers local module sources and local backends. Remote sources and backends, Terragrunt hooks, saved-plan apply, and state-function integration remain incomplete. Do not assume full Terragrunt compatibility. The package instructions list the supported and rejected constructs. - -## Get Involved - -Review the [Terragrunt integration requirements](https://github.com/cloudposse/atmos/blob/feat/component-plugin-contracts/docs/prd/terragrunt-support.md) and help identify configurations that need additional compatibility tests. diff --git a/website/src/data/roadmap.js b/website/src/data/roadmap.js index 800a9f6b36e..fe4c977e8fa 100644 --- a/website/src/data/roadmap.js +++ b/website/src/data/roadmap.js @@ -509,7 +509,7 @@ export const roadmapConfig = { status: 'in-progress', milestones: [ { label: 'Native Terragrunt state and compatibility adapters', status: 'in-progress', quarter: 'q4-2026', experimental: true, pr: 3576, prd: 'terragrunt-support', changelog: 'native-terragrunt-compatibility', description: 'Extend native HCL adoption with hooks and extra arguments run under Atmos, state-function dispatch, reviewed-plan bindings, explicit imports, file provenance, backend and generation semantics, and installed-package acceptance.' }, - { label: 'Native Terragrunt unit and stack discovery', status: 'in-progress', quarter: 'q4-2026', experimental: true, pr: 3571, prd: 'terragrunt-support', changelog: 'native-terragrunt-discovery', description: 'Opt into local HCL discovery and native Terraform execution with preserved dependency ordering, state paths, scoped environments, and isolated workdirs. Revision-aware affected selection is implemented; published installation and broader compatibility remain in progress.' }, + { label: 'Native Terragrunt unit and stack discovery', status: 'in-progress', quarter: 'q4-2026', experimental: true, pr: 3571, prd: 'terragrunt-support', changelog: 'native-terragrunt-compatibility', description: 'Opt into local HCL discovery and native Terraform execution with preserved dependency ordering, state paths, scoped environments, and isolated workdirs. Revision-aware affected selection is implemented; published installation and broader compatibility remain in progress.' }, { label: 'Configurable concurrent YAML exec evaluation', status: 'shipped', quarter: 'q4-2026', changelog: 'parallel-yaml-exec', docs: '/cli/configuration/settings/functions/exec', description: 'Run ordinary !exec expressions concurrently within a document evaluation with a configurable limit, preserving result placement and serial execution by default.', benefits: 'Reduce time spent waiting on independent configuration lookups without new tags or grouping syntax.' }, { label: 'Native Go authentication plugins and OIDC starter', status: 'in-progress', quarter: 'q4-2026', experimental: true, changelog: 'native-auth-plugins', docs: '/cli/commands/plugin/usage', description: 'Scaffold and test a Go OIDC provider, chain its broker credentials into built-in identities, and distribute compiled plugins through OCI with explicit installation and release locks.' }, { label: 'Official public plugin catalog and secret-store authentication', status: 'in-progress', quarter: 'q4-2026', experimental: true, changelog: 'official-auth-secrets-plugins', docs: '/cli/configuration/plugins#official-secret-store-authentication', description: 'Discover official plugins through the default Cloud Posse OCI catalog and use auth-secrets to read explicitly configured secret-store credentials into an environment identity. Plugin manifests control independent package versions, with native platform validation and public OCI publication before catalog updates.', benefits: 'Install official plugins without configuring a registry, map selected secret values into child-process environment variables, and update individual plugins independently of Atmos releases.' }, From 13eac3e02de1d9aed069e730a2b329488bc98a61 Mon Sep 17 00:00:00 2001 From: Erik Osterman Date: Fri, 13 Nov 2026 07:46:13 -0600 Subject: [PATCH 11/28] test(terragrunt): bound and reap each streaming CLI run Each CLI run in the streaming acceptance test now has a per-run deadline, a wait delay for inherited pipes, and a cleanup that kills and reaps the process on every exit path, including early subtest failures. Co-Authored-By: Claude Opus 5.5 --- tests/terragrunt_streaming_test.go | 72 ++++++++++++++++++++++++------ 1 file changed, 58 insertions(+), 14 deletions(-) diff --git a/tests/terragrunt_streaming_test.go b/tests/terragrunt_streaming_test.go index fccd4f19735..83959aaaf3b 100644 --- a/tests/terragrunt_streaming_test.go +++ b/tests/terragrunt_streaming_test.go @@ -1,6 +1,7 @@ package tests import ( + "context" "fmt" "os" "os/exec" @@ -71,6 +72,28 @@ func (w *stampedWriter) text() string { return all.String() } +const ( + // The time one CLI run may take, so that a hung CLI or plugin fails its subtest instead of the whole suite. + cliRunTimeout = 5 * time.Minute + // How long a killed CLI's output pipes may stay open before the run stops waiting. + cliRunWaitDelay = 10 * time.Second +) + +// cliRun is one CLI process with its captured output. Done closes after the process has exited and been +// reaped; err holds its result from then on. +type cliRun struct { + stdout *stampedWriter + stderr *stampedWriter + done chan struct{} + err error +} + +// wait blocks until the process exits and returns its result. +func (r *cliRun) wait() error { + <-r.done + return r.err +} + // buildGateTool compiles the acceptance helper that blocks until a file exists. It is the same Go helper // that stands in for tools elsewhere in the plugin's acceptance tests, so no shell is involved. func buildGateTool(t *testing.T) string { @@ -110,20 +133,40 @@ func TestTerragruntLogsReachTheTerminalWhileAUnitIsStillEvaluating(t *testing.T) gate := filepath.Join(t.TempDir(), "released") project.write("live/dev/slow/terragrunt.hcl", fmt.Sprintf(slowUnit, filepath.ToSlash(gateTool), filepath.ToSlash(gate))) - run := func(args ...string) (*stampedWriter, *stampedWriter, chan error) { - cmd := atmosRunner.Command(args...) + run := func(t *testing.T, args ...string) *cliRun { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), cliRunTimeout) + cmd := atmosRunner.CommandContext(ctx, args...) cmd.Dir = project.root cmd.Env = append(cmd.Env, "NO_COLOR=1", "ATMOS_TELEMETRY_ENABLED=false", "TF_IN_AUTOMATION=true") - stdout, stderr := &stampedWriter{}, &stampedWriter{} - cmd.Stdout, cmd.Stderr = stdout, stderr - require.NoError(t, cmd.Start()) - done := make(chan error, 1) - go func() { done <- cmd.Wait() }() - return stdout, stderr, done + // A plugin or tool the CLI started can keep the output pipes open after the CLI is killed; stop waiting + // for them once the CLI itself has exited. + cmd.WaitDelay = cliRunWaitDelay + started := &cliRun{stdout: &stampedWriter{}, stderr: &stampedWriter{}, done: make(chan struct{})} + cmd.Stdout, cmd.Stderr = started.stdout, started.stderr + if err := cmd.Start(); err != nil { + cancel() + t.Fatalf("cannot start the CLI: %v", err) + } + go func() { + started.err = cmd.Wait() + if ctx.Err() != nil { + started.err = fmt.Errorf("the CLI did not finish within %s: %w", cliRunTimeout, started.err) + } + cancel() + close(started.done) + }() + // Kill and reap the CLI on every exit path, including a failed assertion that ends the subtest early. + t.Cleanup(func() { + cancel() + <-started.done + }) + return started } t.Run("an earlier log line is on screen before the command it precedes finishes", func(t *testing.T) { - stdout, stderr, done := run("terraform", "plan", "slow", "-s", "dev", "--logs-level=Debug") + cli := run(t, "terraform", "plan", "slow", "-s", "dev", "--logs-level=Debug") + stdout, stderr := cli.stdout, cli.stderr defer func() { _ = os.WriteFile(gate, nil, 0o600) }() require.Eventually(t, func() bool { @@ -134,8 +177,8 @@ func TestTerragruntLogsReachTheTerminalWhileAUnitIsStillEvaluating(t *testing.T) // runs the held command right after logging this line. early, _ := stderr.find("Evaluating unit", "component=slow", "stack=dev") select { - case err := <-done: - t.Fatalf("the command finished before it was released (%v), so the line was not delivered live:\n%s", err, stderr.text()) + case <-cli.done: + t.Fatalf("the command finished before it was released (%v), so the line was not delivered live:\n%s", cli.err, stderr.text()) default: } assert.Contains(t, early.Text, "unit=live/dev/slow") @@ -143,7 +186,7 @@ func TestTerragruntLogsReachTheTerminalWhileAUnitIsStillEvaluating(t *testing.T) released := time.Now() require.NoError(t, os.WriteFile(gate, nil, 0o600)) - err := <-done + err := cli.wait() finished := time.Now() require.NoError(t, err, "stderr:\n%s", stderr.text()) assert.True(t, early.At.Before(released), "line at %s, release at %s", early.At, released) @@ -153,8 +196,9 @@ func TestTerragruntLogsReachTheTerminalWhileAUnitIsStillEvaluating(t *testing.T) t.Run("the default level shows no engine events", func(t *testing.T) { require.NoError(t, os.WriteFile(gate, nil, 0o600)) - stdout, stderr, done := run("terraform", "plan", "slow", "-s", "dev") - require.NoError(t, <-done, "stderr:\n%s", stderr.text()) + cli := run(t, "terraform", "plan", "slow", "-s", "dev") + stdout, stderr := cli.stdout, cli.stderr + require.NoError(t, cli.wait(), "stderr:\n%s", stderr.text()) assert.NotContains(t, stderr.text(), "Evaluating unit") assert.NotContains(t, stdout.text(), "Evaluating unit") }) From 94e86774c7aade3f70ca6d852812cd1f3165611f Mon Sep 17 00:00:00 2001 From: Erik Osterman Date: Fri, 13 Nov 2026 07:47:40 -0600 Subject: [PATCH 12/28] fix(sdk): bound fallback logs by encoded response bytes Fallback log entries retained for the response are now bounded by their encoded protobuf size (1 MiB by default, configurable with WithLogBytes) as well as by count. Room for the omission warning is always reserved, and entries that do not fit are counted as omitted. Co-Authored-By: Claude Opus 5.5 --- sdk/api/logs.go | 64 +++++++++++++++++++++++++++++----- sdk/api/logs_test.go | 83 ++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 135 insertions(+), 12 deletions(-) diff --git a/sdk/api/logs.go b/sdk/api/logs.go index e951bb3e08a..adf18589d33 100644 --- a/sdk/api/logs.go +++ b/sdk/api/logs.go @@ -3,11 +3,14 @@ package api import ( "context" "fmt" + "math" "sync" "time" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/proto" pluginv1 "github.com/cloudposse/atmos/sdk/proto/atmos/plugin/v1" ) @@ -22,8 +25,22 @@ const ( // DefaultLogFlush is how long Close waits for Atmos to render the entries still queued. Zero waits until // every entry is delivered or the call is cancelled, so no entry is lost to a slow terminal. DefaultLogFlush = time.Duration(0) + // DefaultLogBytes bounds the encoded size of the entries Close returns, including the omission warning, so + // that they stay well under the 16 MiB plugin message limit together with the rest of the response. + DefaultLogBytes = 1 << 20 ) +// omissionFormat is the message of the entry that reports how many entries were not shown. +const omissionFormat = "%d log events were not shown" + +// logTagBytes is the largest encoded tag of a log entry field in a response; two bytes hold field numbers up +// to 2047. +const logTagBytes = 2 + +// omissionReserve is the encoded size of the largest possible omission warning, which the byte bound always +// leaves room for. +var omissionReserve = encodedLogSize(omission(math.MaxInt)) + // LogOption configures a LogStream. type LogOption func(*LogStream) @@ -51,6 +68,18 @@ func WithLogBatch(entries int) LogOption { } } +// WithLogBytes sets the encoded size, in bytes, that the entries Close returns may take in a response, +// including the omission warning. Entries that do not fit are counted as omitted. Values below one are ignored. +// +//nolint:lintroller // Pure SDK helper; the standalone SDK cannot import host perf tracking. +func WithLogBytes(size int) LogOption { + return func(s *LogStream) { + if size > 0 { + s.bytes = size + } + } +} + // WithLogFlush caps how long Close waits for queued entries to reach Atmos; entries cut off by the cap are // counted as omitted. The default is no cap. Values below zero are ignored. // @@ -69,8 +98,9 @@ func WithLogFlush(wait time.Duration) LogOption { // the speed of the terminal. Send never fails the call, and it stops waiting when the call is cancelled. // // Entries that Atmos did not take, because the log service is unavailable, are retained up to the queue -// capacity for Close to return in the response; further entries are counted as omitted. The default capacity -// is 1,024 entries and WithLogQueue changes it. Entries delivered live are +// capacity and the response byte bound for Close to return in the response; further entries are counted as +// omitted. The default capacity is 1,024 entries and WithLogQueue changes it; the default byte bound is 1 MiB +// of encoded entries and WithLogBytes changes it. Entries delivered live are // never returned, so nothing is shown twice. An entry whose delivery was cut off in flight, by cancellation or // an optional flush cap or an ambiguous transport failure, is counted as omitted rather than returned: it // may already be on screen. @@ -79,6 +109,7 @@ type LogStream struct { ctx context.Context cancel context.CancelFunc capacity int + bytes int batch int flush time.Duration wake chan struct{} @@ -89,6 +120,8 @@ type LogStream struct { mu sync.Mutex queue []*pluginv1.LogEntry undelivered []*pluginv1.LogEntry + // The encoded size of undelivered as a repeated field of a response. + retained int omitted int unavailable bool closing bool @@ -97,12 +130,12 @@ type LogStream struct { } // OpenLogs starts delivering log entries for the invocation. It never fails: when the Atmos API is not -// configured or the invocation is unknown, Close returns up to the queue capacity (1,024 by default), -// followed by an omission warning if more entries were sent. The caller must call Close before returning. +// configured or the invocation is unknown, Close returns up to the queue capacity (1,024 by default) and the +// byte bound (1 MiB by default), followed by an omission warning if more entries were sent. The caller must call Close before returning. // //nolint:lintroller // Pure SDK helper; the standalone SDK cannot import host perf tracking. func (c *Client) OpenLogs(ctx context.Context, invocationID string, options ...LogOption) *LogStream { - stream := &LogStream{capacity: DefaultLogQueue, batch: DefaultLogBatch, flush: DefaultLogFlush, wake: make(chan struct{}, 1), done: make(chan struct{})} + stream := &LogStream{capacity: DefaultLogQueue, bytes: DefaultLogBytes, batch: DefaultLogBatch, flush: DefaultLogFlush, wake: make(chan struct{}, 1), done: make(chan struct{})} for _, apply := range options { apply(stream) } @@ -164,14 +197,27 @@ func (s *LogStream) wakeSenders() { s.space.Broadcast() } -// keepLocked remembers an undelivered entry for the response, up to the queue bound, which keeps the response -// within the transport's message size. The caller holds the lock. +// keepLocked remembers an undelivered entry for the response, up to the queue bound and the byte bound, which +// keeps the response within the transport's message size. An entry that does not fit in the bytes left is +// counted as omitted, and room for the omission warning is always kept. The caller holds the lock. func (s *LogStream) keepLocked(entry *pluginv1.LogEntry) { - if len(s.undelivered) >= s.capacity { + size := encodedLogSize(entry) + if len(s.undelivered) >= s.capacity || s.retained+size > s.bytes-omissionReserve { s.omitted++ return } s.undelivered = append(s.undelivered, entry) + s.retained += size +} + +// encodedLogSize is the size of an entry as one element of a repeated log field in a response. +func encodedLogSize(entry *pluginv1.LogEntry) int { + return logTagBytes + protowire.SizeBytes(proto.Size(entry)) +} + +// omission is the entry that reports how many entries were not shown. +func omission(count int) *pluginv1.LogEntry { + return &pluginv1.LogEntry{Level: pluginv1.LogLevel_LOG_LEVEL_WARN, Message: fmt.Sprintf(omissionFormat, count)} } // Close waits for queued entries to reach Atmos, for at most the flush cap when one is set, stops the stream, and returns @@ -205,7 +251,7 @@ func (s *LogStream) Close() []*pluginv1.LogEntry { s.queue = nil s.result = s.undelivered if s.omitted > 0 { - s.result = append(s.result, &pluginv1.LogEntry{Level: pluginv1.LogLevel_LOG_LEVEL_WARN, Message: fmt.Sprintf("%d log events were not shown", s.omitted)}) + s.result = append(s.result, omission(s.omitted)) } s.closed = true return append([]*pluginv1.LogEntry(nil), s.result...) diff --git a/sdk/api/logs_test.go b/sdk/api/logs_test.go index ae1c766ee88..52530719df2 100644 --- a/sdk/api/logs_test.go +++ b/sdk/api/logs_test.go @@ -4,7 +4,9 @@ import ( "context" "errors" "fmt" + "math" "runtime" + "strings" "sync" "testing" "time" @@ -13,6 +15,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/emptypb" pluginv1 "github.com/cloudposse/atmos/sdk/proto/atmos/plugin/v1" @@ -352,10 +355,10 @@ func TestLogStreamCloseIsIdempotentAndNilSafe(t *testing.T) { func TestLogStreamOptionsIgnoreInvalidValues(t *testing.T) { t.Parallel() - stream := (*Client)(nil).OpenLogs(t.Context(), "id", WithLogQueue(0), WithLogBatch(-1), WithLogFlush(-time.Second)) + stream := (*Client)(nil).OpenLogs(t.Context(), "id", WithLogQueue(0), WithLogBatch(-1), WithLogFlush(-time.Second), WithLogBytes(0)) defer stream.Close() - if stream.capacity != DefaultLogQueue || stream.batch != DefaultLogBatch || stream.flush != DefaultLogFlush { - t.Fatalf("invalid options changed defaults: %d %d %s", stream.capacity, stream.batch, stream.flush) + if stream.capacity != DefaultLogQueue || stream.batch != DefaultLogBatch || stream.flush != DefaultLogFlush || stream.bytes != DefaultLogBytes { + t.Fatalf("invalid options changed defaults: %d %d %s %d", stream.capacity, stream.batch, stream.flush, stream.bytes) } limited := (*Client)(nil).OpenLogs(t.Context(), "id", WithLogQueue(1)) limited.Send(entry("a")) @@ -365,6 +368,80 @@ func TestLogStreamOptionsIgnoreInvalidValues(t *testing.T) { } } +// responseSize is the encoded size of entries as a repeated field of a message, as a response carries them. +func responseSize(entries []*pluginv1.LogEntry) int { + return proto.Size(&pluginv1.LogRequest{Entries: entries}) +} + +func TestLogStreamBoundsReturnedEntriesByEncodedSize(t *testing.T) { + t.Parallel() + payload := strings.Repeat("x", 1000) + single := encodedLogSize(entry(payload)) + // Room for exactly three entries next to the omission warning. + budget := omissionReserve + 3*single + stream := (*Client)(nil).OpenLogs(t.Context(), "id", WithLogBytes(budget)) + for i := range 5 { + stream.Send(entry(fmt.Sprintf("%d%s", i, payload[1:]))) + } + got := stream.Close() + if len(got) != 4 { + t.Fatalf("returned %d entries, want 3 and a warning", len(got)) + } + if got[0].GetMessage()[0] != '0' || got[2].GetMessage()[0] != '2' { + t.Fatalf("returned entries out of order: %q .. %q", got[0].GetMessage()[:1], got[2].GetMessage()[:1]) + } + if last := got[3].GetMessage(); last != "2 log events were not shown" || got[3].GetLevel() != pluginv1.LogLevel_LOG_LEVEL_WARN { + t.Fatalf("warning = %v %q", got[3].GetLevel(), last) + } + if size := responseSize(got); size > budget { + t.Fatalf("returned %d bytes, budget %d", size, budget) + } +} + +func TestLogStreamOmitsAnOversizedEntryButKeepsLaterOnes(t *testing.T) { + t.Parallel() + budget := 4096 + stream := (*Client)(nil).OpenLogs(t.Context(), "id", WithLogBytes(budget)) + stream.Send(entry("before")) + stream.Send(&pluginv1.LogEntry{Message: "huge", Fields: map[string]string{"blob": strings.Repeat("é", budget)}}) + stream.Send(entry("after")) + got := stream.Close() + if !equal(messages(got), []string{"before", "after", "1 log events were not shown"}) { + t.Fatalf("returned = %v", messages(got)) + } + if size := responseSize(got); size > budget { + t.Fatalf("returned %d bytes, budget %d", size, budget) + } +} + +func TestLogStreamDefaultByteBoundHoldsAFullQueueOfLargeEntries(t *testing.T) { + t.Parallel() + payload := strings.Repeat("x", 4096) + stream := (*Client)(nil).OpenLogs(t.Context(), "id") + for range DefaultLogQueue { + stream.Send(entry(payload)) + } + got := stream.Close() + kept := len(got) - 1 + want := (DefaultLogBytes - omissionReserve) / encodedLogSize(entry(payload)) + if kept != want { + t.Fatalf("kept %d entries, want %d", kept, want) + } + if last := got[kept].GetMessage(); last != fmt.Sprintf("%d log events were not shown", DefaultLogQueue-want) { + t.Fatalf("warning = %q", last) + } + if size := responseSize(got); size > DefaultLogBytes { + t.Fatalf("returned %d bytes, bound %d", size, DefaultLogBytes) + } +} + +func TestOmissionReserveFitsTheLargestWarning(t *testing.T) { + t.Parallel() + if size := responseSize([]*pluginv1.LogEntry{omission(math.MaxInt)}); size > omissionReserve { + t.Fatalf("warning takes %d bytes, reserve %d", size, omissionReserve) + } +} + func stabilised() int { runtime.GC() time.Sleep(50 * time.Millisecond) From f5cc919b1e57f2952de267ae85963aad2bfcc6ff Mon Sep 17 00:00:00 2001 From: Erik Osterman Date: Fri, 13 Nov 2026 07:48:03 -0600 Subject: [PATCH 13/28] fix(plugin): warn that queued logs may be lost on cancellation When a plugin call is interrupted, times out, or is cancelled by its caller, the host now tells the user that log events the plugin had not yet delivered may not have been shown. The plugin's own omission count travels in the response that cancellation discards, so the host notice is qualified and carries no count. Co-Authored-By: Claude Opus 5.5 --- pkg/plugin/runtime/native/lifecycle.go | 17 +++- .../runtime/native/lifecycle_notice_test.go | 92 +++++++++++++++++++ 2 files changed, 108 insertions(+), 1 deletion(-) create mode 100644 pkg/plugin/runtime/native/lifecycle_notice_test.go diff --git a/pkg/plugin/runtime/native/lifecycle.go b/pkg/plugin/runtime/native/lifecycle.go index 9c8426048cf..77148e96797 100644 --- a/pkg/plugin/runtime/native/lifecycle.go +++ b/pkg/plugin/runtime/native/lifecycle.go @@ -31,6 +31,14 @@ var ( resetSignals = signal.Stop ) +// The omitted-logs notice is qualified because the host cannot know how many log events the +// plugin still had queued once the call was cancelled; the plugin's own count travels in the +// response that cancellation discards. +const omittedLogsNotice = "Log events the plugin had not yet delivered may not have been shown." + +// Warnings are routed through a variable so tests can observe what reaches the user. +var warn = ui.Warning + // interrupt is a context that ends on SIGINT or SIGTERM, like signal.NotifyContext, and also // remembers which signal arrived so Atmos can exit with the matching shell status. type interrupt struct { @@ -119,13 +127,20 @@ func (h *Handle) finishInvocation(callCtx context.Context, err error) error { } if h.interrupt != nil && h.interrupt.fired() { h.Close() - ui.Warning("Interrupted; the plugin process was stopped.") + warn("Interrupted; the plugin process was stopped.") + warn(omittedLogsNotice) return errors.Join(context.Canceled, errUtils.ExitCodeError{Code: h.interrupt.exitCode(), Silent: true}) } if deadlineExceeded(callCtx, err) { h.Close() + warn(omittedLogsNotice) return timeoutError(callCtx) } + // A caller that cancels the call (for example, after a sibling operation failed) gets the + // error unchanged, but the user still learns that the plugin's queued logs may be missing. + if errors.Is(callCtx.Err(), context.Canceled) { + warn(omittedLogsNotice) + } return err } diff --git a/pkg/plugin/runtime/native/lifecycle_notice_test.go b/pkg/plugin/runtime/native/lifecycle_notice_test.go new file mode 100644 index 00000000000..c9f4d72fa41 --- /dev/null +++ b/pkg/plugin/runtime/native/lifecycle_notice_test.go @@ -0,0 +1,92 @@ +package native + +import ( + "context" + "errors" + "os" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/require" + + errUtils "github.com/cloudposse/atmos/errors" + "github.com/cloudposse/atmos/pkg/plugin/testkit/fakeplugin" +) + +// captureWarnings records every warning the host shows the user for the rest of the test. +func captureWarnings(t *testing.T) func() []string { + t.Helper() + var mu sync.Mutex + var shown []string + previous := warn + warn = func(text string) { + mu.Lock() + defer mu.Unlock() + shown = append(shown, text) + } + t.Cleanup(func() { warn = previous }) + return func() []string { + mu.Lock() + defer mu.Unlock() + return append([]string(nil), shown...) + } +} + +// awaitResult waits for a running invocation to return after it was cancelled. +func awaitResult(t *testing.T, result <-chan error) error { + t.Helper() + select { + case err := <-result: + return err + case <-time.After(eventually): + t.Fatal("Invoke must return after cancellation") + return nil + } +} + +func TestCancelledInvocationTellsUserPluginLogsMayBeOmitted(t *testing.T) { + t.Run("interrupt", func(t *testing.T) { + shown := captureWarnings(t) + deliver := injectSignals(t) + handle, directory := startFake(t, t.Context(), fakeplugin.ModeHang) + _, result := runHanging(t, handle, directory, t.Context()) + deliver(os.Interrupt) + require.ErrorIs(t, awaitResult(t, result), context.Canceled) + require.Equal(t, []string{"Interrupted; the plugin process was stopped.", omittedLogsNotice}, shown()) + }) + t.Run("call timeout", func(t *testing.T) { + shown := captureWarnings(t) + handle, directory := startFake(t, t.Context(), fakeplugin.ModeHang, WithCallTimeout(500*time.Millisecond)) + _, result := runHanging(t, handle, directory, t.Context()) + require.ErrorIs(t, awaitResult(t, result), errUtils.ErrPluginTimeout) + require.Equal(t, []string{omittedLogsNotice}, shown()) + }) + t.Run("parent context", func(t *testing.T) { + shown := captureWarnings(t) + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + handle, directory := startFake(t, t.Context(), fakeplugin.ModeHang) + _, result := runHanging(t, handle, directory, ctx) + cancel() + err := awaitResult(t, result) + require.Error(t, err) + require.NotErrorIs(t, err, errUtils.ErrPluginTimeout, "a caller cancellation is not a timeout") + require.Equal(t, []string{omittedLogsNotice}, shown()) + }) +} + +func TestOmittedLogsNoticeOnlyFollowsCancellation(t *testing.T) { + shown := captureWarnings(t) + handle := &Handle{} + failure := errors.New("plugin failed") + + require.NoError(t, handle.finishInvocation(t.Context(), nil)) + require.ErrorIs(t, handle.finishInvocation(t.Context(), failure), failure) + require.Empty(t, shown(), "a completed or plainly failed call has delivered its logs in the response") + + ctx, cancel := context.WithCancel(t.Context()) + cancel() + require.ErrorIs(t, handle.finishInvocation(ctx, failure), failure, "a caller cancellation keeps the original error") + require.Equal(t, []string{omittedLogsNotice}, shown()) +} From 10fa05f794dc80bf0ce2fd700d5055c726048d0d Mon Sep 17 00:00:00 2001 From: Erik Osterman Date: Fri, 13 Nov 2026 14:08:55 -0600 Subject: [PATCH 14/28] fix(tests): build streaming helper with plugin toolchain --- tests/terragrunt_streaming_test.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/terragrunt_streaming_test.go b/tests/terragrunt_streaming_test.go index 83959aaaf3b..397ac26d48b 100644 --- a/tests/terragrunt_streaming_test.go +++ b/tests/terragrunt_streaming_test.go @@ -105,6 +105,8 @@ func buildGateTool(t *testing.T) string { output := filepath.Join(t.TempDir(), name) build := exec.Command("go", "build", "-o", output, "./fixtures/toolprobe") build.Dir = filepath.Join(repoRoot, "plugins", "terragrunt") + // This helper belongs to the plugin module, whose Go version can exceed the root module's. + build.Env = append(os.Environ(), "CGO_ENABLED=0", "GOTOOLCHAIN=auto", "GOWORK=off") if combined, err := build.CombinedOutput(); err != nil { t.Fatalf("cannot build the gate helper: %v\n%s", err, combined) } From 34728c296ed0a72e2ab26f95d43d623816fb9228 Mon Sep 17 00:00:00 2001 From: Erik Osterman Date: Fri, 13 Nov 2026 14:14:25 -0600 Subject: [PATCH 15/28] fix(plugin): validate IAM probes independently of module preparation --- pkg/plugin/adapter/component/calls.go | 3 +++ pkg/plugin/adapter/component/calls_test.go | 19 +++++++++++++++++++ pkg/plugin/adapter/component/main_test.go | 3 +++ pkg/plugin/adapter/component/responses.go | 17 +++++++++++++++++ 4 files changed, 42 insertions(+) diff --git a/pkg/plugin/adapter/component/calls.go b/pkg/plugin/adapter/component/calls.go index 6de1487c165..888cf2e3b1a 100644 --- a/pkg/plugin/adapter/component/calls.go +++ b/pkg/plugin/adapter/component/calls.go @@ -86,6 +86,9 @@ func (p *Provider) Prepare(ctx context.Context, input *pluginv1.ComponentRequest if err != nil { return err } + if request.GetOperation().GetMode() == "iam-probe" { + return checkIAMProbe(result) + } return checkPreparation(result) }) if err != nil { diff --git a/pkg/plugin/adapter/component/calls_test.go b/pkg/plugin/adapter/component/calls_test.go index 84871b324bd..231941684f2 100644 --- a/pkg/plugin/adapter/component/calls_test.go +++ b/pkg/plugin/adapter/component/calls_test.go @@ -446,3 +446,22 @@ func TestNonSchemaSettingsErrorStillNamesTheSection(t *testing.T) { require.ErrorIs(t, err, errUtils.ErrPluginInvalidConfig) assert.Contains(t, strings.Join(errUtils.AllDetails(err), "\n"), "components.terraform.terragrunt") } + +func TestProviderIAMProbeAcceptsRoleOnlyResponse(t *testing.T) { + p := fixtureProvider(t) + result, err := p.Prepare(t.Context(), &pluginv1.ComponentRequest{ + RootDirectory: t.TempDir(), Address: fixtureAddress(), + Operation: &pluginv1.ComponentOperation{Command: "plan", Mode: "iam-probe"}, + }) + require.NoError(t, err) + require.Equal(t, "arn:aws:iam::1:role/test", result.GetIam().GetRole()) + require.ErrorIs(t, checkPreparation(result), errUtils.ErrPluginProtocol) +} + +func TestIAMProbeRejectsModulePreparation(t *testing.T) { + t.Parallel() + require.NoError(t, checkIAMProbe(&pluginv1.PrepareComponentResponse{})) + require.ErrorIs(t, checkIAMProbe(nil), errUtils.ErrPluginProtocol) + require.ErrorIs(t, checkIAMProbe(&pluginv1.PrepareComponentResponse{ModuleSource: "./module"}), errUtils.ErrPluginProtocol) + require.ErrorIs(t, checkIAMProbe(&pluginv1.PrepareComponentResponse{Diagnostics: []*pluginv1.Diagnostic{{Message: "failure"}}}), errUtils.ErrPluginInvalidConfig) +} diff --git a/pkg/plugin/adapter/component/main_test.go b/pkg/plugin/adapter/component/main_test.go index 37003f5c180..33e2f5373b5 100644 --- a/pkg/plugin/adapter/component/main_test.go +++ b/pkg/plugin/adapter/component/main_test.go @@ -134,6 +134,9 @@ func (f *componentFixture) Prepare(ctx context.Context, request *pluginv1.Compon <-ctx.Done() return nil, status.FromContextError(ctx.Err()).Err() } + if request.GetOperation().GetMode() == "iam-probe" { + return &pluginv1.PrepareComponentResponse{Iam: &pluginv1.ComponentIam{Role: "arn:aws:iam::1:role/test"}}, nil + } var returned []*pluginv1.LogEntry switch request.GetOperation().GetCommand() { case "live-logs": diff --git a/pkg/plugin/adapter/component/responses.go b/pkg/plugin/adapter/component/responses.go index 2992e48f950..7ce5a81d83e 100644 --- a/pkg/plugin/adapter/component/responses.go +++ b/pkg/plugin/adapter/component/responses.go @@ -3,6 +3,8 @@ package component import ( "path/filepath" + "google.golang.org/protobuf/proto" + errUtils "github.com/cloudposse/atmos/errors" pluginv1 "github.com/cloudposse/atmos/pkg/plugin/proto/atmos/plugin/v1" ) @@ -96,3 +98,18 @@ func checkGeneratedFiles(files []*pluginv1.ComponentGeneratedFile) error { } return nil } + +// checkIAMProbe accepts only role settings and diagnostics; probing does not prepare a module. +func checkIAMProbe(result *pluginv1.PrepareComponentResponse) error { + if result == nil { + return errUtils.ErrPluginProtocol + } + if err := firstDiagnosticError(result.Diagnostics); err != nil { + return err + } + allowed := &pluginv1.PrepareComponentResponse{Iam: result.Iam, Diagnostics: result.Diagnostics} + if !proto.Equal(result, allowed) { + return errUtils.ErrPluginProtocol + } + return nil +} From c3ff4c75feb4c3da69ffec8ca1441fe8fb0261d9 Mon Sep 17 00:00:00 2001 From: Erik Osterman Date: Fri, 13 Nov 2026 14:34:48 -0600 Subject: [PATCH 16/28] test: separate tool preconditions and clean acceptance lint policy --- .golangci.yml | 3 + tests/cli_scaffold_source_oci_test.go | 22 +- tests/preconditions.go | 254 +----------------- tests/preconditions_tools.go | 262 +++++++++++++++++++ tests/terraform_floci_dag_test.go | 3 +- tests/yaml_func_terraform_output_jit_test.go | 2 +- tests/yaml_func_terraform_source_jit_test.go | 2 +- 7 files changed, 283 insertions(+), 265 deletions(-) create mode 100644 tests/preconditions_tools.go diff --git a/.golangci.yml b/.golangci.yml index 9dd846e806a..69e12160611 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -69,6 +69,9 @@ linters: provider-agnostic-auth: files: - "$all" + # Acceptance AWS credential checks and Floci SSM fixtures are AWS-specific. + - "!**/tests/preconditions.go" + - "!**/tests/terraform_floci_dag_test.go" - "!**/pkg/auth/providers/**" - "!**/pkg/store/providers/**" - "!**/pkg/auth/identities/**" diff --git a/tests/cli_scaffold_source_oci_test.go b/tests/cli_scaffold_source_oci_test.go index 604ab399c06..bc60e881436 100644 --- a/tests/cli_scaffold_source_oci_test.go +++ b/tests/cli_scaffold_source_oci_test.go @@ -59,9 +59,10 @@ func TestScaffoldGenerate_OCISource(t *testing.T) { }) target := filepath.Join(root, "output") - runAtmosForScaffoldTest(t, root, map[string]string{ - "XDG_CACHE_HOME": filepath.Join(t.TempDir(), ".cache"), - }, 2*time.Minute, + runAtmosForScaffoldTest( + t, root, map[string]string{ + "XDG_CACHE_HOME": filepath.Join(t.TempDir(), ".cache"), + }, 2*time.Minute, "scaffold", "generate", "oci://"+imageRef, target, "--defaults", "--no-git", @@ -99,7 +100,8 @@ func TestScaffoldGenerate_OCISourceUpdate(t *testing.T) { env := map[string]string{ "XDG_CACHE_HOME": filepath.Join(t.TempDir(), ".cache"), } - runAtmosForScaffoldTest(t, root, env, 2*time.Minute, + runAtmosForScaffoldTest( + t, root, env, 2*time.Minute, "scaffold", "generate", "oci://"+imageRef, target, "--defaults", "--git", @@ -120,7 +122,8 @@ func TestScaffoldGenerate_OCISourceUpdate(t *testing.T) { "file.txt": "updated content\n", }) - runAtmosForScaffoldTest(t, root, env, 2*time.Minute, + runAtmosForScaffoldTest( + t, root, env, 2*time.Minute, "scaffold", "generate", "oci://"+imageRef, target, "--defaults", "--update", @@ -138,7 +141,7 @@ func TestScaffoldGenerate_OCISourceUpdate(t *testing.T) { // that test alone was scaffold-generate-only CLI coverage; this is the `atmos // init` counterpart. // -// atmos init has no --defaults flag (unlike scaffold generate): the +// Atmos init has no --defaults flag (unlike scaffold generate): the // non-interactive equivalent here is --interactive=false, which also makes // executeInit fall back to the scaffold.yaml fields' declared defaults (see // ExecuteWithBaseRef's useDefaults parameter in pkg/generator/ui/ui.go, wired @@ -162,9 +165,10 @@ func TestInit_OCISource(t *testing.T) { }) target := filepath.Join(root, "output") - runAtmosForScaffoldTest(t, root, map[string]string{ - "XDG_CACHE_HOME": filepath.Join(t.TempDir(), ".cache"), - }, 2*time.Minute, + runAtmosForScaffoldTest( + t, root, map[string]string{ + "XDG_CACHE_HOME": filepath.Join(t.TempDir(), ".cache"), + }, 2*time.Minute, "init", "oci://"+imageRef, target, "--interactive=false", "--no-git", diff --git a/tests/preconditions.go b/tests/preconditions.go index 8b1c79d4c4b..20251fa3791 100644 --- a/tests/preconditions.go +++ b/tests/preconditions.go @@ -9,10 +9,8 @@ import ( "net/http" "os" "os/exec" - "path/filepath" "runtime" "strings" - "sync" "testing" "time" @@ -37,22 +35,6 @@ const ( envAWSProfile = "AWS_PROFILE" ) -var testToolPathLocks sync.Map - -type cachedTestTool struct { - Repo string - Version string - Binary string -} - -var cachedTestTools = []cachedTestTool{ - {Repo: "opentofu/opentofu", Version: "1.12.2", Binary: "tofu"}, - {Repo: "hashicorp/terraform", Version: "1.15.6", Binary: "terraform"}, - {Repo: "hashicorp/packer", Version: "1.14.2", Binary: "packer"}, - {Repo: "helmfile/helmfile", Version: "v1.1.0", Binary: "helmfile"}, - {Repo: "helm/helm", Version: "v3.19.2", Binary: "helm"}, -} - // ShouldCheckPreconditions returns true if precondition checks should be performed. // Set ATMOS_TEST_SKIP_PRECONDITION_CHECKS=true to bypass all precondition checks. func ShouldCheckPreconditions() bool { @@ -278,7 +260,7 @@ func probeGitHubRateLimit(client *http.Client, requestURL, token string) (*GitHu doer = &noRedirect } - apiResp, err := doer.Do(req) //nolint:gosec // requestURL is always either the hardcoded githubRateLimitURL constant or a test-controlled httptest server URL, never external/user input. + apiResp, err := doer.Do(req) if err != nil { return nil, fmt.Errorf("%w: GitHub rate-limit probe: %w", errUtils.ErrHTTPRequestFailed, err) } @@ -449,238 +431,6 @@ func RequireLiveGitHubAuthenticated(t *testing.T) *GitHubRateLimitInfo { return requireGitHubAccess(t, token) } -// RequireExecutable checks if an executable is available in PATH. -// Unlike requireExecutablePath, a bypass (ATMOS_TEST_SKIP_PRECONDITION_CHECKS=true) -// is a full no-op here: callers that only need a boolean gate, not the resolved -// path, don't need the tool to actually be resolvable when checks are disabled. -func RequireExecutable(t *testing.T, name string, purpose string) { - t.Helper() - - prependCachedTestTool(name) - - if !ShouldCheckPreconditions() { - return - } - - if _, err := exec.LookPath(name); err != nil { - t.Skipf("'%s' not found in PATH: required for %s. Install the tool or set ATMOS_TEST_SKIP_PRECONDITION_CHECKS=true", - name, purpose) - } -} - -// requireExecutablePath resolves and returns the executable's path, skipping -// the test if it is not found. Callers that need the resolved path (to, e.g., -// copy the binary into an isolated per-test directory) should use this instead -// of a separate, independent exec.LookPath call afterward. Two independent -// LookPath calls create a TOCTOU race: the Windows acceptance job runs -// packages concurrently, and another package's test can mutate the shared -// Atmos toolchain cache directory (see prependCachedTestTool) between the two -// calls, turning a binary that existed a moment ago into a spurious -// "not found" error. Resolving the path exactly once here closes that window. -// These constants bound how long requireExecutablePath polls exec.LookPath -// before giving up. CI installs each toolchain binary and updates PATH in an -// earlier job step; on some runners (observed on Windows) that update has -// occasionally not been visible yet to the very first lookup here, so a poll -// avoids failing on a one-off resolution lag rather than the tool actually -// being absent. 15s (rather than a token couple of seconds) is deliberate: -// the Windows acceptance job runs many Go packages' test binaries -// concurrently on constrained runners, and this exact race recurred in CI -// even after closing one confirmed root cause (a test writing real installs -// into the shared toolchain cache dir, see the pkg/toolchain fix referenced -// in this repo's git history) -- so a short window risks masking further, -// not-yet-identified contention rather than tolerating genuine scheduling -// delay under load. -// These are package-level vars, not consts, solely so tests can shrink them -// temporarily (see withShortExecutablePathRetry in -// precondition_require_executable_path_test.go) to exercise the retry loop's -// sleep/exhaustion branches without waiting out the real 15s production -// window. Production code paths never mutate them. -var ( - executablePathRetryTimeout = 15 * time.Second - executablePathRetryInterval = 100 * time.Millisecond -) - -func requireExecutablePath(t *testing.T, name string, purpose string) string { - t.Helper() - - prependCachedTestTool(name) - - deadline := time.Now().Add(executablePathRetryTimeout) - var path string - var err error - for { - path, err = exec.LookPath(name) - if err == nil || time.Now().After(deadline) { - break - } - time.Sleep(executablePathRetryInterval) - } - if err != nil { - forensics := executableLookupForensics(name) - if !ShouldCheckPreconditions() { - // ATMOS_TEST_SKIP_PRECONDITION_CHECKS=true (set for every CI - // acceptance job) means the caller wants a hard failure instead of - // a skip when a tool that CI is expected to provision is missing -- - // never silently hand back an empty path, which turns into a far - // more confusing "open : file not found" error downstream. - t.Fatalf("'%s' not found in PATH: required for %s. Precondition checks are disabled (ATMOS_TEST_SKIP_PRECONDITION_CHECKS=true), so this is a hard failure rather than a skip: %v\n%s", - name, purpose, err, forensics) - } - t.Skipf("'%s' not found in PATH: required for %s. Install the tool or set ATMOS_TEST_SKIP_PRECONDITION_CHECKS=true\n%s", - name, purpose, forensics) - } - return path -} - -// executableLookupForensics reports the on-disk state of every toolchain-like -// PATH entry at the moment a binary lookup failed. The Windows acceptance job -// has a recurring "installed tool vanished mid-suite" failure whose root cause -// is still being pinned down (writer-side install/uninstall windows in the -// shared toolchain cache are the leading theory); this dump turns the next CI -// failure into direct evidence of WHICH mechanism fired: directory deleted -// (uninstall/reinstall), tree renamed aside (onedir .bak present), writer -// mid-flight (.lock sibling present), or PATH itself corrupted (no toolchain -// entries at all). -func executableLookupForensics(name string) string { - var b strings.Builder - entries := filepath.SplitList(os.Getenv("PATH")) - fmt.Fprintf(&b, "-- lookup forensics for %q (%d PATH entries) --\n", name, len(entries)) - - candidates := []string{name} - if withExt := cachedTestToolBinaryNameForOS(name, runtime.GOOS); withExt != name { - candidates = append(candidates, withExt) - } - - toolchainEntries := 0 - for _, dir := range entries { - if !strings.Contains(strings.ToLower(dir), "toolchain") { - continue - } - toolchainEntries++ - describeToolchainPathEntry(&b, dir, candidates) - } - if toolchainEntries == 0 { - b.WriteString("NO toolchain-like PATH entries found -- PATH itself lost the toolchain dirs\n") - } - return b.String() -} - -// describeToolchainPathEntry appends one PATH entry's on-disk state (target -// presence, directory contents, writer-lock sibling) to the forensics report. -func describeToolchainPathEntry(b *strings.Builder, dir string, candidates []string) { - present := false - for _, cand := range candidates { - // #nosec G703 -- dir comes from this process's own PATH and cand from a fixed test-tool list; read-only stat for diagnostics. - if st, statErr := os.Stat(filepath.Join(dir, cand)); statErr == nil && !st.IsDir() { - present = true - break - } - } - fmt.Fprintf(b, "%s -> target present=%v", dir, present) - if dirEntries, readErr := os.ReadDir(dir); readErr == nil { - names := make([]string, 0, len(dirEntries)) - for _, e := range dirEntries { - names = append(names, e.Name()) - } - fmt.Fprintf(b, "; contents(%d): %s", len(names), strings.Join(names, ", ")) - } else { - fmt.Fprintf(b, "; dir unreadable: %v", readErr) - } - // The installer's writer lock is a ".lock" sibling of the version dir - // (see pkg/toolchain/installer); its presence means a writer was active. - // #nosec G703 -- dir comes from this process's own PATH; read-only stat for diagnostics. - if _, lockErr := os.Stat(dir + ".lock"); lockErr == nil { - b.WriteString("; WRITER LOCK PRESENT") - } - b.WriteString("\n") -} - -func prependCachedTestTool(binary string) { - tool, ok := cachedTestToolForBinary(binary) - if !ok { - return - } - - lockValue, _ := testToolPathLocks.LoadOrStore(binary, &sync.Once{}) - lockValue.(*sync.Once).Do(func() { - cacheDir, err := os.UserCacheDir() - if err != nil { - return - } - - // Unit tests provision tools into test-toolchain, while CI uses the normal - // Atmos toolchain cache. Check both so package-local integration tests can - // use the tools installed by the acceptance workflow on every platform. - for _, binDir := range cachedTestToolBinDirs(cacheDir, tool) { - if _, ok := cachedTestToolBinaryPath(binDir, tool.Binary); !ok { - continue - } - - path := os.Getenv("PATH") - if path == "" { - os.Setenv("PATH", binDir) - return - } - os.Setenv("PATH", binDir+string(os.PathListSeparator)+path) - return - } - }) -} - -func cachedTestToolBinDirs(cacheDir string, tool cachedTestTool) []string { - toolPath := filepath.Join(filepath.FromSlash(tool.Repo), tool.Version) - return []string{ - filepath.Join(cacheDir, "atmos", "test-toolchain", "bin", toolPath), - filepath.Join(cacheDir, "atmos", "toolchain", "bin", toolPath), - } -} - -// cachedTestToolBinaryPath returns the installed test-tool binary path, including -// the .exe artifact generated by the Windows toolchain. -func cachedTestToolBinaryPath(binDir string, binary string) (string, bool) { - candidates := []string{filepath.Join(binDir, binary)} - if filepath.Ext(binary) == "" { - candidates = append(candidates, filepath.Join(binDir, binary+".exe")) - } - - for _, candidate := range candidates { - if _, err := os.Stat(candidate); err == nil { - return candidate, true - } - } - - return "", false -} - -// cachedTestToolBinaryName returns the expected on-disk binary name for the -// current OS. Used by test fixture setup, which needs the exact deterministic -// name a real install would produce -- unlike cachedTestToolBinaryPath, which -// tries multiple candidates when looking up an existing cached binary. -func cachedTestToolBinaryName(binary string) string { - return cachedTestToolBinaryNameForOS(binary, runtime.GOOS) -} - -func cachedTestToolBinaryNameForOS(binary, goos string) string { - if goos == "windows" { - return binary + ".exe" - } - return binary -} - -func cachedTestToolBinaryExists(binDir, binary string) bool { - _, err := os.Stat(filepath.Join(binDir, cachedTestToolBinaryName(binary))) - return err == nil -} - -func cachedTestToolForBinary(binary string) (cachedTestTool, bool) { - for _, tool := range cachedTestTools { - if tool.Binary == binary { - return tool, true - } - } - return cachedTestTool{}, false -} - // RequireEnvVar checks if an environment variable is set. func RequireEnvVar(t *testing.T, name string, purpose string) { t.Helper() @@ -815,7 +565,7 @@ func RequireOCIAuthentication(t *testing.T) { t.Logf("Warning: Could not create ghcr.io request: %v", err) } else { req.Header.Set("Authorization", "Bearer "+githubToken) - resp, reqErr := client.Do(req) //nolint:gosec // URL is a hardcoded constant (ghcr.io), not user input. + resp, reqErr := client.Do(req) if reqErr != nil { t.Skipf("Cannot reach ghcr.io: %v. OCI registry access required. Set ATMOS_TEST_SKIP_PRECONDITION_CHECKS=true to skip.", reqErr) } diff --git a/tests/preconditions_tools.go b/tests/preconditions_tools.go new file mode 100644 index 00000000000..47191854d68 --- /dev/null +++ b/tests/preconditions_tools.go @@ -0,0 +1,262 @@ +//nolint:forbidigo // Test tool discovery inspects and updates the process environment. +package tests + +import ( + "fmt" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "sync" + "testing" + "time" +) + +var testToolPathLocks sync.Map + +type cachedTestTool struct { + Repo string + Version string + Binary string +} + +var cachedTestTools = []cachedTestTool{ + {Repo: "opentofu/opentofu", Version: "1.12.2", Binary: "tofu"}, + {Repo: "hashicorp/terraform", Version: "1.15.6", Binary: "terraform"}, + {Repo: "hashicorp/packer", Version: "1.14.2", Binary: "packer"}, + {Repo: "helmfile/helmfile", Version: "v1.1.0", Binary: "helmfile"}, + {Repo: "helm/helm", Version: "v3.19.2", Binary: "helm"}, +} + +// RequireExecutable checks if an executable is available in PATH. +// Unlike requireExecutablePath, a bypass (ATMOS_TEST_SKIP_PRECONDITION_CHECKS=true) +// is a full no-op here: callers that only need a boolean gate, not the resolved +// path, don't need the tool to actually be resolvable when checks are disabled. +func RequireExecutable(t *testing.T, name string, purpose string) { + t.Helper() + + prependCachedTestTool(name) + + if !ShouldCheckPreconditions() { + return + } + + if _, err := exec.LookPath(name); err != nil { + t.Skipf("'%s' not found in PATH: required for %s. Install the tool or set ATMOS_TEST_SKIP_PRECONDITION_CHECKS=true", + name, purpose) + } +} + +// requireExecutablePath resolves and returns the executable's path, skipping +// the test if it is not found. Callers that need the resolved path (to, e.g., +// copy the binary into an isolated per-test directory) should use this instead +// of a separate, independent exec.LookPath call afterward. Two independent +// LookPath calls create a TOCTOU race: the Windows acceptance job runs +// packages concurrently, and another package's test can mutate the shared +// Atmos toolchain cache directory (see prependCachedTestTool) between the two +// calls, turning a binary that existed a moment ago into a spurious +// "not found" error. Resolving the path exactly once here closes that window. +// These constants bound how long requireExecutablePath polls exec.LookPath +// before giving up. CI installs each toolchain binary and updates PATH in an +// earlier job step; on some runners (observed on Windows) that update has +// occasionally not been visible yet to the very first lookup here, so a poll +// avoids failing on a one-off resolution lag rather than the tool actually +// being absent. 15s (rather than a token couple of seconds) is deliberate: +// the Windows acceptance job runs many Go packages' test binaries +// concurrently on constrained runners, and this exact race recurred in CI +// even after closing one confirmed root cause (a test writing real installs +// into the shared toolchain cache dir, see the pkg/toolchain fix referenced +// in this repo's git history) -- so a short window risks masking further, +// not-yet-identified contention rather than tolerating genuine scheduling +// delay under load. +// These are package-level vars, not consts, solely so tests can shrink them +// temporarily (see withShortExecutablePathRetry in +// precondition_require_executable_path_test.go) to exercise the retry loop's +// sleep/exhaustion branches without waiting out the real 15s production +// window. Production code paths never mutate them. +var ( + executablePathRetryTimeout = 15 * time.Second + executablePathRetryInterval = 100 * time.Millisecond +) + +func requireExecutablePath(t *testing.T, name string, purpose string) string { + t.Helper() + + prependCachedTestTool(name) + + deadline := time.Now().Add(executablePathRetryTimeout) + var path string + var err error + for { + path, err = exec.LookPath(name) + if err == nil || time.Now().After(deadline) { + break + } + time.Sleep(executablePathRetryInterval) + } + if err != nil { + forensics := executableLookupForensics(name) + if !ShouldCheckPreconditions() { + // ATMOS_TEST_SKIP_PRECONDITION_CHECKS=true (set for every CI + // acceptance job) means the caller wants a hard failure instead of + // a skip when a tool that CI is expected to provision is missing -- + // never silently hand back an empty path, which turns into a far + // more confusing "open : file not found" error downstream. + t.Fatalf("'%s' not found in PATH: required for %s. Precondition checks are disabled (ATMOS_TEST_SKIP_PRECONDITION_CHECKS=true), so this is a hard failure rather than a skip: %v\n%s", + name, purpose, err, forensics) + } + t.Skipf("'%s' not found in PATH: required for %s. Install the tool or set ATMOS_TEST_SKIP_PRECONDITION_CHECKS=true\n%s", + name, purpose, forensics) + } + return path +} + +// executableLookupForensics reports the on-disk state of every toolchain-like +// PATH entry at the moment a binary lookup failed. The Windows acceptance job +// has a recurring "installed tool vanished mid-suite" failure whose root cause +// is still being pinned down (writer-side install/uninstall windows in the +// shared toolchain cache are the leading theory); this dump turns the next CI +// failure into direct evidence of WHICH mechanism fired: directory deleted +// (uninstall/reinstall), tree renamed aside (onedir .bak present), writer +// mid-flight (.lock sibling present), or PATH itself corrupted (no toolchain +// entries at all). +func executableLookupForensics(name string) string { + var b strings.Builder + entries := filepath.SplitList(os.Getenv("PATH")) + fmt.Fprintf(&b, "-- lookup forensics for %q (%d PATH entries) --\n", name, len(entries)) + + candidates := []string{name} + if withExt := cachedTestToolBinaryNameForOS(name, runtime.GOOS); withExt != name { + candidates = append(candidates, withExt) + } + + toolchainEntries := 0 + for _, dir := range entries { + if !strings.Contains(strings.ToLower(dir), "toolchain") { + continue + } + toolchainEntries++ + describeToolchainPathEntry(&b, dir, candidates) + } + if toolchainEntries == 0 { + b.WriteString("NO toolchain-like PATH entries found -- PATH itself lost the toolchain dirs\n") + } + return b.String() +} + +// describeToolchainPathEntry appends one PATH entry's on-disk state (target +// presence, directory contents, writer-lock sibling) to the forensics report. +func describeToolchainPathEntry(b *strings.Builder, dir string, candidates []string) { + present := false + for _, cand := range candidates { + // #nosec G703 -- dir comes from this process's own PATH and cand from a fixed test-tool list; read-only stat for diagnostics. + if st, statErr := os.Stat(filepath.Join(dir, cand)); statErr == nil && !st.IsDir() { + present = true + break + } + } + fmt.Fprintf(b, "%s -> target present=%v", dir, present) + if dirEntries, readErr := os.ReadDir(dir); readErr == nil { + names := make([]string, 0, len(dirEntries)) + for _, e := range dirEntries { + names = append(names, e.Name()) + } + fmt.Fprintf(b, "; contents(%d): %s", len(names), strings.Join(names, ", ")) + } else { + fmt.Fprintf(b, "; dir unreadable: %v", readErr) + } + // The installer's writer lock is a ".lock" sibling of the version dir + // (see pkg/toolchain/installer); its presence means a writer was active. + // #nosec G703 -- dir comes from this process's own PATH; read-only stat for diagnostics. + if _, lockErr := os.Stat(dir + ".lock"); lockErr == nil { + b.WriteString("; WRITER LOCK PRESENT") + } + b.WriteString("\n") +} + +func prependCachedTestTool(binary string) { + tool, ok := cachedTestToolForBinary(binary) + if !ok { + return + } + + lockValue, _ := testToolPathLocks.LoadOrStore(binary, &sync.Once{}) + lockValue.(*sync.Once).Do(func() { + cacheDir, err := os.UserCacheDir() + if err != nil { + return + } + + // Unit tests provision tools into test-toolchain, while CI uses the normal + // Atmos toolchain cache. Check both so package-local integration tests can + // use the tools installed by the acceptance workflow on every platform. + for _, binDir := range cachedTestToolBinDirs(cacheDir, tool) { + if _, ok := cachedTestToolBinaryPath(binDir, tool.Binary); !ok { + continue + } + + path := os.Getenv("PATH") + if path == "" { + os.Setenv("PATH", binDir) + return + } + os.Setenv("PATH", binDir+string(os.PathListSeparator)+path) + return + } + }) +} + +func cachedTestToolBinDirs(cacheDir string, tool cachedTestTool) []string { + toolPath := filepath.Join(filepath.FromSlash(tool.Repo), tool.Version) + return []string{ + filepath.Join(cacheDir, "atmos", "test-toolchain", "bin", toolPath), + filepath.Join(cacheDir, "atmos", "toolchain", "bin", toolPath), + } +} + +// cachedTestToolBinaryPath returns the installed test-tool binary path, including +// the .exe artifact generated by the Windows toolchain. +func cachedTestToolBinaryPath(binDir string, binary string) (string, bool) { + candidates := []string{filepath.Join(binDir, binary)} + if filepath.Ext(binary) == "" { + candidates = append(candidates, filepath.Join(binDir, binary+".exe")) + } + + for _, candidate := range candidates { + if _, err := os.Stat(candidate); err == nil { + return candidate, true + } + } + + return "", false +} + +// cachedTestToolBinaryName returns the expected on-disk binary name for the +// current OS. Used by test fixture setup, which needs the exact deterministic +// name a real install would produce -- unlike cachedTestToolBinaryPath, which +// tries multiple candidates when looking up an existing cached binary. +func cachedTestToolBinaryName(binary string) string { + return cachedTestToolBinaryNameForOS(binary, runtime.GOOS) +} + +func cachedTestToolBinaryNameForOS(binary, goos string) string { + if goos == "windows" { + return binary + ".exe" + } + return binary +} + +func cachedTestToolBinaryExists(binDir, binary string) bool { + _, err := os.Stat(filepath.Join(binDir, cachedTestToolBinaryName(binary))) + return err == nil +} + +func cachedTestToolForBinary(binary string) (cachedTestTool, bool) { + for _, tool := range cachedTestTools { + if tool.Binary == binary { + return tool, true + } + } + return cachedTestTool{}, false +} diff --git a/tests/terraform_floci_dag_test.go b/tests/terraform_floci_dag_test.go index 1fca525d4ef..e660f878457 100644 --- a/tests/terraform_floci_dag_test.go +++ b/tests/terraform_floci_dag_test.go @@ -1,4 +1,3 @@ -//nolint:forbidigo // This opt-in integration test is configured through environment variables. package tests import ( @@ -303,7 +302,7 @@ func runFlociGit(t *testing.T, dir string, args ...string) { t.Helper() cmdArgs := append([]string{"-C", dir}, args...) - cmd := exec.Command("git", cmdArgs...) //nolint:gosec // Test helper runs fixed git commands against temp fixtures. + cmd := exec.Command("git", cmdArgs...) output, err := cmd.CombinedOutput() require.NoError(t, err, "git %s failed:\n%s", strings.Join(args, " "), string(output)) } diff --git a/tests/yaml_func_terraform_output_jit_test.go b/tests/yaml_func_terraform_output_jit_test.go index a1c94f44ad9..54b1a44d9b8 100644 --- a/tests/yaml_func_terraform_output_jit_test.go +++ b/tests/yaml_func_terraform_output_jit_test.go @@ -19,7 +19,7 @@ import ( // provision.workdir.enabled: true before running terraform init. // // The test asserts that the workdir is created by the auto-provision step. -// terraform output may return empty results if no state exists — that is +// Terraform output may return empty results if no state exists — that is // expected and acceptable; the key assertion is that auto-provision fired. // // Regression test for https://github.com/cloudposse/atmos/issues/2167. diff --git a/tests/yaml_func_terraform_source_jit_test.go b/tests/yaml_func_terraform_source_jit_test.go index 40db5964bd7..17c53be0570 100644 --- a/tests/yaml_func_terraform_source_jit_test.go +++ b/tests/yaml_func_terraform_source_jit_test.go @@ -124,7 +124,7 @@ func seedStateFile(t *testing.T, cwd string) { // provision.workdir.enabled: true. // // The state file lives in the JIT workdir (.workdir/terraform/test-producer-from-source-b2f94c7d/), -// not in components/terraform/. resolveLocalBackendComponentPath must derive the JIT path +// Not in components/terraform/. The resolveLocalBackendComponentPath helper must derive the JIT path // even though the component was hydrated from an external source URI rather than a local // components/ directory. // From 3f277a47c1cc3dd4a04be025005d0407ff06a441 Mon Sep 17 00:00:00 2001 From: Erik Osterman Date: Fri, 13 Nov 2026 14:36:28 -0600 Subject: [PATCH 17/28] test: simplify acceptance setup and preserve command errors --- tests/cli_harness_helpers_test.go | 48 ++++ tests/cli_test.go | 372 ++++++++++++++---------------- 2 files changed, 222 insertions(+), 198 deletions(-) create mode 100644 tests/cli_harness_helpers_test.go diff --git a/tests/cli_harness_helpers_test.go b/tests/cli_harness_helpers_test.go new file mode 100644 index 00000000000..4a86bf31c16 --- /dev/null +++ b/tests/cli_harness_helpers_test.go @@ -0,0 +1,48 @@ +package tests + +import ( + "fmt" + "os" + "path/filepath" + "syscall" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestPTYErrorWrapped(t *testing.T) { + t.Parallel() + eof := &os.PathError{Op: "read", Path: "pty", Err: syscall.EIO} + require.NoError(t, ptyError(fmt.Errorf("read output: %w", eof))) + failure := &os.PathError{Op: "read", Path: "pty", Err: syscall.EBADF} + wrapped := fmt.Errorf("read output: %w", failure) + assert.ErrorIs(t, ptyError(wrapped), syscall.EBADF) + // Bare EIO is not necessarily a closed PTY. + assert.ErrorIs(t, ptyError(syscall.EIO), syscall.EIO) + require.NoError(t, ptyError(nil)) +} + +func TestLoadTestSuitesPreservesReadError(t *testing.T) { + t.Parallel() + _, err := loadTestSuites(filepath.Join(t.TempDir(), "missing")) + require.ErrorIs(t, err, os.ErrNotExist) +} + +func TestSetupTestConfigPath(t *testing.T) { + t.Parallel() + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "atmos.yaml"), nil, 0o600)) + for _, args := range [][]string{nil, {"--chdir", "elsewhere"}, {"-C", "elsewhere"}, {"--chdir=elsewhere"}} { + tc := TestCase{Args: args} + setupTestConfigPath(&tc, dir) + if len(args) == 0 { + assert.Equal(t, dir, tc.Env["ATMOS_CLI_CONFIG_PATH"]) + } else { + assert.NotContains(t, tc.Env, "ATMOS_CLI_CONFIG_PATH") + } + } + tc := TestCase{} + setupTestConfigPath(&tc, t.TempDir()) + assert.NotContains(t, tc.Env, "ATMOS_CLI_CONFIG_PATH") +} diff --git a/tests/cli_test.go b/tests/cli_test.go index dcfe0be507a..c4d76fc8a1f 100644 --- a/tests/cli_test.go +++ b/tests/cli_test.go @@ -665,7 +665,6 @@ func sanitizeTestName(name string) string { return name } -// Drop any lines matched by the ignore patterns so they do not affect the comparison. // stripTrailingWhitespace removes trailing whitespace from each line. func stripTrailingWhitespace(input string) string { lines := strings.Split(input, "\n") @@ -708,15 +707,13 @@ func applyIgnorePatterns(input string, patterns []string) string { // - This matches real terminal behavior where users see everything in one stream. // // For tests that need separate stderr/stdout streams, use non-TTY execution instead. -func simulateTtyCommand(t *testing.T, cmd *exec.Cmd, input string) (string, error) { +func simulateTtyCommand(cmd *exec.Cmd, input string) (string, error) { ptmx, err := pty.Start(cmd) if err != nil { - return "", fmt.Errorf("failed to start TTY: %v", err) + return "", fmt.Errorf("failed to start TTY: %w", err) } defer func() { _ = ptmx.Close() }() - // t.Logf("PTY Fd: %d, IsTerminal: %v", ptmx.Fd(), term.IsTerminal(int(ptmx.Fd()))) - if input != "" { go func() { _, _ = ptmx.Write([]byte(input)) @@ -738,11 +735,10 @@ func simulateTtyCommand(t *testing.T, cmd *exec.Cmd, input string) (string, erro } if readErr := <-done; readErr != nil { - return "", fmt.Errorf("failed to read PTY output: %v", readErr) + return "", fmt.Errorf("failed to read PTY output: %w", readErr) } output := buffer.String() - // t.Logf("Captured Output:\n%s", output) // Return the wait error so exit codes can be captured. return output, waitErr @@ -753,7 +749,8 @@ func simulateTtyCommand(t *testing.T, cmd *exec.Cmd, input string) (string, erro // See https://github.com/creack/pty/issues/21 // See https://github.com/owenthereal/upterm/pull/11 func ptyError(err error) error { - if pathErr, ok := err.(*os.PathError); !ok || pathErr.Err != syscall.EIO { + var pathErr *os.PathError + if !errors.As(err, &pathErr) || !errors.Is(pathErr.Err, syscall.EIO) { return err } return nil @@ -765,7 +762,7 @@ func loadTestSuites(testCasesDir string) (*TestSuite, error) { entries, err := os.ReadDir(testCasesDir) if err != nil { - return nil, fmt.Errorf("failed to read test-cases directory: %v", err) + return nil, fmt.Errorf("failed to read test-cases directory: %w", err) } for _, entry := range entries { @@ -773,7 +770,7 @@ func loadTestSuites(testCasesDir string) (*TestSuite, error) { filePath := filepath.Join(testCasesDir, entry.Name()) suite, err := loadTestSuite(filePath) if err != nil { - return nil, fmt.Errorf("failed to load %s: %v", filePath, err) + return nil, fmt.Errorf("failed to load %s: %w", filePath, err) } mergedSuite.Tests = append(mergedSuite.Tests, suite.Tests...) } @@ -1253,7 +1250,8 @@ func ensureGitMirrorCoversFixtureTokens(t *testing.T, tc *TestCase) { tc.Env["GIT_CONFIG_GLOBAL"] = mirrorConfigPath } -func runCLICommandTest(t *testing.T, tc TestCase) { +func runCLICommandTest(t *testing.T, testCase *TestCase) { + tc := *testCase // Keep per-run field changes local to this execution. // Skip long tests in short mode if testing.Short() && tc.Short != nil && !*tc.Short { t.Skipf("Skipping long-running test in short mode (use 'go test' without -short to run)") @@ -1281,23 +1279,17 @@ func runCLICommandTest(t *testing.T, tc TestCase) { // to prevent any single test from consuming the entire test budget. const defaultTestTimeout = 10 * time.Minute - var ctx context.Context - var cancel context.CancelFunc - + timeout := defaultTestTimeout if tc.Expect.Timeout != "" { - // Parse the timeout from the Expectation - timeout, err := parseTimeout(tc.Expect.Timeout) + parsed, err := parseTimeout(tc.Expect.Timeout) if err != nil { t.Fatalf("Failed to parse timeout for test %s: %v", tc.Name, err) } - if timeout > 0 { - ctx, cancel = context.WithTimeout(context.Background(), timeout) - } else { - ctx, cancel = context.WithTimeout(context.Background(), defaultTestTimeout) + if parsed > 0 { + timeout = parsed } - } else { - ctx, cancel = context.WithTimeout(context.Background(), defaultTestTimeout) } + ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() // Create a temporary HOME directory for the test case that's clean @@ -1444,119 +1436,9 @@ func runCLICommandTest(t *testing.T, tc TestCase) { tc.Env["GIT_TRACE_REDACT"] = "true" } - if runtime.GOOS == "darwin" && isCIEnvironment() { - if liveGitHub { - homeDir := os.Getenv("HOME") - if override, ok := tc.Env["HOME"]; ok { - homeDir = override - } - requireNetrcFreeHome(t, homeDir) - } - // For some reason the empty HOME directory causes issues on macOS in GitHub Actions - // Copying over the `.gitconfig` was not enough to fix the issue. - // A "live_github" case can only keep this HOME after the .netrc guard above passes. - logger.Info("skipping empty home dir on macOS in CI", "GOOS", runtime.GOOS) - } else { - // Set environment variables for the test case - tc.Env["HOME"] = tempDir - tc.Env["XDG_CONFIG_HOME"] = filepath.Join(tempDir, ".config") - tc.Env["XDG_DATA_HOME"] = filepath.Join(tempDir, ".local", "share") - // Copy some files to the temporary HOME directory - originalHome := os.Getenv("HOME") - for _, file := range homeFilesToCopy(liveGitHub) { - src := filepath.Join(originalHome, file) - dest := filepath.Join(tempDir, file) - - if _, err := os.Stat(src); err == nil { // Check if the file/directory exists - // t.Logf("Copying %s to %s\n", src, dest) - // Skip socket files (e.g., SSH agent sockets) that cannot be copied. - copyOpts := copy.Options{ - Skip: func(info os.FileInfo, src, dest string) (bool, error) { - return info.Mode()&os.ModeSocket != 0, nil - }, - } - if err := copy.Copy(src, dest, copyOpts); err != nil { - t.Fatalf("Failed to copy %s to test folder: %v", src, err) - } - } - } - } - - // Change to the specified working directory - if tc.Workdir != "" { - absoluteWorkdir, err := filepath.Abs(tc.Workdir) - if err != nil { - t.Fatalf("failed to resolve absolute path of workdir %q: %v", tc.Workdir, err) - } - t.Chdir(absoluteWorkdir) - - // Setup sandbox environment if enabled - var sandboxEnv *testhelpers.SandboxEnvironment - switch v := tc.Sandbox.(type) { - case bool: - if v { - // Boolean true = isolated sandbox for this test only - logger.Info("Setting up isolated sandbox", "test", tc.Name, "workdir", absoluteWorkdir) - sandboxEnv = createIsolatedSandbox(t, absoluteWorkdir) - // Clean up immediately after test - defer func() { - logger.Debug("Cleaning up isolated sandbox", "tempdir", sandboxEnv.TempDir) - sandboxEnv.Cleanup() - }() - } - case string: - if v != "" { - // Named sandbox = shared across related tests - logger.Info("Using named sandbox", "test", tc.Name, "name", v, "workdir", absoluteWorkdir) - sandboxEnv = getOrCreateNamedSandbox(t, v, absoluteWorkdir) - // Cleanup handled by TestMain - } - } - - // Add sandbox environment variables to override component paths - if sandboxEnv != nil { - if tc.Env == nil { - tc.Env = make(map[string]string) - } - for k, v := range sandboxEnv.GetEnvironmentVariables() { - logger.Debug("Setting sandbox env var", "key", k, "value", v) - tc.Env[k] = v - } - } - - // Clean the directory if enabled - if tc.Clean { - logger.Info("Cleaning directory", "workdir", tc.Workdir) - if err := cleanDirectory(t, absoluteWorkdir); err != nil { - t.Fatalf("Failed to clean directory %q: %v", tc.Workdir, err) - } - } + setupTestHome(t, &tc, tempDir, liveGitHub) - // Set ATMOS_CLI_CONFIG_PATH to ensure test isolation. - // This forces Atmos to use the workdir's atmos.yaml instead of searching - // up the directory tree or using ~/.config/atmos/atmos.yaml. - // BUT: Skip this for tests that use --chdir/-C, since they need to test - // config loading in the target directory. - usesChdirFlag := false - for _, arg := range tc.Args { - if arg == "--chdir" || arg == "-C" || strings.HasPrefix(arg, "--chdir=") { - usesChdirFlag = true - break - } - } - if !usesChdirFlag { - atmosConfigPath := filepath.Join(absoluteWorkdir, "atmos.yaml") - if _, err := os.Stat(atmosConfigPath); err == nil { - if tc.Env == nil { - tc.Env = make(map[string]string) - } - tc.Env["ATMOS_CLI_CONFIG_PATH"] = absoluteWorkdir - logger.Debug("Setting ATMOS_CLI_CONFIG_PATH for test isolation", "path", absoluteWorkdir) - } - } else { - logger.Debug("Skipping ATMOS_CLI_CONFIG_PATH for --chdir test") - } - } + setupTestWorkdir(t, &tc) // Include the system PATH in the test environment tc.Env["PATH"] = os.Getenv("PATH") @@ -1752,67 +1634,29 @@ func runCLICommandTest(t *testing.T, tc TestCase) { var stdout, stderr bytes.Buffer var exitCode int + var commandErr error if tc.Tty { - // Run the command in TTY mode - ptyOutput, err := simulateTtyCommand(t, cmd, "") - - // Check if the context timeout was exceeded - if ctx.Err() == context.DeadlineExceeded { - t.Errorf("Reason: Test timed out after %s", tc.Expect.Timeout) - t.Errorf("Captured stdout:\n%s", stdout.String()) - t.Errorf("Captured stderr:\n%s", stderr.String()) - return - } - - if err != nil { - // Check if the error is an ExitError - if exitErr, ok := err.(*exec.ExitError); ok { - // Capture the actual exit code - exitCode = exitErr.ExitCode() - - if exitCode < 0 { - // Negative exit code indicates interruption by a signal - t.Errorf("TTY Command interrupted by signal: %s, Signal: %d, Error: %v", tc.Command, -exitCode, err) - } - } else { - // Handle other types of errors - t.Fatalf("Failed to simulate TTY command: %v", err) - } - } - stdout.WriteString(ptyOutput) + var output string + output, commandErr = simulateTtyCommand(cmd, "") + stdout.WriteString(output) } else { - // Run the command in non-TTY mode - - // Attach stdout and stderr buffers for non-TTY execution cmd.Stdout = &stdout cmd.Stderr = &stderr - - err := cmd.Run() - if ctx.Err() == context.DeadlineExceeded { - // Handle the timeout case first - t.Errorf("Reason: Test timed out after %s", tc.Expect.Timeout) - t.Errorf("Captured stdout:\n%s", stdout.String()) - t.Errorf("Captured stderr:\n%s", stderr.String()) - return + commandErr = cmd.Run() + } + if ctx.Err() == context.DeadlineExceeded { + t.Errorf("Reason: Test timed out after %s", tc.Expect.Timeout) + dumpCapturedOutput(t, &stdout, &stderr) + return + } + if commandErr != nil { + var exitErr *exec.ExitError + if !errors.As(commandErr, &exitErr) { + t.Fatalf("Failed to run command: %v", commandErr) } - - if err != nil { - // Handle other command execution errors - if exitErr, ok := err.(*exec.ExitError); ok { - // Capture the actual exit code - exitCode = exitErr.ExitCode() - - if exitCode < 0 { - // Negative exit code indicates termination by a signal - t.Errorf("Non-TTY Command terminated by signal: %s, Signal: %d, Error: %v", tc.Command, -exitCode, err) - } - } else { - // Handle other non-exec-related errors - t.Fatalf("Failed to run command; Error: %v", err) - } - } else { - // Successful command execution - exitCode = 0 + exitCode = exitErr.ExitCode() + if exitCode < 0 { + t.Errorf("Command interrupted by signal: %s, Error: %v", tc.Command, commandErr) } } @@ -1850,7 +1694,7 @@ func runCLICommandTest(t *testing.T, tc TestCase) { } // Validate snapshots - if !verifySnapshot(t, tc, stdout.String(), stderr.String(), *regenerateSnapshots) { + if !verifySnapshot(t, &tc, stdout.String(), stderr.String(), *regenerateSnapshots) { t.Errorf("Description: %s", tc.Description) } } @@ -1858,7 +1702,7 @@ func runCLICommandTest(t *testing.T, tc TestCase) { func removeCacheFile() error { cacheFilePath, err := config.GetCacheFilePath() if err != nil { - return nil + return err } if _, err := os.Stat(cacheFilePath); os.IsNotExist(err) { @@ -1908,7 +1752,7 @@ func TestCLICommands(t *testing.T) { // Run tests t.Run(tc.Name, func(t *testing.T) { - runCLICommandTest(t, tc) + runCLICommandTest(t, &tc) }) } } @@ -2196,7 +2040,8 @@ func verifyJSONFormat(t *testing.T, output string) bool { if err != nil { t.Logf("JSON validation failed: %v", err) // Try to provide context about where the error occurred. - if syntaxErr, ok := err.(*json.SyntaxError); ok { + var syntaxErr *json.SyntaxError + if errors.As(err, &syntaxErr) { offset := syntaxErr.Offset // Show a snippet around the error location. start := max(0, int(offset)-50) @@ -2609,14 +2454,14 @@ func colorizeDiffWithThreshold(actual, expected string, threshold int) string { case diffmatchpatch.DiffInsert, diffmatchpatch.DiffDelete: if len(text) < threshold { // For short diffs, highlight entire line - sb.WriteString(fmt.Sprintf("\033[1m\033[33m%s\033[0m", text)) + fmt.Fprintf(&sb, "\033[1m\033[33m%s\033[0m", text) } else { // For long diffs, highlight at word/character level color := "\033[32m" // Insert: green if diff.Type == diffmatchpatch.DiffDelete { color = "\033[31m" // Delete: red } - sb.WriteString(fmt.Sprintf("%s%s\033[0m", color, text)) + fmt.Fprintf(&sb, "%s%s\033[0m", color, text) } case diffmatchpatch.DiffEqual: sb.WriteString(text) @@ -2691,7 +2536,7 @@ func verifyTestOutputs(t *testing.T, tc *TestCase, stdout, stderr string) { } } -func verifySnapshot(t *testing.T, tc TestCase, stdoutOutput, stderrOutput string, regenerate bool) bool { +func verifySnapshot(t *testing.T, tc *TestCase, stdoutOutput, stderrOutput string, regenerate bool) bool { if !tc.Snapshot { return true } @@ -2722,7 +2567,7 @@ func verifySnapshot(t *testing.T, tc TestCase, stdoutOutput, stderrOutput string // TTY mode: combined output in single .tty.golden file if tc.Tty { // In TTY mode, stdout contains the combined output (from PTY) - return verifyTTYSnapshot(t, &tc, ttyPath, stdoutOutput, regenerate) + return verifyTTYSnapshot(t, tc, ttyPath, stdoutOutput, regenerate) } // Non-TTY mode: separate stdout and stderr snapshots @@ -2990,3 +2835,134 @@ func TestRemoveIgnoredEntriesPreservesGitDir(t *testing.T) { assert.FileExists(t, trackedPath, "tracked files must be left untouched") assert.NoFileExists(t, untrackedPath, "untracked/gitignored entries must still be removed") } + +func setupTestHome(t *testing.T, tc *TestCase, tempDir string, liveGitHub bool) { + t.Helper() + if runtime.GOOS == "darwin" && isCIEnvironment() { + if liveGitHub { + homeDir := os.Getenv("HOME") + if override, ok := tc.Env["HOME"]; ok { + homeDir = override + } + requireNetrcFreeHome(t, homeDir) + } + // For some reason the empty HOME directory causes issues on macOS in GitHub Actions + // Copying over the `.gitconfig` was not enough to fix the issue. + // A "live_github" case can only keep this HOME after the .netrc guard above passes. + logger.Info("skipping empty home dir on macOS in CI", "GOOS", runtime.GOOS) + return + } + // Set environment variables for the test case + tc.Env["HOME"] = tempDir + tc.Env["XDG_CONFIG_HOME"] = filepath.Join(tempDir, ".config") + tc.Env["XDG_DATA_HOME"] = filepath.Join(tempDir, ".local", "share") + // Copy some files to the temporary HOME directory + originalHome := os.Getenv("HOME") + for _, file := range homeFilesToCopy(liveGitHub) { + src := filepath.Join(originalHome, file) + dest := filepath.Join(tempDir, file) + + if _, err := os.Stat(src); err == nil { // Check if the file/directory exists + // Skip socket files (e.g., SSH agent sockets) that cannot be copied. + copyOpts := copy.Options{ + Skip: func(info os.FileInfo, src, dest string) (bool, error) { + return info.Mode()&os.ModeSocket != 0, nil + }, + } + if err := copy.Copy(src, dest, copyOpts); err != nil { + t.Fatalf("Failed to copy %s to test folder: %v", src, err) + } + } + } +} + +func setupTestWorkdir(t *testing.T, tc *TestCase) { + t.Helper() + if tc.Workdir == "" { + return + } + + absoluteWorkdir, err := filepath.Abs(tc.Workdir) + if err != nil { + t.Fatalf("failed to resolve absolute path of workdir %q: %v", tc.Workdir, err) + } + t.Chdir(absoluteWorkdir) + + setupTestSandbox(t, tc, absoluteWorkdir) + + // Clean the directory if enabled + if tc.Clean { + logger.Info("Cleaning directory", "workdir", tc.Workdir) + if err := cleanDirectory(t, absoluteWorkdir); err != nil { + t.Fatalf("Failed to clean directory %q: %v", tc.Workdir, err) + } + } + + setupTestConfigPath(tc, absoluteWorkdir) +} + +func setupTestSandbox(t *testing.T, tc *TestCase, absoluteWorkdir string) { + t.Helper() + + // Setup sandbox environment if enabled + var sandboxEnv *testhelpers.SandboxEnvironment + switch v := tc.Sandbox.(type) { + case bool: + if v { + // Boolean true = isolated sandbox for this test only + logger.Info("Setting up isolated sandbox", "test", tc.Name, "workdir", absoluteWorkdir) + sandboxEnv = createIsolatedSandbox(t, absoluteWorkdir) + // Clean up immediately after test + t.Cleanup(func() { + logger.Debug("Cleaning up isolated sandbox", "tempdir", sandboxEnv.TempDir) + sandboxEnv.Cleanup() + }) + } + case string: + if v != "" { + // Named sandbox = shared across related tests + logger.Info("Using named sandbox", "test", tc.Name, "name", v, "workdir", absoluteWorkdir) + sandboxEnv = getOrCreateNamedSandbox(t, v, absoluteWorkdir) + // Cleanup handled by TestMain + } + } + + // Add sandbox environment variables to override component paths + if sandboxEnv != nil { + if tc.Env == nil { + tc.Env = make(map[string]string) + } + for k, v := range sandboxEnv.GetEnvironmentVariables() { + logger.Debug("Setting sandbox env var", "key", k, "value", v) + tc.Env[k] = v + } + } +} + +func setupTestConfigPath(tc *TestCase, absoluteWorkdir string) { + // Set ATMOS_CLI_CONFIG_PATH to ensure test isolation. + // This forces Atmos to use the workdir's atmos.yaml instead of searching + // up the directory tree or using ~/.config/atmos/atmos.yaml. + // BUT: Skip this for tests that use --chdir/-C, since they need to test + // config loading in the target directory. + usesChdirFlag := false + for _, arg := range tc.Args { + if arg == "--chdir" || arg == "-C" || strings.HasPrefix(arg, "--chdir=") { + usesChdirFlag = true + break + } + } + if usesChdirFlag { + logger.Debug("Skipping ATMOS_CLI_CONFIG_PATH for --chdir test") + return + } + atmosConfigPath := filepath.Join(absoluteWorkdir, "atmos.yaml") + if _, err := os.Stat(atmosConfigPath); err != nil { + return + } + if tc.Env == nil { + tc.Env = make(map[string]string) + } + tc.Env["ATMOS_CLI_CONFIG_PATH"] = absoluteWorkdir + logger.Debug("Setting ATMOS_CLI_CONFIG_PATH for test isolation", "path", absoluteWorkdir) +} From 394eda2015aa96e74fa80d90d3d17659a278c3d6 Mon Sep 17 00:00:00 2001 From: Erik Osterman Date: Fri, 13 Nov 2026 15:47:37 -0600 Subject: [PATCH 18/28] test: isolate CI error color expectations from terminal environment --- errors/formatter_test.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/errors/formatter_test.go b/errors/formatter_test.go index 50171afc82c..c8090fb517a 100644 --- a/errors/formatter_test.go +++ b/errors/formatter_test.go @@ -250,6 +250,12 @@ func TestShouldUseColorInCI(t *testing.T) { func TestFormatInCIUsesColorUnlessDisabled(t *testing.T) { t.Setenv("CI", "true") t.Setenv("NO_COLOR", "") + // TERM=dumb intentionally disables automatic CI styling. + t.Setenv("TERM", "xterm-256color") + t.Setenv("CLICOLOR", "") + t.Setenv("CLICOLOR_FORCE", "") + t.Setenv("FORCE_COLOR", "") + t.Setenv("ATMOS_FORCE_COLOR", "") previousProfile := lipgloss.DefaultRenderer().ColorProfile() lipgloss.SetColorProfile(termenv.TrueColor) From 4b861689ade835192eb2826debffea9df517be40 Mon Sep 17 00:00:00 2001 From: Erik Osterman Date: Fri, 13 Nov 2026 15:51:37 -0600 Subject: [PATCH 19/28] test: honor configured timeout for short test suites --- .atmos.d/test.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.atmos.d/test.yaml b/.atmos.d/test.yaml index 7fd44adb9ae..3b6a0c85b7b 100644 --- a/.atmos.d/test.yaml +++ b/.atmos.d/test.yaml @@ -184,7 +184,7 @@ commands: - type: atmos command: build deps - type: shell - command: go test -short ${TEST:-$(go list ./...)} ${TESTARGS:-} -timeout 5m + command: go test -short ${TEST:-$(go list ./...)} ${TESTARGS:-} -timeout "${GO_TEST_TIMEOUT:-5m}" - name: short-cover description: Run quick tests with coverage @@ -197,7 +197,7 @@ commands: - type: atmos command: build deps - type: shell - command: go test -short -cover ${TEST:-$(go list ./...)} ${TESTARGS:-} -timeout 5m + command: go test -short -cover ${TEST:-$(go list ./...)} ${TESTARGS:-} -timeout "${GO_TEST_TIMEOUT:-5m}" - name: coverage description: Run tests with coverage report From 91ea1830632b92b08507156c0f6fed60a2553dc5 Mon Sep 17 00:00:00 2001 From: Erik Osterman Date: Fri, 13 Nov 2026 16:00:36 -0600 Subject: [PATCH 20/28] refactor(errors): organize sentinel declarations by domain --- errors/errors.go | 1667 +------------------------------- errors/errors_components.go | 108 +++ errors/errors_configuration.go | 507 ++++++++++ errors/errors_execution.go | 421 ++++++++ errors/errors_integrations.go | 392 ++++++++ errors/errors_runtime.go | 275 ++++++ 6 files changed, 1707 insertions(+), 1663 deletions(-) create mode 100644 errors/errors_components.go create mode 100644 errors/errors_configuration.go create mode 100644 errors/errors_execution.go create mode 100644 errors/errors_integrations.go create mode 100644 errors/errors_runtime.go diff --git a/errors/errors.go b/errors/errors.go index 5932a3d88f9..b3093db3eb3 100644 --- a/errors/errors.go +++ b/errors/errors.go @@ -2,50 +2,10 @@ package errors import ( "errors" - "fmt" - "github.com/cloudposse/atmos/pkg/duration" schemaPkg "github.com/cloudposse/atmos/pkg/schema" ) -// ErrStarlark identifies embedded Starlark execution or configuration failures. -var ErrStarlark = errors.New("starlark execution failed") - -// ErrScriptRaised identifies an intentional failure raised by a script. -var ErrScriptRaised = errors.New("script raised a failure") - -var ( - // ErrStarlarkInvalidArgument identifies invalid arguments passed to an embedded Starlark builtin. - ErrStarlarkInvalidArgument = errors.New("invalid starlark argument") - // ErrStarlarkTaskTimeout identifies a Starlark task that exceeded its deadline. - ErrStarlarkTaskTimeout = errors.New("starlark task timed out") - // ErrStarlarkProcessFailed identifies a subprocess started by Starlark that failed or never started. - ErrStarlarkProcessFailed = errors.New("starlark process failed") - // ErrStarlarkOutputEncode identifies a top-level Starlark `output` value that cannot be encoded. - ErrStarlarkOutputEncode = errors.New("starlark output encoding failed") - // ErrStarlarkRecursionLimit identifies a Starlark call stack that exceeded the maximum recursion depth. - ErrStarlarkRecursionLimit = errors.New("starlark recursion depth exceeded") - // ErrStarlarkStackIdentity identifies a stack name derived from a !starlark value, which is not computable. - ErrStarlarkStackIdentity = errors.New("stack identity cannot be computed with !starlark") - // ErrScriptUsage identifies command-line input that does not satisfy a standalone script's declared interface. - ErrScriptUsage = errors.New("usage error") -) - -const ( - // ErrWrapFormat is the standard format string for wrapping errors with context. - // Use with fmt.Errorf to wrap a sentinel error with an underlying error: - // fmt.Errorf(ErrWrapFormat, errUtils.ErrSentinel, underlyingErr) - ErrWrapFormat = "%w: %w" - // ErrWrapWithNameFormat is the format string for wrapping errors with a name context. - // Use with fmt.Errorf to wrap a sentinel error with a name: - // fmt.Errorf(ErrWrapWithNameFormat, errUtils.ErrSentinel, name) - ErrWrapWithNameFormat = "%w: %s" - // ErrWrapWithNameAndCauseFormat is the format string for wrapping errors with a name and cause. - // Use with fmt.Errorf to wrap a sentinel error with a name and underlying error: - // fmt.Errorf(ErrWrapWithNameAndCauseFormat, errUtils.ErrSentinel, name, underlyingErr) - ErrWrapWithNameAndCauseFormat = "%w '%s': %w" -) - var ( ErrAISkillSourceInvalid = errors.New("invalid skill source") ErrAISkillSourceDrift = errors.New("skill installation is not current") @@ -252,9 +212,10 @@ var ( ErrInvalidTerraformSingleComponentAndMultiComponentFlags = errors.New("the single-component flags (`--from-plan`, `--planfile`) can't be used with the multi-component (bulk operations) flags (`--affected`, `--all`, `--query`, `--components`)") ErrClosureFlagsRequireMultiComponent = errors.New("the `--include-dependencies` and `--include-dependents` flags expand a multi-component selection and require one of `--all`, `--components`, `--query`, `-s`, `--tags`, `--labels`, or `--affected`") - ErrLabelNotFound = errors.New("component label not found") - ErrYamlFuncInvalidArguments = errors.New("invalid number of arguments in the Atmos YAML function") - ErrYamlFuncTemplateEmbedding = errors.New("a YAML function value cannot be used in this template expression") + ErrLabelNotFound = errors.New("component label not found") + ErrYamlFuncInvalidArguments = errors.New("invalid number of arguments in the Atmos YAML function") + ErrYamlFuncTemplateEmbedding = errors.New("a YAML function value cannot be used in this template expression") + //nolint:staticcheck // Error starts with a proper product name. ErrYamlFuncMaxResolutionDepth = errors.New("Atmos YAML function resolution exceeded the maximum dependency depth (likely an undetected circular dependency)") ErrComponentFuncDuringManifestLoad = errors.New("atmos.Component cannot be evaluated while stack manifests are being loaded") ErrDeferredTemplateContextMissing = errors.New("cannot resolve deferred !template value: template context is unavailable because template processing was disabled for this invocation") @@ -471,1624 +432,4 @@ var ( ErrInvalidHelmPluginSpec = errors.New("invalid helm plugin specification") ErrHelmPluginInstall = errors.New("helm plugin installation failed") ErrHelmBinaryNotFound = errors.New("helm binary not found") - - // Toolchain errors. - ErrToolNotFound = errors.New("tool not found") - ErrInvalidToolSpec = errors.New("invalid tool specification") - ErrToolAlreadyInstalled = errors.New("tool already installed") - ErrDownloadFailed = errors.New("download failed") - ErrDownloadRetryable = errors.New("retryable download error") - ErrSignatureRetryable = errors.New("retryable signature verification error") - ErrExtractionFailed = errors.New("extraction failed") - ErrChecksumMismatch = errors.New("checksum mismatch") - ErrNoVersionsInstalled = errors.New("no versions installed") - ErrLatestFileNotFound = errors.New("latest version file not found") - ErrRegistryNotReachable = errors.New("registry not reachable") - ErrToolNotInRegistry = errors.New("tool not in registry") - ErrToolRegistryIndexUnavailable = errors.New("tool registry index unavailable") - ErrToolPlatformNotSupported = errors.New("tool does not support this platform") - ErrAliasNotFound = errors.New("alias not found") - ErrBinaryNotExecutable = errors.New("binary not executable") - ErrBinaryNotFound = errors.New("binary not found") - ErrLockfileVersionMismatch = errors.New("lockfile version mismatch") - ErrFrozenLockfile = errors.New("frozen toolchain lockfile requires an existing complete entry and prohibits updates") - ErrLockfileEmptyVersion = errors.New("lockfile tool version cannot be empty") - ErrNoAssetTemplate = errors.New("no asset template defined") - ErrAssetTemplateInvalid = errors.New("asset template invalid") - ErrToolVersionsFileOperation = errors.New("tool-versions file operation failed") - ErrNoToolsConfigured = errors.New("no tools configured") - ErrUnsupportedVersionConstraint = errors.New("unsupported version constraint format") - ErrToolchainPlainFormatWithAllFlag = errors.New("--format=plain can't be used with --all") - ErrToolchainCleanRequiresConfirmation = errors.New("toolchain clean requires interactive confirmation or --force flag") - ErrToolchainCleanConfirmation = errors.New("toolchain clean confirmation prompt failed") - - // Flag validation errors. - ErrCompatibilityFlagMissingTarget = errors.New("compatibility flag references non-existent flag") - ErrInvalidFlagValue = errors.New("invalid value for flag") - ErrFlagBinding = errors.New("failed to bind flags") - - // File and URL handling errors. - ErrInvalidPagerCommand = errors.New("invalid pager command") - ErrEmptyURL = errors.New("empty URL provided") - ErrFailedToFindImport = errors.New("failed to find import") - ErrInvalidFilePath = errors.New("invalid file path") - ErrRelPath = errors.New("error determining relative path") - ErrHTTPRequestFailed = errors.New("HTTP request failed") - ErrRedirectLimitExceeded = errors.New("stopped after 10 redirects") - - // Config loading errors. - ErrAtmosDirConfigNotFound = errors.New("atmos config directory not found") - ErrReadConfig = errors.New("failed to read config") - ErrMergeTempConfig = errors.New("failed to merge temp config") - ErrPreprocessYAMLFunctions = errors.New("failed to preprocess YAML functions") - ErrMergeEmbeddedConfig = errors.New("failed to merge embedded config") - ErrExpectedDirOrPattern = errors.New("expected directory or pattern") - ErrFileNotFound = errors.New("file not found") - ErrFileAccessDenied = errors.New("file access denied") - ErrExpectedFile = errors.New("expected file") - ErrAtmosArgConfigNotFound = errors.New("atmos configuration not found") - ErrEmptyConfigPath = errors.New("config path is empty") - ErrEmptyConfigFile = errors.New("config file path is empty") - ErrAtmosFilesDirConfigNotFound = errors.New("atmos configuration file not found in directory") - ErrAtmosConfigNotFound = errors.New("atmos configuration file not found") - - // Profile errors. - ErrProfileNotFound = errors.New("profile not found") - ErrProfileSyntax = errors.New("profile syntax error") - ErrProfileDiscovery = errors.New("failed to discover profiles") - ErrProfileLoad = errors.New("failed to load profile") - ErrProfileMerge = errors.New("failed to merge profile configuration") - ErrProfileDirNotExist = errors.New("profile directory does not exist") - ErrProfileDirNotAccessible = errors.New("profile directory not accessible") - ErrProfileInvalidMetadata = errors.New("invalid profile metadata") - ErrProfileSelectionUnavailable = errors.New("interactive profile selection is not available in this context") - ErrProfileNameReserved = errors.New("profile name is reserved") - - ErrMissingStack = errors.New("stack is required; specify it on the command line using the flag `--stack ` (shorthand `-s`)") - ErrMissingComponent = errors.New("component is required") - ErrNoStacksToSelect = errors.New("no stacks are available to choose from") - ErrNoComponentsToSelect = errors.New("no components are configured to choose from") - ErrLoadSelectionOptions = errors.New("failed to load options for interactive selection") - ErrMissingComponentType = errors.New("component type is required") - ErrRequiredFlagNotProvided = errors.New("required flag not provided") - ErrRequiredFlagEmpty = errors.New("required flag cannot be empty") - ErrInvalidArguments = errors.New("invalid arguments") - ErrUnknownSubcommand = errors.New("unknown subcommand") - ErrInvalidComponent = errors.New("invalid component") - ErrDuplicateComponentConfig = errors.New("duplicate component configuration") - // ErrInvalidStack indicates the user provided an identifier that doesn't match - // the stack's canonical name (e.g., using filename when explicit name is set). - // This differs from ErrStackNotFound which indicates the stack doesn't exist at all. - ErrInvalidStack = errors.New("invalid stack") - ErrInvalidComponentMapType = errors.New("invalid component map type") - ErrAbstractComponentCantBeProvisioned = errors.New("abstract component cannot be provisioned") - ErrLockedComponentCantBeProvisioned = errors.New("locked component cannot be provisioned") - ErrSpaceliftAdminStackWorkspaceNotEnabled = errors.New("spacelift admin stack does not have workspace enabled") - ErrSpaceliftAdminStackComponentNotProvisioned = errors.New("spacelift admin stack component cannot be provisioned") - - // Terraform-specific errors. - ErrHTTPBackendWorkspaces = errors.New("workspaces are not supported for the HTTP backend") - ErrInvalidTerraformComponent = errors.New("invalid Terraform component") - ErrNoTty = errors.New("no TTY attached") - ErrNoSuitableShell = errors.New("no suitable shell found") - ErrFailedToLoadTerraformComponent = errors.New("failed to load terraform component") - ErrNoJSONOutput = errors.New("no JSON output found in terraform show output") - ErrOriginalPlanFileRequired = errors.New("original plan file is required") - ErrOriginalPlanFileNotExist = errors.New("original plan file does not exist") - ErrNewPlanFileNotExist = errors.New("new plan file does not exist") - ErrTerraformGenerateBackendArgument = errors.New("invalid arguments") - ErrFileTemplateRequired = errors.New("file-template is required") - ErrInteractiveNotAvailable = errors.New("interactive confirmation not available in non-TTY environment") - ErrDeprecatedCmdNotCallable = errors.New("deprecated command should not be called") - - ErrMissingPackerTemplate = errors.New("packer template is required") - ErrMissingPackerManifest = errors.New("packer manifest is missing") - - ErrAtmosConfigIsNil = errors.New("atmos config is nil") - ErrFailedToInitializeAtmosConfig = errors.New("failed to initialize atmos config") - ErrInvalidListMergeStrategy = errors.New("invalid list merge strategy") - ErrMerge = errors.New("merge error") - ErrMergeNilDst = errors.New("merge destination must not be nil") - ErrMergeTypeMismatch = errors.New("cannot override two slices with different type") - ErrMergeKeyCollision = errors.New("distinct map keys collide after normalization") - ErrEncode = errors.New("encoding error") - ErrDecode = errors.New("decoding error") - - // Stack processing errors. - ErrStackManifestFileNotFound = errors.New("stack manifest file not found") - ErrInvalidStackManifest = errors.New("invalid stack manifest") - ErrStackManifestSchemaValidation = errors.New("stack manifest schema validation failed") - ErrStackImportSelf = errors.New("stack manifest imports itself") - ErrStackImportNotFound = errors.New("stack import not found") - ErrImportPathTemplate = errors.New("failed to render Go template in import path") - ErrStackCircularInheritance = errors.New("circular component inheritance detected") - ErrInvalidHooksSection = errors.New("invalid 'hooks' section in the file") - ErrInvalidTerraformHooksSection = errors.New("invalid 'terraform.hooks' section in the file") - ErrInvalidComponentVars = errors.New("invalid component vars section") - ErrInvalidComponentLocals = errors.New("invalid component locals section") - ErrInvalidComponentSettings = errors.New("invalid component settings section") - ErrInvalidComponentEnv = errors.New("invalid component env section") - ErrInvalidComponentProviders = errors.New("invalid component providers section") - ErrInvalidComponentRequiredProviders = errors.New("invalid component required_providers section") - ErrInvalidComponentRequiredVersion = errors.New("invalid component required_version attribute") - ErrInvalidComponentHooks = errors.New("invalid component hooks section") - ErrUnsupportedHookEvent = errors.New("unsupported hook event") - ErrUnknownHookKind = errors.New("unknown hook kind") - ErrInvalidHookOnFailure = errors.New("invalid hook on_failure value") - ErrInvalidComponentSecrets = errors.New("invalid component secrets section") - ErrStoreIsSecret = errors.New("store is a secret store; use !secret instead of !store") - ErrStoreNotFound = errors.New("store not found") - ErrInvalidComponentGenerate = errors.New("invalid component generate section") - ErrInvalidComponentFlags = errors.New("invalid component flags section") - ErrInvalidComponentAuth = errors.New("invalid component auth section") - ErrInvalidComponentProvision = errors.New("invalid component provision section") - ErrInvalidComponentMetadata = errors.New("invalid component metadata section") - ErrInvalidComponentDependencies = errors.New("invalid component dependencies section") - ErrInvalidComponentBackendType = errors.New("invalid component backend_type attribute") - ErrInvalidComponentBackend = errors.New("invalid component backend section") - ErrInvalidComponentRemoteStateBackendType = errors.New("invalid component remote_state_backend_type attribute") - ErrInvalidComponentRemoteStateBackend = errors.New("invalid component remote_state_backend section") - ErrInvalidComponentCommand = errors.New("invalid component command attribute") - ErrInvalidComponentSource = errors.New("invalid component source section") - ErrInvalidComponentOverrides = errors.New("invalid component overrides section") - ErrInvalidComponentOverridesVars = errors.New("invalid component overrides vars section") - ErrInvalidComponentOverridesSettings = errors.New("invalid component overrides settings section") - ErrInvalidComponentOverridesEnv = errors.New("invalid component overrides env section") - ErrInvalidComponentOverridesAuth = errors.New("invalid component overrides auth section") - ErrInvalidComponentOverridesCommand = errors.New("invalid component overrides command attribute") - ErrInvalidComponentOverridesProviders = errors.New("invalid component overrides providers section") - ErrInvalidComponentOverridesRequiredProviders = errors.New("invalid component overrides required_providers section") - ErrInvalidComponentOverridesRequiredVersion = errors.New("invalid component overrides required_version attribute") - ErrInvalidComponentOverridesHooks = errors.New("invalid component overrides hooks section") - ErrInvalidComponentOverridesGenerate = errors.New("invalid component overrides generate section") - ErrInvalidComponentOverridesProvision = errors.New("invalid component overrides provision section") - ErrInvalidComponentOverridesFlags = errors.New("invalid component overrides flags section") - ErrInvalidComponentAttribute = errors.New("invalid component attribute") - ErrInvalidComponentMetadataComponent = errors.New("invalid component metadata.component attribute") - ErrInvalidSpaceLiftSettings = errors.New("invalid spacelift settings section") - ErrInvalidComponentMetadataInherits = errors.New("invalid component metadata.inherits section") - ErrComponentNotDefined = errors.New("component not defined in any config files") - - // Component registry errors. - ErrComponentProviderNotFound = errors.New("component provider not found") - ErrComponentProviderNil = errors.New("component provider cannot be nil") - ErrComponentTypeEmpty = errors.New("component type is empty") - ErrComponentEmpty = errors.New("component is empty") - ErrStackEmpty = errors.New("stack is empty") - ErrComponentConfigInvalid = errors.New("component configuration invalid") - ErrComponentListFailed = errors.New("failed to list components") - ErrComponentValidationFailed = errors.New("component validation failed") - ErrComponentExecutionFailed = errors.New("component execution failed") - ErrNoRunningContainer = errors.New("no running container found") - ErrComponentArtifactGeneration = errors.New("component artifact generation failed") - ErrComponentProviderRegistration = errors.New("failed to register component provider") - - // Emulator errors. - ErrUnknownEmulatorDriver = errors.New("unknown emulator driver") - ErrEmulatorNotRunning = errors.New("emulator is not running") - ErrEmulatorNotConfigured = errors.New("emulator is not configured") - ErrEmulatorResolutionFailed = errors.New("failed to resolve emulator") - ErrEmulatorAmbiguous = errors.New("emulator identity is ambiguous") - ErrEmulatorTargetMismatch = errors.New("emulator target does not match") - ErrEmulatorConfigInvalid = errors.New("emulator configuration invalid") - ErrEmulatorResolverUnavailable = errors.New("emulator resolver is not available") - ErrEmulatorResetFailed = errors.New("emulator reset failed") - - ErrInvalidTerraformBackend = errors.New("invalid terraform.backend section") - ErrInvalidTerraformRemoteStateBackend = errors.New("invalid terraform.remote_state_backend section") - ErrBackendTypeMismatch = errors.New("backend_type does not match any key configured under backend") - ErrUnsupportedComponentType = errors.New("unsupported component type") - - // Custom component errors. - ErrCustomComponentTypeRegistration = errors.New("failed to register custom component type") - ErrComponentArgumentNotFound = errors.New("no argument or flag with type 'component' found") - ErrStackArgumentNotFound = errors.New("no argument or flag with type 'stack' found") - - // Generator errors. - ErrGeneratorNotFound = errors.New("generator not found") - ErrInvalidGeneratorCtx = errors.New("invalid generator context") - ErrGeneratorValidation = errors.New("generator validation failed") - ErrGenerationFailed = errors.New("generation failed") - ErrGeneratorWriteFailed = errors.New("failed to write generated file") - ErrGeneratorRemoveFailed = errors.New("failed to remove generated file") - ErrGeneratedNotRegular = errors.New("generated file path is not a regular file") - ErrMissingWorkingDir = errors.New("working directory is required") - ErrMissingProviderSource = errors.New("required_providers entry missing 'source' field") - - // Archive package errors (pkg/archive). - ErrArchiveUnknownFormat = errors.New("unknown or unsupported archive format") - ErrArchiveActionNotImplemented = errors.New("archive action is not yet implemented") - ErrArchiveUpdateUnsupportedFormat = errors.New("archive update is not supported for this format") - ErrArchiveOptionsRequired = errors.New("archive options are required") - ErrArchiveSourceRequired = errors.New("archive source is required") - ErrArchiveSourceNotFound = errors.New("archive source does not exist") - ErrArchiveDestinationRequired = errors.New("archive destination is required") - ErrArchiveInvalidGlobPattern = errors.New("invalid archive include/exclude glob pattern") - ErrArchiveInvalidSubpath = errors.New("invalid archive subpath") - ErrArchiveFormatNotImplemented = errors.New("archive format is not yet implemented") - ErrArchiveWriteFailed = errors.New("failed to write archive") - ErrArchiveWalkFailed = errors.New("failed to walk archive source") - ErrArchiveInvalidMtimeMode = errors.New("invalid archive mtime mode") - - // List command errors. - ErrInvalidStackPattern = errors.New("invalid stack pattern") - ErrEmptyTargetComponentName = errors.New("target component name cannot be empty") - ErrComponentsSectionNotFound = errors.New("components section not found in stack") - ErrComponentNotFoundInSections = errors.New("component not found in terraform or helmfile sections") - ErrUnknownComposition = errors.New("component references an undeclared composition") - ErrUnknownCompositionMembership = errors.New("component claims membership in a service not declared by the composition") - ErrQueryFailed = errors.New("query execution failed") - ErrScalarExtractionNotSupported = errors.New("scalar extraction queries are not supported") - ErrQueryUnexpectedResultType = errors.New("query returned unexpected result type") - ErrTableTooWide = errors.New("the table is too wide to display properly") - ErrGettingCommonFlags = errors.New("error getting common flags") - ErrGettingAbstractFlag = errors.New("error getting abstract flag") - ErrGettingVarsFlag = errors.New("error getting vars flag") - ErrInitializingCLIConfig = errors.New("error initializing CLI config") - ErrDescribingStacks = errors.New("error describing stacks") - ErrComponentNameRequired = errors.New("component name is required") - ErrCreateColumnSelector = errors.New("failed to create column selector") - - // Version command errors. - ErrVersionDisplayFailed = errors.New("failed to display version information") - ErrVersionCheckFailed = errors.New("failed to check for version updates") - ErrVersionFormatInvalid = errors.New("invalid version output format") - ErrVersionCacheLoadFailed = errors.New("failed to load version check cache") - ErrVersionGitHubAPIFailed = errors.New("failed to query GitHub API for releases") - - // Version constraint errors. - ErrVersionConstraint = errors.New("version constraint not satisfied") - ErrInvalidVersionConstraint = errors.New("invalid version constraint") - - // Atlantis errors. - ErrAtlantisInvalidFlags = errors.New("incompatible atlantis flags") - ErrAtlantisProjectTemplateNotDef = errors.New("atlantis project template is not defined") - ErrAtlantisConfigTemplateNotDef = errors.New("atlantis config template is not defined") - ErrAtlantisConfigTemplateNotSpec = errors.New("atlantis config template is not specified") - - // Validation errors. - ErrValidationFailed = errors.New("validation failed") - ErrUnsupportedValidationFormat = errors.New("unsupported validation format: expected text or rich") - ErrUnsupportedCIValidationFormat = errors.New("unsupported CI validation format: expected text, rich, or sarif") - ErrWorkflowArgsWithWorkflowPath = errors.New("workflow-file arguments cannot be used with --workflow-path") - ErrAffectedWithFileArgsOrPath = errors.New("--affected cannot be used with workflow-file arguments or --workflow-path") - ErrCIValidatorNotRegistered = errors.New("CI validator is not registered") - - // EditorConfig validation errors. - ErrEditorConfigValidationFailed = errors.New("EditorConfig validation failed") - ErrEditorConfigVersionMismatch = errors.New("EditorConfig version mismatch") - ErrEditorConfigGetFiles = errors.New("failed to get files for EditorConfig validation") - ErrEditorConfigInvalidFormat = errors.New("invalid EditorConfig output format") - - // Global/Stack-level section errors. - ErrInvalidVarsSection = errors.New("invalid vars section") - ErrInvalidSettingsSection = errors.New("invalid settings section") - ErrInvalidEnvSection = errors.New("invalid env section") - ErrInvalidGenerateSection = errors.New("invalid generate section") - ErrInvalidDependenciesSection = errors.New("invalid dependencies section") - ErrInvalidTerraformSection = errors.New("invalid terraform section") - ErrInvalidHelmfileSection = errors.New("invalid helmfile section") - ErrInvalidPackerSection = errors.New("invalid packer section") - ErrInvalidComponentsSection = errors.New("invalid components section") - ErrInvalidAuthSection = errors.New("invalid auth section") - ErrInvalidGlobalMetadataSection = errors.New("invalid metadata section") - ErrGlobalMetadataFieldNotAllowed = errors.New("metadata field is not allowed at global (stack-wide) scope") - ErrInvalidGlobalRetrySection = errors.New("invalid retry section") - ErrInvalidImportSection = errors.New("invalid import section") - ErrInvalidImport = errors.New("invalid import") - ErrInvalidRemoteImport = errors.New("invalid remote import") - ErrOCIImportMissingPath = errors.New("an oci:// import requires a '//' path to the file inside the artifact") - ErrDownloadRemoteImport = errors.New("failed to download remote import") - ErrCacheDirectoryCreation = errors.New("failed to create cache directory") - ErrClearCache = errors.New("failed to clear cache") - ErrInvalidOverridesSection = errors.New("invalid overrides section") - ErrInvalidTerraformOverridesSection = errors.New("invalid terraform overrides section") - ErrInvalidHelmOverridesSection = errors.New("invalid helm overrides section") - ErrInvalidHelmfileOverridesSection = errors.New("invalid helmfile overrides section") - ErrInvalidBaseComponentConfig = errors.New("invalid base component config") - ErrCircularComponentInheritance = ErrStackCircularInheritance - - // Terraform-specific subsection errors. - ErrInvalidTerraformCommand = errors.New("invalid terraform command") - ErrInvalidTerraformVars = errors.New("invalid terraform vars section") - ErrInvalidTerraformSettings = errors.New("invalid terraform settings section") - ErrInvalidTerraformEnv = errors.New("invalid terraform env section") - ErrInvalidTerraformProviders = errors.New("invalid terraform providers section") - ErrInvalidTerraformGenerateSection = errors.New("invalid terraform generate section") - ErrInvalidTerraformFlagsSection = errors.New("invalid terraform flags section") - ErrInvalidTerraformBackendType = errors.New("invalid terraform backend_type") - ErrMissingTerraformBackendType = errors.New("'backend_type' is missing for the component") - ErrMissingTerraformBackendConfig = errors.New("'backend' config is missing for the component") - ErrMissingTerraformWorkspaceKeyPrefix = errors.New("backend config is missing 'workspace_key_prefix'") - ErrInvalidTerraformRemoteStateType = errors.New("invalid terraform remote_state_backend_type") - ErrInvalidTerraformRemoteStateSection = errors.New("invalid terraform remote_state_backend section") - ErrInvalidTerraformAuth = errors.New("invalid terraform auth section") - ErrInvalidTerraformDependencies = errors.New("invalid terraform dependencies section") - ErrInvalidTerraformSource = errors.New("invalid terraform source section") - ErrInvalidTerraformProvision = errors.New("invalid terraform provision section") - ErrUnresolvedComputedTerraformVar = errors.New("terraform variable contains an unresolved computed value") - - // Helmfile-specific subsection errors. - ErrInvalidHelmfileCommand = errors.New("invalid helmfile command") - ErrInvalidHelmfileVars = errors.New("invalid helmfile vars section") - ErrInvalidHelmfileSettings = errors.New("invalid helmfile settings section") - ErrInvalidHelmfileEnv = errors.New("invalid helmfile env section") - ErrInvalidHelmfileAuth = errors.New("invalid helmfile auth section") - ErrInvalidHelmfileDependencies = errors.New("invalid helmfile dependencies section") - - // Helmfile configuration errors. - ErrMissingHelmfileBasePath = errors.New("helmfile base path is required") - ErrMissingHelmfileKubeconfigPath = errors.New("helmfile kubeconfig path is required") - ErrMissingHelmfileAwsProfilePattern = errors.New("helmfile AWS profile pattern is required") - ErrMissingHelmfileClusterNamePattern = errors.New("helmfile cluster name pattern is required") - ErrMissingHelmfileClusterName = errors.New("helmfile cluster name is required") - ErrMissingHelmfileAuth = errors.New("helmfile AWS authentication is required") - - // Packer configuration errors. - ErrMissingPackerBasePath = errors.New("packer base path is required") - - // Packer-specific subsection errors. - ErrInvalidPackerCommand = errors.New("invalid packer command") - ErrInvalidPackerVars = errors.New("invalid packer vars section") - ErrInvalidPackerSettings = errors.New("invalid packer settings section") - ErrInvalidPackerEnv = errors.New("invalid packer env section") - ErrInvalidPackerAuth = errors.New("invalid packer auth section") - ErrInvalidPackerDependencies = errors.New("invalid packer dependencies section") - - // Ansible configuration errors. - ErrMissingAnsibleBasePath = errors.New("ansible base path is required") - - // Ansible-specific subsection errors. - ErrInvalidAnsibleSection = errors.New("invalid ansible section") - ErrInvalidAnsibleCommand = errors.New("invalid ansible command") - ErrInvalidAnsibleVars = errors.New("invalid ansible vars section") - ErrInvalidAnsibleSettings = errors.New("invalid ansible settings section") - ErrInvalidAnsibleEnv = errors.New("invalid ansible env section") - ErrInvalidAnsibleAuth = errors.New("invalid ansible auth section") - ErrInvalidAnsibleDependencies = errors.New("invalid ansible dependencies section") - - // Ansible execution errors. - ErrAnsiblePlaybookMissing = errors.New("ansible playbook is required") - - // Component type-specific section errors. - ErrInvalidComponentsTerraform = errors.New("invalid components.terraform section") - ErrInvalidComponentsHelmfile = errors.New("invalid components.helmfile section") - ErrInvalidComponentsPacker = errors.New("invalid components.packer section") - ErrInvalidComponentsAnsible = errors.New("invalid components.ansible section") - - // Specific component configuration errors. - ErrInvalidSpecificTerraformComponent = errors.New("invalid terraform component configuration") - ErrInvalidSpecificHelmfileComponent = errors.New("invalid helmfile component configuration") - ErrInvalidSpecificPackerComponent = errors.New("invalid packer component configuration") - ErrInvalidSpecificAnsibleComponent = errors.New("invalid ansible component configuration") - - // Pro API client errors. - ErrFailedToCreateRequest = errors.New("failed to create request") - ErrFailedToMarshalPayload = errors.New("failed to marshal request body") - ErrFailedToCreateAuthRequest = errors.New("failed to create authenticated request") - ErrFailedToMakeRequest = errors.New("failed to make request") - ErrFailedToUploadStacks = errors.New("failed to upload stacks") - ErrFailedToReadResponseBody = errors.New("failed to read response body") - ErrFailedToLockStack = errors.New("failed to lock stack") - ErrFailedToUnlockStack = errors.New("failed to unlock stack") - ErrOIDCWorkspaceIDRequired = errors.New("workspace ID environment variable is required for OIDC authentication") - ErrOIDCTokenExchangeFailed = errors.New("failed to exchange OIDC token for Atmos token") - ErrOIDCAuthFailedNoToken = errors.New("OIDC authentication failed: no token") - ErrNotInGitHubActions = errors.New("not running in GitHub Actions or missing OIDC token environment variables") - ErrFailedToGetOIDCToken = errors.New("failed to get OIDC token") - ErrFailedToDecodeOIDCResponse = errors.New("failed to decode OIDC token response") - ErrFailedToExchangeOIDCToken = errors.New("failed to exchange OIDC token") - ErrFailedToDecodeTokenResponse = errors.New("failed to decode token response") - ErrFailedToGetGitHubOIDCToken = errors.New("failed to get GitHub OIDC token") - ErrFailedToUploadInstances = errors.New("failed to upload instances") - ErrFailedToUploadInstanceStatus = errors.New("failed to upload instance status") - ErrPayloadTooLarge = errors.New("request exceeded the Atmos Pro body size limit") - ErrUploadRetryExhausted = errors.New("upload failed after all retries") - ErrTokenRefreshFailed = errors.New("failed to refresh API token") - ErrFailedToUnmarshalAPIResponse = errors.New("failed to unmarshal API response") - ErrNilRequestDTO = errors.New("nil request DTO") - ErrProExceptionEnvelopeTooLarge = errors.New("pro exception envelope exceeds the ingestion limit") - ErrFailedToUploadExecMetadata = errors.New("failed to upload execution metadata") - ErrFailedToUploadExecData = errors.New("failed to upload execution data") - ErrExecPayloadTooLarge = errors.New("execution metadata payload too large") - ErrExecSyncTimeout = errors.New("execution metadata upload timed out") - - // Pro commit errors. - ErrCommitMessageRequired = errors.New("commit message is required") - ErrCommitMessageTooLong = errors.New("commit message exceeds 500 characters") - ErrCommentTooLong = errors.New("comment exceeds 2000 characters") - ErrBranchRequired = errors.New("GITHUB_HEAD_REF is required (this command only runs in PR workflows)") - ErrBranchInvalid = errors.New("branch name contains invalid characters") - ErrTooManyChanges = errors.New("too many changed files (max 200)") - ErrCommitInvalidFilePath = errors.New("invalid file path for commit") - ErrFileTooLarge = errors.New("file exceeds 2 MiB size limit") - ErrFailedToStageChanges = errors.New("failed to stage changes") - ErrFailedToDetectChanges = errors.New("failed to detect git changes") - ErrFailedToCreateCommit = errors.New("failed to create commit via Atmos Pro") - ErrStagingFlagConflict = errors.New("--add and --all are mutually exclusive") - ErrAPIResponseError = errors.New("API response error") - - // Exec package errors. - ErrComponentAndStackRequired = errors.New("component and stack are both required") - ErrFailedToCreateAPIClient = errors.New("failed to create API client") - ErrFailedToProcessArgs = errors.New("failed to process command-line arguments") - ErrFailedToInitConfig = errors.New("failed to initialize Atmos configuration") - ErrFailedToCreateLogger = errors.New("failed to create logger") - ErrFailedToGetComponentFlag = errors.New("failed to get '--component' flag") - ErrFailedToGetStackFlag = errors.New("failed to get '--stack' flag") - ErrOPAPolicyViolations = errors.New("OPA policy violations detected") - ErrOPATimeout = errors.New("timeout evaluating OPA policy") - ErrInvalidRegoPolicy = errors.New("invalid Rego policy") - ErrInvalidOPAPolicy = errors.New("invalid OPA policy") - ErrTerraformEnvCliVarJSON = errors.New("failed to parse JSON variable from TF_CLI_ARGS environment variable") - ErrWorkflowBasePathNotConfigured = errors.New("'workflows.base_path' must be configured in 'atmos.yaml'") - ErrWorkflowDirectoryDoesNotExist = errors.New("workflow directory does not exist") - ErrWorkflowNoSteps = errors.New("workflow has no steps defined") - ErrInvalidWorkflowStepType = errors.New("invalid workflow step type") - ErrInvalidContinueCondition = errors.New("invalid 'continue' condition") - ErrInvalidFromStep = errors.New("invalid from-step flag") - ErrWorkflowStepFailed = errors.New("workflow step execution failed") - ErrWorkflowNoWorkflow = errors.New("no workflow found") - ErrWorkflowFileNotFound = errors.New("workflow file not found") - ErrInvalidWorkflowManifest = errors.New("invalid workflow manifest") - ErrResolveExecutablePath = errors.New("failed to resolve the running atmos executable's own path") - ErrUnknownStepType = errors.New("unknown step type") - ErrStepOptionsRequired = errors.New("options is required for step") - ErrStepContentOrOptionsRequired = errors.New("either content or options is required for step") - ErrStepDataOrContentRequired = errors.New("either data or content is required for step") - ErrStepEmptyCommand = errors.New("empty command for step") - ErrStepNoFilesFound = errors.New("no files found matching criteria") - ErrStepFieldRequired = errors.New("required field missing for step") - ErrStepExecutionFailed = errors.New("step execution failed") - ErrStepTTYRequired = errors.New("interactive terminal required for step") - ErrStepTimeout = errors.New("step timed out") - ErrStepTimeoutInvalid = errors.New("invalid step timeout") - ErrStepInvalidOutputMode = schemaPkg.ErrStepInvalidOutputMode - ErrCustomCommandArgumentMissing = errors.New("missing required argument for custom command") - ErrCustomCommandFlagType = errors.New("unsupported custom command flag type") - ErrCustomCommandFlagDefault = errors.New("invalid default value for custom command flag") - ErrHTTPStepURLRequired = errors.New("url is required for http step") - ErrHTTPStepInvalidMethod = errors.New("invalid HTTP method for http step") - ErrHTTPStepBodyFormConflict = errors.New("http step cannot set both body and form") - ErrHTTPStepInvalidExpectPattern = errors.New("invalid expect.response regex pattern for http step") - ErrHTTPStepRequestFailed = errors.New("http request failed") - ErrHTTPStepUnexpectedStatus = errors.New("http response did not match expected status") - ErrHTTPStepUnexpectedResponse = errors.New("http response body did not match expected pattern") - ErrArchiveStepInvalidAction = errors.New("invalid action for archive step") - ErrArchiveStepInvalidSource = errors.New("archive step source must be a string path") - ErrStoreStepInvalidAction = errors.New("invalid action for store step") - ErrStoreStepWriteFailed = errors.New("store step failed to write value") - ErrContainerStepResolveStack = errors.New("failed to resolve stack for container step") - ErrRequireStepEmpty = errors.New("require step must specify at least one of tools, files, or dirs") - ErrRequirementsNotMet = errors.New("required tools or paths are missing") - ErrWorkingDirNotFound = errors.New("working directory does not exist") - ErrWorkingDirNotDirectory = errors.New("working directory path is not a directory") - ErrWorkingDirAccessFailed = errors.New("failed to access working directory") - ErrWorkflowExit = errors.New("workflow exit requested") - ErrAuthProviderNotAvailable = errors.New("auth provider is not available") - ErrInvalidComponentArgument = errors.New("invalid arguments. The command requires one argument 'componentName'") - ErrValidation = errors.New("validation failed") - ErrCUEValidationUnsupported = errors.New("validation using CUE is not supported yet") - - // List package errors. - ErrExecuteDescribeStacks = errors.New("failed to execute describe stacks") - ErrProcessInstances = errors.New("failed to process instances") - ErrParseFlag = errors.New("failed to parse flag value") - ErrFailedToFinalizeCSVOutput = errors.New("failed to finalize CSV output") - ErrParseStacks = errors.New("could not parse stacks") - ErrParseComponents = errors.New("could not parse components") - ErrNoComponentsFound = errors.New("no components found") - ErrNoStacksFound = errors.New("no stacks found") - ErrStackNotFound = errors.New("stack not found") - ErrProcessStack = errors.New("error processing stack") - - // Dependency errors. - ErrUnsupportedDependencyType = errors.New("unsupported dependency type") - ErrMissingDependencyField = errors.New("dependency missing required field") - ErrDependencyTargetNotFound = errors.New("dependency target not found") - ErrDependencyTargetUnavailable = errors.New("dependency target unavailable") - // ErrSurvivingConsumers is returned when a destroy selection would remove a component that - // components outside the selection still require. - ErrSurvivingConsumers = errors.New("destroy would leave components that depend on it") - // ErrCustomCommandDependencyNotRegistered is returned when a dependencies.commands entry - // names a command that isn't registered under the custom-command cobra tree. - ErrCustomCommandDependencyNotRegistered = errors.New("dependency command is not registered") - // ErrAmbiguousCommandName is returned when a dependencies.commands entry names a command - // that more than one declared Command shares (e.g. two unrelated parents each with a nested - // child of the same name) -- there is no well-defined "first" match to silently pick. - ErrAmbiguousCommandName = errors.New("multiple commands share this name; use a unique name or restructure your commands") - - // Terraform --all flag errors. - ErrComponentWithAllFlagConflict = errors.New("component argument can't be used with --all flag") - - // ErrCacheCertUntrusted is returned when the OS trust store does not trust the - // registry cache proxy's certificate (macOS/Windows require a one-time trust step). - ErrCacheCertUntrusted = errors.New("registry cache certificate is not trusted") - - // ErrTrustStore is returned when installing or removing the registry cache proxy's - // certificate in the OS trust store fails. - ErrTrustStore = errors.New("registry cache trust store operation failed") - - // Terraform execution errors. - ErrTerraformExecFailed = errors.New("terraform execution failed") - ErrDescribeAffected = errors.New("describe affected failed") - ErrUploadRequiresSupportedEvent = errors.New("upload requires a supported CI event") - ErrDescribeStacks = errors.New("describe stacks failed") - ErrBuildDepGraph = errors.New("build dependency graph failed") - ErrTopologicalOrder = errors.New("topological sort failed") - ErrGraphExecutionCanceled = errors.New("graph execution canceled") - ErrGraphExecutionOptions = errors.New("graph execution options are invalid") - ErrFormatForLogging = errors.New("format affected for logging failed") - ErrQueryEvaluation = errors.New("query evaluation failed") - ErrNilResult = errors.New("nil result") - - // Cache-related errors. - ErrCacheLocked = errors.New("cache file is locked") - ErrCacheRead = errors.New("cache read failed") - ErrCacheWrite = errors.New("cache write failed") - ErrCacheFetch = errors.New("failed to fetch content for cache") - ErrCacheUnmarshal = errors.New("cache unmarshal failed") - ErrCacheMarshal = errors.New("cache marshal failed") - ErrCacheDir = errors.New("cache directory creation failed") - - // Logger errors. - ErrInvalidLogLevel = errors.New("invalid log level") - ErrInvalidLogsColor = errors.New("invalid logs color") - - // File operation errors. - ErrCopyFile = errors.New("failed to copy file") - ErrCreateDirectory = errors.New("failed to create directory") - ErrCreateFile = errors.New("failed to create file") - ErrOpenFile = errors.New("failed to open file") - ErrWriteFile = errors.New("failed to write to file") - ErrCloseFile = errors.New("failed to close file") - ErrStatFile = errors.New("failed to stat file") - ErrRemoveDirectory = errors.New("failed to remove directory") - ErrSetPermissions = errors.New("failed to set permissions") - ErrReadDirectory = errors.New("failed to read directory") - ErrComputeRelativePath = errors.New("failed to compute relative path") - ErrFileOperation = errors.New("file operation failed") - - // Archive extraction safety errors (pkg/filesystem). - ErrArchiveEntryEscapesDest = errors.New("archive entry escapes destination directory") - - // OCI/Container image errors. - ErrCreateTempDirectory = ErrCreateTempDir // Alias to avoid duplicate sentinels - ErrInvalidImageReference = errors.New("invalid image reference") - ErrPullImage = errors.New("failed to pull image") - ErrOCIGetFileUnsupported = errors.New("oci:// sources must be fetched in directory mode, not as a single file") - ErrGetImageDescriptor = errors.New("cannot get a descriptor for the OCI image") - ErrGetImageLayers = errors.New("failed to get image layers") - ErrProcessLayer = errors.New("failed to process layer") - ErrLayerDecompression = errors.New("layer decompression error") - ErrLayerExtraction = errors.New("layer extraction error") - ErrArchiveTooLarge = errors.New("archive exceeds maximum size") - ErrArchiveEntryTooLarge = errors.New("archive entry exceeds maximum extracted size") - - // Initialization and configuration errors. - ErrInitializeCLIConfig = errors.New("error initializing CLI config") - ErrGetHooks = errors.New("error getting hooks") - ErrPerComponentHookFailed = errors.New("per-component hook failed") - ErrSetFlag = errors.New("failed to set flag") - ErrVersionMismatch = errors.New("version mismatch") - - // Download and client errors. - ErrMergeConfiguration = errors.New("failed to merge configuration") - - // Template and documentation errors. - ErrGenerateTerraformDocs = errors.New("failed to generate terraform docs") - ErrMergeInputYAMLs = errors.New("failed to merge input YAMLs") - ErrRenderTemplate = errors.New("failed to render template with datasources") - // ErrGomplateDatasourceUnavailable is returned when a gomplate datasource is read outside a - // template render, or while gomplate functions are disabled, so no datasource registry exists. - ErrGomplateDatasourceUnavailable = errors.New("gomplate datasource functions are unavailable: gomplate is disabled or no template render is in progress") - ErrInvalidDatasourceURL = errors.New("invalid gomplate datasource URL") - ErrResolveOutputPath = errors.New("failed to resolve output path") - ErrWriteOutput = errors.New("failed to write output") - ErrCollectKeysNotMap = errors.New("collectKeys: argument is not a map") - - // Import-related errors. - ErrBasePath = errors.New("base path required to process imports") - ErrTempDir = errors.New("temporary directory required to process imports") - ErrResolveLocal = errors.New("failed to resolve local import path") - ErrSourceDestination = errors.New("source and destination cannot be nil") - ErrImportPathRequired = errors.New("import path required to process imports") - ErrNoFileMatchPattern = errors.New("no files matching patterns found") - ErrMaxImportDepth = errors.New("maximum import depth reached") - ErrNoValidAbsolutePaths = errors.New("no valid absolute paths found") - ErrDownloadRemoteConfig = errors.New("failed to download remote config") - ErrMockImportFailure = errors.New("mock error: simulated import failure") - ErrProcessNestedImports = errors.New("failed to process nested imports") - // ErrRequiredImportFailed is returned when a required (non-optional) CLI-config import - // cannot be resolved or merged. Object-form imports are required by default (fail closed); - // set `skip_if_missing: true` to opt back into warn-and-skip. - ErrRequiredImportFailed = errors.New("required config import failed to load") - // ErrInvalidConfigImport is returned when an object-form CLI-config import entry cannot be - // decoded (e.g. a malformed `skip_if_missing` or `when` value). A malformed entry must fail - // loudly rather than being silently dropped and treated as an optional omission. - ErrInvalidConfigImport = errors.New("invalid config import entry") - - // Profiler-related errors. - ErrProfilerStart = errors.New("profiler start failed") - ErrProfilerUnsupportedType = errors.New("profiler: unsupported profile type") - ErrProfilerStartCPU = errors.New("profiler: failed to start CPU profile") - ErrProfilerStartTrace = errors.New("profiler: failed to start trace profile") - ErrProfilerCreateFile = errors.New("profiler: failed to create profile file") - - // Auth package errors. - ErrAuthNotConfigured = errors.New("authentication not configured in atmos.yaml") - ErrInvalidAuthConfig = errors.New("invalid auth config") - ErrInvalidIdentityKind = errors.New("invalid identity kind") - ErrInvalidIdentityConfig = errors.New("invalid identity config") - ErrInvalidProviderKind = errors.New("invalid provider kind") - ErrInvalidProviderConfig = errors.New("invalid provider config") - ErrInvalidBrowserExecutable = errors.New("invalid browser executable") - ErrAuthenticationFailed = errors.New("authentication failed") - ErrAuthenticationUnavailable = errors.New("authentication unavailable") - ErrPrepareShellEnvironment = errors.New("failed to prepare authenticated shell environment") - ErrInvalidADCContent = errors.New("invalid ADC content") - ErrWriteADCFile = errors.New("failed to write ADC file") - ErrWritePropertiesFile = errors.New("failed to write properties file") - ErrWriteAccessTokenFile = errors.New("failed to write access token file") - ErrPostAuthenticationHookFailed = errors.New("post authentication hook failed") - ErrAuthManager = errors.New("auth manager error") - ErrDefaultIdentity = errors.New("default identity error") - ErrAwsAuth = errors.New("aws auth error") - ErrAwsUserNotConfigured = errors.New("aws user not configured") - ErrAwsUserKeyringReadFailed = errors.New("failed to read AWS user credentials from keyring") - ErrAwsSAMLDecodeFailed = errors.New("aws saml decode failed") - ErrPlaywrightDriverSeed = errors.New("failed to pre-seed the Playwright driver") - ErrAwsMissingEnvVars = errors.New("missing required AWS environment variables") - ErrIdentityNotAWS = errors.New("identity does not produce AWS credentials") - ErrUnsupportedPlatform = errors.New("unsupported platform") - ErrChromeNotFound = errors.New("chrome/chromium not found for isolated browser sessions") - ErrSayNotFound = errors.New("text-to-speech command not found") - ErrVoiceListUnsupported = errors.New("voice enumeration not supported for backend") - ErrUserAborted = errors.New("user aborted") - - // GitHub OIDC provider errors. - // ErrGitHubOIDCEndpointUnavailable marks a token request that failed in a way worth retrying: - // a timeout or other transport error, HTTP 429, or HTTP 5xx. - ErrGitHubOIDCEndpointUnavailable = errors.New("GitHub OIDC token endpoint unavailable") - - // AWS credential_process errors (consuming and producing the AWS process-credential format). - ErrCredentialProcessFailed = errors.New("credential_process command failed") - ErrCredentialProcessInvalidOutput = errors.New("credential_process returned invalid output") - ErrCredentialProcessRecursion = errors.New("credential_process recursion detected") - // ErrCredentialProcessIdentityRequired is returned when the credential-process producer is not - // given a concrete identity (it never opens the interactive selector, which the AWS CLI hides). - ErrCredentialProcessIdentityRequired = errors.New("credential_process requires a specific identity") - // ErrAWSCredentialsIncomplete is returned when AWS credentials lack an access key ID or secret access key. - ErrAWSCredentialsIncomplete = errors.New("AWS credentials are missing an access key ID or secret access key") - - // AWS SSO specific errors. - ErrSSOSessionExpired = errors.New("aws sso session expired") - ErrSSODeviceAuthFailed = errors.New("aws sso device authorization failed") - ErrSSOTokenCreationFailed = errors.New("aws sso token creation failed") - ErrSSOAccountListFailed = errors.New("failed to list aws sso accounts") - ErrSSORoleListFailed = errors.New("failed to list aws sso roles") - ErrSSOProvisioningFailed = errors.New("aws sso identity provisioning failed") - ErrSSOInvalidToken = errors.New("invalid aws sso token") - - // AWS browser webflow errors. - ErrWebflowAuthFailed = errors.New("browser authentication failed") - ErrWebflowDisabled = errors.New("browser authentication is disabled") - ErrWebflowTokenExchange = errors.New("failed to exchange authorization code for credentials") - ErrWebflowCallbackServer = errors.New("failed to start local callback server") - ErrWebflowTimeout = errors.New("browser authentication timed out") - ErrWebflowRefreshFailed = errors.New("failed to refresh browser credentials") - // ErrWebflowRefreshTokenRevoked indicates the refresh token has been definitively - // rejected by the AWS signin service (e.g. HTTP 400 invalid_grant/invalid_token). - // This is the only condition under which the cached refresh token should be deleted; - // transient failures (HTTP 5xx, 429, network errors) must preserve the cache. - ErrWebflowRefreshTokenRevoked = errors.New("browser refresh token has been revoked") - ErrWebflowCodeRequired = errors.New("authorization code is required") - ErrWebflowReadAuthCodeFailed = errors.New("failed to read authorization code") - ErrWebflowAuthorizationError = errors.New("authorization error") - ErrWebflowMissingCallbackCode = errors.New("missing authorization code in callback") - ErrWebflowStateMismatch = errors.New("state mismatch: possible CSRF attack") - ErrWebflowEmptyCachedToken = errors.New("cached refresh token is empty") - // ErrWebflowDPoP indicates a failure generating or serializing the RFC 9449 - // DPoP proof required on AWS signin token requests (issue #2542). - ErrWebflowDPoP = errors.New("failed to build DPoP proof") - - // Credential errors. - ErrCredentialsInvalid = errors.New("credentials are invalid or have been revoked") - ErrInvalidDuration = duration.ErrInvalid // Alias so errors.Is matches pkg/duration errors. - - // Auth manager and identity/provider resolution errors (centralized sentinels). - ErrFailedToInitializeAuthManager = errors.New("failed to initialize auth manager") - ErrNoCredentialsFound = errors.New("no credentials found for identity") - ErrExpiredCredentials = errors.New("credentials for identity are expired or invalid") - ErrNilParam = errors.New("parameter cannot be nil") - ErrInitializingProviders = errors.New("failed to initialize providers") - ErrInitializingIdentities = errors.New("failed to initialize identities") - ErrInitializingCredentialStore = errors.New("failed to initialize credential store") - ErrCircularDependency = errors.New("circular dependency detected in identity chain") - ErrIdentityNotFound = errors.New("identity not found") - ErrProviderNotFound = errors.New("provider not found") - ErrMutuallyExclusiveFlags = errors.New("mutually exclusive flags provided") - ErrNoDefaultIdentity = errors.New("no default identity configured for authentication") - ErrMultipleDefaultIdentities = errors.New("multiple default identities found") - ErrNoIdentitiesAvailable = errors.New("no identities available") - ErrNoProvidersAvailable = errors.New("no providers available") - ErrNoIdentitiesMatchTags = errors.New("no identities match the specified tags") - ErrNoProvidersMatchTags = errors.New("no providers match the specified tags") - ErrNoDefaultProvider = errors.New("no default provider configured and multiple providers exist") - ErrIdentitySelectionRequiresTTY = fmt.Errorf("interactive identity selection: %w", ErrTTYRequired) - ErrProviderSelectionRequiresTTY = fmt.Errorf("interactive provider selection: %w", ErrTTYRequired) - ErrAuthPromptUnavailable = fmt.Errorf("interactive authentication prompt unavailable: %w", ErrTTYRequired) - ErrAuthenticationChainNotBuilt = errors.New("authentication chain not built") - ErrInvalidStackConfig = errors.New("invalid stack config") - ErrNoCommandSpecified = errors.New("no command specified") - ErrCommandNotFound = errors.New("command not found") - ErrCommandFailed = errors.New("command execution failed") - - // Auth validation errors - specific sentinel errors for configuration validation. - ErrMissingPrincipal = errors.New("principal is required") - ErrMissingAssumeRole = errors.New("assume_role is required in principal") - ErrMissingPermissionSet = errors.New("permission set name is required in principal") - ErrMissingAccountSpec = errors.New("account specification is required in principal") - - ErrInvalidSubcommand = errors.New("invalid subcommand") - ErrSubcommandFailed = errors.New("subcommand failed") - - ErrInvalidArgumentError = errors.New("invalid argument error") - ErrMissingInput = errors.New("missing input") - - ErrAuthAwsFileManagerFailed = errors.New("failed to create AWS file manager") - - ErrAuthOidcDecodeFailed = errors.New("failed to decode OIDC token") - ErrAuthOidcUnmarshalFailed = errors.New("failed to unmarshal oidc claims") - - // Realm errors. - ErrFailedToComputeRealm = errors.New("failed to compute realm") - ErrInvalidRealm = errors.New("invalid realm value") - ErrEmptyRealm = errors.New("realm is required for credential isolation but was not set") - - // Logout errors. - ErrFailedGetConfigDir = errors.New("failed to get config directory") - ErrFailedDiscoverRealms = errors.New("failed to discover realms") - ErrFailedRemoveRealm = errors.New("failed to remove realm") - - // Store and hook errors. - ErrNilTerraformOutput = errors.New("terraform output returned nil") - ErrNilStoreValue = errors.New("cannot store nil value") - - // Devcontainer errors. - ErrDevcontainerNotFound = errors.New("devcontainer not found") - ErrContainerRuntimeOperation = errors.New("container runtime operation failed") - ErrContainerNotFound = errors.New("container not found") - ErrContainerAlreadyExists = errors.New("container already exists") - ErrContainerNotRunning = errors.New("container is not running") - ErrContainerRunning = errors.New("container is running") - ErrContainerNotHealthy = errors.New("container did not become healthy") - ErrInvalidDevcontainerConfig = errors.New("invalid devcontainer configuration") - ErrRuntimeNotAvailable = errors.New("container runtime not available") - ErrDevcontainerNameEmpty = errors.New("devcontainer name cannot be empty") - ErrDevcontainerNameInvalid = errors.New("devcontainer name contains invalid characters") - ErrDevcontainerNameTooLong = errors.New("devcontainer name is too long") - ErrPTYNotSupported = errors.New("PTY not supported on this platform") - - // Container bulk-operation errors. - ErrNoContainerComponentSelected = errors.New("no container component selected") - ErrContainerComponentWithAll = errors.New("cannot combine a component argument with --all") - - // Container run configuration errors. - ErrInvalidContainerRestartPolicy = errors.New("invalid container restart policy") - ErrInvalidContainerHealthCheck = errors.New("invalid container healthcheck") - - // Logout errors. - ErrLogoutFailed = errors.New("logout failed") - ErrPartialLogout = errors.New("partial logout") - ErrLogoutNotSupported = errors.New("logout not supported for this provider") - ErrLogoutNotImplemented = errors.New("logout not implemented for this provider") - ErrKeyringDeletion = errors.New("keyring deletion failed") - ErrKeychainDeletionRequiresConfirmation = errors.New("keychain deletion requires interactive confirmation or --force flag") - ErrProviderLogout = errors.New("provider logout failed") - ErrIdentityLogout = errors.New("identity logout failed") - ErrIdentityNotInConfig = errors.New("identity not found in configuration") - ErrProviderNotInConfig = errors.New("provider not found in configuration") - ErrInvalidLogoutOption = errors.New("invalid logout option") - - // Provision target (delivery destination) errors. - ErrProvisionTargetNotFound = errors.New("provision target not found") - ErrProvisionTargetKindUnknown = errors.New("provision target kind is not registered") - ErrProvisionTargetKindMissing = errors.New("provision target is missing a kind") - ErrProvisionTargetNoFetch = errors.New("provision target kind does not support reading current state") - - // Git target pull-request publishing errors. - ErrGitTargetPullRequestConfig = errors.New("invalid git target pull_request configuration") - - // Backend provisioning errors. - ErrBucketRequired = errors.New("backend.bucket is required") - ErrRegionRequired = errors.New("backend.region is required") - ErrBackendNotFound = errors.New("backend configuration not found") - ErrProvisioningNotConfigured = errors.New("provisioning not configured") - ErrCreateNotImplemented = errors.New("create not implemented for backend type") - ErrInvalidBucketNamespace = errors.New("provision.backend.bucket_namespace must be a string") - ErrUnsupportedBucketNamespace = errors.New("unsupported provision.backend.bucket_namespace value") - ErrDeleteNotImplemented = errors.New("delete not implemented for backend type") - ErrProvisionerFailed = errors.New("provisioner failed") - ErrLoadAWSConfig = errors.New("failed to load AWS config") - ErrCheckBucketExist = errors.New("failed to check bucket existence") - ErrCreateBucket = errors.New("failed to create bucket") - ErrApplyBucketDefaults = errors.New("failed to apply bucket defaults") - ErrEnableVersioning = errors.New("failed to enable versioning") - ErrEnableEncryption = errors.New("failed to enable encryption") - ErrBlockPublicAccess = errors.New("failed to block public access") - ErrApplyTags = errors.New("failed to apply tags") - ErrForceRequired = errors.New("--force flag required for backend deletion") - ErrBucketNotEmpty = errors.New("bucket contains objects and cannot be deleted") - ErrStateFilesExist = errors.New("bucket contains terraform state files") - ErrDeleteObjects = errors.New("failed to delete objects from bucket") - ErrDeleteBucket = errors.New("failed to delete bucket") - ErrListObjects = errors.New("failed to list bucket objects") - - // Azure (azurerm) backend provisioning errors. - ErrResourceGroupRequired = errors.New("backend.resource_group_name is required for azurerm backend provisioning") - ErrAzureSubscriptionRequired = errors.New("an Azure subscription id is required for azurerm backend provisioning (set backend.subscription_id or a subscription on the active Azure identity)") - ErrAzureLocationRequired = errors.New("an Azure location is required to create the resource group for azurerm backend provisioning") - ErrLoadAzureConfig = errors.New("failed to build Azure client for backend provisioning") - ErrCheckResourceGroupExist = errors.New("failed to check Azure resource group existence") - ErrCreateResourceGroup = errors.New("failed to create Azure resource group") - ErrCheckStorageAccountExist = errors.New("failed to check Azure storage account existence") - ErrCreateStorageAccount = errors.New("failed to create Azure storage account") - ErrApplyBlobDataProtection = errors.New("failed to apply Azure blob data-protection defaults") - ErrCheckContainerExist = errors.New("failed to check Azure storage container existence") - ErrCreateStorageContainer = errors.New("failed to create Azure storage container") - ErrDeleteStorageAccount = errors.New("failed to delete Azure storage account") - - // Component path resolution errors. - ErrPathNotInComponentDir = errors.New("path is not within Atmos component directories") - ErrComponentTypeMismatch = errors.New("path component type does not match command") - ErrComponentNotInStack = errors.New("component not found in stack configuration") - ErrPathResolutionFailed = errors.New("failed to resolve component from path") - ErrPathIsComponentBase = errors.New("must specify a component directory, not the base directory") - ErrAmbiguousComponentPath = errors.New("ambiguous component path") - ErrComponentPathNotFound = errors.New("component path does not exist") - - // Interactive prompt errors. - ErrInteractiveModeNotAvailable = errors.New("interactive mode not available") - ErrNoOptionsAvailable = errors.New("no options available") - - // Locals-related errors. - ErrLocalsInvalidType = errors.New("locals must be a map") - ErrLocalsCircularDep = errors.New("circular dependency in locals") - ErrLocalsDependencyExtract = errors.New("failed to extract dependencies for local") - ErrLocalsResolution = errors.New("failed to resolve local") - ErrLocalsYamlFunctionFailed = errors.New("failed to process YAML function in local") - - // Init and scaffold errors. - ErrScaffoldNotFound = errors.New("scaffold template not found") - ErrScaffoldValidation = errors.New("scaffold validation failed") - ErrScaffoldGeneration = errors.New("scaffold generation failed") - ErrInitialization = errors.New("initialization failed") - ErrTemplateProcessing = errors.New("template processing failed") - ErrInvalidScaffoldConfig = errors.New("invalid scaffold configuration") - ErrTargetDirectoryExists = errors.New("target directory already exists") - ErrTargetDirectoryNotEmpty = errors.New("target directory is not empty") - ErrScaffoldParseYAML = errors.New("failed to parse scaffold YAML") - ErrPromptFailed = errors.New("interactive prompt failed") - - // Manifest registry errors (pkg/manifest). - ErrManifestKindUnknown = errors.New("unknown manifest kind") - ErrManifestKindEmpty = errors.New("manifest kind is empty") - ErrManifestKindMismatch = errors.New("manifest kind mismatch") - ErrManifestAPIVersion = errors.New("unsupported manifest apiVersion") - ErrManifestParse = errors.New("failed to parse manifest") - ErrManifestPrototypeNil = errors.New("manifest prototype is nil") - ErrManifestSchemaGenerate = errors.New("failed to generate manifest JSON schema") - ErrManifestValidation = errors.New("manifest validation failed") - - // Generator errors. - ErrReadTemplatesDirectory = errors.New("failed to read templates directory") - ErrReadTemplateFiles = errors.New("failed to read template files") - ErrReadTargetDirectory = errors.New("failed to read target directory") - ErrInvalidBaseRef = errors.New("invalid base reference") - ErrTemplateExecution = errors.New("template execution failed") - ErrDirectoryCreation = errors.New("directory creation failed") - ErrFileExists = errors.New("file already exists") - ErrFileWrite = errors.New("file write failed") - ErrUnprocessedTemplate = errors.New("unprocessed template variable found") - ErrThreeWayMerge = errors.New("three-way merge failed") - ErrMergeConflict = errors.New("merge conflict detected") - ErrCreateIOContext = errors.New("failed to create IO context") - ErrLoadScaffoldTemplates = errors.New("failed to load scaffold templates") - ErrResolveTargetDirectory = errors.New("failed to resolve target directory") - ErrScaffoldInvalidPrompt = errors.New("invalid scaffold prompt configuration") - ErrCreateGeneratorContext = errors.New("failed to create generator context") - ErrReadScaffoldConfig = errors.New("failed to read scaffold configuration") - ErrTargetDirRequired = errors.New("target directory is required") - ErrTemplateNameRequired = errors.New("template name is required") - ErrScaffoldFileNotFound = errors.New("scaffold file not found") - ErrInvalidScaffoldFile = errors.New("invalid scaffold file") - ErrScaffoldDirectoryRead = errors.New("failed to read scaffold directory") - ErrScaffoldReadFile = errors.New("failed to read scaffold file") - ErrScaffoldMissingName = errors.New("scaffold is missing required name field") - ErrScaffoldMergeTemplates = errors.New("failed to merge scaffold templates") - ErrScaffoldLoadFromFS = errors.New("failed to load scaffold from filesystem") - ErrScaffoldCreateFromPath = errors.New("failed to create scaffold from path") - ErrScaffoldSelectTemplate = errors.New("failed to select scaffold template") - ErrScaffoldDryRunValues = errors.New("failed to load dry run values") - ErrScaffoldRenderFilePath = errors.New("failed to render file path") - ErrScaffoldValidateSingleFile = errors.New("scaffold file validation failed") - ErrScaffoldFilesNotUnique = errors.New("scaffold files must be unique") - ErrScaffoldTemplatesNotAvailable = errors.New("scaffold templates not available") - ErrScaffoldLoadConfig = errors.New("failed to load scaffold configuration") - ErrInvalidTemplateData = errors.New("invalid template data") - ErrMergeThresholdExceeded = errors.New("merge threshold exceeded") - ErrNoCommonAncestor = errors.New("no common ancestor found") - ErrUnknownMergeStrategy = errors.New("unknown merge strategy") - ErrUnknownMergeDriver = errors.New("unknown merge driver") - ErrUnknownUpdateStrategy = errors.New("unknown update strategy") - ErrRenderedStrategyRequiresConfig = errors.New("--update-strategy=rendered requires a recorded scaffold configuration") - ErrUpdateStrategySwitchedToRendered = errors.New("project was last updated with --update-strategy=tracked") - ErrUpdateStrategySwitchedToTracked = errors.New("project was last updated with --update-strategy=rendered") - ErrRenderedBaseNotConfigured = errors.New("--update-strategy=rendered's base source was never resolved") - ErrRenderedStrategyUnsupportedSource = errors.New("--update-strategy=rendered is not supported for this template source") - ErrGeneratorFieldRequired = errors.New("field is required") - ErrDuplicateScaffoldFieldName = errors.New("duplicate scaffold field name") - ErrScaffoldConfigMissing = errors.New("scaffold configuration not found") - ErrInitializationPartialFailure = errors.New("initialization partially failed") - ErrInitTemplateNotFound = errors.New("init template not found") - ErrInvalidScaffoldSection = errors.New("invalid scaffold section") - ErrScaffoldFetchSource = errors.New("failed to fetch scaffold source") - ErrScaffoldCatalogLoad = errors.New("failed to load scaffold catalog") - ErrTemplateConfigNameRequired = errors.New("template config with metadata.name is required to write a project record") - ErrPathTraversal = errors.New("path traversal not allowed") - ErrSymlinkWrite = errors.New("refusing to write through a symlink") - ErrMetadataLoad = errors.New("failed to load init metadata") - ErrMetadataSave = errors.New("failed to save init metadata") - ErrScaffoldHookKindUnsupported = errors.New("scaffold hook kind not supported") - ErrScaffoldMatrixTargetRequired = errors.New("matrix requires target") - ErrScaffoldMatrixAxisInvalid = errors.New("matrix axis must be a non-empty list, a dot-path string into answers, or a template expression") - ErrScaffoldMatrixSourceNotFound = errors.New("matrix axis source not found in answers") - ErrScaffoldMatrixSourceNotList = errors.New("matrix axis source did not resolve to a list") - ErrScaffoldMatrixExpressionFailed = errors.New("matrix axis expression failed to render") - ErrScaffoldMatrixAxisValueNotScalar = errors.New("matrix axis value is not scalar") - ErrScaffoldDuplicateOutputPath = errors.New("two files rendered to the same output path") - ErrScaffoldFieldOptionsInvalid = errors.New("field options must be a static list, an answers.* dot-path, or a template expression") - ErrScaffoldExpressionFailed = errors.New("template expression failed to render") - ErrScaffoldFilePathPatternInvalid = errors.New("file path glob pattern is malformed") - ErrScaffoldMatrixTargetMissingFileContext = errors.New("matrix target must reference .file.Path or .file.RelPath when its path matches more than one file") - ErrScaffoldComputedFieldInvalid = errors.New("computed field is misconfigured") - ErrScaffoldComputedFieldNotSettable = errors.New("computed field cannot be set") - ErrScaffoldFileDelimitersInvalid = errors.New("spec.files[].delimiters must be exactly two non-empty strings") - - // Source provisioner errors. - ErrSourceProvision = errors.New("source provisioning failed") - ErrSourceNotFound = errors.New("source not found") - ErrSourceAccessDenied = errors.New("source access denied") - ErrSourceInvalidSpec = errors.New("invalid source specification") - ErrSourceAlreadyVendored = errors.New("source already vendored") - ErrSourceCacheOperation = errors.New("source cache operation failed") - ErrSourceCopyFailed = errors.New("failed to copy source files") - ErrSourceMissing = errors.New("source not configured for component") - - // Workdir provisioner errors. - ErrSourceDownload = errors.New("failed to download component source") - ErrSourceCacheRead = errors.New("failed to read source cache") - ErrSourceCacheWrite = errors.New("failed to write source cache") - ErrInvalidSource = errors.New("invalid source configuration") - ErrWorkdirCreation = errors.New("failed to create working directory") - ErrWorkdirSync = errors.New("failed to sync files to working directory") - ErrWorkdirMetadata = errors.New("failed to read/write workdir metadata") - ErrWorkdirProvision = errors.New("workdir provisioning failed") - ErrWorkdirClean = errors.New("failed to clean working directory") - ErrWorkdirIdentityMismatch = errors.New("legacy workdir belongs to a different component/stack") - - // Integration errors. - ErrIntegrationNotFound = errors.New("integration not found") - ErrUnknownIntegrationKind = errors.New("unknown integration kind") - ErrIntegrationFailed = errors.New("integration execution failed") - ErrNoLinkedIntegrations = errors.New("identity has no linked integrations") - - // ECR authentication errors. - ErrECRAuthFailed = errors.New("ECR authentication failed") - ErrECRTokenExpired = errors.New("ECR authorization token expired") - ErrECRRegistryNotFound = errors.New("ECR registry not found") - ErrECRInvalidRegistry = errors.New("invalid ECR registry URL") - ErrECRLoginNoArgs = errors.New("specify an server name, --identity, or --registry") - ErrECRLoginFailed = errors.New("ECR login failed") - ErrDockerConfigWrite = errors.New("failed to write Docker config") - ErrDockerConfigRead = errors.New("failed to read Docker config") - - // ECR Public authentication errors. - ErrECRPublicAuthFailed = errors.New("ECR Public authentication failed") - ErrECRPublicInvalidRegion = errors.New("invalid ECR Public region: only us-east-1 and us-west-2 are supported") - - // EKS server errors. - ErrEKSDescribeCluster = errors.New("failed to describe EKS cluster") - ErrEKSClusterNotFound = errors.New("EKS cluster not found") - ErrEKSIntegrationFailed = errors.New("EKS integration failed") - ErrEKSTokenGeneration = errors.New("failed to generate EKS token") - ErrKubeconfigPath = errors.New("failed to determine kubeconfig path") - ErrKubeconfigWrite = errors.New("failed to write kubeconfig") - ErrKubeconfigMerge = errors.New("failed to merge kubeconfig") - - // AKS server errors. - ErrAKSDescribeCluster = errors.New("failed to describe AKS cluster") - ErrAKSClusterNotFound = errors.New("AKS cluster not found") - ErrAKSClusterAmbiguous = errors.New("AKS cluster resource ID is ambiguous") - ErrAKSClusterNotAADEnabled = errors.New("AKS cluster is not AAD-enabled") - ErrAKSIntegrationFailed = errors.New("AKS integration failed") - ErrAKSTokenGeneration = errors.New("failed to generate AKS token") - - // GKE server errors. - ErrGKEDescribeCluster = errors.New("failed to describe GKE cluster") - ErrGKEClusterNotFound = errors.New("GKE cluster not found") - ErrGKEIntegrationFailed = errors.New("GKE integration failed") - ErrGKETokenGeneration = errors.New("failed to generate GKE token") - - // ACR authentication errors. - ErrACRAuthFailed = errors.New("ACR authentication failed") - ErrACRTokenExpired = errors.New("ACR authorization token expired") - ErrACRRegistryNotFound = errors.New("ACR registry not found") - ErrACRInvalidRegistry = errors.New("invalid ACR registry URL") - ErrACRLoginNoArgs = errors.New("specify an integration, --identity, or --registry") - ErrACRLoginFailed = errors.New("ACR login failed") - - // Atmos Pro authentication (atmos/pro provider) errors. - ErrProAuthFailed = errors.New("authentication to Atmos Pro failed") - ErrProWorkspaceIDMissing = errors.New("workspace ID for Atmos Pro is required (set via auth provider spec.workspace_id, settings.pro.workspace_id, or ATMOS_PRO_WORKSPACE_ID)") - ErrProCredentialsType = errors.New("expected Atmos Pro credentials") - - // GitHub STS integration (github/sts) errors. - ErrSTSMintFailed = errors.New("failed to mint GitHub STS tokens") - ErrSTSNoEntitlement = errors.New("workspace is not entitled to GitHub STS or the feature is disabled") - ErrNotGitHubActionsSession = errors.New("GitHub STS requires a GitHub Actions session") - ErrGitHubTokenRevokeFailed = errors.New("failed to revoke GitHub installation token") - ErrGitSTSStateWrite = errors.New("failed to write GitHub STS state") - ErrGitSTSStateRead = errors.New("failed to read GitHub STS state") - - // Integration via configuration errors. - ErrIntegrationViaMissing = errors.New("integration must define via.identity or via.provider") - ErrIntegrationViaAmbiguous = errors.New("integration must define exactly one of via.identity or via.provider") - - // Identity authentication errors. - ErrIdentityAuthFailed = errors.New("failed to authenticate identity") - ErrIdentityCredentialsNone = errors.New("credentials not available for identity") - - // CI-related errors. - ErrCIDisabled = errors.New("CI server is disabled") - ErrCIProviderNotDetected = errors.New("CI provider not detected") - ErrCIProviderNotFound = errors.New("CI provider not found") - ErrCIOperationNotSupported = errors.New("operation not supported by CI provider") - ErrCICheckRunCreateFailed = errors.New("failed to create check run") - ErrCICheckRunUpdateFailed = errors.New("failed to update check run") - ErrCICheckRunMissingComponent = errors.New("check run requires a resolved component and stack") - ErrCIStatusContextIncomplete = errors.New("status context requires all parts to be non-empty") - ErrCIStatusFetchFailed = errors.New("failed to fetch CI status") - ErrCILabelsFetchFailed = errors.New("failed to fetch CI review labels") - ErrCIMergedPRLookupFailed = errors.New("failed to look up the pull request merged as this commit") - ErrCIOutputWriteFailed = errors.New("failed to write CI output") - ErrCISummaryWriteFailed = errors.New("failed to write CI summary") - ErrCIAnnotationFailed = errors.New("failed to emit CI annotations") - ErrCISARIFUploadFailed = errors.New("failed to upload SARIF to CI provider") - ErrCICommentPostFailed = errors.New("failed to post PR comment") - ErrCICommentListFailed = errors.New("failed to list PR comments") - ErrCICommentUpdateFailed = errors.New("failed to update PR comment") - ErrCICommentNotFound = errors.New("PR comment not found") - ErrCIEnvWriteFailed = errors.New("failed to write CI environment file") - ErrCIMaskFailed = errors.New("failed to register CI mask value") - ErrCIPullRequestUnknown = errors.New("CI pull request number is unknown") - ErrCITemplateNotFound = errors.New("CI report template not found") - ErrGitHubTokenNotFound = errors.New("GitHub token not found") - - // Planfile storage errors. - ErrPlanfileNotFound = errors.New("planfile not found") - ErrPlanfileUploadFailed = errors.New("failed to upload planfile") - ErrPlanfileDownloadFailed = errors.New("failed to download planfile") - ErrPlanfileDeleteFailed = errors.New("failed to delete planfile") - ErrPlanfileListFailed = errors.New("failed to list planfiles") - ErrPlanfileStoreNotFound = errors.New("planfile store not found") - ErrPlanfileKeyInvalid = errors.New("planfile key generation failed: stack, component, and SHA are required") - ErrPlanfileStatFailed = errors.New("failed to check planfile status") - ErrPlanfileMetadataFailed = errors.New("failed to load planfile metadata") - ErrPlanfileMetadataInvalid = errors.New("planfile metadata validation failed: stack, component, and SHA are required") - ErrArtifactMetadataInvalid = errors.New("artifact metadata validation failed: stack, component, and SHA are required") - ErrPlanfileStoreInvalidArgs = errors.New("invalid planfile store arguments") - ErrPlanfileDeleteRequireForce = errors.New("deletion requires --force flag") - ErrAWSConfigLoadFailed = errors.New("failed to load AWS configuration") - - // Artifact storage errors. - ErrArtifactNotFound = errors.New("artifact not found") - ErrArtifactUploadFailed = errors.New("failed to upload artifact") - ErrArtifactDownloadFailed = errors.New("failed to download artifact") - ErrArtifactDeleteFailed = errors.New("failed to delete artifact") - ErrArtifactListFailed = errors.New("failed to list artifacts") - ErrArtifactStoreNotFound = errors.New("artifact store not found") - ErrArtifactStoreInvalidArgs = errors.New("invalid artifact store arguments") - ErrArtifactMetadataFailed = errors.New("failed to load artifact metadata") - ErrArtifactIntegrityFailed = errors.New("artifact integrity check failed") - - // CI cache errors. - ErrCacheUnavailable = errors.New("CI cache is not available in this environment") - ErrCacheNotFound = errors.New("cache entry not found") - ErrCacheAlreadyExists = errors.New("cache entry already exists") - ErrCacheSaveFailed = errors.New("failed to save cache entry") - ErrCacheRestoreFailed = errors.New("failed to restore cache entry") - ErrCacheDeleteFailed = errors.New("failed to delete cache entry") - ErrCacheListFailed = errors.New("failed to list cache entries") - ErrCacheBackendNotFound = errors.New("cache backend not found") - ErrCacheInvalidArgs = errors.New("invalid cache arguments") - ErrCacheKeyRequired = errors.New("cache key is required") - ErrCachePathsRequired = errors.New("cache paths are required") - ErrCacheArchiveFailed = errors.New("failed to build cache archive") - ErrCacheExtractFailed = errors.New("failed to extract cache archive") - ErrCacheBackendRequest = errors.New("cache backend request failed") - - // AI-related errors. - ErrAINotEnabled = errors.New("AI features are not enabled") - ErrAIDisabledInConfiguration = errors.New("AI features are disabled in configuration") - ErrAIAPIKeyNotFound = errors.New("API key not found in environment variable") - ErrAIInsecureBaseURL = errors.New("insecure base_url: an API key would be sent in cleartext over http") - ErrAINoStackFilesFound = errors.New("no stack files found") - ErrAIUnsupportedProvider = errors.New("unsupported AI provider") - ErrAIClientNil = errors.New("AI client cannot be nil") - ErrAINoResponseCandidates = errors.New("no response candidates returned") - ErrAINoResponseContent = errors.New("no content in response") - ErrAIResponseNotText = errors.New("response part does not contain text") - ErrAINoResponseChoices = errors.New("no response choices returned") - ErrAISessionNotFound = errors.New("AI session not found") - ErrAISessionAlreadyExists = errors.New("AI session already exists") - ErrAIToolNotFound = errors.New("AI tool not found") - ErrAIToolExecutionDenied = errors.New("AI tool execution denied by user") - ErrAIToolExecutionFailed = errors.New("AI tool execution failed") - ErrAIToolParameterRequired = errors.New("tool parameter is required") - ErrAIToolNameEmpty = errors.New("tool name cannot be empty") - ErrAIToolAlreadyRegistered = errors.New("tool already registered") - ErrAIToolBlocked = errors.New("tool is blocked") - ErrAIToolsDisabled = errors.New("tools are disabled") - ErrAINoPrompter = errors.New("no prompter available") - ErrAIPermissionPromptFailed = errors.New("permission prompt failed") - ErrAISessionsNotEnabled = errors.New("sessions are not enabled in configuration") - ErrAIInvalidDurationFormat = errors.New("invalid duration format") - ErrAIUnsupportedDurationUnit = errors.New("unsupported duration unit") - ErrAIUnsupportedComponentType = errors.New("unsupported component type") - ErrAIFileAccessDeniedComponents = errors.New("access denied: file path must be within components directory") - ErrAIFileAccessDeniedStacks = errors.New("access denied: file path must be within stacks directory") - ErrAIInvalidConfiguration = errors.New("invalid AI configuration") - ErrAINotInitialized = errors.New("AI client not initialized") - ErrAIFileNotFound = errors.New("file not found") - ErrAIPathIsDirectory = errors.New("path is a directory, not a file") - ErrAISessionManagerNotAvailable = errors.New("session manager not available") - ErrAISessionNameEmpty = errors.New("session name cannot be empty") - ErrAISQLitePragmaFailed = errors.New("failed to set SQLite pragma") - ErrAIAgentNil = errors.New("AI agent cannot be nil") - ErrAIAgentNameEmpty = errors.New("AI agent name cannot be empty") - ErrAIAgentNotFound = errors.New("AI agent not found") - ErrAIAgentAlreadyRegistered = errors.New("AI agent already registered") - ErrAISkillNil = errors.New("AI skill cannot be nil") - ErrAISkillNameEmpty = errors.New("AI skill name cannot be empty") - ErrAISkillNotFound = errors.New("AI skill not found") - ErrAISkillAlreadyRegistered = errors.New("AI skill already registered") - ErrAISkillRequiresAIFlag = errors.New("--skill flag requires --ai") - ErrAISkillLoadFailed = errors.New("failed to load AI skills") - ErrAIPromptRequired = errors.New("prompt is required") - ErrAIExecutionFailed = errors.New("AI execution failed") - ErrAISendMessage = errors.New("failed to send message to AI provider") - ErrAIClientCreation = errors.New("failed to create AI client") - ErrAIMarshalRequest = errors.New("failed to marshal AI request") - ErrAIUnmarshalResponse = errors.New("failed to unmarshal AI response") - ErrAIParseToolInput = errors.New("failed to parse tool input") - ErrAILoadAWSConfig = errors.New("failed to load AWS configuration for AI") - ErrAIBaseURLRequired = errors.New("base URL is required for AI provider") - ErrAIAccessDeniedBasePath = errors.New("access denied: file must be within Atmos base path") - ErrAIAccessDeniedSearchPath = errors.New("access denied: search path must be within Atmos base path") - ErrAIUnknownOperation = errors.New("unknown operation") - ErrAISearchTextNotFound = errors.New("search text not found in file") - ErrAILineNumberOutOfRange = errors.New("line number out of range") - ErrAIInvalidLineRange = errors.New("invalid line range") - ErrAICommandEmpty = errors.New("command cannot be empty") - ErrAICommandBlacklisted = errors.New("command is blacklisted for security reasons") - ErrAICommandRmNotAllowed = errors.New("rm with recursive or force flags is not allowed") - ErrAILSPNotEnabled = errors.New("LSP is not enabled") - ErrAIFileDoesNotExist = errors.New("file does not exist") - ErrAIConfigNil = errors.New("cannot switch provider: atmosConfig is nil") - ErrAIInvalidProviderSelection = errors.New("invalid provider selection") - - // AI session checkpoint/compaction errors. - ErrAICompactPlanNil = errors.New("compact plan is nil") - ErrAIUnsupportedExportFormat = errors.New("unsupported export format") - ErrAICheckpointNil = errors.New("checkpoint is nil") - ErrAICheckpointVersionMissing = errors.New("checkpoint version is missing") - ErrAIUnsupportedCheckpointVersion = errors.New("unsupported checkpoint version") - ErrAISessionNameRequired = errors.New("session name is required") - ErrAISessionProviderRequired = errors.New("session provider is required") - ErrAISessionModelRequired = errors.New("session model is required") - ErrAICheckpointNoMessages = errors.New("checkpoint must contain at least one message") - ErrAIMessageRoleRequired = errors.New("message role is required") - ErrAIMessageInvalidRole = errors.New("invalid message role") - ErrAIStatisticsMismatch = errors.New("statistics message count does not match actual messages") - ErrAIUnsupportedCheckpointFormat = errors.New("unsupported checkpoint format") - ErrAIComponentPathNotFound = errors.New("component path not found") - ErrAIComponentPathNotDirectory = errors.New("component path is not a directory") - - // AI MCP config/stack/vendor get-set-delete-format-list tool errors. - ErrAIConfigFileNotFound = errors.New("atmos config file not found") - ErrAIStackConfigPathNotEditable = errors.New("stack config path is not editable without an explicit file") - ErrAIVendorFileNotFound = errors.New("no vendor manifest found") - ErrAICommandNotFound = errors.New("command not found") - ErrAICommandTreeNotConfigured = errors.New("command tree provider is not configured") - ErrAIToolInvalidOutputType = errors.New("invalid output_type: must be one of 'list', 'map', or 'all'") - ErrAINoSchemaForFile = errors.New("no schema registered for this file; pass schema_path explicitly") - - // AWS security and compliance errors. - ErrAWSSecurityNotEnabled = errors.New("security features are not enabled: add 'aws.security.enabled: true' to atmos.yaml") - ErrAWSSecurityNoFindings = errors.New("no security findings found matching the specified filters") - ErrAWSSecurityFetchFailed = errors.New("failed to fetch security findings from AWS") - ErrAWSSecurityMappingFailed = errors.New("failed to map security finding to Atmos component") - ErrAWSSecurityInvalidSeverity = errors.New("invalid severity filter: valid values are CRITICAL, HIGH, MEDIUM, LOW, INFORMATIONAL") - ErrAWSSecurityInvalidSource = errors.New("invalid finding source: valid values are security-hub, config, inspector, guardduty, macie, access-analyzer, all") - ErrAWSSecurityInvalidFramework = errors.New("invalid compliance framework: valid values are cis-aws, pci-dss, soc2, hipaa, nist") - ErrAWSSecurityInvalidFormat = errors.New("invalid output format: valid values are markdown, json, yaml, csv, sarif") - ErrAWSSecurityAnalysisFailed = errors.New("AI analysis of security findings failed") - ErrAWSCredentialsNotValid = errors.New("AWS credentials are not configured or have expired") - - // CLI provider errors. - ErrCLIProviderBinaryNotFound = errors.New("CLI provider binary not found on PATH") - ErrCLIProviderExecFailed = errors.New("CLI provider execution failed") - ErrCLIProviderParseResponse = errors.New("failed to parse CLI provider response") - ErrCLIProviderToolsNotSupported = errors.New("tool execution not supported for CLI providers; use MCP pass-through instead") - ErrCLIProviderEmptyResponse = errors.New("CLI provider returned an empty response") - ErrCLIProviderMaxTurns = errors.New("CLI provider reached its maximum number of turns before answering") - ErrCLIProviderToolDenied = errors.New("CLI provider tool use was not approved") - ErrAIEmptyResponse = errors.New("AI returned an empty response") - ErrAIToolsInvalidMode = errors.New("invalid ai.tools.mode") - - // Web search errors. - ErrWebSearchFailed = errors.New("web search request failed") - ErrWebSearchParseFailed = errors.New("failed to parse web search results") - ErrWebSearchNotEnabled = errors.New("web search is not enabled in configuration") - - // MCP errors. - ErrMCPNotEnabled = errors.New("MCP server is not enabled") - ErrMCPToolNotFound = errors.New("MCP tool not found") - ErrMCPInvalidJSONRPCVersion = errors.New("invalid JSON-RPC version") - ErrMCPInvalidTransport = errors.New("invalid transport type") - ErrMCPUnsupportedTransport = errors.New("unsupported transport") - ErrMCPServerNotFound = errors.New("MCP server not found in configuration") - ErrMCPServerNotRunning = errors.New("MCP server is not running") - ErrMCPServerStartFailed = errors.New("MCP server failed to start") - ErrMCPServerCommandEmpty = errors.New("MCP server command must not be empty") - ErrMCPServerInvalidTimeout = errors.New("MCP server timeout is invalid") - ErrMCPServerToolListFailed = errors.New("failed to list tools from MCP server") - ErrMCPServerToolError = errors.New("MCP server returned error for tool") - ErrMCPConfigWriteFailed = errors.New("failed to write MCP config file") - ErrMCPConfigPermsFailed = errors.New("failed to set MCP config file permissions") - ErrMCPConfigMarshalFailed = errors.New("failed to marshal MCP config") - ErrMCPServerAuthUnavailable = errors.New("MCP server requires identity but auth manager is not available") - ErrLSPInvalidTransport = errors.New("invalid LSP transport type") - ErrLSPConfigNil = errors.New("LSP config is nil") - ErrLSPNoServerForFile = errors.New("no LSP server found for file") - ErrLSPRPCError = errors.New("RPC error") - ErrLSPNoContentLengthHeader = errors.New("no Content-Length header found") - - // Kubernetes-native component errors. - ErrKubernetesFlagsMutuallyExclusive = errors.New("--all and --affected are mutually exclusive") - ErrKubernetesComponentArgWithSelection = errors.New("component argument cannot be used with --all, --affected, --tags, or --labels") - ErrKubernetesOutputSingleComponentOnly = errors.New("--output and --output-dir are only supported when rendering one component") - ErrKubernetesComponentArgRequired = errors.New("requires exactly one component argument unless --all or --affected is set") - ErrKubernetesUnsupportedOperation = errors.New("unsupported kubernetes operation") - ErrKubernetesUnsupportedSubcommand = errors.New("unsupported kubernetes subcommand") - ErrKubernetesMissingMetadataName = errors.New("object is missing metadata.name") - ErrKubernetesMissingGVK = errors.New("object is missing group/version/kind") - ErrManifestEntryInvalidType = errors.New("manifest entries must be YAML strings or maps") - ErrManifestMissingAPIVersionKind = errors.New("manifest is missing apiVersion or kind") - ErrManifestListItemNotObject = errors.New("list item is not an unstructured object") - ErrKubernetesOutputDirMutuallyExclusive = errors.New("--output and --output-dir are mutually exclusive") - ErrKubernetesSplitRequiresOutputDir = errors.New("--split requires --output-dir and cannot be used with --output") - ErrKubernetesSplitNeedsOutputDir = errors.New("--split requires --output-dir") - ErrKubernetesClientInit = errors.New("failed to initialize kubernetes client") - ErrKubernetesEndpointMismatch = errors.New("effective Kubernetes API endpoint does not match the identity integration") - ErrKubernetesIdentityRequired = errors.New("an Atmos Auth identity is required for this Kubernetes operation") - ErrKubernetesApply = errors.New("failed to apply kubernetes object") - ErrKubernetesDelete = errors.New("failed to delete kubernetes object") - ErrKubernetesDiff = errors.New("failed to diff kubernetes object") - ErrKubernetesMarshal = errors.New("failed to marshal kubernetes object") - ErrKubernetesResolveResource = errors.New("failed to resolve kubernetes resource") - ErrKubernetesComponentDir = errors.New("failed to create kubernetes component directory") - ErrKubernetesRenderOutput = errors.New("failed to write rendered kubernetes manifests") - ErrKubernetesRender = errors.New("failed to render kubernetes object") - ErrKubernetesProviderType = errors.New("provider must be a string") - ErrManifestPathTraversal = errors.New("manifest path escapes the component directory") - ErrKubernetesValidationFailed = errors.New("kubernetes manifest validation failed") - ErrKubernetesManifestInvalidName = errors.New("object metadata.name is not a valid DNS-1123 subdomain") - ErrKubernetesValidate = errors.New("failed to validate kubernetes object") - ErrKubernetesValidateSectionInvalid = errors.New("component 'validate' must be a boolean") - - // Helm-native component errors. - ErrHelmFlagsMutuallyExclusive = errors.New("--all and --affected are mutually exclusive") - ErrHelmComponentArgWithSelection = errors.New("component argument cannot be used with --all, --affected, --tags, or --labels") - ErrHelmOutputSingleComponentOnly = errors.New("--output and --output-dir are only supported when rendering one component") - ErrHelmComponentArgRequired = errors.New("requires exactly one component argument unless --all or --affected is set") - ErrHelmUnsupportedOperation = errors.New("unsupported helm operation") - ErrHelmUnsupportedSubcommand = errors.New("unsupported helm subcommand") - ErrHelmChartNotConfigured = errors.New("helm component is missing a 'chart' reference") - ErrHelmRenderFailed = errors.New("failed to render helm chart") - ErrHelmReleaseNameRequired = errors.New("helm component is missing a release name") - ErrHelmDiffFailed = errors.New("failed to compute helm diff") - ErrHelmBaselineRead = errors.New("failed to read helm diff baseline") - ErrHelmLifecycleDecode = errors.New("failed to decode helm release lifecycle") - ErrHelmFailureActionInvalid = errors.New("invalid helm on_failure action") - ErrHelmWaitStrategyInvalid = errors.New("invalid helm wait strategy") - ErrHelmServerSideApplyInvalid = errors.New("invalid helm server_side_apply value") - ErrHelmForceConflictsRequiresSSA = errors.New("helm force_conflicts requires server-side apply to be enabled") - ErrHelmTimeoutInvalid = errors.New("invalid helm release timeout") - ErrHelmMaxHistoryInvalid = errors.New("invalid helm release history limit") - ErrHelmWaitForJobsRequiresWait = errors.New("helm wait_for_jobs requires watcher or legacy wait strategy") - ErrHelmLifecycleFlagInapplicable = errors.New("helm release lifecycle flag does not apply to selected operation") - ErrHelmLifecycleExternalTarget = errors.New("helm release lifecycle flags require a Kubernetes target") - ErrHelmReleaseHistory = errors.New("failed to inspect helm release history") - ErrHelmReleaseUpgrade = errors.New("failed to upgrade helm release") - ErrHelmReleaseUninstall = errors.New("failed to uninstall helm release") - ErrHelmReleaseRollback = errors.New("failed to roll back helm release") - ErrHelmReleaseOperation = errors.New("failed to perform helm release operation") - - // Native aws/cloudformation component errors. - ErrMissingAwsCloudFormationTemplate = errors.New("aws/cloudformation component is missing a template: set 'template' (inline body) or 'path' (file reference)") - ErrMissingAwsCloudFormationStackName = errors.New("aws/cloudformation component is missing a 'stack_name'") - ErrInvalidAwsCloudFormationCapabilities = errors.New("invalid aws/cloudformation capabilities") - ErrInvalidAwsCloudFormationSettings = errors.New("invalid aws/cloudformation settings") - ErrAwsCloudFormationGenerateUnsupported = errors.New("aws/cloudformation components do not support a 'generate' section") - ErrAwsCloudFormationStackPolicyFileAndBodyMutuallyExclusive = errors.New("'stack_policy.file' and 'stack_policy.body' are mutually exclusive: 'file' is a file reference, 'body' is an inline policy") - ErrInvalidComponentsAwsCloudFormation = errors.New("invalid 'components.aws/cloudformation' section") - ErrInvalidSpecificAwsCloudFormationComponent = errors.New("invalid aws/cloudformation component configuration") - ErrAwsCloudFormationChangeSetFailed = errors.New("aws/cloudformation changeset failed") - ErrAwsCloudFormationChangeSetNotFound = errors.New("aws/cloudformation changeset not found") - ErrAwsCloudFormationDriftDetected = errors.New("aws/cloudformation stack has drifted") - ErrAwsCloudFormationFlagsMutuallyExclusive = errors.New("--all and --affected are mutually exclusive") - ErrAwsCloudFormationComponentArgWithSelection = errors.New("component argument cannot be used with --all, --affected, --tags, or --labels") - ErrAwsCloudFormationComponentArgRequired = errors.New("requires exactly one component argument unless --all, --affected, --tags, or --labels is set") - ErrAwsCloudFormationIdentityResolutionFailed = errors.New("aws/cloudformation component requested an identity, but the auth manager could not resolve it") - ErrAwsCloudFormationAPICallFailed = errors.New("aws/cloudformation API call failed") - ErrAwsCloudFormationFmtNotClean = errors.New("aws/cloudformation template is not formatted") - ErrAwsCloudFormationFmtWriteFailed = errors.New("aws/cloudformation failed to write formatted template") - ErrAwsCloudFormationStackNotFound = errors.New("aws/cloudformation stack not found") - ErrAwsCloudFormationStackSetFailed = errors.New("aws/cloudformation stackset operation failed") - ErrAwsCloudFormationLogsFollowChartExclusive = errors.New("--follow and --chart are mutually exclusive") - ErrAwsCloudFormationOperationFailed = errors.New("aws/cloudformation operation did not complete successfully") - ErrAwsCloudFormationBackendMissing = errors.New("aws/cloudformation packaging bucket does not exist") - ErrAwsCloudFormationIncludeDependentsRequiresAffected = errors.New("--include-dependents requires --affected") - ErrAwsCloudFormationTemplateAndPathMutuallyExclusive = errors.New("'template' and 'path' are mutually exclusive: 'template' is an inline template body, 'path' is a file reference") - ErrAwsCloudFormationFmtRequiresPath = errors.New("aws/cloudformation fmt only applies to file-based templates ('path:'); inline 'template:' bodies have no file to format in place") - ErrAwsCloudFormationTemplateMissingResources = errors.New("aws/cloudformation inline template is missing a top-level 'Resources' section") - ErrInvalidAwsCloudFormationParameters = errors.New("invalid aws/cloudformation parameters") - ErrAwsCloudFormationStackNotDeployed = errors.New("aws/cloudformation stack is not deployed") - ErrAwsCloudFormationOutputNotFound = errors.New("aws/cloudformation output not found") - ErrAwsCloudFormationInvalidFlagCombination = errors.New("invalid flag combination") - ErrAwsCloudFormationConfirmationRequired = errors.New("aws/cloudformation operation requires confirmation; pass --auto-approve in a non-interactive session") - ErrAwsCloudFormationStackRollbackComplete = errors.New("aws/cloudformation stack is in ROLLBACK_COMPLETE and cannot be updated") - ErrAwsCloudFormationStackSetTargetNotApplicable = errors.New("aws/cloudformation apply cannot deliver to a `kind: aws/stackset` provision target") - ErrAwsCloudFormationTerminationProtectionEnabled = errors.New("aws/cloudformation stack has termination protection enabled") - ErrAwsCloudFormationRetainResourcesNotApplicable = errors.New("--retain-resources is only valid for a stack in DELETE_FAILED status") - ErrAwsCloudFormationBackendTargetsFailed = errors.New("aws/cloudformation backend targets could not be inspected") - ErrAwsCloudFormationRainDirective = errors.New("aws/cloudformation template contains Rain directives, which Atmos does not preprocess") -) - -// Provision-target authentication errors. -var ( - // ErrProvisionTargetAuthInvalid indicates a provision target's auth block is malformed. - ErrProvisionTargetAuthInvalid = errors.New("provision target auth is invalid") - // ErrProvisionTargetAuthUnknownKey indicates a provision target's auth block has an unsupported key. - ErrProvisionTargetAuthUnknownKey = errors.New("provision target auth has an unsupported key") - // ErrProvisionTargetAuthNoIdentity indicates a provision target's auth block selects no identity. - ErrProvisionTargetAuthNoIdentity = errors.New("provision target auth did not select an identity") - // ErrProvisionTargetAuthFailed indicates the identity a provision target selected could not be used. - ErrProvisionTargetAuthFailed = errors.New("provision target authentication failed") - // ErrAwsCloudFormationTargetAuthFailed indicates a CloudFormation delivery target's own authentication failed. - ErrAwsCloudFormationTargetAuthFailed = errors.New("aws/cloudformation provision target could not authenticate") - // ErrAwsCloudFormationTargetKeyUnsupported indicates a `kind: aws/cloudformation` target has an unsupported key. - ErrAwsCloudFormationTargetKeyUnsupported = errors.New("aws/cloudformation provision target has an unsupported key") ) - -// Stack dependency (`depends_on`) resolution errors. -var ( - // ErrInvalidDependsOn indicates a legacy `settings.spacelift.depends_on` value - // does not resolve to a known stack or to a component in the current stack. - ErrInvalidDependsOn = errors.New("invalid 'depends_on' dependency") - // ErrInvalidSettingsDependsOn indicates a `settings.depends_on` value does not - // resolve to a known component in a known stack. - ErrInvalidSettingsDependsOn = errors.New("invalid 'settings.depends_on' dependency") -) - -// Vendor update/diff errors. -var ( - // ErrComponentUpdaterConfig indicates invalid component updater configuration. - ErrComponentUpdaterConfig = errors.New("invalid component updater configuration") - // ErrComponentUpdaterDirtyWorktree indicates a publisher's Git worktree has uncommitted changes. - ErrComponentUpdaterDirtyWorktree = errors.New("component updater requires a clean Git worktree") - // ErrPullRequestPublisherUnavailable indicates the selected forge integration is not registered. - ErrPullRequestPublisherUnavailable = errors.New("pull request publisher is unavailable") - // ErrGitHubAuthorization indicates an authentication or permission failure from the GitHub API. - ErrGitHubAuthorization = errors.New("GitHub authorization failed") - // ErrPullRequestReconciliation indicates Atmos could not reconcile an existing or new PR. - ErrPullRequestReconciliation = errors.New("pull request reconciliation failed") - // ErrAzureDevOpsTokenNotFound indicates AZURE_DEVOPS_EXT_PAT is not set. - ErrAzureDevOpsTokenNotFound = errors.New("Azure DevOps personal access token not found") - // ErrAzureDevOpsAuthorization indicates an authentication or permission failure from the Azure DevOps API. - ErrAzureDevOpsAuthorization = errors.New("Azure DevOps authorization failed") - // ErrAzureDevOpsAssigneesUnsupported indicates Azure DevOps pull requests do not support assignees. - ErrAzureDevOpsAssigneesUnsupported = errors.New("Azure DevOps pull requests do not support assignees") - // ErrAzureDevOpsNamespaceInvalid indicates PullRequestOptions.Namespace was not exactly the - // single project segment Azure DevOps' organization/project/repository addressing requires. - ErrAzureDevOpsNamespaceInvalid = errors.New("Azure DevOps pull request namespace must be exactly one project segment") - // ErrAzureDevOpsReviewerNotFound indicates a configured reviewer's display name, account name, - // or email matched no Azure DevOps identity. - ErrAzureDevOpsReviewerNotFound = errors.New("Azure DevOps reviewer identity not found") - // ErrAzureDevOpsReviewerAmbiguous indicates a configured reviewer's display name, account name, - // or email matched more than one Azure DevOps identity. - ErrAzureDevOpsReviewerAmbiguous = errors.New("Azure DevOps reviewer identity is ambiguous") - // ErrGitFetchFailed indicates `git fetch` of a base or feature branch failed. - ErrGitFetchFailed = errors.New("git fetch failed") - // ErrGitCheckoutFailed indicates `git checkout` of a feature branch failed. - ErrGitCheckoutFailed = errors.New("git checkout failed") - // ErrGitLocalBranchDiverged indicates a local feature branch has commits absent from both - // the remote feature branch and the base branch. - ErrGitLocalBranchDiverged = errors.New("local branch has unpushed commits") - // ErrGitDefaultBranchResolution indicates the remote's default branch could not be resolved. - ErrGitDefaultBranchResolution = errors.New("remote default branch resolution failed") - - // ErrGitLsRemoteFailed indicates listing refs from a remote Git repository failed. - ErrGitLsRemoteFailed = errors.New("failed to list refs from remote Git repository") - // ErrNoVersionsAvailable indicates no versions were found for a source. - ErrNoVersionsAvailable = errors.New("no versions available") - // ErrNoVersionsMatchConstraints indicates no available version satisfies the configured constraints. - ErrNoVersionsMatchConstraints = errors.New("no versions match the configured constraints") - // ErrInvalidSemverConstraint indicates a constraints.version value is not a valid semver constraint. - ErrInvalidSemverConstraint = errors.New("invalid semver constraint") - // ErrVersionRangeConflictsWithConstraints indicates a source declared both a semver-range - // version: and a constraints.version ceiling. These are mutually exclusive. constraints.version's - // entire purpose is to bound what `atmos vendor update` can bump an *exact* pin to; that purpose - // no longer applies once version: is itself already a range. - ErrVersionRangeConflictsWithConstraints = errors.New("version: is a semver range; constraints.version is also set. These are mutually exclusive; remove one") - // ErrVendorSourceNotFound indicates a requested component/source was not found in the vendor manifest. - ErrVendorSourceNotFound = errors.New("vendor source not found") - // ErrVendorSourceNotGit indicates a vendor source is not a Git repository (unsupported for update/diff). - ErrVendorSourceNotGit = errors.New("vendor source is not a Git repository") - // ErrVendorDiffFailed indicates the vendor diff operation failed. - ErrVendorDiffFailed = errors.New("failed to produce vendor diff") - // ErrVendorUpdateFailed indicates the vendor update operation failed. - ErrVendorUpdateFailed = errors.New("failed to update vendor manifest") - // ErrReadVendorFile indicates a vendor manifest file could not be read. - ErrReadVendorFile = errors.New("failed to read vendor manifest") - // ErrParseVendorFile indicates a vendor manifest file could not be parsed. - ErrParseVendorFile = errors.New("failed to parse vendor manifest") - // ErrInvalidGitRef indicates a Git ref (tag, branch, or commit) could not be resolved. - ErrInvalidGitRef = errors.New("invalid Git ref") - // ErrComponentManifestNotFound indicates no component.yaml/component.yml exists in a component's directory. - ErrComponentManifestNotFound = errors.New("component vendoring manifest not found") - // ErrInvalidComponentManifestKind indicates a component.yaml's "kind" is not "ComponentVendorConfig". - ErrInvalidComponentManifestKind = errors.New("invalid kind in component vendoring manifest; expected ComponentVendorConfig") - // ErrComponentDirNotFound indicates a component's resolved base directory does not exist. - ErrComponentDirNotFound = errors.New("component directory does not exist") - // ErrResolveComponentPath indicates a component's filesystem path could not be resolved - // (path-joining or symlink resolution failed), distinct from ErrComponentDirNotFound's "the - // path resolved fine but nothing exists there". - ErrResolveComponentPath = errors.New("failed to resolve component path") - // ErrDuplicateVendorComponent indicates the same component name is declared more than once - // across a vendor manifest and its imports, matching the rejection normal `vendor pull` - // processing already applies (internal/exec's ErrDuplicateComponentsFound) for the - // --stack/--tags declared-tags resolution path. - ErrDuplicateVendorComponent = errors.New("duplicate component declared in vendor manifest") -) - -// GitHub Enterprise Server (GHES) endpoint resolution errors. -var ( - // ErrInvalidGitHubEndpointURL indicates a GitHub endpoint environment variable - // (e.g. GITHUB_SERVER_URL, GITHUB_API_URL, ATMOS_TOOLCHAIN_GITHUB_URL) could not be - // parsed as an absolute HTTP(S) URL. The resolver falls back to its default rather - // than failing, so this error is logged at debug level, not surfaced to the user. - ErrInvalidGitHubEndpointURL = errors.New("invalid GitHub endpoint URL") -) - -// Release notes update errors. -var ( - // ErrReleaseTagMissing prevents updating notes without a tag to preserve. - ErrReleaseTagMissing = errors.New("release tag is missing") - // ErrReleaseTagMismatch indicates GitHub did not preserve the tag during a notes update. - ErrReleaseTagMismatch = errors.New("release tag changed during notes update") -) - -// Source provisioning, S3 source, and stack-manifest hardening errors (field-test findings, PR #3251). -var ( - // ErrSourceComponentNameInvalid indicates a component name (metadata.component) that cannot be - // used as a source provisioning destination: absolute, volume-qualified, or escaping the - // components directory. - ErrSourceComponentNameInvalid = errors.New("invalid component name for source provisioning") - // ErrSourceDeleteRefused indicates `source delete` declined to remove a directory it cannot - // prove the source provisioner created, or that another component owns. - ErrSourceDeleteRefused = errors.New("refusing to delete source directory") - // ErrS3SourceRegionMismatch indicates an S3 source bucket lives in a different region than the - // one used for the request. - ErrS3SourceRegionMismatch = errors.New("S3 source bucket is in a different region than the request") - // ErrS3SourceForbidden indicates S3 answered 403 for an object probe: either access is denied - // or the key does not exist and the principal lacks s3:ListBucket. - ErrS3SourceForbidden = errors.New("S3 source access was forbidden") - // ErrS3SourceUnsupportedParam indicates an S3 source URL carries credential query parameters - // that the Atmos S3 getter never honors. - ErrS3SourceUnsupportedParam = errors.New("unsupported S3 source authentication parameter") -) - -// GitHub mock test-helper errors (tests/testhelpers/httpmock). -var ( - // ErrMockFailWithTimesNegative indicates a test called FailWithTimes with a negative - // times value. -1 (unlimited failure) is reserved for FailWith/FailWithHeaders; a caller - // that wants an unlimited failure should call one of those instead of FailWithTimes with - // a negative count, which would otherwise silently behave as unlimited. - ErrMockFailWithTimesNegative = errors.New("httpmock: FailWithTimes called with negative times; use FailWith for an unlimited failure") -) - -// CI reporter and provider sentinels. -var ( - // ErrCICommentKeyRequired is returned when a comment asks to update an existing comment but names no key to find it by. - ErrCICommentKeyRequired = errors.New("a comment key is required to update an existing comment") - - // ErrCICommentTargetInvalid is returned when a comment target is not one of auto, pr, or commit. - ErrCICommentTargetInvalid = errors.New("invalid comment target") - - // ErrCICommitUnknown is returned when a commit comment is requested but the commit SHA is unknown. - ErrCICommitUnknown = errors.New("commit SHA is unknown") -) - -// Automation runtime, standalone script, and custom-command input sentinels. -var ( - // ErrScriptHelpShown is returned by cli.command after the host printed the script's help. - // It ends the script without running its remaining statements; the engine reports success. - ErrScriptHelpShown = errors.New("script help shown") - - // ErrLiteralFieldUnsupported is returned when the !literal tag is written on a field that - // does not support it, so the tag cannot be silently ignored. - ErrLiteralFieldUnsupported = errors.New("!literal is not supported") - - // ErrScriptInterrupted is returned when an interrupt (Ctrl-C) ended a standalone script - // after its deferred calls ran. The process exits with the conventional status 130. - ErrScriptInterrupted = errors.New("script interrupted") -) - -// Step library, process cleanup, Git hook, and !starlark sentinels. -var ( - // ErrStarlarkUnsupportedInConfig is returned when `!starlark` appears in atmos.yaml, which only - // stack manifests evaluate. - ErrStarlarkUnsupportedInConfig = errors.New("!starlark is not supported in atmos.yaml") - - // ErrHookRecursionLimit is returned when lifecycle hooks trigger themselves more than the - // allowed number of levels deep. - ErrHookRecursionLimit = errors.New("hook recursion limit exceeded") -) - -// Test step (`type: test`) failure sentinel. -var ErrTestsFailed = errors.New("tests failed") - -// Policy evaluation errors. -var ( - ErrPolicyInvalid = errors.New("invalid policy") - ErrPolicyInputInvalid = errors.New("invalid policy input") - ErrPolicyEngineUnknown = errors.New("policy engine is not registered") - ErrPolicyEngineRegistered = errors.New("policy engine is already registered") - ErrPolicyEvaluation = errors.New("policy evaluation failed") - ErrPolicyInputUnavailable = errors.New("required policy input is unavailable or incomplete") - ErrPolicyDenied = errors.New("policy denied execution") - ErrPolicyRequirements = errors.New("policy requirements are not satisfied") - ErrPolicyPlan = errors.New("saved plan policy enforcement failed") -) - -// ExitCodeError is a typed error that preserves subcommand exit codes. -// This allows the root command to exit with the same code as the subcommand. -// When Code is 0, it indicates successful completion that should exit cleanly without printing errors. -// This avoids deep exits (os.Exit) which are untestable. -type ExitCodeError struct { - Code int - // Silent suppresses themed error rendering: the process exits with Code - // without printing an error box. Used for terminal-handoff steps (tty, - // interactive, exec) where, like a shell, a non-zero exit from the child - // program should propagate the code without Atmos rendering its own error - // (which would query the terminal and can hang when stdin is contended). - Silent bool -} - -func (e ExitCodeError) Error() string { - return fmt.Sprintf("subcommand exited with code %d", e.Code) -} diff --git a/errors/errors_components.go b/errors/errors_components.go new file mode 100644 index 00000000000..508c05aa21c --- /dev/null +++ b/errors/errors_components.go @@ -0,0 +1,108 @@ +package errors + +import ( + "errors" +) + +var ( + // Kubernetes-native component errors. + ErrKubernetesFlagsMutuallyExclusive = errors.New("--all and --affected are mutually exclusive") + ErrKubernetesComponentArgWithSelection = errors.New("component argument cannot be used with --all, --affected, --tags, or --labels") + ErrKubernetesOutputSingleComponentOnly = errors.New("--output and --output-dir are only supported when rendering one component") + ErrKubernetesComponentArgRequired = errors.New("requires exactly one component argument unless --all or --affected is set") + ErrKubernetesUnsupportedOperation = errors.New("unsupported kubernetes operation") + ErrKubernetesUnsupportedSubcommand = errors.New("unsupported kubernetes subcommand") + ErrKubernetesMissingMetadataName = errors.New("object is missing metadata.name") + ErrKubernetesMissingGVK = errors.New("object is missing group/version/kind") + ErrManifestEntryInvalidType = errors.New("manifest entries must be YAML strings or maps") + ErrManifestMissingAPIVersionKind = errors.New("manifest is missing apiVersion or kind") + ErrManifestListItemNotObject = errors.New("list item is not an unstructured object") + ErrKubernetesOutputDirMutuallyExclusive = errors.New("--output and --output-dir are mutually exclusive") + ErrKubernetesSplitRequiresOutputDir = errors.New("--split requires --output-dir and cannot be used with --output") + ErrKubernetesSplitNeedsOutputDir = errors.New("--split requires --output-dir") + ErrKubernetesClientInit = errors.New("failed to initialize kubernetes client") + ErrKubernetesEndpointMismatch = errors.New("effective Kubernetes API endpoint does not match the identity integration") + ErrKubernetesIdentityRequired = errors.New("an Atmos Auth identity is required for this Kubernetes operation") + ErrKubernetesApply = errors.New("failed to apply kubernetes object") + ErrKubernetesDelete = errors.New("failed to delete kubernetes object") + ErrKubernetesDiff = errors.New("failed to diff kubernetes object") + ErrKubernetesMarshal = errors.New("failed to marshal kubernetes object") + ErrKubernetesResolveResource = errors.New("failed to resolve kubernetes resource") + ErrKubernetesComponentDir = errors.New("failed to create kubernetes component directory") + ErrKubernetesRenderOutput = errors.New("failed to write rendered kubernetes manifests") + ErrKubernetesRender = errors.New("failed to render kubernetes object") + ErrKubernetesProviderType = errors.New("provider must be a string") + ErrManifestPathTraversal = errors.New("manifest path escapes the component directory") + ErrKubernetesValidationFailed = errors.New("kubernetes manifest validation failed") + ErrKubernetesManifestInvalidName = errors.New("object metadata.name is not a valid DNS-1123 subdomain") + ErrKubernetesValidate = errors.New("failed to validate kubernetes object") + ErrKubernetesValidateSectionInvalid = errors.New("component 'validate' must be a boolean") + + // Helm-native component errors. + ErrHelmFlagsMutuallyExclusive = errors.New("--all and --affected are mutually exclusive") + ErrHelmComponentArgWithSelection = errors.New("component argument cannot be used with --all, --affected, --tags, or --labels") + ErrHelmOutputSingleComponentOnly = errors.New("--output and --output-dir are only supported when rendering one component") + ErrHelmComponentArgRequired = errors.New("requires exactly one component argument unless --all or --affected is set") + ErrHelmUnsupportedOperation = errors.New("unsupported helm operation") + ErrHelmUnsupportedSubcommand = errors.New("unsupported helm subcommand") + ErrHelmChartNotConfigured = errors.New("helm component is missing a 'chart' reference") + ErrHelmRenderFailed = errors.New("failed to render helm chart") + ErrHelmReleaseNameRequired = errors.New("helm component is missing a release name") + ErrHelmDiffFailed = errors.New("failed to compute helm diff") + ErrHelmBaselineRead = errors.New("failed to read helm diff baseline") + ErrHelmLifecycleDecode = errors.New("failed to decode helm release lifecycle") + ErrHelmFailureActionInvalid = errors.New("invalid helm on_failure action") + ErrHelmWaitStrategyInvalid = errors.New("invalid helm wait strategy") + ErrHelmServerSideApplyInvalid = errors.New("invalid helm server_side_apply value") + ErrHelmForceConflictsRequiresSSA = errors.New("helm force_conflicts requires server-side apply to be enabled") + ErrHelmTimeoutInvalid = errors.New("invalid helm release timeout") + ErrHelmMaxHistoryInvalid = errors.New("invalid helm release history limit") + ErrHelmWaitForJobsRequiresWait = errors.New("helm wait_for_jobs requires watcher or legacy wait strategy") + ErrHelmLifecycleFlagInapplicable = errors.New("helm release lifecycle flag does not apply to selected operation") + ErrHelmLifecycleExternalTarget = errors.New("helm release lifecycle flags require a Kubernetes target") + ErrHelmReleaseHistory = errors.New("failed to inspect helm release history") + ErrHelmReleaseUpgrade = errors.New("failed to upgrade helm release") + ErrHelmReleaseUninstall = errors.New("failed to uninstall helm release") + ErrHelmReleaseRollback = errors.New("failed to roll back helm release") + ErrHelmReleaseOperation = errors.New("failed to perform helm release operation") + + // Native aws/cloudformation component errors. + ErrMissingAwsCloudFormationTemplate = errors.New("aws/cloudformation component is missing a template: set 'template' (inline body) or 'path' (file reference)") + ErrMissingAwsCloudFormationStackName = errors.New("aws/cloudformation component is missing a 'stack_name'") + ErrInvalidAwsCloudFormationCapabilities = errors.New("invalid aws/cloudformation capabilities") + ErrInvalidAwsCloudFormationSettings = errors.New("invalid aws/cloudformation settings") + ErrAwsCloudFormationGenerateUnsupported = errors.New("aws/cloudformation components do not support a 'generate' section") + ErrAwsCloudFormationStackPolicyFileAndBodyMutuallyExclusive = errors.New("'stack_policy.file' and 'stack_policy.body' are mutually exclusive: 'file' is a file reference, 'body' is an inline policy") + ErrInvalidComponentsAwsCloudFormation = errors.New("invalid 'components.aws/cloudformation' section") + ErrInvalidSpecificAwsCloudFormationComponent = errors.New("invalid aws/cloudformation component configuration") + ErrAwsCloudFormationChangeSetFailed = errors.New("aws/cloudformation changeset failed") + ErrAwsCloudFormationChangeSetNotFound = errors.New("aws/cloudformation changeset not found") + ErrAwsCloudFormationDriftDetected = errors.New("aws/cloudformation stack has drifted") + ErrAwsCloudFormationFlagsMutuallyExclusive = errors.New("--all and --affected are mutually exclusive") + ErrAwsCloudFormationComponentArgWithSelection = errors.New("component argument cannot be used with --all, --affected, --tags, or --labels") + ErrAwsCloudFormationComponentArgRequired = errors.New("requires exactly one component argument unless --all, --affected, --tags, or --labels is set") + ErrAwsCloudFormationIdentityResolutionFailed = errors.New("aws/cloudformation component requested an identity, but the auth manager could not resolve it") + ErrAwsCloudFormationAPICallFailed = errors.New("aws/cloudformation API call failed") + ErrAwsCloudFormationFmtNotClean = errors.New("aws/cloudformation template is not formatted") + ErrAwsCloudFormationFmtWriteFailed = errors.New("aws/cloudformation failed to write formatted template") + ErrAwsCloudFormationStackNotFound = errors.New("aws/cloudformation stack not found") + ErrAwsCloudFormationStackSetFailed = errors.New("aws/cloudformation stackset operation failed") + ErrAwsCloudFormationLogsFollowChartExclusive = errors.New("--follow and --chart are mutually exclusive") + ErrAwsCloudFormationOperationFailed = errors.New("aws/cloudformation operation did not complete successfully") + ErrAwsCloudFormationBackendMissing = errors.New("aws/cloudformation packaging bucket does not exist") + ErrAwsCloudFormationIncludeDependentsRequiresAffected = errors.New("--include-dependents requires --affected") + ErrAwsCloudFormationTemplateAndPathMutuallyExclusive = errors.New("'template' and 'path' are mutually exclusive: 'template' is an inline template body, 'path' is a file reference") + ErrAwsCloudFormationFmtRequiresPath = errors.New("aws/cloudformation fmt only applies to file-based templates ('path:'); inline 'template:' bodies have no file to format in place") + ErrAwsCloudFormationTemplateMissingResources = errors.New("aws/cloudformation inline template is missing a top-level 'Resources' section") + ErrInvalidAwsCloudFormationParameters = errors.New("invalid aws/cloudformation parameters") + ErrAwsCloudFormationStackNotDeployed = errors.New("aws/cloudformation stack is not deployed") + ErrAwsCloudFormationOutputNotFound = errors.New("aws/cloudformation output not found") + ErrAwsCloudFormationInvalidFlagCombination = errors.New("invalid flag combination") + ErrAwsCloudFormationConfirmationRequired = errors.New("aws/cloudformation operation requires confirmation; pass --auto-approve in a non-interactive session") + ErrAwsCloudFormationStackRollbackComplete = errors.New("aws/cloudformation stack is in ROLLBACK_COMPLETE and cannot be updated") + ErrAwsCloudFormationStackSetTargetNotApplicable = errors.New("aws/cloudformation apply cannot deliver to a `kind: aws/stackset` provision target") + ErrAwsCloudFormationTerminationProtectionEnabled = errors.New("aws/cloudformation stack has termination protection enabled") + ErrAwsCloudFormationRetainResourcesNotApplicable = errors.New("--retain-resources is only valid for a stack in DELETE_FAILED status") + ErrAwsCloudFormationBackendTargetsFailed = errors.New("aws/cloudformation backend targets could not be inspected") + ErrAwsCloudFormationRainDirective = errors.New("aws/cloudformation template contains Rain directives, which Atmos does not preprocess") +) diff --git a/errors/errors_configuration.go b/errors/errors_configuration.go new file mode 100644 index 00000000000..93530989cb3 --- /dev/null +++ b/errors/errors_configuration.go @@ -0,0 +1,507 @@ +package errors + +import ( + "errors" + + schemaPkg "github.com/cloudposse/atmos/pkg/schema" +) + +var ( + // Toolchain errors. + ErrToolNotFound = errors.New("tool not found") + ErrInvalidToolSpec = errors.New("invalid tool specification") + ErrToolAlreadyInstalled = errors.New("tool already installed") + ErrDownloadFailed = errors.New("download failed") + ErrDownloadRetryable = errors.New("retryable download error") + ErrSignatureRetryable = errors.New("retryable signature verification error") + ErrExtractionFailed = errors.New("extraction failed") + ErrChecksumMismatch = errors.New("checksum mismatch") + ErrNoVersionsInstalled = errors.New("no versions installed") + ErrLatestFileNotFound = errors.New("latest version file not found") + ErrRegistryNotReachable = errors.New("registry not reachable") + ErrToolNotInRegistry = errors.New("tool not in registry") + ErrToolRegistryIndexUnavailable = errors.New("tool registry index unavailable") + ErrToolPlatformNotSupported = errors.New("tool does not support this platform") + ErrAliasNotFound = errors.New("alias not found") + ErrBinaryNotExecutable = errors.New("binary not executable") + ErrBinaryNotFound = errors.New("binary not found") + ErrLockfileVersionMismatch = errors.New("lockfile version mismatch") + ErrFrozenLockfile = errors.New("frozen toolchain lockfile requires an existing complete entry and prohibits updates") + ErrLockfileEmptyVersion = errors.New("lockfile tool version cannot be empty") + ErrNoAssetTemplate = errors.New("no asset template defined") + ErrAssetTemplateInvalid = errors.New("asset template invalid") + ErrToolVersionsFileOperation = errors.New("tool-versions file operation failed") + ErrNoToolsConfigured = errors.New("no tools configured") + ErrUnsupportedVersionConstraint = errors.New("unsupported version constraint format") + ErrToolchainPlainFormatWithAllFlag = errors.New("--format=plain can't be used with --all") + ErrToolchainCleanRequiresConfirmation = errors.New("toolchain clean requires interactive confirmation or --force flag") + ErrToolchainCleanConfirmation = errors.New("toolchain clean confirmation prompt failed") + + // Flag validation errors. + ErrCompatibilityFlagMissingTarget = errors.New("compatibility flag references non-existent flag") + ErrInvalidFlagValue = errors.New("invalid value for flag") + ErrFlagBinding = errors.New("failed to bind flags") + + // File and URL handling errors. + ErrInvalidPagerCommand = errors.New("invalid pager command") + ErrEmptyURL = errors.New("empty URL provided") + ErrFailedToFindImport = errors.New("failed to find import") + ErrInvalidFilePath = errors.New("invalid file path") + ErrRelPath = errors.New("error determining relative path") + ErrHTTPRequestFailed = errors.New("HTTP request failed") + ErrRedirectLimitExceeded = errors.New("stopped after 10 redirects") + + // Config loading errors. + ErrAtmosDirConfigNotFound = errors.New("atmos config directory not found") + ErrReadConfig = errors.New("failed to read config") + ErrMergeTempConfig = errors.New("failed to merge temp config") + ErrPreprocessYAMLFunctions = errors.New("failed to preprocess YAML functions") + ErrMergeEmbeddedConfig = errors.New("failed to merge embedded config") + ErrExpectedDirOrPattern = errors.New("expected directory or pattern") + ErrFileNotFound = errors.New("file not found") + ErrFileAccessDenied = errors.New("file access denied") + ErrExpectedFile = errors.New("expected file") + ErrAtmosArgConfigNotFound = errors.New("atmos configuration not found") + ErrEmptyConfigPath = errors.New("config path is empty") + ErrEmptyConfigFile = errors.New("config file path is empty") + ErrAtmosFilesDirConfigNotFound = errors.New("atmos configuration file not found in directory") + ErrAtmosConfigNotFound = errors.New("atmos configuration file not found") + + // Profile errors. + ErrProfileNotFound = errors.New("profile not found") + ErrProfileSyntax = errors.New("profile syntax error") + ErrProfileDiscovery = errors.New("failed to discover profiles") + ErrProfileLoad = errors.New("failed to load profile") + ErrProfileMerge = errors.New("failed to merge profile configuration") + ErrProfileDirNotExist = errors.New("profile directory does not exist") + ErrProfileDirNotAccessible = errors.New("profile directory not accessible") + ErrProfileInvalidMetadata = errors.New("invalid profile metadata") + ErrProfileSelectionUnavailable = errors.New("interactive profile selection is not available in this context") + ErrProfileNameReserved = errors.New("profile name is reserved") + + ErrMissingStack = errors.New("stack is required; specify it on the command line using the flag `--stack ` (shorthand `-s`)") + ErrMissingComponent = errors.New("component is required") + ErrNoStacksToSelect = errors.New("no stacks are available to choose from") + ErrNoComponentsToSelect = errors.New("no components are configured to choose from") + ErrLoadSelectionOptions = errors.New("failed to load options for interactive selection") + ErrMissingComponentType = errors.New("component type is required") + ErrRequiredFlagNotProvided = errors.New("required flag not provided") + ErrRequiredFlagEmpty = errors.New("required flag cannot be empty") + ErrInvalidArguments = errors.New("invalid arguments") + ErrUnknownSubcommand = errors.New("unknown subcommand") + ErrInvalidComponent = errors.New("invalid component") + ErrDuplicateComponentConfig = errors.New("duplicate component configuration") + // ErrInvalidStack indicates the user provided an identifier that doesn't match + // the stack's canonical name (e.g., using filename when explicit name is set). + // This differs from ErrStackNotFound which indicates the stack doesn't exist at all. + ErrInvalidStack = errors.New("invalid stack") + ErrInvalidComponentMapType = errors.New("invalid component map type") + ErrAbstractComponentCantBeProvisioned = errors.New("abstract component cannot be provisioned") + ErrLockedComponentCantBeProvisioned = errors.New("locked component cannot be provisioned") + ErrSpaceliftAdminStackWorkspaceNotEnabled = errors.New("spacelift admin stack does not have workspace enabled") + ErrSpaceliftAdminStackComponentNotProvisioned = errors.New("spacelift admin stack component cannot be provisioned") + + // Terraform-specific errors. + ErrHTTPBackendWorkspaces = errors.New("workspaces are not supported for the HTTP backend") + ErrInvalidTerraformComponent = errors.New("invalid Terraform component") + ErrNoTty = errors.New("no TTY attached") + ErrNoSuitableShell = errors.New("no suitable shell found") + ErrFailedToLoadTerraformComponent = errors.New("failed to load terraform component") + ErrNoJSONOutput = errors.New("no JSON output found in terraform show output") + ErrOriginalPlanFileRequired = errors.New("original plan file is required") + ErrOriginalPlanFileNotExist = errors.New("original plan file does not exist") + ErrNewPlanFileNotExist = errors.New("new plan file does not exist") + ErrTerraformGenerateBackendArgument = errors.New("invalid arguments") + ErrFileTemplateRequired = errors.New("file-template is required") + ErrInteractiveNotAvailable = errors.New("interactive confirmation not available in non-TTY environment") + ErrDeprecatedCmdNotCallable = errors.New("deprecated command should not be called") + + ErrMissingPackerTemplate = errors.New("packer template is required") + ErrMissingPackerManifest = errors.New("packer manifest is missing") + + ErrAtmosConfigIsNil = errors.New("atmos config is nil") + ErrFailedToInitializeAtmosConfig = errors.New("failed to initialize atmos config") + ErrInvalidListMergeStrategy = errors.New("invalid list merge strategy") + ErrMerge = errors.New("merge error") + ErrMergeNilDst = errors.New("merge destination must not be nil") + ErrMergeTypeMismatch = errors.New("cannot override two slices with different type") + ErrMergeKeyCollision = errors.New("distinct map keys collide after normalization") + ErrEncode = errors.New("encoding error") + ErrDecode = errors.New("decoding error") + + // Stack processing errors. + ErrStackManifestFileNotFound = errors.New("stack manifest file not found") + ErrInvalidStackManifest = errors.New("invalid stack manifest") + ErrStackManifestSchemaValidation = errors.New("stack manifest schema validation failed") + ErrStackImportSelf = errors.New("stack manifest imports itself") + ErrStackImportNotFound = errors.New("stack import not found") + ErrImportPathTemplate = errors.New("failed to render Go template in import path") + ErrStackCircularInheritance = errors.New("circular component inheritance detected") + ErrInvalidHooksSection = errors.New("invalid 'hooks' section in the file") + ErrInvalidTerraformHooksSection = errors.New("invalid 'terraform.hooks' section in the file") + ErrInvalidComponentVars = errors.New("invalid component vars section") + ErrInvalidComponentLocals = errors.New("invalid component locals section") + ErrInvalidComponentSettings = errors.New("invalid component settings section") + ErrInvalidComponentEnv = errors.New("invalid component env section") + ErrInvalidComponentProviders = errors.New("invalid component providers section") + ErrInvalidComponentRequiredProviders = errors.New("invalid component required_providers section") + ErrInvalidComponentRequiredVersion = errors.New("invalid component required_version attribute") + ErrInvalidComponentHooks = errors.New("invalid component hooks section") + ErrUnsupportedHookEvent = errors.New("unsupported hook event") + ErrUnknownHookKind = errors.New("unknown hook kind") + ErrInvalidHookOnFailure = errors.New("invalid hook on_failure value") + ErrInvalidComponentSecrets = errors.New("invalid component secrets section") + ErrStoreIsSecret = errors.New("store is a secret store; use !secret instead of !store") + ErrStoreNotFound = errors.New("store not found") + ErrInvalidComponentGenerate = errors.New("invalid component generate section") + ErrInvalidComponentFlags = errors.New("invalid component flags section") + ErrInvalidComponentAuth = errors.New("invalid component auth section") + ErrInvalidComponentProvision = errors.New("invalid component provision section") + ErrInvalidComponentMetadata = errors.New("invalid component metadata section") + ErrInvalidComponentDependencies = errors.New("invalid component dependencies section") + ErrInvalidComponentBackendType = errors.New("invalid component backend_type attribute") + ErrInvalidComponentBackend = errors.New("invalid component backend section") + ErrInvalidComponentRemoteStateBackendType = errors.New("invalid component remote_state_backend_type attribute") + ErrInvalidComponentRemoteStateBackend = errors.New("invalid component remote_state_backend section") + ErrInvalidComponentCommand = errors.New("invalid component command attribute") + ErrInvalidComponentSource = errors.New("invalid component source section") + ErrInvalidComponentOverrides = errors.New("invalid component overrides section") + ErrInvalidComponentOverridesVars = errors.New("invalid component overrides vars section") + ErrInvalidComponentOverridesSettings = errors.New("invalid component overrides settings section") + ErrInvalidComponentOverridesEnv = errors.New("invalid component overrides env section") + ErrInvalidComponentOverridesAuth = errors.New("invalid component overrides auth section") + ErrInvalidComponentOverridesCommand = errors.New("invalid component overrides command attribute") + ErrInvalidComponentOverridesProviders = errors.New("invalid component overrides providers section") + ErrInvalidComponentOverridesRequiredProviders = errors.New("invalid component overrides required_providers section") + ErrInvalidComponentOverridesRequiredVersion = errors.New("invalid component overrides required_version attribute") + ErrInvalidComponentOverridesHooks = errors.New("invalid component overrides hooks section") + ErrInvalidComponentOverridesGenerate = errors.New("invalid component overrides generate section") + ErrInvalidComponentOverridesProvision = errors.New("invalid component overrides provision section") + ErrInvalidComponentOverridesFlags = errors.New("invalid component overrides flags section") + ErrInvalidComponentAttribute = errors.New("invalid component attribute") + ErrInvalidComponentMetadataComponent = errors.New("invalid component metadata.component attribute") + ErrInvalidSpaceLiftSettings = errors.New("invalid spacelift settings section") + ErrInvalidComponentMetadataInherits = errors.New("invalid component metadata.inherits section") + ErrComponentNotDefined = errors.New("component not defined in any config files") + + // Component registry errors. + ErrComponentProviderNotFound = errors.New("component provider not found") + ErrComponentProviderNil = errors.New("component provider cannot be nil") + ErrComponentTypeEmpty = errors.New("component type is empty") + ErrComponentEmpty = errors.New("component is empty") + ErrStackEmpty = errors.New("stack is empty") + ErrComponentConfigInvalid = errors.New("component configuration invalid") + ErrComponentListFailed = errors.New("failed to list components") + ErrComponentValidationFailed = errors.New("component validation failed") + ErrComponentExecutionFailed = errors.New("component execution failed") + ErrNoRunningContainer = errors.New("no running container found") + ErrComponentArtifactGeneration = errors.New("component artifact generation failed") + ErrComponentProviderRegistration = errors.New("failed to register component provider") + + // Emulator errors. + ErrUnknownEmulatorDriver = errors.New("unknown emulator driver") + ErrEmulatorNotRunning = errors.New("emulator is not running") + ErrEmulatorNotConfigured = errors.New("emulator is not configured") + ErrEmulatorResolutionFailed = errors.New("failed to resolve emulator") + ErrEmulatorAmbiguous = errors.New("emulator identity is ambiguous") + ErrEmulatorTargetMismatch = errors.New("emulator target does not match") + ErrEmulatorConfigInvalid = errors.New("emulator configuration invalid") + ErrEmulatorResolverUnavailable = errors.New("emulator resolver is not available") + ErrEmulatorResetFailed = errors.New("emulator reset failed") + + ErrInvalidTerraformBackend = errors.New("invalid terraform.backend section") + ErrInvalidTerraformRemoteStateBackend = errors.New("invalid terraform.remote_state_backend section") + ErrBackendTypeMismatch = errors.New("backend_type does not match any key configured under backend") + ErrUnsupportedComponentType = errors.New("unsupported component type") + + // Custom component errors. + ErrCustomComponentTypeRegistration = errors.New("failed to register custom component type") + ErrComponentArgumentNotFound = errors.New("no argument or flag with type 'component' found") + ErrStackArgumentNotFound = errors.New("no argument or flag with type 'stack' found") + + // Generator errors. + ErrGeneratorNotFound = errors.New("generator not found") + ErrInvalidGeneratorCtx = errors.New("invalid generator context") + ErrGeneratorValidation = errors.New("generator validation failed") + ErrGenerationFailed = errors.New("generation failed") + ErrGeneratorWriteFailed = errors.New("failed to write generated file") + ErrGeneratorRemoveFailed = errors.New("failed to remove generated file") + ErrGeneratedNotRegular = errors.New("generated file path is not a regular file") + ErrMissingWorkingDir = errors.New("working directory is required") + ErrMissingProviderSource = errors.New("required_providers entry missing 'source' field") + + // Archive package errors (pkg/archive). + ErrArchiveUnknownFormat = errors.New("unknown or unsupported archive format") + ErrArchiveActionNotImplemented = errors.New("archive action is not yet implemented") + ErrArchiveUpdateUnsupportedFormat = errors.New("archive update is not supported for this format") + ErrArchiveOptionsRequired = errors.New("archive options are required") + ErrArchiveSourceRequired = errors.New("archive source is required") + ErrArchiveSourceNotFound = errors.New("archive source does not exist") + ErrArchiveDestinationRequired = errors.New("archive destination is required") + ErrArchiveInvalidGlobPattern = errors.New("invalid archive include/exclude glob pattern") + ErrArchiveInvalidSubpath = errors.New("invalid archive subpath") + ErrArchiveFormatNotImplemented = errors.New("archive format is not yet implemented") + ErrArchiveWriteFailed = errors.New("failed to write archive") + ErrArchiveWalkFailed = errors.New("failed to walk archive source") + ErrArchiveInvalidMtimeMode = errors.New("invalid archive mtime mode") + + // List command errors. + ErrInvalidStackPattern = errors.New("invalid stack pattern") + ErrEmptyTargetComponentName = errors.New("target component name cannot be empty") + ErrComponentsSectionNotFound = errors.New("components section not found in stack") + ErrComponentNotFoundInSections = errors.New("component not found in terraform or helmfile sections") + ErrUnknownComposition = errors.New("component references an undeclared composition") + ErrUnknownCompositionMembership = errors.New("component claims membership in a service not declared by the composition") + ErrQueryFailed = errors.New("query execution failed") + ErrScalarExtractionNotSupported = errors.New("scalar extraction queries are not supported") + ErrQueryUnexpectedResultType = errors.New("query returned unexpected result type") + ErrTableTooWide = errors.New("the table is too wide to display properly") + ErrGettingCommonFlags = errors.New("error getting common flags") + ErrGettingAbstractFlag = errors.New("error getting abstract flag") + ErrGettingVarsFlag = errors.New("error getting vars flag") + ErrInitializingCLIConfig = errors.New("error initializing CLI config") + ErrDescribingStacks = errors.New("error describing stacks") + ErrComponentNameRequired = errors.New("component name is required") + ErrCreateColumnSelector = errors.New("failed to create column selector") + + // Version command errors. + ErrVersionDisplayFailed = errors.New("failed to display version information") + ErrVersionCheckFailed = errors.New("failed to check for version updates") + ErrVersionFormatInvalid = errors.New("invalid version output format") + ErrVersionCacheLoadFailed = errors.New("failed to load version check cache") + ErrVersionGitHubAPIFailed = errors.New("failed to query GitHub API for releases") + + // Version constraint errors. + ErrVersionConstraint = errors.New("version constraint not satisfied") + ErrInvalidVersionConstraint = errors.New("invalid version constraint") + + // Atlantis errors. + ErrAtlantisInvalidFlags = errors.New("incompatible atlantis flags") + ErrAtlantisProjectTemplateNotDef = errors.New("atlantis project template is not defined") + ErrAtlantisConfigTemplateNotDef = errors.New("atlantis config template is not defined") + ErrAtlantisConfigTemplateNotSpec = errors.New("atlantis config template is not specified") + + // Validation errors. + ErrValidationFailed = errors.New("validation failed") + ErrUnsupportedValidationFormat = errors.New("unsupported validation format: expected text or rich") + ErrUnsupportedCIValidationFormat = errors.New("unsupported CI validation format: expected text, rich, or sarif") + ErrWorkflowArgsWithWorkflowPath = errors.New("workflow-file arguments cannot be used with --workflow-path") + ErrAffectedWithFileArgsOrPath = errors.New("--affected cannot be used with workflow-file arguments or --workflow-path") + ErrCIValidatorNotRegistered = errors.New("CI validator is not registered") + + // EditorConfig validation errors. + ErrEditorConfigValidationFailed = errors.New("EditorConfig validation failed") + ErrEditorConfigVersionMismatch = errors.New("EditorConfig version mismatch") + ErrEditorConfigGetFiles = errors.New("failed to get files for EditorConfig validation") + ErrEditorConfigInvalidFormat = errors.New("invalid EditorConfig output format") + + // Global/Stack-level section errors. + ErrInvalidVarsSection = errors.New("invalid vars section") + ErrInvalidSettingsSection = errors.New("invalid settings section") + ErrInvalidEnvSection = errors.New("invalid env section") + ErrInvalidGenerateSection = errors.New("invalid generate section") + ErrInvalidDependenciesSection = errors.New("invalid dependencies section") + ErrInvalidTerraformSection = errors.New("invalid terraform section") + ErrInvalidHelmfileSection = errors.New("invalid helmfile section") + ErrInvalidPackerSection = errors.New("invalid packer section") + ErrInvalidComponentsSection = errors.New("invalid components section") + ErrInvalidAuthSection = errors.New("invalid auth section") + ErrInvalidGlobalMetadataSection = errors.New("invalid metadata section") + ErrGlobalMetadataFieldNotAllowed = errors.New("metadata field is not allowed at global (stack-wide) scope") + ErrInvalidGlobalRetrySection = errors.New("invalid retry section") + ErrInvalidImportSection = errors.New("invalid import section") + ErrInvalidImport = errors.New("invalid import") + ErrInvalidRemoteImport = errors.New("invalid remote import") + ErrOCIImportMissingPath = errors.New("an oci:// import requires a '//' path to the file inside the artifact") + ErrDownloadRemoteImport = errors.New("failed to download remote import") + ErrCacheDirectoryCreation = errors.New("failed to create cache directory") + ErrClearCache = errors.New("failed to clear cache") + ErrInvalidOverridesSection = errors.New("invalid overrides section") + ErrInvalidTerraformOverridesSection = errors.New("invalid terraform overrides section") + ErrInvalidHelmOverridesSection = errors.New("invalid helm overrides section") + ErrInvalidHelmfileOverridesSection = errors.New("invalid helmfile overrides section") + ErrInvalidBaseComponentConfig = errors.New("invalid base component config") + ErrCircularComponentInheritance = ErrStackCircularInheritance + + // Terraform-specific subsection errors. + ErrInvalidTerraformCommand = errors.New("invalid terraform command") + ErrInvalidTerraformVars = errors.New("invalid terraform vars section") + ErrInvalidTerraformSettings = errors.New("invalid terraform settings section") + ErrInvalidTerraformEnv = errors.New("invalid terraform env section") + ErrInvalidTerraformProviders = errors.New("invalid terraform providers section") + ErrInvalidTerraformGenerateSection = errors.New("invalid terraform generate section") + ErrInvalidTerraformFlagsSection = errors.New("invalid terraform flags section") + ErrInvalidTerraformBackendType = errors.New("invalid terraform backend_type") + ErrMissingTerraformBackendType = errors.New("'backend_type' is missing for the component") + ErrMissingTerraformBackendConfig = errors.New("'backend' config is missing for the component") + ErrMissingTerraformWorkspaceKeyPrefix = errors.New("backend config is missing 'workspace_key_prefix'") + ErrInvalidTerraformRemoteStateType = errors.New("invalid terraform remote_state_backend_type") + ErrInvalidTerraformRemoteStateSection = errors.New("invalid terraform remote_state_backend section") + ErrInvalidTerraformAuth = errors.New("invalid terraform auth section") + ErrInvalidTerraformDependencies = errors.New("invalid terraform dependencies section") + ErrInvalidTerraformSource = errors.New("invalid terraform source section") + ErrInvalidTerraformProvision = errors.New("invalid terraform provision section") + ErrUnresolvedComputedTerraformVar = errors.New("terraform variable contains an unresolved computed value") + + // Helmfile-specific subsection errors. + ErrInvalidHelmfileCommand = errors.New("invalid helmfile command") + ErrInvalidHelmfileVars = errors.New("invalid helmfile vars section") + ErrInvalidHelmfileSettings = errors.New("invalid helmfile settings section") + ErrInvalidHelmfileEnv = errors.New("invalid helmfile env section") + ErrInvalidHelmfileAuth = errors.New("invalid helmfile auth section") + ErrInvalidHelmfileDependencies = errors.New("invalid helmfile dependencies section") + + // Helmfile configuration errors. + ErrMissingHelmfileBasePath = errors.New("helmfile base path is required") + ErrMissingHelmfileKubeconfigPath = errors.New("helmfile kubeconfig path is required") + ErrMissingHelmfileAwsProfilePattern = errors.New("helmfile AWS profile pattern is required") + ErrMissingHelmfileClusterNamePattern = errors.New("helmfile cluster name pattern is required") + ErrMissingHelmfileClusterName = errors.New("helmfile cluster name is required") + ErrMissingHelmfileAuth = errors.New("helmfile AWS authentication is required") + + // Packer configuration errors. + ErrMissingPackerBasePath = errors.New("packer base path is required") + + // Packer-specific subsection errors. + ErrInvalidPackerCommand = errors.New("invalid packer command") + ErrInvalidPackerVars = errors.New("invalid packer vars section") + ErrInvalidPackerSettings = errors.New("invalid packer settings section") + ErrInvalidPackerEnv = errors.New("invalid packer env section") + ErrInvalidPackerAuth = errors.New("invalid packer auth section") + ErrInvalidPackerDependencies = errors.New("invalid packer dependencies section") + + // Ansible configuration errors. + ErrMissingAnsibleBasePath = errors.New("ansible base path is required") + + // Ansible-specific subsection errors. + ErrInvalidAnsibleSection = errors.New("invalid ansible section") + ErrInvalidAnsibleCommand = errors.New("invalid ansible command") + ErrInvalidAnsibleVars = errors.New("invalid ansible vars section") + ErrInvalidAnsibleSettings = errors.New("invalid ansible settings section") + ErrInvalidAnsibleEnv = errors.New("invalid ansible env section") + ErrInvalidAnsibleAuth = errors.New("invalid ansible auth section") + ErrInvalidAnsibleDependencies = errors.New("invalid ansible dependencies section") + + // Ansible execution errors. + ErrAnsiblePlaybookMissing = errors.New("ansible playbook is required") + + // Component type-specific section errors. + ErrInvalidComponentsTerraform = errors.New("invalid components.terraform section") + ErrInvalidComponentsHelmfile = errors.New("invalid components.helmfile section") + ErrInvalidComponentsPacker = errors.New("invalid components.packer section") + ErrInvalidComponentsAnsible = errors.New("invalid components.ansible section") + + // Specific component configuration errors. + ErrInvalidSpecificTerraformComponent = errors.New("invalid terraform component configuration") + ErrInvalidSpecificHelmfileComponent = errors.New("invalid helmfile component configuration") + ErrInvalidSpecificPackerComponent = errors.New("invalid packer component configuration") + ErrInvalidSpecificAnsibleComponent = errors.New("invalid ansible component configuration") + + // Pro API client errors. + ErrFailedToCreateRequest = errors.New("failed to create request") + ErrFailedToMarshalPayload = errors.New("failed to marshal request body") + ErrFailedToCreateAuthRequest = errors.New("failed to create authenticated request") + ErrFailedToMakeRequest = errors.New("failed to make request") + ErrFailedToUploadStacks = errors.New("failed to upload stacks") + ErrFailedToReadResponseBody = errors.New("failed to read response body") + ErrFailedToLockStack = errors.New("failed to lock stack") + ErrFailedToUnlockStack = errors.New("failed to unlock stack") + ErrOIDCWorkspaceIDRequired = errors.New("workspace ID environment variable is required for OIDC authentication") + ErrOIDCTokenExchangeFailed = errors.New("failed to exchange OIDC token for Atmos token") + ErrOIDCAuthFailedNoToken = errors.New("OIDC authentication failed: no token") + ErrNotInGitHubActions = errors.New("not running in GitHub Actions or missing OIDC token environment variables") + ErrFailedToGetOIDCToken = errors.New("failed to get OIDC token") + ErrFailedToDecodeOIDCResponse = errors.New("failed to decode OIDC token response") + ErrFailedToExchangeOIDCToken = errors.New("failed to exchange OIDC token") + ErrFailedToDecodeTokenResponse = errors.New("failed to decode token response") + ErrFailedToGetGitHubOIDCToken = errors.New("failed to get GitHub OIDC token") + ErrFailedToUploadInstances = errors.New("failed to upload instances") + ErrFailedToUploadInstanceStatus = errors.New("failed to upload instance status") + ErrPayloadTooLarge = errors.New("request exceeded the Atmos Pro body size limit") + ErrUploadRetryExhausted = errors.New("upload failed after all retries") + ErrTokenRefreshFailed = errors.New("failed to refresh API token") + ErrFailedToUnmarshalAPIResponse = errors.New("failed to unmarshal API response") + ErrNilRequestDTO = errors.New("nil request DTO") + ErrProExceptionEnvelopeTooLarge = errors.New("pro exception envelope exceeds the ingestion limit") + ErrFailedToUploadExecMetadata = errors.New("failed to upload execution metadata") + ErrFailedToUploadExecData = errors.New("failed to upload execution data") + ErrExecPayloadTooLarge = errors.New("execution metadata payload too large") + ErrExecSyncTimeout = errors.New("execution metadata upload timed out") + + // Pro commit errors. + ErrCommitMessageRequired = errors.New("commit message is required") + ErrCommitMessageTooLong = errors.New("commit message exceeds 500 characters") + ErrCommentTooLong = errors.New("comment exceeds 2000 characters") + ErrBranchRequired = errors.New("GITHUB_HEAD_REF is required (this command only runs in PR workflows)") + ErrBranchInvalid = errors.New("branch name contains invalid characters") + ErrTooManyChanges = errors.New("too many changed files (max 200)") + ErrCommitInvalidFilePath = errors.New("invalid file path for commit") + ErrFileTooLarge = errors.New("file exceeds 2 MiB size limit") + ErrFailedToStageChanges = errors.New("failed to stage changes") + ErrFailedToDetectChanges = errors.New("failed to detect git changes") + ErrFailedToCreateCommit = errors.New("failed to create commit via Atmos Pro") + ErrStagingFlagConflict = errors.New("--add and --all are mutually exclusive") + ErrAPIResponseError = errors.New("API response error") + + // Exec package errors. + ErrComponentAndStackRequired = errors.New("component and stack are both required") + ErrFailedToCreateAPIClient = errors.New("failed to create API client") + ErrFailedToProcessArgs = errors.New("failed to process command-line arguments") + ErrFailedToInitConfig = errors.New("failed to initialize Atmos configuration") + ErrFailedToCreateLogger = errors.New("failed to create logger") + ErrFailedToGetComponentFlag = errors.New("failed to get '--component' flag") + ErrFailedToGetStackFlag = errors.New("failed to get '--stack' flag") + ErrOPAPolicyViolations = errors.New("OPA policy violations detected") + ErrOPATimeout = errors.New("timeout evaluating OPA policy") + ErrInvalidRegoPolicy = errors.New("invalid Rego policy") + ErrInvalidOPAPolicy = errors.New("invalid OPA policy") + ErrTerraformEnvCliVarJSON = errors.New("failed to parse JSON variable from TF_CLI_ARGS environment variable") + ErrWorkflowBasePathNotConfigured = errors.New("'workflows.base_path' must be configured in 'atmos.yaml'") + ErrWorkflowDirectoryDoesNotExist = errors.New("workflow directory does not exist") + ErrWorkflowNoSteps = errors.New("workflow has no steps defined") + ErrInvalidWorkflowStepType = errors.New("invalid workflow step type") + ErrInvalidContinueCondition = errors.New("invalid 'continue' condition") + ErrInvalidFromStep = errors.New("invalid from-step flag") + ErrWorkflowStepFailed = errors.New("workflow step execution failed") + ErrWorkflowNoWorkflow = errors.New("no workflow found") + ErrWorkflowFileNotFound = errors.New("workflow file not found") + ErrInvalidWorkflowManifest = errors.New("invalid workflow manifest") + ErrResolveExecutablePath = errors.New("failed to resolve the running atmos executable's own path") + ErrUnknownStepType = errors.New("unknown step type") + ErrStepOptionsRequired = errors.New("options is required for step") + ErrStepContentOrOptionsRequired = errors.New("either content or options is required for step") + ErrStepDataOrContentRequired = errors.New("either data or content is required for step") + ErrStepEmptyCommand = errors.New("empty command for step") + ErrStepNoFilesFound = errors.New("no files found matching criteria") + ErrStepFieldRequired = errors.New("required field missing for step") + ErrStepExecutionFailed = errors.New("step execution failed") + ErrStepTTYRequired = errors.New("interactive terminal required for step") + ErrStepTimeout = errors.New("step timed out") + ErrStepTimeoutInvalid = errors.New("invalid step timeout") + ErrStepInvalidOutputMode = schemaPkg.ErrStepInvalidOutputMode + ErrCustomCommandArgumentMissing = errors.New("missing required argument for custom command") + ErrCustomCommandFlagType = errors.New("unsupported custom command flag type") + ErrCustomCommandFlagDefault = errors.New("invalid default value for custom command flag") + ErrHTTPStepURLRequired = errors.New("url is required for http step") + ErrHTTPStepInvalidMethod = errors.New("invalid HTTP method for http step") + ErrHTTPStepBodyFormConflict = errors.New("http step cannot set both body and form") + ErrHTTPStepInvalidExpectPattern = errors.New("invalid expect.response regex pattern for http step") + ErrHTTPStepRequestFailed = errors.New("http request failed") + ErrHTTPStepUnexpectedStatus = errors.New("http response did not match expected status") + ErrHTTPStepUnexpectedResponse = errors.New("http response body did not match expected pattern") + ErrArchiveStepInvalidAction = errors.New("invalid action for archive step") + ErrArchiveStepInvalidSource = errors.New("archive step source must be a string path") + ErrStoreStepInvalidAction = errors.New("invalid action for store step") + ErrStoreStepWriteFailed = errors.New("store step failed to write value") + ErrContainerStepResolveStack = errors.New("failed to resolve stack for container step") + ErrRequireStepEmpty = errors.New("require step must specify at least one of tools, files, or dirs") + ErrRequirementsNotMet = errors.New("required tools or paths are missing") + ErrWorkingDirNotFound = errors.New("working directory does not exist") + ErrWorkingDirNotDirectory = errors.New("working directory path is not a directory") + ErrWorkingDirAccessFailed = errors.New("failed to access working directory") + ErrWorkflowExit = errors.New("workflow exit requested") + ErrAuthProviderNotAvailable = errors.New("auth provider is not available") + ErrInvalidComponentArgument = errors.New("invalid arguments. The command requires one argument 'componentName'") + ErrValidation = errors.New("validation failed") + ErrCUEValidationUnsupported = errors.New("validation using CUE is not supported yet") +) diff --git a/errors/errors_execution.go b/errors/errors_execution.go new file mode 100644 index 00000000000..fd8c2f24450 --- /dev/null +++ b/errors/errors_execution.go @@ -0,0 +1,421 @@ +package errors + +import ( + "errors" + "fmt" + + "github.com/cloudposse/atmos/pkg/duration" +) + +var ( + // List package errors. + ErrExecuteDescribeStacks = errors.New("failed to execute describe stacks") + ErrProcessInstances = errors.New("failed to process instances") + ErrParseFlag = errors.New("failed to parse flag value") + ErrFailedToFinalizeCSVOutput = errors.New("failed to finalize CSV output") + ErrParseStacks = errors.New("could not parse stacks") + ErrParseComponents = errors.New("could not parse components") + ErrNoComponentsFound = errors.New("no components found") + ErrNoStacksFound = errors.New("no stacks found") + ErrStackNotFound = errors.New("stack not found") + ErrProcessStack = errors.New("error processing stack") + + // Dependency errors. + ErrUnsupportedDependencyType = errors.New("unsupported dependency type") + ErrMissingDependencyField = errors.New("dependency missing required field") + ErrDependencyTargetNotFound = errors.New("dependency target not found") + ErrDependencyTargetUnavailable = errors.New("dependency target unavailable") + // ErrSurvivingConsumers is returned when a destroy selection would remove a component that + // components outside the selection still require. + ErrSurvivingConsumers = errors.New("destroy would leave components that depend on it") + // ErrCustomCommandDependencyNotRegistered is returned when a dependencies.commands entry + // names a command that isn't registered under the custom-command cobra tree. + ErrCustomCommandDependencyNotRegistered = errors.New("dependency command is not registered") + // ErrAmbiguousCommandName is returned when a dependencies.commands entry names a command + // that more than one declared Command shares (e.g. two unrelated parents each with a nested + // child of the same name) -- there is no well-defined "first" match to silently pick. + ErrAmbiguousCommandName = errors.New("multiple commands share this name; use a unique name or restructure your commands") + + // Terraform --all flag errors. + ErrComponentWithAllFlagConflict = errors.New("component argument can't be used with --all flag") + + // ErrCacheCertUntrusted is returned when the OS trust store does not trust the + // registry cache proxy's certificate (macOS/Windows require a one-time trust step). + ErrCacheCertUntrusted = errors.New("registry cache certificate is not trusted") + + // ErrTrustStore is returned when installing or removing the registry cache proxy's + // certificate in the OS trust store fails. + ErrTrustStore = errors.New("registry cache trust store operation failed") + + // Terraform execution errors. + ErrTerraformExecFailed = errors.New("terraform execution failed") + ErrDescribeAffected = errors.New("describe affected failed") + ErrUploadRequiresSupportedEvent = errors.New("upload requires a supported CI event") + ErrDescribeStacks = errors.New("describe stacks failed") + ErrBuildDepGraph = errors.New("build dependency graph failed") + ErrTopologicalOrder = errors.New("topological sort failed") + ErrGraphExecutionCanceled = errors.New("graph execution canceled") + ErrGraphExecutionOptions = errors.New("graph execution options are invalid") + ErrFormatForLogging = errors.New("format affected for logging failed") + ErrQueryEvaluation = errors.New("query evaluation failed") + ErrNilResult = errors.New("nil result") + + // Cache-related errors. + ErrCacheLocked = errors.New("cache file is locked") + ErrCacheRead = errors.New("cache read failed") + ErrCacheWrite = errors.New("cache write failed") + ErrCacheFetch = errors.New("failed to fetch content for cache") + ErrCacheUnmarshal = errors.New("cache unmarshal failed") + ErrCacheMarshal = errors.New("cache marshal failed") + ErrCacheDir = errors.New("cache directory creation failed") + + // Logger errors. + ErrInvalidLogLevel = errors.New("invalid log level") + ErrInvalidLogsColor = errors.New("invalid logs color") + + // File operation errors. + ErrCopyFile = errors.New("failed to copy file") + ErrCreateDirectory = errors.New("failed to create directory") + ErrCreateFile = errors.New("failed to create file") + ErrOpenFile = errors.New("failed to open file") + ErrWriteFile = errors.New("failed to write to file") + ErrCloseFile = errors.New("failed to close file") + ErrStatFile = errors.New("failed to stat file") + ErrRemoveDirectory = errors.New("failed to remove directory") + ErrSetPermissions = errors.New("failed to set permissions") + ErrReadDirectory = errors.New("failed to read directory") + ErrComputeRelativePath = errors.New("failed to compute relative path") + ErrFileOperation = errors.New("file operation failed") + + // Archive extraction safety errors (pkg/filesystem). + ErrArchiveEntryEscapesDest = errors.New("archive entry escapes destination directory") + + // OCI/Container image errors. + ErrCreateTempDirectory = ErrCreateTempDir // Alias to avoid duplicate sentinels + ErrInvalidImageReference = errors.New("invalid image reference") + ErrPullImage = errors.New("failed to pull image") + ErrOCIGetFileUnsupported = errors.New("oci:// sources must be fetched in directory mode, not as a single file") + ErrGetImageDescriptor = errors.New("cannot get a descriptor for the OCI image") + ErrGetImageLayers = errors.New("failed to get image layers") + ErrProcessLayer = errors.New("failed to process layer") + ErrLayerDecompression = errors.New("layer decompression error") + ErrLayerExtraction = errors.New("layer extraction error") + ErrArchiveTooLarge = errors.New("archive exceeds maximum size") + ErrArchiveEntryTooLarge = errors.New("archive entry exceeds maximum extracted size") + + // Initialization and configuration errors. + ErrInitializeCLIConfig = errors.New("error initializing CLI config") + ErrGetHooks = errors.New("error getting hooks") + ErrPerComponentHookFailed = errors.New("per-component hook failed") + ErrSetFlag = errors.New("failed to set flag") + ErrVersionMismatch = errors.New("version mismatch") + + // Download and client errors. + ErrMergeConfiguration = errors.New("failed to merge configuration") + + // Template and documentation errors. + ErrGenerateTerraformDocs = errors.New("failed to generate terraform docs") + ErrMergeInputYAMLs = errors.New("failed to merge input YAMLs") + ErrRenderTemplate = errors.New("failed to render template with datasources") + // ErrGomplateDatasourceUnavailable is returned when a gomplate datasource is read outside a + // template render, or while gomplate functions are disabled, so no datasource registry exists. + ErrGomplateDatasourceUnavailable = errors.New("gomplate datasource functions are unavailable: gomplate is disabled or no template render is in progress") + ErrInvalidDatasourceURL = errors.New("invalid gomplate datasource URL") + ErrResolveOutputPath = errors.New("failed to resolve output path") + ErrWriteOutput = errors.New("failed to write output") + ErrCollectKeysNotMap = errors.New("collectKeys: argument is not a map") + + // Import-related errors. + ErrBasePath = errors.New("base path required to process imports") + ErrTempDir = errors.New("temporary directory required to process imports") + ErrResolveLocal = errors.New("failed to resolve local import path") + ErrSourceDestination = errors.New("source and destination cannot be nil") + ErrImportPathRequired = errors.New("import path required to process imports") + ErrNoFileMatchPattern = errors.New("no files matching patterns found") + ErrMaxImportDepth = errors.New("maximum import depth reached") + ErrNoValidAbsolutePaths = errors.New("no valid absolute paths found") + ErrDownloadRemoteConfig = errors.New("failed to download remote config") + ErrMockImportFailure = errors.New("mock error: simulated import failure") + ErrProcessNestedImports = errors.New("failed to process nested imports") + // ErrRequiredImportFailed is returned when a required (non-optional) CLI-config import + // cannot be resolved or merged. Object-form imports are required by default (fail closed); + // set `skip_if_missing: true` to opt back into warn-and-skip. + ErrRequiredImportFailed = errors.New("required config import failed to load") + // ErrInvalidConfigImport is returned when an object-form CLI-config import entry cannot be + // decoded (e.g. a malformed `skip_if_missing` or `when` value). A malformed entry must fail + // loudly rather than being silently dropped and treated as an optional omission. + ErrInvalidConfigImport = errors.New("invalid config import entry") + + // Profiler-related errors. + ErrProfilerStart = errors.New("profiler start failed") + ErrProfilerUnsupportedType = errors.New("profiler: unsupported profile type") + ErrProfilerStartCPU = errors.New("profiler: failed to start CPU profile") + ErrProfilerStartTrace = errors.New("profiler: failed to start trace profile") + ErrProfilerCreateFile = errors.New("profiler: failed to create profile file") + + // Auth package errors. + ErrAuthNotConfigured = errors.New("authentication not configured in atmos.yaml") + ErrInvalidAuthConfig = errors.New("invalid auth config") + ErrInvalidIdentityKind = errors.New("invalid identity kind") + ErrInvalidIdentityConfig = errors.New("invalid identity config") + ErrInvalidProviderKind = errors.New("invalid provider kind") + ErrInvalidProviderConfig = errors.New("invalid provider config") + ErrInvalidBrowserExecutable = errors.New("invalid browser executable") + ErrAuthenticationFailed = errors.New("authentication failed") + ErrAuthenticationUnavailable = errors.New("authentication unavailable") + ErrPrepareShellEnvironment = errors.New("failed to prepare authenticated shell environment") + ErrInvalidADCContent = errors.New("invalid ADC content") + ErrWriteADCFile = errors.New("failed to write ADC file") + ErrWritePropertiesFile = errors.New("failed to write properties file") + ErrWriteAccessTokenFile = errors.New("failed to write access token file") + ErrPostAuthenticationHookFailed = errors.New("post authentication hook failed") + ErrAuthManager = errors.New("auth manager error") + ErrDefaultIdentity = errors.New("default identity error") + ErrAwsAuth = errors.New("aws auth error") + ErrAwsUserNotConfigured = errors.New("aws user not configured") + ErrAwsUserKeyringReadFailed = errors.New("failed to read AWS user credentials from keyring") + ErrAwsSAMLDecodeFailed = errors.New("aws saml decode failed") + ErrPlaywrightDriverSeed = errors.New("failed to pre-seed the Playwright driver") + ErrAwsMissingEnvVars = errors.New("missing required AWS environment variables") + ErrIdentityNotAWS = errors.New("identity does not produce AWS credentials") + ErrUnsupportedPlatform = errors.New("unsupported platform") + ErrChromeNotFound = errors.New("chrome/chromium not found for isolated browser sessions") + ErrSayNotFound = errors.New("text-to-speech command not found") + ErrVoiceListUnsupported = errors.New("voice enumeration not supported for backend") + ErrUserAborted = errors.New("user aborted") + + // GitHub OIDC provider errors. + // ErrGitHubOIDCEndpointUnavailable marks a token request that failed in a way worth retrying: + // a timeout or other transport error, HTTP 429, or HTTP 5xx. + ErrGitHubOIDCEndpointUnavailable = errors.New("GitHub OIDC token endpoint unavailable") + + // AWS credential_process errors (consuming and producing the AWS process-credential format). + ErrCredentialProcessFailed = errors.New("credential_process command failed") + ErrCredentialProcessInvalidOutput = errors.New("credential_process returned invalid output") + ErrCredentialProcessRecursion = errors.New("credential_process recursion detected") + // ErrCredentialProcessIdentityRequired is returned when the credential-process producer is not + // given a concrete identity (it never opens the interactive selector, which the AWS CLI hides). + ErrCredentialProcessIdentityRequired = errors.New("credential_process requires a specific identity") + // ErrAWSCredentialsIncomplete is returned when AWS credentials lack an access key ID or secret access key. + ErrAWSCredentialsIncomplete = errors.New("AWS credentials are missing an access key ID or secret access key") + + // AWS SSO specific errors. + ErrSSOSessionExpired = errors.New("aws sso session expired") + ErrSSODeviceAuthFailed = errors.New("aws sso device authorization failed") + ErrSSOTokenCreationFailed = errors.New("aws sso token creation failed") + ErrSSOAccountListFailed = errors.New("failed to list aws sso accounts") + ErrSSORoleListFailed = errors.New("failed to list aws sso roles") + ErrSSOProvisioningFailed = errors.New("aws sso identity provisioning failed") + ErrSSOInvalidToken = errors.New("invalid aws sso token") + + // AWS browser webflow errors. + ErrWebflowAuthFailed = errors.New("browser authentication failed") + ErrWebflowDisabled = errors.New("browser authentication is disabled") + ErrWebflowTokenExchange = errors.New("failed to exchange authorization code for credentials") + ErrWebflowCallbackServer = errors.New("failed to start local callback server") + ErrWebflowTimeout = errors.New("browser authentication timed out") + ErrWebflowRefreshFailed = errors.New("failed to refresh browser credentials") + // ErrWebflowRefreshTokenRevoked indicates the refresh token has been definitively + // rejected by the AWS signin service (e.g. HTTP 400 invalid_grant/invalid_token). + // This is the only condition under which the cached refresh token should be deleted; + // transient failures (HTTP 5xx, 429, network errors) must preserve the cache. + ErrWebflowRefreshTokenRevoked = errors.New("browser refresh token has been revoked") + ErrWebflowCodeRequired = errors.New("authorization code is required") + ErrWebflowReadAuthCodeFailed = errors.New("failed to read authorization code") + ErrWebflowAuthorizationError = errors.New("authorization error") + ErrWebflowMissingCallbackCode = errors.New("missing authorization code in callback") + ErrWebflowStateMismatch = errors.New("state mismatch: possible CSRF attack") + ErrWebflowEmptyCachedToken = errors.New("cached refresh token is empty") + // ErrWebflowDPoP indicates a failure generating or serializing the RFC 9449 + // DPoP proof required on AWS signin token requests (issue #2542). + ErrWebflowDPoP = errors.New("failed to build DPoP proof") + + // Credential errors. + ErrCredentialsInvalid = errors.New("credentials are invalid or have been revoked") + ErrInvalidDuration = duration.ErrInvalid // Alias so errors.Is matches pkg/duration errors. + + // Auth manager and identity/provider resolution errors (centralized sentinels). + ErrFailedToInitializeAuthManager = errors.New("failed to initialize auth manager") + ErrNoCredentialsFound = errors.New("no credentials found for identity") + ErrExpiredCredentials = errors.New("credentials for identity are expired or invalid") + ErrNilParam = errors.New("parameter cannot be nil") + ErrInitializingProviders = errors.New("failed to initialize providers") + ErrInitializingIdentities = errors.New("failed to initialize identities") + ErrInitializingCredentialStore = errors.New("failed to initialize credential store") + ErrCircularDependency = errors.New("circular dependency detected in identity chain") + ErrIdentityNotFound = errors.New("identity not found") + ErrProviderNotFound = errors.New("provider not found") + ErrMutuallyExclusiveFlags = errors.New("mutually exclusive flags provided") + ErrNoDefaultIdentity = errors.New("no default identity configured for authentication") + ErrMultipleDefaultIdentities = errors.New("multiple default identities found") + ErrNoIdentitiesAvailable = errors.New("no identities available") + ErrNoProvidersAvailable = errors.New("no providers available") + ErrNoIdentitiesMatchTags = errors.New("no identities match the specified tags") + ErrNoProvidersMatchTags = errors.New("no providers match the specified tags") + ErrNoDefaultProvider = errors.New("no default provider configured and multiple providers exist") + ErrIdentitySelectionRequiresTTY = fmt.Errorf("interactive identity selection: %w", ErrTTYRequired) + ErrProviderSelectionRequiresTTY = fmt.Errorf("interactive provider selection: %w", ErrTTYRequired) + ErrAuthPromptUnavailable = fmt.Errorf("interactive authentication prompt unavailable: %w", ErrTTYRequired) + ErrAuthenticationChainNotBuilt = errors.New("authentication chain not built") + ErrInvalidStackConfig = errors.New("invalid stack config") + ErrNoCommandSpecified = errors.New("no command specified") + ErrCommandNotFound = errors.New("command not found") + ErrCommandFailed = errors.New("command execution failed") + + // Auth validation errors - specific sentinel errors for configuration validation. + ErrMissingPrincipal = errors.New("principal is required") + ErrMissingAssumeRole = errors.New("assume_role is required in principal") + ErrMissingPermissionSet = errors.New("permission set name is required in principal") + ErrMissingAccountSpec = errors.New("account specification is required in principal") + + ErrInvalidSubcommand = errors.New("invalid subcommand") + ErrSubcommandFailed = errors.New("subcommand failed") + + ErrInvalidArgumentError = errors.New("invalid argument error") + ErrMissingInput = errors.New("missing input") + + ErrAuthAwsFileManagerFailed = errors.New("failed to create AWS file manager") + + ErrAuthOidcDecodeFailed = errors.New("failed to decode OIDC token") + ErrAuthOidcUnmarshalFailed = errors.New("failed to unmarshal oidc claims") + + // Realm errors. + ErrFailedToComputeRealm = errors.New("failed to compute realm") + ErrInvalidRealm = errors.New("invalid realm value") + ErrEmptyRealm = errors.New("realm is required for credential isolation but was not set") + + // Logout errors. + ErrFailedGetConfigDir = errors.New("failed to get config directory") + ErrFailedDiscoverRealms = errors.New("failed to discover realms") + ErrFailedRemoveRealm = errors.New("failed to remove realm") + + // Store and hook errors. + ErrNilTerraformOutput = errors.New("terraform output returned nil") + ErrNilStoreValue = errors.New("cannot store nil value") + + // Devcontainer errors. + ErrDevcontainerNotFound = errors.New("devcontainer not found") + ErrContainerRuntimeOperation = errors.New("container runtime operation failed") + ErrContainerNotFound = errors.New("container not found") + ErrContainerAlreadyExists = errors.New("container already exists") + ErrContainerNotRunning = errors.New("container is not running") + ErrContainerRunning = errors.New("container is running") + ErrContainerNotHealthy = errors.New("container did not become healthy") + ErrInvalidDevcontainerConfig = errors.New("invalid devcontainer configuration") + ErrRuntimeNotAvailable = errors.New("container runtime not available") + ErrDevcontainerNameEmpty = errors.New("devcontainer name cannot be empty") + ErrDevcontainerNameInvalid = errors.New("devcontainer name contains invalid characters") + ErrDevcontainerNameTooLong = errors.New("devcontainer name is too long") + ErrPTYNotSupported = errors.New("PTY not supported on this platform") + + // Container bulk-operation errors. + ErrNoContainerComponentSelected = errors.New("no container component selected") + ErrContainerComponentWithAll = errors.New("cannot combine a component argument with --all") + + // Container run configuration errors. + ErrInvalidContainerRestartPolicy = errors.New("invalid container restart policy") + ErrInvalidContainerHealthCheck = errors.New("invalid container healthcheck") + + // Logout errors. + ErrLogoutFailed = errors.New("logout failed") + ErrPartialLogout = errors.New("partial logout") + ErrLogoutNotSupported = errors.New("logout not supported for this provider") + ErrLogoutNotImplemented = errors.New("logout not implemented for this provider") + ErrKeyringDeletion = errors.New("keyring deletion failed") + ErrKeychainDeletionRequiresConfirmation = errors.New("keychain deletion requires interactive confirmation or --force flag") + ErrProviderLogout = errors.New("provider logout failed") + ErrIdentityLogout = errors.New("identity logout failed") + ErrIdentityNotInConfig = errors.New("identity not found in configuration") + ErrProviderNotInConfig = errors.New("provider not found in configuration") + ErrInvalidLogoutOption = errors.New("invalid logout option") + + // Provision target (delivery destination) errors. + ErrProvisionTargetNotFound = errors.New("provision target not found") + ErrProvisionTargetKindUnknown = errors.New("provision target kind is not registered") + ErrProvisionTargetKindMissing = errors.New("provision target is missing a kind") + ErrProvisionTargetNoFetch = errors.New("provision target kind does not support reading current state") + + // Git target pull-request publishing errors. + ErrGitTargetPullRequestConfig = errors.New("invalid git target pull_request configuration") + + // Backend provisioning errors. + ErrBucketRequired = errors.New("backend.bucket is required") + ErrRegionRequired = errors.New("backend.region is required") + ErrBackendNotFound = errors.New("backend configuration not found") + ErrProvisioningNotConfigured = errors.New("provisioning not configured") + ErrCreateNotImplemented = errors.New("create not implemented for backend type") + ErrInvalidBucketNamespace = errors.New("provision.backend.bucket_namespace must be a string") + ErrUnsupportedBucketNamespace = errors.New("unsupported provision.backend.bucket_namespace value") + ErrDeleteNotImplemented = errors.New("delete not implemented for backend type") + ErrProvisionerFailed = errors.New("provisioner failed") + ErrLoadAWSConfig = errors.New("failed to load AWS config") + ErrCheckBucketExist = errors.New("failed to check bucket existence") + ErrCreateBucket = errors.New("failed to create bucket") + ErrApplyBucketDefaults = errors.New("failed to apply bucket defaults") + ErrEnableVersioning = errors.New("failed to enable versioning") + ErrEnableEncryption = errors.New("failed to enable encryption") + ErrBlockPublicAccess = errors.New("failed to block public access") + ErrApplyTags = errors.New("failed to apply tags") + ErrForceRequired = errors.New("--force flag required for backend deletion") + ErrBucketNotEmpty = errors.New("bucket contains objects and cannot be deleted") + ErrStateFilesExist = errors.New("bucket contains terraform state files") + ErrDeleteObjects = errors.New("failed to delete objects from bucket") + ErrDeleteBucket = errors.New("failed to delete bucket") + ErrListObjects = errors.New("failed to list bucket objects") + + // Azure (azurerm) backend provisioning errors. + ErrResourceGroupRequired = errors.New("backend.resource_group_name is required for azurerm backend provisioning") + ErrAzureSubscriptionRequired = errors.New("an Azure subscription id is required for azurerm backend provisioning (set backend.subscription_id or a subscription on the active Azure identity)") + ErrAzureLocationRequired = errors.New("an Azure location is required to create the resource group for azurerm backend provisioning") + ErrLoadAzureConfig = errors.New("failed to build Azure client for backend provisioning") + ErrCheckResourceGroupExist = errors.New("failed to check Azure resource group existence") + ErrCreateResourceGroup = errors.New("failed to create Azure resource group") + ErrCheckStorageAccountExist = errors.New("failed to check Azure storage account existence") + ErrCreateStorageAccount = errors.New("failed to create Azure storage account") + ErrApplyBlobDataProtection = errors.New("failed to apply Azure blob data-protection defaults") + ErrCheckContainerExist = errors.New("failed to check Azure storage container existence") + ErrCreateStorageContainer = errors.New("failed to create Azure storage container") + ErrDeleteStorageAccount = errors.New("failed to delete Azure storage account") + + // Component path resolution errors. + ErrPathNotInComponentDir = errors.New("path is not within Atmos component directories") + ErrComponentTypeMismatch = errors.New("path component type does not match command") + ErrComponentNotInStack = errors.New("component not found in stack configuration") + ErrPathResolutionFailed = errors.New("failed to resolve component from path") + ErrPathIsComponentBase = errors.New("must specify a component directory, not the base directory") + ErrAmbiguousComponentPath = errors.New("ambiguous component path") + ErrComponentPathNotFound = errors.New("component path does not exist") + + // Interactive prompt errors. + ErrInteractiveModeNotAvailable = errors.New("interactive mode not available") + ErrNoOptionsAvailable = errors.New("no options available") + + // Locals-related errors. + ErrLocalsInvalidType = errors.New("locals must be a map") + ErrLocalsCircularDep = errors.New("circular dependency in locals") + ErrLocalsDependencyExtract = errors.New("failed to extract dependencies for local") + ErrLocalsResolution = errors.New("failed to resolve local") + ErrLocalsYamlFunctionFailed = errors.New("failed to process YAML function in local") + + // Init and scaffold errors. + ErrScaffoldNotFound = errors.New("scaffold template not found") + ErrScaffoldValidation = errors.New("scaffold validation failed") + ErrScaffoldGeneration = errors.New("scaffold generation failed") + ErrInitialization = errors.New("initialization failed") + ErrTemplateProcessing = errors.New("template processing failed") + ErrInvalidScaffoldConfig = errors.New("invalid scaffold configuration") + ErrTargetDirectoryExists = errors.New("target directory already exists") + ErrTargetDirectoryNotEmpty = errors.New("target directory is not empty") + ErrScaffoldParseYAML = errors.New("failed to parse scaffold YAML") + ErrPromptFailed = errors.New("interactive prompt failed") + + // Manifest registry errors (pkg/manifest). + ErrManifestKindUnknown = errors.New("unknown manifest kind") + ErrManifestKindEmpty = errors.New("manifest kind is empty") + ErrManifestKindMismatch = errors.New("manifest kind mismatch") + ErrManifestAPIVersion = errors.New("unsupported manifest apiVersion") + ErrManifestParse = errors.New("failed to parse manifest") + ErrManifestPrototypeNil = errors.New("manifest prototype is nil") + ErrManifestSchemaGenerate = errors.New("failed to generate manifest JSON schema") + ErrManifestValidation = errors.New("manifest validation failed") +) diff --git a/errors/errors_integrations.go b/errors/errors_integrations.go new file mode 100644 index 00000000000..ea090e11d2e --- /dev/null +++ b/errors/errors_integrations.go @@ -0,0 +1,392 @@ +package errors + +import ( + "errors" +) + +var ( + // Generator errors. + ErrReadTemplatesDirectory = errors.New("failed to read templates directory") + ErrReadTemplateFiles = errors.New("failed to read template files") + ErrReadTargetDirectory = errors.New("failed to read target directory") + ErrInvalidBaseRef = errors.New("invalid base reference") + ErrTemplateExecution = errors.New("template execution failed") + ErrDirectoryCreation = errors.New("directory creation failed") + ErrFileExists = errors.New("file already exists") + ErrFileWrite = errors.New("file write failed") + ErrUnprocessedTemplate = errors.New("unprocessed template variable found") + ErrThreeWayMerge = errors.New("three-way merge failed") + ErrMergeConflict = errors.New("merge conflict detected") + ErrCreateIOContext = errors.New("failed to create IO context") + ErrLoadScaffoldTemplates = errors.New("failed to load scaffold templates") + ErrResolveTargetDirectory = errors.New("failed to resolve target directory") + ErrScaffoldInvalidPrompt = errors.New("invalid scaffold prompt configuration") + ErrCreateGeneratorContext = errors.New("failed to create generator context") + ErrReadScaffoldConfig = errors.New("failed to read scaffold configuration") + ErrTargetDirRequired = errors.New("target directory is required") + ErrTemplateNameRequired = errors.New("template name is required") + ErrScaffoldFileNotFound = errors.New("scaffold file not found") + ErrInvalidScaffoldFile = errors.New("invalid scaffold file") + ErrScaffoldDirectoryRead = errors.New("failed to read scaffold directory") + ErrScaffoldReadFile = errors.New("failed to read scaffold file") + ErrScaffoldMissingName = errors.New("scaffold is missing required name field") + ErrScaffoldMergeTemplates = errors.New("failed to merge scaffold templates") + ErrScaffoldLoadFromFS = errors.New("failed to load scaffold from filesystem") + ErrScaffoldCreateFromPath = errors.New("failed to create scaffold from path") + ErrScaffoldSelectTemplate = errors.New("failed to select scaffold template") + ErrScaffoldDryRunValues = errors.New("failed to load dry run values") + ErrScaffoldRenderFilePath = errors.New("failed to render file path") + ErrScaffoldValidateSingleFile = errors.New("scaffold file validation failed") + ErrScaffoldFilesNotUnique = errors.New("scaffold files must be unique") + ErrScaffoldTemplatesNotAvailable = errors.New("scaffold templates not available") + ErrScaffoldLoadConfig = errors.New("failed to load scaffold configuration") + ErrInvalidTemplateData = errors.New("invalid template data") + ErrMergeThresholdExceeded = errors.New("merge threshold exceeded") + ErrNoCommonAncestor = errors.New("no common ancestor found") + ErrUnknownMergeStrategy = errors.New("unknown merge strategy") + ErrUnknownMergeDriver = errors.New("unknown merge driver") + ErrUnknownUpdateStrategy = errors.New("unknown update strategy") + ErrRenderedStrategyRequiresConfig = errors.New("--update-strategy=rendered requires a recorded scaffold configuration") + ErrUpdateStrategySwitchedToRendered = errors.New("project was last updated with --update-strategy=tracked") + ErrUpdateStrategySwitchedToTracked = errors.New("project was last updated with --update-strategy=rendered") + ErrRenderedBaseNotConfigured = errors.New("--update-strategy=rendered's base source was never resolved") + ErrRenderedStrategyUnsupportedSource = errors.New("--update-strategy=rendered is not supported for this template source") + ErrGeneratorFieldRequired = errors.New("field is required") + ErrDuplicateScaffoldFieldName = errors.New("duplicate scaffold field name") + ErrScaffoldConfigMissing = errors.New("scaffold configuration not found") + ErrInitializationPartialFailure = errors.New("initialization partially failed") + ErrInitTemplateNotFound = errors.New("init template not found") + ErrInvalidScaffoldSection = errors.New("invalid scaffold section") + ErrScaffoldFetchSource = errors.New("failed to fetch scaffold source") + ErrScaffoldCatalogLoad = errors.New("failed to load scaffold catalog") + ErrTemplateConfigNameRequired = errors.New("template config with metadata.name is required to write a project record") + ErrPathTraversal = errors.New("path traversal not allowed") + ErrSymlinkWrite = errors.New("refusing to write through a symlink") + ErrMetadataLoad = errors.New("failed to load init metadata") + ErrMetadataSave = errors.New("failed to save init metadata") + ErrScaffoldHookKindUnsupported = errors.New("scaffold hook kind not supported") + ErrScaffoldMatrixTargetRequired = errors.New("matrix requires target") + ErrScaffoldMatrixAxisInvalid = errors.New("matrix axis must be a non-empty list, a dot-path string into answers, or a template expression") + ErrScaffoldMatrixSourceNotFound = errors.New("matrix axis source not found in answers") + ErrScaffoldMatrixSourceNotList = errors.New("matrix axis source did not resolve to a list") + ErrScaffoldMatrixExpressionFailed = errors.New("matrix axis expression failed to render") + ErrScaffoldMatrixAxisValueNotScalar = errors.New("matrix axis value is not scalar") + ErrScaffoldDuplicateOutputPath = errors.New("two files rendered to the same output path") + ErrScaffoldFieldOptionsInvalid = errors.New("field options must be a static list, an answers.* dot-path, or a template expression") + ErrScaffoldExpressionFailed = errors.New("template expression failed to render") + ErrScaffoldFilePathPatternInvalid = errors.New("file path glob pattern is malformed") + ErrScaffoldMatrixTargetMissingFileContext = errors.New("matrix target must reference .file.Path or .file.RelPath when its path matches more than one file") + ErrScaffoldComputedFieldInvalid = errors.New("computed field is misconfigured") + ErrScaffoldComputedFieldNotSettable = errors.New("computed field cannot be set") + ErrScaffoldFileDelimitersInvalid = errors.New("spec.files[].delimiters must be exactly two non-empty strings") + + // Source provisioner errors. + ErrSourceProvision = errors.New("source provisioning failed") + ErrSourceNotFound = errors.New("source not found") + ErrSourceAccessDenied = errors.New("source access denied") + ErrSourceInvalidSpec = errors.New("invalid source specification") + ErrSourceAlreadyVendored = errors.New("source already vendored") + ErrSourceCacheOperation = errors.New("source cache operation failed") + ErrSourceCopyFailed = errors.New("failed to copy source files") + ErrSourceMissing = errors.New("source not configured for component") + + // Workdir provisioner errors. + ErrSourceDownload = errors.New("failed to download component source") + ErrSourceCacheRead = errors.New("failed to read source cache") + ErrSourceCacheWrite = errors.New("failed to write source cache") + ErrInvalidSource = errors.New("invalid source configuration") + ErrWorkdirCreation = errors.New("failed to create working directory") + ErrWorkdirSync = errors.New("failed to sync files to working directory") + ErrWorkdirMetadata = errors.New("failed to read/write workdir metadata") + ErrWorkdirProvision = errors.New("workdir provisioning failed") + ErrWorkdirClean = errors.New("failed to clean working directory") + ErrWorkdirIdentityMismatch = errors.New("legacy workdir belongs to a different component/stack") + + // Integration errors. + ErrIntegrationNotFound = errors.New("integration not found") + ErrUnknownIntegrationKind = errors.New("unknown integration kind") + ErrIntegrationFailed = errors.New("integration execution failed") + ErrNoLinkedIntegrations = errors.New("identity has no linked integrations") + + // ECR authentication errors. + ErrECRAuthFailed = errors.New("ECR authentication failed") + ErrECRTokenExpired = errors.New("ECR authorization token expired") + ErrECRRegistryNotFound = errors.New("ECR registry not found") + ErrECRInvalidRegistry = errors.New("invalid ECR registry URL") + ErrECRLoginNoArgs = errors.New("specify an server name, --identity, or --registry") + ErrECRLoginFailed = errors.New("ECR login failed") + ErrDockerConfigWrite = errors.New("failed to write Docker config") + ErrDockerConfigRead = errors.New("failed to read Docker config") + + // ECR Public authentication errors. + ErrECRPublicAuthFailed = errors.New("ECR Public authentication failed") + ErrECRPublicInvalidRegion = errors.New("invalid ECR Public region: only us-east-1 and us-west-2 are supported") + + // EKS server errors. + ErrEKSDescribeCluster = errors.New("failed to describe EKS cluster") + ErrEKSClusterNotFound = errors.New("EKS cluster not found") + ErrEKSIntegrationFailed = errors.New("EKS integration failed") + ErrEKSTokenGeneration = errors.New("failed to generate EKS token") + ErrKubeconfigPath = errors.New("failed to determine kubeconfig path") + ErrKubeconfigWrite = errors.New("failed to write kubeconfig") + ErrKubeconfigMerge = errors.New("failed to merge kubeconfig") + + // AKS server errors. + ErrAKSDescribeCluster = errors.New("failed to describe AKS cluster") + ErrAKSClusterNotFound = errors.New("AKS cluster not found") + ErrAKSClusterAmbiguous = errors.New("AKS cluster resource ID is ambiguous") + ErrAKSClusterNotAADEnabled = errors.New("AKS cluster is not AAD-enabled") + ErrAKSIntegrationFailed = errors.New("AKS integration failed") + ErrAKSTokenGeneration = errors.New("failed to generate AKS token") + + // GKE server errors. + ErrGKEDescribeCluster = errors.New("failed to describe GKE cluster") + ErrGKEClusterNotFound = errors.New("GKE cluster not found") + ErrGKEIntegrationFailed = errors.New("GKE integration failed") + ErrGKETokenGeneration = errors.New("failed to generate GKE token") + + // ACR authentication errors. + ErrACRAuthFailed = errors.New("ACR authentication failed") + ErrACRTokenExpired = errors.New("ACR authorization token expired") + ErrACRRegistryNotFound = errors.New("ACR registry not found") + ErrACRInvalidRegistry = errors.New("invalid ACR registry URL") + ErrACRLoginNoArgs = errors.New("specify an integration, --identity, or --registry") + ErrACRLoginFailed = errors.New("ACR login failed") + + // Atmos Pro authentication (atmos/pro provider) errors. + ErrProAuthFailed = errors.New("authentication to Atmos Pro failed") + ErrProWorkspaceIDMissing = errors.New("workspace ID for Atmos Pro is required (set via auth provider spec.workspace_id, settings.pro.workspace_id, or ATMOS_PRO_WORKSPACE_ID)") + ErrProCredentialsType = errors.New("expected Atmos Pro credentials") + + // GitHub STS integration (github/sts) errors. + ErrSTSMintFailed = errors.New("failed to mint GitHub STS tokens") + ErrSTSNoEntitlement = errors.New("workspace is not entitled to GitHub STS or the feature is disabled") + ErrNotGitHubActionsSession = errors.New("GitHub STS requires a GitHub Actions session") + ErrGitHubTokenRevokeFailed = errors.New("failed to revoke GitHub installation token") + ErrGitSTSStateWrite = errors.New("failed to write GitHub STS state") + ErrGitSTSStateRead = errors.New("failed to read GitHub STS state") + + // Integration via configuration errors. + ErrIntegrationViaMissing = errors.New("integration must define via.identity or via.provider") + ErrIntegrationViaAmbiguous = errors.New("integration must define exactly one of via.identity or via.provider") + + // Identity authentication errors. + ErrIdentityAuthFailed = errors.New("failed to authenticate identity") + ErrIdentityCredentialsNone = errors.New("credentials not available for identity") + + // CI-related errors. + ErrCIDisabled = errors.New("CI server is disabled") + ErrCIProviderNotDetected = errors.New("CI provider not detected") + ErrCIProviderNotFound = errors.New("CI provider not found") + ErrCIOperationNotSupported = errors.New("operation not supported by CI provider") + ErrCICheckRunCreateFailed = errors.New("failed to create check run") + ErrCICheckRunUpdateFailed = errors.New("failed to update check run") + ErrCICheckRunMissingComponent = errors.New("check run requires a resolved component and stack") + ErrCIStatusContextIncomplete = errors.New("status context requires all parts to be non-empty") + ErrCIStatusFetchFailed = errors.New("failed to fetch CI status") + ErrCILabelsFetchFailed = errors.New("failed to fetch CI review labels") + ErrCIMergedPRLookupFailed = errors.New("failed to look up the pull request merged as this commit") + ErrCIOutputWriteFailed = errors.New("failed to write CI output") + ErrCISummaryWriteFailed = errors.New("failed to write CI summary") + ErrCIAnnotationFailed = errors.New("failed to emit CI annotations") + ErrCISARIFUploadFailed = errors.New("failed to upload SARIF to CI provider") + ErrCICommentPostFailed = errors.New("failed to post PR comment") + ErrCICommentListFailed = errors.New("failed to list PR comments") + ErrCICommentUpdateFailed = errors.New("failed to update PR comment") + ErrCICommentNotFound = errors.New("PR comment not found") + ErrCIEnvWriteFailed = errors.New("failed to write CI environment file") + ErrCIMaskFailed = errors.New("failed to register CI mask value") + ErrCIPullRequestUnknown = errors.New("CI pull request number is unknown") + ErrCITemplateNotFound = errors.New("CI report template not found") + ErrGitHubTokenNotFound = errors.New("GitHub token not found") + + // Planfile storage errors. + ErrPlanfileNotFound = errors.New("planfile not found") + ErrPlanfileUploadFailed = errors.New("failed to upload planfile") + ErrPlanfileDownloadFailed = errors.New("failed to download planfile") + ErrPlanfileDeleteFailed = errors.New("failed to delete planfile") + ErrPlanfileListFailed = errors.New("failed to list planfiles") + ErrPlanfileStoreNotFound = errors.New("planfile store not found") + ErrPlanfileKeyInvalid = errors.New("planfile key generation failed: stack, component, and SHA are required") + ErrPlanfileStatFailed = errors.New("failed to check planfile status") + ErrPlanfileMetadataFailed = errors.New("failed to load planfile metadata") + ErrPlanfileMetadataInvalid = errors.New("planfile metadata validation failed: stack, component, and SHA are required") + ErrArtifactMetadataInvalid = errors.New("artifact metadata validation failed: stack, component, and SHA are required") + ErrPlanfileStoreInvalidArgs = errors.New("invalid planfile store arguments") + ErrPlanfileDeleteRequireForce = errors.New("deletion requires --force flag") + ErrAWSConfigLoadFailed = errors.New("failed to load AWS configuration") + + // Artifact storage errors. + ErrArtifactNotFound = errors.New("artifact not found") + ErrArtifactUploadFailed = errors.New("failed to upload artifact") + ErrArtifactDownloadFailed = errors.New("failed to download artifact") + ErrArtifactDeleteFailed = errors.New("failed to delete artifact") + ErrArtifactListFailed = errors.New("failed to list artifacts") + ErrArtifactStoreNotFound = errors.New("artifact store not found") + ErrArtifactStoreInvalidArgs = errors.New("invalid artifact store arguments") + ErrArtifactMetadataFailed = errors.New("failed to load artifact metadata") + ErrArtifactIntegrityFailed = errors.New("artifact integrity check failed") + + // CI cache errors. + ErrCacheUnavailable = errors.New("CI cache is not available in this environment") + ErrCacheNotFound = errors.New("cache entry not found") + ErrCacheAlreadyExists = errors.New("cache entry already exists") + ErrCacheSaveFailed = errors.New("failed to save cache entry") + ErrCacheRestoreFailed = errors.New("failed to restore cache entry") + ErrCacheDeleteFailed = errors.New("failed to delete cache entry") + ErrCacheListFailed = errors.New("failed to list cache entries") + ErrCacheBackendNotFound = errors.New("cache backend not found") + ErrCacheInvalidArgs = errors.New("invalid cache arguments") + ErrCacheKeyRequired = errors.New("cache key is required") + ErrCachePathsRequired = errors.New("cache paths are required") + ErrCacheArchiveFailed = errors.New("failed to build cache archive") + ErrCacheExtractFailed = errors.New("failed to extract cache archive") + ErrCacheBackendRequest = errors.New("cache backend request failed") + + // AI-related errors. + ErrAINotEnabled = errors.New("AI features are not enabled") + ErrAIDisabledInConfiguration = errors.New("AI features are disabled in configuration") + ErrAIAPIKeyNotFound = errors.New("API key not found in environment variable") + ErrAIInsecureBaseURL = errors.New("insecure base_url: an API key would be sent in cleartext over http") + ErrAINoStackFilesFound = errors.New("no stack files found") + ErrAIUnsupportedProvider = errors.New("unsupported AI provider") + ErrAIClientNil = errors.New("AI client cannot be nil") + ErrAINoResponseCandidates = errors.New("no response candidates returned") + ErrAINoResponseContent = errors.New("no content in response") + ErrAIResponseNotText = errors.New("response part does not contain text") + ErrAINoResponseChoices = errors.New("no response choices returned") + ErrAISessionNotFound = errors.New("AI session not found") + ErrAISessionAlreadyExists = errors.New("AI session already exists") + ErrAIToolNotFound = errors.New("AI tool not found") + ErrAIToolExecutionDenied = errors.New("AI tool execution denied by user") + ErrAIToolExecutionFailed = errors.New("AI tool execution failed") + ErrAIToolParameterRequired = errors.New("tool parameter is required") + ErrAIToolNameEmpty = errors.New("tool name cannot be empty") + ErrAIToolAlreadyRegistered = errors.New("tool already registered") + ErrAIToolBlocked = errors.New("tool is blocked") + ErrAIToolsDisabled = errors.New("tools are disabled") + ErrAINoPrompter = errors.New("no prompter available") + ErrAIPermissionPromptFailed = errors.New("permission prompt failed") + ErrAISessionsNotEnabled = errors.New("sessions are not enabled in configuration") + ErrAIInvalidDurationFormat = errors.New("invalid duration format") + ErrAIUnsupportedDurationUnit = errors.New("unsupported duration unit") + ErrAIUnsupportedComponentType = errors.New("unsupported component type") + ErrAIFileAccessDeniedComponents = errors.New("access denied: file path must be within components directory") + ErrAIFileAccessDeniedStacks = errors.New("access denied: file path must be within stacks directory") + ErrAIInvalidConfiguration = errors.New("invalid AI configuration") + ErrAINotInitialized = errors.New("AI client not initialized") + ErrAIFileNotFound = errors.New("file not found") + ErrAIPathIsDirectory = errors.New("path is a directory, not a file") + ErrAISessionManagerNotAvailable = errors.New("session manager not available") + ErrAISessionNameEmpty = errors.New("session name cannot be empty") + ErrAISQLitePragmaFailed = errors.New("failed to set SQLite pragma") + ErrAIAgentNil = errors.New("AI agent cannot be nil") + ErrAIAgentNameEmpty = errors.New("AI agent name cannot be empty") + ErrAIAgentNotFound = errors.New("AI agent not found") + ErrAIAgentAlreadyRegistered = errors.New("AI agent already registered") + ErrAISkillNil = errors.New("AI skill cannot be nil") + ErrAISkillNameEmpty = errors.New("AI skill name cannot be empty") + ErrAISkillNotFound = errors.New("AI skill not found") + ErrAISkillAlreadyRegistered = errors.New("AI skill already registered") + ErrAISkillRequiresAIFlag = errors.New("--skill flag requires --ai") + ErrAISkillLoadFailed = errors.New("failed to load AI skills") + ErrAIPromptRequired = errors.New("prompt is required") + ErrAIExecutionFailed = errors.New("AI execution failed") + ErrAISendMessage = errors.New("failed to send message to AI provider") + ErrAIClientCreation = errors.New("failed to create AI client") + ErrAIMarshalRequest = errors.New("failed to marshal AI request") + ErrAIUnmarshalResponse = errors.New("failed to unmarshal AI response") + ErrAIParseToolInput = errors.New("failed to parse tool input") + ErrAILoadAWSConfig = errors.New("failed to load AWS configuration for AI") + ErrAIBaseURLRequired = errors.New("base URL is required for AI provider") + ErrAIAccessDeniedBasePath = errors.New("access denied: file must be within Atmos base path") + ErrAIAccessDeniedSearchPath = errors.New("access denied: search path must be within Atmos base path") + ErrAIUnknownOperation = errors.New("unknown operation") + ErrAISearchTextNotFound = errors.New("search text not found in file") + ErrAILineNumberOutOfRange = errors.New("line number out of range") + ErrAIInvalidLineRange = errors.New("invalid line range") + ErrAICommandEmpty = errors.New("command cannot be empty") + ErrAICommandBlacklisted = errors.New("command is blacklisted for security reasons") + ErrAICommandRmNotAllowed = errors.New("rm with recursive or force flags is not allowed") + ErrAILSPNotEnabled = errors.New("LSP is not enabled") + ErrAIFileDoesNotExist = errors.New("file does not exist") + ErrAIConfigNil = errors.New("cannot switch provider: atmosConfig is nil") + ErrAIInvalidProviderSelection = errors.New("invalid provider selection") + + // AI session checkpoint/compaction errors. + ErrAICompactPlanNil = errors.New("compact plan is nil") + ErrAIUnsupportedExportFormat = errors.New("unsupported export format") + ErrAICheckpointNil = errors.New("checkpoint is nil") + ErrAICheckpointVersionMissing = errors.New("checkpoint version is missing") + ErrAIUnsupportedCheckpointVersion = errors.New("unsupported checkpoint version") + ErrAISessionNameRequired = errors.New("session name is required") + ErrAISessionProviderRequired = errors.New("session provider is required") + ErrAISessionModelRequired = errors.New("session model is required") + ErrAICheckpointNoMessages = errors.New("checkpoint must contain at least one message") + ErrAIMessageRoleRequired = errors.New("message role is required") + ErrAIMessageInvalidRole = errors.New("invalid message role") + ErrAIStatisticsMismatch = errors.New("statistics message count does not match actual messages") + ErrAIUnsupportedCheckpointFormat = errors.New("unsupported checkpoint format") + ErrAIComponentPathNotFound = errors.New("component path not found") + ErrAIComponentPathNotDirectory = errors.New("component path is not a directory") + + // AI MCP config/stack/vendor get-set-delete-format-list tool errors. + ErrAIConfigFileNotFound = errors.New("atmos config file not found") + ErrAIStackConfigPathNotEditable = errors.New("stack config path is not editable without an explicit file") + ErrAIVendorFileNotFound = errors.New("no vendor manifest found") + ErrAICommandNotFound = errors.New("command not found") + ErrAICommandTreeNotConfigured = errors.New("command tree provider is not configured") + ErrAIToolInvalidOutputType = errors.New("invalid output_type: must be one of 'list', 'map', or 'all'") + ErrAINoSchemaForFile = errors.New("no schema registered for this file; pass schema_path explicitly") + + // AWS security and compliance errors. + ErrAWSSecurityNotEnabled = errors.New("security features are not enabled: add 'aws.security.enabled: true' to atmos.yaml") + ErrAWSSecurityNoFindings = errors.New("no security findings found matching the specified filters") + ErrAWSSecurityFetchFailed = errors.New("failed to fetch security findings from AWS") + ErrAWSSecurityMappingFailed = errors.New("failed to map security finding to Atmos component") + ErrAWSSecurityInvalidSeverity = errors.New("invalid severity filter: valid values are CRITICAL, HIGH, MEDIUM, LOW, INFORMATIONAL") + ErrAWSSecurityInvalidSource = errors.New("invalid finding source: valid values are security-hub, config, inspector, guardduty, macie, access-analyzer, all") + ErrAWSSecurityInvalidFramework = errors.New("invalid compliance framework: valid values are cis-aws, pci-dss, soc2, hipaa, nist") + ErrAWSSecurityInvalidFormat = errors.New("invalid output format: valid values are markdown, json, yaml, csv, sarif") + ErrAWSSecurityAnalysisFailed = errors.New("AI analysis of security findings failed") + ErrAWSCredentialsNotValid = errors.New("AWS credentials are not configured or have expired") + + // CLI provider errors. + ErrCLIProviderBinaryNotFound = errors.New("CLI provider binary not found on PATH") + ErrCLIProviderExecFailed = errors.New("CLI provider execution failed") + ErrCLIProviderParseResponse = errors.New("failed to parse CLI provider response") + ErrCLIProviderToolsNotSupported = errors.New("tool execution not supported for CLI providers; use MCP pass-through instead") + ErrCLIProviderEmptyResponse = errors.New("CLI provider returned an empty response") + ErrCLIProviderMaxTurns = errors.New("CLI provider reached its maximum number of turns before answering") + ErrCLIProviderToolDenied = errors.New("CLI provider tool use was not approved") + ErrAIEmptyResponse = errors.New("AI returned an empty response") + ErrAIToolsInvalidMode = errors.New("invalid ai.tools.mode") + + // Web search errors. + ErrWebSearchFailed = errors.New("web search request failed") + ErrWebSearchParseFailed = errors.New("failed to parse web search results") + ErrWebSearchNotEnabled = errors.New("web search is not enabled in configuration") + + // MCP errors. + ErrMCPNotEnabled = errors.New("MCP server is not enabled") + ErrMCPToolNotFound = errors.New("MCP tool not found") + ErrMCPInvalidJSONRPCVersion = errors.New("invalid JSON-RPC version") + ErrMCPInvalidTransport = errors.New("invalid transport type") + ErrMCPUnsupportedTransport = errors.New("unsupported transport") + ErrMCPServerNotFound = errors.New("MCP server not found in configuration") + ErrMCPServerNotRunning = errors.New("MCP server is not running") + ErrMCPServerStartFailed = errors.New("MCP server failed to start") + ErrMCPServerCommandEmpty = errors.New("MCP server command must not be empty") + ErrMCPServerInvalidTimeout = errors.New("MCP server timeout is invalid") + ErrMCPServerToolListFailed = errors.New("failed to list tools from MCP server") + ErrMCPServerToolError = errors.New("MCP server returned error for tool") + ErrMCPConfigWriteFailed = errors.New("failed to write MCP config file") + ErrMCPConfigPermsFailed = errors.New("failed to set MCP config file permissions") + ErrMCPConfigMarshalFailed = errors.New("failed to marshal MCP config") + ErrMCPServerAuthUnavailable = errors.New("MCP server requires identity but auth manager is not available") + ErrLSPInvalidTransport = errors.New("invalid LSP transport type") + ErrLSPConfigNil = errors.New("LSP config is nil") + ErrLSPNoServerForFile = errors.New("no LSP server found for file") + ErrLSPRPCError = errors.New("RPC error") + ErrLSPNoContentLengthHeader = errors.New("no Content-Length header found") +) diff --git a/errors/errors_runtime.go b/errors/errors_runtime.go new file mode 100644 index 00000000000..44510803772 --- /dev/null +++ b/errors/errors_runtime.go @@ -0,0 +1,275 @@ +package errors + +import ( + "errors" + "fmt" +) + +// ErrStarlark identifies embedded Starlark execution or configuration failures. +var ErrStarlark = errors.New("starlark execution failed") + +// ErrScriptRaised identifies an intentional failure raised by a script. +var ErrScriptRaised = errors.New("script raised a failure") + +var ( + // ErrStarlarkInvalidArgument identifies invalid arguments passed to an embedded Starlark builtin. + ErrStarlarkInvalidArgument = errors.New("invalid starlark argument") + // ErrStarlarkTaskTimeout identifies a Starlark task that exceeded its deadline. + ErrStarlarkTaskTimeout = errors.New("starlark task timed out") + // ErrStarlarkProcessFailed identifies a subprocess started by Starlark that failed or never started. + ErrStarlarkProcessFailed = errors.New("starlark process failed") + // ErrStarlarkOutputEncode identifies a top-level Starlark `output` value that cannot be encoded. + ErrStarlarkOutputEncode = errors.New("starlark output encoding failed") + // ErrStarlarkRecursionLimit identifies a Starlark call stack that exceeded the maximum recursion depth. + ErrStarlarkRecursionLimit = errors.New("starlark recursion depth exceeded") + // ErrStarlarkStackIdentity identifies a stack name derived from a !starlark value, which is not computable. + ErrStarlarkStackIdentity = errors.New("stack identity cannot be computed with !starlark") + // ErrScriptUsage identifies command-line input that does not satisfy a standalone script's declared interface. + ErrScriptUsage = errors.New("usage error") +) + +const ( + // ErrWrapFormat is the standard format string for wrapping errors with context. + // Use with fmt.Errorf to wrap a sentinel error with an underlying error: + // fmt.Errorf(ErrWrapFormat, errUtils.ErrSentinel, underlyingErr) + ErrWrapFormat = "%w: %w" + // ErrWrapWithNameFormat is the format string for wrapping errors with a name context. + // Use with fmt.Errorf to wrap a sentinel error with a name: + // fmt.Errorf(ErrWrapWithNameFormat, errUtils.ErrSentinel, name) + ErrWrapWithNameFormat = "%w: %s" + // ErrWrapWithNameAndCauseFormat is the format string for wrapping errors with a name and cause. + // Use with fmt.Errorf to wrap a sentinel error with a name and underlying error: + // fmt.Errorf(ErrWrapWithNameAndCauseFormat, errUtils.ErrSentinel, name, underlyingErr) + ErrWrapWithNameAndCauseFormat = "%w '%s': %w" +) + +// Provision-target authentication errors. +var ( + // ErrProvisionTargetAuthInvalid indicates a provision target's auth block is malformed. + ErrProvisionTargetAuthInvalid = errors.New("provision target auth is invalid") + // ErrProvisionTargetAuthUnknownKey indicates a provision target's auth block has an unsupported key. + ErrProvisionTargetAuthUnknownKey = errors.New("provision target auth has an unsupported key") + // ErrProvisionTargetAuthNoIdentity indicates a provision target's auth block selects no identity. + ErrProvisionTargetAuthNoIdentity = errors.New("provision target auth did not select an identity") + // ErrProvisionTargetAuthFailed indicates the identity a provision target selected could not be used. + ErrProvisionTargetAuthFailed = errors.New("provision target authentication failed") + // ErrAwsCloudFormationTargetAuthFailed indicates a CloudFormation delivery target's own authentication failed. + ErrAwsCloudFormationTargetAuthFailed = errors.New("aws/cloudformation provision target could not authenticate") + // ErrAwsCloudFormationTargetKeyUnsupported indicates a `kind: aws/cloudformation` target has an unsupported key. + ErrAwsCloudFormationTargetKeyUnsupported = errors.New("aws/cloudformation provision target has an unsupported key") +) + +// Stack dependency (`depends_on`) resolution errors. +var ( + // ErrInvalidDependsOn indicates a legacy `settings.spacelift.depends_on` value + // does not resolve to a known stack or to a component in the current stack. + ErrInvalidDependsOn = errors.New("invalid 'depends_on' dependency") + // ErrInvalidSettingsDependsOn indicates a `settings.depends_on` value does not + // resolve to a known component in a known stack. + ErrInvalidSettingsDependsOn = errors.New("invalid 'settings.depends_on' dependency") +) + +// Vendor update/diff errors. +var ( + // ErrComponentUpdaterConfig indicates invalid component updater configuration. + ErrComponentUpdaterConfig = errors.New("invalid component updater configuration") + // ErrComponentUpdaterDirtyWorktree indicates a publisher's Git worktree has uncommitted changes. + ErrComponentUpdaterDirtyWorktree = errors.New("component updater requires a clean Git worktree") + // ErrPullRequestPublisherUnavailable indicates the selected forge integration is not registered. + ErrPullRequestPublisherUnavailable = errors.New("pull request publisher is unavailable") + // ErrGitHubAuthorization indicates an authentication or permission failure from the GitHub API. + ErrGitHubAuthorization = errors.New("GitHub authorization failed") + // ErrPullRequestReconciliation indicates Atmos could not reconcile an existing or new PR. + ErrPullRequestReconciliation = errors.New("pull request reconciliation failed") + // ErrAzureDevOpsTokenNotFound indicates AZURE_DEVOPS_EXT_PAT is not set. + //nolint:staticcheck // Error starts with a proper product name. + ErrAzureDevOpsTokenNotFound = errors.New("Azure DevOps personal access token not found") + // ErrAzureDevOpsAuthorization indicates an authentication or permission failure from the Azure DevOps API. + //nolint:staticcheck // Error starts with a proper product name. + ErrAzureDevOpsAuthorization = errors.New("Azure DevOps authorization failed") + // ErrAzureDevOpsAssigneesUnsupported indicates Azure DevOps pull requests do not support assignees. + //nolint:staticcheck // Error starts with a proper product name. + ErrAzureDevOpsAssigneesUnsupported = errors.New("Azure DevOps pull requests do not support assignees") + // ErrAzureDevOpsNamespaceInvalid indicates PullRequestOptions.Namespace was not exactly the + // single project segment Azure DevOps' organization/project/repository addressing requires. + //nolint:staticcheck // Error starts with a proper product name. + ErrAzureDevOpsNamespaceInvalid = errors.New("Azure DevOps pull request namespace must be exactly one project segment") + // ErrAzureDevOpsReviewerNotFound indicates a configured reviewer's display name, account name, + // or email matched no Azure DevOps identity. + //nolint:staticcheck // Error starts with a proper product name. + ErrAzureDevOpsReviewerNotFound = errors.New("Azure DevOps reviewer identity not found") + // ErrAzureDevOpsReviewerAmbiguous indicates a configured reviewer's display name, account name, + // or email matched more than one Azure DevOps identity. + //nolint:staticcheck // Error starts with a proper product name. + ErrAzureDevOpsReviewerAmbiguous = errors.New("Azure DevOps reviewer identity is ambiguous") + // ErrGitFetchFailed indicates `git fetch` of a base or feature branch failed. + ErrGitFetchFailed = errors.New("git fetch failed") + // ErrGitCheckoutFailed indicates `git checkout` of a feature branch failed. + ErrGitCheckoutFailed = errors.New("git checkout failed") + // ErrGitLocalBranchDiverged indicates a local feature branch has commits absent from both + // the remote feature branch and the base branch. + ErrGitLocalBranchDiverged = errors.New("local branch has unpushed commits") + // ErrGitDefaultBranchResolution indicates the remote's default branch could not be resolved. + ErrGitDefaultBranchResolution = errors.New("remote default branch resolution failed") + + // ErrGitLsRemoteFailed indicates listing refs from a remote Git repository failed. + ErrGitLsRemoteFailed = errors.New("failed to list refs from remote Git repository") + // ErrNoVersionsAvailable indicates no versions were found for a source. + ErrNoVersionsAvailable = errors.New("no versions available") + // ErrNoVersionsMatchConstraints indicates no available version satisfies the configured constraints. + ErrNoVersionsMatchConstraints = errors.New("no versions match the configured constraints") + // ErrInvalidSemverConstraint indicates a constraints.version value is not a valid semver constraint. + ErrInvalidSemverConstraint = errors.New("invalid semver constraint") + // ErrVersionRangeConflictsWithConstraints indicates a source declared both a semver-range + // version: and a constraints.version ceiling. These are mutually exclusive. constraints.version's + // entire purpose is to bound what `atmos vendor update` can bump an *exact* pin to; that purpose + // no longer applies once version: is itself already a range. + ErrVersionRangeConflictsWithConstraints = errors.New("version: is a semver range; constraints.version is also set. These are mutually exclusive; remove one") + // ErrVendorSourceNotFound indicates a requested component/source was not found in the vendor manifest. + ErrVendorSourceNotFound = errors.New("vendor source not found") + // ErrVendorSourceNotGit indicates a vendor source is not a Git repository (unsupported for update/diff). + ErrVendorSourceNotGit = errors.New("vendor source is not a Git repository") + // ErrVendorDiffFailed indicates the vendor diff operation failed. + ErrVendorDiffFailed = errors.New("failed to produce vendor diff") + // ErrVendorUpdateFailed indicates the vendor update operation failed. + ErrVendorUpdateFailed = errors.New("failed to update vendor manifest") + // ErrReadVendorFile indicates a vendor manifest file could not be read. + ErrReadVendorFile = errors.New("failed to read vendor manifest") + // ErrParseVendorFile indicates a vendor manifest file could not be parsed. + ErrParseVendorFile = errors.New("failed to parse vendor manifest") + // ErrInvalidGitRef indicates a Git ref (tag, branch, or commit) could not be resolved. + ErrInvalidGitRef = errors.New("invalid Git ref") + // ErrComponentManifestNotFound indicates no component.yaml/component.yml exists in a component's directory. + ErrComponentManifestNotFound = errors.New("component vendoring manifest not found") + // ErrInvalidComponentManifestKind indicates a component.yaml's "kind" is not "ComponentVendorConfig". + ErrInvalidComponentManifestKind = errors.New("invalid kind in component vendoring manifest; expected ComponentVendorConfig") + // ErrComponentDirNotFound indicates a component's resolved base directory does not exist. + ErrComponentDirNotFound = errors.New("component directory does not exist") + // ErrResolveComponentPath indicates a component's filesystem path could not be resolved + // (path-joining or symlink resolution failed), distinct from ErrComponentDirNotFound's "the + // path resolved fine but nothing exists there". + ErrResolveComponentPath = errors.New("failed to resolve component path") + // ErrDuplicateVendorComponent indicates the same component name is declared more than once + // across a vendor manifest and its imports, matching the rejection normal `vendor pull` + // processing already applies (internal/exec's ErrDuplicateComponentsFound) for the + // --stack/--tags declared-tags resolution path. + ErrDuplicateVendorComponent = errors.New("duplicate component declared in vendor manifest") +) + +// GitHub Enterprise Server (GHES) endpoint resolution errors. +var ( + // ErrInvalidGitHubEndpointURL indicates a GitHub endpoint environment variable + // (e.g. GITHUB_SERVER_URL, GITHUB_API_URL, ATMOS_TOOLCHAIN_GITHUB_URL) could not be + // parsed as an absolute HTTP(S) URL. The resolver falls back to its default rather + // than failing, so this error is logged at debug level, not surfaced to the user. + ErrInvalidGitHubEndpointURL = errors.New("invalid GitHub endpoint URL") +) + +// Release notes update errors. +var ( + // ErrReleaseTagMissing prevents updating notes without a tag to preserve. + ErrReleaseTagMissing = errors.New("release tag is missing") + // ErrReleaseTagMismatch indicates GitHub did not preserve the tag during a notes update. + ErrReleaseTagMismatch = errors.New("release tag changed during notes update") +) + +// Source provisioning, S3 source, and stack-manifest hardening errors (field-test findings, PR #3251). +var ( + // ErrSourceComponentNameInvalid indicates a component name (metadata.component) that cannot be + // used as a source provisioning destination: absolute, volume-qualified, or escaping the + // components directory. + ErrSourceComponentNameInvalid = errors.New("invalid component name for source provisioning") + // ErrSourceDeleteRefused indicates `source delete` declined to remove a directory it cannot + // prove the source provisioner created, or that another component owns. + ErrSourceDeleteRefused = errors.New("refusing to delete source directory") + // ErrS3SourceRegionMismatch indicates an S3 source bucket lives in a different region than the + // one used for the request. + ErrS3SourceRegionMismatch = errors.New("S3 source bucket is in a different region than the request") + // ErrS3SourceForbidden indicates S3 answered 403 for an object probe: either access is denied + // or the key does not exist and the principal lacks s3:ListBucket. + ErrS3SourceForbidden = errors.New("S3 source access was forbidden") + // ErrS3SourceUnsupportedParam indicates an S3 source URL carries credential query parameters + // that the Atmos S3 getter never honors. + ErrS3SourceUnsupportedParam = errors.New("unsupported S3 source authentication parameter") +) + +// GitHub mock test-helper errors (tests/testhelpers/httpmock). +var ( + // ErrMockFailWithTimesNegative indicates a test called FailWithTimes with a negative + // times value. -1 (unlimited failure) is reserved for FailWith/FailWithHeaders; a caller + // that wants an unlimited failure should call one of those instead of FailWithTimes with + // a negative count, which would otherwise silently behave as unlimited. + ErrMockFailWithTimesNegative = errors.New("httpmock: FailWithTimes called with negative times; use FailWith for an unlimited failure") +) + +// CI reporter and provider sentinels. +var ( + // ErrCICommentKeyRequired is returned when a comment asks to update an existing comment but names no key to find it by. + ErrCICommentKeyRequired = errors.New("a comment key is required to update an existing comment") + + // ErrCICommentTargetInvalid is returned when a comment target is not one of auto, pr, or commit. + ErrCICommentTargetInvalid = errors.New("invalid comment target") + + // ErrCICommitUnknown is returned when a commit comment is requested but the commit SHA is unknown. + ErrCICommitUnknown = errors.New("commit SHA is unknown") +) + +// Automation runtime, standalone script, and custom-command input sentinels. +var ( + // ErrScriptHelpShown is returned by cli.command after the host printed the script's help. + // It ends the script without running its remaining statements; the engine reports success. + ErrScriptHelpShown = errors.New("script help shown") + + // ErrLiteralFieldUnsupported is returned when the !literal tag is written on a field that + // does not support it, so the tag cannot be silently ignored. + ErrLiteralFieldUnsupported = errors.New("!literal is not supported") + + // ErrScriptInterrupted is returned when an interrupt (Ctrl-C) ended a standalone script + // after its deferred calls ran. The process exits with the conventional status 130. + ErrScriptInterrupted = errors.New("script interrupted") +) + +// Step library, process cleanup, Git hook, and !starlark sentinels. +var ( + // ErrStarlarkUnsupportedInConfig is returned when `!starlark` appears in atmos.yaml, which only + // stack manifests evaluate. + ErrStarlarkUnsupportedInConfig = errors.New("!starlark is not supported in atmos.yaml") + + // ErrHookRecursionLimit is returned when lifecycle hooks trigger themselves more than the + // allowed number of levels deep. + ErrHookRecursionLimit = errors.New("hook recursion limit exceeded") +) + +// Test step (`type: test`) failure sentinel. +var ErrTestsFailed = errors.New("tests failed") + +// Policy evaluation errors. +var ( + ErrPolicyInvalid = errors.New("invalid policy") + ErrPolicyInputInvalid = errors.New("invalid policy input") + ErrPolicyEngineUnknown = errors.New("policy engine is not registered") + ErrPolicyEngineRegistered = errors.New("policy engine is already registered") + ErrPolicyEvaluation = errors.New("policy evaluation failed") + ErrPolicyInputUnavailable = errors.New("required policy input is unavailable or incomplete") + ErrPolicyDenied = errors.New("policy denied execution") + ErrPolicyRequirements = errors.New("policy requirements are not satisfied") + ErrPolicyPlan = errors.New("saved plan policy enforcement failed") +) + +// ExitCodeError is a typed error that preserves subcommand exit codes. +// This allows the root command to exit with the same code as the subcommand. +// When Code is 0, it indicates successful completion that should exit cleanly without printing errors. +// This avoids deep exits (os.Exit) which are untestable. +type ExitCodeError struct { + Code int + // Silent suppresses themed error rendering: the process exits with Code + // without printing an error box. Used for terminal-handoff steps (tty, + // interactive, exec) where, like a shell, a non-zero exit from the child + // program should propagate the code without Atmos rendering its own error + // (which would query the terminal and can hang when stdin is contended). + Silent bool +} + +func (e ExitCodeError) Error() string { + return fmt.Sprintf("subcommand exited with code %d", e.Code) +} From 2004bd1b1e74aff9894c2e72181e87d0bf9b9b8f Mon Sep 17 00:00:00 2001 From: Erik Osterman Date: Fri, 13 Nov 2026 16:01:50 -0600 Subject: [PATCH 21/28] refactor(errors): simplify formatting and Sentry configuration helpers --- errors/builder.go | 45 +++---- errors/error_funcs.go | 92 ++++++-------- errors/formatter.go | 206 -------------------------------- errors/formatter_render.go | 226 +++++++++++++++++++++++++++++++++++ errors/formatter_test.go | 1 + errors/sentry_registry.go | 238 +++++++++++++++++++------------------ 6 files changed, 405 insertions(+), 403 deletions(-) create mode 100644 errors/formatter_render.go diff --git a/errors/builder.go b/errors/builder.go index ebfc2ebe45c..c0dc9f347b8 100644 --- a/errors/builder.go +++ b/errors/builder.go @@ -133,28 +133,29 @@ func (b *ErrorBuilder) WithLocation(file string, line int) *ErrorBuilder { // - Error message includes "container already running" // - Hints and context from cause are preserved func (b *ErrorBuilder) WithCause(cause error) *ErrorBuilder { - if cause != nil { - // Guard against nil b.err - if no sentinel was provided, use cause directly. - if b.err == nil { - b.err = cause - } else { - // Extract hints from cause before wrapping, since fmt.Errorf - // doesn't preserve cockroachdb hint metadata. - if causeHints := AllHints(cause); len(causeHints) > 0 { - b.hints = append(b.hints, causeHints...) - } - causeDetails := AllDetails(cause) - // Extract context from cause before wrapping, since fmt.Errorf - // doesn't preserve cockroachdb safe details metadata. - b.extractContextFromCause(cause) - // Use fmt.Errorf with double %w to maintain both errors in chain. - // This is compatible with std errors.Is() used by testify's assert.ErrorIs(). - // Note: cockroachdb/errors.Wrap() only works with cockroachdb's errors.Is(), - // not the standard library's, which breaks test assertions. - b.err = fmt.Errorf("%w: %w", b.err, cause) - for _, detail := range causeDetails { - b.err = errors.WithDetail(b.err, detail) - } + if cause == nil { + return b + } + // Guard against nil b.err - if no sentinel was provided, use cause directly. + if b.err == nil { + b.err = cause + } else { + // Extract hints from cause before wrapping, since fmt.Errorf + // doesn't preserve cockroachdb hint metadata. + if causeHints := AllHints(cause); len(causeHints) > 0 { + b.hints = append(b.hints, causeHints...) + } + causeDetails := AllDetails(cause) + // Extract context from cause before wrapping, since fmt.Errorf + // doesn't preserve cockroachdb safe details metadata. + b.extractContextFromCause(cause) + // Use fmt.Errorf with double %w to maintain both errors in chain. + // This is compatible with std errors.Is() used by testify's assert.ErrorIs(). + // Note: cockroachdb/errors.Wrap() only works with cockroachdb's errors.Is(), + // not the standard library's, which breaks test assertions. + b.err = fmt.Errorf("%w: %w", b.err, cause) + for _, detail := range causeDetails { + b.err = errors.WithDetail(b.err, detail) } } return b diff --git a/errors/error_funcs.go b/errors/error_funcs.go index 9e10b4d6292..c5becec7486 100644 --- a/errors/error_funcs.go +++ b/errors/error_funcs.go @@ -120,15 +120,6 @@ func formatStructuredPlainError(err error, title string, suggestion string) stri return out.String() } -// printErrorDetails prints the explanation section from error details. -func printErrorDetails(err error) { - var out strings.Builder - appendErrorDetails(&out, err) - if out.Len() > 0 { - _, _ = os.Stderr.WriteString(out.String()) - } -} - func appendErrorDetails(out *strings.Builder, err error) { details := AllDetails(err) if len(details) == 0 { @@ -140,15 +131,6 @@ func appendErrorDetails(out *strings.Builder, err error) { } } -// printErrorHints prints the hints section, filtering out internal prefixes. -func printErrorHints(err error) { - var out strings.Builder - appendErrorHints(&out, err) - if out.Len() > 0 { - _, _ = os.Stderr.WriteString(out.String()) - } -} - func appendErrorHints(out *strings.Builder, err error) { allHints := AllHints(err) var userHints []string @@ -166,15 +148,6 @@ func appendErrorHints(out *strings.Builder, err error) { } } -// printErrorContext prints the context section from safe details. -func printErrorContext(err error) { - var out strings.Builder - appendErrorContext(&out, err) - if out.Len() > 0 { - _, _ = os.Stderr.WriteString(out.String()) - } -} - func appendErrorContext(out *strings.Builder, err error) { contextPairs := extractContextPairs(err) if len(contextPairs) == 0 { @@ -238,36 +211,7 @@ func CheckErrorAndPrint(err error, title string, suggestion string) { // printFormattedError prints an error using the new formatter. // If title or suggestion are provided, they are incorporated into the formatted output. func printFormattedError(err error, title string, suggestion string) { - // If legacy title or suggestion are provided, incorporate them into the error. - if title != "" || suggestion != "" { - // Wrap error with legacy parameters using error builder. - builder := Build(err) - if suggestion != "" { - // Trim leading/trailing whitespace for analysis. - trimmed := strings.TrimSpace(suggestion) - - // Check if suggestion contains markdown sections (backward compatibility). - // Old code passed suggestions like "\n## Explanation\n..." which should be - // added as explanations, not hints. - if strings.Contains(suggestion, "\n##") || strings.HasPrefix(trimmed, "##") { - // Strip the legacy "## Explanation" header if present. - cleaned := strings.TrimLeft(suggestion, "\n") - cleaned = strings.TrimPrefix(cleaned, "## Explanation\n") - cleaned = strings.TrimPrefix(cleaned, "## Explanation") - cleaned = strings.TrimSpace(cleaned) - builder = builder.WithExplanation(cleaned) - } else { - // Only add as hint if it's not empty after trimming. - // This prevents rendering empty hint lines for suggestions that are - // just whitespace or newlines. - if trimmed != "" { - builder = builder.WithHint(trimmed) - } - } - } - // Note: title is handled by the formatter's title parameter, not as a hint. - err = builder.Err() - } + err = withLegacySuggestion(err, title, suggestion) // Check for --verbose flag (CLI flag > env var > config). verbose := atmosConfig.Errors.Format.Verbose @@ -406,3 +350,37 @@ func WrapComponentDescribeError(component, stack string, err error, context stri // For other errors, preserve the full chain. return fmt.Errorf("%s(%s, %s) failed: %w", context, component, stack, err) } + +// withLegacySuggestion preserves explanations and hints from legacy callers. +func withLegacySuggestion(err error, title, suggestion string) error { + // If legacy title or suggestion are provided, incorporate them into the error. + if title == "" && suggestion == "" { + return err + } + // Wrap error with legacy parameters using error builder. + builder := Build(err) + if suggestion != "" { + // Trim leading/trailing whitespace for analysis. + trimmed := strings.TrimSpace(suggestion) + + // Check if suggestion contains markdown sections (backward compatibility). + // Old code passed suggestions like "\n## Explanation\n..." which should be + // added as explanations, not hints. + if strings.Contains(suggestion, "\n##") || strings.HasPrefix(trimmed, "##") { + // Strip the legacy "## Explanation" header if present. + cleaned := strings.TrimLeft(suggestion, "\n") + cleaned = strings.TrimPrefix(cleaned, "## Explanation\n") + cleaned = strings.TrimPrefix(cleaned, "## Explanation") + cleaned = strings.TrimSpace(cleaned) + builder = builder.WithExplanation(cleaned) + } else if trimmed != "" { + // Only add as hint if it's not empty after trimming. + // This prevents rendering empty hint lines for suggestions that are + // just whitespace or newlines. + builder = builder.WithHint(trimmed) + } + } + // Note: title is handled by the formatter's title parameter, not as a hint. + err = builder.Err() + return err +} diff --git a/errors/formatter.go b/errors/formatter.go index c0c6b8cf613..153d89e969a 100644 --- a/errors/formatter.go +++ b/errors/formatter.go @@ -3,8 +3,6 @@ package errors import ( "fmt" "math" - "os" - "regexp" "strconv" "strings" @@ -12,12 +10,10 @@ import ( "github.com/charmbracelet/lipgloss/table" "github.com/cockroachdb/errors" "github.com/spf13/viper" - "golang.org/x/term" "github.com/cloudposse/atmos/pkg/perf" "github.com/cloudposse/atmos/pkg/schema" "github.com/cloudposse/atmos/pkg/terminal" - terminalenv "github.com/cloudposse/atmos/pkg/terminal/env" "github.com/cloudposse/atmos/pkg/ui/markdown" "github.com/cloudposse/atmos/pkg/ui/theme" ) @@ -679,205 +675,3 @@ func addStackTraceSection(md *strings.Builder, err error, useColor bool) { fmt.Fprintf(md, "%+v", err) md.WriteString(newline + "```" + newline) } - -// renderMarkdown renders markdown string through Glamour with specified width. -// -// This function creates a fresh markdown renderer for each call rather than using -// the global renderer from pkg/ui to ensure: -// 1. The FormatterConfig.MaxLineLength parameter is respected (global renderer may have different width) -// 2. Error formatting works before the UI system is initialized (early startup errors) -// 3. No circular dependencies (pkg/ui imports errors package) -func renderMarkdown(md string, maxLineLength int) (string, bool) { - return renderWith(md, maxLineLength, (*markdown.Renderer).RenderErrorf) -} - -// renderReadableMarkdown renders Markdown as plain text for output without styling. -// It avoids the ASCII preset used for non-TTY stderr, which leaves bold markers -// dangling around inline code and drops code-span backticks. -func renderReadableMarkdown(md string, maxLineLength int) (string, bool) { - return renderWith(md, maxLineLength, func(r *markdown.Renderer, content string, _ ...interface{}) (string, error) { - return r.RenderReadable(content) - }) -} - -func renderWith(md string, maxLineLength int, render func(*markdown.Renderer, string, ...interface{}) (string, error)) (string, bool) { - // Use provided maxLineLength, or fall back to default if not set. - width := maxLineLength - if width <= 0 { - width = DefaultMarkdownWidth - } - - // Always create a fresh renderer with the specified width to ensure - // MaxLineLength parameter is respected. The global renderer may have - // a different width configured. - config := schema.AtmosConfiguration{ - Settings: schema.AtmosSettings{ - Docs: schema.Docs{ - MaxWidth: width, - }, - }, - } - - renderer, err := newMarkdownRendererWithWidth(config, width) - if err != nil { - return "", false - } - - rendered, renderErr := render(renderer, md) - if renderErr == nil { - return rendered, true - } - - return "", false -} - -// formatContextForMarkdown formats context as a markdown table. -// Uses GetAllSafeDetails to traverse the entire error chain. -func formatContextForMarkdown(err error) string { - // Get all safe details from entire error chain, not just top-level. - allDetails := errors.GetAllSafeDetails(err) - var allSafeDetails []string - for _, payload := range allDetails { - allSafeDetails = append(allSafeDetails, payload.SafeDetails...) - } - if len(allSafeDetails) == 0 { - return "" - } - - // Parse "component=vpc stack=prod" format into key-value pairs. - var rows []string - for _, detail := range allSafeDetails { - str := fmt.Sprintf("%v", detail) - pairs := strings.Split(str, " ") - for _, pair := range pairs { - if parts := strings.SplitN(pair, "=", 2); len(parts) == 2 { - rows = append(rows, fmt.Sprintf("| %s | %s |", parts[0], parts[1])) - } - } - } - - // Return empty if no rows were parsed. - if len(rows) == 0 { - return "" - } - - // Build table with header. - var md strings.Builder - md.WriteString("| Key | Value |\n") - md.WriteString("|-----|-------|\n") - for _, row := range rows { - md.WriteString(row + "\n") - } - - return md.String() -} - -// shouldUseColor determines if color output should be used. -// This uses the terminal package's color logic which respects: -// - --no-color, --color, --force-color flags -// - NO_COLOR, CLICOLOR, CLICOLOR_FORCE environment variables -// - settings.terminal.color and settings.terminal.no_color in atmos.yaml -func shouldUseColor() bool { - // Build terminal config from all sources (flags, env vars, atmos.yaml). - termConfig := &terminal.Config{ - NoColor: terminalenv.ResolveNoColor(os.Args[1:], viper.GetBool("no-color")), - Color: viper.GetBool("color"), - ForceColor: viper.GetBool("force-color"), - - EnvNoColor: os.Getenv("NO_COLOR") != "", - EnvCLIColor: os.Getenv("CLICOLOR"), - EnvCLIColorForce: os.Getenv("CLICOLOR_FORCE") != "" || os.Getenv("FORCE_COLOR") != "", - //nolint:forbidigo // CI is the standard environment signal used by terminal color detection. - EnvCI: os.Getenv("CI") != "", - } - - // Add atmos.yaml settings if available. - if atmosConfig != nil { - termConfig.AtmosConfig = *atmosConfig - } - - // Check if stderr is a TTY. - isTTY := term.IsTerminal(int(os.Stderr.Fd())) - - // Use terminal package's color logic. - return termConfig.ShouldUseColor(isTTY) -} - -// stripANSI removes ANSI escape codes from a string. -func stripANSI(s string) string { - // ANSI escape code pattern: ESC [ ... m where ... can be numbers separated by semicolons. - // More comprehensive pattern to catch all ANSI codes including SGR (colors/formatting). - ansiPattern := regexp.MustCompile(`\x1b\[[0-9;]*[a-zA-Z]`) - return ansiPattern.ReplaceAllString(s, "") -} - -// wrapText wraps text to the specified width while preserving intentional line breaks. -// -// DEPRECATED: This function is no longer used in production code. -// The markdown renderer (Glamour) handles text wrapping natively and correctly -// preserves markdown structure (code blocks, newlines, etc.). This function -// destroys markdown structure by calling strings.Fields() which removes ALL -// newlines, making it unsuitable for formatting error messages with code blocks. -// -// IMPORTANT: This function should NOT be used on text with intentional newlines, -// as strings.Fields() splits on ALL whitespace including newlines, which destroys -// the original line break structure. Only use this for wrapping single paragraphs. -// NEVER call this on multi-line text that needs to preserve its line break structure. -// -// Line breaks and spacing should be controlled by: -// - Markdown content itself (blank lines between paragraphs, etc.) -// - Markdown stylesheets (renderer configuration) -// - NOT by post-processing that removes newlines -func wrapText(text string, width int) string { - if width <= 0 { - width = DefaultMaxLineLength - } - - var lines []string - var currentLine strings.Builder - - // WARNING: strings.Fields() removes ALL whitespace including newlines. - // This destroys intentional line breaks in the input text. - // Only use this function on single-paragraph text. - words := strings.Fields(text) - for i, word := range words { - // Check if adding this word would exceed the width. - testLine := currentLine.String() - if len(testLine) > 0 { - testLine += space + word - } else { - testLine = word - } - - if len(testLine) > width && currentLine.Len() > 0 { - // Start a new line. - lines = append(lines, currentLine.String()) - currentLine.Reset() - currentLine.WriteString(word) - } else { - if i > 0 && currentLine.Len() > 0 { - currentLine.WriteString(space) - } - currentLine.WriteString(word) - } - } - - // Add the last line. - if currentLine.Len() > 0 { - lines = append(lines, currentLine.String()) - } - - return strings.Join(lines, newline) -} - -// formatStackTrace formats the full error chain with stack traces. -func formatStackTrace(err error, useColor bool) string { - style := lipgloss.NewStyle() - if useColor { - style = style.Foreground(lipgloss.Color("#808080")) // Gray - } - - // Use cockroachdb/errors format with stack traces. - details := fmt.Sprintf("%+v", err) - return style.Render(details) -} diff --git a/errors/formatter_render.go b/errors/formatter_render.go new file mode 100644 index 00000000000..f9f24cc4c0e --- /dev/null +++ b/errors/formatter_render.go @@ -0,0 +1,226 @@ +package errors + +import ( + "fmt" + "os" + "regexp" + "strings" + + "github.com/charmbracelet/lipgloss" + "github.com/cockroachdb/errors" + "github.com/spf13/viper" + "golang.org/x/term" + + "github.com/cloudposse/atmos/pkg/schema" + "github.com/cloudposse/atmos/pkg/terminal" + terminalenv "github.com/cloudposse/atmos/pkg/terminal/env" + "github.com/cloudposse/atmos/pkg/ui/markdown" +) + +// renderMarkdown renders markdown string through Glamour with specified width. +// +// This function creates a fresh markdown renderer for each call rather than using +// the global renderer from pkg/ui to ensure: +// 1. The FormatterConfig.MaxLineLength parameter is respected (global renderer may have different width) +// 2. Error formatting works before the UI system is initialized (early startup errors) +// 3. No circular dependencies (pkg/ui imports errors package). +func renderMarkdown(md string, maxLineLength int) (string, bool) { + return renderWith(md, maxLineLength, (*markdown.Renderer).RenderErrorf) +} + +// renderReadableMarkdown renders Markdown as plain text for output without styling. +// It avoids the ASCII preset used for non-TTY stderr, which leaves bold markers +// dangling around inline code and drops code-span backticks. +func renderReadableMarkdown(md string, maxLineLength int) (string, bool) { + return renderWith(md, maxLineLength, func(r *markdown.Renderer, content string, _ ...interface{}) (string, error) { + return r.RenderReadable(content) + }) +} + +func renderWith(md string, maxLineLength int, render func(*markdown.Renderer, string, ...interface{}) (string, error)) (string, bool) { + // Use provided maxLineLength, or fall back to default if not set. + width := maxLineLength + if width <= 0 { + width = DefaultMarkdownWidth + } + + // Always create a fresh renderer with the specified width to ensure + // MaxLineLength parameter is respected. The global renderer may have + // a different width configured. + config := schema.AtmosConfiguration{ + Settings: schema.AtmosSettings{ + Terminal: schema.Terminal{ + MaxWidth: width, + }, + }, + } + + renderer, err := newMarkdownRendererWithWidth(config, width) + if err != nil { + return "", false + } + + rendered, renderErr := render(renderer, md) + if renderErr == nil { + return rendered, true + } + + return "", false +} + +// formatContextForMarkdown formats context as a markdown table. +// Uses GetAllSafeDetails to traverse the entire error chain. +func formatContextForMarkdown(err error) string { + // Get all safe details from entire error chain, not just top-level. + allDetails := errors.GetAllSafeDetails(err) + var allSafeDetails []string + for _, payload := range allDetails { + allSafeDetails = append(allSafeDetails, payload.SafeDetails...) + } + if len(allSafeDetails) == 0 { + return "" + } + + // Parse "component=vpc stack=prod" format into key-value pairs. + var rows []string + for _, detail := range allSafeDetails { + str := fmt.Sprintf("%v", detail) + pairs := strings.Split(str, " ") + for _, pair := range pairs { + if parts := strings.SplitN(pair, "=", 2); len(parts) == 2 { + rows = append(rows, fmt.Sprintf("| %s | %s |", parts[0], parts[1])) + } + } + } + + // Return empty if no rows were parsed. + if len(rows) == 0 { + return "" + } + + // Build table with header. + var md strings.Builder + md.WriteString("| Key | Value |\n") + md.WriteString("|-----|-------|\n") + for _, row := range rows { + md.WriteString(row + "\n") + } + + return md.String() +} + +// shouldUseColor determines if color output should be used. +// This uses the terminal package's color logic which respects: +// - --no-color, --color, --force-color flags +// - NO_COLOR, CLICOLOR, CLICOLOR_FORCE environment variables +// - settings.terminal.color and settings.terminal.no_color in atmos.yaml. +func shouldUseColor() bool { + // Bind standard color environment signals locally, including during early startup. + env := viper.New() + for _, key := range []string{"NO_COLOR", "CLICOLOR", "CLICOLOR_FORCE", "FORCE_COLOR"} { + _ = env.BindEnv(key, key) + } + + // Build terminal config from all sources (flags, env vars, atmos.yaml). + termConfig := &terminal.Config{ + NoColor: terminalenv.ResolveNoColor(os.Args[1:], viper.GetBool("no-color")), + Color: viper.GetBool("color"), + ForceColor: viper.GetBool("force-color"), + + EnvNoColor: env.GetString("NO_COLOR") != "", + EnvCLIColor: env.GetString("CLICOLOR"), + EnvCLIColorForce: env.GetString("CLICOLOR_FORCE") != "" || env.GetString("FORCE_COLOR") != "", + //nolint:forbidigo // CI is the standard environment signal used by terminal color detection. + EnvCI: os.Getenv("CI") != "", + } + + // Add atmos.yaml settings if available. + if atmosConfig != nil { + termConfig.AtmosConfig = *atmosConfig + } + + // Check if stderr is a TTY. + isTTY := term.IsTerminal(int(os.Stderr.Fd())) + + // Use terminal package's color logic. + return termConfig.ShouldUseColor(isTTY) +} + +// stripANSI removes ANSI escape codes from a string. +func stripANSI(s string) string { + // ANSI escape code pattern: ESC [ ... m where ... can be numbers separated by semicolons. + // More comprehensive pattern to catch all ANSI codes including SGR (colors/formatting). + ansiPattern := regexp.MustCompile(`\x1b\[[0-9;]*[a-zA-Z]`) + return ansiPattern.ReplaceAllString(s, "") +} + +// wrapText wraps text to the specified width while preserving intentional line breaks. +// +// Deprecated: This function is no longer used in production code. +// The markdown renderer (Glamour) handles text wrapping natively and correctly +// preserves markdown structure (code blocks, newlines, etc.). This function +// destroys markdown structure by calling strings.Fields() which removes ALL +// newlines, making it unsuitable for formatting error messages with code blocks. +// +// IMPORTANT: This function should NOT be used on text with intentional newlines, +// as strings.Fields() splits on ALL whitespace including newlines, which destroys +// the original line break structure. Only use this for wrapping single paragraphs. +// NEVER call this on multi-line text that needs to preserve its line break structure. +// +// Line breaks and spacing should be controlled by: +// - Markdown content itself (blank lines between paragraphs, etc.) +// - Markdown stylesheets (renderer configuration) +// - NOT by post-processing that removes newlines +func wrapText(text string, width int) string { + if width <= 0 { + width = DefaultMaxLineLength + } + + var lines []string + var currentLine strings.Builder + + // WARNING: strings.Fields() removes ALL whitespace including newlines. + // This destroys intentional line breaks in the input text. + // Only use this function on single-paragraph text. + words := strings.Fields(text) + for i, word := range words { + // Check if adding this word would exceed the width. + testLine := currentLine.String() + if len(testLine) > 0 { + testLine += space + word + } else { + testLine = word + } + + if len(testLine) > width && currentLine.Len() > 0 { + // Start a new line. + lines = append(lines, currentLine.String()) + currentLine.Reset() + currentLine.WriteString(word) + } else { + if i > 0 && currentLine.Len() > 0 { + currentLine.WriteString(space) + } + currentLine.WriteString(word) + } + } + + // Add the last line. + if currentLine.Len() > 0 { + lines = append(lines, currentLine.String()) + } + + return strings.Join(lines, newline) +} + +// formatStackTrace formats the full error chain with stack traces. +func formatStackTrace(err error, useColor bool) string { + style := lipgloss.NewStyle() + if useColor { + style = style.Foreground(lipgloss.Color("#808080")) // Gray + } + + // Use cockroachdb/errors format with stack traces. + details := fmt.Sprintf("%+v", err) + return style.Render(details) +} diff --git a/errors/formatter_test.go b/errors/formatter_test.go index c8090fb517a..a6fb7ba1e93 100644 --- a/errors/formatter_test.go +++ b/errors/formatter_test.go @@ -1115,6 +1115,7 @@ func TestResolveFormatterWidth(t *testing.T) { config: FormatterConfig{}, atmosConfig: &schema.AtmosConfiguration{ Settings: schema.AtmosSettings{ + //nolint:staticcheck // Verify the supported deprecated docs width fallback. Docs: schema.Docs{MaxWidth: 140}, }, }, diff --git a/errors/sentry_registry.go b/errors/sentry_registry.go index 8967c9c63f6..bbf9e1170dc 100644 --- a/errors/sentry_registry.go +++ b/errors/sentry_registry.go @@ -5,6 +5,7 @@ import ( "crypto/sha256" "encoding/json" "fmt" + "maps" "sync" "github.com/getsentry/sentry-go" @@ -95,35 +96,9 @@ func (r *SentryClientRegistry) GetOrCreateClient(config *schema.SentryConfig) (* return hub, nil } - // Create new Sentry client. - sampleRate := config.SampleRate - if sampleRate == 0 { - sampleRate = 1.0 - } - - client, err := sentry.NewClient(sentry.ClientOptions{ - Transport: sentry.NewHTTPTransport(), - Dsn: config.DSN, - Environment: config.Environment, - Release: config.Release, - Debug: config.Debug, - SampleRate: sampleRate, - AttachStacktrace: config.CaptureStackContext, - }) + hub, err := newSentryHub(config) if err != nil { - return nil, fmt.Errorf("failed to create Sentry client: %w", err) - } - - // Create new hub with this client. - hub := sentry.NewHub(client, sentry.NewScope()) - - // Set tags in the hub's scope. - if len(config.Tags) > 0 { - hub.ConfigureScope(func(scope *sentry.Scope) { - for key, value := range config.Tags { - scope.SetTag(key, value) - } - }) + return nil, err } // Store client and config. @@ -162,25 +137,23 @@ func GetComponentErrorConfig(info *schema.ConfigAndStacksInfo) (*schema.ErrorsCo } // Check if component has errors settings override. - if info.ComponentSettingsSection != nil { - if errorsSettings, ok := info.ComponentSettingsSection["errors"].(map[string]any); ok { - metadata, err := getComponentErrorConfigWithMetadata(errorsSettings) - if err != nil { - return nil, err - } - if metadata.config != nil { - // Store metadata in the config for use during merge. - // Note: We use a package-level map to avoid modifying the schema. - componentMetadataStoreMu.Lock() - componentMetadataStore[metadata.config] = metadata - componentMetadataStoreMu.Unlock() - } - return metadata.config, nil - } + errorsSettings, ok := info.ComponentSettingsSection["errors"].(map[string]any) + if !ok { + // No component-level override, return nil (will use global config). + return nil, nil } - - // No component-level override, return nil (will use global config). - return nil, nil + metadata, err := getComponentErrorConfigWithMetadata(errorsSettings) + if err != nil { + return nil, err + } + if metadata.config != nil { + // Store metadata in the config for use during merge. + // Note: We use a package-level map to avoid modifying the schema. + componentMetadataStoreMu.Lock() + componentMetadataStore[metadata.config] = metadata + componentMetadataStoreMu.Unlock() + } + return metadata.config, nil } // componentMetadataStore maps component configs to their metadata. @@ -283,42 +256,14 @@ func MergeErrorConfigs(global *schema.ErrorsConfig, component *schema.ErrorsConf // Check if component has any explicit Sentry configuration (non-boolean fields). // Boolean fields are handled separately to allow explicit true/false overrides. - hasComponentSentry := component.Sentry.DSN != "" || - component.Sentry.Environment != "" || - component.Sentry.Release != "" || - component.Sentry.SampleRate > 0 || - len(component.Sentry.Tags) > 0 + hasComponentSentry := hasSentrySettings(&component.Sentry) // Get metadata about which boolean fields were explicitly set. componentMetadataStoreMu.RLock() metadata, hasMetadata := componentMetadataStore[component] componentMetadataStoreMu.RUnlock() - // Determine which boolean fields have explicit overrides. - var explicitBooleans booleanOverrides - if hasMetadata { - // YAML caller - use metadata to detect explicit boolean fields. - explicitBooleans.enabled = metadata.sentryEnabledExplicitlySet - explicitBooleans.debug = metadata.sentryDebugExplicitlySet - explicitBooleans.captureStackContext = metadata.sentryCaptureStackExplicitlySet - } else if !hasComponentSentry { - // No metadata AND no explicit non-boolean config. - // Check if boolean fields differ from global (explicit override). - // This preserves the old behavior for tests with only boolean overrides. - explicitBooleans.enabled = component.Sentry.Enabled != global.Sentry.Enabled - explicitBooleans.debug = component.Sentry.Debug != global.Sentry.Debug - explicitBooleans.captureStackContext = component.Sentry.CaptureStackContext != global.Sentry.CaptureStackContext - } else { - // hasComponentSentry && !hasMetadata - // No metadata but has explicit non-boolean config (DSN/Environment/Tags). - // Use conservative heuristic: treat "true" values as explicit overrides, - // but assume "false" values are zero values (to preserve backward compatibility). - // This allows non-YAML callers to enable booleans alongside other config. - // To explicitly set "false", use SetComponentBooleanOverrides(). - explicitBooleans.enabled = component.Sentry.Enabled == true - explicitBooleans.debug = component.Sentry.Debug == true - explicitBooleans.captureStackContext = component.Sentry.CaptureStackContext == true - } + explicitBooleans := resolveBooleanOverrides(global, component, metadata, hasMetadata, hasComponentSentry) hasBooleanOverride := explicitBooleans.enabled || explicitBooleans.debug || explicitBooleans.captureStackContext @@ -351,8 +296,8 @@ type booleanOverrides struct { } // mergeSentryConfigs merges component Sentry config with global Sentry config. -// hasExplicitConfig indicates whether the component has explicit non-boolean Sentry config. -// explicitBooleans indicates which boolean fields were explicitly set in the component YAML. +// HasExplicitConfig indicates whether the component has explicit non-boolean Sentry config. +// ExplicitBooleans indicates which boolean fields were explicitly set in the component YAML. func mergeSentryConfigs(global *schema.SentryConfig, component *schema.SentryConfig, hasExplicitConfig bool, explicitBooleans booleanOverrides) schema.SentryConfig { var merged schema.SentryConfig if global != nil { @@ -360,12 +305,7 @@ func mergeSentryConfigs(global *schema.SentryConfig, component *schema.SentryCon } // Copy global tags to avoid modifying the original. - if global != nil && global.Tags != nil { - merged.Tags = make(map[string]string) - for key, value := range global.Tags { - merged.Tags[key] = value - } - } + merged.Tags = maps.Clone(merged.Tags) // Override fields that are explicitly set in component config. if component.DSN != "" { @@ -381,40 +321,7 @@ func mergeSentryConfigs(global *schema.SentryConfig, component *schema.SentryCon merged.SampleRate = component.SampleRate } - // For boolean fields: - // Apply component boolean values when they were explicitly set in YAML, - // regardless of whether other explicit config (DSN/Environment/Tags) is present. - // This allows components to set `enabled: false` alongside other Sentry fields. - if !hasExplicitConfig && global != nil { - // Component only has boolean overrides (no DSN/Environment/Tags). - // Apply boolean differences - this allows `enabled: false` to disable Sentry. - if component.Enabled != global.Enabled { - merged.Enabled = component.Enabled - } - if component.Debug != global.Debug { - merged.Debug = component.Debug - } - if component.CaptureStackContext != global.CaptureStackContext { - merged.CaptureStackContext = component.CaptureStackContext - } - } else if global == nil { - // No global config - use component values directly. - merged.Enabled = component.Enabled - merged.Debug = component.Debug - merged.CaptureStackContext = component.CaptureStackContext - } else if hasExplicitConfig { - // Component has explicit non-boolean config (DSN/Environment/Tags). - // Apply boolean overrides only if they were explicitly set in YAML. - if explicitBooleans.enabled { - merged.Enabled = component.Enabled - } - if explicitBooleans.debug { - merged.Debug = component.Debug - } - if explicitBooleans.captureStackContext { - merged.CaptureStackContext = component.CaptureStackContext - } - } + applySentryBooleans(&merged, global, component, hasExplicitConfig, explicitBooleans) // Merge tags (component tags override global tags with same key). if len(component.Tags) > 0 { @@ -428,3 +335,98 @@ func mergeSentryConfigs(global *schema.SentryConfig, component *schema.SentryCon return merged } + +func newSentryHub(config *schema.SentryConfig) (*sentry.Hub, error) { + // Create new Sentry client. + sampleRate := config.SampleRate + if sampleRate == 0 { + sampleRate = 1.0 + } + + client, err := sentry.NewClient(sentry.ClientOptions{ + Transport: sentry.NewHTTPTransport(), + Dsn: config.DSN, + Environment: config.Environment, + Release: config.Release, + Debug: config.Debug, + SampleRate: sampleRate, + AttachStacktrace: config.CaptureStackContext, + }) + if err != nil { + return nil, fmt.Errorf("failed to create Sentry client: %w", err) + } + + // Create new hub with this client. + hub := sentry.NewHub(client, sentry.NewScope()) + + // Set tags in the hub's scope. + if len(config.Tags) > 0 { + hub.ConfigureScope(func(scope *sentry.Scope) { + for key, value := range config.Tags { + scope.SetTag(key, value) + } + }) + } + + return hub, nil +} + +func resolveBooleanOverrides(global, component *schema.ErrorsConfig, metadata componentErrorConfigWithMetadata, hasMetadata, hasComponentSentry bool) booleanOverrides { + // Determine which boolean fields have explicit overrides. + var explicitBooleans booleanOverrides + switch { + case hasMetadata: + // YAML caller - use metadata to detect explicit boolean fields. + explicitBooleans.enabled = metadata.sentryEnabledExplicitlySet + explicitBooleans.debug = metadata.sentryDebugExplicitlySet + explicitBooleans.captureStackContext = metadata.sentryCaptureStackExplicitlySet + case !hasComponentSentry: + // No metadata AND no explicit non-boolean config. + // Check if boolean fields differ from global (explicit override). + // This preserves the old behavior for tests with only boolean overrides. + explicitBooleans.enabled = component.Sentry.Enabled != global.Sentry.Enabled + explicitBooleans.debug = component.Sentry.Debug != global.Sentry.Debug + explicitBooleans.captureStackContext = component.Sentry.CaptureStackContext != global.Sentry.CaptureStackContext + default: + // Component has explicit config but no metadata. + // No metadata but has explicit non-boolean config (DSN/Environment/Tags). + // Use conservative heuristic: treat "true" values as explicit overrides, + // but assume "false" values are zero values (to preserve backward compatibility). + // This allows non-YAML callers to enable booleans alongside other config. + // To explicitly set "false", use SetComponentBooleanOverrides(). + explicitBooleans.enabled = component.Sentry.Enabled + explicitBooleans.debug = component.Sentry.Debug + explicitBooleans.captureStackContext = component.Sentry.CaptureStackContext + } + + return explicitBooleans +} + +func hasSentrySettings(config *schema.SentryConfig) bool { + return config.DSN != "" || + config.Environment != "" || + config.Release != "" || + config.SampleRate > 0 || + len(config.Tags) > 0 +} + +func applySentryBooleans(merged, global, component *schema.SentryConfig, hasExplicitConfig bool, explicitBooleans booleanOverrides) { + // Apply all component booleans when there is no global or explicit non-boolean config. + // Apply boolean differences when the component only has boolean overrides. + // With no global config, use component values directly. + // Otherwise apply only booleans explicitly set in YAML, regardless of other config. + // This allows enabled: false alongside DSN/Environment/Tags, while preserving + // inherited values for omitted booleans. + if global == nil || !hasExplicitConfig { + explicitBooleans = booleanOverrides{enabled: true, debug: true, captureStackContext: true} + } + if explicitBooleans.enabled { + merged.Enabled = component.Enabled + } + if explicitBooleans.debug { + merged.Debug = component.Debug + } + if explicitBooleans.captureStackContext { + merged.CaptureStackContext = component.CaptureStackContext + } +} From f0ff59e6c50eefd7c316274b96d39c5526c77a86 Mon Sep 17 00:00:00 2001 From: Erik Osterman Date: Fri, 13 Nov 2026 16:16:46 -0600 Subject: [PATCH 22/28] fix(container): isolate network alias test resources --- pkg/container/common.go | 39 ++++++++++++++++++++-------------- pkg/container/docker_test.go | 10 ++++----- pkg/container/image_summary.go | 29 +++++++++++++------------ pkg/container/podman_test.go | 2 -- 4 files changed, 43 insertions(+), 37 deletions(-) diff --git a/pkg/container/common.go b/pkg/container/common.go index b132a7ff714..7850e633d1e 100644 --- a/pkg/container/common.go +++ b/pkg/container/common.go @@ -299,14 +299,8 @@ func buildBuildArgs(config *BuildConfig) []string { if config.Driver != nil { args = append(args, "--builder", effectiveDriverName(config.Driver)) } - if config.Cache != nil { - for _, entry := range config.Cache.From { - args = append(args, "--cache-from", joinAttrs(entry)) - } - for _, entry := range config.Cache.To { - args = append(args, "--cache-to", joinAttrs(entry)) - } - } + args = appendBuildCacheArgs(args, config.Cache, false) + if config.Load { args = append(args, "--load") } @@ -346,14 +340,7 @@ func buildBakeArgs(config *BuildConfig) []string { if config.Driver != nil { args = append(args, "--builder", effectiveDriverName(config.Driver)) } - if config.Cache != nil { - for _, entry := range config.Cache.From { - args = append(args, "--set", "*.cache-from="+joinAttrs(entry)) - } - for _, entry := range config.Cache.To { - args = append(args, "--set", "*.cache-to="+joinAttrs(entry)) - } - } + args = appendBuildCacheArgs(args, config.Cache, true) for _, file := range appendFile(config.Bake.File, config.Bake.Files) { args = append(args, "--file", file) @@ -678,3 +665,23 @@ func runCommand(cmd *exec.Cmd, runtimeName string) error { } return fmt.Errorf("%w: %s exec failed: %w", errUtils.ErrContainerRuntimeOperation, runtimeName, err) } + +// appendBuildCacheArgs adds cache imports and exports using build or bake syntax. +func appendBuildCacheArgs(args []string, cache *CacheConfig, bake bool) []string { + if cache == nil { + return args + } + fromFlag, toFlag := "--cache-from", "--cache-to" + fromPrefix, toPrefix := "", "" + if bake { + fromFlag, toFlag = "--set", "--set" + fromPrefix, toPrefix = "*.cache-from=", "*.cache-to=" + } + for _, entry := range cache.From { + args = append(args, fromFlag, fromPrefix+joinAttrs(entry)) + } + for _, entry := range cache.To { + args = append(args, toFlag, toPrefix+joinAttrs(entry)) + } + return args +} diff --git a/pkg/container/docker_test.go b/pkg/container/docker_test.go index 8ad89ea8258..9a8558437a0 100644 --- a/pkg/container/docker_test.go +++ b/pkg/container/docker_test.go @@ -353,8 +353,6 @@ func TestDockerRuntime_Pull_Integration(t *testing.T) { // (Create, Start, Stop, Remove) for Docker runtime. Tests are intentionally duplicated // to verify both Docker and Podman implementations independently, ensuring consistency // across runtimes and allowing runtime-specific test evolution if needed. -// -//nolint:dupl // Docker and Podman implement identical Runtime interface with same lifecycle behavior. func TestDockerRuntime_ContainerLifecycle_Integration(t *testing.T) { // Integration test - tests Create, Start, Stop, Remove lifecycle. runtime := NewDockerRuntime() @@ -689,7 +687,9 @@ func TestDockerRuntime_SharedNetworkAliasReachable_Integration(t *testing.T) { return } - const networkName = "atmos-test-alias-net" + // Isolate resources across concurrent test processes sharing one Docker daemon. + runSuffix := strconv.Itoa(os.Getpid()) + "-" + strconv.FormatInt(time.Now().UnixNano(), 10) + networkName := "atmos-test-alias-net-" + runSuffix require.NoError(t, runtime.EnsureNetwork(ctx, networkName)) t.Cleanup(func() { _ = exec.Command("docker", "network", "rm", networkName).Run() // Best-effort test cleanup. @@ -698,7 +698,7 @@ func TestDockerRuntime_SharedNetworkAliasReachable_Integration(t *testing.T) { // The "server" side: a container that just listens on a TCP port, // registered under the alias its sibling will dial. serverID, err := runtime.Create(ctx, &CreateConfig{ - Name: "atmos-test-alias-server", + Name: "atmos-test-alias-server-" + runSuffix, Image: "alpine:latest", Command: []string{"nc", "-l", "-p", "8080"}, Networks: []NetworkAttachment{ @@ -713,7 +713,7 @@ func TestDockerRuntime_SharedNetworkAliasReachable_Integration(t *testing.T) { // no special knowledge of the server beyond its alias -- exactly the // relationship between a job container and an emulator container. clientID, err := runtime.Create(ctx, &CreateConfig{ - Name: "atmos-test-alias-client", + Name: "atmos-test-alias-client-" + runSuffix, Image: "alpine:latest", OverrideCommand: true, // sleep infinity. Networks: []NetworkAttachment{ diff --git a/pkg/container/image_summary.go b/pkg/container/image_summary.go index 9916fc60094..fd3fd86ba86 100644 --- a/pkg/container/image_summary.go +++ b/pkg/container/image_summary.go @@ -13,15 +13,16 @@ import ( ) const ( - labelOCIBase = "org.opencontainers.image." - labelOCIDescription = labelOCIBase + "description" - labelOCILicenses = labelOCIBase + "licenses" - labelOCIRevision = labelOCIBase + "revision" - labelOCISource = labelOCIBase + "source" - labelOCITitle = labelOCIBase + "title" - labelOCIVersion = labelOCIBase + "version" - markdownBacktick = "`" - markdownLineBreak = "\n" + imageSummaryNotAvailable = "n/a" + labelOCIBase = "org.opencontainers.image." + labelOCIDescription = labelOCIBase + "description" + labelOCILicenses = labelOCIBase + "licenses" + labelOCIRevision = labelOCIBase + "revision" + labelOCISource = labelOCIBase + "source" + labelOCITitle = labelOCIBase + "title" + labelOCIVersion = labelOCIBase + "version" + markdownBacktick = "`" + markdownLineBreak = "\n" // The component type and command select the ci.templates.container.image override. imageSummaryComponentType = "container" @@ -111,8 +112,8 @@ func BuildImageSummaryData(info *ImageInfo, opts ImageSummaryOptions) *ImageSumm Source: markdownCell(linkOrText(labels[labelOCISource])), Entrypoint: markdownCell(codeOrNA(strings.Join(info.Entrypoint, " "))), Command: markdownCell(codeOrNA(strings.Join(info.Cmd, " "))), - StopSignal: markdownCell(codeOrNA(firstNonEmpty(info.StopSignal, "n/a"))), - StorageDriver: markdownCell(codeOrNA(firstNonEmpty(info.StorageDriver, "n/a"))), + StopSignal: markdownCell(codeOrNA(firstNonEmpty(info.StopSignal, imageSummaryNotAvailable))), + StorageDriver: markdownCell(codeOrNA(firstNonEmpty(info.StorageDriver, imageSummaryNotAvailable))), ExposedPorts: markdownCell(codeOrNA(joinOrNA(info.ExposedPorts))), Env: envRows(info.Env), Labels: labelRows(labels), @@ -188,7 +189,7 @@ func summaryDigest(info *ImageInfo, pushedDigest string) string { if digest := digestFromRepoDigest(firstString(info.RepoDigests)); digest != "" { return digest } - return "n/a" + return imageSummaryNotAvailable } func envRows(env []string) []ImageSummaryRow { @@ -256,14 +257,14 @@ func digestFromRepoDigest(value string) string { func joinOrNA(values []string) string { if len(values) == 0 { - return "n/a" + return imageSummaryNotAvailable } return strings.Join(values, ", ") } func codeOrNA(value string) string { if value == "" { - value = "n/a" + value = imageSummaryNotAvailable } return markdownBacktick + markdownCodeText(value) + markdownBacktick } diff --git a/pkg/container/podman_test.go b/pkg/container/podman_test.go index 3afa8cf15d8..2b751b73c11 100644 --- a/pkg/container/podman_test.go +++ b/pkg/container/podman_test.go @@ -764,8 +764,6 @@ func isKnownPodmanRuntimeMismatch(err error) bool { // (Create, Start, Stop, Remove) for Podman runtime. Tests are intentionally duplicated // to verify both Docker and Podman implementations independently, ensuring consistency // across runtimes and allowing runtime-specific test evolution if needed. -// -//nolint:dupl // Docker and Podman implement identical Runtime interface with same lifecycle behavior. func TestPodmanRuntime_ContainerLifecycle_Integration(t *testing.T) { // Integration test - tests Create, Start, Stop, Remove lifecycle. runtime := NewPodmanRuntime() From 32705c5cdab664232ed1d6cb568f8812d026fc7e Mon Sep 17 00:00:00 2001 From: Erik Osterman Date: Sat, 14 Nov 2026 07:36:57 -0600 Subject: [PATCH 23/28] fix(errors): pass TERM into the terminal color decision shouldUseColor left EnvTerm empty, so TERM=dumb with CI=true still enabled CI color. Populate EnvTerm from TERM and add a regression test. Co-Authored-By: Claude Sonnet 5.5 --- errors/formatter_render.go | 2 ++ errors/formatter_test.go | 14 ++++++++++++++ 2 files changed, 16 insertions(+) diff --git a/errors/formatter_render.go b/errors/formatter_render.go index f9f24cc4c0e..743247d60df 100644 --- a/errors/formatter_render.go +++ b/errors/formatter_render.go @@ -132,6 +132,8 @@ func shouldUseColor() bool { EnvCLIColorForce: env.GetString("CLICOLOR_FORCE") != "" || env.GetString("FORCE_COLOR") != "", //nolint:forbidigo // CI is the standard environment signal used by terminal color detection. EnvCI: os.Getenv("CI") != "", + //nolint:forbidigo // TERM is the standard environment signal used by terminal color detection. + EnvTerm: os.Getenv("TERM"), } // Add atmos.yaml settings if available. diff --git a/errors/formatter_test.go b/errors/formatter_test.go index a6fb7ba1e93..d1d7d67819f 100644 --- a/errors/formatter_test.go +++ b/errors/formatter_test.go @@ -247,6 +247,20 @@ func TestShouldUseColorInCI(t *testing.T) { assert.True(t, shouldUseColor(), "CI output supports ANSI color without a TTY") } +func TestShouldUseColorDumbTerminalInCI(t *testing.T) { + t.Setenv("CI", "true") + t.Setenv("TERM", "dumb") + t.Setenv("NO_COLOR", "") + t.Setenv("CLICOLOR", "") + t.Setenv("CLICOLOR_FORCE", "") + t.Setenv("FORCE_COLOR", "") + + assert.False(t, shouldUseColor(), "TERM=dumb must disable automatic CI color") + + t.Setenv("TERM", "xterm-256color") + assert.True(t, shouldUseColor(), "CI color stays enabled for a capable terminal") +} + func TestFormatInCIUsesColorUnlessDisabled(t *testing.T) { t.Setenv("CI", "true") t.Setenv("NO_COLOR", "") From a282f4b86aaa2aa5af084c61b9726fef044939ea Mon Sep 17 00:00:00 2001 From: Erik Osterman Date: Tue, 17 Nov 2026 06:43:03 -0600 Subject: [PATCH 24/28] fix(terragrunt): buffer unit paths until sensitive values are known Keep unit-bearing progress events in the redacting log sink until evaluation finishes, withholding them when sensitive values cannot be registered. Cover successful and failed live delivery and concurrent event ordering. --- plugins/terragrunt/internal/engine/logs.go | 14 ++++--- .../terragrunt/internal/engine/logs_test.go | 30 +++++++++++-- plugins/terragrunt/internal/engine/resolve.go | 2 +- .../internal/provider/live_logs_test.go | 42 ++++++++++++++++++- 4 files changed, 77 insertions(+), 11 deletions(-) diff --git a/plugins/terragrunt/internal/engine/logs.go b/plugins/terragrunt/internal/engine/logs.go index 66d18596d25..387dca4b707 100644 --- a/plugins/terragrunt/internal/engine/logs.go +++ b/plugins/terragrunt/internal/engine/logs.go @@ -45,8 +45,8 @@ type LogSink struct { off bool // Withheld is set when the call may have logged a sensitive value the sink cannot redact. withheld bool - // progress receives fixed plugin progress events immediately. Terragrunt events stay buffered until - // sensitive values discovered during evaluation have been registered. + // progress receives fixed plugin progress events without unit paths immediately. Unit paths and + // Terragrunt events stay buffered until sensitive values discovered during evaluation are registered. progress func(*model.LogEntry) } @@ -83,8 +83,8 @@ func NewLogSink(level, root string) *LogSink { //nolint:lintroller // Plugin evaluator code cannot import the host performance tracker. func (s *LogSink) Enabled() bool { return !s.off } -// Forward hands fixed plugin progress events to deliver as they happen. Terragrunt events remain collected -// until the call has finished and all discovered sensitive values can be redacted. +// Forward hands fixed plugin progress events without unit paths to deliver as they happen. Events with +// unit paths and Terragrunt events remain collected until discovered sensitive values can be redacted. // //nolint:lintroller // Plugin evaluator code cannot import the host performance tracker. func (s *LogSink) Forward(deliver func(*model.LogEntry)) { @@ -104,7 +104,9 @@ func (s *LogSink) Event(level log.Level, message, unit string) { s.mu.Lock() defer s.mu.Unlock() event := &model.LogEntry{Time: time.Now(), Level: level.String(), Message: message, Unit: s.relative(unit)} - if s.progress != nil { + // Unit paths can contain secrets discovered later during evaluation. Keep them + // buffered so Entries can redact them or withhold them if evaluation fails. + if s.progress != nil && unit == "" { s.progress(event) return } @@ -294,7 +296,7 @@ func (s *LogSink) add(level log.Level, entry *logrus.Entry) { s.entries = append(s.entries, record) } -// keep collects a plugin progress event when there is no live progress channel. The caller holds the lock. +// keep collects a plugin progress event until it can be safely delivered. The caller holds the lock. func (s *LogSink) keep(entry *model.LogEntry) { if len(s.entries) >= maxLogEntries || s.size >= maxLogBytes { s.dropped++ diff --git a/plugins/terragrunt/internal/engine/logs_test.go b/plugins/terragrunt/internal/engine/logs_test.go index e6f86d034ec..9cf7c13c735 100644 --- a/plugins/terragrunt/internal/engine/logs_test.go +++ b/plugins/terragrunt/internal/engine/logs_test.go @@ -172,7 +172,7 @@ func TestLogSinkForwardsSafeProgressAndBuffersTerragruntEvents(t *testing.T) { assert.Equal(t, "second", entries[1].Message) } -func TestLogSinkForwardingKeepsOrderAcrossConcurrentUnits(t *testing.T) { +func TestLogSinkBufferingKeepsOrderAcrossConcurrentUnits(t *testing.T) { sink := NewLogSink("debug", "") forwarded := make(map[string][]string) var total int @@ -189,8 +189,12 @@ func TestLogSinkForwardingKeepsOrderAcrossConcurrentUnits(t *testing.T) { }) } wg.Wait() - // The deliverer is never called concurrently, so it needs no lock of its own. - assert.Equal(t, 400, total) + assert.Zero(t, total, "unit paths must not be forwarded before secrets are known") + entries := sink.Entries() + require.Len(t, entries, 400) + for _, entry := range entries { + forwarded[entry.Unit] = append(forwarded[entry.Unit], entry.Message) + } for unit := range 8 { var want []string for sequence := range 50 { @@ -506,3 +510,23 @@ func TestUnredactedSensitivityCountsOnlyUnknownValues(t *testing.T) { assert.True(t, unredactedSensitivity(fsys, []string{backend}, backend, true), "other blocks are unknown") assert.True(t, unredactedSensitivity(fsys, []string{broken}, unit, true), "an unparseable file fails closed") } + +func TestLogSinkBuffersUnitPathsUntilSensitiveValuesAreRegistered(t *testing.T) { + root := t.TempDir() + sink := NewLogSink("debug", root) + var forwarded []*model.LogEntry + sink.Forward(func(entry *model.LogEntry) { forwarded = append(forwarded, entry) }) + sink.Event(log.InfoLevel, "Evaluating unit", filepath.Join(root, "live", "private-unit", "app")) + require.Empty(t, forwarded) + sink.RedactValue("private-unit") + entries := sink.Entries() + require.Len(t, entries, 1) + assert.Equal(t, "live//app", entries[0].Unit) + assert.Equal(t, "Evaluating unit", entries[0].Message) + assert.Equal(t, "info", entries[0].Level) + sink.Withhold() + entries = sink.Entries() + require.Len(t, entries, 1) + assert.Empty(t, entries[0].Unit) + assert.Contains(t, entries[0].Message, "withheld") +} diff --git a/plugins/terragrunt/internal/engine/resolve.go b/plugins/terragrunt/internal/engine/resolve.go index 96eb033d535..f80347ae11a 100644 --- a/plugins/terragrunt/internal/engine/resolve.go +++ b/plugins/terragrunt/internal/engine/resolve.go @@ -55,7 +55,7 @@ func resolveRequest(ctx context.Context, request model.Request, filesystem afero if err != nil { return nil, err } - // This fixed progress event is safe to show before configuration values are evaluated. + // The sink buffers the unit path until configuration values can be redacted. if sink := logSinkFrom(ctx); sink != nil { sink.Event(log.InfoLevel, "Evaluating unit", filepath.Dir(path)) } diff --git a/plugins/terragrunt/internal/provider/live_logs_test.go b/plugins/terragrunt/internal/provider/live_logs_test.go index 380c11f7ddf..e0f8e50f0b4 100644 --- a/plugins/terragrunt/internal/provider/live_logs_test.go +++ b/plugins/terragrunt/internal/provider/live_logs_test.go @@ -2,9 +2,11 @@ package provider import ( "context" + "fmt" "net" "os" "path/filepath" + "strings" "sync" "testing" @@ -185,6 +187,44 @@ func TestLiveDeliveryWithholdsUnknownSensitiveValues(t *testing.T) { assert.NotContains(t, value, "secret-live-2718") } } - assert.Contains(t, messagesOf(delivered), "Evaluating unit") + assert.NotContains(t, messagesOf(delivered), "Evaluating unit", "the unit path is withheld when sensitivity is unknown") assert.NotEmpty(t, delivered) } + +func TestLiveDeliveryProtectsSensitiveUnitPaths(t *testing.T) { + for _, broken := range []bool{false, true} { + t.Run(fmt.Sprint("broken=", broken), func(t *testing.T) { + request := brokenUnit(t) + const secret = "private-unit-2718" + unit := filepath.Join(request.RootDirectory, "live", secret, "app") + require.NoError(t, os.MkdirAll(filepath.Join(unit, "module"), 0o755)) + configuration := "terraform { source = \"./module\" }\nlocals { token = sensitive(\"" + secret + "\") }\ninputs = { token = local.token }\n" + if broken { + configuration = strings.Replace(configuration, "token = local.token }", "token = local.token, broken = local.absent }", 1) + } + require.NoError(t, os.WriteFile(filepath.Join(unit, "terragrunt.hcl"), []byte(configuration), 0o644)) + request.Source = filepath.Join("live", secret, "app", "terragrunt.hcl") + receiver := &logReceiver{} + _, err := New(nil, WithAPI(apiClient(t, receiver))).Prepare(t.Context(), request) + if broken { + require.Error(t, err) + } else { + require.NoError(t, err) + } + delivered, _, _ := receiver.snapshot() + require.NotEmpty(t, delivered) + var units []string + for _, entry := range delivered { + assert.NotContains(t, entry.String(), secret) + if entry.GetMessage() == "Evaluating unit" { + units = append(units, entry.GetUnit()) + } + } + if broken { + assert.Empty(t, units) + } else { + assert.Contains(t, units, "live//app") + } + }) + } +} From 31858b288e416d837385b1ba00b668f0fe40695c Mon Sep 17 00:00:00 2001 From: Erik Osterman Date: Tue, 17 Nov 2026 06:48:44 -0600 Subject: [PATCH 25/28] fix(terragrunt): document provider performance tracker boundary Use the existing narrow lintroller exemption on four provider entry points. The standalone plugin depends on the SDK and cannot import the host tracker. --- plugins/terragrunt/internal/provider/discovery.go | 2 ++ plugins/terragrunt/internal/provider/preparation.go | 4 ++++ plugins/terragrunt/internal/provider/provider.go | 2 ++ 3 files changed, 8 insertions(+) diff --git a/plugins/terragrunt/internal/provider/discovery.go b/plugins/terragrunt/internal/provider/discovery.go index 3c7920ae94f..4ea5b61a246 100644 --- a/plugins/terragrunt/internal/provider/discovery.go +++ b/plugins/terragrunt/internal/provider/discovery.go @@ -12,6 +12,8 @@ import ( ) // Discover expands local stacks in an isolated overlay without preparing units. +// +//nolint:lintroller // Plugin code cannot import the host performance tracker. func (p *Provider) Discover(ctx context.Context, request *pluginv1.DiscoverComponentsRequest) (*pluginv1.DiscoverComponentsResponse, error) { ctx, logs := p.withLogs(ctx, request.GetInvocation(), request.GetRootDirectory(), request.GetProviderConfiguration()) response, err := p.discover(ctx, request) diff --git a/plugins/terragrunt/internal/provider/preparation.go b/plugins/terragrunt/internal/provider/preparation.go index 8791f338ece..8e95d2da39b 100644 --- a/plugins/terragrunt/internal/provider/preparation.go +++ b/plugins/terragrunt/internal/provider/preparation.go @@ -58,6 +58,8 @@ func (p *Provider) componentRequest(ctx context.Context, request *pluginv1.Compo // Prepare resolves current inputs after dependencies and returns literal files. // Terraform execution remains owned by Atmos. +// +//nolint:lintroller // Plugin code cannot import the host performance tracker. func (p *Provider) Prepare(ctx context.Context, request *pluginv1.ComponentRequest) (*pluginv1.PrepareComponentResponse, error) { ctx, logs := p.withLogs(ctx, request.GetInvocation(), request.GetRootDirectory(), request.GetConfiguration(), request.GetProviderConfiguration()) response, err := p.prepare(ctx, request) @@ -255,6 +257,8 @@ func stateIdentity(req model.Request, result *model.Resolution) (*pluginv1.Compo } // Resolve reads backend identity in an overlay, independently of dependency outputs. +// +//nolint:lintroller // Plugin code cannot import the host performance tracker. func (p *Provider) Resolve(ctx context.Context, request *pluginv1.ComponentRequest) (*pluginv1.ResolveComponentStateResponse, error) { ctx, logs := p.withLogs(ctx, request.GetInvocation(), request.GetRootDirectory(), request.GetConfiguration(), request.GetProviderConfiguration()) response, err := p.resolveState(ctx, request) diff --git a/plugins/terragrunt/internal/provider/provider.go b/plugins/terragrunt/internal/provider/provider.go index 8d95599be7a..a28a01ad769 100644 --- a/plugins/terragrunt/internal/provider/provider.go +++ b/plugins/terragrunt/internal/provider/provider.go @@ -264,6 +264,8 @@ func sources(root string, resolved *model.Resolution) ([]*pluginv1.ComponentSour } // Validate rejects unsupported operation and provider settings without evaluating HCL. +// +//nolint:lintroller // Plugin code cannot import the host performance tracker. func (p *Provider) Validate(ctx context.Context, request *pluginv1.ComponentRequest) (*pluginv1.ValidateResponse, error) { if err := validate(ctx, request); err != nil { return nil, scoped(rpcError(err), "validate", request.GetRootDirectory(), request.GetAddress()) From a3c4f0e85e71b094a3aad344eb0d77dfc0a75312 Mon Sep 17 00:00:00 2001 From: Erik Osterman Date: Tue, 17 Nov 2026 07:02:18 -0600 Subject: [PATCH 26/28] test(errors): isolate CI color assertion from inherited TERM Select a color-capable terminal for the automatic CI color test, leaving the adjacent dumb-terminal and NO_COLOR assertions unchanged. --- errors/formatter_test.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/errors/formatter_test.go b/errors/formatter_test.go index d1d7d67819f..26d1ec41373 100644 --- a/errors/formatter_test.go +++ b/errors/formatter_test.go @@ -239,6 +239,8 @@ func TestShouldUseColor(t *testing.T) { func TestShouldUseColorInCI(t *testing.T) { t.Setenv("CI", "true") + // Automatic CI color requires a capable terminal, independent of the test runner. + t.Setenv("TERM", "xterm-256color") t.Setenv("NO_COLOR", "") t.Setenv("CLICOLOR", "") t.Setenv("CLICOLOR_FORCE", "") From 4122a18fd286c74040a07bc3d6eb03ec1caebdc1 Mon Sep 17 00:00:00 2001 From: Erik Osterman Date: Tue, 17 Nov 2026 09:25:44 -0600 Subject: [PATCH 27/28] refactor(terragrunt): finish engine and provider lint baseline Share unit parser dependencies through the evaluator and pass requests by address inside the engine. Separate dispatch, generated-file rendering and dependency merging while preserving fail-closed destroy and sensitive logs. Cover literal, unknown, included, malformed and unreadable destroy guards. Document the standalone plugin tracker boundary and value-based evaluator API with function-scoped acknowledgements; full engine/provider lint is clean. --- .../internal/engine/destroy_guard_test.go | 43 ++++++++++ .../terragrunt/internal/engine/discovery.go | 23 ++++-- .../internal/engine/discovery_paths_test.go | 4 +- .../terragrunt/internal/engine/execution.go | 2 +- .../terragrunt/internal/engine/generation.go | 46 +++++++---- .../terragrunt/internal/engine/logs_test.go | 7 +- .../terragrunt/internal/engine/policies.go | 6 +- plugins/terragrunt/internal/engine/resolve.go | 82 ++++++++++--------- .../internal/engine/resolve_test.go | 2 +- .../terragrunt/internal/provider/discovery.go | 9 +- .../terragrunt/internal/provider/provider.go | 7 +- 11 files changed, 154 insertions(+), 77 deletions(-) create mode 100644 plugins/terragrunt/internal/engine/destroy_guard_test.go diff --git a/plugins/terragrunt/internal/engine/destroy_guard_test.go b/plugins/terragrunt/internal/engine/destroy_guard_test.go new file mode 100644 index 00000000000..60e714dd1d9 --- /dev/null +++ b/plugins/terragrunt/internal/engine/destroy_guard_test.go @@ -0,0 +1,43 @@ +package engine + +import ( + "errors" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/require" +) + +func TestStaticDestroyGuardFailsClosed(t *testing.T) { + t.Parallel() + parseErr := errors.New("evaluated guard unavailable") + for _, test := range []struct { + name, content string + missing bool + want error + }{ + {name: "literal true", content: "prevent_destroy = true", want: ErrPreventDestroy}, + {name: "literal false", content: "prevent_destroy = false"}, + {name: "absent", content: "locals { value = 1 }"}, + {name: "included protection cannot be ruled out", content: "include \"base\" { path = \"base.hcl\" }\nprevent_destroy = false", want: parseErr}, + {name: "expression", content: "prevent_destroy = local.protected", want: parseErr}, + {name: "null", content: "prevent_destroy = null", want: parseErr}, + {name: "non boolean", content: "prevent_destroy = \"false\"", want: parseErr}, + {name: "malformed", content: "prevent_destroy = [", want: parseErr}, + {name: "unreadable", missing: true, want: parseErr}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + fs := afero.NewMemMapFs() + if !test.missing { + require.NoError(t, afero.WriteFile(fs, "terragrunt.hcl", []byte(test.content), 0o600)) + } + err := staticDestroyGuard(fs, "terragrunt.hcl", parseErr) + if test.want == nil { + require.NoError(t, err) + } else { + require.ErrorIs(t, err, test.want) + } + }) + } +} diff --git a/plugins/terragrunt/internal/engine/discovery.go b/plugins/terragrunt/internal/engine/discovery.go index 867af38ab1e..2f98bcff62f 100644 --- a/plugins/terragrunt/internal/engine/discovery.go +++ b/plugins/terragrunt/internal/engine/discovery.go @@ -56,7 +56,7 @@ func within(path, directory string) bool { } // discoveryResolver evaluates one configuration file in the discovery overlay. -type discoveryResolver func(context.Context, model.Request, afero.Fs) (*model.Resolution, error) +type discoveryResolver func(context.Context, *model.Request, afero.Fs) (*model.Resolution, error) // projectDiscovery holds one inventory pass. Its overlay is invocation-local: // generated HCL retains its original virtual path and no source files or state @@ -153,7 +153,7 @@ func (d *projectDiscovery) parse(path string, generate bool) (*model.Resolution, if err := d.ctx.Err(); err != nil { return nil, err } - resolved, err := d.evaluate(d.ctx, req, d.overlay) + resolved, err := d.evaluate(d.ctx, &req, d.overlay) if contextErr := d.ctx.Err(); contextErr != nil { return nil, contextErr } @@ -329,7 +329,7 @@ func checkIdentityCollisions(root string, inventory []model.DiscoveredUnit) erro // generation, only this file and the nested stacks it declares are generated; // other stack files under the same directory are never listed or generated. func (r *inventoryReader) resolveStack(pctx *config.ParsingContext, request *model.Request, path string) (*model.Resolution, error) { - if generating(*request) { + if generating(request) { if err := r.generateStack(request, path, 0); err != nil { return nil, err } @@ -358,7 +358,7 @@ func (r *inventoryReader) generateStack(request *model.Request, path string, dep if err := atmosbridge.GenerateStack(r.ctx, r.logger, r.environment, path, request.Tofu); err != nil { return err } - stack, err := readStack(r.ctx, r.logger, r.environment, requestParsingContext(*request, path), path) + stack, err := readStack(r.ctx, r.logger, r.environment, requestParsingContext(request, path), path) if err != nil { return err } @@ -481,12 +481,19 @@ func (r *inventoryReader) resolveUnitInventory(pctx *config.ParsingContext, requ if err != nil { return nil, err } - for _, dependency := range append(slices.Clone(result.OutputDependencies), order...) { - if !slices.Contains(result.Dependencies, dependency) { - result.Dependencies = append(result.Dependencies, dependency) + result.Dependencies = mergedDependencies(result.OutputDependencies, order) + return result, nil +} + +// mergedDependencies preserves output-read order followed by unique scheduling-only dependencies. +func mergedDependencies(outputs, order []string) []string { + var result []string + for _, dependency := range append(slices.Clone(outputs), order...) { + if !slices.Contains(result, dependency) { + result = append(result, dependency) } } - return result, nil + return result } func outputDependencies(environment *atmosbridge.Venv, cfg *config.TerragruntConfig, path string) ([]string, error) { diff --git a/plugins/terragrunt/internal/engine/discovery_paths_test.go b/plugins/terragrunt/internal/engine/discovery_paths_test.go index 37a7c0d0d21..bbbf557fefe 100644 --- a/plugins/terragrunt/internal/engine/discovery_paths_test.go +++ b/plugins/terragrunt/internal/engine/discovery_paths_test.go @@ -452,7 +452,7 @@ func TestDiscoveryEvaluationErrors(t *testing.T) { child = filepath.Join(root, "generated", "terragrunt.stack.hcl") } failed, continued := false, false - evaluate := func(_ context.Context, req model.Request, _ afero.Fs) (*model.Resolution, error) { + evaluate := func(_ context.Context, req *model.Request, _ afero.Fs) (*model.Resolution, error) { if req.Path == later { continued = true return &model.Resolution{Path: later, Source: "module"}, nil @@ -499,7 +499,7 @@ func TestDiscoveryContextCanceledDuringEvaluation(t *testing.T) { require.NoError(t, os.WriteFile(filepath.Join(root, "terragrunt.hcl"), nil, 0o644)) ctx, cancel := context.WithCancel(t.Context()) defer cancel() - result, err := discoverProjectWithResolver(ctx, &model.Request{BasePath: root}, func(context.Context, model.Request, afero.Fs) (*model.Resolution, error) { + result, err := discoverProjectWithResolver(ctx, &model.Request{BasePath: root}, func(context.Context, *model.Request, afero.Fs) (*model.Resolution, error) { cancel() return &model.Resolution{}, nil }) diff --git a/plugins/terragrunt/internal/engine/execution.go b/plugins/terragrunt/internal/engine/execution.go index 4e9335b9183..91744a3e05d 100644 --- a/plugins/terragrunt/internal/engine/execution.go +++ b/plugins/terragrunt/internal/engine/execution.go @@ -73,7 +73,7 @@ func applyTimeExecution(request *model.Request, path string, planned *model.Exec // matches the plan-time evaluation. requestParsingContext also carries the feature flags. applyRequest := *request applyRequest.Command, applyRequest.Arguments = "apply", nil - apply := requestParsingContext(applyRequest, path) + apply := requestParsingContext(&applyRequest, path) // Dependency mock eligibility belongs to the plan being prepared; hook expressions see apply. apply.OriginalTerraformCommand = request.Command cfg, err := parse(apply) diff --git a/plugins/terragrunt/internal/engine/generation.go b/plugins/terragrunt/internal/engine/generation.go index 09b28a92db0..07153faa5d0 100644 --- a/plugins/terragrunt/internal/engine/generation.go +++ b/plugins/terragrunt/internal/engine/generation.go @@ -15,7 +15,7 @@ import ( func generatedFiles(ctx context.Context, logger log.Logger, cfg *config.TerragruntConfig, result *model.Resolution) error { result.GeneratedPolicies = make(map[string]string) result.UnitFileCopies = make(map[string]bool) - for _, generated := range cfg.GenerateConfigs { + for name, generated := range cfg.GenerateConfigs { if generated.Disable && (generated.IfDisabledStr == "" || generated.IfDisabledStr == "skip") { continue } @@ -32,23 +32,8 @@ func generatedFiles(ctx context.Context, logger log.Logger, cfg *config.Terragru Hints: []string{"Give each `generate` block a distinct `path`."}, File: result.Path, Key: "generate", Safe: true, Err: ErrUnsupportedExecution, } } - policy := generated.IfExistsStr - if generated.Disable { - policy = generated.IfDisabledStr - result.Generated[path] = "" - } else { - content, err := atmosbridge.RenderGenerated(ctx, logger, generated) - if err != nil { - return err - } - result.Generated[path] = string(content) - // Any generate block can interpolate credentials, regardless of its target. - markSensitive(result, path) - } - result.GeneratedPolicies[path] = policy - if !generated.Disable && declaresBackend(path, result.Generated[path]) { - // Arbitrary Terraform text has no verified state-reader identity. - return unresolvedGeneratedBackend(result.Path) + if err := renderGeneratedFile(ctx, logger, cfg, result, name); err != nil { + return err } } if err := unitLockFile(result); err != nil { @@ -93,3 +78,28 @@ func markSensitive(result *model.Resolution, path string) { } result.SensitiveGenerated[path] = true } + +// renderGeneratedFile applies a validated generation policy and rejects unverified backends. +func renderGeneratedFile(ctx context.Context, logger log.Logger, cfg *config.TerragruntConfig, result *model.Resolution, name string) error { + generated := cfg.GenerateConfigs[name] + path := filepath.Clean(generated.Path) + policy := generated.IfExistsStr + if generated.Disable { + policy = generated.IfDisabledStr + result.Generated[path] = "" + } else { + content, err := atmosbridge.RenderGenerated(ctx, logger, generated) + if err != nil { + return err + } + result.Generated[path] = string(content) + // Any generate block can interpolate credentials, regardless of its target. + markSensitive(result, path) + } + result.GeneratedPolicies[path] = policy + if !generated.Disable && declaresBackend(path, result.Generated[path]) { + // Arbitrary Terraform text has no verified state-reader identity. + return unresolvedGeneratedBackend(result.Path) + } + return nil +} diff --git a/plugins/terragrunt/internal/engine/logs_test.go b/plugins/terragrunt/internal/engine/logs_test.go index c5eff73581a..6eb992fd62a 100644 --- a/plugins/terragrunt/internal/engine/logs_test.go +++ b/plugins/terragrunt/internal/engine/logs_test.go @@ -578,8 +578,9 @@ func TestApplyTimeReparseWithholdsTransformedSensitiveInput(t *testing.T) { require.NoError(t, err) environment, err := evaluationEnvironment(ctx, &request, nil, request.Path) require.NoError(t, err) - pctx := requestParsingContext(request, request.Path) - cfg, err := parseUnit(ctx, l, environment, pctx, request, request.Path) + pctx := requestParsingContext(&request, request.Path) + unit := unitEvaluator{logger: l, environment: environment, pctx: pctx, request: request, path: request.Path} + cfg, err := unit.parseUnit(ctx) require.NoError(t, err) body, err := os.ReadFile(request.Path) require.NoError(t, err) @@ -587,7 +588,7 @@ func TestApplyTimeReparseWithholdsTransformedSensitiveInput(t *testing.T) { require.NoError(t, os.WriteFile(request.Path, body, 0o600)) l.Debug("before apply-raw-secret") require.NotContains(t, sink.Entries()[0].Message, "withheld") - _, _, err = unitExecution(ctx, l, environment, pctx, request, cfg, request.Path) + _, _, err = unit.unitExecution(ctx, cfg) require.NoError(t, err) entries := sink.Entries() require.Len(t, entries, 1) diff --git a/plugins/terragrunt/internal/engine/policies.go b/plugins/terragrunt/internal/engine/policies.go index 0769efc0d06..53c28c031c5 100644 --- a/plugins/terragrunt/internal/engine/policies.go +++ b/plugins/terragrunt/internal/engine/policies.go @@ -55,7 +55,7 @@ func localModuleSubdir(source string, existingRoot func(root string) bool) (root } root, subdir = volume+rest[:index], rest[index+2:] first := strings.SplitN(strings.TrimPrefix(root, "./"), "/", 2)[0] - if strings.Contains(first, ".") && !strings.HasPrefix(root, ".") && !filepath.IsAbs(root) && (existingRoot == nil || !existingRoot(root)) { + if strings.ContainsRune(first, '.') && !strings.HasPrefix(root, ".") && !filepath.IsAbs(root) && (existingRoot == nil || !existingRoot(root)) { return "", "", false } return root, subdir, true @@ -73,7 +73,7 @@ func safeModuleSubdir(subdir string) bool { return true } -func checkVersions(ctx context.Context, request model.Request, terraform, terragrunt string) error { +func checkVersions(ctx context.Context, request *model.Request, terraform, terragrunt string) error { check := func(name, constraint, actual string) error { if constraint == "" { return nil @@ -123,7 +123,7 @@ func checkUnitPolicies(ctx context.Context, request *model.Request, cfg *config. return missingSourceProblem(path) } if request.Phase != "backend" { - if err := checkVersions(ctx, *request, cfg.TerraformVersionConstraint, cfg.TerragruntVersionConstraint); err != nil { + if err := checkVersions(ctx, request, cfg.TerraformVersionConstraint, cfg.TerragruntVersionConstraint); err != nil { return err } } diff --git a/plugins/terragrunt/internal/engine/resolve.go b/plugins/terragrunt/internal/engine/resolve.go index 37c973a3df7..b75bd719ca7 100644 --- a/plugins/terragrunt/internal/engine/resolve.go +++ b/plugins/terragrunt/internal/engine/resolve.go @@ -15,8 +15,6 @@ import ( "github.com/gruntwork-io/terragrunt/pkg/log" "github.com/gruntwork-io/terragrunt/pkg/log/format" "github.com/gruntwork-io/terragrunt/pkg/options" - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/hclsyntax" "github.com/spf13/afero" "github.com/zclconf/go-cty/cty" @@ -24,16 +22,18 @@ import ( ) // Resolve evaluates HCL using the pinned Terragrunt parser. +// +//nolint:gocritic,lintroller // The value-based evaluator API delegates internally; standalone plugins cannot import the host tracker. func Resolve(ctx context.Context, request model.Request) (*model.Resolution, error) { - return resolve(ctx, request, nil) + return resolve(ctx, &request, nil) } // ErrPreventDestroy rejects a destroy operation on a unit that sets prevent_destroy. var ErrPreventDestroy = errors.New("unit is protected by prevent_destroy") // resolve evaluates one request and describes any rejection as a model.Problem the user can act on. -func resolve(ctx context.Context, request model.Request, filesystem afero.Fs) (*model.Resolution, error) { - result, err := resolveRequest(ctx, &request, filesystem) +func resolve(ctx context.Context, request *model.Request, filesystem afero.Fs) (*model.Resolution, error) { + result, err := resolveRequest(ctx, request, filesystem) if err != nil { return nil, problemFor(err, request.Path) } @@ -46,7 +46,7 @@ func resolveRequest(ctx context.Context, request *model.Request, filesystem afer if request.Phase == "inventory" { return discoverProject(ctx, request) } - filesystem, err := backendGenerationOverlay(ctx, *request, filesystem) + filesystem, err := backendGenerationOverlay(ctx, request, filesystem) if err != nil { return nil, err } @@ -67,8 +67,7 @@ func resolveRequest(ctx context.Context, request *model.Request, filesystem afer if err != nil { return nil, err } - reader := &inventoryReader{ctx: ctx, logger: logger, environment: environment} - pctx := requestParsingContext(*request, path) + pctx := requestParsingContext(request, path) scan := &sensitivityScan{} defer func() { files := append(append(pctx.FilesRead.Paths(), path), scan.applyFiles...) @@ -76,6 +75,14 @@ func resolveRequest(ctx context.Context, request *model.Request, filesystem afer sink.Withhold() } }() + unit := unitEvaluator{logger: logger, environment: environment, pctx: pctx, request: *request, path: path} + return unit.dispatch(ctx, scan) +} + +// dispatch selects the requested evaluation while sharing the sensitivity scan. +func (u *unitEvaluator) dispatch(ctx context.Context, scan *sensitivityScan) (*model.Resolution, error) { + request, pctx, path := &u.request, u.pctx, u.path + reader := &inventoryReader{ctx: ctx, logger: u.logger, environment: u.environment} if request.Phase == "iam" { return reader.resolveIAM(pctx, request, path) } @@ -85,11 +92,10 @@ func resolveRequest(ctx context.Context, request *model.Request, filesystem afer if err := reader.checkRequestFeatureOverrides(pctx, request, path); err != nil { return nil, err } - if discovering(*request) { + if discovering(request) { return reader.resolveUnitInventory(pctx, request, path) } - unit := unitEvaluator{logger: logger, environment: environment, pctx: pctx, request: *request, path: path} - return unit.resolve(ctx, scan) + return u.resolve(ctx, scan) } // unitEvaluator carries the parser dependencies shared by unit resolution stages. @@ -105,11 +111,11 @@ type unitEvaluator struct { // policies, and assembles the resolution with its execution data, backend, overlay, // and generated files. func (u *unitEvaluator) resolve(ctx context.Context, scan *sensitivityScan) (*model.Resolution, error) { - logger, environment, pctx, request, path := u.logger, u.environment, u.pctx, u.request, u.path - if err := checkDestroyGuard(ctx, logger, environment, pctx, request, path); err != nil { + environment, pctx, request, path := u.environment, u.pctx, &u.request, u.path + if err := u.checkDestroyGuard(ctx); err != nil { return nil, err } - cfg, err := parseUnit(ctx, logger, environment, pctx, request, path) + cfg, err := u.parseUnit(ctx) if err != nil { return nil, err } @@ -119,7 +125,7 @@ func (u *unitEvaluator) resolve(ctx context.Context, scan *sensitivityScan) (*mo redactLocals(logSinkFrom(ctx), environment.FS, path, cfg.Locals) scan.registered = true } - if err := checkUnitPolicies(ctx, &request, cfg, path); err != nil { + if err := checkUnitPolicies(ctx, request, cfg, path); err != nil { return nil, err } return u.buildResolution(ctx, cfg, &unitSensitivity{inputs: sensitiveInputs, scan: scan}) @@ -129,7 +135,7 @@ func (u *unitEvaluator) resolve(ctx context.Context, scan *sensitivityScan) (*mo // set before the backend resolves so the backend step sees the final result. func (u *unitEvaluator) buildResolution(ctx context.Context, cfg *config.TerragruntConfig, sensitivity *unitSensitivity) (*model.Resolution, error) { logger, environment, pctx, request, path := u.logger, u.environment, u.pctx, u.request, u.path - execution, applyFiles, err := unitExecution(ctx, logger, environment, pctx, request, cfg, path) + execution, applyFiles, err := u.unitExecution(ctx, cfg) sensitivity.scan.applyFiles = applyFiles if err != nil { return nil, err @@ -171,14 +177,14 @@ const ( // copy-on-write overlay before a backend read or IAM probe of a stack-generated unit. The // host probes IAM before the provider generates the stack, so on a clean checkout the unit // exists only in this overlay. The returned filesystem is the one the unit is then parsed from. -func backendGenerationOverlay(ctx context.Context, request model.Request, filesystem afero.Fs) (afero.Fs, error) { +func backendGenerationOverlay(ctx context.Context, request *model.Request, filesystem afero.Fs) (afero.Fs, error) { if (request.Phase != phaseBackend && request.Phase != "iam") || request.GenerationRoot == "" { return filesystem, nil } filesystem = afero.NewCopyOnWriteFs(afero.NewReadOnlyFs(afero.NewOsFs()), afero.NewMemMapFs()) - generation := request + generation := *request generation.Path, generation.Phase, generation.Command = request.GenerationRoot, phaseDiscover, "generate" - if _, err := resolve(ctx, generation, filesystem); err != nil { + if _, err := resolve(ctx, &generation, filesystem); err != nil { return nil, err } return filesystem, nil @@ -212,11 +218,11 @@ func evaluationLogger(ctx context.Context, level string) (log.Logger, error) { return logger, nil } -func discovering(request model.Request) bool { +func discovering(request *model.Request) bool { return request.Phase == phaseDiscover || request.Command == phaseDiscover } -func generating(request model.Request) bool { +func generating(request *model.Request) bool { return request.Command == "generate" && request.Phase != phaseBackend } @@ -231,8 +237,8 @@ func evaluationEnvironment(ctx context.Context, request *model.Request, filesyst if _, err := environment.FS.Stat(path); err != nil { return nil, err } - if discovering(*request) || request.Phase == phaseBackend || generating(*request) { - environment = atmosbridge.Discovery(environment, generating(*request)) + if discovering(request) || request.Phase == phaseBackend || generating(request) { + environment = atmosbridge.Discovery(environment, generating(request)) } else { environment = atmosbridge.AWS(ctx, environment) } @@ -241,7 +247,7 @@ func evaluationEnvironment(ctx context.Context, request *model.Request, filesyst // requestParsingContext evaluates the unit at path as the request's command; // discovery and generation evaluate as plan. -func requestParsingContext(request model.Request, path string) *config.ParsingContext { +func requestParsingContext(request *model.Request, path string) *config.ParsingContext { command := request.Command if command == "" || command == phaseDiscover || command == "generate" { command = "plan" @@ -303,16 +309,17 @@ func parsingContext(path, tofu, command string, arguments []string) *config.Pars // checkDestroyGuard rejects destroy before a full parse can evaluate HCL functions // for a unit that sets prevent_destroy. Backend reads never destroy. -func checkDestroyGuard(ctx context.Context, logger log.Logger, environment *atmosbridge.Venv, pctx *config.ParsingContext, request model.Request, path string) error { +func (u *unitEvaluator) checkDestroyGuard(ctx context.Context) error { + logger, environment, pctx, request, path := u.logger, u.environment, u.pctx, &u.request, u.path if request.Phase == phaseBackend || (request.Command != "plan" && request.Command != "apply" && request.Command != "destroy") { return nil } guard, err := config.PartialParseConfigFile(ctx, logger, atmosbridge.Discovery(environment, false), pctx.WithDecodeList(config.TerragruntFlags, config.TerraformExtraArgs), path, nil) if err != nil { - return failedDestroyGuard(&request, environment.FS, path, err) + return failedDestroyGuard(request, environment.FS, path, err) } - return checkPreventDestroy(&request, guard) + return checkPreventDestroy(request, guard) } // failedDestroyGuard preserves syntax-only decisions for known destroy requests. @@ -336,13 +343,8 @@ func failedDestroyGuard(request *model.Request, fs afero.Fs, path string, parseE // continues to the ordinary parse. Anything the syntax cannot settle (an expression, an include, an // unreadable or invalid file) keeps the original error, so the guard still fails closed. func staticDestroyGuard(fs afero.Fs, path string, parseErr error) error { - data, err := afero.ReadFile(fs, path) - if err != nil { - return parseErr - } - file, diagnostics := hclsyntax.ParseConfig(data, path, hcl.InitialPos) - body, ok := file.Body.(*hclsyntax.Body) - if diagnostics.HasErrors() || !ok { + body, ok := parseBody(fs, path) + if !ok { return parseErr } for _, block := range body.Blocks { @@ -367,7 +369,8 @@ func staticDestroyGuard(fs afero.Fs, path string, parseErr error) error { // unitExecution returns hooks and extra arguments as data for the host to run; // evaluation never executes them. Backend identity is read from a partial parse // that does not decode them. -func unitExecution(ctx context.Context, logger log.Logger, environment *atmosbridge.Venv, pctx *config.ParsingContext, request model.Request, cfg *config.TerragruntConfig, path string) (*model.Execution, []string, error) { +func (u *unitEvaluator) unitExecution(ctx context.Context, cfg *config.TerragruntConfig) (*model.Execution, []string, error) { + logger, environment, pctx, request, path := u.logger, u.environment, u.pctx, &u.request, u.path if request.Phase == phaseBackend { return nil, nil, nil } @@ -393,10 +396,11 @@ func unitExecution(ctx context.Context, logger log.Logger, environment *atmosbri redactLocals(sink, environment.FS, path, parsed.Locals) return parsed, nil } - return applyTimeExecution(&request, path, execution, executionReads{filesystem: environment.FS, paths: pctx.FilesRead.Paths()}, reparse) + return applyTimeExecution(request, path, execution, executionReads{filesystem: environment.FS, paths: pctx.FilesRead.Paths()}, reparse) } -func parseUnit(ctx context.Context, logger log.Logger, environment *atmosbridge.Venv, pctx *config.ParsingContext, request model.Request, path string) (*config.TerragruntConfig, error) { +func (u *unitEvaluator) parseUnit(ctx context.Context) (*config.TerragruntConfig, error) { + logger, environment, pctx, request, path := u.logger, u.environment, u.pctx, &u.request, u.path if request.Phase == phaseBackend { environment = environment.WithFS(withoutInputsFS{Fs: environment.FS, inputs: newInputReferences(path)}) cfg, err := config.PartialParseConfigFile(ctx, logger, environment, pctx.WithDecodeList(config.TerraformSource, config.RemoteStateBlock), path, nil) @@ -455,11 +459,15 @@ type withoutInputsFS struct { } // Open reads through OpenFile so every read path strips inputs. +// +//nolint:lintroller // Delegates to OpenFile at the standalone plugin boundary. func (f withoutInputsFS) Open(name string) (afero.File, error) { return f.OpenFile(name, os.O_RDONLY, 0) } // OpenFile returns the stripped content for read-only opens of HCL files. +// +//nolint:lintroller // Plugin code cannot import the host performance tracker. func (f withoutInputsFS) OpenFile(name string, flag int, perm os.FileMode) (afero.File, error) { file, err := f.Fs.OpenFile(name, flag, perm) if err != nil || flag != os.O_RDONLY || !strings.HasSuffix(name, ".hcl") { diff --git a/plugins/terragrunt/internal/engine/resolve_test.go b/plugins/terragrunt/internal/engine/resolve_test.go index d16eebcb2bd..6e872b8ae82 100644 --- a/plugins/terragrunt/internal/engine/resolve_test.go +++ b/plugins/terragrunt/internal/engine/resolve_test.go @@ -130,7 +130,7 @@ func TestVersionConstraintsUseSelectedExecutable(t *testing.T) { } { t.Run(test.name, func(t *testing.T) { request := model.Request{Tofu: executable, Environment: map[string]string{"ATMOS_TERRAGRUNT_VERSION_CHILD": test.actual}} - err := checkVersions(t.Context(), request, test.constraint, "") + err := checkVersions(t.Context(), &request, test.constraint, "") if test.want == "" { require.NoError(t, err) } else { diff --git a/plugins/terragrunt/internal/provider/discovery.go b/plugins/terragrunt/internal/provider/discovery.go index db26b8f18a4..520e5adcc61 100644 --- a/plugins/terragrunt/internal/provider/discovery.go +++ b/plugins/terragrunt/internal/provider/discovery.go @@ -227,7 +227,7 @@ func importPaths(request *pluginv1.DiscoverComponentsRequest) ([]string, error) // project-relative unit paths discovery compares against. func directoryPattern(path string) string { clean := filepath.ToSlash(filepath.Clean(filepath.FromSlash(path))) - if clean == "." { + if clean == currentDirectory { return "**" } return clean + "/**" @@ -241,11 +241,14 @@ func derivedAddress(base, path string) (*pluginv1.ComponentAddress, error) { return nil, err } stack, name := "default", "root" - if dir != "." { + if dir != currentDirectory { name = filepath.Base(dir) - if parent := filepath.ToSlash(filepath.Dir(dir)); parent != "." { + if parent := filepath.ToSlash(filepath.Dir(dir)); parent != currentDirectory { stack = parent } } return &pluginv1.ComponentAddress{Stack: stack, Component: name, ComponentType: "terraform"}, nil } + +// currentDirectory is the project-relative identity of its root. +const currentDirectory = "." diff --git a/plugins/terragrunt/internal/provider/provider.go b/plugins/terragrunt/internal/provider/provider.go index a28a01ad769..76bcc6ace87 100644 --- a/plugins/terragrunt/internal/provider/provider.go +++ b/plugins/terragrunt/internal/provider/provider.go @@ -198,7 +198,7 @@ func optionProblem(name, hint string) *model.Problem { } func operation(root, name string, op *pluginv1.ComponentOperation, invocation *pluginv1.Invocation) (model.Request, error) { - if name != "terragrunt" || !filepath.IsAbs(root) || op == nil || (op.Mode != ModeNative && op.Mode != ModeExecutable && op.Mode != "iam-probe") { + if name != "terragrunt" || !filepath.IsAbs(root) || op == nil || !supportedOperationMode(op.Mode) { return model.Request{}, ErrUnsupported } env := maps.Clone(invocation.GetEnvironment()) @@ -283,3 +283,8 @@ func validate(ctx context.Context, request *pluginv1.ComponentRequest) error { } return settings(request.GetProviderConfiguration()) } + +// supportedOperationMode accepts execution modes represented by the native evaluator. +func supportedOperationMode(mode string) bool { + return mode == ModeNative || mode == ModeExecutable || mode == "iam-probe" +} From d5e49114e7a46edb106ee1fa0aa81c9bd0bf6458 Mon Sep 17 00:00:00 2001 From: Erik Osterman Date: Tue, 17 Nov 2026 11:20:06 -0600 Subject: [PATCH 28/28] fix(terragrunt): restore safe live evaluation progress Emit static path-free progress before evaluation, while buffering unit details until sensitivity registration permits redaction. Preserve the unit-path security fix and verify live progress, delayed masked details, and default-level silence through the real CLI acceptance test. --- .../terragrunt/internal/engine/logs_test.go | 28 +++++++++++++++++++ plugins/terragrunt/internal/engine/resolve.go | 4 ++- tests/terragrunt_streaming_test.go | 24 ++++++++++++---- 3 files changed, 50 insertions(+), 6 deletions(-) diff --git a/plugins/terragrunt/internal/engine/logs_test.go b/plugins/terragrunt/internal/engine/logs_test.go index 9cf7c13c735..583e8df66de 100644 --- a/plugins/terragrunt/internal/engine/logs_test.go +++ b/plugins/terragrunt/internal/engine/logs_test.go @@ -530,3 +530,31 @@ func TestLogSinkBuffersUnitPathsUntilSensitiveValuesAreRegistered(t *testing.T) assert.Empty(t, entries[0].Unit) assert.Contains(t, entries[0].Message, "withheld") } + +func TestResolveForwardsPathFreeProgressAndBuffersRedactedDetails(t *testing.T) { + root, err := filepath.EvalSymlinks(t.TempDir()) + require.NoError(t, err) + request := nativeUnitAt(t, filepath.Join(root, "private-unit"), "locals { token = sensitive(\"private-unit\") }\n") + request.BasePath = root + sink := NewLogSink("debug", root) + var forwarded []model.LogEntry + sink.Forward(func(entry *model.LogEntry) { forwarded = append(forwarded, *entry) }) + + _, err = Resolve(WithLogSink(t.Context(), sink), request) + + require.NoError(t, err) + require.Len(t, forwarded, 1) + assert.Equal(t, "Starting unit evaluation", forwarded[0].Message) + assert.Equal(t, "info", forwarded[0].Level) + assert.Empty(t, forwarded[0].Unit) + assert.Empty(t, forwarded[0].Fields) + var detailed []model.LogEntry + for _, entry := range sink.Entries() { + assert.NotContains(t, entry.Unit, "private-unit") + if entry.Message == "Evaluating unit" { + detailed = append(detailed, entry) + } + } + require.Len(t, detailed, 1) + assert.Equal(t, "", detailed[0].Unit) +} diff --git a/plugins/terragrunt/internal/engine/resolve.go b/plugins/terragrunt/internal/engine/resolve.go index 7eb24b7ba30..351e59a9344 100644 --- a/plugins/terragrunt/internal/engine/resolve.go +++ b/plugins/terragrunt/internal/engine/resolve.go @@ -58,8 +58,10 @@ func resolveRequest(ctx context.Context, request *model.Request, filesystem afer if err != nil { return nil, err } - // The sink buffers the unit path until configuration values can be redacted. + // Only static, path-free progress is safe before evaluation discovers secrets. + // The sink buffers the detailed event until configuration values can be redacted. if sink := logSinkFrom(ctx); sink != nil { + sink.Event(log.InfoLevel, "Starting unit evaluation", "") sink.Event(log.InfoLevel, "Evaluating unit", filepath.Dir(path)) } ctx = config.WithCaches(ctx) diff --git a/tests/terragrunt_streaming_test.go b/tests/terragrunt_streaming_test.go index 397ac26d48b..f45c2500d21 100644 --- a/tests/terragrunt_streaming_test.go +++ b/tests/terragrunt_streaming_test.go @@ -116,13 +116,15 @@ func buildGateTool(t *testing.T) string { // A unit whose inputs run a command that stays open until the test releases it, like a slow run_cmd, a // registry fetch, or an STS exchange does in real use. const slowUnit = `terraform { source = "../../../modules/unit" } +locals { path_token = sensitive("live") } inputs = { greeting = run_cmd("--terragrunt-quiet", "%s", "--wait-for", "%s") } ` // TestTerragruntLogsReachTheTerminalWhileAUnitIsStillEvaluating runs the real CLI, the real plugin, and // real OpenTofu. A unit's evaluation is held open by a command; the test watches stderr as the process -// writes it and releases the command only after the earlier log line of that unit is visible. If the plugin -// returned its log events with the result, the line could not appear first, the command would never be +// writes it and releases the command only after path-free progress is visible. Detailed unit paths must +// wait until evaluation registers sensitive values. If the plugin returned all its log events with the +// result, the progress line could not appear first, the command would never be // released, and the unit would fail on the helper's own time limit. func TestTerragruntLogsReachTheTerminalWhileAUnitIsStillEvaluating(t *testing.T) { if testing.Short() { @@ -172,19 +174,22 @@ func TestTerragruntLogsReachTheTerminalWhileAUnitIsStillEvaluating(t *testing.T) defer func() { _ = os.WriteFile(gate, nil, 0o600) }() require.Eventually(t, func() bool { - _, seen := stderr.find("Evaluating unit", "component=slow", "stack=dev") + _, seen := stderr.find("Starting unit evaluation", "component=slow", "stack=dev") return seen }, 2*time.Minute, 10*time.Millisecond, "the unit's log line never appeared while its command was open:\n%s", stderr.text()) // Only preparing the unit scopes an event to its component and stack, and preparing is the call that // runs the held command right after logging this line. - early, _ := stderr.find("Evaluating unit", "component=slow", "stack=dev") + early, _ := stderr.find("Starting unit evaluation", "component=slow", "stack=dev") select { case <-cli.done: t.Fatalf("the command finished before it was released (%v), so the line was not delivered live:\n%s", cli.err, stderr.text()) default: } - assert.Contains(t, early.Text, "unit=live/dev/slow") + assert.NotContains(t, early.Text, "unit=", "paths may contain secrets not yet discovered") + assert.NotContains(t, early.Text, "live/dev/slow") assert.Contains(t, early.Text, "plugin=terragrunt") + _, detailed := stderr.find("Evaluating unit", "component=slow", "stack=dev") + assert.False(t, detailed, "unit details must wait for sensitivity registration") released := time.Now() require.NoError(t, os.WriteFile(gate, nil, 0o600)) @@ -193,6 +198,13 @@ func TestTerragruntLogsReachTheTerminalWhileAUnitIsStillEvaluating(t *testing.T) require.NoError(t, err, "stderr:\n%s", stderr.text()) assert.True(t, early.At.Before(released), "line at %s, release at %s", early.At, released) assert.True(t, released.Before(finished)) + late, found := stderr.find("Evaluating unit", "component=slow", "stack=dev") + require.True(t, found, "the completed evaluation must deliver redacted details:\n%s", stderr.text()) + assert.Contains(t, late.Text, "unit=/dev/slow") + assert.NotContains(t, late.Text, "unit=live/dev/slow") + assert.Contains(t, late.Text, "plugin=terragrunt") + assert.True(t, released.Before(late.At), "detailed event must arrive after the gate opens") + assert.NotContains(t, stdout.text(), "Starting unit evaluation", "progress never reaches the data channel") assert.NotContains(t, stdout.text(), "Evaluating unit", "log events never reach the data channel") }) @@ -201,6 +213,8 @@ func TestTerragruntLogsReachTheTerminalWhileAUnitIsStillEvaluating(t *testing.T) cli := run(t, "terraform", "plan", "slow", "-s", "dev") stdout, stderr := cli.stdout, cli.stderr require.NoError(t, cli.wait(), "stderr:\n%s", stderr.text()) + assert.NotContains(t, stderr.text(), "Starting unit evaluation") + assert.NotContains(t, stdout.text(), "Starting unit evaluation") assert.NotContains(t, stderr.text(), "Evaluating unit") assert.NotContains(t, stdout.text(), "Evaluating unit") })