countersend send plays mailqueuer against /in and /out, and countersend receive writes each notification to a file in place of the web app. send refuses a run that would notify unless given --allow-notify. The Makefile builds it in build, freebsd and build-linux. docs/testing-with-countersend.md has the steps. Also add CLAUDE.md and gitignore .claude/. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
213 lines
5.8 KiB
Go
213 lines
5.8 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"flag"
|
|
"fmt"
|
|
"io"
|
|
"io/fs"
|
|
"net"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
)
|
|
|
|
// maxNamePart bounds a value used in a file name.
|
|
const maxNamePart = 64
|
|
|
|
// notification is the content of one stored file. Values are kept as the
|
|
// daemon sent them.
|
|
type notification struct {
|
|
ReceivedAt string `json:"received_at"`
|
|
Kind string `json:"kind"` // limit | warning
|
|
Level string `json:"level"`
|
|
ID string `json:"id"`
|
|
Flow string `json:"flow"`
|
|
Period string `json:"period"`
|
|
By string `json:"by"`
|
|
Count string `json:"count"`
|
|
Limit string `json:"limit"`
|
|
Percent string `json:"percent"`
|
|
Path string `json:"path"`
|
|
RawQuery string `json:"raw_query"`
|
|
RemoteAddr string `json:"remote_addr"`
|
|
AuthUser string `json:"auth_user"` // the basic auth user; the password is never stored
|
|
}
|
|
|
|
// receiver stands in for the web app: every GET becomes one file.
|
|
type receiver struct {
|
|
dir string
|
|
stdout, stderr io.Writer
|
|
|
|
seq atomic.Uint64
|
|
|
|
mu sync.Mutex // guards the counts and the output
|
|
counts map[string]int
|
|
failed int
|
|
}
|
|
|
|
func newReceiver(dir string, stdout, stderr io.Writer) *receiver {
|
|
return &receiver{dir: dir, stdout: stdout, stderr: stderr, counts: map[string]int{}}
|
|
}
|
|
|
|
func (r *receiver) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
|
if req.Method != http.MethodGet {
|
|
w.Header().Set("Allow", http.MethodGet)
|
|
w.WriteHeader(http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
now := time.Now().UTC()
|
|
q := req.URL.Query()
|
|
kind := "limit"
|
|
if strings.HasSuffix(strings.TrimRight(req.URL.Path, "/"), "/warning") {
|
|
kind = "warning"
|
|
}
|
|
authUser, _, _ := req.BasicAuth()
|
|
n := notification{
|
|
ReceivedAt: now.Format(time.RFC3339Nano), Kind: kind,
|
|
Level: q.Get("level"), ID: q.Get("id"), Flow: q.Get("flow"), Period: q.Get("period"), By: q.Get("by"),
|
|
Count: q.Get("count"), Limit: q.Get("limit"), Percent: q.Get("percent"),
|
|
Path: req.URL.Path, RawQuery: req.URL.RawQuery, RemoteAddr: req.RemoteAddr, AuthUser: authUser,
|
|
}
|
|
name, err := r.store(now, n)
|
|
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
if err != nil {
|
|
r.failed++
|
|
fmt.Fprintf(r.stderr, "could not store notification: %v\n", err)
|
|
// The daemon retries a 5xx, so this one is not lost.
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
return
|
|
}
|
|
r.counts[kind]++
|
|
fmt.Fprintf(r.stdout, "%s %s %s %s count=%s limit=%s -> %s\n", kind, cleanPart(n.Level), cleanPart(n.Flow), cleanPart(n.ID), cleanPart(n.Count), cleanPart(n.Limit), name)
|
|
w.WriteHeader(http.StatusOK)
|
|
}
|
|
|
|
// store writes n to a dotfile and links it to its final name, so a visible
|
|
// file is always complete and an existing one is never overwritten.
|
|
func (r *receiver) store(now time.Time, n notification) (string, error) {
|
|
data, err := json.MarshalIndent(n, "", " ")
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
tmp, err := os.CreateTemp(r.dir, ".tmp-*")
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer os.Remove(tmp.Name())
|
|
_, err = tmp.Write(append(data, '\n'))
|
|
if cerr := tmp.Close(); err == nil {
|
|
err = cerr
|
|
}
|
|
if err == nil {
|
|
err = os.Chmod(tmp.Name(), 0o640)
|
|
}
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
stamp := now.Format("20060102T150405.000000Z")
|
|
for {
|
|
name := fmt.Sprintf("%s-%06d-%s-%s-%s-%s.json", stamp, r.seq.Add(1), n.Kind, cleanPart(n.Level), cleanPart(n.Flow), cleanPart(n.ID))
|
|
err := os.Link(tmp.Name(), filepath.Join(r.dir, name))
|
|
if err == nil {
|
|
return name, nil
|
|
}
|
|
if !errors.Is(err, fs.ErrExist) {
|
|
return "", err
|
|
}
|
|
}
|
|
}
|
|
|
|
// cleanPart makes a request value safe for a file name and the terminal.
|
|
func cleanPart(s string) string {
|
|
if s == "" {
|
|
return "none"
|
|
}
|
|
if len(s) > maxNamePart {
|
|
s = s[:maxNamePart]
|
|
}
|
|
b := []byte(s)
|
|
for i, c := range b {
|
|
switch {
|
|
case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9', c == '@', c == '.', c == '_', c == '-':
|
|
default:
|
|
b[i] = '_'
|
|
}
|
|
}
|
|
return string(b)
|
|
}
|
|
|
|
func (r *receiver) totals() string {
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
return fmt.Sprintf("received limit=%d warning=%d, could not store %d", r.counts["limit"], r.counts["warning"], r.failed)
|
|
}
|
|
|
|
func runReceive(ctx context.Context, args []string, stdout, stderr io.Writer) int {
|
|
fs := flag.NewFlagSet("countersend receive", flag.ContinueOnError)
|
|
fs.SetOutput(stderr)
|
|
listen := fs.String("listen", "127.0.0.1:8099", "address the daemon's notify URLs point at")
|
|
dir := fs.String("dir", "./notifications", "directory for the notification files, created if missing")
|
|
if err := fs.Parse(args); err != nil {
|
|
return exitUsage
|
|
}
|
|
if fs.NArg() != 0 || *dir == "" {
|
|
fs.Usage()
|
|
return exitUsage
|
|
}
|
|
abs, err := filepath.Abs(*dir)
|
|
if err != nil {
|
|
fmt.Fprintln(stderr, err)
|
|
return exitFail
|
|
}
|
|
if err := checkWritable(abs); err != nil {
|
|
fmt.Fprintf(stderr, "cannot store notifications in %s: %v\n", abs, err)
|
|
return exitFail
|
|
}
|
|
ln, err := net.Listen("tcp", *listen)
|
|
if err != nil {
|
|
fmt.Fprintf(stderr, "cannot listen: %v\n", err)
|
|
return exitFail
|
|
}
|
|
rcv := newReceiver(abs, stdout, stderr)
|
|
srv := &http.Server{Handler: rcv, ReadHeaderTimeout: 5 * time.Second}
|
|
fmt.Fprintf(stdout, "listening on %s, storing notifications in %s\n", ln.Addr(), abs)
|
|
|
|
serveErr := make(chan error, 1)
|
|
go func() { serveErr <- srv.Serve(ln) }()
|
|
select {
|
|
case err := <-serveErr:
|
|
fmt.Fprintf(stderr, "server stopped: %v\n", err)
|
|
fmt.Fprintln(stdout, rcv.totals())
|
|
return exitFail
|
|
case <-ctx.Done():
|
|
}
|
|
shutdown, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
if err := srv.Shutdown(shutdown); err != nil {
|
|
fmt.Fprintf(stderr, "shutdown: %v\n", err)
|
|
}
|
|
fmt.Fprintln(stdout, rcv.totals())
|
|
return exitOK
|
|
}
|
|
|
|
func checkWritable(dir string) error {
|
|
if err := os.MkdirAll(dir, 0o750); err != nil {
|
|
return err
|
|
}
|
|
f, err := os.CreateTemp(dir, ".tmp-*")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
f.Close()
|
|
return os.Remove(f.Name())
|
|
}
|