package plugins import ( "bytes" "context" "crypto/rand" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "hash" "io" "net/http" "net/http/httptest" "os" "os/exec" "path/filepath" "strconv" "strings" "sync" "sync/atomic" "time" extism "github.com/extism/go-sdk" "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/plugins/internal/streamtest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) type streamsInput struct { Handle uint32 `json:"handle,omitempty"` Dst uint32 `json:"dst,omitempty"` Size int64 `json:"size,omitempty"` Chunk int `json:"chunk,omitempty"` Text string `json:"text,omitempty"` URL string `json:"url,omitempty"` Path string `json:"path,omitempty"` Headers map[string][]string `json:"headers,omitempty"` TimeoutMs int32 `json:"timeoutMs,omitempty"` } type streamsOutput struct { Count int64 `json:"count"` SHA string `json:"sha"` Data string `json:"data"` Size int64 `json:"size"` Error string `json:"error"` Handle uint32 `json:"handle"` Status int32 `json:"status"` } var patternCycle = func() []byte { b := make([]byte, 251) for i := range b { b[i] = byte(i) } return b }() // patternReader produces the same bytes as the test plugin's write_pattern: byte(offset % 251). type patternReader struct{ pos, size int64 } func (r *patternReader) Read(p []byte) (int, error) { if r.pos >= r.size { return 0, io.EOF } p = p[:min(int64(len(p)), r.size-r.pos)] for i := 0; i < len(p); { i += copy(p[i:], patternCycle[(r.pos+int64(i))%251:]) } r.pos += int64(len(p)) return len(p), nil } func patternSHA(size int64) string { h := sha256.New() _, _ = io.Copy(h, &patternReader{size: size}) return hex.EncodeToString(h.Sum(nil)) } type hashWriter struct { mu sync.Mutex h hash.Hash closes atomic.Int32 } func newHashWriter() *hashWriter { return &hashWriter{h: sha256.New()} } func (w *hashWriter) Write(p []byte) (int, error) { w.mu.Lock() defer w.mu.Unlock() return w.h.Write(p) } func (w *hashWriter) Close() error { w.closes.Add(1); return nil } func (w *hashWriter) sum() string { w.mu.Lock() defer w.mu.Unlock() return hex.EncodeToString(w.h.Sum(nil)) } func readInput(r io.ReadCloser, chunk int) func(*callScope) (streamsInput, error) { return func(s *callScope) (streamsInput, error) { h, err := s.register(newReadStream(r)) return streamsInput{Handle: h, Chunk: chunk}, err } } func writeInput(w io.WriteCloser, size int64, chunk int) func(*callScope) (streamsInput, error) { return func(s *callScope) (streamsInput, error) { h, err := s.register(newWriteStream(w)) return streamsInput{Handle: h, Size: size, Chunk: chunk}, err } } func copyInput(r io.ReadCloser, w io.WriteCloser) func(*callScope) (streamsInput, error) { return func(s *callScope) (streamsInput, error) { src, err := s.register(newReadStream(r)) if err != nil { return streamsInput{}, err } dst, err := s.register(newWriteStream(w)) return streamsInput{Handle: src, Dst: dst}, err } } func callStreams(ctx context.Context, p *plugin, fn string, timeout time.Duration, prepare func(*callScope) (streamsInput, error)) (streamsOutput, error) { return callPluginFunctionScoped[streamsInput, streamsOutput](ctx, p, fn, timeout, prepare, nil) } // errOnlyCtx reports Canceled from Err once stopped, but never closes Done, so wazero does not see the stop. type errOnlyCtx struct { context.Context stopped atomic.Bool } func (c *errOnlyCtx) Err() error { if c.stopped.Load() { return context.Canceled } return c.Context.Err() } type stopAtEOF struct { io.Reader ctx *errOnlyCtx } func (r stopAtEOF) Read(p []byte) (int, error) { n, err := r.Reader.Read(p) if errors.Is(err, io.EOF) { r.ctx.stopped.Store(true) } return n, err } // enteredReader signals when its first Read starts, so tests act only once the host is blocked in I/O. type enteredReader struct { *io.PipeReader entered chan struct{} once sync.Once } func (r *enteredReader) Read(p []byte) (int, error) { r.once.Do(func() { close(r.entered) }) return r.PipeReader.Read(p) } // buildRustTestPlugin skips when the wasm32-wasip1 Rust target is missing; CI does not install it. func buildRustTestPlugin(dir string) string { ctx := GinkgoT().Context() rustup, err := exec.LookPath("rustup") if err != nil { Skip("rustup is not installed") } targets, err := exec.CommandContext(ctx, rustup, "target", "list", "--installed").Output() if err != nil || !strings.Contains(string(targets), "wasm32-wasip1") { Skip("the wasm32-wasip1 Rust target is not installed") } cargoOut, err := exec.CommandContext(ctx, rustup, "which", "cargo").Output() Expect(err).ToNot(HaveOccurred()) rustc, err := exec.CommandContext(ctx, rustup, "which", "rustc").Output() Expect(err).ToNot(HaveOccurred()) cargo := strings.TrimSpace(string(cargoOut)) cmd := exec.CommandContext(ctx, cargo, "build", "--release", "--target", "wasm32-wasip1") cmd.Dir = dir cmd.Env = append(os.Environ(), "CARGO_BUILD_RUSTC="+strings.TrimSpace(string(rustc))) out, err := cmd.CombinedOutput() Expect(err).ToNot(HaveOccurred(), string(out)) name := filepath.Base(dir) wasm := filepath.Join(dir, "target", "wasm32-wasip1", "release", strings.ReplaceAll(name, "-", "_")+".wasm") pkg := name + PackageExtension // Parallel processes build the same plugin, so each writes its own file and renames it into place. tmp := filepath.Join(testdataDir, fmt.Sprintf("%s.build%d.ndp", name, GinkgoParallelProcess())) defer os.Remove(tmp) Expect(packageFiles(tmp, filepath.Join(dir, manifestFileName), wasm)).To(Succeed()) Expect(os.Rename(tmp, filepath.Join(testdataDir, pkg))).To(Succeed()) return pkg } type testStreamService struct { created *trackingWriter blocked *io.PipeWriter // detachedHasScope records whether detachedCtx, in the last Open, still carried the host-function ctx. detachedHasScope atomic.Bool } func (s *testStreamService) Open(ctx context.Context, text string) (io.ReadCloser, error) { s.detachedHasScope.Store(callScopeFrom(detachedCtx(ctx)) != nil) return io.NopCloser(strings.NewReader(text)), nil } func (s *testStreamService) Create(context.Context, string) (io.WriteCloser, error) { return s.created, nil } func (s *testStreamService) Drain(_ context.Context, in io.ReadCloser) (string, error) { if in == nil { return "", nil } defer in.Close() data, err := io.ReadAll(in) return string(data), err } func (s *testStreamService) Wrap(_ context.Context, wrap streamtest.WrapRequest) (*streamtest.WrapResponse, error) { defer wrap.Body.Close() data, err := io.ReadAll(wrap.Body) if err != nil { return nil, err } out := wrap.Prefix + string(data) return &streamtest.WrapResponse{Size: int64(len(out)), Body: io.NopCloser(strings.NewReader(out))}, nil } func (s *testStreamService) Block(context.Context) (io.ReadCloser, error) { pr, pw := io.Pipe() s.blocked = pw return pr, nil } func (s *testStreamService) Echo(_ context.Context, text string) (string, error) { return text, nil } // streamTestSvc serves the StreamTest host functions, registered for every plugin because test-streams imports them. var streamTestSvc = &testStreamService{created: &trackingWriter{}} func init() { hostServices = append(hostServices, hostServiceEntry{ name: "StreamTest", hasPermission: func(*Permissions) bool { return true }, create: func(*serviceContext) ([]extism.HostFunction, io.Closer, error) { return streamtest.RegisterStreamTestHostFunctions(streamTestSvc), nil, nil }, }) } // loadStreamsPlugin loads pkg with its own StreamTest service, capped at memPages Extism pages (0 for no cap). func loadStreamsPlugin(pkg string, memPages uint32) (*plugin, *testStreamService) { svc := &testStreamService{created: &trackingWriter{}} savedPages, savedSvc := extismMaxMemoryPages, streamTestSvc extismMaxMemoryPages, streamTestSvc = memPages, svc DeferCleanup(func() { extismMaxMemoryPages, streamTestSvc = savedPages, savedSvc }) manager, _ := createTestManagerWithPlugins(nil, pkg) return loadedTestPlugin(manager, strings.TrimSuffix(pkg, PackageExtension)), svc } func callText(ctx context.Context, p *plugin, fn, text string) streamsOutput { GinkgoHelper() out, err := callPluginFunction[streamsInput, streamsOutput](ctx, p, fn, streamsInput{Text: text}) Expect(err).ToNot(HaveOccurred()) return out } // generatedClientSpecs are the specs the Go and the Rust generated clients share. func generatedClientSpecs(call func(fn, text string) streamsOutput) { It("returns a host reader to the plugin", func() { Expect(call("open_read", "hello")).To(Equal(streamsOutput{Data: "hello"})) }) It("converts stream fields of request and response structs", func() { Expect(call("wrap", "abc")).To(Equal(streamsOutput{Data: "p:abc", Size: 5})) }) } var _ = Describe("Plugin streams", func() { Describe("in Go", Ordered, func() { var ( ctx context.Context p *plugin ) BeforeAll(func() { manager, _ := createTestManagerWithPlugins(nil, "test-streams"+PackageExtension) p = loadedTestPlugin(manager, "test-streams") }) BeforeEach(func() { ctx = GinkgoT().Context() }) Describe("reading and writing", func() { call := func(fn string, prepare func(*callScope) (streamsInput, error)) streamsOutput { out, err := callStreams(ctx, p, fn, defaultTimeout, prepare) Expect(err).ToNot(HaveOccurred()) return out } It("reads a host stream in small chunks", func() { text := "the quick brown fox jumps over the lazy dog" out := call("read_all", readInput(io.NopCloser(strings.NewReader(text)), 7)) Expect(out.Error).To(BeEmpty()) Expect(out.Data).To(Equal(text)) Expect(out.Count).To(Equal(int64(len(text)))) }) It("reads a stream larger than one buffer", func() { data := make([]byte, 256<<10) _, _ = rand.Read(data) sum := sha256.Sum256(data) out := call("read_all", readInput(io.NopCloser(bytes.NewReader(data)), 64<<10)) Expect(out.Error).To(BeEmpty()) Expect(out.Count).To(Equal(int64(len(data)))) Expect(out.SHA).To(Equal(hex.EncodeToString(sum[:]))) }) It("writes to a host stream and closes it", func() { w := newHashWriter() const size = 512 << 10 out := call("write_pattern", writeInput(w, size, 100_000)) Expect(out.Error).To(BeEmpty()) Expect(out.Count).To(Equal(int64(size))) Expect(w.sum()).To(Equal(patternSHA(size))) Expect(w.closes.Load()).To(Equal(int32(1))) }) It("copies between host streams", func() { w := &trackingWriter{} out := call("copy", copyInput(io.NopCloser(strings.NewReader("copied inside the host")), w)) Expect(out.Error).To(BeEmpty()) Expect(out.Count).To(Equal(int64(22))) Expect(string(w.bytes())).To(Equal("copied inside the host")) }) It("reports a short write as the count and the writer's error", func() { out := call("write_pattern", writeInput(&errWriter{accept: 10, err: errors.New("disk full")}, 1000, 100)) Expect(out.Count).To(Equal(int64(10))) Expect(out.Error).To(Equal("disk full")) }) It("delivers the data before the error that came with it", func() { r := io.NopCloser(&dataErrReader{data: []byte("abc"), err: io.ErrUnexpectedEOF}) out := call("read_all", readInput(r, 16)) Expect(out.Data).To(Equal("abc")) Expect(out.Error).To(Equal(io.ErrUnexpectedEOF.Error())) }) It("refuses to read a write-only stream", func() { out := call("read_all", writeInput(&trackingWriter{}, 0, 8)) Expect(out.Error).To(Equal("stream is not readable")) }) It("forgets a handle once the plugin closed it", func() { out := call("close_twice", readInput(io.NopCloser(strings.NewReader("x")), 1)) Expect(out.Error).To(Equal("|unknown stream handle")) }) It("fails cleanly when a stream function runs outside a plugin call", func() { instance, err := p.instance(ctx) Expect(err).ToNot(HaveOccurred()) DeferCleanup(func() { instance.Close(ctx) }) exit, raw, err := instance.CallWithContext(ctx, "read_all", []byte(`{"handle":1,"chunk":8}`)) Expect(err).ToNot(HaveOccurred()) Expect(exit).To(Equal(uint32(0))) var out streamsOutput Expect(json.Unmarshal(raw, &out)).To(Succeed()) Expect(out.Error).To(Equal("stream operation failed")) }) }) Describe("lifecycle", func() { It("closes a handle the plugin never closed", func() { r := &trackingReader{Reader: strings.NewReader("xyz")} out, err := callStreams(ctx, p, "leak", defaultTimeout, readInput(r, 1)) Expect(err).ToNot(HaveOccurred()) Expect(out.Count).To(Equal(int64(1))) Expect(r.closed()).To(BeTrue()) }) type callResult struct { out streamsOutput err error } // startCall runs the export fn in the background; every wait on it below is bounded. startCall := func(fn string, callCtx context.Context, timeout time.Duration, prepare func(*callScope) (streamsInput, error)) chan callResult { results := make(chan callResult, 1) go func() { out, err := callStreams(callCtx, p, fn, timeout, prepare) results <- callResult{out: out, err: err} }() return results } newEnteredPipe := func() (*enteredReader, *io.PipeWriter) { pr, pw := io.Pipe() DeferCleanup(func() { _ = pw.Close() _ = pr.Close() }) return &enteredReader{PipeReader: pr, entered: make(chan struct{})}, pw } expectUnblocked := func(r *enteredReader, pw *io.PipeWriter, results chan callResult, stop func(), wantErr error) { Eventually(r.entered).WithTimeout(10 * time.Second).Should(BeClosed()) stop() var res callResult Eventually(results).WithTimeout(5 * time.Second).Should(Receive(&res)) Expect(res.err).To(MatchError(wantErr)) _, err := pw.Write([]byte("x")) Expect(err).To(MatchError(io.ErrClosedPipe)) } It("does not let one call use another call's handle", func() { r, pw := newEnteredPipe() handles := make(chan uint32, 1) results := startCall("read_all", ctx, defaultTimeout, func(s *callScope) (streamsInput, error) { h, err := s.register(newReadStream(r)) handles <- h return streamsInput{Handle: h, Chunk: 16}, err }) var h uint32 Eventually(handles).WithTimeout(10 * time.Second).Should(Receive(&h)) Eventually(r.entered).WithTimeout(10 * time.Second).Should(BeClosed()) otherResults := startCall("read_all", ctx, defaultTimeout, func(*callScope) (streamsInput, error) { return streamsInput{Handle: h, Chunk: 16}, nil }) var other callResult Eventually(otherResults).WithTimeout(10 * time.Second).Should(Receive(&other)) Expect(other.err).ToNot(HaveOccurred()) Expect(other.out.Error).To(Equal("unknown stream handle")) _, err := pw.Write([]byte("mine")) Expect(err).ToNot(HaveOccurred()) Expect(pw.Close()).To(Succeed()) var res callResult Eventually(results).WithTimeout(10 * time.Second).Should(Receive(&res)) Expect(res.err).ToNot(HaveOccurred()) Expect(res.out.Data).To(Equal("mine")) }) It("unblocks a read when the call is cancelled", func() { r, pw := newEnteredPipe() callCtx, cancel := context.WithCancel(ctx) defer cancel() results := startCall("read_all", callCtx, defaultTimeout, readInput(r, 16)) expectUnblocked(r, pw, results, cancel, context.Canceled) }) It("unblocks a read when the time limit passes", func() { r, pw := newEnteredPipe() results := startCall("read_all", ctx, 2*time.Second, readInput(r, 16)) expectUnblocked(r, pw, results, func() {}, context.DeadlineExceeded) }) It("reports a cancel even when the plugin returns cleanly", func() { callCtx := &errOnlyCtx{Context: ctx} r := io.NopCloser(stopAtEOF{Reader: strings.NewReader("cut off"), ctx: callCtx}) _, err := callStreams(callCtx, p, "read_all", defaultTimeout, readInput(r, 16)) Expect(err).To(MatchError(context.Canceled)) }) It("unblocks a stream_copy when the call is cancelled", func() { r, pw := newEnteredPipe() callCtx, cancel := context.WithCancel(ctx) defer cancel() results := startCall("copy", callCtx, defaultTimeout, copyInput(r, &trackingWriter{})) expectUnblocked(r, pw, results, cancel, context.Canceled) }) }) }) Describe("under a memory cap", Ordered, func() { // Each memory (the plugin's and Extism's block memory) is capped below the bytes moved, so any per-chunk // allocation that is not freed runs out of memory. const ( memoryPages = 1024 // 64 MiB transferSize = 96 << 20 ) var ( ctx context.Context p *plugin wantSHA string ) BeforeAll(func() { p, _ = loadStreamsPlugin("test-streams"+PackageExtension, memoryPages) wantSHA = patternSHA(transferSize) }) BeforeEach(func() { ctx = GinkgoT().Context() }) It("reads more than the cap through stream_read", func() { out, err := callStreams(ctx, p, "read_all", 2*time.Minute, readInput(io.NopCloser(&patternReader{size: transferSize}), 64<<10)) Expect(err).ToNot(HaveOccurred()) Expect(out.Error).To(BeEmpty()) Expect(out.Count).To(Equal(int64(transferSize))) Expect(out.SHA).To(Equal(wantSHA)) }) It("writes more than the cap through stream_write", func() { w := newHashWriter() out, err := callStreams(ctx, p, "write_pattern", 2*time.Minute, writeInput(w, transferSize, 64<<10)) Expect(err).ToNot(HaveOccurred()) Expect(out.Error).To(BeEmpty()) Expect(w.sum()).To(Equal(wantSHA)) }) It("fails a write cleanly when the stream buffer cannot be allocated", func() { w := &trackingWriter{} out, err := callStreams(ctx, p, "write_when_out_of_memory", defaultTimeout, writeInput(w, 0, 0)) Expect(err).ToNot(HaveOccurred()) Expect(out.Error).To(Equal("stream buffer allocation failed")) Expect(w.bytes()).To(BeEmpty()) }) }) Describe("in Rust", Ordered, func() { var ( ctx context.Context p *plugin ) BeforeAll(func() { pkg := buildRustTestPlugin(filepath.Join(testdataDir, "test-streams-rs")) p, _ = loadStreamsPlugin(pkg, 1024) // 64 MiB, so the out-of-memory spec can fill it }) BeforeEach(func() { ctx = GinkgoT().Context() }) It("reads a host stream with std::io::Read", func() { out, err := callStreams(ctx, p, "read_all", defaultTimeout, readInput(io.NopCloser(strings.NewReader("streamed to rust")), 0)) Expect(err).ToNot(HaveOccurred()) Expect(out.Error).To(BeEmpty()) Expect(out.Data).To(Equal("streamed to rust")) }) It("reads into a slice that starts at an odd address", func() { out, err := callStreams(ctx, p, "read_unaligned", defaultTimeout, readInput(io.NopCloser(strings.NewReader("misaligned bytes here")), 0)) Expect(err).ToNot(HaveOccurred()) Expect(out.Error).To(BeEmpty()) Expect(out.Data).To(Equal("misaligned bytes here")) }) It("writes from a slice that starts at an odd address", func() { w := &trackingWriter{} out, err := callStreams(ctx, p, "write_unaligned", defaultTimeout, writeInput(w, 0, 0)) Expect(err).ToNot(HaveOccurred()) Expect(out.Error).To(BeEmpty()) Expect(string(w.bytes())).To(Equal("unaligned write, 8+ bytes")) }) It("fails a write cleanly when the stream buffer cannot be allocated", func() { w := &trackingWriter{} out, err := callStreams(ctx, p, "write_when_out_of_memory", defaultTimeout, writeInput(w, 0, 0)) Expect(err).ToNot(HaveOccurred()) Expect(out.Error).To(Equal("stream buffer allocation failed")) Expect(w.bytes()).To(BeEmpty()) }) It("writes a host stream with std::io::Write and closes it", func() { w := &trackingWriter{} out, err := callStreams(ctx, p, "write_greeting", defaultTimeout, writeInput(w, 0, 0)) Expect(err).ToNot(HaveOccurred()) Expect(out.Error).To(BeEmpty()) Expect(string(w.bytes())).To(Equal("hello from rust")) Expect(w.closed()).To(BeTrue()) }) }) }) var _ = Describe("Generated stream host functions", func() { Describe("in Go", Ordered, func() { var ( ctx context.Context p *plugin svc *testStreamService ) BeforeAll(func() { p, svc = loadStreamsPlugin("test-streams"+PackageExtension, 0) }) BeforeEach(func() { ctx = GinkgoT().Context() }) call := func(fn, text string) streamsOutput { return callText(ctx, p, fn, text) } generatedClientSpecs(call) It("gives host functions a detached ctx that is not the host-function ctx", func() { svc.detachedHasScope.Store(true) Expect(call("open_read", "x").Data).To(Equal("x")) Expect(svc.detachedHasScope.Load()).To(BeFalse()) }) It("returns a host writer to the plugin", func() { Expect(call("create_write", "written by plugin").Error).To(BeEmpty()) Expect(string(svc.created.bytes())).To(Equal("written by plugin")) Expect(svc.created.closed()).To(BeTrue()) }) It("hands a plugin's stream to the service and invalidates its handle", func() { out := call("drain_own", "abc") Expect(out.Data).To(Equal("abc")) Expect(out.Error).To(Equal("unknown stream handle")) }) It("rejects a reader the plugin made itself", func() { Expect(call("drain_plugin_reader", "x").Error).To(Equal("only streams from Navidrome can be passed to a host function")) }) It("passes no stream as nil", func() { Expect(call("drain_nil", "").Data).To(Equal("")) }) // Runs after "returns a host writer" (Ordered): its scope closes the shared svc.created writer. It("checks the stream direction", func() { Expect(call("drain_writer", "").Error).To(Equal("stream is not readable")) }) It("treats a JSON null handle as no stream", func() { Expect(call("drain_null_raw", "").Data).To(MatchJSON(`{"result":""}`)) }) It("closes a handed-over stream when the call times out, unblocking the service", func() { done := make(chan error, 1) go func() { _, err := callPluginFunctionWithTimeout[streamsInput, streamsOutput](ctx, p, "drain_blocked", 250*time.Millisecond, streamsInput{}) done <- err }() var err error Eventually(done).WithTimeout(5 * time.Second).Should(Receive(&err)) Expect(err).To(Or(Not(HaveOccurred()), MatchError(context.DeadlineExceeded))) _, werr := svc.blocked.Write([]byte("x")) Expect(werr).To(MatchError(io.ErrClosedPipe)) }) }) Describe("under a memory cap", func() { It("frees a stream's buffer when the plugin hands it over", func() { // 24 MiB; drain_loop would keep 800 x 64 KiB buffers if hand-over leaked them p, _ := loadStreamsPlugin("test-streams"+PackageExtension, 384) out, err := callPluginFunctionWithTimeout[streamsInput, streamsOutput](GinkgoT().Context(), p, "drain_loop", time.Minute, streamsInput{Text: "abc"}) Expect(err).ToNot(HaveOccurred()) Expect(out.Error).To(BeEmpty()) Expect(out.Size).To(Equal(int64(800))) }) }) Describe("in Rust", Ordered, func() { var ( ctx context.Context p *plugin ) BeforeAll(func() { p, _ = loadStreamsPlugin(buildRustTestPlugin(filepath.Join(testdataDir, "test-streams-rs")), 0) }) BeforeEach(func() { ctx = GinkgoT().Context() }) generatedClientSpecs(func(fn, text string) streamsOutput { return callText(ctx, p, fn, text) }) }) Describe("in Rust under a memory cap", func() { It("frees every host response", func() { // 16 MiB; 500 leaked 64 KiB responses would not fit p, _ := loadStreamsPlugin(buildRustTestPlugin(filepath.Join(testdataDir, "test-streams-rs")), 256) out, err := callPluginFunctionWithTimeout[streamsInput, streamsOutput](GinkgoT().Context(), p, "echo_loop", time.Minute, streamsInput{}) Expect(err).ToNot(HaveOccurred()) Expect(out.Error).To(BeEmpty()) Expect(out.Size).To(Equal(int64(500))) }) }) }) // requestEnds serves handler and reports, on the returned channel, once the ctx of a request it is blocked on ends. func requestEnds(handler func(w http.ResponseWriter, r *http.Request, wait func())) (string, chan struct{}) { ended := make(chan struct{}) var once sync.Once srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handler(w, r, func() { select { case <-r.Context().Done(): once.Do(func() { close(ended) }) case <-time.After(30 * time.Second): } }) })) DeferCleanup(srv.Close) return srv.URL, ended } func flushed(w http.ResponseWriter, text string) { _, _ = io.WriteString(w, text) w.(http.Flusher).Flush() } var _ = Describe("Storage and HTTP stream host functions", Ordered, func() { var ( ctx context.Context p *plugin storage string ) BeforeAll(func() { DeferCleanup(conf.SnapshotConfig()) conf.Update(func(c *conf.Options) { c.DataFolder = conf.NewDir(GinkgoT().TempDir()) }) p, _ = loadStreamsPlugin("test-streams"+PackageExtension, 0) storage = getHostStoragePath("test-streams") }) BeforeEach(func() { ctx = GinkgoT().Context() }) call := func(fn string, in streamsInput) streamsOutput { GinkgoHelper() out, err := callPluginFunction[streamsInput, streamsOutput](ctx, p, fn, in) Expect(err).ToNot(HaveOccurred()) return out } // callReturning calls fn and transfers the handle it returns to the host. callReturning := func(fn string, in streamsInput) (any, streamsOutput) { GinkgoHelper() var got any out, err := callPluginFunctionScoped[streamsInput, streamsOutput](ctx, p, fn, defaultTimeout, func(*callScope) (streamsInput, error) { return in, nil }, func(s *callScope, out streamsOutput) error { if out.Error != "" { return errors.New(out.Error) } values, err := s.transfer(out.Handle) if err == nil { got = values[0] } return err }) Expect(err).ToNot(HaveOccurred()) return got, out } store := func(path string, r io.Reader) { GinkgoHelper() f, err := os.Create(filepath.Join(storage, path)) Expect(err).ToNot(HaveOccurred()) _, err = io.Copy(f, r) Expect(err).ToNot(HaveOccurred()) Expect(f.Close()).To(Succeed()) } Describe("Storage", func() { It("returns a stored file to the host as a seekable *os.File", func() { store("seek.txt", strings.NewReader("skip this:keep this")) got, _ := callReturning("open_return", streamsInput{Path: "seek.txt"}) Expect(got).To(BeAssignableToTypeOf(&os.File{})) f := got.(*os.File) defer f.Close() _, err := f.Seek(10, io.SeekStart) Expect(err).ToNot(HaveOccurred()) Expect(io.ReadAll(f)).To(Equal([]byte("keep this"))) }) It("gives a created file write rights only", func() { Expect(call("create_read", streamsInput{Path: "w.txt"}).Error).To(Equal("stream is not readable")) }) It("rejects a path outside the storage folder", func() { Expect(call("open_path", streamsInput{Path: "../x"}).Error).To(ContainSubstring("invalid storage path")) }) }) Describe("HTTP.Execute", func() { It("downloads a response body into storage with stream_copy", func() { const size = 3 << 20 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = io.Copy(w, &patternReader{size: size}) })) DeferCleanup(srv.Close) out := call("download", streamsInput{URL: srv.URL, Path: "download.bin"}) Expect(out.Error).To(BeEmpty()) Expect(out.Status).To(Equal(int32(http.StatusOK))) Expect(out.Count).To(Equal(int64(size))) f, err := os.Open(filepath.Join(storage, "download.bin")) Expect(err).ToNot(HaveOccurred()) defer f.Close() h := newHashWriter() _, err = io.Copy(h, f) Expect(err).ToNot(HaveOccurred()) Expect(h.sum()).To(Equal(patternSHA(size))) }) It("keeps a returned body working after the call, and closing it ends the request", func() { more := make(chan struct{}) var releaseOnce sync.Once release := func() { releaseOnce.Do(func() { close(more) }) } url, ended := requestEnds(func(w http.ResponseWriter, _ *http.Request, wait func()) { flushed(w, "hello ") <-more flushed(w, "world") wait() }) DeferCleanup(release) // after requestEnds: it must run before srv.Close, which waits on the handler got, out := callReturning("fetch_return", streamsInput{URL: url}) body, ok := got.(io.ReadCloser) Expect(ok).To(BeTrue()) DeferCleanup(func() { _ = body.Close() }) Expect(out.Status).To(Equal(int32(http.StatusOK))) release() buf := make([]byte, len("hello world")) _, err := io.ReadFull(body, buf) Expect(err).ToNot(HaveOccurred()) Expect(string(buf)).To(Equal("hello world")) Consistently(ended).WithTimeout(200 * time.Millisecond).ShouldNot(BeClosed()) Expect(body.Close()).To(Succeed()) Eventually(ended).WithTimeout(5 * time.Second).Should(BeClosed()) }) It("ends the request of a body the plugin leaked when the call ends", func() { url, ended := requestEnds(func(w http.ResponseWriter, _ *http.Request, wait func()) { flushed(w, "x") wait() }) Expect(call("fetch_leak", streamsInput{URL: url})).To(HaveField("Count", int64(1))) Eventually(ended).WithTimeout(5 * time.Second).Should(BeClosed()) }) It("cancels the request when the call is cancelled while waiting for headers", func() { entered := make(chan struct{}) url, ended := requestEnds(func(_ http.ResponseWriter, _ *http.Request, wait func()) { close(entered) wait() }) callCtx, cancel := context.WithCancel(ctx) defer cancel() done := make(chan error, 1) go func() { _, err := callPluginFunction[streamsInput, streamsOutput](callCtx, p, "fetch", streamsInput{URL: url}) done <- err }() Eventually(entered).WithTimeout(10 * time.Second).Should(BeClosed()) cancel() var err error Eventually(done).WithTimeout(5 * time.Second).Should(Receive(&err)) Expect(err).To(MatchError(context.Canceled)) Eventually(ended).WithTimeout(5 * time.Second).Should(BeClosed()) }) It("times out waiting for headers and cancels the request", func() { url, ended := requestEnds(func(_ http.ResponseWriter, _ *http.Request, wait func()) { wait() }) out := call("fetch", streamsInput{URL: url, TimeoutMs: 200}) Expect(out.Error).To(Equal(errHeaderTimeout.Error())) Eventually(ended).WithTimeout(5 * time.Second).Should(BeClosed()) }) It("does not time out a slow body once the headers arrived", func() { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { flushed(w, "slow ") time.Sleep(400 * time.Millisecond) flushed(w, "body") })) DeferCleanup(srv.Close) out := call("fetch", streamsInput{URL: srv.URL, TimeoutMs: 200}) Expect(out.Error).To(BeEmpty()) Expect(out.Data).To(Equal("slow body")) }) Describe("with a request body", func() { const size = 1 << 20 type received struct { sha string contentLength int64 } var ( url string uploads chan received redirect string ) BeforeAll(func() { store("upload.bin", &patternReader{size: size}) }) BeforeEach(func() { uploads = make(chan received, 1) mux := http.NewServeMux() mux.HandleFunc("/upload", func(_ http.ResponseWriter, r *http.Request) { h := newHashWriter() _, _ = io.Copy(h, r.Body) uploads <- received{sha: h.sum(), contentLength: r.ContentLength} }) mux.HandleFunc("/redirect", func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/upload", http.StatusTemporaryRedirect) }) srv := httptest.NewServer(mux) DeferCleanup(srv.Close) url, redirect = srv.URL+"/upload", srv.URL+"/redirect" }) It("uploads a stored file and consumes its handle", func() { out := call("upload", streamsInput{URL: url, Path: "upload.bin"}) Expect(out.Error).To(BeEmpty()) Expect(out.Status).To(Equal(int32(http.StatusOK))) Expect(out.Data).To(Equal("unknown stream handle")) var got received Expect(uploads).To(Receive(&got)) Expect(got.sha).To(Equal(patternSHA(size))) Expect(got.contentLength).To(Equal(int64(-1)), "unknown length goes chunked") }) It("sends a declared Content-Length", func() { out := call("upload", streamsInput{URL: url, Path: "upload.bin", Headers: map[string][]string{"content-length": {strconv.Itoa(size)}}}) Expect(out.Error).To(BeEmpty()) var got received Expect(uploads).To(Receive(&got)) Expect(got.contentLength).To(Equal(int64(size))) Expect(got.sha).To(Equal(patternSHA(size))) }) It("returns a 307 instead of following it", func() { out := call("upload", streamsInput{URL: redirect, Path: "upload.bin"}) Expect(out.Error).To(BeEmpty()) Expect(out.Status).To(Equal(int32(http.StatusTemporaryRedirect))) Expect(uploads).ToNot(Receive()) }) It("consumes the body when the request fails before it is sent", func() { out := call("upload", streamsInput{URL: "http://not-allowed.invalid/upload", Path: "upload.bin"}) Expect(out.Error).To(Equal(`host "not-allowed.invalid" is not allowed`)) Expect(out.Data).To(Equal("unknown stream handle")) }) }) }) })