Complete safety and transfer remediation verification
This commit is contained in:
@@ -2,22 +2,106 @@ package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
// WriterDownloader is implemented by storage backends that stream an object
|
||||
// into a caller-owned file handle.
|
||||
type WriterDownloader interface {
|
||||
DownloadTo(ctx context.Context, key string, destination io.Writer) error
|
||||
// StreamObject copies one response into a caller-owned destination and closes
|
||||
// its body. A non-nil expected size is authoritative; otherwise the response's
|
||||
// known size bounds the transfer. Unknown response sizes stream to EOF.
|
||||
func StreamObject(ctx context.Context, store ObjectStore, key string, destination io.Writer, expected *int64) (info ObjectInfo, err error) {
|
||||
label := func(size *int64) string {
|
||||
if size != nil {
|
||||
return fmt.Sprintf("download object %q (expected %d bytes)", key, *size)
|
||||
}
|
||||
return fmt.Sprintf("download object %q", key)
|
||||
}
|
||||
if store == nil || destination == nil {
|
||||
return info, fmt.Errorf("download object %q: store and destination are required", key)
|
||||
}
|
||||
if expected != nil && *expected < 0 {
|
||||
return info, fmt.Errorf("download object %q: invalid expected size %d", key, *expected)
|
||||
}
|
||||
if err := context.Cause(ctx); err != nil {
|
||||
return info, fmt.Errorf("%s: %w", label(expected), err)
|
||||
}
|
||||
info, body, readErr := store.Read(ctx, key)
|
||||
sizeKnown := info.SizeKnown || info.Size > 0
|
||||
size := expected
|
||||
if size == nil && sizeKnown {
|
||||
size = &info.Size
|
||||
}
|
||||
if body != nil {
|
||||
defer func() {
|
||||
if closeErr := body.Close(); closeErr != nil {
|
||||
err = errors.Join(err, fmt.Errorf("%s: close response: %w", label(size), closeErr))
|
||||
}
|
||||
}()
|
||||
}
|
||||
if readErr != nil {
|
||||
return info, fmt.Errorf("%s: %w", label(size), readErr)
|
||||
}
|
||||
if body == nil {
|
||||
return info, fmt.Errorf("%s: response body is missing", label(size))
|
||||
}
|
||||
if expected != nil && sizeKnown && info.Size != *expected {
|
||||
return info, fmt.Errorf("download object %q: expected %d bytes, response reports %d", key, *expected, info.Size)
|
||||
}
|
||||
source := contextReader{ctx: ctx, reader: body}
|
||||
tracked := &transferReader{reader: source}
|
||||
if size == nil {
|
||||
_, copyErr := io.Copy(destination, tracked)
|
||||
if tracked.err != nil && !errors.Is(tracked.err, io.EOF) {
|
||||
copyErr = errors.Join(copyErr, tracked.err)
|
||||
}
|
||||
if err := errors.Join(copyErr, context.Cause(ctx)); err != nil {
|
||||
return info, fmt.Errorf("download object %q: copy body: %w", key, err)
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
count, copyErr := io.CopyN(destination, tracked, *size)
|
||||
if tracked.err != nil && !errors.Is(tracked.err, io.EOF) {
|
||||
copyErr = errors.Join(copyErr, tracked.err)
|
||||
}
|
||||
copyErr = errors.Join(copyErr, context.Cause(ctx))
|
||||
if copyErr != nil {
|
||||
if errors.Is(copyErr, io.EOF) && context.Cause(ctx) == nil {
|
||||
return info, fmt.Errorf("download object %q: expected %d bytes, received %d: %w", key, *size, count, io.ErrUnexpectedEOF)
|
||||
}
|
||||
return info, fmt.Errorf("download object %q: expected %d bytes, copied %d: %w", key, *size, count, copyErr)
|
||||
}
|
||||
var probe [1]byte
|
||||
var n int
|
||||
var probeErr error
|
||||
for n == 0 && probeErr == nil {
|
||||
n, probeErr = source.Read(probe[:])
|
||||
}
|
||||
if n > 0 {
|
||||
oversized := fmt.Errorf("download object %q: expected %d bytes, response is oversized", key, *size)
|
||||
if probeErr != nil && !errors.Is(probeErr, io.EOF) {
|
||||
return info, errors.Join(oversized, probeErr, context.Cause(ctx))
|
||||
}
|
||||
return info, errors.Join(oversized, context.Cause(ctx))
|
||||
}
|
||||
if probeErr != nil && !errors.Is(probeErr, io.EOF) {
|
||||
return info, fmt.Errorf("download object %q: expected %d bytes, probe response: %w", key, *size, errors.Join(probeErr, context.Cause(ctx)))
|
||||
}
|
||||
if err := context.Cause(ctx); err != nil {
|
||||
return info, fmt.Errorf("download object %q: expected %d bytes: %w", key, *size, err)
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// DownloadTo streams one object into destination. Destination-confined callers
|
||||
// require this capability rather than granting a backend a mutable pathname.
|
||||
func DownloadTo(ctx context.Context, store ObjectStore, key string, destination io.Writer) error {
|
||||
writer, ok := store.(WriterDownloader)
|
||||
if !ok {
|
||||
return fmt.Errorf("object store does not support handle-confined downloads")
|
||||
}
|
||||
return writer.DownloadTo(ctx, key, destination)
|
||||
type transferReader struct {
|
||||
reader io.Reader
|
||||
err error
|
||||
}
|
||||
|
||||
func (r *transferReader) Read(p []byte) (int, error) {
|
||||
n, err := r.reader.Read(p)
|
||||
if err != nil {
|
||||
r.err = err
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -21,19 +20,17 @@ type FakeBackend struct {
|
||||
|
||||
Objects map[string]FakeObject
|
||||
Uploads []FakeUploadCall
|
||||
Downloads []FakeDownloadCall
|
||||
Reads []FakeReadCall
|
||||
Deletes []string
|
||||
ExistsKeys []string
|
||||
|
||||
ListErr error
|
||||
DownloadErr error
|
||||
UploadErr error
|
||||
DeleteErr error
|
||||
ExistsErr error
|
||||
UploadHook func(FakeUploadCall) error
|
||||
DownloadHook func(FakeDownloadCall) error
|
||||
ReadHook func(FakeReadCall) error
|
||||
ListErr error
|
||||
ReadErr error
|
||||
UploadErr error
|
||||
DeleteErr error
|
||||
ExistsErr error
|
||||
UploadHook func(FakeUploadCall) error
|
||||
ReadHook func(FakeReadCall) error
|
||||
}
|
||||
|
||||
// FakeUploadCall captures one upload invocation in call order.
|
||||
@@ -43,13 +40,6 @@ type FakeUploadCall struct {
|
||||
Options UploadOptions
|
||||
}
|
||||
|
||||
// FakeDownloadCall captures one download invocation in call order.
|
||||
type FakeDownloadCall struct {
|
||||
Key string
|
||||
LocalPath string
|
||||
Bytes int64
|
||||
}
|
||||
|
||||
// FakeReadCall captures one opened object in call order.
|
||||
type FakeReadCall struct {
|
||||
Key string
|
||||
@@ -123,8 +113,8 @@ func (f *FakeBackend) Read(ctx context.Context, key string) (ObjectInfo, io.Read
|
||||
if err := ctx.Err(); err != nil {
|
||||
return ObjectInfo{}, nil, err
|
||||
}
|
||||
if f.DownloadErr != nil {
|
||||
return ObjectInfo{}, nil, f.DownloadErr
|
||||
if f.ReadErr != nil {
|
||||
return ObjectInfo{}, nil, f.ReadErr
|
||||
}
|
||||
normalizedKey := normalizeObjectKey(key)
|
||||
if f.ReadHook != nil {
|
||||
@@ -148,54 +138,6 @@ func (f *FakeBackend) Read(ctx context.Context, key string) (ObjectInfo, io.Read
|
||||
return ObjectInfo{Key: obj.Key, Size: int64(len(obj.Data)), SizeKnown: true, ETag: obj.ETag, LastModified: obj.LastModified}, io.NopCloser(bytes.NewReader(obj.Data)), nil
|
||||
}
|
||||
|
||||
// DownloadTo writes one object to a caller-owned destination writer.
|
||||
func (f *FakeBackend) DownloadTo(ctx context.Context, key string, destination io.Writer) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if f.DownloadErr != nil {
|
||||
return f.DownloadErr
|
||||
}
|
||||
if destination == nil {
|
||||
return fmt.Errorf("download object: destination writer is required")
|
||||
}
|
||||
if f.DownloadHook != nil {
|
||||
if err := f.DownloadHook(FakeDownloadCall{Key: normalizeObjectKey(key)}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
_, source, err := f.Read(ctx, key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer source.Close()
|
||||
count, err := io.Copy(destination, source)
|
||||
if err != nil {
|
||||
return fmt.Errorf("download object %q: write destination: %w", key, err)
|
||||
}
|
||||
f.mu.Lock()
|
||||
f.Downloads = append(f.Downloads, FakeDownloadCall{Key: normalizeObjectKey(key), Bytes: count})
|
||||
f.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Download writes one object to a local path.
|
||||
func (f *FakeBackend) Download(ctx context.Context, key, localPath string) error {
|
||||
if strings.TrimSpace(localPath) == "" {
|
||||
return fmt.Errorf("download object: local path is required")
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(localPath), 0o755); err != nil {
|
||||
return fmt.Errorf("download object %q: create parent directory: %w", key, err)
|
||||
}
|
||||
destination, err := os.Create(localPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("download object %q: create local file: %w", key, err)
|
||||
}
|
||||
defer destination.Close()
|
||||
return f.DownloadTo(ctx, key, destination)
|
||||
}
|
||||
|
||||
// Upload reads a local file and stores it under key.
|
||||
func (f *FakeBackend) Upload(ctx context.Context, localPath, key string, opts UploadOptions) (ObjectInfo, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
|
||||
@@ -27,23 +27,6 @@ func TestFakeBackendListPrefixFiltering(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestFakeBackendDownload(t *testing.T) {
|
||||
fake := &FakeBackend{}
|
||||
fake.SeedObject(FakeObject{Key: "audio/a.flac", Data: []byte("audio-a")})
|
||||
|
||||
dst := filepath.Join(t.TempDir(), "nested", "a.flac")
|
||||
if err := fake.Download(context.Background(), `audio\a.flac`, dst); err != nil {
|
||||
t.Fatalf("Download() error = %v", err)
|
||||
}
|
||||
data, err := os.ReadFile(dst)
|
||||
if err != nil {
|
||||
t.Fatalf("ReadFile() error = %v", err)
|
||||
}
|
||||
if string(data) != "audio-a" {
|
||||
t.Fatalf("downloaded content = %q, want %q", string(data), "audio-a")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFakeBackendUploadAndExists(t *testing.T) {
|
||||
fake := &FakeBackend{}
|
||||
|
||||
@@ -119,13 +102,13 @@ func TestFakeBackendConditionalUploadRejectsStaleGeneration(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestFakeBackendObjectErrors(t *testing.T) {
|
||||
fake := &FakeBackend{DownloadErr: errors.New("download fail"), UploadErr: errors.New("upload fail"), ListErr: errors.New("list fail"), DeleteErr: errors.New("delete fail"), ExistsErr: errors.New("exists fail")}
|
||||
fake := &FakeBackend{ReadErr: errors.New("download fail"), UploadErr: errors.New("upload fail"), ListErr: errors.New("list fail"), DeleteErr: errors.New("delete fail"), ExistsErr: errors.New("exists fail")}
|
||||
|
||||
if _, err := fake.List(context.Background(), "x"); err == nil || !strings.Contains(err.Error(), "list fail") {
|
||||
t.Fatalf("List() error = %v, want list fail", err)
|
||||
}
|
||||
if err := fake.Download(context.Background(), "x", filepath.Join(t.TempDir(), "x")); err == nil || !strings.Contains(err.Error(), "download fail") {
|
||||
t.Fatalf("Download() error = %v, want download fail", err)
|
||||
if _, _, err := fake.Read(context.Background(), "x"); err == nil || !strings.Contains(err.Error(), "download fail") {
|
||||
t.Fatalf("Read() error = %v, want read failure", err)
|
||||
}
|
||||
local := filepath.Join(t.TempDir(), "x.txt")
|
||||
_ = os.WriteFile(local, []byte("x"), 0o644)
|
||||
|
||||
@@ -25,7 +25,6 @@ type ReaderUploader interface {
|
||||
type ObjectStore interface {
|
||||
List(ctx context.Context, prefix string) ([]ObjectInfo, error)
|
||||
Read(ctx context.Context, key string) (ObjectInfo, io.ReadCloser, error)
|
||||
Download(ctx context.Context, key, localPath string) error
|
||||
Upload(ctx context.Context, localPath, key string, opts UploadOptions) (ObjectInfo, error)
|
||||
UploadConditional(ctx context.Context, source io.Reader, key string, opts UploadOptions, condition WriteCondition) (ObjectInfo, error)
|
||||
Delete(ctx context.Context, key string) error
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -175,45 +174,6 @@ func (b *S3Backend) Read(ctx context.Context, key string) (ObjectInfo, io.ReadCl
|
||||
}, resp.Body, nil
|
||||
}
|
||||
|
||||
// DownloadTo retrieves one object into the caller-owned destination writer.
|
||||
func (b *S3Backend) DownloadTo(ctx context.Context, key string, destination io.Writer) error {
|
||||
if destination == nil {
|
||||
return fmt.Errorf("download object: destination writer is required")
|
||||
}
|
||||
_, body, err := b.Read(ctx, key)
|
||||
if err != nil {
|
||||
return fmt.Errorf("download object %q: %w", normalizeObjectKey(key), err)
|
||||
}
|
||||
defer body.Close()
|
||||
|
||||
if _, err := io.Copy(destination, body); err != nil {
|
||||
return fmt.Errorf("download object %q: copy body: %w", normalizeObjectKey(key), err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Download retrieves one object to localPath, creating parent directories as needed.
|
||||
func (b *S3Backend) Download(ctx context.Context, key, localPath string) error {
|
||||
if strings.TrimSpace(localPath) == "" {
|
||||
return fmt.Errorf("download object: local path is required")
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(localPath), 0o755); err != nil {
|
||||
return fmt.Errorf("download object %q: create parent directory: %w", key, err)
|
||||
}
|
||||
dst, err := os.Create(localPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("download object %q: create local file: %w", key, err)
|
||||
}
|
||||
defer dst.Close()
|
||||
if err := b.DownloadTo(ctx, key, dst); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := dst.Sync(); err != nil {
|
||||
return fmt.Errorf("download object %q: sync local file: %w", key, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Upload sends a local file to key.
|
||||
func (b *S3Backend) Upload(ctx context.Context, localPath, key string, opts UploadOptions) (ObjectInfo, error) {
|
||||
normalizedKey := normalizeObjectKey(key)
|
||||
|
||||
@@ -171,27 +171,6 @@ func TestS3BackendListAndKeyNormalization(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestS3BackendDownloadCreatesParentDirectory(t *testing.T) {
|
||||
client := &fakeS3API{getBody: io.NopCloser(strings.NewReader("audio"))}
|
||||
backend := &S3Backend{bucket: "bucket-1", client: client}
|
||||
|
||||
dst := filepath.Join(t.TempDir(), "nested", "clip.flac")
|
||||
if err := backend.Download(context.Background(), `audio\clip.flac`, dst); err != nil {
|
||||
t.Fatalf("Download() error = %v", err)
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(dst)
|
||||
if err != nil {
|
||||
t.Fatalf("ReadFile() error = %v", err)
|
||||
}
|
||||
if string(data) != "audio" {
|
||||
t.Fatalf("downloaded content = %q, want %q", string(data), "audio")
|
||||
}
|
||||
if client.lastGet == nil || *client.lastGet.Key != "audio/clip.flac" {
|
||||
t.Fatalf("GetObject key = %#v, want normalized key", client.lastGet)
|
||||
}
|
||||
}
|
||||
|
||||
func TestS3BackendReadReturnsOpenedObjectMetadata(t *testing.T) {
|
||||
lastModified := time.Date(2026, 8, 11, 1, 2, 3, 0, time.UTC)
|
||||
client := &fakeS3API{
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
// StreamObject copies one response into a caller-owned destination and closes
|
||||
// its body. A non-nil expected size is authoritative; otherwise the response's
|
||||
// known size bounds the transfer. Unknown response sizes stream to EOF.
|
||||
func StreamObject(ctx context.Context, store ObjectStore, key string, destination io.Writer, expected *int64) (info ObjectInfo, err error) {
|
||||
label := func(size *int64) string {
|
||||
if size != nil {
|
||||
return fmt.Sprintf("download object %q (expected %d bytes)", key, *size)
|
||||
}
|
||||
return fmt.Sprintf("download object %q", key)
|
||||
}
|
||||
if store == nil || destination == nil {
|
||||
return info, fmt.Errorf("download object %q: store and destination are required", key)
|
||||
}
|
||||
if expected != nil && *expected < 0 {
|
||||
return info, fmt.Errorf("download object %q: invalid expected size %d", key, *expected)
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return info, fmt.Errorf("%s: %w", label(expected), err)
|
||||
}
|
||||
info, body, err := store.Read(ctx, key)
|
||||
if err != nil {
|
||||
return info, fmt.Errorf("%s: %w", label(expected), err)
|
||||
}
|
||||
if body == nil {
|
||||
return info, fmt.Errorf("%s: response body is missing", label(expected))
|
||||
}
|
||||
sizeKnown := info.SizeKnown || info.Size > 0
|
||||
size := expected
|
||||
if size == nil && sizeKnown {
|
||||
size = &info.Size
|
||||
}
|
||||
defer func() {
|
||||
if closeErr := body.Close(); closeErr != nil {
|
||||
err = errors.Join(err, fmt.Errorf("%s: close response: %w", label(size), closeErr))
|
||||
}
|
||||
}()
|
||||
if expected != nil && sizeKnown && info.Size != *expected {
|
||||
return info, fmt.Errorf("download object %q: expected %d bytes, response reports %d", key, *expected, info.Size)
|
||||
}
|
||||
source := contextReader{ctx: ctx, reader: body}
|
||||
if size == nil {
|
||||
if _, err := io.Copy(destination, source); err != nil {
|
||||
return info, fmt.Errorf("download object %q: copy body: %w", key, err)
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return info, fmt.Errorf("download object %q: %w", key, err)
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
count, copyErr := io.CopyN(destination, source, *size)
|
||||
if copyErr != nil {
|
||||
if errors.Is(copyErr, io.EOF) {
|
||||
return info, fmt.Errorf("download object %q: expected %d bytes, received %d: %w", key, *size, count, io.ErrUnexpectedEOF)
|
||||
}
|
||||
return info, fmt.Errorf("download object %q: expected %d bytes, copied %d: %w", key, *size, count, copyErr)
|
||||
}
|
||||
var probe [1]byte
|
||||
n, probeErr := io.ReadFull(source, probe[:])
|
||||
if n > 0 {
|
||||
return info, fmt.Errorf("download object %q: expected %d bytes, response is oversized", key, *size)
|
||||
}
|
||||
if probeErr != nil && !errors.Is(probeErr, io.EOF) {
|
||||
return info, fmt.Errorf("download object %q: expected %d bytes, probe response: %w", key, *size, probeErr)
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return info, fmt.Errorf("download object %q: expected %d bytes: %w", key, *size, err)
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
@@ -76,3 +76,39 @@ func TestStreamObjectPreservesFailuresAndClosesResponse(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type byteAndErrorReader struct{ err error }
|
||||
|
||||
func (r byteAndErrorReader) Read(p []byte) (int, error) { p[0] = 'x'; return 1, r.err }
|
||||
|
||||
func TestStreamObjectPreservesProbeAndOpenErrors(t *testing.T) {
|
||||
failure := errors.New("synthetic read error")
|
||||
closeErr := errors.New("synthetic close error")
|
||||
body := &trackingReadCloser{reader: byteAndErrorReader{failure}, closeErr: closeErr}
|
||||
store := &boundedReadStore{read: func(context.Context, string) (ObjectInfo, io.ReadCloser, error) {
|
||||
return ObjectInfo{SizeKnown: true}, body, nil
|
||||
}}
|
||||
_, err := StreamObject(context.Background(), store, "key", io.Discard, nil)
|
||||
if !errors.Is(err, failure) || !errors.Is(err, closeErr) || !body.closed {
|
||||
t.Fatalf("probe error=%v closed=%v", err, body.closed)
|
||||
}
|
||||
body = &trackingReadCloser{reader: strings.NewReader(""), closeErr: closeErr}
|
||||
store.read = func(context.Context, string) (ObjectInfo, io.ReadCloser, error) { return ObjectInfo{}, body, failure }
|
||||
_, err = StreamObject(context.Background(), store, "key", io.Discard, nil)
|
||||
if !errors.Is(err, failure) || !errors.Is(err, closeErr) || !body.closed {
|
||||
t.Fatalf("open error=%v closed=%v", err, body.closed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStreamObjectPreservesCancellationCause(t *testing.T) {
|
||||
ctx, cancel := context.WithCancelCause(context.Background())
|
||||
cause := errors.New("synthetic cancellation cause")
|
||||
body := &trackingReadCloser{reader: strings.NewReader("abc"), chunkSize: 1, afterRead: func() { cancel(cause) }}
|
||||
store := &boundedReadStore{read: func(context.Context, string) (ObjectInfo, io.ReadCloser, error) {
|
||||
return ObjectInfo{Size: 3, SizeKnown: true}, body, nil
|
||||
}}
|
||||
_, err := StreamObject(ctx, store, "key", io.Discard, nil)
|
||||
if !errors.Is(err, cause) || !body.closed {
|
||||
t.Fatalf("error=%v closed=%v", err, body.closed)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ func TestDownloadObjectToTempSuccess(t *testing.T) {
|
||||
|
||||
func TestDownloadObjectToTempFailedDownloadRemovesTempFile(t *testing.T) {
|
||||
sentinel := errors.New("download failed")
|
||||
store := &FakeBackend{DownloadErr: sentinel}
|
||||
store := &FakeBackend{ReadErr: sentinel}
|
||||
pattern := "narratio-test-fail-*.txt"
|
||||
before, err := filepath.Glob(filepath.Join(os.TempDir(), "narratio-test-fail-*.txt"))
|
||||
if err != nil {
|
||||
@@ -57,7 +57,7 @@ func TestDownloadObjectToTempFailedDownloadRemovesTempFile(t *testing.T) {
|
||||
|
||||
func TestDownloadObjectToTempCallerContextWrappingPreservesCause(t *testing.T) {
|
||||
sentinel := errors.New("object missing")
|
||||
store := &FakeBackend{DownloadErr: sentinel}
|
||||
store := &FakeBackend{ReadErr: sentinel}
|
||||
|
||||
_, err := DownloadObjectToTemp(context.Background(), store, "sessions/a/runs/run-123/metadata.txt", "narratio-test-*.txt", nil)
|
||||
if err == nil {
|
||||
|
||||
@@ -136,7 +136,7 @@ func TestCleanupFailurePreservesPublishAndRetriesWithoutRepublishing(t *testing.
|
||||
if got := string(remote.Objects["sentinel/remote-state"].Data); got != "unchanged" {
|
||||
t.Fatalf("remote sentinel = %q, want unchanged", got)
|
||||
}
|
||||
if len(remote.Uploads)+len(remote.Downloads)+len(remote.Reads)+len(remote.Deletes)+len(remote.ExistsKeys) != 0 {
|
||||
if len(remote.Uploads)+len(remote.Reads)+len(remote.Deletes)+len(remote.ExistsKeys) != 0 {
|
||||
t.Fatalf("cleanup touched remote storage: %#v", remote)
|
||||
}
|
||||
|
||||
|
||||
@@ -50,7 +50,4 @@ func TestRestoreCommandDryRunLeavesMissingWorkspaceAbsent(t *testing.T) {
|
||||
if _, err := os.Stat(paths.Root); !os.IsNotExist(err) {
|
||||
t.Fatalf("dry run created workspace: %v", err)
|
||||
}
|
||||
if len(fake.Downloads) != 0 {
|
||||
t.Fatal("dry run installed remote payloads")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,8 +110,10 @@ func TestRestorePlanExistingAudioRequiresVerifiedReplacement(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("buildRestorePlan() error = %v", err)
|
||||
}
|
||||
if len(store.Downloads) != 0 {
|
||||
t.Fatalf("downloads = %d, want no remote checksum download for audio", len(store.Downloads))
|
||||
for _, read := range store.Reads {
|
||||
if read.Key == current.SessionPrefix+"audio/alice.flac" {
|
||||
t.Fatal("audio unexpectedly read during planning")
|
||||
}
|
||||
}
|
||||
actionByRel := map[string]RestoreAction{}
|
||||
for _, action := range plan.Actions {
|
||||
|
||||
@@ -135,7 +135,7 @@ func TestSessionStateCommandReturnsPartialRemoteFailure(t *testing.T) {
|
||||
t.Fatalf("partial report=%#v", report)
|
||||
}
|
||||
}
|
||||
if len(fake.Downloads) != 0 || len(fake.Reads) != 0 || len(fake.Uploads) != 0 || len(fake.Deletes) != 0 {
|
||||
if len(fake.Reads) != 0 || len(fake.Uploads) != 0 || len(fake.Deletes) != 0 {
|
||||
t.Fatal("inspection touched remote payloads")
|
||||
}
|
||||
}
|
||||
@@ -221,8 +221,8 @@ func TestSessionStateCommandsLeaveManifestUnchanged(t *testing.T) {
|
||||
if err != nil || !bytes.Equal(before, after) {
|
||||
t.Fatal("inspection modified manifest")
|
||||
}
|
||||
if len(fake.Uploads) != 0 || len(fake.Downloads) != 0 || len(fake.Deletes) != 0 {
|
||||
t.Fatal("inspection mutated remote state or downloaded payloads")
|
||||
if len(fake.Uploads) != 0 || len(fake.Deletes) != 0 {
|
||||
t.Fatal("inspection mutated remote state")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -99,7 +99,7 @@ func TestNativeProgressTracksDownloadsConcurrentSpeakersAndReuse(t *testing.T) {
|
||||
}
|
||||
store.SeedObject(storage.FakeObject{Key: prefix + "audio/a.flac", Data: []byte("replacement-audio"), ETag: "new-generation"})
|
||||
cause := errors.New("audio download failed")
|
||||
store.DownloadErr = cause
|
||||
store.ReadErr = cause
|
||||
var out, diagnostics bytes.Buffer
|
||||
outcome := app.Execute(context.Background(), append([]string{"run", "2026-05-03", "--stage", "prepare", "--force"}, common...), commandkit.Streams{Out: &out, Err: &diagnostics})
|
||||
if outcome.Status != 1 || !errors.Is(outcome.Cause, cause) || strings.Count(diagnostics.String(), "downloading audio") != 1 || strings.Contains(diagnostics.String(), "audio downloaded") {
|
||||
|
||||
@@ -24,6 +24,16 @@ func (c *ArtifactCatalog) HydrateExtractionArtifacts(
|
||||
paths SessionPaths,
|
||||
m *manifest.Manifest,
|
||||
configured map[string]ExtractionArtifactDefinition,
|
||||
) {
|
||||
c.HydrateExtractionArtifactsExcept(paths, m, configured, nil)
|
||||
}
|
||||
|
||||
// HydrateExtractionArtifactsExcept skips payload reads for excluded sources.
|
||||
func (c *ArtifactCatalog) HydrateExtractionArtifactsExcept(
|
||||
paths SessionPaths,
|
||||
m *manifest.Manifest,
|
||||
configured map[string]ExtractionArtifactDefinition,
|
||||
excluded map[string]bool,
|
||||
) {
|
||||
if c == nil || m == nil || len(configured) == 0 {
|
||||
return
|
||||
@@ -32,7 +42,7 @@ func (c *ArtifactCatalog) HydrateExtractionArtifacts(
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
proof := InspectExtractionEvidence(paths, m, configured, input)
|
||||
proof := inspectExtractionEvidence(paths, m, configured, input, excluded)
|
||||
if proof.State != ExtractionEvidenceValid {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -311,3 +311,25 @@ func extractionFixtureChecksum(t *testing.T, path string) string {
|
||||
}
|
||||
return checksum
|
||||
}
|
||||
|
||||
func TestHydrateExtractionArtifactsExcludesCarriedPayload(t *testing.T) {
|
||||
paths, m, definitions := validExtractionCatalogFixture(t)
|
||||
definitions["clues"] = ExtractionArtifactDefinition{LaneID: "clues", PipelineID: "campaign.extract"}
|
||||
path := filepath.Join(paths.ArtifactsDir, "clues.json")
|
||||
writeExtractionFixtureFile(t, path, `{"clues":[]}`)
|
||||
m.Stages["extract"].Outputs = append(m.Stages["extract"].Outputs, manifest.ArtifactRecord{
|
||||
Kind: "notarius_lane", SourceID: ExtractionArtifactSourceID("clues"), LocalPath: path, ProducerRunID: "extract-run-1",
|
||||
Checksum: extractionFixtureChecksum(t, path), Size: int64(len(`{"clues":[]}`)),
|
||||
ExternalProvenance: &artifactmodel.ExternalProvenance{System: "notarius", PipelineID: "campaign.extract", ArtifactID: "clues"},
|
||||
})
|
||||
if err := os.Remove(m.Stages["extract"].Outputs[0].LocalPath); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
catalog := registeredExtractionCatalog(t, definitions)
|
||||
catalog.HydrateExtractionArtifactsExcept(paths, m, definitions, map[string]bool{ExtractionArtifactSourceID("encounters"): true})
|
||||
carried, _ := catalog.Lookup(ExtractionArtifactSourceID("encounters"))
|
||||
unlocked, _ := catalog.Lookup(ExtractionArtifactSourceID("clues"))
|
||||
if carried.Available || !unlocked.Available {
|
||||
t.Fatalf("carried=%+v unlocked=%+v", carried, unlocked)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,6 +41,18 @@ func InspectExtractionEvidence(
|
||||
m *manifest.Manifest,
|
||||
configured map[string]ExtractionArtifactDefinition,
|
||||
input ExtractionInputIdentity,
|
||||
) ExtractionEvidence {
|
||||
return inspectExtractionEvidence(paths, m, configured, input, nil)
|
||||
}
|
||||
|
||||
// inspectExtractionEvidence can omit payload reads for outputs whose remote
|
||||
// declarations will be carried, while retaining bundle identity checks.
|
||||
func inspectExtractionEvidence(
|
||||
paths SessionPaths,
|
||||
m *manifest.Manifest,
|
||||
configured map[string]ExtractionArtifactDefinition,
|
||||
input ExtractionInputIdentity,
|
||||
omitPayload map[string]bool,
|
||||
) ExtractionEvidence {
|
||||
if m == nil || len(configured) == 0 {
|
||||
return ExtractionEvidence{State: ExtractionEvidenceAbsent, Reason: "extraction evidence is absent"}
|
||||
@@ -99,6 +111,10 @@ func InspectExtractionEvidence(
|
||||
if provenance == nil || provenance.System != "notarius" || provenance.RunID != "" || provenance.PipelineID != pipelineID || pipelineID != strings.TrimSpace(d.PipelineID) || provenance.ArtifactID != d.LaneID {
|
||||
return ExtractionEvidence{State: ExtractionEvidenceObsolete, Reason: "extract output lane or pipeline identity is incompatible"}
|
||||
}
|
||||
if omitPayload[out.SourceID] {
|
||||
seen[out.SourceID] = struct{}{}
|
||||
continue
|
||||
}
|
||||
state, reason, size := inspectExtractionPayload(root, out.LocalPath, out.Checksum)
|
||||
if state != ExtractionEvidenceValid {
|
||||
return ExtractionEvidence{State: state, Reason: reason}
|
||||
|
||||
@@ -180,9 +180,7 @@ func TestLoadCurrentStateReadsVerifiedRemoteCommit(t *testing.T) {
|
||||
if state.Manifest.RunID != commit.RunID {
|
||||
t.Fatalf("manifest run ID = %q, want %q", state.Manifest.RunID, commit.RunID)
|
||||
}
|
||||
if len(store.Downloads) != 0 {
|
||||
t.Fatalf("committed current-state downloads = %#v, want direct bounded reads", store.Downloads)
|
||||
}
|
||||
|
||||
wantReads := []string{state.CurrentPointerKey, state.Pointer.CommitKey, state.CurrentManifestKey}
|
||||
if len(store.Reads) != len(wantReads) {
|
||||
t.Fatalf("committed current-state reads = %#v, want %q", store.Reads, wantReads)
|
||||
|
||||
@@ -26,10 +26,11 @@ func TestAnalyzeAbsolutePathSharesPortableIdentity(t *testing.T) {
|
||||
if got := m.Stages["analyze"].AnalyzeArtifacts["session_recap"].Output.LocalPath; got != "artifacts/session_recap.md" {
|
||||
t.Fatalf("checkpoint is not portable: %q", got)
|
||||
}
|
||||
catalog, err := buildPublishRuntimeArtifactCatalog(paths, m, env.Config.ConcreteArtifacts(), nil)
|
||||
catalog, err := newPublishArtifactCatalog(env.Config.ConcreteArtifacts(), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hydratePublishArtifactCatalog(catalog, paths, m, env.Config.ConcreteArtifacts(), nil, nil)
|
||||
source := artifacts.ConfiguredArtifactSourceID("session_recap")
|
||||
resolved, err := artifacts.ResolveSessionArtifactWithCatalog(paths, m, source, catalog)
|
||||
if err != nil || resolved.Path != item.OutputPath {
|
||||
|
||||
@@ -408,16 +408,6 @@ func (s *preparePreviousCaptureStore) Read(ctx context.Context, key string) (sto
|
||||
return s.delegate.Read(ctx, key)
|
||||
}
|
||||
|
||||
func (s *preparePreviousCaptureStore) Download(ctx context.Context, key, localPath string) error {
|
||||
s.accessKeys = append(s.accessKeys, key)
|
||||
return s.delegate.Download(ctx, key, localPath)
|
||||
}
|
||||
|
||||
func (s *preparePreviousCaptureStore) DownloadTo(ctx context.Context, key string, destination io.Writer) error {
|
||||
s.accessKeys = append(s.accessKeys, key)
|
||||
return storage.DownloadTo(ctx, s.delegate, key, destination)
|
||||
}
|
||||
|
||||
func (s *preparePreviousCaptureStore) Upload(ctx context.Context, localPath, key string, opts storage.UploadOptions) (storage.ObjectInfo, error) {
|
||||
return s.delegate.Upload(ctx, localPath, key, opts)
|
||||
}
|
||||
|
||||
@@ -407,7 +407,7 @@ func TestPrepareStageS3AudioFailures(t *testing.T) {
|
||||
name: "download error",
|
||||
setup: func(_ *Env, _ *manifest.Manifest, fake *storage.FakeBackend) {
|
||||
fake.SeedObject(storage.FakeObject{Key: "dnd/campaigns/forsaken/sessions/2026-05-03/audio/alice.flac", Data: []byte("alice")})
|
||||
fake.DownloadErr = os.ErrPermission
|
||||
fake.ReadErr = os.ErrPermission
|
||||
},
|
||||
wantError: "download s3 audio object",
|
||||
},
|
||||
|
||||
@@ -112,12 +112,7 @@ func (publishStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*S
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("publish: collect previous files: %w", err)
|
||||
}
|
||||
runtimeCatalog, err := buildPublishRuntimeArtifactCatalog(
|
||||
sessionPaths,
|
||||
m,
|
||||
env.Config.ConcreteArtifacts(),
|
||||
env.Config.Pipeline.Notarius,
|
||||
)
|
||||
runtimeCatalog, err := newPublishArtifactCatalog(env.Config.ConcreteArtifacts(), env.Config.Pipeline.Notarius)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("publish: build runtime artifact catalog: %w", err)
|
||||
}
|
||||
@@ -133,6 +128,7 @@ func (publishStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*S
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("publish: read publish output locks: %w", err)
|
||||
}
|
||||
hydratePublishArtifactCatalog(runtimeCatalog, sessionPaths, m, env.Config.ConcreteArtifacts(), env.Config.Pipeline.Notarius, initialLocks)
|
||||
var priorCommit *artifacts.RemoteCommitManifest
|
||||
if publishRulesNeedPriorCommit(publishRules, initialLocks) {
|
||||
priorCommit, err = loadPriorPublishCommit(ctx, env.ObjectStore, sessionPrefix, m.Campaign, m.SessionID)
|
||||
|
||||
@@ -172,12 +172,7 @@ func extractionOutputSetFromCatalog(catalog *artifacts.ArtifactCatalog) map[stri
|
||||
return out
|
||||
}
|
||||
|
||||
func buildPublishRuntimeArtifactCatalog(
|
||||
paths artifacts.SessionPaths,
|
||||
m *manifest.Manifest,
|
||||
definitions map[string]config.ScriptoriumArtifactConfig,
|
||||
notariusCfg *config.NotariusConfig,
|
||||
) (*artifacts.ArtifactCatalog, error) {
|
||||
func newPublishArtifactCatalog(definitions map[string]config.ScriptoriumArtifactConfig, notariusCfg *config.NotariusConfig) (*artifacts.ArtifactCatalog, error) {
|
||||
extractionDefinitions := artifacts.ExtractionDefinitionsFromConfig(notariusCfg)
|
||||
configured := artifacts.ConfiguredArtifactDefinitions(definitions)
|
||||
effective, err := artifacts.ResolveEffectiveArtifactSet(configured, nil)
|
||||
@@ -188,11 +183,34 @@ func buildPublishRuntimeArtifactCatalog(
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return catalog, nil
|
||||
}
|
||||
|
||||
func hydratePublishArtifactCatalog(catalog *artifacts.ArtifactCatalog, paths artifacts.SessionPaths, m *manifest.Manifest, definitions map[string]config.ScriptoriumArtifactConfig, notariusCfg *config.NotariusConfig, locks []artifacts.RemoteLock) {
|
||||
excluded := make(map[string]bool, len(locks))
|
||||
for _, lock := range locks {
|
||||
excluded[lock.Source] = true
|
||||
}
|
||||
configured := artifacts.ConfiguredArtifactDefinitions(definitions)
|
||||
for key := range configured {
|
||||
if excluded[artifacts.ConfiguredArtifactSourceID(key)] {
|
||||
delete(configured, key)
|
||||
}
|
||||
}
|
||||
if notariusCfg != nil && notariusCfg.Enabled {
|
||||
catalog.HydrateExtractionArtifacts(paths, m, extractionDefinitions)
|
||||
extraction := artifacts.ExtractionDefinitionsFromConfig(notariusCfg)
|
||||
allExcluded := len(extraction) > 0
|
||||
for key := range extraction {
|
||||
if !excluded[artifacts.ExtractionArtifactSourceID(key)] {
|
||||
allExcluded = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if !allExcluded {
|
||||
catalog.HydrateExtractionArtifactsExcept(paths, m, extraction, excluded)
|
||||
}
|
||||
}
|
||||
catalog.HydrateAnalyzeArtifacts(paths, m, configured)
|
||||
return catalog, nil
|
||||
}
|
||||
|
||||
func publishOutputRemoteKey(runPrefix, destination string) string {
|
||||
|
||||
Reference in New Issue
Block a user