# fetch

> Package fetch is the seam WebFetch reaches the web through, and its default implementation.

<!-- Generated from the Go source of github.com/barevoidco/zelk/core/fetch (cmd/zelk/internal/reference TestReferenceGoAPI). Don't edit: change the code, then run make reference. -->

```go
import "github.com/barevoidco/zelk/core/fetch"
```

Package fetch is the seam WebFetch reaches the web through, and its default implementation.

A Fetcher takes a URL and returns the response's body, bounded. The default Client enforces its address policy when it connects, on the address it actually dials, so a host name that resolves to a private address, or changes what it resolves to between checks, is refused whatever its name; every redirect is checked again the same way. It never reads proxy settings or certificates from the environment: a proxy (WithProxy) and extra roots (WithRootCAs) are explicit options. Compressed responses are decompressed within the same size bound, so a small compressed body can't expand without limit.

An Extractor optionally answers a question about a fetched page with a model, within a token reservation the session checks against its budget.


## Constants

```go
const (
	DefaultMaxBytes     = 10 << 20
	DefaultMaxRedirects = 5
	DefaultTimeout      = 30 * time.Second
	DefaultUserAgent    = "zelk-webfetch/1"
)
```

Defaults of the Client.


## Variables

```go
var (
	// ErrBlocked reports an address the policy doesn't allow: private,
	// loopback, link-local and similar, unless allowed explicitly.
	ErrBlocked = errors.New("address not allowed")
	// ErrURL reports a URL WebFetch can't fetch: not http or https, or
	// with credentials.
	ErrURL = errors.New("unsupported URL")
	// ErrTooManyRedirects reports a chain of redirects past the limit.
	ErrTooManyRedirects = errors.New("too many redirects")
)
```


## Blocked

```go
func Blocked(ip netip.Addr) bool
```

Blocked reports whether the default policy refuses ip: loopback, private, link-local, unspecified, multicast, carrier-grade NAT and the other ranges that don't belong to the public internet.


## Client

```go
type Client struct {
	// contains filtered or unexported fields
}
```

Client is the default Fetcher. It is safe for concurrent use.


### New

```go
func New(opts ...Option) (*Client, error)
```

New returns a Client. It reads nothing from the process environment.


### Client.Close

```go
func (c *Client) Close() error
```

Close releases idle connections.


### Client.Fetch

```go
func (c *Client) Fetch(ctx context.Context, req Request) (Response, error)
```

Fetch gets req.URL. A refused address, a bad URL or too many redirects are errors wrapping ErrBlocked, ErrURL or ErrTooManyRedirects; any HTTP status is a response.


## ExtractRequest

```go
type ExtractRequest struct {
	URL, Content, Prompt string
}
```

ExtractRequest is a page and a question about it.


## Extraction

```go
type Extraction struct {
	Text  string
	Usage *event.Usage
}
```

Extraction is an extractor's answer and what it spent; Usage is nil if the provider didn't report it, and the whole reservation is charged.


## Extractor

```go
type Extractor interface {
	// Limit is the most tokens one extraction may spend.
	Limit() event.Tokens
	Extract(ctx context.Context, req ExtractRequest) (Extraction, error)
}
```

Extractor answers a question about a fetched page with a model, usually a small one. Its calls are budgeted: each extraction reserves Limit from the session's budget before it runs, and reports what it spent.


## Fetcher

```go
type Fetcher interface {
	Fetch(ctx context.Context, req Request) (Response, error)
}
```

Fetcher fetches a URL. Implementations must be safe for concurrent use and honour ctx.


## Model

```go
type Model struct {
	// contains filtered or unexported fields
}
```

Model is an Extractor that asks a model through a provider.


### NewModel

```go
func NewModel(p provider.Provider, model string, limit event.Tokens) (*Model, error)
```

NewModel returns an extractor that asks model through p, spending at most limit per extraction: the page is cut so the request's bytes stay within limit.Input, which bounds its tokens, and the answer within limit.Output.


### Model.Extract

```go
func (m *Model) Extract(ctx context.Context, req ExtractRequest) (Extraction, error)
```

Extract asks the model the request's question about its page.


### Model.Limit

```go
func (m *Model) Limit() event.Tokens
```

Limit returns the most one extraction spends.


## Option

```go
type Option func(*Client)
```

Option configures a Client.


### WithAllow

```go
func WithAllow(prefixes ...netip.Prefix) Option
```

WithAllow permits addresses in prefixes that the policy otherwise blocks, such as an internal network the host trusts.


### WithHosts

```go
func WithHosts(allow func(host, port string) bool) Option
```

WithHosts limits requests to hosts allow accepts, the first request and every redirect alike. port is the URL's port, or the scheme's default. Without it any public host may be fetched.


### WithMaxBytes

```go
func WithMaxBytes(n int64) Option
```

WithMaxBytes sets the default bound on a body, after decompression.


### WithMaxRedirects

```go
func WithMaxRedirects(n int) Option
```

WithMaxRedirects sets how many redirects a fetch follows.


### WithProxy

```go
func WithProxy(proxy func(target *url.URL) (*url.URL, error)) Option
```

WithProxy sends each request through the HTTP or HTTPS proxy proxy names for its URL (an http, https or socks5 URL), or directly when it names none, as http.Transport.Proxy does (golang.org/x/net/http/httpproxy builds one from proxy settings). A proxy is the host's to trust: a connection to it as the proxy is made whatever the policy says (a request that goes direct to the same address is still checked), and it reaches the target itself, so only a target given as an IP address is checked against the policy.


### WithRootCAs

```go
func WithRootCAs(roots *x509.CertPool) Option
```

WithRootCAs verifies servers' certificates against roots instead of the system's, as a proxy that inspects TLS needs.


### WithTimeout

```go
func WithTimeout(d time.Duration) Option
```

WithTimeout bounds a whole fetch, redirects and body included.


### WithUserAgent

```go
func WithUserAgent(s string) Option
```

WithUserAgent sets the User-Agent header.


## RedirectError

```go
type RedirectError struct {
	// URL is where the redirect leads.
	URL string
}
```

RedirectError reports a redirect that SameHost didn't follow.


### RedirectError.Error

```go
func (e *RedirectError) Error() string
```


## Request

```go
type Request struct {
	URL string
	// MaxBytes bounds the body, after decompression; zero is the
	// fetcher's default.
	MaxBytes int64
	// SameHost stops at a redirect to another host, with a *RedirectError,
	// for a caller whose permission to fetch was for this host alone.
	SameHost bool
}
```

Request is one fetch.


## Response

```go
type Response struct {
	// URL is where the body came from, after redirects.
	URL         string
	Status      int
	ContentType string
	Body        []byte
	// Truncated reports a body cut at MaxBytes.
	Truncated bool
}
```

Response is a fetched resource.


### Response.MediaType

```go
func (r Response) MediaType() string
```

MediaType returns a response's media type, lowercase, without parameters.
