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
9 changes: 5 additions & 4 deletions internal/setup/trust_registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,8 @@ func (o *Orchestrator) EnableTrustRegistry(ctx context.Context, s *model.SetupSe
if _, err := MergeRegistryConfig(current, placeholder); err != nil {
return err
}
document, err := o.registryDIDResolver().ResolveDocument(ctx, s.VtcDid)
resolver := o.registryDIDResolver()
document, err := resolver.ResolveDocument(ctx, s.VtcDid)
if err != nil {
return fmt.Errorf("cannot validate existing VTC DID history: %w", err)
}
Expand All @@ -202,7 +203,7 @@ func (o *Orchestrator) EnableTrustRegistry(ctx context.Context, s *model.SetupSe
if err = o.provisionRegistry(ctx, ns, s); err != nil {
return err
}
if err = o.registryDIDResolver().ResolveDID(ctx, s.TrustRegistryDid); err != nil {
if err = resolver.ResolveDID(ctx, s.TrustRegistryDid); err != nil {
return fmt.Errorf("registry DID did not resolve: %w", err)
}
if err = o.RegistryPhase(s, "deploy_registry"); err != nil {
Expand All @@ -216,7 +217,7 @@ func (o *Orchestrator) EnableTrustRegistry(ctx context.Context, s *model.SetupSe
}
// Through the running VTA, which reads its own head immediately before
// editing; the preflight snapshot above is never applied.
if err = o.publishRegistryReferral(ctx, ns, s); err != nil {
if err = o.publishRegistryReferral(ctx, ns, s, resolver); err != nil {
return err
}
if err = o.RegistryPhase(s, "configure_vtc"); err != nil {
Expand Down Expand Up @@ -246,7 +247,7 @@ mv config.toml.vtafarm-registry-next config.toml`}, []k8s.PVCMount{{Name: "vtc-d
if err = o.RegistryPhase(s, "verify"); err != nil {
return err
}
document, err = o.registryDIDResolver().ResolveDocument(ctx, s.VtcDid)
document, err = resolver.ResolveDocument(ctx, s.VtcDid)
if err != nil {
return err
}
Expand Down
9 changes: 6 additions & 3 deletions internal/setup/trust_registry_referral.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"github.com/ic3software/vtafarm-api/internal/k8s"
"github.com/ic3software/vtafarm-api/internal/model"
"github.com/ic3software/vtafarm-api/internal/vta"
"github.com/ic3software/vtafarm-api/internal/webvh"
)

const (
Expand All @@ -30,6 +29,10 @@ const (
// newVtaClient is the seam a test replaces to stand in a VTA.
var newVtaClient = vta.NewEphemeral

type referralDIDResolver interface {
ResolveDocument(context.Context, string) ([]byte, error)
}

// publishRegistryReferral adds the TrustRegistry referral to the VTC's
// published DID document, through the running VTA.
//
Expand All @@ -55,8 +58,8 @@ var newVtaClient = vta.NewEphemeral
// with an unchanged document, which the VTA answers by reconciling the host
// and then appending a version. Either way the verify phase that follows reads
// the host, not this function's belief.
func (o *Orchestrator) publishRegistryReferral(ctx context.Context, ns string, s *model.SetupSession) error {
published, err := webvh.NewResolver(webvh.DefaultTimeout).ResolveDocument(ctx, s.VtcDid)
func (o *Orchestrator) publishRegistryReferral(ctx context.Context, ns string, s *model.SetupSession, resolver referralDIDResolver) error {
published, err := resolver.ResolveDocument(ctx, s.VtcDid)
if err != nil {
return fmt.Errorf("resolve the VTC DID before publishing the referral: %w", err)
}
Expand Down
36 changes: 36 additions & 0 deletions internal/setup/trust_registry_referral_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package setup

import (
"context"
"testing"

"github.com/ic3software/vtafarm-api/internal/model"
)

type staticReferralDIDResolver struct {
document []byte
calls int
}

func (r *staticReferralDIDResolver) ResolveDocument(context.Context, string) ([]byte, error) {
r.calls++
return r.document, nil
}

func TestPublishRegistryReferralUsesSuppliedResolver(t *testing.T) {
const vtcDID = "did:webvh:community"
const registryDID = "did:webvh:registry"
document, changed, err := RegistryReferral([]byte(`{"id":"did:webvh:community"}`), vtcDID, registryDID)
if err != nil || !changed {
t.Fatalf("prepare referral: changed=%t err=%v", changed, err)
}
resolver := &staticReferralDIDResolver{document: document}
session := &model.SetupSession{VtcDid: vtcDID, TrustRegistryDid: registryDID}

if err := (&Orchestrator{}).publishRegistryReferral(t.Context(), "unused", session, resolver); err != nil {
t.Fatal(err)
}
if resolver.calls != 1 {
t.Fatalf("resolver calls = %d, want 1", resolver.calls)
}
}
49 changes: 47 additions & 2 deletions internal/setup/trust_registry_setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import (
"context"
"errors"
"fmt"
"log"
"strings"
"time"

"github.com/ic3software/vtafarm-api/internal/k8s"
"github.com/ic3software/vtafarm-api/internal/model"
Expand All @@ -15,6 +17,11 @@ import (
const registryWorkDir = "/work/trust-registry"
const registryCredentialPath = registryWorkDir + "/vta-credential.json"

// The VTA's HTTP readiness becomes true before its independently reconnecting
// mediator WebSocket. Retry only that pre-session timeout: setup has not
// authenticated or mutated Registry identity state at that point.
var registrySetupRetryDelays = []time.Duration{5 * time.Second, 15 * time.Second, 30 * time.Second}

// The earlier offline flow created contexts without the one-time admin handoff.
// Use a distinct context; never repurpose or delete a legacy context's identity.
func registryContextID(id uint) string { return fmt.Sprintf("trust-registry-%d-headless", id) }
Expand Down Expand Up @@ -65,6 +72,42 @@ func parseRegistrySetupOutput(output string, s *model.SetupSession) (string, err
return values["registry_did"], nil
}

func retryableRegistrySetupError(err error) bool {
if err == nil {
return false
}
return strings.Contains(err.Error(), "WebSocket isActive? command timed out")
}

func waitForRegistrySetupRetry(ctx context.Context, delay time.Duration) error {
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
return nil
}
}

func runRegistrySetupWithRetry(
ctx context.Context,
delays []time.Duration,
run func() (string, error),
wait func(context.Context, time.Duration) error,
) (string, error) {
for attempt := 0; ; attempt++ {
output, err := run()
if err == nil || !retryableRegistrySetupError(err) || attempt >= len(delays) {
return output, err
}
log.Printf("[orchestrator] Trust Registry setup reached the VTA before DIDComm was ready; retrying in %s (attempt %d/%d)", delays[attempt], attempt+2, len(delays)+1)
if err := wait(ctx, delays[attempt]); err != nil {
return "", err
}
}
}

// Provision before VTC setup on new stacks, or during opt-in on existing stacks.
// Successful Jobs are receipts: retries reuse their key, grant and output rather
// than replacing credentials or minting another registry DID.
Expand Down Expand Up @@ -141,8 +184,10 @@ func (o *Orchestrator) provisionRegistry(ctx context.Context, ns string, s *mode
if err := o.RegistryPhase(s, "provision_identity"); err != nil {
return err
}
output, err = o.registryJob(ctx, ns, s, "setup", s.TrustRegistryImage, registryWorkDir,
[]string{"trust-registry", "setup", "--from", "/config/tr-setup.toml"}, mounts, map[string][]byte{"tr-setup.toml": recipe})
output, err = runRegistrySetupWithRetry(ctx, registrySetupRetryDelays, func() (string, error) {
return o.registryJob(ctx, ns, s, "setup", s.TrustRegistryImage, registryWorkDir,
[]string{"trust-registry", "setup", "--from", "/config/tr-setup.toml"}, mounts, map[string][]byte{"tr-setup.toml": recipe})
}, waitForRegistrySetupRetry)
if err != nil {
return err
}
Expand Down
49 changes: 49 additions & 0 deletions internal/setup/trust_registry_setup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package setup
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
Expand All @@ -12,6 +13,7 @@ import (
"strings"
"sync"
"testing"
"time"

"github.com/ic3software/vtafarm-api/internal/config"
"github.com/ic3software/vtafarm-api/internal/k8s"
Expand Down Expand Up @@ -68,6 +70,53 @@ func TestRegistryHeadlessRecipeAndCompletion(t *testing.T) {
}
}

func TestRegistrySetupRetriesOnlyMediatorReadinessFailures(t *testing.T) {
t.Run("DIDComm startup gap", func(t *testing.T) {
attempts := 0
var waited []time.Duration
output, err := runRegistrySetupWithRetry(t.Context(), []time.Duration{time.Second, 2 * time.Second}, func() (string, error) {
attempts++
if attempts == 1 {
return "", errors.New("setup job failed: Could not open an authenticated DIDComm session to the VTA (Transport (HTTP(S)) error: WebSocket isActive? command timed out)")
}
return "registry_did=did:webvh:registry", nil
}, func(_ context.Context, delay time.Duration) error {
waited = append(waited, delay)
return nil
})
if err != nil || output != "registry_did=did:webvh:registry" || attempts != 2 || len(waited) != 1 || waited[0] != time.Second {
t.Fatalf("output=%q err=%v attempts=%d waited=%v", output, err, attempts, waited)
}
})

t.Run("configuration failure", func(t *testing.T) {
attempts := 0
want := errors.New("setup recipe is invalid")
_, err := runRegistrySetupWithRetry(t.Context(), []time.Duration{time.Second}, func() (string, error) {
attempts++
return "", want
}, func(context.Context, time.Duration) error {
t.Fatal("non-transient failures must not wait for a retry")
return nil
})
if !errors.Is(err, want) || attempts != 1 {
t.Fatalf("err=%v attempts=%d", err, attempts)
}
})

t.Run("retry budget exhausted", func(t *testing.T) {
attempts := 0
want := errors.New("WebSocket isActive? command timed out")
_, err := runRegistrySetupWithRetry(t.Context(), []time.Duration{time.Second, 2 * time.Second}, func() (string, error) {
attempts++
return "", want
}, func(context.Context, time.Duration) error { return nil })
if !errors.Is(err, want) || attempts != 3 {
t.Fatalf("err=%v attempts=%d", err, attempts)
}
})
}

func TestRegistryPreparationLeavesOptedOutAndExistingCommunitiesAlone(t *testing.T) {
o := &Orchestrator{}
for _, s := range []*model.SetupSession{
Expand Down