Files
explorer/realtime_test.go
T
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

269 lines
7.0 KiB
Go

package main
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gorilla/websocket"
)
func TestRealtimeHubStats(t *testing.T) {
hub := NewRealtimeHub()
stats := hub.Stats()
if stats["connections"] != 0 {
t.Fatalf("expected 0 connections, got %d", stats["connections"])
}
}
func TestRealtimeWebSocket(t *testing.T) {
hub := NewRealtimeHub()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go hub.Run(ctx)
mux := http.NewServeMux()
mux.HandleFunc("/v1/explorer/realtime", hub.HandleRealtime)
ts := httptest.NewServer(mux)
defer ts.Close()
// Connect WebSocket
wsURL := "ws" + strings.TrimPrefix(ts.URL, "http") + "/v1/explorer/realtime"
conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil)
if err != nil {
t.Fatalf("dial: %v", err)
}
defer conn.Close()
// Read connected message
var msg RealtimeMessage
conn.SetReadDeadline(time.Now().Add(5 * time.Second))
err = conn.ReadJSON(&msg)
if err != nil {
t.Fatalf("read connected: %v", err)
}
if msg.Type != "connected" {
t.Fatalf("expected connected, got %s", msg.Type)
}
// Subscribe to blocks
sub := SubscribeRequest{Subscribe: "blocks", Chain: "cchain"}
conn.WriteJSON(sub)
// Read subscribed confirmation
conn.SetReadDeadline(time.Now().Add(5 * time.Second))
err = conn.ReadJSON(&msg)
if err != nil {
t.Fatalf("read subscribed: %v", err)
}
if msg.Type != "subscribed" {
t.Fatalf("expected subscribed, got %s", msg.Type)
}
// Broadcast a block
hub.Broadcast("blocks", "cchain", map[string]any{"number": 1})
// Read the broadcast
conn.SetReadDeadline(time.Now().Add(5 * time.Second))
err = conn.ReadJSON(&msg)
if err != nil {
t.Fatalf("read broadcast: %v", err)
}
if msg.Type != "blocks" {
t.Fatalf("expected blocks event, got %s", msg.Type)
}
if msg.Chain != "cchain" {
t.Fatalf("expected chain=cchain, got %s", msg.Chain)
}
// Verify stats
stats := hub.Stats()
if stats["connections"] != 1 {
t.Fatalf("expected 1 connection, got %d", stats["connections"])
}
if stats["subscriptions"] != 1 {
t.Fatalf("expected 1 subscription, got %d", stats["subscriptions"])
}
}
func TestRealtimePing(t *testing.T) {
hub := NewRealtimeHub()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go hub.Run(ctx)
mux := http.NewServeMux()
mux.HandleFunc("/v1/explorer/realtime", hub.HandleRealtime)
ts := httptest.NewServer(mux)
defer ts.Close()
wsURL := "ws" + strings.TrimPrefix(ts.URL, "http") + "/v1/explorer/realtime"
conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil)
if err != nil {
t.Fatalf("dial: %v", err)
}
defer conn.Close()
// Consume connected
conn.SetReadDeadline(time.Now().Add(5 * time.Second))
conn.ReadJSON(&RealtimeMessage{})
// Send ping
conn.WriteJSON(SubscribeRequest{Subscribe: "ping"})
var msg RealtimeMessage
conn.SetReadDeadline(time.Now().Add(5 * time.Second))
err = conn.ReadJSON(&msg)
if err != nil {
t.Fatalf("read pong: %v", err)
}
if msg.Type != "pong" {
t.Fatalf("expected pong, got %s", msg.Type)
}
}
func TestRealtimeUnscopedSubscription(t *testing.T) {
hub := NewRealtimeHub()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go hub.Run(ctx)
mux := http.NewServeMux()
mux.HandleFunc("/v1/explorer/realtime", hub.HandleRealtime)
ts := httptest.NewServer(mux)
defer ts.Close()
wsURL := "ws" + strings.TrimPrefix(ts.URL, "http") + "/v1/explorer/realtime"
conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil)
if err != nil {
t.Fatalf("dial: %v", err)
}
defer conn.Close()
// Consume connected
conn.SetReadDeadline(time.Now().Add(5 * time.Second))
conn.ReadJSON(&RealtimeMessage{})
// Subscribe to transactions without chain scope (gets all chains)
conn.WriteJSON(SubscribeRequest{Subscribe: "transactions"})
conn.SetReadDeadline(time.Now().Add(5 * time.Second))
conn.ReadJSON(&RealtimeMessage{}) // subscribed
// Broadcast from any chain should match
hub.Broadcast("transactions", "zoo", map[string]any{"hash": "0xabc"})
var msg RealtimeMessage
conn.SetReadDeadline(time.Now().Add(5 * time.Second))
err = conn.ReadJSON(&msg)
if err != nil {
t.Fatalf("read broadcast: %v", err)
}
if msg.Type != "transactions" {
t.Fatalf("expected transactions, got %s", msg.Type)
}
if msg.Chain != "zoo" {
t.Fatalf("expected chain=zoo, got %s", msg.Chain)
}
}
func TestRealtimeStatsEndpoint(t *testing.T) {
hub := NewRealtimeHub()
mux := http.NewServeMux()
mux.HandleFunc("GET /v1/explorer/realtime/stats", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(hub.Stats())
})
ts := httptest.NewServer(mux)
defer ts.Close()
resp, err := ts.Client().Get(ts.URL + "/v1/explorer/realtime/stats")
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
t.Fatalf("expected 200, got %d", resp.StatusCode)
}
var stats map[string]int
json.NewDecoder(resp.Body).Decode(&stats)
if stats["connections"] != 0 {
t.Fatalf("expected 0 connections, got %d", stats["connections"])
}
}
// The realtime stream carries the chain of the host it was opened on, and
// nothing else. One binary indexes five chains and broadcasts all of them onto
// one hub; an unscoped stream put Lux and Zoo blocks into Hanzo's block list,
// which is how a 50-block page rendered 63 rows.
func TestRealtimeStreamCarriesOnlyTheHostsChain(t *testing.T) {
cfg := Config{Chains: []ChainConfig{
{Slug: "cchain", Default: true},
{Slug: "hanzo"},
{Slug: "zoo"},
}}
hub := NewRealtimeHub()
mux := http.NewServeMux()
mux.HandleFunc("GET /v1/base/realtime", hub.HandleMultiplexedSSE(cfg))
ts := httptest.NewServer(mux)
defer ts.Close()
for _, tc := range []struct {
host string
want string
}{
{"api-explore.hanzo.network", "hanzo"},
{"explore.zoo.network", "zoo"},
{"api-explore.lux.network", "cchain"}, // names no chain -> the default
} {
req, err := http.NewRequest(http.MethodGet, ts.URL+"/v1/base/realtime", nil)
if err != nil {
t.Fatal(err)
}
req.Host = tc.host
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
// Read past the CONNECT frame so the subscriber is attached before the
// broadcasts go out — attaching is what decides which chain it sees.
buf := make([]byte, 4096)
if _, err := resp.Body.Read(buf); err != nil {
t.Fatalf("%s: CONNECT: %v", tc.host, err)
}
for _, chain := range []string{"cchain", "hanzo", "zoo"} {
hub.Broadcast("blocks", chain, map[string]any{"number": 1, "chain": chain})
}
frame := make([]byte, 4096)
n, err := resp.Body.Read(frame)
if err != nil {
t.Fatalf("%s: read: %v", tc.host, err)
}
got := string(frame[:n])
if !strings.Contains(got, `"chain":"`+tc.want+`"`) {
t.Errorf("%s: first frame is not %s: %s", tc.host, tc.want, got)
}
for _, other := range []string{"cchain", "hanzo", "zoo"} {
if other == tc.want {
continue
}
if strings.Contains(got, `"chain":"`+other+`"`) {
t.Errorf("%s: stream carried %s: %s", tc.host, other, got)
}
}
resp.Body.Close()
}
}