Spaces:
Sleeping
Sleeping
PERDYPTO commited on
Upload 22 files
Browse files- .gitignore +5 -0
- Dockerfile +39 -0
- cmd/relayd/bank.go +89 -0
- cmd/relayd/main.go +255 -0
- cmd/relayd/sync.go +131 -0
- go.mod +3 -0
- internal/apierr/apierr.go +78 -0
- internal/bank/bank.go +394 -0
- internal/config/config.go +251 -0
- internal/core/core.go +643 -0
- internal/draw/draw.go +227 -0
- internal/hf/hf.go +611 -0
- internal/httpapi/handlers.go +446 -0
- internal/httpapi/metrics.go +78 -0
- internal/httpapi/server.go +244 -0
- internal/identity/identity.go +378 -0
- internal/limits/limits.go +184 -0
- internal/ratelog/ratelog.go +386 -0
- internal/reputation/reputation.go +116 -0
- internal/store/results.go +74 -0
- internal/store/store.go +461 -0
- internal/syncctl/syncctl.go +524 -0
.gitignore
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Never commit data to this Space. It is public; the dataset is not.
|
| 2 |
+
bank/
|
| 3 |
+
testdata/
|
| 4 |
+
*.env
|
| 5 |
+
.env*
|
Dockerfile
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# syntax=docker/dockerfile:1
|
| 2 |
+
|
| 3 |
+
# ---- build stage -----------------------------------------------------------
|
| 4 |
+
FROM golang:1.22-alpine AS build
|
| 5 |
+
WORKDIR /src
|
| 6 |
+
|
| 7 |
+
# Only stdlib is used, so there is nothing to download: builds work offline.
|
| 8 |
+
COPY go.mod ./
|
| 9 |
+
RUN go mod download
|
| 10 |
+
|
| 11 |
+
COPY . .
|
| 12 |
+
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
|
| 13 |
+
go build -trimpath -ldflags="-s -w -buildid=" -o /out/relayd ./cmd/relayd
|
| 14 |
+
|
| 15 |
+
# ---- runtime stage ---------------------------------------------------------
|
| 16 |
+
# alpine (not scratch) so we ship CA certificates for outbound HTTPS to the
|
| 17 |
+
# Hugging Face API, plus tzdata for correct UTC handling.
|
| 18 |
+
#
|
| 19 |
+
# /app/data and /app/rate hold the identity tree and the rate log. On a Hugging
|
| 20 |
+
# Face Space mount persistent storage at /app/data (and ideally /app/rate) or
|
| 21 |
+
# every restart starts from an empty bank of remembered identities.
|
| 22 |
+
FROM alpine:3.20
|
| 23 |
+
RUN apk add --no-cache ca-certificates tzdata \
|
| 24 |
+
&& addgroup -g 1000 relay \
|
| 25 |
+
&& adduser -D -u 1000 -G relay relay \
|
| 26 |
+
&& mkdir -p /app/data /app/bank /app/rate \
|
| 27 |
+
&& chown -R relay:relay /app
|
| 28 |
+
COPY --from=build /out/relayd /app/relayd
|
| 29 |
+
WORKDIR /app
|
| 30 |
+
USER 1000
|
| 31 |
+
ENV ADDR=:7860 \
|
| 32 |
+
BANK_DIR=/app/bank \
|
| 33 |
+
DATA_DIR=/app/data \
|
| 34 |
+
RATE_DIR=/app/rate \
|
| 35 |
+
TZ=UTC
|
| 36 |
+
EXPOSE 7860
|
| 37 |
+
HEALTHCHECK --interval=30s --timeout=3s --start-period=3s \
|
| 38 |
+
CMD ["/app/relayd", "-healthcheck"]
|
| 39 |
+
ENTRYPOINT ["/app/relayd"]
|
cmd/relayd/bank.go
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package main
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"fmt"
|
| 6 |
+
"log/slog"
|
| 7 |
+
"os"
|
| 8 |
+
"path/filepath"
|
| 9 |
+
"time"
|
| 10 |
+
|
| 11 |
+
"github.com/archnemix/archx-eval/relay/internal/config"
|
| 12 |
+
"github.com/archnemix/archx-eval/relay/internal/hf"
|
| 13 |
+
"github.com/archnemix/archx-eval/relay/internal/syncctl"
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
// bankPrefix is where the question bank lives inside the dataset.
|
| 17 |
+
//
|
| 18 |
+
// The bank is the answer key: it carries reference solutions and tests. It
|
| 19 |
+
// therefore lives ONLY in the private dataset owned by Archnemix, and is pulled
|
| 20 |
+
// into the Space's disk at boot. It is never published by this service (the
|
| 21 |
+
// sync controller ignores this prefix), so an upload made here always means
|
| 22 |
+
// "the operator changed the bank", never "the relay echoed it back".
|
| 23 |
+
const bankPrefix = "bank"
|
| 24 |
+
|
| 25 |
+
// restoreBank pulls the question bank from the private dataset into BANK_DIR.
|
| 26 |
+
//
|
| 27 |
+
// A Space's own repository is a public artefact and its disk is wiped on every
|
| 28 |
+
// restart, so the bank cannot live in either place. The dataset is the only
|
| 29 |
+
// home it has. If this fails the relay still starts and reports itself
|
| 30 |
+
// not-ready, which is strictly better than serving guesses.
|
| 31 |
+
func restoreBank(ctx context.Context, cfg config.Config, log *slog.Logger) error {
|
| 32 |
+
if !cfg.BankFromDataset || !cfg.HFEnabled {
|
| 33 |
+
log.Info("bank restore skipped",
|
| 34 |
+
"bank_from_dataset", cfg.BankFromDataset,
|
| 35 |
+
"hf_enabled", cfg.HFEnabled)
|
| 36 |
+
return nil
|
| 37 |
+
}
|
| 38 |
+
remote := newRemote(cfg)
|
| 39 |
+
if err := remote.(*hf.CommitSink).Ping(ctx); err != nil {
|
| 40 |
+
log.Error("dataset unreachable; the bank will be empty", "err", err)
|
| 41 |
+
return nil
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
started := time.Now()
|
| 45 |
+
n, err := syncctl.Restore(ctx, remote, bankPrefix, cfg.BankDir, 4)
|
| 46 |
+
if err != nil {
|
| 47 |
+
return fmt.Errorf("restore bank from %s: %w", bankPrefix, err)
|
| 48 |
+
}
|
| 49 |
+
if n == 0 {
|
| 50 |
+
log.Warn("the dataset holds no bank yet: publish bank/ to the dataset "+
|
| 51 |
+
"or the relay will report not-ready", "prefix", bankPrefix)
|
| 52 |
+
return nil
|
| 53 |
+
}
|
| 54 |
+
log.Info("bank restored from dataset",
|
| 55 |
+
"files", n,
|
| 56 |
+
"dir", cfg.BankDir,
|
| 57 |
+
"duration_s", int(time.Since(started)/time.Second))
|
| 58 |
+
return nil
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
// localBankPresent reports whether BANK_DIR already holds at least one JSONL
|
| 62 |
+
// shard, without paying the cost of a full validation pass.
|
| 63 |
+
func localBankPresent(dir string) bool {
|
| 64 |
+
found := false
|
| 65 |
+
_ = filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error {
|
| 66 |
+
if err != nil {
|
| 67 |
+
return nil
|
| 68 |
+
}
|
| 69 |
+
if !d.IsDir() && filepath.Ext(path) == ".jsonl" {
|
| 70 |
+
found = true
|
| 71 |
+
return os.ErrExist
|
| 72 |
+
}
|
| 73 |
+
return nil
|
| 74 |
+
})
|
| 75 |
+
return found
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
// ensureBankDir makes BANK_DIR writable before restore, because a Docker Space
|
| 79 |
+
// may give us an image-owned directory the runtime user cannot write to.
|
| 80 |
+
func ensureBankDir(dir string) error {
|
| 81 |
+
if err := os.MkdirAll(dir, 0o750); err != nil {
|
| 82 |
+
return fmt.Errorf("create bank dir %s: %w", dir, err)
|
| 83 |
+
}
|
| 84 |
+
probe := filepath.Join(dir, ".write-probe")
|
| 85 |
+
if err := os.WriteFile(probe, []byte("ok"), 0o640); err != nil {
|
| 86 |
+
return fmt.Errorf("bank dir %s is not writable by uid %d: %w", dir, os.Getuid(), err)
|
| 87 |
+
}
|
| 88 |
+
return os.Remove(probe)
|
| 89 |
+
}
|
cmd/relayd/main.go
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
| 1 |
+
// Command relayd is the Archx-Eval relay: the API layer that sits between a
|
| 2 |
+
// user's front-end runner and the private evaluation bank.
|
| 3 |
+
package main
|
| 4 |
+
|
| 5 |
+
import (
|
| 6 |
+
"context"
|
| 7 |
+
"errors"
|
| 8 |
+
"flag"
|
| 9 |
+
"fmt"
|
| 10 |
+
"log/slog"
|
| 11 |
+
"net/http"
|
| 12 |
+
"os"
|
| 13 |
+
"os/signal"
|
| 14 |
+
"strings"
|
| 15 |
+
"syscall"
|
| 16 |
+
"time"
|
| 17 |
+
|
| 18 |
+
"github.com/archnemix/archx-eval/relay/internal/bank"
|
| 19 |
+
"github.com/archnemix/archx-eval/relay/internal/config"
|
| 20 |
+
"github.com/archnemix/archx-eval/relay/internal/core"
|
| 21 |
+
"github.com/archnemix/archx-eval/relay/internal/hf"
|
| 22 |
+
"github.com/archnemix/archx-eval/relay/internal/httpapi"
|
| 23 |
+
"github.com/archnemix/archx-eval/relay/internal/ratelog"
|
| 24 |
+
"github.com/archnemix/archx-eval/relay/internal/reputation"
|
| 25 |
+
"github.com/archnemix/archx-eval/relay/internal/store"
|
| 26 |
+
"github.com/archnemix/archx-eval/relay/internal/syncctl"
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
func main() {
|
| 30 |
+
var (
|
| 31 |
+
healthcheck = flag.Bool("healthcheck", false, "probe the local /health endpoint and exit")
|
| 32 |
+
printCfg = flag.Bool("print-config", false, "print the resolved configuration and exit")
|
| 33 |
+
sync = flag.Bool("sync", false, "publish the local data tree to the private dataset and exit")
|
| 34 |
+
dryRun = flag.Bool("dry-run", false, "with -sync, write to SYNC_OUT_DIR instead of the dataset")
|
| 35 |
+
)
|
| 36 |
+
flag.Parse()
|
| 37 |
+
|
| 38 |
+
if err := run(*healthcheck, *printCfg, *sync, *dryRun); err != nil {
|
| 39 |
+
fmt.Fprintln(os.Stderr, "relayd:", err)
|
| 40 |
+
os.Exit(1)
|
| 41 |
+
}
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
func run(healthcheck, printCfg, doSync, dryRun bool) error {
|
| 45 |
+
cfg := config.Load()
|
| 46 |
+
|
| 47 |
+
if printCfg {
|
| 48 |
+
fmt.Printf("addr=%s\nbank_dir=%s\ndata_dir=%s\ndraw_max=%d\nwindow=%s\nstale_after=%d\nhf_enabled=%v\nsalt_default=%v\n",
|
| 49 |
+
cfg.Addr, cfg.BankDir, cfg.DataDir, cfg.DrawMax, cfg.Window, cfg.StaleAfterUses, cfg.HFEnabled, cfg.SaltIsDefault())
|
| 50 |
+
return nil
|
| 51 |
+
}
|
| 52 |
+
if healthcheck {
|
| 53 |
+
return probeHealth(cfg)
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
log := newLogger(cfg.LogFormat)
|
| 57 |
+
if cfg.SaltIsDefault() {
|
| 58 |
+
log.Warn("RELAY_SALT is unset: using the insecure development salt. Every marker hash will change once a real salt is configured.")
|
| 59 |
+
}
|
| 60 |
+
if !cfg.HFEnabled {
|
| 61 |
+
log.Warn("HF_DATA_TOKEN is unset: the dataset is neither read nor written")
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
// Pull our own state back from the dataset before opening the store, so the
|
| 65 |
+
// process resumes with its memory of known callers intact.
|
| 66 |
+
bootCtx, bootCancel := context.WithTimeout(context.Background(), 90*time.Second)
|
| 67 |
+
if err := restoreState(bootCtx, cfg, log); err != nil {
|
| 68 |
+
log.Error("restore failed; continuing with local state", "err", err)
|
| 69 |
+
}
|
| 70 |
+
// The bank is the answer key: it lives in the private dataset and nowhere
|
| 71 |
+
// else. Peek at the local directory first so an operator-provided volume
|
| 72 |
+
// wins over the dataset copy, then fetch only if it is empty.
|
| 73 |
+
if !localBankPresent(cfg.BankDir) {
|
| 74 |
+
if err := ensureBankDir(cfg.BankDir); err != nil {
|
| 75 |
+
log.Error("bank directory unusable", "err", err)
|
| 76 |
+
} else if err := restoreBank(bootCtx, cfg, log); err != nil {
|
| 77 |
+
log.Error("bank restore failed; /health will report not-ready", "err", err)
|
| 78 |
+
}
|
| 79 |
+
} else {
|
| 80 |
+
log.Info("local bank present; dataset bank not fetched", "dir", cfg.BankDir)
|
| 81 |
+
}
|
| 82 |
+
bootCancel()
|
| 83 |
+
|
| 84 |
+
st, err := store.Open(cfg.DataDir)
|
| 85 |
+
if err != nil {
|
| 86 |
+
return err
|
| 87 |
+
}
|
| 88 |
+
bm, err := bank.Load(cfg.BankDir, cfg.StaleAfterUses)
|
| 89 |
+
if err != nil {
|
| 90 |
+
return err
|
| 91 |
+
}
|
| 92 |
+
rep, err := reputation.Load(cfg.ReputationFile)
|
| 93 |
+
if err != nil {
|
| 94 |
+
return err
|
| 95 |
+
}
|
| 96 |
+
if bm.Size() == 0 {
|
| 97 |
+
log.Warn("the bank is empty: /health will report not-ready until examples are published")
|
| 98 |
+
} else {
|
| 99 |
+
log.Info("bank loaded", "examples", bm.Size(), "categories", len(bm.Categories()))
|
| 100 |
+
}
|
| 101 |
+
if rep.Loaded() {
|
| 102 |
+
log.Info("reputation table loaded", "ranges", rep.Size())
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
// The rate log retention must exceed the longest window we evaluate, with
|
| 106 |
+
// headroom, or a restart would silently forget evidence of a flood.
|
| 107 |
+
retention := cfg.SpamBan
|
| 108 |
+
if cfg.GlobalWindow > retention {
|
| 109 |
+
retention = cfg.GlobalWindow
|
| 110 |
+
}
|
| 111 |
+
retention *= 2
|
| 112 |
+
rates, err := ratelog.Open(cfg.RateDir, retention)
|
| 113 |
+
if err != nil {
|
| 114 |
+
return err
|
| 115 |
+
}
|
| 116 |
+
defer rates.Close()
|
| 117 |
+
|
| 118 |
+
svc := core.New(cfg, st, bm, rep, rates)
|
| 119 |
+
log.Info("rate log ready", "keys", rates.Keys(), "retention", retention.String())
|
| 120 |
+
|
| 121 |
+
// The dataset is a git repo: writes are sequential, so every state change
|
| 122 |
+
// goes through one batching controller instead of being committed per
|
| 123 |
+
// request. Enqueue never blocks a request.
|
| 124 |
+
var controller *syncctl.Controller
|
| 125 |
+
if cfg.HFEnabled {
|
| 126 |
+
remote := newRemote(cfg)
|
| 127 |
+
controller = syncctl.New(syncctl.Config{
|
| 128 |
+
Interval: cfg.SyncInterval,
|
| 129 |
+
MaxFiles: cfg.SyncMaxFiles,
|
| 130 |
+
MaxQueued: 20000,
|
| 131 |
+
}, remote, log)
|
| 132 |
+
svc.WithSync(controller)
|
| 133 |
+
syncCtx, syncCancel := context.WithCancel(context.Background())
|
| 134 |
+
defer syncCancel()
|
| 135 |
+
go controller.Run(syncCtx)
|
| 136 |
+
defer controller.Stop()
|
| 137 |
+
log.Info("dataset sync enabled", "interval", cfg.SyncInterval.String())
|
| 138 |
+
} else {
|
| 139 |
+
log.Warn("HF_DATA_TOKEN is unset: state stays local and is never published")
|
| 140 |
+
}
|
| 141 |
+
var _ hf.Remote
|
| 142 |
+
|
| 143 |
+
if doSync {
|
| 144 |
+
return syncToDataset(cfg, svc, log, dryRun)
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
srv := httpapi.New(cfg, svc, log, os.Getenv("ADMIN_TOKEN"))
|
| 148 |
+
httpServer := &http.Server{
|
| 149 |
+
Addr: cfg.Addr,
|
| 150 |
+
Handler: srv,
|
| 151 |
+
ReadHeaderTimeout: 5 * time.Second,
|
| 152 |
+
ReadTimeout: 15 * time.Second,
|
| 153 |
+
WriteTimeout: 30 * time.Second,
|
| 154 |
+
IdleTimeout: 60 * time.Second,
|
| 155 |
+
MaxHeaderBytes: 16 << 10,
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
| 159 |
+
defer stop()
|
| 160 |
+
|
| 161 |
+
// Housekeeping: expire raw identity rows and persist counters.
|
| 162 |
+
go housekeep(ctx, svc, cfg, log)
|
| 163 |
+
|
| 164 |
+
errCh := make(chan error, 1)
|
| 165 |
+
go func() {
|
| 166 |
+
log.Info("listening", "addr", cfg.Addr, "version", core.Version)
|
| 167 |
+
if err := httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
| 168 |
+
errCh <- err
|
| 169 |
+
}
|
| 170 |
+
}()
|
| 171 |
+
|
| 172 |
+
select {
|
| 173 |
+
case <-ctx.Done():
|
| 174 |
+
log.Info("shutting down")
|
| 175 |
+
case err := <-errCh:
|
| 176 |
+
log.Error("server error", "err", err)
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
| 180 |
+
defer cancel()
|
| 181 |
+
_ = httpServer.Shutdown(shutdownCtx)
|
| 182 |
+
if err := svc.Flush(); err != nil {
|
| 183 |
+
log.Error("flush failed", "err", err)
|
| 184 |
+
}
|
| 185 |
+
if err := svc.FlushRates(); err != nil {
|
| 186 |
+
log.Error("rate flush failed", "err", err)
|
| 187 |
+
}
|
| 188 |
+
return nil
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
func housekeep(ctx context.Context, svc *core.Service, cfg config.Config, log *slog.Logger) {
|
| 192 |
+
// Bans still expire, so the pruner stays; there is no personal data left to
|
| 193 |
+
// delete, which is the point.
|
| 194 |
+
pruneEvery := 6 * time.Hour
|
| 195 |
+
pruneTicker := time.NewTicker(pruneEvery)
|
| 196 |
+
flushTicker := time.NewTicker(cfg.FlushInterval)
|
| 197 |
+
rateTicker := time.NewTicker(10 * time.Minute)
|
| 198 |
+
defer pruneTicker.Stop()
|
| 199 |
+
defer flushTicker.Stop()
|
| 200 |
+
defer rateTicker.Stop()
|
| 201 |
+
|
| 202 |
+
for {
|
| 203 |
+
select {
|
| 204 |
+
case <-ctx.Done():
|
| 205 |
+
return
|
| 206 |
+
case <-pruneTicker.C:
|
| 207 |
+
n, err := svc.Prune()
|
| 208 |
+
if err != nil {
|
| 209 |
+
log.Error("prune failed", "err", err)
|
| 210 |
+
continue
|
| 211 |
+
}
|
| 212 |
+
if n > 0 {
|
| 213 |
+
log.Info("cleared expired bans", "count", n)
|
| 214 |
+
}
|
| 215 |
+
case <-flushTicker.C:
|
| 216 |
+
if err := svc.Flush(); err != nil {
|
| 217 |
+
log.Error("flush failed", "err", err)
|
| 218 |
+
}
|
| 219 |
+
case <-rateTicker.C:
|
| 220 |
+
n, err := svc.Maintain(time.Now().UTC())
|
| 221 |
+
if err != nil {
|
| 222 |
+
log.Error("rate log maintenance failed", "err", err)
|
| 223 |
+
continue
|
| 224 |
+
}
|
| 225 |
+
if n > 0 {
|
| 226 |
+
log.Info("rate log compacted", "files", n)
|
| 227 |
+
}
|
| 228 |
+
}
|
| 229 |
+
}
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
func probeHealth(cfg config.Config) error {
|
| 233 |
+
addr := cfg.Addr
|
| 234 |
+
if strings.HasPrefix(addr, ":") {
|
| 235 |
+
addr = "127.0.0.1" + addr
|
| 236 |
+
}
|
| 237 |
+
client := &http.Client{Timeout: 2 * time.Second}
|
| 238 |
+
resp, err := client.Get("http://" + addr + "/health")
|
| 239 |
+
if err != nil {
|
| 240 |
+
return err
|
| 241 |
+
}
|
| 242 |
+
defer resp.Body.Close()
|
| 243 |
+
if resp.StatusCode >= 300 {
|
| 244 |
+
return fmt.Errorf("health probe returned %s", resp.Status)
|
| 245 |
+
}
|
| 246 |
+
return nil
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
func newLogger(format string) *slog.Logger {
|
| 250 |
+
opts := &slog.HandlerOptions{Level: slog.LevelInfo}
|
| 251 |
+
if format == "text" {
|
| 252 |
+
return slog.New(slog.NewTextHandler(os.Stdout, opts))
|
| 253 |
+
}
|
| 254 |
+
return slog.New(slog.NewJSONHandler(os.Stdout, opts))
|
| 255 |
+
}
|
cmd/relayd/sync.go
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package main
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"fmt"
|
| 6 |
+
"log/slog"
|
| 7 |
+
"os"
|
| 8 |
+
"path/filepath"
|
| 9 |
+
"time"
|
| 10 |
+
|
| 11 |
+
"github.com/archnemix/archx-eval/relay/internal/config"
|
| 12 |
+
"github.com/archnemix/archx-eval/relay/internal/core"
|
| 13 |
+
"github.com/archnemix/archx-eval/relay/internal/hf"
|
| 14 |
+
"github.com/archnemix/archx-eval/relay/internal/syncctl"
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
// newRemote builds the dataset client described by the configuration.
|
| 18 |
+
func newRemote(cfg config.Config) hf.Remote {
|
| 19 |
+
return hf.NewCommitSink(cfg.HFRepo, cfg.HFToken, cfg.HFBaseURL, "main")
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
// restoreState pulls the relay's own subtree back from the dataset before the
|
| 23 |
+
// service starts. Without this a Space that has been asleep for an hour comes
|
| 24 |
+
// back with no memory of who it has already served.
|
| 25 |
+
//
|
| 26 |
+
// Only the relay's own prefixes are restored. The question bank is never
|
| 27 |
+
// published here, so it is never restored from here either.
|
| 28 |
+
func restoreState(ctx context.Context, cfg config.Config, log *slog.Logger) error {
|
| 29 |
+
if !cfg.RestoreOnBoot || !cfg.HFEnabled {
|
| 30 |
+
log.Info("dataset restore skipped", "enabled", cfg.HFEnabled, "restore_on_boot", cfg.RestoreOnBoot)
|
| 31 |
+
return nil
|
| 32 |
+
}
|
| 33 |
+
remote := newRemote(cfg)
|
| 34 |
+
if err := remote.(*hf.CommitSink).Ping(ctx); err != nil {
|
| 35 |
+
// A restore failure must not stop the relay from serving; it degrades
|
| 36 |
+
// to "no memory of previous callers", which the logs make obvious.
|
| 37 |
+
log.Error("dataset unreachable; starting with empty state", "err", err)
|
| 38 |
+
return nil
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
total := 0
|
| 42 |
+
for _, prefix := range cfg.RestorePrefixes {
|
| 43 |
+
dest := filepath.Join(cfg.DataDir, syncctl.SanitizePath(prefix))
|
| 44 |
+
n, err := syncctl.Restore(ctx, remote, prefix, cfg.DataDir, 8)
|
| 45 |
+
if err != nil {
|
| 46 |
+
log.Error("restore failed for prefix", "prefix", prefix, "dest", dest, "err", err)
|
| 47 |
+
continue
|
| 48 |
+
}
|
| 49 |
+
total += n
|
| 50 |
+
log.Info("restored prefix", "prefix", prefix, "files", n)
|
| 51 |
+
}
|
| 52 |
+
log.Info("dataset restore complete", "files", total)
|
| 53 |
+
return nil
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
// syncToDataset publishes the current state now and exits. Used by -sync.
|
| 57 |
+
//
|
| 58 |
+
// In production the relay publishes continuously through the controller; this
|
| 59 |
+
// one-shot path exists for CI, for a manual push, and for the dry-run mirror
|
| 60 |
+
// that keeps everything inside the repository.
|
| 61 |
+
func syncToDataset(cfg config.Config, svc *core.Service, log *slog.Logger, dryRun bool) error {
|
| 62 |
+
outDir := os.Getenv("SYNC_OUT_DIR")
|
| 63 |
+
if outDir == "" {
|
| 64 |
+
outDir = filepath.Join(os.TempDir(), "archx-sync")
|
| 65 |
+
}
|
| 66 |
+
if err := os.RemoveAll(outDir); err != nil {
|
| 67 |
+
return err
|
| 68 |
+
}
|
| 69 |
+
written, err := svc.ExportSnapshot(outDir)
|
| 70 |
+
if err != nil {
|
| 71 |
+
return err
|
| 72 |
+
}
|
| 73 |
+
log.Info("snapshot exported", "files", len(written), "dir", outDir)
|
| 74 |
+
|
| 75 |
+
files, err := hf.Collect(outDir, 0)
|
| 76 |
+
if err != nil {
|
| 77 |
+
return err
|
| 78 |
+
}
|
| 79 |
+
if len(files) == 0 {
|
| 80 |
+
log.Info("nothing to publish")
|
| 81 |
+
return nil
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
var remote hf.Remote
|
| 85 |
+
switch {
|
| 86 |
+
case dryRun:
|
| 87 |
+
target := os.Getenv("SYNC_MIRROR_DIR")
|
| 88 |
+
if target == "" {
|
| 89 |
+
target = filepath.Join("ci", "outputs", "dataset-mirror")
|
| 90 |
+
}
|
| 91 |
+
log.Info("dry run: mirroring into the repository", "target", target)
|
| 92 |
+
remote = &hf.DirSink{Root: target}
|
| 93 |
+
case cfg.HFEnabled:
|
| 94 |
+
remote = newRemote(cfg)
|
| 95 |
+
default:
|
| 96 |
+
log.Warn("HF_DATA_TOKEN is unset: snapshot stays local", "dir", outDir)
|
| 97 |
+
return nil
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
|
| 101 |
+
defer cancel()
|
| 102 |
+
|
| 103 |
+
sc := syncctl.New(syncctl.Config{
|
| 104 |
+
Interval: cfg.SyncInterval,
|
| 105 |
+
MaxFiles: cfg.SyncMaxFiles,
|
| 106 |
+
MaxQueued: 1 << 20,
|
| 107 |
+
}, remote, log)
|
| 108 |
+
for _, f := range files {
|
| 109 |
+
sc.EnqueueFile(f)
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
started := time.Now()
|
| 113 |
+
if err := sc.FlushNow(ctx); err != nil {
|
| 114 |
+
stats := sc.Stats()
|
| 115 |
+
return fmt.Errorf("publish failed: %w (queued=%d published=%d skipped=%d)",
|
| 116 |
+
err, stats.Queued, stats.Published, stats.Skipped)
|
| 117 |
+
}
|
| 118 |
+
stats := sc.Stats()
|
| 119 |
+
log.Info("published",
|
| 120 |
+
"files", len(files),
|
| 121 |
+
"published", stats.Published,
|
| 122 |
+
"skipped_unchanged", stats.Skipped,
|
| 123 |
+
"commits", stats.Commits,
|
| 124 |
+
"duration_s", int(time.Since(started)/time.Second),
|
| 125 |
+
"dry_run", dryRun,
|
| 126 |
+
)
|
| 127 |
+
if stats.Queued > 0 {
|
| 128 |
+
return fmt.Errorf("%d file(s) still queued after flush", stats.Queued)
|
| 129 |
+
}
|
| 130 |
+
return nil
|
| 131 |
+
}
|
go.mod
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
module github.com/archnemix/archx-eval/relay
|
| 2 |
+
|
| 3 |
+
go 1.22
|
internal/apierr/apierr.go
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Package apierr defines the single error type the HTTP layer knows how to
|
| 2 |
+
// render. Business logic returns *apierr.Error directly so that status codes,
|
| 3 |
+
// machine-readable codes and Retry-After values stay out of the handlers.
|
| 4 |
+
package apierr
|
| 5 |
+
|
| 6 |
+
import (
|
| 7 |
+
"errors"
|
| 8 |
+
"fmt"
|
| 9 |
+
"net/http"
|
| 10 |
+
"time"
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
// Error is a transport-agnostic API failure.
|
| 14 |
+
type Error struct {
|
| 15 |
+
Status int
|
| 16 |
+
Code string
|
| 17 |
+
Message string
|
| 18 |
+
RetryAfter time.Duration
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
func (e *Error) Error() string { return fmt.Sprintf("%s: %s", e.Code, e.Message) }
|
| 22 |
+
|
| 23 |
+
// BadRequest reports a malformed or invalid payload.
|
| 24 |
+
func BadRequest(msg string) *Error {
|
| 25 |
+
return &Error{Status: http.StatusBadRequest, Code: "BAD_REQUEST", Message: msg}
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
// InvalidIdentity reports unusable device identity data.
|
| 29 |
+
func InvalidIdentity(msg string) *Error {
|
| 30 |
+
return &Error{Status: http.StatusBadRequest, Code: "IDENTITY_INVALID", Message: msg}
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
// Forbidden reports a policy refusal with no retry guidance (e.g. known VPN).
|
| 34 |
+
func Forbidden(code, msg string) *Error {
|
| 35 |
+
return &Error{Status: http.StatusForbidden, Code: code, Message: msg}
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
// Limited reports a rate/ban refusal with a retry hint.
|
| 39 |
+
func Limited(code, msg string, retry time.Duration) *Error {
|
| 40 |
+
if retry < time.Second {
|
| 41 |
+
retry = time.Second
|
| 42 |
+
}
|
| 43 |
+
return &Error{
|
| 44 |
+
Status: http.StatusTooManyRequests,
|
| 45 |
+
Code: code,
|
| 46 |
+
Message: msg,
|
| 47 |
+
RetryAfter: retry,
|
| 48 |
+
}
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
// Conflict reports a state clash that is not a rate limit.
|
| 52 |
+
func Conflict(code, msg string) *Error {
|
| 53 |
+
return &Error{Status: http.StatusConflict, Code: code, Message: msg}
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
// NotFound reports an unknown resource.
|
| 57 |
+
func NotFound(msg string) *Error {
|
| 58 |
+
return &Error{Status: http.StatusNotFound, Code: "NOT_FOUND", Message: msg}
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
// Internal reports an unexpected server-side failure.
|
| 62 |
+
func Internal(msg string) *Error {
|
| 63 |
+
return &Error{Status: http.StatusInternalServerError, Code: "INTERNAL", Message: msg}
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
// Unavailable reports a dependency we could not reach.
|
| 67 |
+
func Unavailable(msg string) *Error {
|
| 68 |
+
return &Error{Status: http.StatusServiceUnavailable, Code: "DEPENDENCY_UNAVAILABLE", Message: msg}
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
// As extracts an *Error from err, if there is one.
|
| 72 |
+
func As(err error) (*Error, bool) {
|
| 73 |
+
var e *Error
|
| 74 |
+
if errors.As(err, &e) {
|
| 75 |
+
return e, true
|
| 76 |
+
}
|
| 77 |
+
return nil, false
|
| 78 |
+
}
|
internal/bank/bank.go
ADDED
|
@@ -0,0 +1,394 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Package bank loads and serves the evaluation question bank.
|
| 2 |
+
//
|
| 3 |
+
// On-disk shape (BANK_DIR), category first, then difficulty:
|
| 4 |
+
//
|
| 5 |
+
// BANK_DIR/python/easy.jsonl
|
| 6 |
+
// BANK_DIR/python/medium.jsonl
|
| 7 |
+
// BANK_DIR/python/hard.jsonl
|
| 8 |
+
// BANK_DIR/logic/easy.jsonl
|
| 9 |
+
//
|
| 10 |
+
// Each line is one JSON object. The loader validates the file layout against
|
| 11 |
+
// the row contents, so a misfiled example fails loudly instead of quietly
|
| 12 |
+
// polluting a category.
|
| 13 |
+
package bank
|
| 14 |
+
|
| 15 |
+
import (
|
| 16 |
+
"bufio"
|
| 17 |
+
"encoding/json"
|
| 18 |
+
"errors"
|
| 19 |
+
"fmt"
|
| 20 |
+
"os"
|
| 21 |
+
"path/filepath"
|
| 22 |
+
"sort"
|
| 23 |
+
"strings"
|
| 24 |
+
"sync"
|
| 25 |
+
"time"
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
// Difficulties in ascending order.
|
| 29 |
+
var Difficulties = []string{"easy", "medium", "hard"}
|
| 30 |
+
|
| 31 |
+
// Kind values.
|
| 32 |
+
const (
|
| 33 |
+
KindCode = "code"
|
| 34 |
+
KindQA = "qa"
|
| 35 |
+
KindLogic = "logic"
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
// Example is one banked question.
|
| 39 |
+
type Example struct {
|
| 40 |
+
ID string `json:"id"`
|
| 41 |
+
Category string `json:"category"`
|
| 42 |
+
Difficulty string `json:"difficulty"`
|
| 43 |
+
Kind string `json:"kind"`
|
| 44 |
+
|
| 45 |
+
Prompt string `json:"prompt"`
|
| 46 |
+
Context string `json:"context,omitempty"`
|
| 47 |
+
|
| 48 |
+
// Code examples
|
| 49 |
+
Language string `json:"language,omitempty"`
|
| 50 |
+
Entrypoint string `json:"entrypoint,omitempty"`
|
| 51 |
+
Starter string `json:"starter_code,omitempty"`
|
| 52 |
+
Solution string `json:"reference_solution,omitempty"`
|
| 53 |
+
Tests []string `json:"tests,omitempty"`
|
| 54 |
+
|
| 55 |
+
// Non-code examples
|
| 56 |
+
Answer string `json:"expected_answer,omitempty"`
|
| 57 |
+
Rubric []string `json:"rubric,omitempty"`
|
| 58 |
+
Explanation string `json:"explanation,omitempty"`
|
| 59 |
+
|
| 60 |
+
// Provenance. GeneratedAt/VerifiedBy matter because the whole promise of
|
| 61 |
+
// this bank is that a human checked the facts, not that a model guessed.
|
| 62 |
+
Version int `json:"version"`
|
| 63 |
+
GeneratedAt time.Time `json:"generated_at,omitempty"`
|
| 64 |
+
VerifiedAt time.Time `json:"verified_at,omitempty"`
|
| 65 |
+
VerifiedBy string `json:"verified_by,omitempty"`
|
| 66 |
+
Source string `json:"source,omitempty"`
|
| 67 |
+
|
| 68 |
+
Tags []string `json:"tags,omitempty"`
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
// Validate enforces the invariants every banked example must satisfy.
|
| 72 |
+
func (e *Example) Validate() error {
|
| 73 |
+
if e.ID == "" {
|
| 74 |
+
return errors.New("missing id")
|
| 75 |
+
}
|
| 76 |
+
if e.Category == "" {
|
| 77 |
+
return fmt.Errorf("%s: missing category", e.ID)
|
| 78 |
+
}
|
| 79 |
+
if !validDifficulty(e.Difficulty) {
|
| 80 |
+
return fmt.Errorf("%s: bad difficulty %q", e.ID, e.Difficulty)
|
| 81 |
+
}
|
| 82 |
+
if strings.TrimSpace(e.Prompt) == "" {
|
| 83 |
+
return fmt.Errorf("%s: empty prompt", e.ID)
|
| 84 |
+
}
|
| 85 |
+
switch e.Kind {
|
| 86 |
+
case KindCode:
|
| 87 |
+
if e.Language == "" {
|
| 88 |
+
return fmt.Errorf("%s: code example without language", e.ID)
|
| 89 |
+
}
|
| 90 |
+
if e.Solution == "" {
|
| 91 |
+
return fmt.Errorf("%s: code example without reference solution", e.ID)
|
| 92 |
+
}
|
| 93 |
+
if len(e.Tests) == 0 {
|
| 94 |
+
return fmt.Errorf("%s: code example without tests", e.ID)
|
| 95 |
+
}
|
| 96 |
+
case KindQA, KindLogic:
|
| 97 |
+
if e.Answer == "" {
|
| 98 |
+
return fmt.Errorf("%s: %s example without expected answer", e.ID, e.Kind)
|
| 99 |
+
}
|
| 100 |
+
case "":
|
| 101 |
+
return fmt.Errorf("%s: missing kind", e.ID)
|
| 102 |
+
default:
|
| 103 |
+
return fmt.Errorf("%s: unknown kind %q", e.ID, e.Kind)
|
| 104 |
+
}
|
| 105 |
+
return nil
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
func validDifficulty(d string) bool {
|
| 109 |
+
for _, v := range Difficulties {
|
| 110 |
+
if d == v {
|
| 111 |
+
return true
|
| 112 |
+
}
|
| 113 |
+
}
|
| 114 |
+
return false
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
// Usage counts how often an example has been handed out.
|
| 118 |
+
type Usage struct {
|
| 119 |
+
Count int `json:"count"`
|
| 120 |
+
LastUsed time.Time `json:"last_used,omitempty"`
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
// Manager owns the in-memory bank and the usage counters.
|
| 124 |
+
type Manager struct {
|
| 125 |
+
mu sync.RWMutex
|
| 126 |
+
dir string
|
| 127 |
+
usagePath string
|
| 128 |
+
byID map[string]*Example
|
| 129 |
+
byCategory map[string][]*Example
|
| 130 |
+
usage map[string]Usage
|
| 131 |
+
staleAfter int
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
// Load reads every category/difficulty file under dir.
|
| 135 |
+
func Load(dir string, staleAfter int) (*Manager, error) {
|
| 136 |
+
if staleAfter <= 0 {
|
| 137 |
+
staleAfter = 3
|
| 138 |
+
}
|
| 139 |
+
m := &Manager{
|
| 140 |
+
dir: dir,
|
| 141 |
+
usagePath: filepath.Join(dir, "usage.json"),
|
| 142 |
+
byID: map[string]*Example{},
|
| 143 |
+
byCategory: map[string][]*Example{},
|
| 144 |
+
usage: map[string]Usage{},
|
| 145 |
+
staleAfter: staleAfter,
|
| 146 |
+
}
|
| 147 |
+
if err := m.scan(); err != nil {
|
| 148 |
+
return nil, err
|
| 149 |
+
}
|
| 150 |
+
if err := m.loadUsage(); err != nil {
|
| 151 |
+
return nil, err
|
| 152 |
+
}
|
| 153 |
+
return m, nil
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
func (m *Manager) scan() error {
|
| 157 |
+
entries, err := os.ReadDir(m.dir)
|
| 158 |
+
if errors.Is(err, os.ErrNotExist) {
|
| 159 |
+
// An empty bank is legal: the relay serves 503 until data lands.
|
| 160 |
+
return nil
|
| 161 |
+
}
|
| 162 |
+
if err != nil {
|
| 163 |
+
return fmt.Errorf("bank: read dir: %w", err)
|
| 164 |
+
}
|
| 165 |
+
for _, cat := range entries {
|
| 166 |
+
if !cat.IsDir() || strings.HasPrefix(cat.Name(), ".") {
|
| 167 |
+
continue
|
| 168 |
+
}
|
| 169 |
+
category := cat.Name()
|
| 170 |
+
for _, diff := range Difficulties {
|
| 171 |
+
path := filepath.Join(m.dir, category, diff+".jsonl")
|
| 172 |
+
if err := m.loadFile(path, category, diff); err != nil {
|
| 173 |
+
return err
|
| 174 |
+
}
|
| 175 |
+
}
|
| 176 |
+
}
|
| 177 |
+
return nil
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
func (m *Manager) loadFile(path, category, difficulty string) error {
|
| 181 |
+
f, err := os.Open(path)
|
| 182 |
+
if errors.Is(err, os.ErrNotExist) {
|
| 183 |
+
return nil
|
| 184 |
+
}
|
| 185 |
+
if err != nil {
|
| 186 |
+
return fmt.Errorf("bank: open %s: %w", path, err)
|
| 187 |
+
}
|
| 188 |
+
defer f.Close()
|
| 189 |
+
|
| 190 |
+
sc := bufio.NewScanner(f)
|
| 191 |
+
sc.Buffer(make([]byte, 0, 1<<20), 8<<20)
|
| 192 |
+
line := 0
|
| 193 |
+
for sc.Scan() {
|
| 194 |
+
line++
|
| 195 |
+
raw := strings.TrimSpace(sc.Text())
|
| 196 |
+
if raw == "" || strings.HasPrefix(raw, "//") {
|
| 197 |
+
continue
|
| 198 |
+
}
|
| 199 |
+
var ex Example
|
| 200 |
+
if err := json.Unmarshal([]byte(raw), &ex); err != nil {
|
| 201 |
+
return fmt.Errorf("bank: %s:%d: %w", path, line, err)
|
| 202 |
+
}
|
| 203 |
+
// Path is the source of truth for placement; mismatches are bugs.
|
| 204 |
+
if ex.Category != category {
|
| 205 |
+
return fmt.Errorf("bank: %s:%d: category %q does not match directory %q", path, line, ex.Category, category)
|
| 206 |
+
}
|
| 207 |
+
if ex.Difficulty != difficulty {
|
| 208 |
+
return fmt.Errorf("bank: %s:%d: difficulty %q does not match file %q", path, line, ex.Difficulty, difficulty)
|
| 209 |
+
}
|
| 210 |
+
if err := ex.Validate(); err != nil {
|
| 211 |
+
return fmt.Errorf("bank: %s:%d: %w", path, line, err)
|
| 212 |
+
}
|
| 213 |
+
if _, dup := m.byID[ex.ID]; dup {
|
| 214 |
+
return fmt.Errorf("bank: %s:%d: duplicate id %q", path, line, ex.ID)
|
| 215 |
+
}
|
| 216 |
+
clone := ex
|
| 217 |
+
if clone.Version == 0 {
|
| 218 |
+
clone.Version = 1
|
| 219 |
+
}
|
| 220 |
+
m.byID[clone.ID] = &clone
|
| 221 |
+
m.byCategory[category] = append(m.byCategory[category], &clone)
|
| 222 |
+
}
|
| 223 |
+
return sc.Err()
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
func (m *Manager) loadUsage() error {
|
| 227 |
+
buf, err := os.ReadFile(m.usagePath)
|
| 228 |
+
if errors.Is(err, os.ErrNotExist) {
|
| 229 |
+
return nil
|
| 230 |
+
}
|
| 231 |
+
if err != nil {
|
| 232 |
+
return fmt.Errorf("bank: read usage: %w", err)
|
| 233 |
+
}
|
| 234 |
+
var wrapper struct {
|
| 235 |
+
Usage map[string]Usage `json:"usage"`
|
| 236 |
+
}
|
| 237 |
+
if err := json.Unmarshal(buf, &wrapper); err != nil {
|
| 238 |
+
return fmt.Errorf("bank: parse usage: %w", err)
|
| 239 |
+
}
|
| 240 |
+
for id, u := range wrapper.Usage {
|
| 241 |
+
m.usage[id] = u
|
| 242 |
+
}
|
| 243 |
+
return nil
|
| 244 |
+
}
|
| 245 |
+
|
| 246 |
+
// SaveUsage writes counters to disk atomically.
|
| 247 |
+
func (m *Manager) SaveUsage() error {
|
| 248 |
+
m.mu.RLock()
|
| 249 |
+
buf, err := json.MarshalIndent(struct {
|
| 250 |
+
Usage map[string]Usage `json:"usage"`
|
| 251 |
+
}{Usage: m.usage}, "", " ")
|
| 252 |
+
m.mu.RUnlock()
|
| 253 |
+
if err != nil {
|
| 254 |
+
return err
|
| 255 |
+
}
|
| 256 |
+
tmp, err := os.CreateTemp(m.dir, ".usage-*")
|
| 257 |
+
if err != nil {
|
| 258 |
+
return err
|
| 259 |
+
}
|
| 260 |
+
name := tmp.Name()
|
| 261 |
+
defer os.Remove(name)
|
| 262 |
+
if _, err := tmp.Write(append(buf, '\n')); err != nil {
|
| 263 |
+
tmp.Close()
|
| 264 |
+
return err
|
| 265 |
+
}
|
| 266 |
+
if err := tmp.Close(); err != nil {
|
| 267 |
+
return err
|
| 268 |
+
}
|
| 269 |
+
return os.Rename(name, m.usagePath)
|
| 270 |
+
}
|
| 271 |
+
|
| 272 |
+
// Categories lists the categories present, sorted.
|
| 273 |
+
func (m *Manager) Categories() []string {
|
| 274 |
+
m.mu.RLock()
|
| 275 |
+
defer m.mu.RUnlock()
|
| 276 |
+
out := make([]string, 0, len(m.byCategory))
|
| 277 |
+
for c := range m.byCategory {
|
| 278 |
+
out = append(out, c)
|
| 279 |
+
}
|
| 280 |
+
sort.Strings(out)
|
| 281 |
+
return out
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
+
// Size is the total number of examples loaded.
|
| 285 |
+
func (m *Manager) Size() int {
|
| 286 |
+
m.mu.RLock()
|
| 287 |
+
defer m.mu.RUnlock()
|
| 288 |
+
return len(m.byID)
|
| 289 |
+
}
|
| 290 |
+
|
| 291 |
+
// Get returns an example by ID.
|
| 292 |
+
func (m *Manager) Get(id string) (*Example, bool) {
|
| 293 |
+
m.mu.RLock()
|
| 294 |
+
defer m.mu.RUnlock()
|
| 295 |
+
ex, ok := m.byID[id]
|
| 296 |
+
if !ok {
|
| 297 |
+
return nil, false
|
| 298 |
+
}
|
| 299 |
+
clone := *ex
|
| 300 |
+
return &clone, true
|
| 301 |
+
}
|
| 302 |
+
|
| 303 |
+
// Uses reports how many times an example has been handed out.
|
| 304 |
+
func (m *Manager) Uses(id string) int {
|
| 305 |
+
m.mu.RLock()
|
| 306 |
+
defer m.mu.RUnlock()
|
| 307 |
+
return m.usage[id].Count
|
| 308 |
+
}
|
| 309 |
+
|
| 310 |
+
// Eligible returns the examples in a category/difficulty pair that still have
|
| 311 |
+
// uses left. Stale examples (used StaleAfter times) are excluded: they need
|
| 312 |
+
// replacing or rephrasing before they go back into circulation.
|
| 313 |
+
func (m *Manager) Eligible(category, difficulty string) []*Example {
|
| 314 |
+
m.mu.RLock()
|
| 315 |
+
defer m.mu.RUnlock()
|
| 316 |
+
out := make([]*Example, 0, 16)
|
| 317 |
+
for _, ex := range m.byCategory[category] {
|
| 318 |
+
if ex.Difficulty != difficulty {
|
| 319 |
+
continue
|
| 320 |
+
}
|
| 321 |
+
if m.usage[ex.ID].Count >= m.staleAfter {
|
| 322 |
+
continue
|
| 323 |
+
}
|
| 324 |
+
out = append(out, ex)
|
| 325 |
+
}
|
| 326 |
+
return out
|
| 327 |
+
}
|
| 328 |
+
|
| 329 |
+
// MarkUsed bumps the counters for issued examples.
|
| 330 |
+
func (m *Manager) MarkUsed(ids []string, at time.Time) {
|
| 331 |
+
m.mu.Lock()
|
| 332 |
+
defer m.mu.Unlock()
|
| 333 |
+
for _, id := range ids {
|
| 334 |
+
u := m.usage[id]
|
| 335 |
+
u.Count++
|
| 336 |
+
u.LastUsed = at
|
| 337 |
+
m.usage[id] = u
|
| 338 |
+
}
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
// Stale lists examples that have exhausted their allowed uses.
|
| 342 |
+
func (m *Manager) Stale() []Example {
|
| 343 |
+
m.mu.RLock()
|
| 344 |
+
defer m.mu.RUnlock()
|
| 345 |
+
var out []Example
|
| 346 |
+
for id, u := range m.usage {
|
| 347 |
+
if u.Count < m.staleAfter {
|
| 348 |
+
continue
|
| 349 |
+
}
|
| 350 |
+
if ex, ok := m.byID[id]; ok {
|
| 351 |
+
out = append(out, *ex)
|
| 352 |
+
}
|
| 353 |
+
}
|
| 354 |
+
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
|
| 355 |
+
return out
|
| 356 |
+
}
|
| 357 |
+
|
| 358 |
+
// Stats summarises the bank for health reporting.
|
| 359 |
+
func (m *Manager) Stats() map[string]int {
|
| 360 |
+
m.mu.RLock()
|
| 361 |
+
defer m.mu.RUnlock()
|
| 362 |
+
out := make(map[string]int, len(m.byCategory)+1)
|
| 363 |
+
out["_total"] = len(m.byID)
|
| 364 |
+
for c, list := range m.byCategory {
|
| 365 |
+
out[c] = len(list)
|
| 366 |
+
}
|
| 367 |
+
return out
|
| 368 |
+
}
|
| 369 |
+
|
| 370 |
+
// Counts is a per-category breakdown of total vs still-usable examples.
|
| 371 |
+
type Counts struct {
|
| 372 |
+
Total int `json:"total"`
|
| 373 |
+
ByCat map[string]int `json:"by_category"`
|
| 374 |
+
StaleCount int `json:"stale"`
|
| 375 |
+
Usable int `json:"usable"`
|
| 376 |
+
}
|
| 377 |
+
|
| 378 |
+
// Inventory reports how much of the bank is still in circulation.
|
| 379 |
+
func (m *Manager) Inventory() Counts {
|
| 380 |
+
m.mu.RLock()
|
| 381 |
+
defer m.mu.RUnlock()
|
| 382 |
+
c := Counts{Total: len(m.byID), ByCat: map[string]int{}}
|
| 383 |
+
for cat, list := range m.byCategory {
|
| 384 |
+
c.ByCat[cat] = len(list)
|
| 385 |
+
for _, ex := range list {
|
| 386 |
+
if m.usage[ex.ID].Count >= m.staleAfter {
|
| 387 |
+
c.StaleCount++
|
| 388 |
+
} else {
|
| 389 |
+
c.Usable++
|
| 390 |
+
}
|
| 391 |
+
}
|
| 392 |
+
}
|
| 393 |
+
return c
|
| 394 |
+
}
|
internal/config/config.go
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Package config loads every tunable from the environment. Nothing here reads
|
| 2 |
+
// a file: a Hugging Face Space gives us env vars and nothing else.
|
| 3 |
+
package config
|
| 4 |
+
|
| 5 |
+
import (
|
| 6 |
+
"crypto/sha256"
|
| 7 |
+
"os"
|
| 8 |
+
"strconv"
|
| 9 |
+
"strings"
|
| 10 |
+
"time"
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
// Config is the fully resolved runtime configuration.
|
| 14 |
+
type Config struct {
|
| 15 |
+
Addr string
|
| 16 |
+
BankDir string
|
| 17 |
+
DataDir string
|
| 18 |
+
|
| 19 |
+
// TrustedProxyHops is how many reverse proxies sit in front of us.
|
| 20 |
+
// Hugging Face Spaces puts one in front, so the default is 1.
|
| 21 |
+
TrustedProxyHops int
|
| 22 |
+
|
| 23 |
+
// DrawMax caps how many examples a single caller may receive.
|
| 24 |
+
DrawMax int
|
| 25 |
+
// StaleAfterUses is how many times an example may be served before the
|
| 26 |
+
// bank treats it as stale and stops handing it out.
|
| 27 |
+
StaleAfterUses int
|
| 28 |
+
|
| 29 |
+
Window time.Duration // one draw per window, per identity
|
| 30 |
+
|
| 31 |
+
SpamWindow time.Duration // "N requests in <SpamWindow>"
|
| 32 |
+
SpamCount int
|
| 33 |
+
SpamBan time.Duration
|
| 34 |
+
|
| 35 |
+
BurstWindow time.Duration // "N requests in <BurstWindow>"
|
| 36 |
+
BurstCount int
|
| 37 |
+
BurstBan time.Duration
|
| 38 |
+
|
| 39 |
+
MaxBodyBytes int64
|
| 40 |
+
RequestTimeout time.Duration
|
| 41 |
+
|
| 42 |
+
// AllowLoopback relaxes IP validation for local development.
|
| 43 |
+
AllowLoopback bool
|
| 44 |
+
|
| 45 |
+
// SaltSecret keys every HMAC we compute. Rotating it resets every
|
| 46 |
+
// marker hash, so treat it as permanent.
|
| 47 |
+
SaltSecret string
|
| 48 |
+
|
| 49 |
+
HFRepo string
|
| 50 |
+
HFToken string
|
| 51 |
+
HFBaseURL string
|
| 52 |
+
HFEnabled bool
|
| 53 |
+
|
| 54 |
+
// SyncInterval is the batching cadence for dataset commits. The dataset is
|
| 55 |
+
// a git repo: writes are sequential, so they are coalesced rather than
|
| 56 |
+
// issued per request.
|
| 57 |
+
SyncInterval time.Duration
|
| 58 |
+
SyncMaxFiles int
|
| 59 |
+
// RestoreOnBoot pulls the relay's own state back from the dataset before
|
| 60 |
+
// serving, so a sleeping Space resumes with its memory intact.
|
| 61 |
+
RestoreOnBoot bool
|
| 62 |
+
// RestorePrefixes lists the relay-owned dataset subtrees restored at boot.
|
| 63 |
+
// The bank is deliberately excluded from this list because it is read from
|
| 64 |
+
// the dataset on a separate path (BankFromDataset) and never published.
|
| 65 |
+
RestorePrefixes []string
|
| 66 |
+
|
| 67 |
+
// BankFromDataset pulls the question bank out of the private dataset at
|
| 68 |
+
// boot. The bank is the answer key and must never be committed to this
|
| 69 |
+
// public repository or uploaded into a public Space, and a Space's disk is
|
| 70 |
+
// wiped on restart, so the private dataset is its only durable home.
|
| 71 |
+
BankFromDataset bool
|
| 72 |
+
|
| 73 |
+
// FlushInterval is the maximum time a rejection is allowed to sit in
|
| 74 |
+
// memory before being persisted. Accepted draws always flush inline.
|
| 75 |
+
// RateDir holds the durable sliding-window log. It lives outside DataDir's
|
| 76 |
+
// mirrored tree because it is operational state, not identity data.
|
| 77 |
+
RateDir string
|
| 78 |
+
|
| 79 |
+
AccessToken string
|
| 80 |
+
|
| 81 |
+
// MetricsToken gates /metrics; empty means the endpoint is disabled.
|
| 82 |
+
MetricsToken string
|
| 83 |
+
|
| 84 |
+
// Network caps exist so one subnet cannot exhaust the whole bank.
|
| 85 |
+
NetWindow time.Duration
|
| 86 |
+
NetMaxDraws int
|
| 87 |
+
GlobalWindow time.Duration
|
| 88 |
+
GlobalMax int
|
| 89 |
+
|
| 90 |
+
FlushInterval time.Duration
|
| 91 |
+
|
| 92 |
+
ReputationFile string
|
| 93 |
+
LogFormat string
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
// Load builds a Config from the environment, applying safe defaults.
|
| 97 |
+
func Load() Config {
|
| 98 |
+
c := Config{
|
| 99 |
+
Addr: envStr("ADDR", ":7860"),
|
| 100 |
+
BankDir: envStr("BANK_DIR", "bank"),
|
| 101 |
+
// Default on: the bank is useless if the Space starts without it.
|
| 102 |
+
BankFromDataset: envBool("BANK_FROM_DATASET", true),
|
| 103 |
+
DataDir: envStr("DATA_DIR", "data"),
|
| 104 |
+
|
| 105 |
+
TrustedProxyHops: envInt("TRUSTED_PROXY_HOPS", 1),
|
| 106 |
+
|
| 107 |
+
DrawMax: envInt("DRAW_MAX", 75),
|
| 108 |
+
StaleAfterUses: envInt("STALE_AFTER_USES", 3),
|
| 109 |
+
|
| 110 |
+
Window: envDur("WINDOW", time.Hour),
|
| 111 |
+
|
| 112 |
+
SpamWindow: envDur("SPAM_WINDOW", 60*time.Second),
|
| 113 |
+
SpamCount: envInt("SPAM_COUNT", 30),
|
| 114 |
+
SpamBan: envDur("SPAM_BAN", 48*time.Hour),
|
| 115 |
+
|
| 116 |
+
BurstWindow: envDur("BURST_WINDOW", 10*time.Second),
|
| 117 |
+
BurstCount: envInt("BURST_COUNT", 15),
|
| 118 |
+
BurstBan: envDur("BURST_BAN", 2*time.Hour),
|
| 119 |
+
|
| 120 |
+
MaxBodyBytes: envInt64("MAX_BODY_BYTES", 1<<20),
|
| 121 |
+
RequestTimeout: envDur("REQUEST_TIMEOUT", 15*time.Second),
|
| 122 |
+
|
| 123 |
+
AllowLoopback: envBool("ALLOW_LOOPBACK", false),
|
| 124 |
+
|
| 125 |
+
SaltSecret: os.Getenv("RELAY_SALT"),
|
| 126 |
+
|
| 127 |
+
HFRepo: envStr("HF_DATASET", "Archnemix/Archx-Eval"),
|
| 128 |
+
// HF_DATA_TOKEN is the secret the Space carries for dataset access. It is
|
| 129 |
+
// created by the DATASET owner (Archnemix) and pasted into the Space's
|
| 130 |
+
// settings by hand; the Space's own account is never added as a
|
| 131 |
+
// collaborator and holds no token that can write this dataset.
|
| 132 |
+
//
|
| 133 |
+
// HF_TOKEN is still honoured as a fallback so existing deployments and
|
| 134 |
+
// local test scripts keep working, but the Space must use HF_DATA_TOKEN.
|
| 135 |
+
HFToken: firstNonEmpty(os.Getenv("HF_DATA_TOKEN"), os.Getenv("HF_TOKEN")),
|
| 136 |
+
HFBaseURL: envStr("HF_BASE_URL", "https://huggingface.co"),
|
| 137 |
+
|
| 138 |
+
SyncInterval: envDur("SYNC_INTERVAL", 30*time.Second),
|
| 139 |
+
SyncMaxFiles: envInt("SYNC_MAX_FILES", 100),
|
| 140 |
+
RestoreOnBoot: envBool("RESTORE_ON_BOOT", true),
|
| 141 |
+
// Raw IPs and machine identifiers are never stored at all, so there is
|
| 142 |
+
// no "raw" subtree to restore or publish.
|
| 143 |
+
RestorePrefixes: envList("RESTORE_PREFIXES",
|
| 144 |
+
[]string{"identities", "markers", "events", "results"}),
|
| 145 |
+
|
| 146 |
+
RateDir: envStr("RATE_DIR", "rate"),
|
| 147 |
+
AccessToken: os.Getenv("ACCESS_TOKEN"),
|
| 148 |
+
|
| 149 |
+
MetricsToken: os.Getenv("METRICS_TOKEN"),
|
| 150 |
+
|
| 151 |
+
NetWindow: envDur("NET_WINDOW", time.Hour),
|
| 152 |
+
NetMaxDraws: envInt("NET_MAX_DRAWS", 60),
|
| 153 |
+
GlobalWindow: envDur("GLOBAL_WINDOW", time.Hour),
|
| 154 |
+
GlobalMax: envInt("GLOBAL_MAX_DRAWS", 4000),
|
| 155 |
+
|
| 156 |
+
FlushInterval: envDur("FLUSH_INTERVAL", 5*time.Second),
|
| 157 |
+
|
| 158 |
+
ReputationFile: envStr("REPUTATION_FILE", ""),
|
| 159 |
+
LogFormat: envStr("LOG_FORMAT", "json"),
|
| 160 |
+
}
|
| 161 |
+
c.HFEnabled = c.HFToken != "" && !envBool("HF_DISABLED", false)
|
| 162 |
+
if c.SaltSecret == "" {
|
| 163 |
+
// Development fallback. Logged loudly at startup by the caller.
|
| 164 |
+
c.SaltSecret = "dev-insecure-salt-change-me"
|
| 165 |
+
}
|
| 166 |
+
if c.DrawMax <= 0 {
|
| 167 |
+
c.DrawMax = 75
|
| 168 |
+
}
|
| 169 |
+
if c.TrustedProxyHops < 0 {
|
| 170 |
+
c.TrustedProxyHops = 0
|
| 171 |
+
}
|
| 172 |
+
return c
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
// Salt returns the 32-byte HMAC key derived from SaltSecret.
|
| 176 |
+
func (c Config) Salt() []byte {
|
| 177 |
+
sum := sha256.Sum256([]byte("archx-eval/marker-salt/v1\x00" + c.SaltSecret))
|
| 178 |
+
return sum[:]
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
// SaltIsDefault reports whether the insecure development salt is in use.
|
| 182 |
+
func (c Config) SaltIsDefault() bool {
|
| 183 |
+
return c.SaltSecret == "dev-insecure-salt-change-me"
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
func envList(key string, def []string) []string {
|
| 187 |
+
raw := strings.TrimSpace(os.Getenv(key))
|
| 188 |
+
if raw == "" {
|
| 189 |
+
return def
|
| 190 |
+
}
|
| 191 |
+
out := make([]string, 0, 4)
|
| 192 |
+
for _, part := range strings.Split(raw, ",") {
|
| 193 |
+
if v := strings.TrimSpace(part); v != "" {
|
| 194 |
+
out = append(out, v)
|
| 195 |
+
}
|
| 196 |
+
}
|
| 197 |
+
if len(out) == 0 {
|
| 198 |
+
return def
|
| 199 |
+
}
|
| 200 |
+
return out
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
// firstNonEmpty returns the first non-empty value, so one config field can be
|
| 204 |
+
// fed by a preferred environment variable and a legacy fallback.
|
| 205 |
+
func firstNonEmpty(vals ...string) string {
|
| 206 |
+
for _, v := range vals {
|
| 207 |
+
if v != "" {
|
| 208 |
+
return v
|
| 209 |
+
}
|
| 210 |
+
}
|
| 211 |
+
return ""
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
func envStr(key, def string) string {
|
| 215 |
+
if v := strings.TrimSpace(os.Getenv(key)); v != "" {
|
| 216 |
+
return v
|
| 217 |
+
}
|
| 218 |
+
return def
|
| 219 |
+
}
|
| 220 |
+
|
| 221 |
+
func envInt(key string, def int) int {
|
| 222 |
+
if v, err := strconv.Atoi(strings.TrimSpace(os.Getenv(key))); err == nil {
|
| 223 |
+
return v
|
| 224 |
+
}
|
| 225 |
+
return def
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
func envInt64(key string, def int64) int64 {
|
| 229 |
+
if v, err := strconv.ParseInt(strings.TrimSpace(os.Getenv(key)), 10, 64); err == nil {
|
| 230 |
+
return v
|
| 231 |
+
}
|
| 232 |
+
return def
|
| 233 |
+
}
|
| 234 |
+
|
| 235 |
+
func envBool(key string, def bool) bool {
|
| 236 |
+
switch strings.ToLower(strings.TrimSpace(os.Getenv(key))) {
|
| 237 |
+
case "1", "true", "yes", "on":
|
| 238 |
+
return true
|
| 239 |
+
case "0", "false", "no", "off":
|
| 240 |
+
return false
|
| 241 |
+
default:
|
| 242 |
+
return def
|
| 243 |
+
}
|
| 244 |
+
}
|
| 245 |
+
|
| 246 |
+
func envDur(key string, def time.Duration) time.Duration {
|
| 247 |
+
if v, err := time.ParseDuration(strings.TrimSpace(os.Getenv(key))); err == nil && v > 0 {
|
| 248 |
+
return v
|
| 249 |
+
}
|
| 250 |
+
return def
|
| 251 |
+
}
|
internal/core/core.go
ADDED
|
@@ -0,0 +1,643 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Package core is the relay's decision engine: it wires identity, storage,
|
| 2 |
+
// limits and the bank together into the two operations the API exposes.
|
| 3 |
+
//
|
| 4 |
+
// It knows nothing about HTTP. That keeps the policy testable in isolation and
|
| 5 |
+
// means the transport can change without touching a single rule.
|
| 6 |
+
package core
|
| 7 |
+
|
| 8 |
+
import (
|
| 9 |
+
"context"
|
| 10 |
+
"crypto/hmac"
|
| 11 |
+
"crypto/rand"
|
| 12 |
+
"crypto/sha256"
|
| 13 |
+
"encoding/hex"
|
| 14 |
+
"fmt"
|
| 15 |
+
"net/netip"
|
| 16 |
+
"os"
|
| 17 |
+
"path/filepath"
|
| 18 |
+
"time"
|
| 19 |
+
|
| 20 |
+
"github.com/archnemix/archx-eval/relay/internal/apierr"
|
| 21 |
+
"github.com/archnemix/archx-eval/relay/internal/bank"
|
| 22 |
+
"github.com/archnemix/archx-eval/relay/internal/config"
|
| 23 |
+
"github.com/archnemix/archx-eval/relay/internal/draw"
|
| 24 |
+
"github.com/archnemix/archx-eval/relay/internal/identity"
|
| 25 |
+
"github.com/archnemix/archx-eval/relay/internal/limits"
|
| 26 |
+
"github.com/archnemix/archx-eval/relay/internal/ratelog"
|
| 27 |
+
"github.com/archnemix/archx-eval/relay/internal/reputation"
|
| 28 |
+
"github.com/archnemix/archx-eval/relay/internal/store"
|
| 29 |
+
"github.com/archnemix/archx-eval/relay/internal/syncctl"
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
// Service is the relay core.
|
| 33 |
+
type Service struct {
|
| 34 |
+
cfg config.Config
|
| 35 |
+
store *store.Store
|
| 36 |
+
bank *bank.Manager
|
| 37 |
+
rep *reputation.Table
|
| 38 |
+
pol limits.Policy
|
| 39 |
+
salt []byte
|
| 40 |
+
|
| 41 |
+
// sync queues state changes for the dataset. It is optional: when nil the
|
| 42 |
+
// relay runs in local-only mode. Even when present it never blocks a
|
| 43 |
+
// request, because Enqueue is an in-memory operation.
|
| 44 |
+
sync *syncctl.Controller
|
| 45 |
+
|
| 46 |
+
// rates is the durable sliding-window log behind the spam ladder and the
|
| 47 |
+
// network ceilings. It survives a process restart, which matters because
|
| 48 |
+
// a Hugging Face Space stops and restarts constantly.
|
| 49 |
+
rates *ratelog.Log
|
| 50 |
+
|
| 51 |
+
now func() time.Time
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
// New builds a Service. Callers own the returned value's lifecycle.
|
| 55 |
+
func New(cfg config.Config, st *store.Store, bm *bank.Manager, rep *reputation.Table, rates *ratelog.Log) *Service {
|
| 56 |
+
return &Service{
|
| 57 |
+
cfg: cfg,
|
| 58 |
+
store: st,
|
| 59 |
+
bank: bm,
|
| 60 |
+
rep: rep,
|
| 61 |
+
salt: cfg.Salt(),
|
| 62 |
+
rates: rates,
|
| 63 |
+
now: func() time.Time { return time.Now().UTC() },
|
| 64 |
+
pol: limits.Policy{
|
| 65 |
+
Window: cfg.Window,
|
| 66 |
+
SpamWindow: cfg.SpamWindow,
|
| 67 |
+
SpamCount: cfg.SpamCount,
|
| 68 |
+
SpamBan: cfg.SpamBan,
|
| 69 |
+
BurstWindow: cfg.BurstWindow,
|
| 70 |
+
BurstCount: cfg.BurstCount,
|
| 71 |
+
BurstBan: cfg.BurstBan,
|
| 72 |
+
},
|
| 73 |
+
}
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
// WithSync attaches the dataset write controller.
|
| 77 |
+
func (s *Service) WithSync(c *syncctl.Controller) *Service {
|
| 78 |
+
s.sync = c
|
| 79 |
+
return s
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
// SyncStats reports controller health, or nil when sync is disabled.
|
| 83 |
+
func (s *Service) SyncStats() *syncctl.Stats {
|
| 84 |
+
if s.sync == nil {
|
| 85 |
+
return nil
|
| 86 |
+
}
|
| 87 |
+
st := s.sync.Stats()
|
| 88 |
+
return &st
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
// SetClock overrides the clock (tests only).
|
| 92 |
+
func (s *Service) SetClock(f func() time.Time) { s.now = f }
|
| 93 |
+
|
| 94 |
+
// DrawInput is the caller-supplied half of a draw request.
|
| 95 |
+
type DrawInput struct {
|
| 96 |
+
RequestID string
|
| 97 |
+
Categories []string
|
| 98 |
+
Mix map[string]float64
|
| 99 |
+
Size int
|
| 100 |
+
Device identity.Device
|
| 101 |
+
RemoteAddr netip.Addr
|
| 102 |
+
Headers map[string][]string
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
// Grant is a successful draw.
|
| 106 |
+
type Grant struct {
|
| 107 |
+
RequestID string
|
| 108 |
+
IdentityID string
|
| 109 |
+
Examples []*bank.Example
|
| 110 |
+
ByCat map[string]int
|
| 111 |
+
IssuedAt time.Time
|
| 112 |
+
NextDrawAt time.Time
|
| 113 |
+
Shortfall int
|
| 114 |
+
Notes []string
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
// Hash implements identity.HashFunc with a salted HMAC-SHA256, truncated to
|
| 118 |
+
// 32 hex characters. The truncation keeps marker files short while leaving
|
| 119 |
+
// 128 bits of collision resistance, which is plenty for this corpus.
|
| 120 |
+
func (s *Service) Hash(kind, value string) string {
|
| 121 |
+
mac := hmac.New(sha256.New, s.salt)
|
| 122 |
+
mac.Write([]byte(kind))
|
| 123 |
+
mac.Write([]byte{0})
|
| 124 |
+
mac.Write([]byte(value))
|
| 125 |
+
return hex.EncodeToString(mac.Sum(nil))[:32]
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
// RequestDraw runs the full admission pipeline.
|
| 129 |
+
//
|
| 130 |
+
// Order is deliberate and cheap-first:
|
| 131 |
+
// 1. identity validation (free)
|
| 132 |
+
// 2. VPN/privacy refusal (free)
|
| 133 |
+
// 3. spam ladder (memory only)
|
| 134 |
+
// 4. marker lookup (a handful of file reads)
|
| 135 |
+
// 5. draw window (uses the record we already fetched)
|
| 136 |
+
// 6. stock check (must happen before we record anything)
|
| 137 |
+
// 7. persist usage and only then hand over examples
|
| 138 |
+
func (s *Service) RequestDraw(ctx context.Context, in DrawInput) (*Grant, error) {
|
| 139 |
+
now := s.now()
|
| 140 |
+
|
| 141 |
+
if err := draw.ValidateMix(in.Mix); err != nil {
|
| 142 |
+
return nil, apierr.BadRequest(err.Error())
|
| 143 |
+
}
|
| 144 |
+
size := in.Size
|
| 145 |
+
if size == 0 {
|
| 146 |
+
size = s.cfg.DrawMax
|
| 147 |
+
return nil, apierr.BadRequest("size is required")
|
| 148 |
+
}
|
| 149 |
+
if size < 0 {
|
| 150 |
+
return nil, apierr.BadRequest("size must be positive")
|
| 151 |
+
}
|
| 152 |
+
if size > s.cfg.DrawMax {
|
| 153 |
+
return nil, apierr.BadRequest(fmt.Sprintf("size may not exceed %d", s.cfg.DrawMax))
|
| 154 |
+
}
|
| 155 |
+
// Bound the request shape itself: an unbounded category list or mix map is
|
| 156 |
+
// cheap to send and expensive to process.
|
| 157 |
+
if len(in.Categories) > 32 {
|
| 158 |
+
return nil, apierr.BadRequest("at most 32 categories may be requested")
|
| 159 |
+
}
|
| 160 |
+
if len(in.Mix) > 32 {
|
| 161 |
+
return nil, apierr.BadRequest("at most 32 mix weights may be supplied")
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
id, err := identity.FromRequest(in.RemoteAddr, in.Headers, in.Device, s.Hash, s.cfg.AllowLoopback)
|
| 165 |
+
if err != nil {
|
| 166 |
+
return nil, err
|
| 167 |
+
}
|
| 168 |
+
if s.rep.Loaded() {
|
| 169 |
+
if entry, ok := s.rep.Lookup(id.IP); ok {
|
| 170 |
+
if entry.Tor {
|
| 171 |
+
s.record(ctx, in.RequestID, "", "deny", "TOR_EXIT", id, 0)
|
| 172 |
+
return nil, apierr.Forbidden("PRIVACY_BLOCKED", "requests via Tor are not accepted")
|
| 173 |
+
}
|
| 174 |
+
id.Privacy = identity.SoftFlagsFromIP(id.Privacy, entry.Hosting || entry.VPN, entry.Abuser)
|
| 175 |
+
} else if identity.LooksHosted(id.IP) {
|
| 176 |
+
id.Privacy = identity.SoftFlagsFromIP(id.Privacy, true, 0)
|
| 177 |
+
}
|
| 178 |
+
} else if identity.LooksHosted(id.IP) {
|
| 179 |
+
id.Privacy = identity.SoftFlagsFromIP(id.Privacy, true, 0)
|
| 180 |
+
}
|
| 181 |
+
if id.Privacy.Blocked() {
|
| 182 |
+
s.record(ctx, in.RequestID, "", "deny", "PRIVACY_BLOCKED", id, 0)
|
| 183 |
+
return nil, apierr.Forbidden("PRIVACY_BLOCKED",
|
| 184 |
+
"this request appears to come from a masked network and is not accepted")
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
markerHashes := make([]string, 0, len(id.Markers))
|
| 188 |
+
for _, m := range id.Markers {
|
| 189 |
+
markerHashes = append(markerHashes, m.Hash)
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
// Spam ladder is checked before storage work so a flood costs us nothing,
|
| 193 |
+
// and it reads a durable log so a restart cannot reset the counters.
|
| 194 |
+
rateKey := s.rateKey(markerHashes)
|
| 195 |
+
if d := s.evaluateVolume(rateKey, now); !d.Allow {
|
| 196 |
+
// A ban needs a record to hang off; find or create one first.
|
| 197 |
+
rec, err := s.upsert(ctx, id, markerHashes, now)
|
| 198 |
+
if err != nil {
|
| 199 |
+
return nil, err
|
| 200 |
+
}
|
| 201 |
+
limits.ApplyBan(rec, d, now)
|
| 202 |
+
if err := s.store.Put(rec); err != nil {
|
| 203 |
+
return nil, apierr.Internal("could not record the ban")
|
| 204 |
+
}
|
| 205 |
+
s.record(ctx, in.RequestID, rec.ID, "ban", d.Code, id, int(d.RetryAfter.Seconds()))
|
| 206 |
+
return nil, limits.Refuse(d)
|
| 207 |
+
}
|
| 208 |
+
if err := s.rates.Record(rateKey, now); err != nil {
|
| 209 |
+
fmt.Fprintf(os.Stderr, "warn: rate event not persisted: %v\n", err)
|
| 210 |
+
}
|
| 211 |
+
if err := s.rates.Record(s.netKey(id.Network), now); err != nil {
|
| 212 |
+
fmt.Fprintf(os.Stderr, "warn: network rate event not persisted: %v\n", err)
|
| 213 |
+
}
|
| 214 |
+
if err := s.rates.Record(globalKey, now); err != nil {
|
| 215 |
+
fmt.Fprintf(os.Stderr, "warn: global rate event not persisted: %v\n", err)
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
// Network and global ceilings: a single subnet, or the service as a whole,
|
| 219 |
+
// may not convert traffic into bank inventory faster than this. Checked
|
| 220 |
+
// before the draw so a refused request consumes nothing.
|
| 221 |
+
if d := s.evaluateCeilings(id.Network, now); !d.Allow {
|
| 222 |
+
s.record(ctx, in.RequestID, "", "deny", d.Code, id, int(d.RetryAfter.Seconds()))
|
| 223 |
+
return nil, limits.Refuse(d)
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
matches, err := s.store.Lookup(markerHashes)
|
| 227 |
+
if err != nil {
|
| 228 |
+
return nil, apierr.Internal("identity lookup failed")
|
| 229 |
+
}
|
| 230 |
+
var rec *store.Record
|
| 231 |
+
if len(matches) > 0 {
|
| 232 |
+
rec = matches[0]
|
| 233 |
+
for _, m := range matches {
|
| 234 |
+
if m.LastSeen.After(rec.LastSeen) {
|
| 235 |
+
rec = m
|
| 236 |
+
}
|
| 237 |
+
}
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
if d := limits.EvaluateWindow(s.pol, rec, now); !d.Allow {
|
| 241 |
+
if rec != nil {
|
| 242 |
+
rec.Requests++
|
| 243 |
+
rec.LastSeen = now
|
| 244 |
+
s.mergeMarkers(rec, markerHashes)
|
| 245 |
+
if err := s.store.Put(rec); err != nil {
|
| 246 |
+
return nil, apierr.Internal("could not update identity")
|
| 247 |
+
}
|
| 248 |
+
}
|
| 249 |
+
s.record(ctx, in.RequestID, idOf(rec), "deny", d.Code, id, int(d.RetryAfter.Seconds()))
|
| 250 |
+
return nil, limits.Refuse(d)
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
// Stock check before we commit to issuing anything.
|
| 254 |
+
result, err := draw.Select(s.bank, draw.Request{
|
| 255 |
+
Categories: in.Categories,
|
| 256 |
+
Mix: in.Mix,
|
| 257 |
+
Size: size,
|
| 258 |
+
})
|
| 259 |
+
if err != nil {
|
| 260 |
+
s.record(ctx, in.RequestID, idOf(rec), "deny", "INSUFFICIENT_STOCK", id, 0)
|
| 261 |
+
return nil, err
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
issued := make([]string, 0, len(result.Examples))
|
| 265 |
+
for _, ex := range result.Examples {
|
| 266 |
+
issued = append(issued, ex.ID)
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
if rec == nil {
|
| 270 |
+
rec = &store.Record{
|
| 271 |
+
ID: newID(),
|
| 272 |
+
Markers: markerHashes,
|
| 273 |
+
FirstSeen: now,
|
| 274 |
+
}
|
| 275 |
+
} else {
|
| 276 |
+
s.mergeMarkers(rec, markerHashes)
|
| 277 |
+
}
|
| 278 |
+
rec.LastSeen = now
|
| 279 |
+
rec.Requests++
|
| 280 |
+
rec.Draws++
|
| 281 |
+
rec.LastDraw = now
|
| 282 |
+
if err := s.store.Put(rec); err != nil {
|
| 283 |
+
return nil, apierr.Internal("could not persist identity")
|
| 284 |
+
}
|
| 285 |
+
s.bank.MarkUsed(issued, now)
|
| 286 |
+
if err := s.bank.SaveUsage(); err != nil {
|
| 287 |
+
// Usage persistence is important but must not fail the user's draw:
|
| 288 |
+
// the in-memory counter already prevents double-issue this process.
|
| 289 |
+
fmt.Fprintf(os.Stderr, "warn: usage save failed: %v\n", err)
|
| 290 |
+
}
|
| 291 |
+
s.record(ctx, in.RequestID, rec.ID, "allow", "granted", id, 0)
|
| 292 |
+
s.publishIdentity(rec)
|
| 293 |
+
|
| 294 |
+
return &Grant{
|
| 295 |
+
RequestID: in.RequestID,
|
| 296 |
+
IdentityID: rec.ID,
|
| 297 |
+
Examples: result.Examples,
|
| 298 |
+
ByCat: result.ByCat,
|
| 299 |
+
IssuedAt: now,
|
| 300 |
+
NextDrawAt: now.Add(s.cfg.Window),
|
| 301 |
+
Shortfall: result.Shortfall,
|
| 302 |
+
Notes: result.Notes,
|
| 303 |
+
}, nil
|
| 304 |
+
}
|
| 305 |
+
|
| 306 |
+
// Authenticate verifies the caller's access token. Draws are closed-loop: a
|
| 307 |
+
// token is required so that every draw can be traced to a registered runner,
|
| 308 |
+
// which is what makes the abuse ladder enforceable at all.
|
| 309 |
+
func (s *Service) Authenticate(token string) error {
|
| 310 |
+
if s.cfg.AccessToken == "" {
|
| 311 |
+
return apierr.Forbidden("ACCESS_DISABLED",
|
| 312 |
+
"this relay has no access token configured and is not accepting draws")
|
| 313 |
+
}
|
| 314 |
+
if !constantTimeEqual(token, s.cfg.AccessToken) {
|
| 315 |
+
return apierr.Forbidden("ACCESS_DENIED", "a valid access token is required")
|
| 316 |
+
}
|
| 317 |
+
return nil
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
func constantTimeEqual(a, b string) bool {
|
| 321 |
+
if len(a) != len(b) {
|
| 322 |
+
return false
|
| 323 |
+
}
|
| 324 |
+
var diff byte
|
| 325 |
+
for i := 0; i < len(a); i++ {
|
| 326 |
+
diff |= a[i] ^ b[i]
|
| 327 |
+
}
|
| 328 |
+
return diff == 0
|
| 329 |
+
}
|
| 330 |
+
|
| 331 |
+
// upsert finds an existing record or builds an unsaved one.
|
| 332 |
+
func (s *Service) upsert(ctx context.Context, id *identity.Identity, markers []string, now time.Time) (*store.Record, error) {
|
| 333 |
+
matches, err := s.store.Lookup(markers)
|
| 334 |
+
if err != nil {
|
| 335 |
+
return nil, apierr.Internal("identity lookup failed")
|
| 336 |
+
}
|
| 337 |
+
if len(matches) > 0 {
|
| 338 |
+
rec := matches[0]
|
| 339 |
+
s.mergeMarkers(rec, markers)
|
| 340 |
+
rec.LastSeen = now
|
| 341 |
+
return rec, nil
|
| 342 |
+
}
|
| 343 |
+
return &store.Record{ID: newID(), Markers: markers, FirstSeen: now, LastSeen: now}, nil
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
+
// mergeMarkers keeps a record's marker set current as a caller's device data
|
| 347 |
+
// drifts (a new NIC, a reimaged disk) without ever dropping a known marker.
|
| 348 |
+
func (s *Service) mergeMarkers(rec *store.Record, markers []string) {
|
| 349 |
+
have := make(map[string]bool, len(rec.Markers))
|
| 350 |
+
for _, m := range rec.Markers {
|
| 351 |
+
have[m] = true
|
| 352 |
+
}
|
| 353 |
+
for _, m := range markers {
|
| 354 |
+
if !have[m] {
|
| 355 |
+
rec.Markers = append(rec.Markers, m)
|
| 356 |
+
have[m] = true
|
| 357 |
+
}
|
| 358 |
+
}
|
| 359 |
+
}
|
| 360 |
+
|
| 361 |
+
// publishIdentity queues the hashed record for the dataset.
|
| 362 |
+
//
|
| 363 |
+
// The raw row is deliberately NOT queued. The dataset is a git repository, and
|
| 364 |
+
// git history is permanent: a committed IP address stays recoverable in the
|
| 365 |
+
// commit graph even after the file is deleted, so publishing raw identifiers
|
| 366 |
+
// would make the retention promise impossible to keep. Raw rows stay on the
|
| 367 |
+
// Space's persistent volume and are pruned locally after 30 days.
|
| 368 |
+
func (s *Service) publishIdentity(rec *store.Record) {
|
| 369 |
+
if s.sync == nil || rec == nil {
|
| 370 |
+
return
|
| 371 |
+
}
|
| 372 |
+
if buf, err := store.MarshalRecord(rec); err == nil {
|
| 373 |
+
s.sync.Enqueue(store.RecordPath(rec.ID), buf)
|
| 374 |
+
}
|
| 375 |
+
}
|
| 376 |
+
|
| 377 |
+
func (s *Service) record(ctx context.Context, reqID, id, decision, reason string, ident *identity.Identity, retry int) {
|
| 378 |
+
if ident == nil {
|
| 379 |
+
return
|
| 380 |
+
}
|
| 381 |
+
ev := store.Event{
|
| 382 |
+
TS: s.now(),
|
| 383 |
+
RequestID: reqID,
|
| 384 |
+
IdentityID: id,
|
| 385 |
+
Decision: decision,
|
| 386 |
+
Reason: reason,
|
| 387 |
+
IPHash: s.Hash(identity.MarkerIP, ident.IP.String()),
|
| 388 |
+
NetHash: s.Hash("net", ident.Network.String()),
|
| 389 |
+
Country: ident.Country,
|
| 390 |
+
OS: ident.Device.OSFamily,
|
| 391 |
+
Arch: ident.Device.Arch,
|
| 392 |
+
RetryAfter: retry,
|
| 393 |
+
}
|
| 394 |
+
if err := s.store.AppendEvent(ev); err != nil {
|
| 395 |
+
fmt.Fprintf(os.Stderr, "warn: event not persisted: %v\n", err)
|
| 396 |
+
return
|
| 397 |
+
}
|
| 398 |
+
if s.sync != nil {
|
| 399 |
+
if buf, err := s.store.ReadEventDay(ev.TS); err == nil {
|
| 400 |
+
s.sync.Enqueue(store.EventPath(ev.TS), buf)
|
| 401 |
+
}
|
| 402 |
+
}
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
// rateKey is the durable log key for an identity. Identity markers are already
|
| 406 |
+
// salted hashes, so the key leaks nothing.
|
| 407 |
+
func (s *Service) rateKey(markers []string) string {
|
| 408 |
+
if len(markers) == 0 {
|
| 409 |
+
return ""
|
| 410 |
+
}
|
| 411 |
+
return "id:" + markers[0]
|
| 412 |
+
}
|
| 413 |
+
|
| 414 |
+
func (s *Service) netKey(p netip.Prefix) string {
|
| 415 |
+
if !p.IsValid() {
|
| 416 |
+
return ""
|
| 417 |
+
}
|
| 418 |
+
return "net:" + s.Hash("net", p.String())
|
| 419 |
+
}
|
| 420 |
+
|
| 421 |
+
const globalKey = "global"
|
| 422 |
+
|
| 423 |
+
// evaluateVolume rebuilds the request history from the durable log and asks
|
| 424 |
+
// the limits package for a verdict.
|
| 425 |
+
func (s *Service) evaluateVolume(key string, now time.Time) limits.Decision {
|
| 426 |
+
if key == "" {
|
| 427 |
+
return limits.Decision{Allow: true}
|
| 428 |
+
}
|
| 429 |
+
burst := s.rates.Count(key, s.cfg.BurstWindow, now)
|
| 430 |
+
sustained := s.rates.Count(key, s.cfg.SpamWindow, now)
|
| 431 |
+
|
| 432 |
+
if s.cfg.BurstCount > 0 && burst >= s.cfg.BurstCount {
|
| 433 |
+
return limits.Decision{
|
| 434 |
+
Code: "SPAM_BURST",
|
| 435 |
+
Reason: "request rate far above the permitted rate",
|
| 436 |
+
RetryAfter: s.cfg.BurstBan,
|
| 437 |
+
Ban: s.cfg.BurstBan,
|
| 438 |
+
}
|
| 439 |
+
}
|
| 440 |
+
if s.cfg.SpamCount > 0 && sustained >= s.cfg.SpamCount {
|
| 441 |
+
return limits.Decision{
|
| 442 |
+
Code: "SPAM_SUSTAINED",
|
| 443 |
+
Reason: "too many requests in the spam window",
|
| 444 |
+
RetryAfter: s.cfg.SpamBan,
|
| 445 |
+
Ban: s.cfg.SpamBan,
|
| 446 |
+
}
|
| 447 |
+
}
|
| 448 |
+
return limits.Decision{Allow: true}
|
| 449 |
+
}
|
| 450 |
+
|
| 451 |
+
// evaluateCeilings applies subnet and service-wide draw ceilings. These are
|
| 452 |
+
// separate from the per-identity ladder: they protect the inventory rather than
|
| 453 |
+
// punishing one caller.
|
| 454 |
+
func (s *Service) evaluateCeilings(p netip.Prefix, now time.Time) limits.Decision {
|
| 455 |
+
if s.cfg.NetMaxDraws > 0 {
|
| 456 |
+
if n := s.rates.Count(s.netKey(p), s.cfg.NetWindow, now); n > s.cfg.NetMaxDraws {
|
| 457 |
+
return limits.Decision{
|
| 458 |
+
Code: "NETWORK_CEILING",
|
| 459 |
+
Reason: "this network has reached its draw ceiling",
|
| 460 |
+
RetryAfter: s.cfg.NetWindow,
|
| 461 |
+
}
|
| 462 |
+
}
|
| 463 |
+
}
|
| 464 |
+
if s.cfg.GlobalMax > 0 {
|
| 465 |
+
if n := s.rates.Count(globalKey, s.cfg.GlobalWindow, now); n > s.cfg.GlobalMax {
|
| 466 |
+
return limits.Decision{
|
| 467 |
+
Code: "GLOBAL_CEILING",
|
| 468 |
+
Reason: "the bank is at capacity for this window",
|
| 469 |
+
RetryAfter: s.cfg.GlobalWindow,
|
| 470 |
+
}
|
| 471 |
+
}
|
| 472 |
+
}
|
| 473 |
+
return limits.Decision{Allow: true}
|
| 474 |
+
}
|
| 475 |
+
|
| 476 |
+
// Health summarises readiness.
|
| 477 |
+
type Health struct {
|
| 478 |
+
OK bool `json:"ok"`
|
| 479 |
+
Version string `json:"version"`
|
| 480 |
+
UptimeSeconds int64 `json:"uptime_s"`
|
| 481 |
+
Bank map[string]int `json:"bank"`
|
| 482 |
+
Inventory bank.Counts `json:"inventory"`
|
| 483 |
+
Records int `json:"records"`
|
| 484 |
+
Markers int `json:"markers"`
|
| 485 |
+
Reputation int `json:"reputation_ranges"`
|
| 486 |
+
SaltIsDefault bool `json:"salt_is_default"`
|
| 487 |
+
Sync *syncctl.Stats `json:"sync,omitempty"`
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
var startedAt = time.Now()
|
| 491 |
+
|
| 492 |
+
// Version is stamped at build time via ldflags.
|
| 493 |
+
var Version = "dev"
|
| 494 |
+
|
| 495 |
+
// Health reports service state without touching the bank lists.
|
| 496 |
+
func (s *Service) Health() Health {
|
| 497 |
+
recs, markers := s.store.Stats()
|
| 498 |
+
return Health{
|
| 499 |
+
OK: s.bank.Size() > 0,
|
| 500 |
+
Version: Version,
|
| 501 |
+
UptimeSeconds: int64(time.Since(startedAt).Seconds()),
|
| 502 |
+
Bank: s.bank.Stats(),
|
| 503 |
+
Inventory: s.bank.Inventory(),
|
| 504 |
+
Records: recs,
|
| 505 |
+
Markers: markers,
|
| 506 |
+
Reputation: s.rep.Size(),
|
| 507 |
+
SaltIsDefault: s.cfg.SaltIsDefault(),
|
| 508 |
+
Sync: s.SyncStats(),
|
| 509 |
+
}
|
| 510 |
+
}
|
| 511 |
+
|
| 512 |
+
// Categories lists servable categories.
|
| 513 |
+
func (s *Service) Categories() []string { return s.bank.Categories() }
|
| 514 |
+
|
| 515 |
+
// StaleExamples exposes the stale list for the daily curator job.
|
| 516 |
+
func (s *Service) StaleExamples() []bank.Example { return s.bank.Stale() }
|
| 517 |
+
|
| 518 |
+
// Prune clears expired bans. No personal data is stored, so there is nothing
|
| 519 |
+
// to expire; the retention obligation disappears with the raw values.
|
| 520 |
+
func (s *Service) Prune() (int, error) { return s.store.Prune(s.now()) }
|
| 521 |
+
|
| 522 |
+
// Maintain compacts and fsyncs the durable rate log. Called on a timer.
|
| 523 |
+
func (s *Service) Maintain(now time.Time) (int, error) {
|
| 524 |
+
n, err := s.rates.Compact(now)
|
| 525 |
+
if err != nil {
|
| 526 |
+
return n, err
|
| 527 |
+
}
|
| 528 |
+
return n, s.rates.Flush()
|
| 529 |
+
}
|
| 530 |
+
|
| 531 |
+
// Flush persists counters and the manifest.
|
| 532 |
+
func (s *Service) Flush() error {
|
| 533 |
+
if err := s.bank.SaveUsage(); err != nil {
|
| 534 |
+
return err
|
| 535 |
+
}
|
| 536 |
+
return s.store.FlushIndex()
|
| 537 |
+
}
|
| 538 |
+
|
| 539 |
+
// FlushRates fsyncs the durable rate log; called on shutdown.
|
| 540 |
+
func (s *Service) FlushRates() error { return s.rates.Flush() }
|
| 541 |
+
|
| 542 |
+
// PublishableSubtrees is the single canonical list of store subtrees that may
|
| 543 |
+
// be mirrored to the dataset. "raw" is absent on purpose: raw identity rows
|
| 544 |
+
// must never enter a git repository, whose history is permanent.
|
| 545 |
+
//
|
| 546 |
+
// Both the live sync controller and the one-shot -sync export read this list,
|
| 547 |
+
// so the two paths cannot drift apart (a real leak happened when they did).
|
| 548 |
+
var PublishableSubtrees = []string{"identities", "markers", "events", "results"}
|
| 549 |
+
|
| 550 |
+
// ExportSnapshot copies the publishable store tree into dir for the dataset
|
| 551 |
+
// mirror.
|
| 552 |
+
func (s *Service) ExportSnapshot(dir string) ([]string, error) {
|
| 553 |
+
if err := s.Flush(); err != nil {
|
| 554 |
+
return nil, err
|
| 555 |
+
}
|
| 556 |
+
src := s.cfg.DataDir
|
| 557 |
+
var written []string
|
| 558 |
+
for _, sub := range PublishableSubtrees {
|
| 559 |
+
from := filepath.Join(src, sub)
|
| 560 |
+
to := filepath.Join(dir, sub)
|
| 561 |
+
n, err := copyTree(from, to)
|
| 562 |
+
if err != nil {
|
| 563 |
+
return written, err
|
| 564 |
+
}
|
| 565 |
+
written = append(written, n...)
|
| 566 |
+
}
|
| 567 |
+
return written, nil
|
| 568 |
+
}
|
| 569 |
+
|
| 570 |
+
func copyTree(from, to string) ([]string, error) {
|
| 571 |
+
var out []string
|
| 572 |
+
err := filepath.Walk(from, func(path string, info os.FileInfo, err error) error {
|
| 573 |
+
if err != nil {
|
| 574 |
+
if os.IsNotExist(err) {
|
| 575 |
+
return nil
|
| 576 |
+
}
|
| 577 |
+
return err
|
| 578 |
+
}
|
| 579 |
+
if info.IsDir() {
|
| 580 |
+
return nil
|
| 581 |
+
}
|
| 582 |
+
rel, err := filepath.Rel(from, path)
|
| 583 |
+
if err != nil {
|
| 584 |
+
return err
|
| 585 |
+
}
|
| 586 |
+
buf, err := os.ReadFile(path)
|
| 587 |
+
if err != nil {
|
| 588 |
+
return err
|
| 589 |
+
}
|
| 590 |
+
dest := filepath.Join(to, rel)
|
| 591 |
+
if err := os.MkdirAll(filepath.Dir(dest), 0o750); err != nil {
|
| 592 |
+
return err
|
| 593 |
+
}
|
| 594 |
+
if err := os.WriteFile(dest, buf, 0o640); err != nil {
|
| 595 |
+
return err
|
| 596 |
+
}
|
| 597 |
+
out = append(out, filepath.ToSlash(filepath.Join(filepath.Base(from), rel)))
|
| 598 |
+
return nil
|
| 599 |
+
})
|
| 600 |
+
if os.IsNotExist(err) {
|
| 601 |
+
return out, nil
|
| 602 |
+
}
|
| 603 |
+
return out, err
|
| 604 |
+
}
|
| 605 |
+
|
| 606 |
+
func idOf(rec *store.Record) string {
|
| 607 |
+
if rec == nil {
|
| 608 |
+
return ""
|
| 609 |
+
}
|
| 610 |
+
return rec.ID
|
| 611 |
+
}
|
| 612 |
+
|
| 613 |
+
// newID returns a random 128-bit hex identifier.
|
| 614 |
+
func newID() string {
|
| 615 |
+
var b [16]byte
|
| 616 |
+
if _, err := rand.Read(b[:]); err != nil {
|
| 617 |
+
// crypto/rand failure is not recoverable in any useful way here.
|
| 618 |
+
panic("core: entropy source unavailable")
|
| 619 |
+
}
|
| 620 |
+
return hex.EncodeToString(b[:])
|
| 621 |
+
}
|
| 622 |
+
|
| 623 |
+
// SubmitResult records a benchmark report from a front-end runner.
|
| 624 |
+
func (s *Service) SubmitResult(r store.Result) error {
|
| 625 |
+
return s.store.AppendResult(r)
|
| 626 |
+
}
|
| 627 |
+
|
| 628 |
+
// Erase reports whether an identity is known. There is no personal data to
|
| 629 |
+
// delete: only hashes are stored, so the endpoint is retained for compatibility
|
| 630 |
+
// and answers "nothing to erase" rather than pretending to remove something.
|
| 631 |
+
func (s *Service) Erase(id string) (bool, error) {
|
| 632 |
+
_, known := s.store.Get(id)
|
| 633 |
+
return known, nil
|
| 634 |
+
}
|
| 635 |
+
|
| 636 |
+
// SyncFlush publishes everything queued for the dataset. Used by -sync, by
|
| 637 |
+
// shutdown, and by tests.
|
| 638 |
+
func (s *Service) SyncFlush(ctx context.Context) error {
|
| 639 |
+
if s.sync == nil {
|
| 640 |
+
return nil
|
| 641 |
+
}
|
| 642 |
+
return s.sync.FlushNow(ctx)
|
| 643 |
+
}
|
internal/draw/draw.go
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Package draw turns a validated draw request into a concrete set of examples.
|
| 2 |
+
//
|
| 3 |
+
// Two rules govern selection:
|
| 4 |
+
// 1. A caller may never receive more than DrawMax examples in one draw.
|
| 5 |
+
// 2. Each category gets its share of the budget proportionally; any leftover
|
| 6 |
+
// budget is re-distributed across categories that still have stock. This
|
| 7 |
+
// keeps a single scarce category from starving the others.
|
| 8 |
+
//
|
| 9 |
+
// Every example is handed out at most once per request and is drawn uniformly
|
| 10 |
+
// at random from the still-usable pool, so repeated draws do not follow a
|
| 11 |
+
// predictable order.
|
| 12 |
+
package draw
|
| 13 |
+
|
| 14 |
+
import (
|
| 15 |
+
"crypto/rand"
|
| 16 |
+
"errors"
|
| 17 |
+
"fmt"
|
| 18 |
+
"math/big"
|
| 19 |
+
"sort"
|
| 20 |
+
"strings"
|
| 21 |
+
|
| 22 |
+
"github.com/archnemix/archx-eval/relay/internal/apierr"
|
| 23 |
+
"github.com/archnemix/archx-eval/relay/internal/bank"
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
// Request is a validated draw instruction.
|
| 27 |
+
type Request struct {
|
| 28 |
+
Categories []string
|
| 29 |
+
// Mix optionally pins the split, e.g. map[python]0.6. Empty means
|
| 30 |
+
// "proportional to available stock".
|
| 31 |
+
Mix map[string]float64
|
| 32 |
+
Size int
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
// Result is the outcome of a draw.
|
| 36 |
+
type Result struct {
|
| 37 |
+
Examples []*bank.Example
|
| 38 |
+
ByCat map[string]int
|
| 39 |
+
Shortfall int
|
| 40 |
+
Notes []string
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
// Select performs the draw, returning at most req.Size examples.
|
| 44 |
+
func Select(m *bank.Manager, req Request) (*Result, error) {
|
| 45 |
+
if req.Size <= 0 {
|
| 46 |
+
return nil, apierr.BadRequest("size must be greater than zero")
|
| 47 |
+
}
|
| 48 |
+
if len(req.Categories) == 0 {
|
| 49 |
+
return nil, apierr.BadRequest("at least one category is required")
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
cats, err := resolveCategories(m, req.Categories)
|
| 53 |
+
if err != nil {
|
| 54 |
+
return nil, err
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
// Collect eligible stock per category across all difficulties.
|
| 58 |
+
pools := map[string][]*bank.Example{}
|
| 59 |
+
for _, cat := range cats {
|
| 60 |
+
for _, diff := range bank.Difficulties {
|
| 61 |
+
pools[cat] = append(pools[cat], m.Eligible(cat, diff)...)
|
| 62 |
+
}
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
res := &Result{ByCat: map[string]int{}}
|
| 66 |
+
totalStock := 0
|
| 67 |
+
for _, cat := range cats {
|
| 68 |
+
totalStock += len(pools[cat])
|
| 69 |
+
}
|
| 70 |
+
if totalStock == 0 {
|
| 71 |
+
return nil, apierr.Unavailable("the bank has no usable examples left for the requested categories")
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
// Budget per category, proportional by default.
|
| 75 |
+
desired := map[string]int{}
|
| 76 |
+
remaining := req.Size
|
| 77 |
+
if len(req.Mix) > 0 {
|
| 78 |
+
weightSum := 0.0
|
| 79 |
+
for _, cat := range cats {
|
| 80 |
+
w, ok := req.Mix[cat]
|
| 81 |
+
if !ok {
|
| 82 |
+
continue
|
| 83 |
+
}
|
| 84 |
+
weightSum += w
|
| 85 |
+
}
|
| 86 |
+
if weightSum <= 0 {
|
| 87 |
+
return nil, apierr.BadRequest("mix weights must sum to a positive value")
|
| 88 |
+
}
|
| 89 |
+
for _, cat := range cats {
|
| 90 |
+
w := req.Mix[cat]
|
| 91 |
+
share := int(float64(req.Size) * (w / weightSum))
|
| 92 |
+
desired[cat] = share
|
| 93 |
+
remaining -= share
|
| 94 |
+
}
|
| 95 |
+
} else {
|
| 96 |
+
for _, cat := range cats {
|
| 97 |
+
share := req.Size * len(pools[cat]) / totalStock
|
| 98 |
+
desired[cat] = share
|
| 99 |
+
remaining -= share
|
| 100 |
+
}
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
// Hand out the proportional share first.
|
| 104 |
+
taken := map[string]int{}
|
| 105 |
+
for _, cat := range cats {
|
| 106 |
+
n := desired[cat]
|
| 107 |
+
if n > len(pools[cat]) {
|
| 108 |
+
n = len(pools[cat])
|
| 109 |
+
}
|
| 110 |
+
if n <= 0 {
|
| 111 |
+
continue
|
| 112 |
+
}
|
| 113 |
+
picked := sample(pools[cat], n)
|
| 114 |
+
res.Examples = append(res.Examples, picked...)
|
| 115 |
+
taken[cat] = len(picked)
|
| 116 |
+
remaining -= len(picked) - desired[cat]
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
// Distribute the remainder to any category that still has stock.
|
| 120 |
+
for remaining > 0 {
|
| 121 |
+
progressed := false
|
| 122 |
+
for _, cat := range cats {
|
| 123 |
+
if remaining <= 0 {
|
| 124 |
+
break
|
| 125 |
+
}
|
| 126 |
+
spare := len(pools[cat]) - taken[cat]
|
| 127 |
+
if spare <= 0 {
|
| 128 |
+
continue
|
| 129 |
+
}
|
| 130 |
+
extra := sample(pools[cat][taken[cat]:], 1)
|
| 131 |
+
res.Examples = append(res.Examples, extra...)
|
| 132 |
+
taken[cat]++
|
| 133 |
+
remaining--
|
| 134 |
+
progressed = true
|
| 135 |
+
}
|
| 136 |
+
if !progressed {
|
| 137 |
+
break
|
| 138 |
+
}
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
// Shortfall is derived once, from the truth: what we actually issued.
|
| 142 |
+
if issued := len(res.Examples); issued < req.Size {
|
| 143 |
+
res.Shortfall = req.Size - issued
|
| 144 |
+
res.Notes = append(res.Notes, fmt.Sprintf("served %d of %d requested; limited stock", issued, req.Size))
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
for _, ex := range res.Examples {
|
| 148 |
+
res.ByCat[ex.Category]++
|
| 149 |
+
}
|
| 150 |
+
shuffleExamples(res.Examples)
|
| 151 |
+
return res, nil
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
func resolveCategories(m *bank.Manager, requested []string) ([]string, error) {
|
| 155 |
+
available := map[string]bool{}
|
| 156 |
+
for _, c := range m.Categories() {
|
| 157 |
+
available[c] = true
|
| 158 |
+
}
|
| 159 |
+
seen := map[string]bool{}
|
| 160 |
+
var out []string
|
| 161 |
+
for _, raw := range requested {
|
| 162 |
+
cat := strings.ToLower(strings.TrimSpace(raw))
|
| 163 |
+
if cat == "" || seen[cat] {
|
| 164 |
+
continue
|
| 165 |
+
}
|
| 166 |
+
if !available[cat] {
|
| 167 |
+
return nil, apierr.BadRequest("unknown category: " + cat)
|
| 168 |
+
}
|
| 169 |
+
seen[cat] = true
|
| 170 |
+
out = append(out, cat)
|
| 171 |
+
}
|
| 172 |
+
if len(out) == 0 {
|
| 173 |
+
return nil, apierr.BadRequest("no usable category supplied")
|
| 174 |
+
}
|
| 175 |
+
sort.Strings(out)
|
| 176 |
+
return out, nil
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
// sample returns n distinct elements chosen uniformly at random.
|
| 180 |
+
func sample(pool []*bank.Example, n int) []*bank.Example {
|
| 181 |
+
if n <= 0 || len(pool) == 0 {
|
| 182 |
+
return nil
|
| 183 |
+
}
|
| 184 |
+
if n >= len(pool) {
|
| 185 |
+
out := make([]*bank.Example, len(pool))
|
| 186 |
+
copy(out, pool)
|
| 187 |
+
return out
|
| 188 |
+
}
|
| 189 |
+
// Partial Fisher-Yates: only shuffle the prefix we need.
|
| 190 |
+
tmp := make([]*bank.Example, len(pool))
|
| 191 |
+
copy(tmp, pool)
|
| 192 |
+
for i := 0; i < n; i++ {
|
| 193 |
+
j := i + randIndex(len(tmp)-i)
|
| 194 |
+
tmp[i], tmp[j] = tmp[j], tmp[i]
|
| 195 |
+
}
|
| 196 |
+
return tmp[:n]
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
func shuffleExamples(list []*bank.Example) {
|
| 200 |
+
for i := len(list) - 1; i > 0; i-- {
|
| 201 |
+
j := randIndex(i + 1)
|
| 202 |
+
list[i], list[j] = list[j], list[i]
|
| 203 |
+
}
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
// randIndex returns a cryptographically random int in [0,n) rather than a
|
| 207 |
+
// predictable pseudo-random sequence, so a caller cannot infer draw order.
|
| 208 |
+
func randIndex(n int) int {
|
| 209 |
+
if n <= 1 {
|
| 210 |
+
return 0
|
| 211 |
+
}
|
| 212 |
+
bigN, err := rand.Int(rand.Reader, big.NewInt(int64(n)))
|
| 213 |
+
if err != nil {
|
| 214 |
+
return 0
|
| 215 |
+
}
|
| 216 |
+
return int(bigN.Int64())
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
// Category shares helper for validation of a mix map.
|
| 220 |
+
func ValidateMix(mix map[string]float64) error {
|
| 221 |
+
for cat, w := range mix {
|
| 222 |
+
if w < 0 {
|
| 223 |
+
return errors.New("mix weight for " + cat + " is negative")
|
| 224 |
+
}
|
| 225 |
+
}
|
| 226 |
+
return nil
|
| 227 |
+
}
|
internal/hf/hf.go
ADDED
|
@@ -0,0 +1,611 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Package hf talks to the private Hugging Face dataset that backs this system.
|
| 2 |
+
//
|
| 3 |
+
// The dataset is a *git repository*, which shapes every design decision here:
|
| 4 |
+
//
|
| 5 |
+
// - Writes are sequential. Two commits racing each other produce a rejected
|
| 6 |
+
// push, so all writes must funnel through one controller (see syncctl).
|
| 7 |
+
// - Reads are parallel and cheap, so restoring state at boot downloads files
|
| 8 |
+
// concurrently.
|
| 9 |
+
// - Content is addressed by blob hash. We therefore identify a remote file by
|
| 10 |
+
// its git blob SHA-1, which lets us skip unchanged files with certainty
|
| 11 |
+
// instead of guessing from timestamps.
|
| 12 |
+
// - History is permanent. Anything committed stays in the repository's past
|
| 13 |
+
// for ever, even after it is deleted from the current tree. That is why
|
| 14 |
+
// raw personal values are never published here: only salted hashes are.
|
| 15 |
+
//
|
| 16 |
+
// Two implementations exist: CommitSink targets the real API, DirSink targets a
|
| 17 |
+
// local directory so the controller can be tested without a network.
|
| 18 |
+
package hf
|
| 19 |
+
|
| 20 |
+
import (
|
| 21 |
+
"bytes"
|
| 22 |
+
"context"
|
| 23 |
+
"crypto/sha1"
|
| 24 |
+
"encoding/base64"
|
| 25 |
+
"encoding/hex"
|
| 26 |
+
"encoding/json"
|
| 27 |
+
"fmt"
|
| 28 |
+
"io"
|
| 29 |
+
"io/fs"
|
| 30 |
+
"net/http"
|
| 31 |
+
"net/url"
|
| 32 |
+
"os"
|
| 33 |
+
"path/filepath"
|
| 34 |
+
"sort"
|
| 35 |
+
"strconv"
|
| 36 |
+
"strings"
|
| 37 |
+
"sync"
|
| 38 |
+
"time"
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
// File is one artefact destined for the dataset.
|
| 42 |
+
type File struct {
|
| 43 |
+
Path string // repo-relative, e.g. "identities/ab/abcd.json"
|
| 44 |
+
Content []byte
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
// Version is the content identity of a file: the git blob SHA-1 of its bytes.
|
| 48 |
+
// Hugging Face reports the same value as "oid" when listing a repo tree, so
|
| 49 |
+
// comparing these two numbers tells us exactly whether a file changed.
|
| 50 |
+
func (f File) Version() string { return BlobSHA(f.Content) }
|
| 51 |
+
|
| 52 |
+
// BlobSHA computes the git blob SHA-1 of content, matching the oid the
|
| 53 |
+
// Hugging Face API returns for a stored file.
|
| 54 |
+
func BlobSHA(content []byte) string {
|
| 55 |
+
h := sha1.New()
|
| 56 |
+
fmt.Fprintf(h, "blob %d\x00", len(content))
|
| 57 |
+
h.Write(content)
|
| 58 |
+
return hex.EncodeToString(h.Sum(nil))
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
// RemoteFile describes a file already in the dataset.
|
| 62 |
+
type RemoteFile struct {
|
| 63 |
+
Path string
|
| 64 |
+
Version string // git blob oid, or "" when unknown
|
| 65 |
+
Size int64
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
// Remote is the read/write view of the dataset the controller needs.
|
| 69 |
+
type Remote interface {
|
| 70 |
+
// List returns every file under prefix. An empty prefix means the whole
|
| 71 |
+
// repository.
|
| 72 |
+
List(ctx context.Context, prefix string) ([]RemoteFile, error)
|
| 73 |
+
// Publish creates a single commit containing all files (upserts).
|
| 74 |
+
Publish(ctx context.Context, summary string, files []File) error
|
| 75 |
+
// Download fetches one file's bytes.
|
| 76 |
+
Download(ctx context.Context, path string) ([]byte, error)
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
// ---------------------------------------------------------------------------
|
| 80 |
+
// DirSink: a filesystem stand-in for the dataset.
|
| 81 |
+
// ---------------------------------------------------------------------------
|
| 82 |
+
|
| 83 |
+
// DirSink mirrors the dataset into a local directory. It is used by tests and
|
| 84 |
+
// by CI, which commits the mirror into the repository for auditability.
|
| 85 |
+
type DirSink struct{ Root string }
|
| 86 |
+
|
| 87 |
+
// List walks the directory and reports every file's blob hash.
|
| 88 |
+
func (d *DirSink) List(_ context.Context, prefix string) ([]RemoteFile, error) {
|
| 89 |
+
if d.Root == "" {
|
| 90 |
+
return nil, fmt.Errorf("hf: DirSink has no root")
|
| 91 |
+
}
|
| 92 |
+
base := filepath.Join(d.Root, filepath.FromSlash(prefix))
|
| 93 |
+
var out []RemoteFile
|
| 94 |
+
err := filepath.WalkDir(base, func(p string, e fs.DirEntry, err error) error {
|
| 95 |
+
if err != nil {
|
| 96 |
+
if os.IsNotExist(err) {
|
| 97 |
+
return nil
|
| 98 |
+
}
|
| 99 |
+
return err
|
| 100 |
+
}
|
| 101 |
+
if e.IsDir() {
|
| 102 |
+
return nil
|
| 103 |
+
}
|
| 104 |
+
rel, err := filepath.Rel(d.Root, p)
|
| 105 |
+
if err != nil {
|
| 106 |
+
return err
|
| 107 |
+
}
|
| 108 |
+
buf, err := os.ReadFile(p)
|
| 109 |
+
if err != nil {
|
| 110 |
+
return err
|
| 111 |
+
}
|
| 112 |
+
out = append(out, RemoteFile{
|
| 113 |
+
Path: filepath.ToSlash(rel),
|
| 114 |
+
Version: BlobSHA(buf),
|
| 115 |
+
Size: int64(len(buf)),
|
| 116 |
+
})
|
| 117 |
+
return nil
|
| 118 |
+
})
|
| 119 |
+
if err != nil {
|
| 120 |
+
return nil, err
|
| 121 |
+
}
|
| 122 |
+
sort.Slice(out, func(i, j int) bool { return out[i].Path < out[j].Path })
|
| 123 |
+
return out, nil
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
// Publish writes every file, creating directories as needed.
|
| 127 |
+
func (d *DirSink) Publish(_ context.Context, _ string, files []File) error {
|
| 128 |
+
if d.Root == "" {
|
| 129 |
+
return fmt.Errorf("hf: DirSink has no root")
|
| 130 |
+
}
|
| 131 |
+
for _, f := range files {
|
| 132 |
+
if err := safeJoinCheck(f.Path); err != nil {
|
| 133 |
+
return err
|
| 134 |
+
}
|
| 135 |
+
full := filepath.Join(d.Root, filepath.FromSlash(f.Path))
|
| 136 |
+
if err := os.MkdirAll(filepath.Dir(full), 0o750); err != nil {
|
| 137 |
+
return err
|
| 138 |
+
}
|
| 139 |
+
if err := os.WriteFile(full, f.Content, 0o640); err != nil {
|
| 140 |
+
return err
|
| 141 |
+
}
|
| 142 |
+
}
|
| 143 |
+
return nil
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
// Download reads one file from the mirror.
|
| 147 |
+
func (d *DirSink) Download(_ context.Context, path string) ([]byte, error) {
|
| 148 |
+
if err := safeJoinCheck(path); err != nil {
|
| 149 |
+
return nil, err
|
| 150 |
+
}
|
| 151 |
+
return os.ReadFile(filepath.Join(d.Root, filepath.FromSlash(path)))
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
// ---------------------------------------------------------------------------
|
| 155 |
+
// CommitSink: the real dataset API.
|
| 156 |
+
// ---------------------------------------------------------------------------
|
| 157 |
+
|
| 158 |
+
// CommitSink publishes through the Hugging Face dataset API.
|
| 159 |
+
type CommitSink struct {
|
| 160 |
+
Repo string
|
| 161 |
+
Token string
|
| 162 |
+
BaseURL string
|
| 163 |
+
Branch string
|
| 164 |
+
Client *http.Client
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
// NewCommitSink builds a sink, defaulting to the public endpoint.
|
| 168 |
+
func NewCommitSink(repo, token, baseURL, branch string) *CommitSink {
|
| 169 |
+
if baseURL == "" {
|
| 170 |
+
baseURL = "https://huggingface.co"
|
| 171 |
+
}
|
| 172 |
+
if branch == "" {
|
| 173 |
+
branch = "main"
|
| 174 |
+
}
|
| 175 |
+
return &CommitSink{
|
| 176 |
+
Repo: repo,
|
| 177 |
+
Token: token,
|
| 178 |
+
BaseURL: strings.TrimRight(baseURL, "/"),
|
| 179 |
+
Branch: branch,
|
| 180 |
+
Client: &http.Client{Timeout: 60 * time.Second},
|
| 181 |
+
}
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
type commitFile struct {
|
| 185 |
+
Path string `json:"path"`
|
| 186 |
+
Content string `json:"content"`
|
| 187 |
+
Encoding string `json:"encoding"`
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
type commitRequest struct {
|
| 191 |
+
Summary string `json:"summary"`
|
| 192 |
+
Files []commitFile `json:"files"`
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
// Publish sends all files in one commit.
|
| 196 |
+
func (c *CommitSink) Publish(ctx context.Context, summary string, files []File) error {
|
| 197 |
+
if c.Repo == "" || c.Token == "" {
|
| 198 |
+
return fmt.Errorf("hf: dataset repo and token are both required")
|
| 199 |
+
}
|
| 200 |
+
if len(files) == 0 {
|
| 201 |
+
return nil
|
| 202 |
+
}
|
| 203 |
+
body := commitRequest{Summary: summary, Files: make([]commitFile, 0, len(files))}
|
| 204 |
+
for _, f := range files {
|
| 205 |
+
if err := safeJoinCheck(f.Path); err != nil {
|
| 206 |
+
return err
|
| 207 |
+
}
|
| 208 |
+
body.Files = append(body.Files, commitFile{
|
| 209 |
+
Path: f.Path,
|
| 210 |
+
Content: base64.StdEncoding.EncodeToString(f.Content),
|
| 211 |
+
Encoding: "base64",
|
| 212 |
+
})
|
| 213 |
+
}
|
| 214 |
+
buf, err := json.Marshal(body)
|
| 215 |
+
if err != nil {
|
| 216 |
+
return err
|
| 217 |
+
}
|
| 218 |
+
url := fmt.Sprintf("%s/api/datasets/%s/commit/%s", c.BaseURL, c.Repo, c.Branch)
|
| 219 |
+
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(buf))
|
| 220 |
+
if err != nil {
|
| 221 |
+
return err
|
| 222 |
+
}
|
| 223 |
+
req.Header.Set("Authorization", "Bearer "+c.Token)
|
| 224 |
+
req.Header.Set("Content-Type", "application/json")
|
| 225 |
+
|
| 226 |
+
resp, err := c.Client.Do(req)
|
| 227 |
+
if err != nil {
|
| 228 |
+
return fmt.Errorf("hf: commit request failed: %w", err)
|
| 229 |
+
}
|
| 230 |
+
defer resp.Body.Close()
|
| 231 |
+
if resp.StatusCode >= 300 {
|
| 232 |
+
snippet, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
|
| 233 |
+
return &APIError{
|
| 234 |
+
Status: resp.StatusCode,
|
| 235 |
+
RetryAfter: parseRetryAfter(resp.Header.Get("Retry-After")),
|
| 236 |
+
Message: fmt.Sprintf("commit failed: %s: %s", resp.Status, strings.TrimSpace(string(snippet))),
|
| 237 |
+
}
|
| 238 |
+
}
|
| 239 |
+
return nil
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
// List reads the repository tree under prefix. Reads are safe to run in
|
| 243 |
+
// parallel with each other, which is what the restore path relies on.
|
| 244 |
+
func (c *CommitSink) List(ctx context.Context, prefix string) ([]RemoteFile, error) {
|
| 245 |
+
if c.Repo == "" {
|
| 246 |
+
return nil, fmt.Errorf("hf: dataset repo is required")
|
| 247 |
+
}
|
| 248 |
+
var out []RemoteFile
|
| 249 |
+
next := ""
|
| 250 |
+
for page := 0; page < 200; page++ {
|
| 251 |
+
q := url.Values{}
|
| 252 |
+
q.Set("recursive", "true")
|
| 253 |
+
q.Set("expand", "false")
|
| 254 |
+
if prefix != "" {
|
| 255 |
+
q.Set("path", prefix)
|
| 256 |
+
}
|
| 257 |
+
if next != "" {
|
| 258 |
+
q.Set("cursor", next)
|
| 259 |
+
}
|
| 260 |
+
endpoint := fmt.Sprintf("%s/api/datasets/%s/tree/%s?%s",
|
| 261 |
+
c.BaseURL, c.Repo, c.Branch, q.Encode())
|
| 262 |
+
|
| 263 |
+
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
|
| 264 |
+
if err != nil {
|
| 265 |
+
return nil, err
|
| 266 |
+
}
|
| 267 |
+
c.auth(req)
|
| 268 |
+
resp, err := c.Client.Do(req)
|
| 269 |
+
if err != nil {
|
| 270 |
+
return nil, fmt.Errorf("hf: list request failed: %w", err)
|
| 271 |
+
}
|
| 272 |
+
body, err := io.ReadAll(io.LimitReader(resp.Body, 16<<20))
|
| 273 |
+
resp.Body.Close()
|
| 274 |
+
if err != nil {
|
| 275 |
+
return nil, err
|
| 276 |
+
}
|
| 277 |
+
if resp.StatusCode == http.StatusNotFound {
|
| 278 |
+
// An empty repository has no tree yet.
|
| 279 |
+
return out, nil
|
| 280 |
+
}
|
| 281 |
+
if resp.StatusCode >= 300 {
|
| 282 |
+
return nil, &APIError{
|
| 283 |
+
Status: resp.StatusCode,
|
| 284 |
+
RetryAfter: parseRetryAfter(resp.Header.Get("Retry-After")),
|
| 285 |
+
Message: fmt.Sprintf("list failed: %s: %s", resp.Status, truncate(string(body), 300)),
|
| 286 |
+
}
|
| 287 |
+
}
|
| 288 |
+
|
| 289 |
+
var entries []struct {
|
| 290 |
+
Type string `json:"type"`
|
| 291 |
+
Path string `json:"path"`
|
| 292 |
+
Size int64 `json:"size"`
|
| 293 |
+
OID string `json:"oid"`
|
| 294 |
+
LFS *struct {
|
| 295 |
+
OID string `json:"oid"`
|
| 296 |
+
} `json:"lfs"`
|
| 297 |
+
}
|
| 298 |
+
if err := json.Unmarshal(body, &entries); err != nil {
|
| 299 |
+
return nil, fmt.Errorf("hf: parse tree: %w", err)
|
| 300 |
+
}
|
| 301 |
+
for _, e := range entries {
|
| 302 |
+
if e.Type != "file" {
|
| 303 |
+
continue
|
| 304 |
+
}
|
| 305 |
+
version := e.OID
|
| 306 |
+
if e.LFS != nil && e.LFS.OID != "" {
|
| 307 |
+
version = e.LFS.OID // large files are stored by LFS pointer
|
| 308 |
+
}
|
| 309 |
+
out = append(out, RemoteFile{Path: e.Path, Version: version, Size: e.Size})
|
| 310 |
+
}
|
| 311 |
+
|
| 312 |
+
next = nextCursor(resp.Header.Get("Link"))
|
| 313 |
+
if next == "" {
|
| 314 |
+
break
|
| 315 |
+
}
|
| 316 |
+
}
|
| 317 |
+
sort.Slice(out, func(i, j int) bool { return out[i].Path < out[j].Path })
|
| 318 |
+
return out, nil
|
| 319 |
+
}
|
| 320 |
+
|
| 321 |
+
// Download fetches a single file's raw bytes.
|
| 322 |
+
func (c *CommitSink) Download(ctx context.Context, path string) ([]byte, error) {
|
| 323 |
+
if err := safeJoinCheck(path); err != nil {
|
| 324 |
+
return nil, err
|
| 325 |
+
}
|
| 326 |
+
if c.Repo == "" {
|
| 327 |
+
return nil, fmt.Errorf("hf: dataset repo is required")
|
| 328 |
+
}
|
| 329 |
+
endpoint := fmt.Sprintf("%s/datasets/%s/resolve/%s/%s",
|
| 330 |
+
c.BaseURL, c.Repo, c.Branch, strings.TrimPrefix(path, "/"))
|
| 331 |
+
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
|
| 332 |
+
if err != nil {
|
| 333 |
+
return nil, err
|
| 334 |
+
}
|
| 335 |
+
c.auth(req)
|
| 336 |
+
resp, err := c.Client.Do(req)
|
| 337 |
+
if err != nil {
|
| 338 |
+
return nil, fmt.Errorf("hf: download failed: %w", err)
|
| 339 |
+
}
|
| 340 |
+
defer resp.Body.Close()
|
| 341 |
+
if resp.StatusCode >= 300 {
|
| 342 |
+
body, _ := io.ReadAll(io.LimitReader(resp.Body, 300))
|
| 343 |
+
return nil, &APIError{
|
| 344 |
+
Status: resp.StatusCode,
|
| 345 |
+
RetryAfter: parseRetryAfter(resp.Header.Get("Retry-After")),
|
| 346 |
+
Message: fmt.Sprintf("download %s failed: %s: %s", path, resp.Status, truncate(string(body), 200)),
|
| 347 |
+
}
|
| 348 |
+
}
|
| 349 |
+
return io.ReadAll(io.LimitReader(resp.Body, 64<<20))
|
| 350 |
+
}
|
| 351 |
+
|
| 352 |
+
// Ping verifies the token can see the dataset. It reads nothing sensitive and
|
| 353 |
+
// returns a message safe to log.
|
| 354 |
+
func (c *CommitSink) Ping(ctx context.Context) error {
|
| 355 |
+
if c.Repo == "" || c.Token == "" {
|
| 356 |
+
return fmt.Errorf("hf: dataset repo and token are both required")
|
| 357 |
+
}
|
| 358 |
+
endpoint := fmt.Sprintf("%s/api/datasets/%s", c.BaseURL, c.Repo)
|
| 359 |
+
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
|
| 360 |
+
if err != nil {
|
| 361 |
+
return err
|
| 362 |
+
}
|
| 363 |
+
c.auth(req)
|
| 364 |
+
resp, err := c.Client.Do(req)
|
| 365 |
+
if err != nil {
|
| 366 |
+
return fmt.Errorf("hf: cannot reach the dataset: %w", err)
|
| 367 |
+
}
|
| 368 |
+
defer resp.Body.Close()
|
| 369 |
+
switch {
|
| 370 |
+
case resp.StatusCode == http.StatusOK:
|
| 371 |
+
return nil
|
| 372 |
+
case resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden:
|
| 373 |
+
return fmt.Errorf("hf: token is not authorised for %s (status %d)", c.Repo, resp.StatusCode)
|
| 374 |
+
case resp.StatusCode == http.StatusNotFound:
|
| 375 |
+
return fmt.Errorf("hf: dataset %s not found; check the repo id and that the token can see it", c.Repo)
|
| 376 |
+
default:
|
| 377 |
+
return fmt.Errorf("hf: unexpected status %d from %s", resp.StatusCode, c.Repo)
|
| 378 |
+
}
|
| 379 |
+
}
|
| 380 |
+
|
| 381 |
+
func (c *CommitSink) auth(req *http.Request) {
|
| 382 |
+
if c.Token != "" {
|
| 383 |
+
req.Header.Set("Authorization", "Bearer "+c.Token)
|
| 384 |
+
}
|
| 385 |
+
}
|
| 386 |
+
|
| 387 |
+
// APIError carries the HTTP status so the controller can decide whether a
|
| 388 |
+
// failure is worth retrying.
|
| 389 |
+
type APIError struct {
|
| 390 |
+
Status int
|
| 391 |
+
RetryAfter time.Duration
|
| 392 |
+
Message string
|
| 393 |
+
}
|
| 394 |
+
|
| 395 |
+
func (e *APIError) Error() string { return "hf: " + e.Message }
|
| 396 |
+
|
| 397 |
+
// Retryable reports whether retrying could plausibly succeed.
|
| 398 |
+
func (e *APIError) Retryable() bool {
|
| 399 |
+
switch e.Status {
|
| 400 |
+
case http.StatusTooManyRequests, http.StatusBadGateway, http.StatusServiceUnavailable,
|
| 401 |
+
http.StatusGatewayTimeout, http.StatusInternalServerError:
|
| 402 |
+
return true
|
| 403 |
+
}
|
| 404 |
+
return false
|
| 405 |
+
}
|
| 406 |
+
|
| 407 |
+
func parseRetryAfter(v string) time.Duration {
|
| 408 |
+
if v == "" {
|
| 409 |
+
return 0
|
| 410 |
+
}
|
| 411 |
+
if secs, err := strconv.Atoi(strings.TrimSpace(v)); err == nil && secs > 0 {
|
| 412 |
+
return time.Duration(secs) * time.Second
|
| 413 |
+
}
|
| 414 |
+
return 0
|
| 415 |
+
}
|
| 416 |
+
|
| 417 |
+
// nextCursor extracts the cursor from an RFC 5988 Link header.
|
| 418 |
+
func nextCursor(link string) string {
|
| 419 |
+
if link == "" {
|
| 420 |
+
return ""
|
| 421 |
+
}
|
| 422 |
+
for _, part := range strings.Split(link, ",") {
|
| 423 |
+
part = strings.TrimSpace(part)
|
| 424 |
+
if !strings.Contains(part, `rel="next"`) {
|
| 425 |
+
continue
|
| 426 |
+
}
|
| 427 |
+
start := strings.Index(part, "<")
|
| 428 |
+
end := strings.Index(part, ">")
|
| 429 |
+
if start < 0 || end <= start {
|
| 430 |
+
continue
|
| 431 |
+
}
|
| 432 |
+
u, err := url.Parse(part[start+1 : end])
|
| 433 |
+
if err != nil {
|
| 434 |
+
continue
|
| 435 |
+
}
|
| 436 |
+
return u.Query().Get("cursor")
|
| 437 |
+
}
|
| 438 |
+
return ""
|
| 439 |
+
}
|
| 440 |
+
|
| 441 |
+
// Collect walks a local directory and returns its files as artefacts.
|
| 442 |
+
func Collect(root string, limit int) ([]File, error) {
|
| 443 |
+
var out []File
|
| 444 |
+
err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
|
| 445 |
+
if err != nil {
|
| 446 |
+
if os.IsNotExist(err) {
|
| 447 |
+
return nil
|
| 448 |
+
}
|
| 449 |
+
return err
|
| 450 |
+
}
|
| 451 |
+
if d.IsDir() {
|
| 452 |
+
if strings.HasPrefix(d.Name(), ".") && path != root {
|
| 453 |
+
return fs.SkipDir
|
| 454 |
+
}
|
| 455 |
+
return nil
|
| 456 |
+
}
|
| 457 |
+
if limit > 0 && len(out) >= limit {
|
| 458 |
+
return fs.SkipAll
|
| 459 |
+
}
|
| 460 |
+
rel, err := filepath.Rel(root, path)
|
| 461 |
+
if err != nil {
|
| 462 |
+
return err
|
| 463 |
+
}
|
| 464 |
+
buf, err := os.ReadFile(path)
|
| 465 |
+
if err != nil {
|
| 466 |
+
return err
|
| 467 |
+
}
|
| 468 |
+
out = append(out, File{Path: filepath.ToSlash(rel), Content: buf})
|
| 469 |
+
return nil
|
| 470 |
+
})
|
| 471 |
+
if err != nil {
|
| 472 |
+
return nil, err
|
| 473 |
+
}
|
| 474 |
+
sort.Slice(out, func(i, j int) bool { return out[i].Path < out[j].Path })
|
| 475 |
+
return out, nil
|
| 476 |
+
}
|
| 477 |
+
|
| 478 |
+
// safeJoinCheck rejects paths that could escape the dataset root.
|
| 479 |
+
func safeJoinCheck(p string) error {
|
| 480 |
+
if p == "" {
|
| 481 |
+
return fmt.Errorf("hf: empty path")
|
| 482 |
+
}
|
| 483 |
+
clean := filepath.ToSlash(filepath.Clean(p))
|
| 484 |
+
if strings.HasPrefix(clean, "../") || strings.HasPrefix(clean, "/") ||
|
| 485 |
+
strings.Contains(clean, "/../") || clean == ".." {
|
| 486 |
+
return fmt.Errorf("hf: unsafe path %q", p)
|
| 487 |
+
}
|
| 488 |
+
return nil
|
| 489 |
+
}
|
| 490 |
+
|
| 491 |
+
func truncate(s string, n int) string {
|
| 492 |
+
if len(s) <= n {
|
| 493 |
+
return s
|
| 494 |
+
}
|
| 495 |
+
return s[:n] + "..."
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
// Downloader fetches a set of files concurrently. Reads are independent, so
|
| 499 |
+
// parallelism is safe here even though writes are not.
|
| 500 |
+
type Downloader struct {
|
| 501 |
+
Remote Remote
|
| 502 |
+
Concurrency int
|
| 503 |
+
|
| 504 |
+
// Prefix, when set, is stripped from every remote path before it is joined
|
| 505 |
+
// onto destRoot. It exists because callers ask for a subtree ("bank/") but
|
| 506 |
+
// want its *contents* placed directly in the destination directory.
|
| 507 |
+
Prefix string
|
| 508 |
+
}
|
| 509 |
+
|
| 510 |
+
// trimPrefixPath strips a leading subtree from a remote path. It returns false
|
| 511 |
+
// when the path names the prefix directory itself or a sibling of it, which the
|
| 512 |
+
// caller must skip rather than write outside its destination.
|
| 513 |
+
func trimPrefixPath(path, prefix string) (string, bool) {
|
| 514 |
+
if prefix == "" {
|
| 515 |
+
return path, true
|
| 516 |
+
}
|
| 517 |
+
want := strings.Trim(prefix, "/") + "/"
|
| 518 |
+
if !strings.HasPrefix(path, want) {
|
| 519 |
+
return "", false
|
| 520 |
+
}
|
| 521 |
+
rel := strings.TrimPrefix(path, want)
|
| 522 |
+
if rel == "" {
|
| 523 |
+
return "", false
|
| 524 |
+
}
|
| 525 |
+
return rel, true
|
| 526 |
+
}
|
| 527 |
+
|
| 528 |
+
// DownloadAll fetches paths into destRoot, preserving relative paths. It
|
| 529 |
+
// returns the number of files written. A missing file is skipped, not fatal,
|
| 530 |
+
// because the dataset legitimately lacks files that have never been written.
|
| 531 |
+
func (d Downloader) DownloadAll(ctx context.Context, destRoot string, paths []string) (int, error) {
|
| 532 |
+
n := d.Concurrency
|
| 533 |
+
if n <= 0 {
|
| 534 |
+
n = 8
|
| 535 |
+
}
|
| 536 |
+
if n > 32 {
|
| 537 |
+
n = 32
|
| 538 |
+
}
|
| 539 |
+
|
| 540 |
+
ctx, cancel := context.WithCancel(ctx)
|
| 541 |
+
defer cancel()
|
| 542 |
+
|
| 543 |
+
jobs := make(chan string)
|
| 544 |
+
var (
|
| 545 |
+
wg sync.WaitGroup
|
| 546 |
+
mu sync.Mutex
|
| 547 |
+
written int
|
| 548 |
+
firstErr error
|
| 549 |
+
)
|
| 550 |
+
for i := 0; i < n; i++ {
|
| 551 |
+
wg.Add(1)
|
| 552 |
+
go func() {
|
| 553 |
+
defer wg.Done()
|
| 554 |
+
for p := range jobs {
|
| 555 |
+
buf, err := d.Remote.Download(ctx, p)
|
| 556 |
+
if err != nil {
|
| 557 |
+
if apiErr, ok := err.(*APIError); ok && apiErr.Status == http.StatusNotFound {
|
| 558 |
+
continue
|
| 559 |
+
}
|
| 560 |
+
mu.Lock()
|
| 561 |
+
if firstErr == nil {
|
| 562 |
+
firstErr = err
|
| 563 |
+
cancel()
|
| 564 |
+
}
|
| 565 |
+
mu.Unlock()
|
| 566 |
+
continue
|
| 567 |
+
}
|
| 568 |
+
rel, ok := trimPrefixPath(p, d.Prefix)
|
| 569 |
+
if !ok || safeJoinCheck(rel) != nil {
|
| 570 |
+
continue
|
| 571 |
+
}
|
| 572 |
+
dst := filepath.Join(destRoot, filepath.FromSlash(rel))
|
| 573 |
+
if err := os.MkdirAll(filepath.Dir(dst), 0o750); err != nil {
|
| 574 |
+
mu.Lock()
|
| 575 |
+
if firstErr == nil {
|
| 576 |
+
firstErr = err
|
| 577 |
+
cancel()
|
| 578 |
+
}
|
| 579 |
+
mu.Unlock()
|
| 580 |
+
continue
|
| 581 |
+
}
|
| 582 |
+
if err := os.WriteFile(dst, buf, 0o640); err != nil {
|
| 583 |
+
mu.Lock()
|
| 584 |
+
if firstErr == nil {
|
| 585 |
+
firstErr = err
|
| 586 |
+
cancel()
|
| 587 |
+
}
|
| 588 |
+
mu.Unlock()
|
| 589 |
+
continue
|
| 590 |
+
}
|
| 591 |
+
mu.Lock()
|
| 592 |
+
written++
|
| 593 |
+
mu.Unlock()
|
| 594 |
+
}
|
| 595 |
+
}()
|
| 596 |
+
}
|
| 597 |
+
|
| 598 |
+
go func() {
|
| 599 |
+
defer close(jobs)
|
| 600 |
+
for _, p := range paths {
|
| 601 |
+
select {
|
| 602 |
+
case <-ctx.Done():
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package httpapi
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"crypto/rand"
|
| 5 |
+
"encoding/hex"
|
| 6 |
+
"net/http"
|
| 7 |
+
"net/netip"
|
| 8 |
+
"strings"
|
| 9 |
+
"time"
|
| 10 |
+
|
| 11 |
+
"github.com/archnemix/archx-eval/relay/internal/apierr"
|
| 12 |
+
"github.com/archnemix/archx-eval/relay/internal/bank"
|
| 13 |
+
"github.com/archnemix/archx-eval/relay/internal/core"
|
| 14 |
+
"github.com/archnemix/archx-eval/relay/internal/identity"
|
| 15 |
+
"github.com/archnemix/archx-eval/relay/internal/store"
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
// drawRequest is the public request body. Device facts are grouped so the
|
| 19 |
+
// runner can send them verbatim from its probe.
|
| 20 |
+
type drawRequest struct {
|
| 21 |
+
RequestID string `json:"request_id"`
|
| 22 |
+
Categories []string `json:"categories"`
|
| 23 |
+
Mix map[string]float64 `json:"mix,omitempty"`
|
| 24 |
+
Size int `json:"size"`
|
| 25 |
+
Device devicePayload `json:"device"`
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
type devicePayload struct {
|
| 29 |
+
MachineID string `json:"machine_id"`
|
| 30 |
+
DiskUUID string `json:"disk_uuid"`
|
| 31 |
+
OSFamily string `json:"os_family"`
|
| 32 |
+
Arch string `json:"arch"`
|
| 33 |
+
RunnerVer string `json:"runner_version"`
|
| 34 |
+
PythonVer string `json:"python_version"`
|
| 35 |
+
DeviceClass string `json:"device_class"`
|
| 36 |
+
DMIProduct string `json:"dmi_product"`
|
| 37 |
+
Hypervisor bool `json:"hypervisor"`
|
| 38 |
+
ClockSkewS float64 `json:"clock_skew_s"`
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
|
| 42 |
+
if r.URL.Path != "/" {
|
| 43 |
+
writeError(w, apierr.NotFound("no such endpoint"))
|
| 44 |
+
return
|
| 45 |
+
}
|
| 46 |
+
writeJSON(w, 200, map[string]any{
|
| 47 |
+
"service": "archx-eval relay",
|
| 48 |
+
"version": core.Version,
|
| 49 |
+
"endpoints": []string{
|
| 50 |
+
"GET /health",
|
| 51 |
+
"GET /v1/categories",
|
| 52 |
+
"POST /v1/draw",
|
| 53 |
+
"POST /v1/feedback",
|
| 54 |
+
},
|
| 55 |
+
"limits": map[string]any{
|
| 56 |
+
"max_draw": s.cfg.DrawMax,
|
| 57 |
+
"window": s.cfg.Window.String(),
|
| 58 |
+
"stale_after": s.cfg.StaleAfterUses,
|
| 59 |
+
},
|
| 60 |
+
})
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
|
| 64 |
+
h := s.svc.Health()
|
| 65 |
+
status := 200
|
| 66 |
+
if !h.OK {
|
| 67 |
+
status = 503
|
| 68 |
+
}
|
| 69 |
+
writeJSON(w, status, h)
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
func (s *Server) handleCategories(w http.ResponseWriter, r *http.Request) {
|
| 73 |
+
writeJSON(w, 200, map[string]any{"categories": s.svc.Categories()})
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
func (s *Server) handleDraw(w http.ResponseWriter, r *http.Request) {
|
| 77 |
+
// Closed loop: every draw must be attributable to a registered runner.
|
| 78 |
+
if err := s.svc.Authenticate(bearerToken(r)); err != nil {
|
| 79 |
+
writeError(w, err)
|
| 80 |
+
return
|
| 81 |
+
}
|
| 82 |
+
var req drawRequest
|
| 83 |
+
if err := decodeJSON(r, &req); err != nil {
|
| 84 |
+
writeError(w, err)
|
| 85 |
+
return
|
| 86 |
+
}
|
| 87 |
+
for _, c := range req.Categories {
|
| 88 |
+
if hasControlChars(c) {
|
| 89 |
+
writeError(w, apierr.BadRequest("category names may not contain control characters"))
|
| 90 |
+
return
|
| 91 |
+
}
|
| 92 |
+
}
|
| 93 |
+
reqID := r.Header.Get("X-Request-Id")
|
| 94 |
+
if req.RequestID != "" {
|
| 95 |
+
reqID = req.RequestID
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
remote := remoteAddrOf(r)
|
| 99 |
+
in := core.DrawInput{
|
| 100 |
+
RequestID: reqID,
|
| 101 |
+
Categories: req.Categories,
|
| 102 |
+
Mix: req.Mix,
|
| 103 |
+
Size: req.Size,
|
| 104 |
+
Device: identity.Device{
|
| 105 |
+
MachineID: req.Device.MachineID,
|
| 106 |
+
DiskUUID: req.Device.DiskUUID,
|
| 107 |
+
OSFamily: strings.ToLower(strings.TrimSpace(req.Device.OSFamily)),
|
| 108 |
+
Arch: strings.ToLower(strings.TrimSpace(req.Device.Arch)),
|
| 109 |
+
RunnerVer: req.Device.RunnerVer,
|
| 110 |
+
PythonVer: req.Device.PythonVer,
|
| 111 |
+
DeviceClass: req.Device.DeviceClass,
|
| 112 |
+
DMIProduct: req.Device.DMIProduct,
|
| 113 |
+
Hypervisor: req.Device.Hypervisor,
|
| 114 |
+
ClockSkewS: req.Device.ClockSkewS,
|
| 115 |
+
},
|
| 116 |
+
RemoteAddr: remote,
|
| 117 |
+
Headers: collectHeaders(r),
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
grant, err := s.svc.RequestDraw(r.Context(), in)
|
| 121 |
+
if err != nil {
|
| 122 |
+
s.logDeny(reqID, err)
|
| 123 |
+
writeError(w, err)
|
| 124 |
+
return
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
payload := make([]map[string]any, 0, len(grant.Examples))
|
| 128 |
+
for _, ex := range grant.Examples {
|
| 129 |
+
payload = append(payload, renderExample(ex))
|
| 130 |
+
}
|
| 131 |
+
writeJSON(w, 200, map[string]any{
|
| 132 |
+
"request_id": grant.RequestID,
|
| 133 |
+
"identity_id": grant.IdentityID,
|
| 134 |
+
"issued_at": grant.IssuedAt,
|
| 135 |
+
"next_draw_at": grant.NextDrawAt,
|
| 136 |
+
"count": len(grant.Examples),
|
| 137 |
+
"by_category": grant.ByCat,
|
| 138 |
+
"shortfall": grant.Shortfall,
|
| 139 |
+
"notes": grant.Notes,
|
| 140 |
+
"examples": payload,
|
| 141 |
+
})
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
// renderExample strips everything the caller must not see: reference solutions,
|
| 145 |
+
// test bodies, expected answers and provenance notes.
|
| 146 |
+
func renderExample(ex *bank.Example) map[string]any {
|
| 147 |
+
out := map[string]any{
|
| 148 |
+
"id": ex.ID,
|
| 149 |
+
"category": ex.Category,
|
| 150 |
+
"difficulty": ex.Difficulty,
|
| 151 |
+
"kind": ex.Kind,
|
| 152 |
+
"prompt": ex.Prompt,
|
| 153 |
+
}
|
| 154 |
+
if ex.Context != "" {
|
| 155 |
+
out["context"] = ex.Context
|
| 156 |
+
}
|
| 157 |
+
if ex.Language != "" {
|
| 158 |
+
out["language"] = ex.Language
|
| 159 |
+
}
|
| 160 |
+
if ex.Entrypoint != "" {
|
| 161 |
+
out["entrypoint"] = ex.Entrypoint
|
| 162 |
+
}
|
| 163 |
+
if ex.Starter != "" {
|
| 164 |
+
out["starter_code"] = ex.Starter
|
| 165 |
+
}
|
| 166 |
+
if len(ex.Tags) > 0 {
|
| 167 |
+
out["tags"] = ex.Tags
|
| 168 |
+
}
|
| 169 |
+
return out
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
func (s *Server) handleFeedback(w http.ResponseWriter, r *http.Request) {
|
| 173 |
+
var body struct {
|
| 174 |
+
RequestID string `json:"request_id"`
|
| 175 |
+
IdentityID string `json:"identity_id"`
|
| 176 |
+
ModelID string `json:"model_id"`
|
| 177 |
+
RunnerVer string `json:"runner_version"`
|
| 178 |
+
OS string `json:"os"`
|
| 179 |
+
Arch string `json:"arch"`
|
| 180 |
+
DurationS float64 `json:"duration_s"`
|
| 181 |
+
Items []feedbackItem `json:"items"`
|
| 182 |
+
}
|
| 183 |
+
if err := decodeJSON(r, &body); err != nil {
|
| 184 |
+
writeError(w, err)
|
| 185 |
+
return
|
| 186 |
+
}
|
| 187 |
+
if strings.TrimSpace(body.ModelID) == "" {
|
| 188 |
+
writeError(w, apierr.BadRequest("model_id is required"))
|
| 189 |
+
return
|
| 190 |
+
}
|
| 191 |
+
if len(body.Items) == 0 {
|
| 192 |
+
writeError(w, apierr.BadRequest("items may not be empty"))
|
| 193 |
+
return
|
| 194 |
+
}
|
| 195 |
+
if len(body.Items) > 500 {
|
| 196 |
+
writeError(w, apierr.BadRequest("at most 500 items may be reported at once"))
|
| 197 |
+
return
|
| 198 |
+
}
|
| 199 |
+
if err := validateFeedbackText(body); err != nil {
|
| 200 |
+
writeError(w, err)
|
| 201 |
+
return
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
res := store.Result{
|
| 205 |
+
TS: time.Now().UTC(),
|
| 206 |
+
RequestID: body.RequestID,
|
| 207 |
+
IdentityID: body.IdentityID,
|
| 208 |
+
ModelID: body.ModelID,
|
| 209 |
+
RunnerVer: body.RunnerVer,
|
| 210 |
+
OS: body.OS,
|
| 211 |
+
Arch: body.Arch,
|
| 212 |
+
Summary: store.ResultSummary{
|
| 213 |
+
Total: len(body.Items),
|
| 214 |
+
ByCat: map[string]float64{},
|
| 215 |
+
DurationS: body.DurationS,
|
| 216 |
+
},
|
| 217 |
+
}
|
| 218 |
+
var scoreSum float64
|
| 219 |
+
catSum := map[string]float64{}
|
| 220 |
+
catN := map[string]int{}
|
| 221 |
+
for _, it := range body.Items {
|
| 222 |
+
if strings.TrimSpace(it.ExampleID) == "" {
|
| 223 |
+
writeError(w, apierr.BadRequest("every item needs an example_id"))
|
| 224 |
+
return
|
| 225 |
+
}
|
| 226 |
+
res.Items = append(res.Items, store.ResultItem{
|
| 227 |
+
ExampleID: it.ExampleID,
|
| 228 |
+
Category: it.Category,
|
| 229 |
+
Difficulty: it.Difficulty,
|
| 230 |
+
Answer: it.Answer,
|
| 231 |
+
Code: it.Code,
|
| 232 |
+
Passed: it.Passed,
|
| 233 |
+
Score: clamp01(it.Score),
|
| 234 |
+
LatencyMS: it.LatencyMS,
|
| 235 |
+
Error: it.Error,
|
| 236 |
+
})
|
| 237 |
+
if it.Passed {
|
| 238 |
+
res.Summary.Passed++
|
| 239 |
+
}
|
| 240 |
+
scoreSum += clamp01(it.Score)
|
| 241 |
+
catSum[it.Category] += clamp01(it.Score)
|
| 242 |
+
catN[it.Category]++
|
| 243 |
+
}
|
| 244 |
+
res.Summary.Score = scoreSum / float64(len(res.Items))
|
| 245 |
+
for cat, sum := range catSum {
|
| 246 |
+
if catN[cat] > 0 {
|
| 247 |
+
res.Summary.ByCat[cat] = sum / float64(catN[cat])
|
| 248 |
+
}
|
| 249 |
+
}
|
| 250 |
+
if err := s.svc.SubmitResult(res); err != nil {
|
| 251 |
+
writeError(w, apierr.Internal("could not record results"))
|
| 252 |
+
return
|
| 253 |
+
}
|
| 254 |
+
writeJSON(w, 200, map[string]any{
|
| 255 |
+
"accepted": true,
|
| 256 |
+
"summary": res.Summary,
|
| 257 |
+
})
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
type feedbackItem struct {
|
| 261 |
+
ExampleID string `json:"example_id"`
|
| 262 |
+
Category string `json:"category"`
|
| 263 |
+
Difficulty string `json:"difficulty"`
|
| 264 |
+
Answer string `json:"answer"`
|
| 265 |
+
Code string `json:"code"`
|
| 266 |
+
Passed bool `json:"passed"`
|
| 267 |
+
Score float64 `json:"score"`
|
| 268 |
+
LatencyMS int `json:"latency_ms"`
|
| 269 |
+
Error string `json:"error"`
|
| 270 |
+
}
|
| 271 |
+
|
| 272 |
+
func clamp01(f float64) float64 {
|
| 273 |
+
if f < 0 {
|
| 274 |
+
return 0
|
| 275 |
+
}
|
| 276 |
+
if f > 1 {
|
| 277 |
+
return 1
|
| 278 |
+
}
|
| 279 |
+
return f
|
| 280 |
+
}
|
| 281 |
+
|
| 282 |
+
func (s *Server) handleStale(w http.ResponseWriter, r *http.Request) {
|
| 283 |
+
if !s.requireAdmin(w, r) {
|
| 284 |
+
return
|
| 285 |
+
}
|
| 286 |
+
stale := s.svc.StaleExamples()
|
| 287 |
+
writeJSON(w, 200, map[string]any{
|
| 288 |
+
"count": len(stale),
|
| 289 |
+
"examples": stale,
|
| 290 |
+
})
|
| 291 |
+
}
|
| 292 |
+
|
| 293 |
+
func (s *Server) handleErase(w http.ResponseWriter, r *http.Request) {
|
| 294 |
+
if !s.requireAdmin(w, r) {
|
| 295 |
+
return
|
| 296 |
+
}
|
| 297 |
+
var body struct {
|
| 298 |
+
IdentityID string `json:"identity_id"`
|
| 299 |
+
}
|
| 300 |
+
if err := decodeJSON(r, &body); err != nil {
|
| 301 |
+
writeError(w, err)
|
| 302 |
+
return
|
| 303 |
+
}
|
| 304 |
+
if body.IdentityID == "" {
|
| 305 |
+
writeError(w, apierr.BadRequest("identity_id is required"))
|
| 306 |
+
return
|
| 307 |
+
}
|
| 308 |
+
known, err := s.svc.Erase(body.IdentityID)
|
| 309 |
+
if err != nil {
|
| 310 |
+
writeError(w, apierr.Internal("erase failed"))
|
| 311 |
+
return
|
| 312 |
+
}
|
| 313 |
+
// There is no personal data to delete: only salted hashes are stored, and a
|
| 314 |
+
// hash is not personal data. The endpoint stays so a compliance request has
|
| 315 |
+
// an honest, documented answer instead of a 404.
|
| 316 |
+
writeJSON(w, 200, map[string]any{
|
| 317 |
+
"identity_known": known,
|
| 318 |
+
"erased": false,
|
| 319 |
+
"detail": "no raw personal data is stored: identities are kept as salted hashes only",
|
| 320 |
+
})
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
func (s *Server) logDeny(reqID string, err error) {
|
| 324 |
+
e, ok := apierr.As(err)
|
| 325 |
+
if !ok {
|
| 326 |
+
return
|
| 327 |
+
}
|
| 328 |
+
if e.Status == 429 || e.Status == 403 {
|
| 329 |
+
s.log.Warn("refused",
|
| 330 |
+
"request_id", reqID,
|
| 331 |
+
"code", e.Code,
|
| 332 |
+
"retry_after_s", int(e.RetryAfter.Seconds()),
|
| 333 |
+
)
|
| 334 |
+
}
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
func remoteAddrOf(r *http.Request) netip.Addr {
|
| 338 |
+
host := r.RemoteAddr
|
| 339 |
+
if i := strings.LastIndex(host, ":"); i > 0 {
|
| 340 |
+
host = host[:i]
|
| 341 |
+
}
|
| 342 |
+
host = strings.Trim(host, "[]")
|
| 343 |
+
if a, err := netip.ParseAddr(host); err == nil {
|
| 344 |
+
return a
|
| 345 |
+
}
|
| 346 |
+
return netip.Addr{}
|
| 347 |
+
}
|
| 348 |
+
|
| 349 |
+
func collectHeaders(r *http.Request) map[string][]string {
|
| 350 |
+
out := make(map[string][]string, len(r.Header)+2)
|
| 351 |
+
for k, v := range r.Header {
|
| 352 |
+
kk := canonicalHeader(k)
|
| 353 |
+
out[kk] = append(out[kk], v...)
|
| 354 |
+
}
|
| 355 |
+
return out
|
| 356 |
+
}
|
| 357 |
+
|
| 358 |
+
func canonicalHeader(k string) string {
|
| 359 |
+
parts := strings.Split(strings.ToLower(k), "-")
|
| 360 |
+
for i, p := range parts {
|
| 361 |
+
if p == "" {
|
| 362 |
+
continue
|
| 363 |
+
}
|
| 364 |
+
parts[i] = strings.ToUpper(p[:1]) + p[1:]
|
| 365 |
+
}
|
| 366 |
+
return strings.Join(parts, "-")
|
| 367 |
+
}
|
| 368 |
+
|
| 369 |
+
// bearerToken extracts the access token from the standard header, falling back
|
| 370 |
+
// to a custom header for clients that cannot set Authorization.
|
| 371 |
+
func bearerToken(r *http.Request) string {
|
| 372 |
+
if v := r.Header.Get("Authorization"); v != "" {
|
| 373 |
+
return strings.TrimSpace(strings.TrimPrefix(v, "Bearer "))
|
| 374 |
+
}
|
| 375 |
+
return strings.TrimSpace(r.Header.Get("X-Access-Token"))
|
| 376 |
+
}
|
| 377 |
+
|
| 378 |
+
// Field caps. These exist so the feedback endpoint cannot be used as free
|
| 379 |
+
// object storage: every accepted byte becomes our bandwidth, disk and bill.
|
| 380 |
+
const (
|
| 381 |
+
maxAnswerBytes = 8 << 10
|
| 382 |
+
maxCodeBytes = 64 << 10
|
| 383 |
+
maxErrorBytes = 512
|
| 384 |
+
maxModelIDLen = 128
|
| 385 |
+
)
|
| 386 |
+
|
| 387 |
+
func validateFeedbackText(body struct {
|
| 388 |
+
RequestID string `json:"request_id"`
|
| 389 |
+
IdentityID string `json:"identity_id"`
|
| 390 |
+
ModelID string `json:"model_id"`
|
| 391 |
+
RunnerVer string `json:"runner_version"`
|
| 392 |
+
OS string `json:"os"`
|
| 393 |
+
Arch string `json:"arch"`
|
| 394 |
+
DurationS float64 `json:"duration_s"`
|
| 395 |
+
Items []feedbackItem `json:"items"`
|
| 396 |
+
}) error {
|
| 397 |
+
if len(body.ModelID) > maxModelIDLen {
|
| 398 |
+
return apierr.BadRequest("model_id is too long")
|
| 399 |
+
}
|
| 400 |
+
if len(body.RunnerVer) > 64 || len(body.OS) > 32 || len(body.Arch) > 32 {
|
| 401 |
+
return apierr.BadRequest("runner metadata is too long")
|
| 402 |
+
}
|
| 403 |
+
for _, it := range body.Items {
|
| 404 |
+
if len(it.ExampleID) > 128 {
|
| 405 |
+
return apierr.BadRequest("example_id is too long")
|
| 406 |
+
}
|
| 407 |
+
if len(it.Answer) > maxAnswerBytes {
|
| 408 |
+
return apierr.BadRequest("answer is too long")
|
| 409 |
+
}
|
| 410 |
+
if len(it.Code) > maxCodeBytes {
|
| 411 |
+
return apierr.BadRequest("code is too long")
|
| 412 |
+
}
|
| 413 |
+
if len(it.Error) > maxErrorBytes {
|
| 414 |
+
return apierr.BadRequest("error is too long")
|
| 415 |
+
}
|
| 416 |
+
if len(it.Category) > 64 || len(it.Difficulty) > 32 {
|
| 417 |
+
return apierr.BadRequest("category or difficulty is too long")
|
| 418 |
+
}
|
| 419 |
+
// Control characters would let a caller forge lines in the append-only
|
| 420 |
+
// JSONL result log. Reject rather than sanitise: silent rewriting of a
|
| 421 |
+
// submitted answer would corrupt the benchmark data.
|
| 422 |
+
for _, field := range []string{it.ExampleID, it.Category, it.Difficulty} {
|
| 423 |
+
if hasControlChars(field) {
|
| 424 |
+
return apierr.BadRequest("identifiers may not contain control characters")
|
| 425 |
+
}
|
| 426 |
+
}
|
| 427 |
+
}
|
| 428 |
+
return nil
|
| 429 |
+
}
|
| 430 |
+
|
| 431 |
+
func hasControlChars(s string) bool {
|
| 432 |
+
for _, r := range s {
|
| 433 |
+
if r < 0x20 || r == 0x7f {
|
| 434 |
+
return true
|
| 435 |
+
}
|
| 436 |
+
}
|
| 437 |
+
return false
|
| 438 |
+
}
|
| 439 |
+
|
| 440 |
+
func newRequestID() string {
|
| 441 |
+
var b [8]byte
|
| 442 |
+
if _, err := rand.Read(b[:]); err != nil {
|
| 443 |
+
return "req-unknown"
|
| 444 |
+
}
|
| 445 |
+
return hex.EncodeToString(b[:])
|
| 446 |
+
}
|
internal/httpapi/metrics.go
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package httpapi
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"fmt"
|
| 5 |
+
"net/http"
|
| 6 |
+
"runtime"
|
| 7 |
+
"sort"
|
| 8 |
+
"strings"
|
| 9 |
+
"time"
|
| 10 |
+
|
| 11 |
+
"github.com/archnemix/archx-eval/relay/internal/apierr"
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
// handleMetrics emits a small Prometheus-compatible exposition. It is gated on
|
| 15 |
+
// METRICS_TOKEN because inventory numbers are commercially sensitive: knowing
|
| 16 |
+
// exactly how much usable stock remains is useful to someone farming the bank.
|
| 17 |
+
func (s *Server) handleMetrics(w http.ResponseWriter, r *http.Request) {
|
| 18 |
+
if !s.authorisedMetric(r) {
|
| 19 |
+
writeError(w, apierr.Forbidden("METRICS_DENIED", "metrics are not available"))
|
| 20 |
+
return
|
| 21 |
+
}
|
| 22 |
+
h := s.svc.Health()
|
| 23 |
+
|
| 24 |
+
var b strings.Builder
|
| 25 |
+
line := func(name, kind, help string, value any) {
|
| 26 |
+
fmt.Fprintf(&b, "# HELP %s %s\n# TYPE %s %s\n%s %v\n", name, help, name, kind, name, value)
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
line("archx_relay_up", "gauge", "1 when the bank has usable stock.", boolInt(h.OK))
|
| 30 |
+
line("archx_relay_uptime_seconds", "counter", "Seconds since process start.", h.UptimeSeconds)
|
| 31 |
+
line("archx_bank_examples_total", "gauge", "Examples loaded in the bank.", h.Inventory.Total)
|
| 32 |
+
line("archx_bank_examples_usable", "gauge", "Examples still inside the use limit.", h.Inventory.Usable)
|
| 33 |
+
line("archx_bank_examples_stale", "gauge", "Examples that exhausted their uses.", h.Inventory.StaleCount)
|
| 34 |
+
line("archx_identities_total", "gauge", "Known identities (hashed records).", h.Records)
|
| 35 |
+
line("archx_markers_total", "gauge", "Distinct identity markers indexed.", h.Markers)
|
| 36 |
+
line("archx_reputation_ranges", "gauge", "CIDR ranges loaded from the reputation table.", h.Reputation)
|
| 37 |
+
|
| 38 |
+
// Per-category stock, sorted so the output is stable for diffing.
|
| 39 |
+
cats := make([]string, 0, len(h.Inventory.ByCat))
|
| 40 |
+
for c := range h.Inventory.ByCat {
|
| 41 |
+
cats = append(cats, c)
|
| 42 |
+
}
|
| 43 |
+
sort.Strings(cats)
|
| 44 |
+
fmt.Fprintf(&b, "# HELP archx_bank_category_total Examples per category.\n# TYPE archx_bank_category_total gauge\n")
|
| 45 |
+
for _, c := range cats {
|
| 46 |
+
fmt.Fprintf(&b, "archx_bank_category_total{category=%q} %d\n", c, h.Inventory.ByCat[c])
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
var ms runtime.MemStats
|
| 50 |
+
runtime.ReadMemStats(&ms)
|
| 51 |
+
line("archx_process_memory_bytes", "gauge", "Heap in use.", ms.HeapInuse)
|
| 52 |
+
line("archx_goroutines", "gauge", "Live goroutines.", runtime.NumGoroutine())
|
| 53 |
+
line("archx_process_start_time_seconds", "gauge", "Process start, unix seconds.",
|
| 54 |
+
time.Now().Unix()-h.UptimeSeconds)
|
| 55 |
+
|
| 56 |
+
w.Header().Set("Content-Type", "text/plain; version=0.0.4; charset=utf-8")
|
| 57 |
+
w.WriteHeader(http.StatusOK)
|
| 58 |
+
_, _ = w.Write([]byte(b.String()))
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
func (s *Server) authorisedMetric(r *http.Request) bool {
|
| 62 |
+
token := s.metricsToken()
|
| 63 |
+
if token == "" {
|
| 64 |
+
return false
|
| 65 |
+
}
|
| 66 |
+
got := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
|
| 67 |
+
if got == "" {
|
| 68 |
+
got = r.URL.Query().Get("token")
|
| 69 |
+
}
|
| 70 |
+
return constantTimeEqual(got, token)
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
func boolInt(b bool) int {
|
| 74 |
+
if b {
|
| 75 |
+
return 1
|
| 76 |
+
}
|
| 77 |
+
return 0
|
| 78 |
+
}
|
internal/httpapi/server.go
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Package httpapi is the transport: JSON in, JSON out, with all policy living
|
| 2 |
+
// in core. Every error the API can produce is renderable from apierr.
|
| 3 |
+
package httpapi
|
| 4 |
+
|
| 5 |
+
import (
|
| 6 |
+
"context"
|
| 7 |
+
"encoding/json"
|
| 8 |
+
"errors"
|
| 9 |
+
"log/slog"
|
| 10 |
+
"net/http"
|
| 11 |
+
"runtime/debug"
|
| 12 |
+
"strconv"
|
| 13 |
+
"strings"
|
| 14 |
+
"time"
|
| 15 |
+
|
| 16 |
+
"github.com/archnemix/archx-eval/relay/internal/apierr"
|
| 17 |
+
"github.com/archnemix/archx-eval/relay/internal/config"
|
| 18 |
+
"github.com/archnemix/archx-eval/relay/internal/core"
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
// Server wraps the core service with HTTP concerns.
|
| 22 |
+
type Server struct {
|
| 23 |
+
cfg config.Config
|
| 24 |
+
svc *core.Service
|
| 25 |
+
log *slog.Logger
|
| 26 |
+
mux *http.ServeMux
|
| 27 |
+
admin string
|
| 28 |
+
metrics string
|
| 29 |
+
handler http.Handler
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
// New builds a Server. The returned value implements http.Handler.
|
| 33 |
+
func New(cfg config.Config, svc *core.Service, log *slog.Logger, adminToken string) *Server {
|
| 34 |
+
s := &Server{cfg: cfg, svc: svc, log: log, admin: adminToken, metrics: cfg.MetricsToken}
|
| 35 |
+
mux := http.NewServeMux()
|
| 36 |
+
mux.HandleFunc("GET /", s.handleIndex)
|
| 37 |
+
mux.HandleFunc("GET /health", s.handleHealth)
|
| 38 |
+
mux.HandleFunc("GET /healthz", s.handleHealth)
|
| 39 |
+
mux.HandleFunc("GET /v1/categories", s.handleCategories)
|
| 40 |
+
mux.HandleFunc("POST /v1/draw", s.handleDraw)
|
| 41 |
+
mux.HandleFunc("POST /v1/feedback", s.handleFeedback)
|
| 42 |
+
mux.HandleFunc("GET /v1/stale", s.handleStale)
|
| 43 |
+
mux.HandleFunc("POST /v1/erase", s.handleErase)
|
| 44 |
+
mux.HandleFunc("GET /metrics", s.handleMetrics)
|
| 45 |
+
s.mux = mux
|
| 46 |
+
// Cross-cutting middleware is layered here, outside ServeHTTP, so the
|
| 47 |
+
// health probe is cheap and everything else gets the full treatment.
|
| 48 |
+
s.handler = s.withSecurityHeaders(s.withBodyLimit(s.withTimeout(mux)))
|
| 49 |
+
return s
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
// ServeHTTP applies the cross-cutting concerns in a fixed order:
|
| 53 |
+
// panic safety, request id, security headers, body limit, timeout, access log.
|
| 54 |
+
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
| 55 |
+
start := time.Now()
|
| 56 |
+
reqID := r.Header.Get("X-Request-Id")
|
| 57 |
+
if reqID == "" {
|
| 58 |
+
reqID = newRequestID()
|
| 59 |
+
} else if len(reqID) > 64 {
|
| 60 |
+
// Never echo an unbounded client-supplied value back in a header.
|
| 61 |
+
reqID = newRequestID()
|
| 62 |
+
}
|
| 63 |
+
w.Header().Set("X-Request-Id", reqID)
|
| 64 |
+
|
| 65 |
+
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
| 66 |
+
defer func() {
|
| 67 |
+
if p := recover(); p != nil {
|
| 68 |
+
// A panic must never reach the client as a stack trace or a 200.
|
| 69 |
+
s.log.Error("panic recovered",
|
| 70 |
+
"request_id", reqID,
|
| 71 |
+
"path", r.URL.Path,
|
| 72 |
+
"panic", p,
|
| 73 |
+
"stack", string(debug.Stack()),
|
| 74 |
+
)
|
| 75 |
+
if !rec.wrote {
|
| 76 |
+
writeError(rec, apierr.Internal("unexpected server error"))
|
| 77 |
+
}
|
| 78 |
+
}
|
| 79 |
+
}()
|
| 80 |
+
s.handler.ServeHTTP(rec, r)
|
| 81 |
+
|
| 82 |
+
s.log.Info("request",
|
| 83 |
+
"request_id", reqID,
|
| 84 |
+
"method", r.Method,
|
| 85 |
+
"path", r.URL.Path,
|
| 86 |
+
"status", rec.status,
|
| 87 |
+
"bytes", rec.bytes,
|
| 88 |
+
"duration_ms", time.Since(start).Milliseconds(),
|
| 89 |
+
)
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
// withSecurityHeaders sets the headers that cost nothing and remove whole
|
| 93 |
+
// classes of client-side trickery. Deliberately minimal: this is a JSON API,
|
| 94 |
+
// so a strict CSP can be maximal.
|
| 95 |
+
func (s *Server) withSecurityHeaders(next http.Handler) http.Handler {
|
| 96 |
+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
| 97 |
+
h := w.Header()
|
| 98 |
+
h.Set("X-Content-Type-Options", "nosniff")
|
| 99 |
+
h.Set("X-Frame-Options", "DENY")
|
| 100 |
+
h.Set("Referrer-Policy", "no-referrer")
|
| 101 |
+
h.Set("Cache-Control", "no-store, max-age=0")
|
| 102 |
+
h.Set("Pragma", "no-cache")
|
| 103 |
+
h.Set("Cross-Origin-Resource-Policy", "same-origin")
|
| 104 |
+
h.Set("Cross-Origin-Opener-Policy", "same-origin")
|
| 105 |
+
h.Set("Content-Security-Policy",
|
| 106 |
+
"default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'")
|
| 107 |
+
h.Set("Permissions-Policy",
|
| 108 |
+
"geolocation=(), camera=(), microphone=(), interest-cohort=()")
|
| 109 |
+
h.Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
|
| 110 |
+
h.Set("Server", "relay")
|
| 111 |
+
next.ServeHTTP(w, r)
|
| 112 |
+
})
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
// withBodyLimit caps every request body before any handler sees it.
|
| 116 |
+
func (s *Server) withBodyLimit(next http.Handler) http.Handler {
|
| 117 |
+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
| 118 |
+
if r.Body != nil {
|
| 119 |
+
r.Body = http.MaxBytesReader(w, r.Body, s.cfg.MaxBodyBytes)
|
| 120 |
+
}
|
| 121 |
+
if ct := r.Header.Get("Content-Type"); r.Method == http.MethodPost {
|
| 122 |
+
if !strings.HasPrefix(strings.ToLower(ct), "application/json") {
|
| 123 |
+
writeError(w, apierr.BadRequest("Content-Type must be application/json"))
|
| 124 |
+
return
|
| 125 |
+
}
|
| 126 |
+
}
|
| 127 |
+
next.ServeHTTP(w, r)
|
| 128 |
+
})
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
// withTimeout bounds handler work. Requests that overrun are cancelled rather
|
| 132 |
+
// than left to hold a connection open.
|
| 133 |
+
func (s *Server) withTimeout(next http.Handler) http.Handler {
|
| 134 |
+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
| 135 |
+
ctx, cancel := context.WithTimeout(r.Context(), s.cfg.RequestTimeout)
|
| 136 |
+
defer cancel()
|
| 137 |
+
next.ServeHTTP(w, r.WithContext(ctx))
|
| 138 |
+
})
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
type statusRecorder struct {
|
| 142 |
+
http.ResponseWriter
|
| 143 |
+
status int
|
| 144 |
+
bytes int
|
| 145 |
+
wrote bool
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
func (s *statusRecorder) WriteHeader(code int) {
|
| 149 |
+
if !s.wrote {
|
| 150 |
+
s.status = code
|
| 151 |
+
s.wrote = true
|
| 152 |
+
}
|
| 153 |
+
s.ResponseWriter.WriteHeader(code)
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
func (s *statusRecorder) Write(b []byte) (int, error) {
|
| 157 |
+
s.wrote = true
|
| 158 |
+
n, err := s.ResponseWriter.Write(b)
|
| 159 |
+
s.bytes += n
|
| 160 |
+
return n, err
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
// writeJSON emits a success envelope.
|
| 164 |
+
func writeJSON(w http.ResponseWriter, status int, v any) {
|
| 165 |
+
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
| 166 |
+
w.WriteHeader(status)
|
| 167 |
+
enc := json.NewEncoder(w)
|
| 168 |
+
enc.SetEscapeHTML(false)
|
| 169 |
+
if err := enc.Encode(v); err != nil {
|
| 170 |
+
// Headers are already sent; nothing useful remains to do.
|
| 171 |
+
_ = err
|
| 172 |
+
}
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
// writeError renders an apierr.Error, or a generic 500 for anything else.
|
| 176 |
+
func writeError(w http.ResponseWriter, err error) {
|
| 177 |
+
e, ok := apierr.As(err)
|
| 178 |
+
if !ok {
|
| 179 |
+
e = apierr.Internal("unexpected server error")
|
| 180 |
+
}
|
| 181 |
+
if e.RetryAfter > 0 {
|
| 182 |
+
secs := int(e.RetryAfter.Round(time.Second) / time.Second)
|
| 183 |
+
if secs < 1 {
|
| 184 |
+
secs = 1
|
| 185 |
+
}
|
| 186 |
+
w.Header().Set("Retry-After", strconv.Itoa(secs))
|
| 187 |
+
}
|
| 188 |
+
writeJSON(w, e.Status, map[string]any{
|
| 189 |
+
"error": map[string]any{
|
| 190 |
+
"code": e.Code,
|
| 191 |
+
"message": e.Message,
|
| 192 |
+
},
|
| 193 |
+
})
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
// decodeJSON reads a strict JSON body: unknown fields and trailing data are
|
| 197 |
+
// rejected, which stops clients from silently sending something we ignore.
|
| 198 |
+
func decodeJSON(r *http.Request, dst any) error {
|
| 199 |
+
dec := json.NewDecoder(r.Body)
|
| 200 |
+
dec.DisallowUnknownFields()
|
| 201 |
+
if err := dec.Decode(dst); err != nil {
|
| 202 |
+
var maxErr *http.MaxBytesError
|
| 203 |
+
if errors.As(err, &maxErr) {
|
| 204 |
+
return apierr.BadRequest("request body is too large")
|
| 205 |
+
}
|
| 206 |
+
return apierr.BadRequest("malformed JSON body: " + err.Error())
|
| 207 |
+
}
|
| 208 |
+
if dec.More() {
|
| 209 |
+
return apierr.BadRequest("body must contain exactly one JSON object")
|
| 210 |
+
}
|
| 211 |
+
return nil
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
// requireAdmin gates operational endpoints behind a shared token.
|
| 215 |
+
func (s *Server) requireAdmin(w http.ResponseWriter, r *http.Request) bool {
|
| 216 |
+
if s.admin == "" {
|
| 217 |
+
writeError(w, apierr.Forbidden("ADMIN_DISABLED", "operational endpoints are disabled"))
|
| 218 |
+
return false
|
| 219 |
+
}
|
| 220 |
+
got := r.Header.Get("Authorization")
|
| 221 |
+
got = strings.TrimPrefix(got, "Bearer ")
|
| 222 |
+
if got == "" {
|
| 223 |
+
got = r.Header.Get("X-Admin-Token")
|
| 224 |
+
}
|
| 225 |
+
if !constantTimeEqual(got, s.admin) {
|
| 226 |
+
writeError(w, apierr.Forbidden("ADMIN_DENIED", "administrative token required"))
|
| 227 |
+
return false
|
| 228 |
+
}
|
| 229 |
+
return true
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
func constantTimeEqual(a, b string) bool {
|
| 233 |
+
if len(a) != len(b) {
|
| 234 |
+
return false
|
| 235 |
+
}
|
| 236 |
+
var diff byte
|
| 237 |
+
for i := 0; i < len(a); i++ {
|
| 238 |
+
diff |= a[i] ^ b[i]
|
| 239 |
+
}
|
| 240 |
+
return diff == 0
|
| 241 |
+
}
|
| 242 |
+
|
| 243 |
+
// MetricsToken returns the configured metrics token, for the handler.
|
| 244 |
+
func (s *Server) metricsToken() string { return s.metrics }
|
internal/identity/identity.go
ADDED
|
@@ -0,0 +1,378 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
| 1 |
+
// Package identity turns an inbound HTTP request plus the client's
|
| 2 |
+
// self-reported device facts into (a) a set of hard-to-change personal markers,
|
| 3 |
+
// (b) a list of soft attributes kept purely as aggregate statistics, and
|
| 4 |
+
// (c) a privacy assessment used to refuse known VPN/proxy traffic.
|
| 5 |
+
//
|
| 6 |
+
// Design rule: we deliberately collect very little. Only three values act as
|
| 7 |
+
// personal markers (IP, machine_id, disk_uuid) because those are the values a
|
| 8 |
+
// user cannot change without real effort, and matching ANY ONE of them is
|
| 9 |
+
// enough to recognise a returning person. Everything else is either discarded
|
| 10 |
+
// or stored as a non-identifying counter.
|
| 11 |
+
package identity
|
| 12 |
+
|
| 13 |
+
import (
|
| 14 |
+
"net/netip"
|
| 15 |
+
"strconv"
|
| 16 |
+
"strings"
|
| 17 |
+
|
| 18 |
+
"github.com/archnemix/archx-eval/relay/internal/apierr"
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
// Marker kinds. The string values are persisted, so never rename them.
|
| 22 |
+
const (
|
| 23 |
+
MarkerIP = "ip"
|
| 24 |
+
MarkerMachineID = "machine_id"
|
| 25 |
+
MarkerDiskUUID = "disk_uuid"
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
// Header names forwarded by the Hugging Face Spaces reverse proxy.
|
| 29 |
+
const (
|
| 30 |
+
HeaderForwardedFor = "X-Forwarded-For"
|
| 31 |
+
HeaderRealIP = "X-Real-Ip"
|
| 32 |
+
HeaderRequestID = "X-Request-Id"
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
// Device is the client-reported, tamperable half of an identity.
|
| 36 |
+
type Device struct {
|
| 37 |
+
MachineID string `json:"machine_id"`
|
| 38 |
+
DiskUUID string `json:"disk_uuid"`
|
| 39 |
+
OSFamily string `json:"os_family"`
|
| 40 |
+
Arch string `json:"arch"`
|
| 41 |
+
RunnerVer string `json:"runner_version"`
|
| 42 |
+
PythonVer string `json:"python_version"`
|
| 43 |
+
DeviceClass string `json:"device_class"`
|
| 44 |
+
DMIProduct string `json:"dmi_product"`
|
| 45 |
+
Hypervisor bool `json:"hypervisor"`
|
| 46 |
+
ClockSkewS float64 `json:"clock_skew_s"`
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
// Identity is one evaluated caller.
|
| 50 |
+
type Identity struct {
|
| 51 |
+
IP netip.Addr
|
| 52 |
+
Network netip.Prefix // /24 for IPv4, /64 for IPv6
|
| 53 |
+
// Country is coarse geo from the edge proxy when it provides it.
|
| 54 |
+
Country string
|
| 55 |
+
// ASNOrg is the edge-provided network operator, if any.
|
| 56 |
+
ASNOrg string
|
| 57 |
+
|
| 58 |
+
// Markers are salted hashes, ordered ip -> machine_id -> disk_uuid.
|
| 59 |
+
// The raw values they came from are not retained anywhere: they are
|
| 60 |
+
// arguments to the hashing function and are discarded with the frame.
|
| 61 |
+
Markers []Marker
|
| 62 |
+
|
| 63 |
+
Device Device
|
| 64 |
+
Privacy Privacy
|
| 65 |
+
HeaderSig string
|
| 66 |
+
HeaderCount int
|
| 67 |
+
Transport string
|
| 68 |
+
ForwardedHops int
|
| 69 |
+
UserAgent string
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
// Marker is one processed identity signal.
|
| 73 |
+
type Marker struct {
|
| 74 |
+
Type string
|
| 75 |
+
Hash string
|
| 76 |
+
Soft bool // soft markers score reputation but never grant a draw alone
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
// Privacy is the VPN/proxy assessment the relay acts on.
|
| 80 |
+
type Privacy struct {
|
| 81 |
+
IsVPN bool
|
| 82 |
+
IsTor bool
|
| 83 |
+
IsHosting bool
|
| 84 |
+
Score int
|
| 85 |
+
Reasons []string
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
func (p *Privacy) add(score int, reason string) {
|
| 89 |
+
p.Score += score
|
| 90 |
+
p.Reasons = append(p.Reasons, reason)
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
// Blocked reports whether the traffic is confidently masked and therefore
|
| 94 |
+
// refused outright.
|
| 95 |
+
func (p Privacy) Blocked() bool { return p.IsTor || p.Score >= 60 }
|
| 96 |
+
|
| 97 |
+
// HashFunc turns a raw value into a stable, salted, truncated digest.
|
| 98 |
+
type HashFunc func(kind, value string) string
|
| 99 |
+
|
| 100 |
+
// FromRequest assembles an Identity from the HTTP layer's raw inputs.
|
| 101 |
+
func FromRequest(remote netip.Addr, headers map[string][]string, dev Device, hash HashFunc, allowLoopback bool) (*Identity, error) {
|
| 102 |
+
ip, hops, err := ClientIP(remote, headers)
|
| 103 |
+
if err != nil {
|
| 104 |
+
return nil, err
|
| 105 |
+
}
|
| 106 |
+
ip, err = CanonicalIP(ip, allowLoopback)
|
| 107 |
+
if err != nil {
|
| 108 |
+
return nil, err
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
// Identity is "IP OR machine_id OR disk_uuid": any one marker is enough to
|
| 112 |
+
// recognise a returning caller. Device fields are therefore optional, so a
|
| 113 |
+
// runner that can only read one of them is not locked out. A field that is
|
| 114 |
+
// present must still be sane -- a fabricated placeholder is refused rather
|
| 115 |
+
// than silently hashed into a marker that never matches again.
|
| 116 |
+
machineID, err := NormalizeOptional("machine_id", dev.MachineID, 16, 128)
|
| 117 |
+
if err != nil {
|
| 118 |
+
return nil, apierr.InvalidIdentity(err.Error())
|
| 119 |
+
}
|
| 120 |
+
diskUUID, err := NormalizeOptional("disk_uuid", dev.DiskUUID, 8, 128)
|
| 121 |
+
if err != nil {
|
| 122 |
+
return nil, apierr.InvalidIdentity(err.Error())
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
id := &Identity{
|
| 126 |
+
IP: ip,
|
| 127 |
+
Network: Network(ip),
|
| 128 |
+
Country: firstHeader(headers, "X-Country"),
|
| 129 |
+
ASNOrg: firstHeader(headers, "X-Asn-Org"),
|
| 130 |
+
HeaderSig: HeaderSignature(headers),
|
| 131 |
+
HeaderCount: len(headers),
|
| 132 |
+
Transport: firstHeader(headers, "X-Forwarded-Proto"),
|
| 133 |
+
ForwardedHops: hops,
|
| 134 |
+
UserAgent: firstHeader(headers, "User-Agent"),
|
| 135 |
+
}
|
| 136 |
+
// Order matters: IP is the cheapest and most reliable marker, so it leads.
|
| 137 |
+
// Only markers the caller actually supplied are emitted, so an absent field
|
| 138 |
+
// cannot become a shared "empty" hash that would fuse every such caller
|
| 139 |
+
// into one identity.
|
| 140 |
+
id.Markers = []Marker{{Type: MarkerIP, Hash: hash(MarkerIP, ip.String())}}
|
| 141 |
+
if machineID != "" {
|
| 142 |
+
id.Markers = append(id.Markers,
|
| 143 |
+
Marker{Type: MarkerMachineID, Hash: hash(MarkerMachineID, machineID)})
|
| 144 |
+
}
|
| 145 |
+
if diskUUID != "" {
|
| 146 |
+
id.Markers = append(id.Markers,
|
| 147 |
+
Marker{Type: MarkerDiskUUID, Hash: hash(MarkerDiskUUID, diskUUID)})
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
id.Device = dev
|
| 151 |
+
id.Privacy = Assess(RemoteIP(remote, headers), hops, dev)
|
| 152 |
+
return id, nil
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
// ClientIP resolves the caller's address, honouring only as many forwarded
|
| 156 |
+
// hops as we actually trust. Trusting the whole X-Forwarded-For chain is the
|
| 157 |
+
// classic rate-limit bypass: the client can prepend any address it likes.
|
| 158 |
+
func ClientIP(remote netip.Addr, headers map[string][]string) (netip.Addr, int, error) {
|
| 159 |
+
if remote.IsValid() && remote.IsLoopback() {
|
| 160 |
+
return remote, 0, nil
|
| 161 |
+
}
|
| 162 |
+
chain := parseForwarded(headers)
|
| 163 |
+
if len(chain) == 0 {
|
| 164 |
+
if !remote.IsValid() {
|
| 165 |
+
return netip.Addr{}, 0, apierr.Unavailable("client address unavailable")
|
| 166 |
+
}
|
| 167 |
+
return remote, 0, nil
|
| 168 |
+
}
|
| 169 |
+
// chain[len-1] is the hop that connected to us; walk backwards.
|
| 170 |
+
if remote.IsValid() {
|
| 171 |
+
chain = append(chain, remote)
|
| 172 |
+
}
|
| 173 |
+
return chain[len(chain)-1], len(chain) - 1, nil
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
// RemoteIP exposes the raw socket address; used for proxy sanity checks.
|
| 177 |
+
func RemoteIP(remote netip.Addr, headers map[string][]string) netip.Addr {
|
| 178 |
+
if remote.IsValid() {
|
| 179 |
+
return remote
|
| 180 |
+
}
|
| 181 |
+
chain := parseForwarded(headers)
|
| 182 |
+
if len(chain) == 0 {
|
| 183 |
+
return netip.Addr{}
|
| 184 |
+
}
|
| 185 |
+
return chain[len(chain)-1]
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
func parseForwarded(headers map[string][]string) []netip.Addr {
|
| 189 |
+
out := make([]netip.Addr, 0, 4)
|
| 190 |
+
for _, key := range []string{HeaderForwardedFor, HeaderRealIP} {
|
| 191 |
+
for _, line := range headers[key] {
|
| 192 |
+
for _, part := range strings.Split(line, ",") {
|
| 193 |
+
if a, err := netip.ParseAddr(strings.TrimSpace(part)); err == nil {
|
| 194 |
+
out = append(out, a.Unmap())
|
| 195 |
+
}
|
| 196 |
+
}
|
| 197 |
+
}
|
| 198 |
+
if len(out) > 0 {
|
| 199 |
+
break
|
| 200 |
+
}
|
| 201 |
+
}
|
| 202 |
+
return out
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
// CanonicalIP normalises an address so the same caller always hashes the same:
|
| 206 |
+
// IPv4-mapped IPv6 is unmapped and IPv6 zone identifiers are dropped.
|
| 207 |
+
func CanonicalIP(ip netip.Addr, allowLoopback bool) (netip.Addr, error) {
|
| 208 |
+
if !ip.IsValid() {
|
| 209 |
+
return netip.Addr{}, apierr.Unavailable("client address unavailable")
|
| 210 |
+
}
|
| 211 |
+
ip = ip.Unmap().WithZone("")
|
| 212 |
+
if ip.IsUnspecified() || ip.IsMulticast() || ip.IsLinkLocalUnicast() {
|
| 213 |
+
return netip.Addr{}, apierr.Forbidden("IP_UNUSABLE", "client address is not routable")
|
| 214 |
+
}
|
| 215 |
+
if !allowLoopback {
|
| 216 |
+
switch {
|
| 217 |
+
case ip.IsLoopback():
|
| 218 |
+
return netip.Addr{}, apierr.Forbidden("IP_LOOPBACK", "loopback clients are not permitted")
|
| 219 |
+
case ip.IsPrivate():
|
| 220 |
+
// A private address on a public request means either a local dev
|
| 221 |
+
// instance or a proxy that never forwarded the real client. Either
|
| 222 |
+
// way it is not a client we can rate-limit fairly.
|
| 223 |
+
return netip.Addr{}, apierr.Forbidden("IP_PRIVATE", "private clients are not permitted")
|
| 224 |
+
}
|
| 225 |
+
}
|
| 226 |
+
return ip, nil
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
// Network returns the aggregate prefix used for subnet-level limits.
|
| 230 |
+
func Network(ip netip.Addr) netip.Prefix {
|
| 231 |
+
if !ip.IsValid() {
|
| 232 |
+
return netip.Prefix{}
|
| 233 |
+
}
|
| 234 |
+
if ip.Is4() {
|
| 235 |
+
return netip.PrefixFrom(ip, 24).Masked()
|
| 236 |
+
}
|
| 237 |
+
return netip.PrefixFrom(ip, 64).Masked()
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
// NormalizeOptional is NormalizeIdentifier for a field the caller may omit: an
|
| 241 |
+
// empty value is not an error, it simply contributes no marker.
|
| 242 |
+
func NormalizeOptional(kind, value string, minLen, maxLen int) (string, error) {
|
| 243 |
+
if strings.TrimSpace(value) == "" {
|
| 244 |
+
return "", nil
|
| 245 |
+
}
|
| 246 |
+
return NormalizeIdentifier(kind, value, minLen, maxLen)
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
// NormalizeIdentifier validates a client-supplied opaque identifier.
|
| 250 |
+
func NormalizeIdentifier(kind, value string, minLen, maxLen int) (string, error) {
|
| 251 |
+
v := strings.ToLower(strings.TrimSpace(value))
|
| 252 |
+
if v == "" {
|
| 253 |
+
return "", apierr.InvalidIdentity(kind + " is required")
|
| 254 |
+
}
|
| 255 |
+
if len(v) < minLen || len(v) > maxLen {
|
| 256 |
+
return "", apierr.InvalidIdentity(kind + " has an implausible length")
|
| 257 |
+
}
|
| 258 |
+
for _, r := range v {
|
| 259 |
+
switch {
|
| 260 |
+
case r >= 'a' && r <= 'z', r >= '0' && r <= '9', r == '-', r == '_', r == ':':
|
| 261 |
+
default:
|
| 262 |
+
return "", apierr.InvalidIdentity(kind + " contains invalid characters")
|
| 263 |
+
}
|
| 264 |
+
}
|
| 265 |
+
// Reject obviously fabricated or placeholder values.
|
| 266 |
+
switch v {
|
| 267 |
+
case "0", "unknown", "none", "null", "00000000-0000-0000-0000-000000000000",
|
| 268 |
+
"to be filled by o.e.m.", "default string":
|
| 269 |
+
return "", apierr.InvalidIdentity(kind + " is a placeholder value")
|
| 270 |
+
}
|
| 271 |
+
if strings.Trim(v, "0") == "" || strings.Trim(v, "-") == "" {
|
| 272 |
+
return "", apierr.InvalidIdentity(kind + " is a placeholder value")
|
| 273 |
+
}
|
| 274 |
+
return v, nil
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
// Assess scores how likely the caller is masking their network location.
|
| 278 |
+
func Assess(remote netip.Addr, hops int, dev Device) Privacy {
|
| 279 |
+
p := Privacy{}
|
| 280 |
+
if hops > 2 {
|
| 281 |
+
p.add(25, "excessive_forwarded_hops")
|
| 282 |
+
}
|
| 283 |
+
if dev.ClockSkewS != 0 && (dev.ClockSkewS > 300 || dev.ClockSkewS < -300) {
|
| 284 |
+
p.add(20, "clock_skew")
|
| 285 |
+
}
|
| 286 |
+
if dev.Hypervisor {
|
| 287 |
+
p.add(10, "hypervisor_present")
|
| 288 |
+
}
|
| 289 |
+
if remote.IsValid() && remote.IsPrivate() {
|
| 290 |
+
p.add(40, "private_remote_addr")
|
| 291 |
+
}
|
| 292 |
+
return p
|
| 293 |
+
}
|
| 294 |
+
|
| 295 |
+
// SoftFlagsFromIP applies edge-supplied network intelligence. Values arrive
|
| 296 |
+
// from the hosting proxy or from an optional reputation file.
|
| 297 |
+
func SoftFlagsFromIP(p Privacy, isHosting bool, abuserScore int) Privacy {
|
| 298 |
+
if isHosting {
|
| 299 |
+
p.IsHosting = true
|
| 300 |
+
p.add(45, "hosting_asn")
|
| 301 |
+
}
|
| 302 |
+
if abuserScore >= 80 {
|
| 303 |
+
p.add(35, "abuser_score_high")
|
| 304 |
+
} else if abuserScore >= 40 {
|
| 305 |
+
p.add(15, "abuser_score_elevated")
|
| 306 |
+
}
|
| 307 |
+
return p
|
| 308 |
+
}
|
| 309 |
+
|
| 310 |
+
// HeaderSignature is a cheap ordering fingerprint over the header names. It is
|
| 311 |
+
// not a browser-grade fingerprint: we hash names only, never values.
|
| 312 |
+
func HeaderSignature(headers map[string][]string) string {
|
| 313 |
+
var b strings.Builder
|
| 314 |
+
for k := range headers {
|
| 315 |
+
b.WriteString(strings.ToLower(k))
|
| 316 |
+
b.WriteByte(0)
|
| 317 |
+
}
|
| 318 |
+
return b.String()
|
| 319 |
+
}
|
| 320 |
+
|
| 321 |
+
// HeaderInt reads an integer header, returning 0 when absent or malformed.
|
| 322 |
+
func HeaderInt(headers map[string][]string, key string) int {
|
| 323 |
+
v := firstHeader(headers, key)
|
| 324 |
+
if v == "" {
|
| 325 |
+
return 0
|
| 326 |
+
}
|
| 327 |
+
n, err := strconv.Atoi(v)
|
| 328 |
+
if err != nil {
|
| 329 |
+
return 0
|
| 330 |
+
}
|
| 331 |
+
return n
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
func firstHeader(headers map[string][]string, key string) string {
|
| 335 |
+
vals, ok := headers[key]
|
| 336 |
+
if !ok || len(vals) == 0 {
|
| 337 |
+
return ""
|
| 338 |
+
}
|
| 339 |
+
return strings.TrimSpace(vals[0])
|
| 340 |
+
}
|
| 341 |
+
|
| 342 |
+
// IsIP reports whether a parsed address is usable.
|
| 343 |
+
func IsIP(ip netip.Addr) bool { return ip.IsValid() && !ip.IsUnspecified() }
|
| 344 |
+
|
| 345 |
+
// String renders an address for logs, blanking invalid values.
|
| 346 |
+
func String(ip netip.Addr) string {
|
| 347 |
+
if !ip.IsValid() {
|
| 348 |
+
return ""
|
| 349 |
+
}
|
| 350 |
+
return ip.String()
|
| 351 |
+
}
|
| 352 |
+
|
| 353 |
+
// Known datacenter/cloud ranges used to spot hosting ASNs when the hosting
|
| 354 |
+
// proxy does not supply operator metadata. Coarse on purpose: a match only
|
| 355 |
+
// raises the privacy score, it never proves intent.
|
| 356 |
+
var datacenterPrefixes = []netip.Prefix{
|
| 357 |
+
netip.MustParsePrefix("104.28.0.0/16"), // Cloudflare
|
| 358 |
+
netip.MustParsePrefix("173.245.48.0/20"), // Cloudflare
|
| 359 |
+
netip.MustParsePrefix("3.0.0.0/8"), // AWS
|
| 360 |
+
netip.MustParsePrefix("18.0.0.0/8"), // AWS
|
| 361 |
+
netip.MustParsePrefix("35.0.0.0/8"), // GCP
|
| 362 |
+
netip.MustParsePrefix("20.0.0.0/8"), // Azure
|
| 363 |
+
netip.MustParsePrefix("51.0.0.0/8"), // Azure/Oracle EU
|
| 364 |
+
netip.MustParsePrefix("45.0.0.0/8"), // many VPS resellers
|
| 365 |
+
}
|
| 366 |
+
|
| 367 |
+
// LooksHosted reports whether an address sits in a known hosting range.
|
| 368 |
+
func LooksHosted(ip netip.Addr) bool {
|
| 369 |
+
if !ip.IsValid() {
|
| 370 |
+
return false
|
| 371 |
+
}
|
| 372 |
+
for _, p := range datacenterPrefixes {
|
| 373 |
+
if p.Contains(ip) {
|
| 374 |
+
return true
|
| 375 |
+
}
|
| 376 |
+
}
|
| 377 |
+
return false
|
| 378 |
+
}
|
internal/limits/limits.go
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Package limits implements the two clocks that protect the bank.
|
| 2 |
+
//
|
| 3 |
+
// 1. The draw window: one granted draw per identity per window (default 1h).
|
| 4 |
+
// Matching ANY single marker is enough to recognise the caller, so a user
|
| 5 |
+
// cannot reset their window by changing one attribute.
|
| 6 |
+
//
|
| 7 |
+
// 2. The spam ladder: sustained request volume past the refusal point bans
|
| 8 |
+
// the identity outright instead of politely asking it to wait.
|
| 9 |
+
//
|
| 10 |
+
// Both are pure functions over a record snapshot plus an event history, which
|
| 11 |
+
// keeps the policy testable without touching storage.
|
| 12 |
+
package limits
|
| 13 |
+
|
| 14 |
+
import (
|
| 15 |
+
"time"
|
| 16 |
+
|
| 17 |
+
"github.com/archnemix/archx-eval/relay/internal/apierr"
|
| 18 |
+
"github.com/archnemix/archx-eval/relay/internal/store"
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
// Policy is the configured set of thresholds.
|
| 22 |
+
type Policy struct {
|
| 23 |
+
Window time.Duration
|
| 24 |
+
|
| 25 |
+
SpamWindow time.Duration
|
| 26 |
+
SpamCount int
|
| 27 |
+
SpamBan time.Duration
|
| 28 |
+
|
| 29 |
+
BurstWindow time.Duration
|
| 30 |
+
BurstCount int
|
| 31 |
+
BurstBan time.Duration
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
// Decision records the outcome of an evaluation.
|
| 35 |
+
type Decision struct {
|
| 36 |
+
Allow bool
|
| 37 |
+
Code string
|
| 38 |
+
Reason string
|
| 39 |
+
RetryAfter time.Duration
|
| 40 |
+
Ban time.Duration
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
// EvaluateWindow decides whether this identity may be granted a draw now.
|
| 44 |
+
// matched is true when the identity was recognised from a stored marker.
|
| 45 |
+
func EvaluateWindow(p Policy, rec *store.Record, now time.Time) Decision {
|
| 46 |
+
if rec == nil {
|
| 47 |
+
return Decision{Allow: true, Reason: "new_identity"}
|
| 48 |
+
}
|
| 49 |
+
if rec.Banned(now) {
|
| 50 |
+
return Decision{
|
| 51 |
+
Code: "IDENTITY_BANNED",
|
| 52 |
+
Reason: rec.BanReason,
|
| 53 |
+
RetryAfter: rec.BannedUntil.Sub(now),
|
| 54 |
+
}
|
| 55 |
+
}
|
| 56 |
+
if rec.LastDraw.IsZero() {
|
| 57 |
+
return Decision{Allow: true, Reason: "no_prior_draw"}
|
| 58 |
+
}
|
| 59 |
+
elapsed := now.Sub(rec.LastDraw)
|
| 60 |
+
if elapsed >= p.Window {
|
| 61 |
+
return Decision{Allow: true, Reason: "window_elapsed"}
|
| 62 |
+
}
|
| 63 |
+
return Decision{
|
| 64 |
+
Code: "WINDOW_ACTIVE",
|
| 65 |
+
Reason: "a draw was already served inside the current window",
|
| 66 |
+
RetryAfter: p.Window - elapsed,
|
| 67 |
+
}
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
// EvaluateVolume inspects recent request timestamps and returns a ban when the
|
| 71 |
+
// caller has crossed a spam threshold. times must be newest-last.
|
| 72 |
+
func EvaluateVolume(p Policy, times []time.Time, now time.Time) Decision {
|
| 73 |
+
inBurst := countWithin(times, now, p.BurstWindow)
|
| 74 |
+
if p.BurstCount > 0 && inBurst >= p.BurstCount {
|
| 75 |
+
return Decision{
|
| 76 |
+
Code: "SPAM_BURST",
|
| 77 |
+
Reason: "request rate far above the permitted rate",
|
| 78 |
+
RetryAfter: p.BurstBan,
|
| 79 |
+
Ban: p.BurstBan,
|
| 80 |
+
}
|
| 81 |
+
}
|
| 82 |
+
inSpam := countWithin(times, now, p.SpamWindow)
|
| 83 |
+
if p.SpamCount > 0 && inSpam >= p.SpamCount {
|
| 84 |
+
return Decision{
|
| 85 |
+
Code: "SPAM_SUSTAINED",
|
| 86 |
+
Reason: "too many requests in the spam window",
|
| 87 |
+
RetryAfter: p.SpamBan,
|
| 88 |
+
Ban: p.SpamBan,
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
return Decision{Allow: true}
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
func countWithin(times []time.Time, now time.Time, window time.Duration) int {
|
| 95 |
+
if window <= 0 {
|
| 96 |
+
return 0
|
| 97 |
+
}
|
| 98 |
+
cutoff := now.Add(-window)
|
| 99 |
+
n := 0
|
| 100 |
+
for _, t := range times {
|
| 101 |
+
if !t.Before(cutoff) {
|
| 102 |
+
n++
|
| 103 |
+
}
|
| 104 |
+
}
|
| 105 |
+
return n
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
// ApplyBan stamps a ban on a record, escalating repeat offenders.
|
| 109 |
+
func ApplyBan(rec *store.Record, d Decision, now time.Time) {
|
| 110 |
+
if d.Ban <= 0 {
|
| 111 |
+
return
|
| 112 |
+
}
|
| 113 |
+
rec.BanCount++
|
| 114 |
+
mult := time.Duration(1)
|
| 115 |
+
if rec.BanCount > 1 {
|
| 116 |
+
// Second strike doubles, third triples, capped at two weeks.
|
| 117 |
+
mult = time.Duration(minInt(rec.BanCount, 7))
|
| 118 |
+
}
|
| 119 |
+
dur := d.Ban * mult
|
| 120 |
+
if dur > 14*24*time.Hour {
|
| 121 |
+
dur = 14 * 24 * time.Hour
|
| 122 |
+
}
|
| 123 |
+
rec.BannedUntil = now.Add(dur)
|
| 124 |
+
rec.BanReason = d.Code
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
func minInt(a, b int) int {
|
| 128 |
+
if a < b {
|
| 129 |
+
return a
|
| 130 |
+
}
|
| 131 |
+
return b
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
// Refuse builds the API error for a decision.
|
| 135 |
+
func Refuse(d Decision) *apierr.Error {
|
| 136 |
+
return apierr.Limited(d.Code, d.Reason+" — retry in "+humanise(d.RetryAfter), d.RetryAfter)
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
// humanise renders a duration the way a user-facing message should.
|
| 140 |
+
func humanise(d time.Duration) string {
|
| 141 |
+
if d < time.Minute {
|
| 142 |
+
return plural(int(d.Round(time.Second)/time.Second), "second")
|
| 143 |
+
}
|
| 144 |
+
if d < time.Hour {
|
| 145 |
+
return plural(int(d.Round(time.Minute)/time.Minute), "minute")
|
| 146 |
+
}
|
| 147 |
+
if d < 48*time.Hour {
|
| 148 |
+
return plural(int(d.Round(time.Hour)/time.Hour), "hour")
|
| 149 |
+
}
|
| 150 |
+
return plural(int(d.Round(24*time.Hour)/(24*time.Hour)), "day")
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
func plural(n int, unit string) string {
|
| 154 |
+
if n <= 0 {
|
| 155 |
+
n = 1
|
| 156 |
+
}
|
| 157 |
+
s := "s"
|
| 158 |
+
if n == 1 {
|
| 159 |
+
s = ""
|
| 160 |
+
}
|
| 161 |
+
return itoa(n) + " " + unit + s
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
func itoa(n int) string {
|
| 165 |
+
if n == 0 {
|
| 166 |
+
return "0"
|
| 167 |
+
}
|
| 168 |
+
neg := n < 0
|
| 169 |
+
if neg {
|
| 170 |
+
n = -n
|
| 171 |
+
}
|
| 172 |
+
var buf [20]byte
|
| 173 |
+
i := len(buf)
|
| 174 |
+
for n > 0 {
|
| 175 |
+
i--
|
| 176 |
+
buf[i] = byte('0' + n%10)
|
| 177 |
+
n /= 10
|
| 178 |
+
}
|
| 179 |
+
if neg {
|
| 180 |
+
i--
|
| 181 |
+
buf[i] = '-'
|
| 182 |
+
}
|
| 183 |
+
return string(buf[i:])
|
| 184 |
+
}
|
internal/ratelog/ratelog.go
ADDED
|
@@ -0,0 +1,386 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Package ratelog is a durable, sharded sliding-window event log.
|
| 2 |
+
//
|
| 3 |
+
// It exists because the spam ladder must survive a process restart. On Hugging
|
| 4 |
+
// Face Spaces the container is stopped when idle and restarted on the next
|
| 5 |
+
// request, so an in-memory counter is not a rate limit at all: an attacker
|
| 6 |
+
// simply hammers through a sleep/wake cycle.
|
| 7 |
+
//
|
| 8 |
+
// Durability model, chosen deliberately:
|
| 9 |
+
//
|
| 10 |
+
// - Every event is written with a single append(2) syscall before the request
|
| 11 |
+
// is answered. That data lives in the page cache, so it survives the
|
| 12 |
+
// process being killed or restarted (which is the threat here).
|
| 13 |
+
// - fsync happens on a timer and on shutdown, so a machine-level crash can
|
| 14 |
+
// lose at most FlushInterval of events. Paying fsync per request would cost
|
| 15 |
+
// more than the protection is worth.
|
| 16 |
+
//
|
| 17 |
+
// Layout mirrors the rest of the store so a shard can be inspected by hand:
|
| 18 |
+
//
|
| 19 |
+
// RATE_DIR/<ab>/<key>.jsonl one {"t":<unix-millis>} per line
|
| 20 |
+
//
|
| 21 |
+
// <ab> is the first two hex characters of sha256(key), so no directory grows
|
| 22 |
+
// past ~1/256 of the corpus.
|
| 23 |
+
package ratelog
|
| 24 |
+
|
| 25 |
+
import (
|
| 26 |
+
"bufio"
|
| 27 |
+
"crypto/sha256"
|
| 28 |
+
"encoding/hex"
|
| 29 |
+
"encoding/json"
|
| 30 |
+
"errors"
|
| 31 |
+
"fmt"
|
| 32 |
+
"os"
|
| 33 |
+
"path/filepath"
|
| 34 |
+
"strings"
|
| 35 |
+
"sync"
|
| 36 |
+
"time"
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
// maxEntriesPerKey bounds memory even if a caller floods one key.
|
| 40 |
+
const maxEntriesPerKey = 4096
|
| 41 |
+
|
| 42 |
+
// entry is the on-disk record. A compact integer keeps the log small.
|
| 43 |
+
type entry struct {
|
| 44 |
+
T int64 `json:"t"` // unix milliseconds
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
// Log is a thread-safe durable sliding-window log.
|
| 48 |
+
type Log struct {
|
| 49 |
+
dir string
|
| 50 |
+
retention time.Duration
|
| 51 |
+
|
| 52 |
+
mu sync.Mutex
|
| 53 |
+
entries map[string][]int64 // key -> ascending unix millis
|
| 54 |
+
files map[string]*os.File
|
| 55 |
+
|
| 56 |
+
clock func() time.Time
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
// Open loads any existing log under dir, discarding entries older than
|
| 60 |
+
// retention. retention should exceed the largest window the caller uses.
|
| 61 |
+
func Open(dir string, retention time.Duration) (*Log, error) {
|
| 62 |
+
if dir == "" {
|
| 63 |
+
return nil, errors.New("ratelog: empty directory")
|
| 64 |
+
}
|
| 65 |
+
if retention <= 0 {
|
| 66 |
+
retention = 48 * time.Hour
|
| 67 |
+
}
|
| 68 |
+
if err := os.MkdirAll(dir, 0o750); err != nil {
|
| 69 |
+
return nil, fmt.Errorf("ratelog: create %s: %w", dir, err)
|
| 70 |
+
}
|
| 71 |
+
l := &Log{
|
| 72 |
+
dir: dir,
|
| 73 |
+
retention: retention,
|
| 74 |
+
entries: map[string][]int64{},
|
| 75 |
+
files: map[string]*os.File{},
|
| 76 |
+
clock: func() time.Time { return time.Now().UTC() },
|
| 77 |
+
}
|
| 78 |
+
if err := l.load(); err != nil {
|
| 79 |
+
return nil, err
|
| 80 |
+
}
|
| 81 |
+
return l, nil
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
// SetClock overrides the clock. Tests only.
|
| 85 |
+
func (l *Log) SetClock(f func() time.Time) { l.clock = f }
|
| 86 |
+
|
| 87 |
+
// load replays the shard tree into memory.
|
| 88 |
+
func (l *Log) load() error {
|
| 89 |
+
shards, err := os.ReadDir(l.dir)
|
| 90 |
+
if errors.Is(err, os.ErrNotExist) {
|
| 91 |
+
return nil
|
| 92 |
+
}
|
| 93 |
+
if err != nil {
|
| 94 |
+
return fmt.Errorf("ratelog: read dir: %w", err)
|
| 95 |
+
}
|
| 96 |
+
cutoff := l.clock().Add(-l.retention).UnixMilli()
|
| 97 |
+
|
| 98 |
+
for _, shardDir := range shards {
|
| 99 |
+
if !shardDir.IsDir() || len(shardDir.Name()) != 2 {
|
| 100 |
+
continue
|
| 101 |
+
}
|
| 102 |
+
inner := filepath.Join(l.dir, shardDir.Name())
|
| 103 |
+
files, err := os.ReadDir(inner)
|
| 104 |
+
if err != nil {
|
| 105 |
+
return fmt.Errorf("ratelog: read %s: %w", inner, err)
|
| 106 |
+
}
|
| 107 |
+
for _, f := range files {
|
| 108 |
+
if f.IsDir() || filepath.Ext(f.Name()) != ".jsonl" {
|
| 109 |
+
continue
|
| 110 |
+
}
|
| 111 |
+
key := strings.TrimSuffix(f.Name(), ".jsonl")
|
| 112 |
+
if err := l.loadFile(filepath.Join(inner, f.Name()), key, cutoff); err != nil {
|
| 113 |
+
return err
|
| 114 |
+
}
|
| 115 |
+
}
|
| 116 |
+
}
|
| 117 |
+
return nil
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
func (l *Log) loadFile(path, key string, cutoff int64) error {
|
| 121 |
+
f, err := os.Open(path)
|
| 122 |
+
if err != nil {
|
| 123 |
+
return fmt.Errorf("ratelog: open %s: %w", path, err)
|
| 124 |
+
}
|
| 125 |
+
defer f.Close()
|
| 126 |
+
|
| 127 |
+
sc := bufio.NewScanner(f)
|
| 128 |
+
sc.Buffer(make([]byte, 0, 4096), 1<<20)
|
| 129 |
+
out := l.entries[key]
|
| 130 |
+
for sc.Scan() {
|
| 131 |
+
line := sc.Bytes()
|
| 132 |
+
if len(line) == 0 {
|
| 133 |
+
continue
|
| 134 |
+
}
|
| 135 |
+
var e entry
|
| 136 |
+
if err := json.Unmarshal(line, &e); err != nil {
|
| 137 |
+
// A torn final line from a crash is expected; skip it rather
|
| 138 |
+
// than refusing to start.
|
| 139 |
+
continue
|
| 140 |
+
}
|
| 141 |
+
if e.T < cutoff {
|
| 142 |
+
continue
|
| 143 |
+
}
|
| 144 |
+
out = append(out, e.T)
|
| 145 |
+
}
|
| 146 |
+
if err := sc.Err(); err != nil {
|
| 147 |
+
return fmt.Errorf("ratelog: scan %s: %w", path, err)
|
| 148 |
+
}
|
| 149 |
+
if len(out) > 0 {
|
| 150 |
+
l.entries[key] = out
|
| 151 |
+
}
|
| 152 |
+
return nil
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
// Record appends one event for key. The write reaches the kernel before this
|
| 156 |
+
// returns, so a subsequent process restart still sees it.
|
| 157 |
+
func (l *Log) Record(key string, at time.Time) error {
|
| 158 |
+
if key == "" {
|
| 159 |
+
return errors.New("ratelog: empty key")
|
| 160 |
+
}
|
| 161 |
+
ms := at.UnixMilli()
|
| 162 |
+
|
| 163 |
+
l.mu.Lock()
|
| 164 |
+
defer l.mu.Unlock()
|
| 165 |
+
|
| 166 |
+
list := l.entries[key]
|
| 167 |
+
list = append(list, ms)
|
| 168 |
+
if len(list) > maxEntriesPerKey {
|
| 169 |
+
list = list[len(list)-maxEntriesPerKey:]
|
| 170 |
+
}
|
| 171 |
+
l.entries[key] = list
|
| 172 |
+
|
| 173 |
+
f, err := l.fileForLocked(key)
|
| 174 |
+
if err != nil {
|
| 175 |
+
return err
|
| 176 |
+
}
|
| 177 |
+
line, err := json.Marshal(entry{T: ms})
|
| 178 |
+
if err != nil {
|
| 179 |
+
return err
|
| 180 |
+
}
|
| 181 |
+
_, err = f.Write(append(line, '\n'))
|
| 182 |
+
return err
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
// Count returns how many events for key fall inside window, ending at now.
|
| 186 |
+
func (l *Log) Count(key string, window time.Duration, now time.Time) int {
|
| 187 |
+
if window <= 0 {
|
| 188 |
+
return 0
|
| 189 |
+
}
|
| 190 |
+
cutoff := now.Add(-window).UnixMilli()
|
| 191 |
+
|
| 192 |
+
l.mu.Lock()
|
| 193 |
+
defer l.mu.Unlock()
|
| 194 |
+
|
| 195 |
+
list := l.entries[key]
|
| 196 |
+
|
| 197 |
+
// Events are appended in arrival order, which is only approximately
|
| 198 |
+
// monotonic (a retry can arrive with an earlier timestamp), so this scan
|
| 199 |
+
// must not assume sorted input. The retained slice is bounded by
|
| 200 |
+
// maxEntriesPerKey, so a full pass is cheap and always correct.
|
| 201 |
+
retainCutoff := now.Add(-l.retention).UnixMilli()
|
| 202 |
+
n := 0
|
| 203 |
+
for _, t := range list {
|
| 204 |
+
if t >= cutoff {
|
| 205 |
+
n++
|
| 206 |
+
}
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
// Opportunistically drop events that can never count again, but only when
|
| 210 |
+
// there is enough to be worth the allocation.
|
| 211 |
+
if len(list) > 64 && list[0] < retainCutoff {
|
| 212 |
+
kept := make([]int64, 0, len(list))
|
| 213 |
+
for _, t := range list {
|
| 214 |
+
if t >= retainCutoff {
|
| 215 |
+
kept = append(kept, t)
|
| 216 |
+
}
|
| 217 |
+
}
|
| 218 |
+
l.entries[key] = kept
|
| 219 |
+
}
|
| 220 |
+
return n
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
// CountPrefix sums Count over every key sharing a prefix, used for subnet and
|
| 224 |
+
// network-wide ceilings.
|
| 225 |
+
func (l *Log) CountPrefix(prefix string, window time.Duration, now time.Time) int {
|
| 226 |
+
if window <= 0 {
|
| 227 |
+
return 0
|
| 228 |
+
}
|
| 229 |
+
l.mu.Lock()
|
| 230 |
+
keys := make([]string, 0, 8)
|
| 231 |
+
for k := range l.entries {
|
| 232 |
+
if strings.HasPrefix(k, prefix) {
|
| 233 |
+
keys = append(keys, k)
|
| 234 |
+
}
|
| 235 |
+
}
|
| 236 |
+
l.mu.Unlock()
|
| 237 |
+
|
| 238 |
+
total := 0
|
| 239 |
+
for _, k := range keys {
|
| 240 |
+
total += l.Count(k, window, now)
|
| 241 |
+
}
|
| 242 |
+
return total
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
// Flush fsyncs every open file.
|
| 246 |
+
func (l *Log) Flush() error {
|
| 247 |
+
l.mu.Lock()
|
| 248 |
+
defer l.mu.Unlock()
|
| 249 |
+
var firstErr error
|
| 250 |
+
for _, f := range l.files {
|
| 251 |
+
if err := f.Sync(); err != nil && firstErr == nil {
|
| 252 |
+
firstErr = err
|
| 253 |
+
}
|
| 254 |
+
}
|
| 255 |
+
return firstErr
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
// Compact rewrites every file keeping only entries inside retention, and
|
| 259 |
+
// forgets keys with nothing left. Returns how many files were rewritten.
|
| 260 |
+
func (l *Log) Compact(now time.Time) (int, error) {
|
| 261 |
+
l.mu.Lock()
|
| 262 |
+
defer l.mu.Unlock()
|
| 263 |
+
|
| 264 |
+
cutoff := now.Add(-l.retention).UnixMilli()
|
| 265 |
+
rewritten := 0
|
| 266 |
+
|
| 267 |
+
for key, list := range l.entries {
|
| 268 |
+
kept := make([]int64, 0, len(list))
|
| 269 |
+
for _, t := range list {
|
| 270 |
+
if t >= cutoff {
|
| 271 |
+
kept = append(kept, t)
|
| 272 |
+
}
|
| 273 |
+
}
|
| 274 |
+
if len(kept) == 0 {
|
| 275 |
+
delete(l.entries, key)
|
| 276 |
+
if f, ok := l.files[key]; ok {
|
| 277 |
+
_ = f.Close()
|
| 278 |
+
delete(l.files, key)
|
| 279 |
+
}
|
| 280 |
+
if err := os.Remove(l.pathFor(key)); err != nil && !errors.Is(err, os.ErrNotExist) {
|
| 281 |
+
return rewritten, err
|
| 282 |
+
}
|
| 283 |
+
continue
|
| 284 |
+
}
|
| 285 |
+
l.entries[key] = kept
|
| 286 |
+
if len(kept) == len(list) {
|
| 287 |
+
continue
|
| 288 |
+
}
|
| 289 |
+
if err := l.rewriteLocked(key, kept); err != nil {
|
| 290 |
+
return rewritten, err
|
| 291 |
+
}
|
| 292 |
+
rewritten++
|
| 293 |
+
}
|
| 294 |
+
return rewritten, nil
|
| 295 |
+
}
|
| 296 |
+
|
| 297 |
+
func (l *Log) rewriteLocked(key string, list []int64) error {
|
| 298 |
+
if f, ok := l.files[key]; ok {
|
| 299 |
+
_ = f.Close()
|
| 300 |
+
delete(l.files, key)
|
| 301 |
+
}
|
| 302 |
+
path := l.pathFor(key)
|
| 303 |
+
tmp, err := os.CreateTemp(filepath.Dir(path), ".tmp-*")
|
| 304 |
+
if err != nil {
|
| 305 |
+
return err
|
| 306 |
+
}
|
| 307 |
+
name := tmp.Name()
|
| 308 |
+
w := bufio.NewWriter(tmp)
|
| 309 |
+
for _, t := range list {
|
| 310 |
+
line, err := json.Marshal(entry{T: t})
|
| 311 |
+
if err != nil {
|
| 312 |
+
_ = tmp.Close()
|
| 313 |
+
_ = os.Remove(name)
|
| 314 |
+
return err
|
| 315 |
+
}
|
| 316 |
+
if _, err := w.Write(append(line, '\n')); err != nil {
|
| 317 |
+
_ = tmp.Close()
|
| 318 |
+
_ = os.Remove(name)
|
| 319 |
+
return err
|
| 320 |
+
}
|
| 321 |
+
}
|
| 322 |
+
if err := w.Flush(); err != nil {
|
| 323 |
+
_ = tmp.Close()
|
| 324 |
+
_ = os.Remove(name)
|
| 325 |
+
return err
|
| 326 |
+
}
|
| 327 |
+
if err := tmp.Sync(); err != nil {
|
| 328 |
+
_ = tmp.Close()
|
| 329 |
+
_ = os.Remove(name)
|
| 330 |
+
return err
|
| 331 |
+
}
|
| 332 |
+
if err := tmp.Close(); err != nil {
|
| 333 |
+
_ = os.Remove(name)
|
| 334 |
+
return err
|
| 335 |
+
}
|
| 336 |
+
return os.Rename(name, path)
|
| 337 |
+
}
|
| 338 |
+
|
| 339 |
+
func (l *Log) fileForLocked(key string) (*os.File, error) {
|
| 340 |
+
if f, ok := l.files[key]; ok {
|
| 341 |
+
return f, nil
|
| 342 |
+
}
|
| 343 |
+
path := l.pathFor(key)
|
| 344 |
+
if err := os.MkdirAll(filepath.Dir(path), 0o750); err != nil {
|
| 345 |
+
return nil, err
|
| 346 |
+
}
|
| 347 |
+
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o640)
|
| 348 |
+
if err != nil {
|
| 349 |
+
return nil, err
|
| 350 |
+
}
|
| 351 |
+
l.files[key] = f
|
| 352 |
+
return f, nil
|
| 353 |
+
}
|
| 354 |
+
|
| 355 |
+
func (l *Log) pathFor(key string) string {
|
| 356 |
+
sum := sha256.Sum256([]byte(key))
|
| 357 |
+
shard := hex.EncodeToString(sum[:])[:2]
|
| 358 |
+
return filepath.Join(l.dir, shard, key+".jsonl")
|
| 359 |
+
}
|
| 360 |
+
|
| 361 |
+
// PathFor exposes the on-disk path for a key. Used by tests and operators.
|
| 362 |
+
func (l *Log) PathFor(key string) string { return l.pathFor(key) }
|
| 363 |
+
|
| 364 |
+
// Keys reports how many keys are currently tracked.
|
| 365 |
+
func (l *Log) Keys() int {
|
| 366 |
+
l.mu.Lock()
|
| 367 |
+
defer l.mu.Unlock()
|
| 368 |
+
return len(l.entries)
|
| 369 |
+
}
|
| 370 |
+
|
| 371 |
+
// Close flushes and closes every handle.
|
| 372 |
+
func (l *Log) Close() error {
|
| 373 |
+
l.mu.Lock()
|
| 374 |
+
defer l.mu.Unlock()
|
| 375 |
+
var firstErr error
|
| 376 |
+
for key, f := range l.files {
|
| 377 |
+
if err := f.Sync(); err != nil && firstErr == nil {
|
| 378 |
+
firstErr = err
|
| 379 |
+
}
|
| 380 |
+
if err := f.Close(); err != nil && firstErr == nil {
|
| 381 |
+
firstErr = err
|
| 382 |
+
}
|
| 383 |
+
delete(l.files, key)
|
| 384 |
+
}
|
| 385 |
+
return firstErr
|
| 386 |
+
}
|
internal/reputation/reputation.go
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Package reputation answers one question: given a client address, is this
|
| 2 |
+
// traffic coming from a hosting provider, a known VPN exit, or a network with
|
| 3 |
+
// a bad abuse history?
|
| 4 |
+
//
|
| 5 |
+
// The data is a plain JSON file (REPUTATION_FILE) so it can be refreshed from
|
| 6 |
+
// CI without rebuilding the service. When no file is configured every lookup
|
| 7 |
+
// returns "unknown" and the relay falls back to its static hosted-range list.
|
| 8 |
+
package reputation
|
| 9 |
+
|
| 10 |
+
import (
|
| 11 |
+
"encoding/json"
|
| 12 |
+
"errors"
|
| 13 |
+
"fmt"
|
| 14 |
+
"net/netip"
|
| 15 |
+
"os"
|
| 16 |
+
"sort"
|
| 17 |
+
"strings"
|
| 18 |
+
"sync"
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
// Entry is the intelligence we hold for one network range.
|
| 22 |
+
type Entry struct {
|
| 23 |
+
Prefix netip.Prefix `json:"-"`
|
| 24 |
+
CIDR string `json:"cidr"`
|
| 25 |
+
Hosting bool `json:"hosting,omitempty"`
|
| 26 |
+
VPN bool `json:"vpn,omitempty"`
|
| 27 |
+
Tor bool `json:"tor,omitempty"`
|
| 28 |
+
Abuser int `json:"abuser,omitempty"`
|
| 29 |
+
ASNOrg string `json:"asn_org,omitempty"`
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
// Table is an immutable, longest-prefix-match lookup table.
|
| 33 |
+
type Table struct {
|
| 34 |
+
mu sync.RWMutex
|
| 35 |
+
entries []Entry // sorted by prefix bits descending (longest first)
|
| 36 |
+
loaded bool
|
| 37 |
+
source string
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
// Load reads a reputation file. A missing path yields an empty table, which is
|
| 41 |
+
// a valid (fully permissive) configuration.
|
| 42 |
+
func Load(path string) (*Table, error) {
|
| 43 |
+
t := &Table{source: path}
|
| 44 |
+
if path == "" {
|
| 45 |
+
return t, nil
|
| 46 |
+
}
|
| 47 |
+
buf, err := os.ReadFile(path)
|
| 48 |
+
if errors.Is(err, os.ErrNotExist) {
|
| 49 |
+
return t, nil
|
| 50 |
+
}
|
| 51 |
+
if err != nil {
|
| 52 |
+
return nil, fmt.Errorf("reputation: read %s: %w", path, err)
|
| 53 |
+
}
|
| 54 |
+
var file struct {
|
| 55 |
+
Entries []Entry `json:"entries"`
|
| 56 |
+
}
|
| 57 |
+
if err := json.Unmarshal(buf, &file); err != nil {
|
| 58 |
+
return nil, fmt.Errorf("reputation: parse %s: %w", path, err)
|
| 59 |
+
}
|
| 60 |
+
t.entries = make([]Entry, 0, len(file.Entries))
|
| 61 |
+
for _, e := range file.Entries {
|
| 62 |
+
if strings.TrimSpace(e.CIDR) == "" {
|
| 63 |
+
continue
|
| 64 |
+
}
|
| 65 |
+
p, err := netip.ParsePrefix(strings.TrimSpace(e.CIDR))
|
| 66 |
+
if err != nil {
|
| 67 |
+
return nil, fmt.Errorf("reputation: bad cidr %q: %w", e.CIDR, err)
|
| 68 |
+
}
|
| 69 |
+
e.Prefix = p.Masked()
|
| 70 |
+
t.entries = append(t.entries, e)
|
| 71 |
+
}
|
| 72 |
+
t.sort()
|
| 73 |
+
t.loaded = len(t.entries) > 0
|
| 74 |
+
return t, nil
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
func (t *Table) sort() {
|
| 78 |
+
sort.SliceStable(t.entries, func(i, j int) bool {
|
| 79 |
+
return t.entries[i].Prefix.Bits() > t.entries[j].Prefix.Bits()
|
| 80 |
+
})
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
// Lookup returns the most specific entry covering ip.
|
| 84 |
+
func (t *Table) Lookup(ip netip.Addr) (Entry, bool) {
|
| 85 |
+
if t == nil || !ip.IsValid() {
|
| 86 |
+
return Entry{}, false
|
| 87 |
+
}
|
| 88 |
+
t.mu.RLock()
|
| 89 |
+
defer t.mu.RUnlock()
|
| 90 |
+
for i := range t.entries {
|
| 91 |
+
if t.entries[i].Prefix.Contains(ip) {
|
| 92 |
+
return t.entries[i], true
|
| 93 |
+
}
|
| 94 |
+
}
|
| 95 |
+
return Entry{}, false
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
// Size is the number of ranges loaded.
|
| 99 |
+
func (t *Table) Size() int {
|
| 100 |
+
if t == nil {
|
| 101 |
+
return 0
|
| 102 |
+
}
|
| 103 |
+
t.mu.RLock()
|
| 104 |
+
defer t.mu.RUnlock()
|
| 105 |
+
return len(t.entries)
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
// Loaded reports whether real data was found.
|
| 109 |
+
func (t *Table) Loaded() bool {
|
| 110 |
+
if t == nil {
|
| 111 |
+
return false
|
| 112 |
+
}
|
| 113 |
+
t.mu.RLock()
|
| 114 |
+
defer t.mu.RUnlock()
|
| 115 |
+
return t.loaded
|
| 116 |
+
}
|
internal/store/results.go
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package store
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"encoding/json"
|
| 5 |
+
"errors"
|
| 6 |
+
"os"
|
| 7 |
+
"path/filepath"
|
| 8 |
+
"time"
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
// Result is one benchmark run reported back by a front-end runner. We keep it
|
| 12 |
+
// because the dataset promise is two-way: the user gets a verified bank, and
|
| 13 |
+
// we get the measurements their run produced.
|
| 14 |
+
type Result struct {
|
| 15 |
+
TS time.Time `json:"ts"`
|
| 16 |
+
RequestID string `json:"request_id"`
|
| 17 |
+
IdentityID string `json:"identity_id,omitempty"`
|
| 18 |
+
ModelID string `json:"model_id"`
|
| 19 |
+
RunnerVer string `json:"runner_version,omitempty"`
|
| 20 |
+
OS string `json:"os,omitempty"`
|
| 21 |
+
Arch string `json:"arch,omitempty"`
|
| 22 |
+
Items []ResultItem `json:"items"`
|
| 23 |
+
Summary ResultSummary `json:"summary"`
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
// ResultItem is the outcome for a single example.
|
| 27 |
+
type ResultItem struct {
|
| 28 |
+
ExampleID string `json:"example_id"`
|
| 29 |
+
Category string `json:"category"`
|
| 30 |
+
Difficulty string `json:"difficulty"`
|
| 31 |
+
Answer string `json:"answer,omitempty"`
|
| 32 |
+
Code string `json:"code,omitempty"`
|
| 33 |
+
Passed bool `json:"passed"`
|
| 34 |
+
Score float64 `json:"score"`
|
| 35 |
+
LatencyMS int `json:"latency_ms,omitempty"`
|
| 36 |
+
Error string `json:"error,omitempty"`
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
// ResultSummary is the aggregate the dashboard reads.
|
| 40 |
+
type ResultSummary struct {
|
| 41 |
+
Total int `json:"total"`
|
| 42 |
+
Passed int `json:"passed"`
|
| 43 |
+
Score float64 `json:"score"`
|
| 44 |
+
ByCat map[string]float64 `json:"by_category,omitempty"`
|
| 45 |
+
DurationS float64 `json:"duration_s,omitempty"`
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
// ErrResultTooLarge is returned when a report exceeds the size cap.
|
| 49 |
+
var ErrResultTooLarge = errors.New("store: result payload too large")
|
| 50 |
+
|
| 51 |
+
// AppendResult appends a benchmark report to results/<date>.jsonl.
|
| 52 |
+
func (s *Store) AppendResult(r Result) error {
|
| 53 |
+
if len(r.Items) > 5000 {
|
| 54 |
+
return ErrResultTooLarge
|
| 55 |
+
}
|
| 56 |
+
if r.TS.IsZero() {
|
| 57 |
+
r.TS = time.Now().UTC()
|
| 58 |
+
}
|
| 59 |
+
line, err := json.Marshal(r)
|
| 60 |
+
if err != nil {
|
| 61 |
+
return err
|
| 62 |
+
}
|
| 63 |
+
path := filepath.Join(s.dir, "results", r.TS.UTC().Format("2006-01-02")+".jsonl")
|
| 64 |
+
if err := os.MkdirAll(filepath.Dir(path), 0o750); err != nil {
|
| 65 |
+
return err
|
| 66 |
+
}
|
| 67 |
+
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o640)
|
| 68 |
+
if err != nil {
|
| 69 |
+
return err
|
| 70 |
+
}
|
| 71 |
+
defer f.Close()
|
| 72 |
+
_, err = f.Write(append(line, '\n'))
|
| 73 |
+
return err
|
| 74 |
+
}
|
internal/store/store.go
ADDED
|
@@ -0,0 +1,461 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Package store is the relay's durable state: who we have seen, what they were
|
| 2 |
+
// given, and when. It is deliberately simple — small JSON files in a sharded
|
| 3 |
+
// directory tree — because the whole point is that the data stays readable and
|
| 4 |
+
// searchable by prefix instead of collapsing into one enormous file.
|
| 5 |
+
//
|
| 6 |
+
// Layout under DATA_DIR:
|
| 7 |
+
//
|
| 8 |
+
// index.json manifest: counts, format version, created_at
|
| 9 |
+
// identities/<ab>/<id>.json one record per known caller (hashes only)
|
| 10 |
+
// markers/<ab>/<hash>.json marker -> identity ids reverse index
|
| 11 |
+
// events/<YYYY-MM-DD>.jsonl append-only decision log
|
| 12 |
+
//
|
| 13 |
+
// There is deliberately no raw subtree. Raw IP addresses and machine
|
| 14 |
+
// identifiers are never written to disk anywhere: they exist only as arguments
|
| 15 |
+
// inside one function, are hashed immediately, and are then discarded. What is
|
| 16 |
+
// stored is impossible to turn back into a person, which removes the breach,
|
| 17 |
+
// retention and deletion problems rather than managing them.
|
| 18 |
+
//
|
| 19 |
+
// <ab> is the first two hex characters of a sha256, so no directory ever grows
|
| 20 |
+
// past ~1/256 of the corpus and a lookup is a single file open.
|
| 21 |
+
package store
|
| 22 |
+
|
| 23 |
+
import (
|
| 24 |
+
"crypto/sha256"
|
| 25 |
+
"encoding/hex"
|
| 26 |
+
"encoding/json"
|
| 27 |
+
"errors"
|
| 28 |
+
"fmt"
|
| 29 |
+
"os"
|
| 30 |
+
"path"
|
| 31 |
+
"path/filepath"
|
| 32 |
+
"sort"
|
| 33 |
+
"strings"
|
| 34 |
+
"sync"
|
| 35 |
+
"time"
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
// FormatVersion is bumped whenever the on-disk shape changes.
|
| 39 |
+
const FormatVersion = 1
|
| 40 |
+
|
| 41 |
+
// Record is everything we persist about one caller, using hashes only.
|
| 42 |
+
type Record struct {
|
| 43 |
+
ID string `json:"id"`
|
| 44 |
+
Markers []string `json:"markers"` // marker hashes, order preserved
|
| 45 |
+
FirstSeen time.Time `json:"first_seen"`
|
| 46 |
+
LastSeen time.Time `json:"last_seen"`
|
| 47 |
+
Requests int `json:"requests"`
|
| 48 |
+
Draws int `json:"draws"`
|
| 49 |
+
LastDraw time.Time `json:"last_draw,omitempty"`
|
| 50 |
+
|
| 51 |
+
BannedUntil time.Time `json:"banned_until,omitempty"`
|
| 52 |
+
BanReason string `json:"ban_reason,omitempty"`
|
| 53 |
+
BanCount int `json:"ban_count,omitempty"`
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
// Banned reports whether the record is currently barred.
|
| 57 |
+
func (r *Record) Banned(now time.Time) bool { return now.Before(r.BannedUntil) }
|
| 58 |
+
|
| 59 |
+
// MarkerIndex is the reverse index for one marker hash.
|
| 60 |
+
type MarkerIndex struct {
|
| 61 |
+
Hash string `json:"hash"`
|
| 62 |
+
Identities []IndexEntry `json:"identities"`
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
// IndexEntry links a marker to an identity with the times we care about.
|
| 66 |
+
type IndexEntry struct {
|
| 67 |
+
ID string `json:"id"`
|
| 68 |
+
FirstSeen time.Time `json:"first_seen"`
|
| 69 |
+
LastSeen time.Time `json:"last_seen"`
|
| 70 |
+
LastDraw time.Time `json:"last_draw"`
|
| 71 |
+
BannedUntil time.Time `json:"banned_until,omitempty"`
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
// Event is one append-only decision record.
|
| 75 |
+
type Event struct {
|
| 76 |
+
TS time.Time `json:"ts"`
|
| 77 |
+
RequestID string `json:"request_id"`
|
| 78 |
+
IdentityID string `json:"identity_id"`
|
| 79 |
+
Decision string `json:"decision"`
|
| 80 |
+
Reason string `json:"reason"`
|
| 81 |
+
IPHash string `json:"ip_hash"`
|
| 82 |
+
NetHash string `json:"network_hash"`
|
| 83 |
+
Country string `json:"country,omitempty"`
|
| 84 |
+
OS string `json:"os,omitempty"`
|
| 85 |
+
Arch string `json:"arch,omitempty"`
|
| 86 |
+
Count int `json:"count,omitempty"`
|
| 87 |
+
RetryAfter int `json:"retry_after_s,omitempty"`
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
// Index is the top-level manifest.
|
| 91 |
+
type Index struct {
|
| 92 |
+
Version int `json:"version"`
|
| 93 |
+
CreatedAt time.Time `json:"created_at"`
|
| 94 |
+
UpdatedAt time.Time `json:"updated_at"`
|
| 95 |
+
Records int `json:"records"`
|
| 96 |
+
Events int `json:"events"`
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
// Store is a thread-safe handle on the data directory.
|
| 100 |
+
type Store struct {
|
| 101 |
+
mu sync.RWMutex
|
| 102 |
+
dir string
|
| 103 |
+
|
| 104 |
+
records map[string]*Record // id -> record
|
| 105 |
+
markers map[string][]string // marker hash -> ids
|
| 106 |
+
|
| 107 |
+
events int
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
// Open loads (or initialises) a Store rooted at dir.
|
| 111 |
+
func Open(dir string) (*Store, error) {
|
| 112 |
+
if dir == "" {
|
| 113 |
+
return nil, errors.New("store: empty data dir")
|
| 114 |
+
}
|
| 115 |
+
for _, sub := range []string{"identities", "markers", "events", "results"} {
|
| 116 |
+
if err := os.MkdirAll(filepath.Join(dir, sub), 0o750); err != nil {
|
| 117 |
+
return nil, fmt.Errorf("store: create %s: %w", sub, err)
|
| 118 |
+
}
|
| 119 |
+
}
|
| 120 |
+
s := &Store{
|
| 121 |
+
dir: dir,
|
| 122 |
+
records: map[string]*Record{},
|
| 123 |
+
markers: map[string][]string{},
|
| 124 |
+
}
|
| 125 |
+
if err := s.loadIndex(); err != nil {
|
| 126 |
+
return nil, err
|
| 127 |
+
}
|
| 128 |
+
if err := s.loadRecords(); err != nil {
|
| 129 |
+
return nil, err
|
| 130 |
+
}
|
| 131 |
+
return s, nil
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
func (s *Store) loadIndex() error {
|
| 135 |
+
path := filepath.Join(s.dir, "index.json")
|
| 136 |
+
buf, err := os.ReadFile(path)
|
| 137 |
+
if errors.Is(err, os.ErrNotExist) {
|
| 138 |
+
idx := Index{Version: FormatVersion, CreatedAt: time.Now().UTC(), UpdatedAt: time.Now().UTC()}
|
| 139 |
+
return writeJSON(path, &idx)
|
| 140 |
+
}
|
| 141 |
+
if err != nil {
|
| 142 |
+
return fmt.Errorf("store: read index: %w", err)
|
| 143 |
+
}
|
| 144 |
+
var idx Index
|
| 145 |
+
if err := json.Unmarshal(buf, &idx); err != nil {
|
| 146 |
+
return fmt.Errorf("store: parse index: %w", err)
|
| 147 |
+
}
|
| 148 |
+
if idx.Version != FormatVersion {
|
| 149 |
+
return fmt.Errorf("store: index version %d, expected %d", idx.Version, FormatVersion)
|
| 150 |
+
}
|
| 151 |
+
s.events = idx.Events
|
| 152 |
+
return nil
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
// loadRecords rebuilds records and the marker index from the shard tree.
|
| 156 |
+
// This is what makes a restart (or a Hugging Face Space waking from sleep)
|
| 157 |
+
// behave exactly like the process that wrote the data.
|
| 158 |
+
func (s *Store) loadRecords() error {
|
| 159 |
+
root := filepath.Join(s.dir, "identities")
|
| 160 |
+
entries, err := os.ReadDir(root)
|
| 161 |
+
if errors.Is(err, os.ErrNotExist) {
|
| 162 |
+
return nil
|
| 163 |
+
}
|
| 164 |
+
if err != nil {
|
| 165 |
+
return fmt.Errorf("store: read identities: %w", err)
|
| 166 |
+
}
|
| 167 |
+
for _, shardDir := range entries {
|
| 168 |
+
if !shardDir.IsDir() || !ValidShard(shardDir.Name()) {
|
| 169 |
+
continue
|
| 170 |
+
}
|
| 171 |
+
inner := filepath.Join(root, shardDir.Name())
|
| 172 |
+
files, err := os.ReadDir(inner)
|
| 173 |
+
if err != nil {
|
| 174 |
+
return fmt.Errorf("store: read %s: %w", inner, err)
|
| 175 |
+
}
|
| 176 |
+
for _, f := range files {
|
| 177 |
+
if f.IsDir() || !strings.HasSuffix(f.Name(), ".json") {
|
| 178 |
+
continue
|
| 179 |
+
}
|
| 180 |
+
buf, err := os.ReadFile(filepath.Join(inner, f.Name()))
|
| 181 |
+
if err != nil {
|
| 182 |
+
return fmt.Errorf("store: read %s: %w", f.Name(), err)
|
| 183 |
+
}
|
| 184 |
+
var rec Record
|
| 185 |
+
if err := json.Unmarshal(buf, &rec); err != nil {
|
| 186 |
+
return fmt.Errorf("store: parse %s: %w", f.Name(), err)
|
| 187 |
+
}
|
| 188 |
+
if rec.ID == "" {
|
| 189 |
+
continue
|
| 190 |
+
}
|
| 191 |
+
clone := rec
|
| 192 |
+
s.records[clone.ID] = &clone
|
| 193 |
+
for _, h := range clone.Markers {
|
| 194 |
+
s.markers[h] = append(s.markers[h], clone.ID)
|
| 195 |
+
}
|
| 196 |
+
}
|
| 197 |
+
}
|
| 198 |
+
return nil
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
// shard maps a key to its two-character directory name.
|
| 202 |
+
func shard(key string) string {
|
| 203 |
+
sum := sha256.Sum256([]byte(key))
|
| 204 |
+
return hex.EncodeToString(sum[:])[:2]
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
// Lookup returns every record sharing ANY of the supplied marker hashes.
|
| 208 |
+
// This is the "is this person already known" query and it is O(len(markers))
|
| 209 |
+
// file opens, never a scan.
|
| 210 |
+
func (s *Store) Lookup(markerHashes []string) ([]*Record, error) {
|
| 211 |
+
seen := map[string]bool{}
|
| 212 |
+
var out []*Record
|
| 213 |
+
s.mu.RLock()
|
| 214 |
+
defer s.mu.RUnlock()
|
| 215 |
+
for _, h := range markerHashes {
|
| 216 |
+
ids, ok := s.markers[h]
|
| 217 |
+
if !ok {
|
| 218 |
+
continue
|
| 219 |
+
}
|
| 220 |
+
for _, id := range ids {
|
| 221 |
+
if seen[id] {
|
| 222 |
+
continue
|
| 223 |
+
}
|
| 224 |
+
rec, ok := s.records[id]
|
| 225 |
+
if !ok {
|
| 226 |
+
continue
|
| 227 |
+
}
|
| 228 |
+
seen[id] = true
|
| 229 |
+
out = append(out, rec)
|
| 230 |
+
}
|
| 231 |
+
}
|
| 232 |
+
sort.Slice(out, func(i, j int) bool { return out[i].LastSeen.After(out[j].LastSeen) })
|
| 233 |
+
return out, nil
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
// Get returns a record by ID.
|
| 237 |
+
func (s *Store) Get(id string) (*Record, bool) {
|
| 238 |
+
s.mu.RLock()
|
| 239 |
+
defer s.mu.RUnlock()
|
| 240 |
+
rec, ok := s.records[id]
|
| 241 |
+
return rec, ok
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
// Put persists a record and its marker links atomically enough for our needs:
|
| 245 |
+
// we write the shard files first, then update the in-memory maps under a lock.
|
| 246 |
+
func (s *Store) Put(rec *Record) error {
|
| 247 |
+
s.mu.Lock()
|
| 248 |
+
defer s.mu.Unlock()
|
| 249 |
+
|
| 250 |
+
clone := *rec
|
| 251 |
+
s.records[clone.ID] = &clone
|
| 252 |
+
|
| 253 |
+
for _, h := range clone.Markers {
|
| 254 |
+
ids := s.markers[h]
|
| 255 |
+
found := false
|
| 256 |
+
for _, id := range ids {
|
| 257 |
+
if id == clone.ID {
|
| 258 |
+
found = true
|
| 259 |
+
break
|
| 260 |
+
}
|
| 261 |
+
}
|
| 262 |
+
if !found {
|
| 263 |
+
s.markers[h] = append(ids, clone.ID)
|
| 264 |
+
}
|
| 265 |
+
}
|
| 266 |
+
return s.persistLocked(&clone)
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
func (s *Store) persistLocked(rec *Record) error {
|
| 270 |
+
if err := writeJSON(filepath.Join(s.dir, "identities", shard(rec.ID), rec.ID+".json"), rec); err != nil {
|
| 271 |
+
return err
|
| 272 |
+
}
|
| 273 |
+
for _, h := range rec.Markers {
|
| 274 |
+
idxs := make([]IndexEntry, 0, len(s.markers[h]))
|
| 275 |
+
for _, id := range s.markers[h] {
|
| 276 |
+
r, ok := s.records[id]
|
| 277 |
+
if !ok {
|
| 278 |
+
continue
|
| 279 |
+
}
|
| 280 |
+
idxs = append(idxs, IndexEntry{
|
| 281 |
+
ID: r.ID,
|
| 282 |
+
FirstSeen: r.FirstSeen,
|
| 283 |
+
LastSeen: r.LastSeen,
|
| 284 |
+
LastDraw: r.LastDraw,
|
| 285 |
+
BannedUntil: r.BannedUntil,
|
| 286 |
+
})
|
| 287 |
+
}
|
| 288 |
+
if err := writeJSON(filepath.Join(s.dir, "markers", shard(h), h+".json"), MarkerIndex{Hash: h, Identities: idxs}); err != nil {
|
| 289 |
+
return err
|
| 290 |
+
}
|
| 291 |
+
}
|
| 292 |
+
return nil
|
| 293 |
+
}
|
| 294 |
+
|
| 295 |
+
// AppendEvent adds one line to today's decision log.
|
| 296 |
+
func (s *Store) AppendEvent(ev Event) error {
|
| 297 |
+
if ev.TS.IsZero() {
|
| 298 |
+
ev.TS = time.Now().UTC()
|
| 299 |
+
}
|
| 300 |
+
line, err := json.Marshal(ev)
|
| 301 |
+
if err != nil {
|
| 302 |
+
return err
|
| 303 |
+
}
|
| 304 |
+
path := filepath.Join(s.dir, "events", ev.TS.UTC().Format("2006-01-02")+".jsonl")
|
| 305 |
+
if err := os.MkdirAll(filepath.Dir(path), 0o750); err != nil {
|
| 306 |
+
return err
|
| 307 |
+
}
|
| 308 |
+
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o640)
|
| 309 |
+
if err != nil {
|
| 310 |
+
return err
|
| 311 |
+
}
|
| 312 |
+
defer f.Close()
|
| 313 |
+
if _, err := f.Write(append(line, '\n')); err != nil {
|
| 314 |
+
return err
|
| 315 |
+
}
|
| 316 |
+
s.mu.Lock()
|
| 317 |
+
s.events++
|
| 318 |
+
s.mu.Unlock()
|
| 319 |
+
return nil
|
| 320 |
+
}
|
| 321 |
+
|
| 322 |
+
// Prune clears expired bans. There is no personal data left to expire: only
|
| 323 |
+
// salted hashes are stored, and a hash has no retention obligation.
|
| 324 |
+
func (s *Store) Prune(now time.Time) (int, error) {
|
| 325 |
+
s.mu.Lock()
|
| 326 |
+
defer s.mu.Unlock()
|
| 327 |
+
|
| 328 |
+
cleared := 0
|
| 329 |
+
for _, rec := range s.records {
|
| 330 |
+
if !rec.BannedUntil.IsZero() && !now.Before(rec.BannedUntil) {
|
| 331 |
+
rec.BannedUntil = time.Time{}
|
| 332 |
+
rec.BanReason = ""
|
| 333 |
+
if err := s.persistLocked(rec); err != nil {
|
| 334 |
+
return cleared, err
|
| 335 |
+
}
|
| 336 |
+
cleared++
|
| 337 |
+
}
|
| 338 |
+
}
|
| 339 |
+
return cleared, nil
|
| 340 |
+
}
|
| 341 |
+
|
| 342 |
+
// Stats reports headline counters for the health endpoint.
|
| 343 |
+
func (s *Store) Stats() (records, markers int) {
|
| 344 |
+
s.mu.RLock()
|
| 345 |
+
defer s.mu.RUnlock()
|
| 346 |
+
return len(s.records), len(s.markers)
|
| 347 |
+
}
|
| 348 |
+
|
| 349 |
+
// FlushIndex writes the manifest. Best effort; called on shutdown and by the
|
| 350 |
+
// background flusher.
|
| 351 |
+
func (s *Store) FlushIndex() error {
|
| 352 |
+
s.mu.RLock()
|
| 353 |
+
idx := Index{
|
| 354 |
+
Version: FormatVersion,
|
| 355 |
+
CreatedAt: time.Now().UTC(),
|
| 356 |
+
UpdatedAt: time.Now().UTC(),
|
| 357 |
+
Records: len(s.records),
|
| 358 |
+
Events: s.events,
|
| 359 |
+
}
|
| 360 |
+
s.mu.RUnlock()
|
| 361 |
+
if prev, err := os.ReadFile(filepath.Join(s.dir, "index.json")); err == nil {
|
| 362 |
+
var old Index
|
| 363 |
+
if json.Unmarshal(prev, &old) == nil && !old.CreatedAt.IsZero() {
|
| 364 |
+
idx.CreatedAt = old.CreatedAt
|
| 365 |
+
}
|
| 366 |
+
}
|
| 367 |
+
return writeJSON(filepath.Join(s.dir, "index.json"), &idx)
|
| 368 |
+
}
|
| 369 |
+
|
| 370 |
+
// writeJSON writes atomically: temp file in the same directory, then rename.
|
| 371 |
+
func writeJSON(path string, v any) error {
|
| 372 |
+
if err := os.MkdirAll(filepath.Dir(path), 0o750); err != nil {
|
| 373 |
+
return err
|
| 374 |
+
}
|
| 375 |
+
buf, err := json.MarshalIndent(v, "", " ")
|
| 376 |
+
if err != nil {
|
| 377 |
+
return err
|
| 378 |
+
}
|
| 379 |
+
buf = append(buf, '\n')
|
| 380 |
+
tmp, err := os.CreateTemp(filepath.Dir(path), ".tmp-*")
|
| 381 |
+
if err != nil {
|
| 382 |
+
return err
|
| 383 |
+
}
|
| 384 |
+
name := tmp.Name()
|
| 385 |
+
defer os.Remove(name)
|
| 386 |
+
if _, err := tmp.Write(buf); err != nil {
|
| 387 |
+
tmp.Close()
|
| 388 |
+
return err
|
| 389 |
+
}
|
| 390 |
+
if err := tmp.Sync(); err != nil {
|
| 391 |
+
tmp.Close()
|
| 392 |
+
return err
|
| 393 |
+
}
|
| 394 |
+
if err := tmp.Close(); err != nil {
|
| 395 |
+
return err
|
| 396 |
+
}
|
| 397 |
+
return os.Rename(name, path)
|
| 398 |
+
}
|
| 399 |
+
|
| 400 |
+
// ValidShard reports whether a directory name looks like one we create.
|
| 401 |
+
func ValidShard(name string) bool {
|
| 402 |
+
if len(name) != 2 {
|
| 403 |
+
return false
|
| 404 |
+
}
|
| 405 |
+
_, err := hex.DecodeString(name)
|
| 406 |
+
return err == nil && !strings.ContainsAny(name, "./")
|
| 407 |
+
}
|
| 408 |
+
|
| 409 |
+
// ShardOf exposes the shard directory name for a key, so callers (and tests)
|
| 410 |
+
// never have to reimplement the layout.
|
| 411 |
+
func ShardOf(key string) string { return shard(key) }
|
| 412 |
+
|
| 413 |
+
// --- dataset mirror helpers -------------------------------------------------
|
| 414 |
+
//
|
| 415 |
+
// These expose the canonical on-disk path and serialised form for each artefact
|
| 416 |
+
// so the sync controller publishes byte-identical content to what the store
|
| 417 |
+
// writes locally. Two code paths producing two formats would be a silent
|
| 418 |
+
// source of dataset drift.
|
| 419 |
+
|
| 420 |
+
// RecordPath is the dataset path for a hashed identity record.
|
| 421 |
+
func RecordPath(id string) string { return path.Join("identities", shard(id), id+".json") }
|
| 422 |
+
|
| 423 |
+
// EventPath is the dataset path for one day of the event log.
|
| 424 |
+
func EventPath(at time.Time) string {
|
| 425 |
+
return path.Join("events", at.UTC().Format("2006-01-02")+".jsonl")
|
| 426 |
+
}
|
| 427 |
+
|
| 428 |
+
// ResultPath is the dataset path for one day of benchmark results.
|
| 429 |
+
func ResultPath(at time.Time) string {
|
| 430 |
+
return path.Join("results", at.UTC().Format("2006-01-02")+".jsonl")
|
| 431 |
+
}
|
| 432 |
+
|
| 433 |
+
// MarshalRecord serialises a record exactly as it is stored.
|
| 434 |
+
func MarshalRecord(rec *Record) ([]byte, error) {
|
| 435 |
+
buf, err := json.MarshalIndent(rec, "", " ")
|
| 436 |
+
if err != nil {
|
| 437 |
+
return nil, err
|
| 438 |
+
}
|
| 439 |
+
return append(buf, '\n'), nil
|
| 440 |
+
}
|
| 441 |
+
|
| 442 |
+
// ReadEventDay returns the whole event log for a day, for publication as one
|
| 443 |
+
// file. A day is a natural batching unit: it is append-mostly and small.
|
| 444 |
+
func (s *Store) ReadEventDay(at time.Time) ([]byte, error) {
|
| 445 |
+
p := filepath.Join(s.dir, "events", at.UTC().Format("2006-01-02")+".jsonl")
|
| 446 |
+
buf, err := os.ReadFile(p)
|
| 447 |
+
if errors.Is(err, os.ErrNotExist) {
|
| 448 |
+
return []byte{}, nil
|
| 449 |
+
}
|
| 450 |
+
return buf, err
|
| 451 |
+
}
|
| 452 |
+
|
| 453 |
+
// ReadResultDay returns the whole result log for a day.
|
| 454 |
+
func (s *Store) ReadResultDay(at time.Time) ([]byte, error) {
|
| 455 |
+
p := filepath.Join(s.dir, "results", at.UTC().Format("2006-01-02")+".jsonl")
|
| 456 |
+
buf, err := os.ReadFile(p)
|
| 457 |
+
if errors.Is(err, os.ErrNotExist) {
|
| 458 |
+
return []byte{}, nil
|
| 459 |
+
}
|
| 460 |
+
return buf, err
|
| 461 |
+
}
|
internal/syncctl/syncctl.go
ADDED
|
@@ -0,0 +1,524 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Package syncctl is the single writer for the private dataset.
|
| 2 |
+
//
|
| 3 |
+
// The dataset is a git repository, and git does not merge concurrent pushes:
|
| 4 |
+
// two writers racing each other means one of them is rejected and its data is
|
| 5 |
+
// lost or must be reapplied. Rather than scatter retry logic through the call
|
| 6 |
+
// sites, every write goes through one controller that:
|
| 7 |
+
//
|
| 8 |
+
// 1. Coalesces. Changes are queued and published in batches on a fixed
|
| 9 |
+
// interval, so a burst of traffic becomes one commit instead of hundreds.
|
| 10 |
+
// 2. Serialises. Exactly one publish runs at a time, process-wide, so a race
|
| 11 |
+
// with the remote cannot happen by construction.
|
| 12 |
+
// 3. Deduplicates. A queued path replaces any earlier queued version of
|
| 13 |
+
// itself, so a file rewritten five times costs one write.
|
| 14 |
+
// 4. Skips unchanged files. Content is compared by git blob hash against the
|
| 15 |
+
// remote tree, so an idle system produces no commits at all.
|
| 16 |
+
// 5. Adapts. If the remote rate-limits us, the flush interval doubles (with a
|
| 17 |
+
// ceiling) and is restored on success: gentler when pushed, faster when not.
|
| 18 |
+
// 6. Never blocks a request. Enqueue is a memory operation with a hard budget;
|
| 19 |
+
// if the queue is full the newest change is dropped and counted, because a
|
| 20 |
+
// slow dataset must not slow down draws.
|
| 21 |
+
package syncctl
|
| 22 |
+
|
| 23 |
+
import (
|
| 24 |
+
"context"
|
| 25 |
+
"errors"
|
| 26 |
+
"fmt"
|
| 27 |
+
"io"
|
| 28 |
+
"log/slog"
|
| 29 |
+
"sort"
|
| 30 |
+
"strings"
|
| 31 |
+
"sync"
|
| 32 |
+
"sync/atomic"
|
| 33 |
+
"time"
|
| 34 |
+
|
| 35 |
+
"github.com/archnemix/archx-eval/relay/internal/hf"
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
// Config controls batching and backoff.
|
| 39 |
+
type Config struct {
|
| 40 |
+
// Interval is the target flush cadence.
|
| 41 |
+
Interval time.Duration
|
| 42 |
+
// MinInterval and MaxInterval bound the adaptive backoff.
|
| 43 |
+
MinInterval time.Duration
|
| 44 |
+
MaxInterval time.Duration
|
| 45 |
+
// MaxFiles caps a single commit; larger queues split across commits.
|
| 46 |
+
MaxFiles int
|
| 47 |
+
// MaxQueued caps memory. Beyond this, new changes are dropped and counted.
|
| 48 |
+
MaxQueued int
|
| 49 |
+
// MaxRetries is how many times one batch is retried before being dropped.
|
| 50 |
+
MaxRetries int
|
| 51 |
+
// RetryBase is the first retry delay; it doubles each attempt.
|
| 52 |
+
RetryBase time.Duration
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
// DefaultConfig is tuned for a private dataset with modest traffic.
|
| 56 |
+
func DefaultConfig() Config {
|
| 57 |
+
return Config{
|
| 58 |
+
Interval: 30 * time.Second,
|
| 59 |
+
MinInterval: 15 * time.Second,
|
| 60 |
+
MaxInterval: 10 * time.Minute,
|
| 61 |
+
MaxFiles: 100,
|
| 62 |
+
MaxQueued: 20000,
|
| 63 |
+
MaxRetries: 4,
|
| 64 |
+
RetryBase: 2 * time.Second,
|
| 65 |
+
}
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
// Stats is a snapshot of controller health, safe to serve from /health.
|
| 69 |
+
type Stats struct {
|
| 70 |
+
Queued int `json:"queued"`
|
| 71 |
+
Published int64 `json:"published"`
|
| 72 |
+
Skipped int64 `json:"skipped"`
|
| 73 |
+
Retries int64 `json:"retries"`
|
| 74 |
+
Commits int64 `json:"commits"`
|
| 75 |
+
Failures int64 `json:"failures"`
|
| 76 |
+
Dropped int64 `json:"dropped"`
|
| 77 |
+
IntervalMS int64 `json:"interval_ms"`
|
| 78 |
+
LastFlushUnix int64 `json:"last_flush_unix"`
|
| 79 |
+
LastError string `json:"last_error,omitempty"`
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
// Controller is the single writer.
|
| 83 |
+
type Controller struct {
|
| 84 |
+
cfg Config
|
| 85 |
+
remote hf.Remote
|
| 86 |
+
log *slog.Logger
|
| 87 |
+
|
| 88 |
+
// mu guards the queue and the version cache. It is held only for short
|
| 89 |
+
// in-memory operations, never across a network call.
|
| 90 |
+
mu sync.Mutex
|
| 91 |
+
queue map[string][]byte
|
| 92 |
+
|
| 93 |
+
// publishMu is held across the whole remote write. This is what actually
|
| 94 |
+
// guarantees "one commit in flight": the queue lock is far too wide to hold
|
| 95 |
+
// during a network call, and far too narrow to provide that guarantee.
|
| 96 |
+
// A probe test asserts peak concurrency stays at 1.
|
| 97 |
+
publishMu sync.Mutex
|
| 98 |
+
|
| 99 |
+
// versions caches the remote blob hash per path so we do not re-list the
|
| 100 |
+
// whole tree for every batch. Guarded by mu.
|
| 101 |
+
versions map[string]string
|
| 102 |
+
listed bool
|
| 103 |
+
|
| 104 |
+
interval time.Duration
|
| 105 |
+
|
| 106 |
+
published atomic.Int64
|
| 107 |
+
skipped atomic.Int64
|
| 108 |
+
retries atomic.Int64
|
| 109 |
+
commits atomic.Int64
|
| 110 |
+
failures atomic.Int64
|
| 111 |
+
dropped atomic.Int64
|
| 112 |
+
|
| 113 |
+
lastFlush atomic.Int64
|
| 114 |
+
lastErr atomic.Value // string
|
| 115 |
+
|
| 116 |
+
stopOnce sync.Once
|
| 117 |
+
stop chan struct{}
|
| 118 |
+
done chan struct{}
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
// New builds a controller. It does not start the background loop; call Run.
|
| 122 |
+
func New(cfg Config, remote hf.Remote, log *slog.Logger) *Controller {
|
| 123 |
+
if cfg.Interval <= 0 {
|
| 124 |
+
cfg.Interval = DefaultConfig().Interval
|
| 125 |
+
}
|
| 126 |
+
if cfg.MaxFiles <= 0 {
|
| 127 |
+
cfg.MaxFiles = DefaultConfig().MaxFiles
|
| 128 |
+
}
|
| 129 |
+
if cfg.MaxQueued <= 0 {
|
| 130 |
+
cfg.MaxQueued = DefaultConfig().MaxQueued
|
| 131 |
+
}
|
| 132 |
+
// MinInterval/MaxInterval bound the adaptive backoff. Leaving them zero is
|
| 133 |
+
// not harmless: widen() clamps to MaxInterval, so a zero ceiling would set
|
| 134 |
+
// the interval to 0 on the first failure and the controller would hammer a
|
| 135 |
+
// failing dataset in a tight loop instead of backing off.
|
| 136 |
+
if cfg.MinInterval <= 0 {
|
| 137 |
+
cfg.MinInterval = DefaultConfig().MinInterval
|
| 138 |
+
}
|
| 139 |
+
if cfg.MaxInterval <= 0 {
|
| 140 |
+
cfg.MaxInterval = DefaultConfig().MaxInterval
|
| 141 |
+
}
|
| 142 |
+
if cfg.MaxInterval < cfg.Interval {
|
| 143 |
+
cfg.MaxInterval = cfg.Interval
|
| 144 |
+
}
|
| 145 |
+
if cfg.MinInterval > cfg.Interval {
|
| 146 |
+
cfg.MinInterval = cfg.Interval
|
| 147 |
+
}
|
| 148 |
+
if log == nil {
|
| 149 |
+
log = slog.New(slog.NewTextHandler(io.Discard, nil))
|
| 150 |
+
}
|
| 151 |
+
return &Controller{
|
| 152 |
+
cfg: cfg,
|
| 153 |
+
remote: remote,
|
| 154 |
+
log: log,
|
| 155 |
+
queue: make(map[string][]byte, 64),
|
| 156 |
+
versions: make(map[string]string, 256),
|
| 157 |
+
interval: cfg.Interval,
|
| 158 |
+
stop: make(chan struct{}),
|
| 159 |
+
done: make(chan struct{}),
|
| 160 |
+
}
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
// Enqueue records a change. It never blocks on the network and never returns an
|
| 164 |
+
// error to a request path: if the queue is full the change is dropped and
|
| 165 |
+
// counted, because losing a sync record is better than stalling a draw.
|
| 166 |
+
func (c *Controller) Enqueue(path string, content []byte) {
|
| 167 |
+
if path == "" {
|
| 168 |
+
return
|
| 169 |
+
}
|
| 170 |
+
c.mu.Lock()
|
| 171 |
+
defer c.mu.Unlock()
|
| 172 |
+
if _, exists := c.queue[path]; !exists && len(c.queue) >= c.cfg.MaxQueued {
|
| 173 |
+
c.dropped.Add(1)
|
| 174 |
+
return
|
| 175 |
+
}
|
| 176 |
+
// Replace, never append: the newest version of a path wins.
|
| 177 |
+
c.queue[path] = content
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
// EnqueueFile is a convenience wrapper.
|
| 181 |
+
func (c *Controller) EnqueueFile(f hf.File) { c.Enqueue(f.Path, f.Content) }
|
| 182 |
+
|
| 183 |
+
// Queued reports how many distinct paths are waiting.
|
| 184 |
+
func (c *Controller) Queued() int {
|
| 185 |
+
c.mu.Lock()
|
| 186 |
+
defer c.mu.Unlock()
|
| 187 |
+
return len(c.queue)
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
// Stats snapshots counters.
|
| 191 |
+
func (c *Controller) Stats() Stats {
|
| 192 |
+
s := Stats{
|
| 193 |
+
Queued: c.Queued(),
|
| 194 |
+
Published: c.published.Load(),
|
| 195 |
+
Skipped: c.skipped.Load(),
|
| 196 |
+
Retries: c.retries.Load(),
|
| 197 |
+
Commits: c.commits.Load(),
|
| 198 |
+
Failures: c.failures.Load(),
|
| 199 |
+
Dropped: c.dropped.Load(),
|
| 200 |
+
IntervalMS: int64(c.currentInterval() / time.Millisecond),
|
| 201 |
+
LastFlushUnix: c.lastFlush.Load(),
|
| 202 |
+
}
|
| 203 |
+
if v, ok := c.lastErr.Load().(string); ok {
|
| 204 |
+
s.LastError = v
|
| 205 |
+
}
|
| 206 |
+
return s
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
func (c *Controller) currentInterval() time.Duration {
|
| 210 |
+
c.mu.Lock()
|
| 211 |
+
defer c.mu.Unlock()
|
| 212 |
+
return c.interval
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
// Run drives the flush loop until the context is cancelled or Stop is called.
|
| 216 |
+
// A final flush is attempted on shutdown so queued work is not silently lost.
|
| 217 |
+
func (c *Controller) Run(ctx context.Context) {
|
| 218 |
+
defer close(c.done)
|
| 219 |
+
for {
|
| 220 |
+
timer := time.NewTimer(c.currentInterval())
|
| 221 |
+
select {
|
| 222 |
+
case <-ctx.Done():
|
| 223 |
+
timer.Stop()
|
| 224 |
+
c.flushAll(context.Background())
|
| 225 |
+
return
|
| 226 |
+
case <-c.stop:
|
| 227 |
+
timer.Stop()
|
| 228 |
+
c.flushAll(context.Background())
|
| 229 |
+
return
|
| 230 |
+
case <-timer.C:
|
| 231 |
+
c.flushAll(ctx)
|
| 232 |
+
}
|
| 233 |
+
}
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
// Stop asks the loop to finish and waits for it.
|
| 237 |
+
func (c *Controller) Stop() {
|
| 238 |
+
c.stopOnce.Do(func() { close(c.stop) })
|
| 239 |
+
<-c.done
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
// FlushNow publishes everything queued right now. Used by -sync and by tests.
|
| 243 |
+
func (c *Controller) FlushNow(ctx context.Context) error { return c.flushAll(ctx) }
|
| 244 |
+
|
| 245 |
+
// flushAll repeatedly publishes batches until the queue is empty or a batch
|
| 246 |
+
// fails. Every iteration takes the lock, so no other publish can interleave.
|
| 247 |
+
func (c *Controller) flushAll(ctx context.Context) error {
|
| 248 |
+
var lastErr error
|
| 249 |
+
for {
|
| 250 |
+
err := c.flushOnce(ctx)
|
| 251 |
+
if err != nil {
|
| 252 |
+
lastErr = err
|
| 253 |
+
if !isRetryable(err) {
|
| 254 |
+
break
|
| 255 |
+
}
|
| 256 |
+
}
|
| 257 |
+
if c.Queued() == 0 {
|
| 258 |
+
break
|
| 259 |
+
}
|
| 260 |
+
}
|
| 261 |
+
return lastErr
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
// flushOnce publishes at most MaxFiles changed files as a single commit.
|
| 265 |
+
func (c *Controller) flushOnce(ctx context.Context) error {
|
| 266 |
+
// Lock ordering is always publishMu then mu, never the reverse. Enqueue
|
| 267 |
+
// only ever takes mu, so it can never block behind a network call.
|
| 268 |
+
c.publishMu.Lock()
|
| 269 |
+
|
| 270 |
+
c.mu.Lock()
|
| 271 |
+
if len(c.queue) == 0 {
|
| 272 |
+
c.mu.Unlock()
|
| 273 |
+
c.publishMu.Unlock()
|
| 274 |
+
return nil
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
// Snapshot a batch and clear it from the queue. Clearing before the network
|
| 278 |
+
// call means a change enqueued during the call lands in the next batch
|
| 279 |
+
// instead of being silently included in a commit we might retry.
|
| 280 |
+
batch := make(map[string][]byte, len(c.queue))
|
| 281 |
+
paths := make([]string, 0, len(c.queue))
|
| 282 |
+
for p := range c.queue {
|
| 283 |
+
paths = append(paths, p)
|
| 284 |
+
}
|
| 285 |
+
sort.Strings(paths)
|
| 286 |
+
if len(paths) > c.cfg.MaxFiles {
|
| 287 |
+
paths = paths[:c.cfg.MaxFiles]
|
| 288 |
+
}
|
| 289 |
+
for _, p := range paths {
|
| 290 |
+
batch[p] = c.queue[p]
|
| 291 |
+
delete(c.queue, p)
|
| 292 |
+
}
|
| 293 |
+
for _, p := range paths {
|
| 294 |
+
if !c.listed {
|
| 295 |
+
break
|
| 296 |
+
}
|
| 297 |
+
if cached, ok := c.versions[p]; ok && cached == hf.BlobSHA(batch[p]) {
|
| 298 |
+
delete(batch, p)
|
| 299 |
+
c.skipped.Add(1)
|
| 300 |
+
}
|
| 301 |
+
}
|
| 302 |
+
c.mu.Unlock()
|
| 303 |
+
|
| 304 |
+
if len(batch) == 0 {
|
| 305 |
+
c.publishMu.Unlock()
|
| 306 |
+
return nil
|
| 307 |
+
}
|
| 308 |
+
|
| 309 |
+
// Refresh the remote tree once per process, and again whenever the remote
|
| 310 |
+
// rejects a commit for being out of date.
|
| 311 |
+
if err := c.ensureListed(ctx); err != nil {
|
| 312 |
+
defer c.publishMu.Unlock()
|
| 313 |
+
return c.requeue(batch, err)
|
| 314 |
+
}
|
| 315 |
+
|
| 316 |
+
c.mu.Lock()
|
| 317 |
+
for p, content := range batch {
|
| 318 |
+
if cached, ok := c.versions[p]; ok && cached == hf.BlobSHA(content) {
|
| 319 |
+
delete(batch, p)
|
| 320 |
+
c.skipped.Add(1)
|
| 321 |
+
}
|
| 322 |
+
}
|
| 323 |
+
c.mu.Unlock()
|
| 324 |
+
if len(batch) == 0 {
|
| 325 |
+
c.publishMu.Unlock()
|
| 326 |
+
return nil
|
| 327 |
+
}
|
| 328 |
+
|
| 329 |
+
files := make([]hf.File, 0, len(batch))
|
| 330 |
+
for p, content := range batch {
|
| 331 |
+
files = append(files, hf.File{Path: p, Content: content})
|
| 332 |
+
}
|
| 333 |
+
sort.Slice(files, func(i, j int) bool { return files[i].Path < files[j].Path })
|
| 334 |
+
|
| 335 |
+
summary := fmt.Sprintf("relay sync: %d file(s) at %s",
|
| 336 |
+
len(files), time.Now().UTC().Format(time.RFC3339))
|
| 337 |
+
|
| 338 |
+
retried, err := c.publishWithRetry(ctx, summary, files)
|
| 339 |
+
if retried {
|
| 340 |
+
// The remote pushed back at us even though we eventually got through.
|
| 341 |
+
// Slow down rather than hammering it again on the next tick.
|
| 342 |
+
c.retries.Add(1)
|
| 343 |
+
c.widen()
|
| 344 |
+
}
|
| 345 |
+
if err != nil {
|
| 346 |
+
c.failures.Add(1)
|
| 347 |
+
c.lastErr.Store(err.Error())
|
| 348 |
+
c.widen()
|
| 349 |
+
c.publishMu.Unlock()
|
| 350 |
+
return c.requeue(batch, err)
|
| 351 |
+
}
|
| 352 |
+
|
| 353 |
+
// Success: record the new versions, narrow the interval back, count it.
|
| 354 |
+
// Each lock is taken, released, and never held across another acquisition.
|
| 355 |
+
c.mu.Lock()
|
| 356 |
+
for _, f := range files {
|
| 357 |
+
c.versions[f.Path] = f.Version()
|
| 358 |
+
}
|
| 359 |
+
remaining := len(c.queue)
|
| 360 |
+
c.mu.Unlock()
|
| 361 |
+
|
| 362 |
+
c.published.Add(int64(len(files)))
|
| 363 |
+
c.commits.Add(1)
|
| 364 |
+
c.lastFlush.Store(time.Now().Unix())
|
| 365 |
+
c.lastErr.Store("")
|
| 366 |
+
c.narrow()
|
| 367 |
+
|
| 368 |
+
c.publishMu.Unlock()
|
| 369 |
+
|
| 370 |
+
c.log.Info("dataset sync published",
|
| 371 |
+
"files", len(files), "queued", remaining, "interval_s", int(c.currentInterval()/time.Second))
|
| 372 |
+
return nil
|
| 373 |
+
}
|
| 374 |
+
|
| 375 |
+
// ensureListed loads the remote tree once so unchanged files can be skipped.
|
| 376 |
+
func (c *Controller) ensureListed(ctx context.Context) error {
|
| 377 |
+
c.mu.Lock()
|
| 378 |
+
need := !c.listed
|
| 379 |
+
c.mu.Unlock()
|
| 380 |
+
if !need {
|
| 381 |
+
return nil
|
| 382 |
+
}
|
| 383 |
+
|
| 384 |
+
files, err := c.remote.List(ctx, "")
|
| 385 |
+
if err != nil {
|
| 386 |
+
return err
|
| 387 |
+
}
|
| 388 |
+
|
| 389 |
+
c.mu.Lock()
|
| 390 |
+
for _, f := range files {
|
| 391 |
+
c.versions[f.Path] = f.Version
|
| 392 |
+
}
|
| 393 |
+
c.listed = true
|
| 394 |
+
c.mu.Unlock()
|
| 395 |
+
|
| 396 |
+
c.log.Info("dataset tree indexed", "files", len(files))
|
| 397 |
+
return nil
|
| 398 |
+
}
|
| 399 |
+
|
| 400 |
+
// publishWithRetry retries one commit, honouring Retry-After when given. The
|
| 401 |
+
// first return value reports whether at least one retry was needed.
|
| 402 |
+
func (c *Controller) publishWithRetry(ctx context.Context, summary string, files []hf.File) (bool, error) {
|
| 403 |
+
delay := c.cfg.RetryBase
|
| 404 |
+
var lastErr error
|
| 405 |
+
retried := false
|
| 406 |
+
for attempt := 0; attempt <= c.cfg.MaxRetries; attempt++ {
|
| 407 |
+
if attempt > 0 {
|
| 408 |
+
retried = true
|
| 409 |
+
select {
|
| 410 |
+
case <-ctx.Done():
|
| 411 |
+
return retried, ctx.Err()
|
| 412 |
+
case <-time.After(delay):
|
| 413 |
+
}
|
| 414 |
+
delay *= 2
|
| 415 |
+
}
|
| 416 |
+
err := c.remote.Publish(ctx, summary, files)
|
| 417 |
+
if err == nil {
|
| 418 |
+
return retried, nil
|
| 419 |
+
}
|
| 420 |
+
lastErr = err
|
| 421 |
+
if !isRetryable(err) {
|
| 422 |
+
return retried, err
|
| 423 |
+
}
|
| 424 |
+
// The remote tree may have moved; force a re-list on the next attempt.
|
| 425 |
+
c.mu.Lock()
|
| 426 |
+
c.listed = false
|
| 427 |
+
c.mu.Unlock()
|
| 428 |
+
|
| 429 |
+
if apiErr, ok := err.(*hf.APIError); ok && apiErr.RetryAfter > 0 {
|
| 430 |
+
delay = apiErr.RetryAfter
|
| 431 |
+
}
|
| 432 |
+
c.log.Warn("dataset publish failed, will retry",
|
| 433 |
+
"attempt", attempt+1, "err", err, "next_delay_ms", delay.Milliseconds())
|
| 434 |
+
}
|
| 435 |
+
return retried, lastErr
|
| 436 |
+
}
|
| 437 |
+
|
| 438 |
+
// requeue puts a failed batch back so the next flush retries it. Existing
|
| 439 |
+
// entries win: a newer version must not be overwritten by a stale one.
|
| 440 |
+
func (c *Controller) requeue(batch map[string][]byte, cause error) error {
|
| 441 |
+
c.mu.Lock()
|
| 442 |
+
defer c.mu.Unlock()
|
| 443 |
+
restored := 0
|
| 444 |
+
for p, content := range batch {
|
| 445 |
+
if _, newer := c.queue[p]; newer {
|
| 446 |
+
continue
|
| 447 |
+
}
|
| 448 |
+
c.queue[p] = content
|
| 449 |
+
restored++
|
| 450 |
+
}
|
| 451 |
+
if restored > 0 {
|
| 452 |
+
c.log.Warn("dataset batch requeued after failure", "files", restored, "err", cause)
|
| 453 |
+
}
|
| 454 |
+
return cause
|
| 455 |
+
}
|
| 456 |
+
|
| 457 |
+
// widen doubles the flush interval, up to the ceiling.
|
| 458 |
+
func (c *Controller) widen() {
|
| 459 |
+
c.mu.Lock()
|
| 460 |
+
defer c.mu.Unlock()
|
| 461 |
+
next := c.interval * 2
|
| 462 |
+
if next > c.cfg.MaxInterval {
|
| 463 |
+
next = c.cfg.MaxInterval
|
| 464 |
+
}
|
| 465 |
+
if next != c.interval {
|
| 466 |
+
c.log.Warn("backing off dataset sync", "interval_s", int(next/time.Second))
|
| 467 |
+
}
|
| 468 |
+
c.interval = next
|
| 469 |
+
}
|
| 470 |
+
|
| 471 |
+
// narrow eases the interval back towards the configured target.
|
| 472 |
+
func (c *Controller) narrow() {
|
| 473 |
+
c.mu.Lock()
|
| 474 |
+
defer c.mu.Unlock()
|
| 475 |
+
next := c.interval * 3 / 4
|
| 476 |
+
if next < c.cfg.MinInterval {
|
| 477 |
+
next = c.cfg.MinInterval
|
| 478 |
+
}
|
| 479 |
+
if next < c.cfg.Interval {
|
| 480 |
+
next = c.cfg.Interval
|
| 481 |
+
}
|
| 482 |
+
c.interval = next
|
| 483 |
+
}
|
| 484 |
+
|
| 485 |
+
// isRetryable reports whether a publish failure is worth retrying.
|
| 486 |
+
func isRetryable(err error) bool {
|
| 487 |
+
var apiErr *hf.APIError
|
| 488 |
+
if errors.As(err, &apiErr) {
|
| 489 |
+
return apiErr.Retryable()
|
| 490 |
+
}
|
| 491 |
+
// A transport error (DNS, reset, timeout) is worth retrying; a malformed
|
| 492 |
+
// payload is not, but we cannot distinguish those here, so be optimistic.
|
| 493 |
+
if errors.Is(err, context.Canceled) {
|
| 494 |
+
return false
|
| 495 |
+
}
|
| 496 |
+
return true
|
| 497 |
+
}
|
| 498 |
+
|
| 499 |
+
// Restore downloads a subtree from the dataset into a local directory. Reads
|
| 500 |
+
// are parallel, so this is fast even though writes are strictly ordered.
|
| 501 |
+
func Restore(ctx context.Context, remote hf.Remote, prefix, destRoot string, concurrency int) (int, error) {
|
| 502 |
+
files, err := remote.List(ctx, prefix)
|
| 503 |
+
if err != nil {
|
| 504 |
+
return 0, err
|
| 505 |
+
}
|
| 506 |
+
paths := make([]string, 0, len(files))
|
| 507 |
+
for _, f := range files {
|
| 508 |
+
paths = append(paths, f.Path)
|
| 509 |
+
}
|
| 510 |
+
// Strip the prefix so a subtree's contents land directly in destRoot. The
|
| 511 |
+
// bank is the reason this matters: restore("bank", BANK_DIR) must produce
|
| 512 |
+
// BANK_DIR/python/easy.jsonl, not BANK_DIR/bank/python/easy.jsonl, or the
|
| 513 |
+
// loader finds nothing and the relay serves 503 forever.
|
| 514 |
+
d := hf.Downloader{Remote: remote, Concurrency: concurrency, Prefix: prefix}
|
| 515 |
+
return d.DownloadAll(ctx, destRoot, paths)
|
| 516 |
+
}
|
| 517 |
+
|
| 518 |
+
// SanitizePath trims a leading slash and query so callers cannot smuggle a
|
| 519 |
+
// traversal sequence through a config value.
|
| 520 |
+
func SanitizePath(p string) string {
|
| 521 |
+
// Trim both sides of every slash: a config value like "identities//" must
|
| 522 |
+
// not become "identities/" and then be joined into a doubled path.
|
| 523 |
+
return strings.Trim(strings.TrimSpace(p), "/")
|
| 524 |
+
}
|