diff --git a/.gitignore b/.gitignore index ace101a..eab8ce1 100644 --- a/.gitignore +++ b/.gitignore @@ -8,5 +8,5 @@ .claude/settings.local.json # binary -hp -hittyping +/hp +/hittyping diff --git a/CHANGELOG.md b/CHANGELOG.md index e35950c..21b4b77 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,22 @@ All notable changes to hp (hittyping) will be documented in this file. +## [0.8.8] - 2026-11-15 + +### Added + +- `--skill` prints the agent skill (`skills/hp/SKILL.md`, embedded): how an AI agent should run hp bounded and read its output; a test fails when a flag is missing from it +- `--fail-style dots|bang` (env `HP_FAIL_STYLE`) picks the braille failure marker: `dots` is the purple `⣿` of 0.8.7 (default), `bang` restores the red `!` of 0.8.6 and earlier + +### Changed + +- Fixed-rate sending, as ping does: a request starts every `--interval` whatever earlier ones are doing, so one glyph is one interval of wall time during outages too. Before, a timed-out request blocked the next, and with the defaults each failure glyph stood for 6 s (12 s per braille cell) against 1 s while up. Loss % is now the share of time the host did not answer. Results are drawn in send order; up to timeout ÷ interval requests can be in flight +- Timeline periods start at the send time of their first request + +### Fixed + +- `host:port` targets (`hp example.com:8443`, `hp 127.0.0.1:8080`) no longer fail the startup DNS check with "cannot resolve" + ## [0.8.7] - 2026-11-08 ### Security diff --git a/CLAUDE.md b/CLAUDE.md index deca4d4..01901de 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -50,6 +50,8 @@ hp -3 cloudflare.com # Use HTTP/3 (or --http3) hp -3 -d example.com # HTTP/3 with auto-downgrade on failures hp -3 -D example.com # Auto-downgrade including plain HTTP hp -b cloudflare.com # Braille mode (2x density) +hp -b --fail-style bang cloudflare.com # Braille failures as red ! (up to 0.8.6 look) +hp --skill # Print the agent skill (skills/hp/SKILL.md, embedded) hp -g 100 -y 200 8.8.8.8 # Custom thresholds (or --green, --yellow) HTTPS_PROXY=socks5://host:port hp cloudflare.com # Via SOCKS5 proxy ``` @@ -63,6 +65,7 @@ HTTPS_PROXY=socks5://host:port hp cloudflare.com # Via SOCKS5 proxy | `-j` | `--jitter` | | 0 | Max random jitter to add to interval (e.g., 200ms, 3s) | | `-t` | `--timeout` | | 5s | Request timeout | | `-b` | `--braille` | | false | Use braille visualization (2x density) | +| | `--fail-style` | `HP_FAIL_STYLE` | dots | Braille failure marker: `dots` (purple ⣿) or `bang` (red !, up to 0.8.6) | | | `--legend` | | false | Show legend line | | | `--noheader` | | false | Hide header line | | `-q` | `--quiet` | | false | Hide header and legend | @@ -77,6 +80,7 @@ HTTPS_PROXY=socks5://host:port hp cloudflare.com # Via SOCKS5 proxy | `-d` | `--downgrade` | | false | Auto-downgrade on 3 failures (secure only) | | `-D` | `--downgrade-insecure` | | false | Auto-downgrade including plain HTTP | | `-v` | `--version` | | | Show version and exit | +| | `--skill` | | | Print the agent skill and exit | | `-h` | `--help` | | | Show help and exit | ## Architecture @@ -85,12 +89,21 @@ Go application using `spf13/pflag` for POSIX-style CLI flags. Uses latest stable Key functions: +- `runFixedRate()` - Starts a request every interval (never waits on earlier ones) and hands results over in send order (`schedule.go`) +- `recordResult()` - Adds one result to stats, timeline and bar - `measureRTT()` - HEAD request timing - `createClient()` - Creates HTTP client for given protocol level - `getURLForProto()` - Returns URL with appropriate scheme for protocol - `getBlock()` - Maps latency to Unicode block + color - `printDisplay()` - Live bar and stats rendering with ANSI cursor control - `printFinal()` - Summary on Ctrl+C +- `defineFlags()` - Every CLI flag, on a given FlagSet (tests enumerate it) + +### Agent skill + +`skills/hp/SKILL.md` is the agent-facing usage guide, embedded in the binary and printed by `hp --skill`. +`TestSkillDocumentsEveryFlag` fails when a flag in `defineFlags()` is missing from it, so add or change a flag and +its skill row in the same commit. ## Visual Output diff --git a/README.md b/README.md index 4910ea8..1393890 100644 --- a/README.md +++ b/README.md @@ -98,6 +98,8 @@ hp -3 dns.google # HTTP/3 (QUIC) hp -3 -d example.com # HTTP/3 with auto-downgrade on failures hp -3 -D example.com # Auto-downgrade including plain HTTP hp -b cloudflare.com # Braille mode (2x density) +hp -b --fail-style bang site # Braille failures as red ! (pre-0.8.7 look) +hp --skill # Print the agent skill (usage guide for AI agents) hp -g 50 -y 100 cloudflare.com # Custom thresholds (ms) HTTPS_PROXY=socks5://host:1080 hp site # Via SOCKS5 proxy HTTP_PROXY=http://proxy:8080 hp -1 site # Via HTTP proxy @@ -112,6 +114,7 @@ HTTP_PROXY=http://proxy:8080 hp -1 site # Via HTTP proxy | `-j` | `--jitter` | | 0 | Max random jitter to add to interval (e.g., 200ms, 3s) | | `-t` | `--timeout` | | 5s | Request timeout | | `-b` | `--braille` | | false | Use braille visualization (2x density) | +| | `--fail-style` | `HP_FAIL_STYLE` | dots | Braille failure marker: `dots` (purple ⣿) or `bang` (red !, the look up to 0.8.6) | | | `--legend` | | false | Show legend (hidden by default) | | | `--noheader` | | false | Hide header line | | `-q` | `--quiet` | | false | Hide header and legend | @@ -126,6 +129,7 @@ HTTP_PROXY=http://proxy:8080 hp -1 site # Via HTTP proxy | `-d` | `--downgrade` | | false | Auto-downgrade on 3 failures (secure only) | | `-D` | `--downgrade-insecure` | | false | Auto-downgrade including plain HTTP | | `-v` | `--version` | | | Show version | +| | `--skill` | | | Print the agent skill (how an AI agent should run and read hp) | | `-h` | `--help` | | | Show help | ## Visual Guide @@ -137,6 +141,8 @@ HTTP_PROXY=http://proxy:8080 hp -1 site # Via HTTP proxy Block height scales within each color zone based on latency. +In braille mode (`-b`) a cell holds two requests, and a cell with a failure is a purple `⣿`. `--fail-style bang` brings back the look up to 0.8.6: a red `!` when both requests failed, and a blank column when one did. + ## Platform Support Developed on macOS. Tested on Windows and Linux. diff --git a/ROADMAP.md b/ROADMAP.md index 59d68ff..b446769 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -74,6 +74,13 @@ If hp evolves toward interactive features, consider migrating to [Bubble Tea](ht ## Completed +### v0.8.8 - Fixed-Rate Sending & Agent Skill + +- [x] Fixed-rate sending like ping: one glyph per interval, also during outages; time-based loss % +- [x] `--fail-style dots|bang` to choose the braille failure marker (purple `⣿` or the pre-0.8.7 red `!`) +- [x] `--skill` prints the embedded agent skill +- [x] Fix `host:port` targets failing the startup DNS check + ### v0.8.7 - Braille Failure Cells - [x] Braille mode: failures render as a full purple cell instead of `!` diff --git a/main.go b/main.go index ca51355..a237009 100644 --- a/main.go +++ b/main.go @@ -2,6 +2,7 @@ package main import ( "crypto/tls" + _ "embed" "fmt" "io" "log" @@ -22,21 +23,24 @@ import ( // cleanly pause rendering before the process is actually stopped. var displayMu sync.Mutex -const version = "0.8.7" +const version = "0.8.8" + +//go:embed skills/hp/SKILL.md +var skillText string const ( // ANSI colors - green = "\033[32m" - yellow = "\033[33m" - red = "\033[31m" - purple = "\033[35m" - gray = "\033[90m" - bold = "\033[1m" - reset = "\033[0m" - clearLn = "\033[K" - up = "\033[A" - down = "\033[B" - col0 = "\033[0G" + green = "\033[32m" + yellow = "\033[33m" + red = "\033[31m" + purple = "\033[35m" + gray = "\033[90m" + bold = "\033[1m" + reset = "\033[0m" + clearLn = "\033[K" + up = "\033[A" + down = "\033[B" + col0 = "\033[0G" hideCur = "\033[?25l" showCur = "\033[?25h" steadyCur = "\033[2 q" // DECSCUSR: steady block cursor @@ -74,6 +78,26 @@ var ( yellowThreshold int64 = 400 ) +// failStyle selects how a failed request is drawn in braille mode. +// Block mode always draws a red "!". +type failStyle int + +const ( + failDots failStyle = iota // purple full cell ⣿ for any pair holding a failure (0.8.7+) + failBang // red "!" for two failures, blank side for one (up to 0.8.6) +) + +var failStyleNames = map[string]failStyle{"dots": failDots, "bang": failBang} + +var brailleFail = failDots + +func parseFailStyle(name string) (failStyle, error) { + if fs, ok := failStyleNames[strings.ToLower(name)]; ok { + return fs, nil + } + return 0, fmt.Errorf("invalid fail style %q (want dots or bang)", name) +} + // getEnvInt returns the env var value as int64, or the default if not set/invalid func getEnvInt(key string, def int64) int64 { if v := os.Getenv(key); v != "" { @@ -107,10 +131,11 @@ type stats struct { currentPeriod *period // active period (nil until first request) } -func recordPeriod(s *stats, up bool) { - now := time.Now() +// recordPeriod counts a request into the UP/DOWN timeline. at is when the +// request was sent, so a period starts when its first request went out. +func recordPeriod(s *stats, up bool, at time.Time) { if s.currentPeriod == nil { - s.currentPeriod = &period{up: up, start: now, count: 1} + s.currentPeriod = &period{up: up, start: at, count: 1} return } if s.currentPeriod.up == up { @@ -119,7 +144,46 @@ func recordPeriod(s *stats, up bool) { } // State flipped — close current period and start new one s.periods = append(s.periods, *s.currentPeriod) - s.currentPeriod = &period{up: up, start: now, count: 1} + s.currentPeriod = &period{up: up, start: at, count: 1} +} + +// recordResult adds a finished request to the stats, the timeline and the bar. +func recordResult(s *stats, r result) { + rtt := r.rtt + if r.err != nil { + s.failures++ + rtt = -1 + } else { + s.count++ + s.total += rtt + s.last = rtt + s.min = min(s.min, rtt) + s.max = max(s.max, rtt) + } + recordPeriod(s, r.err == nil, r.sentAt) + + switch { + case s.braille && s.hasPending: + s.blocks = append(s.blocks, getBrailleChar(s.pendingRTT, rtt)) + s.hasPending = false + case s.braille: + s.pendingRTT, s.hasPending = rtt, true + case r.err != nil: + s.blocks = append(s.blocks, red+bold+"!"+reset) + default: + s.blocks = append(s.blocks, getBlock(rtt)) + } +} + +// lowerWorkingProto probes each protocol below current, down to minProto, +// and returns the first one that answers. +func lowerWorkingProto(host string, current, minProto int, timeout time.Duration, insecure bool) (int, bool) { + for p := current - 1; p >= minProto; p-- { + if _, err := measureRTT(createClient(p, timeout, insecure), getURLForProto(host, p), p); err == nil { + return p, true + } + } + return current, false } func closePeriods(s *stats) { @@ -129,48 +193,85 @@ func closePeriods(s *stats) { } } +type options struct { + interval, jitter, timeout *time.Duration + count *int + showLegend, noHeader, useBraille *bool + quiet, silent, insecure *bool + useHTTP1, useHTTP2, useHTTP3 *bool + downgrade, downgradeInsecure *bool + showVersion, showSkill *bool + minFlag, greenFlag, yellowFlag *int64 + failStyle *string +} + +func defineFlags(fs *flag.FlagSet) *options { + return &options{ + interval: fs.DurationP("interval", "i", time.Second, "interval between requests"), + jitter: fs.DurationP("jitter", "j", 0, "max random jitter to add to interval (e.g., 200ms, 3s)"), + timeout: fs.DurationP("timeout", "t", 5*time.Second, "request timeout"), + count: fs.IntP("count", "c", 0, "number of requests (0 = unlimited)"), + showLegend: fs.Bool("legend", false, "show the legend line"), + noHeader: fs.Bool("noheader", false, "hide the header line"), + useBraille: fs.BoolP("braille", "b", false, "use braille visualization (2x density)"), + failStyle: fs.String("fail-style", "", "braille failure marker: dots (purple ⣿) or bang (red !, up to 0.8.6) (env: HP_FAIL_STYLE)"), + quiet: fs.BoolP("quiet", "q", false, "hide header and legend"), + silent: fs.BoolP("silent", "Q", false, "hide header, legend, and final stats"), + minFlag: fs.Int64P("min", "m", 0, "min latency baseline in ms (env: HP_MIN)"), + greenFlag: fs.Int64P("green", "g", 0, "green threshold in ms (env: HP_GREEN)"), + yellowFlag: fs.Int64P("yellow", "y", 0, "yellow threshold in ms (env: HP_YELLOW)"), + insecure: fs.BoolP("insecure", "k", false, "skip TLS certificate verification"), + useHTTP1: fs.BoolP("http", "1", false, "use plain HTTP/1.1"), + useHTTP2: fs.BoolP("http2", "2", false, "force HTTP/2 (fail if not negotiated)"), + useHTTP3: fs.BoolP("http3", "3", false, "use HTTP/3 (QUIC)"), + downgrade: fs.BoolP("downgrade", "d", false, "auto-downgrade protocol on failures (secure only)"), + downgradeInsecure: fs.BoolP("downgrade-insecure", "D", false, "auto-downgrade including plain HTTP"), + showVersion: fs.BoolP("version", "v", false, "show version and exit"), + showSkill: fs.Bool("skill", false, "print the agent skill (how to use hp) and exit"), + } +} + func main() { // Silence quic-go UDP buffer warnings that corrupt terminal display log.SetOutput(io.Discard) - interval := flag.DurationP("interval", "i", time.Second, "interval between requests") - jitter := flag.DurationP("jitter", "j", 0, "max random jitter to add to interval (e.g., 200ms, 3s)") - timeout := flag.DurationP("timeout", "t", 5*time.Second, "request timeout") - count := flag.IntP("count", "c", 0, "number of requests (0 = unlimited)") - showLegend := flag.Bool("legend", false, "show the legend line") - noHeader := flag.Bool("noheader", false, "hide the header line") - useBraille := flag.BoolP("braille", "b", false, "use braille visualization (2x density)") - quiet := flag.BoolP("quiet", "q", false, "hide header and legend") - silent := flag.BoolP("silent", "Q", false, "hide header, legend, and final stats") - minFlag := flag.Int64P("min", "m", 0, "min latency baseline in ms (env: HP_MIN)") - greenFlag := flag.Int64P("green", "g", 0, "green threshold in ms (env: HP_GREEN)") - yellowFlag := flag.Int64P("yellow", "y", 0, "yellow threshold in ms (env: HP_YELLOW)") - insecure := flag.BoolP("insecure", "k", false, "skip TLS certificate verification") - useHTTP1 := flag.BoolP("http", "1", false, "use plain HTTP/1.1") - useHTTP2 := flag.BoolP("http2", "2", false, "force HTTP/2 (fail if not negotiated)") - useHTTP3 := flag.BoolP("http3", "3", false, "use HTTP/3 (QUIC)") - downgrade := flag.BoolP("downgrade", "d", false, "auto-downgrade protocol on failures (secure only)") - downgradeInsecure := flag.BoolP("downgrade-insecure", "D", false, "auto-downgrade including plain HTTP") - showVersion := flag.BoolP("version", "v", false, "show version and exit") + o := defineFlags(flag.CommandLine) flag.Parse() - if *showVersion { + if *o.showVersion { fmt.Printf("hp (hittyping) version %s\n", version) os.Exit(0) } + if *o.showSkill { + fmt.Print(skillText) + os.Exit(0) + } // Apply thresholds: env vars first, flags override minLatency = getEnvInt("HP_MIN", minLatency) greenThreshold = getEnvInt("HP_GREEN", greenThreshold) yellowThreshold = getEnvInt("HP_YELLOW", yellowThreshold) - if *minFlag > 0 { - minLatency = *minFlag + if *o.minFlag > 0 { + minLatency = *o.minFlag } - if *greenFlag > 0 { - greenThreshold = *greenFlag + if *o.greenFlag > 0 { + greenThreshold = *o.greenFlag } - if *yellowFlag > 0 { - yellowThreshold = *yellowFlag + if *o.yellowFlag > 0 { + yellowThreshold = *o.yellowFlag + } + + styleName := os.Getenv("HP_FAIL_STYLE") + if *o.failStyle != "" { + styleName = *o.failStyle + } + if styleName != "" { + fs, err := parseFailStyle(styleName) + if err != nil { + fmt.Fprintln(os.Stderr, "Error:", err) + os.Exit(1) + } + brailleFail = fs } // Extract host (without scheme) for building URLs dynamically @@ -194,8 +295,7 @@ func main() { // Skipped when a proxy is configured: the proxy resolves the host // (e.g. socks5h), so the local resolver may legitimately fail. resolvedIP := "" - // Strip brackets from IPv6 for parsing and display - hostForLookup := strings.TrimPrefix(strings.TrimSuffix(displayURL, "]"), "[") + hostForLookup := hostname(displayURL) if ip := net.ParseIP(hostForLookup); ip == nil && !proxyConfigured() { ips, err := net.LookupHost(hostForLookup) if err != nil { @@ -207,7 +307,7 @@ func main() { } } - s := &stats{min: time.Hour, braille: *useBraille} + s := &stats{min: time.Hour, braille: *o.useBraille} // Disable terminal input processing to prevent keypresses from corrupting // the display (echo, VDISCARD, VREPRINT, etc.). @@ -236,7 +336,7 @@ func main() { go func() { <-sigCh closePeriods(s) - if !*silent { + if !*o.silent { printFinal(displayURL, s) } cleanup() @@ -245,13 +345,13 @@ func main() { // Validate protocol flags (mutually exclusive) protoCount := 0 - if *useHTTP1 { + if *o.useHTTP1 { protoCount++ } - if *useHTTP2 { + if *o.useHTTP2 { protoCount++ } - if *useHTTP3 { + if *o.useHTTP3 { protoCount++ } if protoCount > 1 { @@ -261,20 +361,20 @@ func main() { // Determine initial protocol level currentProto := protoHTTPS - if *useHTTP1 { + if *o.useHTTP1 { currentProto = protoHTTP1 - } else if *useHTTP2 { + } else if *o.useHTTP2 { currentProto = protoHTTP2 - } else if *useHTTP3 { + } else if *o.useHTTP3 { currentProto = protoHTTP3 } // Determine minimum protocol level for downgrade minProto := protoHTTPS // secure only by default - if *downgradeInsecure { + if *o.downgradeInsecure { minProto = protoHTTP1 } - canDowngrade := *downgrade || *downgradeInsecure + canDowngrade := *o.downgrade || *o.downgradeInsecure // Print header printHeader := func() { @@ -286,13 +386,17 @@ func main() { fmt.Printf("%sHittyPing (v%s) %s%s %s(%s)%s\n", gray, version, reset+bold, displayURL, reset+gray, protoNames[currentProto], reset) } } - if !*noHeader && !*quiet && !*silent { + if !*o.noHeader && !*o.quiet && !*o.silent { printHeader() } - if *showLegend && !*quiet && !*silent { - if *useBraille { - fmt.Printf("%sLegend: %s⡀⡄%s<%dms %s⡆%s<%dms %s⡇%s>=%dms %s%s⣿%sfail %s(2x density)%s\n", - gray, green, reset, greenThreshold, yellow, reset, yellowThreshold, red, reset, yellowThreshold, purple, bold, reset, gray, reset) + if *o.showLegend && !*o.quiet && !*o.silent { + if *o.useBraille { + failColor, failGlyph := purple, "⣿" + if brailleFail == failBang { + failColor, failGlyph = red, "!" + } + fmt.Printf("%sLegend: %s⡀⡄%s<%dms %s⡆%s<%dms %s⡇%s>=%dms %s%s%s%sfail %s(2x density)%s\n", + gray, green, reset, greenThreshold, yellow, reset, yellowThreshold, red, reset, yellowThreshold, failColor, bold, failGlyph, reset, gray, reset) } else { fmt.Printf("%sLegend: %s▁▂▃%s<%dms %s▄▅%s<%dms %s▆▇█%s>=%dms %s%s!%sfail%s\n", gray, green, reset, greenThreshold, yellow, reset, yellowThreshold, red, reset, yellowThreshold, red, bold, reset, reset) @@ -303,119 +407,62 @@ func main() { // Create HTTP client url := getURLForProto(host, currentProto) - client := createClient(currentProto, *timeout, *insecure) + client := createClient(currentProto, *o.timeout, *o.insecure) + + gap := func() time.Duration { + d := *o.interval + if *o.jitter > 0 { + d += time.Duration(rand.Int63n(int64(*o.jitter))) + } + return d + } + // Captured when the request starts: a downgrade must not switch the + // protocol under requests already in flight. + prepare := func() func() result { + c, u, p, sentAt := client, url, currentProto, time.Now() + return func() result { + rtt, err := measureRTT(c, u, p) + return result{sentAt: sentAt, proto: p, rtt: rtt, err: err} + } + } consecutiveFailures := 0 - requestNum := 0 - for { - rtt, err := measureRTT(client, url, currentProto) - if err != nil { - s.failures++ + handle := func(r result) { + recordResult(s, r) + printDisplay(s) + switch { + case r.err == nil: + consecutiveFailures = 0 + case r.proto == currentProto: consecutiveFailures++ - recordPeriod(s, false) - if s.braille { - if s.hasPending { - // Pair with pending: pending=left, failure=right - s.blocks = append(s.blocks, getBrailleChar(s.pendingRTT, -1)) - s.hasPending = false - } else { - // Store failure as pending - s.pendingRTT = -1 - s.hasPending = true - } - } else { - s.blocks = append(s.blocks, red+bold+"!"+reset) - } - - // Check for downgrade (only at startup, before first successful ping) - if canDowngrade && consecutiveFailures >= 3 && currentProto > minProto && s.count == 0 { - // Find a working lower protocol by testing each one - candidateProto := currentProto - foundWorking := false - for candidateProto > minProto { - // Try next lower protocol - switch candidateProto { - case protoHTTP3: - candidateProto = protoHTTP2 - case protoHTTP2: - candidateProto = protoHTTPS - case protoHTTPS: - candidateProto = protoHTTP1 - } - - // Test this protocol silently - testURL := getURLForProto(host, candidateProto) - testClient := createClient(candidateProto, *timeout, *insecure) - _, testErr := measureRTT(testClient, testURL, candidateProto) - if testErr == nil { - // Found working protocol - currentProto = candidateProto - url = testURL - client = testClient - foundWorking = true - break - } - // Otherwise continue to even lower protocol - } - - if foundWorking { - consecutiveFailures = 0 - - // Print downgrade message and update header - printDisplay(s) - if !*noHeader && !*quiet && !*silent { - fmt.Printf("\n%s↓ Downgrading to %s (3 initial failures)%s\n", yellow, protoNames[currentProto], reset) - printHeader() - fmt.Println() // Reserve stats line - fmt.Print(up) // Move back to bar line - } + } - // Skip to next iteration - don't double-print or wait - continue - } - } - } else { - s.count++ - consecutiveFailures = 0 // Reset on success - recordPeriod(s, true) - s.total += rtt - s.last = rtt - if rtt < s.min { - s.min = rtt - } - if rtt > s.max { - s.max = rtt - } - if s.braille { - if s.hasPending { - // Pair with pending: pending=left, current=right - s.blocks = append(s.blocks, getBrailleChar(s.pendingRTT, rtt)) - s.hasPending = false - } else { - // Store as pending - s.pendingRTT = rtt - s.hasPending = true - } - } else { - s.blocks = append(s.blocks, getBlock(rtt)) - } + // Downgrade only at startup, before the first success + if !canDowngrade || consecutiveFailures < 3 || currentProto <= minProto || s.count > 0 { + return } - printDisplay(s) - requestNum++ - if *count > 0 && requestNum >= *count { - closePeriods(s) - if !*silent { - printFinal(displayURL, s) - } - cleanup() - os.Exit(0) + p, ok := lowerWorkingProto(host, currentProto, minProto, *o.timeout, *o.insecure) + if !ok { + return } - sleepDuration := *interval - if *jitter > 0 { - sleepDuration += time.Duration(rand.Int63n(int64(*jitter))) + currentProto = p + url = getURLForProto(host, p) + client = createClient(p, *o.timeout, *o.insecure) + consecutiveFailures = 0 + if !*o.noHeader && !*o.quiet && !*o.silent { + fmt.Printf("\n%s↓ Downgrading to %s (3 initial failures)%s\n", yellow, protoNames[currentProto], reset) + printHeader() + fmt.Println() // Reserve stats line + fmt.Print(up) // Move back to bar line } - time.Sleep(sleepDuration) } + + runFixedRate(*o.count, gap, prepare, handle) + closePeriods(s) + if !*o.silent { + printFinal(displayURL, s) + } + cleanup() } func measureRTT(client *http.Client, url string, protoLevel int) (time.Duration, error) { @@ -441,6 +488,15 @@ func measureRTT(client *http.Client, url string, protoLevel int) (time.Duration, return elapsed, nil } +// hostname strips the port and IPv6 brackets from a target, leaving the +// name to resolve: "example.com:8443" → "example.com", "[::1]:80" → "::1". +func hostname(target string) string { + if h, _, err := net.SplitHostPort(target); err == nil { + return h + } + return strings.TrimPrefix(strings.TrimSuffix(target, "]"), "[") +} + // proxyConfigured reports whether any HTTP/HTTPS proxy env var is set. // Mirrors the variables consulted by http.ProxyFromEnvironment. func proxyConfigured() bool { @@ -529,10 +585,15 @@ func getBrailleChar(leftRTT, rightRTT time.Duration) string { leftHeight := getBrailleHeight(leftRTT) rightHeight := getBrailleHeight(rightRTT) - // Any failure in the pair renders as a full purple cell (⣿). - // A failure dominates the slot — the paired success is dropped visually. if leftHeight < 0 || rightHeight < 0 { - return purple + bold + "⣿" + reset + if brailleFail == failDots { + return purple + bold + "⣿" + reset + } + if leftHeight < 0 && rightHeight < 0 { + return red + bold + "!" + reset + } + leftHeight = max(leftHeight, 0) + rightHeight = max(rightHeight, 0) } // Build braille character diff --git a/main_test.go b/main_test.go index fb42146..a88f2be 100644 --- a/main_test.go +++ b/main_test.go @@ -117,9 +117,9 @@ func TestGetURLForProto_ReturnsHTTPSForProtoHTTP3(t *testing.T) { } func TestGetURLForProto_HandlesIPv4Address(t *testing.T) { - result := getURLForProto("192.168.1.1", protoHTTPS) + result := getURLForProto("192.0.2.1", protoHTTPS) - expected := "https://192.168.1.1" + expected := "https://192.0.2.1" if result != expected { t.Errorf("getURLForProto() = %q; want %q", result, expected) } @@ -503,7 +503,7 @@ func TestGetURLForProto_TableDriven(t *testing.T) { {"http3-simple", "example.com", protoHTTP3, "https://example.com"}, {"http1-with-port", "example.com:8080", protoHTTP1, "http://example.com:8080"}, {"https-with-port", "example.com:443", protoHTTPS, "https://example.com:443"}, - {"http1-ipv4", "192.168.1.1", protoHTTP1, "http://192.168.1.1"}, + {"http1-ipv4", "192.0.2.1", protoHTTP1, "http://192.0.2.1"}, {"https-ipv4", "8.8.8.8", protoHTTPS, "https://8.8.8.8"}, {"https-ipv6", "[::1]", protoHTTPS, "https://[::1]"}, {"https-ipv6-full", "[2001:4860:4860::8888]", protoHTTPS, "https://[2001:4860:4860::8888]"}, @@ -624,7 +624,7 @@ func TestFmtDuration_TableDriven(t *testing.T) { func TestRecordPeriod(t *testing.T) { t.Run("first-success-creates-up", func(t *testing.T) { s := &stats{} - recordPeriod(s, true) + recordPeriod(s, true, time.Time{}) if s.currentPeriod == nil { t.Fatal("currentPeriod is nil") } @@ -641,7 +641,7 @@ func TestRecordPeriod(t *testing.T) { t.Run("first-failure-creates-down", func(t *testing.T) { s := &stats{} - recordPeriod(s, false) + recordPeriod(s, false, time.Time{}) if s.currentPeriod == nil { t.Fatal("currentPeriod is nil") } @@ -655,9 +655,9 @@ func TestRecordPeriod(t *testing.T) { t.Run("consecutive-same-increments", func(t *testing.T) { s := &stats{} - recordPeriod(s, true) - recordPeriod(s, true) - recordPeriod(s, true) + recordPeriod(s, true, time.Time{}) + recordPeriod(s, true, time.Time{}) + recordPeriod(s, true, time.Time{}) if s.currentPeriod.count != 3 { t.Errorf("count = %d; want 3", s.currentPeriod.count) } @@ -668,9 +668,9 @@ func TestRecordPeriod(t *testing.T) { t.Run("transition-closes-period", func(t *testing.T) { s := &stats{} - recordPeriod(s, true) - recordPeriod(s, true) - recordPeriod(s, false) // transition + recordPeriod(s, true, time.Time{}) + recordPeriod(s, true, time.Time{}) + recordPeriod(s, false, time.Time{}) // transition if len(s.periods) != 1 { t.Fatalf("periods = %d; want 1", len(s.periods)) } @@ -690,12 +690,12 @@ func TestRecordPeriod(t *testing.T) { t.Run("multiple-transitions", func(t *testing.T) { s := &stats{} - recordPeriod(s, true) // UP - recordPeriod(s, true) // UP (2) - recordPeriod(s, false) // DOWN - recordPeriod(s, false) // DOWN (2) - recordPeriod(s, false) // DOWN (3) - recordPeriod(s, true) // UP again + recordPeriod(s, true, time.Time{}) // UP + recordPeriod(s, true, time.Time{}) // UP (2) + recordPeriod(s, false, time.Time{}) // DOWN + recordPeriod(s, false, time.Time{}) // DOWN (2) + recordPeriod(s, false, time.Time{}) // DOWN (3) + recordPeriod(s, true, time.Time{}) // UP again if len(s.periods) != 2 { t.Fatalf("periods = %d; want 2", len(s.periods)) } @@ -712,8 +712,8 @@ func TestRecordPeriod(t *testing.T) { t.Run("close-periods", func(t *testing.T) { s := &stats{} - recordPeriod(s, true) - recordPeriod(s, false) + recordPeriod(s, true, time.Time{}) + recordPeriod(s, false, time.Time{}) closePeriods(s) if len(s.periods) != 2 { t.Fatalf("periods = %d; want 2", len(s.periods)) @@ -770,3 +770,73 @@ func TestGetEnvInt_TableDriven(t *testing.T) { }) } } + +// ============================================================================= +// Braille failure styles (--fail-style) +// ============================================================================= + +func withFailStyle(fs failStyle, fn func()) { + orig := brailleFail + brailleFail = fs + defer func() { brailleFail = orig }() + fn() +} + +func TestGetBrailleChar_FailStyles(t *testing.T) { + const fail = time.Duration(-1) + ok := 50 * time.Millisecond + slow := 500 * time.Millisecond + tests := []struct { + name string + style failStyle + left, right time.Duration + want string + }{ + {"dots-both-fail", failDots, fail, fail, purple + bold + "⣿" + reset}, + {"dots-left-fail", failDots, fail, ok, purple + bold + "⣿" + reset}, + {"dots-right-fail", failDots, slow, fail, purple + bold + "⣿" + reset}, + {"bang-both-fail", failBang, fail, fail, red + bold + "!" + reset}, + {"bang-left-fail-shows-right-only", failBang, fail, ok, green + "⢀" + reset}, + {"bang-right-fail-shows-left-only", failBang, slow, fail, red + "⡇" + reset}, + {"bang-no-fail-unchanged", failBang, ok, ok, green + "⣀" + reset}, + {"dots-no-fail-unchanged", failDots, ok, ok, green + "⣀" + reset}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + withThresholds(0, 150, 400, func() { + withFailStyle(tc.style, func() { + if got := getBrailleChar(tc.left, tc.right); got != tc.want { + t.Errorf("getBrailleChar(%v, %v) = %q; want %q", tc.left, tc.right, got, tc.want) + } + }) + }) + }) + } +} + +func TestParseFailStyle(t *testing.T) { + for in, want := range map[string]failStyle{"dots": failDots, "bang": failBang, "BANG": failBang} { + got, err := parseFailStyle(in) + if err != nil || got != want { + t.Errorf("parseFailStyle(%q) = %v, %v; want %v, nil", in, got, err, want) + } + } + if _, err := parseFailStyle("purple"); err == nil { + t.Error("parseFailStyle(\"purple\") returned no error") + } +} + +func TestHostname(t *testing.T) { + for in, want := range map[string]string{ + "example.com": "example.com", + "example.com:8443": "example.com", + "127.0.0.1:18555": "127.0.0.1", + "1.1.1.1": "1.1.1.1", + "[::1]": "::1", + "[::1]:8080": "::1", + } { + if got := hostname(in); got != want { + t.Errorf("hostname(%q) = %q; want %q", in, got, want) + } + } +} diff --git a/schedule.go b/schedule.go new file mode 100644 index 0000000..ef51075 --- /dev/null +++ b/schedule.go @@ -0,0 +1,80 @@ +package main + +import "time" + +// result is one finished request. +type result struct { + sentAt time.Time + proto int + rtt time.Duration + err error +} + +// inOrder releases results in send order: a result waits until every +// earlier request has finished. +type inOrder struct { + next int + held map[int]result +} + +func (q *inOrder) add(seq int, r result) []result { + if q.held == nil { + q.held = map[int]result{} + } + q.held[seq] = r + var out []result + for { + r, ok := q.held[q.next] + if !ok { + return out + } + delete(q.held, q.next) + out = append(out, r) + q.next++ + } +} + +// nextSend returns the start time of the request after the one scheduled +// at prev. After a stall (a downgrade probe, Ctrl-Z) it returns now, so +// sending resumes with one request instead of a burst of missed ones. +func nextSend(prev, now time.Time, gap time.Duration) time.Time { + next := prev.Add(gap) + if next.Before(now) { + return now + } + return next +} + +// runFixedRate starts a request every gap(), whatever earlier requests are +// doing, so a slow or timed-out request never stretches the bar's time +// scale. prepare runs on this goroutine when a request starts and returns +// the blocking measurement; handle gets the results in send order. It +// returns once count results are handled; count 0 runs forever. +func runFixedRate(count int, gap func() time.Duration, prepare func() func() result, handle func(result)) { + type done struct { + seq int + r result + } + results := make(chan done) + var order inOrder + timer := time.NewTimer(0) + next := time.Now() + sent, handled := 0, 0 + for count == 0 || handled < count { + select { + case <-timer.C: + run, seq := prepare(), sent + sent++ + go func() { results <- done{seq, run()} }() + if count == 0 || sent < count { + next = nextSend(next, time.Now(), gap()) + timer.Reset(time.Until(next)) + } + case d := <-results: + for _, r := range order.add(d.seq, d.r) { + handle(r) + handled++ + } + } + } +} diff --git a/schedule_test.go b/schedule_test.go new file mode 100644 index 0000000..83649c5 --- /dev/null +++ b/schedule_test.go @@ -0,0 +1,114 @@ +package main + +import ( + "errors" + "testing" + "time" +) + +func TestInOrder_ReleasesInSendOrder(t *testing.T) { + var q inOrder + at := func(i int) result { return result{rtt: time.Duration(i)} } + + if got := q.add(1, at(1)); len(got) != 0 { + t.Fatalf("seq 1 before seq 0 released %d results; want 0", len(got)) + } + if got := q.add(2, at(2)); len(got) != 0 { + t.Fatalf("seq 2 before seq 0 released %d results; want 0", len(got)) + } + got := q.add(0, at(0)) + if len(got) != 3 || got[0].rtt != 0 || got[1].rtt != 1 || got[2].rtt != 2 { + t.Fatalf("seq 0 released %v; want seqs 0,1,2 in order", got) + } + if got := q.add(3, at(3)); len(got) != 1 || got[0].rtt != 3 { + t.Fatalf("seq 3 released %v; want seq 3 alone", got) + } +} + +func TestNextSend(t *testing.T) { + t0 := time.Date(2026, 11, 15, 12, 0, 0, 0, time.UTC) + gap := time.Second + if got := nextSend(t0, t0.Add(10*time.Millisecond), gap); !got.Equal(t0.Add(gap)) { + t.Errorf("on time: next = %v; want %v (stays on the grid)", got, t0.Add(gap)) + } + late := t0.Add(5 * time.Second) + if got := nextSend(t0, late, gap); !got.Equal(late) { + t.Errorf("after a stall: next = %v; want now %v (no burst)", got, late) + } +} + +// A failure that takes 5 intervals must not stretch the time between sends: +// one result per interval, like ping, during an outage as well. +func TestRunFixedRate_OutageKeepsTheTimeScale(t *testing.T) { + const ( + n = 10 + interval = 20 * time.Millisecond + timeout = 100 * time.Millisecond + ) + var got []result + start := time.Now() + runFixedRate(n, + func() time.Duration { return interval }, + func() func() result { + sentAt := time.Now() + return func() result { + time.Sleep(timeout) + return result{sentAt: sentAt, err: errors.New("timeout")} + } + }, + func(r result) { got = append(got, r) }, + ) + elapsed := time.Since(start) + + if len(got) != n { + t.Fatalf("handled %d results; want %d", len(got), n) + } + // Sequential sending would take n*(timeout+interval) = 1.2s. + if limit := (n-1)*interval + timeout + 300*time.Millisecond; elapsed > limit { + t.Errorf("10 failing requests took %v; want under %v (fixed rate)", elapsed, limit) + } + span := got[n-1].sentAt.Sub(got[0].sentAt) + if want := (n - 1) * interval; span < want-5*time.Millisecond || span > want+100*time.Millisecond { + t.Errorf("first to last send = %v; want about %v (one interval per request)", span, want) + } + for i := 1; i < n; i++ { + if got[i].sentAt.Before(got[i-1].sentAt) { + t.Fatalf("result %d sent before result %d: not in send order", i, i-1) + } + } +} + +// A slow request holds back faster later ones, so the bar stays in send order. +func TestRunFixedRate_SlowRequestKeepsItsSlot(t *testing.T) { + seq := 0 + var order []int + runFixedRate(3, + func() time.Duration { return 5 * time.Millisecond }, + func() func() result { + i := seq + seq++ + return func() result { + if i == 0 { + time.Sleep(60 * time.Millisecond) + } + return result{rtt: time.Duration(i)} + } + }, + func(r result) { order = append(order, int(r.rtt)) }, + ) + if len(order) != 3 || order[0] != 0 || order[1] != 1 || order[2] != 2 { + t.Errorf("handled order %v; want [0 1 2]", order) + } +} + +func TestRecordResult_PeriodStartsAtSendTime(t *testing.T) { + sent := time.Date(2026, 11, 15, 12, 0, 0, 0, time.UTC) + s := &stats{min: time.Hour} + recordResult(s, result{sentAt: sent, err: errors.New("timeout")}) + if s.currentPeriod == nil || !s.currentPeriod.start.Equal(sent) { + t.Fatalf("DOWN period start = %v; want the send time %v", s.currentPeriod, sent) + } + if s.failures != 1 || len(s.blocks) != 1 { + t.Errorf("failures=%d blocks=%d; want 1 and 1", s.failures, len(s.blocks)) + } +} diff --git a/skill_test.go b/skill_test.go new file mode 100644 index 0000000..a2952e6 --- /dev/null +++ b/skill_test.go @@ -0,0 +1,27 @@ +package main + +import ( + "strings" + "testing" + + flag "github.com/spf13/pflag" +) + +func TestSkillDocumentsEveryFlag(t *testing.T) { + fs := flag.NewFlagSet("hp", flag.ContinueOnError) + defineFlags(fs) + fs.VisitAll(func(f *flag.Flag) { + if !strings.Contains(skillText, "`--"+f.Name+"`") { + t.Errorf("skills/hp/SKILL.md does not document --%s", f.Name) + } + if f.Shorthand != "" && !strings.Contains(skillText, "`-"+f.Shorthand+"`, `--"+f.Name+"`") { + t.Errorf("skills/hp/SKILL.md does not pair -%s with --%s", f.Shorthand, f.Name) + } + }) +} + +func TestSkillFrontmatterNamesHp(t *testing.T) { + if !strings.HasPrefix(skillText, "---\nname: hp\ndescription: ") { + t.Errorf("skills/hp/SKILL.md must open with frontmatter naming hp; got %q", skillText[:min(40, len(skillText))]) + } +} diff --git a/skills/hp/SKILL.md b/skills/hp/SKILL.md new file mode 100644 index 0000000..30f49f3 --- /dev/null +++ b/skills/hp/SKILL.md @@ -0,0 +1,101 @@ +--- +name: hp +description: Use when checking or watching a host's HTTP(S) latency or reachability with hp (hittyping, prettyping for HTTP): run a bounded probe, pick protocol, thresholds or display flags, or read its output (the glyph bar, the stats line, the exit summary and its UP/DOWN timeline). `hp --skill` prints this guide from the binary. +--- + +# hp: HTTP(S) latency monitor + +hp sends one `HEAD` request at a time to a host and draws each round-trip as a colored glyph, like prettyping does for +ping. It measures the full request (DNS, TCP, TLS, response headers) on a fresh connection every time (keep-alive is +off), so numbers are higher than ICMP ping and include the TLS handshake. Any HTTP response is a success, a `503` or +an unfollowed `301` included: hp measures reachability and latency, not health. + +## Run it bounded + +hp runs until Ctrl+C unless `-c` is given. An agent always passes `-c`: + +```bash +hp -c 10 -q cloudflare.com # 10 requests, then the exit summary +hp -c 30 -i 500ms -t 2s -q 8.8.8.8 # faster probe, shorter timeout +``` + +- The argument is a host, an IP or `host:port`; IPv6 is bracketed for you. No argument means `1.1.1.1`. A leading + `https://` or `http://` is stripped and the scheme comes from the flags, so `hp http://x` still uses HTTPS: pass `-1` + for plain HTTP. A path (`example.com/health`) is not supported: hp reads it as part of the host name and exits 1. +- Exit code: `0` when the run ends (also at 100% loss), `1` for a bad flag or a host that does not resolve. +- Output always carries ANSI colors and cursor movement, even through a pipe. Read the **exit summary** (the + plain-text block after `--- hp statistics ---`); the live bar is redrawn in place and is noise in a capture. + `-Q` hides that summary too, so never use `-Q` when you need the result. + +## Read the result + +```text +--- cloudflare.com hp statistics --- +10 requests, 9 ok, 1 failed, 10% loss +round-trip min/avg/max = 21/34/88 ms +timeline: + 10:02:18 UP 6s (6 ok) + 10:02:24 DOWN 1s (1 lost) + 10:02:25 UP ← active +``` + +- `round-trip` is printed only when at least one request succeeded. +- `timeline` is printed only when a request failed. Each row is a period of consecutive successes (UP) or failures + (DOWN) with its start time, length and request count; the last row is the period still running. Over 20 periods it + keeps the first 5 and last 5. The date is added when the run spans midnight. +- A failure is any error: timeout, refused connection, TLS error, or `-2` without HTTP/2 negotiated. + +The live stats line reads `failed/total (loss%) lost; min/avg/max ms; last: N ms`. + +## The bar + +| Glyph | Block mode (default) | Braille mode (`-b`, two requests per cell) | +|---|---|---| +| green | `▁▂▃` below `--green` (150 ms) | `⡀⡄` | +| yellow | `▄▅` below `--yellow` (400 ms) | `⡆` | +| red | `▆▇█` at or above `--yellow` | `⡇` | +| failure | red `!` | purple `⣿` (`--fail-style dots`, default) or red `!` (`--fail-style bang`) | + +- Braille cells pair two requests (left dot column = older). The cell's color is the slower one's. +- `--fail-style dots` (0.8.7+): any cell holding a failure becomes a purple `⣿`. + `--fail-style bang` (behavior up to 0.8.6): red `!` only when both requests failed; one failure leaves its column + blank and the cell shows the other request. Block mode ignores `--fail-style`. +- One glyph is one `--interval` of wall time, up or down (a braille cell is two). A request starts every interval + whatever earlier ones are doing, as ping does, so loss % is the share of time the host did not answer. Glyphs are + drawn in send order: during an outage the bar runs up to `--timeout` behind, while up to timeout ÷ interval + requests (5 with the defaults) wait in flight. +- With `-b` and an odd `-c`, the last request is counted in the stats but never drawn. + +## Flags + +| Flag | Default | Meaning | +|---|---|---| +| `-c`, `--count` | 0 | requests to send, 0 = until Ctrl+C | +| `-i`, `--interval` | 1s | time from one request's start to the next | +| `-j`, `--jitter` | 0 | add a random 0..N to each interval | +| `-t`, `--timeout` | 5s | per-request timeout | +| `-1`, `--http` | | plain HTTP/1.1 (`http://`) | +| `-2`, `--http2` | | require HTTP/2; a response on another protocol counts as a failure | +| `-3`, `--http3` | | HTTP/3 over QUIC (UDP 443) | +| `-d`, `--downgrade` | | after 3 failures before the first success, step down 3 → 2 → HTTPS until one answers | +| `-D`, `--downgrade-insecure` | | as `-d`, and may fall to plain HTTP | +| `-k`, `--insecure` | | skip TLS certificate checks | +| `-m`, `--min` | 0 | ms mapped to the lowest block (env `HP_MIN`) | +| `-g`, `--green` | 150 | green below this many ms (env `HP_GREEN`) | +| `-y`, `--yellow` | 400 | yellow below this, red at or above (env `HP_YELLOW`) | +| `-b`, `--braille` | | braille bar, two requests per cell | +| `--fail-style` | dots | braille failure glyph, `dots` or `bang` (env `HP_FAIL_STYLE`) | +| `--legend` | | print the legend line | +| `--noheader` | | hide the header line | +| `-q`, `--quiet` | | hide header and legend | +| `-Q`, `--silent` | | also hide the exit summary | +| `-v`, `--version` | | print the version | +| `--skill` | | print this guide | + +`-1`, `-2` and `-3` exclude each other. A flag beats its env var; a threshold flag of 0 is ignored. + +## Proxies + +`HTTPS_PROXY`, `HTTP_PROXY` and `ALL_PROXY` are honored, SOCKS5 included +(`HTTPS_PROXY=socks5://host:1080 hp -c 5 example.com`). With a proxy set, hp skips its local DNS check and the header +shows no resolved IP. HTTP/3 does not go through the proxy.