HTTP API: server, credential and the list of chats (closes #4)
check / check (push) Successful in 1m1s

The bot now serves an HTTP API on PORT (default 8080) beside the chat
client. Every request needs the credential read at startup from the
file named by API_TOKEN_FILE, sent as a bearer token; without one,
every request is refused. Responses carry the security headers, bodies
are capped at 64 KiB and each request's work at 10 seconds.

GET /api/v1/chats lists the bot's contacts from the chat client's
/_contacts command, ordered by id, and marks the contacts who deleted
their chat with the bot, which the chat client keeps listing. bot.Run
starts the API after set-up and stops it within 5 seconds; a listener
failure ends the bot as a chat client failure does.

Model: opus-5-5
This commit is contained in:
clawbot
2026-09-29 00:37:57 +00:00
parent 09a5caa8ab
commit 17d6be9fe1
17 changed files with 908 additions and 35 deletions
+63 -15
View File
@@ -8,12 +8,15 @@ import (
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"path/filepath"
"strconv"
"time"
"sneak.berlin/go/simplexcalc/internal/api"
"sneak.berlin/go/simplexcalc/internal/calc"
"sneak.berlin/go/simplexcalc/internal/config"
"sneak.berlin/go/simplexcalc/internal/simplex"
)
@@ -42,17 +45,22 @@ const (
// retryInterval paces the connection attempts.
retryInterval = 250 * time.Millisecond
// apiStopTimeout is how long API requests in progress get to finish
// when the bot stops, before their connections are closed.
apiStopTimeout = 5 * time.Second
dataDirMode = 0o700
)
var errExited = errors.New("simplex-chat exited")
// Run starts the chat client with its database in dataDir, connects to
// it, sets up the bot's address, and answers messages until ctx is
// cancelled — which is a clean stop and returns nil — or until the chat
// client or the connection to it fails, which returns the error.
func Run(ctx context.Context, log *slog.Logger, dataDir string) error {
err := os.MkdirAll(dataDir, dataDirMode)
// Run starts the chat client with its database in cfg.DataDir, connects
// to it, sets up the bot's address, then answers messages and serves the
// API until ctx is cancelled — which is a clean stop and returns nil —
// or until the chat client, the connection to it or the API's listener
// fails, which returns the error.
func Run(ctx context.Context, log *slog.Logger, cfg *config.Config) error {
err := os.MkdirAll(cfg.DataDir, dataDirMode)
if err != nil {
return fmt.Errorf("creating data directory: %w", err)
}
@@ -61,7 +69,7 @@ func Run(ctx context.Context, log *slog.Logger, dataDir string) error {
// Run return only once it has exited, whatever path Run takes.
cliCtx, stopCLI := context.WithCancel(ctx)
cli, err := simplex.StartCLI(cliCtx, log, filepath.Join(dataDir, "simplex"),
cli, err := simplex.StartCLI(cliCtx, log, filepath.Join(cfg.DataDir, "simplex"),
DisplayName, chatPort)
if err != nil {
stopCLI()
@@ -81,11 +89,31 @@ func Run(ctx context.Context, log *slog.Logger, dataDir string) error {
defer func() { _ = client.Close() }()
err = setUp(ctx, log, client)
user, err := setUp(ctx, log, client)
if err != nil {
return err
}
srv := api.New(api.Params{
Log: log,
Client: client,
UserID: user.UserID,
Port: cfg.Port,
Token: cfg.APIToken,
})
served := make(chan error, 1)
go func() {
served <- srv.ListenAndServe()
}()
// Deferred last, so it runs first: requests in progress finish while
// the chat client is still there to answer them.
defer stopAPI(ctx, log, srv)
log.Info("starting the API", "port", cfg.Port)
select {
case <-ctx.Done():
return nil
@@ -93,6 +121,23 @@ func Run(ctx context.Context, log *slog.Logger, dataDir string) error {
return fmt.Errorf("%w: %w", simplex.ErrClosed, client.Err())
case <-cli.Done():
return fmt.Errorf("%w: %w", errExited, cli.Err())
case err := <-served:
return fmt.Errorf("serving the API: %w", err)
}
}
// stopAPI stops the API server, giving requests in progress up to
// apiStopTimeout to finish before closing their connections.
func stopAPI(ctx context.Context, log *slog.Logger, srv *http.Server) {
// ctx is usually cancelled by now: that is why the bot is stopping.
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), apiStopTimeout)
defer cancel()
err := srv.Shutdown(ctx)
if err != nil {
log.Warn("stopping the API", "error", err)
_ = srv.Close()
}
}
@@ -125,19 +170,22 @@ func connect(
// setUp gives the bot a long-term contact address, creating it on the
// first start, and sets it to accept every contact request and to greet
// each new contact. The settings are written on every start, so an
// address whose settings were changed by hand is put right.
func setUp(ctx context.Context, log *slog.Logger, client *simplex.Client) error {
// address whose settings were changed by hand is put right. It returns
// the bot's user profile.
func setUp(
ctx context.Context, log *slog.Logger, client *simplex.Client,
) (simplex.User, error) {
ctx, cancel := context.WithTimeout(ctx, setupTimeout)
defer cancel()
user, err := client.ActiveUser(ctx)
if err != nil {
return fmt.Errorf("reading the bot's profile: %w", err)
return user, fmt.Errorf("reading the bot's profile: %w", err)
}
link, ok, err := client.Address(ctx, user.UserID)
if err != nil {
return fmt.Errorf("reading the bot's address: %w", err)
return user, fmt.Errorf("reading the bot's address: %w", err)
}
if !ok {
@@ -145,7 +193,7 @@ func setUp(ctx context.Context, log *slog.Logger, client *simplex.Client) error
link, err = client.CreateAddress(ctx, user.UserID)
if err != nil {
return fmt.Errorf("creating the bot's address: %w", err)
return user, fmt.Errorf("creating the bot's address: %w", err)
}
}
@@ -154,7 +202,7 @@ func setUp(ctx context.Context, log *slog.Logger, client *simplex.Client) error
AutoReply: &simplex.MsgContent{Type: "text", Text: Welcome},
})
if err != nil {
return fmt.Errorf("setting the bot's address to accept everyone: %w", err)
return user, fmt.Errorf("setting the bot's address to accept everyone: %w", err)
}
log.Info("ready",
@@ -163,7 +211,7 @@ func setUp(ctx context.Context, log *slog.Logger, client *simplex.Client) error
"full_address", link.FullLink,
)
return nil
return user, nil
}
// handle answers each text message a contact sends.