Files
zeekayandHanzo Dev 216ef5d8bf explorer: answer every request from the chain its host is served
One binary answers explore.lux.network, explore.hanzo.network and
explore.zoo.network. Only /envs.js and the slug-prefixed /v1/indexer/{slug}
routes knew that. Everything else read whichever chain the config called
default, so Hanzo's home page printed 1,107,383 total blocks above its own
Latest blocks list topping out at 29,805 — Lux's number, on Hanzo's page,
overstating Hanzo's chain 37x and Zoo's 49x. Measured on all three brands.

Config.Serves(host) is now the one thing that answers "which chain is this
request about", and the three surfaces that were guessing ask it:

  * StatsService keeps a read handle per chain instead of one pinned at
    startup, so /v1/counters, /v1/lines, /v1/pages/* and /v1/stats report the
    host's chain: 1107259 / 29805 / 22728 on the three brand hosts, where all
    three read 1107259 before.

  * The realtime stream carries the host's chain. It carried all of them: a
    45s read of /v1/base/realtime returned the same 6 cchain + 14 hanzo + 5 zoo
    events on every brand host, and the SPA appends what it is sent, so a
    50-block page rendered 63 rows with 2 Lux on top and 8 Zoo at the bottom.
    ?chain= still overrides; an empty filter no longer means "all chains",
    because no brand host wants another brand's blocks.

  * A slug-less /v1/indexer/* request follows the host, falling back to the
    default only when the host names no chain (api-explore.lux.network) or
    names one that is not up.

Also here, because they were all the same mistake about the same column: the
timestamp in evm_blocks is a Go time.Time bound into a column declared
TIMESTAMP, so SQLite stores a datetime STRING, and everything that read it as
a unix epoch got nothing and said nothing.

  * /stats' daily charts were empty on all three brands. strftime with the
    'unixepoch' modifier returns NULL on a datetime string, the scan failed,
    and handlePagesMain discarded the error into `daily, _ :=` — a nil slice
    marshals to `null`, which the page renders as "No data". Now 22 points.

  * Average block time read 0.0s on a chain producing a block every 10s: the
    three-value Scan failed and its error was never checked, so the zero went
    out as the answer. Now 60.0 on a one-block-per-minute fixture.

  * /v1/blocks reported `"timestamp": 2026` for every block — CAST of a
    datetime string takes its leading digits, and 2026 looks like a number
    rather than a failure. Now a real epoch.

  * Transactions (24h) was the lifetime total. SQLite orders every INTEGER
    below every TEXT, so `timestamp > <epoch>` was true for all 1.1M rows.

blockEpoch and blockDay are the only two spellings allowed to touch that
column now. The fixtures were the reason none of this failed a test: they
declared the column TIMESTAMP and then inserted integers into it, so the suite
exercised a database the indexer never writes. They bind a time.Time now, and
on the old queries they fail with exactly what production showed —
average_block_time "0.0", empty charts, timestamp 2026.

Deleted: the eight per-channel SSE routes at bare /blocks, /transactions,
/tokens, /gas-tracker, /stats, /validators, /token-transfers and /internal-txs.
Every one of those is also an SPA page path, and one mux cannot serve both; the
SPA opens only the multiplexed stream, so they had no subscriber to lose. With
them goes the second envelope, the per-channel framing built on every
broadcast, and the client's channel field — SSE has one endpoint and one shape.

indexer v1.5.3 for the block transaction-count name.

Co-authored-by: Hanzo Dev <[email protected]>
2026-08-08 06:37:03 -07:00

278 lines
6.2 KiB
Go

package main
import (
"context"
"encoding/json"
"log"
"net/http"
"sync"
"time"
"github.com/gorilla/websocket"
)
// RealtimeHub manages multi-chain WebSocket subscriptions, plus a
// parallel set of SSE subscribers (see realtime_sse.go) so the bundled
// SPA — which opens EventSource against /blocks, /transactions, etc.
// — can subscribe to the same broadcast feed without speaking
// WebSocket.
type RealtimeHub struct {
mu sync.RWMutex
clients map[*wsClient]struct{}
sse *sseRegistry
}
type wsClient struct {
conn *websocket.Conn
subs map[string]bool // "blocks", "transactions", "blocks:cchain", etc.
mu sync.Mutex
closed bool
}
// RealtimeMessage is the wire format for realtime events.
type RealtimeMessage struct {
Type string `json:"type"`
Chain string `json:"chain,omitempty"`
Data any `json:"data,omitempty"`
Timestamp int64 `json:"timestamp"`
}
// SubscribeRequest is what clients send to subscribe.
type SubscribeRequest struct {
Subscribe string `json:"subscribe"` // blocks, transactions, token_transfers
Chain string `json:"chain"` // optional chain slug; empty = default
}
// NewRealtimeHub creates a new hub.
func NewRealtimeHub() *RealtimeHub {
return &RealtimeHub{
clients: make(map[*wsClient]struct{}),
sse: newSSERegistry(),
}
}
// Run starts the heartbeat loop. Cancel ctx to stop.
func (h *RealtimeHub) Run(ctx context.Context) {
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
h.closeAll()
return
case <-ticker.C:
h.heartbeat()
}
}
}
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true // CORS handled at mux level
},
HandshakeTimeout: 10 * time.Second,
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
// HandleRealtime is the HTTP handler for /v1/explorer/realtime.
func (h *RealtimeHub) HandleRealtime(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return
}
client := &wsClient{
conn: conn,
subs: make(map[string]bool),
}
h.mu.Lock()
h.clients[client] = struct{}{}
h.mu.Unlock()
// Send connected message
client.send(RealtimeMessage{
Type: "connected",
Timestamp: time.Now().UnixMilli(),
})
// Read loop: handle subscribe/unsubscribe/ping
h.readPump(client)
// Cleanup
h.mu.Lock()
delete(h.clients, client)
h.mu.Unlock()
conn.Close()
}
func (h *RealtimeHub) readPump(c *wsClient) {
c.conn.SetReadLimit(4096)
c.conn.SetReadDeadline(time.Now().Add(60 * time.Second))
c.conn.SetPongHandler(func(string) error {
c.conn.SetReadDeadline(time.Now().Add(60 * time.Second))
return nil
})
for {
_, msg, err := c.conn.ReadMessage()
if err != nil {
return
}
c.conn.SetReadDeadline(time.Now().Add(60 * time.Second))
var req SubscribeRequest
if err := json.Unmarshal(msg, &req); err != nil {
continue
}
switch req.Subscribe {
case "blocks", "transactions", "token_transfers":
key := req.Subscribe
if req.Chain != "" {
key = req.Subscribe + ":" + req.Chain
}
c.mu.Lock()
c.subs[key] = true
c.mu.Unlock()
c.send(RealtimeMessage{
Type: "subscribed",
Chain: req.Chain,
Data: map[string]string{"channel": req.Subscribe},
Timestamp: time.Now().UnixMilli(),
})
case "ping":
c.send(RealtimeMessage{
Type: "pong",
Timestamp: time.Now().UnixMilli(),
})
}
}
}
// Broadcast sends an event to all clients subscribed to the given
// channel+chain — both WebSocket (`HandleRealtime`) and SSE
// (`HandleSSE`).
//
// WebSocket clients receive the JSON-encoded RealtimeMessage as a TEXT
// frame. SSE clients receive the same payload wrapped in the SSE
// `event: <type>\ndata: <json>\n\n` framing so the EventSource
// onmessage / addEventListener('<type>', ...) handlers fire cleanly.
func (h *RealtimeHub) Broadcast(eventType, chain string, data any) {
msg := RealtimeMessage{
Type: eventType,
Chain: chain,
Data: data,
Timestamp: time.Now().UnixMilli(),
}
encoded, err := json.Marshal(msg)
if err != nil {
return
}
// WebSocket subscribers (existing path).
h.mu.RLock()
for client := range h.clients {
client.mu.Lock()
match := client.subs[eventType] || client.subs[eventType+":"+chain]
client.mu.Unlock()
if match {
client.sendRaw(encoded)
}
}
h.mu.RUnlock()
// SSE subscribers — frame the envelope once, fan out cheaply.
//
// data: {"event":<type>,"chain":<slug>,"data":<RealtimeMessage.Data JSON>}\n\n
//
// No `event:` line: the SPA uses `onmessage` and routes off the envelope's
// `event` field. See realtime_sse.go.
if h.sse != nil {
envBody, err := json.Marshal(struct {
Event string `json:"event"`
Chain string `json:"chain,omitempty"`
Data any `json:"data,omitempty"`
}{Event: eventType, Chain: chain, Data: data})
if err != nil {
return
}
envelope := append([]byte("data: "), envBody...)
envelope = append(envelope, '\n', '\n')
h.sse.fanout(chain, envelope)
}
}
func (h *RealtimeHub) heartbeat() {
msg := RealtimeMessage{
Type: "heartbeat",
Timestamp: time.Now().UnixMilli(),
}
h.mu.RLock()
defer h.mu.RUnlock()
for client := range h.clients {
client.send(msg)
}
}
func (h *RealtimeHub) closeAll() {
h.mu.Lock()
defer h.mu.Unlock()
for client := range h.clients {
client.conn.Close()
}
h.clients = make(map[*wsClient]struct{})
}
// Stats returns connection statistics.
func (h *RealtimeHub) Stats() map[string]int {
h.mu.RLock()
defer h.mu.RUnlock()
subs := 0
for client := range h.clients {
client.mu.Lock()
subs += len(client.subs)
client.mu.Unlock()
}
return map[string]int{
"connections": len(h.clients),
"subscriptions": subs,
}
}
func (c *wsClient) send(msg RealtimeMessage) {
c.mu.Lock()
defer c.mu.Unlock()
if c.closed {
return
}
c.conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
if err := c.conn.WriteJSON(msg); err != nil {
c.closed = true
log.Printf("[realtime] write error: %v", err)
}
}
func (c *wsClient) sendRaw(data []byte) {
c.mu.Lock()
defer c.mu.Unlock()
if c.closed {
return
}
c.conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
if err := c.conn.WriteMessage(websocket.TextMessage, data); err != nil {
c.closed = true
}
}