Commit 04f05808 authored by Liz Fong-Jones's avatar Liz Fong-Jones
Browse files

Add 2nd-edition code examples, organized by chapter

Extract the substantive, runnable/copyable code from the 2nd edition into
2e/<chapter-NN-slug>/, each self-contained with its own README and toolchain:

- chapter-05-structured-events (JavaScript): the toy tracer that grows a
  structured log into a trace span (log/logTiming/Span/AsyncLocalStorage).
  node --test passes; npm start runs the demo.
- chapter-07-instrumenting-with-opentelemetry (Java/Maven): Example 7-1, W3C
  trace-context inject/extract. Compiles and prints a live traceparent.
- chapter-12-slo-based-alerts (Go): the predictive burn-alert isBurnViolation,
  with a table test reproducing the chapter's worked example (fires at 805
  projected failures vs a 438 budget).
- chapter-14-clickhouse (SQL): Examples 14-1..14-6 + inline snippets, runnable
  against ClickHouse in Docker via run.sh; 14-5 reproduces the book's exact
  recovery times (nginx 961s, apiserver 63s).
- chapter-15-sampling (Go): the nine sampling strategies as separate compilable
  programs, with teaching-simplifications corrected to build.

Only code a reader would copy/run is included; illustrative query-DSL snippets,
the git-diff in Example 20-1, and pseudo-code are intentionally omitted.

Add a top-level README indexing both editions and a generative-AI disclaimer
(examples authored by humans; GenAI used to maintain the repo).

Co-Authored-By: default avatarClaude Opus 4.8 (1M context) <noreply@anthropic.com>
parent 08db6342
Loading
Loading
Loading
Loading
+3 −0
Changes for .gitignore: 3 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -10,3 +10,6 @@ node_modules/

# Go build artifacts
1e/chapter-07-instrumentation-with-opentelemetry/src/opentelemetry-workshop

# Java / Maven
target/
+27 −0
Changes for 2e/chapter-05-structured-events/README.md: 27 added lines, 0 removed lines.
Original line number Diff line number Diff line
# Chapter 5: Structured Events Are the Building Blocks of Observability

The "Turning Logs Into Distributed Traces" walkthrough, built up step by step: a
plain structured log grows into a trace span once you add a trace ID, a span ID,
and a parent span ID. It's a rudimentary, dependency-free tracing library in
Node.js, meant to show the shape of the data — not for production use.

- `tracer.js` — the library: `log()`, `logTiming()`, the `Span` class, and
  `startSpan()` (which propagates context implicitly via `AsyncLocalStorage`).
- `index.js` — runs the book's progression end to end.
- `tracer.test.js` — asserts a child span inherits its parent's trace ID and
  records the parent's span ID.

A couple of small bugs in the printed snippets are corrected here so it runs:
`JSON.stringify` (the book prints `JSON.format`), and a `getContext()` method on
`Span` (the book calls it in `startSpan` but elides the definition). These are
noted in comments in `tracer.js`.

## Run it

Requires Node.js 18+ (uses the built-in test runner and `AsyncLocalStorage`); no
`npm install` needed.

```bash
npm start   # node index.js  — prints events and a parent/child trace
npm test    # node --test
```
+31 −0
Changes for 2e/chapter-05-structured-events/index.js: 31 added lines, 0 removed lines.
Original line number Diff line number Diff line
// Demonstrates the toy tracer from Chapter 5, following the same progression as
// the book: a structured event, a timed subtask, a single span, and finally a
// parent span with a child span that shares its trace.
//
// Run with: npm start   (or: node index.js)

import { log, logTiming, Span, startSpan } from "./tracer.js";

// 1) A plain structured event.
log("user-authenticated", { userId: "1234", remainingRateLimit: 100 });

// 2) Timing a subtask.
logTiming("query-user-info", () => {
  // pretend to do work here, e.g. db.fetchUserInfo()
});

// 3) A single span, recorded and printed.
let span = new Span("api-request");
span.setAttributes({ responseCode: 200 });
span.end();
console.log(span);

// 4) A parent span and a child span. The child inherits the parent's traceID
//    and records the parent's spanID as its parentSpanID, all via implicit
//    context propagation.
startSpan("parent", async (parentSpan) => {
  parentSpan.setAttributes({ outerSpan: true });
  await startSpan("child", async (childSpan) => {
    childSpan.setAttributes({ outerSpan: false });
  });
});
+11 −0
Changes for 2e/chapter-05-structured-events/package.json: 11 added lines, 0 removed lines.
Original line number Diff line number Diff line
{
  "name": "chapter-05-structured-events",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "description": "Turning logs into distributed traces: the toy tracer from Chapter 5 of Observability Engineering (2nd ed).",
  "scripts": {
    "start": "node index.js",
    "test": "node --test"
  }
}
+82 −0
Changes for 2e/chapter-05-structured-events/tracer.js: 82 added lines, 0 removed lines.
Original line number Diff line number Diff line
// A rudimentary tracing library, built up step by step in Chapter 5,
// "Structured Events Are the Building Blocks of Observability." It shows how an
// ordinary structured log grows into a trace span once you add a trace ID, a
// span ID, and a parent span ID.
//
// Pure Node.js, no dependencies: it uses the built-in crypto and async_hooks
// modules.

import crypto from "node:crypto";
import { AsyncLocalStorage } from "node:async_hooks";

// log emits a structured event as a single JSON line: a timestamp, a name, and
// any additional attributes spread in alongside them.
//
// (The book prints JSON.format(...); the real method is JSON.stringify.)
export function log(name, attributes) {
  console.log(
    JSON.stringify({
      timestamp: new Date().getTime(),
      name,
      ...attributes,
    }),
  );
}

// logTiming times a subtask and logs how long it took, in milliseconds.
export function logTiming(name, lambda) {
  let startTime = new Date().getTime();

  // run some subtask
  lambda();

  let durationMs = new Date().getTime() - startTime;
  log(name, { durationMs });
}

// Span is a structured log entry plus the three fields that turn a pile of logs
// into a trace: a traceID shared across the request, this span's own spanID,
// and the parentSpanID it descends from (undefined for a root span).
export class Span {
  constructor(name, context = {}, attributes = new Map()) {
    this.startTime = new Date().getTime();
    this.traceID = context.traceID ?? crypto.randomBytes(16).toString("hex");
    this.parentSpanID = context.spanID ?? undefined;
    this.spanID = crypto.randomBytes(8).toString("hex");
    this.name = name;
    this.attributes = attributes;
  }

  setAttributes(keyValues) {
    for (let [key, value] of Object.entries(keyValues)) {
      this.attributes.set(key, value);
    }
  }

  // getContext returns the trace context that a child span should inherit. (The
  // book calls span.getContext() inside startSpan but elides the method here.)
  getContext() {
    return { traceID: this.traceID, spanID: this.spanID };
  }

  end() {
    this.durationMs = new Date().getTime() - this.startTime;
  }
}

// In Node.js, trace context is propagated implicitly with the AsyncLocalStorage
// API (in Ruby or Python you would use a thread-local variable instead).
let asyncLocalStorage = new AsyncLocalStorage();
let EMPTY_CONTEXT = {};
asyncLocalStorage.enterWith(EMPTY_CONTEXT);

// startSpan creates a span, makes its context the active store for the duration
// of lambda — so any spans started inside become its children — then ends the
// span and prints it.
export async function startSpan(name, lambda) {
  let ctx = asyncLocalStorage.getStore();
  let span = new Span(name, ctx, new Map());
  await asyncLocalStorage.run(span.getContext(), lambda, span);
  span.end();
  console.log(span);
}
Loading