Make restricted artifact reads cooperatively cancellable
This commit is contained in:
@@ -60,7 +60,7 @@ func (r *restrictedArtifactReader) Read(ctx context.Context, ref promptkit.Artif
|
||||
case promptkit.ArtifactRefInline:
|
||||
return readInlineArtifact(ref)
|
||||
case promptkit.ArtifactRefFile:
|
||||
return r.readFileArtifact(ref)
|
||||
return r.readFileArtifact(ctx, ref)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported artifact reference type %q", ref.Type)
|
||||
}
|
||||
@@ -81,7 +81,7 @@ func readInlineArtifact(ref promptkit.ArtifactRef) (*promptkit.Artifact, error)
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *restrictedArtifactReader) readFileArtifact(ref promptkit.ArtifactRef) (*promptkit.Artifact, error) {
|
||||
func (r *restrictedArtifactReader) readFileArtifact(ctx context.Context, ref promptkit.ArtifactRef) (*promptkit.Artifact, error) {
|
||||
if ref.URI == "" {
|
||||
return nil, errors.New("file artifact path is required")
|
||||
}
|
||||
@@ -93,7 +93,7 @@ func (r *restrictedArtifactReader) readFileArtifact(ref promptkit.ArtifactRef) (
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return readArtifactFile(path, r.maxBytes)
|
||||
return readArtifactFile(ctx, path, r.maxBytes)
|
||||
}
|
||||
|
||||
// resolveLexicalPath checks cleaned path containment without resolving symlinks.
|
||||
@@ -120,49 +120,97 @@ func (r *restrictedArtifactReader) resolveLexicalPath(rawPath string) (string, e
|
||||
return absCandidate, nil
|
||||
}
|
||||
|
||||
func readArtifactFile(path string, maxBytes int64) (*promptkit.Artifact, error) {
|
||||
func readArtifactFile(ctx context.Context, path string, maxBytes int64) (*promptkit.Artifact, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to stat file %s: %w", path, err)
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return nil, fmt.Errorf("file %s is not a regular file", path)
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read file %s: %w", path, err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
info, err := file.Stat()
|
||||
info, err = file.Stat()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to stat file %s: %w", path, err)
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return nil, fmt.Errorf("file %s is not a regular file", path)
|
||||
}
|
||||
if maxBytes > 0 && info.Size() > maxBytes {
|
||||
return nil, ErrFileTooLarge
|
||||
}
|
||||
|
||||
var reader io.Reader = file
|
||||
if maxBytes > 0 {
|
||||
readLimit := maxBytes
|
||||
if readLimit < math.MaxInt64 {
|
||||
readLimit++ // Read one extra byte to detect an oversized file.
|
||||
}
|
||||
reader = io.LimitReader(file, readLimit)
|
||||
}
|
||||
body, err := io.ReadAll(reader)
|
||||
body, err := readArtifactBody(ctx, file, maxBytes)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read file %s: %w", path, err)
|
||||
}
|
||||
if maxBytes > 0 && int64(len(body)) > maxBytes {
|
||||
return nil, ErrFileTooLarge
|
||||
}
|
||||
|
||||
contentType := mime.TypeByExtension(filepath.Ext(path))
|
||||
if contentType == "" {
|
||||
contentType = fallbackArtifactContentType
|
||||
}
|
||||
return &promptkit.Artifact{
|
||||
artifact := &promptkit.Artifact{
|
||||
Name: filepath.Base(path),
|
||||
ContentType: contentType,
|
||||
Body: body,
|
||||
URI: path,
|
||||
Size: int64(len(body)),
|
||||
Hash: artifactHash(body),
|
||||
}, nil
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return artifact, nil
|
||||
}
|
||||
|
||||
type contextReader struct {
|
||||
ctx context.Context
|
||||
reader io.Reader
|
||||
}
|
||||
|
||||
func (r contextReader) Read(p []byte) (int, error) {
|
||||
if err := r.ctx.Err(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
n, err := r.reader.Read(p)
|
||||
if ctxErr := r.ctx.Err(); ctxErr != nil {
|
||||
return n, ctxErr
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func readArtifactBody(ctx context.Context, source io.Reader, maxBytes int64) ([]byte, error) {
|
||||
var reader io.Reader = contextReader{ctx: ctx, reader: source}
|
||||
if maxBytes > 0 {
|
||||
readLimit := maxBytes
|
||||
if readLimit < math.MaxInt64 {
|
||||
readLimit++ // Read one extra byte to detect an oversized file.
|
||||
}
|
||||
reader = io.LimitReader(reader, readLimit)
|
||||
}
|
||||
body, err := io.ReadAll(reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if maxBytes > 0 && int64(len(body)) > maxBytes {
|
||||
return nil, ErrFileTooLarge
|
||||
}
|
||||
|
||||
return body, nil
|
||||
}
|
||||
|
||||
func artifactHash(body []byte) string {
|
||||
|
||||
56
internal/adapter/http/artifact_reader_linux_test.go
Normal file
56
internal/adapter/http/artifact_reader_linux_test.go
Normal file
@@ -0,0 +1,56 @@
|
||||
package httpadapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go.maximumdirect.net/promptkit"
|
||||
)
|
||||
|
||||
func TestRestrictedArtifactReaderRejectsFIFO(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
path := filepath.Join(root, "pipe")
|
||||
if err := syscall.Mkfifo(path, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reader, err := NewRestrictedArtifactReader(root, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := reader.Read(context.Background(), promptkit.File("pipe"))
|
||||
done <- err
|
||||
}()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err == nil {
|
||||
t.Fatal("expected FIFO rejection")
|
||||
}
|
||||
return
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
// Release an old blocking FIFO open before joining the worker.
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
fd, err := syscall.Open(path, syscall.O_WRONLY|syscall.O_NONBLOCK, 0)
|
||||
if err == nil {
|
||||
_ = syscall.Close(fd)
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-done:
|
||||
t.Fatal("FIFO read did not reject promptly")
|
||||
case <-time.After(10 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-done:
|
||||
t.Fatal("FIFO read did not reject promptly")
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("FIFO reader could not be released")
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package httpadapter
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"math"
|
||||
"mime"
|
||||
"os"
|
||||
@@ -13,6 +14,38 @@ import (
|
||||
"go.maximumdirect.net/promptkit"
|
||||
)
|
||||
|
||||
type cancelingBodyReader struct {
|
||||
cancel context.CancelFunc
|
||||
err error
|
||||
}
|
||||
|
||||
func (r cancelingBodyReader) Read(p []byte) (int, error) {
|
||||
r.cancel()
|
||||
return copy(p, "data"), r.err
|
||||
}
|
||||
|
||||
func TestArtifactBodyReadHonorsCancellation(t *testing.T) {
|
||||
for _, readErr := range []error{nil, io.EOF} {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
body, err := readArtifactBody(ctx, cancelingBodyReader{cancel: cancel, err: readErr}, 4)
|
||||
if !errors.Is(err, context.Canceled) || body != nil {
|
||||
t.Errorf("read error %v: body=%q, err=%v", readErr, body, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestrictedArtifactReaderRejectsDirectory(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
reader, err := NewRestrictedArtifactReader(root, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
artifact, err := reader.Read(context.Background(), promptkit.File("."))
|
||||
if err == nil || artifact != nil {
|
||||
t.Fatalf("expected directory rejection, got %#v, %v", artifact, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestrictedArtifactReaderReturnsDetachedBodies(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(root, "input.txt"), []byte("original"), 0o644); err != nil {
|
||||
|
||||
@@ -28,6 +28,49 @@ type fakeRunner struct {
|
||||
|
||||
type runnerFunc func(context.Context, promptkit.RunRequest) (*promptkit.RunResult, error)
|
||||
|
||||
type cancelingArtifactReader struct {
|
||||
cancel context.CancelFunc
|
||||
reader promptkit.ArtifactReader
|
||||
}
|
||||
|
||||
func (r cancelingArtifactReader) Read(ctx context.Context, ref promptkit.ArtifactRef) (*promptkit.Artifact, error) {
|
||||
r.cancel()
|
||||
return r.reader.Read(ctx, ref)
|
||||
}
|
||||
|
||||
func TestHandlerCancellationDuringRestrictedArtifactAcquisition(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(root, "input.txt"), []byte("input"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reader, err := NewRestrictedArtifactReader(root, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
client := &blockingLLMClient{started: make(chan struct{}, 1), release: make(chan struct{})}
|
||||
close(client.release)
|
||||
engine := newHandlerEngineWithOptions(t, promptkit.WithArtifactReader(cancelingArtifactReader{cancel: cancel, reader: reader}), promptkit.WithLLMClient(client))
|
||||
var runErr error
|
||||
h := NewHandler(runnerFunc(func(ctx context.Context, req promptkit.RunRequest) (*promptkit.RunResult, error) {
|
||||
result, err := engine.Run(ctx, req)
|
||||
runErr = err
|
||||
return result, err
|
||||
}))
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, httptest.NewRequestWithContext(ctx, http.MethodPost, "/v1/runs", strings.NewReader(`{"prompt_id":"p","inputs":{"input":{"type":"file","uri":"input.txt"}}}`)))
|
||||
assertHTTPErrorCode(t, w, http.StatusRequestTimeout, "request_canceled")
|
||||
if !errors.Is(runErr, context.Canceled) {
|
||||
t.Fatalf("engine lost cancellation identity: %v", runErr)
|
||||
}
|
||||
select {
|
||||
case <-client.started:
|
||||
t.Fatal("provider was dispatched after cancellation")
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func (run runnerFunc) Run(ctx context.Context, req promptkit.RunRequest) (*promptkit.RunResult, error) {
|
||||
return run(ctx, req)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user