惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Vercel News
Vercel News
The GitHub Blog
The GitHub Blog
博客园 - 【当耐特】
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Recent Announcements
Recent Announcements
D
Docker
GbyAI
GbyAI
酷 壳 – CoolShell
酷 壳 – CoolShell
WordPress大学
WordPress大学
The Cloudflare Blog
雷峰网
雷峰网
A
About on SuperTechFans
小众软件
小众软件
博客园 - Franky
博客园 - 聂微东
F
Full Disclosure
大猫的无限游戏
大猫的无限游戏
C
Check Point Blog
MongoDB | Blog
MongoDB | Blog
G
Google Developers Blog
Microsoft Azure Blog
Microsoft Azure Blog
U
Unit 42
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
V
V2EX
Engineering at Meta
Engineering at Meta
宝玉的分享
宝玉的分享
aimingoo的专栏
aimingoo的专栏
量子位
P
Proofpoint News Feed
Hugging Face - Blog
Hugging Face - Blog
博客园_首页
罗磊的独立博客
Martin Fowler
Martin Fowler
D
DataBreaches.Net
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
S
Secure Thoughts
Project Zero
Project Zero
L
LangChain Blog
阮一峰的网络日志
阮一峰的网络日志
C
Cybersecurity and Infrastructure Security Agency CISA
T
Tailwind CSS Blog
S
Schneier on Security
Blog — PlanetScale
Blog — PlanetScale
The Hacker News
The Hacker News
Spread Privacy
Spread Privacy
Security Latest
Security Latest
NISL@THU
NISL@THU
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
C
CXSECURITY Database RSS Feed - CXSecurity.com
J
Java Code Geeks

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
SwiftDeploy: Building a Self-Governing Deployment Tool with OPA, Prometheus, and a Single YAML File
Felix Gogoda · 2026-05-07 · via DEV Community

Series: Firstly,, I built the engine (manifest → rendered nginx + compose, gated lifecycle). Then I added the eyes (Prometheus /metrics) and the brain (OPA policy sidecar). This post covers the complete journey.


Table of Contents

  1. What problem are we solving?
  2. The single source of truth
  3. Architecture overview
  4. The engine: writing its own infrastructure
  5. The eyes: Prometheus instrumentation
  6. The brain: OPA policy sidecar
  7. Gated lifecycle: deploy and promote
  8. The live dashboard: swiftdeploy status
  9. The memory: swiftdeploy audit
  10. Injecting chaos and watching the gates fire
  11. Lessons learned

1. What problem are we solving?

Most deployment tooling separates three concerns that should be tightly coupled:

Concern Typical state
Configuration Scattered across Compose files, env files, CI yamls
Policy Implicit — "the person who ran the deploy knew it was safe"
Observability A separate system bolted on afterward

SwiftDeploy collapses all three into one loop: a single manifest.yaml drives rendered infrastructure, feeds thresholds to OPA at deploy/promote time, and tells the API how long to keep rolling-window metrics.


2. The single source of truth

Every value that changes between environments lives in one file:

services:
  image: swiftdeploy-hng14-api:latest
  port: 3000
  mode: stable           # swiftdeploy promote rewrites this in-place

nginx:
  image: nginx:1.27-alpine
  port: 8080
  proxy_timeout: 60s

network:
  name: swiftdeploy-net
  driver_type: bridge

metadata:
  version: "1.0.0"
  service_name: swiftdeploy-api
  contact: "you@example.com"
  deployed_by: "swiftdeploy"

compose_project: swiftdeploy

policy:
  thresholds:          # fed to OPA as input.thresholds — never hardcoded in .rego
    min_disk_free_gb: 10
    min_mem_available_gb: 1
    max_cpu_load: 2.0
    max_error_rate_percent: 1
    max_p99_latency_ms: 500
    metrics_window_seconds: 30
  opa:
    image: openpolicyagent/opa:0.69.0
    host_port: 9182

Enter fullscreen mode Exit fullscreen mode

The CLI (swiftdeploy) reads this file, renders nginx.conf and docker-compose.yml via Jinja2, and never asks you to edit either generated file.


3. Architecture overview

Architecture Diagram

Key isolation properties

Property How it is enforced
OPA not reachable via Nginx OPA bound to 127.0.0.1:9182 only; Nginx only proxies to api
API port not public expose: only — no ports: mapping on the api service
No decision logic in CLI CLI POSTs context, reads back allowed + checks[]; all logic lives in Rego
Thresholds not in Rego .rego files reference only input.thresholds.* — values come from manifest.yaml

4. The engine: writing its own infrastructure

swiftdeploy init parses manifest.yaml with PyYAML and feeds the result into two Jinja2 templates:

  • templates/nginx.conf.j2 — upstream block, proxy timeouts, error pages, access log format, X-Deployed-By header, temp paths under /tmp so the nginx user can write
  • templates/docker-compose.yml.j2 — three services (api, nginx, opa), security hardening on api (cap_drop: ALL, no-new-privileges, user: 1000:1000), healthcheck, named volume

The METRICS_WINDOW_SECONDS env var is written from policy.thresholds.metrics_window_seconds — the same value that OPA uses as the SLO window — so the API's rolling gauge and the Rego rule are always in sync.

swiftdeploy validate runs five pre-flight checks before any container starts:

  1. manifest.yaml exists and parses
  2. All required fields are non-empty (including the full policy block)
  3. docker image inspect <services.image> succeeds
  4. nginx.port is free on the host
  5. Rendered nginx.conf passes nginx -t inside a throwaway container

5. The eyes: Prometheus instrumentation

The FastAPI app exposes GET /metrics in Prometheus text format. There are two layers of middleware:

request in
    │
    ▼
[chaos middleware]       <- injects slow/error in canary mode (skipped on POST /chaos)
    │
    ▼
[prometheus middleware]  <- times the full stack including chaos delay
    │
    ▼
route handler

Enter fullscreen mode Exit fullscreen mode

Standard metrics:

http_requests_total{method, path, status_code}
http_request_duration_seconds{method, path}   <- histogram, standard buckets
app_uptime_seconds
app_mode                                       <- 0=stable, 1=canary
chaos_active                                   <- 0=none, 1=slow, 2=error

Enter fullscreen mode Exit fullscreen mode

Rolling-window gauges (what OPA queries for canary SLOs):

swiftdeploy_window_requests_total       <- count of requests in last N seconds
swiftdeploy_window_errors_total         <- 5xx count in window
swiftdeploy_window_p99_latency_seconds  <- in-process P99 over same window

Enter fullscreen mode Exit fullscreen mode

The window is a collections.deque. On every request, a (timestamp, duration, is_error) tuple is appended, stale entries are evicted, and the three gauges are recomputed — P99 via sorted index. No external TSDB needed; the gauge values are always current when scraped.


6. The brain: OPA policy sidecar

Why OPA instead of if-statements in the CLI?

The key constraint: the CLI must not make any allow/deny decision itself. With if-statements in Python, the logic and the thresholds are co-located with the operator tool. With OPA:

  • Thresholds live only in manifest.yaml (one place to change for all environments)
  • Policy logic lives only in .rego (auditable, testable with opa test)
  • The CLI is a dumb messenger — it assembles context, posts it, reads back a decision object

Domain isolation

Each policy domain owns exactly one question and one data shape:

Domain Question Input shape
swiftdeploy.infrastructure Is the host healthy enough to deploy? {phase, host: {disk_free_gb, cpu_load_1m, mem_available_gb}, thresholds}
swiftdeploy.canary Is the canary safe enough to promote? {phase, promotion_target, metrics: {error_rate_percent, p99_latency_ms, window_seconds}, thresholds}

A change to the infrastructure rules never touches canary/policy.rego and vice versa.

Decision structure (never a bare boolean)

Every decision document carries per-rule checks:

decision := {
    "allowed": count(reasons) == 0,
    "domain": "infrastructure",
    "phase": input.phase,
    "reasons": sort([r | reasons[r]]),
    "checks": [
        {"rule_id": "infra_disk_free_minimum",
         "passed": disk_ok, "detail": disk_detail},
        {"rule_id": "infra_cpu_load_maximum",
         "passed": cpu_ok,  "detail": cpu_detail},
        {"rule_id": "infra_memory_available_minimum",
         "passed": mem_ok,  "detail": mem_detail},
    ],
    ...
}

Enter fullscreen mode Exit fullscreen mode

The CLI iterates checks[] directly for the live status display — it never infers pass/fail itself.

Failure handling

Every distinct failure mode has a unique failure_kind and a human-readable message:

Situation failure_kind Message shown to operator
OPA container not started opa_connection_refused "Start with: docker compose up -d opa"
OPA slow to respond opa_timeout "OPA request timed out (read)"
OPA returns non-JSON opa_bad_json includes raw snippet
OPA returns no result key opa_no_result includes raw snippet
psutil not installed host_stats_unavailable install instructions

None of these paths crash or hang the CLI.


7. Gated lifecycle: deploy and promote

swiftdeploy deploy

init (render nginx.conf + docker-compose.yml)
    |
    v
docker compose up -d opa
    |
    v
wait_opa_ready (polls /health, up to 75s)
    |
    v
collect_host_stats --> POST /v1/data/swiftdeploy/infrastructure/decision
                                |
                      +---------+-----------+
                      |                     |
                 allowed: false        allowed: true
                      |                     |
               print FAIL checks    docker compose up --build -d
               exit(1)                      |
               (no stack up)                v
                                   poll GET /healthz via nginx

Enter fullscreen mode Exit fullscreen mode

Real output on a day when CPU spiked:

Policy compliance (infrastructure (pre-deploy)):
  [PASS] infra_disk_free_minimum: PASS: disk free 66.57 GB meets minimum 10.00 GB.
  [FAIL] infra_cpu_load_maximum: FAIL: CPU load 2.52 exceeds maximum 2.00.
  [PASS] infra_memory_available_minimum: PASS: memory available 8.10 GB meets minimum 1.00 GB.
[swiftdeploy] POLICY VIOLATION - deploy blocked (infrastructure).
  - Policy violation: CPU load (2.52) exceeds maximum allowed (2.00).

Enter fullscreen mode Exit fullscreen mode

The stack never started. No compose up ran. The OPA sidecar is the only container that exists at this point.

swiftdeploy promote canary

Before rewriting manifest.yaml, the CLI:

  1. Scrapes GET /metrics via Nginx
  2. Derives error_rate_percent and p99_latency_ms from the rolling-window gauges
  3. Posts to swiftdeploy/canary/decision with promotion_target: "canary"
  4. On allowed: false — exits without touching manifest.yaml

Promoting to stable takes a different Rego branch that skips SLO evaluation entirely (there are no "canary metrics" to check when moving away from canary).


8. The live dashboard: swiftdeploy status

python swiftdeploy status --interval 2 -n 5

Enter fullscreen mode Exit fullscreen mode

Each sample scrapes /healthz, /metrics, and both OPA domains independently, then prints:

=== 2026-05-06T18:16:17Z  mode='stable'  req/s~=3.2100 ===
  window(30s): errors=2/41 err_rate=4.8780% p99=312.45ms
  chaos_active: 2 (error)
  Policy compliance (infrastructure (pre-deploy)):
    [PASS] infra_disk_free_minimum: PASS: disk free 66.62 GB meets minimum 10.00 GB.
    [PASS] infra_cpu_load_maximum: PASS: CPU load 0.89 is within maximum 2.00.
    [PASS] infra_memory_available_minimum: PASS: memory available 11.38 GB meets minimum 1.00 GB.
  OPA [infrastructure (pre-deploy)] aggregate: ALLOW
  Policy compliance (canary (hypothetical promote->canary)):
    [FAIL] canary_error_rate_window: FAIL: error rate 4.8780% exceeds maximum 1.0000% over 30 s window.
    [PASS] canary_p99_latency_window: PASS: P99 latency 312.45 ms within maximum 500.00 ms over 30 s window.
  OPA [canary (hypothetical promote->canary)] aggregate: DENY

Enter fullscreen mode Exit fullscreen mode

Every sample is appended as one JSON line to history.jsonl including chaos_active, window metrics, and both OPA snapshots with their checks[].


9. The memory: swiftdeploy audit

python swiftdeploy audit

Enter fullscreen mode Exit fullscreen mode

audit_report.md is generated from history.jsonl with four sections:

  • Summary — sample count, denial count, transport error count
  • Timeline events — mode transitions and chaos transitions detected by diffing consecutive records
  • Violations — every allowed: false from any domain, with reasons
  • Recent timeline — last 25 samples in a table with Chaos column and per-domain OPA status

Example timeline events table:

Time (UTC) Event Detail
2026-05-06T18:17:02Z chaos_change none -> error
2026-05-06T18:20:14Z mode_change stable -> canary
2026-05-06T18:23:41Z chaos_change error -> none

10. Injecting chaos and watching the gates fire

In canary mode, POST /chaos arms the process-global chaos state:

# arm 40% error rate
curl -s -X POST http://127.0.0.1:8080/chaos \
  -H "Content-Type: application/json" \
  -d '{"mode": "error", "rate": 0.40}'

# arm 2-second slow response on every request
curl -s -X POST http://127.0.0.1:8080/chaos \
  -H "Content-Type: application/json" \
  -d '{"mode": "slow", "duration": 2.0}'

# recover
curl -s -X POST http://127.0.0.1:8080/chaos \
  -H "Content-Type: application/json" \
  -d '{"mode": "recover"}'

Enter fullscreen mode Exit fullscreen mode

With 40% error rate active and traffic flowing, the status dashboard shows canary_error_rate_window FAIL within one 30-second window. Attempting swiftdeploy promote canary while this is true produces:

Swiftdeploy promote canary blocked by OPA canary safety policy

  Policy compliance (canary (pre-promote)):
    [FAIL] canary_error_rate_window: FAIL: error rate 50.8772% exceeds maximum 1.0000% over 30 s window.
    [PASS] canary_p99_latency_window: PASS: P99 latency 1.96 ms within maximum 500.00 ms over 30 s window.
[swiftdeploy] POLICY VIOLATION - promote blocked (canary safety policy).
  - Policy violation: error rate (50.8772%) exceeds maximum (1.0000%) over last 30 seconds.

Enter fullscreen mode Exit fullscreen mode

manifest.yaml is not modified. After recovering and waiting for the window to clear, the same command succeeds.


11. Lessons learned

1. One source of truth is a forcing function, not a convenience.
When thresholds are only in manifest.yaml and nowhere else, you cannot accidentally have a tighter limit in the Rego file than in your runbook. The manifest is the runbook.

2. OPA's value is in the separation, not the language.
Rego has a learning curve. The real benefit is that a policy change is a PR to a .rego file with a clear audit trail, not a diff buried inside deployment tooling.

3. Rolling-window gauges beat querying a TSDB for CLI gates.
The alternative — running Prometheus Server just to evaluate a PromQL expression at deploy time — adds infrastructure for something the app can compute in-process with a deque. The CLI scrapes the gauge, not the raw counter buckets.

4. Failure modes are the real API.
The most useful work in this project was not the happy path. It was giving every OPA transport failure a distinct failure_kind and message so an operator at 2am knows immediately whether OPA is down, slow, returning bad JSON, or returning a policy decision that says no.

5. Windows CPU approximation is not Linux load average.
The infrastructure policy uses 1-minute load average on Linux. On Windows, psutil.cpu_percent x logical_cpus spikes aggressively during container start. The gate working correctly the first time it fired was both the most satisfying and most annoying moment of the project.


Repository

github.com/Trojanhorse7/swift-deploy