feat: rework engine and CLI for dnstraverse parity
Port the traversal engine to the Ruby dnstraverse model so behaviour and output match dns.squish.net: - dns: single RD=0 query path (RD=1 only for upstream root discovery), per-run packet cache, EDNS0 512-fallback with warnings, UDP->TCP on truncation; fix --retries 0 and --root-server IP-literal handling; drop all hardcoded 127.0.0.1:53 resolvers - traverse: hierarchical per-branch InfoCache, 7-step response classification with the full 10-status vocabulary, bailiwick partitioning, strictly-deeper lame-referral rule, refid grammar with .0 resolve subtrees and childset digits, per-IP branching at 1/n weight, cache-based glue resolution with noglue/loop dead ends, CNAME restarts from the deepest cached zone, fast-mode memoization, probability aggregation with Ruby-identical stats keys (sums to 1.0) - output: byte-for-byte reference text format pinned by a golden test, reference CLI defaults, working --quiet/--show-X=false, TTY-aware colour, deduplicated deterministic JSON - web: adapt API/SPA to the new engine, SSE events carry refid/status, fix subscribe/snapshot duplicate-event race and a statusCls TDZ bug, align SPA type list with the backend - delete the old engine and dead code (net -4,350 lines) Verified against live runs of the reference Ruby engine across five domains (answers, NXDOMAIN, null MX, CNAME restart, glueless resolve) with no divergences beyond the documented typo fixes. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
af15c9c2d4
commit
d71c7fbef2
+154
-67
@@ -7,6 +7,8 @@ import (
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -40,23 +42,57 @@ type TraverseStartResponse struct {
|
||||
|
||||
// ProgressEvent carries a single traversal hook event.
|
||||
type ProgressEvent struct {
|
||||
Stage string `json:"stage"`
|
||||
Depth int `json:"depth"`
|
||||
Name string `json:"name"`
|
||||
QType string `json:"qtype"`
|
||||
Server string `json:"server,omitempty"`
|
||||
Bailiwick string `json:"bailiwick,omitempty"`
|
||||
IsResolve bool `json:"is_resolve,omitempty"`
|
||||
Stage string `json:"stage"`
|
||||
RefID string `json:"refid"`
|
||||
Depth int `json:"depth"`
|
||||
Name string `json:"name"`
|
||||
QType string `json:"qtype"`
|
||||
Server string `json:"server,omitempty"`
|
||||
IPs string `json:"ips,omitempty"`
|
||||
Bailiwick string `json:"bailiwick,omitempty"`
|
||||
Status string `json:"status,omitempty"`
|
||||
IsResolve bool `json:"is_resolve,omitempty"`
|
||||
CompletedEarlier string `json:"completed_earlier,omitempty"`
|
||||
}
|
||||
|
||||
// ResultItem is a single traversal step result for API consumers.
|
||||
// ResultItem is one aggregated leaf outcome for API consumers. Parent and
|
||||
// ParentIP identify the referring server so clients can render the noglue and
|
||||
// lame-referral wordings; Qname/Qclass/Qtype are the failing query so clients
|
||||
// can render the "While querying" line when it differs from the original.
|
||||
type ResultItem struct {
|
||||
Depth int `json:"depth"`
|
||||
Probability float64 `json:"probability"`
|
||||
ResponseType string `json:"response_type"`
|
||||
Server string `json:"server,omitempty"`
|
||||
Answers []string `json:"answers,omitempty"`
|
||||
CNAMEChain []string `json:"cname_chain,omitempty"`
|
||||
RefID string `json:"refid,omitempty"`
|
||||
Depth int `json:"depth"`
|
||||
Probability float64 `json:"probability"`
|
||||
Status string `json:"status"`
|
||||
Server string `json:"server,omitempty"`
|
||||
IP string `json:"ip,omitempty"`
|
||||
Parent string `json:"parent,omitempty"`
|
||||
ParentIP string `json:"parent_ip,omitempty"`
|
||||
Qname string `json:"qname,omitempty"`
|
||||
Qclass string `json:"qclass,omitempty"`
|
||||
Qtype string `json:"qtype,omitempty"`
|
||||
Answers []string `json:"answers,omitempty"`
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
// SummaryAnswer is one distinct answered RRset with its accumulated
|
||||
// probability (traverse.SummaryStats).
|
||||
type SummaryAnswer struct {
|
||||
Probability float64 `json:"probability"`
|
||||
Records []string `json:"records"`
|
||||
}
|
||||
|
||||
// SummaryStatus is the accumulated probability of one non-answered status.
|
||||
type SummaryStatus struct {
|
||||
Status string `json:"status"`
|
||||
Probability float64 `json:"probability"`
|
||||
}
|
||||
|
||||
// Summary is the grouped view of the aggregated leaves; probabilities across
|
||||
// Answers plus ByStatus sum to 1.0.
|
||||
type Summary struct {
|
||||
Answers []SummaryAnswer `json:"answers,omitempty"`
|
||||
ByStatus []SummaryStatus `json:"by_status,omitempty"`
|
||||
}
|
||||
|
||||
// TraversalJob holds all state for a single asynchronous traversal.
|
||||
@@ -66,6 +102,7 @@ type TraversalJob struct {
|
||||
Domain string `json:"domain"`
|
||||
QueryType string `json:"query_type"`
|
||||
Results []ResultItem `json:"results,omitempty"`
|
||||
Summary *Summary `json:"summary,omitempty"`
|
||||
Progress []ProgressEvent `json:"progress,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
@@ -76,14 +113,18 @@ type TraversalJob struct {
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
// subscribe returns a channel that receives future progress events.
|
||||
// The channel is closed when the job finishes.
|
||||
func (j *TraversalJob) subscribe() <-chan ProgressEvent {
|
||||
// subscribeSnapshot atomically registers a subscriber and snapshots the
|
||||
// progress recorded so far. Publishing appends to Progress and sends to
|
||||
// subscribers under the same lock, so every event lands either in the
|
||||
// returned snapshot or on the channel — never both, never neither.
|
||||
func (j *TraversalJob) subscribeSnapshot() (sub <-chan ProgressEvent, past []ProgressEvent, done bool) {
|
||||
ch := make(chan ProgressEvent, 32)
|
||||
j.mu.Lock()
|
||||
defer j.mu.Unlock()
|
||||
j.subs = append(j.subs, ch)
|
||||
j.mu.Unlock()
|
||||
return ch
|
||||
past = make([]ProgressEvent, len(j.Progress))
|
||||
copy(past, j.Progress)
|
||||
return ch, past, j.Status != statusRunning
|
||||
}
|
||||
|
||||
// publishLocked sends ev to all current subscribers. Caller must hold j.mu.
|
||||
@@ -259,6 +300,7 @@ func (h *Handler) getTraversal(w http.ResponseWriter, r *http.Request) {
|
||||
Domain string `json:"domain"`
|
||||
QueryType string `json:"query_type"`
|
||||
Results []ResultItem `json:"results,omitempty"`
|
||||
Summary *Summary `json:"summary,omitempty"`
|
||||
Progress []ProgressEvent `json:"progress,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
@@ -269,6 +311,7 @@ func (h *Handler) getTraversal(w http.ResponseWriter, r *http.Request) {
|
||||
Domain: job.Domain,
|
||||
QueryType: job.QueryType,
|
||||
Results: job.Results,
|
||||
Summary: job.Summary,
|
||||
Progress: job.Progress,
|
||||
Error: job.Error,
|
||||
StartedAt: job.StartedAt,
|
||||
@@ -300,19 +343,12 @@ func (h *Handler) streamTraversal(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// Subscribe before snapshotting progress so we don't miss events between
|
||||
// the two operations. Unsubscribe when the client disconnects so stale
|
||||
// channels don't accumulate.
|
||||
sub := job.subscribe()
|
||||
// Subscribe and snapshot atomically so events published in between are
|
||||
// neither missed nor delivered twice. Unsubscribe when the client
|
||||
// disconnects so stale channels don't accumulate.
|
||||
sub, past, alreadyDone := job.subscribeSnapshot()
|
||||
defer job.unsubscribe(sub)
|
||||
|
||||
// Replay events already recorded.
|
||||
job.mu.RLock()
|
||||
past := make([]ProgressEvent, len(job.Progress))
|
||||
copy(past, job.Progress)
|
||||
alreadyDone := job.Status != statusRunning
|
||||
job.mu.RUnlock()
|
||||
|
||||
sendSSE := func(ev ProgressEvent) bool {
|
||||
b, err := json.Marshal(ev)
|
||||
if err != nil {
|
||||
@@ -375,26 +411,22 @@ func (h *Handler) runTraversal(ctx context.Context, job *TraversalJob, domain st
|
||||
}
|
||||
cfg.Hooks = &traverse.TraverserHooks{
|
||||
OnEvent: func(event traverse.TraversalEvent) {
|
||||
ref := event.Result.Referral
|
||||
if ref == nil {
|
||||
ref := event.Referral
|
||||
if ref == nil || ref.IsRootRoot() {
|
||||
return
|
||||
}
|
||||
stage := "start"
|
||||
if event.Stage == traverse.EventComplete {
|
||||
stage = "complete"
|
||||
}
|
||||
server := ""
|
||||
if event.Result.Response != nil && event.Result.Response.Server != nil {
|
||||
server = event.Result.Response.Server.String()
|
||||
}
|
||||
ev := ProgressEvent{
|
||||
Stage: stage,
|
||||
Depth: ref.Depth,
|
||||
Name: trimFQDN(ref.Name),
|
||||
QType: idns.QNameType(ref.Qtype),
|
||||
Server: server,
|
||||
Bailiwick: trimFQDN(ref.Bailiwick),
|
||||
IsResolve: event.IsResolve,
|
||||
Stage: event.Stage.String(),
|
||||
RefID: event.RefID,
|
||||
Depth: ref.Depth(),
|
||||
Name: ref.Qname,
|
||||
QType: traverse.TypeToString(ref.Qtype),
|
||||
Server: ref.Server,
|
||||
IPs: ref.TxtIPs(),
|
||||
Bailiwick: ref.Bailiwick,
|
||||
Status: string(event.Status),
|
||||
IsResolve: event.IsResolve,
|
||||
CompletedEarlier: event.CompletedEarlier,
|
||||
}
|
||||
|
||||
job.mu.Lock()
|
||||
@@ -405,7 +437,7 @@ func (h *Handler) runTraversal(ctx context.Context, job *TraversalJob, domain st
|
||||
}
|
||||
|
||||
tr := traverse.NewTraverser(cfg)
|
||||
rawResults, err := tr.Traverse(ctx, domain)
|
||||
root, err := tr.Run(ctx, domain)
|
||||
|
||||
now := time.Now()
|
||||
job.mu.Lock()
|
||||
@@ -419,31 +451,87 @@ func (h *Handler) runTraversal(ctx context.Context, job *TraversalJob, domain st
|
||||
return
|
||||
}
|
||||
|
||||
items := make([]ResultItem, 0, len(rawResults))
|
||||
for _, r := range rawResults {
|
||||
items = append(items, toResultItem(r))
|
||||
var items []ResultItem
|
||||
if root != nil {
|
||||
leaves := root.StatsList()
|
||||
items = make([]ResultItem, 0, len(leaves))
|
||||
for _, leaf := range leaves {
|
||||
items = append(items, toResultItem(leaf))
|
||||
}
|
||||
job.Summary = toSummary(root.SummaryStats())
|
||||
}
|
||||
job.Results = items
|
||||
job.Status = statusComplete
|
||||
}
|
||||
|
||||
// toResultItem converts a TraversalResult to its API representation.
|
||||
func toResultItem(r traverse.TraversalResult) ResultItem {
|
||||
item := ResultItem{}
|
||||
if r.Referral != nil {
|
||||
item.Depth = r.Referral.Depth
|
||||
item.Probability = r.Referral.Prob
|
||||
// toSummary converts the engine's grouped stats to the API representation:
|
||||
// answers sorted by RRset key (as SummaryStats returns them), remaining
|
||||
// statuses sorted lexically like the CLI Summary Results section.
|
||||
func toSummary(stats *traverse.SummaryStats) *Summary {
|
||||
if stats == nil {
|
||||
return nil
|
||||
}
|
||||
if r.Response != nil {
|
||||
item.ResponseType = r.Response.Type.String()
|
||||
if r.Response.Server != nil {
|
||||
item.Server = r.Response.Server.String()
|
||||
summary := &Summary{}
|
||||
for _, answer := range stats.Answers {
|
||||
item := SummaryAnswer{Probability: answer.Prob}
|
||||
for _, rr := range answer.RRs {
|
||||
item.Records = append(item.Records, collapseWhitespace(rr.String()))
|
||||
}
|
||||
if r.Response.Decoded != nil {
|
||||
for _, rr := range r.Response.Decoded.Answers {
|
||||
item.Answers = append(item.Answers, idns.FormatRecord(rr))
|
||||
}
|
||||
item.CNAMEChain = append(item.CNAMEChain, r.Response.Decoded.CNAMEChain...)
|
||||
summary.Answers = append(summary.Answers, item)
|
||||
}
|
||||
statuses := make([]traverse.Status, 0, len(stats.ByStatus))
|
||||
for status := range stats.ByStatus {
|
||||
if status != traverse.StatusAnswered {
|
||||
statuses = append(statuses, status)
|
||||
}
|
||||
}
|
||||
sort.Slice(statuses, func(i, j int) bool { return statuses[i] < statuses[j] })
|
||||
for _, status := range statuses {
|
||||
summary.ByStatus = append(summary.ByStatus, SummaryStatus{
|
||||
Status: string(status),
|
||||
Probability: stats.ByStatus[status],
|
||||
})
|
||||
}
|
||||
return summary
|
||||
}
|
||||
|
||||
// collapseWhitespace renders an RR on one line with runs of whitespace
|
||||
// collapsed to single spaces, matching the CLI summary records.
|
||||
func collapseWhitespace(s string) string {
|
||||
return strings.Join(strings.Fields(s), " ")
|
||||
}
|
||||
|
||||
// toResultItem converts one aggregated leaf to its API representation.
|
||||
func toResultItem(leaf *traverse.StatsEntry) ResultItem {
|
||||
resp := leaf.Response
|
||||
item := ResultItem{
|
||||
Probability: leaf.Prob,
|
||||
Status: string(resp.Status),
|
||||
IP: resp.IP,
|
||||
Server: resp.Server,
|
||||
ParentIP: resp.ParentIP,
|
||||
Qname: trimFQDN(resp.Qname),
|
||||
Qclass: traverse.ClassToString(resp.Qclass),
|
||||
Qtype: traverse.TypeToString(resp.Qtype),
|
||||
}
|
||||
if leaf.Referral != nil {
|
||||
item.RefID = leaf.Referral.RefID
|
||||
item.Depth = leaf.Referral.Depth()
|
||||
item.Server = leaf.Referral.Server
|
||||
item.ParentIP = leaf.Referral.ParentIP
|
||||
if leaf.Referral.Parent != nil {
|
||||
item.Parent = leaf.Referral.Parent.Server
|
||||
}
|
||||
}
|
||||
if resp.DQ != nil {
|
||||
for _, rr := range resp.DQ.Answers {
|
||||
item.Answers = append(item.Answers, idns.FormatRecord(rr))
|
||||
}
|
||||
switch resp.Status {
|
||||
case traverse.StatusError:
|
||||
item.Message = resp.DQ.ErrorMessage
|
||||
case traverse.StatusException:
|
||||
item.Message = resp.DQ.ExceptionMessage
|
||||
}
|
||||
}
|
||||
return item
|
||||
@@ -495,4 +583,3 @@ func newUUID() string {
|
||||
b[8] = (b[8] & 0x3f) | 0x80 // variant bits
|
||||
return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestSubscribeSnapshot_NoDuplicates regresses the subscribe/snapshot race:
|
||||
// subscribers arriving while events are being published must never see the
|
||||
// same event twice (once from the snapshot replay and once from the channel).
|
||||
// Events are numbered, so any duplicate breaks strict monotonicity. Slow
|
||||
// subscribers may legitimately drop events (publishLocked is non-blocking),
|
||||
// so gaps are not an error.
|
||||
func TestSubscribeSnapshot_NoDuplicates(t *testing.T) {
|
||||
job := &TraversalJob{Status: statusRunning}
|
||||
|
||||
const total = 2000
|
||||
const subscribers = 8
|
||||
|
||||
var pub sync.WaitGroup
|
||||
pub.Add(1)
|
||||
go func() {
|
||||
defer pub.Done()
|
||||
for i := 0; i < total; i++ {
|
||||
ev := ProgressEvent{RefID: strconv.Itoa(i)}
|
||||
job.mu.Lock()
|
||||
job.Progress = append(job.Progress, ev)
|
||||
job.publishLocked(ev)
|
||||
job.mu.Unlock()
|
||||
}
|
||||
job.mu.Lock()
|
||||
job.Status = statusComplete
|
||||
job.mu.Unlock()
|
||||
job.closeSubscribers()
|
||||
}()
|
||||
|
||||
var subs sync.WaitGroup
|
||||
errs := make(chan string, subscribers)
|
||||
for s := 0; s < subscribers; s++ {
|
||||
subs.Add(1)
|
||||
go func() {
|
||||
defer subs.Done()
|
||||
sub, past, done := job.subscribeSnapshot()
|
||||
defer job.unsubscribe(sub)
|
||||
|
||||
last := -1
|
||||
check := func(refid string) {
|
||||
n, err := strconv.Atoi(refid)
|
||||
if err != nil {
|
||||
errs <- "bad refid " + refid
|
||||
return
|
||||
}
|
||||
if n <= last {
|
||||
errs <- "event " + refid + " out of order or duplicated after " + strconv.Itoa(last)
|
||||
return
|
||||
}
|
||||
last = n
|
||||
}
|
||||
for _, ev := range past {
|
||||
check(ev.RefID)
|
||||
}
|
||||
if !done {
|
||||
for ev := range sub {
|
||||
check(ev.RefID)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
pub.Wait()
|
||||
subs.Wait()
|
||||
close(errs)
|
||||
for msg := range errs {
|
||||
t.Error(msg)
|
||||
}
|
||||
}
|
||||
@@ -5,12 +5,15 @@ import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.hansenits.com.au/hits/ExploreDNS/internal/config"
|
||||
"gitea.hansenits.com.au/hits/ExploreDNS/web/api"
|
||||
)
|
||||
|
||||
@@ -264,6 +267,43 @@ func TestStaticSPA_Index(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestStaticSPA_TypeOptions asserts the SPA type dropdown offers exactly the
|
||||
// query types config.ParseQueryType accepts.
|
||||
func TestStaticSPA_TypeOptions(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Shutdown(5 * time.Second) //nolint:errcheck
|
||||
|
||||
resp, err := http.Get("http://" + srv.Addr() + "/")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
page := string(body)
|
||||
|
||||
re := regexp.MustCompile(`<option>([A-Z]+)</option>`)
|
||||
var got []string
|
||||
for _, m := range re.FindAllStringSubmatch(page, -1) {
|
||||
got = append(got, m[1])
|
||||
}
|
||||
want := []string{"A", "AAAA", "NS", "CNAME", "MX", "TXT", "SOA", "PTR", "ANY"}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("type options = %v, want %v", got, want)
|
||||
}
|
||||
for i, typ := range want {
|
||||
if got[i] != typ {
|
||||
t.Fatalf("type options = %v, want %v", got, want)
|
||||
}
|
||||
if _, err := config.ParseQueryType(typ); err != nil {
|
||||
t.Fatalf("option %s rejected by ParseQueryType: %v", typ, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStaticSPA_FallbackToIndex(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Shutdown(5 * time.Second) //nolint:errcheck
|
||||
|
||||
+209
-155
@@ -285,22 +285,28 @@
|
||||
content: 'Awaiting traversal…';
|
||||
color: var(--text-dim);
|
||||
}
|
||||
.pe { display: flex; gap: 0.5rem; }
|
||||
.pe { display: flex; gap: 0.5rem; align-items: baseline; }
|
||||
.pe-badge {
|
||||
flex-shrink: 0;
|
||||
min-width: 70px;
|
||||
text-align: center;
|
||||
font-size: 0.65rem;
|
||||
padding: 1px 5px;
|
||||
border-radius: 3px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
background: rgba(139,143,168,0.15);
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.pe-badge.start { background: rgba(74,124,246,0.18); color: var(--primary); }
|
||||
.pe-badge.complete { background: rgba(62,207,142,0.18); color: var(--success); }
|
||||
.pe-badge.resolve { background: rgba(56,189,248,0.18); color: var(--info); }
|
||||
.pe-depth { color: var(--text-dim); }
|
||||
.pe-name { color: var(--text); }
|
||||
.pe-server { color: var(--text-muted); }
|
||||
.pe-badge.st-working { background: rgba(74,124,246,0.18); color: var(--primary); }
|
||||
.pe-badge.st-answered { background: rgba(62,207,142,0.18); color: var(--success); }
|
||||
.pe-badge.st-resolve { background: rgba(56,189,248,0.18); color: var(--info); }
|
||||
.pe-badge.st-warn { background: rgba(245,166,35,0.18); color: var(--warning); }
|
||||
.pe-badge.st-err { background: rgba(240,68,56,0.18); color: var(--danger); }
|
||||
/* Progress lines mirror the CLI: "<refid> <server> (<ips>)" — keep the
|
||||
spacing intact. */
|
||||
.pe-text { color: var(--text); white-space: pre; }
|
||||
|
||||
/* ── Results tree ───────────────────────────────────────────────── */
|
||||
.results-section h2 {
|
||||
@@ -318,57 +324,44 @@
|
||||
color: var(--text-dim);
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
.result-item {
|
||||
/* Aggregated leaves rendered like the CLI Results section: fixed-width
|
||||
text with significant leading spaces, so white-space must be pre. */
|
||||
.result-block {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.8rem;
|
||||
font-size: 0.78rem;
|
||||
line-height: 1.5;
|
||||
white-space: pre;
|
||||
overflow-x: auto;
|
||||
margin: 0 0 0.5rem;
|
||||
padding: 0.5rem 0.75rem;
|
||||
border-radius: var(--radius-sm);
|
||||
border: 1px solid var(--border);
|
||||
margin-bottom: 0.5rem;
|
||||
border-left-width: 3px;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg-card);
|
||||
transition: border-color 0.12s;
|
||||
color: var(--text);
|
||||
}
|
||||
.result-item:hover { border-color: var(--border-focus); }
|
||||
.result-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.result-indent { color: var(--text-dim); flex-shrink: 0; }
|
||||
.rtype-badge {
|
||||
font-size: 0.65rem;
|
||||
padding: 1px 5px;
|
||||
border-radius: 3px;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.rtype-answer { background: rgba(62,207,142,0.15); color: var(--success); }
|
||||
.rtype-referral { background: rgba(74,124,246,0.15); color: var(--primary); }
|
||||
.rtype-nxdomain,
|
||||
.rtype-servfail { background: rgba(240,68,56,0.15); color: var(--danger); }
|
||||
.rtype-timeout { background: rgba(245,166,35,0.15); color: var(--warning); }
|
||||
.rtype-nodata { background: rgba(56,189,248,0.15); color: var(--info); }
|
||||
.rtype-cname { background: rgba(168,85,247,0.15); color: #c084fc; }
|
||||
.rtype-other { background: rgba(139,143,168,0.15);color: var(--text-muted); }
|
||||
.result-block.st-answered { border-left-color: var(--success); }
|
||||
.result-block.st-warn { border-left-color: var(--warning); }
|
||||
.result-block.st-err { border-left-color: var(--danger); }
|
||||
.result-block.st-other { border-left-color: var(--text-dim); }
|
||||
|
||||
.result-prob {
|
||||
color: var(--text-muted);
|
||||
font-size: 0.72rem;
|
||||
}
|
||||
.result-server { color: var(--text-dim); font-size: 0.72rem; margin-left: auto; }
|
||||
.result-answers {
|
||||
margin-top: 0.35rem;
|
||||
padding-left: 1.2rem;
|
||||
color: var(--text-muted);
|
||||
/* ── Summary Results ───────────────────────────────────────────── */
|
||||
.summary-pre {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.75rem;
|
||||
line-height: 1.6;
|
||||
white-space: pre;
|
||||
overflow-x: auto;
|
||||
margin: 0 0 1rem;
|
||||
padding: 0.6rem 0.75rem;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
}
|
||||
.result-answers span { display: block; }
|
||||
.cname-chain {
|
||||
color: #c084fc;
|
||||
font-size: 0.72rem;
|
||||
margin-top: 0.2rem;
|
||||
padding-left: 1.2rem;
|
||||
.summary-pre:empty::before {
|
||||
content: 'No summary yet.';
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
/* ── Stats panel ────────────────────────────────────────────────── */
|
||||
@@ -478,17 +471,16 @@
|
||||
autocapitalize="off"
|
||||
spellcheck="false"
|
||||
/>
|
||||
<!-- Options must match config.ParseQueryType exactly. -->
|
||||
<select id="typeSelect" class="type-select" title="DNS record type">
|
||||
<option>A</option>
|
||||
<option>AAAA</option>
|
||||
<option>MX</option>
|
||||
<option>NS</option>
|
||||
<option>CNAME</option>
|
||||
<option>SOA</option>
|
||||
<option>MX</option>
|
||||
<option>TXT</option>
|
||||
<option>SOA</option>
|
||||
<option>PTR</option>
|
||||
<option>SRV</option>
|
||||
<option>CAA</option>
|
||||
<option>ANY</option>
|
||||
</select>
|
||||
<button id="submitBtn" class="submit-btn">
|
||||
@@ -549,14 +541,17 @@
|
||||
<!-- Right: stats panel -->
|
||||
<div>
|
||||
<div class="card">
|
||||
<div class="card-title">📊 Summary</div>
|
||||
<div class="card-title">📊 Summary Results</div>
|
||||
<pre class="summary-pre" id="summaryPre"></pre>
|
||||
|
||||
<div class="card-title">Overview</div>
|
||||
<div class="stat-grid" id="statGrid">
|
||||
<div class="stat-item">
|
||||
<div class="stat-label">Status</div>
|
||||
<div class="stat-value" id="statStatus">—</div>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<div class="stat-label">Steps</div>
|
||||
<div class="stat-label">Results</div>
|
||||
<div class="stat-value" id="statSteps">—</div>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
@@ -640,6 +635,7 @@
|
||||
const detailType = document.getElementById('detailType');
|
||||
const detailStarted = document.getElementById('detailStarted');
|
||||
const detailFinished= document.getElementById('detailFinished');
|
||||
const summaryPre = document.getElementById('summaryPre');
|
||||
|
||||
// ── State ─────────────────────────────────────────────────────────
|
||||
let currentJobId = null;
|
||||
@@ -647,6 +643,7 @@
|
||||
let startTime = null;
|
||||
let timerInterval = null;
|
||||
let progressItems = [];
|
||||
let progressRows = new Map(); // refid → row elements, updated in place
|
||||
let resultItems = [];
|
||||
|
||||
// ── Theme toggle ──────────────────────────────────────────────────
|
||||
@@ -745,41 +742,57 @@
|
||||
}
|
||||
|
||||
// ── Progress rendering ────────────────────────────────────────────
|
||||
// One row per refid, updated in place as later events (start/answer/
|
||||
// answer_fast) arrive for the same node. Line format mirrors the CLI:
|
||||
// "<refid> <server> (<ips>)" plus resolving / completed-earlier markers.
|
||||
function appendProgress(ev) {
|
||||
progressItems.push(ev);
|
||||
progressCount.textContent = progressItems.length;
|
||||
if (!ev.refid) return;
|
||||
|
||||
const row = document.createElement('div');
|
||||
row.className = 'pe';
|
||||
|
||||
const badgeClass = ev.is_resolve ? 'resolve' : ev.stage;
|
||||
const badge = document.createElement('span');
|
||||
badge.className = `pe-badge ${badgeClass}`;
|
||||
badge.textContent = ev.is_resolve ? 'glue' : ev.stage;
|
||||
|
||||
const depth = document.createElement('span');
|
||||
depth.className = 'pe-depth';
|
||||
depth.textContent = `[d${ev.depth}]`;
|
||||
|
||||
const name = document.createElement('span');
|
||||
name.className = 'pe-name';
|
||||
name.textContent = ev.name + ' (' + ev.qtype + ')';
|
||||
|
||||
row.appendChild(badge);
|
||||
row.appendChild(depth);
|
||||
row.appendChild(name);
|
||||
|
||||
if (ev.server) {
|
||||
const srv = document.createElement('span');
|
||||
srv.className = 'pe-server';
|
||||
srv.textContent = '@ ' + ev.server;
|
||||
row.appendChild(srv);
|
||||
let row = progressRows.get(ev.refid);
|
||||
if (!row) {
|
||||
const el = document.createElement('div');
|
||||
el.className = 'pe';
|
||||
const badge = document.createElement('span');
|
||||
badge.className = 'pe-badge';
|
||||
const text = document.createElement('span');
|
||||
text.className = 'pe-text';
|
||||
el.appendChild(badge);
|
||||
el.appendChild(text);
|
||||
row = { el, badge, text };
|
||||
progressRows.set(ev.refid, row);
|
||||
progressFeed.appendChild(el);
|
||||
}
|
||||
|
||||
progressFeed.appendChild(row);
|
||||
const status = ev.status || ev.stage;
|
||||
row.badge.textContent = ev.is_resolve ? 'glue ' + status : status;
|
||||
row.badge.className = 'pe-badge ' + progressBadgeCls(ev);
|
||||
|
||||
let line = ev.refid + ' ' + (ev.server || ev.name);
|
||||
if (ev.ips) line += ' (' + ev.ips + ')';
|
||||
if (ev.completed_earlier) {
|
||||
line += ' -- completed earlier (' + ev.completed_earlier + ')';
|
||||
} else if (ev.stage === 'start' && !ev.ips) {
|
||||
line += ' -- resolving';
|
||||
}
|
||||
row.text.textContent = line;
|
||||
|
||||
progressFeed.scrollTop = progressFeed.scrollHeight;
|
||||
}
|
||||
|
||||
function progressBadgeCls(ev) {
|
||||
if (ev.is_resolve) return 'st-resolve';
|
||||
switch (ev.status) {
|
||||
case 'answered': return 'st-answered';
|
||||
case 'referral_lame': case 'noglue': return 'st-warn';
|
||||
case 'error': case 'exception':
|
||||
case 'loop': case 'cname_loop': return 'st-err';
|
||||
case 'referral': case 'restart': return 'st-working';
|
||||
default: return 'st-working';
|
||||
}
|
||||
}
|
||||
|
||||
// ── Results rendering ─────────────────────────────────────────────
|
||||
function renderResults(job) {
|
||||
detailDomain.textContent = job.domain || '—';
|
||||
@@ -809,98 +822,137 @@
|
||||
resultsEmpty.classList.add('hidden');
|
||||
|
||||
items.forEach(item => {
|
||||
resultsContainer.appendChild(buildResultItem(item));
|
||||
resultsContainer.appendChild(buildResultBlock(item, job));
|
||||
});
|
||||
|
||||
setStatus('complete', `Traversal complete — ${items.length} step${items.length === 1 ? '' : 's'}`);
|
||||
renderSummary(job.summary);
|
||||
|
||||
setStatus('complete', `Traversal complete — ${items.length} result${items.length === 1 ? '' : 's'}`);
|
||||
updateStats(job);
|
||||
}
|
||||
|
||||
function buildResultItem(item) {
|
||||
const el = document.createElement('div');
|
||||
el.className = 'result-item';
|
||||
// pct5 renders "%5.1f%%" like the CLI Results head.
|
||||
function pct5(p) {
|
||||
return (p * 100).toFixed(1).padStart(5) + '%';
|
||||
}
|
||||
|
||||
const header = document.createElement('div');
|
||||
header.className = 'result-header';
|
||||
|
||||
// Depth indent
|
||||
const indent = document.createElement('span');
|
||||
indent.className = 'result-indent';
|
||||
indent.textContent = ' '.repeat(item.depth) + (item.depth > 0 ? '└─ ' : '');
|
||||
|
||||
// Type badge
|
||||
const rtype = (item.response_type || 'unknown').toLowerCase();
|
||||
const badge = document.createElement('span');
|
||||
badge.className = `rtype-badge rtype-${rtypeCls(rtype)}`;
|
||||
badge.textContent = item.response_type || '?';
|
||||
|
||||
// Probability
|
||||
const prob = document.createElement('span');
|
||||
prob.className = 'result-prob';
|
||||
if (typeof item.probability === 'number' && item.probability > 0) {
|
||||
prob.textContent = (item.probability * 100).toFixed(1) + '%';
|
||||
}
|
||||
|
||||
// Server
|
||||
const server = document.createElement('span');
|
||||
server.className = 'result-server';
|
||||
server.textContent = item.server || '';
|
||||
|
||||
header.appendChild(indent);
|
||||
header.appendChild(badge);
|
||||
if (prob.textContent) header.appendChild(prob);
|
||||
if (server.textContent) header.appendChild(server);
|
||||
|
||||
el.appendChild(header);
|
||||
|
||||
// CNAME chain
|
||||
if (item.cname_chain && item.cname_chain.length > 0) {
|
||||
const chain = document.createElement('div');
|
||||
chain.className = 'cname-chain';
|
||||
chain.textContent = 'CNAME → ' + item.cname_chain.join(' → ');
|
||||
el.appendChild(chain);
|
||||
}
|
||||
|
||||
// Answers
|
||||
if (item.answers && item.answers.length > 0) {
|
||||
const ansBox = document.createElement('div');
|
||||
ansBox.className = 'result-answers';
|
||||
item.answers.forEach(a => {
|
||||
const s = document.createElement('span');
|
||||
s.textContent = a;
|
||||
ansBox.appendChild(s);
|
||||
});
|
||||
el.appendChild(ansBox);
|
||||
}
|
||||
// pctTrim renders the Summary Results probability: %5.1f%% with a trailing
|
||||
// ".0" trimmed, right-justified to width 5.
|
||||
function pctTrim(p) {
|
||||
let t = (p * 100).toFixed(1) + '%';
|
||||
t = t.replace('.0%', '%');
|
||||
return t.padStart(5);
|
||||
}
|
||||
|
||||
// buildResultBlock renders one aggregated leaf with the CLI Results wording
|
||||
// as a pre block (leading spaces are significant).
|
||||
function buildResultBlock(item, job) {
|
||||
const el = document.createElement('pre');
|
||||
el.className = 'result-block ' + statusCls(item.status);
|
||||
el.textContent = leafLines(item, job).join('\n');
|
||||
return el;
|
||||
}
|
||||
|
||||
function rtypeCls(rtype) {
|
||||
if (rtype.includes('answer')) return 'answer';
|
||||
if (rtype.includes('referral')) return 'referral';
|
||||
if (rtype.includes('nxdomain')) return 'nxdomain';
|
||||
if (rtype.includes('servfail')) return 'servfail';
|
||||
if (rtype.includes('timeout')) return 'timeout';
|
||||
if (rtype.includes('nodata')) return 'nodata';
|
||||
if (rtype.includes('cname')) return 'cname';
|
||||
return 'other';
|
||||
function leafLines(item, job) {
|
||||
const indent = ' '.repeat(12);
|
||||
const head = pct5(item.probability || 0) + ': ';
|
||||
const where = `${item.server || ''} (${item.ip || ''})`;
|
||||
const lines = [];
|
||||
|
||||
switch (item.status) {
|
||||
case 'answered':
|
||||
lines.push(head + 'Answer from ' + where);
|
||||
(item.answers || []).forEach(a => lines.push(indent + a));
|
||||
break;
|
||||
case 'nodata':
|
||||
lines.push(head + 'NODATA (for this type) at ' + where);
|
||||
break;
|
||||
case 'noglue':
|
||||
lines.push(head + `No glue at ${item.parent || ''} (${item.ip || ''}) for ${item.server || ''}`);
|
||||
break;
|
||||
case 'referral_lame':
|
||||
lines.push(head + `Lame referral from ${item.parent || ''} (${item.parent_ip || ''}) to ${where}`);
|
||||
break;
|
||||
case 'loop':
|
||||
lines.push(head + `Loop encountered at ${item.server || ''}`);
|
||||
break;
|
||||
case 'cname_loop':
|
||||
lines.push(head + `CNAME loop encountered at ${item.server || ''}`);
|
||||
break;
|
||||
case 'error':
|
||||
case 'exception':
|
||||
lines.push(head + `${item.message || item.status} at ${where}`);
|
||||
break;
|
||||
default:
|
||||
lines.push(head + 'Stopped at ' + where);
|
||||
}
|
||||
|
||||
if (item.status !== 'answered' && item.qname) {
|
||||
const orig = (job.domain || '').replace(/\.$/, '').toLowerCase();
|
||||
const qn = item.qname.replace(/\.$/, '').toLowerCase();
|
||||
if (qn !== orig || (item.qtype || '') !== (job.query_type || '')) {
|
||||
lines.push(indent + `While querying ${item.qname}/${item.qclass || 'IN'}/${item.qtype || ''}`);
|
||||
}
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
function statusCls(status) {
|
||||
switch (status) {
|
||||
case 'answered': return 'st-answered';
|
||||
case 'referral_lame': case 'noglue': return 'st-warn';
|
||||
case 'error': case 'exception':
|
||||
case 'loop': case 'cname_loop': return 'st-err';
|
||||
default: return 'st-other';
|
||||
}
|
||||
}
|
||||
|
||||
// ── Summary Results rendering (CLI Summary Results wording) ───────
|
||||
function renderSummary(summary) {
|
||||
if (!summary) { summaryPre.textContent = ''; return; }
|
||||
const lines = [];
|
||||
(summary.answers || []).forEach(a => {
|
||||
const initial = pctTrim(a.probability) + ' answered with ';
|
||||
const recs = a.records || [];
|
||||
if (recs.length === 0) {
|
||||
lines.push(initial.trimEnd());
|
||||
return;
|
||||
}
|
||||
lines.push(initial + recs[0]);
|
||||
for (let i = 1; i < recs.length; i++) {
|
||||
lines.push(' '.repeat(initial.length) + recs[i]);
|
||||
}
|
||||
});
|
||||
(summary.by_status || []).forEach(s => {
|
||||
lines.push(pctTrim(s.probability) + ' ' + summaryStatusLabel(s.status));
|
||||
});
|
||||
summaryPre.textContent = lines.join('\n');
|
||||
}
|
||||
|
||||
function summaryStatusLabel(status) {
|
||||
switch (status) {
|
||||
case 'nodata': return 'found no such record';
|
||||
case 'referral_lame': return 'resulted in a lame referral';
|
||||
case 'exception': return 'resulted in an exception';
|
||||
case 'error': return 'resulted in an error';
|
||||
case 'noglue': return 'found no glue';
|
||||
case 'loop': return 'resulted in a loop';
|
||||
case 'cname_loop': return 'resulted in a CNAME loop';
|
||||
default: return status;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Stats ─────────────────────────────────────────────────────────
|
||||
function updateStats(job) {
|
||||
const items = job.results || [];
|
||||
const steps = items.length;
|
||||
const answers = items.filter(r => (r.response_type||'').toLowerCase().includes('answer')).length;
|
||||
const errors = items.filter(r => {
|
||||
const t = (r.response_type||'').toLowerCase();
|
||||
return t.includes('error') || t.includes('servfail') || t.includes('timeout') || t.includes('nxdomain');
|
||||
}).length;
|
||||
const answers = items.filter(r => r.status === 'answered').length;
|
||||
const errors = items.filter(r => statusCls(r.status) === 'st-err').length;
|
||||
const maxDepth = items.reduce((m, r) => Math.max(m, r.depth || 0), 0);
|
||||
|
||||
const statusCls = job.status === 'complete' ? 'ok' : job.status === 'error' ? 'err' : '';
|
||||
const jobStateCls = job.status === 'complete' ? 'ok' : job.status === 'error' ? 'err' : '';
|
||||
statStatus.textContent = job.status || '—';
|
||||
statStatus.className = `stat-value ${statusCls}`;
|
||||
statStatus.className = `stat-value ${jobStateCls}`;
|
||||
statSteps.textContent = steps || '—';
|
||||
statAnswers.textContent = answers || '—';
|
||||
statErrors.className = `stat-value ${errors > 0 ? 'warn' : ''}`;
|
||||
@@ -919,7 +971,9 @@
|
||||
errorBox.textContent = '';
|
||||
progressFeed.innerHTML = '';
|
||||
progressItems = [];
|
||||
progressRows = new Map();
|
||||
progressCount.textContent = '0';
|
||||
summaryPre.textContent = '';
|
||||
resultItems = [];
|
||||
resultsCount.textContent = '0';
|
||||
// Remove old result items but keep resultsEmpty
|
||||
|
||||
Reference in New Issue
Block a user