Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion backend/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ require (
github.com/hashicorp/hcl/v2 v2.25.0
github.com/jackc/pgx/v5 v5.10.0
github.com/michielvha/logger v0.0.5
github.com/michielvha/stackweaver/core v0.631.4
github.com/michielvha/stackweaver/core v0.631.8
github.com/redis/go-redis/v9 v9.23.0
github.com/robfig/cron/v3 v3.0.1
github.com/zclconf/go-cty v1.19.0
Expand Down
4 changes: 2 additions & 2 deletions backend/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,8 @@ github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/michielvha/logger v0.0.5 h1:zcepKGWRMgo32j6nU++RBWtzzz2Q5txVquGDbaSlCro=
github.com/michielvha/logger v0.0.5/go.mod h1:YJjpbm0AlPmmLBFO8tPyBAruWMJisu2sPo/DX9qxKJk=
github.com/michielvha/stackweaver/core v0.631.4 h1:UJ9fJ5l0h0K0wXZJZDmmFJ7vtjciB9Qn8e4zo84F/Ic=
github.com/michielvha/stackweaver/core v0.631.4/go.mod h1:Bt8/peil8riL5pzhiLbkoT5b9d30PH+GYKQVpfeqKKI=
github.com/michielvha/stackweaver/core v0.631.8 h1:Qkuq41VnfKltbcQdWVEilNANLm7PDreU4iZCNLjTrsk=
github.com/michielvha/stackweaver/core v0.631.8/go.mod h1:Bt8/peil8riL5pzhiLbkoT5b9d30PH+GYKQVpfeqKKI=
github.com/microsoft/go-mssqldb v1.7.2 h1:CHkFJiObW7ItKTJfHo1QX7QBBD1iV+mn1eOyRP3b/PA=
github.com/microsoft/go-mssqldb v1.7.2/go.mod h1:kOvZKUdrhhFQmxLZqbwUV0rHkNkZpthMITIb2Ko1IoA=
github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0=
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
// Copyright (c) 2026 VH & Co BV. Licensed under the Business Source License 1.1. See LICENSE for details.

// A webhook-triggered file sync runs only for the source the delivery matched, and editing an
// inventory's source ends the file syncs requested for the old one: a waiting or running sync is
// canceled, and an artifacts request whose sync was canceled meanwhile hands out nothing.
//
// go test -tags integration ./internal/api/v2/handlers/ -run TestInventorySyncSource

//go:build integration

package handlers

import (
"net/http"
"strings"
"sync"
"sync/atomic"
"testing"

"github.com/google/uuid"
"github.com/michielvha/stackweaver/core/models"
"github.com/michielvha/stackweaver/core/repository"
"github.com/michielvha/stackweaver/core/services/ansible"
"gorm.io/gorm"
)

// editSource changes the inventory's repository as the inventory routes do.
func (f *workItemRunnerFixture) editSource(t *testing.T, id uuid.UUID, repo string) {
t.Helper()
svc := ansible.NewInventoryService(repository.NewAnsibleInventoryRepository(f.db), repository.NewOrganizationRepository(f.db))
if _, err := svc.UpdateInventory(id, nil, nil, nil, nil, nil, &repo, nil, nil, ansible.IdentityChange{}); err != nil {
t.Errorf("editing the inventory's source: %v", err)
}
}

func (f *workItemRunnerFixture) wantCanceledBySourceEdit(t *testing.T, id string) {
t.Helper()
got := f.reload(t, id)
if got.Status != models.WorkItemStatusCanceled || !strings.Contains(got.ErrorMessage, "sync source changed") || got.FinishedAt == nil {
t.Errorf("work item = %s %q (finished %v), want canceled by the source edit", got.Status, got.ErrorMessage, got.FinishedAt)
}
}

func TestInventorySyncSource_WebhookForAnEditedSourceQueuesNothing(t *testing.T) {
f := setupWorkItemRunner(t)
h := &VCSAppInstallationHandlerV2{workItems: f.items}
for name, refused := range map[string]bool{"a sync it would queue": false, "a refusal it would record": true} {
t.Run(name, func(t *testing.T) {
inv := f.boundFileSyncInventory(t)
if refused {
restricted := &models.AgentPool{ID: uuid.New(), OrganizationID: f.orgA, Name: "srcedit-restricted-" + uuid.NewString()[:6]}
if err := f.db.Create(restricted).Error; err != nil {
t.Fatal(err)
}
t.Cleanup(func() { f.db.Where("id = ?", restricted.ID).Delete(&models.AgentPool{}) })
b := f.binding(t, restricted.ID, "restricted")
if err := f.db.Model(inv).Update("identity_binding_id", b.ID).Error; err != nil {
t.Fatal(err)
}
inv.IdentityBindingID = &b.ID
}
// The delivery matched inv as it was loaded; the source changes before the request is
// serialized.
var once sync.Once
f.onSyncLock(t, true, func(*gorm.DB) {
once.Do(func() {
if err := f.db.Session(&gorm.Session{NewDB: true}).Exec("UPDATE ansible_inventories SET vcs_repository = ? WHERE id = ?", "acme/replaced-"+uuid.NewString()[:6], inv.ID).Error; err != nil {
t.Error(err)
}
})
})
h.requestInventorySync(inv)
if status, syncErr, n := f.webhookState(t, inv.ID); status != "completed" || syncErr != "" || n != 0 {
t.Errorf("a webhook for the former source: status %q error %q, %d active; want nothing queued or written", status, syncErr, n)
}
})
}
}

func TestInventorySyncSource_EditCancelsTheSyncsOfTheOldSource(t *testing.T) {
f := setupWorkItemRunner(t)
inv := f.fileSyncInventory(t, models.InventoryTypeVCS)
running, err := f.items.RequestInventorySync(t.Context(), inv, "manual")
if err != nil {
t.Fatal(err)
}
f.onPool(t, running)
f.claim(t, "a1", running.ID, "srcedit")

// An edit that keeps the source leaves the sync as it is.
description := "edited"
svc := ansible.NewInventoryService(repository.NewAnsibleInventoryRepository(f.db), repository.NewOrganizationRepository(f.db))
if _, err := svc.UpdateInventory(inv.ID, nil, &description, nil, nil, nil, nil, nil, nil, ansible.IdentityChange{}); err != nil {
t.Fatal(err)
}
if got := f.reload(t, running.ID); got.Status != models.WorkItemStatusRunning {
t.Fatalf("after an edit of the description the sync is %s, want running", got.Status)
}

f.editSource(t, inv.ID, "acme/replaced-"+uuid.NewString()[:6])
f.wantCanceledBySourceEdit(t, running.ID)
if rec, art := f.artifacts(t, "srcedit", running.ID); rec.Code == http.StatusOK || art.Clone != nil {
t.Errorf("artifacts of the canceled sync = %d, want no clone inputs", rec.Code)
}
var history models.AnsibleInventorySync
if err := f.db.First(&history, "id = ?", f.reload(t, running.ID).SyncRunID).Error; err != nil {
t.Fatal(err)
}
if history.Status != models.InventorySyncStatusFailed || !strings.Contains(history.Error, "sync source changed") {
t.Errorf("history = %s %q, want the canceled sync", history.Status, history.Error)
}

// A sync that waits for a launcher is canceled the same way.
waiting, err := f.items.RequestInventorySync(t.Context(), inv, "manual")
if err != nil {
t.Fatal(err)
}
f.editSource(t, inv.ID, "acme/replaced-"+uuid.NewString()[:6])
f.wantCanceledBySourceEdit(t, waiting.ID)
}

func TestInventorySyncSource_ArtifactsRequestDuringAnEdit(t *testing.T) {
f := setupWorkItemRunner(t)
inv := f.fileSyncInventory(t, models.InventoryTypeVCS)
item, err := f.items.RequestInventorySync(t.Context(), inv, "manual")
if err != nil {
t.Fatal(err)
}
f.onPool(t, item)
f.claim(t, "a1", item.ID, "srcedit-art")

// The edit commits after the artifacts request loaded its work item and before it reads the
// inventory.
// The flag is taken before the edit, whose own reads of the inventory pass through this hook.
var started atomic.Bool
cb := "test:edit-before-artifacts-read-" + uuid.NewString()[:8]
if err := f.db.Callback().Query().Before("gorm:query").Register(cb, func(tx *gorm.DB) {
if tx.Statement.Table == "ansible_inventories" && started.CompareAndSwap(false, true) {
f.editSource(t, inv.ID, "acme/replaced-"+uuid.NewString()[:6])
}
}); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = f.db.Callback().Query().Remove(cb) })
rec, art := f.artifacts(t, "srcedit-art", item.ID)
if rec.Code == http.StatusOK || art.Clone != nil {
t.Errorf("artifacts while the source changed = %d %s, want no clone inputs", rec.Code, rec.Body.String())
}
f.wantCanceledBySourceEdit(t, item.ID)
}

// An edit takes the inventory's sync lock before its work items and its row, as a sync request does.
func TestInventorySyncSource_EditTakesTheSyncLockFirst(t *testing.T) {
f := setupWorkItemRunner(t)
inv := f.fileSyncInventory(t, models.InventoryTypeVCS)
holder := f.db.Begin()
if err := holder.Exec("SELECT pg_advisory_xact_lock(?)", ansible.InventorySyncLockKey(inv.ID)).Error; err != nil {
t.Fatal(err)
}
done := make(chan struct{})
go func() {
defer close(done)
f.editSource(t, inv.ID, "acme/replaced-"+uuid.NewString()[:6])
}()
f.waitForSyncLockWaiter(t, inv.ID)
select {
case <-done:
t.Fatal("the edit finished while another transaction held the inventory's sync lock")
default:
}
holder.Rollback()
<-done
}
9 changes: 9 additions & 0 deletions backend/internal/api/v2/handlers/runner_agent_work_items.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,15 @@ func (h *RunnerAgentHandler) workItemArtifacts(ctx context.Context, item *models
if err := validatedInventoryScope(item, &inventory); err != nil {
return nil, err
}
// An edit of the inventory's source cancels its syncs: one canceled before the row above was
// read gets none of the new source's inputs.
current, err := h.workItems.WithContext(ctx).Items().GetByID(item.ID)
if err != nil {
return nil, fmt.Errorf("reading work item %s: %w", item.ID, err)
}
if current.Finished() {
return nil, fmt.Errorf("%s: %w", current.ErrorMessage, ansible.ErrInvalidInput)
}
clone, err := h.fileSyncCloneSource(ctx, item, &inventory)
if err != nil {
return nil, err
Expand Down
11 changes: 7 additions & 4 deletions backend/internal/api/v2/handlers/vcs_app_installation.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,15 +166,18 @@ var webhookSyncTimeout = 30 * time.Second
// requestInventorySync requests the webhook-triggered sync of an inventory as a work item. The
// credential the clone needs is resolved when a launcher runs it, never carried on the request. A
// refused or failed file sync request is recorded on the inventory unless a file sync of it is
// waiting or running; a request whose wait timed out writes nothing (#1113, D2).
// waiting or running; a request whose wait timed out writes nothing (#1113, D2). The request is for the
// source the delivery matched inv by: an inventory whose source changed since gets no sync and no
// record.
func (h *VCSAppInstallationHandlerV2) requestInventorySync(inv *models.AnsibleInventory) {
if h.workItems == nil {
return
}
ctx, cancel := context.WithTimeout(context.Background(), webhookSyncTimeout)
defer cancel()
_, err := h.workItems.RequestInventorySync(ctx, inv, "webhook")
if err == nil {
source := coreansible.SourceOf(inv)
_, err := h.workItems.RequestInventorySyncOf(ctx, inv, "webhook", source)
if err == nil || errors.Is(err, coreansible.ErrSyncSourceChanged) {
return
}
logger.Errorf("Error requesting a sync of inventory %s: %v", inv.ID, err)
Expand All @@ -187,7 +190,7 @@ func (h *VCSAppInstallationHandlerV2) requestInventorySync(inv *models.AnsibleIn
}
recordCtx, recordCancel := context.WithTimeout(context.Background(), webhookSyncTimeout)
defer recordCancel()
if recErr := h.workItems.RecordFileSyncFailure(recordCtx, inv.ID, reason, coreansible.WebhookSyncFailure); recErr != nil {
if recErr := h.workItems.RecordFileSyncFailure(recordCtx, inv.ID, reason, coreansible.WebhookSyncFailure, source); recErr != nil {
logger.Errorf("Error recording the refused sync of inventory %s: %v", inv.ID, recErr)
}
}
Expand Down
Loading