Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d1e95ebd9a | |||
| 02c2eb35f4 | |||
| f80424d707 | |||
| 6335670ddb | |||
| e4f3618424 | |||
| 0b8ac34aee | |||
| 52c4d1f1e6 |
@@ -8,9 +8,6 @@ name: build
|
||||
# daemon keeps that contract and means a knox change needs no registry
|
||||
# credentials at all.
|
||||
#
|
||||
# act_runner runs JS actions (actions/checkout) with whatever `node` is on the
|
||||
# job container's PATH, so each job installs one before checkout.
|
||||
#
|
||||
# Deployment stays with tf-net: this workflow only makes the new image available
|
||||
# and restarts the stack when the app is already installed.
|
||||
|
||||
@@ -35,18 +32,7 @@ jobs:
|
||||
container:
|
||||
image: golang:1.27-alpine
|
||||
steps:
|
||||
- name: Install node for JS actions
|
||||
run: apk add --no-cache nodejs
|
||||
- uses: actions/checkout@v4
|
||||
# act_runner injects ACTIONS_CACHE_URL, so this hits the runner-local
|
||||
# cache server (config: cache.dir) instead of re-downloading modules.
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/go/pkg/mod
|
||||
~/.cache/go-build
|
||||
key: go-${{ hashFiles('go.sum') }}
|
||||
restore-keys: go-
|
||||
- run: go vet ./... && go test ./...
|
||||
|
||||
image:
|
||||
@@ -54,26 +40,19 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: docker:27-cli
|
||||
# The runner already injects /var/run/docker.sock (declaring it again is a
|
||||
# duplicate mount error). CasaOS keeps app definitions under
|
||||
# /var/lib/casaos/apps, which is whitelisted in the runner's valid_volumes;
|
||||
# mount it at /apps so the restart step sees the installed compose file.
|
||||
# Whitelisted in the runner config (valid_volumes): the host daemon and
|
||||
# the CasaOS app directory where compose files live.
|
||||
volumes:
|
||||
- /var/lib/casaos/apps:/apps
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
- /apps:/apps
|
||||
env:
|
||||
IMAGE: docker.notsosm.art/knox
|
||||
steps:
|
||||
- name: Install node for JS actions
|
||||
run: apk add --no-cache nodejs git
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Check the daemon
|
||||
run: docker version --format '{{.Server.Version}}'
|
||||
|
||||
- name: Build image on the host daemon
|
||||
run: |
|
||||
set -eu
|
||||
git config --global --add safe.directory "$GITHUB_WORKSPACE" || true
|
||||
# .git is present in the checkout, so the binary records the commit
|
||||
# it was built from (`knox --version`).
|
||||
docker build \
|
||||
@@ -90,6 +69,10 @@ jobs:
|
||||
echo "apps/knox is not installed yet; image built, skipping restart"
|
||||
exit 0
|
||||
fi
|
||||
if ! docker compose version >/dev/null 2>&1; then
|
||||
echo "compose plugin unavailable in this image; restart deferred to tf-net"
|
||||
exit 0
|
||||
fi
|
||||
cd /apps/knox
|
||||
docker compose up -d
|
||||
docker compose ps
|
||||
|
||||
+3
-10
@@ -1,4 +1,3 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
# Headless knox node: CLI + MCP stdio + gossip sync, one static binary.
|
||||
#
|
||||
# docker build -t docker.notsosm.art/knox:latest .
|
||||
@@ -10,18 +9,12 @@
|
||||
FROM golang:1.27-alpine AS build
|
||||
WORKDIR /src
|
||||
|
||||
# Dependencies first so source edits do not invalidate the module layer.
|
||||
# Dependencies first so source edits do not invalidate the module cache.
|
||||
COPY go.mod go.sum ./
|
||||
RUN --mount=type=cache,target=/go/pkg/mod \
|
||||
--mount=type=cache,target=/root/.cache/go-build \
|
||||
go mod download
|
||||
RUN go mod download
|
||||
|
||||
COPY . .
|
||||
# Cache mounts persist on the build daemon across builds, so a go.sum change no
|
||||
# longer forces a full re-download and rebuild of every dependency.
|
||||
RUN --mount=type=cache,target=/go/pkg/mod \
|
||||
--mount=type=cache,target=/root/.cache/go-build \
|
||||
CGO_ENABLED=0 go build -trimpath -ldflags='-s -w' -o /out/knox .
|
||||
RUN CGO_ENABLED=0 go build -trimpath -ldflags='-s -w' -o /out/knox .
|
||||
|
||||
FROM alpine:3.22
|
||||
RUN apk add --no-cache ca-certificates \
|
||||
|
||||
@@ -31,7 +31,6 @@ DNS name: a self-signed certificate and a shared bearer token are enough.
|
||||
| `KNOX_TLS_CERT` / `KNOX_TLS_KEY` | Serve TLS. Generate with `knox tls init`. |
|
||||
| `KNOX_TLS_CA` | Client side: trust a peer's self-signed cert. |
|
||||
| `KNOX_INSECURE_TLS=1` | Client side: skip verification (trusted overlay only). |
|
||||
| `KNOX_LISTEN_ADDR` | Address the gossip server binds (use `0.0.0.0:8931` in a container). |
|
||||
| `KNOX_PEER_ADDR` | Address this node advertises to peers. |
|
||||
| `KNOX_PEERS` | Comma-separated seed peers, e.g. `https://172.30.170.155:8931`. |
|
||||
| `KNOX_LOCAL_SOURCES=none` | Replicate only: skip ingest of local files/sessions. |
|
||||
|
||||
@@ -54,54 +54,6 @@ func NewGossipCmd(kdb *db.KnoxDB) *cobra.Command {
|
||||
return gossipDiff(kdb, args[0])
|
||||
},
|
||||
},
|
||||
&cobra.Command{
|
||||
Use: "peer <list|rm>",
|
||||
Short: "List or forget known peers",
|
||||
Args: cobra.RangeArgs(0, 2),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
action := "list"
|
||||
if len(args) > 0 {
|
||||
action = args[0]
|
||||
}
|
||||
switch action {
|
||||
case "list":
|
||||
peers, err := kdb.ListPeers()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(peers) == 0 {
|
||||
fmt.Println("no peers")
|
||||
return nil
|
||||
}
|
||||
for _, p := range peers {
|
||||
fmt.Printf("%s %-30s last=%s cursor=%d\n", p.PeerID, p.Addr, p.LastHandshake, p.Cursor)
|
||||
}
|
||||
return nil
|
||||
case "rm":
|
||||
if len(args) != 2 {
|
||||
return fmt.Errorf("usage: knox gossip peer rm <peer-id|address>")
|
||||
}
|
||||
deleted, err := kdb.DeletePeer(args[1])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if deleted == 0 {
|
||||
return fmt.Errorf("no peer matching %q", args[1])
|
||||
}
|
||||
fmt.Printf("forgot %s\n", args[1])
|
||||
// A static seed would simply be re-learned on the next
|
||||
// sweep, so say so rather than let the operator wonder.
|
||||
for _, seeded := range watch.PeerAddrs() {
|
||||
if seeded == args[1] {
|
||||
fmt.Printf("warning: %s is still in KNOX_PEERS and will be re-learned\n", args[1])
|
||||
}
|
||||
}
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("unknown peer action %q (use list or rm)", action)
|
||||
}
|
||||
},
|
||||
},
|
||||
&cobra.Command{
|
||||
Use: "sync",
|
||||
Short: "Run one anti-entropy sweep against configured peers",
|
||||
|
||||
@@ -952,20 +952,6 @@ func (k *KnoxDB) MarkSessionIndexed(sessionID string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// DerivedStateCounts returns the number of observations in the append-only log
|
||||
// and the number of materialized entries. Callers use it to decide whether the
|
||||
// derived cache needs rebuilding (e.g. a replica that starts with a log but no
|
||||
// entries because it never saw a push or pull since the cache was wiped).
|
||||
func (k *KnoxDB) DerivedStateCounts() (observations, entries int, err error) {
|
||||
if err = k.db.QueryRow("SELECT COUNT(*) FROM observations").Scan(&observations); err != nil {
|
||||
return 0, 0, fmt.Errorf("count observations: %w", err)
|
||||
}
|
||||
if err = k.db.QueryRow("SELECT COUNT(*) FROM entries").Scan(&entries); err != nil {
|
||||
return 0, 0, fmt.Errorf("count entries: %w", err)
|
||||
}
|
||||
return observations, entries, nil
|
||||
}
|
||||
|
||||
func (k *KnoxDB) Stats() (map[string]any, error) {
|
||||
stats := make(map[string]any)
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// GossipObservation is the serializable wire form of an observation exchanged
|
||||
@@ -306,18 +305,3 @@ func (k *KnoxDB) ThreadStatusByCluster() (map[string]string, error) {
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// DeletePeer removes a peer by exact peer_id or exact address and reports how
|
||||
// many rows went. Without this, a peer learned once (or seeded from KNOX_PEERS
|
||||
// and later retired) stays in the table forever and fails on every sweep.
|
||||
func (k *KnoxDB) DeletePeer(identifier string) (int64, error) {
|
||||
identifier = strings.TrimSpace(identifier)
|
||||
if identifier == "" {
|
||||
return 0, fmt.Errorf("peer id or address required")
|
||||
}
|
||||
res, err := k.db.Exec(`DELETE FROM peers WHERE peer_id=? OR addr=?`, identifier, identifier)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("delete peer: %w", err)
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
package db_test
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/david/knox/internal/db"
|
||||
)
|
||||
|
||||
// TestDeletePeer: peers are only ever merged, so a retired node used to linger
|
||||
// forever and fail on every sweep. Deletion must work by id and by address, and
|
||||
// must not touch unrelated peers.
|
||||
func TestDeletePeer(t *testing.T) {
|
||||
kdb, err := db.Open(filepath.Join(t.TempDir(), "index.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("open: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = kdb.Close() })
|
||||
|
||||
if err := kdb.MergePeer("aaaa", "http://10.0.0.1:8931", "old"); err != nil {
|
||||
t.Fatalf("merge a: %v", err)
|
||||
}
|
||||
if err := kdb.MergePeer("bbbb", "https://10.0.0.2:8931", "new"); err != nil {
|
||||
t.Fatalf("merge b: %v", err)
|
||||
}
|
||||
|
||||
t.Run("by address", func(t *testing.T) {
|
||||
n, err := kdb.DeletePeer("http://10.0.0.1:8931")
|
||||
if err != nil {
|
||||
t.Fatalf("delete: %v", err)
|
||||
}
|
||||
if n != 1 {
|
||||
t.Errorf("deleted %d rows, want 1", n)
|
||||
}
|
||||
peers, err := kdb.ListPeers()
|
||||
if err != nil {
|
||||
t.Fatalf("list: %v", err)
|
||||
}
|
||||
if len(peers) != 1 || peers[0].PeerID != "bbbb" {
|
||||
t.Fatalf("wrong survivor: %+v", peers)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("by id", func(t *testing.T) {
|
||||
n, err := kdb.DeletePeer("bbbb")
|
||||
if err != nil {
|
||||
t.Fatalf("delete: %v", err)
|
||||
}
|
||||
if n != 1 {
|
||||
t.Errorf("deleted %d rows, want 1", n)
|
||||
}
|
||||
peers, _ := kdb.ListPeers()
|
||||
if len(peers) != 0 {
|
||||
t.Fatalf("peers remain: %+v", peers)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("unknown is a no-op", func(t *testing.T) {
|
||||
n, err := kdb.DeletePeer("nope")
|
||||
if err != nil {
|
||||
t.Fatalf("delete: %v", err)
|
||||
}
|
||||
if n != 0 {
|
||||
t.Errorf("deleted %d rows for an unknown peer, want 0", n)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("empty identifier is rejected", func(t *testing.T) {
|
||||
if _, err := kdb.DeletePeer(" "); err == nil {
|
||||
t.Error("want error for empty identifier")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -31,11 +31,6 @@ type Node struct {
|
||||
Name string
|
||||
Addr string // advertised base URL, e.g. http://192.168.1.20:8931
|
||||
Metrics *metrics.Metrics
|
||||
// OnIngest runs when a peer's push added observations. Receiving a push
|
||||
// changes the log just like pulling does, so the caller needs to rebuild
|
||||
// derived state — otherwise a push-only node (a replica with no peers of
|
||||
// its own) keeps an empty entries cache.
|
||||
OnIngest func(inserted int)
|
||||
}
|
||||
|
||||
// pingResponse is the anti-entropy summary returned by /v1/ping.
|
||||
@@ -53,10 +48,6 @@ func (n *Node) Handler() http.Handler {
|
||||
mux.HandleFunc("GET /v1/log", n.handleLog)
|
||||
mux.HandleFunc("POST /v1/obs/batch", n.handleBatch)
|
||||
mux.HandleFunc("GET /v1/diff", n.handleDiff)
|
||||
mux.HandleFunc("DELETE /v1/peers/{id}", n.handleDeletePeer)
|
||||
// Addresses contain slashes, so they travel as ?addr= rather than a path
|
||||
// segment.
|
||||
mux.HandleFunc("DELETE /v1/peers", n.handleDeletePeer)
|
||||
return mux
|
||||
}
|
||||
|
||||
@@ -109,22 +100,13 @@ func nextCursor(rows []db.GossipObservation) int64 {
|
||||
return rows[len(rows)-1].HCL
|
||||
}
|
||||
|
||||
// maxPushBytes is the payload budget for one push: observations carry the full
|
||||
// source text, so a row-count limit alone can still produce a batch larger than
|
||||
// the receiver accepts, which then fails on every sweep.
|
||||
const maxPushBytes = 2 << 20
|
||||
|
||||
// maxBatchBody is the largest body a node accepts from a peer. Comfortably
|
||||
// above maxPushBytes so a sender using a different batching rule still lands.
|
||||
const maxBatchBody = 8 << 20
|
||||
|
||||
// maxBatchRows bounds the number of observations a peer may push in one POST.
|
||||
// Pull already pages at 500 rows, so any larger batch is at best redundant and
|
||||
// at worst a flood; capping keeps memory and insert work bounded.
|
||||
const maxBatchRows = 1000
|
||||
|
||||
func (n *Node) handleBatch(w http.ResponseWriter, r *http.Request) {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxBatchBody)
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 4<<20) // 4 MiB
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, "batch too large or unreadable", http.StatusBadRequest)
|
||||
@@ -144,9 +126,6 @@ func (n *Node) handleBatch(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if inserted > 0 && n.OnIngest != nil {
|
||||
n.OnIngest(inserted)
|
||||
}
|
||||
writeJSON(w, map[string]any{
|
||||
"accepted": inserted,
|
||||
"conflict": len(rows) - inserted,
|
||||
@@ -187,31 +166,6 @@ func (n *Node) handleDiff(w http.ResponseWriter, r *http.Request) {
|
||||
})
|
||||
}
|
||||
|
||||
// handleDeletePeer forgets a peer, either by id in the path or by ?addr= for
|
||||
// addresses that contain slashes. Deletion is not permanent against a static
|
||||
// seed: KNOX_PEERS is re-merged on the next sweep, so a seeded peer must also
|
||||
// be removed from the environment.
|
||||
func (n *Node) handleDeletePeer(w http.ResponseWriter, r *http.Request) {
|
||||
key := r.PathValue("id")
|
||||
if addr := r.URL.Query().Get("addr"); addr != "" {
|
||||
key = addr
|
||||
}
|
||||
if key == "" {
|
||||
http.Error(w, "peer id or address required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
deleted, err := n.Kdb.DeletePeer(key)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if deleted == 0 {
|
||||
http.Error(w, "no such peer: "+key, http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
writeJSON(w, map[string]any{"deleted": deleted})
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
enc := json.NewEncoder(w)
|
||||
@@ -279,21 +233,6 @@ func (c *Client) Push(kdb *db.KnoxDB, peerVector map[string]int64) (int, error)
|
||||
if len(rows) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
// Trim to a byte budget. Rows are ordered by HCL, so dropping the tail
|
||||
// keeps the cursor monotonic and the remainder arrives on the next push.
|
||||
budget, n := maxPushBytes, 0
|
||||
for _, r := range rows {
|
||||
b, err := json.Marshal(r)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
if n > 0 && len(b) > budget {
|
||||
break
|
||||
}
|
||||
budget -= len(b)
|
||||
n++
|
||||
}
|
||||
rows = rows[:n]
|
||||
body, _ := json.Marshal(rows)
|
||||
req, err := http.NewRequest(http.MethodPost, c.Addr+"/v1/obs/batch", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
@@ -477,29 +416,14 @@ func isLoopbackAddr(addr string) bool {
|
||||
return host == "localhost"
|
||||
}
|
||||
|
||||
// ListenAddr is the address the gossip server binds. It is separate from the
|
||||
// advertised address because a container cannot bind the host's public or
|
||||
// overlay IP: inside the netns it listens on all interfaces while advertising
|
||||
// something peers can dial (KNOX_PEER_ADDR).
|
||||
// ListenAddr returns the advertised HTTP address (KNOX_PEER_ADDR or default).
|
||||
func ListenAddr() (addr string) {
|
||||
if addr = os.Getenv("KNOX_LISTEN_ADDR"); addr != "" {
|
||||
return addr
|
||||
}
|
||||
if addr = os.Getenv("KNOX_PEER_ADDR"); addr != "" {
|
||||
return addr
|
||||
}
|
||||
return "localhost:" + defaultPort
|
||||
}
|
||||
|
||||
// AdvertiseAddr is the base URL this node publishes to peers (/v1/ping), which
|
||||
// is what they store and dial. Falls back to the listen address.
|
||||
func AdvertiseAddr() string {
|
||||
if addr := os.Getenv("KNOX_PEER_ADDR"); addr != "" {
|
||||
return addr
|
||||
}
|
||||
return ListenAddr()
|
||||
}
|
||||
|
||||
const defaultMetricsPort = "8932"
|
||||
|
||||
// MetricsAddr returns the Prometheus scrape address (KNOX_METRICS_ADDR or
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -290,7 +289,7 @@ func TestHandleBatchRejectsOversizedBatch(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleBatchRejectsHugeBody: an oversized body (beyond maxBatchBody)
|
||||
// TestHandleBatchRejectsHugeBody: an oversized body (beyond the 4 MiB cap)
|
||||
// must be refused even when the row count is small.
|
||||
func TestHandleBatchRejectsHugeBody(t *testing.T) {
|
||||
b := tmpKnoxDB(t)
|
||||
@@ -301,7 +300,7 @@ func TestHandleBatchRejectsHugeBody(t *testing.T) {
|
||||
rows := []db.GossipObservation{{
|
||||
NodeID: "0123456789abcdef0123456789abcdef", HCL: 1,
|
||||
Fingerprint: "fp:huge", SourceID: "test", Title: "t",
|
||||
Summary: strings.Repeat("x", 9<<20), // 9 MiB, past maxBatchBody
|
||||
Summary: strings.Repeat("x", 5<<20), // 5 MiB summary
|
||||
CollectedAt: "2026-08-29T00:00:00Z",
|
||||
}}
|
||||
body, _ := json.Marshal(rows)
|
||||
@@ -364,47 +363,3 @@ func TestClientPushSurfacesHTTPError(t *testing.T) {
|
||||
t.Fatal("expected push error on HTTP 500, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleDeletePeer: the peer list is otherwise append-only, so there must be
|
||||
// a way to forget a node that moved or was decommissioned. Both addressing
|
||||
// forms are accepted, and an unknown peer is a 404 rather than a silent success.
|
||||
func TestHandleDeletePeer(t *testing.T) {
|
||||
b := tmpKnoxDB(t)
|
||||
node := &Node{Kdb: b, Name: "A"}
|
||||
sv := httptest.NewServer(node.Handler())
|
||||
defer sv.Close()
|
||||
|
||||
if err := b.MergePeer("0123456789abcdef0123456789abcdef", "http://10.0.0.9:8931", "old"); err != nil {
|
||||
t.Fatalf("merge: %v", err)
|
||||
}
|
||||
|
||||
del := func(path string) int {
|
||||
req, _ := http.NewRequest(http.MethodDelete, sv.URL+path, nil)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("delete %s: %v", path, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
return resp.StatusCode
|
||||
}
|
||||
|
||||
if code := del("/v1/peers/unknown-id"); code != http.StatusNotFound {
|
||||
t.Errorf("unknown peer: got %d, want 404", code)
|
||||
}
|
||||
if code := del("/v1/peers/0123456789abcdef0123456789abcdef"); code != http.StatusOK {
|
||||
t.Errorf("by id: got %d, want 200", code)
|
||||
}
|
||||
if peers, _ := b.ListPeers(); len(peers) != 0 {
|
||||
t.Fatalf("peer not deleted: %+v", peers)
|
||||
}
|
||||
|
||||
if err := b.MergePeer("ffff", "http://10.0.0.10:8931", "old2"); err != nil {
|
||||
t.Fatalf("merge2: %v", err)
|
||||
}
|
||||
if code := del("/v1/peers?addr=" + url.QueryEscape("http://10.0.0.10:8931")); code != http.StatusOK {
|
||||
t.Errorf("by addr: got %d, want 200", code)
|
||||
}
|
||||
if peers, _ := b.ListPeers(); len(peers) != 0 {
|
||||
t.Fatalf("peer not deleted by addr: %+v", peers)
|
||||
}
|
||||
}
|
||||
|
||||
+17
-41
@@ -51,9 +51,6 @@ type Watcher struct {
|
||||
metricsSrv *http.Server
|
||||
quit chan struct{}
|
||||
quitOnce sync.Once
|
||||
// pendingReconcile is set when a peer's push added observations, so the
|
||||
// next sweep rebuilds derived state without reconciling per HTTP request.
|
||||
pendingReconcile atomic.Bool
|
||||
}
|
||||
|
||||
// fileDebouncer schedules one ingest per path a settle-window after the last
|
||||
@@ -160,8 +157,7 @@ func (w *Watcher) Start() error {
|
||||
// Start the gossip server first so peers can reach us while the initial
|
||||
// seed is still ingesting. Vault/dirs are logged after the seed below.
|
||||
gossipAddr := ListenAddr()
|
||||
node := &Node{Kdb: w.knoxDB, Name: "knox", Addr: AdvertiseAddr(), Metrics: w.metrics}
|
||||
node.OnIngest = func(int) { w.pendingReconcile.Store(true) }
|
||||
node := &Node{Kdb: w.knoxDB, Name: "knox", Addr: gossipAddr, Metrics: w.metrics}
|
||||
srv := &http.Server{
|
||||
Addr: gossipAddr,
|
||||
Handler: httpauth.Middleware(node.Handler()),
|
||||
@@ -209,19 +205,6 @@ func (w *Watcher) Start() error {
|
||||
log.Printf("[knox] obsidian vault: %s", w.vault)
|
||||
}
|
||||
|
||||
// A node that starts with a populated log but an empty entries cache — a
|
||||
// freshly deployed replica, or any node whose derived state was wiped — has
|
||||
// nothing to trigger a reconcile, so build it once at startup. Reconcile is
|
||||
// only cheap-ish, not free, hence the guard.
|
||||
if obs, entries, err := w.knoxDB.DerivedStateCounts(); err == nil && obs > 0 && entries == 0 {
|
||||
log.Printf("[knox] derived state empty with %d observations: rebuilding", obs)
|
||||
if created, linked, err := Reconcile(w.knoxDB); err != nil {
|
||||
log.Printf("[knox] startup reconcile: %v", err)
|
||||
} else {
|
||||
log.Printf("[knox] startup reconcile done: %d created, %d linked", created, linked)
|
||||
}
|
||||
}
|
||||
|
||||
debounce := newFileDebouncer()
|
||||
browserTicker := time.NewTicker(browserInterval)
|
||||
giteaTicker := time.NewTicker(10 * time.Minute)
|
||||
@@ -233,21 +216,16 @@ func (w *Watcher) Start() error {
|
||||
snippetTicker := time.NewTicker(snippetInterval)
|
||||
gossipTicker := time.NewTicker(gossipInterval)
|
||||
|
||||
// Derivation always runs. Threads and snippets are computed from rows that
|
||||
// are already in the log, so a replica needs them exactly as much as the
|
||||
// origin does — gating them with the ingesters left a replica with an
|
||||
// almost empty thread list while the data sat right there.
|
||||
threadC, snippetC := threadTicker.C, snippetTicker.C
|
||||
|
||||
// Ingestion only runs where the sources exist. A node with no local
|
||||
// sources (KNOX_LOCAL_SOURCES=none) leaves these nil: nil channels block
|
||||
// forever, so the select never fires for them.
|
||||
var browserC, giteaC, gitC, opencodeC, karakeepC, healthC <-chan time.Time
|
||||
// A node that only replicates peers (a server with none of the local
|
||||
// sources) skips the ingest/derive tickers entirely. Nil channels block
|
||||
// forever, so the select simply never fires for them.
|
||||
var browserC, giteaC, gitC, opencodeC, karakeepC, healthC, threadC, snippetC <-chan time.Time
|
||||
if LocalSourcesEnabled() {
|
||||
browserC, giteaC, gitC = browserTicker.C, giteaTicker.C, gitTicker.C
|
||||
opencodeC, karakeepC, healthC = opencodeTicker.C, karakeepTicker.C, healthTicker.C
|
||||
threadC, snippetC = threadTicker.C, snippetTicker.C
|
||||
} else {
|
||||
log.Printf("[knox] KNOX_LOCAL_SOURCES=none: local ingest disabled, derivation still active")
|
||||
log.Printf("[knox] KNOX_LOCAL_SOURCES=none: gossip-only mode, local ingest disabled")
|
||||
}
|
||||
var browserRunning, giteaRunning, gitRunning, threadRunning, gossipRunning atomic.Bool
|
||||
var opencodeRunning, karakeepRunning, healthRunning, snippetRunning atomic.Bool
|
||||
@@ -872,20 +850,18 @@ func (w *Watcher) extractSnippets() {
|
||||
// syncGossip runs one anti-entropy sweep against configured peers and rebuilds
|
||||
// derived state if anything new arrived.
|
||||
func (w *Watcher) syncGossip() {
|
||||
// Taken before the peer check: a replica with no seed peers still receives
|
||||
// pushes, and that is the only thing that ever changes its log. Returning
|
||||
// early on an empty peer list would leave its entries cache empty forever.
|
||||
pushedIn := w.pendingReconcile.Swap(false)
|
||||
|
||||
pulled := 0
|
||||
if peers := PeerAddrs(); len(peers) > 0 {
|
||||
pulled = Run(w.knoxDB, w.metrics, peers)
|
||||
peers := PeerAddrs()
|
||||
if len(peers) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
// Reconcile when this sweep changed the log, in either direction: a pull
|
||||
// inserts rows here, a peer's push inserted them in the HTTP handler. The
|
||||
// entries cache and auto-threads are derived state that reconcile rebuilds.
|
||||
if pulled > 0 || pushedIn {
|
||||
pulled := Run(w.knoxDB, w.metrics, peers)
|
||||
|
||||
// A pull only appends to the observation log; the entries cache and
|
||||
// auto-threads are derived state that reconcile rebuilds. Comparing entry
|
||||
// counts can never trigger this (pushes/pulls never touch entries directly),
|
||||
// so reconcile fires on the sweep's newly-inserted observation count.
|
||||
if pulled > 0 {
|
||||
created, linked, err := Reconcile(w.knoxDB)
|
||||
if err != nil {
|
||||
log.Printf("[knox] gossip reconcile: %v", err)
|
||||
|
||||
Reference in New Issue
Block a user