ptnop

package module
v0.0.0-...-c215995 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 13, 2026 License: GPL-3.0 Imports: 20 Imported by: 0

README

Pass-through Network Observation Pipelines

GoDoc Build Status codecov

The ptnop Go package provides composable primitives for building network measurement pipelines with structured logging. Each primitive is a Func[A, B] that can be chained via type-safe composition (Compose2 through Compose8).

Basic usage (DNS-over-UDP lookup):

import (
	"context"
	"log/slog"
	"net/netip"
	"os"
	"time"

	"github.com/bassosimone/dnscodec"
	"github.com/bassosimone/ptnop"
	"github.com/miekg/dns"
)

// Use LevelDebug to include per-I/O events (read, write, deadline);
// Use LevelInfo to see only lifecycle and protocol events.
logger := slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{
	Level: slog.LevelDebug,
}))

// Create configuration with default settings.
cfg := ptnop.NewConfig()
cfg.SLogger = logger

pipeline := ptnop.Compose4(
	// Dial a UDP socket to the target endpoint.
	ptnop.NewConnectFunc(cfg, "udp"),

	// Wrap the connection to log each read, write, and deadline change.
	ptnop.NewObserveConnFunc(cfg),

	// Close the connection when the context is cancelled (e.g., ^C).
	ptnop.NewCancelWatchFunc(),

	// Wrap the UDP connection as a DNS-over-UDP connection.
	ptnop.NewDNSOverUDPConnFunc(cfg),
)

// The context controls the overall timeout for the pipeline.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

// Pass the target endpoint directly as input to the pipeline.
conn := pipeline.Call(ctx, netip.MustParseAddrPort("8.8.8.8:53"))
defer conn.Close()

// Use the connection to perform a DNS exchange.
query := dnscodec.NewQuery("dns.google", dns.TypeA)
resp, err := conn.Exchange(ctx, query)

See the package documentation and testable examples for DNS-over-TCP, DNS-over-TLS, DNS-over-HTTPS, and HTTPS round trip pipelines.

Installation

To add this package as a dependency to your module:

go get github.com/bassosimone/ptnop

Development

To run the tests:

go test -v .

To measure test coverage:

go test -v -cover .

License

SPDX-License-Identifier: GPL-3.0-or-later

History

Adapted from nop. The main difference is that nop stops logging events mid-pipeline on the first error. By contrast, ptnop does not interrupt the pipeline and introduces a specific sentinel error ErrSkip to note that a previous pipeline stage has failed. The resulting ptnop events are more suitable for automatic processing, since they also include the configuration of the skipped stages.

The pt in ptnop means "pass-through" and refers to the ErrSkip mechanism so that we pass through each stage regardless of whether the previous stages failed or not.

In turn, nop was adapted from ooni/probe-cli and rbmk-project/rbmk.

Documentation

Overview

Package ptnop allows composing observable network measurement pipelines.

This package is built around:

  1. the *Config struct containing the pipeline configuration.

  2. the Func interface and the Compose2 ... Compose8 function composition primitives.

  3. constructors for network operations such as NewConnectFunc.

From these primitives, one can build a pipeline of operations. Pipelines always yield a persistent network connection to a remote endpoint speaking a given protocol.

For example, by composing these primitives:

One obtains a persistent HTTPS connection to a remote host, which has a RoundTrip method to perform round trips and a Close method to close the conn.

The *Config contains an SLogger field that configures a log/slog like logger. While the default implementation does not log, if you override it with a real *log/slog.Logger, you get structured events covering:

  1. TCP/UDP connection establishment
  2. I/O events (read, write, set deadline, close)
  3. TLS handshake events
  4. HTTP round trip events
  5. DNS exchange events

With a logger configured to log at the log/slog.LevelDebug level one gets all events. Restricting to log/slog.LevelInfo only yields the events tailored for batch consumption of the event stream:

  • closeDone
  • connectDone
  • dnsExchangeDone
  • dnsResponse
  • httpBodyStreamDone
  • httpRoundTripDone
  • tlsHandshakeDone

Each pipeline stage that may fail returns a Result type containing either the on-success value or an error with either-or semantics. Subsequent stages keep running on failure and must check the Result value state.

With the exception of I/O events, all other events are produced even when the previous pipeline stage failed. This design choice ensures that it is always possible to reconstruct ex-post what the pipeline wanted to do, regardless of whether there were early failures. For example, assuming this pipeline:

even if ConnectFunc fails you still see TLSHandshakeFunc and HTTPConnFunc generated events showing what would have been done had the previous stages succeeded.

This particular condition when a stage runs when the previous stage failed is marked with the ErrSkip error.

We classify all errors in the structured log using DefaultErrClassifier by default. This classifier is such that, when ErrSkip is the error, the corresponding `errClass` field value is "ESKIP".

All in all, this design allows a machine consumer to parse the event stream generated by a pipeline and transform it into a tabular data structure (e.g. parquet), where every row has every column filled and skipped stages are marked as "ESKIP". Thus, for example, it is obvious which failed rows belong to, say, TLS handshakes that would have been made to send specific HTTP requests, versus, say, TLS handshakes that were motivated by sending DNS-over-TLS requests.

As a caveat, some I/O events (e.g. closeStart/Done and readDone events) may be emitted after the code running the pipeline has returned when using net/http. This happens because net/http manages the conn in a background goroutine and closes it asynchronously. Thus, a tool that exits when its pipelines are done might miss these events.

To distinguish between the output of multiple pipelines, it is advised to use log/slog.Logger.With, so that each pipeline is bound to a unique identifier (for example a UUIDv4 or a UUIDv7).

Func axioms

  1. every Func that receives a Result containing an error must eventually return an ErrSkip wrapping the error

  2. regardless of ErrSkip or other errors, the Func must run to completion and emit events, obviously skipping any network operation that would have been run if possible

  3. if the Func receives a struct with a `Close` method and fails such that it would return a Result containing an error, then it invokes the `Close` method; otherwise, the ownership is passed to the next stage

Timing out

You should always include CancelWatchFunc in your pipeline to interrupt network operations when the context is canceled.

HTTP vs HTTPS

The HTTPConnFunc takes in input a net.Conn and checks whether such a conn implements TLSConn. If that is the case, then it uses the HTTPS protocol; otherwise, it uses HTTP. Hence, when you want to use HTTPS, the previous stage must be TLSHandshakeFunc.

Complex measurements

Even something as simple as measuring https://www.example.com/ entails complex operations: DNS lookup, and then a TCP + TLS + HTTP pipeline for each resolved endpoint. This package does not tell you how to compose these operations and it's up to you to decide whether, for example, you want to test all the resolved endpoints, just the first one, one IPv4 and one IPv6 endpoint, etc.

The only thing that this package provides you with is the ability to define a single pipeline, with a single possible failure, that runs end-to-end and always produces the same major events (connect, TLS, HTTP, DNS) regardless of intermediate errors, so that later on you can create tabular results.

All other concerns are policy concerns that are outside of the scope of this package and up to you, the user.

Mutability

Structs can be modified before use. Do not modify them once you have used them, to avoid potential data races.

Mutating interface fields of structs by type asserting is not how we expect you to use this library. In particular, this may cause mutation of globals, which will cause data races.

If you follow the above rules, this package is goroutine safe.

Lazy carriers

The *HTTPConn and the DNSConn types carry the Result inside them so that you notice the actual failure when attempting to perform the related operation. That is, the fact that *HTTPConnFunc always returns *HTTPConn doesn't mean that it always succeeds. It means that the error, if any, is observed when calling the *HTTPConn.RoundTrip method such that the related events may be emitted.

Close on a lazy carrier whose Result holds an error is a no-op: there is nothing to close.

HTTP body events

*HTTPConn.RoundTrip automatically returns an *net/http.Response where the Body field is an *HTTPBodyWrapper so that by reading the body you also generate the related structured logs as a side effect. If this annoys you, you can type assert for *HTTPBodyWrapper: its Body field is public and carries the original *net/http.Response body.

Skipped pipeline error

When a complex pipeline fails midway, the returned error is an instance of ErrSkip, possibly with multiple levels of ErrSkip wrapping. Because ErrSkip does not modify the string representation of the error and it implements the golang unwrap protocol for errors, you won't notice this unless you try to classify the returned error. In such a case, you will see the "ESKIP" value because the outer layer is an ErrSkip.

So, if your aim is to classify the overall pipeline outcome based on the error of the final operation you perform, you need to recursively unwrap ErrSkip first, just in case, so that you get the actual error classification.

Example (DnsOverHTTPS)

This example shows how to compose a DNS-over-HTTPS pipeline that resolves a domain name using Google's public DNS server.

package main

import (
	"context"
	"crypto/tls"
	"fmt"
	"log/slog"
	"net/netip"
	"os"
	"slices"
	"time"

	"github.com/bassosimone/dnscodec"
	"github.com/bassosimone/ptnop"
	"github.com/bassosimone/runtimex"
	"github.com/google/uuid"
	"github.com/miekg/dns"
)

func main() {
	// Create context with overall timeout for the entire operation.
	// Caller controls timeout externally and ptnop never modifies the context.
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	// Create a logger that emits JSON to stderr. Use LevelDebug to include
	// per-I/O events (read, write, deadline); use LevelInfo to see only
	// lifecycle and protocol events (connect, close, TLS, DNS, HTTP).
	logger := slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{
		Level: slog.LevelDebug,
	}))

	// Generate a span ID (UUIDv7) and attach it to the logger so that
	// all log entries from this operation can be correlated.
	spanID := uuid.Must(uuid.NewV7()).String()
	logger = logger.With("spanId", spanID)

	// Create the shared configuration for ptnop operations.
	cfg := ptnop.NewConfig()
	cfg.SLogger = logger

	// Create pipeline for establishing a DNS-over-HTTPS connection.
	// CancelWatchFunc binds context lifecycle to connection lifecycle:
	// when context is done (timeout, cancel, signal), connection closes.
	connectOp := ptnop.NewConnectFunc(cfg, "tcp")

	observeOp := ptnop.NewObserveConnFunc(cfg)

	autoCancelOp := ptnop.NewCancelWatchFunc()

	tlsConfig := &tls.Config{ServerName: "dns.google", NextProtos: []string{"h2", "http/1.1"}}
	tlsHandshakeOp := ptnop.NewTLSHandshakeFunc(cfg, tlsConfig)

	httpConnOp := ptnop.NewHTTPConnFunc(cfg)

	wrapOp := ptnop.NewDNSOverHTTPSConnFunc(cfg, "https://dns.google/dns-query")

	dialPipe := ptnop.Compose6(connectOp, observeOp, autoCancelOp, tlsHandshakeOp, httpConnOp, wrapOp)

	// Connect and wrap in DNSOverHTTPSConn (which owns the underlying conn)
	endpoint := netip.MustParseAddrPort("8.8.8.8:443")
	dnsConn := dialPipe.Call(ctx, endpoint)
	defer dnsConn.Close()

	// Perform the DNS exchange
	dnsQuery := dnscodec.NewQuery("dns.google", dns.TypeA)
	dnsResp := runtimex.PanicOnError1(dnsConn.Exchange(ctx, dnsQuery))

	// Print the results
	addrs := runtimex.PanicOnError1(dnsResp.RecordsA())
	slices.Sort(addrs)
	fmt.Printf("%+v\n", addrs)

}
Output:
[8.8.4.4 8.8.8.8]
Example (DnsOverTCP)

This example shows how to compose a DNS-over-TCP pipeline that resolves a domain name using Google's public DNS server.

package main

import (
	"context"
	"fmt"
	"log/slog"
	"net/netip"
	"os"
	"slices"
	"time"

	"github.com/bassosimone/dnscodec"
	"github.com/bassosimone/ptnop"
	"github.com/bassosimone/runtimex"
	"github.com/google/uuid"
	"github.com/miekg/dns"
)

func main() {
	// Create context with overall timeout for the entire operation.
	// Caller controls timeout externally and ptnop never modifies the context.
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	// Create a logger that emits JSON to stderr. Use LevelDebug to include
	// per-I/O events (read, write, deadline); use LevelInfo to see only
	// lifecycle and protocol events (connect, close, TLS, DNS, HTTP).
	logger := slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{
		Level: slog.LevelDebug,
	}))

	// Generate a span ID (UUIDv7) and attach it to the logger so that
	// all log entries from this operation can be correlated.
	spanID := uuid.Must(uuid.NewV7()).String()
	logger = logger.With("spanId", spanID)

	// Create the shared configuration for ptnop operations.
	cfg := ptnop.NewConfig()
	cfg.SLogger = logger

	// Create pipeline for establishing a DNS-over-TCP connection.
	// CancelWatchFunc binds context lifecycle to connection lifecycle:
	// when context is done (timeout, cancel, signal), connection closes.
	connectOp := ptnop.NewConnectFunc(cfg, "tcp")

	observeOp := ptnop.NewObserveConnFunc(cfg)

	autoCancelOp := ptnop.NewCancelWatchFunc()

	wrapOp := ptnop.NewDNSOverTCPConnFunc(cfg)

	dialPipe := ptnop.Compose4(connectOp, observeOp, autoCancelOp, wrapOp)

	// Connect and wrap in DNSOverTCPConn (which owns the underlying connection)
	endpoint := netip.MustParseAddrPort("8.8.8.8:53")
	dnsConn := dialPipe.Call(ctx, endpoint)
	defer dnsConn.Close()

	// Perform the DNS exchange
	dnsQuery := dnscodec.NewQuery("dns.google", dns.TypeA)
	dnsResp := runtimex.PanicOnError1(dnsConn.Exchange(ctx, dnsQuery))

	// Print the results
	addrs := runtimex.PanicOnError1(dnsResp.RecordsA())
	slices.Sort(addrs)
	fmt.Printf("%+v\n", addrs)

}
Output:
[8.8.4.4 8.8.8.8]
Example (DnsOverTLS)

This example shows how to compose a DNS-over-TLS pipeline that resolves a domain name using Google's public DNS server.

package main

import (
	"context"
	"crypto/tls"
	"fmt"
	"log/slog"
	"net/netip"
	"os"
	"slices"
	"time"

	"github.com/bassosimone/dnscodec"
	"github.com/bassosimone/ptnop"
	"github.com/bassosimone/runtimex"
	"github.com/google/uuid"
	"github.com/miekg/dns"
)

func main() {
	// Create context with overall timeout for the entire operation.
	// Caller controls timeout externally and ptnop never modifies the context.
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	// Create a logger that emits JSON to stderr. Use LevelDebug to include
	// per-I/O events (read, write, deadline); use LevelInfo to see only
	// lifecycle and protocol events (connect, close, TLS, DNS, HTTP).
	logger := slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{
		Level: slog.LevelDebug,
	}))

	// Generate a span ID (UUIDv7) and attach it to the logger so that
	// all log entries from this operation can be correlated.
	spanID := uuid.Must(uuid.NewV7()).String()
	logger = logger.With("spanId", spanID)

	// Create the shared configuration for ptnop operations.
	cfg := ptnop.NewConfig()
	cfg.SLogger = logger

	// Create pipeline for establishing a DNS-over-TLS connection.
	// CancelWatchFunc binds context lifecycle to connection lifecycle:
	// when context is done (timeout, cancel, signal), connection closes.
	connectOp := ptnop.NewConnectFunc(cfg, "tcp")

	observeOp := ptnop.NewObserveConnFunc(cfg)

	autoCancelOp := ptnop.NewCancelWatchFunc()

	tlsConfig := &tls.Config{ServerName: "dns.google", NextProtos: []string{"dot"}}
	tlsHandshakeOp := ptnop.NewTLSHandshakeFunc(cfg, tlsConfig)

	wrapOp := ptnop.NewDNSOverTLSConnFunc(cfg)

	dialPipe := ptnop.Compose5(connectOp, observeOp, autoCancelOp, tlsHandshakeOp, wrapOp)

	// Connect and wrap in DNSOverTLSConn (which owns the underlying connection)
	endpoint := netip.MustParseAddrPort("8.8.8.8:853")
	dnsConn := dialPipe.Call(ctx, endpoint)
	defer dnsConn.Close()

	// Perform the DNS exchange
	dnsQuery := dnscodec.NewQuery("dns.google", dns.TypeA)
	dnsResp := runtimex.PanicOnError1(dnsConn.Exchange(ctx, dnsQuery))

	// Print the results
	addrs := runtimex.PanicOnError1(dnsResp.RecordsA())
	slices.Sort(addrs)
	fmt.Printf("%+v\n", addrs)

}
Output:
[8.8.4.4 8.8.8.8]
Example (DnsOverUDP)

This example shows how to compose a DNS-over-UDP pipeline that resolves a domain name using Google's public DNS server.

package main

import (
	"context"
	"fmt"
	"log/slog"
	"net/netip"
	"os"
	"slices"
	"time"

	"github.com/bassosimone/dnscodec"
	"github.com/bassosimone/ptnop"
	"github.com/bassosimone/runtimex"
	"github.com/google/uuid"
	"github.com/miekg/dns"
)

func main() {
	// Create context with overall timeout for the entire operation.
	// Caller controls timeout externally and ptnop never modifies the context.
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	// Create a logger that emits JSON to stderr. Use LevelDebug to include
	// per-I/O events (read, write, deadline); use LevelInfo to see only
	// lifecycle and protocol events (connect, close, TLS, DNS, HTTP).
	logger := slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{
		Level: slog.LevelDebug,
	}))

	// Generate a span ID (UUIDv7) and attach it to the logger so that
	// all log entries from this operation can be correlated.
	spanID := uuid.Must(uuid.NewV7()).String()
	logger = logger.With("spanId", spanID)

	// Create the shared configuration for ptnop operations.
	cfg := ptnop.NewConfig()
	cfg.SLogger = logger

	// Create pipeline for establishing a DNS-over-UDP connection.
	// CancelWatchFunc binds context lifecycle to connection lifecycle:
	// when context is done (timeout, cancel, signal), connection closes.
	connectOp := ptnop.NewConnectFunc(cfg, "udp")

	observeOp := ptnop.NewObserveConnFunc(cfg)

	autoCancelOp := ptnop.NewCancelWatchFunc()

	wrapOp := ptnop.NewDNSOverUDPConnFunc(cfg)

	dialPipe := ptnop.Compose4(connectOp, observeOp, autoCancelOp, wrapOp)

	// Connect and wrap in DNSOverUDPConn (which owns the underlying connection)
	endpoint := netip.MustParseAddrPort("8.8.8.8:53")
	dnsConn := dialPipe.Call(ctx, endpoint)
	defer dnsConn.Close()

	// Perform the DNS exchange
	dnsQuery := dnscodec.NewQuery("dns.google", dns.TypeA)
	dnsResp := runtimex.PanicOnError1(dnsConn.Exchange(ctx, dnsQuery))

	// Print the results
	addrs := runtimex.PanicOnError1(dnsResp.RecordsA())
	slices.Sort(addrs)
	fmt.Printf("%+v\n", addrs)

}
Output:
[8.8.4.4 8.8.8.8]
Example (HttpsRoundTrip)

This example shows how to compose an HTTPS pipeline that performs an HTTP round trip and reads the response body.

//
// SPDX-License-Identifier: GPL-3.0-or-later
//
// Adapted from: https://github.com/bassosimone/nop/blob/89b21810488/example_httpconn_test.go
//

package main

import (
	"context"
	"crypto/tls"
	"fmt"
	"io"
	"log/slog"
	"net/http"
	"net/netip"
	"os"
	"strings"
	"time"

	"github.com/bassosimone/ptnop"
	"github.com/bassosimone/runtimex"
	"github.com/google/uuid"
)

// This example shows how to compose an HTTPS pipeline that performs
// an HTTP round trip and reads the response body.
func main() {
	// Create context with overall timeout for the entire operation.
	// Caller controls timeout externally and ptnop never modifies the context.
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	// Create a logger that emits JSON to stderr. Use LevelDebug to include
	// per-I/O events (read, write, deadline); use LevelInfo to see only
	// lifecycle and protocol events (connect, close, TLS, DNS, HTTP).
	logger := slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{
		Level: slog.LevelDebug,
	}))

	// Generate a span ID (UUIDv7) and attach it to the logger so that
	// all log entries from this operation can be correlated.
	spanID := uuid.Must(uuid.NewV7()).String()
	logger = logger.With("spanId", spanID)

	// Create the shared configuration for ptnop operations.
	cfg := ptnop.NewConfig()
	cfg.SLogger = logger

	// Create pipeline for establishing an HTTPS connection.
	// CancelWatchFunc binds context lifecycle to connection lifecycle:
	// when context is done (timeout, cancel, signal), connection closes.
	connectOp := ptnop.NewConnectFunc(cfg, "tcp")

	observeOp := ptnop.NewObserveConnFunc(cfg)

	autoCancelOp := ptnop.NewCancelWatchFunc()

	tlsConfig := &tls.Config{ServerName: "dns.google", NextProtos: []string{"h2", "http/1.1"}}
	tlsHandshakeOp := ptnop.NewTLSHandshakeFunc(cfg, tlsConfig)

	httpConnOp := ptnop.NewHTTPConnFunc(cfg)

	dialPipe := ptnop.Compose5(connectOp, observeOp, autoCancelOp, tlsHandshakeOp, httpConnOp)

	// Connect and wrap in HTTPConn
	endpoint := netip.MustParseAddrPort("8.8.8.8:443")
	httpConn := dialPipe.Call(ctx, endpoint)
	defer httpConn.Close()

	// Create the HTTP request and perform the round trip
	httpReq := runtimex.PanicOnError1(
		http.NewRequestWithContext(ctx, "GET", "https://dns.google/", http.NoBody))
	resp := runtimex.PanicOnError1(httpConn.RoundTrip(httpReq))
	defer resp.Body.Close()
	runtimex.Assert(resp.StatusCode < 400)

	// Read the body
	body := runtimex.PanicOnError1(io.ReadAll(resp.Body))

	// Extract and print the title from the HTML
	title := extractTitle(string(body))
	fmt.Printf("%s\n", title)

}

// extractTitle extracts the content of the <title> tag from HTML.
func extractTitle(html string) string {
	const startTag = "<title>"
	const endTag = "</title>"
	start := strings.Index(html, startTag)
	if start == -1 {
		return ""
	}
	start += len(startTag)
	end := strings.Index(html[start:], endTag)
	if end == -1 {
		return ""
	}
	return html[start : start+end]
}
Output:
Google Public DNS

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultDialer

func DefaultDialer() *net.Dialer

DefaultDialer returns the default *net.Dialer we use.

We disable multipath TCP explicitly. Since Go 1.24 the default (`multipathtcp=2`) enables it only for listeners, so this is a guard against a future change of the default rather than a fix: see https://go.dev/doc/godebug#go-124.

Types

type CancelWatchFunc

type CancelWatchFunc struct{}

CancelWatchFunc is the Func that closes a net.Conn when the context is canceled.

Use NewCancelWatchFunc to construct.

func NewCancelWatchFunc

func NewCancelWatchFunc() *CancelWatchFunc

NewCancelWatchFunc creates a new *CancelWatchFunc.

func (*CancelWatchFunc) Call

func (op *CancelWatchFunc) Call(ctx context.Context, conn Result[net.Conn]) Result[net.Conn]

Call wraps `conn` so that it is closed when the context is done. Closing the returned conn unregisters the watcher.

type Config

type Config struct {
	Dialer        Dialer
	ErrClassifier ErrClassifier
	SLogger       SLogger
	TimeNow       TimeNowProvider
}

Config holds common configuration for network operations.

Use NewConfig to create a new instance.

func NewConfig

func NewConfig() *Config

NewConfig creates a *Config using:

  1. DefaultDialer
  2. DefaultErrClassifier
  3. DefaultSLogger
  4. DefaultTimeNowProvider

Modify the fields as needed before usage.

type ConnectFunc

type ConnectFunc struct {
	Dialer        Dialer
	ErrClassifier ErrClassifier
	Network       string
	SLogger       SLogger
	TimeNow       TimeNowProvider
}

ConnectFunc is the Func that performs net.Conn dialing.

Use NewConnectFunc to create a new instance.

func NewConnectFunc

func NewConnectFunc(cfg *Config, network string) *ConnectFunc

NewConnectFunc creates a *ConnectFunc using the *Config and `network` to properly initialize all the *ConnectFunc fields.

func (*ConnectFunc) Call

func (op *ConnectFunc) Call(ctx context.Context, address netip.AddrPort) Result[net.Conn]

Call dials a net.Conn and, on success, transfers its ownership to the next stage.

type DNSConn

type DNSConn interface {
	Close() error
	Exchange(ctx context.Context, query *dnscodec.Query) (*dnscodec.Response, error)
}

DNSConn is the conn returned by stages such as *DNSOverUDPConnFunc.

type DNSOverHTTPSConn

type DNSOverHTTPSConn struct {
	ErrClassifier  ErrClassifier
	HTTPConn       HTTPEngineConn
	LocalAddr      string
	OverrideHeader http.Header
	Proto          string
	RemoteAddr     string
	SLogger        SLogger
	TimeNow        TimeNowProvider
	URL            string
}

DNSOverHTTPSConn wraps a HTTPS conn and allows executing DNS exchanges.

Typically constructed by *DNSOverHTTPSConnFunc.

func (*DNSOverHTTPSConn) Close

func (c *DNSOverHTTPSConn) Close() (err error)

Close closes the underlying *HTTPConn.

func (*DNSOverHTTPSConn) Exchange

func (c *DNSOverHTTPSConn) Exchange(
	ctx context.Context, query *dnscodec.Query) (*dnscodec.Response, error)

Exchange performs a DNS exchange over HTTPS.

type DNSOverHTTPSConnFunc

type DNSOverHTTPSConnFunc struct {
	ErrClassifier  ErrClassifier
	OverrideHeader http.Header
	SLogger        SLogger
	TimeNow        TimeNowProvider
	URL            string
}

DNSOverHTTPSConnFunc is the Func that creates *DNSOverHTTPSConn.

Use NewDNSOverHTTPSConnFunc to create a new instance.

Manually set OverrideHeader ahead of usage to override the request headers that would be sent. Values in OverrideHeader (1) replace the values we would normally send (e.g. `Content-Type: application/dns-message`) and (2) are copied in the request otherwise. A nil/empty list of values removes the header. To send no `User-Agent`, set it to `[]string{""}`.

func NewDNSOverHTTPSConnFunc

func NewDNSOverHTTPSConnFunc(cfg *Config, targetURL string) *DNSOverHTTPSConnFunc

NewDNSOverHTTPSConnFunc creates a *DNSOverHTTPSConnFunc using the *Config to properly initialize all the *DNSOverHTTPSConnFunc fields. The `targetURL` is also necessary to set the `Host` header and the URL path. However, note that *DNSOverHTTPSConnFunc takes as input an *HTTPConn, so the URL host will not be used for dialing. The scheme is not used for dialing either, but HTTP/2 sends it as the `:scheme` pseudo-header, so use `https`.

func (*DNSOverHTTPSConnFunc) Call

func (op *DNSOverHTTPSConnFunc) Call(ctx context.Context, httpConn *HTTPConn) DNSConn

Call transforms an *HTTPConn into a DNSConn thus allowing for DNS exchanges.

The returned value is a *DNSOverHTTPSConn.

type DNSOverTCPConn

type DNSOverTCPConn struct {
	Conn          Result[net.Conn]
	ErrClassifier ErrClassifier
	SLogger       SLogger
	TimeNow       TimeNowProvider
}

DNSOverTCPConn wraps a TCP conn and allows executing DNS exchanges.

Typically constructed by *DNSOverTCPConnFunc.

func (*DNSOverTCPConn) Close

func (c *DNSOverTCPConn) Close() error

Close closes the underlying TCP connection.

func (*DNSOverTCPConn) Exchange

func (c *DNSOverTCPConn) Exchange(
	ctx context.Context, query *dnscodec.Query) (*dnscodec.Response, error)

Exchange performs a DNS exchange over TCP.

type DNSOverTCPConnFunc

type DNSOverTCPConnFunc struct {
	ErrClassifier ErrClassifier
	SLogger       SLogger
	TimeNow       TimeNowProvider
}

DNSOverTCPConnFunc is the Func that creates *DNSOverTCPConn.

Use NewDNSOverTCPConnFunc to create a new instance.

func NewDNSOverTCPConnFunc

func NewDNSOverTCPConnFunc(cfg *Config) *DNSOverTCPConnFunc

NewDNSOverTCPConnFunc creates a *DNSOverTCPConnFunc using the *Config to properly initialize all the *DNSOverTCPConnFunc fields.

func (*DNSOverTCPConnFunc) Call

func (op *DNSOverTCPConnFunc) Call(ctx context.Context, conn Result[net.Conn]) DNSConn

Call transforms a net.Conn into an DNSConn thus allowing for DNS exchanges.

The returned value is a *DNSOverTCPConn.

type DNSOverTLSConn

type DNSOverTLSConn struct {
	Conn          Result[net.Conn]
	ErrClassifier ErrClassifier
	SLogger       SLogger
	TimeNow       TimeNowProvider
}

DNSOverTLSConn wraps a TLS conn and allows executing DNS exchanges.

Typically constructed by *DNSOverTLSConnFunc.

func (*DNSOverTLSConn) Close

func (c *DNSOverTLSConn) Close() error

Close closes the underlying TLS connection.

func (*DNSOverTLSConn) Exchange

func (c *DNSOverTLSConn) Exchange(
	ctx context.Context, query *dnscodec.Query) (*dnscodec.Response, error)

Exchange performs a DNS exchange over TLS.

type DNSOverTLSConnFunc

type DNSOverTLSConnFunc struct {
	ErrClassifier ErrClassifier
	SLogger       SLogger
	TimeNow       TimeNowProvider
}

DNSOverTLSConnFunc is the Func that creates *DNSOverTLSConn.

Use NewDNSOverTLSConnFunc to create a new instance.

func NewDNSOverTLSConnFunc

func NewDNSOverTLSConnFunc(cfg *Config) *DNSOverTLSConnFunc

NewDNSOverTLSConnFunc creates a *DNSOverTLSConnFunc using the *Config to properly initialize all the *DNSOverTLSConnFunc fields.

func (*DNSOverTLSConnFunc) Call

func (op *DNSOverTLSConnFunc) Call(ctx context.Context, conn Result[net.Conn]) DNSConn

Call transforms a net.Conn into an DNSConn thus allowing for DNS exchanges.

The returned value is a *DNSOverTLSConn.

type DNSOverUDPConn

type DNSOverUDPConn struct {
	Conn          Result[net.Conn]
	ErrClassifier ErrClassifier
	SLogger       SLogger
	TimeNow       TimeNowProvider
}

DNSOverUDPConn wraps a UDP conn and allows executing DNS exchanges.

Typically constructed by *DNSOverUDPConnFunc.

func (*DNSOverUDPConn) Close

func (c *DNSOverUDPConn) Close() error

Close closes the underlying UDP conn.

func (*DNSOverUDPConn) Exchange

func (c *DNSOverUDPConn) Exchange(
	ctx context.Context, query *dnscodec.Query) (*dnscodec.Response, error)

Exchange performs a DNS exchange over UDP.

type DNSOverUDPConnFunc

type DNSOverUDPConnFunc struct {
	ErrClassifier ErrClassifier
	SLogger       SLogger
	TimeNow       TimeNowProvider
}

DNSOverUDPConnFunc is the Func that creates *DNSOverUDPConn.

Use NewDNSOverUDPConnFunc to create a new instance.

func NewDNSOverUDPConnFunc

func NewDNSOverUDPConnFunc(cfg *Config) *DNSOverUDPConnFunc

NewDNSOverUDPConnFunc creates a *DNSOverUDPConnFunc using the *Config to properly initialize all the *DNSOverUDPConnFunc fields.

func (*DNSOverUDPConnFunc) Call

func (op *DNSOverUDPConnFunc) Call(ctx context.Context, conn Result[net.Conn]) DNSConn

Call transforms a net.Conn into an DNSConn thus allowing for DNS exchanges.

The returned value is a *DNSOverUDPConn.

type Dialer

type Dialer interface {
	DialContext(ctx context.Context, network, address string) (net.Conn, error)
}

Dialer abstracts the *net.Dialer behavior for testing.

type ErrClassifier

type ErrClassifier interface {
	Classify(err error) string
}

ErrClassifier classifies errors into categorical strings.

func DefaultErrClassifier

func DefaultErrClassifier() ErrClassifier

DefaultErrClassifier returns the default ErrClassifier to use.

We map ErrSkip to "ESKIP" and defer to the errclass.New function otherwise.

type ErrSkip

type ErrSkip struct {
	PrevErr error
}

ErrSkip indicates that a stage has been skipped due to previous failures.

func (ErrSkip) Error

func (e ErrSkip) Error() string

Error implements the error interface.

func (ErrSkip) Unwrap

func (e ErrSkip) Unwrap() error

Unwrap returns the underlying error.

type Func

type Func[A, B any] interface {
	Call(ctx context.Context, input A) B
}

Func is a function that accepts an input and returns a result.

func Compose2

func Compose2[A, B, C any](op1 Func[A, B], op2 Func[B, C]) Func[A, C]

Compose2 chains two Func instances together into a pipeline.

func Compose3

func Compose3[A, B, C, D any](op1 Func[A, B], op2 Func[B, C], op3 Func[C, D]) Func[A, D]

Compose3 chains three Func instances together.

func Compose4

func Compose4[A, B, C, D, E any](op1 Func[A, B], op2 Func[B, C],
	op3 Func[C, D], op4 Func[D, E]) Func[A, E]

Compose4 chains four Func instances together.

func Compose5

func Compose5[A, B, C, D, E, F any](op1 Func[A, B], op2 Func[B, C],
	op3 Func[C, D], op4 Func[D, E], op5 Func[E, F]) Func[A, F]

Compose5 chains five Func instances together.

func Compose6

func Compose6[A, B, C, D, E, F, G any](
	op1 Func[A, B], op2 Func[B, C], op3 Func[C, D], op4 Func[D, E],
	op5 Func[E, F], op6 Func[F, G]) Func[A, G]

Compose6 chains six Func instances together.

func Compose7

func Compose7[A, B, C, D, E, F, G, H any](
	op1 Func[A, B], op2 Func[B, C], op3 Func[C, D], op4 Func[D, E],
	op5 Func[E, F], op6 Func[F, G], op7 Func[G, H]) Func[A, H]

Compose7 chains seven Func instances together.

func Compose8

func Compose8[A, B, C, D, E, F, G, H, I any](op1 Func[A, B],
	op2 Func[B, C], op3 Func[C, D], op4 Func[D, E], op5 Func[E, F],
	op6 Func[F, G], op7 Func[G, H], op8 Func[H, I]) Func[A, I]

Compose8 chains eight Func instances together.

type FuncAdapter

type FuncAdapter[A, B any] func(ctx context.Context, input A) B

FuncAdapter creates a Func from an ordinary func.

func (FuncAdapter[A, B]) Call

func (fx FuncAdapter[A, B]) Call(ctx context.Context, input A) B

Call implements Func.

type HTTPBodyWrapper

type HTTPBodyWrapper struct {
	// Body is the wrapped body.
	//
	// Must be public to allow callers to unwrap and opt-out of
	// logging the body events if so they wish.
	Body io.ReadCloser
	// contains filtered or unexported fields
}

HTTPBodyWrapper wraps a response body and emits structured logs when we start and when we finish reading the body.

Use NewHTTPBodyWrapper to create a new instance.

Must not use if you use *HTTPConn: it automatically wraps the body itself.

func NewHTTPBodyWrapper

func NewHTTPBodyWrapper(hc *HTTPConn, body io.ReadCloser) *HTTPBodyWrapper

NewHTTPBodyWrapper creates an *HTTPBodyWrapper using the *HTTPConn and the given io.ReadCloser to initialize all *HTTPBodyWrapper fields.

Must not use if you use *HTTPConn: it automatically wraps the body itself.

func (*HTTPBodyWrapper) Close

func (b *HTTPBodyWrapper) Close() (err error)

Close closes the underlying body emitting `httpBodyStreamDone` if we did ever attempt reading from the body. In such a case, the event error is the last error observed when reading, which might indicate a network filtering issue.

func (*HTTPBodyWrapper) Read

func (b *HTTPBodyWrapper) Read(buffer []byte) (int, error)

Read reads a chunk of the body and emits `httpBodyStreamStart` on the first read.

type HTTPConn

type HTTPConn struct {
	ErrClassifier ErrClassifier
	HTTPCc        Result[HTTPEngineConn]
	LocalAddr     string
	Proto         string
	RemoteAddr    string
	SLogger       SLogger
	TimeNow       TimeNowProvider
}

HTTPConn is an HTTPEngineConn using the net.Conn dialed by a previous stage.

Typically constructed using *HTTPConnFunc.Call.

func (*HTTPConn) Close

func (hc *HTTPConn) Close() error

Close cleans up the transport and closes the underlying connection.

func (*HTTPConn) RoundTrip

func (hc *HTTPConn) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper as implemented by *http.ClientConn.RoundTrip.

On success the *http.Response body is an *HTTPBodyWrapper emitting logs.

type HTTPConnFunc

type HTTPConnFunc struct {
	Engine        HTTPEngine
	ErrClassifier ErrClassifier
	SLogger       SLogger
	TimeNow       TimeNowProvider
}

HTTPConnFunc is the func that constructs *HTTPConn from net.Conn. We pick the correct protocol scheme ("https" or "http") depending on whether the net.Conn implements TLSConn or not. Hence, the TLSConn must be the outermost net.Conn reaching this func: a wrapper around it hides both the type assertion and the ConnectionState method that HTTP/2 negotiation needs.

Use NewHTTPConnFunc to create a new instance.

func NewHTTPConnFunc

func NewHTTPConnFunc(cfg *Config) *HTTPConnFunc

NewHTTPConnFunc creates a *HTTPConnFunc using the *Config to properly initialize all the *HTTPConnFunc fields. We also initialize the Engine field by using DefaultHTTPEngine.

func (*HTTPConnFunc) Call

func (op *HTTPConnFunc) Call(ctx context.Context, input Result[net.Conn]) *HTTPConn

Call transforms a net.Conn into an *HTTPConn thus allowing for HTTP round trips.

type HTTPEngine

type HTTPEngine interface {
	// NewClientConn creates a new [HTTPClientConn] by using:
	//
	//	1. the context to limit the dialing duration
	//	2. the dialer or tlsDialer to dial depending on the scheme
	//	3. the given scheme ("http" or "https") to choose how to dial
	//	4. the given remote endpoint address
	//
	// The stdlib equivalent of this function calls for setting DialContext and
	// DialTLSContext on a transport using dialer.DialContext and tlsDialer.DialContext and
	// then invoking the NewClientConn method of the transport to get the client conn.
	//
	// Our default implementation, [DefaultHTTPEngine], also sets the
	// DisableCompression field to true, which causes the stdlib to stop
	// automatic response body decompression, as described by the
	// field's docs: [http.Transport.DisableCompression].
	NewClientConn(ctx context.Context, dialer, tlsDialer Dialer,
		scheme, raddr string) (HTTPEngineConn, error)
}

HTTPEngine abstracts over *http.ClientConn creation for testing.

func DefaultHTTPEngine

func DefaultHTTPEngine() HTTPEngine

DefaultHTTPEngine returns the default HTTPEngine. The engine implementation is exactly as described by HTTPEngine.NewClientConn docs.

type HTTPEngineConn

type HTTPEngineConn interface {
	RoundTrip(req *http.Request) (*http.Response, error)
	Close() error
}

HTTPEngineConn abstracts over *http.ClientConn for testing.

type ObserveConnFunc

type ObserveConnFunc struct {
	ErrClassifier ErrClassifier
	SLogger       SLogger
	TimeNow       TimeNowProvider
}

ObserveConnFunc is the Func that observes I/O operations as a side effect.

Use NewObserveConnFunc to create a new instance.

func NewObserveConnFunc

func NewObserveConnFunc(cfg *Config) *ObserveConnFunc

NewObserveConnFunc creates an *ObserveConnFunc using the *Config to properly initialize all the *ObserveConnFunc fields.

func (*ObserveConnFunc) Call

func (op *ObserveConnFunc) Call(ctx context.Context, conn Result[net.Conn]) Result[net.Conn]

Call wraps `conn` to observe I/O operations and transfers ownership to the next stage.

type Result

type Result[T any] struct {
	// Err indicates whether the [Func] failed.
	Err error

	// V is a zero value on failure.
	V T
}

Result represents the result of an operation that may fail.

type SLogger

type SLogger interface {
	Debug(msg string, args ...any)
	Info(msg string, args ...any)
}

SLogger abstracts the *slog.Logger behavior for testing.

func DefaultSLogger

func DefaultSLogger() SLogger

DefaultSLogger returns the default SLogger to use: a discard logger that drops any message passed to it.

type TLSConn

type TLSConn interface {
	ConnectionState() tls.ConnectionState
	HandshakeContext(ctx context.Context) error
	net.Conn
}

TLSConn abstracts over *tls.Conn for testing.

type TLSEngine

type TLSEngine interface {
	Client(conn net.Conn, config *tls.Config) TLSConn
	MaybeExtractCerts(err error) [][]byte
	Name() string
	Parrot() string
}

TLSEngine allows mocking the crypto/tls library for testing.

MaybeExtractCerts checks for the TLS engine specific error emitted on certificate verification error and extracts the certs. When using crypto/tls, the specific error is *tls.CertificateVerificationError; uTLS has an error with the same name.

func DefaultTLSEngine

func DefaultTLSEngine() TLSEngine

DefaultTLSEngine returns the default TLSEngine using crypto/tls.

type TLSHandshakeFunc

type TLSHandshakeFunc struct {
	Config        *tls.Config
	Engine        TLSEngine
	ErrClassifier ErrClassifier
	SLogger       SLogger
	TimeNow       TimeNowProvider
}

TLSHandshakeFunc is the Func that performs TLS handshakes.

Use NewTLSHandshakeFunc to create a new instance.

func NewTLSHandshakeFunc

func NewTLSHandshakeFunc(cfg *Config, tlsConfig *tls.Config) *TLSHandshakeFunc

NewTLSHandshakeFunc creates a *TLSHandshakeFunc using the *Config and `tlsConfig` to properly initialize all the *TLSHandshakeFunc fields. We also initialize the `Engine` field using the DefaultTLSEngine.

func (*TLSHandshakeFunc) Call

func (op *TLSHandshakeFunc) Call(ctx context.Context, input Result[net.Conn]) Result[net.Conn]

Call performs a TLS handshake and, on success, transfers the TLS conn ownership to the next stage.

The return value is type-erased to net.Conn to simplify creating pipelines. The type of conn returned on success is *tls.Conn. Subsequent stages should not depend on the exact type; rather use type assertions (e.g., on `ConnectionState`) to manipulate the returned conn.

type TimeNowProvider

type TimeNowProvider interface {
	Get() time.Time
}

TimeNowProvider abstracts over time.Now for testing.

func DefaultTimeNowProvider

func DefaultTimeNowProvider() TimeNowProvider

DefaultTimeNowProvider returns a TimeNowProvider using time.Now.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL