olly

package module
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Sep 18, 2026 License: Apache-2.0 Imports: 18 Imported by: 0

README

olly

Agents: start at AGENTS.md. Skills: ai-copilots/.

Portable OpenTelemetry helper for Behavior Engineering services.

Module: github.com/behaviorengineering/olly.

Apps map their own config and logger at the boundary, then call olly.Init once at process start. olly installs the global tracer provider, optional OTLP export, and an optional local failure-trace dump processor.

What olly owns

Package Role
olly Provider lifecycle (Init, Shutdown, Flush), sampling, W3C propagation, env-aware OTLP (gRPC/HTTP)
olly/dump Buffer spans by trace_id; write JSON when SERVER envelopes end with ERROR
olly/errors Annotate spans from Go errors; expose trace/span IDs for logs
olly/http WrapHandler, Middleware, WrapTransport, Client (otelhttp)
olly/cli AddFlags, ConfigFromEnv, Run, Lifecycle (stdlib flag only)

What stays in the app

  • Service names, operation taxonomies, product-specific span attributes
  • Redaction of product-specific attributes (pass dump hooks)
  • Business metrics and logger implementations
  • Pipeline execution records (strop/runreport)

Environment (OTLP)

When Config fields are empty, Init / Resolve read the OpenTelemetry env contract:

  • OTEL_SERVICE_NAME
  • OTEL_RESOURCE_ATTRIBUTES (comma-separated k=v)
  • OTEL_EXPORTER_OTLP_TRACES_ENDPOINT (wins) / OTEL_EXPORTER_OTLP_ENDPOINT
  • OTEL_EXPORTER_OTLP_TRACES_PROTOCOL (wins) / OTEL_EXPORTER_OTLP_PROTOCOL (grpc or http/protobuf)
  • OTEL_EXPORTER_OTLP_TRACES_HEADERS (wins) / OTEL_EXPORTER_OTLP_HEADERS (comma-separated k=v)

Empty OTLPEndpoint after env resolution still means dump-only (no OTLP). Use constant DefaultOTLPEndpoint (localhost:4319, Polypus HyperDX gRPC) from apps or cli.ConfigFromEnv.

Failure dumps

Default completion policy (one mode for gateway and CLI):

  1. Buffer spans by trace_id.
  2. Treat SpanKindServer as this process's envelope (not IsRoot(); inbound traceparent makes the local envelope a remote child).
  3. Write JSON when envelope in-flight hits zero and any buffered span had ERROR.
  4. On shutdown, dump leftover error buffers.

Successful traces are not written. Retention is by max age and max files.

Quick start

import (
    "context"

    "github.com/behaviorengineering/olly"
    "github.com/behaviorengineering/olly/dump"
)

shutdown, err := olly.Init(olly.Config{
    Enabled:      true,
    ServiceName:  "my-service",
    OTLPEndpoint: olly.DefaultOTLPEndpoint, // empty = dump-only / no OTLP
    Dump: dump.Config{
        Dir:         "logs/failures",
        MaxAgeHours: 48,
        MaxFiles:    20,
    },
})
if err != nil {
    return err
}
defer shutdown(context.Background())
HTTP (one line)
import ollyhttp "github.com/behaviorengineering/olly/http"

handler = ollyhttp.WrapHandler(mux, "my-service")
client := ollyhttp.Client(http.DefaultClient, "my-service")
CLI (stdlib)
import ollicli "github.com/behaviorengineering/olly/cli"

cfg := ollicli.ConfigFromEnv("my-cli")
ollicli.AddFlags(flag.CommandLine, &cfg)
flag.Parse()
os.Exit(ollicli.Run(context.Background(), cfg, run))
Cobra (no dependency)
var otelLife *ollicli.Lifecycle

root.PersistentPreRunE = func(cmd *cobra.Command, _ []string) error {
    var err error
    otelLife, err = ollicli.Start(ollicli.ConfigFromEnv(cmd.Root().Name()))
    return err
}
root.PersistentPostRunE = func(cmd *cobra.Command, _ []string) error {
    return otelLife.Stop(cmd.Context())
}

Releases (for agents)

olly is a Go library. Releases are source tags (v*) plus a GitHub Release from GoReleaser (builds.skip: true).

CI quality: workflow ci.yml runs go mod tidy check, gofmt, go vet, go test -race, and go build on pushes and pull requests.

Auto patch on main: every push to main that is not docs/chore/ci-only creates vX.Y.(Z+1) and publishes a release (workflow auto-patch-release.yml). Put [skip release] in the commit subject to opt out once.

Skip (no tag): when every commit subject since the last v* tag is only docs:, chore:, or ci: (conventional prefixes).

Manual minor/major: run workflow Auto patch release with bump=minor or bump=major (or push a v* tag yourself). Use major only for breaking public API changes.

After a new tag, consumer agents MUST pin:

git -C providers/olly fetch --tags origin
git -C providers/olly checkout "vX.Y.Z"
go get github.com/behaviorengineering/olly@vX.Y.Z
go mod tidy

Documentation

Overview

Package olly is a portable OpenTelemetry helper for Go services.

Boundary rules:

  1. No imports of product application packages.
  2. No product-specific service names, operation names, or metric names.
  3. Apps own business span names and redaction policy.
  4. olly owns provider lifecycle, optional OTLP export, local failure-trace dumps, HTTP middleware, CLI Run helpers, and small span error helpers.

Package layout:

  • olly: Init, Config, Shutdown, Flush (env-aware OTLP)
  • olly/dump: SpanProcessor that buffers by trace and writes JSON on envelope ERROR
  • olly/errors: span annotation helpers (Record, EndWithStatus, IDs)
  • olly/http: WrapHandler, Middleware, WrapTransport, Client
  • olly/cli: AddFlags, ConfigFromEnv, Run, Lifecycle (stdlib flag; no cobra)

Index

Constants

View Source
const DefaultOTLPEndpoint = "localhost:4319"

DefaultOTLPEndpoint is the local Polypus HyperDX OTLP/gRPC host:port. Init does not apply it automatically when OTLPEndpoint is empty (empty still means dump-only). Apps and ConfigFromEnv may use this constant.

Variables

This section is empty.

Functions

func BoolPtr added in v0.1.5

func BoolPtr(b bool) *bool

BoolPtr returns a pointer to b for Config.Insecure.

func EnvelopeKind

func EnvelopeKind() trace.SpanKind

EnvelopeKind is the default process envelope for failure dumps (SERVER).

func Flush

func Flush(ctx context.Context) error

Flush flushes pending spans when an SDK provider is active.

func Init

func Init(cfg Config) (func(context.Context) error, error)

Init installs the global TracerProvider, W3C propagator, optional OTLP exporter, and optional failure-dump processor. Returns a shutdown function.

Environment fallbacks (when Config fields are empty) follow the OpenTelemetry spec names; see Config and Config.Resolve.

func Provider

func Provider() *sdktrace.TracerProvider

Provider returns the SDK provider installed by Init, or nil.

func SamplerForRatio

func SamplerForRatio(ratio float64) sdktrace.Sampler

SamplerForRatio returns AlwaysSample for local/full capture (ratio <=0 or >=1). Otherwise ParentBased TraceIDRatioBased for partial export.

func Shutdown

func Shutdown(ctx context.Context) error

Shutdown shuts down the provider installed by Init.

func Tracer

func Tracer(instrumentationName string) trace.Tracer

Tracer returns a named tracer from the global provider.

Types

type Config

type Config struct {
	// Enabled installs a real TracerProvider. When false, Init installs noop.
	Enabled bool
	// ServiceName is set on the resource as service.name.
	// Empty falls back to OTEL_SERVICE_NAME, then "olly".
	ServiceName string
	// OTLPEndpoint is host:port or URL for OTLP. Empty skips OTLP after env
	// fallback (dump-only tracing still works when Dump.Dir is set).
	// Env fallback: OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, then OTEL_EXPORTER_OTLP_ENDPOINT.
	OTLPEndpoint string
	// Protocol is grpc or http/protobuf. Empty falls back to
	// OTEL_EXPORTER_OTLP_TRACES_PROTOCOL, then OTEL_EXPORTER_OTLP_PROTOCOL, then grpc.
	Protocol Protocol
	// Headers are sent with OTLP export (e.g. authorization for HyperDX cloud).
	// Env fallback: OTEL_EXPORTER_OTLP_TRACES_HEADERS, then OTEL_EXPORTER_OTLP_HEADERS
	// (comma-separated k=v). Explicit Headers win over env for the same key.
	Headers map[string]string
	// Insecure overrides TLS. Nil derives from the endpoint: localhost, 127.0.0.1,
	// or an http:// scheme uses insecure; otherwise TLS.
	Insecure *bool
	// OTLPTimeout bounds exporter construction. Zero uses 10s.
	OTLPTimeout time.Duration
	// BatchTimeout is the OTLP batch export interval. Zero uses 3s.
	BatchTimeout time.Duration
	// SampleRatio is 0..1. Values <=0 or >=1 use AlwaysSample.
	SampleRatio float64
	// AllowOTLPFailure continues with dump-only tracing when OTLP setup fails.
	// When false, Init returns the exporter error.
	AllowOTLPFailure bool
	// Dump configures the local failure-trace processor. Empty Dir disables it.
	Dump dump.Config
	// ExtraProcessors are appended after the dump processor (if any).
	ExtraProcessors []sdktrace.SpanProcessor
	// ResourceAttributes are merged onto the default resource (service.name wins from ServiceName).
	// Env OTEL_RESOURCE_ATTRIBUTES (comma-separated k=v) fill keys not set here.
	ResourceAttributes map[string]string
	// Diagnostics receives dump write/prune messages. Nil uses stderr.
	Diagnostics dump.Diagnostics
}

Config controls provider construction.

func (Config) Defaults

func (c Config) Defaults() Config

Defaults fills zero-value timeouts and dump retention.

func (Config) Resolve added in v0.1.5

func (c Config) Resolve() Config

Resolve applies environment fallbacks onto a copy of Config without mutating c. Explicit non-empty Config fields win over env.

type Protocol added in v0.1.5

type Protocol string

Protocol selects the OTLP transport.

const (
	// ProtocolGRPC is OTLP over gRPC (default).
	ProtocolGRPC Protocol = "grpc"
	// ProtocolHTTP is OTLP over HTTP protobuf (http/protobuf).
	ProtocolHTTP Protocol = "http/protobuf"
)

Directories

Path Synopsis
Package cli provides stdlib helpers to wire OpenTelemetry into Go CLIs with minimal boilerplate.
Package cli provides stdlib helpers to wire OpenTelemetry into Go CLIs with minimal boilerplate.
Package dump buffers OpenTelemetry spans and writes JSON when a process envelope ends with an ERROR somewhere in the trace.
Package dump buffers OpenTelemetry spans and writes JSON when a process envelope ends with an ERROR somewhere in the trace.
Package errors annotates OpenTelemetry spans from Go errors.
Package errors annotates OpenTelemetry spans from Go errors.
Package http wraps net/http handlers and clients with OpenTelemetry spans.
Package http wraps net/http handlers and clients with OpenTelemetry spans.

Jump to

Keyboard shortcuts

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