feat(servicekit): OpenTelemetry tracer provider and RPC propagation

This commit is contained in:
sam committed 2026-10-25 23:11:03 +11:00
1 parent b30cb0b1db
commit bc41094b14
23 files changed
+288 -29

No files matched your search

@@ -58,6 +58,9 @@ func (l *Loader) applyDefaults(cfg *config.Config) {
if cfg.Health.DependencyTimeout == 0 {
cfg.Health.DependencyTimeout = config.Duration(defaultHealthDependencyTimeout)
}
if cfg.Telemetry.SampleRatio == 0 {
cfg.Telemetry.SampleRatio = 1
}
l.applyGeneralDefaults(cfg)
applyForgeDefaults(cfg)
applyDispatchDefaults(cfg)
@@ -24,6 +24,7 @@ var DeniedKeys = map[string]string{
"services.*": "Binds service listeners and remote clients at startup.",
"nats.*": "Constructs the broker connection at startup.",
"web.*": "Binds the dashboard listener and authentication at startup.",
"telemetry.*": "Constructs the trace exporter at startup.",
"health.*": "Constructs health listeners and probes at startup.",
"bindings.encryption_key": "Selects the State Store encryption key at startup.",
"bindings.previous_encryption_keys": "Selects the State Store's previous encryption key at startup.",
+2 -1
View File
@@ -10,6 +10,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/presence"
"github.com/samcharles93/archie-core/internal/infrastructure/rpcidentity"
"github.com/samcharles93/archie-core/internal/infrastructure/rpctls"
"github.com/samcharles93/archie-core/internal/infrastructure/telemetry"
)
type Client struct{ rpc pb.DaemonServiceClient }
@@ -19,7 +20,7 @@ func Dial(target string, id *rpctls.Identity) (*Client, func(), error) {
if err != nil {
return nil, nil, err
}
conn, err := grpc.NewClient(target, creds)
conn, err := grpc.NewClient(target, creds, telemetry.ClientOption())
if err != nil {
return nil, nil, err
}
@@ -8,6 +8,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/presence"
"github.com/samcharles93/archie-core/internal/infrastructure/rpctls"
"github.com/samcharles93/archie-core/internal/infrastructure/telemetry"
)
// Dial returns a Gateway chat client for target, authenticated by id. The
@@ -23,6 +24,7 @@ func Dial(target string, id *rpctls.Identity, options ...grpc.DialOption) (*Clie
}
opts := []grpc.DialOption{
creds,
telemetry.ClientOption(),
grpc.WithUnaryInterceptor(unaryPrincipal),
grpc.WithStreamInterceptor(streamPrincipal),
}
@@ -18,6 +18,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/presence"
"github.com/samcharles93/archie-core/internal/infrastructure/rpcidentity"
"github.com/samcharles93/archie-core/internal/infrastructure/rpctls"
"github.com/samcharles93/archie-core/internal/infrastructure/telemetry"
)
// Client opens sessions against a daemon's HarnessService.
@@ -40,7 +41,7 @@ func Dial(target string, id *rpctls.Identity, options ...grpc.DialOption) (*Clie
if err != nil {
return nil, nil, fmt.Errorf("harness: %w", err)
}
conn, err := grpc.NewClient(target, append([]grpc.DialOption{creds}, options...)...)
conn, err := grpc.NewClient(target, append([]grpc.DialOption{creds, telemetry.ClientOption()}, options...)...)
if err != nil {
return nil, nil, fmt.Errorf("create harness client: %w", err)
}
@@ -16,6 +16,7 @@ import (
pb "github.com/samcharles93/archie-core/internal/contracts/messaging/v1"
"github.com/samcharles93/archie-core/internal/domain/presence"
"github.com/samcharles93/archie-core/internal/infrastructure/rpctls"
"github.com/samcharles93/archie-core/internal/infrastructure/telemetry"
"github.com/samcharles93/archie-core/internal/logging"
)
@@ -79,7 +80,7 @@ func Dial(target string, id *rpctls.Identity) (*Client, func(), error) {
if err != nil {
return nil, nil, fmt.Errorf("messaging: %w", err)
}
conn, err := grpc.NewClient(target, creds)
conn, err := grpc.NewClient(target, creds, telemetry.ClientOption())
if err != nil {
return nil, nil, fmt.Errorf("create messaging client: %w", err)
}
+2
View File
@@ -10,6 +10,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/presence"
"github.com/samcharles93/archie-core/internal/infrastructure/rpctls"
"github.com/samcharles93/archie-core/internal/infrastructure/telemetry"
)
// Dial returns a State Store client for target, attributed to the caller
@@ -39,6 +40,7 @@ func DialTask(target string, caPEM []byte, grant string) (*Client, func(), error
func dial(target string, creds grpc.DialOption, caller, grant string, options []grpc.DialOption) (*Client, func(), error) {
opts := []grpc.DialOption{
creds,
telemetry.ClientOption(),
// Keepalive detects a dead peer on an otherwise silent watch stream.
grpc.WithKeepaliveParams(ClientKeepaliveParams()),
// GetInstalledPackage returns the whole layer, which for an extension is
+2 -1
View File
@@ -13,6 +13,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/presence"
"github.com/samcharles93/archie-core/internal/infrastructure/rpctls"
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
"github.com/samcharles93/archie-core/internal/infrastructure/telemetry"
)
// Client never accepts an identity, org or permission list from the harness.
@@ -53,7 +54,7 @@ func Dial(target string, id *rpctls.Identity) (*Client, func(), error) {
if err != nil {
return nil, nil, err
}
conn, err := grpc.NewClient(target, creds, grpc.WithUnaryInterceptor(staterpc.UnaryClientCredentialInterceptor(presence.Daemon, "")), grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(messaging.MaxInboundAttachmentBytes+(1<<20))))
conn, err := grpc.NewClient(target, creds, telemetry.ClientOption(), grpc.WithUnaryInterceptor(staterpc.UnaryClientCredentialInterceptor(presence.Daemon, "")), grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(messaging.MaxInboundAttachmentBytes+(1<<20))))
if err != nil {
return nil, nil, err
}
@@ -0,0 +1,137 @@
// Package telemetry installs the process's OpenTelemetry tracer provider and
// builds the instrumentation options every RPC and HTTP edge shares.
package telemetry
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"net/http"
"os"
"strconv"
"strings"
"time"
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/filters"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.43.0"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"github.com/samcharles93/archie-core/internal/config"
)
const shutdownTimeout = 5 * time.Second
// Start installs the global tracer provider and propagators for component and
// returns the function that flushes and stops them. With no endpoint it
// installs nothing, so the global provider stays a no-op and the returned
// function does nothing. Call it before any server or client is built: the
// instrumentation reads the globals once, at construction.
func Start(ctx context.Context, cfg config.Telemetry, component, version string) (func(), error) {
if cfg.Endpoint == "" {
return func() {}, nil
}
res, err := resource.Merge(resource.Default(), resource.NewWithAttributes(semconv.SchemaURL,
semconv.ServiceName(component),
semconv.ServiceVersion(version),
semconv.ServiceInstanceID(instanceID()),
))
if err != nil {
return nil, fmt.Errorf("telemetry resource: %w", err)
}
opts, err := exporterOptions(cfg)
if err != nil {
return nil, err
}
exporter, err := otlptracegrpc.New(ctx, opts...)
if err != nil {
return nil, fmt.Errorf("telemetry exporter: %w", err)
}
tp := sdktrace.NewTracerProvider(
sdktrace.WithBatcher(exporter),
sdktrace.WithResource(res),
sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.TraceIDRatioBased(cfg.SampleRatio))),
)
otel.SetTracerProvider(tp)
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{}))
return func() { shutdown(ctx, tp) }, nil
}
// shutdown flushes after ctx has typically ended, so the deadline hangs off
// a context detached from its cancellation.
func shutdown(ctx context.Context, tp *sdktrace.TracerProvider) {
flush, cancel := context.WithTimeout(context.WithoutCancel(ctx), shutdownTimeout)
defer cancel()
_ = tp.Shutdown(flush)
}
func exporterOptions(cfg config.Telemetry) ([]otlptracegrpc.Option, error) {
opts := []otlptracegrpc.Option{otlptracegrpc.WithEndpoint(cfg.Endpoint)}
if len(cfg.Headers) > 0 {
opts = append(opts, otlptracegrpc.WithHeaders(cfg.Headers))
}
if cfg.Insecure {
return append(opts, otlptracegrpc.WithInsecure()), nil
}
if cfg.CAFile != "" {
pool, err := caPool(cfg.CAFile)
if err != nil {
return nil, err
}
opts = append(opts, otlptracegrpc.WithTLSCredentials(credentials.NewTLS(&tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS12})))
}
return opts, nil
}
func caPool(path string) (*x509.CertPool, error) {
pem, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("read telemetry ca_file: %w", err)
}
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(pem) {
return nil, errors.New("telemetry ca_file holds no certificate")
}
return pool, nil
}
func instanceID() string {
host, _ := os.Hostname()
return host + "-" + strconv.Itoa(os.Getpid())
}
// ServerOption traces every inbound RPC except health probes.
func ServerOption() grpc.ServerOption {
return grpc.StatsHandler(otelgrpc.NewServerHandler(otelgrpc.WithFilter(filters.Not(filters.HealthCheck()))))
}
// ClientOption traces every outbound RPC and sends the span context.
func ClientOption() grpc.DialOption {
return grpc.WithStatsHandler(otelgrpc.NewClientHandler())
}
// Handler traces every HTTP request except health probes, naming the span by
// the ServeMux pattern. Place it outermost.
func Handler(next http.Handler) http.Handler {
return otelhttp.NewHandler(next, "http",
otelhttp.WithFilter(func(r *http.Request) bool { return !isHealth(r.URL.Path) }),
)
}
func isHealth(path string) bool {
return strings.HasPrefix(path, "/health")
}
// Transport traces outbound HTTP requests made through base.
func Transport(base http.RoundTripper) http.RoundTripper {
return otelhttp.NewTransport(base)
}