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 VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.1.0
1.2.0
92 changes: 92 additions & 0 deletions internal/api/attachments.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package api

import (
"context"
"errors"
"io"
"mime/multipart"
"net/http"
"net/url"
"path/filepath"
"strings"
)

// AttachmentBatch holds paths in delivery order and an opener for each path.
// A send opens and closes at most one input at a time.
type AttachmentBatch struct {
Paths []string
Open func(string) (io.ReadCloser, error)
}

// AttachmentReadError means an input could not be opened or streamed.
type AttachmentReadError struct {
Path string
Err error
}

func (e *AttachmentReadError) Error() string { return "could not read attachment" }
func (e *AttachmentReadError) Unwrap() error { return e.Err }

// NotifyUserWithAttachments sends a batch to the user's private chat.
func (c *Client) NotifyUserWithAttachments(ctx context.Context, token, userID, message, platform string, batch AttachmentBatch) (Delivery, error) {
return c.notifyMultipart(ctx, "/cli/notify/user/"+url.PathEscape(userID), token, message, platform, batch)
}

// NotifyChatWithAttachments sends a batch to a chat.
func (c *Client) NotifyChatWithAttachments(ctx context.Context, token, chatID, message string, batch AttachmentBatch) (Delivery, error) {
return c.notifyMultipart(ctx, "/cli/notify/chat/"+url.PathEscape(chatID), token, message, "", batch)
}

func (c *Client) notifyMultipart(ctx context.Context, path, token, message, platform string, batch AttachmentBatch) (Delivery, error) {
reader, writer := io.Pipe()
form := multipart.NewWriter(writer)
contentType := form.FormDataContentType()
done := make(chan struct{})
var producerErr error
go func() {
defer close(done)
producerErr = writeAttachments(form, message, platform, batch)
_ = writer.CloseWithError(producerErr)
}()
status, body, err := c.callBody(ctx, http.MethodPost, path, token, reader, contentType)
_ = reader.Close()
<-done
var inputErr *AttachmentReadError
if status == 0 && errors.As(producerErr, &inputErr) {
return Delivery{}, inputErr
}
return notifyResult(status, body, err)
}

func writeAttachments(form *multipart.Writer, message, platform string, batch AttachmentBatch) error {
if err := form.WriteField("message", message); err != nil {
return err
}
if platform != "" {
if err := form.WriteField("platform", platform); err != nil {
return err
}
}
var buffer [32 * 1024]byte
for _, path := range batch.Paths {
// percent-encode line breaks so a basename cannot add headers to its part.
name := strings.ReplaceAll(strings.ReplaceAll(filepath.Base(path), "\r", "%0D"), "\n", "%0A")
part, err := form.CreateFormFile("attachments", name)
if err != nil {
return err
}
file, err := batch.Open(path)
if err != nil {
return &AttachmentReadError{Path: path, Err: err}
}
_, err = io.CopyBuffer(part, struct{ io.Reader }{file}, buffer[:])
_ = file.Close()
if err != nil {
if errors.Is(err, io.ErrClosedPipe) {
return err
}
return &AttachmentReadError{Path: path, Err: err}
}
}
return form.Close()
}
21 changes: 12 additions & 9 deletions internal/api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,22 +78,25 @@ func New(o Options) *Client {
// call sends one request and returns the body of a 2xx answer. A non-2xx answer is a classified
// *Error; a transport failure is KindUnreachable. token is sent as a bearer token when not empty.
func (c *Client) call(ctx context.Context, method, path, token string, payload any) (status int, body []byte, err error) {
var reader io.Reader
if payload != nil {
encoded, err := json.Marshal(payload)
if err != nil {
return 0, nil, err
}
reader = bytes.NewReader(encoded)
if payload == nil {
return c.callBody(ctx, method, path, token, nil, "")
}
encoded, err := json.Marshal(payload)
if err != nil {
return 0, nil, err
}
return c.callBody(ctx, method, path, token, bytes.NewReader(encoded), "application/json")
}

func (c *Client) callBody(ctx context.Context, method, path, token string, reader io.Reader, contentType string) (status int, body []byte, err error) {
req, err := http.NewRequestWithContext(ctx, method, c.base+path, reader)
if err != nil {
return 0, nil, &Error{Kind: KindUnreachable, Cause: err}
}
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", c.userAgent)
if payload != nil {
req.Header.Set("Content-Type", "application/json")
if contentType != "" {
req.Header.Set("Content-Type", contentType)
}
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
Expand Down
4 changes: 4 additions & 0 deletions internal/api/endpoints.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,10 @@ func (c *Client) NotifyChat(ctx context.Context, token, chatID, message string)

func (c *Client) notify(ctx context.Context, path, token string, payload any) (Delivery, error) {
status, body, err := c.call(ctx, http.MethodPost, path, token, payload)
return notifyResult(status, body, err)
}

func notifyResult(status int, body []byte, err error) (Delivery, error) {
if err != nil && (status < 200 || status >= 300) {
return Delivery{}, err
}
Expand Down
159 changes: 159 additions & 0 deletions internal/api/endpoints_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,19 @@
package api_test

import (
"context"
"encoding/json"
"errors"
"io"
"mime"
"net/http"
"net/http/httptest"
"path/filepath"
"slices"
"strings"
"sync/atomic"
"testing"
"testing/iotest"
"time"

"github.com/appifyhub/agent-cli/internal/api"
Expand Down Expand Up @@ -314,3 +324,152 @@ func TestNotifyErrorsAreClassified(t *testing.T) {
_, err := newClient(b).NotifyUser(t.Context(), secretToken, "u1", "hi", "")
_ = wantKind(t, err, api.KindInsufficientCredits)
}

func TestNotifyMultipartContract(t *testing.T) {
for _, tc := range []struct {
name, route string
fields [][3]string
}{
{"private", "/cli/notify/user/u%2F%3F", [][3]string{{"message", "", "caption"}, {"platform", "", "whatsapp"}}},
{"chat", "/cli/notify/chat/c%2F%3F", [][3]string{{"message", "", "caption"}}},
} {
t.Run(tc.name, func(t *testing.T) {
first, second := filepath.Join("local", "a.png"), filepath.Join("local", "b, revised.pdf")
data := map[string]string{first: "\x00one", second: "two\xff"}
want := append(tc.fields, [3]string{"attachments", "a.png", data[first]}, [3]string{"attachments", "b, revised.pdf", data[second]})
var hits atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hits.Add(1)
if r.Method != http.MethodPost || r.URL.EscapedPath() != tc.route || r.URL.RawQuery != "" || r.Header.Get("Authorization") != "Bearer "+secretToken {
t.Errorf("unexpected route or credentials: %s %s", r.Method, r.URL)
}
form, err := r.MultipartReader()
if err != nil {
t.Error(err)
w.WriteHeader(http.StatusBadRequest)
return
}
var got [][3]string
for {
part, err := form.NextPart()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
t.Error(err)
break
}
bytes, err := io.ReadAll(part)
if err != nil {
t.Error(err)
}
disposition, params, err := mime.ParseMediaType(part.Header.Get("Content-Disposition"))
if err != nil || disposition != "form-data" {
t.Errorf("invalid multipart disposition: %q, %v", disposition, err)
}
got = append(got, [3]string{params["name"], params["filename"], string(bytes)})
}
if !slices.Equal(got, want) {
t.Errorf("multipart parts = %q, want %q", got, want)
}
w.WriteHeader(http.StatusNoContent)
}))
defer server.Close()
client := api.New(api.Options{BaseURL: server.URL, Transport: server.Client().Transport})
batch := api.AttachmentBatch{Paths: []string{first, second}, Open: func(path string) (io.ReadCloser, error) {
return io.NopCloser(strings.NewReader(data[path])), nil
}}
var err error
if tc.name == "private" {
_, err = client.NotifyUserWithAttachments(t.Context(), secretToken, "u/?", "caption", "whatsapp", batch)
} else {
_, err = client.NotifyChatWithAttachments(t.Context(), secretToken, "c/?", "caption", batch)
}
if err != nil || hits.Load() != 1 {
t.Fatalf("send = %v; requests = %d", err, hits.Load())
}
})
}
}

func TestNotifyMultipartInterruptions(t *testing.T) {
for _, scenario := range []string{"cancelled", "input read failure", "early rejection", "lost response", "unreadable success"} {
t.Run(scenario, func(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
readErr := errors.New("input failed")
var reader io.Reader = strings.NewReader(strings.Repeat("x", 64*1024))
if scenario == "input read failure" {
reader = iotest.ErrReader(readErr)
}
file := &trackedResponseBody{Reader: reader}
opens, hits := 0, 0
batch := api.AttachmentBatch{Paths: []string{"a.png"}, Open: func(string) (io.ReadCloser, error) {
opens++
return file, nil
}}
unreadable := unusableBody(`{"credit_balance":1}`, false)
client := api.New(api.Options{
BaseURL: "http://backend.test",
Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
hits++
if scenario == "cancelled" || scenario == "early rejection" {
form, err := req.MultipartReader()
if err != nil {
t.Fatal(err)
}
if _, err := form.NextPart(); err != nil {
t.Fatal(err)
}
part, err := form.NextPart()
if err != nil {
t.Fatal(err)
}
var firstByte [1]byte
if _, err := io.ReadFull(part, firstByte[:]); err != nil {
t.Fatal(err)
}
if scenario == "cancelled" {
cancel()
return nil, req.Context().Err()
}
return &http.Response{StatusCode: http.StatusTooManyRequests, Body: io.NopCloser(strings.NewReader(""))}, nil
}
if _, err := io.Copy(io.Discard, req.Body); err != nil {
return nil, err
}
if scenario == "lost response" {
return nil, io.ErrUnexpectedEOF
}
return &http.Response{StatusCode: http.StatusAccepted, Body: unreadable}, nil
}),
})
got, err := client.NotifyChatWithAttachments(ctx, secretToken, "c1", "caption", batch)
switch scenario {
case "cancelled":
if !errors.Is(err, context.Canceled) {
t.Fatal(err)
}
case "input read failure":
var inputErr *api.AttachmentReadError
if !errors.Is(err, readErr) || !errors.As(err, &inputErr) || inputErr.Path != "a.png" {
t.Fatalf("missing local read failure: %v", err)
}
case "early rejection":
_ = wantKind(t, err, api.KindRateLimited)
case "lost response":
failure := wantKind(t, err, api.KindUnreachable)
if failure.Status != 0 {
t.Fatal("a lost response cannot establish delivery progress")
}
case "unreadable success":
if err != nil || got.CreditBalance != nil || got.Chat != nil || unreadable.closes != 1 {
t.Fatalf("delivery = %+v, %v; response closes = %d", got, err, unreadable.closes)
}
}
if hits != 1 || opens != 1 || file.closes != 1 {
t.Fatalf("requests = %d, input opens/closes = %d/%d", hits, opens, file.closes)
}
})
}
}
2 changes: 1 addition & 1 deletion internal/api/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ func decodeErrorBody(body []byte) (code int, message string, detail bool) {

var (
errorMarker = regexp.MustCompile(`^\s*\[E\d+\][^\p{L}\p{N}]*`)
causeSuffix = regexp.MustCompile(`\s+# Caused by:.*$`)
causeSuffix = regexp.MustCompile(`(?s)\s+# Caused by:.*$`)
)

// CleanMessage reduces a server message to its text: the leading [E<digits>] marker with the emoji
Expand Down
Loading
Loading