Skip to content

Commit 338d315

Browse files
authored
Merge pull request #36 from saintparish4/fix/truth
feat: usage pipeline, SLOs, Helm/EKS, multi-replica runs; TLA+ specs
2 parents c2d54c5 + 9851dca commit 338d315

96 files changed

Lines changed: 7485 additions & 71 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/workflows/ci.yml‎

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,25 @@ jobs:
5959
- name: Validate Terraform and test the ALB exposure rules
6060
run: make tf-validate tf-test
6161

62+
# The SLO rules are only as good as their ability to fire: their unit tests
63+
# feed each burn and check the alert. promtool runs from the Prometheus
64+
# image compose already pins.
65+
- name: Check the SLO rules and their tests
66+
run: make slo-check
67+
68+
- name: Set up Helm
69+
uses: azure/setup-helm@v4
70+
with:
71+
version: v3.16.4
72+
73+
# Lint, render every template, schema-check the result (CRDs included), and
74+
# check the chart refuses what it must: a public plaintext ALB, `latest`.
75+
- name: Check the Helm chart
76+
run: |
77+
curl -fsSL https://github.com/yannh/kubeconform/releases/download/v0.6.7/kubeconform-linux-amd64.tar.gz \
78+
| tar -xz -C /usr/local/bin kubeconform
79+
make helm-check
80+
6281
# `cache: sbt` includes ~/.cache/coursier, where sbt keeps downloaded jars.
6382
# The hand-rolled cache this replaces saved ~/.ivy2/cache, which sbt stopped
6483
# using in 1.3, so every job fetched every dependency again.
@@ -73,7 +92,7 @@ jobs:
7392
uses: sbt/setup-sbt@v1
7493

7594
- name: Check formatting
76-
run: sbt scalafmtCheckAll
95+
run: sbt scalafmtCheckAll aggregator/scalafmtCheckAll
7796

7897
- name: Compile
7998
run: sbt compile
@@ -87,6 +106,11 @@ jobs:
87106
- name: Prove the correctness invariants can fail
88107
run: sbt loadSim/test
89108

109+
# Includes the usage aggregator's exactly-once test: lost answers, failed
110+
# reads, and two readers on the same shards.
111+
- name: Run the usage aggregator's tests
112+
run: sbt aggregator/test
113+
90114
# Separate from `unit` so a formatting or unit failure reports in about two
91115
# minutes instead of waiting behind TestContainers.
92116
integration:
@@ -174,6 +198,21 @@ jobs:
174198
env:
175199
DOCKER_BUILD_RECORD_UPLOAD: false
176200

201+
# The usage aggregator, cached under its own scope. The tag is the name
202+
# compose looks for, so `up --no-build` below fails loudly if they part.
203+
- name: Build usage aggregator image (layers cached between runs)
204+
uses: docker/build-push-action@v7
205+
with:
206+
builder: ${{ steps.buildx.outputs.name }}
207+
context: .
208+
file: aggregator.Dockerfile
209+
tags: ${{ env.COMPOSE_PROJECT_NAME }}-usage-aggregator
210+
load: true
211+
cache-from: type=gha,scope=usage-aggregator
212+
cache-to: type=gha,mode=max,scope=usage-aggregator
213+
env:
214+
DOCKER_BUILD_RECORD_UPLOAD: false
215+
177216
- name: Wait for LocalStack image
178217
run: |
179218
while [ ! -f "$RUNNER_TEMP/localstack-build.rc" ]; do sleep 1; done
@@ -224,6 +263,14 @@ jobs:
224263
- name: "Run correctness invariants (A: token-bucket non-over-issue, B: idempotency exactly-one-Created, C: quota non-over-admission, D: cross-tenant isolation)"
225264
run: sbt "loadSim/run --scenario correctness"
226265

266+
# Every event the service published during the run, committed to usage
267+
# once. It waits for the service's queues to drain and the aggregator to
268+
# catch up.
269+
- name: Usage pipeline — published events committed exactly once
270+
run: make usage-check
271+
env:
272+
WAIT_SECONDS: "180"
273+
227274
- name: Cleanup
228275
if: always()
229276
run: docker compose down -v

‎.gitignore‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ book/
5757
.env.*.local
5858
# Demo API keys written by scripts/deploy-demo.sh
5959
.demo-keys.env
60+
.eks-keys.env
6061
# Names the account's state bucket; written by scripts/bootstrap.sh
6162
terraform/backend.hcl
6263
# Only root configurations pin providers; a module's lock file comes from tf-test
@@ -112,3 +113,7 @@ base/
112113

113114
# Build-in-public drafts (unpublished)
114115
notes/
116+
117+
# TLC working files from running the specs by hand (scripts/check-specs.sh uses a temp dir)
118+
spec/states/
119+
spec/*_TTrace_*

‎Makefile‎

Lines changed: 39 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,9 @@ SMOKE_ID := $(shell date +%s 2>/dev/null || echo 0)
2424
NEED_SBT = @command -v sbt >/dev/null 2>&1 || { echo "Error: sbt not found in PATH."; echo " Install it: https://www.scala-sbt.org/download.html"; echo " Or skip sbt entirely and use Docker: make stack"; exit 1; }
2525

2626
.DEFAULT_GOAL := help
27-
.PHONY: help up up-clean down clean logs status run dev stack obs \
28-
fmt test test-it test-all smoke health correctness env-drift monitoring-check tf-validate tf-test
27+
.PHONY: help up up-clean down clean logs status run dev stack stack-scaled obs \
28+
fmt test test-it test-all smoke health correctness env-drift monitoring-check tf-validate tf-test spec \
29+
slo-check usage-check helm-check
2930

3031
help: ## Show this help
3132
@awk 'BEGIN { FS = ":.*##"; printf "Usage: make <target>\n" } \
@@ -47,6 +48,10 @@ stack: ## Start the whole stack in Docker (LocalStack + app) — no sbt needed
4748
$(COMPOSE) up -d --build --wait
4849
@echo "Gate is up at $(APP_URL). Follow it with 'make logs'."
4950

51+
stack-scaled: ## Start GATE_REPLICAS (default 3) replicas behind a load balancer on :8080
52+
$(COMPOSE) -f docker-compose.yml -f docker-compose.scale.yml up -d --build --wait
53+
@echo "$${GATE_REPLICAS:-3} replicas behind http://localhost:8080. Stop with: $(COMPOSE) -f docker-compose.yml -f docker-compose.scale.yml down -v"
54+
5055
obs: ## Start the stack plus Prometheus, Grafana and Jaeger
5156
$(COMPOSE) --profile obs up -d --build --wait
5257
@echo "Grafana http://localhost:3000 | Prometheus http://localhost:9090 | Jaeger http://localhost:16686"
@@ -90,10 +95,10 @@ fmt: ## Format all Scala sources (CI fails on unformatted code)
9095
$(NEED_SBT)
9196
sbt scalafmtAll
9297

93-
test: ## Run unit tests, and the load simulator's own tests
98+
test: ## Run unit tests, the load simulator's own tests, and the aggregator's
9499
$(NEED_SBT)
95100
sbt unitTest
96-
sbt loadSim/test
101+
sbt loadSim/test aggregator/test
97102

98103
test-it: ## Run integration tests (TestContainers — needs Docker, not LocalStack)
99104
$(NEED_SBT)
@@ -109,6 +114,9 @@ correctness: ## Check the correctness invariants (APP_URL=... to target a deploy
109114
@echo "Correctness invariants against $(APP_URL) (keys from API_KEY and FREE_API_KEY; not printed)"
110115
@API_KEY='$(API_KEY)' FREE_API_KEY='$(FREE_API_KEY)' sbt "loadSim/run --scenario correctness --url $(APP_URL)"
111116

117+
spec: ## Model-check the TLA+ specs in spec/ against spec/expected.txt (needs Java, ~6 min)
118+
bash scripts/check-specs.sh
119+
112120
##@ Probes
113121

114122
health: ## Print /health, /ready and a sample rate-limit status
@@ -142,8 +150,33 @@ smoke: ## Send 100 rate-limit checks and verify the X-RateLimit-* headers
142150
done; \
143151
echo "OK: 100 requests sent; X-RateLimit-Limit, -Remaining and -Reset all present."
144152

153+
usage-check: ## Check the usage aggregator committed every event the service published (stack running)
154+
bash scripts/check-usage-pipeline.sh
155+
145156
##@ Infrastructure
146157

158+
HELM_CHART = deploy/helm/gate
159+
helm-check: ## Lint and render the Helm chart, schema-check it, and check what it refuses
160+
@command -v helm >/dev/null 2>&1 || { echo "Error: helm not found in PATH."; exit 1; }
161+
@command -v kubeconform >/dev/null 2>&1 || { echo "Error: kubeconform not found in PATH."; exit 1; }
162+
helm lint $(HELM_CHART) -f $(HELM_CHART)/ci/test-values.yaml
163+
helm lint $(HELM_CHART) -f $(HELM_CHART)/ci/kind-values.yaml
164+
helm template gate $(HELM_CHART) -f $(HELM_CHART)/ci/test-values.yaml 2>/dev/null \
165+
| kubeconform -strict -summary -kubernetes-version 1.31.0 -schema-location default \
166+
-schema-location 'https://raw.githubusercontent.com/datreeio/CRDs-catalog/main/{{.Group}}/{{.ResourceKind}}_{{.ResourceAPIVersion}}.json'
167+
@for bad in "--set ingress.certificateArn= --set ingress.inboundCidrs={0.0.0.0/0}" \
168+
"--set gate.image.tag=latest" "--set gate.env.SECRETS_MANAGER_ENABLED=false"; do \
169+
if helm template gate $(HELM_CHART) -f $(HELM_CHART)/ci/test-values.yaml $$bad >/dev/null 2>&1; then \
170+
echo "FAIL: the chart rendered with $$bad"; exit 1; \
171+
fi; \
172+
done; echo "OK: the chart refuses a public plaintext ALB, a latest tag, and Secrets Manager off"
173+
174+
# promtool from the Prometheus image compose already uses, so nothing to install.
175+
PROMTOOL = docker run --rm -v "$(CURDIR)/observability/prometheus:/p" -w /p --entrypoint promtool prom/prometheus:v2.54.1
176+
slo-check: ## Check the SLO rules, and run their unit tests (needs Docker)
177+
$(PROMTOOL) check rules rules/slo.yml
178+
$(PROMTOOL) test rules tests/slo_test.yml
179+
147180
env-drift: ## Compare env vars across application.conf, compose and Terraform
148181
./scripts/check-env-drift.sh
149182

@@ -152,10 +185,11 @@ monitoring-check: ## Check every app metric the Terraform dashboard and alarms u
152185

153186
# -backend=false: validation needs no state, so it runs without AWS access or
154187
# the S3 bucket bootstrap.sh creates.
155-
tf-validate: ## Validate both Terraform roots (no AWS access needed)
188+
tf-validate: ## Validate the three Terraform roots (no AWS access needed)
156189
@command -v terraform >/dev/null 2>&1 || { echo "Error: terraform not found in PATH."; echo " Install it: https://www.terraform.io/downloads"; exit 1; }
157190
cd terraform && terraform init -backend=false -input=false >/dev/null && terraform validate
158191
cd terraform/bootstrap && terraform init -backend=false -input=false >/dev/null && terraform validate
192+
cd terraform/eks && terraform init -backend=false -input=false >/dev/null && terraform validate
159193

160194
tf-test: ## Plan the ALB's TLS and exposure rules against a mocked AWS provider
161195
@command -v terraform >/dev/null 2>&1 || { echo "Error: terraform not found in PATH."; exit 1; }

‎README.md‎

Lines changed: 45 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -64,9 +64,11 @@ deliberately out of scope for now.
6464
| Tenancy | Every storage key scoped to the authenticated client ([ADR-005](docs/adr/005-tenant-namespaced-storage-keys.md)), with cross-tenant tests and invariant D | | Hosted multi-tenant service: accounts, billing, a managed control plane |
6565
| Access | API keys from Secrets Manager, a permission per route, a per-task throttle per key and on unknown keys per source | Audit records for failed authentication and permission refusals | SSO and role management |
6666
| Failure behavior | Resilience stack on the rate-limit path; timeout and bulkhead on idempotency and quota; corrupt state fails closed and self-heals | | Serving decisions from a local cache during an outage |
67-
| Events and audit | Kinesis events at most once; `AUDIT` log lines | Firehose to S3 (Parquet), Glue, Athena, and 7-year retention: in Terraform, never deployed ([COMPLIANCE.md](docs/COMPLIANCE.md)) | |
67+
| Events and audit | Kinesis events at most once; `AUDIT` log lines; per-client, per-minute usage folded from the stream, each record once ([ADR-007](docs/adr/007-usage-aggregation-from-the-event-stream.md)) | Firehose to S3 (Parquet), Glue, Athena, and 7-year retention: in Terraform, never deployed ([COMPLIANCE.md](docs/COMPLIANCE.md)) | |
6868
| Consistency | One AWS Region is the consistency boundary | A written statement of the single-region semantics | Exact limits across Regions (global tables) |
69-
| Evidence | Invariants A-D in CI and against a Terraform deploy on AWS; LocalStack latency figures | A benchmark report on real AWS | |
69+
| Evidence | Invariants A-D in CI, against a Terraform deploy on AWS, and across three replicas behind a load balancer on LocalStack; LocalStack latency figures | A benchmark report on real AWS | |
70+
| Deployment | ECS Fargate by Terraform, run on AWS; a Helm chart and an EKS Terraform root, rehearsed on kind ([deploy/README.md](deploy/README.md)) | The first EKS deploy on AWS | |
71+
| Objectives | Written SLOs with burn-rate alerts and a Grafana dashboard ([SLO.md](docs/SLO.md)) | Revising the targets against a month of real traffic | |
7072
| Interfaces | HTTP API; a local demo dashboard (Terraform pins it off) | | A product web UI or admin console |
7173

7274
## Architecture
@@ -405,12 +407,17 @@ make obs # the stack plus Prometheus, Grafana and Jaeger
405407

406408
| Tool | URL | Notes |
407409
|---|---|---|
408-
| Grafana | <http://localhost:3000> | `admin` / `admin`, anonymous viewer enabled; dashboard "Gate — Rate Limiting & Quotas" |
409-
| Prometheus | <http://localhost:9090> | Scrapes the app every 5 s with the development `admin-api-key` |
410+
| Grafana | <http://localhost:3000> | `admin` / `admin`, anonymous viewer enabled; dashboards "Gate — Rate Limiting & Quotas" and "Gate — SLOs" |
411+
| Prometheus | <http://localhost:9090> | Scrapes every app replica and the usage aggregator every 5 s, and loads the SLO rules |
410412
| Jaeger | <http://localhost:16686> | Service `gate`; compose points the OTLP exporter at it |
411413

412-
The dashboard source is
413-
[`observability/grafana/dashboards/gate.json`](observability/grafana/dashboards/gate.json).
414+
The dashboard sources are in
415+
[`observability/grafana/dashboards`](observability/grafana/dashboards). The SLO
416+
dashboard reads the recording rules in
417+
[`observability/prometheus/rules/slo.yml`](observability/prometheus/rules/slo.yml),
418+
and [docs/SLO.md](docs/SLO.md) says what each objective promises. `make
419+
slo-check` runs the rules' own tests, which feed each kind of burn and check
420+
that its alert fires.
414421

415422
**Prometheus metrics** (`GET /metrics` with an `AdminMetrics` key)
416423

@@ -426,6 +433,15 @@ The dashboard source is
426433
| `gate_quota_tokens_admitted_total` | counter | `level`; tokens reserved by admitted quota checks, i.e. the pre-request estimate |
427434
| `gate_events_published_total` | counter | `event_type`; counted once a Kinesis put succeeds |
428435
| `gate_events_dropped_total` | counter | Kinesis events dropped after the retry |
436+
| `gate_http_requests_total` | counter | `route` (the template, never a key), `code`, `degraded`; every answer, which is what the availability SLO counts |
437+
| `gate_http_request_duration_seconds` | histogram | `route`; request to response headers, which is what the latency SLO counts |
438+
439+
The usage aggregator serves its own metrics on `:9095/metrics`:
440+
`gate_usage_records_total{event_type}`, `gate_usage_commits_total{result}`
441+
(`committed`, `fenced`, `error`), `gate_usage_millis_behind_latest{shard}`,
442+
`gate_usage_tokens_total{direction}` and `gate_usage_decisions_total{result}`.
443+
`make usage-check` (run in CI) compares what the service published with what
444+
the aggregator committed, type by type.
429445

430446
The bounded label combinations exist at zero from startup, so a quiet series
431447
reads 0 rather than "No data".
@@ -530,6 +546,17 @@ and they reach the load simulator through the environment: as command-line
530546
flags they were echoed by `make` and by sbt, so a run printed them. Source:
531547
[`LoadSim.scala`](loadSim/src/main/scala/LoadSim.scala).
532548

549+
### Across replicas
550+
551+
`make stack-scaled` runs three replicas over one LocalStack, behind a
552+
round-robin load balancer on `:8080`. They share only DynamoDB and Kinesis, as
553+
tasks behind an ALB do. On 20 October 2026 the scenario passed A-D against it
554+
with `errors=0` (run 1792536390218), the load split 2,418 / 2,413 / 2,412
555+
requests across the replicas, and the aggregator committed every one of the
556+
9,462 events published, once. That is one run on LocalStack, so it is evidence
557+
that the claim holds across processes, not a measurement of AWS
558+
([docs/evidence/2026-10-20-three-replicas](docs/evidence/2026-10-20-three-replicas/README.md)).
559+
533560
### On AWS
534561

535562
Two runs, each from a laptop over the internet against the Terraform-deployed
@@ -766,18 +793,29 @@ terraform apply -var-file=environments/dev.tfvars \
766793
terraform output api_endpoint
767794
```
768795

796+
### Kubernetes (EKS)
797+
798+
A Helm chart and an EKS Terraform root are prepared but not yet applied on
799+
AWS. [deploy/README.md](deploy/README.md) covers what they create, the
800+
deploy and teardown scripts, the cost (about $13 a day while up), and a local
801+
rehearsal on kind.
802+
769803
## Documentation
770804

771805
- [API reference](docs/API.md) — request and response schemas for every route
772806
- [Architecture](docs/ARCHITECTURE.md) — what the code does on each path, and why
773807
- [Performance](docs/PERFORMANCE.md) — the April LocalStack latency figures (historical) and the derived DynamoDB cost per decision
774808
- [Compliance notes](docs/COMPLIANCE.md) — what the audit trail records today, and what is planned
809+
- [Service level objectives](docs/SLO.md) — availability, latency, usage freshness and event delivery, with their alerts
810+
- [Deploying on Kubernetes](deploy/README.md) — the Helm chart and the EKS root
775811
- ADRs: [DynamoDB over Redis](docs/adr/001-dynamodb-over-redis.md),
776812
[hand-rolled circuit breaker](docs/adr/002-hand-rolled-circuit-breaker.md),
777813
[fire-and-forget event publishing](docs/adr/003-fire-and-forget-event-publishing.md),
778814
[OCC over pessimistic locking](docs/adr/004-occ-over-pessimistic-locking.md),
779815
[tenant-namespaced storage keys](docs/adr/005-tenant-namespaced-storage-keys.md),
780-
[idempotency claim token](docs/adr/006-idempotency-claim-token.md)
816+
[idempotency claim token](docs/adr/006-idempotency-claim-token.md),
817+
[usage aggregation from the event stream](docs/adr/007-usage-aggregation-from-the-event-stream.md),
818+
[Kubernetes as a second deployment target](docs/adr/008-kubernetes-as-a-second-deployment-target.md)
781819

782820
## Technology stack
783821

‎aggregator.Dockerfile‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# syntax=docker/dockerfile:1.7
2+
3+
# The usage aggregator (ADR-007). Built from the same build definition as the
4+
# service, but only its own sources go in.
5+
FROM eclipse-temurin:17-jdk-jammy AS builder
6+
7+
ARG SBT_VERSION=1.12.0
8+
RUN apt-get update && \
9+
apt-get install -y --no-install-recommends curl ca-certificates unzip && \
10+
curl -fsSL https://github.com/sbt/sbt/releases/download/v${SBT_VERSION}/sbt-${SBT_VERSION}.tgz | tar -xz -C /usr/local && \
11+
ln -s /usr/local/sbt/bin/sbt /usr/local/bin/sbt && \
12+
apt-get clean && rm -rf /var/lib/apt/lists/*
13+
14+
WORKDIR /build
15+
COPY project/ ./project/
16+
COPY build.sbt ./
17+
RUN sbt aggregator/update || true
18+
19+
COPY aggregator/src/main/ ./aggregator/src/main/
20+
RUN sbt aggregator/universal:stage
21+
22+
FROM eclipse-temurin:17-jre-jammy AS runtime
23+
24+
LABEL org.opencontainers.image.title="Gate usage aggregator" \
25+
org.opencontainers.image.description="Folds Gate's Kinesis event stream into per-client usage in DynamoDB" \
26+
org.opencontainers.image.version="0.1.0" \
27+
org.opencontainers.image.source="https://github.com/saintparish4/gate"
28+
29+
RUN apt-get update && \
30+
apt-get install -y --no-install-recommends curl ca-certificates && \
31+
apt-get clean && rm -rf /var/lib/apt/lists/* && \
32+
groupadd -r appuser && useradd -r -g appuser -u 1000 appuser
33+
34+
WORKDIR /app
35+
COPY --from=builder --chown=appuser:appuser /build/aggregator/target/universal/stage/ ./
36+
USER appuser
37+
EXPOSE 9095
38+
ENV JAVA_OPTS="-XX:+UseContainerSupport -XX:MaxRAMPercentage=75.0 -XX:+ExitOnOutOfMemoryError"
39+
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \
40+
CMD curl -f http://localhost:9095/health || exit 1
41+
ENTRYPOINT ["./bin/gate-usage-aggregator"]
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<configuration>
2+
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
3+
<encoder>
4+
<pattern>%d{HH:mm:ss.SSS} %-5level %logger{36} - %msg%n</pattern>
5+
</encoder>
6+
</appender>
7+
8+
<!-- The AWS SDK and Netty log every request, response and wire-level hex dump
9+
at DEBUG. Without this the shipped image writes hundreds of thousands of
10+
lines an hour and buries the application's own logs. -->
11+
<logger name="software.amazon.awssdk" level="WARN"/>
12+
<logger name="io.netty" level="WARN"/>
13+
<logger name="org.http4s" level="INFO"/>
14+
15+
<root level="${LOG_LEVEL:-INFO}">
16+
<appender-ref ref="STDOUT"/>
17+
</root>
18+
</configuration>

0 commit comments

Comments
 (0)