graph

package
v0.136.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: Apache-2.0 Imports: 25 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package graph instruments fleet-wide service-to-service calls and emits them to go-fleet-graph. The collector aggregates edges into a queryable live graph; go-fleet-visualizer renders the result.

The standard outbound and inbound chokepoints in go-common observe fleet calls:

  • safehttp.NewClient wraps the outbound *http.Transport with graph.RoundTripper, recording one outbound Event per call.
  • fleetfetch's internal cache client uses graph.RoundTripper while keeping its Docker-DNS request outside the environment proxy.
  • server.New runs graph.Middleware inside authentication middleware, recording one inbound Event per request with a verified service principal. Unauthenticated or generic principals are recorded as "unknown".

Inbound identity is never inferred from User-Agent. The keystore middleware marks a verified principal; custom HTTP servers may opt in to X-Auth-User only from exact gateway IPs configured with GRAPH_TRUSTED_CALLER_IPS. When an inbound server span is active, Middleware copies that same resolved identity to fleet.caller.id and records fleet.caller.verified. Unverified callers use the fixed value "unknown"; arbitrary request headers and user names are never copied into span attributes. Outbound events derive caller identity from the running service itself.

When both ends are instrumented, one end-to-end HTTP request can emit both an outbound and inbound Event. go-fleet-graph aggregates those emitted observations as topology evidence; its volume is not a unique-request, user, prompt, or LLM-invocation count.

Both call Record under the hood. Services get automatic coverage by using the standard go-common server and safehttp client. An outbound caller that addresses a catalogued service through an ambiguous shared IP should attach graph.WithTarget(ctx, serviceID) to that request context so the emitted edge keeps its canonical logical destination.

Identity comes from server.Run via Init(serviceID, version), or from GRAPH_SERVICE_ID when that is set. Events recorded before either has supplied it (a secrets lookup or poller started ahead of server.New) are held without an owner and stamped with the identity when they are sent; the sender ships nothing until the identity is known. If Init is never called those events are never sent, because the collector rejects a whole batch containing an event that does not belong to the authenticated writer.

An invalid GRAPH_SERVICE_ID (set, but not a lowercase DNS label: [a-z0-9-], at most 63 characters, no leading or trailing '-', so a legacy name such as "go_example_service" fails) makes the identity fail closed: Graph emits nothing for the process, and the collector sees no error because nothing is sent. That state is observable without changing it. Every event dropped for it, whether Record was reached or the RoundTripper / Middleware stopped the call first, is counted in Counters.EventsDroppedInvalidIdentity (fleet_graph_events_dropped_invalid_identity_total), but only while Graph is otherwise configured to emit (GRAPH_ENABLED, a valid collector URL, a writer key). The first time Init or the pre-Init bootstrap resolves the invalid value the package logs one line per process through the standard library logger (graph cannot import the server package, which imports it), naming the variable and saying emission is off; it never logs a key, secret or the rejected value, and Record itself never logs: it does one atomic add.

Origin of events. Replicas of one service share a service id, so the id alone cannot say which server or VM a batch came from. When FLEET_NODE is set the sender adds the X-Fleet-Node header to each batch POST (graph.NodeHeader, graph.Node()). It is deliberately a header: the collector decodes batches with DisallowUnknownFields, so a new JSON field would make an older collector reject every batch from a newer sender, whereas an unknown header is ignored. The value is self-asserted diagnostic metadata and is never used for authorization.

A batch the collector refuses for its content (403, 400, 413, 415, 422) is dropped and counted in Counters.BatchesRejected instead of being retried forever; 401, 408, 429 and 5xx keep the batch for a later flush. Record drops an observation whose string field lengths total more than MaxEventStringBytes (4 KiB), counted in EventsDroppedOversized and fleet_graph_events_dropped_oversized_total. It never truncates an identity or interrupts the HTTP request being observed. The ring's count limit therefore also bounds the total queued string payload lengths during a collector outage. The sender checks the actual JSON size before a POST. Oversized batches split into smaller FIFO batches; an event that exceeds the encoded limit alone is dropped locally and counted in BatchesFailed and BatchesRejected.

Configuration is env-driven, read once at first use:

GRAPH_ENABLED        — default "false". Event emission is opt-in.
GRAPH_SERVICE_ID     — optional canonical registry ID supplied by the
                       fleet-rendered Compose overlay. It overrides a
                       legacy Go package name for writer identity. If set
                       it must be a lowercase DNS label; an invalid value
                       turns emission off (logged once, counted).
GRAPH_COLLECTOR_URL  — exactly "https://fleet-graph.0exec.com" for a
                       remote collector. HTTP/HTTPS loopback endpoints
                       are allowed only for local development and tests.
GRAPH_SAMPLE_RATE    — float 0..1, default 1.0.
GRAPH_API_KEY_FILE   — optional protected file containing the dedicated
                       event-writer key. When set, it takes precedence
                       and read failures fail closed without env fallback.
GRAPH_API_KEY        — compatibility env source for the dedicated writer
                       key. Never falls back to FLEET_API_KEY.
GRAPH_READER_API_KEY — dedicated read key for Lookup only. It is never
                       used to write events.
GRAPH_TARGET_ALIASES - optional comma-separated
                       go-fleet-*=fleet-* mappings for known bare
                       Docker hostnames; it changes telemetry only.
GRAPH_TRUSTED_CALLER_IPS — optional comma-separated literal IP allowlist
                            for custom gateways stamping X-Auth-User.
FLEET_NODE           — optional logical host (the VM) this process runs on,
                       as named in the host-placement policy, e.g.
                       "dockerhost" or "infer-runtime"; injected per host
                       and per pool replica by the deploy tooling. Sent as
                       the X-Fleet-Node header on every batch so the
                       collector can say which server/VM events come from.
                       Lowercase DNS label; invalid values are ignored with
                       one log line. It is a header, never a JSON field.
GRAPH_BUFFER_SIZE    — ring capacity (default 10000 events).
GRAPH_FLUSH_INTERVAL — flush cadence in seconds (default 30, each wait spread by up to 10 % either way).
GRAPH_FLUSH_BATCH    — max events per flush request (default 2000; needs go-fleet-graph 0.4.44, which accepts that many).

Design rules:

  • Opt-in: event recording and emission require GRAPH_ENABLED=true, a valid collector URL, and GRAPH_API_KEY. Missing configuration makes no request and records no event.
  • Fail-open: collector failures never block callers. One failed batch is retained for the next scheduled retry; later batches remain queued.
  • Async: Record never blocks the calling request.
  • Bounded: the ring buffer plus at most one failed batch caps memory; oldest ring events drop first when the buffer is full.
  • Scoped: writers and readers use separate keys; a broad FLEET_API_KEY is never considered for graph transport. File-backed writer keys take precedence over the compatibility environment source.
  • Endpoint-bound: remote graph requests target only the canonical HTTPS graph host and do not follow redirects, so an environment override or collector response cannot forward a graph credential elsewhere.
  • Self-describing: every batch carries schema_version so the collector can tolerate +1 evolution without coordinated deploys.
  • No PII: path templating strips IDs/UUIDs/tokens before recording.
  • Alias-safe: GRAPH_TARGET_ALIASES is an explicit bounded mapping for internal Docker aliases. It never rewrites a request, accepts no URL, port, path, or domain, and malformed entries retain ordinary external target classification.
  • Context-aware identity: WithTarget annotates only the graph event for one request. It does not rewrite the URL or affect request routing.
  • Bounded shutdown: Shutdown accepts an optional context and caps the final flush at five seconds; callers may impose a shorter deadline.

Index

Constants

View Source
const MaxEventStringBytes = 4 << 10

MaxEventStringBytes bounds the sum of the string field lengths Record admits into the send ring. Oversized observations are dropped, never HTTP requests. Together with GRAPH_BUFFER_SIZE this bounds queued telemetry payload bytes during a collector outage; fields are not silently truncated into new identities.

View Source
const NodeHeader = "X-Fleet-Node"

NodeHeader is the HTTP header a Graph writer puts on every batch POST to say which logical host (the VM the process runs on) the batch comes from. It is a header and not a JSON field on purpose: the collector decodes batches with DisallowUnknownFields, so a new field would make an older collector reject every batch from a newer sender, while an unknown header is simply ignored. The value is self-asserted diagnostic metadata, never an authorization input.

View Source
const SchemaVersion = 1

SchemaVersion is the wire-format version of Event/Batch payloads. Collector accepts current and N+1; bump when adding optional fields.

Variables

View Source
var ErrNotConfigured = errors.New("graph: collector URL not configured")

ErrNotConfigured is returned by Lookup when GRAPH_COLLECTOR_URL is unset. Callers fall back to a hardcoded URL in that case.

View Source
var ErrNotFound = errors.New("graph: service not found")

ErrNotFound is returned when the collector has no entry for the slug.

View Source
var ErrReaderKeyNotConfigured = errors.New("graph: reader API key not configured")

ErrReaderKeyNotConfigured is returned before any network request when GRAPH_READER_API_KEY is absent. Reader credentials are distinct from event writer credentials and must be provisioned explicitly.

Functions

func Enabled

func Enabled() bool

Enabled reports whether event emission is on. Useful in tests and in hot paths that want to skip Event allocation.

func Forget

func Forget(slug string)

Forget removes slug from the cache so the next Lookup re-fetches. Useful after a known deploy or in test setup.

func Init

func Init(serviceID, version string)

Init configures the package with the calling service's identity. Called from server.Run / server.New so every fleet service is automatically wired. Safe to call once; subsequent calls update both event and sender identity without restarting the sender.

If the package was already initialised (e.g. via an earlier Record from a probe) the existing ring and sender are preserved.

func Middleware

func Middleware(next http.Handler) http.Handler

Middleware records one inbound Event per authenticated request. server.New mounts it inside authentication middleware so it can read a verified principal from context. Requests that have no verified service identity are recorded with caller "unknown".

Health/version/metrics paths are excluded to avoid drowning the collector in load-balancer probe traffic.

func Node

func Node() string

Node returns the logical host this process reports in the X-Fleet-Node header of its batches, or "" when FLEET_NODE is unset or invalid. It is read once, at first use.

func Record

func Record(e Event)

Record adds an event to the ring. Never blocks; if the ring is full the oldest event is dropped to make room.

func RoundTripper

func RoundTripper(next http.RoundTripper) http.RoundTripper

RoundTripper wraps next with outbound observation. Every request that completes (or fails) emits one outbound Event. The wrapper preserves the underlying transport's behaviour exactly; it only observes timing and metadata.

safehttp.NewClient wraps its transport with this so every fleet outbound call is automatically recorded.

func ServiceID

func ServiceID() string

ServiceID returns the configured identity, useful for callers that want to tag custom events. It is empty until Init (or GRAPH_SERVICE_ID) has supplied one; an Event left without Caller/Target is stamped with the identity when it is sent.

func SetMTLSClientFactory

func SetMTLSClientFactory(f MTLSClientFactory)

SetMTLSClientFactory installs the factory the sender uses when the SPIFFE path is configured. The first non-nil factory wins and later calls are ignored, so a service that installs its own before server.New keeps it. A sender that starts before any factory is installed waits for one and uses the writer key meanwhile.

func Shutdown

func Shutdown(contexts ...context.Context) error

Shutdown stops the background sender and makes a final best-effort flush. The optional caller context can shorten the five-second maximum; omitting it preserves compatibility with existing callers while remaining bounded.

func WithTarget

func WithTarget(ctx context.Context, serviceID string) (context.Context, error)

WithTarget annotates an outbound request context with the canonical Fleet Graph service ID for its destination. Use it when a catalogued service is reached through a shared IP or another address that cannot identify the logical service. It changes telemetry only; it never changes routing.

Types

type Batch

type Batch struct {
	Service       string  `json:"service"`
	Version       string  `json:"version"`
	SchemaVersion int     `json:"schema_version"`
	Events        []Event `json:"events"`
}

Batch is the wire payload POSTed to /events.

type Counters

type Counters struct {
	EventsRecorded int64 `json:"events_recorded"`
	EventsDropped  int64 `json:"events_dropped"`
	EventsSampled  int64 `json:"events_sampled"`
	BatchesSent    int64 `json:"batches_sent"`
	BatchesFailed  int64 `json:"batches_failed"`
	// BatchesRejected is the subset of BatchesFailed the collector refused
	// for content (403, 400, 413, 415, 422), plus single events that cannot fit
	// the local encoded batch limit. They are dropped, not retried, so a
	// nonzero value means events were lost.
	BatchesRejected int64 `json:"batches_rejected"`
	// EventsDroppedInvalidIdentity counts events that would have been recorded
	// (Graph emission is configured) but were dropped because GRAPH_SERVICE_ID
	// is set and is not a valid lowercase DNS label, so the identity fails
	// closed. A nonzero, rising value means the service emits nothing until
	// the variable is fixed or unset.
	EventsDroppedInvalidIdentity int64 `json:"events_dropped_invalid_identity"`
	// EventsDroppedOversized counts observations whose string fields exceed
	// MaxEventStringBytes before admission to the send ring.
	EventsDroppedOversized int64 `json:"events_dropped_oversized"`
	// BatchesSentSPIFFE is the subset of BatchesSent delivered over the SPIFFE
	// mTLS path (GRAPH_SPIFFE_COLLECTOR_URL), without the writer key.
	BatchesSentSPIFFE int64 `json:"batches_sent_spiffe"`
	// BatchesSPIFFEFallback counts batches the SPIFFE path failed to deliver
	// (no answer, or 401, 404, 405, 421) that were then sent with the writer
	// key in the same flush. A rising value means the mTLS path is broken and
	// the key is carrying the traffic.
	BatchesSPIFFEFallback int64 `json:"batches_spiffe_fallback"`
}

Counters are package-level statistics, exposed via Stats() and served on /metrics by every fleet service.

func Stats

func Stats() Counters

Stats returns a snapshot of the package counters. Suitable for exposing via /metrics; never blocks more than one atomic load each.

type Event

type Event struct {
	Direction string `json:"dir"`    // "out" or "in"
	Caller    string `json:"caller"` // service slug (or "unknown" for an unverified inbound caller / "external:<host>")
	Target    string `json:"target"` // service slug (or "external:<host>")
	Path      string `json:"path"`   // templatised, no query string
	Method    string `json:"method"`
	Status    int    `json:"status"`
	LatencyMs int64  `json:"latency_ms"`
	Timestamp int64  `json:"ts"` // unix nanos
}

Event is one emitted fleet HTTP observation. An instrumented caller can record an outbound Event and an instrumented target can record an inbound Event for the same end-to-end request. The collector aggregates emitted events; consumers must not treat their count as a de-duplicated request, user, prompt, or LLM-invocation total.

type MTLSClient

type MTLSClient interface {
	Do(*http.Request) (*http.Response, error)
	Close() error
}

MTLSClient is what the sender needs from a SPIFFE mTLS HTTP client. *spiffe.HTTPClient satisfies it.

type MTLSClientFactory

type MTLSClientFactory func(ctx context.Context, socket string, allowedServerIDs []string, timeout time.Duration) (MTLSClient, error)

MTLSClientFactory connects to the Workload API at socket and returns a client that presents this workload's X.509-SVID and accepts only a server that proves one of allowedServerIDs, with timeout as its total request timeout. It may block until the first SVID arrives or ctx ends.

type Service

type Service struct {
	ID         string `json:"id"`
	Mesh       string `json:"mesh"`
	URL        string `json:"url"`
	HealthURL  string `json:"health_url"`
	Kind       string `json:"kind"`
	Healthy    bool   `json:"healthy"`
	LastSeenMs int64  `json:"last_seen_ms"`
}

Service describes a fleet member, returned by Lookup. Mirrors the fields in services.json that consumers actually need at runtime.

func Lookup

func Lookup(slug string) (Service, error)

Lookup returns Service metadata for slug. The collector resolves fleet members from the latest services.json mirror; this gives callers a runtime-fresh URL instead of a hardcoded constant.

Designed for replacing hardcoded service URLs:

svc, err := graph.Lookup("go-js-proxy")
if err != nil { /* fall back to env or constant */ }
resp, err := client.Get(svc.URL + "/render")

Lookup is cached for ~5 minutes; pass force=true semantics by calling Forget(slug) first if you need a fresh fetch.

func LookupCtx

func LookupCtx(ctx context.Context, slug string) (Service, error)

LookupCtx is the context-aware Lookup. Honours deadlines.

Jump to

Keyboard shortcuts

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