-
Notifications
You must be signed in to change notification settings - Fork 0
feat: TUI skeleton and a synthetic workload generator #2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mickamy
wants to merge
5
commits into
main
Choose a base branch
from
feat/tui-skeleton
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
0d1a450
feat(tui): add the TUI skeleton wired to the CLI
mickamy 75cac73
feat(workload): add a synthetic load generator with compose wiring
mickamy 42e49c9
fix(tui): truncate query text on rune boundaries
mickamy 3902de0
fix(tui): prevent duplicate poll loops on pause/unpause
mickamy 7025c8d
test: raise coverage and ignore the dev workload tool
mickamy File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,227 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "log" | ||
| "math/rand/v2" | ||
| "os" | ||
| "os/signal" | ||
| "sync" | ||
| "syscall" | ||
| "time" | ||
|
|
||
| "github.com/jackc/pgx/v5/pgxpool" | ||
| ) | ||
|
|
||
| const ( | ||
| // defaultDSN points at the local compose database; password is the dev one. | ||
| defaultDSN = "postgres://postgres:pass@postgres:5432/dev" //nolint:gosec // dev-only default DSN | ||
| poolSize = 20 | ||
| seedRows = 1000 | ||
| normalWorkers = 8 | ||
| extraWorkers = 4 // nPlusOne, longQueries, blocker, contender | ||
| hotRowID = 1 // the single row the blocker and contenders fight over | ||
| ) | ||
|
|
||
| func main() { | ||
| if err := run(); err != nil { | ||
| log.Fatalf("workload: %v", err) | ||
| } | ||
| } | ||
|
|
||
| func run() error { | ||
| ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) | ||
| defer stop() | ||
|
|
||
| dsn := os.Getenv("WORKLOAD_DSN") | ||
| if dsn == "" { | ||
| dsn = defaultDSN | ||
| } | ||
|
|
||
| pool, err := connect(ctx, dsn) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| defer pool.Close() | ||
|
|
||
| if err := setup(ctx, pool); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| log.Println("workload: generating traffic (ctrl-c to stop)") | ||
|
|
||
| workers := make([]func(context.Context, *pgxpool.Pool), 0, normalWorkers+extraWorkers) | ||
| for range normalWorkers { | ||
| workers = append(workers, normalLoad) | ||
| } | ||
|
|
||
| workers = append(workers, nPlusOne, longQueries, blocker, contender) | ||
|
|
||
| var wg sync.WaitGroup | ||
|
|
||
| for _, w := range workers { | ||
| wg.Go(func() { | ||
| w(ctx, pool) | ||
| }) | ||
| } | ||
|
mickamy marked this conversation as resolved.
mickamy marked this conversation as resolved.
|
||
|
|
||
| <-ctx.Done() | ||
| wg.Wait() | ||
| log.Println("workload: stopped") | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| func connect(ctx context.Context, dsn string) (*pgxpool.Pool, error) { | ||
| cfg, err := pgxpool.ParseConfig(dsn) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("parse dsn: %w", err) | ||
| } | ||
|
|
||
| cfg.MaxConns = poolSize | ||
|
|
||
| for { | ||
| pool, err := pgxpool.NewWithConfig(ctx, cfg) | ||
| if err == nil { | ||
| if pingErr := pool.Ping(ctx); pingErr == nil { | ||
| return pool, nil | ||
| } else { | ||
| pool.Close() | ||
| err = pingErr | ||
| } | ||
| } | ||
|
|
||
| log.Printf("workload: waiting for db: %v", err) | ||
|
|
||
| if !wait(ctx, time.Second) { | ||
| return nil, fmt.Errorf("canceled while connecting: %w", ctx.Err()) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func setup(ctx context.Context, pool *pgxpool.Pool) error { | ||
| // pg_stat_statements needs shared_preload_libraries; tolerate its absence. | ||
| if _, err := pool.Exec(ctx, `CREATE EXTENSION IF NOT EXISTS pg_stat_statements`); err != nil { | ||
| log.Printf("workload: pg_stat_statements unavailable: %v", err) | ||
| } | ||
|
|
||
| schema := []string{ | ||
| `CREATE TABLE IF NOT EXISTS items ( | ||
| id int PRIMARY KEY, | ||
| name text NOT NULL, | ||
| value int NOT NULL | ||
| )`, | ||
| fmt.Sprintf(`INSERT INTO items | ||
| SELECT g, 'item-' || g, g | ||
| FROM generate_series(1, %d) g | ||
| ON CONFLICT (id) DO NOTHING`, seedRows), | ||
| } | ||
|
|
||
| for _, stmt := range schema { | ||
| if _, err := pool.Exec(ctx, stmt); err != nil { | ||
| return fmt.Errorf("setup: %w", err) | ||
| } | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| // normalLoad does steady point reads and writes across random rows. | ||
| func normalLoad(ctx context.Context, pool *pgxpool.Pool) { | ||
| for wait(ctx, jitter(5*time.Millisecond, 45*time.Millisecond)) { | ||
| id := rand.IntN(seedRows) + 1 //nolint:gosec // weak RNG is fine for a load generator | ||
|
|
||
| var ( | ||
| name string | ||
| value int | ||
| ) | ||
|
|
||
| _ = pool.QueryRow(ctx, `SELECT name, value FROM items WHERE id = $1`, id).Scan(&name, &value) | ||
| _, _ = pool.Exec(ctx, `UPDATE items SET value = value + 1 WHERE id = $1`, id) | ||
| } | ||
| } | ||
|
|
||
| // nPlusOne fetches a batch of ids then queries each one separately, the classic | ||
| // pattern that is cheap per call but dominates pg_stat_statements by count. | ||
| func nPlusOne(ctx context.Context, pool *pgxpool.Pool) { | ||
| for wait(ctx, 500*time.Millisecond) { | ||
| rows, err := pool.Query(ctx, `SELECT id FROM items ORDER BY random() LIMIT 50`) | ||
| if err != nil { | ||
| continue | ||
| } | ||
|
|
||
| var ids []int | ||
|
|
||
| for rows.Next() { | ||
| var id int | ||
| if err := rows.Scan(&id); err == nil { | ||
| ids = append(ids, id) | ||
| } | ||
| } | ||
|
|
||
| rows.Close() | ||
|
|
||
| for _, id := range ids { | ||
| var name string | ||
|
|
||
| _ = pool.QueryRow(ctx, `SELECT name FROM items WHERE id = $1`, id).Scan(&name) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // longQueries runs an occasional multi-second query so the Activity screen has | ||
| // a long DURATION to surface. | ||
| func longQueries(ctx context.Context, pool *pgxpool.Pool) { | ||
| for wait(ctx, 2*time.Second) { | ||
| seconds := rand.IntN(8) + 3 //nolint:gosec // weak RNG is fine for a load generator | ||
|
|
||
| _, _ = pool.Exec(ctx, `SELECT pg_sleep($1)`, seconds) | ||
| } | ||
| } | ||
|
|
||
| // blocker holds a row lock inside an open transaction, then sits idle, creating | ||
| // an idle-in-transaction backend that blocks the contender. | ||
| func blocker(ctx context.Context, pool *pgxpool.Pool) { | ||
| for wait(ctx, 3*time.Second) { | ||
| holdLock(ctx, pool) | ||
| } | ||
| } | ||
|
|
||
| func holdLock(ctx context.Context, pool *pgxpool.Pool) { | ||
| tx, err := pool.Begin(ctx) | ||
| if err != nil { | ||
| return | ||
| } | ||
| defer func() { _ = tx.Rollback(ctx) }() | ||
|
|
||
| if _, err := tx.Exec(ctx, `UPDATE items SET value = value WHERE id = $1`, hotRowID); err != nil { | ||
| return | ||
| } | ||
|
|
||
| wait(ctx, 5*time.Second) | ||
|
|
||
| _ = tx.Commit(ctx) | ||
| } | ||
|
|
||
| // contender repeatedly updates the hot row, so it blocks whenever the blocker | ||
| // is holding the lock. | ||
| func contender(ctx context.Context, pool *pgxpool.Pool) { | ||
| for wait(ctx, time.Second) { | ||
| _, _ = pool.Exec(ctx, `UPDATE items SET value = value + 1 WHERE id = $1`, hotRowID) | ||
| } | ||
| } | ||
|
|
||
| // wait sleeps for d, returning false if the context is canceled first. | ||
| func wait(ctx context.Context, d time.Duration) bool { | ||
| select { | ||
| case <-ctx.Done(): | ||
| return false | ||
| case <-time.After(d): | ||
| return true | ||
| } | ||
| } | ||
|
|
||
| func jitter(minimum, maximum time.Duration) time.Duration { | ||
| return minimum + rand.N(maximum-minimum) //nolint:gosec // weak RNG is fine for a load generator | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| ignore: | ||
| - "cmd/workload" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| -- Runs once on a fresh data directory (after postgres starts with | ||
| -- shared_preload_libraries=pg_stat_statements), so the Statements screen works | ||
| -- out of the box in local and CI databases. | ||
| CREATE EXTENSION IF NOT EXISTS pg_stat_statements; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.