HTTP API: a chat's recent messages, and sending a message (closes #5)
check / check (push) Successful in 1m21s

GET /api/v1/chats/{id}/messages returns the messages among a chat's
last count items (default 20, at most 100), oldest first. POST sends a
text, waits for the chat client's answer and returns 201 with the
message as sent. A chat the bot does not have is 404, a contact who
deleted the chat is 409, a text too long for one message is 413, and
any other failure is 500 with a chosen sentence.

The chat client spells out a message's formatting in its answer, up to
26 times the text's length, so 100 items in one answer can pass the
16 MiB read limit and end the connection. Items are read five at a
time.

Model: opus-5-5
This commit is contained in:
2026-09-29 03:48:45 +00:00
parent 8f0906d677
commit 2ad0b68e35
10 changed files with 1018 additions and 28 deletions
+97 -4
View File
@@ -14,6 +14,7 @@ import (
"errors"
"fmt"
"log/slog"
"slices"
"strconv"
"strings"
"sync"
@@ -21,15 +22,33 @@ import (
"github.com/gorilla/websocket"
)
// maxMessageSize bounds one message from the chat client. The largest
// thing it sends is a record carrying a contact's profile picture, well
// under this.
// maxMessageSize bounds one message from the chat client; a larger one
// ends the connection. The largest it sends are the pages of chat items
// ChatItems asks for, which chatItemsPage keeps under this.
const maxMessageSize = 16 << 20
// chatItemsPage is how many chat items ChatItems asks for at a time. An
// item repeats a message's text and spells out its formatting, which for
// text made of short mentions makes it 26 times as long as the text, and
// a contact's message can hold 64 KiB: one item can take 1.7 MiB. Five
// stay well under maxMessageSize.
const chatItemsPage = 5
var (
// ErrClosed is returned by Command once the connection has ended.
ErrClosed = errors.New("connection to the chat client closed")
// ErrNoContact is returned for a contact the user does not have.
ErrNoContact = errors.New("no such contact")
// ErrContactNotReady is returned for sending to a contact who cannot
// receive messages: one who has deleted their chat with the user, or
// who has not finished connecting.
ErrContactNotReady = errors.New("the contact cannot receive messages")
// ErrMessageTooLarge is returned for a message too large to send.
ErrMessageTooLarge = errors.New("the message is too large")
errUnexpected = errors.New("unexpected response")
errCommand = errors.New("command failed")
)
@@ -180,6 +199,43 @@ func (c *Client) Contacts(ctx context.Context, userID int64) ([]Contact, error)
return r.Contacts, err
}
// ChatItems returns the last count items of the chat with a contact,
// oldest first, or all of them if the chat has fewer.
func (c *Client) ChatItems(
ctx context.Context, contactID int64, count int,
) ([]ChatItem, error) {
var (
items []ChatItem
before int64 // 0 asks for the chat's last items
)
for len(items) < count {
page := min(count-len(items), chatItemsPage)
//nolint:tagliatelle // the chat client's wire format.
var r struct {
Chat struct {
ChatItems []ChatItem `json:"chatItems"`
} `json:"chat"`
}
err := c.command(ctx, cmdGetChat(contactID, before, page), TypeAPIChat, &r)
if err != nil {
return nil, err
}
items = slices.Concat(r.Chat.ChatItems, items)
if len(r.Chat.ChatItems) < page {
break
}
before = items[0].Meta.ItemID
}
return items, nil
}
// SendText sends a text message to a contact, as a reply to the message
// quotedItemID (0 for none). It does not wait for the chat client to
// accept it; a failure is logged when the client's answer arrives.
@@ -196,6 +252,32 @@ func (c *Client) SendText(contactID, quotedItemID int64, text string) error {
return c.write(id, cmd)
}
// SendMessage sends a text message to a contact and returns it as the
// chat client recorded it. Unlike SendText, it waits for the chat
// client's answer, so an EventHandler must never call it.
func (c *Client) SendMessage(
ctx context.Context, contactID int64, text string,
) (ChatItem, error) {
cmd, err := cmdSendText(contactID, 0, text)
if err != nil {
return ChatItem{}, err
}
var r NewChatItems
err = c.command(ctx, cmd, TypeNewChatItems, &r)
if err != nil {
return ChatItem{}, err
}
if len(r.ChatItems) != 1 {
return ChatItem{}, fmt.Errorf("%w to %q: %d chat items",
errUnexpected, cmdName(cmd), len(r.ChatItems))
}
return r.ChatItems[0].ChatItem, nil
}
// CommandError is a command the chat client refused. Type and Detail
// are the discriminators of its chatError record, such as "errorStore"
// and "userContactLinkNotFound".
@@ -341,6 +423,8 @@ func (c *Client) dispatch(data []byte) {
}
}
// commandError returns the error in a chatCmdError record, marked with
// this package's error for the refusals that have one.
func commandError(ev Event) error {
var r cmdError
@@ -359,7 +443,16 @@ func commandError(ev Event) error {
}
}
return e
switch e.Detail {
case "contactNotFound":
return fmt.Errorf("%w: %w", ErrNoContact, e)
case "contactNotReady":
return fmt.Errorf("%w: %w", ErrContactNotReady, e)
case "largeMsg":
return fmt.Errorf("%w: %w", ErrMessageTooLarge, e)
default:
return e
}
}
// cmdName is a command without its arguments, for error messages: the