diff --git a/CLAUDE.md b/CLAUDE.md index 3c9886e..832d1f1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -10,7 +10,8 @@ - Browser-based DevOps simulator for beginners. Everything is simulated; nothing runs real commands. - `backend/`: Rails 8.1 API-only app (SQLite, Action Cable). The engine lives in `backend/lib/sim/`: `world.rb` (state), `shell.rb` (command interpreter), `engine.rb` (time + objectives), - `scenarios/*.rb` (one chapter each, listed in `scenarios.rb`). + `scenarios/*.rb` (one chapter each, listed in `scenarios.rb`). Delivery chapters use `repo.rb` (fake git), + `delivery_commands.rb` (git, gh, bin/rails test, deploy), `delivery_ci.rb` and `delivery_world.rb`. - `frontend/`: React + TypeScript (Vite), xterm.js terminal. Play screen is `src/components/PlayScreen.tsx`. - UI follows Royal's UI style rules (Geist, motion, accessibility) with this app's own "System map" theme in `frontend/src/styles.css`. Don't reuse the helpdesk look (dark sidebar + blue pill). diff --git a/README.md b/README.md index 06b7ece..97138a5 100644 --- a/README.md +++ b/README.md @@ -9,13 +9,13 @@ so you can't break anything. | # | Topic | Chapter | Status | |---|------------|------------------------|-------------| -| 1 | GitHub | Open your first PR | planned | -| 2 | CI | The build is red | planned | -| 3 | Deploy | Roll back a bad release| planned | +| 1 | GitHub | Open your first pull request | playable | +| 2 | CI | Works on my machine | playable | +| 3 | Deploy | The health check is lying | playable | | 4 | Linux | The disk is full | playable | | 5 | Monitoring | Memory is climbing | playable | -Each chapter can be played on its own. +Each chapter can be played on its own, and each ends with a short note on the real incident or practice it's based on. ## Running it diff --git a/backend/app/presenters/run_presenter.rb b/backend/app/presenters/run_presenter.rb index f23c869..beebe46 100644 --- a/backend/app/presenters/run_presenter.rb +++ b/backend/app/presenters/run_presenter.rb @@ -15,7 +15,7 @@ def full scenario: { key: scenario.key, title: scenario.title, topic: scenario.topic, chapter: scenario.chapter, summary: scenario.summary, briefing: scenario.briefing, - focus_metric: scenario.focus_metric + focus_metric: scenario.focus_metric, real_world: scenario.real_world } }.merge(live) end diff --git a/backend/lib/sim/delivery_ci.rb b/backend/lib/sim/delivery_ci.rb new file mode 100644 index 0000000..ce3d391 --- /dev/null +++ b/backend/lib/sim/delivery_ci.rb @@ -0,0 +1,29 @@ +module Sim + # Fake GitHub Actions: a run takes two ticks, then runs the tests on the + # pushed commit in a clean environment (only the workflow's env vars). + module DeliveryCi + RUN_TICKS = 2 + + module_function + + def advance(world, scenario) + repo = Repo.new(world) + repo.prs.each do |pr| + pr["runs"].each do |run| + next unless run["status"] == "in_progress" && world.clock - run["started"] >= RUN_TICKS + files = repo.snapshot(run["sha"]) + passed, lines = DeliveryWorld.run_tests(files, DeliveryWorld.ci_env(files)) + run["status"] = "completed" + run["conclusion"] = passed ? "success" : "failure" + run["tests"] = 2 + run["log"] = [ "Run actions/checkout@v7", "Run ruby/setup-ruby@v1", "Ruby 3.3 installed", + "Run bin/rails test", *lines.map { |l| " #{l}" } ] + run["log"] << "Error: Process completed with exit code 1." unless passed + world.data["messages"] << (passed ? + { "kind" => "resolved", "text" => "[CI] PR ##{pr['number']}: all checks passed." } : + { "kind" => "alert", "text" => "[CI] PR ##{pr['number']}: test failed. Run `gh pr checks` for details." }) + end + end + end + end +end diff --git a/backend/lib/sim/delivery_commands.rb b/backend/lib/sim/delivery_commands.rb new file mode 100644 index 0000000..d5dad21 --- /dev/null +++ b/backend/lib/sim/delivery_commands.rb @@ -0,0 +1,292 @@ +module Sim + # Shell commands for the delivery chapters: git, the GitHub CLI (gh), + # running the test suite, and a small deploy tool. Mixed into Shell. + module DeliveryCommands + private + + def repo = (@repo ||= Repo.new(world)) + def repo? = world.data.key?("repo") && world.current_host == Repo::HOST + + def in_repo + return fail("fatal: not a git repository (or any of the parent directories): .git", 128) unless repo? && repo.inside?(world.session["cwd"]) + yield + end + + # --- git ---------------------------------------------------------------- + + def cmd_git(args) + return fail("bash: git: command not found", 127) unless world.data.key?("repo") + sub, *rest = args + return ok("usage: git \n\nTry: status, branch, switch -c, add, commit -m, log, diff, push, revert") unless sub + in_repo do + scenario.on_inspect(world, :git, sub) + case sub + when "status" then git_status + when "branch" then git_branch(rest) + when "checkout", "switch" then git_switch(rest) + when "add" then git_add(rest) + when "commit" then git_commit(rest) + when "log" then git_log(rest) + when "diff" then git_diff(rest) + when "push" then git_push(rest) + when "pull", "fetch" then ok("Already up to date.") + when "revert" then git_revert(rest) + when "restore" then git_restore(rest) + else fail("git: '#{sub}' is not a git command in this simulator. Try `git` for a list.") + end + end + end + + def git_status + c = repo.changes + lines = [ "On branch #{repo.branch}" ] + pushed = world.data["repo"]["remote"][repo.branch] + lines << (pushed == repo.head_sha ? "Your branch is up to date with 'origin/#{repo.branch}'." : pushed ? "Your branch is ahead of 'origin/#{repo.branch}'." : "Your branch is not on GitHub yet (git push -u origin #{repo.branch}).") + lines << "" + if c[:staged].any? + lines += [ "Changes to be committed:" ] + c[:staged].map { |p| "\tmodified: #{p}" } + [ "" ] + end + if c[:unstaged].any? + lines += [ "Changes not staged for commit:", ' (use "git add ..." to update what will be committed)' ] + + c[:unstaged].map { |p| "\t#{repo.working_tree.key?(p) ? 'modified' : 'deleted'}: #{p}" } + [ "" ] + end + if c[:untracked].any? + lines += [ "Untracked files:" ] + c[:untracked].map { |p| "\t#{p}" } + [ "" ] + end + lines << "nothing to commit, working tree clean" if c.values.all?(&:empty?) + ok(lines.join("\n").rstrip) + end + + def git_branch(rest) + return git_switch([ "-c", rest.first ]) if rest.first && !rest.first.start_with?("-") + ok(world.data["repo"]["branches"].keys.sort.map { |b| b == repo.branch ? "* #{b}" : " #{b}" }.join("\n")) + end + + def git_switch(rest) + create = rest.delete("-b") || rest.delete("-c") + name = rest.first + return fail("usage: git switch -c ") unless name + branches = world.data["repo"]["branches"] + if create + return fail("fatal: a branch named '#{name}' already exists") if branches.key?(name) + return fail("fatal: '#{name}' is not a valid branch name (no spaces)") if name.match?(/\s/) + branches[name] = repo.head_sha + world.data["repo"]["branch"] = name + return ok("Switched to a new branch '#{name}'") + end + return fail("error: pathspec '#{name}' did not match any branch. Use `git switch -c #{name}` to create it.") unless branches.key?(name) + c = repo.changes + return fail("error: you have uncommitted changes. Commit them first.") if (c[:staged] + c[:unstaged]).any? + world.data["repo"]["branch"] = name + repo.write_tree(repo.snapshot) + ok("Switched to branch '#{name}'") + end + + def git_add(rest) + return fail("Nothing specified, nothing added.\nhint: Maybe you wanted to say 'git add .'?") if rest.empty? + return (repo.stage_all || ok("")) && ok("") if rest.include?(".") || rest.include?("-A") || rest.include?("--all") + paths = rest.map { |r| repo.rel(world.resolve(r)) } + missing = paths.reject { |p| repo.working_tree.key?(p) || repo.index.key?(p) } + return fail("fatal: pathspec '#{missing.first}' did not match any files") if missing.any? + repo.stage(paths) + ok("") + end + + def git_commit(rest) + repo.stage_all if rest.delete("-a") || rest.delete("-am")&.then { rest.unshift("-m") } + i = rest.index("-m") + message = i && rest[i + 1] + return fail("Aborting commit: write a message with -m, for example:\n git commit -m \"Add free shipping banner\"") if message.to_s.strip.empty? + return fail("On branch #{repo.branch}\nnothing to commit (use \"git add\" to stage changes)") if repo.changes[:staged].empty? + files = repo.changes[:staged].size + sha = repo.commit!(message) + scenario.on_commit(world, sha) + ok("[#{repo.branch} #{sha}] #{message}\n #{files} file#{'s' unless files == 1} changed") + end + + def git_log(rest) + entries = repo.log.first(rest.include?("-1") ? 1 : 10) + if rest.include?("--oneline") + ok(entries.map { |sha, c| "#{sha} #{c['message']}" }.join("\n")) + else + ok(entries.map { |sha, c| "commit #{sha}\nAuthor: #{c['author']}\n\n #{c['message']}\n" }.join("\n").rstrip) + end + end + + def git_diff(rest) + ref = rest.find { |r| !r.start_with?("-") } + if ref + sha = world.data["repo"]["branches"][ref] || world.data["repo"]["commits"].keys.find { |s| s.start_with?(ref) } + return fail("fatal: ambiguous argument '#{ref}': unknown revision") unless sha + return ok(repo.diff(repo.snapshot(sha), repo.working_tree)) + end + out = rest.include?("--staged") || rest.include?("--cached") ? repo.diff(repo.snapshot, repo.index) : repo.diff(repo.index, repo.working_tree) + ok(out) + end + + def git_restore(rest) + paths = rest.reject { |r| r.start_with?("-") }.map { |r| repo.rel(world.resolve(r)) } + paths.each { |p| repo.index[p] ? world.write_file(repo.abs(p), repo.index[p], Repo::HOST) : nil } + ok("") + end + + def git_push(rest) + name = rest.reject { |r| r.start_with?("-") || r == "origin" }.first || repo.branch + return fail("error: src refspec #{name} does not match any") unless world.data["repo"]["branches"].key?(name) + remote = world.data["repo"]["remote"] + was = remote[name] + return ok("Everything up-to-date") if was == repo.head_sha(name) + remote[name] = repo.head_sha(name) + scenario.on_push(world, name) + lines = [ "To github.com:shop/shop.git", was ? " #{was}..#{remote[name]} #{name} -> #{name}" : " * [new branch] #{name} -> #{name}" ] + if (pr = repo.pr_for(name)) + repo.start_run!(pr) + lines << "CI started for pull request ##{pr['number']}. Check it with `gh pr checks`." + elsif name != "main" + lines += [ "", "remote: Create a pull request for '#{name}' on GitHub by running:", "remote: gh pr create --title \"...\"" ] + end + ok(lines.join("\n")) + end + + def git_revert(rest) + sha = rest.reject { |r| r.start_with?("-") }.first + return fail("usage: git revert ") unless sha + target = world.data["repo"]["commits"].keys.find { |s| s.start_with?(sha) } + return fail("fatal: bad revision '#{sha}'") unless target + parent = repo.commit(target)["parent"] + reverted = repo.snapshot.dup + (repo.snapshot(target).keys | repo.snapshot(parent).keys).each do |p| + next if repo.snapshot(target)[p] == repo.snapshot(parent)[p] + repo.snapshot(parent)[p] ? reverted[p] = repo.snapshot(parent)[p] : reverted.delete(p) + end + repo.write_tree(reverted) + repo.stage_all + message = "Revert \"#{repo.commit(target)['message']}\"" + new_sha = repo.commit!(message) + scenario.on_commit(world, new_sha) + ok("[#{repo.branch} #{new_sha}] #{message}") + end + + # --- GitHub CLI ------------------------------------------------------- + + def cmd_gh(args) + return fail("bash: gh: command not found", 127) unless world.data.key?("repo") + area, action, *rest = args + in_repo do + scenario.on_inspect(world, :gh, "#{area} #{action}") + case [ area, action ] + in [ "pr", "create" ] then gh_pr_create(rest) + in [ "pr", "list" ] then gh_pr_list + in [ "pr", "view" ] then gh_pr_view + in [ "pr", "checks" ] then gh_pr_checks + in [ "run", "view" ] then gh_run_view(rest) + in [ "run", "list" ] then gh_pr_checks + else ok("Work with GitHub from the terminal. Try:\n gh pr create --title \"...\"\n gh pr view\n gh pr checks\n gh run view --log-failed") + end + end + end + + def gh_pr_create(rest) + name = repo.branch + return fail("You're on main. Make a branch first: git switch -c my-change") if name == "main" + remote = world.data["repo"]["remote"][name] + return fail("aborted: you must first push the current branch to GitHub, for example:\n git push -u origin #{name}") unless remote + return fail("a pull request for branch \"#{name}\" already exists:\n #{pr_url(repo.pr_for(name))}") if repo.pr_for(name) + i = rest.index("--title") || rest.index("-t") + title = (i && rest[i + 1]) || (rest.include?("--fill") && repo.commit(remote)["message"]) + return fail("Give your pull request a title:\n gh pr create --title \"Add free shipping banner\"") if title.to_s.strip.empty? + pr = repo.open_pr!(title, name) + scenario.on_pr(world, pr) + ok("Creating pull request for #{name} into main in shop/shop\n\n#{pr_url(pr)}\n\nCI is running. Check it with `gh pr checks`.") + end + + def pr_url(pr) = "https://github.com/shop/shop/pull/#{pr['number']}" + + def current_pr = repo.pr_for(repo.branch) || repo.prs.reverse.find { |p| p["state"] == "open" } + + def gh_pr_list + open = repo.prs.select { |p| p["state"] == "open" } + return ok("no open pull requests in shop/shop") if open.empty? + ok(open.map { |p| "##{p['number']} #{p['title']} #{p['branch']} #{run_label(repo.latest_run(p))}" }.join("\n")) + end + + def gh_pr_view + pr = current_pr or return fail("no pull requests found for branch \"#{repo.branch}\"") + run = repo.latest_run(pr) + ok([ "#{pr['title']} ##{pr['number']}", "Open · you wants to merge #{pr['branch']} into main".sub("you wants", "you want"), + "", "Checks: #{run_label(run)}", "", pr_url(pr) ].join("\n")) + end + + def run_label(run) + return "no checks" unless run + return "running..." if run["status"] == "in_progress" + run["conclusion"] == "success" ? "all checks passed" : "1 failing check" + end + + def gh_pr_checks + pr = current_pr or return fail("no pull requests found for branch \"#{repo.branch}\"") + run = repo.latest_run(pr) or return ok("no checks reported on the '#{pr['branch']}' branch") + line = + case run["status"] + when "in_progress" then "* test running (run #{run['id']})" + else run["conclusion"] == "success" ? "✓ test passed (run #{run['id']})" : "X test failed (run #{run['id']})" + end + code = run["conclusion"] == "failure" ? 1 : 0 + Shell::Result.new(output: "#{run_label(run).capitalize}\n\n#{line}\n\nSee the log with: gh run view #{run['id']} --log-failed", exit_code: code) + end + + def gh_run_view(rest) + pr = current_pr or return fail("no runs found") + id = rest.find { |r| r.match?(/\A\d+\z/) }&.to_i + run = id ? repo.prs.flat_map { |p| p["runs"] }.find { |r| r["id"] == id } : repo.latest_run(pr) + return fail("could not find run #{id}") unless run + return ok("Run #{run['id']} is still in progress. Try again in a moment.") if run["status"] == "in_progress" + return ok("✓ Run #{run['id']} passed. All #{run['tests'] || 'the'} tests are green.") if run["conclusion"] == "success" + ok(([ "X test · run #{run['id']} · failed", "" ] + run["log"]).join("\n")) + end + + # --- tests ------------------------------------------------------------ + + def cmd_rails(args) + return fail("bash: rails: command not found", 127) unless world.data.key?("repo") + return ok("Usage: bin/rails test") unless args.first == "test" + in_repo do + return fail("bin/rails: run this from the project root (cd ~/shop)") unless world.session["cwd"] == repo.root + passed, lines = scenario.run_tests(world, repo.working_tree) + scenario.on_inspect(world, :tests, passed ? "pass" : "fail") + Shell::Result.new(output: lines.join("\n"), exit_code: passed ? 0 : 1) + end + end + + # --- deploys ------------------------------------------------------------ + + def cmd_deploy(args) + d = world.data["deploy"] + return fail("bash: deploy: command not found", 127) unless d + sub, *rest = args + scenario.on_inspect(world, :deploy, sub.to_s) + case sub + when "status" + r = release(d["current"]) + ok("Production: shop.example\nCurrent release: #{r['id']} (#{r['sha']} \"#{r['message']}\")\nDeployed: #{world.timestamp(r['at'])} by #{r['by']}\nHealth check: #{scenario.http(world, 'https://shop.example/health')&.first}") + when "releases", "history" + ok(([ "RELEASE COMMIT DEPLOYED BY MESSAGE" ] + d["releases"].reverse.map { |r| + format("%-8s %-8s %-17s %-7s %s%s", r["id"], r["sha"], world.timestamp(r["at"])[0, 15], r["by"], r["message"], r["id"] == d["current"] ? " <- live" : "") + }).join("\n")) + when "logs" + ok(Array(d["logs"]).last(rest.include?("-n") ? rest[rest.index("-n") + 1].to_i : 12).join("\n")) + when "rollback" + target = rest.first || d["releases"][-2]&.dig("id") + r = release(target) or return fail("deploy: no release called #{target}. See `deploy releases`.") + return ok("#{r['id']} is already live.") if r["id"] == d["current"] + d["current"] = r["id"] + scenario.on_rollback(world, r) + ok("Rolling back production to #{r['id']} (#{r['sha']})...\n ✓ Switched web-01 to #{r['id']}\n ✓ Restarted shop-web\nDone. #{r['id']} is live.") + else + ok("deploy: ship and roll back the shop.\n\n deploy status what is live right now\n deploy releases recent releases\n deploy logs recent app logs from production\n deploy rollback put an earlier release back") + end + end + + def release(id) = world.data["deploy"]["releases"].find { |r| r["id"] == id } + end +end diff --git a/backend/lib/sim/delivery_world.rb b/backend/lib/sim/delivery_world.rb new file mode 100644 index 0000000..4e60be7 --- /dev/null +++ b/backend/lib/sim/delivery_world.rb @@ -0,0 +1,192 @@ +module Sim + # The setting for the delivery chapters (GitHub, CI, Deploy): the shop's + # code on your laptop in ~/shop, its GitHub repo, CI, and production. + module DeliveryWorld + ROOT = "/home/dev/shop".freeze + + module_function + + CART_FIXED = <<~RUBY.freeze + class Cart + FREE_SHIPPING_FROM = 50 + + def initialize(subtotal) + @subtotal = subtotal + end + + def shipping + free_shipping? ? 0 : 4.99 + end + + def free_shipping? + @subtotal >= FREE_SHIPPING_FROM + end + end + RUBY + + CART_FROM_ENV = <<~RUBY.freeze + class Cart + def initialize(subtotal) + @subtotal = subtotal + end + + def shipping + free_shipping? ? 0 : 4.99 + end + + # The threshold now comes from the environment so marketing can change it. + def free_shipping? + @subtotal >= ENV["FREE_SHIPPING_FROM"].to_i + end + end + RUBY + + CART_TEST = <<~RUBY.freeze + require "test_helper" + + class CartTest < ActiveSupport::TestCase + test "small carts pay shipping" do + assert_equal 4.99, Cart.new(20).shipping + end + + test "carts of $50 or more ship free" do + assert_equal 0, Cart.new(50).shipping + end + end + RUBY + + CI_WORKFLOW = <<~YAML.freeze + name: CI + on: [pull_request] + + jobs: + test: + runs-on: ubuntu-latest + env: + RAILS_ENV: test + steps: + - uses: actions/checkout@v7 + - uses: ruby/setup-ruby@v1 + - run: bin/rails test + YAML + + BANNER_FILE = { "app/views/layouts/_banner.html.erb" => "

Free shipping on orders over $50

\n" }.freeze + + PAYMENTS_V1 = "endpoint: https://payments.internal/v1/charge\ntimeout_seconds: 5\n".freeze + PAYMENTS_V2 = "endpoint: https://payments.internal/v2/charge\ntimeout_seconds: 5\n".freeze + + def base_files(cart: CART_FIXED, payments: PAYMENTS_V1) + { + "README.md" => "# Shop\n\nThe Rails app behind shop.example.\n\nRun the tests with `bin/rails test`.\n", + ".gitignore" => ".env\nlog/\ntmp/\n", + ".github/workflows/ci.yml" => CI_WORKFLOW, + "app/models/cart.rb" => cart, + "app/views/layouts/_banner.html.erb" => "<%# TODO: free shipping banner goes here %>\n", + "config/payments.yml" => payments, + "test/models/cart_test.rb" => CART_TEST + } + end + + # Builds ~/shop on the laptop with the given history. + # history: [[message, files], ...] oldest first, all on main. + def add_repo(data, history:, env_file: nil) + laptop = data["hosts"]["laptop"] + repo = { "root" => ROOT, "branch" => "main", "staged" => {}, "commits" => {}, "branches" => {}, "remote" => {}, "prs" => [] } + parent = nil + history.each_with_index do |(message, files, author), i| + sha = Digest::SHA1.hexdigest("#{message}#{i}")[0, 7] + repo["commits"][sha] = { "message" => message, "parent" => parent, "files" => files, "author" => author || "sam", "tick" => -100 + i } + parent = sha + end + repo["branches"]["main"] = parent + repo["remote"]["main"] = parent + history.last[1].each { |path, content| laptop["fs"]["#{ROOT}/#{path}"] = ShopWorld.text(content) } + laptop["fs"]["#{ROOT}/.env"] = ShopWorld.text(env_file) if env_file + laptop["dirs"] << ROOT + data["repo"] = repo + repo + end + + # Which free-shipping threshold the code ends up using, given env vars. + # Understands the forms a beginner is likely to write. + def threshold(cart_rb, env) + if (m = cart_rb.match(/ENV\.fetch\(\s*["']FREE_SHIPPING_FROM["']\s*,\s*["']?(\d+)["']?\s*\)/)) + (env["FREE_SHIPPING_FROM"] || m[1]).to_i + elsif (m = cart_rb.match(/ENV\[\s*["']FREE_SHIPPING_FROM["']\s*\]\s*(?:\|\|\s*["']?(\d+)["']?)?/)) + value = env["FREE_SHIPPING_FROM"] || m[1] + value.to_i + elsif (m = cart_rb.match(/FREE_SHIPPING_FROM\s*=\s*(\d+)/)) + m[1].to_i + else + 0 + end + end + + def parse_env_file(content) + content.to_s.lines.filter_map { |l| l.strip.split("=", 2) if l.include?("=") && !l.start_with?("#") }.to_h + end + + def ci_env(files) + files[".github/workflows/ci.yml"].to_s.scan(/^\s+([A-Z_]+):\s*["']?([^"'\n]+)["']?\s*$/).to_h + end + + # The two cart tests, run against a set of files and environment. + def run_tests(files, env) + return [ false, [ "Error: app/models/cart.rb is missing" ] ] unless files["app/models/cart.rb"] + t = threshold(files["app/models/cart.rb"], env) + results = [ + [ "small carts pay shipping", 9, t > 20, "Expected: 4.99\n Actual: 0" ], + [ "carts of $50 or more ship free", 13, t <= 50, "Expected: 0\n Actual: 4.99" ] + ] + failures = results.reject { |r| r[2] } + lines = [ "Running 2 tests in a single process", "# Running:", "", + results.map { |r| r[2] ? "." : "F" }.join, "" ] + failures.each do |name, line, _, detail| + lines += [ "Failure:", "CartTest#test_#{name.tr(' $', '_').squeeze('_')} [test/models/cart_test.rb:#{line}]:", detail, "" ] + end + lines << "2 runs, 2 assertions, #{failures.size} failures, 0 errors, 0 skips" + [ failures.empty?, lines ] + end + + # --- map -------------------------------------------------------------- + + def map(world, production: false) + repo = Repo.new(world) + pr = repo.prs.reverse.find { |p| p["state"] == "open" } + run = pr && repo.latest_run(pr) + changes = repo.changes + dirty = (changes[:staged] + changes[:unstaged] + changes[:untracked]).any? + ci_status, ci_detail = + if run.nil? then [ "ok", "waiting for a PR" ] + elsif run["status"] == "in_progress" then [ "warn", "running…" ] + elsif run["conclusion"] == "success" then [ "ok", "passing" ] + else [ "bad", "failing" ] + end + row = production ? 30 : 45 + nodes = [ + { "id" => "laptop", "label" => "Your laptop", "kind" => "~/shop", "host" => "dev", "status" => "ok", + "detail" => "on #{repo.branch}#{dirty ? ' · changes' : ''}", "inspect" => "git status", "pos" => [ 12, row ], "pos_narrow" => [ 26, 9 ] }, + { "id" => "github", "label" => "GitHub", "kind" => "shop/shop", "host" => "github.com", "status" => "ok", + "detail" => pr ? "PR ##{pr['number']} open" : "#{world.data['repo']['remote'].size} branch#{'es' unless world.data['repo']['remote'].size == 1}", + "inspect" => pr ? "gh pr view" : "git log --oneline", "pos" => [ 38, row ], "pos_narrow" => [ 74, 9 ] }, + { "id" => "ci", "label" => "CI", "kind" => "bin/rails test", "host" => "github actions", "status" => ci_status, + "detail" => ci_detail, "inspect" => "gh pr checks", "pos" => [ 64, row ], "pos_narrow" => [ 26, 37 ] } + ] + edges = [ %w[laptop github], %w[github ci] ] + if production + d = world.data["deploy"] + rate = world.host("web-01")["error_rate"].to_i + nodes << { "id" => "production", "label" => "Production", "kind" => "shop.example", "host" => "web-01", + "status" => rate >= 5 ? "bad" : "ok", "detail" => "#{d['current']} · #{rate}% errors", "inspect" => "deploy status", + "pos" => [ 64, 72 ], "pos_narrow" => [ 74, 37 ] } + nodes << { "id" => "payments", "label" => "Payments API", "kind" => "payments.internal", "host" => "internal", "status" => "ok", + "detail" => "v1 only", "inspect" => "deploy logs", "pos" => [ 88, 72 ], "pos_narrow" => [ 74, 64 ] } + nodes << { "id" => "users", "label" => "Shoppers", "kind" => "checkout", "host" => "internet", "status" => rate >= 5 ? "bad" : "ok", + "detail" => rate >= 5 ? "seeing errors" : "happy", "inspect" => "curl https://shop.example/checkout", + "pos" => [ 41, 72 ], "pos_narrow" => [ 26, 64 ] } + edges += [ %w[ci production], %w[users production], %w[production payments] ] + end + { "nodes" => nodes, "edges" => edges } + end + end +end diff --git a/backend/lib/sim/repo.rb b/backend/lib/sim/repo.rb new file mode 100644 index 0000000..8ad5002 --- /dev/null +++ b/backend/lib/sim/repo.rb @@ -0,0 +1,131 @@ +require "digest" + +module Sim + # A tiny git: enough to teach branch, add, commit, push, revert and pull + # requests. The working tree is the laptop's real (simulated) files under + # `root`; commits store full snapshots, which keeps everything simple. + # + # world["repo"] = { + # "root", "branch", "staged" => { path => content|nil }, + # "commits" => { sha => { "message", "parent", "files", "author", "tick" } }, + # "branches" => { name => sha }, "remote" => { name => sha }, + # "prs" => [ { "number", "title", "branch", "state", "runs" => [...] } ] + # } + class Repo + HOST = "laptop".freeze + + attr_reader :world + + def initialize(world) + @world = world + end + + def data = world.data["repo"] + def root = data["root"] + def branch = data["branch"] + def head_sha(name = branch) = data["branches"][name] + def commit(sha) = data["commits"].fetch(sha) + def snapshot(sha = head_sha) = sha ? commit(sha)["files"] : {} + def prs = data["prs"] + def pr_for(name) = prs.find { |p| p["branch"] == name && p["state"] == "open" } + + def inside?(path) = path == root || path.start_with?(root + "/") + def rel(path) = path.delete_prefix(root + "/") + def abs(rel_path) = File.join(root, rel_path) + + # Files in the working tree, relative to the repo root. + def working_tree + tree = world.files(HOST).each_with_object({}) do |(path, f), out| + out[rel(path)] = f["content"].to_s if inside?(path) && path != root + end + ignored = tree[".gitignore"].to_s.lines.map(&:strip).reject { |l| l.empty? || l.start_with?("#") } + tree.reject { |p, _| ignored.any? { |pat| p == pat || p.start_with?(pat.end_with?("/") ? pat : "#{pat}/") } } + end + + # Files git ignores but that still affect the laptop (like .env). + def ignored_file(rel_path) = world.file(abs(rel_path), HOST)&.dig("content") + + # What `git commit` would record: HEAD with the staged changes on top. + def index + snapshot.merge(data["staged"]).compact + end + + def changes + tree = working_tree + idx = index + head = snapshot + { + staged: (idx.keys | head.keys).select { |p| idx[p] != head[p] }.sort, + unstaged: idx.keys.select { |p| tree.key?(p) ? tree[p] != idx[p] : true }.sort, + untracked: (tree.keys - idx.keys).sort + } + end + + def stage(paths) + tree = working_tree + paths.each { |p| data["staged"][p] = tree[p] } # nil means "deleted" + end + + def stage_all + tree = working_tree + (tree.keys | index.keys).each { |p| data["staged"][p] = tree[p] } + end + + def commit!(message, author: "you") + files = index + sha = Digest::SHA1.hexdigest("#{head_sha}#{message}#{files.hash}#{world.clock}")[0, 7] + data["commits"][sha] = { "message" => message, "parent" => head_sha, "files" => files, "author" => author, "tick" => world.clock } + data["branches"][branch] = sha + data["staged"] = {} + sha + end + + # Make the working tree match a commit (used by checkout and revert). + def write_tree(files) + world.files(HOST).keys.select { |p| inside?(p) && p != root }.each { |p| world.delete_file(p, HOST) } + files.each { |p, content| world.write_file(abs(p), content, HOST) } + end + + def log(sha = head_sha) + out = [] + while sha + out << [ sha, commit(sha) ] + sha = commit(sha)["parent"] + end + out + end + + + # Simple line diff: removed lines then added lines, per file. + def diff(from, to) + (from.keys | to.keys).sort.filter_map do |path| + next if from[path] == to[path] + old_lines = from[path].to_s.lines.map(&:chomp) + new_lines = to[path].to_s.lines.map(&:chomp) + removed = old_lines - new_lines + added = new_lines - old_lines + [ "diff --git a/#{path} b/#{path}", "--- a/#{path}", "+++ b/#{path}", + *removed.map { |l| "-#{l}" }, *added.map { |l| "+#{l}" } ].join("\n") + end.join("\n") + end + + # --- pull requests and CI ------------------------------------------- + + def open_pr!(title, name = branch) + number = (prs.map { |p| p["number"] }.max || 11) + 1 + pr = { "number" => number, "title" => title, "branch" => name, "state" => "open", "runs" => [] } + prs << pr + start_run!(pr) + pr + end + + def start_run!(pr) + sha = data["remote"][pr["branch"]] + return if pr["runs"].any? { |r| r["sha"] == sha } + pr["runs"] << { "id" => 7000 + world.clock * 10 + pr["runs"].size, "sha" => sha, "status" => "in_progress", + "started" => world.clock, "conclusion" => nil, "log" => [] } + end + + def latest_run(pr) = pr["runs"].last + end +end diff --git a/backend/lib/sim/scenario.rb b/backend/lib/sim/scenario.rb index d0cf33f..1e82541 100644 --- a/backend/lib/sim/scenario.rb +++ b/backend/lib/sim/scenario.rb @@ -11,7 +11,7 @@ class << self def all = Scenarios::ALL.sort_by(&:chapter) def find(key) = all.find { |s| s.key == key } || raise(KeyError, "Unknown scenario #{key}") - attr_accessor :key, :title, :chapter, :topic, :summary, :briefing, :focus_metric + attr_accessor :key, :title, :chapter, :topic, :summary, :briefing, :focus_metric, :real_world end def key = self.class.key @@ -35,6 +35,13 @@ def on_inspect(world, kind, target) end def on_file_changed(world, path); end + def on_commit(world, sha); end + def on_push(world, branch); end + def on_pr(world, pr); end + def on_rollback(world, release); end + + # [passed?, output lines] for `bin/rails test` and CI, given repo files. + def run_tests(_world, _files) = [ true, [ "0 runs, 0 assertions, 0 failures" ] ] def on_ssh(world, host); end def on_kill(world, process, _signal) diff --git a/backend/lib/sim/scenarios.rb b/backend/lib/sim/scenarios.rb index 77d5968..151f08a 100644 --- a/backend/lib/sim/scenarios.rb +++ b/backend/lib/sim/scenarios.rb @@ -3,6 +3,9 @@ module Sim # story can change without touching the engine. module Scenarios ALL = [ + GithubFirstPr, + CiWorksOnMyMachine, + DeployRollback, LinuxDiskFull, MonitoringMemoryLeak ].freeze diff --git a/backend/lib/sim/scenarios/ci_works_on_my_machine.rb b/backend/lib/sim/scenarios/ci_works_on_my_machine.rb new file mode 100644 index 0000000..277cc34 --- /dev/null +++ b/backend/lib/sim/scenarios/ci_works_on_my_machine.rb @@ -0,0 +1,95 @@ +module Sim + module Scenarios + # Chapter: tests pass on your laptop and fail in CI. Your local .env sets + # a value the code depends on; CI is a clean machine that doesn't have it. + class CiWorksOnMyMachine < Scenario + self.key = "ci-works-on-my-machine" + self.chapter = 2 + self.topic = "CI" + self.title = "Works on my machine" + self.summary = "Your tests pass locally but CI is red. Read the logs and find out what's different." + self.focus_metric = nil + self.briefing = <<~TEXT + Yesterday you opened PR #14, "Make free-shipping threshold configurable". + Your teammate pings you: "CI is red on your PR, can you take a look?" + You're in ~/shop on the feature branch. The tests passed on your laptop... + TEXT + self.real_world = { + "text" => "\"Passes locally, fails in CI\" is one of the most common CI problems. A frequent cause is an environment variable or secret that exists on your machine but not on the CI runner. CI starts from a clean machine on every run, and that's exactly why it's useful.", + "source_title" => "Six reasons your build passes locally and fails in CI", + "source_url" => "https://dev.to/fernforge/six-reasons-your-build-passes-locally-and-fails-in-ci-and-how-to-catch-each-before-you-push-2dgg" + } + + BRANCH = "configurable-shipping".freeze + + def build_world + data = empty_world + data["hosts"]["laptop"] = ShopWorld.laptop + data["session"] = { "host" => "laptop", "user" => "dev", "cwd" => DeliveryWorld::ROOT } + repo = DeliveryWorld.add_repo(data, history: [ + [ "Initial shop", DeliveryWorld.base_files ], + [ "Add cart tests", DeliveryWorld.base_files ] + ], env_file: "# Local settings, not committed (see .gitignore)\nFREE_SHIPPING_FROM=50\n") + + world = World.new(data) + r = Repo.new(world) + r.data["branches"][BRANCH] = r.head_sha + r.data["branch"] = BRANCH + world.write_file("#{DeliveryWorld::ROOT}/app/models/cart.rb", DeliveryWorld::CART_FROM_ENV, "laptop") + r.stage_all + r.commit!("Read free-shipping threshold from ENV", author: "you") + repo["remote"][BRANCH] = r.head_sha + pr = r.open_pr!("Make free-shipping threshold configurable", BRANCH) + pr["number"] = 14 + world.clock = 0 + DeliveryCi.advance(world.tap { |w| w.clock = DeliveryCi::RUN_TICKS }, self) + world.clock = 0 + world.data["messages"].clear + data + end + + def objectives + [ + Objective.new(id: "checks", title: "See which check failed", + hint: "Ask GitHub about your PR: `gh pr checks`.", + check: ->(w) { inspected?(w, :gh, "pr checks") || inspected?(w, :gh, "pr view") }), + Objective.new(id: "ci-log", title: "Read the failing test in the CI log", + hint: "`gh run view --log-failed` shows the part of the log that failed.", + check: ->(w) { inspected?(w, :gh, "run view") }), + Objective.new(id: "local", title: "Run the tests on your laptop", + hint: "From ~/shop run `bin/rails test`. Do they fail here too?", + check: ->(w) { inspected?(w, :tests) }), + Objective.new(id: "difference", title: "Find what's different between your laptop and CI", + hint: "Look at what changed: `git log --oneline` and `git diff main`. Then `ls -a` and `cat .env`. CI doesn't have your .env file.", + check: ->(w) { inspected?(w, :read, "#{DeliveryWorld::ROOT}/.env") || inspected?(w, :ls_hidden) }), + Objective.new(id: "fix", title: "Make the code work without your .env", + hint: "Give the code a default so it works anywhere: `sed -i 's/ENV\\[\"FREE_SHIPPING_FROM\"\\]/ENV.fetch(\"FREE_SHIPPING_FROM\", \"50\")/' app/models/cart.rb`, then `bin/rails test`.", + check: ->(w) { clean_pass?(Repo.new(w).working_tree) || clean_pass?(Repo.new(w).snapshot) }), + Objective.new(id: "green", title: "Commit, push and get CI green", + hint: "`git commit -am \"Default the free-shipping threshold\"`, `git push`, then `gh pr checks` until it passes.", + check: lambda { |w| + repo = Repo.new(w) + repo.prs.any? { |pr| repo.latest_run(pr)&.dig("conclusion") == "success" } + }) + ] + end + + # Would the tests pass on a clean CI machine? + def clean_pass?(files) = DeliveryWorld.run_tests(files, DeliveryWorld.ci_env(files)).first + + def on_inspect(world, kind, target) + super + super(world, :ls_hidden, target) if kind == :ls && world.history.last&.dig("input").to_s.match?(/\s-\w*a/) + end + + def run_tests(world, files) + env = DeliveryWorld.parse_env_file(Repo.new(world).ignored_file(".env")) + DeliveryWorld.run_tests(files, env) + end + + def tick(world) = DeliveryCi.advance(world, self) + def map(world) = DeliveryWorld.map(world) + def logs(_world) = {} + end + end +end diff --git a/backend/lib/sim/scenarios/deploy_rollback.rb b/backend/lib/sim/scenarios/deploy_rollback.rb new file mode 100644 index 0000000..2c2aa75 --- /dev/null +++ b/backend/lib/sim/scenarios/deploy_rollback.rb @@ -0,0 +1,130 @@ +module Sim + module Scenarios + # Chapter: a config change breaks checkout. The health check still says + # OK, so only the error alert and the logs tell the truth. Roll back first, + # then revert the commit so the next deploy doesn't ship it again. + class DeployRollback < Scenario + self.key = "deploy-rollback" + self.chapter = 3 + self.topic = "Deploy" + self.title = "The health check is lying" + self.summary = "A release breaks checkout while the health check stays green. Roll it back, then stop it coming back." + self.focus_metric = "errors" + self.briefing = <<~TEXT + Release r43 went out ten minutes ago: "Switch checkout to payments v2". + The deploy finished, the health check is green... and then your phone buzzes. + The deploy tool works from your laptop: try `deploy` to see what it can do. + TEXT + self.real_world = { + "text" => "Config changes cause a surprising share of big outages. In August 2024 a database config change took GitHub's read path down for 36 minutes until it was reverted. In December 2025 a config change rolled out to all of Cloudflare at once and caused HTTP 500 errors. The usual first move is the same as yours: roll back first, investigate after.", + "source_title" => "Dan Luu's collection of post-mortems", + "source_url" => "https://github.com/danluu/post-mortems" + } + + GOOD = "r42".freeze + BAD = "r43".freeze + + def build_world + data = empty_world + data["hosts"]["laptop"] = ShopWorld.laptop + data["hosts"]["web-01"] = ShopWorld.web01.merge("error_rate" => 38) + data["session"] = { "host" => "laptop", "user" => "dev", "cwd" => DeliveryWorld::ROOT } + repo = DeliveryWorld.add_repo(data, history: [ + [ "Add cart tests", DeliveryWorld.base_files ], + [ "Show free shipping banner", DeliveryWorld.base_files.merge(DeliveryWorld::BANNER_FILE) ], + [ "Switch checkout to payments v2", DeliveryWorld.base_files(payments: DeliveryWorld::PAYMENTS_V2).merge(DeliveryWorld::BANNER_FILE), "alex" ] + ]) + shas = Repo.new(World.new(data)).log.map(&:first).reverse + data["deploy"] = { + "current" => BAD, + "releases" => [ + { "id" => "r41", "sha" => shas[0], "message" => "Add cart tests", "by" => "sam", "at" => -300 }, + { "id" => GOOD, "sha" => shas[1], "message" => "Show free shipping banner", "by" => "you", "at" => -120 }, + { "id" => BAD, "sha" => shas[2], "message" => "Switch checkout to payments v2", "by" => "alex", "at" => -10 } + ], + "logs" => bad_logs(-9) + } + world = World.new(data) + ShopWorld.boot(self, world, "postgresql", "nginx", "shop-web", "shop-worker") + world.fire_alert("CheckoutErrors", "severity" => "critical", "summary" => "38% of POST /checkout requests return 500") + data + end + + def bad_logs(at) + (0..5).flat_map do |i| + t = format("09:%02d:%02d", (at + 10 + i) % 60, (i * 13) % 60) + [ "#{t} Started POST \"/checkout\" for 203.0.113.#{20 + i}", + "#{t} PaymentsClient::NotFound (404 from https://payments.internal/v2/charge):", + "#{t} app/services/charge_card.rb:18:in 'call'", + "#{t} Completed 500 Internal Server Error in 31ms" ] + end + [ "09:00:59 Started GET \"/health\" for 10.0.0.5", "09:00:59 Completed 200 OK in 2ms" ] + end + + def objectives + [ + Objective.new(id: "symptom", title: "Check what shoppers are seeing", + hint: "Try the health check and the checkout: `curl -i https://shop.example/health` then `curl -i -X POST https://shop.example/checkout`.", + check: ->(w) { w.flags.key?("saw_checkout_500") }), + Objective.new(id: "changes", title: "See what was deployed recently", + hint: "`deploy releases` lists what went out and when.", + check: ->(w) { inspected?(w, :deploy, "releases") || inspected?(w, :deploy, "history") || inspected?(w, :deploy, "status") }), + Objective.new(id: "logs", title: "Find the error in the production logs", + hint: "`deploy logs` shows the last lines from production. What's failing?", + check: ->(w) { inspected?(w, :deploy, "logs") }), + Objective.new(id: "rollback", title: "Roll back to the last good release", + hint: "Put #{GOOD} back: `deploy rollback #{GOOD}`.", + check: ->(w) { w.data["deploy"]["current"] != BAD }), + Objective.new(id: "verify", title: "Confirm checkout works again", + hint: "`curl -i -X POST https://shop.example/checkout` should say 200 now.", + check: ->(w) { w.flags["checkout_ok_at"].to_i >= w.flags["rolled_back_at"].to_i && w.flags.key?("rolled_back_at") }), + Objective.new(id: "revert", title: "Revert the bad commit on main so it can't ship again", + hint: "`git log --oneline` to find the commit, `git revert `, then `git push`.", + check: lambda { |w| + repo = Repo.new(w) + repo.snapshot(w.data["repo"]["remote"]["main"])["config/payments.yml"] == DeliveryWorld::PAYMENTS_V1 + }) + ] + end + + def on_rollback(world, release) + good = release["id"] != BAD + world.host("web-01")["error_rate"] = good ? 0 : 38 + world.flags["rolled_back_at"] = world.clock if good + d = world.data["deploy"] + d["logs"] = good ? [ "09:#{format('%02d', world.clock % 60)}:00 Booted #{release['id']} (#{release['sha']})", + "09:#{format('%02d', world.clock % 60)}:04 Started POST \"/checkout\" for 203.0.113.40", + "09:#{format('%02d', world.clock % 60)}:04 Completed 302 Found in 48ms" ] : bad_logs(world.clock) + end + + def tick(world) + DeliveryCi.advance(world, self) + broken = world.data["deploy"]["current"] == BAD + if !broken && world.firing_alerts.any? { |a| a["id"] == "CheckoutErrors" } + world.resolve_alert("CheckoutErrors") + world.data["messages"] << { "kind" => "resolved", "text" => "[RESOLVED] CheckoutErrors: checkout error rate is back to 0%." } + end + end + + def http(world, url) + return nil unless url.match?(%r{\A(https?://)?shop\.example(/.*)?\z}) + broken = world.data["deploy"]["current"] == BAD + if url.include?("/checkout") + if broken + world.flags["saw_checkout_500"] ||= world.clock + [ "500 Internal Server Error", "We're sorry, but something went wrong." ] + else + world.flags["checkout_ok_at"] = world.clock + [ "200 OK", "{\"order\":\"#{4200 + world.clock}\",\"status\":\"paid\"}" ] + end + elsif url.include?("/health") + [ "200 OK", "{\"status\":\"ok\",\"release\":\"#{world.data['deploy']['current']}\"}" ] + else + [ "200 OK", "

Ruby Shop

Free shipping on orders over $50

" ] + end + end + + def map(world) = DeliveryWorld.map(world, production: true) + def logs(world) = { "production" => world.data["deploy"]["logs"] } + end + end +end diff --git a/backend/lib/sim/scenarios/github_first_pr.rb b/backend/lib/sim/scenarios/github_first_pr.rb new file mode 100644 index 0000000..7a1fbc9 --- /dev/null +++ b/backend/lib/sim/scenarios/github_first_pr.rb @@ -0,0 +1,78 @@ +module Sim + module Scenarios + # Chapter: the everyday GitHub flow. Branch, change, commit, push, PR. + class GithubFirstPr < Scenario + self.key = "github-first-pr" + self.chapter = 1 + self.topic = "GitHub" + self.title = "Open your first pull request" + self.summary = "Make a small change on a branch, push it, and open a pull request." + self.focus_metric = nil + self.briefing = <<~TEXT + Welcome to the team! Your first task from the product channel: + "Can we show 'Free shipping on orders over $50' at the top of the shop?" + The code is in ~/shop. Changes go through a pull request, never straight to main. + TEXT + self.real_world = { + "text" => "Almost every team works like this: no one pushes straight to main. A pull request lets teammates and CI check a change before it ships, and it leaves a record of why the change was made.", + "source_title" => "GitHub Docs: About pull requests", + "source_url" => "https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests" + } + + BANNER = "app/views/layouts/_banner.html.erb".freeze + + def build_world + data = empty_world + data["hosts"]["laptop"] = ShopWorld.laptop + data["session"] = { "host" => "laptop", "user" => "dev", "cwd" => "/home/dev" } + DeliveryWorld.add_repo(data, history: [ + [ "Initial shop", DeliveryWorld.base_files ], + [ "Add cart tests", DeliveryWorld.base_files ] + ]) + data + end + + def objectives + [ + Objective.new(id: "open-repo", title: "Go to the shop's code", + hint: "The code lives in ~/shop. Run `cd ~/shop`, then `git status` to look around.", + check: ->(w) { Repo.new(w).inside?(w.session["cwd"]) }), + Objective.new(id: "branch", title: "Create a branch for your change", + hint: "Never work on main. Make a branch: `git switch -c free-shipping-banner`.", + check: ->(w) { w.data["repo"]["branches"].keys.any? { |b| b != "main" } }), + Objective.new(id: "edit", title: "Add the banner text", + hint: "Replace the TODO in #{BANNER}: echo '

Free shipping on orders over $50

' > #{BANNER}", + check: ->(w) { banner_done?(Repo.new(w).working_tree[BANNER]) || banner_committed?(w) }), + Objective.new(id: "commit", title: "Commit your change", + hint: "Stage it with `git add #{BANNER}`, then `git commit -m \"Add free shipping banner\"`.", + check: ->(w) { banner_committed?(w) }), + Objective.new(id: "push", title: "Push your branch to GitHub", + hint: "Send it up: `git push -u origin `. `git branch` shows the name.", + check: ->(w) { w.data["repo"]["remote"].any? { |b, sha| b != "main" && banner_done?(Repo.new(w).snapshot(sha)[BANNER]) } }), + Objective.new(id: "open-pr", title: "Open a pull request and let CI pass", + hint: "Run `gh pr create --title \"Add free shipping banner\"`, then `gh pr checks` until it's green.", + check: lambda { |w| + repo = Repo.new(w) + repo.prs.any? { |pr| repo.latest_run(pr)&.dig("conclusion") == "success" } + }) + ] + end + + def banner_done?(content) = content.to_s.match?(/free shipping/i) + + def banner_committed?(world) + repo = Repo.new(world) + world.data["repo"]["branches"].any? { |b, sha| b != "main" && banner_done?(repo.snapshot(sha)[BANNER]) } + end + + def run_tests(world, files) + env = DeliveryWorld.parse_env_file(Repo.new(world).ignored_file(".env")) + DeliveryWorld.run_tests(files, env) + end + + def tick(world) = DeliveryCi.advance(world, self) + def map(world) = DeliveryWorld.map(world) + def logs(_world) = {} + end + end +end diff --git a/backend/lib/sim/shell.rb b/backend/lib/sim/shell.rb index e93f6b2..6c5c8db 100644 --- a/backend/lib/sim/shell.rb +++ b/backend/lib/sim/shell.rb @@ -6,6 +6,8 @@ module Sim # and `>` / `>>` redirection. Every command reads and changes the World; # nothing ever touches the real machine. class Shell + include DeliveryCommands + Result = Struct.new(:output, :exit_code, keyword_init: true) FILTERS = %w[grep head tail sort wc].freeze @@ -70,6 +72,7 @@ def dispatch(argv, redirect: nil, sudo: false) @sudo = sudo || root? args = args.flat_map { |a| expand_glob(a) } unless %w[grep sed echo].include?(name) + name = "rails" if %w[bin/rails ./bin/rails].include?(name) handler = "cmd_#{name.to_s.tr('-', '_')}" result = if name == ":" then ok("") @@ -218,7 +221,7 @@ def cmd_ls(args) path = world.resolve(raw) entries = if world.file?(path) then [ [ File.basename(path), path, false ] ] - elsif world.directory?(path) then world.children(path) + elsif world.directory?(path) then world.children(path).reject { |name, _, _| name.start_with?(".") && !flags.include?("a") } else next "ls: cannot access '#{raw}': No such file or directory" end remember_listing(path) @@ -379,7 +382,7 @@ def cmd_sed(args) rescue RegexpError Regexp.new(Regexp.escape(m[1])) end - replacement = m[2].gsub("\\/", "/") + replacement = m[2].gsub("\\/", "/").gsub("\\n", "\n") updated = m[3] == "g" ? f["content"].gsub(pattern, replacement) : f["content"].lines.map { |l| l.sub(pattern, replacement) }.join return ok(updated.chomp) unless in_place return fail("sed: couldn't open temporary file #{File.dirname(path)}/sedXXXX: Permission denied") unless writable?(path) @@ -537,7 +540,8 @@ def cmd_journalctl(args) # --- network ------------------------------------------------------------ def cmd_curl(args) - url = args.reject { |a| a.start_with?("-") }.first + skip = args.each_index.select { |i| %w[-X -d -H --data --header --request].include?(args[i - 1]) && i.positive? } + url = args.each_with_index.reject { |a, i| a.start_with?("-") || skip.include?(i) }.map(&:first).first return fail("curl: try 'curl https://shop.example/health'") unless url status, body = scenario.http(world, url) return fail("curl: (6) Could not resolve host: #{url}", 6) unless status diff --git a/backend/lib/sim/world.rb b/backend/lib/sim/world.rb index e3c1c9a..c0f1672 100644 --- a/backend/lib/sim/world.rb +++ b/backend/lib/sim/world.rb @@ -177,7 +177,7 @@ def record_metrics next unless host(name)["monitored"] series = (data["metrics"][name] ||= []) series << { "t" => clock, "memory" => memory_percent(name), "disk" => disk_percent(name), - "cpu" => host(name).fetch("cpu_percent", 12) } + "cpu" => host(name).fetch("cpu_percent", 12), "errors" => host(name).fetch("error_rate", 0) } series.shift while series.size > 120 end end diff --git a/backend/test/integration/runs_api_test.rb b/backend/test/integration/runs_api_test.rb index da8e587..a20ccb2 100644 --- a/backend/test/integration/runs_api_test.rb +++ b/backend/test/integration/runs_api_test.rb @@ -4,7 +4,7 @@ class RunsApiTest < ActionDispatch::IntegrationTest test "lists scenarios" do get "/api/scenarios" assert_response :success - assert_equal %w[linux-disk-full monitoring-memory-leak], response.parsed_body.map { |s| s["key"] } + assert_equal %w[github-first-pr ci-works-on-my-machine deploy-rollback linux-disk-full monitoring-memory-leak], response.parsed_body.map { |s| s["key"] } end test "starts a run, runs a command and saves the world" do diff --git a/backend/test/lib/sim/delivery_chapters_test.rb b/backend/test/lib/sim/delivery_chapters_test.rb new file mode 100644 index 0000000..574e620 --- /dev/null +++ b/backend/test/lib/sim/delivery_chapters_test.rb @@ -0,0 +1,91 @@ +require "test_helper" + +class Sim::DeliveryChaptersTest < ActiveSupport::TestCase + def play(engine, *inputs) + inputs.flat_map { |i| engine.execute(i).completed.map { |c| c[:id] } } + end + + def wait_for_ci(engine, ticks = 3) = ticks.times.flat_map { engine.tick.completed.map { |c| c[:id] } } + + test "github: the full flow completes every objective in order" do + e = Sim::Engine.start("github-first-pr") + ids = play(e, "cd ~/shop", "git status", "git switch -c free-shipping-banner", + "echo '

Free shipping on orders over $50

' > app/views/layouts/_banner.html.erb", + "git add app/views/layouts/_banner.html.erb", "git commit -m \"Add free shipping banner\"", + "git push -u origin free-shipping-banner", "gh pr create --title \"Add free shipping banner\"") + ids += wait_for_ci(e) + assert_equal %w[open-repo branch edit commit push open-pr], ids + assert e.finished? + end + + test "github: guard rails explain what to do" do + e = Sim::Engine.start("github-first-pr") + assert_match "not a git repository", e.execute("git status").output + e.execute("cd ~/shop") + assert_match "make a branch", e.execute("gh pr create --title x").output.downcase + e.execute("git switch -c b") + assert_match "nothing to commit", e.execute("git commit -m x").output + assert_match "write a message", e.execute("git commit").output + assert_match "push the current branch", e.execute("gh pr create --title x").output + end + + test "github: git status shows changes and .env stays ignored" do + e = Sim::Engine.start("github-first-pr") + e.execute("cd ~/shop") + e.execute("echo hi > notes.txt") + out = e.execute("git status").output + assert_match "Untracked files", out + assert_match "notes.txt", out + end + + test "ci: starts red, passes locally, and the full fix turns CI green" do + e = Sim::Engine.start("ci-works-on-my-machine") + assert_match "failed", e.execute("gh pr checks").output + assert_match "Expected: 4.99", e.execute("gh run view --log-failed").output + assert_match "0 failures", e.execute("bin/rails test").output + e.execute("ls -a") + e.execute(%q(sed -i 's/ENV\["FREE_SHIPPING_FROM"\]/ENV.fetch("FREE_SHIPPING_FROM", "50")/' app/models/cart.rb)) + assert_match "0 failures", e.execute("bin/rails test").output + e.execute("git commit -am \"Default the free-shipping threshold\"") + assert_match "CI started", e.execute("git push").output + wait_for_ci(e) + assert_match "passed", e.execute("gh pr checks").output + assert e.finished?, e.objectives.inspect + end + + test "ci: deleting .env reproduces the failure locally" do + e = Sim::Engine.start("ci-works-on-my-machine") + e.execute("rm .env") + assert_match "1 failures", e.execute("bin/rails test").output + end + + test "ci: setting the variable in the workflow also fixes CI" do + e = Sim::Engine.start("ci-works-on-my-machine") + e.execute("sed -i 's/RAILS_ENV: test/RAILS_ENV: test\\n FREE_SHIPPING_FROM: 50/' .github/workflows/ci.yml") + files = Sim::Repo.new(e.world).working_tree + assert_equal "50", Sim::DeliveryWorld.ci_env(files)["FREE_SHIPPING_FROM"] + end + + test "deploy: health is green while checkout fails, and the full fix works" do + e = Sim::Engine.start("deploy-rollback") + assert_match "200 OK", e.execute("curl -i https://shop.example/health").output + assert_match "500", e.execute("curl -i -X POST https://shop.example/checkout").output + assert_match "r43", e.execute("deploy releases").output + assert_match "payments.internal/v2", e.execute("deploy logs").output + e.execute("deploy rollback r42") + assert_match "200 OK", e.execute("curl -i -X POST https://shop.example/checkout").output + bad = Sim::Repo.new(e.world).log.first.first + e.execute("git revert #{bad}") + e.execute("git push") + assert e.finished?, e.objectives.inspect + assert_empty e.world.firing_alerts + end + + test "deploy: the map shows production in trouble until the rollback" do + e = Sim::Engine.start("deploy-rollback") + prod = -> { e.scenario.map(e.world)["nodes"].find { |n| n["id"] == "production" } } + assert_equal "bad", prod.call["status"] + e.execute("deploy rollback r42") + assert_equal "ok", prod.call["status"] + end +end diff --git a/backend/test/lib/sim/monitoring_memory_leak_test.rb b/backend/test/lib/sim/monitoring_memory_leak_test.rb index 764f8ad..bbabfcc 100644 --- a/backend/test/lib/sim/monitoring_memory_leak_test.rb +++ b/backend/test/lib/sim/monitoring_memory_leak_test.rb @@ -26,7 +26,7 @@ def wait_for_alert test "metrics record one point per tick for the dashboard" do 3.times { @engine.tick } assert_equal 4, @world.data["metrics"]["web-01"].size - assert_equal %w[cpu disk memory t], @world.data["metrics"]["web-01"].last.keys.sort + assert_equal %w[cpu disk errors memory t], @world.data["metrics"]["web-01"].last.keys.sort end test "restarting without fixing the config only buys time" do diff --git a/frontend/src/components/MetricChart.tsx b/frontend/src/components/MetricChart.tsx index 5ae811e..b8dfcf2 100644 --- a/frontend/src/components/MetricChart.tsx +++ b/frontend/src/components/MetricChart.tsx @@ -1,8 +1,8 @@ -import type { MetricPoint } from '../types' +import type { Metric, MetricPoint } from '../types' interface Props { points: MetricPoint[] - metric: 'memory' | 'disk' + metric: Metric threshold: number } @@ -15,7 +15,8 @@ export function MetricChart({ points, metric, threshold }: Props) { const y = (v: number) => h - (v / 100) * h const line = 'M' + data.map((v, i) => `${(i * step).toFixed(1)},${y(v).toFixed(1)}`).join(' L') const now = data.at(-1) ?? 0 - const tone = now >= threshold ? 'var(--bad)' : now >= threshold - 10 ? 'var(--warn)' : 'var(--ok)' + const warnAt = metric === 'errors' ? 2 : threshold - 10 + const tone = now >= threshold ? 'var(--bad)' : now >= warnAt ? 'var(--warn)' : 'var(--ok)' return ( diff --git a/frontend/src/components/PlayScreen.tsx b/frontend/src/components/PlayScreen.tsx index 91287e3..bf5eba4 100644 --- a/frontend/src/components/PlayScreen.tsx +++ b/frontend/src/components/PlayScreen.tsx @@ -27,7 +27,9 @@ export function PlayScreen({ run, onExit, onNext }: Props) { const term = useRef(null) const scenario = run.scenario const metric = scenario.focus_metric - const threshold = metric === 'disk' ? 90 : 85 + const threshold = metric === 'disk' ? 90 : metric === 'errors' ? 5 : 85 + const warnAt = metric === 'errors' ? 2 : threshold - 10 + const metricLabel = metric === 'disk' ? 'Disk' : metric === 'errors' ? 'Checkout errors' : 'Memory' const showNotices = useCallback((notices: Notice[]) => { notices.forEach((n) => term.current?.print(n.text, n.kind === 'resolved' ? 'green' : 'amber')) @@ -86,9 +88,9 @@ export function PlayScreen({ run, onExit, onNext }: Props) { const current = objectives.find((o) => !o.done) const firing = live.alerts.filter((a) => a.state === 'firing') const points = live.metrics['web-01'] ?? [] - const now = points.at(-1)?.[metric] ?? 0 + const now = metric ? points.at(-1)?.[metric] ?? 0 : 0 const hotService = live.map.nodes.find((n) => n.status !== 'ok' && live.logs[n.id])?.id - const shownLogs = logService ?? hotService ?? 'shop-web' + const shownLogs = logService ?? hotService ?? Object.keys(live.logs)[0] ?? '' return (
@@ -107,9 +109,9 @@ export function PlayScreen({ run, onExit, onNext }: Props) {
-
- {metric === 'disk' ? 'Disk' : 'Memory'} · web-01 -
= threshold ? 'bad' : now >= threshold - 10 ? 'warn' : 'ok'}`}>{now}%
+ {metric &&
+ {metricLabel} · web-01 +
= threshold ? 'bad' : now >= warnAt ? 'warn' : 'ok'}`}>{now}%
    {live.alerts.length === 0 &&
  • No alerts yet.
  • } @@ -119,7 +121,7 @@ export function PlayScreen({ run, onExit, onNext }: Props) { ))}
-
+
}