diff --git a/doc/rfc/stovepipe/steps/process.md b/doc/rfc/stovepipe/steps/process.md index 9ef04dabd..1b4a75b24 100644 --- a/doc/rfc/stovepipe/steps/process.md +++ b/doc/rfc/stovepipe/steps/process.md @@ -60,13 +60,13 @@ Strategy and baseline are **immutable once processing**: a redelivery sees `proc Validation is expensive and shares a baseline, so heads arriving while an earlier one runs `build → buildsignal → record` must not all start builds at once. -**Runtime state** lives on the Queue row; the **concurrency cap** does not — it is deployment configuration, resolved at gate-check time the same way SubmitQueue separates `storage` from `queueconfig` (see [submitqueue/extension/queueconfig/README.md](../../../../submitqueue/extension/queueconfig/README.md)): pipeline stages read mutable state from the store and read knobs like `max_concurrent` from a config `Store` (or a wiring default for MVP). Config is not written by ingest/process/record and does not need optimistic locking. +**Runtime state** lives on the Queue row; the **concurrency cap** does not — it is deployment configuration, resolved at gate-check time the same way SubmitQueue separates `storage` from `queueconfig` (see [submitqueue/extension/queueconfig/README.md](../../../../submitqueue/extension/queueconfig/README.md)): pipeline stages read mutable state from the store and read knobs like `max_concurrent` from a config `Store`. Config is not written by ingest/process/record and does not need optimistic locking. | Source | Field | Meaning | |---|---|---| | Queue row | `last_green_uri` | Bookmark `buildsignal` advances on a successful build; empty until first green. | | Queue row | `in_flight_count` | Requests past `process` and not yet terminal. `process` increments on admit; `record` (or DLQ reconciliation) decrements on terminal. | -| Queue config | `max_concurrent` | Cap on concurrent in-flight validations. **Default 1** (global wiring default for MVP; per-queue override when a Stovepipe `queueconfig` extension lands). | +| Queue config | `max_concurrent` | Cap on concurrent in-flight validations. **Default 1** in the shared stage configuration; optional shared and per-queue overrides live under the process stage configuration. | A slot is held from admit until the build goes terminal (`process → build → buildsignal`), not just while `process` runs. It is released when the Request reaches **any** terminal state and `in_flight_count` is decremented — `buildsignal` recording the build's outcome, success *or* failure, or the DLQ reconciler forcing a terminal `failed` (see [integrity](#in_flight_count-integrity)). A build *failure* frees the slot just like a success; only a Request that never terminates keeps its slot. diff --git a/service/stovepipe/README.md b/service/stovepipe/README.md index ff242b92a..aa99a8f92 100644 --- a/service/stovepipe/README.md +++ b/service/stovepipe/README.md @@ -49,10 +49,19 @@ The Stovepipe controllers live under [`stovepipe/controller/`](../../stovepipe/c |---------------------|----------|------------------------------------------|----------------------| | `STORAGE_MYSQL_DSN` | yes | Storage database DSN | — | | `QUEUE_MYSQL_DSN` | yes | Queue database DSN | — | +| `MQ_TENANTS` | yes | Comma-separated queue names served by this instance | — | | `QUEUE_LOG_LEVEL` | no | Message-queue logger level | `info` | | `PORT` | no | gRPC listen address | `:8083` | | `HOSTNAME` | no | Subscriber name for the queue consumers | `stovepipe-` | +## Queue and stage configuration + +`MQ_TENANTS` defines the queues served by this instance. Stage settings use built-in values unless overridden through a YAML file selected with `-config`. + +The file supports shared settings under `stages` and optional per-queue overrides under `queues`. Omitted fields inherit shared settings or built-in values. Per-queue overrides must reference a registered queue. + +Configuration is validated at startup; changes require a restart. See the [configuration provider](../../stovepipe/extension/queueconfig/README.md) for details. + ## Running ### Docker Compose (recommended) diff --git a/service/stovepipe/server/BUILD.bazel b/service/stovepipe/server/BUILD.bazel index 2703fd9d3..dc941dc3f 100644 --- a/service/stovepipe/server/BUILD.bazel +++ b/service/stovepipe/server/BUILD.bazel @@ -44,7 +44,8 @@ go_library( "//stovepipe/extension/fixer/noop:go_default_library", "//stovepipe/extension/projectissues/noop:go_default_library", "//stovepipe/extension/projectstatus/noop:go_default_library", - "//stovepipe/extension/queueconfig/default:go_default_library", + "//stovepipe/extension/queueconfig:go_default_library", + "//stovepipe/extension/queueconfig/yaml:go_default_library", "//stovepipe/extension/sourcecontrol:go_default_library", "//stovepipe/extension/sourcecontrol/fake:go_default_library", "//stovepipe/extension/storage:go_default_library", @@ -98,9 +99,13 @@ go_test( "//platform/extension/messagequeue/mock:go_default_library", "//stovepipe/controller/dlq:go_default_library", "//stovepipe/core/messagequeue:go_default_library", + "//stovepipe/core/queueconfig:go_default_library", "//stovepipe/core/requestlog:go_default_library", "//stovepipe/entity:go_default_library", "//stovepipe/extension/buildissue/noop:go_default_library", + "//stovepipe/extension/queueconfig:go_default_library", + "//stovepipe/extension/queueconfig/mock:go_default_library", + "//stovepipe/extension/queueconfig/yaml:go_default_library", "//stovepipe/extension/sourcecontrol:go_default_library", "//stovepipe/extension/storage:go_default_library", "//stovepipe/extension/storage/mock:go_default_library", @@ -108,6 +113,8 @@ go_test( "@com_github_stretchr_testify//require:go_default_library", "@com_github_uber_go_tally//:go_default_library", "@org_uber_go_mock//gomock:go_default_library", + "@org_uber_go_zap//:go_default_library", "@org_uber_go_zap//zaptest:go_default_library", + "@org_uber_go_zap//zaptest/observer:go_default_library", ], ) diff --git a/service/stovepipe/server/main.go b/service/stovepipe/server/main.go index 227b3e239..e7d954c96 100644 --- a/service/stovepipe/server/main.go +++ b/service/stovepipe/server/main.go @@ -18,6 +18,7 @@ import ( "context" "database/sql" "errors" + "flag" "fmt" "net" "os" @@ -66,7 +67,8 @@ import ( fixernoop "github.com/uber/submitqueue/stovepipe/extension/fixer/noop" projectissuesnoop "github.com/uber/submitqueue/stovepipe/extension/projectissues/noop" projectstatusnoop "github.com/uber/submitqueue/stovepipe/extension/projectstatus/noop" - queueconfigdefault "github.com/uber/submitqueue/stovepipe/extension/queueconfig/default" + queueconfigprovider "github.com/uber/submitqueue/stovepipe/extension/queueconfig" + queueconfigyaml "github.com/uber/submitqueue/stovepipe/extension/queueconfig/yaml" "github.com/uber/submitqueue/stovepipe/extension/sourcecontrol" sourcecontrolfake "github.com/uber/submitqueue/stovepipe/extension/sourcecontrol/fake" "github.com/uber/submitqueue/stovepipe/extension/storage" @@ -122,8 +124,10 @@ func (hookResolver) For(*basehook.HookEvent) []hookext.Hook { } func main() { + configPath := flag.String("config", "", "optional path to Stovepipe stage settings and per-queue overrides") + flag.Parse() code := 0 - if err := run(); err != nil { + if err := run(*configPath); err != nil { if errors.Is(err, context.Canceled) { fmt.Println("Stovepipe server stopped by signal") @@ -139,7 +143,7 @@ func main() { os.Exit(code) } -func run() error { +func run(configPath string) error { // Set up signal handling early so retry loops can respond to SIGTERM ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer cancel() @@ -151,6 +155,18 @@ func run() error { } defer logger.Sync() + tenants, err := servicemq.ParseRequiredTenants(os.Getenv("MQ_TENANTS")) + if err != nil { + return fmt.Errorf("failed to configure queue subscribers: %w", err) + } + + configs, err := queueconfigyaml.NewStore(configPath, tenants) + if err != nil { + return fmt.Errorf("load queue configurations: %w", err) + } + + logEffectiveQueueConfigurations(ctx, logger, configs) + // Initialize metrics scope scope := tally.NewTestScope("stovepipe", nil) metricsStopCh := make(chan interface{}, 1) @@ -213,11 +229,6 @@ func run() error { return fmt.Errorf("failed to configure queue database pool: %w", err) } - tenants, err := servicemq.ParseRequiredTenants(os.Getenv("MQ_TENANTS")) - if err != nil { - return fmt.Errorf("failed to configure queue subscribers: %w", err) - } - mysqlQueue, err := queueMySQL.NewQueue(queueMySQL.Params{ DB: queueDB, Logger: logger, @@ -271,7 +282,20 @@ func run() error { storageFty := storageFactory{backend: store} materializer := requestlog.NewMaterializer(scope) - primaryCount, err := registerPrimaryControllers(primaryConsumer, logger.Sugar(), scope, storageFty, materializer, registry, sourceControl, brf, hookResolver{}, detectorFactory, repairExecutors) + primaryCount, err := registerPrimaryControllers( + primaryConsumer, + logger.Sugar(), + scope, + storageFty, + materializer, + configs, + registry, + sourceControl, + brf, + hookResolver{}, + detectorFactory, + repairExecutors, + ) if err != nil { return err } @@ -385,6 +409,21 @@ func run() error { return err } +func logEffectiveQueueConfigurations(ctx context.Context, logger *zap.Logger, configs queueconfigprovider.Store) { + resolved, err := configs.List(ctx) + if err != nil { + logger.Warn("failed to list effective queue configurations", zap.Error(err)) + return + } + + for _, cfg := range resolved { + logger.Info("queue configuration loaded", + zap.String("queue", cfg.Name), + zap.Any("stages", cfg.Stages), + ) + } +} + // registerPrimaryControllers creates the primary-pipeline queue controllers and // registers them with c, returning how many were registered. func registerPrimaryControllers( @@ -393,6 +432,7 @@ func registerPrimaryControllers( scope tally.Scope, store storage.Factory, materializer requestlog.Materializer, + configs queueconfigprovider.Store, registry consumer.TopicRegistry, sourceControl sourcecontrol.Factory, brf buildrunner.Factory, @@ -407,7 +447,7 @@ func registerPrimaryControllers( scope, store, materializer, - queueconfigdefault.NewStore(), + configs, sourceControl, registry, stovepipemq.TopicKeyProcess, diff --git a/service/stovepipe/server/main_test.go b/service/stovepipe/server/main_test.go index f03186f88..d5edf89c3 100644 --- a/service/stovepipe/server/main_test.go +++ b/service/stovepipe/server/main_test.go @@ -30,14 +30,20 @@ import ( queuemock "github.com/uber/submitqueue/platform/extension/messagequeue/mock" "github.com/uber/submitqueue/stovepipe/controller/dlq" stovepipemq "github.com/uber/submitqueue/stovepipe/core/messagequeue" + "github.com/uber/submitqueue/stovepipe/core/queueconfig" "github.com/uber/submitqueue/stovepipe/core/requestlog" "github.com/uber/submitqueue/stovepipe/entity" buildissuenoop "github.com/uber/submitqueue/stovepipe/extension/buildissue/noop" + queueconfigprovider "github.com/uber/submitqueue/stovepipe/extension/queueconfig" + queueconfigmock "github.com/uber/submitqueue/stovepipe/extension/queueconfig/mock" + queueconfigyaml "github.com/uber/submitqueue/stovepipe/extension/queueconfig/yaml" "github.com/uber/submitqueue/stovepipe/extension/sourcecontrol" "github.com/uber/submitqueue/stovepipe/extension/storage" storagemock "github.com/uber/submitqueue/stovepipe/extension/storage/mock" "go.uber.org/mock/gomock" + "go.uber.org/zap" "go.uber.org/zap/zaptest" + "go.uber.org/zap/zaptest/observer" ) // recordingConsumer captures what the host registers instead of subscribing. @@ -54,11 +60,25 @@ func (c *recordingConsumer) Start(context.Context) error { return nil } func (c *recordingConsumer) Stop(int64) error { return nil } +func testQueueConfigs(t *testing.T) queueconfigprovider.Store { + t.Helper() + + configs, err := queueconfigyaml.NewStore("", []string{"monorepo/main"}) + require.NoError(t, err) + + return configs +} + // registeredControllers runs the host's registration exactly as run() does and // returns the registry it registers against, the primary controllers, and the // DLQ controllers. func registeredControllers(t *testing.T) (consumer.TopicRegistry, []consumer.Controller, []consumer.Controller) { t.Helper() + return registeredControllersWithConfig(t, testQueueConfigs(t)) +} + +func registeredControllersWithConfig(t *testing.T, configs queueconfigprovider.Store) (consumer.TopicRegistry, []consumer.Controller, []consumer.Controller) { + t.Helper() registry, err := newTopicRegistry(nil, "subscriber") require.NoError(t, err) @@ -68,8 +88,20 @@ func registeredControllers(t *testing.T) (consumer.TopicRegistry, []consumer.Con primary := &recordingConsumer{} deadLetter := &recordingConsumer{} - _, err = registerPrimaryControllers(primary, logger, tally.NoopScope, store, requestlog.NewMaterializer(tally.NoopScope), registry, - &fakeSourceControlFactory{}, fakeBuildRunnerFactory{}, hookResolver{}, buildissuenoop.New(), noopRepairExecutorFactory{}) + _, err = registerPrimaryControllers( + primary, + logger, + tally.NoopScope, + store, + requestlog.NewMaterializer(tally.NoopScope), + configs, + registry, + &fakeSourceControlFactory{}, + fakeBuildRunnerFactory{}, + hookResolver{}, + buildissuenoop.New(), + noopRepairExecutorFactory{}, + ) require.NoError(t, err) _, err = registerDLQControllers(deadLetter, logger, tally.NoopScope, store, requestlog.NewMaterializer(tally.NoopScope), registry, noopRepairExecutorFactory{}) @@ -215,9 +247,20 @@ func TestRegisteredFixControllerRetainsPerExecutorDisposition(t *testing.T) { registry, err := newTopicRegistry(queue, "subscriber") require.NoError(t, err) primary := &recordingConsumer{} - _, err = registerPrimaryControllers(primary, zaptest.NewLogger(t).Sugar(), tally.NoopScope, stores, - requestlog.NewMaterializer(tally.NoopScope), registry, &fakeSourceControlFactory{}, fakeBuildRunnerFactory{}, - hookResolver{}, buildissuenoop.New(), noopRepairExecutorFactory{}) + _, err = registerPrimaryControllers( + primary, + zaptest.NewLogger(t).Sugar(), + tally.NoopScope, + stores, + requestlog.NewMaterializer(tally.NoopScope), + testQueueConfigs(t), + registry, + &fakeSourceControlFactory{}, + fakeBuildRunnerFactory{}, + hookResolver{}, + buildissuenoop.New(), + noopRepairExecutorFactory{}, + ) require.NoError(t, err) var fixController consumer.Controller for _, controller := range primary.controllers { @@ -348,3 +391,43 @@ func TestFakeSourceControlFactorySharesPromotionPerQueue(t *testing.T) { require.NoError(t, err) assert.Empty(t, current) } + +func TestLogEffectiveQueueConfigurations(t *testing.T) { + for _, tt := range []struct { + name string + listError error + }{ + {"resolved settings", nil}, + {"lookup failure is a warning", assert.AnError}, + } { + t.Run(tt.name, func(t *testing.T) { + ctrl := gomock.NewController(t) + provider := queueconfigmock.NewMockStore(ctrl) + configs := []queueconfig.QueueConfig{ + {Name: "ordinary", Stages: queueconfig.DefaultStages()}, + {Name: "fast", Stages: queueconfig.DefaultStages()}, + } + configs[1].Stages.BuildAnalysis.PollDelayMs = 250 + provider.EXPECT().List(gomock.Any()).Return(configs, tt.listError) + core, observed := observer.New(zap.InfoLevel) + + logEffectiveQueueConfigurations(context.Background(), zap.New(core), provider) + + entries := observed.All() + if tt.listError != nil { + require.Len(t, entries, 1) + assert.Equal(t, zap.WarnLevel, entries[0].Level) + assert.Contains(t, entries[0].ContextMap(), "error") + return + } + + require.Len(t, entries, len(configs)) + for i, cfg := range configs { + assert.Equal(t, zap.InfoLevel, entries[i].Level) + fields := entries[i].ContextMap() + assert.Equal(t, cfg.Name, fields["queue"]) + assert.Equal(t, cfg.Stages, fields["stages"]) + } + }) + } +} diff --git a/stovepipe/controller/process/BUILD.bazel b/stovepipe/controller/process/BUILD.bazel index a48c7a35e..314a8df84 100644 --- a/stovepipe/controller/process/BUILD.bazel +++ b/stovepipe/controller/process/BUILD.bazel @@ -16,6 +16,7 @@ go_library( "//stovepipe/core/hookevent:go_default_library", "//stovepipe/core/loader:go_default_library", "//stovepipe/core/messagequeue:go_default_library", + "//stovepipe/core/queueconfig:go_default_library", "//stovepipe/core/requestlog:go_default_library", "//stovepipe/entity:go_default_library", "//stovepipe/extension/queueconfig:go_default_library", @@ -43,10 +44,11 @@ go_test( "//platform/metrics:go_default_library", "//stovepipe/core/hookevent:go_default_library", "//stovepipe/core/messagequeue:go_default_library", + "//stovepipe/core/queueconfig:go_default_library", "//stovepipe/core/requestlog:go_default_library", "//stovepipe/core/requestlog/mock:go_default_library", "//stovepipe/entity:go_default_library", - "//stovepipe/extension/queueconfig/default:go_default_library", + "//stovepipe/extension/queueconfig/mock:go_default_library", "//stovepipe/extension/sourcecontrol:go_default_library", "//stovepipe/extension/sourcecontrol/mock:go_default_library", "//stovepipe/extension/storage:go_default_library", diff --git a/stovepipe/controller/process/process.go b/stovepipe/controller/process/process.go index 78e0d6a06..c150599b5 100644 --- a/stovepipe/controller/process/process.go +++ b/stovepipe/controller/process/process.go @@ -35,9 +35,10 @@ import ( "github.com/uber/submitqueue/stovepipe/core/hookevent" "github.com/uber/submitqueue/stovepipe/core/loader" stovepipemq "github.com/uber/submitqueue/stovepipe/core/messagequeue" + "github.com/uber/submitqueue/stovepipe/core/queueconfig" "github.com/uber/submitqueue/stovepipe/core/requestlog" "github.com/uber/submitqueue/stovepipe/entity" - "github.com/uber/submitqueue/stovepipe/extension/queueconfig" + queueconfigprovider "github.com/uber/submitqueue/stovepipe/extension/queueconfig" "github.com/uber/submitqueue/stovepipe/extension/sourcecontrol" "github.com/uber/submitqueue/stovepipe/extension/storage" "go.uber.org/zap" @@ -51,7 +52,7 @@ type Controller struct { metricsScope tally.Scope stores storage.Factory materializer requestlog.Materializer - queueConfigs queueconfig.Store + queueConfigs queueconfigprovider.Store sourceControl sourcecontrol.Factory registry consumer.TopicRegistry topicKey consumer.TopicKey @@ -70,7 +71,7 @@ func NewController( scope tally.Scope, stores storage.Factory, materializer requestlog.Materializer, - queueConfigs queueconfig.Store, + queueConfigs queueconfigprovider.Store, sourceControl sourcecontrol.Factory, registry consumer.TopicRegistry, topicKey consumer.TopicKey, @@ -185,8 +186,6 @@ func (c *Controller) processAccepted(ctx context.Context, store storage.Storage, cfg, err := c.queueConfigs.Get(ctx, request.Queue) if err != nil { - // TODO(queueconfig): decide retryability when a real config store lands — is a - // missing queue "drop" (non-retryable) or "retry until configured"? return fmt.Errorf("failed to load queue config for %s: %w", request.Queue, err) } @@ -228,9 +227,9 @@ func (c *Controller) coalesce(ctx context.Context, store storage.Storage, reques // admitRequest holds the delivery while the build-slot gate is closed; otherwise it marks the // request processing, counts its build slot, and publishes it to build. -func (c *Controller) admitRequest(ctx context.Context, store storage.Storage, delivery consumer.Delivery, request entity.Request, queueRow entity.Queue, cfg entity.QueueConfig) error { - if queueRow.InFlightCount >= cfg.MaxConcurrent { - return c.holdForBuildSlot(ctx, delivery, request, queueRow.InFlightCount, cfg.GateWaitDelayMs) +func (c *Controller) admitRequest(ctx context.Context, store storage.Storage, delivery consumer.Delivery, request entity.Request, queueRow entity.Queue, cfg queueconfig.QueueConfig) error { + if queueRow.InFlightCount >= cfg.Stages.Process.MaxConcurrent { + return c.holdForBuildSlot(ctx, delivery, request, queueRow.InFlightCount, cfg.Stages.Process.GateWaitDelayMs) } strategy, baseURI, err := c.deriveBuildStrategy(ctx, queueRow, request) diff --git a/stovepipe/controller/process/process_test.go b/stovepipe/controller/process/process_test.go index 834d3ab44..e86a1a554 100644 --- a/stovepipe/controller/process/process_test.go +++ b/stovepipe/controller/process/process_test.go @@ -32,10 +32,11 @@ import ( "github.com/uber/submitqueue/platform/metrics" "github.com/uber/submitqueue/stovepipe/core/hookevent" stovepipemq "github.com/uber/submitqueue/stovepipe/core/messagequeue" + "github.com/uber/submitqueue/stovepipe/core/queueconfig" "github.com/uber/submitqueue/stovepipe/core/requestlog" requestlogmock "github.com/uber/submitqueue/stovepipe/core/requestlog/mock" "github.com/uber/submitqueue/stovepipe/entity" - queueconfigdefault "github.com/uber/submitqueue/stovepipe/extension/queueconfig/default" + queueconfigmock "github.com/uber/submitqueue/stovepipe/extension/queueconfig/mock" "github.com/uber/submitqueue/stovepipe/extension/sourcecontrol" sourcecontrolmock "github.com/uber/submitqueue/stovepipe/extension/sourcecontrol/mock" "github.com/uber/submitqueue/stovepipe/extension/storage" @@ -104,12 +105,17 @@ func newControllerWithScope(t *testing.T, ctrl *gomock.Controller, scope tally.S }) require.NoError(t, err) + configs := queueconfigmock.NewMockStore(ctrl) + cfg := queueconfig.QueueConfig{Name: testQueue} + cfg.Stages.Process = queueconfig.Process{MaxConcurrent: 1, GateWaitDelayMs: 5000} + configs.EXPECT().Get(gomock.Any(), gomock.Any()).Return(cfg, nil).AnyTimes() + c := NewController( zap.NewNop().Sugar(), scope, staticStorageFactory{store: m.store}, m.materializer, - queueconfigdefault.NewStore(), + configs, m.sourceFactory, registry, stovepipemq.TopicKeyProcess, diff --git a/stovepipe/core/queueconfig/BUILD.bazel b/stovepipe/core/queueconfig/BUILD.bazel index 84e62d2b0..ccc5ddf95 100644 --- a/stovepipe/core/queueconfig/BUILD.bazel +++ b/stovepipe/core/queueconfig/BUILD.bazel @@ -11,6 +11,7 @@ go_library( "issue_track_overrides.go", "process.go", "process_overrides.go", + "queue_config.go", "stage_overrides.go", "stages.go", ], @@ -29,6 +30,7 @@ go_test( "issue_track_test.go", "process_overrides_test.go", "process_test.go", + "queue_config_test.go", "stage_overrides_test.go", "stages_test.go", ], diff --git a/stovepipe/entity/queue_config.go b/stovepipe/core/queueconfig/queue_config.go similarity index 51% rename from stovepipe/entity/queue_config.go rename to stovepipe/core/queueconfig/queue_config.go index b6681cd83..7295d2f10 100644 --- a/stovepipe/entity/queue_config.go +++ b/stovepipe/core/queueconfig/queue_config.go @@ -1,4 +1,4 @@ -// Copyright (c) 2025 Uber Technologies, Inc. +// Copyright (c) 2026 Uber Technologies, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,18 +12,28 @@ // See the License for the specific language governing permissions and // limitations under the License. -package entity +package queueconfig -// QueueConfig holds deployment configuration for a Stovepipe validation queue. -// Mutable runtime state (latest head, in-flight count) lives on the Queue row; -// knobs such as max_concurrent are resolved here at gate-check time. Immutable -// after load. +import "fmt" + +// QueueConfig is an immutable, resolved configuration for a validation queue. type QueueConfig struct { // Name uniquely identifies this queue within the system. - // Referenced by Request.Queue. Name string `json:"name" yaml:"name"` - // MaxConcurrent is the cap on concurrent in-flight validations for the queue. - MaxConcurrent int32 `json:"max_concurrent" yaml:"max_concurrent"` - // GateWaitDelayMs is the redelivery delay while the latest head waits for a slot. - GateWaitDelayMs int64 `json:"gate_wait_delay_ms" yaml:"gate_wait_delay_ms"` + + // Stages contains configuration grouped by pipeline stage. + Stages Stages `json:"stages" yaml:"stages"` +} + +// Validate checks queue identity and stage configuration constraints. +func (c QueueConfig) Validate() error { + if c.Name == "" { + return fmt.Errorf("queue name must not be empty") + } + + if err := c.Stages.Validate(); err != nil { + return fmt.Errorf("queue %q: %w", c.Name, err) + } + + return nil } diff --git a/stovepipe/core/queueconfig/queue_config_test.go b/stovepipe/core/queueconfig/queue_config_test.go new file mode 100644 index 000000000..330372e1b --- /dev/null +++ b/stovepipe/core/queueconfig/queue_config_test.go @@ -0,0 +1,33 @@ +// Copyright (c) 2026 Uber Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package queueconfig + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestQueueConfigValidate(t *testing.T) { + cfg := QueueConfig{Name: "known", Stages: testStages()} + require.NoError(t, cfg.Validate()) + + cfg.Name = "" + require.Error(t, cfg.Validate()) + + cfg.Name = "known" + cfg.Stages.BuildAnalysis = BuildAnalysis{} + require.Error(t, cfg.Validate()) +} diff --git a/stovepipe/entity/BUILD.bazel b/stovepipe/entity/BUILD.bazel index 1dad63104..7220c4fee 100644 --- a/stovepipe/entity/BUILD.bazel +++ b/stovepipe/entity/BUILD.bazel @@ -20,7 +20,6 @@ go_library( "project_issues.go", "project_status.go", "queue.go", - "queue_config.go", "queue_log.go", "queue_state.go", "queue_status.go", diff --git a/stovepipe/extension/queueconfig/BUILD.bazel b/stovepipe/extension/queueconfig/BUILD.bazel index a654ec803..1ce5237b7 100644 --- a/stovepipe/extension/queueconfig/BUILD.bazel +++ b/stovepipe/extension/queueconfig/BUILD.bazel @@ -5,5 +5,5 @@ go_library( srcs = ["queueconfig.go"], importpath = "github.com/uber/submitqueue/stovepipe/extension/queueconfig", visibility = ["//visibility:public"], - deps = ["//stovepipe/entity:go_default_library"], + deps = ["//stovepipe/core/queueconfig:go_default_library"], ) diff --git a/stovepipe/extension/queueconfig/README.md b/stovepipe/extension/queueconfig/README.md index 40f88558d..998b2a345 100644 --- a/stovepipe/extension/queueconfig/README.md +++ b/stovepipe/extension/queueconfig/README.md @@ -1,17 +1,21 @@ -# Queue Config Extension +# Queue configuration -Vendor-agnostic interface for providing Stovepipe queue configurations. +Queue configuration is deployment policy, separate from mutable queue state in storage. The provider interface supplies immutable, fully resolved settings by queue name; it does not imply database persistence. Controllers obtain one configuration snapshot per delivery without knowing how it was loaded. -Pipeline stages read mutable runtime state from storage and read knobs such as `max_concurrent` from a config `Store` at call time, matching the SubmitQueue split documented in [submitqueue/extension/queueconfig/README.md](../../../submitqueue/extension/queueconfig/README.md). +## Stage ownership -## Interfaces +Configuration is grouped by stage: process, build signal, build analysis, and issue tracking. Resolved configuration types, validation, standard values, and source-independent optional overrides live together in `stovepipe/core/queueconfig`, organized by stage. Stage-specific application helpers copy values, truncate durations to milliseconds, and replace only explicitly supplied fields. Providers can use these helpers but are not required to expose or use overrides. Aggregates compose stages rather than inspecting individual settings. -`Store` provides queue configurations by name via `Get` and `List`. See `queueconfig.go`. +The process stage owns concurrency and admission waits. The other current stage settings control build-status polling, build-issue analysis polling, and issue-tracking recheck and recovery waits. Stage configuration can contain both timing and non-timing settings. Immediate batch continuation and consumer error-retry policies remain separate. -## Entities +## YAML provider -Queue configuration entity lives in `stovepipe/entity/queue_config.go` and carries deployment knobs (`max_concurrent`, `gate_wait_delay_ms`) separate from the mutable `Queue` row. +The YAML implementation decodes the shared optional configuration types directly and retains an immutable snapshot resolved at construction. The host supplies the registered queue names; an optional file supplies shared settings under `stages` and per-queue overrides under `queues`. Queue entries customize existing queues rather than register them. Resolution starts with the shared package's standard stage values, applies shared settings, then applies per-queue overrides. Omitted values inherit; explicit zero or negative values are retained and fail validation if still present in the resolved queue configuration. Only resolved configurations undergo semantic validation. The current concurrency limits and millisecond intervals must be positive. -## Implementations +The provider rejects malformed configuration, unknown fields, duplicate keys or queue overrides, overrides for unregistered queues, and multiple YAML documents. It serves the host-registered queues, returns independent values, and preserves host registration order when listing. It does not watch files or merge multiple files. Standard stage values are defined once in the shared configuration package, not repeated in each YAML file. -`default` returns the global wiring defaults for any non-empty queue name until a file- or service-backed store lands. +## Host integration + +Hosts choose and construct the provider and inject the lookup interface. The example server uses its existing messaging tenant list to supply queue names and uses built-in stage settings unless a configuration file is selected. E2e selects a file containing only shorter shared stage waits through the same configuration path. A host using another configuration framework can return the same resolved values without adopting the YAML schema or its defaults mechanism. Messaging tenant registration remains a separate host concern. + +Adding a setting requires updating its stage's resolved value, validation, standard value, and optional input with its application logic. A standard value lets existing configuration files keep working when a tuning setting is added. The YAML provider does not repeat stage schemas or field mappings. It does not require field-level logic in the lookup interface or the aggregate. diff --git a/stovepipe/extension/queueconfig/default/default.go b/stovepipe/extension/queueconfig/default/default.go deleted file mode 100644 index 5fb696710..000000000 --- a/stovepipe/extension/queueconfig/default/default.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) 2025 Uber Technologies, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package defaultconfig provides a queueconfig.Store that returns global wiring -// defaults for any non-empty queue name. Replace with a YAML- or service-backed -// store when per-queue overrides are needed. -package defaultconfig - -import ( - "context" - - "github.com/uber/submitqueue/stovepipe/entity" - "github.com/uber/submitqueue/stovepipe/extension/queueconfig" -) - -const ( - _defaultMaxConcurrent = 1 - _defaultGateWaitDelayMs = 5000 -) - -// Store is a queueconfig.Store that returns the same defaults for every queue. -type Store struct{} - -// NewStore returns a Store backed by global wiring defaults. -func NewStore() Store { - return Store{} -} - -// Get returns the default configuration for any non-empty queue name. -func (Store) Get(_ context.Context, name string) (entity.QueueConfig, error) { - if name == "" { - return entity.QueueConfig{}, queueconfig.ErrNotFound - } - return entity.QueueConfig{ - Name: name, - MaxConcurrent: _defaultMaxConcurrent, - GateWaitDelayMs: _defaultGateWaitDelayMs, - }, nil -} - -// List returns an empty slice; this store does not enumerate known queues. -func (Store) List(context.Context) ([]entity.QueueConfig, error) { - return nil, nil -} diff --git a/stovepipe/extension/queueconfig/default/default_test.go b/stovepipe/extension/queueconfig/default/default_test.go deleted file mode 100644 index 490ff35a7..000000000 --- a/stovepipe/extension/queueconfig/default/default_test.go +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2025 Uber Technologies, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package defaultconfig - -import ( - "context" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/uber/submitqueue/stovepipe/extension/queueconfig" -) - -func TestStore_Get(t *testing.T) { - store := NewStore() - - t.Run("returns defaults for named queue", func(t *testing.T) { - cfg, err := store.Get(context.Background(), "monorepo/main") - require.NoError(t, err) - assert.Equal(t, "monorepo/main", cfg.Name) - assert.Equal(t, int32(1), cfg.MaxConcurrent) - assert.Equal(t, int64(5000), cfg.GateWaitDelayMs) - }) - - t.Run("empty name is not found", func(t *testing.T) { - _, err := store.Get(context.Background(), "") - require.ErrorIs(t, err, queueconfig.ErrNotFound) - }) -} - -func TestStore_List(t *testing.T) { - store := NewStore() - - cfg, err := store.List(context.Background()) - require.NoError(t, err) - assert.Empty(t, cfg) -} diff --git a/stovepipe/extension/queueconfig/mock/BUILD.bazel b/stovepipe/extension/queueconfig/mock/BUILD.bazel index e36da38a6..d9e126b3b 100644 --- a/stovepipe/extension/queueconfig/mock/BUILD.bazel +++ b/stovepipe/extension/queueconfig/mock/BUILD.bazel @@ -6,7 +6,7 @@ go_library( importpath = "github.com/uber/submitqueue/stovepipe/extension/queueconfig/mock", visibility = ["//visibility:public"], deps = [ - "//stovepipe/entity:go_default_library", + "//stovepipe/core/queueconfig:go_default_library", "@org_uber_go_mock//gomock:go_default_library", ], ) diff --git a/stovepipe/extension/queueconfig/mock/queueconfig_mock.go b/stovepipe/extension/queueconfig/mock/queueconfig_mock.go index 98114bc91..4209e0d9a 100644 --- a/stovepipe/extension/queueconfig/mock/queueconfig_mock.go +++ b/stovepipe/extension/queueconfig/mock/queueconfig_mock.go @@ -13,7 +13,7 @@ import ( context "context" reflect "reflect" - entity "github.com/uber/submitqueue/stovepipe/entity" + queueconfig "github.com/uber/submitqueue/stovepipe/core/queueconfig" gomock "go.uber.org/mock/gomock" ) @@ -42,10 +42,10 @@ func (m *MockStore) EXPECT() *MockStoreMockRecorder { } // Get mocks base method. -func (m *MockStore) Get(ctx context.Context, name string) (entity.QueueConfig, error) { +func (m *MockStore) Get(ctx context.Context, name string) (queueconfig.QueueConfig, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Get", ctx, name) - ret0, _ := ret[0].(entity.QueueConfig) + ret0, _ := ret[0].(queueconfig.QueueConfig) ret1, _ := ret[1].(error) return ret0, ret1 } @@ -57,10 +57,10 @@ func (mr *MockStoreMockRecorder) Get(ctx, name any) *gomock.Call { } // List mocks base method. -func (m *MockStore) List(ctx context.Context) ([]entity.QueueConfig, error) { +func (m *MockStore) List(ctx context.Context) ([]queueconfig.QueueConfig, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "List", ctx) - ret0, _ := ret[0].([]entity.QueueConfig) + ret0, _ := ret[0].([]queueconfig.QueueConfig) ret1, _ := ret[1].(error) return ret0, ret1 } diff --git a/stovepipe/extension/queueconfig/queueconfig.go b/stovepipe/extension/queueconfig/queueconfig.go index 437d9a2ba..82bb7139e 100644 --- a/stovepipe/extension/queueconfig/queueconfig.go +++ b/stovepipe/extension/queueconfig/queueconfig.go @@ -20,19 +20,19 @@ import ( "context" "errors" - "github.com/uber/submitqueue/stovepipe/entity" + "github.com/uber/submitqueue/stovepipe/core/queueconfig" ) // ErrNotFound is returned when the requested queue configuration does not exist. var ErrNotFound = errors.New("queue config not found") -// Store loads and provides queue configurations. +// Store supplies validated, immutable queue configuration snapshots. // Implementations may read from YAML files, databases, remote services, etc. type Store interface { - // Get returns the configuration for a named queue. + // Get returns a fully resolved and validated configuration for a named queue. // Returns ErrNotFound if no configuration exists for the given name. - Get(ctx context.Context, name string) (entity.QueueConfig, error) + Get(ctx context.Context, name string) (queueconfig.QueueConfig, error) // List returns all configured queues. - List(ctx context.Context) ([]entity.QueueConfig, error) + List(ctx context.Context) ([]queueconfig.QueueConfig, error) } diff --git a/stovepipe/extension/queueconfig/default/BUILD.bazel b/stovepipe/extension/queueconfig/yaml/BUILD.bazel similarity index 65% rename from stovepipe/extension/queueconfig/default/BUILD.bazel rename to stovepipe/extension/queueconfig/yaml/BUILD.bazel index f2c8fc3dc..018a1fa82 100644 --- a/stovepipe/extension/queueconfig/default/BUILD.bazel +++ b/stovepipe/extension/queueconfig/yaml/BUILD.bazel @@ -2,20 +2,26 @@ load("@rules_go//go:def.bzl", "go_library", "go_test") go_library( name = "go_default_library", - srcs = ["default.go"], - importpath = "github.com/uber/submitqueue/stovepipe/extension/queueconfig/default", + srcs = [ + "config_file.go", + "resolve.go", + "store.go", + ], + importpath = "github.com/uber/submitqueue/stovepipe/extension/queueconfig/yaml", visibility = ["//visibility:public"], deps = [ - "//stovepipe/entity:go_default_library", + "//stovepipe/core/queueconfig:go_default_library", "//stovepipe/extension/queueconfig:go_default_library", + "@in_gopkg_yaml_v3//:go_default_library", ], ) go_test( name = "go_default_test", - srcs = ["default_test.go"], + srcs = ["yaml_test.go"], embed = [":go_default_library"], deps = [ + "//stovepipe/core/queueconfig:go_default_library", "//stovepipe/extension/queueconfig:go_default_library", "@com_github_stretchr_testify//assert:go_default_library", "@com_github_stretchr_testify//require:go_default_library", diff --git a/stovepipe/extension/queueconfig/yaml/config_file.go b/stovepipe/extension/queueconfig/yaml/config_file.go new file mode 100644 index 000000000..d6f03427b --- /dev/null +++ b/stovepipe/extension/queueconfig/yaml/config_file.go @@ -0,0 +1,70 @@ +// Copyright (c) 2026 Uber Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package yaml + +import ( + "fmt" + "io" + "os" + + "github.com/uber/submitqueue/stovepipe/core/queueconfig" + yamlv3 "gopkg.in/yaml.v3" +) + +type fileConfig struct { + SharedStages queueconfig.StageOverrides `yaml:"stages"` + QueueOverrides []queueOverride `yaml:"queues"` +} + +type queueOverride struct { + QueueName string `yaml:"name"` + Stages queueconfig.StageOverrides `yaml:"stages"` +} + +func readConfigFile(path string) (fileConfig, error) { + file, err := os.Open(path) + if err != nil { + return fileConfig{}, fmt.Errorf("open queue configuration %q: %w", path, err) + } + defer file.Close() + + cfg, err := decodeConfig(file) + if err != nil { + return fileConfig{}, fmt.Errorf("decode queue configuration %q: %w", path, err) + } + + return cfg, nil +} + +func decodeConfig(reader io.Reader) (fileConfig, error) { + decoder := yamlv3.NewDecoder(reader) + decoder.KnownFields(true) + + var cfg fileConfig + if err := decoder.Decode(&cfg); err != nil && err != io.EOF { + return fileConfig{}, err + } + + var extra any + if err := decoder.Decode(&extra); err != io.EOF { + if err != nil { + return fileConfig{}, err + } + + return fileConfig{}, fmt.Errorf("configuration must contain exactly one YAML document") + } + + return cfg, nil +} diff --git a/stovepipe/extension/queueconfig/yaml/resolve.go b/stovepipe/extension/queueconfig/yaml/resolve.go new file mode 100644 index 000000000..e2e112cdc --- /dev/null +++ b/stovepipe/extension/queueconfig/yaml/resolve.go @@ -0,0 +1,71 @@ +// Copyright (c) 2026 Uber Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package yaml + +import ( + "fmt" + + "github.com/uber/submitqueue/stovepipe/core/queueconfig" +) + +func (cfg fileConfig) resolveQueues(queueNames []string) ([]queueconfig.QueueConfig, error) { + overridesByQueue, err := cfg.indexQueueOverrides() + if err != nil { + return nil, err + } + + sharedStages := cfg.SharedStages.Apply(queueconfig.DefaultStages()) + registeredQueues := make(map[string]struct{}, len(queueNames)) + queues := make([]queueconfig.QueueConfig, 0, len(queueNames)) + + for _, name := range queueNames { + if _, exists := registeredQueues[name]; exists { + return nil, fmt.Errorf("duplicate registered queue %q", name) + } + + queue := queueconfig.QueueConfig{ + Name: name, + Stages: overridesByQueue[name].Apply(sharedStages), + } + + if err := queue.Validate(); err != nil { + return nil, err + } + + registeredQueues[name] = struct{}{} + queues = append(queues, queue) + } + + for _, override := range cfg.QueueOverrides { + if _, exists := registeredQueues[override.QueueName]; !exists { + return nil, fmt.Errorf("override refers to unregistered queue %q", override.QueueName) + } + } + + return queues, nil +} + +func (cfg fileConfig) indexQueueOverrides() (map[string]queueconfig.StageOverrides, error) { + overridesByQueue := make(map[string]queueconfig.StageOverrides, len(cfg.QueueOverrides)) + for _, override := range cfg.QueueOverrides { + if _, exists := overridesByQueue[override.QueueName]; exists { + return nil, fmt.Errorf("duplicate queue override %q", override.QueueName) + } + + overridesByQueue[override.QueueName] = override.Stages + } + + return overridesByQueue, nil +} diff --git a/stovepipe/extension/queueconfig/yaml/store.go b/stovepipe/extension/queueconfig/yaml/store.go new file mode 100644 index 000000000..ce5a3dca3 --- /dev/null +++ b/stovepipe/extension/queueconfig/yaml/store.go @@ -0,0 +1,77 @@ +// Copyright (c) 2026 Uber Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package yaml provides immutable queue configuration resolved from built-in +// defaults and optional YAML overrides for host-registered queues. +package yaml + +import ( + "context" + "fmt" + + "github.com/uber/submitqueue/stovepipe/core/queueconfig" + queueconfigprovider "github.com/uber/submitqueue/stovepipe/extension/queueconfig" +) + +// store holds immutable, resolved settings for host-registered queues. +// Get and List return independent values and are safe for concurrent use. +type store struct { + queues []queueconfig.QueueConfig +} + +// NewStore resolves settings for queueNames in the supplied order. +// An empty path uses built-in defaults; otherwise one file supplies optional +// shared settings and per-queue overrides. Files are read once and are not watched. +func NewStore(path string, queueNames []string) (queueconfigprovider.Store, error) { + var cfg fileConfig + if path != "" { + var err error + cfg, err = readConfigFile(path) + if err != nil { + return nil, err + } + } + + queues, err := cfg.resolveQueues(queueNames) + if err != nil { + if path != "" { + return nil, fmt.Errorf("resolve queue configuration %q: %w", path, err) + } + + return nil, err + } + + return store{queues: queues}, nil +} + +// Get returns ErrNotFound for queues not registered by the host. +func (s store) Get(_ context.Context, name string) (queueconfig.QueueConfig, error) { + for _, cfg := range s.queues { + if cfg.Name == name { + return cfg, nil + } + } + + return queueconfig.QueueConfig{}, queueconfigprovider.ErrNotFound +} + +// List returns independent values in host registration order. +func (s store) List(context.Context) ([]queueconfig.QueueConfig, error) { + configs := make([]queueconfig.QueueConfig, len(s.queues)) + copy(configs, s.queues) + + return configs, nil +} + +var _ queueconfigprovider.Store = store{} diff --git a/stovepipe/extension/queueconfig/yaml/yaml_test.go b/stovepipe/extension/queueconfig/yaml/yaml_test.go new file mode 100644 index 000000000..d4decba44 --- /dev/null +++ b/stovepipe/extension/queueconfig/yaml/yaml_test.go @@ -0,0 +1,236 @@ +// Copyright (c) 2026 Uber Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package yaml + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/uber/submitqueue/stovepipe/core/queueconfig" + queueconfigprovider "github.com/uber/submitqueue/stovepipe/extension/queueconfig" +) + +const testStages = `stages: + process: + maxConcurrent: 3 + gateWaitDelay: 123ms + buildSignal: + acceptedPollDelay: 234ms + runningPollDelay: 345ms + buildAnalysis: + pollDelay: 456ms + issueTrack: + recheckDelay: 567ms + recoveryWaitDelay: 678ms +` + +func writeTestConfig(t *testing.T, input string) string { + t.Helper() + + path := filepath.Join(t.TempDir(), "queues.yaml") + require.NoError(t, os.WriteFile(path, []byte(input), 0600)) + return path +} + +func TestStageAndQueueOverrides(t *testing.T) { + store, err := NewStore(writeTestConfig(t, testStages+`queues: + - name: special + stages: + process: + maxConcurrent: 4 + buildAnalysis: + pollDelay: 2s +`), []string{"ordinary", "special"}) + require.NoError(t, err) + + ordinary, err := store.Get(context.Background(), "ordinary") + require.NoError(t, err) + + special, err := store.Get(context.Background(), "special") + require.NoError(t, err) + + assert.Equal(t, int32(3), ordinary.Stages.Process.MaxConcurrent) + assert.Equal(t, int64(123), ordinary.Stages.Process.GateWaitDelayMs) + assert.Equal(t, int64(234), ordinary.Stages.BuildSignal.AcceptedPollDelayMs) + assert.Equal(t, int64(345), ordinary.Stages.BuildSignal.RunningPollDelayMs) + assert.Equal(t, int64(456), ordinary.Stages.BuildAnalysis.PollDelayMs) + assert.Equal(t, int64(567), ordinary.Stages.IssueTrack.RecheckDelayMs) + assert.Equal(t, int64(678), ordinary.Stages.IssueTrack.RecoveryWaitDelayMs) + + assert.Equal(t, int32(4), special.Stages.Process.MaxConcurrent) + assert.Equal(t, ordinary.Stages.Process.GateWaitDelayMs, special.Stages.Process.GateWaitDelayMs) + assert.Equal(t, int64(2000), special.Stages.BuildAnalysis.PollDelayMs) + assert.Equal(t, ordinary.Stages.BuildSignal, special.Stages.BuildSignal) + assert.Equal(t, ordinary.Stages.IssueTrack, special.Stages.IssueTrack) +} + +func TestOmittedStageSettingsUseStandardValues(t *testing.T) { + baseline := queueconfig.DefaultStages() + + for _, tt := range []struct { + name string + input string + analysisDelayMs int64 + }{ + {"empty file", "", baseline.BuildAnalysis.PollDelayMs}, + {"empty document", "{}", baseline.BuildAnalysis.PollDelayMs}, + {"empty queue overrides", "queues: []", baseline.BuildAnalysis.PollDelayMs}, + {"empty stages", "stages: {}", baseline.BuildAnalysis.PollDelayMs}, + {"partial shared stages", "stages: {buildAnalysis: {pollDelay: 250ms}}", 250}, + {"partial queue stages", "queues: [{name: known, stages: {buildAnalysis: {pollDelay: 250ms}}}]", 250}, + {"fractional milliseconds truncate", "queues: [{name: known, stages: {buildAnalysis: {pollDelay: 1500us}}}]", 1}, + {"queue overrides shared stages", "stages: {buildAnalysis: {pollDelay: 1s}}\nqueues: [{name: known, stages: {buildAnalysis: {pollDelay: 250ms}}}]", 250}, + } { + t.Run(tt.name, func(t *testing.T) { + store, err := NewStore(writeTestConfig(t, tt.input), []string{"known"}) + require.NoError(t, err) + + cfg, err := store.Get(context.Background(), "known") + require.NoError(t, err) + require.NoError(t, cfg.Validate()) + want := baseline + want.BuildAnalysis.PollDelayMs = tt.analysisDelayMs + assert.Equal(t, want, cfg.Stages) + }) + } +} + +func TestValidationUsesResolvedQueueSettings(t *testing.T) { + input := strings.Replace(testStages, "pollDelay: 456ms", "pollDelay: 0s", 1) + `queues: + - name: known + stages: + buildAnalysis: + pollDelay: 2s +` + store, err := NewStore(writeTestConfig(t, input), []string{"known"}) + require.NoError(t, err) + + cfg, err := store.Get(context.Background(), "known") + require.NoError(t, err) + require.NoError(t, cfg.Validate()) + assert.Equal(t, int64(2000), cfg.Stages.BuildAnalysis.PollDelayMs) +} + +func TestRejectsInvalidConfiguration(t *testing.T) { + valid := testStages + "queues:\n - name: known\n" + + for _, tt := range []struct { + name string + input string + }{ + {"unknown section", valid + "default: {}"}, + {"unknown stages field", strings.Replace(valid, "stages:", "stagez:", 1)}, + {"unknown stage", strings.Replace(valid, " process:", " unknown:", 1)}, + {"unknown process field", strings.Replace(valid, "maxConcurrent:", "maxConcurent:", 1)}, + {"unknown signal field", strings.Replace(valid, "acceptedPollDelay:", "pollDelay:", 1)}, + {"unknown analysis field", strings.Replace(valid, "pollDelay:", "polDelay:", 1)}, + {"unknown tracking field", strings.Replace(valid, "recheckDelay:", "pollDelay:", 1)}, + {"unknown queue field", valid + " stagez: {}"}, + {"unknown queue stage", valid + " stages: {unknown: {}}"}, + {"duplicate key", strings.Replace(valid, "maxConcurrent: 3", "maxConcurrent: 3\n maxConcurrent: 4", 1)}, + {"duplicate queue override", valid + " - name: known\n"}, + {"unregistered queue override", valid + " - name: unknown\n"}, + {"empty name", strings.Replace(valid, "name: known", "name: ''", 1)}, + {"missing name", testStages + "queues: [{}]"}, + {"zero concurrency", strings.Replace(valid, "maxConcurrent: 3", "maxConcurrent: 0", 1)}, + {"zero wait", strings.Replace(valid, "pollDelay: 456ms", "pollDelay: 0s", 1)}, + {"negative wait", strings.Replace(valid, "recheckDelay: 567ms", "recheckDelay: -1s", 1)}, + {"invalid duration", strings.Replace(valid, "gateWaitDelay: 123ms", "gateWaitDelay: soon", 1)}, + {"submillisecond", strings.Replace(valid, "acceptedPollDelay: 234ms", "acceptedPollDelay: 1us", 1)}, + {"invalid queue override", valid + " stages: {process: {gateWaitDelay: 0s}}"}, + {"invalid sibling queue", valid + " - name: invalid\n stages: {buildAnalysis: {pollDelay: 0s}}"}, + {"invalid partial shared settings", "stages: {buildAnalysis: {pollDelay: 0s}}\nqueues: [{name: known}]"}, + {"invalid partial queue settings", "queues: [{name: known, stages: {process: {maxConcurrent: 0}}}]"}, + {"obsolete defaults wrapper", "defaults: {}\nqueues: [{name: known}]"}, + {"second document", valid + "---\n{}"}, + {"malformed second document", valid + "---\n["}, + } { + t.Run(tt.name, func(t *testing.T) { + store, err := NewStore(writeTestConfig(t, tt.input), []string{"known", "invalid"}) + require.Error(t, err) + require.Nil(t, store) + }) + } +} + +func TestStoreSnapshotAndIsolation(t *testing.T) { + ctx := context.Background() + path := writeTestConfig(t, testStages) + names := []string{"second", "first"} + store, err := NewStore(path, names) + require.NoError(t, err) + + names[0] = "changed" + want, err := store.Get(ctx, "second") + require.NoError(t, err) + + require.NoError(t, os.WriteFile(path, []byte("invalid replacement"), 0600)) + + got := want + got.Stages.Process.MaxConcurrent = 99 + + listed, err := store.List(ctx) + require.NoError(t, err) + require.Len(t, listed, 2) + assert.Equal(t, []string{"second", "first"}, []string{listed[0].Name, listed[1].Name}) + listed[0] = got + + again, err := store.Get(ctx, "second") + require.NoError(t, err) + assert.Equal(t, want, again) + + listedAgain, err := store.List(ctx) + require.NoError(t, err) + assert.Equal(t, want, listedAgain[0]) + + for _, name := range []string{"", "unknown"} { + _, err := store.Get(ctx, name) + require.ErrorIs(t, err, queueconfigprovider.ErrNotFound) + } +} + +func TestMissingFileFails(t *testing.T) { + _, err := NewStore(filepath.Join(t.TempDir(), "missing"), []string{"known"}) + require.ErrorIs(t, err, os.ErrNotExist) +} + +func TestNoFileUsesStandardSettingsForRegisteredQueues(t *testing.T) { + store, err := NewStore("", []string{"known"}) + require.NoError(t, err) + + cfg, err := store.Get(context.Background(), "known") + require.NoError(t, err) + assert.Equal(t, queueconfig.QueueConfig{Name: "known", Stages: queueconfig.DefaultStages()}, cfg) +} + +func TestRejectsInvalidRegisteredQueues(t *testing.T) { + for _, tt := range []struct { + name string + queues []string + }{ + {"empty name", []string{""}}, + {"duplicate name", []string{"known", "known"}}, + } { + t.Run(tt.name, func(t *testing.T) { + _, err := NewStore("", tt.queues) + require.Error(t, err) + }) + } +}