Skip to content

About

Go instrumentation for propagating E2Engine test execution IDs through applications and dependency calls.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

E2Engine Go Instrumentation

Go instrumentation for propagating E2Engine test execution IDs through applications and dependency calls.

Part of E2Engine, an open-source platform for declarative end-to-end testing.

E2Engine uses a test execution ID to correlate calls made by a system under test with the test execution that caused them. This repository provides lightweight instrumentation for carrying that ID through Go applications and propagating it across supported protocols.

Instrumentation does not introduce an execution ID when no valid ID is available. Outbound instrumentation still removes invalid or ambiguous execution-ID headers or metadata. The same application binary can be used both with and without E2Engine.

Requirements

The root, HTTP, and AWS modules require Go 1.25.12 or later. The gRPC module requires Go 1.26.0 or later.

Packages

The repository is split into independent Go modules so applications only need the dependencies required by the protocols they use.

Module / Package Purpose
github.com/e2engine/instrumentation-go Context propagation and execution-ID validation
github.com/e2engine/instrumentation-go/http HTTP server and client instrumentation
github.com/e2engine/instrumentation-go/grpc gRPC unary server and client instrumentation
github.com/e2engine/instrumentation-go/aws AWS SDK for Go v2 instrumentation
github.com/e2engine/instrumentation-go/aws/lambda AWS Lambda API Gateway HTTP API v2 instrumentation

The Lambda adapter is provided by the AWS module.

How it works

E2Engine attaches a test execution ID to requests sent to the system under test.

Instrumentation extracts and validates that ID at the application boundary, stores valid IDs in context.Context, and injects them into outgoing dependency calls.

E2Engine
    │
    │ test execution ID
    ▼
┌──────────────────────────┐
│ System under test        │
│                          │
│ inbound instrumentation  │
│            │             │
│            ▼             │
│      context.Context     │
│            │             │
│            ▼             │
│ outbound instrumentation │
└────────────┬─────────────┘
             │
             │ test execution ID
             ▼
        Dependency

Application code only needs to propagate context.Context normally. The protocol-specific instrumentation handles extraction and injection of the execution ID.

Execution ID validation

A valid E2Engine test execution ID contains exactly 64 lowercase alphanumeric ASCII characters (a-z, 0-9).

Identifiers generated by E2Engine currently contain 64 lowercase hexadecimal characters (a-f, 0-9), which satisfy this validation rule.

The root module exposes:

valid := e2engine.ValidTestExecutionID(id)

WithTestExecutionID ignores invalid identifiers and returns the original context unchanged. If that context already contains a valid execution ID, the existing value is preserved.

Invalid incoming execution IDs therefore do not enter the application context through the instrumentation extractors. Requests continue normally without a new execution ID.

Execution IDs are correlation metadata, not authentication or authorization credentials.

HTTP

Install the HTTP module:

go get github.com/e2engine/instrumentation-go/http

Instrument incoming requests with Handler and outgoing requests with Transport.

HTTP instrumentation uses the E2Engine-Test-Execution-ID header:

  • Handler uses Extract to accept exactly one valid incoming header value. Missing, empty, invalid, or multiple values leave the original request and context unchanged. A valid incoming ID replaces any execution ID already in context.
  • Transport uses Inject to preserve exactly one valid explicitly supplied outgoing header value, even when context contains a different ID. If the header is missing, invalid, or contains multiple values, a valid context ID is used instead. Without a valid context ID, invalid or multiple header values are removed.
  • Inject never modifies the supplied request or its headers. It clones the request only when changes are necessary and otherwise returns the original request.
package main

import (
    "log"
    "net/http"

    e2enginehttp "github.com/e2engine/instrumentation-go/http"
)

func main() {
    // Instrument outgoing HTTP requests to propagate the E2Engine execution ID
    // from the request context to HTTP headers.
    client := &http.Client{
        Transport: e2enginehttp.Transport(),
    }

    // Use the instrumented request context for outgoing dependency calls.
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        request, err := http.NewRequestWithContext(
            r.Context(),
            http.MethodGet,
            "http://dependency:8080",
            nil,
        )
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }

        response, err := client.Do(request)
        if err != nil {
            http.Error(w, err.Error(), http.StatusBadGateway)
            return
        }
        defer response.Body.Close()

        w.WriteHeader(response.StatusCode)
    })

    // Instrument incoming HTTP requests to extract the E2Engine execution ID
    // from HTTP headers into the request context.
    log.Fatal(
        http.ListenAndServe(
            ":8080",
            e2enginehttp.Handler(),
        ),
    )
}

Handler() uses http.DefaultServeMux by default. An explicit handler can also be supplied:

handler := e2enginehttp.Handler(mux)

An existing transport can be wrapped:

client := &http.Client{
    Transport: e2enginehttp.Transport(customTransport),
}

The HTTP package also exposes lower-level helpers when direct header manipulation is required:

id := e2enginehttp.TestExecutionID(header)

header = e2enginehttp.WithTestExecutionID(
    header,
    executionID,
)

header = e2enginehttp.WithoutTestExecutionID(header)

Here, executionID is a valid 64-character E2Engine execution ID.

TestExecutionID returns the first header value without validation, or an empty string if no value is present. WithTestExecutionID returns a copy: a valid ID replaces existing values; an invalid or empty ID removes the header. WithoutTestExecutionID returns a copy with the header removed. Neither mutation helper modifies the supplied headers.

gRPC

Install the gRPC module:

go get github.com/e2engine/instrumentation-go/grpc

E2Engine currently provides instrumentation for unary gRPC calls.

Instrument the server and client with the corresponding interceptors.

gRPC instrumentation uses the e2engine-test-execution-id metadata key:

  • UnaryServerInterceptor uses Extract to accept exactly one valid incoming value. Missing, empty, invalid, or multiple values preserve the original context. A valid incoming ID replaces any execution ID already in context.
  • UnaryClientInterceptor uses Inject to preserve exactly one valid explicitly supplied outgoing value, even when context contains a different ID. If the outgoing ID is missing, invalid, or contains multiple values, a valid context ID is used instead. Without a valid context ID, invalid or multiple outgoing values are removed.
  • Inject preserves unrelated metadata and never modifies caller-owned metadata. It returns the original context when no changes are necessary. Values added with metadata.AppendToOutgoingContext follow the same rules and do not accumulate duplicate execution IDs through repeated injection.
package main

import (
    "log"
    "net"

    "google.golang.org/grpc"
    "google.golang.org/grpc/credentials/insecure"

    e2enginegrpc "github.com/e2engine/instrumentation-go/grpc"
)

func main() {
    // Instrument outgoing unary calls. A single valid outgoing metadata ID
    // takes precedence; otherwise, a valid context ID is used.
    connection, err := grpc.NewClient(
        "dependency:8081",
        grpc.WithTransportCredentials(
            insecure.NewCredentials(),
        ),
        grpc.WithUnaryInterceptor(
            e2enginegrpc.UnaryClientInterceptor(),
        ),
    )
    if err != nil {
        log.Fatal(err)
    }
    defer connection.Close()

    // The service implementation can use connection normally as long as it
    // propagates the incoming request context to dependency calls.

    listener, err := net.Listen("tcp", ":8080")
    if err != nil {
        log.Fatal(err)
    }

    // Instrument incoming unary calls to extract the E2Engine execution ID
    // from gRPC metadata into the request context.
    server := grpc.NewServer(
        grpc.UnaryInterceptor(
            e2enginegrpc.UnaryServerInterceptor(),
        ),
    )

    // Register the service with server.

    log.Fatal(server.Serve(listener))
}

The gRPC package also exposes lower-level metadata helpers:

id := e2enginegrpc.TestExecutionID(md)

md = e2enginegrpc.WithTestExecutionID(
    md,
    executionID,
)

md = e2enginegrpc.WithoutTestExecutionID(md)

TestExecutionID returns the first metadata value without validation, or an empty string if no value is present. WithTestExecutionID returns a copy: a valid ID replaces existing values; an invalid or empty ID removes the key. WithoutTestExecutionID returns a copy with the key removed. Neither mutation helper modifies the supplied metadata.

AWS SDK for Go v2

Install the AWS module:

go get github.com/e2engine/instrumentation-go/aws

Add the E2Engine option when loading the AWS configuration:

package main

import (
    "context"
    "log"

    "github.com/aws/aws-sdk-go-v2/config"

    e2engineaws "github.com/e2engine/instrumentation-go/aws"
)

func main() {
    cfg, err := config.LoadDefaultConfig(
        context.Background(),
        e2engineaws.Option(),
    )
    if err != nil {
        log.Fatal(err)
    }

    _ = cfg
}

Exactly one valid E2Engine-Test-Execution-ID outgoing header value takes precedence over the operation context. If the header is missing, invalid, or contains multiple values, the context passed to the individual AWS SDK operation supplies the fallback ID:

_, err := client.PutItem(
    ctx,
    &dynamodb.PutItemInput{
        // ...
    },
)

The instrumentation adds the execution ID during the Smithy Build step, before AWS request signing. When an execution ID is present, the propagation header is included in the AWS SigV4 signed headers.

If neither source supplies a valid ID, invalid or multiple execution-ID header values are removed before signing. The original request and unrelated headers are preserved; a copy is passed downstream only when a change is needed. The Smithy request stream is preserved.

AWS Lambda

The AWS module also provides inbound instrumentation for Lambda functions invoked through API Gateway HTTP API payload format 2.0.

Install the AWS module:

go get github.com/e2engine/instrumentation-go/aws

Wrap your Lambda handler with e2enginelambda.Handler:

package main

import (
    "context"
    "net/http"

    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambda"

    e2enginelambda "github.com/e2engine/instrumentation-go/aws/lambda"
)

func handle(
    ctx context.Context,
    request events.APIGatewayV2HTTPRequest,
) (events.APIGatewayV2HTTPResponse, error) {
    // The context contains the E2Engine execution ID when a valid
    // ID was supplied in the incoming API Gateway request.

    return events.APIGatewayV2HTTPResponse{
        StatusCode: http.StatusOK,
    }, nil
}

func main() {
    lambda.Start(
        e2enginelambda.Handler(handle),
    )
}

The wrapper extracts the E2Engine-Test-Execution-ID HTTP header, validates the execution ID through the shared context API, and passes the enriched context to the application handler.

Header names are handled case-insensitively, including the lowercase header names normally supplied by API Gateway HTTP API v2.

Exactly one valid header value is accepted. Missing, empty, malformed, or comma-joined values are ignored, as are multiple matching header names with different casing. API Gateway HTTP API v2 combines repeated header values with commas. Rejected IDs leave the original context unchanged, including any existing execution ID; a valid incoming ID replaces it.

The wrapper does not modify the original API Gateway request, HTTP response, or handler error.

Lower-level Lambda helpers

The Lambda package also exposes helpers for extracting the execution ID explicitly:

ctx = e2enginelambda.Extract(ctx, request)

id := e2enginelambda.TestExecutionID(request.Headers)

Extract validates the ID through e2engine.WithTestExecutionID and preserves the original context when the header contains no valid ID.

TestExecutionID reads the raw header value without validating it. It returns an empty string when the header is missing or appears under multiple case-insensitive names.

Combining Lambda and AWS SDK instrumentation

AWS Lambda and AWS SDK instrumentation can be combined to propagate execution IDs through DynamoDB and other AWS dependency calls.

API Gateway HTTP API v2
         │
         ▼
e2enginelambda.Handler
         │
         ▼
   context.Context
         │
         ▼
Application / Service
         │
         ▼
AWS SDK with e2engineaws.Option()
         │
         ▼
    AWS Dependency

Configure the AWS SDK with e2engineaws.Option(), wrap the Lambda handler with e2enginelambda.Handler, and pass the incoming context to AWS SDK operations.

Both integrations work independently. Lambda instrumentation handles inbound extraction, while AWS SDK instrumentation handles outgoing propagation.

The Lambda adapter currently supports API Gateway HTTP API v2 events. Other Lambda event sources are not included.

Context propagation

The root module provides the protocol-independent context API:

go get github.com/e2engine/instrumentation-go

An execution ID can be validated, stored, and retrieved directly:

executionID := "a1b2c3d4a1b2c3d4a1b2c3d4a1b2c3d4a1b2c3d4a1b2c3d4a1b2c3d4a1b2c3d4"

if e2engine.ValidTestExecutionID(executionID) {
    ctx = e2engine.WithTestExecutionID(ctx, executionID)
}

id := e2engine.TestExecutionID(ctx)

WithTestExecutionID performs validation automatically, so the explicit validation check is optional.

When the supplied ID is invalid or empty, the original context is returned unchanged.

Most applications should not need to use these functions directly. Protocol instrumentation extracts the execution ID into the context and propagates it to outgoing calls automatically.

The important requirement is to preserve the request context through the application.

For example:

request, err := http.NewRequestWithContext(
    r.Context(),
    http.MethodGet,
    url,
    nil,
)

And:

response, err := grpcClient.Call(
    r.Context(),
    request,
)

If an application replaces the incoming context with context.Background() before making a dependency call, the execution ID is lost and that call cannot be correlated with its E2Engine test execution.

Using multiple protocols

Instrumentation can be combined freely.

For example, an HTTP or Lambda service can call HTTP, gRPC, and AWS dependencies:

HTTP / API Gateway request
          │
          ▼
  Inbound instrumentation
          │
          ▼
    context.Context
          │
          ├──► HTTP Transport ──► HTTP dependency
          │
          ├──► gRPC Interceptor ──► gRPC dependency
          │
          └──► AWS SDK Option ──► AWS dependency

The execution ID remains protocol-neutral while it is carried through the application context. Each outgoing adapter translates it into the representation required by its protocol.

Production use

E2Engine instrumentation is designed to be safe to include in the normal application binary.

When a request does not contain a valid E2Engine test execution ID:

  • Inbound instrumentation does not introduce a new execution ID into the application context.
  • Outbound instrumentation does not add propagation information when no ID exists in the context.
  • Normal application behavior is preserved.

This means a separate E2Engine-specific application build is not required.

Execution IDs are treated as untrusted correlation metadata. Invalid identifiers are ignored by the context API rather than causing request failures.

Instrumentation does not provide authentication, authorization, or verification of the identity of the caller. Applications must enforce their own security controls.

Execution ID precedence

When making an outgoing dependency call, instrumentation first examines the execution ID explicitly supplied in the outgoing request headers or metadata.

If exactly one valid execution ID is present, it is preserved, even if the application context contains a different ID.

If the outgoing execution ID is absent, invalid, or ambiguous, instrumentation falls back to the valid execution ID stored in context.Context.

If neither source provides a valid ID, the outgoing request contains no E2Engine execution ID.

This allows applications to explicitly override execution-ID propagation when necessary, while preventing malformed or ambiguous IDs from being forwarded.

Development

Run tests for all modules:

make test

Aggregate targets select Go 1.25.12 for the root, HTTP, and AWS modules and Go 1.26.0 for gRPC. Each toolchain group can also be tested separately:

make test-go125
make test-grpc

The same -go125 and -grpc suffixes are available for tidy, lint, lint-fix, test-cov, test-race, and verify.

Use GO_TOOLCHAIN to override the root, HTTP, and AWS toolchain and GRPC_GO_TOOLCHAIN to override the gRPC toolchain. For example, to test all modules with the installed Go version without automatic toolchain switching:

make test GO_TOOLCHAIN=local GRPC_GO_TOOLCHAIN=local

Run the full verification suite:

make verify

Run tests with coverage:

make test-cov

Run the race detector:

make test-race

CI tests the root, HTTP, and AWS modules with Go 1.25.12 and gRPC with Go 1.26.0. It also runs lint and race tests for all modules with stable Go.

License

Licensed under the Apache License, Version 2.0. See LICENSE.

About

Go instrumentation for propagating E2Engine test execution IDs through applications and dependency calls.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages