Adds real-time block detection via ckpool log tailing and a push channel for the upcoming Svelte UI, all stdlib-only: - logmon.Tailer follows ckpool.log with rotation/truncation survival (inode + size tracking) and parses "Solved and confirmed block N" into BlockEvent values. - state.Aggregator grows a 256-entry block ring, an OnRefresh hook, and IngestBlockEvents which best-effort enriches events with the block hash via bitcoind getblockhash. - httpapi.Hub implements RFC 6455 from scratch (SHA1 handshake, unmasked text frames out, masked frames in, ping keepalive, per-client write mutex, slow-client drop) so we don't pull in a ws dependency before we can go mod tidy. - New routes: GET /api/blocks and GET /api/ws. Snapshot pushes fire on every poll tick and immediately on block-solve. ZMQ hashblock subscription and SQLite persistence are deferred to Phase 2b.5 once the s9pk packaging repo exists and we have a real build environment for adding Go deps.
158 lines
4.3 KiB
Go
158 lines
4.3 KiB
Go
// Package state merges data from CKPool (via Unix socket), Bitcoin Core
|
|
// (via JSON-RPC), and future sources (ZMQ, log tailer) into a single
|
|
// thread-safe snapshot the HTTP layer can serve. The snapshot is refreshed
|
|
// on a ticker; readers get a copy without blocking the refresh.
|
|
package state
|
|
|
|
import (
|
|
"context"
|
|
"log/slog"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/kamadopool/kamado-api/internal/bitcoind"
|
|
"github.com/kamadopool/kamado-api/internal/ckpool"
|
|
)
|
|
|
|
// Snapshot is the merged view served to the UI. All fields are safe to
|
|
// JSON-serialize directly.
|
|
type Snapshot struct {
|
|
GeneratedAt time.Time `json:"generated_at"`
|
|
|
|
// CKPool-derived fields
|
|
Pool *ckpool.PoolStats `json:"pool"`
|
|
Uptime int64 `json:"uptime_seconds"`
|
|
Users []ckpool.User `json:"users"`
|
|
Workers []ckpool.Worker `json:"workers"`
|
|
Clients []ckpool.StratumClient `json:"clients"`
|
|
|
|
// Derived/enriched fields
|
|
HashrateHs float64 `json:"hashrate_hs_1m"` // from PoolStats.DSPS1
|
|
HashrateHs5m float64 `json:"hashrate_hs_5m"`
|
|
HashrateHs1h float64 `json:"hashrate_hs_1h"`
|
|
HashrateHs24h float64 `json:"hashrate_hs_24h"`
|
|
|
|
// Bitcoin Core fields
|
|
Chain *bitcoind.BlockchainInfo `json:"chain"`
|
|
NetworkHashrateHs float64 `json:"network_hashrate_hs"`
|
|
|
|
// Recent found blocks (in-memory history; persisted in Phase 2b.5).
|
|
RecentBlocks []BlockRecord `json:"recent_blocks,omitempty"`
|
|
|
|
// Health
|
|
CKPoolOK bool `json:"ckpool_ok"`
|
|
BitcoinOK bool `json:"bitcoin_ok"`
|
|
LastError string `json:"last_error,omitempty"`
|
|
}
|
|
|
|
// Aggregator refreshes a Snapshot on a ticker.
|
|
type Aggregator struct {
|
|
CK *ckpool.Client
|
|
RPC *bitcoind.RPC
|
|
Interval time.Duration
|
|
Log *slog.Logger
|
|
|
|
// OnRefresh, if set, is called (non-blocking) after each snapshot
|
|
// refresh. Used by the WebSocket hub to push updates to clients.
|
|
OnRefresh func(Snapshot)
|
|
|
|
mu sync.RWMutex
|
|
snap Snapshot
|
|
blocks []BlockRecord
|
|
}
|
|
|
|
func New(ck *ckpool.Client, rpc *bitcoind.RPC, interval time.Duration, log *slog.Logger) *Aggregator {
|
|
return &Aggregator{
|
|
CK: ck,
|
|
RPC: rpc,
|
|
Interval: interval,
|
|
Log: log,
|
|
}
|
|
}
|
|
|
|
// Run blocks until ctx is cancelled, refreshing the snapshot every Interval.
|
|
// It runs one immediate refresh at startup so readers don't see an empty
|
|
// snapshot after ctx launches the goroutine.
|
|
func (a *Aggregator) Run(ctx context.Context) {
|
|
a.refresh(ctx)
|
|
t := time.NewTicker(a.Interval)
|
|
defer t.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-t.C:
|
|
a.refresh(ctx)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Snapshot returns a copy of the current snapshot.
|
|
func (a *Aggregator) Snapshot() Snapshot {
|
|
a.mu.RLock()
|
|
defer a.mu.RUnlock()
|
|
return a.snap
|
|
}
|
|
|
|
func (a *Aggregator) refresh(ctx context.Context) {
|
|
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
|
defer cancel()
|
|
|
|
next := Snapshot{GeneratedAt: time.Now()}
|
|
|
|
// --- ckpool: poolstats, users, workers, clients, uptime ---
|
|
if ps, err := a.CK.PoolStats(ctx); err == nil {
|
|
next.Pool = ps
|
|
next.HashrateHs = ckpool.DSPSToHashrate(ps.DSPS1)
|
|
next.HashrateHs5m = ckpool.DSPSToHashrate(ps.DSPS5)
|
|
next.HashrateHs1h = ckpool.DSPSToHashrate(ps.DSPS60)
|
|
next.HashrateHs24h = ckpool.DSPSToHashrate(ps.DSPS1440)
|
|
next.CKPoolOK = true
|
|
} else {
|
|
a.Log.Warn("ckpool poolstats failed", "err", err)
|
|
next.LastError = err.Error()
|
|
}
|
|
if u, err := a.CK.Uptime(ctx); err == nil {
|
|
next.Uptime = u
|
|
}
|
|
if us, err := a.CK.Users(ctx); err == nil {
|
|
next.Users = us
|
|
}
|
|
if ws, err := a.CK.Workers(ctx); err == nil {
|
|
next.Workers = ws
|
|
}
|
|
if cs, err := a.CK.Clients(ctx); err == nil {
|
|
next.Clients = cs
|
|
}
|
|
|
|
// --- bitcoind: chain + network hashrate ---
|
|
if bi, err := a.RPC.GetBlockchainInfo(ctx); err == nil {
|
|
next.Chain = bi
|
|
next.BitcoinOK = true
|
|
if nh, err := a.RPC.GetNetworkHashPS(ctx, -1, int(bi.Blocks)); err == nil {
|
|
next.NetworkHashrateHs = nh
|
|
}
|
|
} else {
|
|
a.Log.Warn("bitcoind getblockchaininfo failed", "err", err)
|
|
if next.LastError == "" {
|
|
next.LastError = err.Error()
|
|
}
|
|
}
|
|
|
|
a.mu.Lock()
|
|
// Attach current block history so /api/snapshot and WebSocket
|
|
// pushes carry the same view.
|
|
if len(a.blocks) > 0 {
|
|
next.RecentBlocks = make([]BlockRecord, len(a.blocks))
|
|
copy(next.RecentBlocks, a.blocks)
|
|
}
|
|
a.snap = next
|
|
cb := a.OnRefresh
|
|
pushed := next
|
|
a.mu.Unlock()
|
|
|
|
if cb != nil {
|
|
cb(pushed)
|
|
}
|
|
}
|