diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 7814fce985..3133ae9e3d 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -1024,7 +1024,8 @@ jobs: needs: [changes, lockfile] if: needs.changes.outputs.performance == 'true' && needs.changes.outputs.full == 'true' runs-on: ubuntu-24.04 - timeout-minutes: 45 + # Two release builds: about 20 minutes on a warm cache, past 40 when Cargo.lock changed. + timeout-minutes: 60 strategy: fail-fast: false matrix: diff --git a/Cargo.lock b/Cargo.lock index e3cab15926..490cdde3e4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3930,6 +3930,16 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "serde_ignored" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115dffd5f3853e06e746965a20dcbae6ee747ae30b543d91b0e089668bb07798" +dependencies = [ + "serde", + "serde_core", +] + [[package]] name = "serde_json" version = "1.0.151" @@ -4305,6 +4315,7 @@ dependencies = [ name = "sqlbuild-config" version = "0.0.0" dependencies = [ + "dotenvy", "saphyr-parser", "sqlbuild-core", "tempfile", @@ -4380,7 +4391,9 @@ dependencies = [ "reqwest", "rusqlite", "serde", + "serde_ignored", "serde_json", + "serde_path_to_error", "sqlbuild-core", "sqlbuild-cursor", "sqlbuild-model-config", @@ -4741,8 +4754,8 @@ dependencies = [ [[package]] name = "sqlclean" -version = "0.9.6" -source = "git+https://github.com/sqlstack-io/sqlclean.git?rev=bbc94e556dc51e936e86fa4c85111c87a7915fc5#bbc94e556dc51e936e86fa4c85111c87a7915fc5" +version = "0.11.1" +source = "git+https://github.com/sqlstack-io/sqlclean.git?rev=b0728bb990b7d8ff196cb00cc20545f2fa4df555#b0728bb990b7d8ff196cb00cc20545f2fa4df555" dependencies = [ "rayon", "rustc-hash", @@ -4759,8 +4772,8 @@ dependencies = [ [[package]] name = "sqlquack-derive" -version = "0.12.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=75d4c8486ab262a6c9c02a6c913334856367d890#75d4c8486ab262a6c9c02a6c913334856367d890" +version = "0.22.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" dependencies = [ "proc-macro2", "quote", @@ -4769,8 +4782,8 @@ dependencies = [ [[package]] name = "sqlquack-diagnostics" -version = "0.12.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=75d4c8486ab262a6c9c02a6c913334856367d890#75d4c8486ab262a6c9c02a6c913334856367d890" +version = "0.22.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" dependencies = [ "serde", "serde_json", @@ -4779,8 +4792,8 @@ dependencies = [ [[package]] name = "sqlquack-fingerprint" -version = "0.12.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=75d4c8486ab262a6c9c02a6c913334856367d890#75d4c8486ab262a6c9c02a6c913334856367d890" +version = "0.22.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" dependencies = [ "sha2 0.10.9", "sqlquack-parse", @@ -4789,8 +4802,8 @@ dependencies = [ [[package]] name = "sqlquack-format" -version = "0.12.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=75d4c8486ab262a6c9c02a6c913334856367d890#75d4c8486ab262a6c9c02a6c913334856367d890" +version = "0.22.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" dependencies = [ "serde_json", "sqlquack-parse", @@ -4799,8 +4812,8 @@ dependencies = [ [[package]] name = "sqlquack-lint" -version = "0.12.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=75d4c8486ab262a6c9c02a6c913334856367d890#75d4c8486ab262a6c9c02a6c913334856367d890" +version = "0.22.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" dependencies = [ "rayon", "rustc-hash", @@ -4812,8 +4825,8 @@ dependencies = [ [[package]] name = "sqlquack-parse" -version = "0.12.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=75d4c8486ab262a6c9c02a6c913334856367d890#75d4c8486ab262a6c9c02a6c913334856367d890" +version = "0.22.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" dependencies = [ "sqlquack-syntax", "sqlquack-syntax-bigquery", @@ -4825,8 +4838,8 @@ dependencies = [ [[package]] name = "sqlquack-semantics" -version = "0.12.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=75d4c8486ab262a6c9c02a6c913334856367d890#75d4c8486ab262a6c9c02a6c913334856367d890" +version = "0.22.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" dependencies = [ "regex", "rustc-hash", @@ -4841,8 +4854,8 @@ dependencies = [ [[package]] name = "sqlquack-syntax" -version = "0.12.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=75d4c8486ab262a6c9c02a6c913334856367d890#75d4c8486ab262a6c9c02a6c913334856367d890" +version = "0.22.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" dependencies = [ "serde", "serde_json", @@ -4854,8 +4867,8 @@ dependencies = [ [[package]] name = "sqlquack-syntax-bigquery" -version = "0.12.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=75d4c8486ab262a6c9c02a6c913334856367d890#75d4c8486ab262a6c9c02a6c913334856367d890" +version = "0.22.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" dependencies = [ "sqlquack-syntax", "stacker", @@ -4863,8 +4876,8 @@ dependencies = [ [[package]] name = "sqlquack-syntax-clickhouse" -version = "0.12.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=75d4c8486ab262a6c9c02a6c913334856367d890#75d4c8486ab262a6c9c02a6c913334856367d890" +version = "0.22.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" dependencies = [ "sqlquack-syntax", "stacker", @@ -4872,8 +4885,8 @@ dependencies = [ [[package]] name = "sqlquack-syntax-databricks" -version = "0.12.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=75d4c8486ab262a6c9c02a6c913334856367d890#75d4c8486ab262a6c9c02a6c913334856367d890" +version = "0.22.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" dependencies = [ "sqlquack-syntax", "stacker", @@ -4881,8 +4894,8 @@ dependencies = [ [[package]] name = "sqlquack-syntax-duckdb" -version = "0.12.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=75d4c8486ab262a6c9c02a6c913334856367d890#75d4c8486ab262a6c9c02a6c913334856367d890" +version = "0.22.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" dependencies = [ "sqlquack-syntax", "stacker", @@ -4890,8 +4903,8 @@ dependencies = [ [[package]] name = "sqlquack-syntax-postgres" -version = "0.12.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=75d4c8486ab262a6c9c02a6c913334856367d890#75d4c8486ab262a6c9c02a6c913334856367d890" +version = "0.22.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" dependencies = [ "sqlquack-syntax", "stacker", @@ -4899,8 +4912,8 @@ dependencies = [ [[package]] name = "sqlquack-syntax-snowflake" -version = "0.12.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=75d4c8486ab262a6c9c02a6c913334856367d890#75d4c8486ab262a6c9c02a6c913334856367d890" +version = "0.22.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" dependencies = [ "serde", "serde_json", @@ -4912,8 +4925,8 @@ dependencies = [ [[package]] name = "sqlquack-syntax-sqlite" -version = "0.12.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=75d4c8486ab262a6c9c02a6c913334856367d890#75d4c8486ab262a6c9c02a6c913334856367d890" +version = "0.22.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" dependencies = [ "sqlquack-syntax", "stacker", @@ -4921,8 +4934,8 @@ dependencies = [ [[package]] name = "sqlquack-syntax-sqlserver" -version = "0.12.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=75d4c8486ab262a6c9c02a6c913334856367d890#75d4c8486ab262a6c9c02a6c913334856367d890" +version = "0.22.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed#fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" dependencies = [ "sqlquack-syntax", "stacker", diff --git a/Cargo.toml b/Cargo.toml index aac6c8e5f8..5b2453d6bc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -83,6 +83,8 @@ publish = false rust-version = "1.88" [workspace.dependencies] +# Reads the project env file with dotenv semantics; sqlx-postgres already depends on it. +dotenvy = "0.15.7" argon2 = "0.5.3" axum = { version = "0.8", default-features = false, features = ["http1", "json", "query", "tokio"] } axum-server = { version = "0.8", default-features = false, features = ["tls-rustls-no-provider"] } @@ -152,11 +154,15 @@ errno = "0.3" windows-sys = { version = "0.61", default-features = false, features = ["Win32_System_Diagnostics_Debug"] } # Recall's local store: SQLite compiled in, so every build has the same engine version. rusqlite = { version = "0.37", features = ["bundled", "column_decltype"] } -rustix = { version = "1.1.4", default-features = false, features = ["fs", "process", "std", "stdio", "termios"] } +rustix = { version = "1.1.4", default-features = false, features = ["event", "fs", "process", "pty", "std", "stdio", "termios"] } saphyr-parser = "0.1" regex = "1" reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } serde = { version = "1", features = ["derive"] } +# Reports every field a decode ignores; a worker refuses a run request it can only partly read. +serde_ignored = "0.1" +# Names where a decode failed; with serde_ignored, a worker names any part of a run request it can't read. +serde_path_to_error = "0.1" # Every crate relies on insertion-ordered JSON objects, which the extension has always built with. serde_json = { version = "1", features = ["preserve_order"] } sha2 = "0.10" @@ -203,22 +209,22 @@ sqlbuild-scopes = { path = "crates/sqlbuild-scopes" } sqlbuild-sqltext = { path = "crates/sqlbuild-sqltext" } sqlbuild-state = { path = "crates/sqlbuild-state" } # SQL lint Rules, quality Rules and the formatter. -sqlclean = { git = "https://github.com/sqlstack-io/sqlclean.git", rev = "bbc94e556dc51e936e86fa4c85111c87a7915fc5" } +sqlclean = { git = "https://github.com/sqlstack-io/sqlclean.git", rev = "b0728bb990b7d8ff196cb00cc20545f2fa4df555" } # SQL change fingerprints over SQLQuack's tokenizers. -sqlquack-fingerprint = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "75d4c8486ab262a6c9c02a6c913334856367d890", features = ["bigquery", "databricks", "duckdb", "postgres", "snowflake", "sqlite", "sqlserver"] } +sqlquack-fingerprint = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed", features = ["bigquery", "databricks", "duckdb", "postgres", "snowflake", "sqlite", "sqlserver"] } # Scopes, name resolution, types and lineage for the native analysis route. -sqlquack-semantics = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "75d4c8486ab262a6c9c02a6c913334856367d890", features = ["bigquery", "clickhouse", "databricks", "duckdb", "postgres", "snowflake", "sqlite", "sqlserver"] } +sqlquack-semantics = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed", features = ["bigquery", "clickhouse", "databricks", "duckdb", "postgres", "snowflake", "sqlite", "sqlserver"] } # SQLQuack's Snowflake-family parser and tokenizer, reached as SQLQuack exposes them. -sqlquack-parse = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "75d4c8486ab262a6c9c02a6c913334856367d890" } +sqlquack-parse = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" } # SQLQuack's syntax tree and lossless tokens. -sqlquack-syntax = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "75d4c8486ab262a6c9c02a6c913334856367d890" } -sqlquack-syntax-bigquery = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "75d4c8486ab262a6c9c02a6c913334856367d890" } -sqlquack-syntax-clickhouse = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "75d4c8486ab262a6c9c02a6c913334856367d890" } -sqlquack-syntax-databricks = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "75d4c8486ab262a6c9c02a6c913334856367d890" } -sqlquack-syntax-duckdb = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "75d4c8486ab262a6c9c02a6c913334856367d890" } -sqlquack-syntax-postgres = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "75d4c8486ab262a6c9c02a6c913334856367d890" } -sqlquack-syntax-sqlite = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "75d4c8486ab262a6c9c02a6c913334856367d890" } -sqlquack-syntax-sqlserver = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "75d4c8486ab262a6c9c02a6c913334856367d890" } +sqlquack-syntax = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" } +sqlquack-syntax-bigquery = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" } +sqlquack-syntax-clickhouse = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" } +sqlquack-syntax-databricks = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" } +sqlquack-syntax-duckdb = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" } +sqlquack-syntax-postgres = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" } +sqlquack-syntax-sqlite = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" } +sqlquack-syntax-sqlserver = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "fe3d1caf5ed81981abf8abd1d00cc9d99462e6ed" } stacker = "0.1" # Counts heap allocations in growth tests, which measure work instead of time. stats_alloc = "0.1" diff --git a/benchmarks/duckshop/edge_cases/named_selectors/orchestration/sensors/on_orders_built_sensor.py b/benchmarks/duckshop/edge_cases/named_selectors/orchestration/sensors/on_orders_built_sensor.py index 5d1d4ca3ba..515ad69ab8 100644 --- a/benchmarks/duckshop/edge_cases/named_selectors/orchestration/sensors/on_orders_built_sensor.py +++ b/benchmarks/duckshop/edge_cases/named_selectors/orchestration/sensors/on_orders_built_sensor.py @@ -2,11 +2,12 @@ from orchestration.sensors._orders_conditions import landed_after -from sqlbuild.orchestration import sensor +from sqlbuild.orchestration import RunRequest, sensor -on_orders_built = sensor( - "on_orders_built_sensor", + +@sensor( description="Refresh order totals after the totals model", when=landed_after("order_totals"), - run="orders_folder_job", ) +def on_orders_built_sensor(ctx): + return RunRequest(job="orders_folder_job") diff --git a/benchmarks/duckshop/edge_cases/named_selectors/orchestration/sensors/on_orders_computed_sensor.py b/benchmarks/duckshop/edge_cases/named_selectors/orchestration/sensors/on_orders_computed_sensor.py index 21e65b12db..81b7f4262f 100644 --- a/benchmarks/duckshop/edge_cases/named_selectors/orchestration/sensors/on_orders_computed_sensor.py +++ b/benchmarks/duckshop/edge_cases/named_selectors/orchestration/sensors/on_orders_computed_sensor.py @@ -1,12 +1,13 @@ """A condition whose select is not a string literal cannot be counted and is reported.""" -from sqlbuild.orchestration import node_event, sensor +from sqlbuild.orchestration import RunRequest, node_event, sensor ORDERS_SELECTION = "stg_orders" -on_orders_computed = sensor( - "on_orders_computed_sensor", + +@sensor( description="Refresh totals when staged orders change", when=node_event(select=ORDERS_SELECTION, kinds=["success"]), - run="orders_folder_job", ) +def on_orders_computed_sensor(ctx): + return RunRequest(job="orders_folder_job") diff --git a/benchmarks/duckshop/edge_cases/named_selectors/orchestration/sensors/on_orders_failure_sensor.py b/benchmarks/duckshop/edge_cases/named_selectors/orchestration/sensors/on_orders_failure_sensor.py index 4557faaa40..4162b63b51 100644 --- a/benchmarks/duckshop/edge_cases/named_selectors/orchestration/sensors/on_orders_failure_sensor.py +++ b/benchmarks/duckshop/edge_cases/named_selectors/orchestration/sensors/on_orders_failure_sensor.py @@ -1,14 +1,15 @@ """Starts the repair job when any of four models fails: one over the limit, bound to a name.""" -from sqlbuild.orchestration import node_event, sensor +from sqlbuild.orchestration import RunRequest, node_event, sensor ORDERS_FAILED = node_event( select="stg_orders stg_payments int_orders order_totals", kinds=["failure"] ) -on_orders_failure = sensor( - "on_orders_failure_sensor", + +@sensor( description="Repair orders after a failure", when=ORDERS_FAILED, - run="orders_repair_job", ) +def on_orders_failure_sensor(ctx): + return RunRequest(job="orders_repair_job") diff --git a/benchmarks/duckshop/edge_cases/named_selectors/orchestration/sensors/on_orders_landed_sensor.py b/benchmarks/duckshop/edge_cases/named_selectors/orchestration/sensors/on_orders_landed_sensor.py index 33c4d56878..68c30166f3 100644 --- a/benchmarks/duckshop/edge_cases/named_selectors/orchestration/sensors/on_orders_landed_sensor.py +++ b/benchmarks/duckshop/edge_cases/named_selectors/orchestration/sensors/on_orders_landed_sensor.py @@ -2,11 +2,12 @@ from orchestration.sensors._orders_conditions import ORDERS_LANDED -from sqlbuild.orchestration import sensor +from sqlbuild.orchestration import RunRequest, sensor -on_orders_landed = sensor( - "on_orders_landed_sensor", + +@sensor( description="Refresh order totals after orders land", when=ORDERS_LANDED, - run="orders_folder_job", ) +def on_orders_landed_sensor(ctx): + return RunRequest(job="orders_folder_job") diff --git a/benchmarks/duckshop/edge_cases/named_selectors/orchestration/sensors/on_tick_overdue_sensor.py b/benchmarks/duckshop/edge_cases/named_selectors/orchestration/sensors/on_tick_overdue_sensor.py index d1ddca6d62..55407d065c 100644 --- a/benchmarks/duckshop/edge_cases/named_selectors/orchestration/sensors/on_tick_overdue_sensor.py +++ b/benchmarks/duckshop/edge_cases/named_selectors/orchestration/sensors/on_tick_overdue_sensor.py @@ -2,11 +2,12 @@ from orchestration.sensors._orders_conditions import TICK_OVERDUE -from sqlbuild.orchestration import sensor +from sqlbuild.orchestration import RunRequest, sensor -on_tick_overdue = sensor( - "on_tick_overdue_sensor", + +@sensor( description="Repair orders after an overdue tick", when=TICK_OVERDUE, - run="orders_repair_job", ) +def on_tick_overdue_sensor(ctx): + return RunRequest(job="orders_repair_job") diff --git a/benchmarks/duckshop/edge_cases/orchestration/attached_checks.json b/benchmarks/duckshop/edge_cases/orchestration/attached_checks.json index 76c5dad560..6d32048449 100644 --- a/benchmarks/duckshop/edge_cases/orchestration/attached_checks.json +++ b/benchmarks/duckshop/edge_cases/orchestration/attached_checks.json @@ -5,6 +5,7 @@ "cancelled": "import signal\nfrom sqlbuild.checks import check\nfrom sqlbuild.refs import model\n@check(depends_on=model('orders'), description='Heartbeat cancellation interrupts the driver without SIGTERM.')\ndef orders_valid(ctx):\n signal.signal(signal.SIGTERM, signal.SIG_IGN)\n ctx.query('WITH RECURSIVE pending(i) AS ((SELECT i FROM range(10000000000) AS seed(i) LIMIT 1) UNION ALL SELECT i FROM pending) SELECT sum(i) FROM pending')\n return ctx.pass_()\n", "on_failure_job": "name = \"annual_orders_job\"\ndescription = \"Build orders.\"\nselect = \"orders\"\nschedule = { cron = \"0 0 * * *\", timezone = \"UTC\", starts_at = \"2000-01-01T00:00:00Z\" }\n", "on_failure_destination": "name = \"refresh_inventory_job\"\ndescription = \"Refresh inventory.\"\nselect = \"inventory\"\n", - "on_failure_sensor": "from sqlbuild.orchestration import NodeEventKind, node_event, sensor\n\nfailed_orders = sensor(\n 'failed_orders_sensor',\n description='React to an actual orders check failure.',\n when=node_event(select='check:orders_valid', kinds=[NodeEventKind.FAILED]),\n run='refresh_inventory_job',\n minimum_interval_seconds=1,\n)\n", + "on_failure_sensor": "from sqlbuild.orchestration import NodeEventKind, RunRequest, node_event, sensor\n\n\n@sensor(\n description='React to an actual orders check failure.',\n when=node_event(select='check:orders_valid', kinds=[NodeEventKind.FAILED]),\n minimum_interval_seconds=1,\n)\ndef failed_orders_sensor(ctx):\n return RunRequest(job='refresh_inventory_job')\n", + "on_check_event_sensor": "from sqlbuild.orchestration import CheckEvent, CheckEventKind, RunRequest, SensorContext, check_event, sensor\n\n\n@sensor(\n description='React to any failed check on orders.',\n when=check_event(select='orders', kinds=[CheckEventKind.FAILED]),\n minimum_interval_seconds=1,\n)\ndef failed_orders_sensor(ctx: SensorContext[CheckEvent]):\n assert ctx.event.check == 'check:orders_valid' and ctx.event.status == CheckEventKind.FAILED\n return RunRequest(job='refresh_inventory_job')\n", "inventory": "MODEL (description 'Inventory after check failure.', materialized table);\nSELECT 59 AS amount;\n" } diff --git a/benchmarks/duckshop/edge_cases/orchestration/changed_source_orders/sensors/on_source_orders_sensor.py b/benchmarks/duckshop/edge_cases/orchestration/changed_source_orders/sensors/on_source_orders_sensor.py index a8abd75682..a726e11a8e 100644 --- a/benchmarks/duckshop/edge_cases/orchestration/changed_source_orders/sensors/on_source_orders_sensor.py +++ b/benchmarks/duckshop/edge_cases/orchestration/changed_source_orders/sensors/on_source_orders_sensor.py @@ -1,11 +1,12 @@ """Start the changed-only refresh for each new source version.""" -from sqlbuild.orchestration import sensor, source_new_data +from sqlbuild.orchestration import RunRequest, sensor, source_new_data -on_source_orders = sensor( - "on_source_orders_sensor", + +@sensor( description="Refresh orders for each changed source version.", when=source_new_data(select="source:raw_orders"), - run="orders_refresh_job", minimum_interval_seconds=1, ) +def on_source_orders_sensor(ctx): + return RunRequest(job="orders_refresh_job") diff --git a/benchmarks/duckshop/edge_cases/orchestration/custom_orders/sensors/poll_orders_sensor.py b/benchmarks/duckshop/edge_cases/orchestration/custom_orders/sensors/poll_orders_sensor.py index ad888268d6..d38ee6bb85 100644 --- a/benchmarks/duckshop/edge_cases/orchestration/custom_orders/sensors/poll_orders_sensor.py +++ b/benchmarks/duckshop/edge_cases/orchestration/custom_orders/sensors/poll_orders_sensor.py @@ -4,12 +4,11 @@ @sensor( - "poll_orders_sensor", description="Poll fulfillment readiness.", - run="annual_orders_job", minimum_interval_seconds=1, + timeout_seconds=20, ) -def poll_orders(ctx, fulfillment): +def poll_orders_sensor(ctx, fulfillment): def poll(): return fulfillment.poll(ctx) diff --git a/benchmarks/duckshop/edge_cases/orchestration/dynamic_hold_without_dynamic_adapter.json b/benchmarks/duckshop/edge_cases/orchestration/dynamic_hold_without_dynamic_adapter.json new file mode 100644 index 0000000000..67241b1cb7 --- /dev/null +++ b/benchmarks/duckshop/edge_cases/orchestration/dynamic_hold_without_dynamic_adapter.json @@ -0,0 +1,13 @@ +{ + "model": "MODEL (description 'Orders.', materialized table); SELECT 17 AS amount\n", + "dynamic": "[dynamic]\nheartbeat_grace = \"10m\"\n", + "holds": [ + {"run_id": "stopped-build", "model": "daily_totals", "idle_seconds": 900}, + {"run_id": "running-build", "model": "weekly_totals", "idle_seconds": 0} + ], + "lifecycle": [ + "a DuckDB warehouse holds a pause table with one hold silent past the project's grace and one live hold", + "a served location's sync completes", + "DuckDB cannot build dynamic models, so the sync opens no resume session and both holds stay open" + ] +} diff --git a/benchmarks/duckshop/edge_cases/orchestration/failed_import/sensors/broken_orders_sensor.py b/benchmarks/duckshop/edge_cases/orchestration/failed_import/sensors/broken_orders_sensor.py index 454fea133b..56f789790b 100644 --- a/benchmarks/duckshop/edge_cases/orchestration/failed_import/sensors/broken_orders_sensor.py +++ b/benchmarks/duckshop/edge_cases/orchestration/failed_import/sensors/broken_orders_sensor.py @@ -1,12 +1,13 @@ """Negative fixture: a failed declaration import must fail every publication retry.""" -from sqlbuild.orchestration import PlatformEventKind, platform_event, sensor +from sqlbuild.orchestration import PlatformEventKind, RunRequest, platform_event, sensor raise RuntimeError("broken declaration") -broken_orders = sensor( - "broken_orders_sensor", + +@sensor( description="Never declared: the module fails first.", when=platform_event(kinds=[PlatformEventKind.HEARTBEAT]), - run="orders_job", ) +def broken_orders_sensor(ctx): + return RunRequest(job="orders_job") diff --git a/benchmarks/duckshop/edge_cases/orchestration/node_orders/sensors/on_orders_sensor.py b/benchmarks/duckshop/edge_cases/orchestration/node_orders/sensors/on_orders_sensor.py index 40d4d909f0..0ba6524355 100644 --- a/benchmarks/duckshop/edge_cases/orchestration/node_orders/sensors/on_orders_sensor.py +++ b/benchmarks/duckshop/edge_cases/orchestration/node_orders/sensors/on_orders_sensor.py @@ -1,10 +1,11 @@ """Trigger on each real orders rebuild, not on freshness-only success.""" -from sqlbuild.orchestration import NodeEventKind, node_event, sensor +from sqlbuild.orchestration import NodeEventKind, RunRequest, node_event, sensor -on_orders = sensor( - "on_orders_sensor", + +@sensor( description="Build inventory for every genuine orders rebuild.", when=node_event(select="orders orders*", kinds=[NodeEventKind.SUCCESS]), - run="inventory_job", ) +def on_orders_sensor(ctx): + return RunRequest(job="inventory_job") diff --git a/benchmarks/duckshop/edge_cases/orchestration/platform_orders/sensors/other_target_orders_sensor.py b/benchmarks/duckshop/edge_cases/orchestration/platform_orders/sensors/other_target_orders_sensor.py index b3301c5519..bfd595d1b2 100644 --- a/benchmarks/duckshop/edge_cases/orchestration/platform_orders/sensors/other_target_orders_sensor.py +++ b/benchmarks/duckshop/edge_cases/orchestration/platform_orders/sensors/other_target_orders_sensor.py @@ -1,11 +1,12 @@ """A sensor declared for another target is left out of this target's snapshot.""" -from sqlbuild.orchestration import PlatformEventKind, platform_event, sensor +from sqlbuild.orchestration import PlatformEventKind, RunRequest, platform_event, sensor -other_target_orders = sensor( - "other_target_orders_sensor", + +@sensor( description="Refresh another target.", when=platform_event(kinds=[PlatformEventKind.HEARTBEAT]), - run="health_orders_job", targets=("production",), ) +def other_target_orders_sensor(ctx): + return RunRequest(job="health_orders_job") diff --git a/benchmarks/duckshop/edge_cases/orchestration/platform_orders/sensors/overdue_orders_sensor.py b/benchmarks/duckshop/edge_cases/orchestration/platform_orders/sensors/overdue_orders_sensor.py index 6f2d759337..df7592822f 100644 --- a/benchmarks/duckshop/edge_cases/orchestration/platform_orders/sensors/overdue_orders_sensor.py +++ b/benchmarks/duckshop/edge_cases/orchestration/platform_orders/sensors/overdue_orders_sensor.py @@ -1,22 +1,19 @@ -"""A sensor returned from a factory, aliased and held in a cyclic container, is found once.""" +"""A decorated sensor that is aliased and held in a cyclic container is found once.""" -from sqlbuild.orchestration import PlatformEventKind, platform_event, sensor +from sqlbuild.orchestration import PlatformEventKind, RunRequest, platform_event, sensor -def definitions(): - return [ - sensor( - "overdue_orders_sensor", - description="Catch up overdue order reporting.", - when=platform_event(kinds=[PlatformEventKind.TICK_OVERDUE]), - run="health_orders_job", - minimum_interval_seconds=7, - default_status="paused", - targets=("development",), - ) - ] +@sensor( + description="Catch up overdue order reporting.", + when=platform_event(kinds=[PlatformEventKind.TICK_OVERDUE]), + minimum_interval_seconds=7, + default_status="paused", + targets=("development",), +) +def overdue_orders_sensor(ctx): + return RunRequest(job="health_orders_job") -triggers = definitions() +triggers = [overdue_orders_sensor] alias = triggers[0] triggers.append(triggers) diff --git a/benchmarks/duckshop/edge_cases/orchestration/private_folder_sensor/sensors/inventory/_helpers/on_orders_sensor.py b/benchmarks/duckshop/edge_cases/orchestration/private_folder_sensor/sensors/inventory/_helpers/on_orders_sensor.py index b0eae06441..f1da7c9aba 100644 --- a/benchmarks/duckshop/edge_cases/orchestration/private_folder_sensor/sensors/inventory/_helpers/on_orders_sensor.py +++ b/benchmarks/duckshop/edge_cases/orchestration/private_folder_sensor/sensors/inventory/_helpers/on_orders_sensor.py @@ -1,10 +1,11 @@ """A sensor declared inside a private support folder fails compile instead of never running.""" -from sqlbuild.orchestration import NodeEventKind, node_event, sensor +from sqlbuild.orchestration import NodeEventKind, RunRequest, node_event, sensor -on_orders = sensor( - "on_orders_sensor", + +@sensor( description="Build inventory for every genuine orders rebuild.", when=node_event(select="orders orders*", kinds=[NodeEventKind.SUCCESS]), - run="inventory_job", ) +def on_orders_sensor(ctx): + return RunRequest(job="inventory_job") diff --git a/benchmarks/duckshop/edge_cases/orchestration/private_support_orders/sensors/inventory/on_orders_sensor.py b/benchmarks/duckshop/edge_cases/orchestration/private_support_orders/sensors/inventory/on_orders_sensor.py index 9dcfcbb4e5..cf9389df3d 100644 --- a/benchmarks/duckshop/edge_cases/orchestration/private_support_orders/sensors/inventory/on_orders_sensor.py +++ b/benchmarks/duckshop/edge_cases/orchestration/private_support_orders/sensors/inventory/on_orders_sensor.py @@ -2,11 +2,12 @@ from orchestration.sensors.inventory._helpers.selection import ORDERS_SELECTION -from sqlbuild.orchestration import NodeEventKind, node_event, sensor +from sqlbuild.orchestration import NodeEventKind, RunRequest, node_event, sensor -on_orders = sensor( - "on_orders_sensor", + +@sensor( description="Build inventory for every genuine orders rebuild.", when=node_event(select=ORDERS_SELECTION, kinds=[NodeEventKind.SUCCESS]), - run="inventory_job", ) +def on_orders_sensor(ctx): + return RunRequest(job="inventory_job") diff --git a/benchmarks/duckshop/edge_cases/orchestration/run_orders/sensors/on_orders_sensor.py b/benchmarks/duckshop/edge_cases/orchestration/run_orders/sensors/on_orders_sensor.py index d8fbf6746d..4874b7a189 100644 --- a/benchmarks/duckshop/edge_cases/orchestration/run_orders/sensors/on_orders_sensor.py +++ b/benchmarks/duckshop/edge_cases/orchestration/run_orders/sensors/on_orders_sensor.py @@ -1,14 +1,15 @@ """Freeze source-job selectors without executing user code in the scheduler.""" -from sqlbuild.orchestration import RunEventKind, run_event, sensor +from sqlbuild.orchestration import RunEventKind, RunRequest, run_event, sensor -on_orders = sensor( - "on_orders_sensor", + +@sensor( description="Build inventory only after orders actually succeeds.", when=run_event( job="source_orders_job", kinds=[RunEventKind.COMPLETED], executed_successfully=("orders",), ), - run="inventory_job", ) +def on_orders_sensor(ctx): + return RunRequest(job="inventory_job") diff --git a/benchmarks/duckshop/edge_cases/orchestration/source_orders/sensors/on_source_orders_sensor.py b/benchmarks/duckshop/edge_cases/orchestration/source_orders/sensors/on_source_orders_sensor.py index 7ee39f8dd1..dd1ad1f3ad 100644 --- a/benchmarks/duckshop/edge_cases/orchestration/source_orders/sensors/on_source_orders_sensor.py +++ b/benchmarks/duckshop/edge_cases/orchestration/source_orders/sensors/on_source_orders_sensor.py @@ -1,11 +1,12 @@ """Consume changed warehouse source versions without treating a sync poll as new data.""" -from sqlbuild.orchestration import sensor, source_new_data +from sqlbuild.orchestration import RunRequest, sensor, source_new_data -on_source_orders = sensor( - "on_source_orders_sensor", + +@sensor( description="Refresh orders for the first source version and each changed version.", when=source_new_data(select="source:raw_orders"), - run="orders_refresh_job", minimum_interval_seconds=1, ) +def on_source_orders_sensor(ctx): + return RunRequest(job="orders_refresh_job") diff --git a/benchmarks/duckshop/edge_cases/orchestration/stale_orders/sensors/on_stale_orders_sensor.py b/benchmarks/duckshop/edge_cases/orchestration/stale_orders/sensors/on_stale_orders_sensor.py index 01ad500306..9198855351 100644 --- a/benchmarks/duckshop/edge_cases/orchestration/stale_orders/sensors/on_stale_orders_sensor.py +++ b/benchmarks/duckshop/edge_cases/orchestration/stale_orders/sensors/on_stale_orders_sensor.py @@ -1,11 +1,12 @@ """Start one refresh for each timestamp source version older than a minute.""" -from sqlbuild.orchestration import sensor, source_stale +from sqlbuild.orchestration import RunRequest, sensor, source_stale -on_stale_orders = sensor( - "on_stale_orders_sensor", + +@sensor( description="Refresh orders once for each timestamp version older than one minute.", when=source_stale(select="source:raw_orders", after_seconds=60), - run="orders_refresh_job", minimum_interval_seconds=1, ) +def on_stale_orders_sensor(ctx): + return RunRequest(job="orders_refresh_job") diff --git a/benchmarks/duckshop/edge_cases/python_rules/conforming/orchestration/sensors/fulfillment/shipment_backlog.py b/benchmarks/duckshop/edge_cases/python_rules/conforming/orchestration/sensors/fulfillment/shipment_backlog.py index 0a9c1bdbe3..bc738e0a3f 100644 --- a/benchmarks/duckshop/edge_cases/python_rules/conforming/orchestration/sensors/fulfillment/shipment_backlog.py +++ b/benchmarks/duckshop/edge_cases/python_rules/conforming/orchestration/sensors/fulfillment/shipment_backlog.py @@ -9,10 +9,8 @@ @sensor( - "shipment_backlog_sensor", description="Rebuild shipments when the backlog grows.", - run="restock_shipments_job", minimum_interval_seconds=60, ) -def shipment_backlog(ctx: SensorContext) -> SkipReason: +def shipment_backlog_sensor(ctx: SensorContext[None]) -> SkipReason: return SkipReason(prefixed(BACKLOG_REASON) + _REASON_SUFFIX) diff --git a/benchmarks/duckshop/edge_cases/python_rules/expected_findings.json b/benchmarks/duckshop/edge_cases/python_rules/expected_findings.json index 6b7fa5c2c4..dc6170c9ed 100644 --- a/benchmarks/duckshop/edge_cases/python_rules/expected_findings.json +++ b/benchmarks/duckshop/edge_cases/python_rules/expected_findings.json @@ -8,7 +8,7 @@ ["SQBRPYTHON016", "orchestration/sensors/stock_feed.py", 1, 1], ["SQBRPYTHON019", "orchestration/sensors/stock_feed.py", 3, 8], ["SQBRPYTHON018", "orchestration/sensors/stock_feed.py", 7, 1], - ["SQBRPYTHON020", "orchestration/sensors/stock_feed.py", 16, 5], + ["SQBRPYTHON020", "orchestration/sensors/stock_feed.py", 14, 5], ["SQBRPYTHON015", "providers/carrier_api/provider.py", 3, 8], ["SQBRPYTHON014", "providers/carrier_api/provider.py", 8, 5], ["SQBRPYTHON013", "providers/stock_feed.py", 1, 1], diff --git a/benchmarks/duckshop/edge_cases/python_rules/violations/orchestration/sensors/stock_feed.py b/benchmarks/duckshop/edge_cases/python_rules/violations/orchestration/sensors/stock_feed.py index b6998d0668..7a4ce09da2 100644 --- a/benchmarks/duckshop/edge_cases/python_rules/violations/orchestration/sensors/stock_feed.py +++ b/benchmarks/duckshop/edge_cases/python_rules/violations/orchestration/sensors/stock_feed.py @@ -8,11 +8,9 @@ @sensor( - "stock_feed_stale_sensor", description="Count stock when the supplier feed goes stale.", - run="stock_count_job", minimum_interval_seconds=60, ) -def stock_feed_stale(ctx: SensorContext) -> SkipReason: +def stock_feed_stale_sensor(ctx: SensorContext[None]) -> SkipReason: """Count stock when the supplier feed goes stale.""" return SkipReason(f"{STALE_REASON} {python.report.__name__}") diff --git a/benchmarks/duckshop/project/orchestration/sensors/edge_cases/edge_group_outcomes_sensor.py b/benchmarks/duckshop/project/orchestration/sensors/edge_cases/edge_group_outcomes_sensor.py index a1f8a750dc..286c3a6b20 100644 --- a/benchmarks/duckshop/project/orchestration/sensors/edge_cases/edge_group_outcomes_sensor.py +++ b/benchmarks/duckshop/project/orchestration/sensors/edge_cases/edge_group_outcomes_sensor.py @@ -1,15 +1,16 @@ """Observe group completion, including cancellation and presumed failure.""" -from sqlbuild.orchestration import RunEventKind, run_event, sensor +from sqlbuild.orchestration import RunEventKind, RunRequest, run_event, sensor -edge_group_outcomes = sensor( - "edge_group_outcomes_sensor", + +@sensor( description="Observe group completion including cancellation and presumed failure.", when=run_event( job="edge_snapshot_job_group", kinds=[RunEventKind.COMPLETED], executed_successfully=("tag:edge_case",), ), - run="edge_snapshot_inventory_job", default_status="paused", ) +def edge_group_outcomes_sensor(ctx): + return RunRequest(job="edge_snapshot_inventory_job") diff --git a/benchmarks/duckshop/project/orchestration/sensors/edge_cases/edge_job_outcomes_sensor.py b/benchmarks/duckshop/project/orchestration/sensors/edge_cases/edge_job_outcomes_sensor.py index fc35482e56..bd601e2aac 100644 --- a/benchmarks/duckshop/project/orchestration/sensors/edge_cases/edge_job_outcomes_sensor.py +++ b/benchmarks/duckshop/project/orchestration/sensors/edge_cases/edge_job_outcomes_sensor.py @@ -1,11 +1,12 @@ """Keep warning and partial job outcomes distinct from success.""" -from sqlbuild.orchestration import RunEventKind, run_event, sensor +from sqlbuild.orchestration import RunEventKind, RunRequest, run_event, sensor -edge_job_outcomes = sensor( - "edge_job_outcomes_sensor", + +@sensor( description="Keep warning and partial outcomes distinct from success.", when=run_event(job="edge_snapshot_orders_job", kinds=[RunEventKind.WARN, RunEventKind.PARTIAL]), - run="edge_snapshot_inventory_job", default_status="paused", ) +def edge_job_outcomes_sensor(ctx): + return RunRequest(job="edge_snapshot_inventory_job") diff --git a/benchmarks/duckshop/project/orchestration/sensors/edge_cases/edge_platform_orders_sensor.py b/benchmarks/duckshop/project/orchestration/sensors/edge_cases/edge_platform_orders_sensor.py index 5275a45811..2b5648e76f 100644 --- a/benchmarks/duckshop/project/orchestration/sensors/edge_cases/edge_platform_orders_sensor.py +++ b/benchmarks/duckshop/project/orchestration/sensors/edge_cases/edge_platform_orders_sensor.py @@ -1,9 +1,9 @@ """Exercise alias deduplication and cyclic containers while discovering a sensor module.""" -from sqlbuild.orchestration import PlatformEventKind, platform_event, sensor +from sqlbuild.orchestration import PlatformEventKind, RunRequest, platform_event, sensor -edge_health = sensor( - "edge_platform_orders_sensor", + +@sensor( description="Catch up retained platform observations with a stopped group sensor.", when=platform_event( kinds=[ @@ -12,10 +12,13 @@ PlatformEventKind.LAUNCH_FAILED, ] ), - run="edge_snapshot_job_group", minimum_interval_seconds=7, default_status="paused", ) -edge_alias = edge_health -edge_factory_results = [[edge_health], (edge_alias,)] +def edge_platform_orders_sensor(ctx): + return RunRequest(job="edge_snapshot_job_group") + + +edge_alias = edge_platform_orders_sensor +edge_factory_results = [[edge_platform_orders_sensor], (edge_alias,)] edge_factory_results.append(edge_factory_results) diff --git a/clients/typescript/src/schema.d.ts b/clients/typescript/src/schema.d.ts index 73b65d5055..066fd0b112 100644 --- a/clients/typescript/src/schema.d.ts +++ b/clients/typescript/src/schema.d.ts @@ -210,6 +210,22 @@ export interface paths { patch?: never; trace?: never; }; + "/api/auth/password/people": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + post: operations["createPasswordPerson"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/auth/session": { parameters: { query?: never; @@ -914,6 +930,22 @@ export interface paths { patch?: never; trace?: never; }; + "/api/control/locations/{location_id}/targets/{target}/sensors/{name}/events": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get: operations["readPersonSensorEvents"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/control/locations/{location_id}/targets/{target}/snapshots": { parameters: { query?: never; @@ -1542,6 +1574,11 @@ export interface paths { export type webhooks = Record; export interface components { schemas: { + /** + * @description Why a tick ended before its function's answer was committed. + * @enum {string} + */ + AbandonReason: "unanswered" | "superseded" | "republished" | "paused" | "cursor_reset" | "leader_changed" | "skipped"; /** @description Marks a run as handled for everyone who can see it, or withdraws the mark; retried with the same event ID it applies once. */ AcknowledgementRequest: { acknowledged: boolean; @@ -1800,6 +1837,11 @@ export interface components { /** Format: uuid */ session_id: string; }; + /** + * @description How a check, audit or SQL test that ran inside a run fell short. + * @enum {string} + */ + CheckEventKind: "failed" | "warn"; /** @description One result's stored evidence rows; `view.evidence` reads them, audited. */ CheckEvidence: { binding_key: string; @@ -1986,24 +2028,6 @@ export interface components { }; record: components["schemas"]["SnapshotRecord"]; }; - /** @description Location-owned Python returns data; only the fenced scheduler may apply it. */ - CustomSensorOutcome: { - cursor?: string | null; - run_keys: string[]; - /** @enum {string} */ - status: "completed"; - } | { - cursor?: string | null; - reason: string; - /** @enum {string} */ - status: "skipped"; - } | { - /** @enum {string} */ - status: "failed"; - } | { - /** @enum {string} */ - status: "timed_out"; - }; /** @description Where a declaration was written, relative to the project root. */ DeclaredAt: { /** Format: int32 */ @@ -2026,6 +2050,20 @@ export interface components { /** @enum {string} */ status: "unavailable"; }; + /** @description A calendar whose pending past-due times a republish dropped, because its previous definition can't be read; it clears at its next successful tick. */ + DroppedCalendarTimes: { + /** Format: date-time */ + dropped_at: string; + /** Format: uuid */ + location_id: string; + location_name: string; + name: string; + target: string; + /** @description The times that were due by the republish but never ticked, oldest first. */ + times: string[]; + /** Format: uuid */ + trigger_id: string; + }; ExternalIdentityResponse: { csrf_token: string; /** Format: date-time */ @@ -2224,8 +2262,13 @@ export interface components { generation: number; /** @enum {string} */ kind: "provider_secrets"; - /** Format: int64 */ + /** + * Format: int64 + * @description Unset secrets of providers the target doesn't allow to miss them; above zero is a health problem. + */ missing: number; + /** @description Every provider missing a secret, including those the target allows; names only, never values. */ + providers: components["schemas"]["MissingProviderSecrets"][]; } | { /** Format: int64 */ generation: number; @@ -2308,6 +2351,12 @@ export interface components { command: string[]; /** @description Plan again even when the location kept a plan for the same request. */ fresh: boolean; + /** @description The settings the command gives, `warehouse` included though a plan never takes it; they replace the pinned jobs' own. */ + given?: string[]; + /** @description The jobs the command names, pinned as an ad-hoc build of it pins them. */ + jobs?: { + [key: string]: components["schemas"]["PinnedJob"]; + }; /** @enum {string} */ kind: "plan"; selection: string[]; @@ -2331,7 +2380,7 @@ export interface components { } | { /** @enum {string} */ kind: "sensor_evaluation"; - outcome: components["schemas"]["CustomSensorOutcome"]; + outcome: components["schemas"]["SensorFunctionOutcome"]; } | { /** @description Model diff text, which the document never carries; stored apart, never read back here. */ diffs?: { @@ -2484,6 +2533,24 @@ export interface components { physical_generation_id: string; target_name: string; }; + /** @description A provider whose required secrets are unset: what is missing and which nodes need it, never a value. */ + MissingProviderSecrets: { + /** @description The target's `allow_missing_secrets` lists the provider, so its location shows a note, not a problem. */ + allowed: boolean; + /** @description Snapshot node keys that run the provider, such as `source:raw_payments`. */ + nodes: string[]; + /** @description The provider's file, relative to the project directory. */ + path: string; + provider: string; + settings: components["schemas"]["MissingProviderSetting"][]; + }; + /** @description One unset required setting: the field, the variable it reads and the field's line in the provider file. */ + MissingProviderSetting: { + field: string; + /** Format: int64 */ + line?: number | null; + variable: string; + }; MutationResponse: { applied: boolean; }; @@ -2642,6 +2709,12 @@ export interface components { password: string; username: string; }; + /** @description A person to add who signs in with a password: their sign-in name, first password and built-in role everywhere, if any. */ + PasswordPersonRequest: { + name: string; + password: string; + role?: null | components["schemas"]["BuiltinRole"]; + }; PasswordSessionResponse: { csrf_token: string; identity: components["schemas"]["SessionIdentity"]; @@ -2654,6 +2727,11 @@ export interface components { /** Format: uuid */ principal_id: string; }; + /** @description The person just added. */ + PersonCreated: { + /** Format: uuid */ + principal_id: string; + }; /** @description A stored platform event a person may see; the location target is absent for server-wide events. */ PersonPlatformEvent: { event: components["schemas"]["PlatformEvent"]; @@ -2688,28 +2766,41 @@ export interface components { role_key: string; target?: string | null; }; - /** @description The control event position built-in conditions read from, and a custom sensor's own value after secret redaction; the value needs view.evidence. */ + /** @description The event position a condition reads from, and a polling sensor's own value after secret redaction; the value needs view.evidence. */ PersonSensorCursor: { custom?: string | null; /** Format: int64 */ event_storage_id: number; }; PersonSensorEvaluation: { + abandoned_because?: null | components["schemas"]["AbandonReason"]; cursor_after?: null | components["schemas"]["PersonSensorCursor"]; cursor_before: components["schemas"]["PersonSensorCursor"]; definition_fingerprint: string; + /** @description The traceback or refusal of a failed tick, redacted; needs view.evidence. */ + error?: string | null; /** Format: uuid */ evaluation_id: string; - /** @description The failure code of a failed check. */ + /** @description The event the function was called with; absent for a polling sensor. */ + event_id?: string | null; + event_summary?: string | null; + /** @description The failure code of a failed tick. */ failure_code?: string | null; /** Format: date-time */ finished_at?: string | null; - /** @description The latest phase: `requested` alone means the check is in flight; otherwise `completed`, `failed`, `timed_out` or `abandoned`. */ + /** @description What the function did: `handled`, `skipped`, `started`, `failed`, `timed_out`, `abandoned`, or `running` while in flight. */ + outcome: string; + /** @description The latest phase: `requested` alone means the tick is in flight; otherwise `completed`, `failed`, `timed_out` or `abandoned`. */ phase: string; /** Format: date-time */ requested_at: string; - run_count: number; - /** @description For each matched request the job's `skip` overlap dropped, the run that was active. */ + /** @description The runs the tick started. */ + run_ids: string[]; + /** @description Why the function skipped, redacted; needs view.evidence. */ + skip_reason?: string | null; + /** @description The operator who skipped the tick's event, so the function wasn't called. */ + skipped_by?: string | null; + /** @description For each requested run the job's `skip` overlap dropped, the run that was active. */ skipped_for: string[]; }; /** @description A run key is redacted and withheld like the custom cursor it usually derives from: empty without view.evidence. */ @@ -2730,6 +2821,7 @@ export interface components { definition_fingerprint: string; /** @description Newest first. */ evaluations: components["schemas"]["PersonSensorEvaluation"][]; + failing?: null | components["schemas"]["SensorFailing"]; /** @description Runs the sensor requested, by run key, newest first. */ run_requests: components["schemas"]["PersonSensorRunRequest"][]; }; @@ -2778,6 +2870,7 @@ export interface components { /** @description A trigger as people list it, with its newest tick so a list needs no read per trigger. */ PersonTriggerRecord: components["schemas"]["TriggerRecord"] & { latest_tick?: null | components["schemas"]["TickRecord"]; + sensor_failing?: null | components["schemas"]["SensorFailing"]; /** @description A running schedule's next due times from `next_due_at` on, at most five; empty otherwise. */ upcoming: string[]; }; @@ -2797,6 +2890,13 @@ export interface components { /** @enum {string} */ status: "unavailable"; }; + /** @description A job an ad-hoc selection names: the frozen nodes it gives its settings to, and those settings. */ + PinnedJob: { + selection: string[]; + settings: { + [key: string]: unknown; + }; + }; /** @description A planned model's diff text, stored beside its plan document. */ PlanDiffRead: components["schemas"]["PlanModelDiff"] & { model: string; @@ -2914,21 +3014,52 @@ export interface components { run_id: string; run_kind: components["schemas"]["RunKind"]; target: string; + } | { + /** @enum {string} */ + kind: "trigger_skipped"; + reason: string; + /** Format: uuid */ + snapshot_id: string; + /** Format: uuid */ + trigger_id: string; + } | { + /** Format: uuid */ + evaluation_id: string; + /** @enum {string} */ + kind: "sensor_rechecked"; + /** Format: uuid */ + snapshot_id: string; + /** Format: uuid */ + trigger_id: string; + } | { + /** @enum {string} */ + kind: "calendar_times_dropped"; + /** Format: uuid */ + snapshot_id: string; + times: string[]; + /** Format: uuid */ + trigger_id: string; }; /** @enum {string} */ - PlatformEventKind: "heartbeat" | "scheduler_no_leader" | "tick_overdue" | "calendar_horizon_low" | "location_broken" | "launch_failed" | "run_failed"; + PlatformEventKind: "heartbeat" | "scheduler_no_leader" | "tick_overdue" | "calendar_horizon_low" | "location_broken" | "launch_failed" | "run_failed" | "trigger_skipped" | "sensor_rechecked" | "calendar_times_dropped"; /** @description Problems derived from live state when read; nothing here is stored. */ PlatformProblems: { broken_locations: components["schemas"]["BrokenLocation"][]; + /** @description Calendars whose pending times a republish dropped, until their next successful tick. */ + dropped_calendar_times?: components["schemas"]["DroppedCalendarTimes"][]; /** @description Running calendar schedules whose dates run out within a day. */ low_calendars?: components["schemas"]["LowCalendar"][]; overdue_ticks: components["schemas"]["OverdueTick"][]; + /** @description Sensors checked again from scratch because their last check can't be read, until a check completes. */ + rechecked_sensors?: components["schemas"]["RecheckedSensor"][]; scheduler_leader: boolean; /** * Format: date-time * @description When the last scheduler lease ran out, or will run out; absent until a server first leads. */ scheduler_lease_expires_at?: string | null; + /** @description Triggers skipped because their stored job or pinned snapshot can't be read, until their location publishes again. */ + skipped_triggers?: components["schemas"]["SkippedTrigger"][]; }; /** @description A job or group asking for more of a pool than this server's cap, so it runs alone in that pool. */ PoolCapWarning: { @@ -3162,6 +3293,23 @@ export interface components { kind: "blob"; value: number[]; }; + /** @description A sensor whose last check, recorded by an earlier release, can't be read, so it is checked again from scratch; it clears once a check completes. */ + RecheckedSensor: { + /** Format: uuid */ + location_id: string; + location_name: string; + name: string; + /** Format: date-time */ + rechecked_at: string; + target: string; + /** Format: uuid */ + trigger_id: string; + }; + /** @description A run a sensor's function asked for; the key defaults to the event ID and the job. */ + RequestedRun: { + job: string; + run_key: string; + }; /** @description A retry derives its execution scope from a terminal run, never from caller selectors. */ RerunRequest: { from_failure: boolean; @@ -3520,6 +3668,14 @@ export interface components { command?: components["schemas"]["RunCommand"]; image_id?: string | null; job_key?: string | null; + /** @description The build-wide settings those jobs give where `settings` is silent; they decide its gates and write set. */ + job_settings?: { + [key: string]: unknown; + }; + /** @description The jobs an ad-hoc build's selection names, each pinned to its frozen nodes and settings. */ + jobs?: { + [key: string]: components["schemas"]["PinnedJob"]; + }; kind: components["schemas"]["RunKind"]; /** Format: uuid */ location_id: string; @@ -3728,6 +3884,7 @@ export interface components { /** @description `tag:` values: the SQL resources and Python nodes with each tag. */ tags: components["schemas"]["VocabularyEntry"][]; }; + /** @description What wakes a sensor; a sensor without one polls every `minimum_interval_seconds`. */ SensorCondition: { /** @enum {string} */ kind: "platform_event"; @@ -3743,6 +3900,11 @@ export interface components { kind: "node_event"; kinds: components["schemas"]["NodeEventKind"][]; selection: string[]; + } | { + /** @enum {string} */ + kind: "check_event"; + kinds: components["schemas"]["CheckEventKind"][]; + selection: string[]; } | { /** @enum {string} */ kind: "source_new_data"; @@ -3753,22 +3915,142 @@ export interface components { /** @enum {string} */ kind: "source_stale"; selection: string[]; - } | { - code_hash: string; - function: string; - /** @enum {string} */ - kind: "custom"; }; + /** @description A sensor: the function the location runs, and the condition that wakes it. */ SensorDefinition: { + code_hash: string; declared_at?: null | components["schemas"]["DeclaredAt"]; default_status?: components["schemas"]["TriggerStatus"]; description: string; - job_key: string; + /** @description The decorated function's name, such as `orders_failed`. */ + function: string; /** Format: int32 */ minimum_interval_seconds: number; /** @description The targets the declaration is limited to; empty for every target. */ targets?: string[]; - when: components["schemas"]["SensorCondition"]; + /** + * Format: int32 + * @description How long one call of the function may take before its tick fails. + */ + timeout_seconds: number; + when?: null | components["schemas"]["SensorCondition"]; + }; + /** @description One event a sensor's function is called with; `id` is stable across redeliveries. */ + SensorEvent: { + error?: string | null; + failed_checks: string[]; + failed_nodes: string[]; + id: string; + job: string; + /** @enum {string} */ + kind: "run"; + /** Format: date-time */ + occurred_at: string; + /** Format: uuid */ + run_id: string; + status: components["schemas"]["RunOutcome"]; + target: string; + url?: string | null; + } | { + event: components["schemas"]["NodeEventKind"]; + id: string; + job?: string | null; + /** @enum {string} */ + kind: "node"; + node: string; + /** Format: date-time */ + occurred_at: string; + /** Format: uuid */ + run_id: string; + target: string; + url?: string | null; + } | { + check: string; + id: string; + job?: string | null; + /** @enum {string} */ + kind: "check"; + /** Format: date-time */ + occurred_at: string; + /** Format: uuid */ + run_id: string; + status: components["schemas"]["CheckEventKind"]; + target: string; + url?: string | null; + } | { + data_version?: string | null; + id: string; + /** @enum {string} */ + kind: "source_new_data"; + /** Format: date-time */ + occurred_at: string; + source: string; + target: string; + } | { + /** Format: int32 */ + after_seconds: number; + data_version?: string | null; + id: string; + /** @enum {string} */ + kind: "source_stale"; + /** Format: date-time */ + occurred_at: string; + source: string; + target: string; + } | { + details: Record; + event: components["schemas"]["PlatformEventKind"]; + id: string; + /** @enum {string} */ + kind: "platform"; + /** Format: date-time */ + occurred_at: string; + }; + /** @description A sensor whose latest ticks failed: since when, and the event it is stuck on. */ + SensorFailing: { + /** @description The event the failed ticks were called with; absent for a polling sensor. */ + event_id?: string | null; + event_summary?: string | null; + failed_ticks: number; + /** @description Why the newest failing tick failed, when the function gave no error, as for a location that didn't answer. */ + reason?: string | null; + /** + * Format: date-time + * @description When the first of the failed ticks since the last good one started. + */ + since: string; + }; + /** @description What one call of a sensor's function returned; only the fenced scheduler applies it. */ + SensorFunctionOutcome: { + cursor?: string | null; + /** @enum {string} */ + status: "handled"; + } | { + cursor?: string | null; + reason: string; + /** @enum {string} */ + status: "skipped"; + } | { + cursor?: string | null; + runs: components["schemas"]["RequestedRun"][]; + /** @enum {string} */ + status: "requested"; + } | { + error: string; + /** @enum {string} */ + status: "failed"; + } | { + /** @enum {string} */ + status: "timed_out"; + }; + /** @description A published sensor and the events a trial chose for it, newest first. */ + SensorTrialEvents: { + events: components["schemas"]["SensorEvent"][]; + function: string; + sensor: string; + /** Format: int32 */ + timeout_seconds: number; + when?: null | components["schemas"]["SensorCondition"]; }; /** @description How long the server keeps each kind of record. */ ServerRetention: { @@ -3822,6 +4104,22 @@ export interface components { /** Format: uuid */ session_id: string; }; + /** @description A trigger the scheduler skips because its stored job or pinned snapshot can't be read, or a sensor whose check failed; it clears once its location publishes again or, for a sensor, a later check completes. */ + SkippedTrigger: { + /** Format: uuid */ + location_id: string; + location_name: string; + name: string; + reason: string; + /** + * Format: date-time + * @description When it was first skipped for this snapshot. + */ + skipped_at: string; + target: string; + /** Format: uuid */ + trigger_id: string; + }; /** @description Node-level changes do not duplicate unchanged definitions or source text. */ SnapshotChange: { after_hash?: string | null; @@ -3956,6 +4254,10 @@ export interface components { } | { /** @enum {string} */ kind: "reset_cursor"; + } | { + event: string; + /** @enum {string} */ + kind: "skip_event"; }; TriggerChangeRecord: { /** Format: date-time */ @@ -3988,7 +4290,8 @@ export interface components { }; TriggerRecord: { definition_json: components["schemas"]["TriggerDeclaration"]; - job_key: string; + /** @description The job or group a schedule starts; `None` for a sensor, whose function chooses. */ + job_key?: string | null; /** Format: date-time */ last_tick_for?: string | null; name: string; @@ -4753,6 +5056,56 @@ export interface operations { }; }; }; + createPasswordPerson: { + parameters: { + query?: never; + header: { + /** @description Session CSRF token */ + "x-sqb-csrf": string; + }; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["PasswordPersonRequest"]; + }; + }; + responses: { + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["PersonCreated"]; + }; + }; + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; + }; + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AuthenticationDenial"]; + }; + }; + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; + }; + }; + }; currentSession: { parameters: { query?: never; @@ -5125,7 +5478,10 @@ export interface operations { listPersonChecks: { parameters: { query?: never; - header?: never; + header?: { + /** @description An ETag from an earlier response; 304 while every check's newest result is unchanged */ + "If-None-Match"?: string | null; + }; path: { location_id: string; target: string; @@ -5137,12 +5493,22 @@ export interface operations { /** @description The newest result of every check */ 200: { headers: { + /** @description ":", or "" before the first publication */ + ETag?: string; [name: string]: unknown; }; content: { "application/json": components["schemas"]["CheckResult"][]; }; }; + /** @description Unchanged since the If-None-Match ETag */ + 304: { + headers: { + ETag?: string; + [name: string]: unknown; + }; + content?: never; + }; /** @description Session rejected */ 401: { headers: { @@ -6751,6 +7117,67 @@ export interface operations { }; }; }; + readPersonSensorEvents: { + parameters: { + query?: never; + header?: never; + path: { + location_id: string; + target: string; + name: string; + limit: number | null; + latest: boolean | null; + event: string | null; + run: string | null; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description The published sensor and the chosen events, newest first; reading them changes nothing */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["SensorTrialEvents"]; + }; + }; + /** @description More than one of latest, event and run */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; + }; + /** @description Session rejected */ + 401: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; + }; + /** @description No such sensor, event or matching run, and why */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; + }; + }; + }; listPersonSnapshots: { parameters: { query?: { diff --git a/crates/README.md b/crates/README.md index d77addadd6..824db62595 100644 --- a/crates/README.md +++ b/crates/README.md @@ -182,7 +182,7 @@ Triggers start paused before scheduling can begin. Publication pauses newly intr triggers in the same transaction as the snapshot, using ordinary audited operator facts rather than rewriting code definitions. Reload preserves explicit operator changes to retained triggers. `--triggers` skips these automatic pauses; it does not undo an operator's persisted pause. -SIGINT or SIGTERM shuts down the scheduler, API streams and location interpreter together. +SIGINT, SIGTERM or SIGHUP shuts down the scheduler, API streams and location interpreter together. ## Warehouse event identity diff --git a/crates/sqlbuild-analysis/src/analysis_route/_helpers/dialects/bigquery_dialect.rs b/crates/sqlbuild-analysis/src/analysis_route/_helpers/dialects/bigquery_dialect.rs index 2de8b6192c..58091bd099 100644 --- a/crates/sqlbuild-analysis/src/analysis_route/_helpers/dialects/bigquery_dialect.rs +++ b/crates/sqlbuild-analysis/src/analysis_route/_helpers/dialects/bigquery_dialect.rs @@ -139,8 +139,10 @@ impl LineageSchema for BigQueryTypes<'_> { /// A type BigQuery's dry run accepts, as BigQuery names it; `None` for one it refuses. fn native_type(data_type: &DataType) -> Option { Some(match data_type { - DataType::BigInt { length: None } => "INT64".to_owned(), - DataType::Decimal { precision, scale } => { + DataType::BigInt { length: None, .. } => "INT64".to_owned(), + DataType::Decimal { + precision, scale, .. + } => { let given: Vec = [*precision, *scale].into_iter().flatten().collect(); decimal("NUMERIC", &given, NUMERIC_DIGITS)? } @@ -155,14 +157,17 @@ fn native_type(data_type: &DataType) -> Option { DataType::Time { precision: None, timezone: false, + .. } => "TIME".to_owned(), DataType::Timestamp { precision: None, timezone: false, + .. } => "DATETIME".to_owned(), DataType::Timestamp { precision: None, timezone: true, + .. } => "TIMESTAMP".to_owned(), DataType::Interval { unit: None, diff --git a/crates/sqlbuild-analysis/src/analysis_route/_helpers/dialects/databricks_dialect.rs b/crates/sqlbuild-analysis/src/analysis_route/_helpers/dialects/databricks_dialect.rs index 23a37654d4..d83be763ce 100644 --- a/crates/sqlbuild-analysis/src/analysis_route/_helpers/dialects/databricks_dialect.rs +++ b/crates/sqlbuild-analysis/src/analysis_route/_helpers/dialects/databricks_dialect.rs @@ -130,7 +130,9 @@ fn canonical(data_type: &DataType) -> Option { DataType::String { .. } | DataType::Char { .. } | DataType::VarChar { .. } => { DATABRICKS_STRING_TYPE.to_owned() } - DataType::Decimal { precision, scale } => { + DataType::Decimal { + precision, scale, .. + } => { let (default_precision, default_scale) = DATABRICKS_DEFAULT_DECIMAL; format!( "DECIMAL({},{})", diff --git a/crates/sqlbuild-analysis/src/analysis_route/tests/test_bigquery_dialect.rs b/crates/sqlbuild-analysis/src/analysis_route/tests/test_bigquery_dialect.rs index 595f18436e..7bad745656 100644 --- a/crates/sqlbuild-analysis/src/analysis_route/tests/test_bigquery_dialect.rs +++ b/crates/sqlbuild-analysis/src/analysis_route/tests/test_bigquery_dialect.rs @@ -401,7 +401,7 @@ fn given_sql_bigquery_refuses_when_parsing_then_the_gap_says_whether_it_is_a_syn }, ParseFailureTestCase { description: "the nesting limit is not a syntax error", - sql: format!("SELECT {}1{}", "(".repeat(300), ")".repeat(300)), + sql: format!("SELECT {}1{}", "(".repeat(600), ")".repeat(600)), expected_syntax: false, expected_offset: None, }, diff --git a/crates/sqlbuild-analysis/src/analysis_route/tests/test_databricks_dialect.rs b/crates/sqlbuild-analysis/src/analysis_route/tests/test_databricks_dialect.rs index 3126ff3d5e..5296d4e3de 100644 --- a/crates/sqlbuild-analysis/src/analysis_route/tests/test_databricks_dialect.rs +++ b/crates/sqlbuild-analysis/src/analysis_route/tests/test_databricks_dialect.rs @@ -45,11 +45,11 @@ fn given_databricks_model_sql_when_probing_its_parser_then_only_sql_it_reads_who }, NativeGapTestCase { description: "a construct the shared tree lacks is a gap named by the parser", - sql: "VACUUM t", + sql: "REPAIR PRIVILEGES t", placeholders: &[], expected_gap: Some(LocatedGap { - construct: "vacuum".to_owned(), - message: "vacuum".to_owned(), + construct: "repair".to_owned(), + message: "repair".to_owned(), line: 1, column: 1, syntax: false, @@ -275,7 +275,7 @@ fn given_sql_databricks_refuses_when_parsing_then_the_gap_says_whether_it_is_a_s }, ParseFailureTestCase { description: "the nesting limit is not a syntax error", - sql: format!("SELECT {}1{}", "(".repeat(300), ")".repeat(300)), + sql: format!("SELECT {}1{}", "(".repeat(600), ")".repeat(600)), expected_syntax: false, expected_offset: None, }, diff --git a/crates/sqlbuild-analysis/src/compiler/_helpers/sql_tests/mod.rs b/crates/sqlbuild-analysis/src/compiler/_helpers/sql_tests/mod.rs index 29fd6921cc..5ec8b68396 100644 --- a/crates/sqlbuild-analysis/src/compiler/_helpers/sql_tests/mod.rs +++ b/crates/sqlbuild-analysis/src/compiler/_helpers/sql_tests/mod.rs @@ -13,6 +13,7 @@ pub mod helper_scope; pub mod macro_call_names; pub mod markers; pub mod mock_reads; +pub(crate) mod partition_inputs; pub mod planning; pub mod reader_references; pub(crate) mod real_model_limit; diff --git a/crates/sqlbuild-analysis/src/compiler/_helpers/sql_tests/partition_inputs.rs b/crates/sqlbuild-analysis/src/compiler/_helpers/sql_tests/partition_inputs.rs new file mode 100644 index 0000000000..3e514510b5 --- /dev/null +++ b/crates/sqlbuild-analysis/src/compiler/_helpers/sql_tests/partition_inputs.rs @@ -0,0 +1,481 @@ +//! A mocked call's `TABLE( )` dropped, and a partitioned call's inputs read as one row, as a build gives them. + +use std::collections::BTreeMap; + +use regex::Regex; + +use crate::compiler::_helpers::sql_tests::markers::ProtectedRanges; +use crate::compiler::_helpers::sql_tests::planning::compile_error; +use crate::relation_markers::main::lateral_start::lateral_start; +use sqlbuild_sqltext::resolution::main::over_clause_open::over_clause_open; +use sqlbuild_sqltext::sql_scan::main::dialect_matching_paren::dialect_matching_paren; +use sqlbuild_sqltext::sql_scan::main::skip_whitespace::skip_whitespace; +use sqlbuild_sqltext::sql_scan::models::LexicalSyntax; + +const FROM_KEYWORD: &str = "from"; +const SELECT_KEYWORD: &str = "select"; +const TABLE_KEYWORD: &str = "table"; +const AS_KEYWORD: &str = "as"; +const PARTITION_KEYWORD: &str = "partition"; +const BY_KEYWORD: &str = "by"; +const CROSS_JOIN: &str = " CROSS JOIN "; +const INPUTS_ALIAS: &str = "__sqb_partition_inputs"; +const CALL_ALIAS: &str = "__sqb_partition_call"; +const JOIN_WORDS: [&str; 8] = [ + "join", "cross", "inner", "left", "right", "full", "outer", "natural", +]; +const SET_OPERATORS: [&str; 4] = ["union", "intersect", "except", "minus"]; +/// Words after a relation that are not its alias. +const CLAUSE_WORDS: [&str; 24] = [ + "where", + "group", + "having", + "qualify", + "order", + "limit", + "offset", + "fetch", + "window", + "on", + "using", + "join", + "cross", + "inner", + "left", + "right", + "full", + "natural", + "lateral", + "union", + "intersect", + "except", + "minus", + "match_recognize", +]; + +/// The edits to one SQL text, by start: each one's end and replacement. +type Edits = BTreeMap; + +/// `sql` with each mocked call out of `TABLE( )` and each mocked partitioned call's inputs as `p RIGHT JOIN (SELECT 1) ON FALSE`, its `PARTITION BY` columns read from the fixture's columns of the same name. +pub(crate) fn collapse_partition_inputs( + sql: &str, + pattern: &Regex, + syntax: &LexicalSyntax, + fixture_columns: impl Fn(&str) -> Option>, +) -> Result { + let mut protected = ProtectedRanges::new(syntax, sql); + let mut edits: Edits = BTreeMap::new(); + let mut collapsed = 0; + for captures in pattern.captures_iter(sql) { + let (Some(full), Some(name)) = (captures.get(0), captures.get(1)) else { + continue; + }; + if protected.contains(full.start()) { + continue; + } + let Some(columns) = fixture_columns(name.as_str()) else { + continue; + }; + let arguments = skip_whitespace(sql, full.end()); + if !sql[arguments..].starts_with('(') { + continue; + } + let Ok(close) = dialect_matching_paren(sql.as_bytes(), arguments, syntax) else { + continue; + }; + let over = over_clause_open(sql, close + 1, &syntax.line_comment_prefixes) + .filter(|over| !protected.contains(*over)); + let over_close = match over.map(|over| dialect_matching_paren(sql.as_bytes(), over, syntax)) + { + Some(Ok(over_close)) => Some(over_close), + Some(Err(_)) => continue, + None => None, + }; + let call = (full.start(), over_close.unwrap_or(close) + 1); + let (relation, unwrapping) = unwrapped(sql, call, syntax); + edits.extend(unwrapping); + let (Some(over), Some(over_close)) = (over, over_close) else { + continue; + }; + let call_start = lateral_start(sql, relation.0, |index| !protected.contains(index)) + .unwrap_or(relation.0); + let Some(scan) = scan_inputs(sql, call_start, &mut protected) else { + return Err(compile_error(&format!( + "a __table_fn__{} fixture replaces a call with an OVER clause, which must stand \ + in a FROM clause", + name.as_str() + ))); + }; + let Some(separator) = scan.separator else { + continue; + }; + for (start, edit) in collapse(sql, (&scan.commas, separator), collapsed) { + let _ = edits.entry(start).or_insert(edit); + } + let references = partition_references(sql, (over, over_close), &columns); + if !references.is_empty() { + let scope = select_scope(sql, (scan.from, relation.1), &mut protected); + let read = PartitionRead { + relation, + inputs_from: scan.from, + references: &references, + scope, + ordinal: collapsed, + }; + for (start, edit) in read_partition_columns(sql, &read, &mut protected) { + let _ = edits.entry(start).or_insert(edit); + } + } + collapsed += 1; + } + let mut output = String::with_capacity(sql.len()); + let mut cursor = 0; + for (start, (end, text)) in edits { + if start < cursor { + continue; + } + output.push_str(&sql[cursor..start]); + output.push_str(&text); + cursor = end; + } + output.push_str(&sql[cursor..]); + Ok(output) +} + +/// What joins a call to the relations before it. +enum Separator { + /// The byte offset of the comma. + Comma(usize), + /// The start of the join keywords. + Join(usize), +} + +/// The relations before a call in its FROM clause. +struct Inputs { + /// Where the clause's `FROM` keyword starts. + from: usize, + /// The top-level commas between `FROM` and the call. + commas: Vec, + /// What joins the call to them, or `None` when the call follows `FROM` directly. + separator: Option, +} + +/// A partitioned call whose `PARTITION BY` columns read the fixture's columns. +struct PartitionRead<'a> { + /// The call as a relation, `TABLE( )` included. + relation: (usize, usize), + /// Where the call's FROM clause starts; the inputs before the call, read as NULL, keep their columns. + inputs_from: usize, + /// Each `qualifier.column` partition reference whose column the fixture has. + references: &'a [(String, String)], + /// The SELECT the call stands in. + scope: (usize, usize), + ordinal: usize, +} + +/// The call's extent as a relation, and the edits that remove an enclosing `TABLE( )`. +fn unwrapped( + sql: &str, + (start, end): (usize, usize), + syntax: &LexicalSyntax, +) -> ((usize, usize), Edits) { + let before = sql[..start].trim_end(); + if !before.ends_with('(') { + return ((start, end), Edits::new()); + } + let open = before.len() - 1; + let word = sql[..open].trim_end(); + let Some(table) = word.len().checked_sub(TABLE_KEYWORD.len()) else { + return ((start, end), Edits::new()); + }; + let close = skip_whitespace(sql, end); + let wrapped = word[table..].eq_ignore_ascii_case(TABLE_KEYWORD) + && !word[..table].bytes().next_back().is_some_and(is_word_byte) + && matches!(dialect_matching_paren(sql.as_bytes(), open, syntax), Ok(found) if found == close); + if !wrapped { + return ((start, end), Edits::new()); + } + let edits: Edits = [ + (table, (start, String::new())), + (end, (close + 1, String::new())), + ] + .into_iter() + .collect(); + ((table, close + 1), edits) +} + +/// The edits that join the inputs before the call as one row of NULLs. +fn collapse(sql: &str, (commas, separator): (&[usize], Separator), ordinal: usize) -> Edits { + let mut edits: Edits = Edits::new(); + for &comma in commas { + let _ = edits.insert( + comma, + (skip_whitespace(sql, comma + 1), CROSS_JOIN.to_owned()), + ); + } + let collapse = + format!(" RIGHT JOIN (SELECT 1 AS {INPUTS_ALIAS}) AS {INPUTS_ALIAS}_{ordinal} ON FALSE"); + match separator { + Separator::Comma(comma) => { + let end = skip_whitespace(sql, comma + 1); + let _ = edits.insert(comma, (end, format!("{collapse}{CROSS_JOIN}"))); + } + Separator::Join(start) => { + let _ = edits.insert(start, (start, format!("{} ", collapse.trim_start()))); + } + } + edits +} + +/// The edits that point each partition reference in the call's SELECT at the call's row, naming the call when it has no alias. +fn read_partition_columns( + sql: &str, + read: &PartitionRead<'_>, + protected: &mut ProtectedRanges<'_>, +) -> Edits { + let mut edits: Edits = Edits::new(); + let alias = match call_alias(sql, read.relation.1) { + Alias::Named(alias) => alias, + Alias::Renamed => return edits, + Alias::Missing => { + let alias = format!("{CALL_ALIAS}_{}", read.ordinal); + let _ = edits.insert(read.relation.1, (read.relation.1, format!(" AS {alias}"))); + alias + } + }; + let lower = sql.to_ascii_lowercase(); + for (qualifier, column) in read.references { + let reference = format!("{qualifier}.{column}"); + let mut from = read.scope.0; + while let Some(found) = lower[from..read.scope.1].find(&reference) { + let start = from + found; + let end = start + reference.len(); + from = end; + let standalone = !sql[..start] + .bytes() + .next_back() + .is_some_and(|byte| is_word_byte(byte) || byte == b'.') + && !sql.as_bytes().get(end).copied().is_some_and(is_word_byte); + let outside_inputs = start < read.inputs_from || start >= read.relation.1; + if standalone && outside_inputs && !protected.contains(start) { + let _ = edits + .entry(start) + .or_insert((end, format!("{alias}.{}", &sql[end - column.len()..end]))); + } + } + } + edits +} + +/// How the relation after `end` is named. +enum Alias { + Named(String), + /// Named with a column list, which renames the fixture's columns. + Renamed, + Missing, +} + +/// The alias written after a relation ending at `end`. +fn call_alias(sql: &str, end: usize) -> Alias { + let mut start = skip_whitespace(sql, end); + let mut word = word_at(sql, start); + if word.eq_ignore_ascii_case(AS_KEYWORD) { + start = skip_whitespace(sql, start + word.len()); + word = word_at(sql, start); + } + let is_clause = CLAUSE_WORDS + .iter() + .any(|clause| word.eq_ignore_ascii_case(clause)); + if word.is_empty() || is_clause { + return Alias::Missing; + } + if sql[skip_whitespace(sql, start + word.len())..].starts_with('(') { + return Alias::Renamed; + } + Alias::Named(word.to_owned()) +} + +/// The word of identifier bytes starting at `start`. +fn word_at(sql: &str, start: usize) -> &str { + let length = sql.as_bytes()[start..] + .iter() + .take_while(|byte| is_word_byte(**byte)) + .count(); + &sql[start..start + length] +} + +/// Each `qualifier.column` expression of the `PARTITION BY` list in the `OVER (...)` at `(open, close)`, lowercased, whose column `columns` has. +fn partition_references( + sql: &str, + (open, close): (usize, usize), + columns: &[String], +) -> Vec<(String, String)> { + let clause = sql[open + 1..close].trim_start(); + let mut words = clause.split_ascii_whitespace(); + let partitioned = words + .next() + .is_some_and(|word| word.eq_ignore_ascii_case(PARTITION_KEYWORD)) + && words + .next() + .is_some_and(|word| word.eq_ignore_ascii_case(BY_KEYWORD)); + if !partitioned { + return Vec::new(); + } + let list = clause[PARTITION_KEYWORD.len()..].trim_start()[BY_KEYWORD.len()..] + .to_ascii_lowercase() + .split_ascii_whitespace() + .collect::>() + .join(" "); + let list = list.split(" order by ").next().unwrap_or_default(); + let mut references: Vec<(String, String)> = Vec::new(); + for expression in list.split(',') { + let Some((qualifier, column)) = expression.trim().split_once('.') else { + continue; + }; + let known = columns + .iter() + .any(|known| known.eq_ignore_ascii_case(column)); + if simple_name(qualifier) && simple_name(column) && known { + references.push((qualifier.to_owned(), column.to_owned())); + } + } + references +} + +/// Whether `name` is one unquoted identifier. +fn simple_name(name: &str) -> bool { + !name.is_empty() && name.bytes().all(is_word_byte) +} + +/// The SELECT whose FROM keyword starts at `from`: from its `SELECT` to the end of its query, after `after`. +fn select_scope( + sql: &str, + (from, after): (usize, usize), + protected: &mut ProtectedRanges<'_>, +) -> (usize, usize) { + let bytes = sql.as_bytes(); + let mut start = 0; + let mut depth = 0usize; + let mut index = from; + while index > 0 { + index -= 1; + if protected.contains(index) { + continue; + } + match bytes[index] { + b')' => depth += 1, + b'(' if depth == 0 => { + start = index + 1; + break; + } + b'(' => depth -= 1, + byte if depth == 0 && is_word_byte(byte) => { + let end = index + 1; + while index > 0 && is_word_byte(bytes[index - 1]) { + index -= 1; + } + if sql[index..end].eq_ignore_ascii_case(SELECT_KEYWORD) { + start = index; + break; + } + } + _ => {} + } + } + let mut end = sql.len(); + let mut depth = 0usize; + let mut index = after; + while index < bytes.len() { + if protected.contains(index) { + index += 1; + continue; + } + match bytes[index] { + b'(' => depth += 1, + b')' if depth == 0 => { + end = index; + break; + } + b')' => depth -= 1, + byte if depth == 0 && is_word_byte(byte) => { + let word = word_at(sql, index); + if SET_OPERATORS + .iter() + .any(|operator| word.eq_ignore_ascii_case(operator)) + { + end = index; + break; + } + index += word.len(); + continue; + } + _ => {} + } + index += 1; + } + (start, end) +} + +/// The inputs before `call_start`, back to its FROM keyword, or `None` outside a FROM clause. +fn scan_inputs( + sql: &str, + call_start: usize, + protected: &mut ProtectedRanges<'_>, +) -> Option { + let bytes = sql.as_bytes(); + let mut commas: Vec = Vec::new(); + let mut words: Vec<(usize, usize)> = Vec::new(); + let mut depth = 0usize; + let mut index = call_start; + while index > 0 { + index -= 1; + if protected.contains(index) { + continue; + } + match bytes[index] { + b')' => depth += 1, + b'(' => depth = depth.checked_sub(1)?, + b',' if depth == 0 => commas.push(index), + byte if depth == 0 && is_word_byte(byte) => { + let end = index + 1; + while index > 0 && is_word_byte(bytes[index - 1]) && !protected.contains(index - 1) + { + index -= 1; + } + if sql[index..end].eq_ignore_ascii_case(FROM_KEYWORD) { + return Some(Inputs { + from: index, + separator: separator(sql, &commas, &words), + commas, + }); + } + words.push((index, end)); + } + _ => {} + } + } + None +} + +/// The separator right before the call, or `None` when the call follows `FROM` directly. +fn separator(sql: &str, commas: &[usize], words: &[(usize, usize)]) -> Option { + let last_comma = commas.first().copied(); + let mut join_start = None; + for &(start, end) in words { + if last_comma.is_some_and(|comma| start < comma) + || !JOIN_WORDS + .iter() + .any(|word| sql[start..end].eq_ignore_ascii_case(word)) + { + break; + } + join_start = Some(start); + } + join_start + .map(Separator::Join) + .or_else(|| last_comma.map(Separator::Comma)) +} + +fn is_word_byte(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'$') +} diff --git a/crates/sqlbuild-analysis/src/compiler/_helpers/sql_tests/planning.rs b/crates/sqlbuild-analysis/src/compiler/_helpers/sql_tests/planning.rs index 954566bf1c..895ab1f435 100644 --- a/crates/sqlbuild-analysis/src/compiler/_helpers/sql_tests/planning.rs +++ b/crates/sqlbuild-analysis/src/compiler/_helpers/sql_tests/planning.rs @@ -28,6 +28,7 @@ use crate::compiler::_helpers::sql_tests::markers::{ ProtectedRanges, marker_names, marker_names_in, replace_callable_markers, replace_dbt_ref_markers, replace_named_markers, }; +use crate::compiler::_helpers::sql_tests::partition_inputs::collapse_partition_inputs; use crate::compiler::_helpers::sql_tests::reader_references::{ CompilerReads, assertion_ref_targets, calls_reference, unresolvable_call, unresolved_reference_error, @@ -179,6 +180,8 @@ pub(crate) struct TestFixtures { pub(crate) mock_seeds: BTreeMap, pub(crate) mock_dbt_refs: BTreeMap, pub(crate) mock_table_functions: BTreeMap, + /// Each table-function fixture's column names, when its SQL names them. + pub(crate) mock_table_function_columns: BTreeMap>, pub(crate) helpers: Vec, pub(crate) scope: ScopeGraph, pub(crate) expected: BTreeMap, @@ -774,6 +777,11 @@ fn plan_model_test( ) -> Result { let mut fixtures = classify_fixtures(plan.authored_ctes, plan.expected_ctes, plan.assertion_ctes); + fixtures.mock_table_function_columns = fixtures + .mock_table_functions + .iter() + .filter_map(|(name, sql)| Some((name.clone(), expected_columns(sql, context.parser)?))) + .collect(); fixtures.scope = ScopeGraph::new(&ScopeRequest { fixtures: &fixtures, patterns: &context.patterns, @@ -1331,6 +1339,7 @@ fn classify_fixtures( mock_seeds: BTreeMap::new(), mock_dbt_refs: BTreeMap::new(), mock_table_functions: BTreeMap::new(), + mock_table_function_columns: BTreeMap::new(), helpers: Vec::new(), scope: ScopeGraph::default(), expected: BTreeMap::new(), @@ -1707,8 +1716,18 @@ fn resolve_table_function_fixtures<'a>( if fixtures.mock_table_functions.is_empty() { return Ok(resolved); } + let collapsed = + collapse_partition_inputs(sql, &patterns.table_function, &patterns.lexical, |name| { + fixtures.mock_table_functions.contains_key(name).then(|| { + fixtures + .mock_table_function_columns + .get(name) + .cloned() + .unwrap_or_default() + }) + })?; let (replaced, reached) = replace_callable_markers( - sql, + &collapsed, (&patterns.table_function, true, true), &patterns.lexical, |name, _call_suffix| { diff --git a/crates/sqlbuild-analysis/src/compiler/_helpers/sql_tests/scenario_scope.rs b/crates/sqlbuild-analysis/src/compiler/_helpers/sql_tests/scenario_scope.rs index 5e78330479..fb065c067a 100644 --- a/crates/sqlbuild-analysis/src/compiler/_helpers/sql_tests/scenario_scope.rs +++ b/crates/sqlbuild-analysis/src/compiler/_helpers/sql_tests/scenario_scope.rs @@ -42,6 +42,7 @@ fn scenario_fixtures(ctes: &[(String, String)], checks: &[(String, String)]) -> mock_seeds: BTreeMap::new(), mock_dbt_refs: BTreeMap::new(), mock_table_functions: BTreeMap::new(), + mock_table_function_columns: BTreeMap::new(), helpers: Vec::new(), scope: ScopeGraph::default(), expected: BTreeMap::new(), diff --git a/crates/sqlbuild-analysis/src/compiler/tests.rs b/crates/sqlbuild-analysis/src/compiler/tests.rs index de87bae234..4193e0f2da 100644 --- a/crates/sqlbuild-analysis/src/compiler/tests.rs +++ b/crates/sqlbuild-analysis/src/compiler/tests.rs @@ -28,6 +28,8 @@ mod sql_test_helper_references; mod sql_test_markers; #[path = "tests/test_sql_test_name_isolation.rs"] mod sql_test_name_isolation; +#[path = "tests/test_sql_test_partition_inputs.rs"] +mod sql_test_partition_inputs; #[path = "tests/test_sql_test_planning.rs"] mod sql_test_planning; #[path = "tests/test_sql_test_relation_markers.rs"] diff --git a/crates/sqlbuild-analysis/src/compiler/tests/test_sql_test_partition_inputs.rs b/crates/sqlbuild-analysis/src/compiler/tests/test_sql_test_partition_inputs.rs new file mode 100644 index 0000000000..85aa252254 --- /dev/null +++ b/crates/sqlbuild-analysis/src/compiler/tests/test_sql_test_partition_inputs.rs @@ -0,0 +1,151 @@ +use regex::Regex; + +use crate::compiler::_helpers::sql_tests::partition_inputs::collapse_partition_inputs; +use crate::compiler::tests::test_types::PartitionInputsTestCase; +use sqlbuild_sqltext::sql_scan::models::LexicalSyntax; + +#[test] +fn given_a_mocked_partitioned_call_when_collapsing_then_its_inputs_read_as_one_null_row() { + let test_cases = [ + PartitionInputsTestCase { + description: "a comma before the call joins the inputs as one row", + sql: "SELECT s.a FROM p, __table_fn(\"f\")(p.x) OVER (PARTITION BY p.k) s", + expected_outcome: Ok( + "SELECT s.a FROM p RIGHT JOIN (SELECT 1 AS __sqb_partition_inputs) AS \ + __sqb_partition_inputs_0 ON FALSE CROSS JOIN __table_fn(\"f\")(p.x) OVER \ + (PARTITION BY p.k) s", + ), + }, + PartitionInputsTestCase { + description: "earlier comma inputs become cross joins so the collapse covers them all", + sql: "SELECT s.a FROM a, (SELECT 1, 2) b, LATERAL __table_fn(\"f\")(b.x) over (partition by b.k) AS s, c", + expected_outcome: Ok( + "SELECT s.a FROM a CROSS JOIN (SELECT 1, 2) b RIGHT JOIN (SELECT 1 AS \ + __sqb_partition_inputs) AS __sqb_partition_inputs_0 ON FALSE CROSS JOIN LATERAL \ + __table_fn(\"f\")(b.x) over (partition by b.k) AS s, c", + ), + }, + PartitionInputsTestCase { + description: "a join before the call keeps its condition", + sql: "SELECT s.a FROM p LEFT JOIN __table_fn(\"f\")(p.x) OVER (PARTITION BY p.k) s ON TRUE", + expected_outcome: Ok( + "SELECT s.a FROM p RIGHT JOIN (SELECT 1 AS __sqb_partition_inputs) AS \ + __sqb_partition_inputs_0 ON FALSE LEFT JOIN __table_fn(\"f\")(p.x) OVER \ + (PARTITION BY p.k) s ON TRUE", + ), + }, + PartitionInputsTestCase { + description: "a call inside a subquery stops at its own FROM, past comments and strings", + sql: "SELECT * FROM t, (SELECT s.a FROM p /* , */, __table_fn(\"f\")(',', p.x) OVER (PARTITION BY p.k) s) q", + expected_outcome: Ok( + "SELECT * FROM t, (SELECT s.a FROM p /* , */ RIGHT JOIN (SELECT 1 AS \ + __sqb_partition_inputs) AS __sqb_partition_inputs_0 ON FALSE CROSS JOIN \ + __table_fn(\"f\")(',', p.x) OVER (PARTITION BY p.k) s) q", + ), + }, + PartitionInputsTestCase { + description: "a call right after FROM has no inputs to collapse", + sql: "SELECT * FROM __table_fn(\"f\")(1) OVER (PARTITION BY 1) s", + expected_outcome: Ok("SELECT * FROM __table_fn(\"f\")(1) OVER (PARTITION BY 1) s"), + }, + PartitionInputsTestCase { + description: "an unpartitioned call stays joined to each input row", + sql: "SELECT s.a FROM p, __table_fn(\"f\")(p.x) s", + expected_outcome: Ok("SELECT s.a FROM p, __table_fn(\"f\")(p.x) s"), + }, + PartitionInputsTestCase { + description: "a call without a fixture is left alone", + sql: "SELECT s.a FROM p, __table_fn(\"g\")(p.x) OVER (PARTITION BY p.k) s", + expected_outcome: Ok( + "SELECT s.a FROM p, __table_fn(\"g\")(p.x) OVER (PARTITION BY p.k) s", + ), + }, + PartitionInputsTestCase { + description: "a partitioned call in TABLE( ) loses the wrapper and collapses its inputs", + sql: "SELECT s.a FROM p, TABLE(__table_fn(\"f\")(p.x) OVER (PARTITION BY p.k)) s", + expected_outcome: Ok( + "SELECT s.a FROM p RIGHT JOIN (SELECT 1 AS __sqb_partition_inputs) AS \ + __sqb_partition_inputs_0 ON FALSE CROSS JOIN __table_fn(\"f\")(p.x) OVER \ + (PARTITION BY p.k) s", + ), + }, + PartitionInputsTestCase { + description: "an unpartitioned call in LATERAL TABLE( ) loses the wrapper only", + sql: "SELECT s.a FROM p, LATERAL table ( __table_fn(\"f\")(p.x) ) s", + expected_outcome: Ok("SELECT s.a FROM p, LATERAL __table_fn(\"f\")(p.x) s"), + }, + PartitionInputsTestCase { + description: "partition columns the fixture has read the fixture row, outside the call", + sql: "SELECT p.k, P.K, s.a, p.kk FROM p, __table_fn(\"f\")(p.k) OVER (PARTITION BY p.k) s \ + WHERE p.k = 1 AND 'p.k' <> q.p.k", + expected_outcome: Ok( + "SELECT s.k, s.K, s.a, p.kk FROM p RIGHT JOIN (SELECT 1 AS __sqb_partition_inputs) \ + AS __sqb_partition_inputs_0 ON FALSE CROSS JOIN __table_fn(\"f\")(p.k) OVER \ + (PARTITION BY p.k) s WHERE s.k = 1 AND 'p.k' <> q.p.k", + ), + }, + PartitionInputsTestCase { + description: "a call without an alias is named for its partition columns", + sql: "SELECT p.k FROM p, __table_fn(\"f\")(p.x) OVER (PARTITION BY p.k, p.z ORDER BY p.x)", + expected_outcome: Ok( + "SELECT __sqb_partition_call_0.k FROM p RIGHT JOIN (SELECT 1 AS \ + __sqb_partition_inputs) AS __sqb_partition_inputs_0 ON FALSE CROSS JOIN \ + __table_fn(\"f\")(p.x) OVER (PARTITION BY p.k, p.z ORDER BY p.x) AS \ + __sqb_partition_call_0", + ), + }, + PartitionInputsTestCase { + description: "an alias with a column list keeps the partition columns NULL", + sql: "SELECT p.k FROM p, __table_fn(\"f\")(p.x) OVER (PARTITION BY p.k) s (k, a)", + expected_outcome: Ok( + "SELECT p.k FROM p RIGHT JOIN (SELECT 1 AS __sqb_partition_inputs) AS \ + __sqb_partition_inputs_0 ON FALSE CROSS JOIN __table_fn(\"f\")(p.x) OVER \ + (PARTITION BY p.k) s (k, a)", + ), + }, + PartitionInputsTestCase { + description: "a join before the call keeps its partition columns, which it reads as inputs", + sql: "SELECT p.k FROM p JOIN c ON c.id = p.k, __table_fn(\"f\")(p.x) OVER (PARTITION BY p.k) s \ + JOIN d ON d.id = p.k WHERE p.k = 1", + expected_outcome: Ok( + "SELECT s.k FROM p JOIN c ON c.id = p.k RIGHT JOIN (SELECT 1 AS \ + __sqb_partition_inputs) AS __sqb_partition_inputs_0 ON FALSE CROSS JOIN \ + __table_fn(\"f\")(p.x) OVER (PARTITION BY p.k) s JOIN d ON d.id = s.k WHERE s.k = 1", + ), + }, + PartitionInputsTestCase { + description: "partition columns read the fixture only in the call's own SELECT", + sql: "SELECT p.k FROM p UNION ALL SELECT p.k FROM p, __table_fn(\"f\")(p.x) OVER \ + (PARTITION BY p.k) s", + expected_outcome: Ok( + "SELECT p.k FROM p UNION ALL SELECT s.k FROM p RIGHT JOIN (SELECT 1 AS \ + __sqb_partition_inputs) AS __sqb_partition_inputs_0 ON FALSE CROSS JOIN \ + __table_fn(\"f\")(p.x) OVER (PARTITION BY p.k) s", + ), + }, + PartitionInputsTestCase { + description: "a partitioned call outside a FROM clause is an error", + sql: "SELECT (__table_fn(\"f\")(1) OVER (PARTITION BY 1))", + expected_outcome: Err( + "compile_input:a __table_fn__f fixture replaces a call with an OVER clause, which \ + must stand in a FROM clause", + ), + }, + ]; + let pattern = Regex::new(r#"(?i)__table_fn\("([^"]+)"\)"#).expect("valid marker pattern"); + let syntax = LexicalSyntax { + line_comment_prefixes: vec!["--".to_string()], + ..LexicalSyntax::default() + }; + for test_case in test_cases { + let collapsed = collapse_partition_inputs(test_case.sql, &pattern, &syntax, |name| { + (name == "f").then(|| vec!["k".to_owned(), "a".to_owned()]) + }); + assert_eq!( + collapsed.as_deref().map_err(String::as_str), + test_case.expected_outcome, + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-analysis/src/compiler/tests/test_types.rs b/crates/sqlbuild-analysis/src/compiler/tests/test_types.rs index b0404a61b6..f0553c451b 100644 --- a/crates/sqlbuild-analysis/src/compiler/tests/test_types.rs +++ b/crates/sqlbuild-analysis/src/compiler/tests/test_types.rs @@ -243,3 +243,9 @@ pub(crate) struct SimpleTemplateCorpusOutcome { pub(crate) recognized: usize, pub(crate) mismatches: Vec, } + +pub(crate) struct PartitionInputsTestCase { + pub(crate) description: &'static str, + pub(crate) sql: &'static str, + pub(crate) expected_outcome: Result<&'static str, &'static str>, +} diff --git a/crates/sqlbuild-analysis/src/parse_guard/constants.rs b/crates/sqlbuild-analysis/src/parse_guard/constants.rs index 1d65848990..ab0e6e617a 100644 --- a/crates/sqlbuild-analysis/src/parse_guard/constants.rs +++ b/crates/sqlbuild-analysis/src/parse_guard/constants.rs @@ -1,4 +1,4 @@ //! Constants of parse_guard. -/// The deepest function-call nesting a Polyglot or SQLQuack shared or Snowflake parse accepts. +/// The deepest function-call nesting that a guarded parse or a SQLClean lint accepts. pub const MAX_FUNCTION_CALL_DEPTH: usize = 256; diff --git a/crates/sqlbuild-analysis/src/parse_guard/mod.rs b/crates/sqlbuild-analysis/src/parse_guard/mod.rs index c636c77864..9a3d52ceff 100644 --- a/crates/sqlbuild-analysis/src/parse_guard/mod.rs +++ b/crates/sqlbuild-analysis/src/parse_guard/mod.rs @@ -1,4 +1,4 @@ -//! One call depth for Polyglot and SQLQuack's shared and Snowflake parsers, not per-dialect ones. +//! One call depth for Polyglot, SQLQuack's shared and Snowflake parsers and SQLClean's lint. pub mod constants; pub mod main; diff --git a/crates/sqlbuild-analysis/src/source_drift/_helpers/walk.rs b/crates/sqlbuild-analysis/src/source_drift/_helpers/walk.rs index 04078968dd..fe45723dbc 100644 --- a/crates/sqlbuild-analysis/src/source_drift/_helpers/walk.rs +++ b/crates/sqlbuild-analysis/src/source_drift/_helpers/walk.rs @@ -3,7 +3,7 @@ use std::collections::HashSet; use sqlbuild_core::text::main::python_casefold::python_casefold; -use sqlquack_syntax::expressions::queries::models::{JoinKind, Select, With}; +use sqlquack_syntax::expressions::queries::models::{Join, JoinKind, Select, With}; use sqlquack_syntax::{Expression, ExpressionWalk}; use crate::source_drift::constants::{COUNT_FUNCTION, OPAQUE_KINDS, SHARED_SCOPE_RELATIONS}; @@ -141,17 +141,14 @@ impl<'a> Walk<'a> { .map(|cte| std::ptr::from_ref(&cte.this)) .collect(); let mut local: Vec<(Option, bool)> = Vec::new(); - let relations = select - .from - .iter() - .flat_map(|from| from.expressions.iter()) - .chain(select.joins.iter().map(|join| &join.this)); + let (items, joins): (Vec<&Expression>, Vec<&Join>) = from_items_and_joins(select); + let relations = items.into_iter().chain(joins.iter().map(|join| &join.this)); for relation in relations { walked.insert(std::ptr::from_ref(relation)); local.extend(self.relation(relation, &ctes, outer)); } let drifted_here: bool = local.iter().any(|(_, exposes)| *exposes); - for join in &select.joins { + for join in joins { let natural: bool = matches!( join.kind, JoinKind::Natural @@ -338,3 +335,19 @@ fn nested_queries(expression: &Expression) -> Vec<&Expression> { } found } + +/// The select's FROM items and joins, with each unaliased joined FROM item read as its left side and joins. +fn from_items_and_joins(select: &Select) -> (Vec<&Expression>, Vec<&Join>) { + let mut items: Vec<&Expression> = Vec::new(); + let mut joins: Vec<&Join> = select.joins.iter().collect(); + for item in select.from.iter().flat_map(|from| from.expressions.iter()) { + match item { + Expression::JoinedTable(joined) if joined.alias.is_none() => { + items.push(&joined.left); + joins.extend(joined.joins.iter()); + } + _ => items.push(item), + } + } + (items, joins) +} diff --git a/crates/sqlbuild-analysis/src/source_drift/tests/test_reads_added_columns.rs b/crates/sqlbuild-analysis/src/source_drift/tests/test_reads_added_columns.rs index df91ab1e75..42035be434 100644 --- a/crates/sqlbuild-analysis/src/source_drift/tests/test_reads_added_columns.rs +++ b/crates/sqlbuild-analysis/src/source_drift/tests/test_reads_added_columns.rs @@ -1,5 +1,5 @@ use crate::source_drift::main::reads_added_columns::reads_added_columns; -use crate::source_drift::tests::test_types::AddedColumnsTestCase; +use crate::source_drift::tests::test_types::{AddedColumnsTestCase, DialectAddedColumnsTestCase}; #[test] fn given_a_source_gaining_columns_when_reading_models_then_only_column_list_readers_are_affected() { @@ -102,3 +102,86 @@ fn given_a_source_gaining_columns_when_reading_models_then_only_column_list_read ); } } + +#[test] +fn given_comma_items_with_joins_when_a_joined_source_gains_columns_then_their_keys_and_names_count() +{ + let test_cases = [ + DialectAddedColumnsTestCase { + description: "postgres: a later comma item joining the source USING a column it gains", + dialect: "postgres", + sql: r#"SELECT c.customer_id FROM __ref("customers") AS c, + __ref("products") AS p JOIN __source("orders") AS o USING (region)"#, + expected_affected: true, + }, + DialectAddedColumnsTestCase { + description: "postgres: an unqualified name in a later comma item's join ON", + dialect: "postgres", + sql: r#"SELECT c.customer_id FROM __ref("customers") AS c, + __ref("products") AS p JOIN __source("orders") AS o ON p.product_id = product_ref"#, + expected_affected: true, + }, + DialectAddedColumnsTestCase { + description: "postgres: qualified names across comma items and their joins", + dialect: "postgres", + sql: r#"SELECT c.customer_id FROM __ref("customers") AS c, + __ref("products") AS p JOIN __source("orders") AS o ON p.product_id = o.product_id"#, + expected_affected: false, + }, + DialectAddedColumnsTestCase { + description: "duckdb: a later comma item joining the source USING a column it gains", + dialect: "duckdb", + sql: r#"SELECT c.customer_id FROM __ref("customers") AS c, + __ref("products") AS p JOIN __source("orders") AS o USING (region)"#, + expected_affected: true, + }, + DialectAddedColumnsTestCase { + description: "duckdb: an unqualified name in a later comma item's join ON", + dialect: "duckdb", + sql: r#"SELECT c.customer_id FROM __ref("customers") AS c, + __ref("products") AS p JOIN __source("orders") AS o ON p.product_id = product_ref"#, + expected_affected: true, + }, + DialectAddedColumnsTestCase { + description: "duckdb: qualified names across comma items and their joins", + dialect: "duckdb", + sql: r#"SELECT c.customer_id FROM __ref("customers") AS c, + __ref("products") AS p JOIN __source("orders") AS o ON p.product_id = o.product_id"#, + expected_affected: false, + }, + DialectAddedColumnsTestCase { + description: "databricks: a later comma item joining the source USING a column it gains", + dialect: "databricks", + sql: r#"SELECT c.customer_id FROM __ref("customers") AS c, + __ref("products") AS p JOIN __source("orders") AS o USING (region)"#, + expected_affected: true, + }, + DialectAddedColumnsTestCase { + description: "databricks: an unqualified name in a later comma item's join ON", + dialect: "databricks", + sql: r#"SELECT c.customer_id FROM __ref("customers") AS c, + __ref("products") AS p JOIN __source("orders") AS o ON p.product_id = product_ref"#, + expected_affected: true, + }, + DialectAddedColumnsTestCase { + description: "databricks: qualified names across comma items and their joins", + dialect: "databricks", + sql: r#"SELECT c.customer_id FROM __ref("customers") AS c, + __ref("products") AS p JOIN __source("orders") AS o ON p.product_id = o.product_id"#, + expected_affected: false, + }, + ]; + for test_case in test_cases { + assert_eq!( + reads_added_columns( + test_case.dialect, + (test_case.sql, &[]), + &["orders".to_owned()], + &["region".to_owned()], + ), + test_case.expected_affected, + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-analysis/src/source_drift/tests/test_types.rs b/crates/sqlbuild-analysis/src/source_drift/tests/test_types.rs index daf66cf1a3..8e6ee2b9a8 100644 --- a/crates/sqlbuild-analysis/src/source_drift/tests/test_types.rs +++ b/crates/sqlbuild-analysis/src/source_drift/tests/test_types.rs @@ -4,3 +4,10 @@ pub(super) struct AddedColumnsTestCase { pub(super) sql: &'static str, pub(super) expected_affected: bool, } + +pub(super) struct DialectAddedColumnsTestCase { + pub(super) description: &'static str, + pub(super) dialect: &'static str, + pub(super) sql: &'static str, + pub(super) expected_affected: bool, +} diff --git a/crates/sqlbuild-analysis/src/sql_tree/_helpers/clauses.rs b/crates/sqlbuild-analysis/src/sql_tree/_helpers/clauses.rs index e8a0712125..082d531fe1 100644 --- a/crates/sqlbuild-analysis/src/sql_tree/_helpers/clauses.rs +++ b/crates/sqlbuild-analysis/src/sql_tree/_helpers/clauses.rs @@ -1,11 +1,16 @@ -//! Join and CTE clauses, which SQLQuack keeps as statement fields rather than expressions. +//! Clauses SQLQuack keeps as statement fields rather than expressions: CTEs, joins, a query's other clauses and a window's. use sqlquack_syntax::Expression; use sqlquack_syntax::expressions::names::models::Identifier; -use sqlquack_syntax::expressions::queries::models::{Cte, Join, JoinKind, With}; +use sqlquack_syntax::expressions::queries::models::{ + Cte, From, Join, JoinKind, OrderBy, Ordered, Over, Select, Where, With, +}; use sqlquack_syntax::tokens::models::Span; -use crate::sql_tree::constants::{CTE_KIND, JOIN_KIND}; +use crate::sql_tree::constants::{ + CTE_KIND, FROM_KIND, GROUP_BY_KIND, HAVING_KIND, JOIN_KIND, LIMIT_KIND, ORDER_BY_KIND, + PARTITION_BY_KIND, PROJECTION_KIND, QUALIFY_KIND, WHERE_KIND, WINDOW_ORDER_BY_KIND, +}; /// One clause of a statement: its kind, its span, its name, and the expressions it owns. pub(crate) struct Clause<'ast> { @@ -13,10 +18,28 @@ pub(crate) struct Clause<'ast> { pub(crate) span: Option, pub(crate) name: Option<&'ast Identifier>, pub(crate) children: Vec<&'ast Expression>, + /// Whether a clause without its own span covers its children's, as the clauses the parser records no span for do. + pub(crate) spans_children: bool, } -/// The CTEs and explicit joins `expression` holds directly, CTEs first. +/// The clauses `expression` holds directly, as written: CTEs, the select list, `FROM`, its joins, then the rest. pub(crate) fn clauses(expression: &Expression) -> Vec> { + let (ctes, joins) = ctes_and_joins(expression); + let mut written: Vec> = written_clauses(expression); + let after_sources: usize = written + .iter() + .rposition(|clause| [PROJECTION_KIND, FROM_KIND].contains(&clause.kind)) + .map_or(0, |index| index + 1); + let rest: Vec> = written.split_off(after_sources); + ctes.into_iter() + .chain(written) + .chain(joins) + .chain(rest) + .collect() +} + +/// The CTEs and the explicit joins `expression` holds directly. +fn ctes_and_joins(expression: &Expression) -> (Vec>, Vec>) { let (with, joins): (Option<&With>, Vec<&[Join]>) = match expression { Expression::Select(select) => (select.with.as_ref(), vec![select.joins.as_slice()]), Expression::Union(union) => (union.with.as_ref(), Vec::new()), @@ -40,7 +63,7 @@ pub(crate) fn clauses(expression: &Expression) -> Vec> { .flatten() .filter(|join| !is_comma_item(join)) .map(join_clause); - ctes.chain(joins).collect() + (ctes.collect(), joins.collect()) } fn cte_clause(cte: &Cte) -> Clause<'_> { @@ -49,6 +72,7 @@ fn cte_clause(cte: &Cte) -> Clause<'_> { span: cte.span.0, name: Some(&cte.alias), children: vec![&cte.this], + spans_children: false, } } @@ -62,6 +86,7 @@ fn join_clause(join: &Join) -> Clause<'_> { span: join.span.0, name: None, children, + spans_children: false, } } @@ -69,3 +94,126 @@ fn join_clause(join: &Join) -> Clause<'_> { fn is_comma_item(join: &Join) -> bool { join.kind == JoinKind::Implicit } + +/// A query's, a DML statement's or a window's other clauses, in the order they are written. +fn written_clauses(expression: &Expression) -> Vec> { + match expression { + Expression::Select(select) => select_clauses(select), + Expression::Union(union) => tail_clauses(union.order_by.as_ref(), union.limit.as_deref()), + Expression::Intersect(intersect) => { + tail_clauses(intersect.order_by.as_ref(), intersect.limit.as_deref()) + } + Expression::Except(except) => { + tail_clauses(except.order_by.as_ref(), except.limit.as_deref()) + } + Expression::Update(update) => change_clauses( + update.where_clause.as_ref(), + update.order_by.as_ref(), + update.limit.as_ref(), + ), + Expression::Delete(delete) => change_clauses( + delete.where_clause.as_ref(), + delete.order_by.as_ref(), + delete.limit.as_ref(), + ), + Expression::WindowFunction(window) => window_clauses(&window.over), + _ => Vec::new(), + } +} + +fn select_clauses(select: &Select) -> Vec> { + let mut found: Vec> = + vec![owning(PROJECTION_KIND, select.expressions.iter().collect())]; + found.extend( + select + .from + .iter() + .map(|from| owning(FROM_KIND, from_sources(from, &select.joins))), + ); + found.extend( + select + .where_clause + .iter() + .map(|clause| owning(WHERE_KIND, vec![&clause.this])), + ); + found.extend( + select + .group_by + .iter() + .map(|group_by| owning(GROUP_BY_KIND, group_by.expressions.iter().collect())), + ); + found.extend( + select + .having + .iter() + .map(|having| owning(HAVING_KIND, vec![&having.this])), + ); + found.extend( + select + .qualify + .iter() + .map(|qualify| owning(QUALIFY_KIND, vec![&qualify.this])), + ); + found.extend(tail_clauses( + select.order_by.as_ref(), + select.limit.as_ref().map(|limit| &limit.this), + )); + found +} + +/// An `UPDATE`'s or `DELETE`'s `WHERE`, `ORDER BY` and `LIMIT`, where written. +fn change_clauses<'ast>( + where_clause: Option<&'ast Where>, + order_by: Option<&'ast OrderBy>, + limit: Option<&'ast Expression>, +) -> Vec> { + let filtered = where_clause.map(|clause| owning(WHERE_KIND, vec![&clause.this])); + filtered + .into_iter() + .chain(tail_clauses(order_by, limit)) + .collect() +} + +/// The `FROM` sources, then each comma-separated source written after an explicit join. +fn from_sources<'ast>(from: &'ast From, joins: &'ast [Join]) -> Vec<&'ast Expression> { + let commas = joins.iter().filter(|join| is_comma_item(join)); + from.expressions + .iter() + .chain(commas.map(|join| &join.this)) + .collect() +} + +/// The expressions sorted by, without their directions. +fn sort_keys(keys: &[Ordered]) -> Vec<&Expression> { + keys.iter().map(|key| &key.this).collect() +} + +/// `ORDER BY` and `LIMIT`, where written. +fn tail_clauses<'ast>( + order_by: Option<&'ast OrderBy>, + limit: Option<&'ast Expression>, +) -> Vec> { + let ordered = order_by.map(|order_by| owning(ORDER_BY_KIND, sort_keys(&order_by.expressions))); + let limited = limit.map(|limit| owning(LIMIT_KIND, vec![limit])); + ordered.into_iter().chain(limited).collect() +} + +/// A window's `PARTITION BY` and `ORDER BY`, where written. +fn window_clauses(over: &Over) -> Vec> { + let partition = (!over.partition_by.is_empty()) + .then(|| owning(PARTITION_BY_KIND, over.partition_by.iter().collect())); + let order = (!over.order_by.is_empty()) + .then(|| owning(WINDOW_ORDER_BY_KIND, sort_keys(&over.order_by))); + partition.into_iter().chain(order).collect() +} + +/// A clause the parser records no span for, owning `children`. +fn owning<'ast>(kind: &'static str, children: Vec<&'ast Expression>) -> Clause<'ast> { + Clause { + kind, + span: None, + name: None, + children, + spans_children: true, + } +} diff --git a/crates/sqlbuild-analysis/src/sql_tree/_helpers/node_facts.rs b/crates/sqlbuild-analysis/src/sql_tree/_helpers/node_facts.rs index 43d629debb..4e768cc433 100644 --- a/crates/sqlbuild-analysis/src/sql_tree/_helpers/node_facts.rs +++ b/crates/sqlbuild-analysis/src/sql_tree/_helpers/node_facts.rs @@ -81,12 +81,14 @@ fn marker_call<'source>(identifier: &Identifier, map: &SourceMap<'source>) -> Op fn literal_type(literal: &Literal) -> &'static str { match literal { - Literal::String(_) => "string", + Literal::String(_) | Literal::JoinedString(_, _) => "string", Literal::Number(_) => "number", Literal::HexString(_) => "hex_string", Literal::HexNumber(_) => "hex_number", Literal::BitString(_) => "bit_string", - Literal::ByteString(_) => "byte_string", + Literal::ByteString(_) | Literal::RawByteString(_) | Literal::JoinedBytes(_, _) => { + "byte_string" + } Literal::NationalString(_) => "national_string", Literal::Date(_) => "date", Literal::Time(_) => "time", diff --git a/crates/sqlbuild-analysis/src/sql_tree/_helpers/table_wrapped.rs b/crates/sqlbuild-analysis/src/sql_tree/_helpers/table_wrapped.rs index c8ca4b19e1..f3851ebfaa 100644 --- a/crates/sqlbuild-analysis/src/sql_tree/_helpers/table_wrapped.rs +++ b/crates/sqlbuild-analysis/src/sql_tree/_helpers/table_wrapped.rs @@ -1,5 +1,6 @@ -//! Snowflake table function markers wrapped in `TABLE( )`, as SQLBuild renders them. +//! Snowflake table function markers and their `OVER (...)` wrapped in `TABLE( )`, as rendered. +use sqlbuild_sqltext::resolution::main::over_clause_open::over_clause_open; use sqlbuild_sqltext::sql_scan::constants::TABLE_WRAPPER; use sqlbuild_sqltext::sql_scan::main::dialect_matching_paren::dialect_matching_paren; use sqlbuild_sqltext::sql_scan::main::follows_table_wrapper::follows_table_wrapper; @@ -37,6 +38,13 @@ pub(crate) fn table_wrapped( let Ok(close) = dialect_matching_paren(bytes, open, syntax) else { continue; }; + let close = match over_clause_open(named, close + 1, &syntax.line_comment_prefixes) { + Some(over) => match dialect_matching_paren(bytes, over, syntax) { + Ok(over_close) => over_close, + Err(_) => continue, + }, + None => close, + }; let spaces = bytes[name_end..] .iter() .take_while(|byte| **byte == b' ') diff --git a/crates/sqlbuild-analysis/src/sql_tree/_helpers/walk.rs b/crates/sqlbuild-analysis/src/sql_tree/_helpers/walk.rs index bde0b75c17..d7e214bccd 100644 --- a/crates/sqlbuild-analysis/src/sql_tree/_helpers/walk.rs +++ b/crates/sqlbuild-analysis/src/sql_tree/_helpers/walk.rs @@ -10,7 +10,7 @@ use crate::sql_tree::_helpers::node_facts::{named, node_literal, node_name, tabl use crate::sql_tree::_helpers::source_map::SourceMap; use crate::sql_tree::constants::OPAQUE_KINDS; use crate::sql_tree::errors::SqlTreeError; -use crate::sql_tree::models::SqlTreeNode; +use crate::sql_tree::models::{NodeExtent, SqlTreeNode}; /// Child expressions mapped to the index of the clause node that owns them. type Owners = HashMap<*const Expression, usize>; @@ -26,12 +26,16 @@ pub(crate) fn walk( .rev() .map(|statement| (statement, None)) .collect(); + let mut covering: Vec = Vec::new(); while let Some((expression, parent)) = stack.pop() { let index: usize = nodes.len(); let node: SqlTreeNode = expression_node(&nodes, expression, parent, map)?; let (clause_nodes, owners) = clause_nodes(expression, &node, index, map); nodes.push(node); - nodes.extend(clause_nodes); + for clause in clause_nodes { + covering.extend(clause.1.then_some(nodes.len())); + nodes.push(clause.0); + } for child in expression.children().into_iter().rev() { let owner: usize = owners .get(&std::ptr::from_ref(child)) @@ -40,9 +44,36 @@ pub(crate) fn walk( stack.push((child, Some(owner))); } } + cover_children(&mut nodes, &covering); Ok(nodes) } +/// Give each of `covering`, a clause without its own span, the extent from its first child's start to its last child's end, among children with spans. +fn cover_children(nodes: &mut [SqlTreeNode], covering: &[usize]) { + let mut extents: HashMap = HashMap::new(); + for child in nodes.iter() { + let (Some(parent), Some(extent)) = (child.parent, child.extent.as_ref()) else { + continue; + }; + let covered = extents + .entry(parent) + .or_insert_with(|| (child.line, child.column, extent.clone())); + if extent.span.0 < covered.2.span.0 { + (covered.0, covered.1, covered.2.span.0) = (child.line, child.column, extent.span.0); + } + if extent.span.1 > covered.2.span.1 { + covered.2.span.1 = extent.span.1; + (covered.2.end_line, covered.2.end_column) = (extent.end_line, extent.end_column); + } + } + for index in covering { + if let Some((line, column, extent)) = extents.remove(index) { + let clause: &mut SqlTreeNode = &mut nodes[*index]; + (clause.line, clause.column, clause.extent) = (line, column, Some(extent)); + } + } +} + /// `expression`'s node, at its own start or else at its parent's, with its end only where the parser recorded one. fn expression_node( nodes: &[SqlTreeNode], @@ -72,21 +103,21 @@ fn expression_node( }) } -/// The clause nodes `expression` holds, numbered after `index`, and the children each one owns. +/// The clause nodes `expression` holds, numbered after `index`, each with whether it covers its children, and the children each one owns. fn clause_nodes( expression: &Expression, node: &SqlTreeNode, index: usize, map: &SourceMap<'_>, -) -> (Vec, Owners) { - let mut built: Vec = Vec::new(); +) -> (Vec<(SqlTreeNode, bool)>, Owners) { + let mut built: Vec<(SqlTreeNode, bool)> = Vec::new(); let mut owners: Owners = HashMap::new(); for clause in clauses(expression) { let clause_index: usize = index + 1 + built.len(); let (line, column) = clause .span .map_or((node.line, node.column), |span| map.start(span.start)); - built.push(SqlTreeNode { + let node = SqlTreeNode { kind: clause.kind, line, column, @@ -94,7 +125,8 @@ fn clause_nodes( extent: clause.span.map(|span| map.extent(span)), name: clause.name.map(|name| named(name, &[], map)), literal: None, - }); + }; + built.push((node, clause.span.is_none() && clause.spans_children)); for child in clause.children { let _ = owners.insert(std::ptr::from_ref(child), clause_index); } diff --git a/crates/sqlbuild-analysis/src/sql_tree/constants.rs b/crates/sqlbuild-analysis/src/sql_tree/constants.rs index a679be39eb..7f9de74d81 100644 --- a/crates/sqlbuild-analysis/src/sql_tree/constants.rs +++ b/crates/sqlbuild-analysis/src/sql_tree/constants.rs @@ -4,6 +4,26 @@ pub(crate) const JOIN_KIND: &str = "join"; /// The kind of a common table expression, which SQLQuack keeps as a field of its statement. pub(crate) const CTE_KIND: &str = "cte"; +/// The kind owning a query's select list. +pub(crate) const PROJECTION_KIND: &str = "projection"; +/// The kind owning a query's `FROM` sources; explicit joins stay `join` nodes beside it. +pub(crate) const FROM_KIND: &str = "from"; +/// The kind owning a `WHERE` predicate. +pub(crate) const WHERE_KIND: &str = "where"; +/// The kind owning `GROUP BY` keys. +pub(crate) const GROUP_BY_KIND: &str = "group_by"; +/// The kind owning a `HAVING` predicate. +pub(crate) const HAVING_KIND: &str = "having"; +/// The kind owning a `QUALIFY` predicate. +pub(crate) const QUALIFY_KIND: &str = "qualify"; +/// The kind owning a statement's `ORDER BY` keys. +pub(crate) const ORDER_BY_KIND: &str = "order_by"; +/// The kind owning a `LIMIT` count. +pub(crate) const LIMIT_KIND: &str = "limit"; +/// The kind owning a window's `PARTITION BY` keys. +pub(crate) const PARTITION_BY_KIND: &str = "partition_by"; +/// The kind owning a window's `ORDER BY` keys. +pub(crate) const WINDOW_ORDER_BY_KIND: &str = "window_order_by"; /// Kinds that hold a statement the parser kept as unparsed text, so no rule can see inside it. pub(crate) const OPAQUE_KINDS: [&str; 2] = ["command", "raw"]; /// Dialect names read with the shared DuckDB grammar; `generic` matches the fingerprint tokenizer. diff --git a/crates/sqlbuild-analysis/src/sql_tree/tests/helpers.rs b/crates/sqlbuild-analysis/src/sql_tree/tests/helpers.rs index 37326bf842..61a5815f1f 100644 --- a/crates/sqlbuild-analysis/src/sql_tree/tests/helpers.rs +++ b/crates/sqlbuild-analysis/src/sql_tree/tests/helpers.rs @@ -1,6 +1,19 @@ use crate::sql_tree::models::{NodeExtent, NodeName, SqlTreeNode}; const SHAPE_KINDS: [&str; 5] = ["select", "cte", "join", "subquery", "star"]; +/// The clause kinds the rule tree adds for a query's and a window's clauses. +const CLAUSE_KINDS: [&str; 10] = [ + "projection", + "from", + "where", + "group_by", + "having", + "qualify", + "order_by", + "limit", + "partition_by", + "window_order_by", +]; /// How a name's fact reads unquoted, then quoted. const QUOTING: [&str; 2] = ["", " quoted"]; @@ -44,6 +57,16 @@ pub(crate) fn facts(sql: &str, nodes: &[SqlTreeNode]) -> Vec { .collect() } +/// As `facts`, leaving out the clause nodes, which carry no names, literals or spans of their own. +pub(crate) fn expression_facts(sql: &str, nodes: &[SqlTreeNode]) -> Vec { + facts(sql, nodes) + .into_iter() + .zip(nodes) + .filter(|(_, node)| !CLAUSE_KINDS.contains(&node.kind)) + .map(|(fact, _)| fact) + .collect() +} + fn name_fact(name: &NodeName) -> String { let quoted: &str = QUOTING[usize::from(name.quoted)]; let qualifier: String = name @@ -59,3 +82,33 @@ fn extent_fact(sql: &str, extent: &NodeExtent) -> String { let text: String = sql.chars().skip(start).take(end - start).collect(); format!(" to {}:{} {text:?}", extent.end_line, extent.end_column) } + +/// Each clause node, in tree order, with its direct children as `kind line:column` sorted by position. +pub(crate) fn clauses(nodes: &[SqlTreeNode]) -> Vec<(&'static str, Vec)> { + nodes + .iter() + .enumerate() + .filter(|(_, node)| CLAUSE_KINDS.contains(&node.kind)) + .map(|(index, node)| { + let mut children: Vec<&SqlTreeNode> = nodes + .iter() + .filter(|child| child.parent == Some(index)) + .collect(); + children.sort_by_key(|child| (child.line, child.column)); + let described: Vec = children + .iter() + .map(|child| format!("{} {}:{}", child.kind, child.line, child.column)) + .collect(); + (node.kind, described) + }) + .collect() +} + +/// The kinds of the first statement's direct children, in tree order. +pub(crate) fn statement_children(nodes: &[SqlTreeNode]) -> Vec<&'static str> { + nodes + .iter() + .filter(|node| node.parent == Some(0)) + .map(|node| node.kind) + .collect() +} diff --git a/crates/sqlbuild-analysis/src/sql_tree/tests/test_sql_tree.rs b/crates/sqlbuild-analysis/src/sql_tree/tests/test_sql_tree.rs index b16b116e67..d63486640c 100644 --- a/crates/sqlbuild-analysis/src/sql_tree/tests/test_sql_tree.rs +++ b/crates/sqlbuild-analysis/src/sql_tree/tests/test_sql_tree.rs @@ -1,8 +1,11 @@ use crate::sql_tree::errors::SqlTreeError; use crate::sql_tree::main::sql_tree_nodes::sql_tree_nodes; -use crate::sql_tree::tests::helpers::{facts, shape}; +use crate::sql_tree::tests::helpers::{ + clauses, expression_facts, facts, shape, statement_children, +}; use crate::sql_tree::tests::test_types::{ - TreeFactsTestCase, TreeFailureTestCase, TreeShapeTestCase, + TreeChildrenTestCase, TreeClausesTestCase, TreeFactsTestCase, TreeFailureTestCase, + TreeShapeTestCase, }; const CTE_AND_JOIN_SQL: &str = @@ -10,6 +13,8 @@ const CTE_AND_JOIN_SQL: &str = const SNOWFLAKE_MARKER_SQL: &str = "WITH o AS (SELECT * FROM __ref(\"orders\"))\nSELECT o.*, c.name\nFROM o JOIN __ref(\"customers\") c ON o.id = c.id JOIN (SELECT 2 AS id) s ON s.id = o.id\nWHERE o.id IN (SELECT id FROM __source(\"raw_returns\"))"; +const CLAUSES_SQL: &str = "SELECT o.order_id, o.total > 2, COUNT(*) AS c\nFROM orders o\nWHERE o.is_paid\nGROUP BY o.order_id, o.region\nHAVING COUNT(*) > 1\nQUALIFY ROW_NUMBER() OVER (PARTITION BY o.order_id ORDER BY o.placed_at) = 1\nORDER BY o.order_id\nLIMIT 5"; + const NAMES_AND_LITERALS_SQL: &str = "SELECT o.\"Id\" AS order_id, 'x''y' AS s, 42 + 1\nFROM db.sch.orders AS o WHERE o.v = N'z'"; @@ -24,7 +29,7 @@ fn given_sql_when_building_a_rule_tree_then_clauses_own_their_queries_at_their_s ("select", 1, 1, None), ("cte", 1, 6, Some("select")), ("select", 1, 12, Some("cte")), - ("star", 2, 8, Some("select")), + ("star", 2, 8, Some("projection")), ("join", 3, 10, Some("select")), ("subquery", 3, 15, Some("join")), ("select", 3, 16, Some("subquery")), @@ -38,7 +43,7 @@ fn given_sql_when_building_a_rule_tree_then_clauses_own_their_queries_at_their_s ("select", 1, 1, None), ("cte", 1, 6, Some("select")), ("select", 1, 12, Some("cte")), - ("star", 2, 8, Some("select")), + ("star", 2, 8, Some("projection")), ("join", 3, 10, Some("select")), ("select", 3, 15, Some("subquery")), ("subquery", 3, 15, Some("join")), @@ -50,7 +55,7 @@ fn given_sql_when_building_a_rule_tree_then_clauses_own_their_queries_at_their_s sql: "SELECT o.*,\n (SELECT MAX(id) FROM orders) AS top_id\nFROM orders o", expected_nodes: vec![ ("select", 1, 1, None), - ("star", 1, 8, Some("select")), + ("star", 1, 8, Some("projection")), ("select", 2, 3, Some("subquery")), ("subquery", 2, 3, Some("alias")), ], @@ -63,8 +68,8 @@ fn given_sql_when_building_a_rule_tree_then_clauses_own_their_queries_at_their_s ("select", 1, 1, None), ("cte", 1, 6, Some("select")), ("select", 1, 12, Some("cte")), - ("star", 1, 19, Some("select")), - ("star", 2, 8, Some("select")), + ("star", 1, 19, Some("projection")), + ("star", 2, 8, Some("projection")), ("join", 3, 8, Some("select")), ("join", 3, 49, Some("select")), ("select", 3, 54, Some("subquery")), @@ -78,7 +83,7 @@ fn given_sql_when_building_a_rule_tree_then_clauses_own_their_queries_at_their_s sql: "SELECT l.*\nFROM __table_fn(\"lines_for\")('B-1', __ref(\"orders\").k) AS l JOIN (SELECT 1 AS k) s ON s.k = l.k", expected_nodes: vec![ ("select", 1, 1, None), - ("star", 1, 8, Some("select")), + ("star", 1, 8, Some("projection")), ("join", 2, 61, Some("select")), ("select", 2, 66, Some("subquery")), ("subquery", 2, 66, Some("join")), @@ -91,8 +96,8 @@ fn given_sql_when_building_a_rule_tree_then_clauses_own_their_queries_at_their_s expected_nodes: vec![ ("select", 1, 1, None), ("select", 2, 6, Some("subquery")), - ("subquery", 2, 6, Some("select")), - ("star", 2, 14, Some("select")), + ("subquery", 2, 6, Some("from")), + ("star", 2, 14, Some("projection")), ("join", 2, 43, Some("select")), ("select", 2, 48, Some("subquery")), ("subquery", 2, 48, Some("join")), @@ -111,6 +116,17 @@ fn given_sql_when_building_a_rule_tree_then_clauses_own_their_queries_at_their_s ("subquery", 3, 6, Some("join")), ], }, + TreeShapeTestCase { + description: "a partitioned Snowflake table function marker reads with its OVER clause inside TABLE( )", + dialect: "snowflake", + sql: "SELECT s.a\nFROM p, __table_fn(\"f\")(p.x) OVER (PARTITION BY p.k) s JOIN (SELECT 2 AS k) q ON 1=1", + expected_nodes: vec![ + ("select", 1, 1, None), + ("join", 2, 56, Some("select")), + ("select", 2, 61, Some("subquery")), + ("subquery", 2, 61, Some("join")), + ], + }, TreeShapeTestCase { description: "a Snowflake table function marker already inside TABLE( ) is not wrapped twice", dialect: "snowflake", @@ -130,7 +146,7 @@ fn given_sql_when_building_a_rule_tree_then_clauses_own_their_queries_at_their_s ("select", 1, 1, None), ("join", 2, 8, Some("select")), ("select", 2, 31, Some("subquery")), - ("subquery", 2, 31, Some("select")), + ("subquery", 2, 31, Some("from")), ], }, ]; @@ -235,7 +251,9 @@ fn given_sql_when_building_a_rule_tree_then_nodes_carry_names_literals_and_sourc for test_case in test_cases { let nodes = sql_tree_nodes(test_case.sql, test_case.dialect); assert_eq!( - nodes.as_deref().map(|nodes| facts(test_case.sql, nodes)), + nodes + .as_deref() + .map(|nodes| expression_facts(test_case.sql, nodes)), Ok(test_case .expected_facts .iter() @@ -290,3 +308,191 @@ fn given_sql_without_a_full_tree_when_building_a_rule_tree_then_the_reason_is_re ); } } + +#[test] +fn given_a_query_when_building_a_rule_tree_then_each_clause_owns_its_expressions() { + let every_clause = || { + vec![ + ("projection", vec!["column 1:8", "gt 1:20", "alias 1:33"]), + ("from", vec!["table 2:6"]), + ("where", vec!["column 3:7"]), + ("group_by", vec!["column 4:10", "column 4:22"]), + ("having", vec!["gt 5:8"]), + ("qualify", vec!["eq 6:9"]), + ("order_by", vec!["column 7:10"]), + ("limit", vec!["literal 1:1"]), + ("partition_by", vec!["column 6:41"]), + ("window_order_by", vec!["column 6:61"]), + ] + }; + let test_cases = [ + TreeClausesTestCase { + description: "Snowflake: every clause, and a window's partition and order keys apart", + dialect: "snowflake", + sql: CLAUSES_SQL, + expected_clauses: every_clause(), + }, + TreeClausesTestCase { + description: "DuckDB: every clause, and a window's partition and order keys apart", + dialect: "duckdb", + sql: CLAUSES_SQL, + expected_clauses: every_clause(), + }, + TreeClausesTestCase { + description: "a set operation's ORDER BY and LIMIT belong to the whole query", + dialect: "duckdb", + sql: "SELECT a FROM t\nUNION ALL\nSELECT a FROM u\nORDER BY a\nLIMIT 3", + expected_clauses: vec![ + ("order_by", vec!["column 4:10"]), + ("limit", vec!["literal 1:1"]), + ("projection", vec!["column 1:8"]), + ("from", vec!["table 1:15"]), + ("projection", vec!["column 3:8"]), + ("from", vec!["table 3:15"]), + ], + }, + TreeClausesTestCase { + description: "a comma-separated source after an explicit join belongs to FROM", + dialect: "snowflake", + sql: "SELECT 1\nFROM a JOIN b ON a.k = b.k, c", + expected_clauses: vec![ + ("projection", vec!["literal 1:1"]), + ("from", vec!["table 2:6", "table 2:29"]), + ], + }, + TreeClausesTestCase { + description: "SQLite: an UPDATE's WHERE, ORDER BY and LIMIT own their expressions", + dialect: "sqlite", + sql: "UPDATE t SET a = 1\nWHERE b = 2\nORDER BY c\nLIMIT 3", + expected_clauses: vec![ + ("where", vec!["eq 2:7"]), + ("order_by", vec!["column 3:10"]), + ("limit", vec!["literal 1:1"]), + ], + }, + TreeClausesTestCase { + description: "Snowflake: an UPDATE's WHERE owns its predicate", + dialect: "snowflake", + sql: "UPDATE t SET a = 1\nFROM u\nWHERE t.b = u.b", + expected_clauses: vec![("where", vec!["eq 3:7"])], + }, + TreeClausesTestCase { + description: "DuckDB: an UPDATE's WHERE owns its predicate", + dialect: "duckdb", + sql: "UPDATE t SET a = 1\nWHERE b = 2", + expected_clauses: vec![("where", vec!["eq 2:7"])], + }, + TreeClausesTestCase { + description: "a DELETE's WHERE owns its predicate", + dialect: "snowflake", + sql: "DELETE FROM t\nWHERE t.a = 1", + expected_clauses: vec![("where", vec!["eq 2:7"])], + }, + ]; + + for test_case in test_cases { + let nodes = sql_tree_nodes(test_case.sql, test_case.dialect).expect(test_case.description); + let found: Vec<(&str, Vec)> = clauses(&nodes); + let described: Vec<(&str, Vec<&str>)> = found + .iter() + .map(|(kind, children)| (*kind, children.iter().map(String::as_str).collect())) + .collect(); + + assert_eq!( + described, test_case.expected_clauses, + "{}", + test_case.description + ); + } +} + +#[test] +fn given_a_clause_without_its_own_span_when_building_a_rule_tree_then_it_covers_its_children() { + let test_cases = [ + TreeFactsTestCase { + description: "Snowflake: each clause runs from its first child's start to its last child's end", + dialect: "snowflake", + sql: "SELECT a, b\nFROM t\nWHERE a > 1", + expected_facts: &[ + "select 1:1 to 3:12 \"SELECT a, b\\nFROM t\\nWHERE a > 1\"", + "projection 1:8 to 1:12 \"a, b\"", + "from 2:6 to 2:7 \"t\"", + "where 3:7 to 3:12 \"a > 1\"", + "column 1:8 name=a to 1:9 \"a\"", + "column 1:11 name=b to 1:12 \"b\"", + "table 2:6 name=t to 2:7 \"t\"", + "gt 3:7 to 3:12 \"a > 1\"", + "column 3:7 name=a to 3:8 \"a\"", + "literal 3:7 number=1", + ], + }, + TreeFactsTestCase { + description: "DuckDB: a clause whose children have no span has none, and reports its statement's start", + dialect: "duckdb", + sql: "SELECT a\nFROM t\nLIMIT 5", + expected_facts: &[ + "select 1:1 to 3:8 \"SELECT a\\nFROM t\\nLIMIT 5\"", + "projection 1:8 to 1:9 \"a\"", + "from 2:6 to 2:7 \"t\"", + "limit 1:1", + "column 1:8 name=a to 1:9 \"a\"", + "table 2:6 name=t to 2:7 \"t\"", + "literal 1:1 number=5", + ], + }, + ]; + + for test_case in test_cases { + let nodes = sql_tree_nodes(test_case.sql, test_case.dialect).expect(test_case.description); + + assert_eq!( + facts(test_case.sql, &nodes), + test_case.expected_facts, + "{}", + test_case.description + ); + } +} + +#[test] +fn given_a_query_when_building_a_rule_tree_then_its_clauses_come_in_the_order_written() { + const EVERY_CLAUSE_SQL: &str = "WITH x AS (SELECT 1 AS id)\nSELECT x.id\nFROM x\nJOIN y ON y.id = x.id\nLEFT JOIN z ON z.id = x.id\nWHERE x.id > 0\nGROUP BY x.id\nHAVING COUNT(*) > 0\nQUALIFY ROW_NUMBER() OVER (ORDER BY x.id) = 1\nORDER BY x.id\nLIMIT 3"; + const WRITTEN: &[&str] = &[ + "cte", + "projection", + "from", + "join", + "join", + "where", + "group_by", + "having", + "qualify", + "order_by", + "limit", + ]; + let test_cases = [ + TreeChildrenTestCase { + description: "Snowflake: CTEs, the select list, FROM, its joins, then the other clauses", + dialect: "snowflake", + sql: EVERY_CLAUSE_SQL, + expected_children: WRITTEN, + }, + TreeChildrenTestCase { + description: "DuckDB: CTEs, the select list, FROM, its joins, then the other clauses", + dialect: "duckdb", + sql: EVERY_CLAUSE_SQL, + expected_children: WRITTEN, + }, + ]; + + for test_case in test_cases { + let nodes = sql_tree_nodes(test_case.sql, test_case.dialect).expect(test_case.description); + + assert_eq!( + statement_children(&nodes), + test_case.expected_children, + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-analysis/src/sql_tree/tests/test_types.rs b/crates/sqlbuild-analysis/src/sql_tree/tests/test_types.rs index c328f404aa..98a1b467f8 100644 --- a/crates/sqlbuild-analysis/src/sql_tree/tests/test_types.rs +++ b/crates/sqlbuild-analysis/src/sql_tree/tests/test_types.rs @@ -25,3 +25,19 @@ pub(crate) struct TreeFactsTestCase { pub(crate) sql: &'static str, pub(crate) expected_facts: &'static [&'static str], } + +/// SQL, its dialect, and each clause node as `kind`, followed by its direct children as `kind line:column`, in position order. +pub(crate) struct TreeClausesTestCase { + pub(crate) description: &'static str, + pub(crate) dialect: &'static str, + pub(crate) sql: &'static str, + pub(crate) expected_clauses: Vec<(&'static str, Vec<&'static str>)>, +} + +/// SQL, its dialect, and the kinds of its first statement's direct children, in tree order. +pub(crate) struct TreeChildrenTestCase { + pub(crate) description: &'static str, + pub(crate) dialect: &'static str, + pub(crate) sql: &'static str, + pub(crate) expected_children: &'static [&'static str], +} diff --git a/crates/sqlbuild-analysis/src/warehouse_types/_helpers/type_trees.rs b/crates/sqlbuild-analysis/src/warehouse_types/_helpers/type_trees.rs index fe8e746a20..e489646a9f 100644 --- a/crates/sqlbuild-analysis/src/warehouse_types/_helpers/type_trees.rs +++ b/crates/sqlbuild-analysis/src/warehouse_types/_helpers/type_trees.rs @@ -3,10 +3,11 @@ use serde_json::Value; use sqlquack_parse::parse_strict; use sqlquack_syntax::Expression; +use sqlquack_syntax::expressions::types::models::DataType; use sqlquack_syntax::tokens::models::Dialect; use crate::parse_guard::main::sqlquack_parse_options::sqlquack_parse_options; -use crate::warehouse_types::constants::{CAST_KEY, CAST_TARGET_KEY}; +use crate::warehouse_types::constants::{CAST_KEY, CAST_TARGET_KEY, DATA_TYPE_KEY, NAMED_TYPE_TAG}; /// `spelling` read by `sqlquack-syntax-postgres`'s type grammar. pub(crate) fn postgres_type(spelling: &str) -> Result { @@ -40,11 +41,41 @@ fn cast(spelling: &str) -> String { fn single_cast_target(spelling: &str, statements: &[Expression]) -> Result { let tree: Value = serde_json::to_value(statements).map_err(|error| error.to_string())?; match (statements.len(), cast_targets(&tree).as_slice()) { - (1, [target]) => Ok((*target).clone()), + (1, [target]) => unnamed((*target).clone()), _ => Err(format!("`{spelling}` is not a single type name")), } } +/// `tree` with every type kept as written, such as Snowflake's `NUMBER(10, 2)`, read as the type it denotes. +fn unnamed(tree: Value) -> Result { + match tree { + Value::Object(fields) + if fields.get(DATA_TYPE_KEY).and_then(Value::as_str) == Some(NAMED_TYPE_TAG) => + { + let written: Value = Value::Object(fields); + let data_type: DataType = + serde_json::from_value(written.clone()).map_err(|error| error.to_string())?; + match data_type.unnamed() { + Some(denoted) => serde_json::to_value(denoted).map_err(|error| error.to_string()), + None => Ok(written), + } + } + Value::Object(fields) => Ok(Value::Object( + fields + .into_iter() + .map(|(key, value)| Ok((key, unnamed(value)?))) + .collect::>()?, + )), + Value::Array(items) => Ok(Value::Array( + items + .into_iter() + .map(unnamed) + .collect::>()?, + )), + other => Ok(other), + } +} + /// Every cast's target type in `tree`, in order. fn cast_targets(tree: &Value) -> Vec<&Value> { let mut targets: Vec<&Value> = Vec::new(); diff --git a/crates/sqlbuild-analysis/src/warehouse_types/constants.rs b/crates/sqlbuild-analysis/src/warehouse_types/constants.rs index 3a91139238..d64f706fbd 100644 --- a/crates/sqlbuild-analysis/src/warehouse_types/constants.rs +++ b/crates/sqlbuild-analysis/src/warehouse_types/constants.rs @@ -10,3 +10,7 @@ pub(crate) const POSTGRES_DIALECT: &str = "postgres"; pub(crate) const SNOWFLAKE_DIALECT: &str = "snowflake"; /// The dialect whose type names are parsed as a BigQuery cast's target. pub(crate) const BIGQUERY_DIALECT: &str = "bigquery"; +/// The tree key naming a type's kind. +pub(crate) const DATA_TYPE_KEY: &str = "data_type"; +/// The kind of a type SQLQuack keeps as written with its parameters in fields, such as Snowflake's `NUMBER(10, 2)`. +pub(crate) const NAMED_TYPE_TAG: &str = "named"; diff --git a/crates/sqlbuild-cache/src/project_reuse/_helpers/attempt.rs b/crates/sqlbuild-cache/src/project_reuse/_helpers/attempt.rs index ed6080411f..25cb4d1c3c 100644 --- a/crates/sqlbuild-cache/src/project_reuse/_helpers/attempt.rs +++ b/crates/sqlbuild-cache/src/project_reuse/_helpers/attempt.rs @@ -1,5 +1,6 @@ //! Python's `attempt_reuse` and `write_compile_entry` over the native store. +use sqlbuild_core::process_environment::main::environment_var_os::environment_var_os; use std::collections::{HashMap, HashSet}; use std::path::Path; use std::time::{SystemTime, UNIX_EPOCH}; @@ -50,7 +51,7 @@ fn now_ns() -> i64 { fn bypassed(check: &ReuseCheck<'_>) -> bool { check.bypass_requested || check.rules.disabling_variables.iter().any(|(name, value)| { - std::env::var_os(name).is_some_and(|current| current == value.as_str()) + environment_var_os(name).is_some_and(|current| current == value.as_str()) }) || !check .rules diff --git a/crates/sqlbuild-cache/src/project_reuse/_helpers/identity.rs b/crates/sqlbuild-cache/src/project_reuse/_helpers/identity.rs index e3043bbc1c..b49cc5eb27 100644 --- a/crates/sqlbuild-cache/src/project_reuse/_helpers/identity.rs +++ b/crates/sqlbuild-cache/src/project_reuse/_helpers/identity.rs @@ -1,5 +1,7 @@ //! Search path, environment, provider settings and module identity of a compile. +use sqlbuild_core::process_environment::main::environment_var_os::environment_var_os; +use sqlbuild_core::process_environment::main::environment_vars_os::environment_vars_os; use std::collections::HashSet; use std::ffi::OsString; use std::path::{Path, PathBuf}; @@ -77,7 +79,8 @@ pub(crate) fn tracked_environment_names( template_names: &[String], rules: &ReuseRules, ) -> Vec { - let mut names: Vec = std::env::vars_os() + let mut names: Vec = environment_vars_os() + .into_iter() .filter_map(|(name, _)| unicode_name(name)) .filter(|name| tracked(name, rules)) .chain(template_names.iter().cloned()) @@ -115,7 +118,7 @@ pub(crate) fn environment_digest(names: &[String], rules: &ReuseRules) -> String for name in names { let _ = hasher.update(name.as_bytes()); let _ = hasher.update(b"\0"); - let value: Vec = std::env::var_os(name).map_or_else( + let value: Vec = environment_var_os(name).map_or_else( || rules.missing_environment_value.as_bytes().to_vec(), |value| os_bytes(&value), ); @@ -151,7 +154,8 @@ pub(crate) fn settings_inputs_digest(inputs: &[SettingsInputs], rules: &ReuseRul } fn settings_environment(inputs: &SettingsInputs) -> Vec<(Vec, Vec)> { - let mut matched: Vec<(Vec, Vec)> = std::env::vars_os() + let mut matched: Vec<(Vec, Vec)> = environment_vars_os() + .into_iter() .filter(|(name, _)| { let name: String = name.to_string_lossy().into_owned(); let key: String = if inputs.case_sensitive { diff --git a/crates/sqlbuild-cli/src/adhoc/_helpers/evaluation.rs b/crates/sqlbuild-cli/src/adhoc/_helpers/evaluation.rs index c79c54c128..996646e74e 100644 --- a/crates/sqlbuild-cli/src/adhoc/_helpers/evaluation.rs +++ b/crates/sqlbuild-cli/src/adhoc/_helpers/evaluation.rs @@ -66,6 +66,7 @@ pub(crate) fn vocabulary(publication: &IndexedPublication) -> SelectionVocabular } let jobs: BTreeMap = publication .jobs + .selections .iter() .map(|(name, keys)| (name.clone(), keys.len() as u64)) .collect(); diff --git a/crates/sqlbuild-cli/src/adhoc/_helpers/job_pins.rs b/crates/sqlbuild-cli/src/adhoc/_helpers/job_pins.rs new file mode 100644 index 0000000000..3e04e53ee4 --- /dev/null +++ b/crates/sqlbuild-cli/src/adhoc/_helpers/job_pins.rs @@ -0,0 +1,124 @@ +//! The jobs an ad-hoc build names: the build-wide settings they give it and the frozen nodes each pins. + +use std::collections::{BTreeMap, BTreeSet}; + +use serde_json::Value as Json; +use sqlbuild_analysis::assembly::project::types::ObjectKey; +use sqlbuild_analysis::graph::errors::SelectorError; +use sqlbuild_analysis::job_settings::constants::JOB_SETTING_CONFLICT_CODE; +use sqlbuild_analysis::job_settings::errors::NodeJobSettingsError; +use sqlbuild_analysis::job_settings::main::resolve_job_settings::resolve_job_settings; +use sqlbuild_analysis::job_settings::models::DeclaredRun; +use sqlbuild_orchestration::runs::models::PinnedJob; + +use crate::adhoc::_helpers::planner::{key_text, selected_keys}; +use crate::adhoc::_helpers::publication::IndexedPublication; +use crate::adhoc::models::Refusal; + +/// Each published job with its settings and each group with its jobs, as a build declares them. +fn declared(publication: &IndexedPublication) -> BTreeMap { + let jobs = &publication.jobs; + jobs.selections + .keys() + .map(|name| { + let run = match jobs.groups.get(name) { + Some(members) => DeclaredRun::Group { + members: members.clone(), + }, + None => DeclaredRun::Job { + settings: jobs.settings.get(name).cloned().unwrap_or_default(), + retry: None, + }, + }; + (name.clone(), run) + }) + .collect() +} + +fn refusal(error: NodeJobSettingsError) -> Refusal { + match error { + NodeJobSettingsError::Conflict(conflict) => { + Refusal::Selection(format!("{JOB_SETTING_CONFLICT_CODE}: {}", conflict.message)) + } + NodeJobSettingsError::Selector(failure) => Refusal::Selector(failure.error), + } +} + +/// The jobs `select` names and the build-wide settings they give where the command's `settings` are silent; a warehouse they share counts as build-wide whatever the adapter, so it is always gated. +pub(crate) fn named_job_settings( + publication: &IndexedPublication, + select: &[String], + settings: &BTreeMap, +) -> Result<(Vec, BTreeMap), Refusal> { + let given: BTreeSet = settings.keys().cloned().collect(); + let resolved = + resolve_job_settings(declared(publication), (select, &given), None).map_err(refusal)?; + let mut build: BTreeMap = resolved.whole_run; + build.extend(resolved.build); + Ok((resolved.named, build)) +} + +/// Each job `select` names, pinned to the nodes of `selection` it gives its settings to; named jobs that give one node different values are refused, as `sqb build` refuses them. +pub(crate) fn pinned_jobs( + publication: &IndexedPublication, + (select, exclude): (&[String], &[String]), + (settings, include_python): (&BTreeMap, bool), + selection: &BTreeSet, +) -> Result, Refusal> { + let token_nodes = + |token: &str, exclude: &[String]| -> Result, SelectorError> { + selected_keys(publication, &[token.to_owned()], exclude, include_python) + }; + let given: BTreeSet = settings.keys().cloned().collect(); + let resolved = resolve_job_settings( + declared(publication), + (select, &given), + Some(( + publication.graph_with_jobs(include_python), + (select, exclude), + &token_nodes, + )), + ) + .map_err(refusal)?; + let mut pinned: BTreeMap> = resolved + .named + .into_iter() + .map(|job| (job, BTreeSet::new())) + .collect(); + for (key, jobs) in resolved + .nodes + .map(|nodes| nodes.node_jobs) + .unwrap_or_default() + { + for job in jobs { + pinned.entry(job).or_default().insert(key.clone()); + } + } + Ok(pinned + .into_iter() + .map(|(name, keys)| { + let job = PinnedJob { + selection: frozen_keys(publication, &keys, selection), + settings: publication + .jobs + .settings + .get(&name) + .cloned() + .unwrap_or_default(), + }; + (name, job) + }) + .collect()) +} + +/// A job's selected graph keys as the frozen node keys of `selection`. +fn frozen_keys( + publication: &IndexedPublication, + keys: &BTreeSet, + selection: &BTreeSet, +) -> BTreeSet { + keys.iter() + .map(|key| key_text(publication, key)) + .filter(|key| selection.contains(key)) + .collect() +} diff --git a/crates/sqlbuild-cli/src/adhoc/_helpers/mod.rs b/crates/sqlbuild-cli/src/adhoc/_helpers/mod.rs index 1b1e8f84ec..e8ad7efbef 100644 --- a/crates/sqlbuild-cli/src/adhoc/_helpers/mod.rs +++ b/crates/sqlbuild-cli/src/adhoc/_helpers/mod.rs @@ -1,3 +1,4 @@ pub(crate) mod evaluation; +pub(crate) mod job_pins; pub(crate) mod planner; pub(crate) mod publication; diff --git a/crates/sqlbuild-cli/src/adhoc/_helpers/planner.rs b/crates/sqlbuild-cli/src/adhoc/_helpers/planner.rs index d668c196f5..a59d8137f2 100644 --- a/crates/sqlbuild-cli/src/adhoc/_helpers/planner.rs +++ b/crates/sqlbuild-cli/src/adhoc/_helpers/planner.rs @@ -4,6 +4,8 @@ use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use serde_json::{Value as Json, json}; +use sqlbuild_analysis::assembly::project::types::ObjectKey; +use sqlbuild_analysis::graph::errors::SelectorError; use sqlbuild_analysis::graph::main::selectors_need_jobs::selectors_need_jobs; use sqlbuild_analysis::planner_selection::main::split_unit_test_selectors::split_unit_test_selectors; use sqlbuild_analysis::planner_selection::models::SelectorGroups; @@ -12,12 +14,14 @@ use sqlbuild_analysis::python_selection::main::resolve_python_sql_run_selection: use sqlbuild_analysis::python_selection::models::SqlSelectionGraph; use sqlbuild_core::text::main::python_str_repr::python_str_repr; use sqlbuild_orchestration::runs::models::{ - CommandPlan, PlannerResource, PublicationCache, SelectionProblem, SelectionVocabulary, + CommandPlan, PinnedJob, PlannerResource, PublicationCache, PublishedJobs, SelectionProblem, + SelectionVocabulary, }; -use sqlbuild_orchestration::runs::types::{CommandPlanner, PreparedPublication, PublishedJobs}; +use sqlbuild_orchestration::runs::types::{CommandPlanner, PreparedPublication}; use crate::adhoc::_helpers::evaluation::{evaluate, vocabulary}; -use crate::adhoc::_helpers::publication::IndexedPublication; +use crate::adhoc::_helpers::job_pins::{named_job_settings, pinned_jobs}; +use crate::adhoc::_helpers::publication::{IndexedPublication, python_kind}; use crate::adhoc::models::Refusal; use crate::adhoc::constants::{ @@ -65,6 +69,11 @@ impl PreparedPublication for IndexedPublication { let mut select: Vec = selectors.remove("select").unwrap_or_default(); select.extend(selectors.remove("positional_select").unwrap_or_default()); let exclude: Vec = selectors.remove("exclude").unwrap_or_default(); + let (named, job_settings) = if verb == BUILD_VERB { + named_job_settings(self, &select, &settings)? + } else { + (Vec::new(), BTreeMap::new()) + }; let selection: BTreeSet = match verb.as_str() { SEED_VERB => { let seeds: BTreeSet = resolve(self, &select, &exclude)? @@ -78,16 +87,25 @@ impl PreparedPublication for IndexedPublication { } FRESHNESS_VERB => freshness_sources(self, &select, &exclude)?, LOAD_VERB => managed_sources(self, &select, &exclude)?, - _ => { - let python = verb == BUILD_VERB - && settings.get(INCLUDE_PYTHON_DEST) != Some(&Json::Bool(false)); - resolve_with_tests((&verb, python), self, &select, &exclude)? - } + _ => resolve_with_tests( + (&verb, runs_python(&verb, (&settings, &job_settings))), + self, + &select, + &exclude, + )?, + }; + let jobs: BTreeMap = if named.is_empty() { + BTreeMap::new() + } else { + let python = runs_python(&verb, (&settings, &job_settings)); + pinned_jobs(self, (&select, &exclude), (&settings, python), &selection)? }; Ok(CommandPlan { verb, selection, settings, + jobs, + job_settings, }) } @@ -100,6 +118,18 @@ impl PreparedPublication for IndexedPublication { } } +/// Whether a command runs Python nodes: a build does unless its flags or named jobs turn them off. +fn runs_python( + verb: &str, + (settings, job_settings): (&BTreeMap, &BTreeMap), +) -> bool { + verb == BUILD_VERB + && settings + .get(INCLUDE_PYTHON_DEST) + .or_else(|| job_settings.get(INCLUDE_PYTHON_DEST)) + != Some(&Json::Bool(false)) +} + /// A command's verb, selectors by destination and validated settings. type CommandParts = ( String, @@ -313,6 +343,27 @@ fn resolved( exclude: &[String], include_python: bool, ) -> Result, Refusal> { + Ok(selected_keys(publication, select, exclude, include_python)? + .iter() + .map(|key| key_text(publication, key)) + .collect()) +} + +/// A selected graph key as a frozen node key; a loader's Python key names the source it loads. +pub(crate) fn key_text(publication: &IndexedPublication, (kind, name): &ObjectKey) -> String { + if python_kind(&format!("{kind}:{name}")).is_some() { + return python_run_key(&publication.sources, (kind, name)); + } + format!("{kind}:{name}") +} + +/// The graph keys the selectors match, SQL and Python alike. +pub(crate) fn selected_keys( + publication: &IndexedPublication, + select: &[String], + exclude: &[String], + include_python: bool, +) -> Result, SelectorError> { let python = publication.python(include_python); let selectors: Vec = select.iter().chain(exclude).cloned().collect(); let node_names: Vec<&str> = python.names.iter().map(String::as_str).collect(); @@ -335,13 +386,12 @@ fn resolved( Ok(selection .sql_keys .into_iter() - .map(|(kind, name)| format!("{kind}:{name}")) - .chain(selection.python_node_names.iter().filter_map(|name| { - Some(python_run_key( - sources, - (python.kinds.get(name.as_str())?, name), - )) - })) + .chain( + selection + .python_node_names + .iter() + .filter_map(|name| Some((python.kinds.get(name.as_str())?.clone(), name.clone()))), + ) .collect()) } diff --git a/crates/sqlbuild-cli/src/adhoc/_helpers/publication.rs b/crates/sqlbuild-cli/src/adhoc/_helpers/publication.rs index 2533962232..dfd70afd90 100644 --- a/crates/sqlbuild-cli/src/adhoc/_helpers/publication.rs +++ b/crates/sqlbuild-cli/src/adhoc/_helpers/publication.rs @@ -10,8 +10,8 @@ use sqlbuild_analysis::graph::models::{GraphResource, JobSelection, ProjectGraph use sqlbuild_analysis::planner_selection::models::UnitTestSelectorNames; use sqlbuild_analysis::python_selection::main::published_python_graph::published_python_graph; use sqlbuild_analysis::python_selection::models::{PublishedPythonNode, PythonSelectionGraph}; +use sqlbuild_orchestration::runs::models::PublishedJobs; use sqlbuild_orchestration::runs::models::{PlannerResource, SelectionVocabulary}; -use sqlbuild_orchestration::runs::types::PublishedJobs; use crate::adhoc::constants::SQL_TEST_KIND; @@ -58,7 +58,7 @@ impl IndexedPublication { resources: others .iter() .map(|resource| name_of(&resource.key).to_owned()) - .chain(jobs.keys().cloned()) + .chain(jobs.selections.keys().cloned()) .collect(), }; let (python, sql): (Vec<&PlannerResource>, Vec<&PlannerResource>) = others @@ -156,7 +156,7 @@ fn published_python_node(resource: &PlannerResource) -> Option BTreeMap { let mut selections: BTreeMap = BTreeMap::new(); - for (name, keys) in jobs { + for (name, keys) in &jobs.selections { let keys: Vec<(String, String)> = keys .iter() .filter(|key| include_python || python_kind(key).is_none()) diff --git a/crates/sqlbuild-cli/src/adhoc/tests.rs b/crates/sqlbuild-cli/src/adhoc/tests.rs index 6e8cf3cd4b..5b3529382c 100644 --- a/crates/sqlbuild-cli/src/adhoc/tests.rs +++ b/crates/sqlbuild-cli/src/adhoc/tests.rs @@ -2,6 +2,8 @@ mod adhoc_planner; #[path = "tests/helpers.rs"] mod helpers; +#[path = "tests/test_job_pins.rs"] +mod job_pins; #[path = "tests/test_selection_evaluation.rs"] mod selection_evaluation; #[path = "tests/test_types.rs"] diff --git a/crates/sqlbuild-cli/src/adhoc/tests/helpers.rs b/crates/sqlbuild-cli/src/adhoc/tests/helpers.rs index 1150df03db..c9c835f6ea 100644 --- a/crates/sqlbuild-cli/src/adhoc/tests/helpers.rs +++ b/crates/sqlbuild-cli/src/adhoc/tests/helpers.rs @@ -69,10 +69,13 @@ pub(super) fn orders_publication() ), resource("loader:stage_shipments", &[], &[], Some("python/loaders")), ]; - let jobs = std::collections::BTreeMap::from([( - "carrier_sync".to_owned(), - std::collections::BTreeSet::from(["asset:request_carrier_collection".to_owned()]), - )]); + let jobs = sqlbuild_orchestration::runs::models::PublishedJobs { + selections: std::collections::BTreeMap::from([( + "carrier_sync".to_owned(), + std::collections::BTreeSet::from(["asset:request_carrier_collection".to_owned()]), + )]), + ..Default::default() + }; crate::adhoc::main::adhoc_planner::adhoc_planner().prepare(resources, jobs) } @@ -102,3 +105,25 @@ pub(super) fn owned_evaluation( }) }) } + +/// A pinned `nightly` job holding `selection`, with its settings. +pub(super) fn nightly_pin(selection: &[&str]) -> serde_json::Value { + serde_json::json!({"selection": selection, "settings": {"concurrency": 1, "full_refresh": true, "vars": {"region": "north"}}}) +} + +/// A pinned `weekly` job holding `selection`, with its settings. +pub(super) fn weekly_pin(selection: &[&str]) -> serde_json::Value { + serde_json::json!({"selection": selection, "settings": {"vars": {"region": "north"}, "warehouse": "REPORTS_XS"}}) +} + +/// A pinning case's expected keys, pinned jobs and build-wide settings, or refusal fragment, owned. +pub(super) fn expected_pins( + expected: Result<(&[&str], serde_json::Value, serde_json::Value), &str>, +) -> Result<(Vec, serde_json::Value, serde_json::Value), String> { + expected + .map(|(selection, jobs, build)| { + let selection: Vec = selection.iter().map(|key| (*key).to_owned()).collect(); + (selection, jobs, build) + }) + .map_err(str::to_owned) +} diff --git a/crates/sqlbuild-cli/src/adhoc/tests/test_adhoc_planner.rs b/crates/sqlbuild-cli/src/adhoc/tests/test_adhoc_planner.rs index 5e955a3c09..392c280e50 100644 --- a/crates/sqlbuild-cli/src/adhoc/tests/test_adhoc_planner.rs +++ b/crates/sqlbuild-cli/src/adhoc/tests/test_adhoc_planner.rs @@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet}; use serde_json::json; use sqlbuild_orchestration::runs::models::PlannerResource; -use sqlbuild_orchestration::runs::types::PublishedJobs; +use sqlbuild_orchestration::runs::models::PublishedJobs; use crate::adhoc::main::adhoc_planner::adhoc_planner; use crate::adhoc::tests::helpers::{owned_plan, resource}; @@ -31,16 +31,19 @@ fn given_ad_hoc_commands_when_planned_then_flags_follow_the_allowlist_and_select resource("seed:currencies", &[], &[], None), resource("sql_test:orders_keep_amounts", &["model:orders"], &[], None), ]; - let jobs: PublishedJobs = BTreeMap::from([ - ( - "nightly".to_owned(), - BTreeSet::from(["model:orders".to_owned(), "model:order_totals".to_owned()]), - ), - ( - "daily_group".to_owned(), - BTreeSet::from(["model:customers".to_owned(), "model:orders".to_owned()]), - ), - ]); + let jobs: PublishedJobs = PublishedJobs { + selections: BTreeMap::from([ + ( + "nightly".to_owned(), + BTreeSet::from(["model:orders".to_owned(), "model:order_totals".to_owned()]), + ), + ( + "daily_group".to_owned(), + BTreeSet::from(["model:customers".to_owned(), "model:orders".to_owned()]), + ), + ]), + ..Default::default() + }; let test_cases = [ AdhocPlanTestCase { description: "a published job selects its published nodes", @@ -396,10 +399,13 @@ fn given_published_python_nodes_when_planned_then_selectors_resolve_as_on_the_co ), resource("loader:stage_shipments", &[], &[], Some("python/loaders")), ]; - let jobs: PublishedJobs = BTreeMap::from([( - "carrier_sync".to_owned(), - BTreeSet::from(["asset:request_carrier_collection".to_owned()]), - )]); + let jobs: PublishedJobs = PublishedJobs { + selections: BTreeMap::from([( + "carrier_sync".to_owned(), + BTreeSet::from(["asset:request_carrier_collection".to_owned()]), + )]), + ..Default::default() + }; let test_cases = [ AdhocPlanTestCase { description: "a published job selects its Python nodes", diff --git a/crates/sqlbuild-cli/src/adhoc/tests/test_job_pins.rs b/crates/sqlbuild-cli/src/adhoc/tests/test_job_pins.rs new file mode 100644 index 0000000000..4cee584b57 --- /dev/null +++ b/crates/sqlbuild-cli/src/adhoc/tests/test_job_pins.rs @@ -0,0 +1,202 @@ +//! A build naming jobs pins each to the frozen nodes it gives settings to, as `sqb build` decides them. + +use std::collections::{BTreeMap, BTreeSet}; + +use serde_json::{Value, json}; +use sqlbuild_orchestration::runs::models::PublishedJobs; + +use crate::adhoc::main::adhoc_planner::adhoc_planner; +use crate::adhoc::tests::helpers::{expected_pins, nightly_pin, resource, weekly_pin}; +use crate::adhoc::tests::test_types::JobPinTestCase; + +#[test] +fn given_a_build_naming_jobs_when_planned_then_each_is_pinned_to_the_nodes_it_gives_settings_to() { + let resources = [ + resource("model:orders", &[], &["daily"], None), + resource("model:order_totals", &["model:orders"], &["daily"], None), + resource("model:customers", &[], &[], None), + resource("model:nightly", &[], &["daily"], None), + ]; + let keys = + |keys: &[&str]| -> BTreeSet { keys.iter().map(|key| (*key).to_owned()).collect() }; + let settings = |value: Value| -> BTreeMap { + serde_json::from_value(value).expect("settings") + }; + let jobs = PublishedJobs { + selections: BTreeMap::from([ + ( + "nightly".to_owned(), + keys(&["model:order_totals", "model:orders"]), + ), + ("weekly".to_owned(), keys(&["model:customers"])), + ("south".to_owned(), keys(&["model:customers"])), + ("keep_orders".to_owned(), keys(&["model:orders"])), + ( + "reports".to_owned(), + keys(&["model:customers", "model:order_totals", "model:orders"]), + ), + ]), + groups: BTreeMap::from([( + "reports".to_owned(), + vec!["nightly".to_owned(), "weekly".to_owned()], + )]), + settings: BTreeMap::from([ + ( + "nightly".to_owned(), + settings( + json!({"concurrency": 1, "full_refresh": true, "vars": {"region": "north"}}), + ), + ), + ( + "weekly".to_owned(), + settings(json!({"vars": {"region": "north"}, "warehouse": "REPORTS_XS"})), + ), + ( + "south".to_owned(), + settings(json!({"vars": {"region": "south"}})), + ), + ( + "keep_orders".to_owned(), + settings(json!({"full_refresh": false, "vars": {"region": "north"}})), + ), + ]), + }; + let north = json!({"vars": {"region": "north"}}); + let test_cases = [ + JobPinTestCase { + description: "a named job pins its nodes and gives its build-wide vars", + command: &["build", "--select", "job:nightly"], + expected_plan: Ok(( + &["model:order_totals", "model:orders"], + json!({"nightly": nightly_pin(&["model:order_totals", "model:orders"])}), + north.clone(), + )), + }, + JobPinTestCase { + description: "an intersection pins only the nodes its token selects", + command: &["build", "--select", "job:nightly,orders"], + expected_plan: Ok(( + &["model:orders"], + json!({"nightly": nightly_pin(&["model:orders"])}), + north.clone(), + )), + }, + JobPinTestCase { + description: "an excluded node is not pinned", + command: &[ + "build", + "--select", + "job:nightly", + "--exclude", + "order_totals", + ], + expected_plan: Ok(( + &["model:orders"], + json!({"nightly": nightly_pin(&["model:orders"])}), + north.clone(), + )), + }, + JobPinTestCase { + description: "a group pins each of its jobs", + command: &["build", "--select", "job:reports"], + expected_plan: Ok(( + &["model:customers", "model:order_totals", "model:orders"], + json!({ + "nightly": nightly_pin(&["model:order_totals", "model:orders"]), + "weekly": weekly_pin(&["model:customers"]), + }), + north.clone(), + )), + }, + JobPinTestCase { + description: "a named job left with none of its nodes stays pinned for its build-wide settings, its warehouse among them", + command: &[ + "build", + "--select", + "job:weekly", + "orders", + "--exclude", + "customers", + ], + expected_plan: Ok(( + &["model:orders"], + json!({"weekly": weekly_pin(&[])}), + json!({"vars": {"region": "north"}, "warehouse": "REPORTS_XS"}), + )), + }, + JobPinTestCase { + description: "typed vars replace the jobs' vars", + command: &[ + "build", + "--select", + "job:nightly", + "--vars", + "{\"region\": \"east\"}", + ], + expected_plan: Ok(( + &["model:order_totals", "model:orders"], + json!({"nightly": nightly_pin(&["model:order_totals", "model:orders"])}), + json!({}), + )), + }, + JobPinTestCase { + description: "a tag selecting the model named like a job pins no job", + command: &["build", "--select", "tag:daily"], + expected_plan: Ok(( + &["model:nightly", "model:order_totals", "model:orders"], + json!({}), + json!({}), + )), + }, + JobPinTestCase { + description: "a test run takes no job settings", + command: &["test", "--select", "job:nightly"], + expected_plan: Ok(( + &["model:order_totals", "model:orders"], + json!({}), + json!({}), + )), + }, + JobPinTestCase { + description: "named jobs that set vars differently are refused, as the build would", + command: &["build", "--select", "job:nightly", "job:south"], + expected_plan: Err("set vars differently"), + }, + JobPinTestCase { + description: "named jobs that give one node different values are refused with S027, as the build would", + command: &["build", "--select", "job:nightly", "job:keep_orders"], + expected_plan: Err("S027: "), + }, + ]; + let publication = adhoc_planner().prepare(resources.to_vec(), jobs); + for test_case in test_cases { + let command: Vec = test_case + .command + .iter() + .map(|token| (*token).to_owned()) + .collect(); + let planned = publication + .plan(&command) + .map(|plan| { + ( + plan.selection.into_iter().collect::>(), + json!(plan.jobs), + json!(plan.job_settings), + ) + }) + .map_err(|refusal| { + test_case + .expected_plan + .as_ref() + .err() + .filter(|fragment| refusal.contains(**fragment)) + .map_or(refusal.clone(), |fragment| (*fragment).to_owned()) + }); + assert_eq!( + planned, + expected_pins(test_case.expected_plan), + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-cli/src/adhoc/tests/test_types.rs b/crates/sqlbuild-cli/src/adhoc/tests/test_types.rs index 1cda212340..5ebc38f04b 100644 --- a/crates/sqlbuild-cli/src/adhoc/tests/test_types.rs +++ b/crates/sqlbuild-cli/src/adhoc/tests/test_types.rs @@ -7,6 +7,20 @@ pub(super) struct AdhocPlanTestCase { pub(super) expected_plan: Result<(&'static [&'static str], serde_json::Value), &'static str>, } +/// A build command, and the keys it selects, the jobs it pins and their build-wide settings, or how it is refused. +pub(super) struct JobPinTestCase { + pub(super) description: &'static str, + pub(super) command: &'static [&'static str], + pub(super) expected_plan: Result< + ( + &'static [&'static str], + serde_json::Value, + serde_json::Value, + ), + &'static str, + >, +} + /// A selection as typed, and the keys it selects or how `sqb` refuses it. pub(super) struct SelectionEvaluationTestCase { pub(super) description: &'static str, diff --git a/crates/sqlbuild-cli/src/argv/command_table.json b/crates/sqlbuild-cli/src/argv/command_table.json index 322ddc5b85..f509e7e865 100644 --- a/crates/sqlbuild-cli/src/argv/command_table.json +++ b/crates/sqlbuild-cli/src/argv/command_table.json @@ -95,6 +95,30 @@ ] } }, + { + "name": "sensor", + "parser": { + "prog": "sqb sensor", + "description": "Try a published sensor's function from this project's code: with no event chosen, list the recent events its condition matches; with --event, --latest or --run, call the function once with that event, using the target's real providers. No run starts and no tick is recorded. Events come from the server through your sqb login session with --server, or from the local sqb dev store.", + "groups": [{"title": "positional arguments"}, {"title": "options"}], + "mutex_groups": [false], + "actions": [ + {"kind": "help", "options": ["-h", "--help"], "dest": "help", "nargs": 0, "default": {"suppress": true}, "help": "show this help message and exit", "group": 1}, + {"kind": "store", "options": [], "dest": "sensor_action", "required": true, "choices": ["try"], "help": "try: list the sensor's recent events, or call its function with one", "group": 0}, + {"kind": "store", "options": [], "dest": "sensor_name", "required": true, "help": "the sensor's name, such as orders_failed_sensor", "group": 0}, + {"kind": "store", "options": ["--event"], "dest": "sensor_event", "help": "call the function with this event ID, as a tick or the listing shows it", "group": 1, "mutex_group": 0}, + {"kind": "store_true", "options": ["--latest"], "dest": "sensor_latest", "nargs": 0, "const": true, "default": false, "help": "call the function with the newest matching event; a polling sensor is called once", "group": 1, "mutex_group": 0}, + {"kind": "store", "options": ["--run"], "dest": "sensor_run", "help": "for a run_event sensor, call the function with this run's terminal event", "group": 1, "mutex_group": 0}, + {"kind": "store", "options": ["--limit"], "dest": "sensor_limit", "type": "int", "default": 10, "help": "events to list when none is chosen (default: 10)", "group": 1}, + {"kind": "store", "options": ["--target"], "dest": "target", "help": "configured project target (default: the project's default target)", "group": 1}, + {"kind": "store", "options": ["--server"], "dest": "login_server", "help": "HTTPS SQLBuild server origin used by sqb login; without it, the local sqb dev store", "group": 1}, + {"kind": "store", "options": ["--ca-cert"], "dest": "login_ca", "help": "additional trusted PEM CA certificate", "group": 1}, + {"kind": "store", "options": ["--location-id"], "dest": "person_location", "help": "published location UUID; required with --server", "group": 1}, + {"kind": "store", "options": ["--control-store-url"], "dest": "development_store_url", "help": "sqb dev control store URL or path (default: .sqlbuild/control.sqlite3 in the project)", "group": 1}, + {"kind": "store", "options": ["--project-dir", "--sqb-project-dir"], "dest": "project_dir", "default": {"suppress": true}, "help": "SQLBuild project directory (default: the current directory)", "group": 1} + ] + } + }, { "name": "login", "parser": { @@ -136,7 +160,8 @@ {"kind": "store", "options": ["--port"], "dest": "control_port", "default": 8000, "type": "int", "help": "loopback TCP port, or 0 to choose a free port (default: 8000)", "group": 1}, {"kind": "store", "options": ["--control-store-url"], "dest": "development_store_url", "help": "control store URL or path (default: .sqlbuild/control.sqlite3 in the project)", "group": 1}, {"kind": "store_true", "options": ["--no-scheduler"], "dest": "control_no_scheduler", "nargs": 0, "const": true, "default": false, "help": "serve and reload without executing scheduled work", "group": 1}, - {"kind": "store_true", "options": ["--triggers"], "dest": "development_triggers", "nargs": 0, "const": true, "default": false, "help": "preserve trigger defaults and operator overrides instead of pausing on startup", "group": 1} + {"kind": "store_true", "options": ["--triggers"], "dest": "development_triggers", "nargs": 0, "const": true, "default": false, "help": "preserve trigger defaults and operator overrides instead of pausing on startup", "group": 1}, + {"kind": "store_true", "options": ["--plain"], "dest": "development_plain", "nargs": 0, "const": true, "default": false, "help": "append plain lines instead of redrawing the screen; chosen automatically when stdout or stderr is not a terminal", "group": 1} ] } }, @@ -899,10 +924,11 @@ "pause", "reset-default", "set-cursor", - "reset-cursor" + "reset-cursor", + "skip-event" ], "required": true, - "help": "runtime change; reset-default restores the published status default", + "help": "runtime change; reset-default restores the published status default, reset-cursor re-delivers every retained event to a sensor, skip-event marks one sensor event delivered", "group": 0 }, { @@ -933,6 +959,15 @@ "dest": "admin_cursor", "help": "RFC3339 timestamp with offset; required only for set-cursor", "group": 1 + }, + { + "kind": "store", + "options": [ + "--event" + ], + "dest": "admin_sensor_event", + "help": "the sensor event ID to mark delivered without calling the function; required only for skip-event", + "group": 1 } ] } @@ -9118,7 +9153,7 @@ } ], "choices_help": [ - {"dest": "control", "metavar": "control", "help": "inspect published SQL with your saved person session"}, + {"dest": "control", "metavar": "control", "help": "inspect published SQL with your saved person session"}, {"dest": "sensor", "metavar": "sensor", "help": "try a sensor's function with a recent event, using this project's code"}, {"dest": "login", "metavar": "login", "help": "sign in through a browser or verify a saved CLI session"}, {"dest": "logout", "metavar": "logout", "help": "revoke the CLI session and remove local credentials"}, { diff --git a/crates/sqlbuild-cli/src/argv/constants.rs b/crates/sqlbuild-cli/src/argv/constants.rs index a7d78b7319..88245da71b 100644 --- a/crates/sqlbuild-cli/src/argv/constants.rs +++ b/crates/sqlbuild-cli/src/argv/constants.rs @@ -288,3 +288,6 @@ pub(crate) const CLI_NAMESPACE_DEFAULTS: [(&str, NamespaceDefault); 194] = [ ("refactor_from_file", NamespaceDefault::None), ("refactor_cascade", NamespaceDefault::Bool(false)), ]; + +/// Columns for the help text of a parse that only reads options, which nothing shows. +pub(crate) const UNSHOWN_COLUMNS: i64 = 80; diff --git a/crates/sqlbuild-cli/src/argv/main/command_project_and_target.rs b/crates/sqlbuild-cli/src/argv/main/command_project_and_target.rs new file mode 100644 index 0000000000..75aa488ff3 --- /dev/null +++ b/crates/sqlbuild-cli/src/argv/main/command_project_and_target.rs @@ -0,0 +1,27 @@ +//! The `--project-dir` and `--target` a command line names, read before the command runs. + +use crate::argv::_helpers::job_settings::IntegerHost; +use crate::argv::constants::UNSHOWN_COLUMNS; +use crate::argv::main::namespace_defaults::namespace_defaults; +use crate::argv::main::parse_cli_arguments::parse_cli_arguments; +use crate::argv::models::{ArgvSettings, Value}; + +/// The named project directory and target as written, parsing numbers and defaults typed as the command's own parse does; `None` when the arguments don't parse, which the command reports. +pub(crate) fn command_project_and_target( + arguments: &[String], +) -> Option<(Option, Option)> { + let settings = ArgvSettings { + columns: UNSHOWN_COLUMNS, + use_color: false, + }; + let outcome = parse_cli_arguments(arguments, namespace_defaults(), settings, &mut IntegerHost); + let namespace = match outcome.parsed { + Ok(namespace) => namespace, + Err(_reported_by_the_command) => return None, + }; + let text = |name: &str| match namespace.get(name) { + Some(Value::Str(text) | Value::Path(text)) => Some(text.clone()), + _ => None, + }; + Some((text("project_dir"), text("target"))) +} diff --git a/crates/sqlbuild-cli/src/argv/main/mod.rs b/crates/sqlbuild-cli/src/argv/main/mod.rs index 62fed59be5..8916c50ed8 100644 --- a/crates/sqlbuild-cli/src/argv/main/mod.rs +++ b/crates/sqlbuild-cli/src/argv/main/mod.rs @@ -1,8 +1,10 @@ pub mod accepted_settings_arguments; pub mod cli_namespace_defaults; +pub(crate) mod command_project_and_target; pub mod command_settings_arguments; pub mod given_setting_dests; pub mod job_run_arguments; pub mod job_settings_arguments; +pub(crate) mod namespace_defaults; pub mod parse_cli_arguments; pub mod parse_dbt_execution_arguments; diff --git a/crates/sqlbuild-cli/src/argv/main/namespace_defaults.rs b/crates/sqlbuild-cli/src/argv/main/namespace_defaults.rs new file mode 100644 index 0000000000..2789875ce4 --- /dev/null +++ b/crates/sqlbuild-cli/src/argv/main/namespace_defaults.rs @@ -0,0 +1,25 @@ +//! The namespace a parse without an interpreter starts from. + +use crate::argv::main::cli_namespace_defaults::cli_namespace_defaults; +use crate::argv::models::{NamespaceDefault, Value}; + +/// The parse's starting namespace: every `CliNamespace` default. +pub(crate) fn namespace_defaults() -> Vec<(String, Value)> { + cli_namespace_defaults() + .iter() + .map(|(name, default)| { + let value: Value = match default { + NamespaceDefault::None => Value::None, + NamespaceDefault::Bool(flag) => Value::Bool(*flag), + NamespaceDefault::Int(number) => Value::Int(number.to_string()), + NamespaceDefault::Text(text) => Value::Str((*text).to_owned()), + NamespaceDefault::EmptyList => Value::List(Vec::new()), + NamespaceDefault::EmptyDict => Value::EmptyDict, + NamespaceDefault::CompileLineageFast | NamespaceDefault::ColumnLineageRich => { + Value::Host(0) + } + }; + ((*name).to_owned(), value) + }) + .collect() +} diff --git a/crates/sqlbuild-cli/src/argv/tests.rs b/crates/sqlbuild-cli/src/argv/tests.rs index c8b4187dfd..bb5435651b 100644 --- a/crates/sqlbuild-cli/src/argv/tests.rs +++ b/crates/sqlbuild-cli/src/argv/tests.rs @@ -1,3 +1,5 @@ +#[path = "tests/test_command_project_and_target.rs"] +mod command_project_and_target; #[path = "tests/test_given_setting_dests.rs"] mod given_setting_dests; #[path = "tests/helpers.rs"] diff --git a/crates/sqlbuild-cli/src/argv/tests/test_command_project_and_target.rs b/crates/sqlbuild-cli/src/argv/tests/test_command_project_and_target.rs new file mode 100644 index 0000000000..0f97c5e1ae --- /dev/null +++ b/crates/sqlbuild-cli/src/argv/tests/test_command_project_and_target.rs @@ -0,0 +1,69 @@ +use crate::argv::main::command_project_and_target::command_project_and_target; +use crate::argv::tests::test_types::CommandProjectTestCase; + +#[test] +fn given_a_command_line_when_reading_its_project_and_target_then_typed_options_still_parse() { + let test_cases = [ + CommandProjectTestCase { + description: "no typed options", + argv: &["--project-dir", "shop", "build", "--target", "dev"], + expected_project_and_target: Some(("shop", Some("dev"))), + }, + CommandProjectTestCase { + description: "a concurrency", + argv: &[ + "--project-dir", + "shop", + "build", + "--concurrency", + "4", + "--target", + "dev", + ], + expected_project_and_target: Some(("shop", Some("dev"))), + }, + CommandProjectTestCase { + description: "run variables", + argv: &[ + "--project-dir", + "shop", + "build", + "--vars", + "region: north", + "--target", + "dev", + ], + expected_project_and_target: Some(("shop", Some("dev"))), + }, + CommandProjectTestCase { + description: "a command whose numeric defaults are validated", + argv: &[ + "--project-dir", + "shop", + "scope", + "--at", + "models", + "--browse", + "models", + ], + expected_project_and_target: Some(("shop", None)), + }, + CommandProjectTestCase { + description: "an unknown option", + argv: &["--project-dir", "shop", "build", "--no-such-option"], + expected_project_and_target: None, + }, + ]; + + for test_case in test_cases { + let arguments: Vec = test_case.argv.iter().copied().map(str::to_owned).collect(); + assert_eq!( + command_project_and_target(&arguments), + test_case + .expected_project_and_target + .map(|(project, target)| (Some(project.to_owned()), target.map(str::to_owned))), + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-cli/src/argv/tests/test_types.rs b/crates/sqlbuild-cli/src/argv/tests/test_types.rs index 5ec630d3a1..ef95462a5e 100644 --- a/crates/sqlbuild-cli/src/argv/tests/test_types.rs +++ b/crates/sqlbuild-cli/src/argv/tests/test_types.rs @@ -117,3 +117,10 @@ pub(super) struct JobSettingFaultsTestCase { pub(super) faults: fn() -> Vec<&'static str>, pub(super) expected_faults: Vec<&'static str>, } + +/// A command line and the project and target read from it before it runs. +pub(super) struct CommandProjectTestCase { + pub(super) description: &'static str, + pub(super) argv: &'static [&'static str], + pub(super) expected_project_and_target: Option<(&'static str, Option<&'static str>)>, +} diff --git a/crates/sqlbuild-cli/src/bin/sqlbuild.rs b/crates/sqlbuild-cli/src/bin/sqlbuild.rs index ca32528190..d581d579e7 100644 --- a/crates/sqlbuild-cli/src/bin/sqlbuild.rs +++ b/crates/sqlbuild-cli/src/bin/sqlbuild.rs @@ -22,7 +22,7 @@ fn main() -> ExitCode { return ExitCode::FAILURE; }; let arguments: Vec = std::env::args_os().skip(1).collect(); - match hand_off(&sqb, &arguments) { + match hand_off(&sqb, &arguments, &[]) { Ok(Some(code)) => process_exit(code), Ok(None) => ExitCode::FAILURE, Err(error) => { diff --git a/crates/sqlbuild-cli/src/dev_screen/_helpers/apply_screen_message.rs b/crates/sqlbuild-cli/src/dev_screen/_helpers/apply_screen_message.rs index 5e68c57115..d3f621d30d 100644 --- a/crates/sqlbuild-cli/src/dev_screen/_helpers/apply_screen_message.rs +++ b/crates/sqlbuild-cli/src/dev_screen/_helpers/apply_screen_message.rs @@ -6,10 +6,10 @@ use sqlbuild_core::screen_text::models::PhaseState; use crate::dev_screen::_helpers::lines::{compose, ready_lines}; use crate::dev_screen::_helpers::transitions::{ - child_event, client_text, key_pressed, located, logged, run_reported, step_finished, - step_started, warehouse_settled, + child_event, client_text, key_pressed, logged, run_cancelling, run_reported, service_stopped, + step_failed, step_finished, step_started, warehouse_settled, }; -use crate::dev_screen::models::{DevScreen, DevStep, ScreenAction, ScreenMessage, ScreenOutput}; +use crate::dev_screen::models::{DevScreen, ScreenAction, ScreenMessage, ScreenOutput}; /// `screen` changed by `message` at `now` (local wall time `clock`), and the text to write. pub(crate) fn apply_screen_message( @@ -19,23 +19,38 @@ pub(crate) fn apply_screen_message( clock: &str, ) -> (DevScreen, ScreenOutput) { let mut action: ScreenAction = ScreenAction::None; - let mut raw: String = String::new(); - let (mut screen, mut lines): (DevScreen, Vec) = match message { + let (screen, lines): (DevScreen, Vec) = match message { ScreenMessage::Started { step, detail } => step_started(screen, (step, detail), now), ScreenMessage::Finished { step, detail } => { step_finished(screen, (step, PhaseState::Ok), detail, now) } + ScreenMessage::Failed { + step, + detail, + problem, + } => step_failed(screen, (step, detail, problem), now), ScreenMessage::Child(event) => child_event(screen, event, now, clock), - ScreenMessage::Location(location) => located(screen, location), + ScreenMessage::Location(location) => (DevScreen { location, ..screen }, Vec::new()), ScreenMessage::Triggers(triggers) => (DevScreen { triggers, ..screen }, Vec::new()), ScreenMessage::Warehouse { adapter, state } => { - let (screen, closing, lines) = warehouse_settled(screen, (adapter, state), now, clock); - raw = closing; - (screen, lines) + warehouse_settled(screen, (adapter, state), now, clock) } ScreenMessage::ClientOutput(text) => { - let (screen, text) = client_text(screen, &text, now); - return (screen, ScreenOutput { text, action }); + if !screen.live { + let (mut screen, mut output) = compose(screen, Vec::new(), now); + if !text.is_empty() { + screen.client_partial = !text.ends_with('\n'); + } + output.push_str(&text); + return ( + screen, + ScreenOutput { + text: output, + action, + }, + ); + } + (client_text(screen, &text, now), Vec::new()) } ScreenMessage::Run { name, @@ -52,32 +67,36 @@ pub(crate) fn apply_screen_message( (screen, shown) } ScreenMessage::Tick => { - if !screen.live || screen.ready || screen.client_output || connecting(&screen) { - return ( - screen, - ScreenOutput { - text: String::new(), - action, - }, - ); - } let frame: usize = screen.frame + 1; (DevScreen { frame, ..screen }, Vec::new()) } + ScreenMessage::Stopping => { + let stopping = screen.stopping.or(Some(now)); + ( + DevScreen { + stopping, + prompt: None, + ..screen + }, + Vec::new(), + ) + } + ScreenMessage::Cancelling { label } => { + let lines: Vec = run_cancelling(&screen, label); + (screen, lines) + } + ScreenMessage::Stopped { label, elapsed } => { + let lines: Vec = service_stopped(&screen, label, elapsed); + (screen, lines) + } + }; + let (screen, mut lines) = (screen, lines); + let (screen, ready) = if screen.stopping.is_some() { + (screen, Vec::new()) + } else { + ready_lines(screen) }; - if screen.event_gap && !lines.is_empty() { - screen.event_gap = false; - lines.insert(0, String::new()); - } - let (screen, ready) = ready_lines(screen, now); lines.extend(ready); - let (screen, text) = compose(screen, (&raw, &lines), now); + let (screen, text) = compose(screen, lines, now); (screen, ScreenOutput { text, action }) } - -/// The foreground connection may prompt on the terminal itself, so nothing redraws over it. -fn connecting(screen: &DevScreen) -> bool { - screen.steps.iter().any(|row| { - row.step == DevStep::Warehouse && matches!(row.state, PhaseState::Running { .. }) - }) -} diff --git a/crates/sqlbuild-cli/src/dev_screen/_helpers/drawing.rs b/crates/sqlbuild-cli/src/dev_screen/_helpers/drawing.rs index 6046427f86..fffc1a79ca 100644 --- a/crates/sqlbuild-cli/src/dev_screen/_helpers/drawing.rs +++ b/crates/sqlbuild-cli/src/dev_screen/_helpers/drawing.rs @@ -1,70 +1,111 @@ -//! The screen task: apply each message, write its text, and leave the closing text behind. +//! The screen task: apply each message, write its text, and leave the result line behind. use std::fs::File; use std::io::Write; use std::time::Instant; use sqlbuild_core::screen_text::main::redraw_rows::redraw_rows; +use sqlbuild_core::screen_text::main::render_log_line::render_log_line; +use sqlbuild_core::screen_text::main::render_result::render_result; use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender}; use tokio::sync::oneshot; use crate::dev_screen::_helpers::apply_screen_message::apply_screen_message; use crate::dev_screen::_helpers::capture::release_stderr; use crate::dev_screen::_helpers::keys::KeyReader; +use crate::dev_screen::_helpers::lines::{compose, physical_rows}; use crate::dev_screen::constants::{FAILURE_LOG_LINES, TICK}; -use crate::dev_screen::models::{DevScreen, ScreenAction, ScreenMessage}; +use crate::dev_screen::main::terminal_size::terminal_size; +use crate::dev_screen::models::{DevScreen, ScreenAction, ScreenEnd, ScreenMessage}; +use crate::dev_stop::main::stop_switch::stop_switch; -/// Apply each message and write what it draws, until the session finishes; then leave the closing text. +/// Apply each message and write what it draws until the session finishes; then leave its result. pub(crate) async fn draw_screen( mut screen: DevScreen, (mut inbox, actions): ( UnboundedReceiver, UnboundedSender, ), - mut finished: oneshot::Receiver, + mut finished: oneshot::Receiver, (keys, terminal): (Option, Option), ) { let mut tick = tokio::time::interval(TICK); tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); - let failed: bool = loop { + let end: Option = loop { let message: ScreenMessage = tokio::select! { - failed = &mut finished => break failed.unwrap_or(false), + biased; message = inbox.recv() => match message { Some(message) => message, - None => break false, + None => break None, + }, + end = &mut finished => break end.ok(), + _ = tick.tick(), if screen.live => { + if let Some((columns, rows)) = terminal_size(terminal.as_ref()) { + screen.facts.columns = columns; + screen.facts.rows = rows; + } + ScreenMessage::Tick }, - _ = tick.tick(), if screen.live => ScreenMessage::Tick, }; - let clock: String = chrono::Local::now().format("%H:%M:%S").to_string(); - let output; - (screen, output) = apply_screen_message(screen, message, Instant::now(), &clock); - write_screen(terminal.as_ref(), &output.text); - if output.action != ScreenAction::None { - let _ = actions.send(output.action); - } + screen = apply(screen, message, (terminal.as_ref(), &actions)); }; + while let Ok(message) = inbox.try_recv() { + screen = apply(screen, message, (terminal.as_ref(), &actions)); + } drop(keys); + let text: String = closing_text(screen, end.as_ref()); + write_screen(terminal.as_ref(), &text); if let Some(terminal) = terminal.as_ref() { release_stderr(terminal); } - write_screen(None, &closing_text(&screen, failed)); + stop_switch().save_output(None); } -/// What stays on the terminal after the screen stops: the live rows cleared and, on failure, the newest log lines that explain it. -fn closing_text(screen: &DevScreen, failed: bool) -> String { - let mut text: String = if screen.live && screen.drawn > 0 { - redraw_rows(screen.drawn, &[]) - } else { - String::new() - }; - if failed && !screen.show_log { - let skip: usize = screen.log.len().saturating_sub(FAILURE_LOG_LINES); - for line in screen.log.iter().skip(skip) { - text.push_str(line); - text.push('\n'); +fn apply( + screen: DevScreen, + message: ScreenMessage, + (terminal, actions): (Option<&File>, &UnboundedSender), +) -> DevScreen { + let clock: String = chrono::Local::now().format("%H:%M:%S").to_string(); + let (screen, output) = apply_screen_message(screen, message, Instant::now(), &clock); + write_screen(terminal, &output.text); + if output.action != ScreenAction::None { + let _ = actions.send(output.action); + } + screen +} + +/// The live rows cleared, the newest log lines when the screen did not explain the failure, then the result line. +pub(crate) fn closing_text(screen: DevScreen, end: Option<&ScreenEnd>) -> String { + let mut lines: Vec = Vec::new(); + if let Some(end) = end { + if end.show_log && !screen.show_log { + let skip: usize = screen.log.len().saturating_sub(FAILURE_LOG_LINES); + for line in screen.log.iter().skip(skip) { + lines.extend(render_log_line(line, &screen.facts)); + } } + lines.extend(render_result(&end.result, &screen.facts)); + } + let header_printed: bool = screen.header_printed; + let live: bool = screen.live; + let previous: usize = physical_rows(&screen.drawn, screen.facts.columns); + if !live || !header_printed { + let (_, text) = compose( + DevScreen { + live: false, + ..screen + }, + lines, + Instant::now(), + ); + return if live && previous > 0 { + format!("{}{text}", redraw_rows(previous, &[])) + } else { + text + }; } - text + redraw_rows(previous, &lines) } /// Write to the terminal stderr was taken from, or to stderr when it was not redirected. diff --git a/crates/sqlbuild-cli/src/dev_screen/_helpers/keys.rs b/crates/sqlbuild-cli/src/dev_screen/_helpers/keys.rs index 0e5c825d7f..d03e1f28d5 100644 --- a/crates/sqlbuild-cli/src/dev_screen/_helpers/keys.rs +++ b/crates/sqlbuild-cli/src/dev_screen/_helpers/keys.rs @@ -1,10 +1,10 @@ -//! Hotkeys from the terminal: stdin in raw mode, handed back to the warehouse client while it prompts. +//! Keys from the terminal in raw mode: Ctrl+C and `q` stop `sqb dev`, Ctrl+\\ forces the stop, typing at a sign-in prompt goes to the client, and a terminal that hangs up stops it. +#[cfg(unix)] +use std::io::Write; use std::sync::Arc; use std::sync::atomic::Ordering; use std::thread::JoinHandle; -#[cfg(unix)] -use std::time::Duration; #[cfg(unix)] use rustix::termios::{ @@ -13,88 +13,126 @@ use rustix::termios::{ use tokio::sync::mpsc::UnboundedSender; #[cfg(unix)] -use crate::dev_screen::constants::KEY_POLL; -use crate::dev_screen::models::{KeyGate, ScreenMessage}; +use crate::dev_screen::constants::{ + FORCE_BYTE, INTERRUPT_BYTE, KEY_WAIT, SUSPEND_BYTE, SUSPEND_UNSUPPORTED, +}; +use crate::dev_screen::models::{KeyInput, ScreenMessage}; +use crate::dev_stop::main::stop_switch::stop_switch; +#[cfg(unix)] +use crate::dev_stop::models::StopReason; -/// The hotkey thread; dropping it restores the terminal. +/// The key thread; dropping it stops the thread and restores the terminal. pub(crate) struct KeyReader { - gate: Arc, + input: Arc, thread: Option>, } impl KeyReader { - /// Start reading keys into `keys`, or `None` when stdin is not a terminal. + /// Put stdin in raw mode and read keys into `keys`, or `None` when stdin is not a terminal. #[cfg(unix)] pub(crate) fn start(keys: UnboundedSender) -> Option { let cooked: Termios = match tcgetattr(std::io::stdin()) { Ok(cooked) => cooked, - Err(_) => return None, + Err(_not_a_terminal) => return None, }; - let gate: Arc = Arc::new(KeyGate::default()); - let shared: Arc = Arc::clone(&gate); - let thread = std::thread::spawn(move || read_keys(&shared, &cooked, &keys)); + stop_switch().save_cooked(cooked.clone()); + if let Err(_unchangeable) = + tcsetattr(std::io::stdin(), OptionalActions::Now, &raw_mode(&cooked)) + { + return None; + } + let input: Arc = Arc::new(KeyInput::default()); + let shared: Arc = Arc::clone(&input); + let thread = std::thread::spawn(move || read_keys(&shared, &keys)); Some(Self { - gate, + input, thread: Some(thread), }) } - /// Hotkeys need a Unix terminal; the screen is plain elsewhere. + /// Keys need a Unix terminal; the screen is plain elsewhere. #[cfg(not(unix))] pub(crate) fn start(_keys: UnboundedSender) -> Option { None } - pub(crate) fn gate(&self) -> Arc { - Arc::clone(&self.gate) + pub(crate) fn input(&self) -> Arc { + Arc::clone(&self.input) } } impl Drop for KeyReader { fn drop(&mut self) { - self.gate.stop.store(true, Ordering::SeqCst); + self.input.stop.store(true, Ordering::SeqCst); if let Some(thread) = self.thread.take() { drop(thread.join()); } + stop_switch().restore_terminal(); } } -/// Keys without echo or line buffering; Ctrl-C still interrupts, and reads give up after a tenth of a second. +/// No echo, no line buffering and no signal keys, so Ctrl+C, Ctrl+\\ and Ctrl+Z arrive as bytes; a read returns what is there without waiting. #[cfg(unix)] fn raw_mode(cooked: &Termios) -> Termios { let mut raw: Termios = cooked.clone(); - raw.local_modes -= LocalModes::ICANON | LocalModes::ECHO; + raw.local_modes -= LocalModes::ICANON | LocalModes::ECHO | LocalModes::ISIG; raw.special_codes[SpecialCodeIndex::VMIN] = 0; - raw.special_codes[SpecialCodeIndex::VTIME] = 1; + raw.special_codes[SpecialCodeIndex::VTIME] = 0; raw } +/// Wait up to `KEY_WAIT` for a key; a terminal that is readable but has nothing to read has hung up. #[cfg(unix)] -fn read_keys(gate: &KeyGate, cooked: &Termios, keys: &UnboundedSender) { - let raw: Termios = raw_mode(cooked); +fn read_keys(input: &KeyInput, keys: &UnboundedSender) { + use rustix::event::{PollFd, PollFlags, Timespec, poll}; + let wait: Timespec = Timespec { + tv_sec: 0, + tv_nsec: i64::from(KEY_WAIT.subsec_nanos()), + }; let mut byte: [u8; 1] = [0]; - while !gate.stop.load(Ordering::SeqCst) && !keys.is_closed() { - let reading: bool = gate.reading.load(Ordering::SeqCst); - if gate.closed.load(Ordering::SeqCst) { - if reading { - let _ = tcsetattr(std::io::stdin(), OptionalActions::Now, cooked); - gate.reading.store(false, Ordering::SeqCst); - } - std::thread::sleep(KEY_POLL); - continue; - } - if !reading { - if tcsetattr(std::io::stdin(), OptionalActions::Now, &raw).is_err() { - return; - } - gate.reading.store(true, Ordering::SeqCst); - } - match rustix::io::read(std::io::stdin(), &mut byte) { - Ok(1) => drop(keys.send(ScreenMessage::Key(char::from(byte[0]).to_ascii_lowercase()))), + while !input.stop.load(Ordering::SeqCst) { + let stdin = std::io::stdin(); + let mut ready: [PollFd<'_>; 1] = [PollFd::new(&stdin, PollFlags::IN)]; + match poll(&mut ready, Some(&wait)) { + Ok(0) | Err(rustix::io::Errno::INTR | rustix::io::Errno::AGAIN) => continue, Ok(_) => {} - Err(_) => std::thread::sleep(Duration::from_millis(100)), + Err(_) => return hung_up(), + } + match rustix::io::read(&stdin, &mut byte) { + Ok(1) => key(input, keys, byte[0]), + Err(rustix::io::Errno::INTR | rustix::io::Errno::AGAIN) => {} + Ok(_) | Err(_) => return hung_up(), } } - let _ = tcsetattr(std::io::stdin(), OptionalActions::Now, cooked); - gate.reading.store(false, Ordering::SeqCst); +} + +/// The terminal went away: stop as SIGHUP would. +#[cfg(unix)] +fn hung_up() { + stop_switch().request(StopReason::Hangup); +} + +#[cfg(unix)] +fn key(input: &KeyInput, keys: &UnboundedSender, byte: u8) { + if byte == INTERRUPT_BYTE { + stop_switch().request(StopReason::Interrupt); + return; + } + if byte == FORCE_BYTE { + stop_switch().force(StopReason::Interrupt); + } + if byte == SUSPEND_BYTE { + drop(keys.send(ScreenMessage::Log(SUSPEND_UNSUPPORTED.to_owned()))); + return; + } + if let Ok(mut forward) = input.forward.lock() + && let Some(client) = forward.as_mut() + { + drop(client.write_all(&[byte])); + return; + } + match char::from(byte).to_ascii_lowercase() { + 'q' => stop_switch().request(StopReason::Quit), + key => drop(keys.send(ScreenMessage::Key(key))), + } } diff --git a/crates/sqlbuild-cli/src/dev_screen/_helpers/labels.rs b/crates/sqlbuild-cli/src/dev_screen/_helpers/labels.rs new file mode 100644 index 0000000000..627a3a66bc --- /dev/null +++ b/crates/sqlbuild-cli/src/dev_screen/_helpers/labels.rs @@ -0,0 +1,57 @@ +//! What each step is called while it waits, runs and is done. + +use std::time::{Duration, Instant}; + +use sqlbuild_core::screen_text::models::PhaseState; + +use crate::dev_screen::models::DevStep; + +/// `step`'s label in `state`: `Compile project`, `Compiling project`, `Compiled project`; a failed or warned step keeps the running form. +pub(crate) fn step_label(step: DevStep, state: PhaseState) -> &'static str { + let (pending, running, done): (&str, &str, &str) = match step { + DevStep::Config => ( + "Read configuration", + "Reading configuration", + "Read configuration", + ), + DevStep::ControlStore => ( + "Open control store", + "Opening control store", + "Opened control store", + ), + DevStep::Api => ("Start UI server", "Starting UI server", "Started UI server"), + DevStep::Scheduler => ("Start scheduler", "Starting scheduler", "Started scheduler"), + DevStep::Discover => ( + "Discover project", + "Discovering project", + "Discovered project", + ), + DevStep::Compile => ("Compile project", "Compiling project", "Compiled project"), + DevStep::Publish => ( + "Publish snapshot", + "Publishing snapshot", + "Published snapshot", + ), + DevStep::Warehouse => ( + "Connect warehouse", + "Connecting warehouse", + "Connected warehouse", + ), + }; + match state { + PhaseState::Pending => pending, + PhaseState::Ok => done, + PhaseState::Running { .. } | PhaseState::Warn | PhaseState::Fail => { + if step == DevStep::Config { + pending + } else { + running + } + } + } +} + +/// How long ago `started` was, if it was. +pub(crate) fn elapsed_since(started: Option, now: Instant) -> Option { + started.map(|started| now.saturating_duration_since(started)) +} diff --git a/crates/sqlbuild-cli/src/dev_screen/_helpers/lines.rs b/crates/sqlbuild-cli/src/dev_screen/_helpers/lines.rs index e188225929..9d80fae738 100644 --- a/crates/sqlbuild-cli/src/dev_screen/_helpers/lines.rs +++ b/crates/sqlbuild-cli/src/dev_screen/_helpers/lines.rs @@ -1,106 +1,169 @@ -//! The lines the `sqb dev` screen prints: event lines, the ready card, and the redraw that places them. +//! The lines the `sqb dev` screen prints for good, and the redraw that places them above the live rows. -use std::time::{Duration, Instant}; +use std::time::Instant; -use sqlbuild_core::screen_text::main::format_plain_line::format_plain_line; use sqlbuild_core::screen_text::main::redraw_rows::redraw_rows; -use sqlbuild_core::screen_text::main::render_event_line::render_event_line; -use sqlbuild_core::screen_text::main::render_ready_card::render_ready_card; -use sqlbuild_core::screen_text::models::{EventLine, EventMark, ReadyCard, Segment}; +use sqlbuild_core::screen_text::main::render_dev_header::render_dev_header; +use sqlbuild_core::screen_text::main::render_labelled_parts::render_labelled_parts; +use sqlbuild_core::screen_text::main::render_ready_box::render_ready_box; +use sqlbuild_core::screen_text::main::render_step_line::render_step_line; +use sqlbuild_core::screen_text::main::visible_cells::visible_cells; +use sqlbuild_core::screen_text::models::{BoxRow, StepLine, WarehouseState}; use crate::dev_screen::_helpers::rows::live_rows; -use crate::dev_screen::models::{DevScreen, DevStep}; +use crate::dev_screen::models::DevScreen; -/// One event: its live line, and the plain line's message. -pub(crate) struct Report<'a> { - pub(crate) clock: &'a str, - pub(crate) mark: EventMark, - pub(crate) title: String, - pub(crate) detail: String, - pub(crate) elapsed: Option, - pub(crate) notes: Vec>, - pub(crate) plain: String, +/// A step line printed for good, its detail wrapped in full. +pub(crate) fn lasting_step(screen: &DevScreen, line: &StepLine) -> Vec { + render_step_line(line, &screen.facts, true) } -/// The event's rows on a live screen, or its one plain line. -pub(crate) fn report_lines(screen: &DevScreen, report: Report<'_>) -> Vec { - if !screen.live { - return vec![format_plain_line(&report.plain, report.elapsed)]; +/// The Warehouse line's parts: the adapter, then its labelled settings, or why it is not connected. +pub(crate) fn warehouse_parts(adapter: &str, state: &WarehouseState) -> Vec { + let mut parts: Vec = Vec::new(); + if !adapter.is_empty() { + parts.push(adapter.to_owned()); } - render_event_line( - &EventLine { - clock: report.clock.to_owned(), - mark: report.mark, - title: report.title, - detail: report.detail, - elapsed: report.elapsed, - notes: report.notes, - }, - &screen.facts, - ) + match state { + WarehouseState::Connected { facts } => parts.extend(facts.iter().cloned()), + WarehouseState::NotConnected { reason } => { + parts.push(format!("not connected: {reason}")); + } + WarehouseState::Failed { message } => parts.push(format!("failed: {message}")), + } + parts } -/// The card, or the plain `ready` line, once the first generation is published and the warehouse settled. -pub(crate) fn ready_lines(mut screen: DevScreen, now: Instant) -> (DevScreen, Vec) { - let published: bool = screen - .steps - .iter() - .any(|row| row.step == DevStep::Publish && row.elapsed.is_some()); - let (Some(generation), Some(warehouse), false, true) = ( - screen.serving, - screen.warehouse.clone(), - screen.ready, - published, - ) else { +/// The ready box, or plain `✓ ready` lines, once the first snapshot serves and the warehouse settled. +pub(crate) fn ready_lines(mut screen: DevScreen) -> (DevScreen, Vec) { + let (Some(_), Some(warehouse), false) = + (&screen.serving, screen.warehouse.clone(), screen.ready) + else { return (screen, Vec::new()); }; screen.ready = true; + let parts: Vec = warehouse_parts(&screen.adapter, &warehouse); if !screen.live { - let line: String = format_plain_line(&format!("ready {}", screen.ui_url), None); - return (screen, vec![line]); + let mut lines: Vec = vec![format!("\u{2713} ready {}", screen.ui_url)]; + lines.extend(render_labelled_parts( + "warehouse", + &parts, + screen.facts.columns, + )); + if !screen.location.is_empty() { + lines.extend(render_labelled_parts( + "location ", + std::slice::from_ref(&screen.location), + screen.facts.columns, + )); + } + if !screen.triggers.is_empty() { + lines.extend(render_labelled_parts( + "triggers ", + std::slice::from_ref(&screen.triggers), + screen.facts.columns, + )); + } + if let Some(env_file) = &screen.env_file { + lines.extend(render_labelled_parts( + "env file ", + std::slice::from_ref(env_file), + screen.facts.columns, + )); + } + return (screen, lines); } - let mut location: String = format!("{} \u{b7} gen {generation}", screen.header.target); - if !screen.compile_detail.is_empty() { - location = format!("{location} \u{b7} {}", screen.compile_detail); + let mut project: Vec = vec![ + screen.header.project.clone(), + home_relative(&screen.project_root), + ]; + if !screen.header.target.is_empty() { + project.push(format!("target {}", screen.header.target)); } - let lines: Vec = render_ready_card( - &ReadyCard { - version: screen.header.version.clone(), - ready_in: now.saturating_duration_since(screen.started), - ui_url: screen.ui_url.clone(), - location, - adapter: screen.adapter.clone(), - warehouse, - triggers: screen.triggers.clone(), - watching: screen.watching.clone(), + let mut rows: Vec = vec![ + BoxRow { + label: "UI".to_owned(), + parts: vec![screen.ui_url.clone()], + link: Some(screen.ui_url.clone()), + }, + BoxRow { + label: "Project".to_owned(), + parts: project, + link: None, + }, + BoxRow { + label: "Warehouse".to_owned(), + parts, + link: None, }, - &screen.facts, - ); - screen.event_gap = true; + ]; + if !screen.triggers.is_empty() { + rows.push(BoxRow { + label: "Triggers".to_owned(), + parts: vec![screen.triggers.clone()], + link: None, + }); + } + if let Some(env_file) = &screen.env_file { + rows.push(BoxRow { + label: "Env file".to_owned(), + parts: vec![env_file.clone()], + link: None, + }); + } + let lines: Vec = render_ready_box(&rows, &screen.facts); (screen, lines) } -/// `raw` client text, then `lines` printed for good, then the live rows redrawn below them. +/// `path` with the home directory written as `~`. +fn home_relative(path: &str) -> String { + match std::env::var("HOME") { + Ok(home) if !home.is_empty() && path.starts_with(&home) => { + format!("~{}", &path[home.len()..]) + } + _ => path.to_owned(), + } +} + +/// The header once, then `lines` printed for good, then the live rows redrawn below them. pub(crate) fn compose( mut screen: DevScreen, - (raw, lines): (&str, &[String]), + lines: Vec, now: Instant, ) -> (DevScreen, String) { - let mut text: String = raw.to_owned(); + let mut lasting: Vec = Vec::new(); + if !screen.header_printed { + screen.header_printed = true; + lasting.extend(render_dev_header(&screen.header, &screen.facts)); + } + lasting.extend(lines); if !screen.live { - for line in lines { - text.push_str(line); + let mut text: String = String::new(); + if screen.client_partial && !lasting.is_empty() { + screen.client_partial = false; + text.push('\n'); + } + for line in lasting { + text.push_str(&line); text.push('\n'); } - return (screen, text); - } - if screen.client_output { return (screen, text); } let live: Vec = live_rows(&screen, now); - let mut rows: Vec = lines.to_vec(); - rows.extend(live.iter().cloned()); - text.push_str(&redraw_rows(screen.drawn, &rows)); - screen.drawn = live.len(); + if lasting.is_empty() && live == screen.drawn { + return (screen, String::new()); + } + let previous: usize = physical_rows(&screen.drawn, screen.facts.columns); + lasting.extend(live.iter().cloned()); + let text: String = redraw_rows(previous, &lasting); + screen.drawn = live; (screen, text) } + +/// The terminal rows `rows` cover at `columns`, after a resize may have wrapped them. +pub(crate) fn physical_rows(rows: &[String], columns: usize) -> usize { + let columns: usize = columns.max(1); + rows.iter() + .map(|row| visible_cells(row).div_ceil(columns).max(1)) + .sum() +} diff --git a/crates/sqlbuild-cli/src/dev_screen/_helpers/mod.rs b/crates/sqlbuild-cli/src/dev_screen/_helpers/mod.rs index 0c724e415a..cc39afcfa8 100644 --- a/crates/sqlbuild-cli/src/dev_screen/_helpers/mod.rs +++ b/crates/sqlbuild-cli/src/dev_screen/_helpers/mod.rs @@ -2,7 +2,9 @@ pub(crate) mod apply_screen_message; pub(crate) mod capture; pub(crate) mod drawing; pub(crate) mod keys; +pub(crate) mod labels; pub(crate) mod lines; pub(crate) mod new_dev_screen; pub(crate) mod rows; +pub(crate) mod secrets; pub(crate) mod transitions; diff --git a/crates/sqlbuild-cli/src/dev_screen/_helpers/new_dev_screen.rs b/crates/sqlbuild-cli/src/dev_screen/_helpers/new_dev_screen.rs index 81d20482e8..611e8378b1 100644 --- a/crates/sqlbuild-cli/src/dev_screen/_helpers/new_dev_screen.rs +++ b/crates/sqlbuild-cli/src/dev_screen/_helpers/new_dev_screen.rs @@ -1,38 +1,38 @@ //! A `sqb dev` screen before its first step. use std::collections::VecDeque; -use std::time::Instant; use crate::dev_screen::_helpers::transitions::pending; use crate::dev_screen::constants::STEPS; use crate::dev_screen::models::{DevScreen, ScreenSetup}; /// Every step pending, the warehouse unknown and nothing drawn yet. -pub(crate) fn new_dev_screen(setup: ScreenSetup, started: Instant) -> DevScreen { +pub(crate) fn new_dev_screen(setup: ScreenSetup) -> DevScreen { DevScreen { live: setup.live, facts: setup.facts, header: setup.header, + header_printed: false, ui_url: String::new(), - watching: setup.watching, + location: String::new(), + env_file: setup.env_file, + missing_secrets: Vec::new(), triggers: String::new(), - started, steps: STEPS.into_iter().map(pending).collect(), ready: false, - location: String::new(), - adapter: String::new(), + adapter: setup.adapter, warehouse: None, generation_started: None, pending_changes: 0, serving: None, compile_detail: String::new(), project_root: setup.project_root, - client_output: false, + prompt: None, client_partial: false, - event_gap: false, + stopping: None, log: VecDeque::new(), show_log: false, frame: 0, - drawn: 0, + drawn: Vec::new(), } } diff --git a/crates/sqlbuild-cli/src/dev_screen/_helpers/rows.rs b/crates/sqlbuild-cli/src/dev_screen/_helpers/rows.rs index 5a056c694b..7295f4ae14 100644 --- a/crates/sqlbuild-cli/src/dev_screen/_helpers/rows.rs +++ b/crates/sqlbuild-cli/src/dev_screen/_helpers/rows.rs @@ -1,85 +1,146 @@ -//! The live rows of the `sqb dev` screen: the checklist before ready, the hotkey bar after. +//! The live rows of the `sqb dev` screen: a prompt, the running and waiting steps, and the key line, never taller than the terminal. -use std::time::{Duration, Instant}; +use std::time::Instant; -use sqlbuild_core::screen_text::main::render_dev_header::render_dev_header; -use sqlbuild_core::screen_text::main::render_frame_rule::render_frame_rule; -use sqlbuild_core::screen_text::main::render_hotkey_bar::render_hotkey_bar; -use sqlbuild_core::screen_text::main::render_phase_lines::render_phase_lines; -use sqlbuild_core::screen_text::models::{Hotkey, PhaseLayout, PhaseLine, PhaseState}; +use sqlbuild_core::screen_text::main::render_key_line::render_key_line; +use sqlbuild_core::screen_text::main::render_prompt::render_prompt; +use sqlbuild_core::screen_text::main::render_step_line::render_step_line; +use sqlbuild_core::screen_text::models::{Hotkey, PhaseState, PromptBlock, StepLine}; -use crate::dev_screen::constants::{HOTKEYS, WAREHOUSE_FRAME_LABEL}; -use crate::dev_screen::models::{DevScreen, DevStep, StepRow}; +use crate::dev_screen::_helpers::labels::{elapsed_since, step_label}; +use crate::dev_screen::_helpers::secrets::secrets_rows; +use crate::dev_screen::constants::{READY_KEYS, STARTING_KEYS}; +use crate::dev_screen::models::{DevScreen, StepRow}; -/// The label a checklist row shows for `step`. -pub(crate) fn step_label(step: DevStep) -> &'static str { - match step { - DevStep::ControlStore => "Control store", - DevStep::Api => "API", - DevStep::Scheduler => "Scheduler", - DevStep::Discover => "Discover project", - DevStep::Compile => "Compile snapshot", - DevStep::Publish => "Publish", - DevStep::Warehouse => "Warehouse", +/// The rows redrawn in place below everything printed for good. +pub(crate) fn live_rows(screen: &DevScreen, now: Instant) -> Vec { + if !screen.live { + return Vec::new(); } + let facts = &screen.facts; + if let Some(since) = screen.stopping { + let line: StepLine = StepLine { + state: PhaseState::Running { + frame: screen.frame, + }, + label: "Stopping sqb dev".to_owned(), + elapsed: Some(now.saturating_duration_since(since)), + detail: String::new(), + }; + return render_step_line(&line, facts, false); + } + let mut prompt: Vec = match &screen.prompt { + Some(prompt) => render_prompt( + &PromptBlock { + title: sign_in_title(&screen.adapter), + text: prompt.text.clone(), + waited: now.saturating_duration_since(prompt.since), + }, + facts, + ), + None => Vec::new(), + }; + let (mut running, waiting): (Vec, Vec) = if screen.ready { + (Vec::new(), Vec::new()) + } else { + let rows = |wanted: fn(PhaseState) -> bool| -> Vec { + screen + .steps + .iter() + .filter(|row| wanted(row.state)) + .flat_map(|row| render_step_line(&step_line(row, screen.frame, now), facts, false)) + .collect() + }; + ( + rows(|state| matches!(state, PhaseState::Running { .. })), + rows(|state| state == PhaseState::Pending), + ) + }; + let secrets: Vec = secrets_rows(screen); + let key: String = render_key_line(&hotkeys(screen), facts); + let budget: usize = facts.rows.saturating_sub(1).max(1); + let fixed: usize = secrets.len() + 1; + let room: usize = budget.saturating_sub(prompt.len() + running.len() + fixed); + let waiting: Vec = fit_waiting(waiting, room, facts); + let over: usize = (prompt.len() + running.len() + waiting.len() + fixed).saturating_sub(budget); + if over > 0 { + let keep: usize = budget.saturating_sub(prompt.len() + fixed).max(1); + running.truncate(keep); + let over: usize = (prompt.len() + running.len() + fixed).saturating_sub(budget); + prompt.drain(..over.min(prompt.len())); + } + let mut rows: Vec = prompt; + rows.extend(running); + rows.extend(waiting); + rows.extend(secrets); + rows.push(key); + let extra: usize = rows.len().saturating_sub(budget); + rows.drain(..extra); + rows } -/// How long ago `started` was, if it was. -pub(crate) fn elapsed_since(started: Option, now: Instant) -> Option { - started.map(|started| now.saturating_duration_since(started)) -} - -/// The rows redrawn in place: header and checklist, with the client's framed output under them. -pub(crate) fn live_rows(screen: &DevScreen, now: Instant) -> Vec { - if screen.ready { - return vec![String::new(), render_hotkey_bar(&hotkeys(), &screen.facts)]; +/// The waiting steps in `room` rows; when they do not fit, the first few and `· N more waiting`. +fn fit_waiting( + waiting: Vec, + room: usize, + facts: &sqlbuild_core::screen_text::models::ScreenFacts, +) -> Vec { + if waiting.len() <= room { + return waiting; } - let lines: Vec = screen - .steps - .iter() - .map(|row| phase_line(row, screen.frame, now)) - .collect(); - let mut rows: Vec = vec![ - render_dev_header(&screen.header, &screen.facts), - String::new(), - ]; - rows.extend(render_phase_lines( - &lines, - PhaseLayout::TimeLast, - &screen.facts, - )); - if screen.client_output { - let label: &str = if screen.adapter.is_empty() { - WAREHOUSE_FRAME_LABEL - } else { - &screen.adapter - }; - rows.push(String::new()); - rows.push(render_frame_rule(Some(label), &screen.facts)); + if room == 0 { + return Vec::new(); } + let shown: usize = room - 1; + let mut rows: Vec = waiting[..shown].to_vec(); + rows.push( + facts + .style + .muted(&format!("\u{b7} {} more waiting", waiting.len() - shown)), + ); rows } -/// One checklist row; a running row shows the current spinner frame and its live timer. -fn phase_line(row: &StepRow, frame: usize, now: Instant) -> PhaseLine { - PhaseLine { - state: match row.state { - PhaseState::Running { .. } => PhaseState::Running { frame }, - state => state, +/// One step as a live row: a running step shows the current spinner frame and its live timer. +pub(crate) fn step_line(row: &StepRow, frame: usize, now: Instant) -> StepLine { + let state: PhaseState = match row.state { + PhaseState::Running { .. } => PhaseState::Running { frame }, + state => state, + }; + StepLine { + state, + label: step_label(row.step, state).to_owned(), + elapsed: row.elapsed.or_else(|| match state { + PhaseState::Pending => None, + _ => elapsed_since(row.started, now), + }), + detail: if state == PhaseState::Pending && row.detail.is_empty() { + "waiting".to_owned() + } else { + row.detail.clone() }, - label: step_label(row.step).to_owned(), - detail: row.detail.clone(), - elapsed: row.elapsed.or_else(|| elapsed_since(row.started, now)), } } -/// The hotkey bar's keys. -pub(crate) fn hotkeys() -> Vec { - HOTKEYS - .iter() +/// `snowflake needs you to sign in`, or a general title before the adapter is known. +pub(crate) fn sign_in_title(adapter: &str) -> String { + if adapter.is_empty() { + return "the warehouse client is waiting for you".to_owned(); + } + format!("{adapter} needs you to sign in") +} + +/// The keys for where the session stands. +pub(crate) fn hotkeys(screen: &DevScreen) -> Vec { + let keys: Vec<(char, &str)> = if screen.ready { + READY_KEYS.to_vec() + } else { + STARTING_KEYS.to_vec() + }; + keys.into_iter() .map(|(key, label)| Hotkey { - key: *key, - label: (*label).to_owned(), + key, + label: label.to_owned(), }) .collect() } diff --git a/crates/sqlbuild-cli/src/dev_screen/_helpers/secrets.rs b/crates/sqlbuild-cli/src/dev_screen/_helpers/secrets.rs new file mode 100644 index 0000000000..64b169a5fd --- /dev/null +++ b/crates/sqlbuild-cli/src/dev_screen/_helpers/secrets.rs @@ -0,0 +1,57 @@ +//! The warning `sqb dev` shows while providers miss secrets: their variables and how to set them, until a health read shows none. + +use sqlbuild_core::screen_text::main::render_step_line::render_step_line; +use sqlbuild_core::screen_text::models::{PhaseState, StepLine}; +use sqlbuild_orchestration::dev_events::models::UnsetProviderSecrets; + +use crate::dev_screen::constants::{SECRETS_FIX, SECRETS_MISSING, SECRETS_SET}; +use crate::dev_screen::models::DevScreen; + +/// Each provider and the variables it misses, then how to set them; empty when none is missing. +pub(crate) fn secrets_rows(screen: &DevScreen) -> Vec { + if screen.missing_secrets.is_empty() { + return Vec::new(); + } + let providers: Vec = screen + .missing_secrets + .iter() + .map(|provider| format!("{} {}", provider.provider, provider.variables.join(", "))) + .collect(); + let line: StepLine = StepLine { + state: PhaseState::Warn, + label: SECRETS_MISSING.to_owned(), + elapsed: None, + detail: format!("{}; {SECRETS_FIX}", providers.join(" \u{b7} ")), + }; + render_step_line(&line, &screen.facts, true) +} + +/// Take the latest health read's providers missing secrets. A live screen redraws its warning row; a plain one prints the warning when it changes and a line when it clears. +pub(crate) fn secrets_reported( + mut screen: DevScreen, + providers: Vec, +) -> (DevScreen, Vec) { + if providers == screen.missing_secrets { + return (screen, Vec::new()); + } + let had_missing: bool = !screen.missing_secrets.is_empty(); + screen.missing_secrets = providers; + if screen.live { + return (screen, Vec::new()); + } + if !screen.missing_secrets.is_empty() { + let lines: Vec = secrets_rows(&screen); + return (screen, lines); + } + if !had_missing { + return (screen, Vec::new()); + } + let line: StepLine = StepLine { + state: PhaseState::Ok, + label: SECRETS_SET.to_owned(), + elapsed: None, + detail: "no provider is missing a secret".to_owned(), + }; + let lines: Vec = render_step_line(&line, &screen.facts, true); + (screen, lines) +} diff --git a/crates/sqlbuild-cli/src/dev_screen/_helpers/transitions.rs b/crates/sqlbuild-cli/src/dev_screen/_helpers/transitions.rs index 66debdf4f9..5dff7cb7e7 100644 --- a/crates/sqlbuild-cli/src/dev_screen/_helpers/transitions.rs +++ b/crates/sqlbuild-cli/src/dev_screen/_helpers/transitions.rs @@ -2,24 +2,31 @@ use std::time::{Duration, Instant}; -use sqlbuild_core::screen_text::main::format_plain_line::format_plain_line; -use sqlbuild_core::screen_text::main::redraw_rows::redraw_rows; -use sqlbuild_core::screen_text::main::render_frame_rule::render_frame_rule; +use sqlbuild_core::screen_text::main::render_event_line::render_event_line; use sqlbuild_core::screen_text::main::render_log_line::render_log_line; -use sqlbuild_core::screen_text::models::{EventMark, PhaseState, Segment, Tone, WarehouseState}; +use sqlbuild_core::screen_text::main::render_problem::render_problem; +use sqlbuild_core::screen_text::models::{ + EventLine, EventMark, PhaseState, Problem, ProblemLevel, Segment, StepLine, Tone, + WarehouseState, +}; use sqlbuild_orchestration::dev_events::models::{ DevEvent, DevPhase, DevStepState, SourcePosition, }; -use crate::dev_screen::_helpers::lines::{Report, report_lines}; -use crate::dev_screen::_helpers::rows::{elapsed_since, live_rows}; -use crate::dev_screen::constants::{FAILED_HINT, LOG_RING_LINES, SNAPSHOT_ID_CHARS}; -use crate::dev_screen::models::{DevScreen, DevStep, ScreenAction, StepRow}; +use crate::dev_screen::_helpers::labels::elapsed_since; +use crate::dev_screen::_helpers::lines::lasting_step; +use crate::dev_screen::_helpers::rows::step_line; +use crate::dev_screen::_helpers::secrets::secrets_reported; +use crate::dev_screen::constants::{LOG_RING_LINES, SIGN_IN_DETAIL, SNAPSHOT_ID_CHARS}; +use crate::dev_screen::models::{DevScreen, DevStep, Prompt, ScreenAction, StepRow}; /// The screen after a message, and the lines it prints for good. pub(crate) type Printed = (DevScreen, Vec); -/// A startup step began; discovery starts a new generation, so its later steps go back to pending. +/// The most client text a sign-in prompt keeps; older text drops off the front. +const PROMPT_TEXT_LIMIT: usize = 4_000; + +/// A step began; discovery starts a new generation, so its later steps go back to pending. pub(crate) fn step_started( mut screen: DevScreen, (step, detail): (DevStep, String), @@ -52,7 +59,7 @@ pub(crate) fn step_started( (screen, Vec::new()) } -/// A checklist row that has not started. +/// A step that has not started. pub(crate) fn pending(step: DevStep) -> StepRow { StepRow { step, @@ -63,57 +70,67 @@ pub(crate) fn pending(step: DevStep) -> StepRow { } } -/// The location is known; the plain screen names it and the target. -pub(crate) fn located(mut screen: DevScreen, location: String) -> Printed { - screen.location = location; - if screen.live { - return (screen, Vec::new()); - } - let line: String = format_plain_line( - &format!( - "location {} \u{b7} target {}", - screen.location, screen.header.target - ), - None, - ); - (screen, vec![line]) -} - -/// A startup step ended in `state`; the plain screen reports the control store and the compile. +/// A step ended in `state`: its line is printed for good, except publishing, which waits for the snapshot ID. pub(crate) fn step_finished( mut screen: DevScreen, (step, state): (DevStep, PhaseState), detail: String, now: Instant, ) -> Printed { - match step { - DevStep::Compile => screen.compile_detail.clone_from(&detail), - DevStep::Api => screen.ui_url = format!("http://{detail}"), - _ => {} - } + let detail: String = match step { + DevStep::Compile => { + screen.compile_detail.clone_from(&detail); + detail + } + DevStep::Api => { + screen.ui_url = format!("http://{detail}"); + screen.ui_url.clone() + } + _ => detail, + }; if screen.ready { return (screen, Vec::new()); } - let mut elapsed: Option = None; - for row in &mut screen.steps { - if row.step == step { - row.elapsed = Some(elapsed_since(row.started, now).unwrap_or_default()); - row.state = state; - row.detail.clone_from(&detail); - elapsed = row.elapsed; - } - } - if screen.live { + let Some(index) = screen.steps.iter().position(|row| row.step == step) else { return (screen, Vec::new()); - } - let lines: Vec = match step { - DevStep::ControlStore => vec![format_plain_line("control store ready", elapsed)], - DevStep::Compile => vec![format_plain_line( - &format!("discovered {}", screen.compile_detail), - elapsed_since(screen.generation_started, now), - )], - _ => Vec::new(), }; + let row: &mut StepRow = &mut screen.steps[index]; + row.elapsed = Some(elapsed_since(row.started, now).unwrap_or_default()); + row.state = state; + row.detail = detail; + if step == DevStep::Publish && screen.serving.is_none() { + return (screen, Vec::new()); + } + let line: StepLine = step_line(&screen.steps[index], 0, now); + let lines: Vec = lasting_step(&screen, &line); + (screen, lines) +} + +/// A step of `sqb dev` itself failed: its line, then the problem under it. +pub(crate) fn step_failed( + mut screen: DevScreen, + (step, detail, problem): (DevStep, String, Problem), + now: Instant, +) -> Printed { + let mut row: StepRow = screen + .steps + .iter() + .find(|row| row.step == step) + .cloned() + .unwrap_or_else(|| StepRow { + started: Some(now), + ..pending(step) + }); + row.state = PhaseState::Fail; + row.elapsed = Some(elapsed_since(row.started, now).unwrap_or_default()); + row.detail = detail; + let mut lines: Vec = lasting_step(&screen, &step_line(&row, 0, now)); + lines.extend(render_problem(&problem, &screen.facts)); + for kept in &mut screen.steps { + if kept.step == step { + kept.clone_from(&row); + } + } (screen, lines) } @@ -153,273 +170,335 @@ pub(crate) fn child_event( } let lines: Vec = titles .into_iter() - .flat_map(|title| changed_line(&screen, clock, title)) + .flat_map(|title| { + event_lines( + &screen, + event_line( + clock, + EventMark::Changed, + format!("{title} changed"), + String::new(), + ), + ) + }) .collect(); (screen, lines) } DevEvent::Restarted { reason } => { - let lines: Vec = report_lines( + let lines: Vec = event_lines( &screen, - Report { + event_line( clock, - mark: EventMark::Restarted, - title: "location restarted".to_owned(), - plain: format!("location restarted: {reason}"), - detail: reason, - elapsed: None, - notes: Vec::new(), - }, + EventMark::Restarted, + "location restarted".to_owned(), + reason, + ), ); (screen, lines) } - DevEvent::Published { - generation, - snapshot_id, - .. - } => published(screen, (generation, &snapshot_id), now, clock), + DevEvent::Published { snapshot_id, .. } => published(screen, &snapshot_id, now, clock), DevEvent::Failed { - generation, message, position, - } => failed( - screen, - (generation, &message, position.as_ref()), - now, - clock, - ), + code, + help, + .. + } => { + let problem: Problem = failure_problem( + &screen.project_root, + (&message, position.as_ref()), + (code, help), + ); + failed(screen, problem, now, clock) + } + DevEvent::MissingSecrets { providers } => secrets_reported(screen, providers), DevEvent::Warning { title, detail } => { - let lines: Vec = report_lines( - &screen, - Report { - clock, - mark: EventMark::Warning, - plain: format!("{title}: {detail}"), + let lines: Vec = render_problem( + &Problem { + level: ProblemLevel::Warning, title, - detail: String::new(), - elapsed: None, - notes: vec![vec![Segment { - text: detail, - tone: Tone::Muted, - link: None, - }]], + code: String::new(), + at: Vec::new(), + why: detail, + fix: String::new(), }, + &screen.facts, ); (screen, lines) } } } -fn changed_line(screen: &DevScreen, clock: &str, title: String) -> Vec { - report_lines( - screen, - Report { - clock, - mark: EventMark::Changed, - plain: format!("changed {title}"), - title, - detail: String::new(), - elapsed: None, - notes: Vec::new(), - }, - ) +/// An event line without elapsed time or notes. +fn event_line(clock: &str, mark: EventMark, title: String, detail: String) -> EventLine { + EventLine { + clock: clock.to_owned(), + mark, + title, + detail, + elapsed: None, + notes: Vec::new(), + } } -fn published( - mut screen: DevScreen, - (generation, snapshot_id): (i64, &str), - now: Instant, - clock: &str, -) -> Printed { +/// The event's rows, wrapped in full in both live and plain mode. +pub(crate) fn event_lines(screen: &DevScreen, line: EventLine) -> Vec { + render_event_line(&line, &screen.facts) +} + +fn published(mut screen: DevScreen, snapshot_id: &str, now: Instant, clock: &str) -> Printed { let short: String = snapshot_id.chars().take(SNAPSHOT_ID_CHARS).collect(); let elapsed: Option = elapsed_since(screen.generation_started.take(), now); let changes: usize = std::mem::take(&mut screen.pending_changes); - screen.serving = Some(generation); - let plain: String = format!("published gen {generation} {short}"); + screen.serving = Some(short.clone()); if !screen.ready { - let mut row_elapsed: Option = None; - for row in &mut screen.steps { - if row.step == DevStep::Publish { - row.detail = format!("gen {generation} \u{b7} {short}"); - row_elapsed = row.elapsed; - } - } - if screen.live { + let Some(index) = screen + .steps + .iter() + .position(|row| row.step == DevStep::Publish) + else { return (screen, Vec::new()); - } - return (screen, vec![format_plain_line(&plain, row_elapsed)]); + }; + let row: &mut StepRow = &mut screen.steps[index]; + row.state = PhaseState::Ok; + row.elapsed = row + .elapsed + .or_else(|| Some(elapsed_since(row.started, now).unwrap_or_default())); + row.detail = format!("snapshot {short}"); + let line: StepLine = step_line(&screen.steps[index], 0, now); + let lines: Vec = lasting_step(&screen, &line); + return (screen, lines); } let detail: String = match changes { 0 => String::new(), 1 => "1 file changed".to_owned(), count => format!("{count} files changed"), }; - let lines: Vec = report_lines( + let lines: Vec = event_lines( &screen, - Report { - clock, - mark: EventMark::Succeeded, - title: format!("gen {generation} published"), - detail, + EventLine { elapsed, - notes: Vec::new(), - plain, + ..event_line( + clock, + EventMark::Succeeded, + format!("published snapshot {short}"), + detail, + ) }, ); (screen, lines) } -fn failed( - mut screen: DevScreen, - (generation, message, position): (i64, &str, Option<&SourcePosition>), - now: Instant, - clock: &str, -) -> Printed { +/// The problem block for a failed generation: the file it points at, its code, the message and the fix. +pub(crate) fn failure_problem( + project_root: &str, + (message, position): (&str, Option<&SourcePosition>), + (code, help): (Option, Option), +) -> Problem { + let code: String = code.unwrap_or_default(); + let prefix: String = format!("[{code}] "); + let mut why: &str = message.strip_prefix(prefix.as_str()).unwrap_or(message); + if let Some(position) = position { + for place in [ + format!("{}:{}:{}:", position.path, position.line, position.column), + format!("{}:{}:", position.path, position.line), + ] { + why = why.strip_prefix(place.as_str()).unwrap_or(why); + } + } + let (title, at): (String, Vec) = match position { + Some(position) => ( + position.path.clone(), + vec![Segment { + text: format!("{}:{}:{}", position.path, position.line, position.column), + tone: Tone::Link, + link: Some(format!( + "file://{}/{}", + project_root.trim_end_matches('/'), + position.path + )), + }], + ), + None => ("project".to_owned(), Vec::new()), + }; + Problem { + level: ProblemLevel::Error, + title, + code, + at, + why: why.trim().to_owned(), + fix: help.unwrap_or_else(|| { + "fix it and save; sqb dev compiles again (r recompiles now)".to_owned() + }), + } +} + +/// A generation failed: before ready, the running steps fail and wait for a fix; after, one event line. The problem follows in full. +fn failed(mut screen: DevScreen, problem: Problem, now: Instant, clock: &str) -> Printed { screen.generation_started = None; screen.pending_changes = 0; - for row in &mut screen.steps { - if !screen.ready && matches!(row.state, PhaseState::Running { .. }) { + let mut lines: Vec = Vec::new(); + if screen.ready { + let title: String = match &screen.serving { + Some(serving) => format!("compile failed \u{b7} still serving snapshot {serving}"), + None => "compile failed".to_owned(), + }; + lines.extend(event_lines( + &screen, + event_line(clock, EventMark::Failed, title, String::new()), + )); + } else { + for index in 0..screen.steps.len() { + if !matches!(screen.steps[index].state, PhaseState::Running { .. }) + || screen.steps[index].step == DevStep::Warehouse + { + continue; + } + let mut row: StepRow = screen.steps[index].clone(); row.state = PhaseState::Fail; row.elapsed = elapsed_since(row.started, now); - row.detail = format!("gen {generation} failed"); + row.detail = "1 error".to_owned(); + lines.extend(lasting_step(&screen, &step_line(&row, 0, now))); + } + for row in &mut screen.steps { + if matches!( + row.step, + DevStep::Discover | DevStep::Compile | DevStep::Publish + ) { + *row = pending(row.step); + } + if row.step == DevStep::Discover { + row.detail = "waiting for a fix (r recompiles)".to_owned(); + } } } - let title: String = match screen.serving { - Some(serving) => format!("gen {generation} failed \u{b7} still serving gen {serving}"), - None => format!("gen {generation} failed"), - }; - let (place, mut first_note): (String, Vec) = match position { - Some(position) => position_note(&screen.project_root, position), - None => (String::new(), Vec::new()), - }; - first_note.push(Segment { - text: message.to_owned(), - tone: Tone::Plain, - link: None, - }); - let lines: Vec = report_lines( - &screen, - Report { - clock, - mark: EventMark::Failed, - plain: format!("{title}: {place}{message}"), - title, - detail: String::new(), - elapsed: None, - notes: vec![ - first_note, - vec![Segment { - text: FAILED_HINT.to_owned(), - tone: Tone::Muted, - link: None, - }], - ], - }, - ); + lines.extend(render_problem(&problem, &screen.facts)); (screen, lines) } -/// `path:line:col ` for the plain line, and the clickable position the live note starts with. -fn position_note(project_root: &str, position: &SourcePosition) -> (String, Vec) { - let place: String = format!("{}:{}:{}", position.path, position.line, position.column); - let note: Vec = vec![ - Segment { - text: place.clone(), - tone: Tone::Link, - link: Some(format!( - "file://{}/{}", - project_root.trim_end_matches('/'), - position.path - )), - }, - Segment { - text: " ".to_owned(), - tone: Tone::Plain, - link: None, - }, - ]; - (format!("{place} "), note) -} - -/// The foreground connection settled: close any framed client block and record the outcome. +/// The foreground connection settled: the prompt goes, and its step line or event line is printed. pub(crate) fn warehouse_settled( mut screen: DevScreen, (adapter, state): (String, WarehouseState), now: Instant, clock: &str, -) -> (DevScreen, String, Vec) { - let mut raw: String = String::new(); - if screen.client_output { - if screen.client_partial { - raw.push('\n'); - } - if screen.live { - raw.push_str(&render_frame_rule(None, &screen.facts)); - raw.push_str("\n\n"); - } - screen.client_output = false; - screen.client_partial = false; - screen.drawn = 0; +) -> Printed { + screen.prompt = None; + if !adapter.is_empty() { + screen.adapter.clone_from(&adapter); } - screen.adapter.clone_from(&adapter); screen.warehouse = Some(state.clone()); - let (row_state, detail, plain): (PhaseState, String, Option) = match &state { - WarehouseState::Connected { detail } => { - (PhaseState::Ok, format!("{adapter} \u{b7} {detail}"), None) - } - WarehouseState::NotConnected { reason } => ( - PhaseState::Warn, - format!("not connected \u{b7} {reason}"), - Some(format!("warehouse not connected: {reason}")), + let adapter: String = screen.adapter.clone(); + let (row_state, detail): (PhaseState, String) = match &state { + WarehouseState::Connected { facts } => ( + PhaseState::Ok, + [adapter.clone()] + .into_iter() + .chain( + facts + .iter() + .filter_map(|fact| fact.strip_prefix("auth ").map(str::to_owned)), + ) + .filter(|part| !part.is_empty()) + .collect::>() + .join(" \u{b7} "), ), - WarehouseState::Failed { message } => ( + WarehouseState::NotConnected { reason } => { + (PhaseState::Warn, format!("not connected \u{b7} {reason}")) + } + WarehouseState::Failed { .. } => ( PhaseState::Fail, - message.clone(), - Some(format!("warehouse connection failed: {message}")), + [adapter.as_str(), "failed"] + .into_iter() + .filter(|part| !part.is_empty()) + .collect::>() + .join(" \u{b7} "), ), }; - if !screen.ready { - let (screen, _) = step_finished(screen, (DevStep::Warehouse, row_state), detail, now); - let lines: Vec = match (screen.live, plain) { - (false, Some(plain)) => vec![format_plain_line(&plain, None)], - _ => Vec::new(), + let mut lines: Vec = Vec::new(); + if screen.ready { + let (mark, title): (EventMark, &str) = match row_state { + PhaseState::Ok => (EventMark::Succeeded, "warehouse connected"), + _ => (EventMark::Failed, "warehouse not connected"), }; - return (screen, raw, lines); + lines.extend(event_lines( + &screen, + event_line(clock, mark, title.to_owned(), detail), + )); + } else { + let printed: Printed = step_finished(screen, (DevStep::Warehouse, row_state), detail, now); + screen = printed.0; + lines.extend(printed.1); } - let (mark, title): (EventMark, &str) = match row_state { - PhaseState::Ok => (EventMark::Succeeded, "warehouse connected"), - _ => (EventMark::Failed, "warehouse not connected"), - }; - let lines: Vec = report_lines( - &screen, - Report { - clock, - mark, - title: title.to_owned(), - plain: plain.unwrap_or_else(|| format!("warehouse connected: {detail}")), - detail, - elapsed: None, - notes: Vec::new(), - }, - ); - (screen, raw, lines) + if let WarehouseState::Failed { message } = &state { + lines.extend(render_problem( + &Problem { + level: ProblemLevel::Error, + title: "warehouse connection".to_owned(), + code: adapter, + at: vec![Segment { + text: format!("target {}", screen.header.target), + tone: Tone::Plain, + link: None, + }], + why: message.clone(), + fix: "sqb debug shows the whole connection check; fix the target's connection \ + settings, then start sqb dev again" + .to_owned(), + }, + &screen.facts, + )); + } + (screen, lines) } -/// The client's own output, written as it came; the first chunk freezes the checklist above a rule. -pub(crate) fn client_text(mut screen: DevScreen, text: &str, now: Instant) -> (DevScreen, String) { - let mut output: String = String::new(); - if !screen.client_output { - screen.client_output = true; - if screen.live { - let rows: Vec = live_rows(&screen, now); - output.push_str(&redraw_rows(screen.drawn, &rows)); - screen.drawn = 0; +/// The client's own text: kept in the prompt block above the live steps until the connection settles. +pub(crate) fn client_text(mut screen: DevScreen, text: &str, now: Instant) -> DevScreen { + let prompt: &mut Prompt = screen.prompt.get_or_insert(Prompt { + text: String::new(), + since: now, + }); + prompt.text = typed(std::mem::take(&mut prompt.text), text); + if prompt.text.len() > PROMPT_TEXT_LIMIT { + let mut start: usize = prompt.text.len() - PROMPT_TEXT_LIMIT; + while !prompt.text.is_char_boundary(start) { + start += 1; } + prompt.text.drain(..start); } - if !text.is_empty() { - screen.client_partial = !text.ends_with('\n'); + for row in &mut screen.steps { + if row.step == DevStep::Warehouse && matches!(row.state, PhaseState::Running { .. }) { + row.detail = SIGN_IN_DETAIL.to_owned(); + } } - output.push_str(text); - (screen, output) + screen +} + +/// `buffer` with `text` appended as a terminal would show it: backspaces erase, escape sequences and carriage returns go. +fn typed(mut buffer: String, text: &str) -> String { + let mut characters = text.chars().peekable(); + while let Some(character) = characters.next() { + match character { + '\u{8}' | '\u{7f}' => { + if !buffer.ends_with('\n') { + buffer.pop(); + } + } + '\u{1b}' => { + if characters.peek() == Some(&'[') { + characters.next(); + for next in characters.by_ref() { + if next.is_ascii_alphabetic() { + break; + } + } + } + } + '\r' => {} + character => buffer.push(character), + } + } + buffer } /// A run started or finished. @@ -429,33 +508,16 @@ pub(crate) fn run_reported( finished: Option<(bool, Duration)>, clock: &str, ) -> Vec { - let (mark, plain, elapsed): (EventMark, String, Option) = match finished { - None => ( - EventMark::Started, - format!("run {name} started: {detail}"), - None, - ), - Some((true, elapsed)) => ( - EventMark::Succeeded, - format!("run {name} succeeded: {detail}"), - Some(elapsed), - ), - Some((false, elapsed)) => ( - EventMark::Failed, - format!("run {name} failed: {detail}"), - Some(elapsed), - ), + let (mark, elapsed): (EventMark, Option) = match finished { + None => (EventMark::Started, None), + Some((true, elapsed)) => (EventMark::Succeeded, Some(elapsed)), + Some((false, elapsed)) => (EventMark::Failed, Some(elapsed)), }; - report_lines( + event_lines( screen, - Report { - clock, - mark, - title: format!("run {name}"), - detail, + EventLine { elapsed, - notes: Vec::new(), - plain, + ..event_line(clock, mark, format!("run {name}"), detail) }, ) } @@ -465,8 +527,8 @@ pub(crate) fn logged(mut screen: DevScreen, line: String) -> Printed { if screen.log.len() == LOG_RING_LINES { screen.log.pop_front(); } - let shown: Vec = if screen.live && screen.show_log { - vec![render_log_line(&line, &screen.facts)] + let shown: Vec = if screen.show_log { + render_log_line(&line, &screen.facts) } else { Vec::new() }; @@ -479,14 +541,9 @@ pub(crate) fn key_pressed( mut screen: DevScreen, key: char, ) -> (DevScreen, Vec, ScreenAction) { - if !screen.live { - return (screen, Vec::new(), ScreenAction::None); - } let action: ScreenAction = match key { 'o' => ScreenAction::OpenUi, 'r' => ScreenAction::Recompile, - 's' => ScreenAction::RetryWarehouse, - 'q' => ScreenAction::Quit, _ => ScreenAction::None, }; if key != 'l' { @@ -497,10 +554,36 @@ pub(crate) fn key_pressed( screen .log .iter() - .map(|line| render_log_line(line, &screen.facts)) + .flat_map(|line| render_log_line(line, &screen.facts)) .collect() } else { Vec::new() }; (screen, shown, action) } + +/// The line a stop prints while it cancels a run, in the live view and plain output alike. +pub(crate) fn run_cancelling(screen: &DevScreen, label: String) -> Vec { + lasting_step( + screen, + &StepLine { + state: PhaseState::Pending, + label, + elapsed: None, + detail: String::new(), + }, + ) +} + +/// A service stopped: `· Stopped UI server 0.1s`. +pub(crate) fn service_stopped(screen: &DevScreen, label: String, elapsed: Duration) -> Vec { + lasting_step( + screen, + &StepLine { + state: PhaseState::Pending, + label, + elapsed: Some(elapsed), + detail: String::new(), + }, + ) +} diff --git a/crates/sqlbuild-cli/src/dev_screen/constants.rs b/crates/sqlbuild-cli/src/dev_screen/constants.rs index 408a61a69c..3514cd77ac 100644 --- a/crates/sqlbuild-cli/src/dev_screen/constants.rs +++ b/crates/sqlbuild-cli/src/dev_screen/constants.rs @@ -6,19 +6,18 @@ use crate::dev_screen::models::DevStep; /// Detailed log lines kept in memory for `l`; older lines drop off the front. pub(crate) const LOG_RING_LINES: usize = 500; -/// The keys the hotkey bar shows, in order. -pub(crate) const HOTKEYS: [(char, &str); 5] = [ +/// The keys before the services are ready. +pub(crate) const STARTING_KEYS: [(char, &str); 2] = [('l', "full log"), ('q', "quit")]; +/// The keys once they are. +pub(crate) const READY_KEYS: [(char, &str); 4] = [ ('o', "open UI"), + ('l', "full log"), ('r', "recompile"), - ('s', "retry warehouse"), - ('l', "logs"), ('q', "quit"), ]; -/// The note under a failed generation's event line. -pub(crate) const FAILED_HINT: &str = "r retry \u{b7} l full log"; /// The snapshot ID characters a published line shows. pub(crate) const SNAPSHOT_ID_CHARS: usize = 8; -/// The checklist's steps, in the order they are drawn. +/// The steps listed as pending until they start, in order; reading the configuration is never pending. pub(crate) const STEPS: [DevStep; 7] = [ DevStep::ControlStore, DevStep::Api, @@ -28,11 +27,27 @@ pub(crate) const STEPS: [DevStep; 7] = [ DevStep::Publish, DevStep::Warehouse, ]; -/// The framed sign-in block's label while the adapter is not yet known. -pub(crate) const WAREHOUSE_FRAME_LABEL: &str = "warehouse"; -/// How often the hotkey thread checks whether it may read stdin. -pub(crate) const KEY_POLL: Duration = Duration::from_millis(50); -/// How often the running step's spinner and timer redraw. +/// The warehouse step's detail while the client waits for the person. +pub(crate) const SIGN_IN_DETAIL: &str = "waiting for the sign-in above"; +/// How often the running steps' spinners and timers redraw. pub(crate) const TICK: Duration = Duration::from_millis(100); -/// Log lines printed when `sqb dev` stops on an error, so the cause stays on screen. +/// How long the key reader waits for a key before it checks whether to stop. +pub(crate) const KEY_WAIT: Duration = Duration::from_millis(100); +/// Log lines left on screen when `sqb dev` stops on an error the screen did not explain. pub(crate) const FAILURE_LOG_LINES: usize = 40; +/// Ctrl+C, read as a byte while the terminal is in raw mode. +pub(crate) const INTERRUPT_BYTE: u8 = 0x03; +/// Ctrl+\, read as a byte while the terminal is in raw mode: stop at once, without cancelling runs. +pub(crate) const FORCE_BYTE: u8 = 0x1c; +/// Ctrl+Z, read as a byte while the terminal is in raw mode; `sqb dev` does not suspend. +pub(crate) const SUSPEND_BYTE: u8 = 0x1a; +/// What the log says when Ctrl+Z is pressed. +pub(crate) const SUSPEND_UNSUPPORTED: &str = + "Ctrl+Z does not suspend sqb dev; press q to stop it, or Ctrl+C"; + +/// The warning row's label while providers miss secrets. +pub(crate) const SECRETS_MISSING: &str = "Secrets missing"; +/// What the warning row says to do about the missing secrets. +pub(crate) const SECRETS_FIX: &str = "set them in .env or the environment; press r to reload"; +/// The plain line once no provider misses a secret. +pub(crate) const SECRETS_SET: &str = "Secrets set"; diff --git a/crates/sqlbuild-cli/src/dev_screen/main/mod.rs b/crates/sqlbuild-cli/src/dev_screen/main/mod.rs index c96d41d3cd..067f49b196 100644 --- a/crates/sqlbuild-cli/src/dev_screen/main/mod.rs +++ b/crates/sqlbuild-cli/src/dev_screen/main/mod.rs @@ -1 +1,2 @@ pub(crate) mod start_dev_screen; +pub(crate) mod terminal_size; diff --git a/crates/sqlbuild-cli/src/dev_screen/main/start_dev_screen.rs b/crates/sqlbuild-cli/src/dev_screen/main/start_dev_screen.rs index 0be3b4b1f2..30b051ad80 100644 --- a/crates/sqlbuild-cli/src/dev_screen/main/start_dev_screen.rs +++ b/crates/sqlbuild-cli/src/dev_screen/main/start_dev_screen.rs @@ -1,7 +1,6 @@ //! Run the `sqb dev` screen as the only writer to the terminal. use std::fs::File; -use std::time::Instant; use tokio::sync::mpsc; use tokio::sync::oneshot; @@ -11,21 +10,22 @@ use crate::dev_screen::_helpers::drawing::draw_screen; use crate::dev_screen::_helpers::keys::KeyReader; use crate::dev_screen::_helpers::new_dev_screen::new_dev_screen; use crate::dev_screen::models::{ - DevScreen, DevScreenHandle, ScreenAction, ScreenMessage, ScreenSetup, + DevScreen, DevScreenHandle, ScreenAction, ScreenEnd, ScreenMessage, ScreenSetup, }; +use crate::dev_stop::main::stop_switch::stop_switch; -/// Draw `setup`'s screen from the messages sent to the handle; a live screen also reads hotkeys. +/// Draw `setup`'s screen from the messages sent to the handle; a live screen also reads keys. pub(crate) fn start_dev_screen(setup: ScreenSetup) -> DevScreenHandle { let live: bool = setup.live; let (messages, inbox) = mpsc::unbounded_channel::(); let (actions, asked) = mpsc::unbounded_channel::(); - let (finish, finished) = oneshot::channel::(); + let (finish, finished) = oneshot::channel::(); let keys: Option = if live { KeyReader::start(messages.clone()) } else { None }; - let gate = keys.as_ref().map(KeyReader::gate); + let input = keys.as_ref().map(KeyReader::input); let terminal: Option = match capture_stderr(messages.clone()) { Ok(terminal) => terminal, Err(error) => { @@ -35,7 +35,11 @@ pub(crate) fn start_dev_screen(setup: ScreenSetup) -> DevScreenHandle { None } }; - let screen: DevScreen = new_dev_screen(setup, Instant::now()); + stop_switch().save_output(match terminal.as_ref().map(File::try_clone) { + Some(Ok(copy)) => Some(copy), + Some(Err(_)) | None => None, + }); + let screen: DevScreen = new_dev_screen(setup); let task = tokio::spawn(draw_screen( screen, (inbox, actions), @@ -45,7 +49,7 @@ pub(crate) fn start_dev_screen(setup: ScreenSetup) -> DevScreenHandle { DevScreenHandle { messages, actions: asked, - keys: gate, + keys: input, finish, task, } diff --git a/crates/sqlbuild-cli/src/dev_screen/main/terminal_size.rs b/crates/sqlbuild-cli/src/dev_screen/main/terminal_size.rs new file mode 100644 index 0000000000..9b95f091f5 --- /dev/null +++ b/crates/sqlbuild-cli/src/dev_screen/main/terminal_size.rs @@ -0,0 +1,25 @@ +//! How big the terminal is. + +use std::fs::File; + +/// The width and height of `terminal`, or of stderr without one; `None` when it is not a terminal or the platform cannot tell. +pub(crate) fn terminal_size(terminal: Option<&File>) -> Option<(usize, usize)> { + #[cfg(unix)] + { + let size = match terminal { + Some(terminal) => rustix::termios::tcgetwinsize(terminal), + None => rustix::termios::tcgetwinsize(std::io::stderr()), + }; + match size { + Ok(size) if size.ws_col > 0 && size.ws_row > 0 => { + Some((usize::from(size.ws_col), usize::from(size.ws_row))) + } + Ok(_) | Err(_) => None, + } + } + #[cfg(not(unix))] + { + let _ = terminal; + None + } +} diff --git a/crates/sqlbuild-cli/src/dev_screen/models.rs b/crates/sqlbuild-cli/src/dev_screen/models.rs index 2ac0e72884..86519fb79c 100644 --- a/crates/sqlbuild-cli/src/dev_screen/models.rs +++ b/crates/sqlbuild-cli/src/dev_screen/models.rs @@ -1,20 +1,24 @@ //! The state of the `sqb dev` screen and the messages that change it. use std::collections::VecDeque; -use std::sync::Arc; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::fs::File; +use std::sync::Mutex; +use std::sync::atomic::AtomicBool; use std::time::{Duration, Instant}; use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender}; use tokio::sync::oneshot; use tokio::task::JoinHandle; -use sqlbuild_core::screen_text::models::{DevHeader, PhaseState, ScreenFacts, WarehouseState}; -use sqlbuild_orchestration::dev_events::models::DevEvent; +use sqlbuild_core::screen_text::models::{ + DevHeader, PhaseState, Problem, ResultLine, ScreenFacts, WarehouseState, +}; +use sqlbuild_orchestration::dev_events::models::{DevEvent, UnsetProviderSecrets}; -/// One startup step of the checklist, in the order it is drawn. +/// One start-up step, in the order pending steps are listed. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum DevStep { + Config, ControlStore, Api, Scheduler, @@ -24,10 +28,10 @@ pub(crate) enum DevStep { Warehouse, } -/// What the screen hears about: its own steps, the location child, the warehouse, logs and keys. +/// What the screen hears about: its own steps, the location child, the warehouse, logs, keys and the stop. #[derive(Clone, Debug)] pub(crate) enum ScreenMessage { - /// A step began; `detail` says what it waits on, such as `snowflake \u{b7} waiting for sign-in`. + /// A step began; `detail` says what it waits on. Started { step: DevStep, detail: String, @@ -36,8 +40,14 @@ pub(crate) enum ScreenMessage { step: DevStep, detail: String, }, + /// A step of `sqb dev` itself failed, with the problem to show under it. + Failed { + step: DevStep, + detail: String, + problem: Problem, + }, Child(DevEvent), - /// The development location's ID, known once the control store is open. + /// The development location's ID, known once the control store is open; plain output prints it with `ready`. Location(String), /// The dev target's triggers, such as `41 paused`, read after the first publication. Triggers(String), @@ -46,9 +56,9 @@ pub(crate) enum ScreenMessage { adapter: String, state: WarehouseState, }, - /// A line of the warehouse client's own output, drawn inside the framed block. + /// Text the warehouse client wrote while it connects, such as a sign-in prompt. ClientOutput(String), - /// A run started, or finished with `ok`; `detail` names its origin or node count. + /// A run started, or finished with `ok`; `detail` names its origin or outcome. Run { name: String, detail: String, @@ -57,8 +67,19 @@ pub(crate) enum ScreenMessage { /// A detailed log line, kept for `l`. Log(String), Key(char), - /// Redraw the running step's spinner and timer. + /// Redraw the running steps' spinners and timers. Tick, + /// The session is stopping; the live rows give way to one line per stopped service. + Stopping, + /// A stop is cancelling a run first, such as `Cancelling run orders_job… 2 queries (Ctrl+C again to force)`. + Cancelling { + label: String, + }, + /// A service stopped, such as `Stopped UI server`, after `elapsed`. + Stopped { + label: String, + elapsed: Duration, + }, } /// What the screen asks its owner to do after a key. @@ -67,8 +88,6 @@ pub(crate) enum ScreenAction { None, OpenUi, Recompile, - RetryWarehouse, - Quit, } /// The text one message writes and the action it asks for. @@ -78,7 +97,7 @@ pub(crate) struct ScreenOutput { pub(crate) action: ScreenAction, } -/// One checklist row: its state, detail and when it started. +/// One step: its state, detail and when it started. #[derive(Clone, Debug)] pub(crate) struct StepRow { pub(crate) step: DevStep, @@ -88,77 +107,79 @@ pub(crate) struct StepRow { pub(crate) elapsed: Option, } +/// The warehouse client's text while it waits for the person, and since when. +#[derive(Clone, Debug)] +pub(crate) struct Prompt { + pub(crate) text: String, + pub(crate) since: Instant, +} + /// What the screen knows before the first step starts. #[derive(Clone, Debug)] pub(crate) struct ScreenSetup { pub(crate) live: bool, pub(crate) facts: ScreenFacts, pub(crate) header: DevHeader, - pub(crate) watching: String, + /// The configured adapter, such as `snowflake`, for the sign-in prompt; empty when unknown. + pub(crate) adapter: String, pub(crate) project_root: String, + /// The env file row of the ready box, such as `.env · 3 variables · edit it, then press r to reload`. + pub(crate) env_file: Option, } -/// Everything the screen draws, and how many live rows sit below the last printed line. +/// Everything the screen draws, and the live rows it last drew below the printed lines. #[derive(Clone, Debug)] pub(crate) struct DevScreen { - /// Redraws in place with a spinner and hotkeys; otherwise plain stable lines. + /// Redraws in place with spinners and keys; otherwise appended lines only. pub(crate) live: bool, pub(crate) facts: ScreenFacts, pub(crate) header: DevHeader, + pub(crate) header_printed: bool, pub(crate) ui_url: String, - pub(crate) watching: String, + pub(crate) location: String, + /// The env file row of the ready box. + pub(crate) env_file: Option, + /// Providers the latest health read shows missing secrets; drawn as a warning row until a read shows none. + pub(crate) missing_secrets: Vec, pub(crate) triggers: String, - pub(crate) started: Instant, pub(crate) steps: Vec, pub(crate) ready: bool, - pub(crate) location: String, pub(crate) adapter: String, pub(crate) warehouse: Option, /// When the generation being compiled started, for its event line's time. pub(crate) generation_started: Option, /// Changed files since the last generation finished. pub(crate) pending_changes: usize, - /// The newest published generation, which keeps serving after a failure. - pub(crate) serving: Option, + /// The snapshot that serves, which keeps serving after a failure. + pub(crate) serving: Option, /// The last compile's summary, such as `412 python nodes, 2280 models`. pub(crate) compile_detail: String, /// The project directory, which error positions link into. pub(crate) project_root: String, - /// The warehouse client is writing inside the framed block; nothing is redrawn until it ends. - pub(crate) client_output: bool, - /// The client's last output ended mid-line, such as at a prompt. + pub(crate) prompt: Option, + /// Plain mode: the client's last text ended mid-line, such as at a prompt. pub(crate) client_partial: bool, - /// The ready card was printed and no line follows it yet; the first one is set apart by a blank row. - pub(crate) event_gap: bool, + pub(crate) stopping: Option, pub(crate) log: VecDeque, pub(crate) show_log: bool, pub(crate) frame: usize, - /// Rows drawn below the last permanent line, redrawn by the next message. - pub(crate) drawn: usize, + /// The live rows drawn below the last printed line, redrawn by the next message. + pub(crate) drawn: Vec, } -/// Who may read stdin: the hotkey thread, or a foreground child while the gate is closed. +/// Keys from the terminal: where they go while a foreground child reads them, and when to stop. #[derive(Debug, Default)] -pub(crate) struct KeyGate { - pub(crate) closed: AtomicBool, - /// Whether stdin is in raw mode and the thread reads it. - pub(crate) reading: AtomicBool, +pub(crate) struct KeyInput { + /// A sign-in prompt's pseudo-terminal; typed keys go there instead of to the screen. + pub(crate) forward: Mutex>, pub(crate) stop: AtomicBool, } -impl KeyGate { - /// Restore the terminal and stop reading keys; returns once the thread has let go of stdin. - pub(crate) async fn close(&self) { - self.closed.store(true, Ordering::SeqCst); - while self.reading.load(Ordering::SeqCst) { - tokio::time::sleep(crate::dev_screen::constants::KEY_POLL).await; - } - } - - /// Read keys again. - pub(crate) fn open(&self) { - self.closed.store(false, Ordering::SeqCst); - } +/// How the session ended: the result line, and whether to leave the newest log lines above it. +#[derive(Clone, Debug)] +pub(crate) struct ScreenEnd { + pub(crate) result: ResultLine, + pub(crate) show_log: bool, } /// A running screen: where to send messages, the actions its keys ask for, and how to stop it. @@ -166,8 +187,8 @@ impl KeyGate { pub(crate) struct DevScreenHandle { pub(crate) messages: UnboundedSender, pub(crate) actions: UnboundedReceiver, - /// Closed while a foreground child owns the terminal's input; `None` without hotkeys. - pub(crate) keys: Option>, - pub(crate) finish: oneshot::Sender, + /// The key reader's input; `None` without a terminal to read keys from. + pub(crate) keys: Option>, + pub(crate) finish: oneshot::Sender, pub(crate) task: JoinHandle<()>, } diff --git a/crates/sqlbuild-cli/src/dev_screen/tests.rs b/crates/sqlbuild-cli/src/dev_screen/tests.rs index 1797dac3e5..f7f1cd1d05 100644 --- a/crates/sqlbuild-cli/src/dev_screen/tests.rs +++ b/crates/sqlbuild-cli/src/dev_screen/tests.rs @@ -2,5 +2,7 @@ mod apply_screen_message; #[path = "tests/helpers.rs"] mod helpers; +#[path = "tests/test_missing_secrets.rs"] +mod missing_secrets; #[path = "tests/test_types.rs"] mod test_types; diff --git a/crates/sqlbuild-cli/src/dev_screen/tests/helpers.rs b/crates/sqlbuild-cli/src/dev_screen/tests/helpers.rs index 51666d2ebb..046fc5734c 100644 --- a/crates/sqlbuild-cli/src/dev_screen/tests/helpers.rs +++ b/crates/sqlbuild-cli/src/dev_screen/tests/helpers.rs @@ -1,43 +1,44 @@ -//! Screens at fixed widths, the messages of a session, and a terminal that replays the redraws. +//! Screens at fixed sizes, the messages of a session, and a terminal that replays the redraws into a viewport. use std::time::{Duration, Instant}; use sqlbuild_core::cli_text::models::CliStyle; -use sqlbuild_core::screen_text::models::{DevHeader, ScreenFacts, WarehouseState}; +use sqlbuild_core::screen_text::models::{ + DevHeader, Problem, ProblemLevel, ResultLine, ScreenFacts, WarehouseState, +}; +use sqlbuild_core::text::main::cell_len::cell_len; use sqlbuild_orchestration::dev_events::models::{ - DevEvent, DevPhase, DevStepState, SourcePosition, + DevEvent, DevPhase, DevStepState, SourcePosition, UnsetProviderSecrets, }; use crate::dev_screen::_helpers::apply_screen_message::apply_screen_message; +use crate::dev_screen::_helpers::drawing::closing_text; use crate::dev_screen::_helpers::new_dev_screen::new_dev_screen; -use crate::dev_screen::models::{DevScreen, DevStep, ScreenMessage, ScreenOutput, ScreenSetup}; -use crate::dev_screen::tests::test_types::Transcript; - -const LOCATION_ID: &str = "01a1d7ff-0b3a-7631-ba35-e44d44d072f2"; -const CLEAR_BELOW: &str = "\u{1b}[J"; -const CURSOR_UP: &str = "\u{1b}["; +use crate::dev_screen::models::{ + DevScreen, DevStep, ScreenAction, ScreenEnd, ScreenMessage, ScreenSetup, +}; +use crate::dev_screen::tests::test_types::{Terminal, Transcript}; -/// An uncoloured screen `columns` wide; `None` makes it plain. -pub(super) fn screen(columns: Option, start: Instant) -> DevScreen { - new_dev_screen( - ScreenSetup { - live: columns.is_some(), - facts: ScreenFacts { - columns: columns.unwrap_or(80), - style: CliStyle { use_color: false }, - links: false, - indent: 2, - }, - header: DevHeader { - version: "0.232.0".to_owned(), - project: "shop".to_owned(), - target: "dev".to_owned(), - }, - watching: "project/".to_owned(), - project_root: "/work/shop".to_owned(), +/// An uncoloured screen `size` big (columns, rows); `None` makes it plain. +pub(super) fn screen(size: Option<(usize, usize)>) -> DevScreen { + let (columns, rows): (usize, usize) = size.unwrap_or((80, 24)); + new_dev_screen(ScreenSetup { + live: size.is_some(), + facts: ScreenFacts { + columns, + rows, + style: CliStyle { use_color: false }, + links: false, }, - start, - ) + header: DevHeader { + version: "0.256.0".to_owned(), + project: "shop".to_owned(), + target: "dev".to_owned(), + }, + adapter: "snowflake".to_owned(), + project_root: "/home/analyst/projects/shop".to_owned(), + env_file: None, + }) } pub(super) fn step(phase: DevPhase, state: DevStepState, detail: Option<&str>) -> ScreenMessage { @@ -48,42 +49,48 @@ pub(super) fn step(phase: DevPhase, state: DevStepState, detail: Option<&str>) - }) } -/// Startup up to the first publication, each message 100 ms after the last. -pub(super) fn startup() -> Vec { +fn started(step: DevStep) -> ScreenMessage { + ScreenMessage::Started { + step, + detail: String::new(), + } +} + +fn finished(step: DevStep, detail: &str) -> ScreenMessage { + ScreenMessage::Finished { + step, + detail: detail.to_owned(), + } +} + +/// The front's own steps, then discovery running. +pub(super) fn discovering() -> Vec { vec![ - ScreenMessage::Started { - step: DevStep::ControlStore, - detail: String::new(), - }, - ScreenMessage::Finished { - step: DevStep::ControlStore, - detail: "sqlite \u{b7} /home/analyst/projects/shop/.sqlbuild/control.sqlite3" - .to_owned(), - }, - ScreenMessage::Location(LOCATION_ID.to_owned()), - ScreenMessage::Started { - step: DevStep::Api, - detail: String::new(), - }, - ScreenMessage::Finished { - step: DevStep::Api, - detail: "127.0.0.1:8000".to_owned(), - }, - ScreenMessage::Started { - step: DevStep::Scheduler, - detail: String::new(), - }, - ScreenMessage::Finished { - step: DevStep::Scheduler, - detail: "41 paused".to_owned(), - }, + started(DevStep::ControlStore), + finished(DevStep::ControlStore, "sqlite"), + started(DevStep::Api), + finished(DevStep::Api, "127.0.0.1:8640"), + started(DevStep::Scheduler), + finished(DevStep::Scheduler, "triggers start paused"), step(DevPhase::Discover, DevStepState::Started, None), - step(DevPhase::Discover, DevStepState::Finished, None), + ScreenMessage::Tick, + ] +} + +/// Start-up up to the first snapshot, then the warehouse connection running. +pub(super) fn connecting() -> Vec { + let mut messages: Vec = discovering(); + messages.extend([ + step( + DevPhase::Discover, + DevStepState::Finished, + Some("118 models \u{b7} 24 seeds \u{b7} 2 Python nodes"), + ), step(DevPhase::Compile, DevStepState::Started, None), step( DevPhase::Compile, DevStepState::Finished, - Some("412 python nodes, 2280 models"), + Some("0 errors \u{b7} 1 warning"), ), step(DevPhase::Publish, DevStepState::Started, None), step(DevPhase::Publish, DevStepState::Finished, None), @@ -95,175 +102,228 @@ pub(super) fn startup() -> Vec { ScreenMessage::Triggers("41 paused".to_owned()), ScreenMessage::Started { step: DevStep::Warehouse, - detail: "duckdb \u{b7} connecting".to_owned(), + detail: "connecting".to_owned(), }, - ] + ScreenMessage::Tick, + ]); + messages } -pub(super) fn connected() -> ScreenMessage { - ScreenMessage::Warehouse { - adapter: "duckdb".to_owned(), - state: WarehouseState::Connected { - detail: "main".to_owned(), - }, - } +/// Snowflake's OAuth sign-in prompt while the connection waits. +pub(super) fn signing_in() -> Vec { + let mut messages: Vec = connecting(); + messages.extend([ + ScreenMessage::ClientOutput( + "Go to https://xy12345.snowflakecomputing.com/oauth/authorize?client_id=SQLBUILD&state=8f3a21c0&redirect_uri=http%3A%2F%2Flocalhost%3A8001 to sign in\n" + .to_owned(), + ), + ScreenMessage::ClientOutput("Enter the URL the OAuth flow redirected you to: ".to_owned()), + ScreenMessage::ClientOutput("http://localhost:8001/?code=ab".to_owned()), + ScreenMessage::Tick, + ]); + messages } -pub(super) fn not_connected() -> ScreenMessage { - ScreenMessage::Warehouse { +/// Start-up through a connected warehouse: the ready box. +pub(super) fn ready() -> Vec { + let mut messages: Vec = signing_in(); + messages.push(ScreenMessage::Warehouse { adapter: "snowflake".to_owned(), - state: WarehouseState::NotConnected { - reason: "sign-in skipped".to_owned(), + state: WarehouseState::Connected { + facts: [ + "account xy12345", + "auth browser sign-in (OAuth)", + "role TRANSFORMER", + "warehouse TRANSFORM_XS", + ] + .map(str::to_owned) + .to_vec(), }, - } + }); + messages } -/// `messages` after startup. -pub(super) fn after_startup(messages: Vec) -> Vec { - startup().into_iter().chain(messages).collect() +/// Start-up through the ready box, then one health read per report of the providers missing secrets. +pub(super) fn secrets_reported(reports: Vec)>>) -> Vec { + let mut messages: Vec = ready(); + for report in reports { + messages.push(ScreenMessage::Child(DevEvent::MissingSecrets { + providers: report + .into_iter() + .map(|(provider, variables)| UnsetProviderSecrets { + provider: provider.to_owned(), + variables: variables.into_iter().map(str::to_owned).collect(), + }) + .collect(), + })); + } + messages } -/// Two edits after ready: one publishes, the next fails at a source position; then a sync stops. -pub(super) fn edits() -> Vec { - vec![ - ScreenMessage::Child(DevEvent::Changed { - paths: vec!["models/orders/int_orders.sql".to_owned()], - more: 0, - }), - step(DevPhase::Discover, DevStepState::Started, None), - ScreenMessage::Child(DevEvent::Published { - generation: 2, - snapshot_id: "c01d2e3f4a".to_owned(), - record: serde_json::Value::Null, - }), - ScreenMessage::Child(DevEvent::Changed { - paths: vec!["models/finance/fct_revenue.sql".to_owned()], - more: 2, - }), - step(DevPhase::Discover, DevStepState::Started, None), - ScreenMessage::Child(DevEvent::Failed { - generation: 3, - message: "unknown column net_amount_usd".to_owned(), - position: Some(SourcePosition { - path: "models/finance/fct_revenue.sql".to_owned(), - line: 42, - column: 7, - }), - }), - ScreenMessage::Child(DevEvent::Warning { - title: "warehouse sync stopped".to_owned(), - detail: "5 failed reads in a row: ProgrammingError: insufficient privileges".to_owned(), +/// Discovery fails with a long error that names its file, code and fix. +pub(super) fn failed_compile() -> Vec { + let mut messages: Vec = discovering(); + messages.push(ScreenMessage::Child(DevEvent::Failed { + generation: 1, + message: + "[D001] models/marts/fct_orders.sql:42:7: column net_amount_usd does not exist in \ + stg_payments; the column was renamed to amount_usd_net when the payments source \ + moved to the v2 export, and fct_orders still selects the old name" + .to_owned(), + position: Some(SourcePosition { + path: "models/marts/fct_orders.sql".to_owned(), + line: 42, + column: 7, }), - ] + code: Some("D001".to_owned()), + help: Some("select amount_usd_net instead, or alias it as net_amount_usd".to_owned()), + })); + messages.push(ScreenMessage::Tick); + messages } -/// A Snowflake-style sign-in prompt, ticks while it waits, a log line, then the connection. -pub(super) fn framed_sign_in() -> Vec { - vec![ - ScreenMessage::ClientOutput( - "Initiating login request with your identity provider...\n".to_owned(), - ), - ScreenMessage::Tick, - ScreenMessage::ClientOutput("Enter the URL the OAuth flow redirected you to: ".to_owned()), +/// The configuration names a key that was removed, before anything else starts. +pub(super) fn removed_key() -> Vec { + vec![ScreenMessage::Failed { + step: DevStep::Config, + detail: "1 error".to_owned(), + problem: Problem { + level: ProblemLevel::Error, + title: "sqlbuild_project.toml".to_owned(), + code: "D001".to_owned(), + at: Vec::new(), + why: "[dbt] option(s) were removed: defer_clone_from; use dbt-native --state/--defer" + .to_owned(), + fix: "remove defer_clone_from from [dbt]".to_owned(), + }, + }] +} + +/// Ctrl+C once ready: the services stop one by one. +pub(super) fn interrupted() -> Vec { + let mut messages: Vec = ready(); + messages.extend([ + ScreenMessage::Stopping, ScreenMessage::Tick, - ScreenMessage::Log("connection check started".to_owned()), - connected(), - ] + ScreenMessage::Stopped { + label: "Stopped code location".to_owned(), + elapsed: Duration::from_millis(300), + }, + ScreenMessage::Stopped { + label: "Stopped scheduler".to_owned(), + elapsed: Duration::from_millis(400), + }, + ScreenMessage::Stopped { + label: "Stopped UI server".to_owned(), + elapsed: Duration::from_millis(500), + }, + ]); + messages } -/// The ready card with `warehouse` on its warehouse row. -pub(super) fn card(warehouse: &str, ready_in: &str) -> Vec { - vec![ - format!(" sqlbuild dev v0.232.0 ready in {ready_in}"), - String::new(), - " \u{279c} UI http://127.0.0.1:8000".to_owned(), - " \u{279c} Location dev \u{b7} gen 1 \u{b7} 412 python nodes, 2280 models".to_owned(), - format!(" \u{279c} Warehouse {warehouse}"), - " \u{279c} Triggers 41 paused".to_owned(), - " \u{279c} Watching project/".to_owned(), - ] +/// The result line Ctrl+C leaves. +pub(super) fn interrupted_end() -> ScreenEnd { + ScreenEnd { + result: ResultLine { + failed: false, + title: "sqb dev stopped (interrupted)".to_owned(), + detail: "ran 42m 10s".to_owned(), + elapsed: Some(Duration::from_millis(1_100)), + next: Vec::new(), + }, + show_log: false, + } } -/// The startup checklist, its detail column `width` wide. -pub(super) fn checklist(control_store: &str, width: usize) -> Vec { - let row = |glyph: &str, label: &str, detail: &str, time: &str| -> String { - format!(" {glyph} {label:<20} {detail:8}") - }; - vec![ - " sqlbuild dev v0.232.0 \u{b7} shop \u{b7} target dev".to_owned(), - String::new(), - row("\u{2713}", "Control store", control_store, "0.1s"), - row("\u{2713}", "API", "127.0.0.1:8000", "0.1s"), - row("\u{2713}", "Scheduler", "41 paused", "0.1s"), - row("\u{2713}", "Discover project", "", "0.1s"), - row( - "\u{2713}", - "Compile snapshot", - "412 python nodes, 2280 models", - "0.1s", - ), - row("\u{2713}", "Publish", "gen 1 \u{b7} b429729b", "0.1s"), - row("\u{280b}", "Warehouse", "duckdb \u{b7} connecting", "0.0s"), - ] +/// The result line a configuration error leaves. +pub(super) fn not_started_end() -> ScreenEnd { + ScreenEnd { + result: ResultLine { + failed: true, + title: "sqb dev did not start".to_owned(), + detail: "configuration error in sqlbuild_project.toml".to_owned(), + elapsed: Some(Duration::from_millis(100)), + next: vec![( + "sqb debug".to_owned(), + "check the configuration on its own".to_owned(), + )], + }, + show_log: false, + } } -/// Lines in order, each followed by a newline. -pub(super) fn lines_of, S: Into>(lines: I) -> Vec { - lines.into_iter().map(Into::into).collect() +/// Nothing: the session is still running. +pub(super) fn still_running(_screen: DevScreen) -> String { + String::new() } -/// Apply `messages` 100 ms apart at clock `09:41:`, then replay what they wrote. -pub(super) fn play(columns: Option, messages: Vec) -> Transcript { - let start: Instant = Instant::now(); - let (_, outputs): (DevScreen, Vec) = messages.into_iter().enumerate().fold( - (screen(columns, start), Vec::new()), - |(screen, mut outputs), (index, message)| { - let now: Instant = start + Duration::from_millis(100 * (index as u64 + 1)); - let (screen, output) = - apply_screen_message(screen, message, now, &format!("09:41:{:02}", index % 60)); - outputs.push(output); - (screen, outputs) - }, - ); - Transcript { - rows: replay(outputs.iter().map(|output| output.text.as_str())), - actions: outputs.iter().map(|output| output.action).collect(), - } +/// The closing text Ctrl+C leaves. +pub(super) fn close_interrupted(screen: DevScreen) -> String { + closing_text(screen, Some(&interrupted_end())) } -/// The rows a terminal shows after `writes`; `ESC[nF ESC[J` erases the last `n` rows. -fn replay<'a>(writes: impl Iterator) -> Vec { - let text: String = writes - .flat_map(|write| write.split_inclusive(CLEAR_BELOW)) - .fold(String::new(), |shown, piece| { - let clears: bool = piece.ends_with(CLEAR_BELOW); - let piece: &str = piece.trim_end_matches(CLEAR_BELOW); - let (printed, up): (&str, usize) = piece - .rsplit_once(CURSOR_UP) - .filter(|_| clears) - .map_or((piece, 0), |(printed, rows)| { - (printed, rows.trim_end_matches('F').parse().unwrap_or(0)) - }); - let shown: String = shown + printed; - let keep: usize = shown.split_inclusive('\n').count().saturating_sub(up); - shown.split_inclusive('\n').take(keep).collect() - }); - text.split_inclusive('\n') - .map(|row| row.trim_end_matches('\n').to_owned()) - .collect() +/// The closing text a configuration error leaves. +pub(super) fn close_not_started(screen: DevScreen) -> String { + closing_text(screen, Some(¬_started_end())) } -/// `count` log lines from `log line `, as the open log shows them. -pub(super) fn log_rows(first: usize, count: usize) -> Vec { - (first..first + count) - .map(|index| format!(" log line {index}")) - .collect() +/// Apply `messages` 100 ms apart at `size`, then write what `close` leaves; what the terminal shows and keeps. +pub(super) fn play( + size: Option<(usize, usize)>, + messages: Vec, + close: fn(DevScreen) -> String, +) -> Transcript { + let start: Instant = Instant::now(); + let mut screen: DevScreen = screen(size); + let mut terminal: Terminal = Terminal::new(size.map_or(usize::MAX, |(_, rows)| rows)); + let mut actions: Vec = Vec::new(); + for (index, message) in messages.into_iter().enumerate() { + let now: Instant = start + Duration::from_millis(100 * (index as u64 + 1)); + let output; + (screen, output) = apply_screen_message(screen, message, now, "14:20:31"); + terminal.write(&output.text); + actions.push(output.action); + } + terminal.write(&close(screen)); + Transcript { + viewport: terminal.viewport(), + scrollback: terminal.lines(), + actions, + } } -/// Every row that is a log line. -pub(super) fn shown_log(rows: &[String]) -> Vec { - rows.iter() - .filter(|row| row.starts_with(" log line ")) - .cloned() +/// What is wrong with every session's layout at `size`: a header printed other than once, more rows than the terminal, or a row as wide as it. +pub(super) fn layout_problems((columns, rows): (usize, usize)) -> Vec { + let sessions: [Vec; 5] = [ + connecting(), + failed_compile(), + signing_in(), + ready(), + interrupted(), + ]; + sessions + .into_iter() + .flat_map(|messages| { + let transcript: Transcript = play(Some((columns, rows)), messages, close_interrupted); + let headers: usize = transcript + .scrollback + .iter() + .filter(|line| line.starts_with("sqb dev shop")) + .count(); + let wide = transcript + .scrollback + .iter() + .filter(|line| cell_len(line) >= columns) + .map(|line| format!("{columns}x{rows}: too wide: {line}")); + [ + (headers != 1).then(|| format!("{columns}x{rows}: header printed {headers} times")), + (transcript.viewport.len() > rows) + .then(|| format!("{columns}x{rows}: {} rows shown", transcript.viewport.len())), + ] + .into_iter() + .flatten() + .chain(wide) + .collect::>() + }) .collect() } diff --git a/crates/sqlbuild-cli/src/dev_screen/tests/test_apply_screen_message.rs b/crates/sqlbuild-cli/src/dev_screen/tests/test_apply_screen_message.rs index e7fe423e19..299c427753 100644 --- a/crates/sqlbuild-cli/src/dev_screen/tests/test_apply_screen_message.rs +++ b/crates/sqlbuild-cli/src/dev_screen/tests/test_apply_screen_message.rs @@ -1,151 +1,250 @@ -//! The `sqb dev` screen: checklist, framed sign-in, ready card, event lines, plain mode and keys. - -use sqlbuild_core::text::main::cell_len::cell_len; - -use crate::dev_screen::constants::LOG_RING_LINES; -use crate::dev_screen::models::{ScreenAction, ScreenMessage}; +use crate::dev_screen::models::ScreenAction; use crate::dev_screen::tests::helpers::{ - after_startup, card, checklist, connected, edits, framed_sign_in, lines_of, log_rows, - not_connected, play, shown_log, startup, + close_interrupted, close_not_started, connecting, failed_compile, interrupted, layout_problems, + play, ready, removed_key, signing_in, still_running, }; -use crate::dev_screen::tests::test_types::{KeyTestCase, ScreenTestCase}; +use crate::dev_screen::tests::test_types::{KeyTestCase, LayoutTestCase, ScreenTestCase}; -const HOTKEY_BAR: &str = - " o open UI \u{b7} r recompile \u{b7} s retry warehouse \u{b7} l logs \u{b7} q quit"; +const SHORT: Option<(usize, usize)> = Some((80, 10)); +const TALL: Option<(usize, usize)> = Some((80, 24)); #[test] -fn given_a_session_when_each_message_is_applied_then_the_terminal_shows_stable_uncut_rows() { - let edited: Vec = [ - card("\u{25cf} duckdb \u{b7} main", "1.7s"), - lines_of([ - "", - " 09:41:17 ~ models/orders/int_orders.sql", - " 09:41:19 \u{2713} gen 2 published 1 file changed 0.1s", - " 09:41:20 ~ models/finance/fct_revenue.sql", - " 09:41:20 ~ 2 more files", - " 09:41:22 \u{2717} gen 3 failed \u{b7} still serving gen 2", - " models/finance/fct_revenue.sql:42:7 unknown column net_amount_usd", - " r retry \u{b7} l full log", - " 09:41:23 \u{26a0} warehouse sync stopped", - " 5 failed reads in a row: ProgrammingError: insufficient privileges", - "", - HOTKEY_BAR, - ]), - ] - .concat(); - let rule: String = "\u{2500}".repeat(78); +fn given_a_session_when_drawn_then_the_viewport_matches_the_snapshot() { let test_cases = [ ScreenTestCase { - description: "starting at 80 columns cuts the long control store path with an ellipsis", - columns: Some(80), - messages: startup(), - expected_rows: checklist( - "sqlite \u{b7} /home/analyst/projects/shop/.sqlbuil\u{2026}", - 46, - ), + description: "start-up at 80x24", + size: TALL, + messages: connecting(), + close: still_running, + expected_viewport: vec![ + "sqb dev shop \u{b7} target dev \u{b7} sqb 0.256.0", + "\u{2713} Opened control store 0.1s sqlite", + "\u{2713} Started UI server 0.1s http://127.0.0.1:8640", + "\u{2713} Started scheduler 0.1s triggers start paused", + "\u{2713} Discovered project 0.2s 118 models \u{b7} 24 seeds \u{b7} 2 Python nodes", + "\u{2713} Compiled project 0.1s 0 errors \u{b7} 1 warning", + "\u{2713} Published snapshot 0.1s snapshot b429729b", + "\u{2839} Connecting warehouse 0.1s connecting", + "keys l full log \u{b7} q quit", + ], }, ScreenTestCase { - description: "starting at 120 columns shows the whole path", - columns: Some(120), - messages: startup(), - expected_rows: checklist( - "sqlite \u{b7} /home/analyst/projects/shop/.sqlbuild/control.sqlite3", - 62, - ), + description: "start-up at 80x10", + size: SHORT, + messages: connecting(), + close: still_running, + expected_viewport: vec![ + "sqb dev shop \u{b7} target dev \u{b7} sqb 0.256.0", + "\u{2713} Opened control store 0.1s sqlite", + "\u{2713} Started UI server 0.1s http://127.0.0.1:8640", + "\u{2713} Started scheduler 0.1s triggers start paused", + "\u{2713} Discovered project 0.2s 118 models \u{b7} 24 seeds \u{b7} 2 Python nodes", + "\u{2713} Compiled project 0.1s 0 errors \u{b7} 1 warning", + "\u{2713} Published snapshot 0.1s snapshot b429729b", + "\u{2839} Connecting warehouse 0.1s connecting", + "keys l full log \u{b7} q quit", + ], }, ScreenTestCase { - description: "at 80 columns the checklist collapses into the card and events print above the hotkeys", - columns: Some(80), - messages: after_startup([vec![connected()], edits()].concat()), - expected_rows: edited.clone(), + description: "a failed step with a long error at 80x24", + size: TALL, + messages: failed_compile(), + close: still_running, + expected_viewport: vec![ + "sqb dev shop \u{b7} target dev \u{b7} sqb 0.256.0", + "\u{2713} Opened control store 0.1s sqlite", + "\u{2713} Started UI server 0.1s http://127.0.0.1:8640", + "\u{2713} Started scheduler 0.1s triggers start paused", + "\u{2717} Discovering project 0.2s 1 error", + "\u{2717} error models/marts/fct_orders.sql D001", + " at models/marts/fct_orders.sql:42:7", + " why column net_amount_usd does not exist in stg_payments; the column was", + " renamed to amount_usd_net when the payments source moved to the v2", + " export, and fct_orders still selects the old name", + " fix select amount_usd_net instead, or alias it as net_amount_usd", + "\u{b7} Discover project waiting for a fix (r recompiles)", + "\u{b7} Compile project waiting", + "\u{b7} Publish snapshot waiting", + "\u{b7} Connect warehouse waiting", + "keys l full log \u{b7} q quit", + ], }, ScreenTestCase { - description: "at 120 columns event lines keep their columns", - columns: Some(120), - messages: after_startup([vec![connected()], edits()].concat()), - expected_rows: edited, + description: "a failed step with a long error at 80x10", + size: SHORT, + messages: failed_compile(), + close: still_running, + expected_viewport: vec![ + " why column net_amount_usd does not exist in stg_payments; the column was", + " renamed to amount_usd_net when the payments source moved to the v2", + " export, and fct_orders still selects the old name", + " fix select amount_usd_net instead, or alias it as net_amount_usd", + "\u{b7} Discover project waiting for a fix (r recompiles)", + "\u{b7} Compile project waiting", + "\u{b7} Publish snapshot waiting", + "\u{b7} Connect warehouse waiting", + "keys l full log \u{b7} q quit", + ], }, ScreenTestCase { - description: "an unavailable warehouse says not connected and how to retry", - columns: Some(80), - messages: after_startup(vec![not_connected()]), - expected_rows: [ - card( - "\u{25cb} not connected \u{b7} sign-in skipped \u{b7} press s to retry", - "1.7s", - ), - lines_of(["", HOTKEY_BAR]), - ] - .concat(), + description: "the sign-in prompt at 80x24", + size: TALL, + messages: signing_in(), + close: still_running, + expected_viewport: vec![ + "sqb dev shop \u{b7} target dev \u{b7} sqb 0.256.0", + "\u{2713} Opened control store 0.1s sqlite", + "\u{2713} Started UI server 0.1s http://127.0.0.1:8640", + "\u{2713} Started scheduler 0.1s triggers start paused", + "\u{2713} Discovered project 0.2s 118 models \u{b7} 24 seeds \u{b7} 2 Python nodes", + "\u{2713} Compiled project 0.1s 0 errors \u{b7} 1 warning", + "\u{2713} Published snapshot 0.1s snapshot b429729b", + "\u{25cc} sign in snowflake needs you to sign in", + " Go to https://xy12345.snowflakecomputing.com/oauth/authorize?client_id=SQLBUI", + " LD&state=8f3a21c0&redirect_uri=http%3A%2F%2Flocalhost%3A8001 to sign in", + " Enter the URL the OAuth flow redirected you to: http://localhost:8001/?code=a", + " b", + " wait 0:00 \u{b7} Ctrl+C cancels and stops sqb dev", + "\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}", + "\u{2838} Connecting warehouse 0.5s waiting for the sign-in above", + "keys l full log \u{b7} q quit", + ], }, ScreenTestCase { - description: "a client prompting for sign-in is framed verbatim and ticks never redraw over it", - columns: Some(80), - messages: after_startup(framed_sign_in()), - expected_rows: [ - checklist( - "sqlite \u{b7} /home/analyst/projects/shop/.sqlbuil\u{2026}", - 46, - )[..8] - .to_vec(), - lines_of([ - " \u{280b} Warehouse duckdb \u{b7} connecting 0.1s", - "", - ]), - vec![format!( - " \u{2500}\u{2500} warehouse {}", - "\u{2500}".repeat(65) - )], - lines_of([ - "Initiating login request with your identity provider...", - "Enter the URL the OAuth flow redirected you to: ", - ]), - vec![format!(" {rule}"), String::new()], - card("\u{25cf} duckdb \u{b7} main", "2.2s"), - lines_of(["", HOTKEY_BAR]), - ] - .concat(), + description: "the sign-in prompt at 80x10", + size: SHORT, + messages: signing_in(), + close: still_running, + expected_viewport: vec![ + "\u{25cc} sign in snowflake needs you to sign in", + " Go to https://xy12345.snowflakecomputing.com/oauth/authorize?client_id=SQLBUI", + " LD&state=8f3a21c0&redirect_uri=http%3A%2F%2Flocalhost%3A8001 to sign in", + " Enter the URL the OAuth flow redirected you to: http://localhost:8001/?code=a", + " b", + " wait 0:00 \u{b7} Ctrl+C cancels and stops sqb dev", + "\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}", + "\u{2838} Connecting warehouse 0.5s waiting for the sign-in above", + "keys l full log \u{b7} q quit", + ], }, ScreenTestCase { - description: "plain output is stable unstyled lines that ignore ticks and keys", - columns: None, - messages: after_startup( - [ - vec![ScreenMessage::Tick, ScreenMessage::Key('q'), not_connected()], - edits(), - ] - .concat(), - ), - expected_rows: lines_of([ - "sqlbuild dev: control store ready (0.1s)", - "sqlbuild dev: location 01a1d7ff-0b3a-7631-ba35-e44d44d072f2 \u{b7} target dev", - "sqlbuild dev: discovered 412 python nodes, 2280 models (0.3s)", - "sqlbuild dev: published gen 1 b429729b (0.1s)", - "sqlbuild dev: warehouse not connected: sign-in skipped", - "sqlbuild dev: ready http://127.0.0.1:8000", - "sqlbuild dev: changed models/orders/int_orders.sql", - "sqlbuild dev: published gen 2 c01d2e3f (0.1s)", - "sqlbuild dev: changed models/finance/fct_revenue.sql", - "sqlbuild dev: changed 2 more files", - "sqlbuild dev: gen 3 failed \u{b7} still serving gen 2: models/finance/fct_revenue.sql:42:7 unknown column net_amount_usd", - "sqlbuild dev: warehouse sync stopped: 5 failed reads in a row: ProgrammingError: insufficient privileges", - ]), + description: "ready at 80x24", + size: TALL, + messages: ready(), + close: still_running, + expected_viewport: vec![ + "sqb dev shop \u{b7} target dev \u{b7} sqb 0.256.0", + "\u{2713} Opened control store 0.1s sqlite", + "\u{2713} Started UI server 0.1s http://127.0.0.1:8640", + "\u{2713} Started scheduler 0.1s triggers start paused", + "\u{2713} Discovered project 0.2s 118 models \u{b7} 24 seeds \u{b7} 2 Python nodes", + "\u{2713} Compiled project 0.1s 0 errors \u{b7} 1 warning", + "\u{2713} Published snapshot 0.1s snapshot b429729b", + "\u{2713} Connected warehouse 0.6s snowflake \u{b7} browser sign-in (OAuth)", + "\u{256d}\u{2500} ready \u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{256e}", + "\u{2502} UI http://127.0.0.1:8640 \u{2502}", + "\u{2502} Project shop \u{b7} /home/analyst/projects/shop \u{b7} target dev \u{2502}", + "\u{2502} Warehouse snowflake \u{b7} account xy12345 \u{b7} auth browser sign-in (OAuth) \u{2502}", + "\u{2502} role TRANSFORMER \u{b7} warehouse TRANSFORM_XS \u{2502}", + "\u{2502} Triggers 41 paused \u{2502}", + "\u{2570}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{256f}", + "keys o open UI \u{b7} l full log \u{b7} r recompile \u{b7} q quit", + ], + }, + ScreenTestCase { + description: "Ctrl+C at 80x24", + size: TALL, + messages: interrupted(), + close: close_interrupted, + expected_viewport: vec![ + "sqb dev shop \u{b7} target dev \u{b7} sqb 0.256.0", + "\u{2713} Opened control store 0.1s sqlite", + "\u{2713} Started UI server 0.1s http://127.0.0.1:8640", + "\u{2713} Started scheduler 0.1s triggers start paused", + "\u{2713} Discovered project 0.2s 118 models \u{b7} 24 seeds \u{b7} 2 Python nodes", + "\u{2713} Compiled project 0.1s 0 errors \u{b7} 1 warning", + "\u{2713} Published snapshot 0.1s snapshot b429729b", + "\u{2713} Connected warehouse 0.6s snowflake \u{b7} browser sign-in (OAuth)", + "\u{256d}\u{2500} ready \u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{256e}", + "\u{2502} UI http://127.0.0.1:8640 \u{2502}", + "\u{2502} Project shop \u{b7} /home/analyst/projects/shop \u{b7} target dev \u{2502}", + "\u{2502} Warehouse snowflake \u{b7} account xy12345 \u{b7} auth browser sign-in (OAuth) \u{2502}", + "\u{2502} role TRANSFORMER \u{b7} warehouse TRANSFORM_XS \u{2502}", + "\u{2502} Triggers 41 paused \u{2502}", + "\u{2570}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{256f}", + "\u{b7} Stopped code location 0.3s", + "\u{b7} Stopped scheduler 0.4s", + "\u{b7} Stopped UI server 0.5s", + "\u{b7} sqb dev stopped (interrupted) ran 42m 10s 1.1s", + ], + }, + ScreenTestCase { + description: "Ctrl+C at 80x10", + size: SHORT, + messages: interrupted(), + close: close_interrupted, + expected_viewport: vec![ + "\u{2502} Project shop \u{b7} /home/analyst/projects/shop \u{b7} target dev \u{2502}", + "\u{2502} Warehouse snowflake \u{b7} account xy12345 \u{b7} auth browser sign-in (OAuth) \u{2502}", + "\u{2502} role TRANSFORMER \u{b7} warehouse TRANSFORM_XS \u{2502}", + "\u{2502} Triggers 41 paused \u{2502}", + "\u{2570}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{256f}", + "\u{b7} Stopped code location 0.3s", + "\u{b7} Stopped scheduler 0.4s", + "\u{b7} Stopped UI server 0.5s", + "\u{b7} sqb dev stopped (interrupted) ran 42m 10s 1.1s", + ], + }, + ScreenTestCase { + description: "a configuration error at 80x10", + size: SHORT, + messages: removed_key(), + close: close_not_started, + expected_viewport: vec![ + "sqb dev shop \u{b7} target dev \u{b7} sqb 0.256.0", + "\u{2717} Read configuration 0.0s 1 error", + "\u{2717} error sqlbuild_project.toml D001", + " why [dbt] option(s) were removed: defer_clone_from; use dbt-native", + " --state/--defer", + " fix remove defer_clone_from from [dbt]", + "\u{2717} sqb dev did not start configuration error in sqlbuild_project.toml 0.1s", + "Next", + " sqb debug check the configuration on its own", + ], + }, + ScreenTestCase { + description: "--plain appends finished lines only", + size: None, + messages: interrupted(), + close: close_interrupted, + expected_viewport: vec![ + "sqb dev shop \u{b7} target dev \u{b7} sqb 0.256.0", + "\u{2713} Opened control store 0.1s sqlite", + "\u{2713} Started UI server 0.1s http://127.0.0.1:8640", + "\u{2713} Started scheduler 0.1s triggers start paused", + "\u{2713} Discovered project 0.2s 118 models \u{b7} 24 seeds \u{b7} 2 Python nodes", + "\u{2713} Compiled project 0.1s 0 errors \u{b7} 1 warning", + "\u{2713} Published snapshot 0.1s snapshot b429729b", + "Go to https://xy12345.snowflakecomputing.com/oauth/authorize?client_id=SQLBUILD&state=8f3a21c0&redirect_uri=http%3A%2F%2Flocalhost%3A8001 to sign in", + "Enter the URL the OAuth flow redirected you to: http://localhost:8001/?code=ab", + "\u{2713} Connected warehouse 0.6s snowflake \u{b7} browser sign-in (OAuth)", + "\u{2713} ready http://127.0.0.1:8640", + " warehouse snowflake \u{b7} account xy12345 \u{b7} auth browser sign-in (OAuth)", + " role TRANSFORMER \u{b7} warehouse TRANSFORM_XS", + " triggers 41 paused", + "\u{b7} Stopped code location 0.3s", + "\u{b7} Stopped scheduler 0.4s", + "\u{b7} Stopped UI server 0.5s", + "\u{b7} sqb dev stopped (interrupted) ran 42m 10s 1.1s", + ], }, ]; for test_case in test_cases { - let transcript = play(test_case.columns, test_case.messages); + let transcript = play(test_case.size, test_case.messages, test_case.close); assert_eq!( - transcript.rows, test_case.expected_rows, - "{}", - test_case.description - ); - assert!( - transcript - .rows - .iter() - .all(|row| cell_len(row) <= test_case.columns.unwrap_or(usize::MAX)), + transcript.viewport, test_case.expected_viewport, "{}", test_case.description ); @@ -153,47 +252,68 @@ fn given_a_session_when_each_message_is_applied_then_the_terminal_shows_stable_u } #[test] -fn given_keys_after_ready_when_pressed_then_they_ask_for_actions_and_l_shows_the_newest_log_lines() -{ - let flood: Vec = (0..=LOG_RING_LINES) - .map(|index| ScreenMessage::Log(format!("log line {index}"))) - .collect(); +fn given_any_session_when_drawn_then_the_header_is_printed_once_and_no_row_overflows() { let test_cases = [ - KeyTestCase { - description: "l opens the ring's newest lines, x does nothing, l closes, then o r s q act", - columns: Some(80), - messages: after_startup([vec![connected()], flood.clone()].concat()), - keys: "lxlorsq", - expected_actions: vec![ - ScreenAction::None, - ScreenAction::None, - ScreenAction::None, - ScreenAction::OpenUi, - ScreenAction::Recompile, - ScreenAction::RetryWarehouse, - ScreenAction::Quit, - ], - expected_log: log_rows(1, LOG_RING_LINES), + LayoutTestCase { + description: "80x10", + size: (80, 10), + expected_problems: Vec::new(), }, - KeyTestCase { - description: "plain output has no hotkeys", - columns: None, - messages: after_startup([vec![connected()], flood].concat()), - keys: "lq", - expected_actions: vec![ScreenAction::None, ScreenAction::None], - expected_log: Vec::new(), + LayoutTestCase { + description: "80x24", + size: (80, 24), + expected_problems: Vec::new(), + }, + LayoutTestCase { + description: "120x30", + size: (120, 30), + expected_problems: Vec::new(), + }, + LayoutTestCase { + description: "a terminal only 6 rows tall", + size: (60, 6), + expected_problems: Vec::new(), }, ]; + for test_case in test_cases { + assert_eq!( + layout_problems(test_case.size), + test_case.expected_problems, + "{}", + test_case.description + ); + } +} + +#[test] +fn given_keys_after_ready_when_pressed_then_they_ask_for_actions() { + let test_cases = [KeyTestCase { + description: "o and r act; l toggles the log; other keys, s among them, do nothing", + keys: "olrsx", + expected_actions: vec![ + ScreenAction::OpenUi, + ScreenAction::None, + ScreenAction::Recompile, + ScreenAction::None, + ScreenAction::None, + ], + }]; + for test_case in test_cases { let keys: usize = test_case.keys.len(); let transcript = play( - test_case.columns, + TALL, [ - test_case.messages, - test_case.keys.chars().map(ScreenMessage::Key).collect(), + ready(), + test_case + .keys + .chars() + .map(crate::dev_screen::models::ScreenMessage::Key) + .collect(), ] .concat(), + still_running, ); assert_eq!( @@ -202,11 +322,5 @@ fn given_keys_after_ready_when_pressed_then_they_ask_for_actions_and_l_shows_the "{}", test_case.description ); - assert_eq!( - shown_log(&transcript.rows), - test_case.expected_log, - "{}", - test_case.description - ); } } diff --git a/crates/sqlbuild-cli/src/dev_screen/tests/test_missing_secrets.rs b/crates/sqlbuild-cli/src/dev_screen/tests/test_missing_secrets.rs new file mode 100644 index 0000000000..73ba297adf --- /dev/null +++ b/crates/sqlbuild-cli/src/dev_screen/tests/test_missing_secrets.rs @@ -0,0 +1,71 @@ +//! Providers missing secrets show a warning row naming them and their variables until a health read shows none. + +use crate::dev_screen::tests::helpers::{play, secrets_reported, still_running}; +use crate::dev_screen::tests::test_types::MissingSecretsTestCase; + +const TALL: Option<(usize, usize)> = Some((80, 24)); + +#[test] +fn given_providers_missing_secrets_when_health_is_read_then_a_warning_names_them_until_none_is_missing() + { + let test_cases = [ + MissingSecretsTestCase { + description: "a live screen draws the warning above the keys", + size: TALL, + reports: vec![vec![("region", vec!["REGION_TOKEN", "REGION_CODE"])]], + expected_tail: vec![ + "\u{2502} Triggers 41 paused \u{2502}", + "\u{2570}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{256f}", + "\u{26a0} Secrets missing region REGION_TOKEN, REGION_CODE; set them in", + " .env or the environment; press r to reload", + "keys o open UI \u{b7} l full log \u{b7} r recompile \u{b7} q quit", + ], + }, + MissingSecretsTestCase { + description: "a live screen drops the warning once a read shows none", + size: TALL, + reports: vec![ + vec![("region", vec!["REGION_TOKEN", "REGION_CODE"])], + vec![], + ], + expected_tail: vec![ + "\u{2502} Triggers 41 paused \u{2502}", + "\u{2570}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{256f}", + "keys o open UI \u{b7} l full log \u{b7} r recompile \u{b7} q quit", + ], + }, + MissingSecretsTestCase { + description: "plain output prints the warning once per change, then that the secrets are set", + size: None, + reports: vec![ + vec![("region", vec!["REGION_TOKEN"])], + vec![("region", vec!["REGION_TOKEN"])], + vec![], + vec![], + ], + expected_tail: vec![ + " triggers 41 paused", + "\u{26a0} Secrets missing region REGION_TOKEN; set them in .env or the", + " environment; press r to reload", + "\u{2713} Secrets set no provider is missing a secret", + ], + }, + ]; + + for test_case in test_cases { + let viewport: Vec = play( + test_case.size, + secrets_reported(test_case.reports), + still_running, + ) + .viewport; + let tail: &[String] = + &viewport[viewport.len().saturating_sub(test_case.expected_tail.len())..]; + assert_eq!( + tail, + test_case.expected_tail.as_slice(), + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-cli/src/dev_screen/tests/test_types.rs b/crates/sqlbuild-cli/src/dev_screen/tests/test_types.rs index 818fa620b9..da423d21ab 100644 --- a/crates/sqlbuild-cli/src/dev_screen/tests/test_types.rs +++ b/crates/sqlbuild-cli/src/dev_screen/tests/test_types.rs @@ -1,27 +1,121 @@ //! Table rows for the `sqb dev` screen. -use crate::dev_screen::models::{ScreenAction, ScreenMessage}; +use crate::dev_screen::models::{DevScreen, ScreenAction, ScreenMessage}; -/// What a terminal shows after a session, and the action each message asked for. +/// What a terminal shows after a session, everything it kept, and the action each message asked for. pub(super) struct Transcript { - pub(super) rows: Vec, + pub(super) viewport: Vec, + pub(super) scrollback: Vec, pub(super) actions: Vec, } -/// A session at `columns` (`None` for plain output) and every row it leaves on the terminal. +/// A session at `size` (`None` for plain output) and the screen it leaves. pub(super) struct ScreenTestCase { pub(super) description: &'static str, - pub(super) columns: Option, + pub(super) size: Option<(usize, usize)>, pub(super) messages: Vec, - pub(super) expected_rows: Vec, + /// What the screen leaves when the session ends, or nothing while it runs. + pub(super) close: fn(DevScreen) -> String, + pub(super) expected_viewport: Vec<&'static str>, } -/// A session ending in keys: the actions the keys ask for and the log lines left on screen. +/// Providers missing secrets reported after the ready screen, then the next reports: the rows a session ends on. +pub(super) struct MissingSecretsTestCase { + pub(super) description: &'static str, + pub(super) size: Option<(usize, usize)>, + /// Each health read's providers and the variables they miss, in order. + pub(super) reports: Vec)>>, + /// The last rows the terminal shows. + pub(super) expected_tail: Vec<&'static str>, +} + +/// Every session's layout at one terminal size, and what is wrong with it. +pub(super) struct LayoutTestCase { + pub(super) description: &'static str, + pub(super) size: (usize, usize), + pub(super) expected_problems: Vec, +} + +/// A terminal `height` rows tall that keeps its scrollback: lines, `ESC[nF` (up, never above the top of the screen) and `ESC[J`. +pub(super) struct Terminal { + lines: Vec, + cursor: usize, + height: usize, +} + +impl Terminal { + pub(super) fn new(height: usize) -> Self { + Self { + lines: vec![String::new()], + cursor: 0, + height, + } + } + + pub(super) fn write(&mut self, text: &str) { + let mut characters = text.chars().peekable(); + while let Some(character) = characters.next() { + match (character, characters.peek()) { + ('\u{1b}', Some('[')) => { + characters.next(); + let mut argument: String = String::new(); + let command: Option = characters.by_ref().find(|next| { + let end: bool = next.is_ascii_alphabetic(); + argument.extend((!end).then_some(*next)); + end + }); + self.escape(command, &argument); + } + ('\n', _) => { + self.cursor += 1; + let rows: usize = self.lines.len().max(self.cursor + 1); + self.lines.resize(rows, String::new()); + } + (character, _) => self.lines[self.cursor].push(character), + } + } + } + + /// `ESC[nF` moves up `n` rows, never above the top of the screen, to an emptied row; `ESC[J` clears below. + fn escape(&mut self, command: Option, argument: &str) { + match command { + Some('F') => { + let top: usize = self.lines.len().saturating_sub(self.height); + let up: usize = argument.parse().unwrap_or(1); + self.cursor = self.cursor.saturating_sub(up).max(top); + self.lines[self.cursor].clear(); + } + Some('J') => { + self.lines.truncate(self.cursor + 1); + self.lines[self.cursor].clear(); + } + _ => {} + } + } + + /// Every line written, scrollback included, without the cursor's empty last line. + pub(super) fn lines(&self) -> Vec { + let mut lines: Vec = self.lines.clone(); + while lines.last().is_some_and(String::is_empty) { + lines.pop(); + } + lines + } + + /// What the screen shows: the last `height` rows, the cursor's row included. + pub(super) fn viewport(&self) -> Vec { + let skip: usize = self.lines.len().saturating_sub(self.height); + let mut rows: Vec = self.lines[skip..].to_vec(); + while rows.last().is_some_and(String::is_empty) { + rows.pop(); + } + rows + } +} + +/// Keys after ready: the actions they ask for. pub(super) struct KeyTestCase { pub(super) description: &'static str, - pub(super) columns: Option, - pub(super) messages: Vec, pub(super) keys: &'static str, pub(super) expected_actions: Vec, - pub(super) expected_log: Vec, } diff --git a/crates/sqlbuild-cli/src/dev_screen/types.rs b/crates/sqlbuild-cli/src/dev_screen/types.rs index d9650b1926..e36a17adb3 100644 --- a/crates/sqlbuild-cli/src/dev_screen/types.rs +++ b/crates/sqlbuild-cli/src/dev_screen/types.rs @@ -4,11 +4,11 @@ use std::sync::Arc; use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender}; -use crate::dev_screen::models::{KeyGate, ScreenAction, ScreenMessage}; +use crate::dev_screen::models::{KeyInput, ScreenAction, ScreenMessage}; -/// Where to send messages, the actions keys ask for, and the hotkey gate. +/// Where to send messages, the actions keys ask for, and the key reader's input. pub(crate) type DevScreenParts = ( UnboundedSender, UnboundedReceiver, - Option>, + Option>, ); diff --git a/crates/sqlbuild-cli/src/dev_session/_helpers/connection.rs b/crates/sqlbuild-cli/src/dev_session/_helpers/connection.rs index 32794a331f..8dbbd08d6f 100644 --- a/crates/sqlbuild-cli/src/dev_session/_helpers/connection.rs +++ b/crates/sqlbuild-cli/src/dev_session/_helpers/connection.rs @@ -4,8 +4,9 @@ use serde_json::Value; use sqlbuild_core::screen_text::models::WarehouseState; use crate::dev_session::constants::{ - ADAPTER_LABEL, CONNECTION_TEST_LABEL, ERROR_STATUS, LIFECYCLE_STATUSES, NO_REPORT, OK_STATUS, - REPORT_ERROR_SECTIONS, + ADAPTER_LABEL, AUTH_KEYS, AUTH_NAMES, CONNECTION_TEST_LABEL, ERROR_STATUS, KEY_PAIR_KEYS, + LIFECYCLE_STATUSES, NO_REPORT, OK_STATUS, PLACE_KEYS, REPORT_ERROR_SECTIONS, ROLE_KEYS, + STORAGE_KEYS, UNSHOWN_VALUES, }; /// SQLBuild's own progress row, such as `Project discovery OK (0.02s)`, never the client's. @@ -66,16 +67,15 @@ pub(crate) fn connection_outcome(report: &[u8]) -> (String, WarehouseState) { .find(|row| row["label"] == CONNECTION_TEST_LABEL) .cloned(); if test.as_ref().is_some_and(|row| row["status"] == OK_STATUS) { - let detail: Vec = connection + let settings: Vec<(String, String)> = connection .iter() .filter(|row| row["status"].is_null()) - .map(|row| field(row, "message")) - .filter(|message| !message.is_empty()) + .map(|row| (field(row, "label").to_lowercase(), field(row, "message"))) .collect(); return ( adapter, WarehouseState::Connected { - detail: detail.join(" \u{b7} "), + facts: connection_facts(&settings), }, ); } @@ -91,3 +91,55 @@ pub(crate) fn connection_outcome(report: &[u8]) -> (String, WarehouseState) { .unwrap_or_else(|| NO_REPORT.to_owned()); (adapter, WarehouseState::Failed { message }) } + +/// The connection's labelled settings in a fixed order: where (account or host), auth, role, then the warehouse or database. Unknown, masked, boolean and nested values are left out. +pub(crate) fn connection_facts(settings: &[(String, String)]) -> Vec { + let mut facts: Vec = Vec::new(); + if let Some((label, place)) = setting(settings, &PLACE_KEYS) { + facts.push(format!("{label} {place}")); + } + let auth: Option = setting(settings, &AUTH_KEYS) + .map(|(_, method)| auth_name(&method)) + .or_else(|| setting(settings, &KEY_PAIR_KEYS).map(|_| "key pair".to_owned())); + if let Some(auth) = auth { + facts.push(format!("auth {auth}")); + } + if let Some((_, role)) = setting(settings, &ROLE_KEYS) { + facts.push(format!("role {role}")); + } + if let Some((label, storage)) = setting(settings, &STORAGE_KEYS) { + facts.push(format!("{label} {storage}")); + } + facts +} + +/// The first of `keys` that `settings` has with a value worth showing, and that value. +fn setting(settings: &[(String, String)], keys: &[&str]) -> Option<(String, String)> { + for key in keys { + for (label, value) in settings { + if label == key && shown(value) { + return Some((label.clone(), value.clone())); + } + } + } + None +} + +/// A readable name for an authenticator, such as `browser sign-in (OAuth)` for `OAUTH_AUTHORIZATION_CODE`. +fn auth_name(method: &str) -> String { + let method: String = method.to_lowercase(); + AUTH_NAMES + .iter() + .find(|(name, _)| *name == method) + .map_or(method.clone(), |(_, readable)| (*readable).to_owned()) +} + +/// Whether a setting's value says something: not empty, masked, a boolean, `None` or a nested setting. +fn shown(value: &str) -> bool { + let value: &str = value.trim(); + !value.is_empty() + && !UNSHOWN_VALUES.contains(&value.to_lowercase().as_str()) + && !value.starts_with('{') + && !value.starts_with('[') + && !value.chars().all(|character| character == '*') +} diff --git a/crates/sqlbuild-cli/src/dev_session/_helpers/foreground.rs b/crates/sqlbuild-cli/src/dev_session/_helpers/foreground.rs index 471cbaf0ee..84c49e13cc 100644 --- a/crates/sqlbuild-cli/src/dev_session/_helpers/foreground.rs +++ b/crates/sqlbuild-cli/src/dev_session/_helpers/foreground.rs @@ -1,32 +1,33 @@ -//! Open the dev target's first connection in the foreground, attached to the terminal. +//! Open the dev target's first connection in the foreground: the client owns a pseudo-terminal the screen types into as its controlling terminal, so Ctrl+C stays with `sqb dev` and a password prompt can turn echo off itself. +use std::fs::File; +use std::io::Read; use std::process::Stdio; use sqlbuild_core::screen_text::models::WarehouseState; -use sqlbuild_orchestration::dev_events::constants::DEV_EVENTS_VARIABLE; +use sqlbuild_orchestration::dev_events::constants::{DEBUG_REPORT_VARIABLE, DEV_EVENTS_VARIABLE}; use tokio::io::AsyncReadExt; use tokio::process::Command; use tokio::sync::mpsc::UnboundedSender; -use crate::dev_screen::models::{DevStep, KeyGate, ScreenMessage}; +use crate::dev_screen::models::{DevStep, KeyInput, ScreenMessage}; use crate::dev_session::_helpers::connection::{connection_outcome, split_debug_output}; use crate::dev_session::constants::{CONNECTING, DEBUG_DRAIN, NO_REPORT}; use crate::dev_session::models::DevProject; +use crate::dev_stop::main::stop_switch::stop_switch; +use sqlbuild_core::process_environment::main::apply_environment_overlay::apply_environment_overlay; -/// Run `sqb debug --json` with the terminal's input, framing the client's own output; true when it connected. +/// Run `sqb debug --json`, showing the client's own text as a prompt above the live steps; the connection's state. pub(crate) async fn connect_in_foreground( screen: &UnboundedSender, - keys: Option<&KeyGate>, + keys: Option<&KeyInput>, dev: &DevProject, -) -> bool { +) -> WarehouseState { drop(screen.send(ScreenMessage::Started { step: DevStep::Warehouse, detail: CONNECTING.to_owned(), })); - if let Some(keys) = keys { - keys.close().await; - } - let (adapter, state): (String, WarehouseState) = match run_debug(screen, dev).await { + let (adapter, state): (String, WarehouseState) = match run_debug(screen, keys, dev).await { Ok(report) => connection_outcome(&report), Err(error) => ( String::new(), @@ -35,34 +36,93 @@ pub(crate) async fn connect_in_foreground( }, ), }; - if let Some(keys) = keys { - keys.open(); + drop(screen.send(ScreenMessage::Warehouse { + adapter, + state: state.clone(), + })); + state +} + +/// While the client runs: typed keys go to its terminal, and its process group dies with `sqb dev`. +struct Foreground<'a> { + keys: Option<&'a KeyInput>, + group: Option, +} + +impl Drop for Foreground<'_> { + fn drop(&mut self) { + if let Some(keys) = self.keys + && let Ok(mut forward) = keys.forward.lock() + { + *forward = None; + } + if let Some(group) = self.group { + stop_switch().forget_group(group); + } } - let connected: bool = matches!(state, WarehouseState::Connected { .. }); - drop(screen.send(ScreenMessage::Warehouse { adapter, state })); - connected } -/// The report on stdout and stderr streamed to the screen, until `sqb debug` exits even if a browser it opened keeps the pipes. +/// The report from its own file; the client's text on stdout and stderr streamed to the screen, until `sqb debug` exits even if a browser it opened keeps the pipes. async fn run_debug( screen: &UnboundedSender, + keys: Option<&KeyInput>, dev: &DevProject, ) -> std::io::Result> { - let mut child = Command::new(&dev.executable) + let report: ReportFile = ReportFile( + std::env::temp_dir().join(format!("sqb-dev-debug-{}.json", uuid::Uuid::now_v7())), + ); + let mut command = Command::new(&dev.executable); + apply_environment_overlay(command.as_std_mut()); + command .arg("--project-dir") .arg(&dev.project) .args(["debug", "--target", &dev.target, "--json"]) .env_remove(DEV_EVENTS_VARIABLE) - .stdin(Stdio::inherit()) + .env(DEBUG_REPORT_VARIABLE, &report.0) .stdout(Stdio::piped()) .stderr(Stdio::piped()) - .kill_on_drop(true) - .spawn()?; + .kill_on_drop(true); + let terminal: Option<(File, File)> = match keys.map(|_| open_terminal()) { + Some(Ok(terminal)) => Some(terminal), + Some(Err(error)) => { + drop(screen.send(ScreenMessage::Log(format!( + "the warehouse client reads this terminal directly: {error}" + )))); + None + } + None => None, + }; + match &terminal { + Some((_, client)) => { + command.stdin(Stdio::from(client.try_clone()?)); + #[cfg(unix)] + sqlbuild_process_ownership::terminal::main::controlling_terminal::controlling_terminal( + command.as_std_mut(), + ); + } + None => { + command.stdin(Stdio::inherit()); + } + } + let mut child = command.spawn()?; + let mut foreground: Foreground<'_> = Foreground { keys, group: None }; + if let Some((controller, client)) = terminal { + drop(client); + if let Some(pid) = child.id() { + stop_switch().register_group(pid); + foreground.group = Some(pid); + } + if let Some(keys) = keys + && let Ok(mut forward) = keys.forward.lock() + { + *forward = Some(controller.try_clone()?); + } + echo_terminal(controller, screen.clone()); + } let (Some(mut stdout), Some(mut stderr)) = (child.stdout.take(), child.stderr.take()) else { return Err(std::io::Error::other("sqb debug output is unavailable")); }; - let mut report: Vec = Vec::new(); - let relay = async { + let errors = async { let mut chunk: [u8; 4096] = [0; 4096]; loop { let read: usize = stderr.read(&mut chunk).await?; @@ -78,8 +138,20 @@ async fn run_debug( } } }; + let output = async { + let mut chunk: [u8; 4096] = [0; 4096]; + loop { + let read: usize = stdout.read(&mut chunk).await?; + if read == 0 { + return Ok::<(), std::io::Error>(()); + } + drop(screen.send(ScreenMessage::ClientOutput( + String::from_utf8_lossy(&chunk[..read]).into_owned(), + ))); + } + }; { - let reading = async { tokio::try_join!(relay, stdout.read_to_end(&mut report)) }; + let reading = async { tokio::try_join!(errors, output) }; tokio::pin!(reading); tokio::select! { read = &mut reading => { read?; } @@ -92,5 +164,66 @@ async fn run_debug( } } child.wait().await?; - Ok(report) + drop(foreground); + std::fs::read(&report.0) +} + +/// The file `sqb debug` writes its report to, removed once read or abandoned. +struct ReportFile(std::path::PathBuf); + +impl Drop for ReportFile { + fn drop(&mut self) { + drop(std::fs::remove_file(&self.0)); + } +} + +/// Anything the client writes to its terminal, shown in the prompt, with what is typed when the client leaves echo on. +fn echo_terminal(controller: File, screen: UnboundedSender) { + std::thread::spawn(move || { + let mut controller: File = controller; + let mut chunk: [u8; 1024] = [0; 1024]; + while let Ok(read) = controller.read(&mut chunk) { + if read == 0 + || screen + .send(ScreenMessage::ClientOutput( + String::from_utf8_lossy(&chunk[..read]).into_owned(), + )) + .is_err() + { + return; + } + } + }); +} + +/// A pseudo-terminal: the controller `sqb dev` writes keys to, and the terminal the client reads, sized like this one. It echoes as a terminal does, so a plain prompt shows what is typed and a password prompt that turns echo off hides it. Outside Linux `openpt` can't open close-on-exec, so that is set straight after. +#[cfg(unix)] +fn open_terminal() -> std::io::Result<(File, File)> { + use rustix::fs::{Mode, OFlags}; + use rustix::pty::{OpenptFlags, grantpt, openpt, ptsname, unlockpt}; + #[cfg(target_os = "linux")] + let controller = openpt(OpenptFlags::RDWR | OpenptFlags::NOCTTY | OpenptFlags::CLOEXEC)?; + #[cfg(not(target_os = "linux"))] + let controller = { + let controller = openpt(OpenptFlags::RDWR | OpenptFlags::NOCTTY)?; + rustix::io::fcntl_setfd(&controller, rustix::io::FdFlags::CLOEXEC)?; + controller + }; + grantpt(&controller)?; + unlockpt(&controller)?; + let name = ptsname(&controller, Vec::new())?; + let client = rustix::fs::open( + name.as_c_str(), + OFlags::RDWR | OFlags::NOCTTY | OFlags::CLOEXEC, + Mode::empty(), + )?; + if let Ok(size) = rustix::termios::tcgetwinsize(std::io::stdin()) { + let _ = rustix::termios::tcsetwinsize(&client, size); + } + Ok((File::from(controller), File::from(client))) +} + +#[cfg(not(unix))] +fn open_terminal() -> std::io::Result<(File, File)> { + Err(std::io::Error::other("pseudo-terminals need Unix")) } diff --git a/crates/sqlbuild-cli/src/dev_session/_helpers/runs.rs b/crates/sqlbuild-cli/src/dev_session/_helpers/runs.rs index 2b4d02b731..3a0c13ef0c 100644 --- a/crates/sqlbuild-cli/src/dev_session/_helpers/runs.rs +++ b/crates/sqlbuild-cli/src/dev_session/_helpers/runs.rs @@ -3,7 +3,7 @@ use std::collections::HashMap; use std::time::Duration; -use sqlbuild_orchestration::runs::models::{RunRecord, RunStatus}; +use sqlbuild_orchestration::runs::models::{RunOrigin, RunRecord, RunStatus}; use uuid::Uuid; use crate::dev_screen::models::ScreenMessage; @@ -26,14 +26,18 @@ pub(crate) fn run_messages( if before.is_none() { messages.push(ScreenMessage::Run { name: run_name(run), - detail: format!("started from {}", run.origin.as_str()), + detail: started_by(run), finished: None, }); } if run.status.is_terminal() && before.is_none_or(|status| !status.is_terminal()) { messages.push(ScreenMessage::Run { name: run_name(run), - detail: format!("{} nodes", run.node_counts_json.values().sum::()), + detail: format!( + "{} \u{b7} {} nodes", + outcome(run.status), + run.node_counts_json.values().sum::() + ), finished: Some(( matches!(run.status, RunStatus::Success | RunStatus::Warn), run_elapsed(run), @@ -44,6 +48,36 @@ pub(crate) fn run_messages( (messages, now) } +/// How a finished run ended, in words. +fn outcome(status: RunStatus) -> &'static str { + match status { + RunStatus::Success => "succeeded", + RunStatus::Warn => "succeeded with warnings", + RunStatus::Partial => "partly succeeded", + RunStatus::Failed => "failed", + RunStatus::Cancelled => "cancelled", + RunStatus::Skipped => "skipped", + RunStatus::Queued | RunStatus::Launched | RunStatus::Running | RunStatus::Unresponsive => { + "ended" + } + } +} + +/// `started manually`, `started by schedule nightly` or `started as a rerun`; the trigger is named unless it already names the run. +fn started_by(run: &RunRecord) -> String { + let trigger: String = match (&run.job_key, &run.trigger_name) { + (Some(_), Some(name)) => format!(" {name}"), + _ => String::new(), + }; + match run.origin { + RunOrigin::Manual => "started manually".to_owned(), + RunOrigin::Schedule => format!("started by schedule{trigger}"), + RunOrigin::Sensor => format!("started by sensor{trigger}"), + RunOrigin::Rerun => "started as a rerun".to_owned(), + RunOrigin::Backfill => "started by a backfill".to_owned(), + } +} + fn run_name(run: &RunRecord) -> String { run.job_key .clone() diff --git a/crates/sqlbuild-cli/src/dev_session/constants.rs b/crates/sqlbuild-cli/src/dev_session/constants.rs index 33d092f88a..e0d8a6589a 100644 --- a/crates/sqlbuild-cli/src/dev_session/constants.rs +++ b/crates/sqlbuild-cli/src/dev_session/constants.rs @@ -24,3 +24,33 @@ pub(crate) const RUN_PAGE: u32 = 20; pub(crate) const CONNECTING: &str = "connecting"; /// How long the foreground `sqb debug`'s pipes are drained after it exits. pub(crate) const DEBUG_DRAIN: Duration = Duration::from_secs(2); +/// Connection settings that say where the warehouse is, in the order they are looked for. +pub(crate) const PLACE_KEYS: [&str; 3] = ["account", "host", "project"]; +/// Connection settings that name the authentication method. +pub(crate) const AUTH_KEYS: [&str; 2] = ["authenticator", "method"]; +/// Connection settings that mean key-pair authentication when no method is named. +pub(crate) const KEY_PAIR_KEYS: [&str; 2] = ["private_key_file", "private_key_path"]; +/// Connection settings that name the role. +pub(crate) const ROLE_KEYS: [&str; 1] = ["role"]; +/// Connection settings that name the compute or storage, a warehouse before a database. +pub(crate) const STORAGE_KEYS: [&str; 4] = ["warehouse", "database", "dataset", "path"]; +/// Readable names for authenticators, keyed by their lower-case setting. +pub(crate) const AUTH_NAMES: [(&str, &str); 8] = [ + ("oauth_authorization_code", "browser sign-in (OAuth)"), + ("externalbrowser", "browser sign-in (SSO)"), + ("snowflake_jwt", "key pair"), + ("snowflake", "password"), + ("username_password_mfa", "password and MFA"), + ("oauth", "OAuth token"), + ("oauth_client_credentials", "OAuth client credentials"), + ("programmatic_access_token", "access token"), +]; +/// Setting values that say nothing on the Warehouse line. +pub(crate) const UNSHOWN_VALUES: [&str; 6] = + ["none", "null", "true", "false", "not configured", "not set"]; +/// Why `sqb dev` stops when the first warehouse connection fails. +pub(crate) const WAREHOUSE_FAILED: &str = "could not connect to the warehouse"; +/// Why `sqb dev` stops when the code location exits by itself. +pub(crate) const LOCATION_STOPPED: &str = "the code location stopped unexpectedly"; +/// The stop line of a warehouse connection that was still open. +pub(crate) const CANCELLED_CONNECT: &str = "Cancelled warehouse connection"; diff --git a/crates/sqlbuild-cli/src/dev_session/main/run_dev_session.rs b/crates/sqlbuild-cli/src/dev_session/main/run_dev_session.rs index e96a94f026..7abcb3e7d6 100644 --- a/crates/sqlbuild-cli/src/dev_session/main/run_dev_session.rs +++ b/crates/sqlbuild-cli/src/dev_session/main/run_dev_session.rs @@ -1,5 +1,8 @@ -//! Feed the `sqb dev` screen from the location child, open the warehouse in the foreground and act on hotkeys. +//! Feed the `sqb dev` screen from the location child, open the warehouse in the foreground and act on keys. +use std::time::Duration; + +use sqlbuild_core::screen_text::models::WarehouseState; use sqlbuild_orchestration::declarations::main::list_triggers::list_triggers; use sqlbuild_orchestration::dev_events::main::parse_dev_event::parse_dev_event; use sqlbuild_orchestration::dev_events::models::{DevControl, DevEvent}; @@ -16,11 +19,15 @@ use crate::dev_session::_helpers::child::{publish_record, relay_logs, send_contr use crate::dev_session::_helpers::foreground::connect_in_foreground; use crate::dev_session::_helpers::runs::{SeenRuns, run_messages}; use crate::dev_session::_helpers::triggers::trigger_summary; -use crate::dev_session::constants::{RUN_PAGE, RUN_POLL}; +use crate::dev_session::constants::{ + CANCELLED_CONNECT, LOCATION_STOPPED, RUN_PAGE, RUN_POLL, WAREHOUSE_FAILED, +}; use crate::dev_session::models::{DevProject, LocationPipes}; +use crate::dev_session::types::Connecting; +use crate::dev_stop::main::stop_switch::stop_switch; use crate::person_login::main::open_browser::open_browser; -/// Run until `q`, shutdown or the location child closing its output. +/// Run until shutdown; the location child closing its output, or the first connection failing, is an error. pub(crate) async fn run_dev_session( (screen, mut actions, keys): DevScreenParts, (pipes, dev): (LocationPipes, DevProject), @@ -36,17 +43,29 @@ pub(crate) async fn run_dev_session( let mut events = BufReader::new(stdout).lines(); let mut runs: Option = None; let mut connected: Option = None; + let mut connecting: Option> = None; let mut poll = tokio::time::interval(RUN_POLL); + let connect = + || -> Connecting<'_> { Box::pin(connect_in_foreground(&screen, keys.as_deref(), &dev)) }; loop { tokio::select! { changed = shutdown.changed() => { if changed.is_err() || *shutdown.borrow() { + if connecting.take().is_some() { + drop(screen.send(ScreenMessage::Stopped { + label: CANCELLED_CONNECT.to_owned(), + elapsed: Duration::ZERO, + })); + } return Ok(()); } } line = events.next_line() => { let Some(line) = line? else { - return Ok(()); + if *shutdown.borrow() { + return Ok(()); + } + return Err(ControlError::Invalid(LOCATION_STOPPED.into())); }; let Some(event) = parse_dev_event(&line) else { drop(screen.send(ScreenMessage::Log(line))); @@ -58,24 +77,28 @@ pub(crate) async fn run_dev_session( trigger_summary(&list_triggers(&store, location_id, &dev.target).await?), ))); } - let first: bool = matches!(event, DevEvent::Published { .. }) && connected.is_none(); + let first: bool = matches!(event, DevEvent::Published { .. }) + && connected.is_none() + && connecting.is_none(); drop(screen.send(ScreenMessage::Child(event))); if first { - let verdict: bool = connect_in_foreground(&screen, keys.as_deref(), &dev).await; - connected = Some(verdict); - send_control(&mut stdin, DevControl::Warehouse { connected: verdict }).await?; + connecting = Some(connect()); } } - action = actions.recv() => match action { - Some(ScreenAction::Quit) | None => return Ok(()), - Some(ScreenAction::OpenUi) => drop(open_browser(&url)), - Some(ScreenAction::Recompile) => send_control(&mut stdin, DevControl::Recompile).await?, - Some(ScreenAction::RetryWarehouse) => { - let verdict: bool = connect_in_foreground(&screen, keys.as_deref(), &dev).await; - connected = Some(verdict); - send_control(&mut stdin, DevControl::Warehouse { connected: verdict }).await?; + state = settle(&mut connecting), if connecting.is_some() => { + connecting = None; + let verdict: bool = matches!(state, WarehouseState::Connected { .. }); + if !verdict && connected.is_none() { + return Err(ControlError::Invalid(WAREHOUSE_FAILED.into())); } - Some(ScreenAction::None) => {} + connected = Some(verdict); + stop_switch().mark_ready(); + send_control(&mut stdin, DevControl::Warehouse { connected: verdict }).await?; + } + Some(action) = actions.recv() => match action { + ScreenAction::OpenUi => drop(open_browser(&url)), + ScreenAction::Recompile => send_control(&mut stdin, DevControl::Recompile).await?, + ScreenAction::None => {} }, _ = poll.tick(), if connected.is_some() => { let records = list_runs(&store, (location_id, &dev.target), RUN_PAGE).await?; @@ -91,3 +114,11 @@ pub(crate) async fn run_dev_session( } } } + +/// The open connection's state once it settles; without one, never. +async fn settle(connecting: &mut Option>) -> WarehouseState { + match connecting { + Some(future) => future.await, + None => std::future::pending().await, + } +} diff --git a/crates/sqlbuild-cli/src/dev_session/mod.rs b/crates/sqlbuild-cli/src/dev_session/mod.rs index d031795eef..1a6e1a7541 100644 --- a/crates/sqlbuild-cli/src/dev_session/mod.rs +++ b/crates/sqlbuild-cli/src/dev_session/mod.rs @@ -4,6 +4,7 @@ pub(crate) mod _helpers; pub(crate) mod constants; pub(crate) mod main; pub(crate) mod models; +pub(crate) mod types; #[cfg(test)] mod tests; diff --git a/crates/sqlbuild-cli/src/dev_session/tests/test_connection.rs b/crates/sqlbuild-cli/src/dev_session/tests/test_connection.rs index d1ee910ff8..f08b8fb55f 100644 --- a/crates/sqlbuild-cli/src/dev_session/tests/test_connection.rs +++ b/crates/sqlbuild-cli/src/dev_session/tests/test_connection.rs @@ -25,7 +25,42 @@ fn given_a_debug_report_when_read_then_the_adapter_and_warehouse_state_follow_it ]), ), expected_adapter: "duckdb", - expected_state: r#"Connected { detail: "/work/shop/warehouse.duckdb" }"#.to_owned(), + expected_state: r#"Connected { facts: ["database /work/shop/warehouse.duckdb"] }"# + .to_owned(), + }, + OutcomeTestCase { + description: "a Snowflake connection is labelled in a fixed order, without booleans, dicts or masked values", + report: report( + json!([row("adapter", Some("OK"), "snowflake", "found")]), + json!([ + row("user", None, "sam.lee@example.com", ""), + row("warehouse", None, "TRANSFORM_XS", ""), + row("client_session_keep_alive", None, "True", ""), + row("role", None, "TRANSFORMER", ""), + row("session_parameters", None, "{'QUERY_TAG': 'sqb', 'TIMEOUT': 0}", ""), + row("authenticator", None, "OAUTH_AUTHORIZATION_CODE", ""), + row("password", None, "****", ""), + row("account", None, "xy12345", ""), + row("database", None, "ANALYTICS", ""), + row("connection test", Some("OK"), "", "connected"), + ]), + ), + expected_adapter: "snowflake", + expected_state: r#"Connected { facts: ["account xy12345", "auth browser sign-in (OAuth)", "role TRANSFORMER", "warehouse TRANSFORM_XS"] }"# + .to_owned(), + }, + OutcomeTestCase { + description: "a private key without an authenticator is key-pair authentication", + report: report( + json!([row("adapter", Some("OK"), "snowflake", "found")]), + json!([ + row("account", None, "xy12345", ""), + row("private_key_file", None, "/keys/sqb.p8", ""), + row("connection test", Some("OK"), "", "connected"), + ]), + ), + expected_adapter: "snowflake", + expected_state: r#"Connected { facts: ["account xy12345", "auth key pair"] }"#.to_owned(), }, OutcomeTestCase { description: "a failing connection test reports its own message, not the skipped query test", diff --git a/crates/sqlbuild-cli/src/dev_session/tests/test_run_messages.rs b/crates/sqlbuild-cli/src/dev_session/tests/test_run_messages.rs index ebb23fb906..aa09207ee2 100644 --- a/crates/sqlbuild-cli/src/dev_session/tests/test_run_messages.rs +++ b/crates/sqlbuild-cli/src/dev_session/tests/test_run_messages.rs @@ -41,9 +41,9 @@ fn given_runs_since_the_last_poll_when_read_then_each_start_and_end_is_reported_ ), ], expected_messages: vec![ - "new_orders_file | started from sensor | running".to_owned(), - "new_orders_file | 4 nodes | failed 12s".to_owned(), - "orders_daily | started from schedule | running".to_owned(), + "new_orders_file | started by sensor | running".to_owned(), + "new_orders_file | failed \u{b7} 4 nodes | failed 12s".to_owned(), + "orders_daily | started by schedule | running".to_owned(), ], }, RunPollTestCase { @@ -58,7 +58,9 @@ fn given_runs_since_the_last_poll_when_read_then_each_start_and_end_is_reported_ (5, 3), ), ], - expected_messages: vec!["adhoc | 5 nodes | ok 90s".to_owned()], + expected_messages: vec![ + "adhoc | succeeded with warnings \u{b7} 5 nodes | ok 90s".to_owned(), + ], }, RunPollTestCase { description: "a run already seen ending is not reported again", diff --git a/crates/sqlbuild-cli/src/dev_session/types.rs b/crates/sqlbuild-cli/src/dev_session/types.rs new file mode 100644 index 0000000000..4726c4339c --- /dev/null +++ b/crates/sqlbuild-cli/src/dev_session/types.rs @@ -0,0 +1,9 @@ +//! The shapes a `sqb dev` session passes around. + +use std::future::Future; +use std::pin::Pin; + +use sqlbuild_core::screen_text::models::WarehouseState; + +/// A foreground connection that is still open. +pub(crate) type Connecting<'a> = Pin + Send + 'a>>; diff --git a/crates/sqlbuild-cli/src/dev_stop/_helpers/mod.rs b/crates/sqlbuild-cli/src/dev_stop/_helpers/mod.rs new file mode 100644 index 0000000000..a5de8b3e98 --- /dev/null +++ b/crates/sqlbuild-cli/src/dev_stop/_helpers/mod.rs @@ -0,0 +1,2 @@ +pub(crate) mod processes; +pub(crate) mod switch; diff --git a/crates/sqlbuild-cli/src/dev_stop/_helpers/processes.rs b/crates/sqlbuild-cli/src/dev_stop/_helpers/processes.rs new file mode 100644 index 0000000000..0079fa57dc --- /dev/null +++ b/crates/sqlbuild-cli/src/dev_stop/_helpers/processes.rs @@ -0,0 +1,61 @@ +//! Signals for the processes `sqb dev` started, and the terminal mode it changed. + +#[cfg(target_os = "linux")] +use rustix::process::kill_process; +#[cfg(unix)] +use rustix::process::{Pid, Signal, kill_process_group}; +#[cfg(unix)] +use rustix::termios::{OptionalActions, Termios, tcsetattr}; + +/// SIGKILL `group` when `kill`, else SIGTERM; a group that already exited is fine. +#[cfg(unix)] +pub(crate) fn signal_group(group: i32, kill: bool) { + if let Some(pid) = Pid::from_raw(group) { + let signal: Signal = if kill { Signal::KILL } else { Signal::TERM }; + let _ = kill_process_group(pid, signal); + } +} + +#[cfg(not(unix))] +pub(crate) fn signal_group(_group: i32, _kill: bool) {} + +/// On Linux, also SIGKILL every direct child still running and the process group it leads, as a backstop for children nothing registered; registered groups, such as each local worker's, are killed on every Unix. +#[cfg(target_os = "linux")] +pub(crate) fn kill_children() { + let own: i32 = rustix::process::getpid().as_raw_nonzero().get(); + let Ok(entries) = std::fs::read_dir("/proc") else { + return; + }; + for entry in entries.flatten() { + let Some(Ok(pid)) = entry.file_name().to_str().map(str::parse::) else { + continue; + }; + let Ok(stat) = std::fs::read_to_string(entry.path().join("stat")) else { + continue; + }; + if let Some(Ok(parent)) = parent_of(&stat) + && parent == own + && let Some(pid) = Pid::from_raw(pid) + { + let _ = kill_process_group(pid, Signal::KILL); + let _ = kill_process(pid, Signal::KILL); + } + } +} + +/// Elsewhere, children die with their registered groups, which `killpg` reaches on every Unix, or when their handles drop. +#[cfg(not(target_os = "linux"))] +pub(crate) fn kill_children() {} + +/// The parent ID in a `/proc//stat` line, read after the parenthesised command name. +#[cfg(target_os = "linux")] +fn parent_of(stat: &str) -> Option> { + let rest: &str = &stat[stat.rfind(')')? + 1..]; + Some(rest.split_whitespace().nth(1)?.parse::()) +} + +/// Put stdin's terminal back in `cooked` mode. +#[cfg(unix)] +pub(crate) fn restore_termios(cooked: &Termios) { + let _ = tcsetattr(std::io::stdin(), OptionalActions::Now, cooked); +} diff --git a/crates/sqlbuild-cli/src/dev_stop/_helpers/switch.rs b/crates/sqlbuild-cli/src/dev_stop/_helpers/switch.rs new file mode 100644 index 0000000000..cc2e69012e --- /dev/null +++ b/crates/sqlbuild-cli/src/dev_stop/_helpers/switch.rs @@ -0,0 +1,8 @@ +//! The one stop switch of the process. + +use std::sync::OnceLock; + +use crate::dev_stop::models::StopSwitch; + +/// Set on first use by `stop_switch`. +pub(crate) static SWITCH: OnceLock = OnceLock::new(); diff --git a/crates/sqlbuild-cli/src/dev_stop/constants.rs b/crates/sqlbuild-cli/src/dev_stop/constants.rs new file mode 100644 index 0000000000..304292c20c --- /dev/null +++ b/crates/sqlbuild-cli/src/dev_stop/constants.rs @@ -0,0 +1,38 @@ +//! How long a stop may take, and the exit status of each reason. + +use std::time::Duration; + +/// Roles get this long to stop on their own; then their processes are killed. +pub(crate) const STOP_GRACE: Duration = Duration::from_millis(800); +/// After the grace period, this long more before the process exits whatever is still running. +pub(crate) const STOP_DEADLINE: Duration = Duration::from_millis(2_500); +/// `q`: a stop that was asked for. +pub(crate) const QUIT_STATUS: i32 = 0; +/// Ctrl+C or SIGINT, as shells report it. +pub(crate) const INTERRUPT_STATUS: i32 = 130; +/// SIGHUP, as shells report it. +pub(crate) const HANGUP_STATUS: i32 = 129; +/// With a run active, its cancellation gets this long before the stop forces it. +pub(crate) const CANCEL_DEADLINE: Duration = Duration::from_secs(30); +/// How often a stop checks whether the runs it cancels have ended. +pub(crate) const CANCEL_POLL: Duration = Duration::from_millis(250); +/// The newest runs a stop looks through for ones to cancel. +pub(crate) const RUN_SCAN: u32 = 100; +/// Who a stop's cancellations name in the audit log. +pub(crate) const DEV_ACTOR: &str = "local-development"; +/// The role a stop's cancellations are granted by: the local control store's owner. +pub(crate) const DEV_GRANTING_ROLE: &str = "control-store-owner"; +/// Why a stop cancels a run. +pub(crate) const CANCEL_REASON: &str = "sqb dev stopped"; +/// SIGTERM, as shells report it. +pub(crate) const TERMINATE_STATUS: i32 = 143; +/// What a forced stop prints on the terminal before it exits. +pub(crate) const FORCED_LINE: &str = "\u{b7} sqb dev stopped (forced)\n"; +/// `sqb dev` could not start. +pub(crate) const START_FAILURE_STATUS: i32 = 2; +/// A service failed after `sqb dev` was ready. +pub(crate) const RUN_FAILURE_STATUS: i32 = 1; +/// How long aborted roles get to unwind after the grace period. +pub(crate) const ABORT_WAIT: Duration = Duration::from_millis(300); +/// How long tasks left over after `sqb dev` ends get before the process exits. +pub(crate) const RUNTIME_SHUTDOWN: Duration = Duration::from_millis(200); diff --git a/crates/sqlbuild-cli/src/dev_stop/main/mod.rs b/crates/sqlbuild-cli/src/dev_stop/main/mod.rs new file mode 100644 index 0000000000..e397c527ad --- /dev/null +++ b/crates/sqlbuild-cli/src/dev_stop/main/mod.rs @@ -0,0 +1,2 @@ +pub(crate) mod stop_switch; +pub(crate) mod watch_signals; diff --git a/crates/sqlbuild-cli/src/dev_stop/main/stop_switch.rs b/crates/sqlbuild-cli/src/dev_stop/main/stop_switch.rs new file mode 100644 index 0000000000..a897ad393e --- /dev/null +++ b/crates/sqlbuild-cli/src/dev_stop/main/stop_switch.rs @@ -0,0 +1,9 @@ +//! The process's one stop switch. + +use crate::dev_stop::_helpers::switch::SWITCH; +use crate::dev_stop::models::StopSwitch; + +/// The switch the signal task, the key thread and every `sqb dev` role share. +pub(crate) fn stop_switch() -> &'static StopSwitch { + SWITCH.get_or_init(StopSwitch::new) +} diff --git a/crates/sqlbuild-cli/src/dev_stop/main/watch_signals.rs b/crates/sqlbuild-cli/src/dev_stop/main/watch_signals.rs new file mode 100644 index 0000000000..a42a346763 --- /dev/null +++ b/crates/sqlbuild-cli/src/dev_stop/main/watch_signals.rs @@ -0,0 +1,44 @@ +//! Turn SIGINT, SIGTERM and SIGHUP into stop requests. + +use crate::dev_stop::main::stop_switch::stop_switch; +use crate::dev_stop::models::StopReason; + +/// Every SIGINT, SIGTERM or SIGHUP asks the switch to stop; the second forces it. +pub(crate) fn watch_signals() -> std::io::Result<()> { + #[cfg(unix)] + { + use tokio::signal::unix::{SignalKind, signal}; + let mut interrupt = signal(SignalKind::interrupt())?; + let mut terminate = signal(SignalKind::terminate())?; + let mut hangup = signal(SignalKind::hangup())?; + tokio::spawn(async move { + loop { + let reason: StopReason = tokio::select! { + received = interrupt.recv() => match received { + Some(()) => StopReason::Interrupt, + None => return, + }, + received = terminate.recv() => match received { + Some(()) => StopReason::Terminate, + None => return, + }, + received = hangup.recv() => match received { + Some(()) => StopReason::Hangup, + None => return, + }, + }; + stop_switch().request(reason); + } + }); + } + #[cfg(not(unix))] + tokio::spawn(async { + loop { + match tokio::signal::ctrl_c().await { + Ok(()) => stop_switch().request(StopReason::Interrupt), + Err(_) => return, + } + } + }); + Ok(()) +} diff --git a/crates/sqlbuild-cli/src/dev_stop/mod.rs b/crates/sqlbuild-cli/src/dev_stop/mod.rs new file mode 100644 index 0000000000..4eb3c15418 --- /dev/null +++ b/crates/sqlbuild-cli/src/dev_stop/mod.rs @@ -0,0 +1,6 @@ +//! How `sqb dev` stops: Ctrl+C, `q` or a signal ask once for a clean stop, and a second Ctrl+C forces it. + +pub(crate) mod _helpers; +pub(crate) mod constants; +pub(crate) mod main; +pub(crate) mod models; diff --git a/crates/sqlbuild-cli/src/dev_stop/models.rs b/crates/sqlbuild-cli/src/dev_stop/models.rs new file mode 100644 index 0000000000..a134a81b12 --- /dev/null +++ b/crates/sqlbuild-cli/src/dev_stop/models.rs @@ -0,0 +1,259 @@ +//! Why `sqb dev` stops, and the switch every stop request goes through. + +use std::fs::File; +use std::io::Write; +use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::time::{Duration, Instant}; + +#[cfg(unix)] +use rustix::termios::Termios; +use tokio::sync::watch; + +#[cfg(unix)] +use crate::dev_stop::_helpers::processes::restore_termios; +use crate::dev_stop::_helpers::processes::{kill_children, signal_group}; +use crate::dev_stop::constants::{ + FORCED_LINE, HANGUP_STATUS, INTERRUPT_STATUS, QUIT_STATUS, STOP_DEADLINE, STOP_GRACE, + TERMINATE_STATUS, +}; + +/// What asked `sqb dev` to stop. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum StopReason { + /// `q`. + Quit, + /// Ctrl+C or SIGINT. + Interrupt, + /// SIGTERM. + Terminate, + /// SIGHUP, or the terminal went away under the key reader. + Hangup, +} + +impl StopReason { + /// The exit status a shell expects for this reason. + pub(crate) fn status(self) -> i32 { + match self { + Self::Quit => QUIT_STATUS, + Self::Interrupt => INTERRUPT_STATUS, + Self::Terminate => TERMINATE_STATUS, + Self::Hangup => HANGUP_STATUS, + } + } + + /// The result line's note, such as `(interrupted)`. + pub(crate) fn note(self) -> &'static str { + match self { + Self::Quit => "", + Self::Interrupt => " (interrupted)", + Self::Terminate => " (terminated)", + Self::Hangup => " (terminal closed)", + } + } +} + +/// Shared by the signal task, the key thread and the roles: the first request stops cleanly under a deadline, a second Ctrl+C or signal forces it. +#[derive(Debug)] +pub(crate) struct StopSwitch { + asked: watch::Sender>, + requests: AtomicUsize, + /// Bumped by every `arm` and `disarm`; a deadline fires only while its own value is current. + deadline: AtomicU64, + /// Process groups of children that must not outlive `sqb dev`. + groups: Mutex>, + /// The terminal's cooked mode, put back however `sqb dev` exits. + #[cfg(unix)] + cooked: Mutex>, + /// The terminal the screen writes to while it captures stderr. + output: Mutex>, + ready: AtomicBool, + asked_at: Mutex>, +} + +impl StopSwitch { + pub(crate) fn new() -> Self { + Self { + asked: watch::channel(None).0, + requests: AtomicUsize::new(0), + deadline: AtomicU64::new(0), + groups: Mutex::new(Vec::new()), + #[cfg(unix)] + cooked: Mutex::new(None), + output: Mutex::new(None), + ready: AtomicBool::new(false), + asked_at: Mutex::new(None), + } + } + + /// Ask to stop: the first request starts a clean stop with a deadline that exits with its status; a later Ctrl+C, SIGINT or SIGTERM exits at once with its own, and a later `q` or hang-up changes nothing: a closed terminal reports itself twice, as SIGHUP and as the end of its input. + pub(crate) fn request(&'static self, reason: StopReason) { + let earlier: usize = self.requests.fetch_add(1, Ordering::SeqCst); + if earlier == 0 { + if let Ok(mut asked_at) = self.asked_at.lock() { + *asked_at = Some(Instant::now()); + } + self.asked.send_replace(Some(reason)); + self.arm(STOP_GRACE + STOP_DEADLINE); + return; + } + if !matches!(reason, StopReason::Quit | StopReason::Hangup) { + self.force(reason); + } + } + + /// Kill everything and exit now with `reason`'s status, as Ctrl+\ or a second Ctrl+C asks. + pub(crate) fn force(&self, reason: StopReason) -> ! { + self.exit_now(reason.status(), FORCED_LINE) + } + + /// Force the stop `after` from now, with the stop request's status, unless it is armed again or disarmed first; without a stop request, such as when a service failed, nothing is forced. + pub(crate) fn arm(&'static self, after: Duration) { + let Some(reason) = self.reason() else { + return; + }; + let armed: u64 = self.deadline.fetch_add(1, Ordering::SeqCst) + 1; + std::thread::spawn(move || { + std::thread::sleep(after); + if self.deadline.load(Ordering::SeqCst) == armed { + self.force(reason); + } + }); + } + + /// The stop finished cleanly; no deadline fires after this. + pub(crate) fn disarm(&self) { + self.deadline.fetch_add(1, Ordering::SeqCst); + } + + /// The first stop reason, once something asked. + pub(crate) fn reason(&self) -> Option { + *self.asked.borrow() + } + + /// How long ago the stop was asked for. + pub(crate) fn stopping_for(&self) -> Option { + match self.asked_at.lock() { + Ok(asked_at) => asked_at.map(|asked_at| asked_at.elapsed()), + Err(_poisoned) => None, + } + } + + /// Wait until something asks to stop. + pub(crate) async fn requested(&self) -> StopReason { + let mut asked = self.asked.subscribe(); + loop { + if let Some(reason) = *asked.borrow_and_update() { + return reason; + } + if asked.changed().await.is_err() { + return StopReason::Terminate; + } + } + } + + /// `pid` leads a process group that is killed with `sqb dev`. + pub(crate) fn register_group(&self, pid: u32) { + if let (Ok(pid), Ok(mut groups)) = (i32::try_from(pid), self.groups.lock()) { + groups.push(pid); + } + } + + /// `pid`'s group has exited. + pub(crate) fn forget_group(&self, pid: u32) { + if let (Ok(pid), Ok(mut groups)) = (i32::try_from(pid), self.groups.lock()) { + groups.retain(|group| *group != pid); + } + } + + /// The process groups registered now. + pub(crate) fn groups(&self) -> Vec { + match self.groups.lock() { + Ok(groups) => groups.clone(), + Err(_poisoned) => Vec::new(), + } + } + + /// Kill every registered group, such as each local worker's, on every Unix, then on Linux any child left over. + pub(crate) fn kill_all(&self) { + for group in self.groups() { + signal_group(group, true); + } + kill_children(); + } + + /// Ask every registered group to stop. + pub(crate) fn terminate_groups(&self) { + for group in self.groups() { + signal_group(group, false); + } + } + + /// Remember the terminal's cooked mode, to put back on every exit. + #[cfg(unix)] + pub(crate) fn save_cooked(&self, cooked: Termios) { + if let Ok(mut saved) = self.cooked.lock() { + saved.get_or_insert(cooked); + } + } + + /// Put the terminal's cooked mode back. + pub(crate) fn restore_terminal(&self) { + #[cfg(unix)] + if let Ok(saved) = self.cooked.lock() + && let Some(cooked) = saved.as_ref() + { + restore_termios(cooked); + } + } + + /// Where a forced stop writes while stderr is captured. + pub(crate) fn save_output(&self, terminal: Option) { + if let Ok(mut output) = self.output.lock() { + *output = terminal; + } + } + + /// The development services are up; a later failure is no longer a start-up failure. + pub(crate) fn mark_ready(&self) { + self.ready.store(true, Ordering::SeqCst); + } + + pub(crate) fn is_ready(&self) -> bool { + self.ready.load(Ordering::SeqCst) + } + + /// Kill everything, restore the terminal, say so, and exit with `status`. + fn exit_now(&self, status: i32, line: &str) -> ! { + self.kill_all(); + self.restore_terminal(); + let text: String = format!("\n{line}"); + let terminal: Option = match self.output.lock() { + Ok(output) => match output.as_ref().map(File::try_clone) { + Some(Ok(terminal)) => Some(terminal), + Some(Err(_)) | None => None, + }, + Err(_poisoned) => None, + }; + match terminal { + Some(mut terminal) => drop(terminal.write_all(text.as_bytes())), + None => drop(std::io::stderr().write_all(text.as_bytes())), + } + std::process::exit(status) + } +} + +/// How a `sqb dev` session ended. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum DevEnd { + /// Something asked it to stop. + Stopped(StopReason), + /// It did not start: why, whether the screen already showed the problem, and what to try next. + NotStarted { + reason: String, + explained: bool, + next: Vec<(String, String)>, + }, + /// A service failed after the services were ready. + Failed { reason: String }, +} diff --git a/crates/sqlbuild-cli/src/launcher/_helpers/dispatch.rs b/crates/sqlbuild-cli/src/launcher/_helpers/dispatch.rs index 0df005b918..287652d3f4 100644 --- a/crates/sqlbuild-cli/src/launcher/_helpers/dispatch.rs +++ b/crates/sqlbuild-cli/src/launcher/_helpers/dispatch.rs @@ -4,7 +4,10 @@ use std::ffi::OsString; use std::path::{Path, PathBuf}; use std::time::{Instant, SystemTime}; +use crate::launcher::_helpers::env_file::load_project_env_file; use crate::launcher::_helpers::handoff::{beside, hand_off}; +use sqlbuild_core::process_environment::main::environment_overlay::environment_overlay; + use crate::launcher::_helpers::launch_key::{launch_key, launch_record_path}; use crate::launcher::_helpers::messages::{ print_version, report_handoff_failure, report_missing_python_cli, @@ -18,6 +21,7 @@ use crate::native_commands::main::run_location_invocation::run_location_invocati use crate::native_commands::main::run_login_invocation::run_login_invocation; use crate::native_commands::main::run_native_invocation::run_native_invocation; use crate::native_commands::main::run_person_invocation::run_person_invocation; +use crate::native_commands::main::run_sensor_invocation::run_sensor_invocation; use crate::native_commands::models::NativeParse; use crate::replay::main::serve_reused_compile::serve_reused_compile; @@ -34,6 +38,23 @@ fn launch_record( launch_record_path(arguments, &cwd, &key).map(|path| (path, key)) } +/// The variables the Python CLI must have set or unset, from this process's environment overlay. +fn overlay_changes() -> Vec<(OsString, Option)> { + let overlay = environment_overlay(); + let mut changes: Vec<(OsString, Option)> = overlay + .remove + .into_iter() + .map(|name| (name, None)) + .collect(); + changes.extend( + overlay + .set + .into_iter() + .map(|(name, value)| (name, Some(value))), + ); + changes +} + fn exit_code(code: i64) -> i32 { i32::try_from(code).unwrap_or(HANDOFF_FAILURE_EXIT_CODE) } @@ -46,6 +67,9 @@ pub(crate) fn launch(arguments: Vec, started: (Instant, SystemTime)) - print_version(); return 0; } + if let Err(code) = load_project_env_file(&arguments) { + return code; + } let native = parse_native_invocation(&arguments); if let Ok(NativeParse::Exit(code)) = &native { return *code; @@ -72,6 +96,11 @@ pub(crate) fn launch(arguments: Vec, started: (Instant, SystemTime)) - { return code; } + if let Ok(NativeParse::Invocation { namespace, .. }) = &native + && let Some(code) = run_sensor_invocation(namespace, script.as_deref()) + { + return code; + } let Some(script) = script else { report_missing_python_cli(&program); return HANDOFF_FAILURE_EXIT_CODE; @@ -97,7 +126,7 @@ pub(crate) fn launch(arguments: Vec, started: (Instant, SystemTime)) - handed.push(option); } handed.extend(arguments); - match hand_off(&script, &handed) { + match hand_off(&script, &handed, &overlay_changes()) { Ok(Some(code)) => code, Ok(None) => HANDOFF_FAILURE_EXIT_CODE, Err(error) => { diff --git a/crates/sqlbuild-cli/src/launcher/_helpers/env_file.rs b/crates/sqlbuild-cli/src/launcher/_helpers/env_file.rs new file mode 100644 index 0000000000..a1895f9a84 --- /dev/null +++ b/crates/sqlbuild-cli/src/launcher/_helpers/env_file.rs @@ -0,0 +1,90 @@ +//! Load the project's env file once, before anything reads the environment or starts a child. + +use std::ffi::OsString; +use std::io::Write; +use std::path::Path; + +use sqlbuild_config::env_file::main::load_env_file::load_env_file; +use sqlbuild_core::process_environment::constants::{ENV_FILE_ERROR_VARIABLE, RUN_TOKEN_VARIABLE}; +use sqlbuild_core::process_environment::main::env_file_marker::env_file_marker; +use sqlbuild_core::process_environment::main::environment_var_os::environment_var_os; +use sqlbuild_core::process_environment::main::install_environment_overlay::install_environment_overlay; +use sqlbuild_core::process_environment::models::EnvironmentOverlay; + +use crate::argv::main::command_project_and_target::command_project_and_target; +use crate::native_commands::main::effective_target::effective_target; + +/// Exit code when the configured env file cannot be loaded, as for other configuration errors. +const ENV_FILE_FAILURE_EXIT_CODE: i32 = 1; + +/// The project directory and target the arguments name, `None` when they are not Unicode or do not parse. +fn command_line_project(arguments: &[OsString]) -> Option<(Option, Option)> { + let mut texts: Vec = Vec::new(); + for argument in arguments { + texts.push(argument.to_str()?.to_owned()); + } + command_project_and_target(&texts) +} + +/// Whether this process inherited the load of the same project and target from its parent. +fn inherited(project_dir: &Path, target: Option<&str>) -> bool { + let Some(marker) = env_file_marker() else { + return false; + }; + let canonical = project_dir + .canonicalize() + .unwrap_or_else(|_| project_dir.to_path_buf()); + Path::new(&marker.project_dir) == canonical && marker.target.as_deref() == target +} + +/// Load the env file the project and target choose once per process tree; `Err` is the exit code after reporting why not, except in a run worker, which records why for the run. +pub(crate) fn load_project_env_file(arguments: &[OsString]) -> Result<(), i32> { + let Some((named_dir, selected)) = command_line_project(arguments) else { + return Ok(()); + }; + let Ok(cwd) = std::env::current_dir() else { + return Ok(()); + }; + let project_dir = named_dir.map_or_else(|| cwd.clone(), |named| cwd.join(named)); + if !project_dir + .join(sqlbuild_core::constants::PROJECT_CONFIG_FILENAME) + .is_file() + { + return Ok(()); + } + let Ok(target) = effective_target(&project_dir, selected) else { + return Ok(()); + }; + if inherited(&project_dir, target.as_deref()) { + return Ok(()); + } + match load_env_file(&project_dir, target.as_deref()) { + Ok(None) => Ok(()), + Ok(Some(load)) => { + if let Some(warning) = &load.warning { + let _ = writeln!(std::io::stderr(), "warning: {warning}"); + } + install_environment_overlay(load.overlay); + Ok(()) + } + Err(error) => { + let _ = writeln!( + std::io::stderr(), + "error: {}\n = help: {}", + error.message(), + error.help() + ); + if environment_var_os(RUN_TOKEN_VARIABLE).is_none() { + return Err(ENV_FILE_FAILURE_EXIT_CODE); + } + install_environment_overlay(EnvironmentOverlay { + set: vec![( + OsString::from(ENV_FILE_ERROR_VARIABLE), + OsString::from(error.message()), + )], + remove: Vec::new(), + }); + Ok(()) + } + } +} diff --git a/crates/sqlbuild-cli/src/launcher/_helpers/handoff.rs b/crates/sqlbuild-cli/src/launcher/_helpers/handoff.rs index 405f82a5b5..d6b6f3e6e6 100644 --- a/crates/sqlbuild-cli/src/launcher/_helpers/handoff.rs +++ b/crates/sqlbuild-cli/src/launcher/_helpers/handoff.rs @@ -16,18 +16,42 @@ pub(crate) fn beside(program: &Path, name: &str) -> Option { /// Replace this process with `target`; returns only the error that kept it from starting. #[cfg(unix)] -pub(crate) fn hand_off(target: &Path, arguments: &[OsString]) -> std::io::Result> { +pub(crate) fn hand_off( + target: &Path, + arguments: &[OsString], + environment: &[(OsString, Option)], +) -> std::io::Result> { use std::os::unix::process::CommandExt; - Err(Command::new(target).args(arguments).exec()) + Err(command_for(target, arguments, environment).exec()) +} + +/// `target` with `arguments`, each variable of `environment` set, or unset where its value is `None`. +fn command_for( + target: &Path, + arguments: &[OsString], + environment: &[(OsString, Option)], +) -> Command { + let mut command = Command::new(target); + for (name, value) in environment { + match value { + Some(value) => command.env(name, value), + None => command.env_remove(name), + }; + } + command.args(arguments); + command } /// Run `target` as a child that alone handles Ctrl+C and Ctrl+Break, and return its exit code. #[cfg(not(unix))] -pub(crate) fn hand_off(target: &Path, arguments: &[OsString]) -> std::io::Result> { +pub(crate) fn hand_off( + target: &Path, + arguments: &[OsString], + environment: &[(OsString, Option)], +) -> std::io::Result> { let _ = ctrlc::set_handler(|| {}); - Command::new(target) - .args(arguments) + command_for(target, arguments, environment) .status() .map(|status| status.code()) } diff --git a/crates/sqlbuild-cli/src/launcher/_helpers/launch_key.rs b/crates/sqlbuild-cli/src/launcher/_helpers/launch_key.rs index 1ef154b517..665b3e3d30 100644 --- a/crates/sqlbuild-cli/src/launcher/_helpers/launch_key.rs +++ b/crates/sqlbuild-cli/src/launcher/_helpers/launch_key.rs @@ -5,6 +5,8 @@ use std::io::IsTerminal; use std::path::{Path, PathBuf}; use std::time::UNIX_EPOCH; +use sqlbuild_core::process_environment::main::environment_vars_os::environment_vars_os; + use crate::launcher::constants::{ LAUNCH_KEY_DOMAIN, MISSING_FILE_STAMP, PROJECT_DIR_ABBREVIATION_PREFIXES, PROJECT_DIR_OPTIONS, VOLATILE_ENVIRONMENT, @@ -69,7 +71,8 @@ pub(crate) fn launch_key( update(&mut hasher, &os_bytes(argument)); } update(&mut hasher, &os_bytes(cwd.as_os_str())); - let mut environment: Vec<(OsString, OsString)> = std::env::vars_os() + let mut environment: Vec<(OsString, OsString)> = environment_vars_os() + .into_iter() .filter(|(name, _)| !is_volatile(name)) .collect(); environment.sort(); diff --git a/crates/sqlbuild-cli/src/launcher/_helpers/mod.rs b/crates/sqlbuild-cli/src/launcher/_helpers/mod.rs index cbeb91cd81..d9b9c27dd7 100644 --- a/crates/sqlbuild-cli/src/launcher/_helpers/mod.rs +++ b/crates/sqlbuild-cli/src/launcher/_helpers/mod.rs @@ -1,4 +1,5 @@ pub(crate) mod dispatch; +pub(crate) mod env_file; pub(crate) mod handoff; pub(crate) mod launch_key; pub(crate) mod messages; diff --git a/crates/sqlbuild-cli/src/lib.rs b/crates/sqlbuild-cli/src/lib.rs index 781d162aa3..b275b14686 100644 --- a/crates/sqlbuild-cli/src/lib.rs +++ b/crates/sqlbuild-cli/src/lib.rs @@ -8,6 +8,7 @@ pub mod compute_logs; pub mod cost_store; pub(crate) mod dev_screen; pub(crate) mod dev_session; +pub(crate) mod dev_stop; pub mod diff_report; pub mod dispatch; pub mod launcher; diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/command/argv_host.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/command/argv_host.rs index 4a7f8b62de..2620d699a4 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/command/argv_host.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/command/argv_host.rs @@ -4,8 +4,7 @@ use sqlbuild_core::text::main::decimal_digit_value::decimal_digit_value; use sqlbuild_core::text::main::python_isspace::python_isspace; use sqlbuild_core::text::main::python_str_repr::python_str_repr; -use crate::argv::main::cli_namespace_defaults::cli_namespace_defaults; -use crate::argv::models::{NamespaceDefault, TypeFailure, Value}; +use crate::argv::models::{TypeFailure, Value}; use crate::argv::types::ArgvHost; use crate::launcher::constants::PROGRAM_VERSION; use crate::native_commands::constants::{ @@ -97,24 +96,3 @@ impl ArgvHost for NativeArgvHost { PROGRAM_VERSION.to_owned() } } - -/// The parse's starting namespace: every `CliNamespace` default. -pub(crate) fn namespace_defaults() -> Vec<(String, Value)> { - cli_namespace_defaults() - .iter() - .map(|(name, default)| { - let value: Value = match default { - NamespaceDefault::None => Value::None, - NamespaceDefault::Bool(flag) => Value::Bool(*flag), - NamespaceDefault::Int(number) => Value::Int(number.to_string()), - NamespaceDefault::Text(text) => Value::Str((*text).to_owned()), - NamespaceDefault::EmptyList => Value::List(Vec::new()), - NamespaceDefault::EmptyDict => Value::EmptyDict, - NamespaceDefault::CompileLineageFast | NamespaceDefault::ColumnLineageRich => { - Value::Host(0) - } - }; - ((*name).to_owned(), value) - }) - .collect() -} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/command/decision.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/command/decision.rs index 6b32a28178..fcac7c9416 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/command/decision.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/command/decision.rs @@ -208,6 +208,10 @@ pub(crate) fn control_admin(namespace: &Namespace) -> Result Result(built: &'a Built, name: &str) -> Option<&'a Built> { @@ -71,16 +75,82 @@ pub(crate) fn development_project_name(project_dir: &Path) -> Result, -) -> Result { - effective_target(project_dir, selected) - .map_err(ControlError::Invalid)? - .ok_or_else(|| { - ControlError::Invalid("sqb dev requires --target or a configured default target".into()) +) -> Result<(String, String), Box> { + let paths: ConfigPaths = project_config_paths(project_dir); + let project: Built = + load_project_config(&paths).map_err(|failure| load_problem(&paths, failure))?; + load_local_config(&paths).map_err(|failure| load_problem(&paths, failure))?; + let target_problem = |why: String| { + Box::new(Problem { + level: ProblemLevel::Error, + title: "target".to_owned(), + code: String::new(), + at: Vec::new(), + why, + fix: "pass --target , or set default_target in sqlbuild_project.toml".to_owned(), }) + }; + let target: String = effective_target(project_dir, selected) + .map_err(target_problem)? + .ok_or_else(|| target_problem("sqb dev needs a target and none is selected".to_owned()))?; + let adapter: String = match object_field(&project, "adapter") { + Some(Built::Value(ConfigValue::String(adapter))) => adapter.clone(), + _ => String::new(), + }; + Ok((target, adapter)) +} + +/// A configuration file the loader rejected, with its message and help in full. +fn load_problem(paths: &ConfigPaths, failure: LoadFailure) -> Box { + let name = |file: ConfigFile| -> String { + let path = match file { + ConfigFile::Project => &paths.project, + ConfigFile::LegacyProject => &paths.legacy_project, + ConfigFile::Local => &paths.local, + ConfigFile::LegacyLocal => &paths.legacy_local, + }; + path.file_name().map_or_else( + || path.display().to_string(), + |name| name.to_string_lossy().into_owned(), + ) + }; + let problem = |title: String, why: String| Problem { + level: ProblemLevel::Error, + title, + code: String::new(), + at: Vec::new(), + why, + fix: "sqb debug checks the configuration on its own".to_owned(), + }; + Box::new(match failure { + LoadFailure::Config(failure) => { + let title: String = failure + .message + .iter() + .find_map(|piece| match piece { + MessagePiece::File(file) => Some(name(*file)), + MessagePiece::Text(_) => None, + }) + .unwrap_or_else(|| "configuration".to_owned()); + let why: String = failure.render(|_| String::new()).trim().to_owned(); + Problem { + code: CONFIG_ERROR_CODE.to_owned(), + fix: failure + .help + .unwrap_or_else(|| "sqb debug checks the configuration on its own".to_owned()), + ..problem(title, why) + } + } + LoadFailure::Io(file, error) => problem(name(file), format!("could not read it: {error}")), + LoadFailure::Utf8(_) => problem( + "configuration".to_owned(), + "a configuration file is not UTF-8 text".to_owned(), + ), + }) } /// The project's configured name, or its directory's name when the configuration has none. diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/command/terminal.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/command/terminal.rs index 8c4c91c37d..2df4747392 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/command/terminal.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/command/terminal.rs @@ -4,9 +4,9 @@ use crate::argv::models::Stream; use crate::native_commands::_helpers::command::argv_host::python_int; use crate::native_commands::constants::CLEAR_TERMINAL_LINE; use crate::native_commands::constants::{ - BROKEN_PIPE_EXCEPTION, CI_VARIABLE, COLUMNS_VARIABLE, EXIT_FLUSH_FAILURE, + BROKEN_PIPE_EXCEPTION, CI_VARIABLE, COLUMNS_VARIABLE, DUMB_TERMINAL, EXIT_FLUSH_FAILURE, EXIT_FLUSH_FAILURE_STATUS, FALLBACK_COLUMNS, NO_COLOR_VARIABLE, NO_PROGRESS_VARIABLE, - PASSWORD_INPUT_BYTES, PYTHON_STDOUT_BUFFER_SIZE, UNCAUGHT_EXCEPTION_STATUS, + PASSWORD_INPUT_BYTES, PYTHON_STDOUT_BUFFER_SIZE, TERM_VARIABLE, UNCAUGHT_EXCEPTION_STATUS, }; use crate::native_commands::errors::PythonNeeded; use crate::native_commands::models::LostStdout; @@ -204,28 +204,21 @@ pub(crate) fn finish_lost_stdout(lost: Option<&LostStdout>, exit_code: i32) -> i } } -/// Whether the `sqb dev` screen can redraw in place: on Unix, stderr is a terminal and nothing asks for plain lines. -pub(crate) fn live_screen() -> bool { +/// Whether the `sqb dev` screen redraws in place: on Unix, unless `--plain` asks for appended lines, stdout or stderr is not a terminal, `TERM=dumb`, or `CI` or `SQLBUILD_NO_PROGRESS` is set. +pub(crate) fn live_screen(plain: bool) -> bool { cfg!(unix) + && !plain + && io::stdout().is_terminal() && io::stderr().is_terminal() - && [NO_COLOR_VARIABLE, CI_VARIABLE, NO_PROGRESS_VARIABLE] + && std::env::var(TERM_VARIABLE).as_deref() != Ok(DUMB_TERMINAL) + && [CI_VARIABLE, NO_PROGRESS_VARIABLE] .iter() .all(|variable| std::env::var_os(variable).is_none()) } -/// The width of the terminal on stderr, or the fallback when stderr is not one. -#[cfg(unix)] -pub(crate) fn stderr_columns() -> usize { - match rustix::termios::tcgetwinsize(io::stderr()) { - Ok(size) if size.ws_col > 0 => usize::from(size.ws_col), - _ => usize::try_from(FALLBACK_COLUMNS).unwrap_or(80), - } -} - -/// Without the console API, the fallback width. -#[cfg(not(unix))] -pub(crate) fn stderr_columns() -> usize { - usize::try_from(FALLBACK_COLUMNS).unwrap_or(80) +/// Whether a live `sqb dev` screen is coloured: `NO_COLOR` turns colour off and nothing else. +pub(crate) fn screen_colour(live: bool) -> bool { + live && std::env::var_os(NO_COLOR_VARIABLE).is_none() } /// A child interpreter now writes to this terminal; later writes clear its spinner line first. diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/dev_cancel.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/dev_cancel.rs new file mode 100644 index 0000000000..3c4255d8ec --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/dev_cancel.rs @@ -0,0 +1,154 @@ +//! A stop with runs in flight cancels them first, through the workers' own SIGTERM path, so each ends Cancelled with its statements cancelled and its claims released. + +use std::time::Instant; + +use sqlbuild_orchestration::credentials::models::AuditContext; +use sqlbuild_orchestration::runs::main::execution::change_run::change_run; +use sqlbuild_orchestration::runs::main::execution::observe_run::observe_run; +use sqlbuild_orchestration::runs::main::listings::list_runs::list_runs; +use sqlbuild_orchestration::runs::models::{ + RunAuthority, RunChange, RunChangeRequest, RunKind, RunRecord, RunStatus, +}; +use sqlbuild_orchestration::store::models::ControlStore; +use tokio::sync::mpsc::UnboundedSender; +use uuid::Uuid; + +use crate::dev_screen::models::ScreenMessage; +use crate::dev_stop::constants::{ + CANCEL_DEADLINE, CANCEL_POLL, CANCEL_REASON, DEV_ACTOR, DEV_GRANTING_ROLE, RUN_SCAN, + STOP_DEADLINE, STOP_GRACE, +}; +use crate::dev_stop::main::stop_switch::stop_switch; + +/// The dev target whose runs a stop cancels. +pub(crate) struct DevRuns { + pub(crate) store: ControlStore, + pub(crate) location_id: Uuid, + pub(crate) target: String, +} + +/// A run being cancelled: its ID, its name on the screen and how many of its nodes were running. +struct Cancelling { + run_id: Uuid, + name: String, + running: i64, +} + +/// Ask every executing run to cancel, then wait for each to end; reading the runs counts against the same `CANCEL_DEADLINE`. Whatever is left is killed, and the rest of the stop gets the usual deadline. +pub(crate) async fn cancel_active_runs(runs: &DevRuns, messages: &UnboundedSender) { + stop_switch().arm(CANCEL_DEADLINE + STOP_GRACE + STOP_DEADLINE); + let began: Instant = Instant::now(); + let active: Vec = + match list_runs(&runs.store, (runs.location_id, &runs.target), RUN_SCAN).await { + Ok(records) => records.into_iter().filter(executing).collect(), + Err(error) => { + drop(messages.send(ScreenMessage::Log(format!( + "could not read the runs to cancel: {error}" + )))); + Vec::new() + } + }; + if active.is_empty() { + stop_switch().arm(STOP_GRACE + STOP_DEADLINE); + return; + } + let context: AuditContext = AuditContext { + actor: DEV_ACTOR.to_owned(), + granting_role: DEV_GRANTING_ROLE.to_owned(), + request_id: Uuid::now_v7(), + ip_address: None, + }; + let mut pending: Vec = Vec::new(); + for run in active { + let cancelling: Cancelling = Cancelling { + run_id: run.run_id, + name: run.job_key.clone().unwrap_or_else(|| "ad hoc".to_owned()), + running: run.node_counts_json.get("running").copied().unwrap_or(0), + }; + drop(messages.send(ScreenMessage::Cancelling { + label: format!( + "Cancelling run {}\u{2026} {} (Ctrl+C again to force)", + cancelling.name, + running_nodes(cancelling.running) + ), + })); + let requested = change_run( + &runs.store, + RunAuthority::Operator(&context), + &RunChangeRequest { + event_id: Uuid::now_v7(), + run_id: run.run_id, + claim_id: None, + change: RunChange::CancelRequested { + actor: context.actor.clone(), + reason: CANCEL_REASON.to_owned(), + }, + }, + ) + .await; + if let Err(error) = requested { + drop(messages.send(ScreenMessage::Log(format!( + "could not cancel run {}: {error}", + cancelling.name + )))); + } + pending.push(cancelling); + } + while !pending.is_empty() && began.elapsed() < CANCEL_DEADLINE { + tokio::time::sleep(CANCEL_POLL).await; + let mut left: Vec = Vec::new(); + for run in pending { + match observe_run(&runs.store, run.run_id).await { + Ok(state) if !open(state.status) => { + drop(messages.send(ScreenMessage::Stopped { + label: cancelled_line(&run), + elapsed: began.elapsed(), + })); + } + Ok(_) | Err(_) => left.push(run), + } + } + pending = left; + } + if !pending.is_empty() { + stop_switch().kill_all(); + } + stop_switch().arm(STOP_GRACE + STOP_DEADLINE); +} + +/// A run a worker is executing; queued runs stay queued, and a group ends with its members. +fn executing(run: &RunRecord) -> bool { + run.kind != RunKind::Group + && matches!( + run.status, + RunStatus::Launched | RunStatus::Running | RunStatus::Unresponsive + ) +} + +/// Whether a run has not ended yet. +fn open(status: RunStatus) -> bool { + matches!( + status, + RunStatus::Queued | RunStatus::Launched | RunStatus::Running | RunStatus::Unresponsive + ) +} + +/// `1 running node` or `N running nodes`. +fn running_nodes(count: i64) -> String { + match count { + 1 => "1 running node".to_owned(), + count => format!("{count} running nodes"), + } +} + +/// `Cancelled run orders_job 2 running nodes cancelled`, naming nodes only when some were running. +fn cancelled_line(run: &Cancelling) -> String { + match run.running { + 0 => format!("Cancelled run {}", run.name), + running => format!( + "Cancelled run {} {} cancelled", + run.name, + running_nodes(running) + ), + } +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/dev_start.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/dev_start.rs new file mode 100644 index 0000000000..ab0924cbc1 --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/dev_start.rs @@ -0,0 +1,248 @@ +//! Read `sqb dev`'s configuration and start its roles step by step, each stoppable, and the result line its end leaves. + +use std::net::SocketAddr; +use std::path::PathBuf; +use std::time::Instant; + +use sqlbuild_core::screen_text::models::{Problem, ProblemLevel, ResultLine}; +use sqlbuild_orchestration::api::models::DevelopmentScope; +use sqlbuild_orchestration::store::errors::ControlError; +use sqlbuild_orchestration::store::models::ControlStore; +use tokio::net::TcpListener; +use tokio::sync::mpsc::UnboundedSender; + +use crate::argv::models::Namespace; +use crate::dev_screen::models::{DevStep, ScreenEnd, ScreenMessage}; +use crate::dev_screen::types::DevScreenParts; +use crate::dev_stop::constants::{RUN_FAILURE_STATUS, START_FAILURE_STATUS}; +use crate::dev_stop::main::stop_switch::stop_switch; +use crate::dev_stop::models::{DevEnd, StopReason}; +use crate::native_commands::_helpers::command::decision::flag; +use crate::native_commands::_helpers::command::project_facts::development_config; +use crate::native_commands::_helpers::location::execution::{ + announced_store, loopback_address, run_development_roles, +}; + +/// Open the store and the port, each a step that can fail, then run every role; a stop before then ends it cleanly. +pub(crate) async fn start_roles( + namespace: &Namespace, + (project, target): (PathBuf, String), + (messages, actions, keys): DevScreenParts, +) -> DevEnd { + let opened = tokio::select! { + opened = open_services(namespace, (&project, &target), &messages) => opened, + reason = stop_switch().requested() => return DevEnd::Stopped(reason), + }; + let ((store, scope), listener, executable) = match opened { + Ok(opened) => opened, + Err(end) => return end, + }; + match run_development_roles( + (store, scope), + (project, executable), + listener, + ( + !flag(namespace, "control_no_scheduler"), + (messages.clone(), actions, keys), + ), + ) + .await + { + Ok(end) => end, + Err(error) => DevEnd::NotStarted { + reason: message(error), + explained: false, + next: Vec::new(), + }, + } +} + +/// The announced store, the bound port and the `sqb` executable, or how starting them failed. +async fn open_services( + namespace: &Namespace, + (project, target): (&PathBuf, &String), + messages: &UnboundedSender, +) -> Result<((ControlStore, DevelopmentScope), TcpListener, PathBuf), DevEnd> { + let not_started = |step: DevStep, title: &str, (why, fix): (String, &str)| { + drop(messages.send(ScreenMessage::Failed { + step, + detail: "failed".to_owned(), + problem: Problem { + level: ProblemLevel::Error, + title: title.to_owned(), + code: String::new(), + at: Vec::new(), + why: why.clone(), + fix: fix.to_owned(), + }, + })); + DevEnd::NotStarted { + reason: format!("could not {title_verb}", title_verb = verb(step)), + explained: true, + next: Vec::new(), + } + }; + let address: SocketAddr = match loopback_address(namespace) { + Ok(address) => address, + Err(error) => { + return Err(not_started( + DevStep::Api, + "UI server address", + (message(error), "pass --port with a free port on 127.0.0.1"), + )); + } + }; + let executable: PathBuf = match std::env::current_exe() { + Ok(executable) => executable, + Err(error) => { + return Err(DevEnd::NotStarted { + reason: format!("could not find the sqb executable: {error}"), + explained: false, + next: Vec::new(), + }); + } + }; + let (store, scope) = match announced_store(namespace, (project, target), messages).await { + Ok(opened) => opened, + Err(error) => { + return Err(not_started( + DevStep::ControlStore, + "control store", + ( + message(error), + "check --control-store-url, or remove .sqlbuild/control.sqlite3 if it is damaged", + ), + )); + } + }; + let listener = match tokio::net::TcpListener::bind(address).await { + Ok(listener) => listener, + Err(error) => { + return Err(not_started( + DevStep::Api, + "UI server", + ( + format!("could not listen on {address}: {error}"), + "stop whatever uses the port, or pick another with --port (0 picks a free one)", + ), + )); + } + }; + Ok(((store, scope), listener, executable)) +} + +/// What a failed step could not do, for the result line. +fn verb(step: DevStep) -> &'static str { + match step { + DevStep::ControlStore => "open the control store", + DevStep::Api => "start the UI server", + _ => "start", + } +} + +/// A control error's own words, without the category prefix. +fn message(error: ControlError) -> String { + match error { + ControlError::Invalid(message) => message, + error => error.to_string(), + } +} + +/// The exit status and result line for how the session ended; a stop before the services were ready says so. +pub(crate) fn result_line(end: &DevEnd, started: Instant) -> (i32, ResultLine) { + match end { + DevEnd::Stopped(reason) => ( + reason.status(), + ResultLine { + failed: false, + title: format!( + "sqb dev stopped{}{}", + reason.note(), + if stop_switch().is_ready() { + "" + } else { + " before it was ready" + } + ), + detail: format!("ran {}", ran(started)), + elapsed: stop_switch().stopping_for(), + next: Vec::new(), + }, + ), + DevEnd::NotStarted { reason, next, .. } => ( + START_FAILURE_STATUS, + ResultLine { + failed: true, + title: "sqb dev did not start".to_owned(), + detail: reason.clone(), + elapsed: Some(started.elapsed()), + next: next.clone(), + }, + ), + DevEnd::Failed { reason } => ( + RUN_FAILURE_STATUS, + ResultLine { + failed: true, + title: "sqb dev stopped".to_owned(), + detail: reason.clone(), + elapsed: None, + next: Vec::new(), + }, + ), + } +} + +/// How long the session ran, as `42m 10s`. +fn ran(started: Instant) -> String { + let seconds: u64 = started.elapsed().as_secs(); + match seconds { + 0..60 => format!("{seconds}s"), + 60..3600 => format!("{}m {:02}s", seconds / 60, seconds % 60), + _ => format!("{}h {:02}m", seconds / 3600, (seconds % 3600) / 60), + } +} + +/// The session has ended cleanly: no forced stop follows. Leave its result line, with the newest log lines when the screen did not explain a failure, and put the terminal back; its exit status. +pub(crate) async fn finish_session( + end: &DevEnd, + started: Instant, + (finish, task): ( + tokio::sync::oneshot::Sender, + tokio::task::JoinHandle<()>, + ), +) -> i32 { + stop_switch().disarm(); + let (status, result): (i32, ResultLine) = result_line(end, started); + let show_log: bool = matches!( + end, + DevEnd::NotStarted { + explained: false, + .. + } + ) || matches!(end, DevEnd::Failed { .. }); + drop(finish.send(ScreenEnd { result, show_log })); + drop(task.await); + stop_switch().kill_all(); + stop_switch().restore_terminal(); + status +} + +/// The development target and adapter, read off the runtime's threads so a stop meanwhile is seen at once. +pub(crate) async fn load_config( + project: &std::path::Path, + selected: Option, +) -> Result>, StopReason> { + let project: PathBuf = project.to_path_buf(); + let loading = tokio::task::spawn_blocking(move || development_config(&project, selected)); + tokio::select! { + loaded = loading => Ok(loaded.unwrap_or_else(|error| Err(Box::new(Problem { + level: ProblemLevel::Error, + title: "sqb dev configuration".to_owned(), + code: String::new(), + at: Vec::new(), + why: error.to_string(), + fix: String::new(), + })))), + reason = stop_switch().requested() => Err(reason), + } +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/dev_supervision.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/dev_supervision.rs new file mode 100644 index 0000000000..742713572b --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/dev_supervision.rs @@ -0,0 +1,117 @@ +//! Stop the development roles together within a grace period, one line per service, and say how the session ended; a stop with runs in flight cancels them first. + +use std::collections::HashMap; +use std::future::Future; + +use sqlbuild_orchestration::store::errors::ControlError; +use tokio::sync::mpsc::UnboundedSender; +use tokio::sync::watch; +use tokio::task::{Id, JoinError, JoinSet}; +use tokio::time::Instant; + +use crate::dev_screen::models::ScreenMessage; +use crate::dev_session::constants::WAREHOUSE_FAILED; +use crate::dev_stop::constants::{ABORT_WAIT, STOP_GRACE}; +use crate::dev_stop::main::stop_switch::stop_switch; +use crate::dev_stop::models::DevEnd; +use crate::native_commands::_helpers::location::dev_cancel::{DevRuns, cancel_active_runs}; + +/// A role's end as `JoinSet::join_next_with_id` reports it; `None` when no role was left. +type RoleEnd = Option), JoinError>>; + +/// The development roles, the name each stop line gives them, and the runs a stop cancels while the scheduler runs. +#[derive(Default)] +pub(crate) struct DevRoles { + pub(crate) tasks: JoinSet>, + labels: HashMap, + pub(crate) runs: Option, +} + +impl DevRoles { + /// Run `role`; a `label` such as `UI server` gives it a `Stopped UI server` line. + pub(crate) fn spawn( + &mut self, + label: Option<&'static str>, + role: impl Future> + Send + 'static, + ) { + let id: Id = self.tasks.spawn(role).id(); + if let Some(label) = label { + self.labels.insert(id, label); + } + } +} + +/// Wait for a stop request or a role to end; a requested stop, or a service failing after ready, cancels the runs in flight first. Then stop every role: each gets the grace period, then its processes are killed and the rest aborted. +pub(crate) async fn supervise_development_roles( + mut roles: DevRoles, + stop: watch::Sender, + messages: &UnboundedSender, +) -> DevEnd { + let end: DevEnd = tokio::select! { + joined = roles.tasks.join_next_with_id() => role_ended(joined, &roles.labels), + reason = stop_switch().requested() => DevEnd::Stopped(reason), + }; + drop(messages.send(ScreenMessage::Stopping)); + if let (DevEnd::Stopped(_) | DevEnd::Failed { .. }, Some(runs)) = (&end, &roles.runs) { + cancel_active_runs(runs, messages).await; + } + stop.send_replace(true); + stop_switch().terminate_groups(); + let began: Instant = Instant::now(); + loop { + match tokio::time::timeout_at(began + STOP_GRACE, roles.tasks.join_next_with_id()).await { + Ok(Some(joined)) => { + if let Ok((id, _)) = &joined + && let Some(label) = roles.labels.get(id) + { + drop(messages.send(ScreenMessage::Stopped { + label: format!("Stopped {label}"), + elapsed: began.elapsed(), + })); + } + } + Ok(None) => break, + Err(_) => { + stop_switch().kill_all(); + roles.tasks.abort_all(); + while let Ok(Some(_)) = + tokio::time::timeout(ABORT_WAIT, roles.tasks.join_next()).await + { + } + break; + } + } + } + end +} + +/// Why the session ends when a role ended by itself: before ready it did not start, after it failed. +fn role_ended(joined: RoleEnd, labels: &HashMap) -> DevEnd { + let reason: String = match joined { + None => "every service stopped".to_owned(), + Some(Ok((id, Ok(())))) => format!( + "the {} stopped unexpectedly", + labels.get(&id).copied().unwrap_or("platform maintenance") + ), + Some(Ok((_, Err(ControlError::Invalid(message))))) => message, + Some(Ok((_, Err(error)))) => error.to_string(), + Some(Err(error)) => format!("a service crashed: {error}"), + }; + if stop_switch().is_ready() { + return DevEnd::Failed { reason }; + } + let explained: bool = reason == WAREHOUSE_FAILED; + let next: Vec<(String, String)> = if explained { + vec![( + "sqb debug".to_owned(), + "test the connection on its own".to_owned(), + )] + } else { + Vec::new() + }; + DevEnd::NotStarted { + reason, + explained, + next, + } +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/dynamic_resume.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/dynamic_resume.rs new file mode 100644 index 0000000000..3890a69b17 --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/dynamic_resume.rs @@ -0,0 +1,122 @@ +//! A completed synchronization resumes the dynamic models whose pausing builds stopped heartbeating. + +use std::time::Duration; + +use sqlbuild_core::constants::DYNAMIC_RESUME_SECONDS; +use sqlbuild_orchestration::warehouse_metadata::constants::DYNAMIC_RESUME_REQUEST; +use sqlbuild_orchestration::warehouse_metadata::models::{ + DynamicResumeLocation, DynamicResumeReply, +}; +use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt}; + +use crate::argv::models::Stream; +use crate::native_commands::_helpers::command::terminal::write_output; +use crate::native_commands::_helpers::location::execution::location_warning; +use crate::native_commands::constants::METADATA_REPLY_BYTES; +use crate::native_commands::models::{LocationCompiler, LocationMetadataSync}; + +/// Ask the reader to resume expired holds, sending each location's quiet token; a failure only warns. +pub(crate) async fn resume_expired_holds(mut state: LocationMetadataSync) -> LocationMetadataSync { + if state.halted { + return state; + } + let Some(reader) = state.reader.take() else { + return state; + }; + let locations: Vec = state + .locations + .iter() + .chain( + state + .dynamic_quiet_tokens + .keys() + .filter(|location| !state.locations.contains(location)), + ) + .map(|location| DynamicResumeLocation { + location: location.clone(), + quiet_token: state.dynamic_quiet_tokens.get(location).cloned(), + }) + .collect(); + let request = serde_json::json!({ DYNAMIC_RESUME_REQUEST: locations }).to_string(); + let reason = match tokio::time::timeout( + Duration::from_secs(DYNAMIC_RESUME_SECONDS), + exchange(reader, request), + ) + .await + { + Ok((reader, Ok(DynamicResumeReply::Resumed(resumed)))) => { + state.reader = Some(reader); + state.dynamic_quiet_tokens = resumed + .quiet_tokens + .into_iter() + .filter_map(|resume| Some((resume.location, resume.quiet_token?))) + .collect(); + for failure in &resumed.failures { + drop(write_output(&[( + Stream::Stderr, + &format!("Resuming an expired dynamic hold failed: {failure}\n"), + )])); + } + for hold in resumed.holds { + drop(write_output(&[( + Stream::Stderr, + &format!( + "Resumed dynamic model {}: run {} stopped heartbeating.\n", + hold.relation, hold.run_id + ), + )])); + } + return state; + } + Ok((reader, Ok(DynamicResumeReply::Failed(reason)))) => { + state.reader = Some(reader); + reason + } + Ok((reader, Err(reason))) => { + state.reader = Some(reader); + drop(write_output(&[( + Stream::Stderr, + &format!("Resuming expired dynamic holds failed: {reason}\n"), + )])); + reason + } + Err(_) => { + let reason = format!("no reply in {DYNAMIC_RESUME_SECONDS} s"); + drop(write_output(&[( + Stream::Stderr, + &format!("Resuming expired dynamic holds failed: {reason}\n"), + )])); + reason + } + }; + location_warning("dynamic resume failed", reason); + state +} + +/// One request line and its bounded reply line, handing the reader back. +async fn exchange( + mut reader: LocationCompiler, + request: String, +) -> (LocationCompiler, Result) { + let reply: Result = async { + let fail = |error: std::io::Error| error.to_string(); + reader + .stdin + .write_all(format!("{request}\n").as_bytes()) + .await + .map_err(fail)?; + reader.stdin.flush().await.map_err(fail)?; + let mut line = String::new(); + let read = (&mut reader.stdout) + .take(METADATA_REPLY_BYTES + 1) + .read_line(&mut line) + .await + .map_err(fail)?; + if read == 0 { + return Err("location runtime exited before replying".into()); + } + serde_json::from_str(&line).map_err(|_| "invalid location reply".to_owned()) + } + .await; + (reader, reply) +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/env_reload.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/env_reload.rs new file mode 100644 index 0000000000..960a383530 --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/env_reload.rs @@ -0,0 +1,81 @@ +//! `sqb dev` re-reads the project env file before each publication, so `r` picks up an edit. + +use sqlbuild_core::process_environment::main::project_relative_path::project_relative_path; +use std::path::Path; + +use sqlbuild_config::env_file::main::load_env_file::load_env_file; +use sqlbuild_core::process_environment::constants::ENV_FILE_MARKER_VARIABLE; +use sqlbuild_core::process_environment::main::env_file_marker::env_file_marker; +use sqlbuild_core::process_environment::main::environment_var_os::environment_var_os; +use sqlbuild_core::process_environment::main::install_environment_overlay::install_environment_overlay; +use sqlbuild_core::process_environment::models::EnvironmentOverlay; + +use crate::native_commands::_helpers::location::execution::location_warning; +use crate::native_commands::models::LocationServe; + +/// Between the parts of a ready card value. +const SEPARATOR: &str = " \u{b7} "; + +/// Whether `overlay` changes any variable this process now sees, the marker aside. +fn changes_values(overlay: &EnvironmentOverlay) -> bool { + overlay + .set + .iter() + .filter(|(name, _)| name != ENV_FILE_MARKER_VARIABLE) + .any(|(name, value)| environment_var_os(name).as_ref() != Some(value)) + || overlay + .remove + .iter() + .any(|name| environment_var_os(name).is_some()) +} + +/// Re-read the env file under `sqb dev`, keeping the last good read with a warning; `true` means restart the interpreter. +pub(crate) fn reload_env_file(options: &LocationServe) -> bool { + if !options.dev_events { + return false; + } + match load_env_file(&options.project_dir, Some(&options.target)) { + Ok(Some(load)) => { + let changed: bool = changes_values(&load.overlay); + if changed { + install_environment_overlay(load.overlay); + } + changed + } + Ok(None) => false, + Err(error) => { + location_warning( + "env file not reloaded", + format!("{}; runs fail until it is fixed", error.message()), + ); + false + } + } +} + +/// The ready card's env file row: the file, how many variables it set, and how to reload it. +pub(crate) fn env_file_summary(project: &Path) -> Option { + let marker = env_file_marker()?; + let Some(path) = marker.path else { + return Some("off (env_file = \"\")".to_owned()); + }; + let shown: String = project_relative_path(project, Path::new(&path)); + if !marker.loaded { + return Some(format!( + "{shown} not found{SEPARATOR}create it, then press r to load it" + )); + } + let count: usize = marker.names.len(); + let mut text: String = format!( + "{shown}{SEPARATOR}{count} variable{}", + if count == 1 { "" } else { "s" } + ); + if !marker.overridden.is_empty() { + text.push_str(&format!( + " ({} already set in the environment)", + marker.overridden.len() + )); + } + text.push_str(&format!("{SEPARATOR}edit it, then press r to reload")); + Some(text) +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/execution.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/execution.rs index 5252ad6ac4..1eae0370af 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/location/execution.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/execution.rs @@ -8,11 +8,14 @@ use crate::compute_logs::main::finish_capture::finish_capture; use crate::compute_logs::main::open_log_root::open_log_root; use crate::compute_logs::main::start_capture::start_capture; use crate::compute_logs::models::{CaptureEnd, CaptureStart, OpenCapture}; +use crate::dev_screen::main::terminal_size::terminal_size; use crate::dev_screen::models::ScreenSetup; use crate::dev_screen::models::{DevStep, ScreenMessage}; use crate::dev_screen::types::DevScreenParts; use crate::dev_session::main::run_dev_session::run_dev_session; use crate::dev_session::models::{DevProject, LocationPipes}; +use crate::dev_stop::main::stop_switch::stop_switch; +use crate::dev_stop::models::DevEnd; use crate::native_commands::_helpers::command::decision::{ control_address, control_database, control_database_variable, flag, text, }; @@ -22,7 +25,7 @@ use crate::native_commands::_helpers::command::paths::exclude_location_databases use crate::native_commands::_helpers::command::paths::{location_database_files, project_location}; use crate::native_commands::_helpers::command::project_facts::has_no_runtime_extensions; use crate::native_commands::_helpers::command::project_facts::{ - development_project_name, project_directory_name, project_name, + development_project_name, project_name, }; use crate::native_commands::_helpers::command::rules::run_rules; use crate::native_commands::_helpers::command::skills::{run_skills, skill_freshness_notice}; @@ -30,14 +33,20 @@ use crate::native_commands::_helpers::command::terminal::share_terminal; use crate::native_commands::_helpers::command::terminal::{ finish_lost_stdout, terminal_columns, write_output, }; -use crate::native_commands::_helpers::command::terminal::{live_screen, stderr_columns}; +use crate::native_commands::_helpers::command::terminal::{live_screen, screen_colour}; +use crate::native_commands::_helpers::location::dev_cancel::DevRuns; +use crate::native_commands::_helpers::location::dev_supervision::{ + DevRoles, supervise_development_roles, +}; +use crate::native_commands::_helpers::location::dynamic_resume::resume_expired_holds; +use crate::native_commands::_helpers::location::env_reload::env_file_summary; +use crate::native_commands::_helpers::location::provider_secrets::report_provider_secrets; use crate::native_commands::_helpers::location::sync_report::{ metadata_health, read_timeout_seconds, rows_text, scan_line, }; use crate::native_commands::constants::PLAN_NOT_PRODUCED; -use crate::native_commands::constants::SCREEN_INDENT; use crate::native_commands::constants::{ - ADMIN_COMMAND, CHANGED_PATHS_SHOWN, COLUMNS_VARIABLE, FALLBACK_COLUMNS, + ADMIN_COMMAND, CHANGED_PATHS_SHOWN, COLUMNS_VARIABLE, FALLBACK_COLUMNS, FALLBACK_ROWS, METADATA_OVERLAP_SECONDS, METADATA_POLL_SECONDS, METADATA_READER_CLOSE_SECONDS, METADATA_RECONCILE_SECONDS, METADATA_REPLY_BYTES, METADATA_SAFETY_SYNC_SECONDS, METADATA_SYNC_CHECK_SECONDS, SAFETY_SYNC_ENV, SCHEDULER_COMMAND, UNCAUGHT_EXCEPTION_STATUS, @@ -71,6 +80,8 @@ use sqlbuild_config::project::main::project_config_paths::project_config_paths; use sqlbuild_config::project::main::sync_interval_seconds::sync_interval_seconds; use sqlbuild_config::project::models::ControlConfig; use sqlbuild_core::cli_text::models::CliStyle; +use sqlbuild_core::process_environment::constants::RUN_TOKEN_VARIABLE; +use sqlbuild_core::process_environment::main::apply_environment_overlay::apply_environment_overlay; use sqlbuild_core::redaction::main::redact_error_text::redact_error_text; use sqlbuild_core::screen_text::models::{DevHeader, ScreenFacts}; use sqlbuild_orchestration::api::constants::BODY_BYTES; @@ -95,6 +106,7 @@ use sqlbuild_orchestration::platform::main::health::report_remote_location_healt use sqlbuild_orchestration::platform::main::installation::run_maintenance::run_maintenance; use sqlbuild_orchestration::platform::models::ConnectionCheckTrigger; use sqlbuild_orchestration::platform::models::LocationRuleFailure; +use sqlbuild_orchestration::platform::models::PublishedGeneration; use sqlbuild_orchestration::platform::models::{ LocationHealth, LocationHealthReport, LocationWorkClient, LocationWorkPoll, RetentionPolicies, WarehouseSyncFailure, @@ -135,13 +147,13 @@ use tokio::task::JoinSet; use tokio::time::{Instant, Interval, MissedTickBehavior}; use uuid::Uuid; -/// Own the API, scheduler and outbound location as one development process tree, drawn by `screen`. +/// Own the API, scheduler and outbound location as one development process tree, drawn by `screen`, until a stop or a role ends it. pub(crate) async fn run_development_roles( (store, scope): (ControlStore, DevelopmentScope), (project, executable): (PathBuf, PathBuf), listener: tokio::net::TcpListener, (scheduler, (messages, actions, keys)): (bool, DevScreenParts), -) -> Result<(), ControlError> { +) -> Result { let address = listener.local_addr()?; let url = format!("http://{address}"); let location_id = scope.location_id; @@ -153,79 +165,98 @@ pub(crate) async fn run_development_roles( url.clone(), )?; let (stop, shutdown) = watch::channel(false); - let mut tasks = JoinSet::new(); + let mut roles: DevRoles = DevRoles::default(); drop(messages.send(ScreenMessage::Started { step: DevStep::Api, detail: String::new(), })); let api_ready = messages.clone(); - tasks.spawn(serve_api( - store.clone(), - listener, - ( - ApiAuthentication { - login: HumanLogin::Development(scope), - ..ApiAuthentication::default() - }, - (Vec::new(), adhoc_planner()), - ServerFacts { - version: env!("CARGO_PKG_VERSION").into(), - scheduler, - ..ServerFacts::default() - }, - ), - ( - move || { - drop(api_ready.send(ScreenMessage::Finished { - step: DevStep::Api, - detail: address.to_string(), - })); - }, - development_stopped(shutdown.clone()), + roles.spawn( + Some("UI server"), + serve_api( + store.clone(), + listener, + ( + ApiAuthentication { + login: HumanLogin::Development(scope), + ..ApiAuthentication::default() + }, + (Vec::new(), adhoc_planner()), + ServerFacts { + version: env!("CARGO_PKG_VERSION").into(), + scheduler, + ..ServerFacts::default() + }, + ), + ( + move || { + drop(api_ready.send(ScreenMessage::Finished { + step: DevStep::Api, + detail: address.to_string(), + })); + }, + development_stopped(shutdown.clone()), + ), ), - )); - start_platform_roles(&mut tasks, (&store, &shutdown), Default::default())?; + ); + start_platform_roles(&mut roles.tasks, (&store, &shutdown), Default::default())?; let (location, pipes) = development_location_role( (&project, &executable), (location_id, &target), (&url, &store), shutdown.clone(), )?; - tasks.spawn(location); - tasks.spawn(run_dev_session( - (messages.clone(), actions, keys), - ( - pipes, - DevProject { - executable: executable.clone(), - project: project.clone(), - target: target.clone(), - }, + roles.spawn(Some("code location"), location); + roles.spawn( + None, + run_dev_session( + (messages.clone(), actions, keys), + ( + pipes, + DevProject { + executable: executable.clone(), + project: project.clone(), + target: target.clone(), + }, + ), + (store.clone(), location_id, url.clone()), + shutdown.clone(), ), - (store.clone(), location_id, url), - shutdown.clone(), - )); + ); drop(messages.send(ScreenMessage::Started { step: DevStep::Scheduler, detail: String::new(), })); if scheduler { + roles.runs = Some(DevRuns { + store: store.clone(), + location_id, + target: target.clone(), + }); let scheduler_store = store.clone(); - tasks.spawn(async move { + let origin = Some(url.clone()); + roles.spawn(Some("scheduler"), async move { run_scheduler( &scheduler_store, - SchedulerState::new(Uuid::now_v7()), + SchedulerState::new(Uuid::now_v7()).with_origin(origin), shutdown, workers, ) .await }); } - drop(messages.send(ScreenMessage::Finished { - step: DevStep::Scheduler, - detail: if scheduler { "started" } else { "off" }.to_owned(), - })); - supervise_control_roles(tasks, stop).await + drop( + messages.send(ScreenMessage::Finished { + step: DevStep::Scheduler, + detail: if scheduler { + "triggers start paused" + } else { + "off (--no-scheduler)" + } + .to_owned(), + }), + ); + Ok(supervise_development_roles(roles, stop, &messages).await) } async fn development_stopped(mut shutdown: watch::Receiver) { @@ -250,6 +281,7 @@ fn development_location_role( ControlError, > { let mut command = Command::new(executable); + apply_environment_overlay(command.as_std_mut()); command .args(["--project-dir"]) .arg(project) @@ -267,13 +299,15 @@ fn development_location_role( .env_remove("SQLBUILD_CONTROL_DATABASE_URL") .env_remove("SQLBUILD_PLATFORM_WEBHOOK_URL") .env_remove(SECURITY_AUDIT_WEBHOOK_VARIABLE) - .env_remove("SQLBUILD_RUN_TOKEN") + .env_remove(RUN_TOKEN_VARIABLE) .env_remove("SQLBUILD_DEVELOPMENT_CONTROL_FILE") .env(DEV_EVENTS_VARIABLE, DEV_EVENTS_ON) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .kill_on_drop(true); + #[cfg(unix)] + command.process_group(0); if let ControlStore::Sqlite(path) = store { command.env( "SQLBUILD_DEVELOPMENT_CONTROL_FILE", @@ -281,6 +315,10 @@ fn development_location_role( ); } let mut child = command.spawn()?; + let group: Option = child.id(); + if let Some(group) = group { + stop_switch().register_group(group); + } let (Some(stdin), Some(stdout), Some(stderr)) = (child.stdin.take(), child.stdout.take(), child.stderr.take()) else { @@ -295,20 +333,25 @@ fn development_location_role( }; Ok(( async move { - tokio::select! { + let ended: Result<(), ControlError> = tokio::select! { result = child.wait() => { - result?; - Err(ControlError::Invalid("development code location stopped unexpectedly".into())) + let status = result?; + Err(ControlError::Invalid(format!("the code location stopped unexpectedly ({status})"))) }, () = development_stopped(shutdown) => { - terminate_child(&mut child)?; + stop_switch().terminate_groups(); + terminate_child(&mut child, false)?; match tokio::time::timeout(Duration::from_secs(10), child.wait()).await { Ok(result) => { result?; }, Err(_) => child.kill().await?, } Ok(()) }, + }; + if let Some(group) = group { + stop_switch().forget_group(group); } + ended }, pipes, )) @@ -355,7 +398,13 @@ pub(crate) async fn compile_generation( } } }; - let Some((record, refresh, locations)) = load.published else { + let Some(PublishedGeneration { + record, + refresh_at: refresh, + state_locations: locations, + missing_secrets, + }) = load.published + else { if let Some(rules) = &load.rules { dev_failure(dev_events, generation, rule_failure_text(rules)); } @@ -382,7 +431,7 @@ pub(crate) async fn compile_generation( record.snapshot_id ))); } - Ok(Some(Ok((refresh_at, locations)))) + Ok(Some(Ok((refresh_at, locations, missing_secrets)))) } /// Under `sqb dev`, tell the screen a generation failed; the last good generation keeps serving. @@ -394,6 +443,8 @@ fn dev_failure(dev_events: bool, generation: i64, message: String) { generation, position: None, message, + code: None, + help: None, }), )])); } @@ -512,6 +563,7 @@ pub(crate) fn metadata_sync( state_history_versions: None, progress: SyncProgress::new(), reads_wake_compute: false, + dynamic_quiet_tokens: std::collections::BTreeMap::new(), } } @@ -956,7 +1008,7 @@ pub(crate) async fn check_published_location( )])); tokio::pin!(stopped); let started = Instant::now(); - let Some((connected, (missing, wakes_compute), files)) = + let Some((connected, wakes_compute, files)) = check_location_connection((options, script, connect), stopped.as_mut()).await? else { return Ok(None); @@ -971,22 +1023,6 @@ pub(crate) async fn check_published_location( result = &mut stopped => { result?; return Ok(None); }, () = report_location_health(options, bearer, session_id, health) => {}, } - tokio::select! { - result = &mut stopped => { result?; return Ok(None); }, - () = report_location_health(options, bearer, session_id, LocationHealth::ProviderSecrets { generation, missing }) => {}, - } - if missing > 0 { - drop(write_output(&[( - Stream::Stderr, - &format!( - "{missing} provider secret(s) are unset in this location's environment; runs that use them fail. Run sqb debug for the list.\n" - ), - )])); - location_warning( - "provider secrets unset", - format!("{missing} unset; runs that use them fail; sqb debug lists them"), - ); - } drop(write_output(&[( Stream::Stderr, if connected { @@ -998,11 +1034,11 @@ pub(crate) async fn check_published_location( Ok(Some((files, wakes_compute))) } -/// Capture the debug check's local file paths, missing secret count and whether history reads wake billed compute; under `sqb dev` it never connects, so nobody signs in twice. +/// Capture the debug check's local file paths and whether history reads wake billed compute; under `sqb dev` it never connects, so nobody signs in twice. pub(crate) async fn check_location_connection( (options, script, connect): (&LocationServe, &Path, bool), stopped: impl Future>, -) -> Result)>, ControlError> { +) -> Result)>, ControlError> { let mut command = location_child(options, script); command.args(["debug", "--target", &options.target, "--json"]); if !connect || options.dev_events { @@ -1023,13 +1059,12 @@ pub(crate) async fn check_location_connection( }, result = async { tokio::try_join!(child.wait(), stdout.read_to_end(&mut output)) } => result?.0.success(), }; - let (files, missing, wakes_compute): (Vec, u64, bool) = match serde_json::from_slice::< + let (files, wakes_compute): (Vec, bool) = match serde_json::from_slice::< serde_json::Value, >(&output) .and_then(|report| { Ok(( serde_json::from_value(report["local_files"].clone())?, - report["missing_secrets"].as_u64().unwrap_or_default(), report["history_reads_wake_compute"] .as_bool() .unwrap_or_default(), @@ -1041,18 +1076,19 @@ pub(crate) async fn check_location_connection( Stream::Stderr, "Location connection check did not produce a valid report; retaining the published snapshot.\n", )])); - return Ok(Some((false, (0, false), Vec::new()))); + return Ok(Some((false, false, Vec::new()))); } }; Ok(Some(( connect && connected, - (missing, wakes_compute), + wakes_compute, location_database_files(&options.project_dir, files), ))) } pub(crate) fn location_child(options: &LocationServe, script: &Path) -> Command { let mut command = Command::new(script); + apply_environment_overlay(command.as_std_mut()); command.arg("--project-dir").arg(&options.project_dir); if terminal_columns().is_err() { command.env(COLUMNS_VARIABLE, FALLBACK_COLUMNS.to_string()); @@ -1180,43 +1216,6 @@ pub(crate) async fn open_control_workers( Ok((workers, (images, adhoc_planner()))) } -pub(crate) async fn shutdown_signal() -> Result<(), ControlError> { - #[cfg(unix)] - { - let mut terminate = - tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?; - tokio::select! { - result = tokio::signal::ctrl_c() => result?, - _ = terminate.recv() => {}, - } - } - #[cfg(not(unix))] - tokio::signal::ctrl_c().await?; - Ok(()) -} - -/// Stop sibling roles on a signal or role failure, then drain their shutdown results. -pub(crate) async fn supervise_control_roles( - mut tasks: JoinSet>, - stop: watch::Sender, -) -> Result<(), ControlError> { - let mut result = tokio::select! { - result = tasks.join_next() => match result { - Some(result) => result.map_err(ControlError::from).and_then(std::convert::identity), - None => Ok(()), - }, - result = shutdown_signal() => result, - }; - stop.send_replace(true); - while let Some(joined) = tasks.join_next().await { - let joined = joined - .map_err(ControlError::from) - .and_then(std::convert::identity); - result = result.and(joined); - } - result -} - /// The capture Python's `dispatch_with_compute_logs` opens; a failure only loses the log. fn open_capture( invocation: &NativeInvocation, @@ -1438,14 +1437,20 @@ pub(crate) async fn read_metadata_page( Ok(Some((state, read))) } -/// A completed synchronization closes its reader, so no warehouse session outlives the sync. +/// A completed synchronization resumes expired dynamic holds, then closes its reader, so no warehouse session outlives the sync. pub(crate) async fn finish_metadata_page( state: LocationMetadataSync, + stopped: impl Future>, ) -> Result, ControlError> { - if state.idle { - return Ok(Some(close_metadata_reader(state).await?)); + if !state.idle { + return Ok(Some(state)); } - Ok(Some(state)) + tokio::pin!(stopped); + let state: LocationMetadataSync = tokio::select! { + result = &mut stopped => { result?; return Ok(None); }, + state = resume_expired_holds(state) => state, + }; + Ok(Some(close_metadata_reader(state).await?)) } /// End of input lets the reader close its warehouse session; one that ignores it is killed. @@ -1541,7 +1546,7 @@ pub(crate) async fn next_turn( } } -/// `sqb dev`'s control lines from stdin; outside `sqb dev`, a fixed connected state. +/// `sqb dev`'s control lines from stdin; outside `sqb dev`, a fixed connected state. `sqb dev` holds stdin open while it lives, so its end, even after `sqb dev` was killed, stops the location as SIGTERM does. pub(crate) fn dev_controls(options: &LocationServe) -> watch::Receiver { let (sender, receiver) = watch::channel(DevControlState { warehouse: (!options.dev_events).then_some(true), @@ -1560,6 +1565,11 @@ pub(crate) fn dev_controls(options: &LocationServe) -> watch::Receiver {} } } + #[cfg(unix)] + let _ = rustix::process::kill_process( + rustix::process::getpid(), + rustix::process::Signal::TERM, + ); }); } receiver @@ -1636,13 +1646,16 @@ pub(crate) async fn settle_publication( stopped: impl Future>, ) -> Result, ControlError> { let (mut metadata, deferred) = if connect { - let sync: LocationMetadataSync = metadata_sync( + let mut sync: LocationMetadataSync = metadata_sync( (locations, generation), ( options.metadata_reconcile_seconds, options.safety_sync_seconds, ), ); + sync.dynamic_quiet_tokens = metadata + .map(|previous| previous.dynamic_quiet_tokens) + .unwrap_or_default(); (Some(sync), None) } else { (metadata, Some((locations, generation))) @@ -1727,24 +1740,35 @@ pub(crate) async fn announced_store( Ok((store, scope)) } -/// The header, width and paths the screen starts with. -pub(crate) fn screen_setup(project: &Path, target: &str) -> ScreenSetup { - let live: bool = live_screen(); +/// The header, size and paths the screen starts with; `plain` asks for appended lines. +pub(crate) fn screen_setup( + project: &Path, + (target, adapter): (&str, &str), + plain: bool, +) -> ScreenSetup { + let live: bool = live_screen(plain); + let (columns, rows): (usize, usize) = terminal_size(None).unwrap_or(( + usize::try_from(FALLBACK_COLUMNS).unwrap_or(80), + FALLBACK_ROWS, + )); ScreenSetup { live, facts: ScreenFacts { - columns: stderr_columns(), - style: CliStyle { use_color: live }, + columns, + rows, + style: CliStyle { + use_color: screen_colour(live), + }, links: live, - indent: SCREEN_INDENT, }, header: DevHeader { version: env!("CARGO_PKG_VERSION").to_owned(), project: project_name(project), target: target.to_owned(), }, - watching: format!("{}/", project_directory_name(project)), + adapter: adapter.to_owned(), project_root: project.to_string_lossy().into_owned(), + env_file: env_file_summary(project), } } @@ -1796,7 +1820,7 @@ pub(crate) async fn finish_compile( ), ) -> Result, ControlError> { tokio::pin!(stopped); - let (refresh_at, locations) = match load { + let (refresh_at, locations, missing_secrets) = match load { Ok(published) => published, Err(rules) => { watch.retry_at = Some(Instant::now() + Duration::from_secs(30)); @@ -1812,6 +1836,10 @@ pub(crate) async fn finish_compile( } }; watch.retry_at = refresh_at; + tokio::select! { + result = &mut stopped => { result?; return Ok(None); }, + () = report_provider_secrets(options, session, (generation, missing_secrets)) => {}, + } let trigger = if watch.checked { ConnectionCheckTrigger::Publish } else { diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/mod.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/mod.rs index ad8a09edea..0751361819 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/location/mod.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/mod.rs @@ -1,9 +1,17 @@ pub(crate) mod changed_build; +pub(crate) mod dev_cancel; +pub(crate) mod dev_start; +pub(crate) mod dev_supervision; +pub(crate) mod dynamic_resume; +pub(crate) mod env_reload; pub(crate) mod execution; pub(crate) mod held_copy; pub(crate) mod plan_document; pub(crate) mod plan_request; pub(crate) mod plan_reuse; +pub(crate) mod provider_secrets; +pub(crate) mod sensor_function; +pub(crate) mod shutdown; pub(crate) mod sync_outcomes; pub(crate) mod sync_report; pub(crate) mod work; diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/plan_request.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/plan_request.rs index 4b96ec98a4..25aa759eae 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/location/plan_request.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/plan_request.rs @@ -4,6 +4,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::future::Future; use serde_json::Value; +use sqlbuild_orchestration::runs::models::PinnedJob; use sqlbuild_orchestration::store::errors::ControlError; use tokio::sync::{mpsc, oneshot}; @@ -14,6 +15,7 @@ use crate::native_commands::_helpers::location::execution::{ plan_error, plan_failure, without_diffs, }; use crate::native_commands::_helpers::location::plan_document::plan_document; +use crate::native_commands::constants::CHANGED_SETTING; use crate::native_commands::constants::{PLAN_COMMAND, PLAN_NOT_PRODUCED}; use crate::native_commands::models::{LocationPlanRequest, LocationRuntimeRequest, LocationServe}; use crate::native_commands::types::LocationPlan; @@ -36,9 +38,38 @@ pub(crate) fn plan_arguments( Ok(argv) } -/// The node names of a frozen selection, each selected as `--select ` would. -pub(crate) fn selected_names(selection: &BTreeSet) -> Result, String> { - selection.iter().map(|key| selected_name(key)).collect() +/// Whether a plan shows what changed, so it reads the copy's consumption: `--changed`, or else a pinned job's `changed`. +pub(crate) fn plans_changes( + settings: &BTreeMap, + jobs: &BTreeMap, +) -> bool { + let changed: Option<&Value> = settings.get(CHANGED_SETTING).or_else(|| { + jobs.values() + .find_map(|job| job.settings.get(CHANGED_SETTING)) + }); + changed.is_some_and(|changed| !matches!(changed, Value::Null | Value::Bool(false))) +} + +/// Every setting a plan request's command gives, `settings` and `given` together, and [`plans_changes`]. +pub(crate) fn given_and_changes( + (settings, given): (&BTreeMap, &BTreeSet), + jobs: &BTreeMap, +) -> (BTreeSet, bool) { + let all: BTreeSet = given.iter().chain(settings.keys()).cloned().collect(); + (all, plans_changes(settings, jobs)) +} + +/// The node names of a frozen selection, each selected as `--select ` would, then `job:` for each pinned job. +pub(crate) fn selected_names( + selection: &BTreeSet, + jobs: &BTreeMap, +) -> Result, String> { + let mut names: Vec = selection + .iter() + .map(|key| selected_name(key)) + .collect::>()?; + names.extend(jobs.keys().map(|job| format!("job:{job}"))); + Ok(names) } /// The name of one frozen node key, such as `model:orders`. diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/provider_secrets.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/provider_secrets.rs new file mode 100644 index 0000000000..14d00b0f29 --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/provider_secrets.rs @@ -0,0 +1,68 @@ +//! Reporting the providers a publication shows missing secrets. + +use sqlbuild_orchestration::dev_events::main::emit_dev_event::emit_dev_event; +use sqlbuild_orchestration::dev_events::models::{DevEvent, UnsetProviderSecrets}; +use sqlbuild_orchestration::platform::main::health::unallowed_secret_count::unallowed_secret_count; +use sqlbuild_orchestration::platform::models::{LocationHealth, MissingProviderSecrets}; +use uuid::Uuid; + +use crate::argv::models::Stream; +use crate::native_commands::_helpers::command::terminal::write_output; +use crate::native_commands::_helpers::location::execution::report_location_health; +use crate::native_commands::models::LocationServe; + +/// The providers whose missing secrets stop runs, by the variables they read: a provider the target allows to miss secrets is left out. +pub(crate) fn unset_provider_secrets( + providers: &[MissingProviderSecrets], +) -> Vec { + let mut unset: Vec = Vec::new(); + for provider in providers.iter().filter(|provider| !provider.allowed) { + let mut variables: Vec = Vec::new(); + for setting in &provider.settings { + variables.push(setting.variable.clone()); + } + unset.push(UnsetProviderSecrets { + provider: provider.provider.clone(), + variables, + }); + } + unset +} + +/// Report the providers a publication shows missing secrets; under `sqb dev`, also tell the screen, which warns until a report shows none. +pub(crate) async fn report_provider_secrets( + options: &LocationServe, + (bearer, session_id): (&str, Uuid), + (generation, providers): (i64, Vec), +) { + let missing: u64 = unallowed_secret_count(&providers); + if missing > 0 { + let mut variables: Vec = Vec::new(); + for provider in providers.iter().filter(|provider| !provider.allowed) { + for setting in &provider.settings { + variables.push(format!("{} {}", provider.provider, setting.variable)); + } + } + drop(write_output(&[( + Stream::Stderr, + &format!( + "Providers are missing secrets in this location's environment; runs that use them stop before the warehouse: {}\n", + variables.join(", ") + ), + )])); + } + drop(emit_dev_event(&DevEvent::MissingSecrets { + providers: unset_provider_secrets(&providers), + })); + report_location_health( + options, + bearer, + session_id, + LocationHealth::ProviderSecrets { + generation, + missing, + providers, + }, + ) + .await; +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/sensor_function.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/sensor_function.rs new file mode 100644 index 0000000000..861f311374 --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/sensor_function.rs @@ -0,0 +1,57 @@ +//! A sensor's function gets its own interpreter; its timeout and shutdown reap it before reporting a result. + +use std::future::Future; +use std::path::Path; +use std::time::Duration; + +use serde::Serialize; +use sqlbuild_orchestration::sensors::models::SensorFunctionOutcome; +use sqlbuild_orchestration::store::errors::ControlError; + +use crate::native_commands::_helpers::location::execution::location_result; +use crate::native_commands::constants::SENSOR_RESULT_BYTES; +use crate::native_commands::models::LocationServe; + +/// Run one call of a sensor's function for `request`, a tick or a trial; `None` when `stopped` ends it first. +pub(crate) async fn run_sensor_function( + (options, script): (&LocationServe, &Path), + (request, timeout_seconds): (&impl Serialize, u32), + stopped: impl Future>, +) -> Result, ControlError> { + let request = + serde_json::to_vec(request).map_err(|error| ControlError::Invalid(error.to_string()))?; + let (mut child, reply) = + match location_result((options, script), (request, SENSOR_RESULT_BYTES)) { + Ok(exchange) => exchange, + Err(error) => { + return Ok(Some(SensorFunctionOutcome::Failed { + error: format!("the location couldn't start the sensor's interpreter: {error}"), + })); + } + }; + tokio::pin!(stopped); + let outcome = tokio::select! { + result = &mut stopped => { + child.kill().await?; + result?; + return Ok(None); + }, + result = tokio::time::timeout(Duration::from_secs(u64::from(timeout_seconds)), async { + let outcome = reply.await?; + if !child.wait().await?.success() { + return Err(ControlError::Invalid("the sensor's interpreter exited with an error".into())); + } + Ok(outcome) + }) => { + match result { + Ok(Ok(outcome)) => outcome, + Ok(Err(error)) => SensorFunctionOutcome::Failed { error: error.to_string() }, + Err(_) => SensorFunctionOutcome::TimedOut, + } + }, + }; + if child.try_wait()?.is_none() { + child.kill().await?; + } + Ok(Some(outcome)) +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/shutdown.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/shutdown.rs new file mode 100644 index 0000000000..81869750b4 --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/shutdown.rs @@ -0,0 +1,87 @@ +//! Stop on SIGINT, SIGTERM or SIGHUP; during the shutdown that starts, a second signal kills the workers instead of waiting for them. + +use tokio::sync::watch; +use tokio::task::JoinSet; + +use sqlbuild_orchestration::store::errors::ControlError; + +use crate::argv::models::Stream; +use crate::dev_stop::main::stop_switch::stop_switch; +use crate::native_commands::_helpers::command::terminal::write_output; +use crate::native_commands::constants::FORCED_WORKER_STOP; +use crate::native_commands::models::ShutdownSignals; + +impl ShutdownSignals { + /// Listen for SIGINT, SIGTERM and SIGHUP from now on. + pub(crate) fn listen() -> Result { + #[cfg(unix)] + { + use tokio::signal::unix::{SignalKind, signal}; + Ok(Self { + interrupt: signal(SignalKind::interrupt())?, + terminate: signal(SignalKind::terminate())?, + hangup: signal(SignalKind::hangup())?, + }) + } + #[cfg(not(unix))] + Ok(Self {}) + } + + /// The next SIGINT or SIGTERM, or SIGHUP too when `hang_up`: a closed terminal stops the process as SIGTERM does, but a repeated hang-up never forces a shutdown already under way. + pub(crate) async fn next(&mut self, hang_up: bool) -> Result<(), ControlError> { + #[cfg(unix)] + tokio::select! { + _ = self.interrupt.recv() => {}, + _ = self.terminate.recv() => {}, + _ = self.hangup.recv(), if hang_up => {}, + } + #[cfg(not(unix))] + { + let _ = hang_up; + tokio::signal::ctrl_c().await?; + } + Ok(()) + } +} + +/// The first SIGINT, SIGTERM or SIGHUP. +pub(crate) async fn shutdown_signal() -> Result<(), ControlError> { + ShutdownSignals::listen()?.next(true).await +} + +/// Stop sibling roles on a signal or role failure, then drain their shutdown results; a second SIGINT or SIGTERM meanwhile kills the workers' process groups at once instead of waiting for them. +pub(crate) async fn supervise_control_roles( + mut tasks: JoinSet>, + stop: watch::Sender, +) -> Result<(), ControlError> { + let mut signals: ShutdownSignals = ShutdownSignals::listen()?; + let mut result = tokio::select! { + result = tasks.join_next() => match result { + Some(result) => result.map_err(ControlError::from).and_then(std::convert::identity), + None => Ok(()), + }, + result = signals.next(true) => result, + }; + stop.send_replace(true); + let mut forced: bool = false; + loop { + tokio::select! { + joined = tasks.join_next() => { + let Some(joined) = joined else { + break; + }; + let joined = joined + .map_err(ControlError::from) + .and_then(std::convert::identity); + result = result.and(joined); + } + signalled = signals.next(false), if !forced => { + signalled?; + forced = true; + drop(write_output(&[(Stream::Stderr, FORCED_WORKER_STOP)])); + stop_switch().kill_all(); + } + } + } + result +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/sync_outcomes.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/sync_outcomes.rs index e488f2b107..72fb8c532a 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/location/sync_outcomes.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/sync_outcomes.rs @@ -141,5 +141,5 @@ pub(crate) async fn deliver_metadata_page( result = &mut stopped => { result?; return Ok(None); }, () = metadata_health(&state, (client, poll), (started, None)) => {}, } - finish_metadata_page(acknowledge_metadata_page(state)).await + finish_metadata_page(acknowledge_metadata_page(state), stopped).await } diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/mod.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/mod.rs index 63ce5196ed..a4bc0c525f 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/mod.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/mod.rs @@ -1,2 +1,3 @@ pub(crate) mod command; pub(crate) mod location; +pub(crate) mod sensor_trial; diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/sensor_trial/arguments.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/sensor_trial/arguments.rs new file mode 100644 index 0000000000..96a247bd66 --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/sensor_trial/arguments.rs @@ -0,0 +1,66 @@ +//! A trial's arguments from the parsed command line, or the usage error that stops it. + +use std::path::PathBuf; + +use sqlbuild_orchestration::sensors::models::SensorEventChoice; + +use crate::argv::models::{Namespace, Value}; +use crate::native_commands::_helpers::command::decision::{flag, text}; +use crate::native_commands::main::effective_target::effective_target; +use crate::native_commands::models::{EventSource, SensorTrialArguments}; + +/// The trial `namespace` asks for; the error is the message of a usage error. +pub(crate) fn trial_arguments(namespace: &Namespace) -> Result { + let sensor = text(namespace, "sensor_name").unwrap_or_default(); + if sensor.trim().is_empty() { + return Err("sensor try needs the sensor's name".into()); + } + let project_dir: PathBuf = + std::fs::canonicalize(text(namespace, "project_dir").unwrap_or_else(|| ".".into())) + .map_err(|error| format!("project directory is unreadable: {error}"))?; + let target = effective_target(&project_dir, text(namespace, "target"))? + .ok_or("the project names no default target; pass --target")?; + let limit: u32 = match namespace.get("sensor_limit") { + Some(Value::Int(limit)) => match limit.parse::() { + Ok(limit) if limit > 0 => limit, + _ => return Err("--limit must be a positive whole number".into()), + }, + _ => 10, + }; + let choice = if flag(namespace, "sensor_latest") { + SensorEventChoice::Latest + } else if let Some(event_id) = text(namespace, "sensor_event") { + SensorEventChoice::Event { event_id } + } else if let Some(run) = text(namespace, "sensor_run") { + SensorEventChoice::Run { + run_id: run.parse().map_err(|_| "--run must be a run UUID")?, + } + } else { + SensorEventChoice::Recent { limit } + }; + let source = match text(namespace, "login_server") { + Some(origin) => EventSource::Server { + origin, + ca: text(namespace, "login_ca").map(PathBuf::from), + location_id: text(namespace, "person_location") + .ok_or("--location-id is required with --server")? + .parse() + .map_err(|_| "--location-id must be a UUID")?, + }, + None => EventSource::Development { + store_url: text(namespace, "development_store_url").unwrap_or_else(|| { + project_dir + .join(".sqlbuild/control.sqlite3") + .to_string_lossy() + .into_owned() + }), + }, + }; + Ok(SensorTrialArguments { + sensor, + project_dir, + target, + choice, + source, + }) +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/sensor_trial/events.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/sensor_trial/events.rs new file mode 100644 index 0000000000..9725763209 --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/sensor_trial/events.rs @@ -0,0 +1,61 @@ +//! The published sensor and its chosen events, from a server or the local `sqb dev` store. + +use sqlbuild_orchestration::sensors::main::read_sensor_events::read_sensor_events as read_store_events; +use sqlbuild_orchestration::sensors::models::SensorTrialEvents; +use sqlbuild_orchestration::store::main::open_store::open_store; +use sqlbuild_orchestration::warehouse_metadata::main::location_reads::read_development_location::read_development_location; +use uuid::Uuid; + +use crate::native_commands::models::{EventSource, SensorTrialArguments}; +use crate::person_login::main::read_sensor_events::read_sensor_events; + +/// The location the events belong to, and the sensor with the events the trial chose. +pub(crate) fn trial_events( + trial: &SensorTrialArguments, +) -> Result<(Uuid, SensorTrialEvents), String> { + match &trial.source { + EventSource::Server { + origin, + ca, + location_id, + } => read_sensor_events( + (origin, ca.as_deref()), + (*location_id, &trial.target, &trial.sensor), + &trial.choice, + ) + .map(|events| (*location_id, events)) + .map_err(|error| error.to_string()), + EventSource::Development { store_url } => tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(|error| error.to_string())? + .block_on(development_events(trial, store_url)), + } +} + +async fn development_events( + trial: &SensorTrialArguments, + store_url: &str, +) -> Result<(Uuid, SensorTrialEvents), String> { + let store = open_store(store_url) + .await + .map_err(|error| format!("can't open the sqb dev store at {store_url}: {error}"))?; + let project = trial.project_dir.to_string_lossy(); + let location_id = read_development_location(&store, &trial.target, |path| path == project) + .await + .map_err(|error| error.to_string())? + .ok_or_else(|| { + format!( + "the sqb dev store at {store_url} has no location for this project and target {}; start sqb dev, or pass --server", + trial.target + ) + })?; + let events = read_store_events( + &store, + ((location_id, &trial.target), (&trial.sensor, &trial.choice)), + None, + ) + .await + .map_err(|error| error.to_string())??; + Ok((location_id, events)) +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/sensor_trial/mod.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/sensor_trial/mod.rs new file mode 100644 index 0000000000..0d58333e6b --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/sensor_trial/mod.rs @@ -0,0 +1,3 @@ +pub(crate) mod arguments; +pub(crate) mod events; +pub(crate) mod report; diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/sensor_trial/report.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/sensor_trial/report.rs new file mode 100644 index 0000000000..d59bd36bd3 --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/sensor_trial/report.rs @@ -0,0 +1,92 @@ +//! What `sqb sensor try` prints: the events to choose from, the warning before a real call, and what the function did. + +use std::fmt::Write as _; + +use sqlbuild_orchestration::sensors::models::{ + SensorCondition, SensorEvent, SensorFunctionOutcome, SensorTrialEvents, +}; + +/// The listing of a bare `try`: each event's ID, time and summary, then how to choose one. +pub(crate) fn event_listing(events: &SensorTrialEvents) -> String { + let name = &events.sensor; + let Some(condition) = &events.when else { + return format!( + "{name} polls instead of reacting to events.\nCall it once with: sqb sensor try {name} --latest\n" + ); + }; + if events.events.is_empty() { + return format!("No recent events match {name}'s condition.\n"); + } + let mut text = String::new(); + let width = events + .events + .iter() + .map(|event| event.id().len()) + .max() + .unwrap_or_default(); + for event in &events.events { + let _ = writeln!( + text, + "{:width$} {} {}", + event.id(), + event.occurred_at().format("%Y-%m-%d %H:%M:%S UTC"), + event.summary() + ); + } + let run = if matches!(condition, SensorCondition::RunEvent { .. }) { + ", --run " + } else { + "" + }; + let _ = writeln!( + text, + "\nCall {name} with one: sqb sensor try {name} --event (or --latest{run})" + ); + text +} + +/// The line before the call: the function runs for real, with the target's providers. +pub(crate) fn call_warning( + events: &SensorTrialEvents, + (event, target): (Option<&SensorEvent>, &str), +) -> String { + let with = event.map_or_else( + || "once, as a poll".to_owned(), + |event| format!("with {} ({})", event.id(), event.summary()), + ); + format!( + "Calling {}() for sensor {} {with}, using target {target}'s providers.\nWhat they do, such as sending a message, really happens; no run starts and no tick is recorded.\n", + events.function, events.sensor + ) +} + +/// What the function did, and the exit status: `0` when it returned, `1` when it failed or timed out. +pub(crate) fn outcome_report( + outcome: &SensorFunctionOutcome, + timeout_seconds: u32, +) -> (String, i32) { + match outcome { + SensorFunctionOutcome::Handled { .. } => { + ("Handled: the function returned None.\n".into(), 0) + } + SensorFunctionOutcome::Skipped { reason, .. } => (format!("Skipped: {reason}\n"), 0), + SensorFunctionOutcome::Requested { runs, .. } => { + let mut text = format!( + "The function asked for {} run{}; try starts none:\n", + runs.len(), + if runs.len() == 1 { "" } else { "s" } + ); + for run in runs { + let _ = writeln!(text, " {} (run key {})", run.job, run.run_key); + } + (text, 0) + } + SensorFunctionOutcome::Failed { error } => { + (format!("{error}\n\nThe function failed.\n"), 1) + } + SensorFunctionOutcome::TimedOut => ( + format!("The function timed out after {timeout_seconds} seconds.\n"), + 1, + ), + } +} diff --git a/crates/sqlbuild-cli/src/native_commands/constants.rs b/crates/sqlbuild-cli/src/native_commands/constants.rs index 8f89b1fe35..4e20c2f681 100644 --- a/crates/sqlbuild-cli/src/native_commands/constants.rs +++ b/crates/sqlbuild-cli/src/native_commands/constants.rs @@ -16,11 +16,19 @@ pub(crate) const CI_VARIABLE: &str = "CI"; /// Turns live progress off; `sqb dev` then prints plain lines. pub(crate) const NO_PROGRESS_VARIABLE: &str = "SQLBUILD_NO_PROGRESS"; +/// Names the terminal type; `dumb` cannot move the cursor. +pub(crate) const TERM_VARIABLE: &str = "TERM"; +/// The `TERM` of a terminal without cursor movement. +pub(crate) const DUMB_TERMINAL: &str = "dumb"; pub(crate) const COLUMNS_VARIABLE: &str = "COLUMNS"; /// `shutil.get_terminal_size`'s fallback width. pub(crate) const FALLBACK_COLUMNS: i64 = 80; +/// The height a screen assumes when the terminal does not say. +pub(crate) const FALLBACK_ROWS: usize = 24; +/// The code of a rejected project configuration, as `ProjectConfigError` reports it. +pub(crate) const CONFIG_ERROR_CODE: &str = "D001"; /// Variables that change where Python imports `sqlbuild` from. pub(crate) const PYTHON_PATH_VARIABLES: [&str; 2] = ["PYTHONPATH", "PYTHONHOME"]; @@ -152,9 +160,7 @@ pub(crate) const EXIT_FLUSH_FAILURE_STATUS: i32 = 120; pub(crate) const UNCAUGHT_EXCEPTION_STATUS: i32 = 1; -/// Reserve half the location work claim for acknowledgement retries after killing a callback. -pub(crate) const SENSOR_EVALUATION_SECONDS: u64 = 30; - +/// The largest answer a sensor's interpreter may send back. pub(crate) const SENSOR_RESULT_BYTES: u64 = 1_048_576; /// Read timeout, and the delay before retrying a failed page of an unfinished synchronization. @@ -203,9 +209,6 @@ pub(crate) const PLAN_OUTPUT_BYTES: usize = /// `sqb dev` names at most this many changed inputs per change event. pub(crate) const CHANGED_PATHS_SHOWN: usize = 3; -/// The spaces every `sqb dev` screen row starts with. -pub(crate) const SCREEN_INDENT: usize = 2; - /// Seconds a state-table or catalog page may take; its byte budget bounds the transfer. pub(crate) const METADATA_PAGE_SECONDS: u64 = 120; @@ -233,3 +236,17 @@ pub(crate) const PLAN_NOT_PRODUCED: &str = /// Return to the start of the line and erase it: a child's spinner may be drawn there. pub(crate) const CLEAR_TERMINAL_LINE: &str = "\r\u{1b}[K"; + +/// The setting of `--changed`, which makes a plan read the synced copy's consumption. +pub(crate) const CHANGED_SETTING: &str = "changed"; + +/// What a second signal during worker shutdown prints before it kills the workers. +pub(crate) const FORCED_WORKER_STOP: &str = + "Stopping now: killing the workers' process groups instead of waiting for them\n"; + +/// The command `sqb sensor` answers. +pub(crate) const SENSOR_COMMAND: &str = "sensor"; +/// Exit status of a misused command, as for other usage errors. +pub(crate) const SENSOR_USAGE_EXIT: i32 = 2; +/// Exit status when the function failed, timed out, or there was nothing to call it with. +pub(crate) const SENSOR_FAILED_EXIT: i32 = 1; diff --git a/crates/sqlbuild-cli/src/native_commands/main/_location_changed_build.rs b/crates/sqlbuild-cli/src/native_commands/main/_location_changed_build.rs index 2901c1bbae..79078ecdf6 100644 --- a/crates/sqlbuild-cli/src/native_commands/main/_location_changed_build.rs +++ b/crates/sqlbuild-cli/src/native_commands/main/_location_changed_build.rs @@ -1,6 +1,6 @@ //! After each publish and each completed sync the location plans the web UI's "Build what changed" with the plan page's own path, from the synced copy, and reports what it runs. -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; use std::future::Future; use sqlbuild_orchestration::node_states::constants::MAX_FAILING_REASON_CHARS; @@ -47,7 +47,11 @@ pub(super) async fn report_changed_build( report("Planning what changed from the synced warehouse copy...\n"); let Some(((document, diffs), keep)) = plan_location( (options, runtime), - (&BTreeSet::new(), &settings, false), + ( + (&BTreeSet::new(), &BTreeMap::new()), + (&settings, &BTreeSet::new()), + false, + ), (client, session_id, generation), stopped, ) diff --git a/crates/sqlbuild-cli/src/native_commands/main/_location_compiler.rs b/crates/sqlbuild-cli/src/native_commands/main/_location_compiler.rs index d01508dc23..2bc283d094 100644 --- a/crates/sqlbuild-cli/src/native_commands/main/_location_compiler.rs +++ b/crates/sqlbuild-cli/src/native_commands/main/_location_compiler.rs @@ -10,6 +10,7 @@ use tokio::sync::mpsc; use crate::argv::models::Stream; use crate::native_commands::_helpers::command::terminal::write_output; +use crate::native_commands::_helpers::location::env_reload::reload_env_file; use crate::native_commands::_helpers::location::execution::{ exchange_location_generation, exchange_location_plan, }; @@ -62,16 +63,22 @@ async fn publish( mut compiler: Option, mut request: LocationCompileRequest, ) -> Result<(Option, bool), ControlError> { - if compiler + let env_changed: bool = reload_env_file(options); + let python_changed: bool = compiler .as_ref() - .is_some_and(|compiler| compiler.python_sources != request.python_sources) - { + .is_some_and(|compiler| compiler.python_sources != request.python_sources); + if compiler.is_some() && (python_changed || env_changed) { stop_location_runtime(compiler.take()).await?; if options.dev_events { + let reason: &str = if python_changed { + "Python changed" + } else { + "env file changed" + }; drop(write_output(&[( Stream::Stdout, &dev_event_line(&DevEvent::Restarted { - reason: "Python changed".into(), + reason: reason.into(), }), )])); } diff --git a/crates/sqlbuild-cli/src/native_commands/main/_location_metadata.rs b/crates/sqlbuild-cli/src/native_commands/main/_location_metadata.rs index 5c4216cbe4..eaab7273b5 100644 --- a/crates/sqlbuild-cli/src/native_commands/main/_location_metadata.rs +++ b/crates/sqlbuild-cli/src/native_commands/main/_location_metadata.rs @@ -99,7 +99,7 @@ pub(crate) async fn sync_location_metadata( result = &mut stopped => { result?; return Ok(None); }, () = metadata_health(&state, (client, poll), (started, None)) => {}, } - return finish_metadata_page(next_scan(state)).await; + return finish_metadata_page(next_scan(state), stopped.as_mut()).await; } state = freeze_history_page(state, page, poll)?; } diff --git a/crates/sqlbuild-cli/src/native_commands/main/_location_plan.rs b/crates/sqlbuild-cli/src/native_commands/main/_location_plan.rs index 4443cf2113..de71a5405b 100644 --- a/crates/sqlbuild-cli/src/native_commands/main/_location_plan.rs +++ b/crates/sqlbuild-cli/src/native_commands/main/_location_plan.rs @@ -1,10 +1,10 @@ //! A requested plan runs in the location's runtime interpreter on frozen node keys, from the synced copy. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::BTreeSet; use std::future::Future; use chrono::{DateTime, Utc}; -use serde_json::{Value, json}; +use serde_json::json; use sqlbuild_orchestration::platform::models::LocationWorkClient; use sqlbuild_orchestration::store::errors::ControlError; use sqlbuild_orchestration::warehouse_metadata::models::PreviewCopyRead; @@ -14,30 +14,29 @@ use uuid::Uuid; use crate::native_commands::_helpers::location::execution::{plan_failure, without_diffs}; use crate::native_commands::_helpers::location::held_copy::{HELD_COPY, held_copy, hold_copy}; use crate::native_commands::_helpers::location::plan_request::{ - plan_arguments, run_plan, selected_names, + given_and_changes, plan_arguments, run_plan, selected_names, }; use crate::native_commands::_helpers::location::plan_reuse::{PLAN_REUSE, reused_plan}; use crate::native_commands::models::{ HeldCopy, LocationRuntimeRequest, LocationServe, PlanKey, PlanToKeep, }; use crate::native_commands::types::LocationPlan; +use crate::native_commands::types::{PlanSelection, PlanSettings}; /// The plan with what to keep once its checks pass, an `{"error": ...}` report, or `None` when stopped first. pub(super) async fn plan_location( (options, runtime): (&LocationServe, &mpsc::Sender), - (selection, settings, fresh): (&BTreeSet, &BTreeMap, bool), + ((selection, jobs), (settings, given), fresh): (PlanSelection<'_>, PlanSettings<'_>, bool), (client, session_id, generation): (&LocationWorkClient, Uuid, i64), stopped: impl Future>, ) -> Result)>, ControlError> { let (argv, select) = match plan_arguments(options, settings) - .and_then(|argv| Ok((argv, selected_names(selection)?))) + .and_then(|argv| Ok((argv, selected_names(selection, jobs)?))) { Ok(planned) => planned, Err(message) => return Ok(Some((without_diffs(plan_failure(&message)), None))), }; - let consumption: bool = settings - .get("changed") - .is_some_and(|changed| !matches!(changed, Value::Null | Value::Bool(false))); + let (given, consumption): (BTreeSet, bool) = given_and_changes((settings, given), jobs); let held: Option = held_copy(&HELD_COPY, (&options.target, generation), consumption); let read_consumption: bool = consumption || held.as_ref().is_some_and(|held| held.consumption); let read = PreviewCopyRead { @@ -65,6 +64,8 @@ pub(super) async fn plan_location( argv: argv.clone(), select: select.clone(), consumption: planned.consumption, + jobs: jobs.clone(), + given: given.clone(), }; let planned_at: DateTime = Utc::now(); if !fresh @@ -83,6 +84,10 @@ pub(super) async fn plan_location( "copy": planned.path.to_string_lossy(), "version": planned.version, "consumption": planned.consumption, + "jobs": jobs, + "given": given, + "project_dir": options.project_dir, + "target": options.target, }}); let keep = PlanToKeep { generation, diff --git a/crates/sqlbuild-cli/src/native_commands/main/_location_sensor.rs b/crates/sqlbuild-cli/src/native_commands/main/_location_sensor.rs deleted file mode 100644 index 6dc9aeff42..0000000000 --- a/crates/sqlbuild-cli/src/native_commands/main/_location_sensor.rs +++ /dev/null @@ -1,52 +0,0 @@ -//! A callback gets its own interpreter; timeout and shutdown reap it before reporting a result. - -use std::future::Future; -use std::path::Path; -use std::time::Duration; - -use sqlbuild_orchestration::sensors::models::{CustomSensorOutcome, SensorEvaluationRequest}; -use sqlbuild_orchestration::store::errors::ControlError; - -use crate::native_commands::_helpers::location::execution::location_result; -use crate::native_commands::constants::{SENSOR_EVALUATION_SECONDS, SENSOR_RESULT_BYTES}; -use crate::native_commands::models::LocationServe; - -pub(super) async fn evaluate_location_sensor( - options: &LocationServe, - script: &Path, - evaluation: &SensorEvaluationRequest, - stopped: impl Future>, -) -> Result, ControlError> { - let request = - serde_json::to_vec(evaluation).map_err(|error| ControlError::Invalid(error.to_string()))?; - let (mut child, reply) = - match location_result((options, script), (request, SENSOR_RESULT_BYTES)) { - Ok(exchange) => exchange, - Err(_) => return Ok(Some(CustomSensorOutcome::Failed)), - }; - tokio::pin!(stopped); - let outcome = tokio::select! { - result = &mut stopped => { - child.kill().await?; - result?; - return Ok(None); - }, - result = tokio::time::timeout(Duration::from_secs(SENSOR_EVALUATION_SECONDS), async { - let outcome = reply.await?; - if !child.wait().await?.success() { - return Err(ControlError::Invalid("location sensor interpreter failed".into())); - } - Ok(outcome) - }) => { - match result { - Ok(Ok(outcome)) => outcome, - Ok(Err(_)) => CustomSensorOutcome::Failed, - Err(_) => CustomSensorOutcome::TimedOut, - } - }, - }; - if child.try_wait()?.is_none() { - child.kill().await?; - } - Ok(Some(outcome)) -} diff --git a/crates/sqlbuild-cli/src/native_commands/main/_location_work.rs b/crates/sqlbuild-cli/src/native_commands/main/_location_work.rs index 32fbf8b992..bec64273ca 100644 --- a/crates/sqlbuild-cli/src/native_commands/main/_location_work.rs +++ b/crates/sqlbuild-cli/src/native_commands/main/_location_work.rs @@ -19,9 +19,9 @@ use crate::native_commands::_helpers::command::paths::location_files; use crate::native_commands::_helpers::command::terminal::write_output; use crate::native_commands::_helpers::location::execution::check_location_connection; use crate::native_commands::_helpers::location::plan_reuse::keep_plan; +use crate::native_commands::_helpers::location::sensor_function::run_sensor_function; use crate::native_commands::_helpers::location::work::work_error; use crate::native_commands::main::_location_plan::plan_location; -use crate::native_commands::main::_location_sensor::evaluate_location_sensor; use crate::native_commands::models::{ LocationRuntimeRequest, LocationServe, LocationWatch, LocationWorkTurn, PlanToKeep, }; @@ -165,7 +165,7 @@ async fn perform_work( let message = match &work { LocationWork::CheckConnection {} => "Checking requested location connection...\n", LocationWork::SyncWarehouse {} => "Synchronizing warehouse history on request...\n", - LocationWork::EvaluateSensor { .. } => "Evaluating requested custom sensor...\n", + LocationWork::EvaluateSensor { .. } => "Running a sensor's function...\n", LocationWork::Plan { .. } => "Planning requested command...\n", }; drop(write_output(&[(Stream::Stderr, message)])); @@ -180,25 +180,29 @@ async fn perform_work( (LocationWorkOutcome::Connection { healthy }, files, None) }) } - LocationWork::EvaluateSensor { evaluation } => { - evaluate_location_sensor(options, script, &evaluation, expires) - .await? - .map(|outcome| { - ( - LocationWorkOutcome::SensorEvaluation { outcome }, - Vec::new(), - None, - ) - }) - } + LocationWork::EvaluateSensor { evaluation } => run_sensor_function( + (options, script), + (&*evaluation, evaluation.definition.timeout_seconds.get()), + expires, + ) + .await? + .map(|outcome| { + ( + LocationWorkOutcome::SensorEvaluation { outcome }, + Vec::new(), + None, + ) + }), LocationWork::Plan { selection, settings, fresh, + jobs, + given, .. } => plan_location( (options, runtime), - (&selection, &settings, fresh), + ((&selection, &jobs), (&settings, &given), fresh), copy, expires, ) diff --git a/crates/sqlbuild-cli/src/native_commands/main/_run_control.rs b/crates/sqlbuild-cli/src/native_commands/main/_run_control.rs index dd34353031..0962a26722 100644 --- a/crates/sqlbuild-cli/src/native_commands/main/_run_control.rs +++ b/crates/sqlbuild-cli/src/native_commands/main/_run_control.rs @@ -14,8 +14,9 @@ use crate::argv::models::{Namespace, Stream}; use crate::native_commands::_helpers::command::decision::{control_address, control_api_settings}; use crate::native_commands::_helpers::command::terminal::write_output; use crate::native_commands::_helpers::location::execution::{ - open_control_store, open_control_workers, start_platform_roles, supervise_control_roles, + open_control_store, open_control_workers, start_platform_roles, }; +use crate::native_commands::_helpers::location::shutdown::supervise_control_roles; use crate::server_config::main::read_server_config::read_server_config; use crate::workers::models::Workers; @@ -78,14 +79,15 @@ pub(crate) async fn run_control( )?; } if facts.scheduler { - start_scheduler(&mut tasks, store, shutdown, workers); + start_scheduler(&mut tasks, (store, facts.origin.clone()), shutdown, workers); } supervise_control_roles(tasks, stop).await } +/// Start the scheduler, whose sensor events link runs under `origin`. fn start_scheduler( tasks: &mut JoinSet>, - store: ControlStore, + (store, origin): (ControlStore, Option), shutdown: watch::Receiver, workers: Workers, ) { @@ -93,7 +95,7 @@ fn start_scheduler( tasks.spawn(async move { run_scheduler( &store, - SchedulerState::new(Uuid::now_v7()), + SchedulerState::new(Uuid::now_v7()).with_origin(origin), shutdown, workers, ) diff --git a/crates/sqlbuild-cli/src/native_commands/main/_run_dev.rs b/crates/sqlbuild-cli/src/native_commands/main/_run_dev.rs index eeb8101cc9..d301acaa51 100644 --- a/crates/sqlbuild-cli/src/native_commands/main/_run_dev.rs +++ b/crates/sqlbuild-cli/src/native_commands/main/_run_dev.rs @@ -1,48 +1,107 @@ //! Collapse the production API, scheduler and outbound location into one local process tree. -use std::net::SocketAddr; +use std::path::PathBuf; +use std::time::Instant; -use sqlbuild_orchestration::store::errors::ControlError; +use sqlbuild_core::screen_text::models::Problem; -use crate::argv::models::Namespace; +use crate::argv::models::{Namespace, Stream}; use crate::dev_screen::main::start_dev_screen::start_dev_screen; -use crate::dev_screen::models::DevScreenHandle; +use crate::dev_screen::models::{DevScreenHandle, DevStep, ScreenMessage}; +use crate::dev_stop::constants::{RUNTIME_SHUTDOWN, START_FAILURE_STATUS}; +use crate::dev_stop::main::watch_signals::watch_signals; +use crate::dev_stop::models::{DevEnd, StopReason}; use crate::native_commands::_helpers::command::decision::{flag, text}; -use crate::native_commands::_helpers::command::project_facts::development_target; -use crate::native_commands::_helpers::location::execution::run_development_roles; -use crate::native_commands::_helpers::location::execution::{ - announced_store, loopback_address, screen_setup, +use crate::native_commands::_helpers::command::terminal::write_output; +use crate::native_commands::_helpers::location::dev_start::{ + finish_session, load_config, start_roles, }; +use crate::native_commands::_helpers::location::execution::screen_setup; -pub(super) async fn run_dev(namespace: &Namespace) -> Result<(), ControlError> { - let project = - std::fs::canonicalize(text(namespace, "project_dir").unwrap_or_else(|| ".".into()))?; - let target = development_target(&project, text(namespace, "target"))?; - let address: SocketAddr = loopback_address(namespace)?; - let executable = std::env::current_exe()?; +/// Run `sqb dev` until it is stopped or fails, leave its result line, and return its exit status. +async fn run_dev(namespace: &Namespace) -> i32 { + let started: Instant = Instant::now(); + let project: PathBuf = + match std::fs::canonicalize(text(namespace, "project_dir").unwrap_or_else(|| ".".into())) { + Ok(project) => project, + Err(error) => { + drop(write_output(&[( + Stream::Stderr, + &format!("\u{2717} sqb dev did not start project directory: {error}\n"), + )])); + return START_FAILURE_STATUS; + } + }; + if let Err(error) = watch_signals() { + drop(write_output(&[( + Stream::Stderr, + &format!("\u{2717} sqb dev did not start signals: {error}\n"), + )])); + return START_FAILURE_STATUS; + } + let config: Result>, StopReason> = + load_config(&project, text(namespace, "target")).await; + let (target, adapter): (String, String) = match &config { + Ok(Ok(found)) => found.clone(), + Ok(Err(_)) | Err(_) => (String::new(), String::new()), + }; let DevScreenHandle { messages, actions, keys, finish, task, - } = start_dev_screen(screen_setup(&project, &target)); - let result: Result<(), ControlError> = async { - let (store, scope) = announced_store(namespace, (&project, &target), &messages).await?; - let listener = tokio::net::TcpListener::bind(address).await?; - run_development_roles( - (store, scope), - (project.clone(), executable), - listener, - ( - !flag(namespace, "control_no_scheduler"), + } = start_dev_screen(screen_setup( + &project, + (&target, &adapter), + flag(namespace, "development_plain"), + )); + let end: DevEnd = match config { + Err(reason) => DevEnd::Stopped(reason), + Ok(Err(problem)) => { + let file: String = problem.title.clone(); + drop(messages.send(ScreenMessage::Failed { + step: DevStep::Config, + detail: "1 error".to_owned(), + problem: *problem, + })); + DevEnd::NotStarted { + reason: format!("configuration error in {file}"), + explained: true, + next: vec![( + "sqb debug".to_owned(), + "check the configuration on its own".to_owned(), + )], + } + } + Ok(Ok(_)) => { + start_roles( + namespace, + (project, target), (messages.clone(), actions, keys), - ), - ) - .await - } - .await; - let _ = finish.send(result.is_err()); - drop(task.await); - result + ) + .await + } + }; + finish_session(&end, started, (finish, task)).await +} + +/// `sqb dev`: its own result line and exit status; leftover tasks get a moment, never a hang. +pub(super) fn run_development(namespace: &Namespace) -> i32 { + let runtime = match tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + { + Ok(runtime) => runtime, + Err(error) => { + drop(write_output(&[( + Stream::Stderr, + &format!("\u{2717} sqb dev did not start {error}\n"), + )])); + return START_FAILURE_STATUS; + } + }; + let status: i32 = runtime.block_on(run_dev(namespace)); + runtime.shutdown_timeout(RUNTIME_SHUTDOWN); + status } diff --git a/crates/sqlbuild-cli/src/native_commands/main/_run_location.rs b/crates/sqlbuild-cli/src/native_commands/main/_run_location.rs index ecdb881096..11fbfc7af7 100644 --- a/crates/sqlbuild-cli/src/native_commands/main/_run_location.rs +++ b/crates/sqlbuild-cli/src/native_commands/main/_run_location.rs @@ -22,8 +22,9 @@ use crate::native_commands::_helpers::location::execution::{ apply_dev_controls, compile_next_generation, finish_compile, }; use crate::native_commands::_helpers::location::execution::{ - dev_controls, location_clock, location_heartbeats, next_turn, shutdown_signal, + dev_controls, location_clock, location_heartbeats, next_turn, }; +use crate::native_commands::_helpers::location::shutdown::shutdown_signal; use crate::native_commands::_helpers::location::work::next_work_check; use crate::native_commands::constants::LOCATION_WORK_IDLE_POLL; use crate::native_commands::main::_location_changed_build::report_changed_build; diff --git a/crates/sqlbuild-cli/src/native_commands/main/mod.rs b/crates/sqlbuild-cli/src/native_commands/main/mod.rs index 76c593bc99..74ccce17f3 100644 --- a/crates/sqlbuild-cli/src/native_commands/main/mod.rs +++ b/crates/sqlbuild-cli/src/native_commands/main/mod.rs @@ -3,7 +3,6 @@ pub(super) mod _location_changed_build; pub(super) mod _location_compiler; pub(super) mod _location_metadata; pub(super) mod _location_plan; -pub(super) mod _location_sensor; pub(super) mod _location_work; pub(super) mod _run_admin; pub(super) mod _run_control; @@ -18,3 +17,4 @@ pub(crate) mod run_location_invocation; pub(crate) mod run_login_invocation; pub mod run_native_invocation; pub(crate) mod run_person_invocation; +pub(crate) mod run_sensor_invocation; diff --git a/crates/sqlbuild-cli/src/native_commands/main/parse_native_invocation.rs b/crates/sqlbuild-cli/src/native_commands/main/parse_native_invocation.rs index c01272c482..6efc185ff7 100644 --- a/crates/sqlbuild-cli/src/native_commands/main/parse_native_invocation.rs +++ b/crates/sqlbuild-cli/src/native_commands/main/parse_native_invocation.rs @@ -2,9 +2,10 @@ use std::ffi::OsString; +use crate::argv::main::namespace_defaults::namespace_defaults; use crate::argv::main::parse_cli_arguments::parse_cli_arguments; use crate::argv::models::{ArgvOutcome, ArgvSettings, Namespace}; -use crate::native_commands::_helpers::command::argv_host::{NativeArgvHost, namespace_defaults}; +use crate::native_commands::_helpers::command::argv_host::NativeArgvHost; use crate::native_commands::_helpers::command::decision::{review_json_failure, text}; use crate::native_commands::_helpers::command::terminal::{ finish_rejected_parse, stdout_supports_color, terminal_columns, diff --git a/crates/sqlbuild-cli/src/native_commands/main/run_location_invocation.rs b/crates/sqlbuild-cli/src/native_commands/main/run_location_invocation.rs index ef994b83c4..ec18abe481 100644 --- a/crates/sqlbuild-cli/src/native_commands/main/run_location_invocation.rs +++ b/crates/sqlbuild-cli/src/native_commands/main/run_location_invocation.rs @@ -12,7 +12,7 @@ use crate::argv::models::{Namespace, Stream}; use crate::native_commands::_helpers::command::decision::text; use crate::native_commands::_helpers::command::terminal::write_output; use crate::native_commands::_helpers::location::execution::location_options; -use crate::native_commands::main::_run_dev::run_dev; +use crate::native_commands::main::_run_dev::run_development; use crate::native_commands::main::_run_location::run_location; /// Health needs no Python CLI; serving and development return `None` without one so the caller reports it. @@ -29,13 +29,13 @@ pub(crate) fn run_location_invocation(namespace: &Namespace, script: Option<&Pat return None; } let script = script?; + if development { + return Some(run_development(namespace)); + } let result = (|| { let runtime = tokio::runtime::Builder::new_multi_thread() .enable_all() .build()?; - if development { - return runtime.block_on(run_dev(namespace)); - } let options = location_options(namespace)?; let bearer = std::env::var("SQLBUILD_LOCATION_TOKEN").map_err(|_| { std::io::Error::other( @@ -51,25 +51,14 @@ pub(crate) fn run_location_invocation(namespace: &Namespace, script: Option<&Pat Ok(()) => { drop(write_output(&[( Stream::Stderr, - if development { - "Development services stopped successfully\n" - } else { - "Code location stopped successfully\n" - }, + "Code location stopped successfully\n", )])); 0 } Err(error) => { drop(write_output(&[( Stream::Stderr, - &format!( - "{} failed: {error}\n", - if development { - "Development services" - } else { - "Code location" - } - ), + &format!("Code location failed: {error}\n"), )])); 1 } diff --git a/crates/sqlbuild-cli/src/native_commands/main/run_sensor_invocation.rs b/crates/sqlbuild-cli/src/native_commands/main/run_sensor_invocation.rs new file mode 100644 index 0000000000..3ef1dd54e1 --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/main/run_sensor_invocation.rs @@ -0,0 +1,143 @@ +//! `sqb sensor try`: list a published sensor's recent events, or call its function from the project's code with one. + +use std::path::Path; + +use serde_json::json; +use sqlbuild_orchestration::sensors::constants::TRY_SENSOR_REQUEST; +use sqlbuild_orchestration::sensors::models::{SensorEventChoice, SensorTrial, SensorTrialEvents}; +use sqlbuild_orchestration::store::errors::ControlError; +use uuid::Uuid; + +use crate::argv::models::{Namespace, Stream}; +use crate::native_commands::_helpers::command::decision::text; +use crate::native_commands::_helpers::command::terminal::write_output; +use crate::native_commands::_helpers::location::sensor_function::run_sensor_function; +use crate::native_commands::_helpers::sensor_trial::arguments::trial_arguments; +use crate::native_commands::_helpers::sensor_trial::events::trial_events; +use crate::native_commands::_helpers::sensor_trial::report::{ + call_warning, event_listing, outcome_report, +}; +use crate::native_commands::constants::{SENSOR_COMMAND, SENSOR_FAILED_EXIT, SENSOR_USAGE_EXIT}; +use crate::native_commands::models::{EventSource, LocationServe, SensorTrialArguments}; + +/// The exit status of `sqb sensor`, or `None` for another command; `script` starts the project's interpreter. +pub(crate) fn run_sensor_invocation(namespace: &Namespace, script: Option<&Path>) -> Option { + if text(namespace, "command").as_deref() != Some(SENSOR_COMMAND) { + return None; + } + let trial = match trial_arguments(namespace) { + Ok(trial) => trial, + Err(message) => { + drop(write_output(&[( + Stream::Stderr, + &format!("sqb sensor: error: {message}\n"), + )])); + return Some(SENSOR_USAGE_EXIT); + } + }; + drop(write_output(&[( + Stream::Stderr, + &format!("Reading sensor {}'s events…\n", trial.sensor), + )])); + let read = match trial_events(&trial) { + Ok(read) => read, + Err(message) => { + drop(write_output(&[( + Stream::Stderr, + &format!("Reading sensor events failed: {message}\n"), + )])); + return Some(SENSOR_FAILED_EXIT); + } + }; + let runtime = match tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + { + Ok(runtime) => runtime, + Err(error) => { + drop(write_output(&[( + Stream::Stderr, + &format!("Sensor try failed: {error}\n"), + )])); + return Some(SENSOR_FAILED_EXIT); + } + }; + Some(runtime.block_on(try_sensor(&trial, read, script))) +} + +async fn try_sensor( + trial: &SensorTrialArguments, + (location_id, events): (Uuid, SensorTrialEvents), + script: Option<&Path>, +) -> i32 { + if matches!(trial.choice, SensorEventChoice::Recent { .. }) { + drop(write_output(&[ + (Stream::Stdout, &event_listing(&events)), + (Stream::Stderr, "Sensor events read successfully\n"), + ])); + return 0; + } + let event = events.events.first(); + if events.when.is_some() && event.is_none() { + drop(write_output(&[( + Stream::Stderr, + &format!( + "No events match {}'s condition, so there is nothing to call it with.\n", + events.sensor + ), + )])); + return SENSOR_FAILED_EXIT; + } + let Some(script) = script else { + drop(write_output(&[( + Stream::Stderr, + "Sensor try failed: the Python CLI that runs project code is missing\n", + )])); + return SENSOR_FAILED_EXIT; + }; + drop(write_output(&[( + Stream::Stderr, + &call_warning(&events, (event, &trial.target)), + )])); + let options = LocationServe { + project_dir: trial.project_dir.clone(), + server_url: match &trial.source { + EventSource::Server { origin, .. } => origin.clone(), + EventSource::Development { .. } => String::new(), + }, + location_id, + target: trial.target.clone(), + image_id: None, + metadata_reconcile_seconds: 0, + safety_sync_seconds: 0, + dev_events: false, + }; + let request = json!({ + TRY_SENSOR_REQUEST: SensorTrial { + sensor: trial.sensor.clone(), + target: trial.target.clone(), + event: event.cloned(), + }, + }); + let outcome = run_sensor_function( + (&options, script), + (&request, events.timeout_seconds), + std::future::pending::>(), + ) + .await; + match outcome { + Ok(Some(outcome)) => { + let (report, code) = outcome_report(&outcome, events.timeout_seconds); + drop(write_output(&[(Stream::Stdout, &report)])); + code + } + Ok(None) => SENSOR_FAILED_EXIT, + Err(error) => { + drop(write_output(&[( + Stream::Stderr, + &format!("Sensor try failed: {error}\n"), + )])); + SENSOR_FAILED_EXIT + } + } +} diff --git a/crates/sqlbuild-cli/src/native_commands/models.rs b/crates/sqlbuild-cli/src/native_commands/models.rs index 46655c1562..d65a409ae1 100644 --- a/crates/sqlbuild-cli/src/native_commands/models.rs +++ b/crates/sqlbuild-cli/src/native_commands/models.rs @@ -1,5 +1,6 @@ //! Python-free commands, the invocation facts they run with and what they print. +use sqlbuild_orchestration::platform::models::PublishedGeneration; use std::collections::HashMap; use std::path::PathBuf; @@ -9,6 +10,7 @@ use sqlbuild_orchestration::credentials::models::CredentialScope; use sqlbuild_orchestration::declarations::models::TriggerChange; use sqlbuild_orchestration::platform::models::{LocationWorkRequest, WarehouseReadFailure}; use sqlbuild_orchestration::runs::models::{JobRunRequest, RerunRequest}; +use sqlbuild_orchestration::sensors::models::SensorEventChoice; use sqlbuild_orchestration::warehouse_metadata::constants::MAX_HISTORY_PAGE_RECORDS; use sqlbuild_orchestration::warehouse_metadata::models::{ MetadataBatch, StatisticsRead, WarehouseHistoryFailure, WarehouseHistoryKind, @@ -18,7 +20,6 @@ use uuid::{NoContext, Timestamp, Uuid}; use crate::argv::models::Namespace; use crate::native_commands::constants::{METADATA_FAILURE_LIMIT, METADATA_POLL_SECONDS}; -use crate::native_commands::types::LocationPublication; /// Privileged local operations require direct ownership of the control database. pub(crate) enum ControlAdmin { @@ -200,7 +201,7 @@ pub(crate) struct LocationCompileRequest { /// The runtime's reply to a generation: its publication, or the rule findings that failed its compile. #[derive(Debug, serde::Deserialize)] pub(crate) struct LocationLoad { - pub(crate) published: Option, + pub(crate) published: Option, pub(crate) rules: Option, } @@ -287,6 +288,8 @@ pub(crate) struct LocationMetadataSync { pub(crate) applied: bool, /// The generation was published after the last plan of what changed, which waits for this sync. pub(crate) replan: bool, + /// Per state location, the pause table's change token after a resume pass left no hold open. + pub(crate) dynamic_quiet_tokens: std::collections::BTreeMap, } /// Rows delivered and time taken by the current synchronization and its current table. @@ -574,6 +577,11 @@ pub(crate) struct PlanKey { pub(crate) select: Vec, /// Whether the plan read the copy's consumption. pub(crate) consumption: bool, + /// The jobs the request pins, with the nodes and settings each gives. + pub(crate) jobs: + std::collections::BTreeMap, + /// The settings the request's command gives, which replace the pinned jobs' own. + pub(crate) given: std::collections::BTreeSet, } /// One finished plan, kept as the JSON text of its document and of the diffs beside it. @@ -613,3 +621,37 @@ pub(crate) struct HeldCopy { pub(crate) consumption: bool, pub(crate) path: PathBuf, } + +/// SIGINT, SIGTERM and SIGHUP, listened for from the first request to stop until the process ends, so a second is never missed. +#[derive(Debug)] +pub(crate) struct ShutdownSignals { + #[cfg(unix)] + pub(crate) interrupt: tokio::signal::unix::Signal, + #[cfg(unix)] + pub(crate) terminate: tokio::signal::unix::Signal, + #[cfg(unix)] + pub(crate) hangup: tokio::signal::unix::Signal, +} + +/// Where the events come from: a server through the saved session, or a local `sqb dev` store. +#[derive(Clone, Debug)] +pub(crate) enum EventSource { + Server { + origin: String, + ca: Option, + location_id: uuid::Uuid, + }, + Development { + store_url: String, + }, +} + +/// One trial: the sensor, the project and target its code runs for, and how the event is chosen. +#[derive(Clone, Debug)] +pub(crate) struct SensorTrialArguments { + pub(crate) sensor: String, + pub(crate) project_dir: PathBuf, + pub(crate) target: String, + pub(crate) choice: SensorEventChoice, + pub(crate) source: EventSource, +} diff --git a/crates/sqlbuild-cli/src/native_commands/tests.rs b/crates/sqlbuild-cli/src/native_commands/tests.rs index a2448e824f..021c851fc7 100644 --- a/crates/sqlbuild-cli/src/native_commands/tests.rs +++ b/crates/sqlbuild-cli/src/native_commands/tests.rs @@ -16,6 +16,8 @@ mod location_plan; mod paths; #[path = "tests/test_project_facts.rs"] mod project_facts; +#[path = "tests/test_provider_secrets.rs"] +mod provider_secrets; #[path = "tests/test_rules.rs"] mod rules; #[path = "tests/test_sync_schedule.rs"] diff --git a/crates/sqlbuild-cli/src/native_commands/tests/helpers.rs b/crates/sqlbuild-cli/src/native_commands/tests/helpers.rs index 775f6eb238..54fd72e4d4 100644 --- a/crates/sqlbuild-cli/src/native_commands/tests/helpers.rs +++ b/crates/sqlbuild-cli/src/native_commands/tests/helpers.rs @@ -7,9 +7,10 @@ use serde_json::json; use sqlbuild_orchestration::warehouse_metadata::models::{MetadataBatch, WarehouseStateLocation}; use uuid::Uuid; +use crate::argv::main::namespace_defaults::namespace_defaults; use crate::argv::main::parse_cli_arguments::parse_cli_arguments; use crate::argv::models::{ArgvOutcome, ArgvSettings}; -use crate::native_commands::_helpers::command::argv_host::{NativeArgvHost, namespace_defaults}; +use crate::native_commands::_helpers::command::argv_host::NativeArgvHost; use crate::native_commands::_helpers::command::paths::location_watch; use crate::native_commands::_helpers::location::execution::{ acknowledge_metadata_page, settle_publication, @@ -85,6 +86,20 @@ pub(super) fn one_location() -> Vec { }] } +/// A location in `directory` served by an unreachable server. +pub(super) fn location_options(directory: &Path) -> LocationServe { + LocationServe { + project_dir: directory.to_path_buf(), + server_url: "http://127.0.0.1:1".into(), + location_id: Uuid::nil(), + target: "development".into(), + image_id: None, + metadata_reconcile_seconds: 3600, + safety_sync_seconds: 1800, + dev_events: false, + } +} + /// A location in `directory` whose `sqb debug` reports `wakes_compute` and whose every history read fails, published to an unreachable server: its options, script, work channel and the sync the publication starts. pub(super) fn published_location( directory: &Path, @@ -93,6 +108,22 @@ pub(super) fn published_location( (LocationServe, std::path::PathBuf), (LocationWorkClient, LocationWorkPoll), LocationMetadataSync, +) { + let (location, work, mut state) = republished_location(directory, wakes_compute, None); + state.begin_sync(chrono::Utc::now()); + state.idle = false; + (location, work, state) +} + +/// A location in `directory` published again over the sync `previous` left, and the new sync. +pub(super) fn republished_location( + directory: &Path, + wakes_compute: bool, + previous: Option, +) -> ( + (LocationServe, std::path::PathBuf), + (LocationWorkClient, LocationWorkPoll), + LocationMetadataSync, ) { let script = directory.join(format!("location-{wakes_compute}")); std::fs::write( @@ -107,16 +138,7 @@ pub(super) fn published_location( let mut permissions = std::fs::metadata(&script).expect("metadata").permissions(); std::os::unix::fs::PermissionsExt::set_mode(&mut permissions, 0o755); std::fs::set_permissions(&script, permissions).expect("executable"); - let options = LocationServe { - project_dir: directory.to_path_buf(), - server_url: "http://127.0.0.1:1".into(), - location_id: Uuid::nil(), - target: "development".into(), - image_id: None, - metadata_reconcile_seconds: 3600, - safety_sync_seconds: 1800, - dev_events: false, - }; + let options = location_options(directory); let client = connect_location_work((&options.server_url, "token"), options.location_id) .expect("work client"); let poll = LocationWorkPoll { @@ -130,14 +152,12 @@ pub(super) fn published_location( .block_on(settle_publication( (&options, &script, ("token", Uuid::nil())), ((one_location(), 1), true, ConnectionCheckTrigger::Publish), - (location_watch(directory), None), + (location_watch(directory), previous), std::future::pending(), )) .expect("no control error") .expect("not stopped"); - let mut state = metadata.expect("a connected publication starts a sync"); - state.begin_sync(chrono::Utc::now()); - state.idle = false; + let state = metadata.expect("a connected publication starts a sync"); ((options, script), (client, poll), state) } @@ -147,6 +167,8 @@ pub(super) fn reuse_key(select: &[&str]) -> PlanKey { argv: vec!["plan".into(), "--json".into(), "--changed".into()], select: select.iter().map(|name| (*name).to_owned()).collect(), consumption: true, + jobs: Default::default(), + given: Default::default(), } } diff --git a/crates/sqlbuild-cli/src/native_commands/tests/test_location_metadata.rs b/crates/sqlbuild-cli/src/native_commands/tests/test_location_metadata.rs index a5c34766e6..b77835d974 100644 --- a/crates/sqlbuild-cli/src/native_commands/tests/test_location_metadata.rs +++ b/crates/sqlbuild-cli/src/native_commands/tests/test_location_metadata.rs @@ -1,5 +1,8 @@ use crate::native_commands::_helpers::command::paths::location_watch; use crate::native_commands::_helpers::location::execution::metadata_sync; +use crate::native_commands::_helpers::location::execution::{ + finish_metadata_page, open_location_runtime, +}; use crate::native_commands::_helpers::location::execution::{ history_request, read_metadata_page, safety_sync_setting, }; @@ -11,10 +14,13 @@ use crate::native_commands::constants::{METADATA_FAILURE_LIMIT, METADATA_SAFETY_ use crate::native_commands::main::_location_metadata::sync_location_metadata; use crate::native_commands::models::{LocationMetadataPage, LocationServe, ReadFailure}; use crate::native_commands::tests::helpers::{ - acknowledge_complete_pages, one_location, published_location, + acknowledge_complete_pages, location_options, one_location, published_location, + republished_location, }; use crate::native_commands::tests::test_types::BilledDeferralTestCase; +use crate::native_commands::tests::test_types::DynamicResumeTestCase; use crate::native_commands::tests::test_types::FastClockScanTestCase; +use crate::native_commands::tests::test_types::RepublishTokenTestCase; use crate::native_commands::tests::test_types::{ FailedReadHealthTestCase, NewestVersionsTestCase, ReadFailureTestCase, }; @@ -1268,3 +1274,182 @@ fn given_a_fast_location_clock_when_scanning_then_a_ddl_after_the_page_read_is_s ); } } + +#[test] +fn given_a_completed_sync_when_finishing_then_its_reader_resumes_expired_holds_once_before_closing() +{ + const UNTOKENED: &str = r#"{"dynamic_resume":[{"location":{"database":"analytics","schema":"state"},"quiet_token":null}]}"#; + const TOKENED: &str = r#"{"dynamic_resume":[{"location":{"database":"analytics","schema":"state"},"quiet_token":"7/12:00"}]}"#; + let test_cases = [ + DynamicResumeTestCase { + description: "a completed sync sends the locations it read, then closes the reader", + idle: true, + halted: false, + quiet_token: None, + reply: r#"{"resumed":{"holds":[{"run_id":"run-1","relation":"analytics.marts.orders"}],"quiet_tokens":[{"location":{"database":"analytics","schema":"state"},"quiet_token":null}],"failures":[]}}"#, + expected_requests: &[UNTOKENED], + expected_reader_open: false, + expected_quiet_token: None, + }, + DynamicResumeTestCase { + description: "a pass that leaves no hold open keeps its token for the next sync", + idle: true, + halted: false, + quiet_token: None, + reply: r#"{"resumed":{"holds":[],"quiet_tokens":[{"location":{"database":"analytics","schema":"state"},"quiet_token":"7/12:00"}],"failures":[]}}"#, + expected_requests: &[UNTOKENED], + expected_reader_open: false, + expected_quiet_token: Some("7/12:00"), + }, + DynamicResumeTestCase { + description: "a kept token is sent, and a pass that finds a hold drops it", + idle: true, + halted: false, + quiet_token: Some("7/12:00"), + reply: r#"{"resumed":{"holds":[],"quiet_tokens":[{"location":{"database":"analytics","schema":"state"},"quiet_token":null}],"failures":[]}}"#, + expected_requests: &[TOKENED], + expected_reader_open: false, + expected_quiet_token: None, + }, + DynamicResumeTestCase { + description: "a hold that failed to resume is reported, and the pass's tokens still apply", + idle: true, + halted: false, + quiet_token: Some("7/12:00"), + reply: r#"{"resumed":{"holds":[],"quiet_tokens":[{"location":{"database":"analytics","schema":"state"},"quiet_token":null}],"failures":["analytics.marts.orders: insufficient privileges"]}}"#, + expected_requests: &[TOKENED], + expected_reader_open: false, + expected_quiet_token: None, + }, + DynamicResumeTestCase { + description: "a failed resume only warns, keeps the token, and the reader still closes", + idle: true, + halted: false, + quiet_token: Some("7/12:00"), + reply: r#"{"failed":"permission denied"}"#, + expected_requests: &[TOKENED], + expected_reader_open: false, + expected_quiet_token: Some("7/12:00"), + }, + DynamicResumeTestCase { + description: "an unreadable reply only warns, and the reader still closes", + idle: true, + halted: false, + quiet_token: None, + reply: "not json", + expected_requests: &[UNTOKENED], + expected_reader_open: false, + expected_quiet_token: None, + }, + DynamicResumeTestCase { + description: "a sync stopped by failed reads writes nothing", + idle: true, + halted: true, + quiet_token: None, + reply: r#"{"resumed":{"holds":[],"quiet_tokens":[{"location":{"database":"analytics","schema":"state"},"quiet_token":"7/12:00"}],"failures":[]}}"#, + expected_requests: &[], + expected_reader_open: false, + expected_quiet_token: None, + }, + DynamicResumeTestCase { + description: "a sync with scans left neither resumes nor closes its reader", + idle: false, + halted: false, + quiet_token: None, + reply: r#"{"resumed":{"holds":[],"quiet_tokens":[{"location":{"database":"analytics","schema":"state"},"quiet_token":"7/12:00"}],"failures":[]}}"#, + expected_requests: &[], + expected_reader_open: true, + expected_quiet_token: None, + }, + ]; + for test_case in test_cases { + let directory = tempfile::tempdir().expect("temporary directory"); + let requests = directory.path().join("requests"); + let script = directory.path().join("location"); + std::fs::write( + &script, + format!( + "#!/bin/sh\nwhile read line; do echo \"$line\" >> '{}'; echo '{}'; done\n", + requests.display(), + test_case.reply + ), + ) + .expect("location script"); + let mut permissions = std::fs::metadata(&script).expect("metadata").permissions(); + std::os::unix::fs::PermissionsExt::set_mode(&mut permissions, 0o755); + std::fs::set_permissions(&script, permissions).expect("executable"); + let options = location_options(directory.path()); + let state = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("runtime") + .block_on(async { + let mut state = metadata_sync((one_location(), 1), (3600, 1800)); + state.idle = test_case.idle; + state.halted = test_case.halted; + state.dynamic_quiet_tokens.extend( + test_case + .quiet_token + .map(|token| (one_location().remove(0), token.to_owned())), + ); + state.reader = + Some(open_location_runtime(&options, &script, Vec::new()).expect("runtime")); + finish_metadata_page(state, std::future::pending()).await + }) + .expect("no control error") + .expect("not stopped"); + let received = std::fs::read_to_string(&requests).unwrap_or_default(); + assert_eq!( + ( + received.lines().collect::>(), + state.reader.is_some(), + state + .dynamic_quiet_tokens + .get(&one_location().remove(0)) + .map(String::as_str), + ), + ( + test_case.expected_requests.to_vec(), + test_case.expected_reader_open, + test_case.expected_quiet_token, + ), + "{}", + test_case.description + ); + } +} + +#[test] +fn given_a_quiet_pause_table_when_the_location_publishes_again_then_the_new_sync_keeps_its_token() { + let test_cases = [ + RepublishTokenTestCase { + description: "a publication after a quiet sync keeps the pause table's token", + previous_token: Some("7/12:00"), + expected_token: Some("7/12:00"), + }, + RepublishTokenTestCase { + description: "the first publication has no token yet", + previous_token: None, + expected_token: None, + }, + ]; + for test_case in test_cases { + let directory = tempfile::tempdir().expect("temporary directory"); + let mut previous = metadata_sync((one_location(), 1), (3600, 1800)); + previous.dynamic_quiet_tokens.extend( + test_case + .previous_token + .map(|token| (one_location().remove(0), token.to_owned())), + ); + let (_, _, state) = republished_location(directory.path(), false, Some(previous)); + assert_eq!( + state + .dynamic_quiet_tokens + .get(&one_location().remove(0)) + .map(String::as_str), + test_case.expected_token, + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-cli/src/native_commands/tests/test_location_plan.rs b/crates/sqlbuild-cli/src/native_commands/tests/test_location_plan.rs index 2f0c5f3083..a670a8cf8e 100644 --- a/crates/sqlbuild-cli/src/native_commands/tests/test_location_plan.rs +++ b/crates/sqlbuild-cli/src/native_commands/tests/test_location_plan.rs @@ -1,12 +1,15 @@ +use std::collections::BTreeMap; + use serde_json::{Value, json}; use sqlbuild_orchestration::platform::constants::PLAN_DOCUMENT_BYTES; +use sqlbuild_orchestration::runs::models::PinnedJob; use std::sync::Mutex; use chrono::TimeDelta; use crate::native_commands::_helpers::location::plan_document::plan_document; -use crate::native_commands::_helpers::location::plan_request::plan_arguments; +use crate::native_commands::_helpers::location::plan_request::{plan_arguments, plans_changes}; use crate::native_commands::_helpers::location::plan_reuse::{remember_plan, reused_plan}; use crate::native_commands::_helpers::location::work::next_work_check; use crate::native_commands::constants::LOCATION_WORK_IDLE_POLL; @@ -14,10 +17,12 @@ use crate::native_commands::constants::{REUSED_PLAN_BYTES, REUSED_PLANS}; use crate::native_commands::models::LocationServe; use crate::native_commands::models::LocationWorkTurn; use crate::native_commands::models::PlanReuse; +use crate::native_commands::models::{PlanKey, PlanToKeep}; use crate::native_commands::tests::helpers::{ finished_plan, finished_plan_bytes, kept_plans, plan_output, plan_to_keep, reuse_clock, reuse_key, }; +use crate::native_commands::tests::test_types::{PinnedReuseTestCase, PlanChangesTestCase}; use crate::native_commands::tests::test_types::{ PlanArgumentsTestCase, PlanDocumentTestCase, PlanReuseBoundTestCase, PlanReuseTestCase, WorkCheckTestCase, @@ -193,6 +198,129 @@ fn given_a_kept_plan_when_the_same_request_comes_again_then_only_the_same_genera } } +#[test] +fn given_a_kept_plan_when_a_request_pins_other_jobs_then_it_plans_again() { + let pinned = |settings: serde_json::Value| -> BTreeMap { + BTreeMap::from([( + "nightly".to_owned(), + PinnedJob { + selection: ["model:orders".to_owned()].into(), + settings: serde_json::from_value(settings).expect("settings"), + }, + )]) + }; + let test_cases = [ + PinnedReuseTestCase { + description: "the same pinned jobs reuse the plan", + kept: pinned(json!({"full_refresh": true})), + asked: pinned(json!({"full_refresh": true})), + given: (&[], &[]), + expected_reused: true, + }, + PinnedReuseTestCase { + description: "a typed warehouse, which replaces the pinned jobs' own, plans again", + kept: pinned(json!({"warehouse": "REPORTS_XS"})), + asked: pinned(json!({"warehouse": "REPORTS_XS"})), + given: (&[], &["warehouse"]), + expected_reused: false, + }, + PinnedReuseTestCase { + description: "a pinned job with other settings plans again", + kept: pinned(json!({"full_refresh": true})), + asked: pinned(json!({"full_refresh": false})), + given: (&[], &[]), + expected_reused: false, + }, + PinnedReuseTestCase { + description: "a request that pins no job does not reuse one that pinned a job", + kept: pinned(json!({"full_refresh": true})), + asked: BTreeMap::new(), + given: (&[], &[]), + expected_reused: false, + }, + ]; + for test_case in test_cases { + let reuse: Mutex> = Mutex::new(None); + let (document, diffs) = finished_plan(false); + let mut keep: PlanToKeep = plan_to_keep(3, "copy-1", &["orders"]); + keep.key.jobs = test_case.kept; + keep.key.given = test_case + .given + .0 + .iter() + .map(|name| (*name).to_owned()) + .collect(); + remember_plan( + (&reuse, (REUSED_PLANS, REUSED_PLAN_BYTES)), + keep, + (&document, &diffs), + ); + let mut asked: PlanKey = reuse_key(&["orders"]); + asked.jobs = test_case.asked; + asked.given = test_case + .given + .1 + .iter() + .map(|name| (*name).to_owned()) + .collect(); + let reused = reused_plan(&reuse, (3, "copy-1"), &asked, reuse_clock()); + assert_eq!( + reused.is_some(), + test_case.expected_reused, + "{}", + test_case.description + ); + } +} + +#[test] +fn given_a_plan_request_when_deciding_whether_it_shows_what_changed_then_a_pinned_jobs_changed_counts() + { + let test_cases = [ + PlanChangesTestCase { + description: "a typed --changed reads consumption", + settings: json!({"changed": true}), + job_settings: json!({}), + expected_changes: true, + }, + PlanChangesTestCase { + description: "a pinned job's changed reads consumption, as a typed --changed does", + settings: json!({}), + job_settings: json!({"changed": ["definition", "source_data"]}), + expected_changes: true, + }, + PlanChangesTestCase { + description: "a typed --changed=false replaces the job's changed", + settings: json!({"changed": false}), + job_settings: json!({"changed": true}), + expected_changes: false, + }, + PlanChangesTestCase { + description: "neither reads none", + settings: json!({}), + job_settings: json!({"full_refresh": true}), + expected_changes: false, + }, + ]; + for test_case in test_cases { + let settings: BTreeMap = + serde_json::from_value(test_case.settings).expect("settings"); + let jobs = BTreeMap::from([( + "changed_job".to_owned(), + PinnedJob { + selection: ["model:orders".to_owned()].into(), + settings: serde_json::from_value(test_case.job_settings).expect("job settings"), + }, + )]); + assert_eq!( + plans_changes(&settings, &jobs), + test_case.expected_changes, + "{}", + test_case.description + ); + } +} + #[test] fn given_more_finished_plans_than_kept_when_planning_then_the_oldest_is_dropped_and_a_newer_copy_drops_all() { diff --git a/crates/sqlbuild-cli/src/native_commands/tests/test_provider_secrets.rs b/crates/sqlbuild-cli/src/native_commands/tests/test_provider_secrets.rs new file mode 100644 index 0000000000..6737ce2cb7 --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/tests/test_provider_secrets.rs @@ -0,0 +1,83 @@ +//! `sqb dev` warns only about providers whose missing secrets stop runs, never one the target allows to miss them. + +use sqlbuild_orchestration::dev_events::models::UnsetProviderSecrets; +use sqlbuild_orchestration::platform::models::{MissingProviderSecrets, MissingProviderSetting}; + +use crate::native_commands::_helpers::location::provider_secrets::unset_provider_secrets; +use crate::native_commands::tests::test_types::UnsetProviderSecretsTestCase; + +#[test] +fn given_providers_missing_secrets_when_the_dev_warning_is_built_then_allowed_providers_are_left_out() + { + let test_cases = [ + UnsetProviderSecretsTestCase { + description: "a provider the target allows to miss secrets is left out", + providers: vec![("export_bucket", true, vec!["EXPORT_BUCKET_KEY"])], + expected_unset: vec![], + }, + UnsetProviderSecretsTestCase { + description: "a provider that isn't allowed is kept with every variable it misses", + providers: vec![("region", false, vec!["REGION_TOKEN", "REGION_CODE"])], + expected_unset: vec![("region", vec!["REGION_TOKEN", "REGION_CODE"])], + }, + UnsetProviderSecretsTestCase { + description: "only the providers that aren't allowed are kept, in order", + providers: vec![ + ("export_bucket", true, vec!["EXPORT_BUCKET_KEY"]), + ("region", false, vec!["REGION_TOKEN"]), + ("payments", false, vec!["PAYMENTS_KEY"]), + ], + expected_unset: vec![ + ("region", vec!["REGION_TOKEN"]), + ("payments", vec!["PAYMENTS_KEY"]), + ], + }, + ]; + + for test_case in test_cases { + let providers: Vec = test_case + .providers + .iter() + .map(|(provider, allowed, variables)| MissingProviderSecrets { + provider: (*provider).to_owned(), + path: format!("providers/{provider}.py"), + settings: variables + .iter() + .map(|variable| MissingProviderSetting { + field: variable.to_lowercase(), + variable: (*variable).to_owned(), + line: None, + }) + .collect(), + nodes: Vec::new(), + allowed: *allowed, + }) + .collect(); + let unset: Vec<(String, Vec)> = unset_provider_secrets(&providers) + .into_iter() + .map( + |UnsetProviderSecrets { + provider, + variables, + }| (provider, variables), + ) + .collect(); + + assert_eq!( + unset, + test_case + .expected_unset + .iter() + .map(|(provider, variables)| ( + (*provider).to_owned(), + variables + .iter() + .map(|variable| (*variable).to_owned()) + .collect() + )) + .collect::)>>(), + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-cli/src/native_commands/tests/test_types.rs b/crates/sqlbuild-cli/src/native_commands/tests/test_types.rs index 1d42d8c8d6..12950ddca5 100644 --- a/crates/sqlbuild-cli/src/native_commands/tests/test_types.rs +++ b/crates/sqlbuild-cli/src/native_commands/tests/test_types.rs @@ -98,6 +98,26 @@ pub(super) struct PlanArgumentsTestCase { pub(super) expected_refused: bool, } +/// The jobs a kept plan pinned, those a new request pins, and whether the kept plan answers it. +pub(super) struct PinnedReuseTestCase { + pub(super) description: &'static str, + pub(super) kept: + std::collections::BTreeMap, + pub(super) asked: + std::collections::BTreeMap, + /// The settings the kept and the new request's commands give. + pub(super) given: (&'static [&'static str], &'static [&'static str]), + pub(super) expected_reused: bool, +} + +/// A plan request's settings and pinned jobs' settings, and whether it reads the copy's consumption. +pub(super) struct PlanChangesTestCase { + pub(super) description: &'static str, + pub(super) settings: serde_json::Value, + pub(super) job_settings: serde_json::Value, + pub(super) expected_changes: bool, +} + /// One kept plan, then one request for a plan. pub(super) struct PlanReuseTestCase { pub(super) description: &'static str, @@ -353,3 +373,34 @@ pub(super) struct FastClockScanTestCase { /// Whether a table altered a second after the page read is still described live. pub(super) expected_described_live: bool, } + +/// The token a quiet sync left before the location published again, and the token kept. +pub(super) struct RepublishTokenTestCase { + pub(super) description: &'static str, + pub(super) previous_token: Option<&'static str>, + pub(super) expected_token: Option<&'static str>, +} + +pub(super) struct DynamicResumeTestCase { + pub(super) description: &'static str, + /// Whether the synchronization completed, and whether failed reads stopped it. + pub(super) idle: bool, + pub(super) halted: bool, + /// The pause table token the location's last quiet pass left, before this sync finishes. + pub(super) quiet_token: Option<&'static str>, + /// The runtime's reply line to any request. + pub(super) reply: &'static str, + /// The request lines the runtime received, and whether the sync still holds its reader. + pub(super) expected_requests: &'static [&'static str], + pub(super) expected_reader_open: bool, + /// The token the next sync sends for the location. + pub(super) expected_quiet_token: Option<&'static str>, +} + +/// Providers a health report shows missing secrets, and those `sqb dev` warns about. +pub(super) struct UnsetProviderSecretsTestCase { + pub(super) description: &'static str, + /// Each provider, whether the target allows it to miss secrets, and the variables it misses. + pub(super) providers: Vec<(&'static str, bool, Vec<&'static str>)>, + pub(super) expected_unset: Vec<(&'static str, Vec<&'static str>)>, +} diff --git a/crates/sqlbuild-cli/src/native_commands/types.rs b/crates/sqlbuild-cli/src/native_commands/types.rs index 7d2d5458a8..6bbb77e3a6 100644 --- a/crates/sqlbuild-cli/src/native_commands/types.rs +++ b/crates/sqlbuild-cli/src/native_commands/types.rs @@ -1,18 +1,9 @@ //! Private interpreter protocol shapes owned by the location supervisor. use crate::native_commands::models::{LocationMetadataSync, LocationWatch}; -use chrono::{DateTime, Utc}; -use sqlbuild_orchestration::platform::models::LocationRuleFailure; -use sqlbuild_orchestration::snapshots::models::SnapshotRecord; +use sqlbuild_orchestration::platform::models::{LocationRuleFailure, MissingProviderSecrets}; use sqlbuild_orchestration::warehouse_metadata::models::WarehouseStateLocation; -/// Publication metadata and the earliest calendar refresh deadline. -pub(crate) type LocationPublication = ( - SnapshotRecord, - Option>, - Vec, -); - /// A settled publication: the watch without its local databases, its metadata sync, and the sync deferred until the warehouse connects. pub(crate) type Settled = ( LocationWatch, @@ -27,9 +18,13 @@ pub(crate) type NextGeneration = ( Option>, ); -/// A published generation's refresh deadline and state locations, or the rule findings that failed it. +/// A published generation's refresh deadline, state locations and providers missing secrets, or the rule findings that failed it. pub(crate) type LoadOutcome = Result< - (Option, Vec), + ( + Option, + Vec, + Vec, + ), Option, >; @@ -38,3 +33,15 @@ pub(crate) type LocationPlan = ( serde_json::Value, std::collections::BTreeMap, ); + +/// The frozen nodes a plan request selects, and the jobs it pins with their nodes and settings. +pub(crate) type PlanSelection<'a> = ( + &'a std::collections::BTreeSet, + &'a std::collections::BTreeMap, +); + +/// A plan request's settings, and the names of every setting its command gives, `warehouse` included. +pub(crate) type PlanSettings<'a> = ( + &'a std::collections::BTreeMap, + &'a std::collections::BTreeSet, +); diff --git a/crates/sqlbuild-cli/src/person_login/_helpers/transport.rs b/crates/sqlbuild-cli/src/person_login/_helpers/transport.rs index e6bdf19a7f..961c124caf 100644 --- a/crates/sqlbuild-cli/src/person_login/_helpers/transport.rs +++ b/crates/sqlbuild-cli/src/person_login/_helpers/transport.rs @@ -8,6 +8,7 @@ use sqlbuild_orchestration::api::main::parse_origin::parse_origin; use sqlbuild_orchestration::api::models::{ApiErrorBody, MutationResponse}; use sqlbuild_orchestration::credentials::models::SessionIdentity; use sqlbuild_orchestration::platform::models::PersonWorkRequest; +use sqlbuild_orchestration::sensors::models::{SensorEventChoice, SensorTrialEvents}; use sqlbuild_orchestration::snapshots::models::NodeSql; use uuid::Uuid; @@ -158,6 +159,41 @@ pub(crate) async fn warehouse_sync( .map(|response| response.applied) } +/// The published sensor and the events `choice` picks; a refusal carries the server's reason. +pub(crate) async fn sensor_events( + client: &PersonClient, + credential: &PersonCredential, + (location, target, name): (Uuid, &str, &str), + choice: &SensorEventChoice, +) -> Result { + let path = target_path(client, (location, target), &["sensors", name, "events"])?; + let query: [(&str, String); 1] = match choice { + SensorEventChoice::Recent { limit } => [("limit", limit.to_string())], + SensorEventChoice::Latest => [("latest", "true".to_owned())], + SensorEventChoice::Event { event_id } => [("event", event_id.clone())], + SensorEventChoice::Run { run_id } => [("run", run_id.to_string())], + }; + let response = authorized(client, reqwest::Method::GET, &path, credential)? + .query(&query) + .send() + .await + .map_err(|_| std::io::Error::other("could not read sensor events from the server"))?; + if response.status() == reqwest::StatusCode::CONFLICT { + let body: ApiErrorBody = response + .json() + .await + .map_err(|_| std::io::Error::other("server returned an invalid error response"))?; + return Err(std::io::Error::other(body.error)); + } + if !response.status().is_success() { + return Err(rejection(response, "Reading sensor events").await); + } + response + .json() + .await + .map_err(|_| std::io::Error::other("server returned invalid sensor events")) +} + /// The location targets the signed-in person can view. pub(crate) async fn location_targets( client: &PersonClient, diff --git a/crates/sqlbuild-cli/src/person_login/main/mod.rs b/crates/sqlbuild-cli/src/person_login/main/mod.rs index 499c63845c..94767ec95b 100644 --- a/crates/sqlbuild-cli/src/person_login/main/mod.rs +++ b/crates/sqlbuild-cli/src/person_login/main/mod.rs @@ -1,5 +1,6 @@ pub(crate) mod open_browser; pub(crate) mod read_node_sql; +pub(crate) mod read_sensor_events; pub(crate) mod request_warehouse_sync; pub(crate) mod run_login; pub mod signed_in_principal; diff --git a/crates/sqlbuild-cli/src/person_login/main/read_sensor_events.rs b/crates/sqlbuild-cli/src/person_login/main/read_sensor_events.rs new file mode 100644 index 0000000000..36078fe36f --- /dev/null +++ b/crates/sqlbuild-cli/src/person_login/main/read_sensor_events.rs @@ -0,0 +1,19 @@ +//! A saved person session can read a published sensor's events for `sqb sensor try`; reading changes nothing. + +use std::path::Path; + +use sqlbuild_orchestration::sensors::models::{SensorEventChoice, SensorTrialEvents}; +use uuid::Uuid; + +use crate::person_login::_helpers::transport; + +/// The published sensor and the events `choice` picks, read with the saved session for `server`. +pub(crate) fn read_sensor_events( + server: (&str, Option<&Path>), + (location, target, name): (Uuid, &str, &str), + choice: &SensorEventChoice, +) -> Result { + transport::with_person_session(server, async |client, credential| { + transport::sensor_events(client, credential, (location, target, name), choice).await + }) +} diff --git a/crates/sqlbuild-cli/src/workers/_helpers/child.rs b/crates/sqlbuild-cli/src/workers/_helpers/child.rs index fb14d6452e..664c4d18dc 100644 --- a/crates/sqlbuild-cli/src/workers/_helpers/child.rs +++ b/crates/sqlbuild-cli/src/workers/_helpers/child.rs @@ -46,7 +46,7 @@ impl WorkerChild { pub(in crate::workers) async fn terminate(&mut self) -> Result<(), ControlError> { match self { - Self::Local(child) => terminate_child(child), + Self::Local(child) => terminate_child(child, false), Self::RecoveredLocal(owner) => Ok(stop_worker(owner, false)?), Self::Docker(child) => child.signal("SIGTERM").await, } @@ -55,6 +55,7 @@ impl WorkerChild { pub(in crate::workers) async fn kill(&mut self) -> Result<(), ControlError> { match self { Self::Local(child) => { + terminate_child(child, true)?; child.start_kill()?; Ok(()) } diff --git a/crates/sqlbuild-cli/src/workers/_helpers/invocation.rs b/crates/sqlbuild-cli/src/workers/_helpers/invocation.rs index f1721202a0..79bf5ed7a2 100644 --- a/crates/sqlbuild-cli/src/workers/_helpers/invocation.rs +++ b/crates/sqlbuild-cli/src/workers/_helpers/invocation.rs @@ -1,6 +1,7 @@ //! Both launchers hand off the same scoped invocation and exclude privileged credentials. use sqlbuild_core::command_output::constants::INVOCATION_CONTEXT_ENV; +use sqlbuild_core::process_environment::constants::RUN_TOKEN_VARIABLE; use sqlbuild_orchestration::platform::constants::PLATFORM_WEBHOOK_VARIABLE; use sqlbuild_orchestration::runs::models::RunClaim; use sqlbuild_orchestration::webhooks::constants::SECURITY_AUDIT_WEBHOOK_VARIABLE; @@ -42,7 +43,7 @@ pub(in crate::workers) fn environment( bearer: &str, ) -> [(&'static str, String); 2] { [ - ("SQLBUILD_RUN_TOKEN", bearer.into()), + (RUN_TOKEN_VARIABLE, bearer.into()), (INVOCATION_CONTEXT_ENV, serde_json::json!({ "run_id": claim.request.run_id, "integration": {"name": "sqlbuild", "run_id": claim.request.run_id, "job_name": claim.request.job_key}, diff --git a/crates/sqlbuild-cli/src/workers/_helpers/recovery.rs b/crates/sqlbuild-cli/src/workers/_helpers/recovery.rs index 397bb4bdf0..d98fd07d6e 100644 --- a/crates/sqlbuild-cli/src/workers/_helpers/recovery.rs +++ b/crates/sqlbuild-cli/src/workers/_helpers/recovery.rs @@ -67,6 +67,7 @@ impl Workers { exit: None, launch_failure: rejected.then_some("docker_configuration_rejected"), recovered: true, + group: None, }); if rejected { self.active[index] diff --git a/crates/sqlbuild-cli/src/workers/_helpers/shutdown.rs b/crates/sqlbuild-cli/src/workers/_helpers/shutdown.rs index fddd95b8c4..6e336d3752 100644 --- a/crates/sqlbuild-cli/src/workers/_helpers/shutdown.rs +++ b/crates/sqlbuild-cli/src/workers/_helpers/shutdown.rs @@ -36,12 +36,9 @@ impl ClaimedWorker { } let deadline = self.stopping.unwrap_or_else(Instant::now) + Duration::from_secs(60); let mut renew = tokio::time::interval(Duration::from_secs(RENEW_INTERVAL_SECONDS)); - loop { + let exit = loop { tokio::select! { - exit = child.wait() => { - self.exit = Some(exit?); - return Ok(()); - } + exit = child.wait() => break exit?, _ = tokio::time::sleep_until(deadline.into()), if !killed => { child.kill().await?; killed = true; @@ -54,7 +51,9 @@ impl ClaimedWorker { } } } - } + }; + self.record_exit(Some(exit)); + Ok(()) } async fn finish_shutdown( @@ -138,7 +137,7 @@ impl Workers { self.active.swap_remove(index); continue; } - Ok(exit) => self.active[index].exit = exit, + Ok(exit) => self.active[index].record_exit(exit), Err(error) => { failure.get_or_insert(error); continue; diff --git a/crates/sqlbuild-cli/src/workers/_helpers/supervisor.rs b/crates/sqlbuild-cli/src/workers/_helpers/supervisor.rs index 7ea00cf410..20d8e19f38 100644 --- a/crates/sqlbuild-cli/src/workers/_helpers/supervisor.rs +++ b/crates/sqlbuild-cli/src/workers/_helpers/supervisor.rs @@ -1,5 +1,6 @@ //! One privileged owner supervises both launchers; workers receive only claim-scoped HTTP. +use sqlbuild_core::process_environment::main::environment_without_env_file::environment_without_env_file; use std::io::Write; use std::process::{ExitStatus, Stdio}; use std::time::{Duration, Instant}; @@ -25,6 +26,7 @@ use sqlbuild_process_ownership::ownership::main::{ use tokio::process::Command; use uuid::Uuid; +use crate::dev_stop::main::stop_switch::stop_switch; use crate::workers::_helpers::invocation::{arguments, environment, excluded}; use crate::workers::constants::SLOW_SCHEDULER_CYCLE; use crate::workers::models::{ @@ -68,7 +70,8 @@ impl sqlbuild_orchestration::scheduler::types::RunLauncher for Workers { let worker = &mut self.active[index]; let mut state = observe_run(store, worker.claim.request.run_id).await?; if let Some(child) = worker.child.as_mut() { - worker.exit = worker.exit.or(child.try_wait().await?); + let exit = child.try_wait().await?; + worker.record_exit(exit); } if worker.exit.is_none() && let Some(child) = worker.child.as_mut() @@ -92,7 +95,8 @@ impl sqlbuild_orchestration::scheduler::types::RunLauncher for Workers { .is_some_and(|at| at.elapsed() >= Duration::from_secs(60)) { child.kill().await?; - worker.exit = child.try_wait().await?; + let exit = child.try_wait().await?; + worker.record_exit(exit); state = observe_run(store, worker.claim.request.run_id).await?; } } @@ -225,6 +229,7 @@ impl Workers { exit: None, launch_failure: None, recovered: false, + group: None, }); let worker = &mut self.active[index]; let claim = &worker.claim; @@ -298,6 +303,10 @@ impl Workers { .await?; let launched = match local_command { Some(command) => command.spawn().map(|child| { + worker.group = child.id(); + if let Some(group) = worker.group { + stop_switch().register_group(group); + } worker.child = Some(WorkerChild::Local(child)); }), None => { @@ -354,7 +363,7 @@ impl Workers { } } -/// The worker holds its claim's ownership before it runs any code; other platforms never adopt. +/// The worker holds its claim's ownership before it runs any code; other platforms never adopt. It leads its own process group, so a terminal's Ctrl+C reaches the server, not the worker, and stopping the worker stops everything it started. fn prepare_spawn( location: &LocalLauncher, claim: &RunClaim, @@ -367,14 +376,20 @@ fn prepare_spawn( .arg(&location.project_dir) .current_dir(&location.project_dir) .env_clear() - .envs(std::env::vars_os().filter(|(key, _)| { - key.to_str() - .is_none_or(|key| !excluded(key, control_variable)) - })) + .envs( + environment_without_env_file() + .into_iter() + .filter(|(key, _)| { + key.to_str() + .is_none_or(|key| !excluded(key, control_variable)) + }), + ) .envs(environment(claim, bearer)) .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::inherit()); + #[cfg(unix)] + std::os::unix::process::CommandExt::process_group(&mut command, 0); let (command, ownership) = prepare_worker(command, &location.claim(claim))?; let mut command = Command::from(command); command.kill_on_drop(true); @@ -410,7 +425,26 @@ impl LocalSpawn { } } +impl Drop for ClaimedWorker { + /// A worker dropped before its exit was seen no longer belongs to this scheduler's stop. + fn drop(&mut self) { + if let Some(group) = self.group.take() { + stop_switch().forget_group(group); + } + } +} + impl ClaimedWorker { + /// Record the worker's exit once it is seen; its process group may be reused from then on, so a forced stop, even one that retries shutdown while the store is away, must no longer signal it. + pub(in crate::workers) fn record_exit(&mut self, exit: Option) { + self.exit = self.exit.or(exit); + if self.exit.is_some() + && let Some(group) = self.group.take() + { + stop_switch().forget_group(group); + } + } + pub(in crate::workers) async fn publish_launch_failure( &mut self, store: &ControlStore, diff --git a/crates/sqlbuild-cli/src/workers/constants.rs b/crates/sqlbuild-cli/src/workers/constants.rs index 142ef1cfcf..1956252643 100644 --- a/crates/sqlbuild-cli/src/workers/constants.rs +++ b/crates/sqlbuild-cli/src/workers/constants.rs @@ -3,7 +3,7 @@ /// Immutable Docker image identities use the full SHA-256 hexadecimal digest. pub(super) const IMAGE_ID_HEX_LENGTH: usize = 64; -/// A scheduler cycle longer than this is logged with its phase timings. +/// A scheduler cycle longer than this, half the lease, is a real overrun and is logged with its phase timings. pub(super) const SLOW_SCHEDULER_CYCLE: std::time::Duration = std::time::Duration::from_secs( - sqlbuild_orchestration::scheduler::constants::RENEW_INTERVAL_SECONDS, + sqlbuild_orchestration::scheduler::constants::LEASE_TTL_SECONDS.unsigned_abs() / 2, ); diff --git a/crates/sqlbuild-cli/src/workers/main/terminate_child.rs b/crates/sqlbuild-cli/src/workers/main/terminate_child.rs index 1c2c371306..0b64de115b 100644 --- a/crates/sqlbuild-cli/src/workers/main/terminate_child.rs +++ b/crates/sqlbuild-cli/src/workers/main/terminate_child.rs @@ -1,21 +1,27 @@ -//! Signal only a child whose process handle is still owned by the caller. +//! Signal only a child whose process handle is still owned by the caller, with the process group it leads. use sqlbuild_orchestration::store::errors::ControlError; use tokio::process::Child; -pub(crate) fn terminate_child(child: &mut Child) -> Result<(), ControlError> { +/// SIGTERM the local worker's process group, or SIGKILL it when `kill`; a worker that already exited is fine. +pub(crate) fn terminate_child(child: &mut Child, kill: bool) -> Result<(), ControlError> { #[cfg(unix)] if let Some(id) = child.id() { let raw = i32::try_from(id) .map_err(|error| ControlError::Invalid(format!("invalid child process ID: {error}")))?; let pid = rustix::process::Pid::from_raw(raw) .ok_or_else(|| ControlError::Invalid("invalid child process ID".into()))?; - match rustix::process::kill_process(pid, rustix::process::Signal::TERM) { + let signal = if kill { + rustix::process::Signal::KILL + } else { + rustix::process::Signal::TERM + }; + match rustix::process::kill_process_group(pid, signal) { Ok(()) | Err(rustix::io::Errno::SRCH) => {} Err(error) => return Err(std::io::Error::from(error).into()), } } #[cfg(not(unix))] - let _ = child; + let _ = (child, kill); Ok(()) } diff --git a/crates/sqlbuild-cli/src/workers/mod.rs b/crates/sqlbuild-cli/src/workers/mod.rs index 59bf71d77a..94abf074a3 100644 --- a/crates/sqlbuild-cli/src/workers/mod.rs +++ b/crates/sqlbuild-cli/src/workers/mod.rs @@ -4,3 +4,6 @@ mod _helpers; mod constants; pub(crate) mod main; pub(crate) mod models; + +#[cfg(test)] +mod tests; diff --git a/crates/sqlbuild-cli/src/workers/models.rs b/crates/sqlbuild-cli/src/workers/models.rs index b8c679b950..09ae7aa202 100644 --- a/crates/sqlbuild-cli/src/workers/models.rs +++ b/crates/sqlbuild-cli/src/workers/models.rs @@ -124,6 +124,8 @@ pub(super) struct ClaimedWorker { pub(super) launch_failure: Option<&'static str>, /// Supervision resumed after a scheduler restart rather than from this scheduler's launch. pub(super) recovered: bool, + /// The process group a local worker this scheduler started leads, registered with the stop switch until its exit is seen, so a forced stop kills it on every Unix and never a reused group. + pub(super) group: Option, } /// Physical ownership survives leadership loss; only the current fence changes durable lifecycle. diff --git a/crates/sqlbuild-cli/src/workers/tests.rs b/crates/sqlbuild-cli/src/workers/tests.rs new file mode 100644 index 0000000000..84f6c5507b --- /dev/null +++ b/crates/sqlbuild-cli/src/workers/tests.rs @@ -0,0 +1,6 @@ +#[path = "tests/helpers.rs"] +mod helpers; +#[path = "tests/test_record_exit.rs"] +mod record_exit; +#[path = "tests/test_types.rs"] +mod test_types; diff --git a/crates/sqlbuild-cli/src/workers/tests/helpers.rs b/crates/sqlbuild-cli/src/workers/tests/helpers.rs new file mode 100644 index 0000000000..c0d3e53421 --- /dev/null +++ b/crates/sqlbuild-cli/src/workers/tests/helpers.rs @@ -0,0 +1,41 @@ +//! A claimed local worker without a child process, for supervision bookkeeping. + +use crate::workers::models::ClaimedWorker; + +/// A claimed worker that leads process group `group`, registered as a launch registers it. +pub(super) fn worker_leading(group: u32) -> ClaimedWorker { + let claim = serde_json::from_value(serde_json::json!({ + "claim_id": "00000000-0000-0000-0000-000000000001", + "request": { + "run_id": "00000000-0000-0000-0000-000000000002", + "location_id": "00000000-0000-0000-0000-000000000003", + "target": "development", + "snapshot_id": "00000000-0000-0000-0000-000000000004", + "image_id": null, + "kind": "job", + "origin": "manual", + "job_key": "orders", + "parent_run_id": null, + "root_run_id": "00000000-0000-0000-0000-000000000002", + "trigger_id": null, + "tick_id": null, + "rerun_of_run_id": null, + "requested_by": "test", + "priority": 0, + "selection": ["model:orders"], + "write_set": ["model:orders"], + "settings": {} + } + })) + .expect("a run claim"); + crate::dev_stop::main::stop_switch::stop_switch().register_group(group); + ClaimedWorker { + claim, + child: None, + stopping: None, + exit: None, + launch_failure: None, + recovered: false, + group: Some(group), + } +} diff --git a/crates/sqlbuild-cli/src/workers/tests/test_record_exit.rs b/crates/sqlbuild-cli/src/workers/tests/test_record_exit.rs new file mode 100644 index 0000000000..8d59d385b7 --- /dev/null +++ b/crates/sqlbuild-cli/src/workers/tests/test_record_exit.rs @@ -0,0 +1,49 @@ +//! A local worker's process group stays registered for a forced stop only until its exit is seen, so a group ID reused afterwards is never killed. + +use crate::dev_stop::main::stop_switch::stop_switch; +use crate::workers::models::WorkerExit; +use crate::workers::tests::helpers::worker_leading; +use crate::workers::tests::test_types::RecordExitTestCase; + +/// Far above the highest process ID any Unix hands out (Linux caps `pid_max` at 2^22, macOS and the BSDs at 99,999), so signalling these groups can never reach a real process. +const IMPOSSIBLE_GROUP: u32 = 2_000_000_001; + +#[test] +fn given_a_registered_worker_group_when_its_exit_is_seen_then_a_forced_stop_no_longer_signals_it() { + let test_cases = [ + RecordExitTestCase { + description: "the worker exited and was reaped", + group: IMPOSSIBLE_GROUP, + seen: Some(WorkerExit::Code(0)), + expected_registered: false, + }, + RecordExitTestCase { + description: "a recovered worker reported absent", + group: IMPOSSIBLE_GROUP + 1, + seen: Some(WorkerExit::Absent), + expected_registered: false, + }, + RecordExitTestCase { + description: "the worker is still running", + group: IMPOSSIBLE_GROUP + 2, + seen: None, + expected_registered: true, + }, + ]; + + for test_case in test_cases { + let mut worker = worker_leading(test_case.group); + + worker.record_exit(test_case.seen); + + let registered: bool = stop_switch() + .groups() + .contains(&i32::try_from(test_case.group).unwrap_or_default()); + assert_eq!( + registered, test_case.expected_registered, + "{}", + test_case.description + ); + drop(worker); + } +} diff --git a/crates/sqlbuild-cli/src/workers/tests/test_types.rs b/crates/sqlbuild-cli/src/workers/tests/test_types.rs new file mode 100644 index 0000000000..b9eb81fa77 --- /dev/null +++ b/crates/sqlbuild-cli/src/workers/tests/test_types.rs @@ -0,0 +1,13 @@ +//! Table rows for local worker supervision. + +use crate::workers::models::WorkerExit; + +/// A local worker whose process group is registered, and what supervision then sees of its exit. +pub(super) struct RecordExitTestCase { + pub(super) description: &'static str, + /// The group the worker leads: unique per case, since the stop switch is shared by the process, and never a real process ID. + pub(super) group: u32, + pub(super) seen: Option, + /// Whether a forced stop still signals the group afterwards. + pub(super) expected_registered: bool, +} diff --git a/crates/sqlbuild-cli/tests/native_commands/admin/test_admin.rs b/crates/sqlbuild-cli/tests/native_commands/admin/test_admin.rs index e308b9c0dd..be6ed9f890 100644 --- a/crates/sqlbuild-cli/tests/native_commands/admin/test_admin.rs +++ b/crates/sqlbuild-cli/tests/native_commands/admin/test_admin.rs @@ -140,6 +140,17 @@ fn given_a_standalone_control_server_when_bootstrapped_by_an_operator_then_scope assert_eq!(triggers[0].status.as_str(), case.expected_status, "{}", case.description); assert_eq!(triggers[0].last_tick_for.map(|value| value.to_rfc3339()).as_deref(), case.expected_cursor, "{}", case.description); } + for (change, extra, expected) in [ + ("skip-event", ["--event", "run:orders-1"], "skip-event is for sensors"), + ("pause", ["--event", "run:orders-1"], "--event is only valid for skip-event"), + ] { + let event_id = Uuid::now_v7().to_string(); + let mut arguments = vec!["change-trigger", &trigger_id, change, "--event-id", &event_id, "--reason", "Skip a stuck event"]; + arguments.extend_from_slice(&extra); + let refused = invoke_admin(&control, &arguments); + assert!(!refused.status.success(), "{change} is refused"); + assert!(String::from_utf8_lossy(&refused.stderr).contains(expected), "{change}: {}", String::from_utf8_lossy(&refused.stderr)); + } snapshot.generation = 2; snapshot.documents.get_mut("triggers").expect("trigger document")["daily_orders"]["default_status"] = serde_json::json!("running"); publish_remote_snapshot(&url, bearer, &snapshot).await.expect("publish a new default"); diff --git a/crates/sqlbuild-cli/tests/native_commands/test_control.rs b/crates/sqlbuild-cli/tests/native_commands/test_control.rs index 197e53199f..b1673e9d9d 100644 --- a/crates/sqlbuild-cli/tests/native_commands/test_control.rs +++ b/crates/sqlbuild-cli/tests/native_commands/test_control.rs @@ -379,13 +379,13 @@ fn given_a_control_store_when_running_server_migrate_then_dry_run_lists_and_migr StoreMigrationCommandTestCase { description: "migrate an empty store", arguments: &["server", "migrate"], - expected_stdout: "The control store is empty: created schema version 4.\n", + expected_stdout: "The control store is empty: created schema version 5.\n", expected_store: true, }, StoreMigrationCommandTestCase { description: "dry run on a current store", arguments: &["server", "migrate", "--dry-run"], - expected_stdout: "The control store is at schema version 4: nothing to migrate.\n", + expected_stdout: "The control store is at schema version 5: nothing to migrate.\n", expected_store: true, }, ]; diff --git a/crates/sqlbuild-cli/tests/native_commands/test_location_health.rs b/crates/sqlbuild-cli/tests/native_commands/test_location_health.rs index 37f938cdfd..3ad4b99559 100644 --- a/crates/sqlbuild-cli/tests/native_commands/test_location_health.rs +++ b/crates/sqlbuild-cli/tests/native_commands/test_location_health.rs @@ -64,7 +64,7 @@ fn given_location_health_reports_when_checking_health_then_down_falling_back_or_ description: "a provider secret is unset, even with a failed connection check", reports: &[ r#"{"kind":"connection","generation":2,"healthy":false}"#, - r#"{"kind":"provider_secrets","generation":2,"missing":1}"#, + r#"{"kind":"provider_secrets","generation":2,"missing":1,"providers":[]}"#, ], other_target_connections: 0, expected_state: "missing_secrets", @@ -73,8 +73,8 @@ fn given_location_health_reports_when_checking_health_then_down_falling_back_or_ LocationHealthTestCase { description: "a later load found every provider secret set", reports: &[ - r#"{"kind":"provider_secrets","generation":2,"missing":2}"#, - r#"{"kind":"provider_secrets","generation":3,"missing":0}"#, + r#"{"kind":"provider_secrets","generation":2,"missing":2,"providers":[]}"#, + r#"{"kind":"provider_secrets","generation":3,"missing":0,"providers":[]}"#, ], other_target_connections: 0, expected_state: "healthy", diff --git a/crates/sqlbuild-config/Cargo.toml b/crates/sqlbuild-config/Cargo.toml index 8b819bf109..beeeddafcc 100644 --- a/crates/sqlbuild-config/Cargo.toml +++ b/crates/sqlbuild-config/Cargo.toml @@ -8,6 +8,7 @@ publish.workspace = true rust-version.workspace = true [dependencies] +dotenvy.workspace = true saphyr-parser.workspace = true toml_edit.workspace = true toml_parser.workspace = true diff --git a/crates/sqlbuild-config/src/effective/constants.rs b/crates/sqlbuild-config/src/effective/constants.rs index 18b48d3613..14dad5e45e 100644 --- a/crates/sqlbuild-config/src/effective/constants.rs +++ b/crates/sqlbuild-config/src/effective/constants.rs @@ -245,4 +245,18 @@ pub(crate) const TARGET_FIELDS: &[TargetField] = &[ decided_by: &["pause_dynamic"], }, }, + TargetField { + group: None, + name: "env_file", + rule: MergeRule::Overlay { + decided_by: &["env_file"], + }, + }, + TargetField { + group: None, + name: "allow_missing_secrets", + rule: MergeRule::Overlay { + decided_by: &["allow_missing_secrets"], + }, + }, ]; diff --git a/crates/sqlbuild-config/src/env_file/_helpers/choice.rs b/crates/sqlbuild-config/src/env_file/_helpers/choice.rs new file mode 100644 index 0000000000..c3a31982b7 --- /dev/null +++ b/crates/sqlbuild-config/src/env_file/_helpers/choice.rs @@ -0,0 +1,88 @@ +//! The `env_file` the project and the selected target set. + +use std::path::Path; + +use sqlbuild_core::constants::PROJECT_CONFIG_FILENAME; + +use crate::env_file::constants::DEFAULT_ENV_FILE; +use crate::env_file::models::{ChoiceSource, EnvFileChoice}; +use crate::models::ConfigValue; +use crate::project::main::load_project_config::load_project_config; +use crate::project::main::project_config_paths::project_config_paths; +use crate::project::models::Built; + +fn field<'a>(built: &'a Built, name: &str) -> Option<&'a Built> { + match built { + Built::Object(_, fields) => fields + .iter() + .find(|(key, _)| *key == name) + .map(|(_, value)| value), + Built::Dict(entries) => entries + .iter() + .find(|(key, _)| key == name) + .map(|(_, value)| value), + _ => None, + } +} + +fn text(built: Option<&Built>) -> Option { + match built { + Some(Built::Value(ConfigValue::String(text))) => Some(text.clone()), + _ => None, + } +} + +/// The selected target's `env_file`, else the project's, with where it was set. +pub(crate) fn configured_source( + project: &Built, + (project_dir, target): (&Path, Option<&str>), +) -> ChoiceSource { + let from_target: Option = target.and_then(|name| { + text( + field(project, "targets") + .and_then(|targets| field(targets, name)) + .and_then(|config| field(config, "env_file")), + ) + }); + if from_target.is_some() { + return ChoiceSource { + text: from_target, + target: target.map(str::to_owned), + project_dir: project_dir.to_path_buf(), + }; + } + ChoiceSource { + text: text(field(project, "env_file")), + target: None, + project_dir: project_dir.to_path_buf(), + } +} + +/// The path to read, relative to the project directory unless absolute; `""` turns loading off. +pub(crate) fn choice(source: ChoiceSource) -> EnvFileChoice { + let configured: bool = source.text.is_some(); + let written: String = source.text.unwrap_or_else(|| DEFAULT_ENV_FILE.to_owned()); + let setting: String = match (&source.target, configured) { + (Some(target), _) => format!("[targets.{target}] env_file in {PROJECT_CONFIG_FILENAME}"), + (None, true) => format!("env_file in {PROJECT_CONFIG_FILENAME}"), + (None, false) => format!("the default env_file = \"{DEFAULT_ENV_FILE}\""), + }; + EnvFileChoice { + path: (!written.is_empty()).then(|| source.project_dir.join(&written)), + display: written, + configured, + setting, + } +} + +/// The chosen env file, `None` without a valid `sqlbuild_project.toml`, which the command itself reports. +pub(crate) fn env_file_choice(project_dir: &Path, target: Option<&str>) -> Option { + let paths = project_config_paths(project_dir); + if !paths.project.is_file() { + return None; + } + match load_project_config(&paths) { + Ok(project) => Some(choice(configured_source(&project, (project_dir, target)))), + Err(_invalid) => None, + } +} diff --git a/crates/sqlbuild-config/src/env_file/_helpers/mod.rs b/crates/sqlbuild-config/src/env_file/_helpers/mod.rs new file mode 100644 index 0000000000..f3a61bc038 --- /dev/null +++ b/crates/sqlbuild-config/src/env_file/_helpers/mod.rs @@ -0,0 +1,3 @@ +pub(crate) mod choice; +pub(crate) mod overlay; +pub(crate) mod read; diff --git a/crates/sqlbuild-config/src/env_file/_helpers/overlay.rs b/crates/sqlbuild-config/src/env_file/_helpers/overlay.rs new file mode 100644 index 0000000000..589f18a416 --- /dev/null +++ b/crates/sqlbuild-config/src/env_file/_helpers/overlay.rs @@ -0,0 +1,99 @@ +//! The overlay and marker a load of the chosen env file gives every process. + +use std::collections::BTreeSet; +use std::ffi::OsString; +use std::path::Path; + +use sqlbuild_core::process_environment::constants::ENV_FILE_MARKER_VARIABLE; +use sqlbuild_core::process_environment::main::environment_var_os::environment_var_os; +use sqlbuild_core::process_environment::main::marker_json::marker_json; +use sqlbuild_core::process_environment::models::{EnvFileMarker, EnvironmentOverlay}; + +use crate::env_file::_helpers::read::{read_pairs, shared_read_warning}; +use crate::env_file::errors::EnvFileError; +use crate::env_file::models::EnvFileChoice; +use crate::env_file::types::ChosenPairs; + +/// The file's pairs and its permissions warning; `None` pairs when loading is off or an unconfigured file is absent. +pub(crate) fn chosen_pairs(choice: &EnvFileChoice) -> Result { + let Some(path) = &choice.path else { + return Ok((None, None)); + }; + match read_pairs(path, choice)? { + Some(pairs) => Ok((Some(pairs), shared_read_warning(path, choice))), + None if choice.configured => Err(EnvFileError::Missing { + choice: choice.clone(), + }), + None => Ok((None, None)), + } +} + +/// The variables a load takes and those the environment already set, sorted; `previous` names an earlier load's. +pub(crate) fn taken_variables( + pairs: Vec<(String, String)>, + previous: &[String], +) -> ( + Vec<(OsString, OsString)>, + BTreeSet, + BTreeSet, +) { + let mut set: Vec<(OsString, OsString)> = Vec::new(); + let mut names: BTreeSet = BTreeSet::new(); + let mut overridden: BTreeSet = BTreeSet::new(); + for (name, value) in pairs { + if name == ENV_FILE_MARKER_VARIABLE { + continue; + } + let earlier: bool = previous.contains(&name); + if !earlier && environment_var_os(&name).is_some() { + overridden.insert(name); + continue; + } + set.push((OsString::from(&name), OsString::from(value))); + names.insert(name); + } + (set, names, overridden) +} + +/// The overlay: the variables taken, an earlier load's variables this one drops removed, and the marker. +pub(crate) fn overlay_with_marker( + set: Vec<(OsString, OsString)>, + previous: Vec, + marker: &EnvFileMarker, +) -> EnvironmentOverlay { + let mut overlay = EnvironmentOverlay { + set, + remove: previous + .into_iter() + .filter(|name| !marker.names.contains(name)) + .map(OsString::from) + .collect(), + }; + overlay.set.push(( + OsString::from(ENV_FILE_MARKER_VARIABLE), + OsString::from(marker_json(marker)), + )); + overlay +} + +/// The marker child processes inherit, so they don't load the same file again. +pub(crate) fn marker_for( + (project_dir, target): (&Path, Option<&str>), + choice: &EnvFileChoice, + (loaded, names, overridden): (bool, BTreeSet, BTreeSet), +) -> EnvFileMarker { + let canonical = project_dir + .canonicalize() + .unwrap_or_else(|_| project_dir.to_path_buf()); + EnvFileMarker { + project_dir: canonical.to_string_lossy().into_owned(), + target: target.map(str::to_owned), + path: choice + .path + .as_ref() + .map(|path| path.to_string_lossy().into_owned()), + loaded, + names: names.into_iter().collect(), + overridden: overridden.into_iter().collect(), + } +} diff --git a/crates/sqlbuild-config/src/env_file/_helpers/read.rs b/crates/sqlbuild-config/src/env_file/_helpers/read.rs new file mode 100644 index 0000000000..f737b87984 --- /dev/null +++ b/crates/sqlbuild-config/src/env_file/_helpers/read.rs @@ -0,0 +1,102 @@ +//! The variables an env file sets, read with dotenv semantics. + +use std::path::Path; + +use crate::env_file::errors::EnvFileError; +use crate::env_file::models::EnvFileChoice; + +/// The physical line number where the logical line `text` starts, `1` when it cannot be found. +fn line_number(path: &Path, text: &str) -> usize { + let Ok(contents) = std::fs::read_to_string(path) else { + return 1; + }; + let first: &str = text.lines().next().unwrap_or_default().trim_end(); + contents + .lines() + .position(|line| line.trim_end() == first) + .map_or(1, |index| index + 1) +} + +/// Each `KEY=value` in file order, a later duplicate replacing an earlier one; `None` when there is no file. +pub(crate) fn read_pairs( + path: &Path, + choice: &EnvFileChoice, +) -> Result>, EnvFileError> { + let iter = match dotenvy::from_path_iter(path) { + Ok(iter) => iter, + Err(error) if error.not_found() => return Ok(None), + Err(error) => { + return Err(EnvFileError::Unreadable { + choice: choice.clone(), + reason: error.to_string(), + }); + } + }; + let mut pairs: Vec<(String, String)> = Vec::new(); + for item in iter { + match item { + Ok((name, value)) => { + pairs.retain(|(kept, _)| *kept != name); + pairs.push((name, value)); + } + Err(dotenvy::Error::LineParse(text, _)) => { + return Err(EnvFileError::Invalid { + choice: choice.clone(), + line: line_number(path, &text), + }); + } + Err(dotenvy::Error::Io(error)) => { + return Err(EnvFileError::Unreadable { + choice: choice.clone(), + reason: error.kind().to_string(), + }); + } + Err(dotenvy::Error::EnvVar(_)) => { + return Err(EnvFileError::Unreadable { + choice: choice.clone(), + reason: "a value is not valid Unicode".to_owned(), + }); + } + Err(_) => { + return Err(EnvFileError::Unreadable { + choice: choice.clone(), + reason: "unexpected parse failure".to_owned(), + }); + } + } + } + Ok(Some(pairs)) +} + +/// The warning when the group or others may read the file. +#[cfg(unix)] +pub(crate) fn shared_read_warning(path: &Path, choice: &EnvFileChoice) -> Option { + use std::os::unix::fs::PermissionsExt; + + use crate::env_file::constants::SHARED_READ_BITS; + + let mode: u32 = match std::fs::metadata(path) { + Ok(metadata) => metadata.permissions().mode(), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return None, + Err(error) => { + return Some(format!( + "cannot check who may read env file {}: {error}", + choice.display + )); + } + }; + (mode & SHARED_READ_BITS != 0).then(|| { + format!( + "env file {} is readable by group or others (mode {:o}); restrict it with chmod 600 {}", + choice.display, + mode & 0o777, + choice.display + ) + }) +} + +/// Other platforms have no group or other read bits. +#[cfg(not(unix))] +pub(crate) fn shared_read_warning(_path: &Path, _choice: &EnvFileChoice) -> Option { + None +} diff --git a/crates/sqlbuild-config/src/env_file/constants.rs b/crates/sqlbuild-config/src/env_file/constants.rs new file mode 100644 index 0000000000..bf0b03fa70 --- /dev/null +++ b/crates/sqlbuild-config/src/env_file/constants.rs @@ -0,0 +1,7 @@ +//! The env file a project loads when it sets none. + +/// `env_file` when neither the project nor the selected target sets one. +pub(crate) const DEFAULT_ENV_FILE: &str = ".env"; +/// Permission bits that let the group or others read a file. +#[cfg(unix)] +pub(crate) const SHARED_READ_BITS: u32 = 0o044; diff --git a/crates/sqlbuild-config/src/env_file/errors.rs b/crates/sqlbuild-config/src/env_file/errors.rs new file mode 100644 index 0000000000..14ffbf344f --- /dev/null +++ b/crates/sqlbuild-config/src/env_file/errors.rs @@ -0,0 +1,55 @@ +//! Why the chosen env file could not be loaded. + +use crate::env_file::models::EnvFileChoice; + +/// Why the chosen env file could not be loaded; no message ever includes a value. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum EnvFileError { + /// `env_file` names a file that does not exist. + Missing { choice: EnvFileChoice }, + /// The file exists but could not be read. + Unreadable { + choice: EnvFileChoice, + reason: String, + }, + /// A line is not `KEY=value`; only its number is reported, never its text. + Invalid { choice: EnvFileChoice, line: usize }, +} + +impl EnvFileError { + /// The one-line message, naming the file and where it was set. + #[must_use] + pub fn message(&self) -> String { + match self { + Self::Missing { choice } => format!( + "env file {} does not exist (set by {})", + choice.display, choice.setting + ), + Self::Unreadable { choice, reason } => format!( + "cannot read env file {} (set by {}): {reason}", + choice.display, choice.setting + ), + Self::Invalid { choice, line } => format!( + "env file {} line {line} is not KEY=value (set by {})", + choice.display, choice.setting + ), + } + } + + /// What to change. + #[must_use] + pub fn help(&self) -> String { + match self { + Self::Missing { choice } => format!( + "create {}, or change env_file in sqlbuild_project.toml (\"\" turns it off)", + choice.display + ), + Self::Unreadable { choice, .. } => { + format!("check that {} is a readable file", choice.display) + } + Self::Invalid { .. } => "write each line as KEY=value, quoting values with spaces; \ + # starts a comment" + .to_owned(), + } + } +} diff --git a/crates/sqlbuild-config/src/env_file/main/load_env_file.rs b/crates/sqlbuild-config/src/env_file/main/load_env_file.rs new file mode 100644 index 0000000000..5a06d1ef9b --- /dev/null +++ b/crates/sqlbuild-config/src/env_file/main/load_env_file.rs @@ -0,0 +1,36 @@ +//! Load the chosen env file under the environment's precedence. + +use std::path::Path; + +use sqlbuild_core::process_environment::main::env_file_marker::env_file_marker; + +use crate::env_file::_helpers::choice::env_file_choice; +use crate::env_file::_helpers::overlay::{ + chosen_pairs, marker_for, overlay_with_marker, taken_variables, +}; +use crate::env_file::errors::EnvFileError; +use crate::env_file::models::EnvFileLoad; + +/// The overlay giving every process the env file's variables the environment leaves unset; `None` without a valid project. +pub fn load_env_file( + project_dir: &Path, + target: Option<&str>, +) -> Result, EnvFileError> { + let Some(choice) = env_file_choice(project_dir, target) else { + return Ok(None); + }; + let previous: Vec = env_file_marker() + .map(|marker| marker.names) + .unwrap_or_default(); + let (pairs, warning) = chosen_pairs(&choice)?; + let loaded: bool = pairs.is_some(); + let (set, names, overridden) = taken_variables(pairs.unwrap_or_default(), &previous); + let marker = marker_for((project_dir, target), &choice, (loaded, names, overridden)); + let overlay = overlay_with_marker(set, previous, &marker); + Ok(Some(EnvFileLoad { + choice, + overlay, + marker, + warning, + })) +} diff --git a/crates/sqlbuild-config/src/env_file/main/mod.rs b/crates/sqlbuild-config/src/env_file/main/mod.rs new file mode 100644 index 0000000000..5ade495f1e --- /dev/null +++ b/crates/sqlbuild-config/src/env_file/main/mod.rs @@ -0,0 +1 @@ +pub mod load_env_file; diff --git a/crates/sqlbuild-config/src/env_file/mod.rs b/crates/sqlbuild-config/src/env_file/mod.rs new file mode 100644 index 0000000000..e9b32021dc --- /dev/null +++ b/crates/sqlbuild-config/src/env_file/mod.rs @@ -0,0 +1,9 @@ +pub(crate) mod _helpers; +pub(crate) mod constants; +pub mod errors; +pub mod main; +pub mod models; +pub(crate) mod types; + +#[cfg(test)] +mod tests; diff --git a/crates/sqlbuild-config/src/env_file/models.rs b/crates/sqlbuild-config/src/env_file/models.rs new file mode 100644 index 0000000000..8093e30e0d --- /dev/null +++ b/crates/sqlbuild-config/src/env_file/models.rs @@ -0,0 +1,36 @@ +//! Which env file a command loads, what it took from it, and why it could not. + +use std::path::PathBuf; + +use sqlbuild_core::process_environment::models::{EnvFileMarker, EnvironmentOverlay}; + +/// The env file the project and target choose, before it is read. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct EnvFileChoice { + /// The resolved path; `None` when `env_file = ""` turns loading off. + pub path: Option, + /// The path as written, such as `.env`, for messages. + pub display: String, + /// Whether `env_file` was set; a missing file is then an error rather than skipped. + pub configured: bool, + /// Where it was set, such as `[targets.uat] env_file in sqlbuild_project.toml`. + pub setting: String, +} + +/// What loading the chosen env file gives every process this command starts. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct EnvFileLoad { + pub choice: EnvFileChoice, + pub overlay: EnvironmentOverlay, + pub marker: EnvFileMarker, + /// Set when the file is readable by its group or others. + pub warning: Option, +} + +/// Where the chosen path came from, for `EnvFileChoice::setting`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct ChoiceSource { + pub(crate) text: Option, + pub(crate) target: Option, + pub(crate) project_dir: PathBuf, +} diff --git a/crates/sqlbuild-config/src/env_file/tests.rs b/crates/sqlbuild-config/src/env_file/tests.rs new file mode 100644 index 0000000000..517c317657 --- /dev/null +++ b/crates/sqlbuild-config/src/env_file/tests.rs @@ -0,0 +1,6 @@ +#[path = "tests/helpers.rs"] +mod helpers; +#[path = "tests/test_load_env_file.rs"] +mod load_env_file; +#[path = "tests/test_types.rs"] +mod test_types; diff --git a/crates/sqlbuild-config/src/env_file/tests/helpers.rs b/crates/sqlbuild-config/src/env_file/tests/helpers.rs new file mode 100644 index 0000000000..6017522b3a --- /dev/null +++ b/crates/sqlbuild-config/src/env_file/tests/helpers.rs @@ -0,0 +1,82 @@ +use std::ffi::OsString; +use std::path::Path; + +use sqlbuild_core::process_environment::constants::ENV_FILE_MARKER_VARIABLE; +use sqlbuild_core::process_environment::main::marker_json::marker_json; +use sqlbuild_core::process_environment::models::{EnvFileMarker, EnvironmentOverlay}; +use tempfile::TempDir; + +use crate::env_file::models::EnvFileLoad; + +/// A project with `toml` after its `name` and `adapter`, and `files` readable by their owner only. +pub(super) fn project(toml: &str, files: &[(&str, &str)]) -> TempDir { + let directory = TempDir::new().expect("temporary directory"); + std::fs::write( + directory.path().join("sqlbuild_project.toml"), + format!("name = \"shop\"\nadapter = \"duckdb\"\n{toml}"), + ) + .expect("project file"); + for (path, contents) in files { + let path = directory.path().join(path); + std::fs::create_dir_all(path.parent().expect("parent")).expect("directory"); + std::fs::write(&path, contents).expect("env file"); + with_mode(&path, 0o600); + } + directory +} + +/// Set a file's permission bits; other platforms have none to set. +#[cfg(unix)] +pub(super) fn with_mode(path: &Path, mode: u32) { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).expect("chmod"); +} + +/// Set a file's permission bits; other platforms have none to set. +#[cfg(not(unix))] +pub(super) fn with_mode(_path: &Path, _mode: u32) {} + +/// The variables a load sets for every process, the marker aside. +pub(super) fn set_pairs(load: &EnvFileLoad) -> Vec<(String, String)> { + load.overlay + .set + .iter() + .filter(|(name, _)| name != ENV_FILE_MARKER_VARIABLE) + .map(|(name, value)| { + ( + name.to_string_lossy().into_owned(), + value.to_string_lossy().into_owned(), + ) + }) + .collect() +} + +/// The environment an earlier load of `project_dir`'s `.env` left: `earlier` set, and the marker naming them. +pub(super) fn earlier_load(project_dir: &Path, earlier: &[(&str, &str)]) -> EnvironmentOverlay { + let mut names: Vec = earlier.iter().map(|(name, _)| (*name).to_owned()).collect(); + names.sort(); + let marker = EnvFileMarker { + project_dir: project_dir + .canonicalize() + .expect("project directory") + .to_string_lossy() + .into_owned(), + target: None, + path: Some(project_dir.join(".env").to_string_lossy().into_owned()), + loaded: true, + names, + overridden: Vec::new(), + }; + let mut set: Vec<(OsString, OsString)> = earlier + .iter() + .map(|(name, value)| (OsString::from(name), OsString::from(value))) + .collect(); + set.push(( + OsString::from(ENV_FILE_MARKER_VARIABLE), + OsString::from(marker_json(&marker)), + )); + EnvironmentOverlay { + set, + remove: Vec::new(), + } +} diff --git a/crates/sqlbuild-config/src/env_file/tests/test_load_env_file.rs b/crates/sqlbuild-config/src/env_file/tests/test_load_env_file.rs new file mode 100644 index 0000000000..a16ddaad41 --- /dev/null +++ b/crates/sqlbuild-config/src/env_file/tests/test_load_env_file.rs @@ -0,0 +1,251 @@ +use crate::env_file::main::load_env_file::load_env_file; +use crate::env_file::tests::helpers::{earlier_load, project, set_pairs, with_mode}; +use crate::env_file::tests::test_types::{ + EnvFileFailureTestCase, EnvFileTestCase, EnvironmentWinsTestCase, ReloadTestCase, + SharedReadTestCase, +}; +use sqlbuild_core::process_environment::main::install_environment_overlay::install_environment_overlay; +use sqlbuild_core::process_environment::models::EnvironmentOverlay; + +#[test] +fn given_project_and_target_env_files_when_loading_then_the_chosen_file_fills_unset_variables() { + let test_cases = [ + EnvFileTestCase { + description: "the default .env loads, with quotes, comments and export", + project: "", + files: &[( + ".env", + "# provider settings\nSQB_T1_TOKEN=abc\nSQB_T1_QUOTED=\"two words\" # note\nexport SQB_T1_EXPORTED='x=y'\n", + )], + target: None, + expected_display: ".env", + expected_loaded: true, + expected_set: &[ + ("SQB_T1_TOKEN", "abc"), + ("SQB_T1_QUOTED", "two words"), + ("SQB_T1_EXPORTED", "x=y"), + ], + }, + EnvFileTestCase { + description: "a later duplicate replaces an earlier one", + project: "", + files: &[(".env", "SQB_T2_TOKEN=first\nSQB_T2_TOKEN=second\n")], + target: None, + expected_display: ".env", + expected_loaded: true, + expected_set: &[("SQB_T2_TOKEN", "second")], + }, + EnvFileTestCase { + description: "a missing default .env is fine", + project: "", + files: &[], + target: None, + expected_display: ".env", + expected_loaded: false, + expected_set: &[], + }, + EnvFileTestCase { + description: "the selected target's env_file replaces the project's", + project: "env_file = \"project.env\"\n[targets.uat]\nenv_file = \"conf/uat.env\"\n", + files: &[ + ("project.env", "SQB_T3_PROJECT=yes\n"), + ("conf/uat.env", "SQB_T3_UAT=yes\n"), + ], + target: Some("uat"), + expected_display: "conf/uat.env", + expected_loaded: true, + expected_set: &[("SQB_T3_UAT", "yes")], + }, + EnvFileTestCase { + description: "a target without env_file keeps the project's", + project: "env_file = \"project.env\"\n[targets.dev]\nschema = \"dev\"\n", + files: &[("project.env", "SQB_T4_PROJECT=yes\n")], + target: Some("dev"), + expected_display: "project.env", + expected_loaded: true, + expected_set: &[("SQB_T4_PROJECT", "yes")], + }, + EnvFileTestCase { + description: "env_file = \"\" turns loading off", + project: "env_file = \"\"\n", + files: &[(".env", "SQB_T5_TOKEN=abc\n")], + target: None, + expected_display: "", + expected_loaded: false, + expected_set: &[], + }, + EnvFileTestCase { + description: "a target's env_file = \"\" turns off the project's", + project: "[targets.ci]\nenv_file = \"\"\n", + files: &[(".env", "SQB_T6_TOKEN=abc\n")], + target: Some("ci"), + expected_display: "", + expected_loaded: false, + expected_set: &[], + }, + ]; + for test_case in test_cases { + let directory = project(test_case.project, test_case.files); + let load = load_env_file(directory.path(), test_case.target) + .expect(test_case.description) + .expect("a project"); + assert_eq!( + load.choice.display, test_case.expected_display, + "{}", + test_case.description + ); + assert_eq!( + load.marker.loaded, test_case.expected_loaded, + "{}", + test_case.description + ); + let expected: Vec<(String, String)> = test_case + .expected_set + .iter() + .map(|(name, value)| ((*name).to_owned(), (*value).to_owned())) + .collect(); + assert_eq!(set_pairs(&load), expected, "{}", test_case.description); + assert!(load.warning.is_none(), "{}", test_case.description); + } +} + +#[test] +fn given_a_variable_already_in_the_environment_when_loading_then_the_environment_wins() { + let test_cases = [EnvironmentWinsTestCase { + description: "PATH stays the environment's; the file fills the rest", + file: "PATH=/from/file\nSQB_T7_TOKEN=abc\n", + expected_set: &[("SQB_T7_TOKEN", "abc")], + expected_names: &["SQB_T7_TOKEN"], + expected_overridden: &["PATH"], + }]; + for test_case in test_cases { + let directory = project("", &[(".env", test_case.file)]); + + let load = load_env_file(directory.path(), None) + .expect(test_case.description) + .expect(test_case.description); + + let expected: Vec<(String, String)> = test_case + .expected_set + .iter() + .map(|(name, value)| ((*name).to_owned(), (*value).to_owned())) + .collect(); + assert_eq!(set_pairs(&load), expected, "{}", test_case.description); + assert_eq!( + load.marker.names, test_case.expected_names, + "{}", + test_case.description + ); + assert_eq!( + load.marker.overridden, test_case.expected_overridden, + "{}", + test_case.description + ); + } +} + +#[test] +fn given_an_env_file_that_cannot_load_when_loading_then_the_error_names_it_but_never_a_value() { + let test_cases = [ + EnvFileFailureTestCase { + description: "a configured env file that does not exist", + project: "[targets.uat]\nenv_file = \"missing/uat.env\"\n", + files: &[], + target: Some("uat"), + expected_message: "env file missing/uat.env does not exist (set by [targets.uat] env_file in sqlbuild_project.toml)", + }, + EnvFileFailureTestCase { + description: "an invalid line, reported by its number only", + project: "", + files: &[(".env", "SQB_T8_OK=1\n\nnot a pair s3cr3t\n")], + target: None, + expected_message: "env file .env line 3 is not KEY=value (set by the default env_file = \".env\")", + }, + ]; + for test_case in test_cases { + let directory = project(test_case.project, test_case.files); + + let error = + load_env_file(directory.path(), test_case.target).expect_err(test_case.description); + + assert_eq!( + error.message(), + test_case.expected_message, + "{}", + test_case.description + ); + } +} + +#[cfg(unix)] +#[test] +fn given_env_file_permissions_when_loading_then_a_file_others_can_read_warns() { + let test_cases = [ + SharedReadTestCase { + description: "readable by group and others", + mode: 0o644, + expected_warning: Some( + "env file .env is readable by group or others (mode 644); restrict it with chmod 600 .env", + ), + }, + SharedReadTestCase { + description: "readable by its owner only", + mode: 0o600, + expected_warning: None, + }, + ]; + for test_case in test_cases { + let directory = project("", &[(".env", "SQB_T9_TOKEN=abc\n")]); + with_mode(&directory.path().join(".env"), test_case.mode); + + let load = load_env_file(directory.path(), None) + .expect(test_case.description) + .expect(test_case.description); + + assert_eq!( + load.warning.as_deref(), + test_case.expected_warning, + "{}", + test_case.description + ); + } +} + +#[test] +fn given_variables_an_earlier_load_took_when_loading_again_then_the_file_replaces_or_unsets_them() { + let test_cases = [ReloadTestCase { + description: "a value the earlier load took is replaced, and one the file dropped is unset", + file: "SQB_T10_KEPT=new\n", + earlier: &[("SQB_T10_KEPT", "old"), ("SQB_T10_DROPPED", "old")], + expected_set: &[("SQB_T10_KEPT", "new")], + expected_remove: &["SQB_T10_DROPPED"], + }]; + for test_case in test_cases { + let directory = project("", &[(".env", test_case.file)]); + install_environment_overlay(earlier_load(directory.path(), test_case.earlier)); + + let reloaded = load_env_file(directory.path(), None); + install_environment_overlay(EnvironmentOverlay::default()); + let reloaded = reloaded + .expect(test_case.description) + .expect(test_case.description); + + let expected: Vec<(String, String)> = test_case + .expected_set + .iter() + .map(|(name, value)| ((*name).to_owned(), (*value).to_owned())) + .collect(); + assert_eq!(set_pairs(&reloaded), expected, "{}", test_case.description); + let removed: Vec = reloaded + .overlay + .remove + .iter() + .map(|name| name.to_string_lossy().into_owned()) + .collect(); + assert_eq!( + removed, test_case.expected_remove, + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-config/src/env_file/tests/test_types.rs b/crates/sqlbuild-config/src/env_file/tests/test_types.rs new file mode 100644 index 0000000000..b3d02424e7 --- /dev/null +++ b/crates/sqlbuild-config/src/env_file/tests/test_types.rs @@ -0,0 +1,47 @@ +/// One project, its env file and the variables a load takes from it. +pub(super) struct EnvFileTestCase { + pub(super) description: &'static str, + /// `sqlbuild_project.toml` after the required `name` and `adapter`. + pub(super) project: &'static str, + /// Files to write, relative to the project directory. + pub(super) files: &'static [(&'static str, &'static str)], + pub(super) target: Option<&'static str>, + pub(super) expected_display: &'static str, + pub(super) expected_loaded: bool, + /// `(name, value)` set for every process, the marker aside. + pub(super) expected_set: &'static [(&'static str, &'static str)], +} + +/// A `.env` some of whose variables the environment already sets. +pub(super) struct EnvironmentWinsTestCase { + pub(super) description: &'static str, + pub(super) file: &'static str, + pub(super) expected_set: &'static [(&'static str, &'static str)], + pub(super) expected_names: &'static [&'static str], + pub(super) expected_overridden: &'static [&'static str], +} + +/// A project whose env file cannot load, and the error's message. +pub(super) struct EnvFileFailureTestCase { + pub(super) description: &'static str, + pub(super) project: &'static str, + pub(super) files: &'static [(&'static str, &'static str)], + pub(super) target: Option<&'static str>, + pub(super) expected_message: &'static str, +} + +/// A `.env` with permission bits, and the warning a load gives. +pub(super) struct SharedReadTestCase { + pub(super) description: &'static str, + pub(super) mode: u32, + pub(super) expected_warning: Option<&'static str>, +} + +/// A `.env` loaded again after an earlier load took `earlier` from it. +pub(super) struct ReloadTestCase { + pub(super) description: &'static str, + pub(super) file: &'static str, + pub(super) earlier: &'static [(&'static str, &'static str)], + pub(super) expected_set: &'static [(&'static str, &'static str)], + pub(super) expected_remove: &'static [&'static str], +} diff --git a/crates/sqlbuild-config/src/env_file/types.rs b/crates/sqlbuild-config/src/env_file/types.rs new file mode 100644 index 0000000000..dfc7de2f7b --- /dev/null +++ b/crates/sqlbuild-config/src/env_file/types.rs @@ -0,0 +1,4 @@ +//! Shapes the env file loader passes between its steps. + +/// The chosen file's `KEY=value` pairs, `None` when nothing was read, and its permissions warning. +pub(crate) type ChosenPairs = (Option>, Option); diff --git a/crates/sqlbuild-config/src/lib.rs b/crates/sqlbuild-config/src/lib.rs index 66fb1a8c59..8aca4a0a02 100644 --- a/crates/sqlbuild-config/src/lib.rs +++ b/crates/sqlbuild-config/src/lib.rs @@ -7,6 +7,7 @@ pub(crate) mod constants; pub mod dbt_manifest; pub mod dbt_profile; pub mod effective; +pub mod env_file; pub mod errors; pub mod models; pub mod project; diff --git a/crates/sqlbuild-config/src/project/_helpers/documents.rs b/crates/sqlbuild-config/src/project/_helpers/documents.rs index 3c940a56aa..04a2ca9100 100644 --- a/crates/sqlbuild-config/src/project/_helpers/documents.rs +++ b/crates/sqlbuild-config/src/project/_helpers/documents.rs @@ -6,8 +6,8 @@ use crate::project::_helpers::defaults::{ load_defaults, load_materialization_defaults, load_path_defaults, }; use crate::project::_helpers::fields::{ - coerce_mapping, get, has, object, optional_mapping, optional_str, require_str, string_mapping, - text_or_none, + coerce_mapping, get, has, object, optional_mapping, optional_str, optional_text_allowing_empty, + require_str, string_mapping, text_or_none, }; use crate::project::_helpers::help::{ Setting, SettingValue, join_helps, setting_help, setting_note, @@ -25,9 +25,9 @@ use crate::project::_helpers::targets::{ }; use crate::project::_helpers::values::is_truthy; use crate::project::constants::{ - ALLOW_MISSING_SECRETS_KEY, COLUMN_CONTRACT_MODES, LEGACY_COLUMN_CONTRACT_MODE_KEY, - LEGACY_EVENT_EXPORTERS_KEY, LOCAL_CONFIG_FILENAME, POOLS_KEY, QUERY_CHANGE_TRACKING_KEY, - REQUIRE_SQL_ANALYSIS_KEY, SHARED_POLICY_SETTINGS, SQL_ANALYSIS_KEY, + ALLOW_MISSING_SECRETS_KEY, COLUMN_CONTRACT_MODES, ENV_FILE_KEY, + LEGACY_COLUMN_CONTRACT_MODE_KEY, LEGACY_EVENT_EXPORTERS_KEY, LOCAL_CONFIG_FILENAME, POOLS_KEY, + QUERY_CHANGE_TRACKING_KEY, REQUIRE_SQL_ANALYSIS_KEY, SHARED_POLICY_SETTINGS, SQL_ANALYSIS_KEY, }; use crate::project::errors::{ConfigFailure, FailureClass, LoadFailure, MessagePiece}; use crate::project::models::{ @@ -200,7 +200,9 @@ fn sections(payload: &Entries) -> Loaded { ), ) .with_help(format!( - "move it to {LOCAL_CONFIG_FILENAME}, or set SQLBUILD_ALLOW_MISSING_SECRETS=1 in CI" + "move it to {LOCAL_CONFIG_FILENAME}, set SQLBUILD_ALLOW_MISSING_SECRETS=1 in CI, or list \ + the providers whose secrets a target may lack in [targets.] \ + {ALLOW_MISSING_SECRETS_KEY}" ))); } Ok(vec![ @@ -310,6 +312,10 @@ fn project_fields(payload: &Entries) -> Loaded { let settings = &fields[5].1; reject_untracked_janitor(&operations[0].1, settings)?; fields.extend(operations); + fields.push(( + ENV_FILE_KEY, + optional_text_allowing_empty(payload, ENV_FILE_KEY)?, + )); Ok(fields) } diff --git a/crates/sqlbuild-config/src/project/_helpers/fields.rs b/crates/sqlbuild-config/src/project/_helpers/fields.rs index b758aa8347..2efe2c11c2 100644 --- a/crates/sqlbuild-config/src/project/_helpers/fields.rs +++ b/crates/sqlbuild-config/src/project/_helpers/fields.rs @@ -65,6 +65,17 @@ pub(crate) fn optional_str(mapping: &Entries, key: &str) -> Loaded Loaded { + match get(mapping, key) { + None => Ok(text_or_none(None)), + Some(ConfigValue::String(text)) => Ok(text_or_none(Some(text.clone()))), + Some(_) => Err(ConfigFailure::plain(format!( + "Expected '{key}' to be a string when provided" + ))), + } +} + /// `_optional_str` as a field value. pub(crate) fn optional_text_field(mapping: &Entries, key: &str) -> Loaded { Ok(text_or_none(optional_str(mapping, key)?)) diff --git a/crates/sqlbuild-config/src/project/_helpers/targets.rs b/crates/sqlbuild-config/src/project/_helpers/targets.rs index 73b6fd74f9..da849df615 100644 --- a/crates/sqlbuild-config/src/project/_helpers/targets.rs +++ b/crates/sqlbuild-config/src/project/_helpers/targets.rs @@ -6,8 +6,8 @@ use crate::project::_helpers::defaults::{ }; use crate::project::_helpers::fields::{ bool_or_none, coerce_mapping, get, key_name, keyed, object, optional_choice, - optional_nullable_bool, optional_str, optional_strict_int, optional_text_field, string_mapping, - text_or_none, value_or_none, + optional_nullable_bool, optional_str, optional_strict_int, optional_text_allowing_empty, + optional_text_field, string_mapping, string_sequence, text_or_none, value_or_none, }; use crate::project::_helpers::keys::{ Place, reject_removed_virtual_keys, reject_unknown_mapping_keys, validate_allowed_keys, @@ -15,9 +15,9 @@ use crate::project::_helpers::keys::{ use crate::project::_helpers::sections::{fixed_duration_seconds, item_timeout}; use crate::project::_helpers::values::{int_below, is_int}; use crate::project::constants::{ - CLONE_KEYS, CONCURRENCY_KEY, CONFIRMATION_POLICIES, EXECUTION_LIMIT_KEYS, - IGNORE_AUDIT_FAILURES_KEY, MAX_FULL_ROWS_KEY, PAUSE_DYNAMIC_KEY, PLAN_FROM_KEY, - PLAN_FROM_SOURCES, POOLS_KEY, RETENTION_MATERIALIZATIONS, TARGET_KEYS, + ALLOW_MISSING_SECRETS_KEY, CLONE_KEYS, CONCURRENCY_KEY, CONFIRMATION_POLICIES, ENV_FILE_KEY, + EXECUTION_LIMIT_KEYS, IGNORE_AUDIT_FAILURES_KEY, MAX_FULL_ROWS_KEY, PAUSE_DYNAMIC_KEY, + PLAN_FROM_KEY, PLAN_FROM_SOURCES, POOLS_KEY, RETENTION_MATERIALIZATIONS, TARGET_KEYS, UNLIMITED_DIFF_FULL_ROWS, WAREHOUSE_GROUPS, }; use crate::project::errors::ConfigFailure; @@ -324,6 +324,16 @@ fn validate_target_keys(mapping: &Entries, target: TargetPlace<'_>) -> Result<() format!("{label}.{POOLS_KEY} is project policy; set it in sqlbuild_project.toml"), )); } + for key in [ENV_FILE_KEY, ALLOW_MISSING_SECRETS_KEY] { + if matches!(target.file, ConfigFile::Local | ConfigFile::LegacyLocal) + && get(mapping, key).is_some() + { + return Err(ConfigFailure::at( + target.file, + format!("{label}.{key} is project configuration; set it in sqlbuild_project.toml"), + )); + } + } if let Some(recall) = get(mapping, RECALL_SECTION) { recall_section(recall, &format!("{label}.{RECALL_SECTION}")) .map_err(|message| ConfigFailure::at(target.file, message))?; @@ -438,6 +448,25 @@ fn local_target(payload: &ConfigValue, target: TargetPlace<'_>) -> Loaded Result<(), WorkspaceError> { @@ -31,5 +32,6 @@ pub fn create_playground(request: &PlaygroundRequest) -> Result<(), WorkspaceErr &request.templates_root, &request.target_dir, &request.template, - ) + )?; + Ok(ignore_env_file(&request.target_dir)?) } diff --git a/crates/sqlbuild-core/src/constants.rs b/crates/sqlbuild-core/src/constants.rs index a6629f8912..5ea4219c11 100644 --- a/crates/sqlbuild-core/src/constants.rs +++ b/crates/sqlbuild-core/src/constants.rs @@ -46,6 +46,8 @@ pub const RESOURCE_COSTS_TABLE_NAME: &str = "_sqlbuild_resource_costs"; pub const RUNS_TABLE_NAME: &str = "_sqlbuild_runs"; /// State table of the dynamic models a build paused, and its heartbeats while it holds them. pub const DYNAMIC_PAUSES_TABLE_NAME: &str = "_sqlbuild_dynamic_pauses"; +/// How long a location may spend resuming dynamic holds before it is killed; older claims are dead. +pub const DYNAMIC_RESUME_SECONDS: u64 = 120; /// Every state table SQLBuild writes in a target's state schema. pub const STATE_TABLE_NAMES: [&str; 14] = [ FINGERPRINT_TABLE_NAME, diff --git a/crates/sqlbuild-core/src/debug_report/_helpers/env_file_line.rs b/crates/sqlbuild-core/src/debug_report/_helpers/env_file_line.rs new file mode 100644 index 0000000000..559c0bdd4f --- /dev/null +++ b/crates/sqlbuild-core/src/debug_report/_helpers/env_file_line.rs @@ -0,0 +1,34 @@ +//! The `sqb debug` line for the env file this process tree loaded. + +use crate::debug_report::models::{DebugLine, DebugStatus}; +use crate::process_environment::models::EnvFileMarker; + +/// Which env file loaded, by path and variable count; never a value. +pub(crate) fn env_file_line(marker: &EnvFileMarker) -> DebugLine { + let Some(path) = &marker.path else { + return DebugLine::checked( + "env file", + "off", + (DebugStatus::Skip, Some("env_file = \"\"")), + ); + }; + if !marker.loaded { + return DebugLine::checked( + "env file", + path, + (DebugStatus::Ok, Some("not found, optional")), + ); + } + let count: usize = marker.names.len(); + let mut status: String = format!( + "loaded, {count} variable{}", + if count == 1 { "" } else { "s" } + ); + if !marker.overridden.is_empty() { + status.push_str(&format!( + ", {} already set in the environment", + marker.overridden.len() + )); + } + DebugLine::checked("env file", path, (DebugStatus::Ok, Some(&status))) +} diff --git a/crates/sqlbuild-core/src/debug_report/_helpers/mod.rs b/crates/sqlbuild-core/src/debug_report/_helpers/mod.rs new file mode 100644 index 0000000000..50bc90c756 --- /dev/null +++ b/crates/sqlbuild-core/src/debug_report/_helpers/mod.rs @@ -0,0 +1 @@ +pub(crate) mod env_file_line; diff --git a/crates/sqlbuild-core/src/debug_report/main/debug_configuration_lines.rs b/crates/sqlbuild-core/src/debug_report/main/debug_configuration_lines.rs index 4c677935c8..6269c056d6 100644 --- a/crates/sqlbuild-core/src/debug_report/main/debug_configuration_lines.rs +++ b/crates/sqlbuild-core/src/debug_report/main/debug_configuration_lines.rs @@ -1,5 +1,6 @@ //! The configuration section of `sqb debug`. +use crate::debug_report::_helpers::env_file_line::env_file_line; use crate::debug_report::constants::{NOT_CONFIGURED, NOT_PRESENT}; use crate::debug_report::models::{DebugLine, DebugProjectFacts, DebugStatus, WarehouseCheck}; @@ -53,6 +54,9 @@ pub fn debug_configuration_lines( NOT_PRESENT }, ), + ]; + lines.extend(facts.env_file.as_ref().map(env_file_line)); + lines.extend([ resolved("project", &facts.project_name, "loaded"), resolved("adapter", &facts.adapter_name, "found"), resolved( @@ -75,7 +79,7 @@ pub fn debug_configuration_lines( facts.schema.as_deref().unwrap_or(NOT_CONFIGURED), "resolved", ), - ]; + ]); lines.extend(warehouses.iter().map(warehouse_line)); lines } diff --git a/crates/sqlbuild-core/src/debug_report/main/debug_provider_lines.rs b/crates/sqlbuild-core/src/debug_report/main/debug_provider_lines.rs index aad5277555..357557511f 100644 --- a/crates/sqlbuild-core/src/debug_report/main/debug_provider_lines.rs +++ b/crates/sqlbuild-core/src/debug_report/main/debug_provider_lines.rs @@ -41,7 +41,9 @@ pub fn debug_provider_lines(providers: &[DebugProvider], verbose: bool) -> Vec std::io::Result<()> { + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + options.open(path)?.write_all(text.as_bytes()) +} diff --git a/crates/sqlbuild-core/src/debug_report/mod.rs b/crates/sqlbuild-core/src/debug_report/mod.rs index 17d3abdfe6..1e64f3d116 100644 --- a/crates/sqlbuild-core/src/debug_report/mod.rs +++ b/crates/sqlbuild-core/src/debug_report/mod.rs @@ -1,3 +1,4 @@ +pub(crate) mod _helpers; pub(crate) mod constants; pub mod main; pub mod models; diff --git a/crates/sqlbuild-core/src/debug_report/models.rs b/crates/sqlbuild-core/src/debug_report/models.rs index 4280f54386..0328bbf21b 100644 --- a/crates/sqlbuild-core/src/debug_report/models.rs +++ b/crates/sqlbuild-core/src/debug_report/models.rs @@ -1,5 +1,6 @@ //! `sqb debug` report lines and the facts they are built from. +use crate::process_environment::models::EnvFileMarker; use std::path::PathBuf; /// The outcome a diagnostic line reports (`DebugCheckStatus`). @@ -97,6 +98,8 @@ pub struct DebugProjectFacts { pub database: Option, /// The effective schema, when it is a non-empty string. pub schema: Option, + /// The env file this process tree loaded, `None` when no launcher loaded one. + pub env_file: Option, } /// One command group's warehouse as `sqb debug` resolved it. @@ -127,6 +130,8 @@ pub struct DebugProvider { pub class_name: String, /// Each secret setting's environment variable and whether the environment sets it. pub secrets: Vec<(String, bool)>, + /// The secret variables the project env file set, by name. + pub from_env_file: Vec, } /// One connection setting value, as Python would print it. diff --git a/crates/sqlbuild-core/src/debug_report/tests/helpers.rs b/crates/sqlbuild-core/src/debug_report/tests/helpers.rs index 12dde6caae..f9d3f1ec52 100644 --- a/crates/sqlbuild-core/src/debug_report/tests/helpers.rs +++ b/crates/sqlbuild-core/src/debug_report/tests/helpers.rs @@ -54,5 +54,6 @@ pub(super) fn provider(name: &str, secrets: &[(&str, bool)]) -> DebugProvider { .iter() .map(|(variable, set)| ((*variable).to_owned(), *set)) .collect(), + from_env_file: Vec::new(), } } diff --git a/crates/sqlbuild-core/src/init_command/constants.rs b/crates/sqlbuild-core/src/init_command/constants.rs index cce5df996c..7ef28d0aa1 100644 --- a/crates/sqlbuild-core/src/init_command/constants.rs +++ b/crates/sqlbuild-core/src/init_command/constants.rs @@ -32,3 +32,9 @@ pub const NEXT_STEPS: [&str; 6] = [ " 5. Add models to models/staging/ and models/marts/", " 6. Add tests to tests/unit/ or tests/scenarios/, reusable audits to audits/generic/, or standalone audits to audits/singular/", ]; + +/// The git ignore file `sqb init` and the playground add the env file to. +pub(crate) const GITIGNORE_FILE: &str = ".gitignore"; +/// The lines that keep the project env file, which holds provider secrets, out of git. +pub(crate) const ENV_FILE_IGNORE: &str = + "# Provider settings and secrets that sqb loads (env_file); never commit them\n.env\n"; diff --git a/crates/sqlbuild-core/src/init_command/main/ignore_env_file.rs b/crates/sqlbuild-core/src/init_command/main/ignore_env_file.rs new file mode 100644 index 0000000000..dd003a07a7 --- /dev/null +++ b/crates/sqlbuild-core/src/init_command/main/ignore_env_file.rs @@ -0,0 +1,30 @@ +//! Keep the project env file out of git. + +use std::fs::{self, OpenOptions}; +use std::io::{ErrorKind, Write}; +use std::path::Path; + +use crate::init_command::constants::{ENV_FILE_IGNORE, GITIGNORE_FILE}; + +/// Add `.env` to `directory/.gitignore`, creating it, unless a line already ignores it. +pub fn ignore_env_file(directory: &Path) -> std::io::Result<()> { + let path = directory.join(GITIGNORE_FILE); + let existing: String = match fs::read_to_string(&path) { + Ok(text) => text, + Err(error) if error.kind() == ErrorKind::NotFound => String::new(), + Err(error) => return Err(error), + }; + if existing + .lines() + .any(|line| matches!(line.trim(), ".env" | "/.env")) + { + return Ok(()); + } + let separator: &str = if existing.is_empty() || existing.ends_with('\n') { + "" + } else { + "\n" + }; + let mut file = OpenOptions::new().create(true).append(true).open(&path)?; + file.write_all(format!("{separator}{ENV_FILE_IGNORE}").as_bytes()) +} diff --git a/crates/sqlbuild-core/src/init_command/main/mod.rs b/crates/sqlbuild-core/src/init_command/main/mod.rs index 815db5c0cc..fd111ae0d4 100644 --- a/crates/sqlbuild-core/src/init_command/main/mod.rs +++ b/crates/sqlbuild-core/src/init_command/main/mod.rs @@ -1,3 +1,4 @@ +pub mod ignore_env_file; pub mod init_project_name; pub mod init_project_toml; pub mod render_init_summary; diff --git a/crates/sqlbuild-core/src/init_command/main/scaffold_blank_project.rs b/crates/sqlbuild-core/src/init_command/main/scaffold_blank_project.rs index eb9c89ff78..2a3c36e4e4 100644 --- a/crates/sqlbuild-core/src/init_command/main/scaffold_blank_project.rs +++ b/crates/sqlbuild-core/src/init_command/main/scaffold_blank_project.rs @@ -5,8 +5,9 @@ use std::io::ErrorKind; use std::path::Path; use crate::constants::PROJECT_CONFIG_FILENAME; -use crate::init_command::constants::{GITKEEP_FILE, SCAFFOLD_DIRECTORIES}; +use crate::init_command::constants::{GITIGNORE_FILE, GITKEEP_FILE, SCAFFOLD_DIRECTORIES}; use crate::init_command::errors::ScaffoldError; +use crate::init_command::main::ignore_env_file::ignore_env_file; fn failed(error: std::io::Error, path: &Path) -> ScaffoldError { ScaffoldError { @@ -34,13 +35,14 @@ fn make_directories(path: &Path) -> Result<(), ScaffoldError> { } } -/// Create the resource directories, the project file, and `.gitkeep` in empty directories. +/// Create the resource directories, the project file, `.env` in `.gitignore`, and `.gitkeep` in empty directories. pub fn scaffold_blank_project(base_dir: &Path, project_toml: &str) -> Result<(), ScaffoldError> { for directory in SCAFFOLD_DIRECTORIES { make_directories(&base_dir.join(directory))?; } let project_file = base_dir.join(PROJECT_CONFIG_FILENAME); fs::write(&project_file, project_toml).map_err(|error| failed(error, &project_file))?; + ignore_env_file(base_dir).map_err(|error| failed(error, &base_dir.join(GITIGNORE_FILE)))?; for directory in SCAFFOLD_DIRECTORIES { let directory = base_dir.join(directory); let mut entries = fs::read_dir(&directory).map_err(|error| failed(error, &directory))?; diff --git a/crates/sqlbuild-core/src/lib.rs b/crates/sqlbuild-core/src/lib.rs index 2c20969d0f..0f4d1c3ae3 100644 --- a/crates/sqlbuild-core/src/lib.rs +++ b/crates/sqlbuild-core/src/lib.rs @@ -46,6 +46,7 @@ pub mod number_text; pub mod panics; pub mod plan_display; pub mod posix_path; +pub mod process_environment; pub mod progress; pub mod query_command; pub mod redaction; diff --git a/crates/sqlbuild-core/src/process_environment/_helpers/mod.rs b/crates/sqlbuild-core/src/process_environment/_helpers/mod.rs new file mode 100644 index 0000000000..775e1e9b63 --- /dev/null +++ b/crates/sqlbuild-core/src/process_environment/_helpers/mod.rs @@ -0,0 +1 @@ +pub(crate) mod overlay; diff --git a/crates/sqlbuild-core/src/process_environment/_helpers/overlay.rs b/crates/sqlbuild-core/src/process_environment/_helpers/overlay.rs new file mode 100644 index 0000000000..f1af768f1b --- /dev/null +++ b/crates/sqlbuild-core/src/process_environment/_helpers/overlay.rs @@ -0,0 +1,21 @@ +//! The one overlay of this process. + +use std::sync::{PoisonError, RwLock}; + +use crate::process_environment::models::EnvironmentOverlay; + +static OVERLAY: RwLock = RwLock::new(EnvironmentOverlay { + set: Vec::new(), + remove: Vec::new(), +}); + +pub(crate) fn current() -> EnvironmentOverlay { + OVERLAY + .read() + .unwrap_or_else(PoisonError::into_inner) + .clone() +} + +pub(crate) fn replace(overlay: EnvironmentOverlay) { + *OVERLAY.write().unwrap_or_else(PoisonError::into_inner) = overlay; +} diff --git a/crates/sqlbuild-core/src/process_environment/constants.rs b/crates/sqlbuild-core/src/process_environment/constants.rs new file mode 100644 index 0000000000..8572be038e --- /dev/null +++ b/crates/sqlbuild-core/src/process_environment/constants.rs @@ -0,0 +1,10 @@ +//! The variables that tell child processes which env file their parent loaded, or why it could not. + +/// Set on every child: the project env file this process tree loaded and the names it took from it. +pub const ENV_FILE_MARKER_VARIABLE: &str = "SQLBUILD_ENV_FILE_LOADED"; + +/// Set on a run worker whose env file can't be read: the reason, naming the line but never a value. +pub const ENV_FILE_ERROR_VARIABLE: &str = "SQLBUILD_ENV_FILE_ERROR"; + +/// Set on a run worker: the bearer the run reports with. +pub const RUN_TOKEN_VARIABLE: &str = "SQLBUILD_RUN_TOKEN"; diff --git a/crates/sqlbuild-core/src/process_environment/main/apply_environment_overlay.rs b/crates/sqlbuild-core/src/process_environment/main/apply_environment_overlay.rs new file mode 100644 index 0000000000..44d91f95a9 --- /dev/null +++ b/crates/sqlbuild-core/src/process_environment/main/apply_environment_overlay.rs @@ -0,0 +1,14 @@ +//! The environment overlay on a command that starts a child process. + +use std::process::Command; + +use crate::process_environment::_helpers::overlay::current; + +/// Give a child the env file variables this process loaded, and unset the ones it dropped. +pub fn apply_environment_overlay(command: &mut Command) { + let overlay = current(); + for name in overlay.remove { + command.env_remove(name); + } + command.envs(overlay.set); +} diff --git a/crates/sqlbuild-core/src/process_environment/main/env_file_marker.rs b/crates/sqlbuild-core/src/process_environment/main/env_file_marker.rs new file mode 100644 index 0000000000..84a48df896 --- /dev/null +++ b/crates/sqlbuild-core/src/process_environment/main/env_file_marker.rs @@ -0,0 +1,45 @@ +//! Which env file this process tree loaded. + +use serde_json::Value; + +use crate::process_environment::constants::ENV_FILE_MARKER_VARIABLE; +use crate::process_environment::main::environment_var_os::environment_var_os; +use crate::process_environment::models::EnvFileMarker; + +fn names(value: &Value, key: &str) -> Option> { + value + .get(key)? + .as_array()? + .iter() + .map(|name| name.as_str().map(str::to_owned)) + .collect() +} + +fn optional_text(value: &Value, key: &str) -> Option> { + match value.get(key)? { + Value::Null => Some(None), + Value::String(text) => Some(Some(text.clone())), + _ => None, + } +} + +/// The marker in the effective environment, `None` when nothing loaded a file or it is malformed. +#[must_use] +pub fn env_file_marker() -> Option { + let text: String = match environment_var_os(ENV_FILE_MARKER_VARIABLE)?.into_string() { + Ok(text) => text, + Err(_not_unicode) => return None, + }; + let value: Value = match serde_json::from_str(&text) { + Ok(value) => value, + Err(_malformed) => return None, + }; + Some(EnvFileMarker { + project_dir: value.get("project_dir")?.as_str()?.to_owned(), + target: optional_text(&value, "target")?, + path: optional_text(&value, "path")?, + loaded: value.get("loaded")?.as_bool()?, + names: names(&value, "names")?, + overridden: names(&value, "overridden")?, + }) +} diff --git a/crates/sqlbuild-core/src/process_environment/main/environment_overlay.rs b/crates/sqlbuild-core/src/process_environment/main/environment_overlay.rs new file mode 100644 index 0000000000..14543ebf19 --- /dev/null +++ b/crates/sqlbuild-core/src/process_environment/main/environment_overlay.rs @@ -0,0 +1,10 @@ +//! This process's environment overlay, for applying to a child's command. + +use crate::process_environment::_helpers::overlay::current; +use crate::process_environment::models::EnvironmentOverlay; + +/// The variables every child this process starts must have set or unset. +#[must_use] +pub fn environment_overlay() -> EnvironmentOverlay { + current() +} diff --git a/crates/sqlbuild-core/src/process_environment/main/environment_var_os.rs b/crates/sqlbuild-core/src/process_environment/main/environment_var_os.rs new file mode 100644 index 0000000000..f64c3278ee --- /dev/null +++ b/crates/sqlbuild-core/src/process_environment/main/environment_var_os.rs @@ -0,0 +1,19 @@ +//! One variable of this process's effective environment. + +use std::ffi::{OsStr, OsString}; + +use crate::process_environment::_helpers::overlay::current; + +/// `std::env::var_os(name)` with this process's overlay applied. +#[must_use] +pub fn environment_var_os(name: impl AsRef) -> Option { + let name: &OsStr = name.as_ref(); + let overlay = current(); + if let Some((_, value)) = overlay.set.iter().rev().find(|(set, _)| set == name) { + return Some(value.clone()); + } + if overlay.remove.iter().any(|removed| removed == name) { + return None; + } + std::env::var_os(name) +} diff --git a/crates/sqlbuild-core/src/process_environment/main/environment_vars_os.rs b/crates/sqlbuild-core/src/process_environment/main/environment_vars_os.rs new file mode 100644 index 0000000000..f159ed8f4f --- /dev/null +++ b/crates/sqlbuild-core/src/process_environment/main/environment_vars_os.rs @@ -0,0 +1,23 @@ +//! This process's effective environment. + +use std::ffi::OsString; + +use crate::process_environment::_helpers::overlay::current; + +/// `std::env::vars_os()` with this process's overlay applied, inherited variables first. +#[must_use] +pub fn environment_vars_os() -> Vec<(OsString, OsString)> { + let overlay = current(); + let mut variables: Vec<(OsString, OsString)> = Vec::new(); + for (name, value) in std::env::vars_os() { + let replaced: bool = overlay.set.iter().any(|(set, _)| *set == name); + if !replaced && !overlay.remove.contains(&name) { + variables.push((name, value)); + } + } + for (name, value) in overlay.set { + variables.retain(|(kept, _)| *kept != name); + variables.push((name, value)); + } + variables +} diff --git a/crates/sqlbuild-core/src/process_environment/main/environment_without_env_file.rs b/crates/sqlbuild-core/src/process_environment/main/environment_without_env_file.rs new file mode 100644 index 0000000000..d887acda77 --- /dev/null +++ b/crates/sqlbuild-core/src/process_environment/main/environment_without_env_file.rs @@ -0,0 +1,26 @@ +//! This process's environment as it was before any env file loaded. + +use std::ffi::OsString; + +use crate::process_environment::constants::ENV_FILE_MARKER_VARIABLE; +use crate::process_environment::main::env_file_marker::env_file_marker; +use crate::process_environment::main::environment_vars_os::environment_vars_os; + +/// The effective environment without the marker or any variable an env file set, so a child loads the file afresh. +#[must_use] +pub fn environment_without_env_file() -> Vec<(OsString, OsString)> { + let taken: Vec = env_file_marker() + .map(|marker| marker.names) + .unwrap_or_default(); + let mut variables: Vec<(OsString, OsString)> = Vec::new(); + for (name, value) in environment_vars_os() { + let from_file: bool = name == ENV_FILE_MARKER_VARIABLE + || name + .to_str() + .is_some_and(|name| taken.iter().any(|taken| taken == name)); + if !from_file { + variables.push((name, value)); + } + } + variables +} diff --git a/crates/sqlbuild-core/src/process_environment/main/install_environment_overlay.rs b/crates/sqlbuild-core/src/process_environment/main/install_environment_overlay.rs new file mode 100644 index 0000000000..fa8d1bda04 --- /dev/null +++ b/crates/sqlbuild-core/src/process_environment/main/install_environment_overlay.rs @@ -0,0 +1,9 @@ +//! Replace this process's environment overlay. + +use crate::process_environment::_helpers::overlay::replace; +use crate::process_environment::models::EnvironmentOverlay; + +/// Make `overlay` what in-process reads and every later child see. +pub fn install_environment_overlay(overlay: EnvironmentOverlay) { + replace(overlay); +} diff --git a/crates/sqlbuild-core/src/process_environment/main/marker_json.rs b/crates/sqlbuild-core/src/process_environment/main/marker_json.rs new file mode 100644 index 0000000000..508742342a --- /dev/null +++ b/crates/sqlbuild-core/src/process_environment/main/marker_json.rs @@ -0,0 +1,19 @@ +//! The `SQLBUILD_ENV_FILE_LOADED` value of a marker. + +use serde_json::{Value, json}; + +use crate::process_environment::models::EnvFileMarker; + +/// The marker as the compact JSON object children read back with `env_file_marker`. +#[must_use] +pub fn marker_json(marker: &EnvFileMarker) -> String { + let value: Value = json!({ + "project_dir": marker.project_dir, + "target": marker.target, + "path": marker.path, + "loaded": marker.loaded, + "names": marker.names, + "overridden": marker.overridden, + }); + value.to_string() +} diff --git a/crates/sqlbuild-core/src/process_environment/main/mod.rs b/crates/sqlbuild-core/src/process_environment/main/mod.rs new file mode 100644 index 0000000000..5b957fd669 --- /dev/null +++ b/crates/sqlbuild-core/src/process_environment/main/mod.rs @@ -0,0 +1,9 @@ +pub mod apply_environment_overlay; +pub mod env_file_marker; +pub mod environment_overlay; +pub mod environment_var_os; +pub mod environment_vars_os; +pub mod environment_without_env_file; +pub mod install_environment_overlay; +pub mod marker_json; +pub mod project_relative_path; diff --git a/crates/sqlbuild-core/src/process_environment/main/project_relative_path.rs b/crates/sqlbuild-core/src/process_environment/main/project_relative_path.rs new file mode 100644 index 0000000000..aae11dfb4a --- /dev/null +++ b/crates/sqlbuild-core/src/process_environment/main/project_relative_path.rs @@ -0,0 +1,26 @@ +//! A path as messages show it: relative to the project when it lies inside it. + +use std::path::{Path, PathBuf}; + +/// `path` with symlinks and `..` resolved, through its parent when the file itself doesn't exist. +fn resolved(path: &Path) -> PathBuf { + if let Ok(canonical) = path.canonicalize() { + return canonical; + } + match (path.parent(), path.file_name()) { + (Some(parent), Some(name)) => parent + .canonicalize() + .map_or_else(|_| path.to_path_buf(), |parent| parent.join(name)), + _ => path.to_path_buf(), + } +} + +/// `path` relative to `project_dir`, comparing resolved paths so relative and symlinked spellings agree; else resolved in full. +#[must_use] +pub fn project_relative_path(project_dir: &Path, path: &Path) -> String { + let file = resolved(path); + match file.strip_prefix(resolved(project_dir)) { + Ok(relative) => relative.to_string_lossy().into_owned(), + Err(_outside_the_project) => file.to_string_lossy().into_owned(), + } +} diff --git a/crates/sqlbuild-core/src/process_environment/mod.rs b/crates/sqlbuild-core/src/process_environment/mod.rs new file mode 100644 index 0000000000..f01181f853 --- /dev/null +++ b/crates/sqlbuild-core/src/process_environment/mod.rs @@ -0,0 +1,7 @@ +pub(crate) mod _helpers; +pub mod constants; +pub mod main; +pub mod models; + +#[cfg(test)] +mod tests; diff --git a/crates/sqlbuild-core/src/process_environment/models.rs b/crates/sqlbuild-core/src/process_environment/models.rs new file mode 100644 index 0000000000..173190071e --- /dev/null +++ b/crates/sqlbuild-core/src/process_environment/models.rs @@ -0,0 +1,29 @@ +//! The variables this process adds to, or removes from, the environment it was started with. + +use std::ffi::OsString; + +/// Changes to the inherited environment that in-process `environment_*` reads and every started child see. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct EnvironmentOverlay { + /// Variables set, or replaced, in order. + pub set: Vec<(OsString, OsString)>, + /// Inherited variables that are unset. + pub remove: Vec, +} + +/// Which env file a process tree loaded, recorded in `SQLBUILD_ENV_FILE_LOADED`; never any value. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct EnvFileMarker { + /// The project directory the file was chosen for. + pub project_dir: String, + /// The target whose `env_file` was used, `None` without a selected target. + pub target: Option, + /// The resolved path, `None` when `env_file = ""` turns loading off. + pub path: Option, + /// Whether the file existed and was read. + pub loaded: bool, + /// The variables taken from the file, sorted; the process environment kept the rest. + pub names: Vec, + /// Variables the file sets that the process environment already set, sorted. + pub overridden: Vec, +} diff --git a/crates/sqlbuild-core/src/process_environment/tests.rs b/crates/sqlbuild-core/src/process_environment/tests.rs new file mode 100644 index 0000000000..3ee7ae32a3 --- /dev/null +++ b/crates/sqlbuild-core/src/process_environment/tests.rs @@ -0,0 +1,4 @@ +#[path = "tests/test_process_environment.rs"] +mod process_environment; +#[path = "tests/test_types.rs"] +mod test_types; diff --git a/crates/sqlbuild-core/src/process_environment/tests/test_process_environment.rs b/crates/sqlbuild-core/src/process_environment/tests/test_process_environment.rs new file mode 100644 index 0000000000..1a113b0093 --- /dev/null +++ b/crates/sqlbuild-core/src/process_environment/tests/test_process_environment.rs @@ -0,0 +1,87 @@ +use std::ffi::OsString; + +use crate::process_environment::constants::ENV_FILE_MARKER_VARIABLE; +use crate::process_environment::main::env_file_marker::env_file_marker; +use crate::process_environment::main::environment_var_os::environment_var_os; +use crate::process_environment::main::environment_vars_os::environment_vars_os; +use crate::process_environment::main::environment_without_env_file::environment_without_env_file; +use crate::process_environment::main::install_environment_overlay::install_environment_overlay; +use crate::process_environment::main::marker_json::marker_json; +use crate::process_environment::models::{EnvFileMarker, EnvironmentOverlay}; +use crate::process_environment::tests::test_types::OverlayTestCase; + +/// One test: the overlay is process-wide, so parallel tests would see each other's. +#[test] +fn given_an_overlay_when_reading_the_environment_then_it_sets_unsets_and_carries_the_marker() { + let test_cases = [OverlayTestCase { + description: "a file variable is set, an inherited one unset, and the marker reads back", + set: ("SQLBUILD_TEST_FROM_FILE", "file value"), + removed: "CARGO_MANIFEST_DIR", + expected_value: "file value", + }]; + for test_case in test_cases { + let (name, value) = test_case.set; + assert!( + std::env::var_os(test_case.removed).is_some(), + "{}: cargo sets the variable the overlay removes", + test_case.description + ); + let marker = EnvFileMarker { + project_dir: "/work/shop".into(), + target: Some("dev".into()), + path: Some("/work/shop/.env".into()), + loaded: true, + names: vec![name.into()], + overridden: vec!["HOME".into()], + }; + install_environment_overlay(EnvironmentOverlay { + set: vec![ + (OsString::from(name), OsString::from(value)), + ( + OsString::from(ENV_FILE_MARKER_VARIABLE), + OsString::from(marker_json(&marker)), + ), + ], + remove: vec![OsString::from(test_case.removed)], + }); + + let variables: Vec<(OsString, OsString)> = environment_vars_os(); + let read: Option = environment_var_os(name); + let removed: Option = environment_var_os(test_case.removed); + let read_marker: Option = env_file_marker(); + let for_children: Vec<(OsString, OsString)> = environment_without_env_file(); + install_environment_overlay(EnvironmentOverlay::default()); + + assert_eq!( + read, + Some(OsString::from(test_case.expected_value)), + "{}", + test_case.description + ); + assert_eq!(removed, None, "{}", test_case.description); + assert_eq!(read_marker, Some(marker), "{}", test_case.description); + assert!( + variables + .iter() + .any(|(listed, listed_value)| listed == name && listed_value == value), + "{}: the effective environment lists set variables", + test_case.description + ); + assert!( + variables + .iter() + .all(|(listed, _)| listed != test_case.removed), + "{}: the effective environment leaves removed variables out", + test_case.description + ); + assert!( + for_children + .iter() + .all(|(listed, _)| listed != name && listed != ENV_FILE_MARKER_VARIABLE), + "{}: children start without the file's variables or its marker", + test_case.description + ); + assert_eq!(environment_var_os(name), None, "{}", test_case.description); + assert_eq!(env_file_marker(), None, "{}", test_case.description); + } +} diff --git a/crates/sqlbuild-core/src/process_environment/tests/test_types.rs b/crates/sqlbuild-core/src/process_environment/tests/test_types.rs new file mode 100644 index 0000000000..6cb4b11356 --- /dev/null +++ b/crates/sqlbuild-core/src/process_environment/tests/test_types.rs @@ -0,0 +1,8 @@ +/// An overlay that sets one variable, removes one inherited variable and carries an env file marker. +pub(super) struct OverlayTestCase { + pub(super) description: &'static str, + pub(super) set: (&'static str, &'static str), + /// An inherited variable the overlay unsets. + pub(super) removed: &'static str, + pub(super) expected_value: &'static str, +} diff --git a/crates/sqlbuild-core/src/screen_text/_helpers/rows.rs b/crates/sqlbuild-core/src/screen_text/_helpers/rows.rs index 640a310506..b75d3023e5 100644 --- a/crates/sqlbuild-core/src/screen_text/_helpers/rows.rs +++ b/crates/sqlbuild-core/src/screen_text/_helpers/rows.rs @@ -1,9 +1,10 @@ -//! Cut, pad and style the spans of one screen row so it never wraps. +//! Cut, wrap and style the spans of screen rows. use std::time::Duration; use crate::screen_text::constants::{ - CUT_MARK, OSC8_END, OSC8_START, SECONDS_PER_HOUR, SECONDS_PER_MINUTE, TENTHS_PER_MINUTE, + CUT_MARK, MIN_WRAP, OSC8_END, OSC8_START, SECONDS_PER_HOUR, SECONDS_PER_MINUTE, + TENTHS_PER_MINUTE, }; use crate::screen_text::models::{ScreenFacts, Segment, Tone}; use crate::text::main::cell_len::cell_len; @@ -65,6 +66,11 @@ pub(crate) fn right(text: &str, cells: usize) -> String { format!("{}{text}", " ".repeat(cells.saturating_sub(cell_len(text)))) } +/// `text` padded with spaces to at least `cells`. +pub(crate) fn pad(text: &str, cells: usize) -> String { + format!("{text}{}", " ".repeat(cells.saturating_sub(cell_len(text)))) +} + /// An elapsed time as `0.1s`, `16m 43s` or `2h 5m`, truncated rather than rounded. pub(crate) fn elapsed_text(elapsed: Duration) -> String { let tenths: u128 = elapsed.as_millis() / 100; @@ -74,31 +80,40 @@ pub(crate) fn elapsed_text(elapsed: Duration) -> String { let seconds: u64 = elapsed.as_secs(); if seconds < SECONDS_PER_HOUR { return format!( - "{}m {}s", + "{}m {:02}s", seconds / SECONDS_PER_MINUTE, seconds % SECONDS_PER_MINUTE ); } format!( - "{}h {}m", + "{}h {:02}m", seconds / SECONDS_PER_HOUR, (seconds % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE ) } -/// The indented row of `segments`, without trailing spaces, cut with `…` to the screen width. -pub(crate) fn render_row(segments: Vec, facts: &ScreenFacts) -> String { +/// The widest a row may be: one cell short of the terminal, so the cursor never wraps. +pub(crate) fn row_width(facts: &ScreenFacts) -> usize { + facts.columns.saturating_sub(1).max(1) +} + +/// The room lasting text has after `column`, never less than a readable minimum. +pub(crate) fn wrap_width(facts: &ScreenFacts, column: usize) -> usize { + row_width(facts).saturating_sub(column).max(MIN_WRAP) +} + +/// `segments` as one row, without trailing spaces, cut with `…` to `width` cells. +pub(crate) fn fit_row(segments: Vec, width: usize, facts: &ScreenFacts) -> String { let segments: Vec = without_trailing_space(segments); - let budget: usize = facts.columns.saturating_sub(facts.indent); let total: usize = segments.iter().map(|segment| cell_len(&segment.text)).sum(); - let mut row: String = " ".repeat(facts.indent); - if total <= budget { + let mut row: String = String::new(); + if total <= width { for segment in &segments { row.push_str(&styled(&segment.text, segment, facts)); } return row; } - let keep: usize = budget.saturating_sub(1); + let keep: usize = width.saturating_sub(1); let mut used: usize = 0; for segment in &segments { if used >= keep { @@ -108,12 +123,99 @@ pub(crate) fn render_row(segments: Vec, facts: &ScreenFacts) -> String used += cell_len(&text); row.push_str(&styled(&text, segment, facts)); } - if budget > 0 { + if width > 0 { row.push_str(&facts.style.muted(CUT_MARK)); } row } +/// `segments` styled, uncut. +pub(crate) fn paint(segments: &[Segment], facts: &ScreenFacts) -> String { + let segments: Vec = without_trailing_space(segments.to_vec()); + segments + .iter() + .map(|segment| styled(&segment.text, segment, facts)) + .collect() +} + +/// `text` wrapped at word boundaries into lines of at most `width` cells; longer words are broken. +pub(crate) fn wrap_words(text: &str, width: usize) -> Vec { + let width: usize = width.max(1); + let mut lines: Vec = Vec::new(); + for paragraph in text.split('\n') { + let mut line: String = String::new(); + for word in paragraph.trim_end().split(' ') { + if word.is_empty() && line.is_empty() { + continue; + } + let mut word: String = word.to_owned(); + loop { + let room: usize = if line.is_empty() { + width + } else { + width.saturating_sub(cell_len(&line) + 1) + }; + if cell_len(&word) <= room { + if !line.is_empty() { + line.push(' '); + } + line.push_str(&word); + break; + } + if !line.is_empty() { + lines.push(std::mem::take(&mut line).trim_end().to_owned()); + if word.is_empty() { + break; + } + continue; + } + let head: String = leading_cells(&word, width); + word = word[head.len()..].to_owned(); + lines.push(head); + if word.is_empty() { + break; + } + } + } + lines.push(line); + } + while lines.len() > 1 && lines.last().is_some_and(String::is_empty) { + lines.pop(); + } + lines +} + +/// `text` broken into rows of at most `width` cells, keeping its spacing; control characters are dropped. +pub(crate) fn break_cells(text: &str, width: usize) -> Vec { + let width: usize = width.max(1); + let mut rows: Vec = Vec::new(); + for line in text.split('\n') { + let mut rest: String = line + .chars() + .filter(|character| !character.is_control()) + .collect(); + loop { + let head: String = leading_cells(&rest, width); + let done: bool = head.len() == rest.len(); + rest = rest[head.len()..].to_owned(); + rows.push(head); + if done || rest.is_empty() { + break; + } + } + } + rows +} + +/// The leading characters of `text` that fit in `cells`, and at least one so wrapping always advances. +fn leading_cells(text: &str, cells: usize) -> String { + let head: String = take_cells(text, cells); + if head.is_empty() { + return text.chars().take(1).collect(); + } + head +} + fn without_trailing_space(mut segments: Vec) -> Vec { while segments .last() diff --git a/crates/sqlbuild-core/src/screen_text/constants.rs b/crates/sqlbuild-core/src/screen_text/constants.rs index 5fedecfaa5..4a7cf03b1a 100644 --- a/crates/sqlbuild-core/src/screen_text/constants.rs +++ b/crates/sqlbuild-core/src/screen_text/constants.rs @@ -1,20 +1,18 @@ -//! The glyphs, widths and escapes of live terminal screens. +//! The glyphs, widths and escapes of the `sqb dev` screen. pub(crate) const OK_GLYPH: &str = "\u{2713}"; pub(crate) const WARN_GLYPH: &str = "\u{26a0}"; pub(crate) const FAIL_GLYPH: &str = "\u{2717}"; pub(crate) const PENDING_GLYPH: &str = "\u{b7}"; +pub(crate) const PROMPT_GLYPH: &str = "\u{25cc}"; pub(crate) const CHANGED_GLYPH: &str = "~"; pub(crate) const RESTARTED_GLYPH: &str = "\u{21bb}"; -pub(crate) const STARTED_GLYPH: &str = "\u{25b6}"; -pub(crate) const CARD_GLYPH: &str = "\u{279c}"; -pub(crate) const CONNECTED_GLYPH: &str = "\u{25cf}"; -pub(crate) const DISCONNECTED_GLYPH: &str = "\u{25cb}"; +pub(crate) const STARTED_GLYPH: &str = "\u{25b8}"; pub(crate) const SPINNER_FRAMES: [&str; 10] = [ "\u{280b}", "\u{2819}", "\u{2839}", "\u{2838}", "\u{283c}", "\u{2834}", "\u{2826}", "\u{2827}", "\u{2807}", "\u{280f}", ]; -/// What replaces the cut tail of a row. +/// What replaces the cut tail of a live row. pub(crate) const CUT_MARK: &str = "\u{2026}"; pub(crate) const SEPARATOR: &str = " \u{b7} "; pub(crate) const RULE_CHAR: char = '\u{2500}'; @@ -22,16 +20,29 @@ pub(crate) const TREE_BRANCH: &str = "\u{251c}\u{2500}\u{2500} "; pub(crate) const TREE_LAST: &str = "\u{2514}\u{2500}\u{2500} "; pub(crate) const TREE_BAR: &str = "\u{2502} "; pub(crate) const TREE_SPACE: &str = " "; -pub(crate) const PRODUCT: &str = "sqlbuild dev"; -pub(crate) const PLAIN_PREFIX: &str = "sqlbuild dev: "; -/// The label column of a phase line. -pub(crate) const PHASE_LABEL_WIDTH: usize = 20; -/// The right-aligned time column of phase and event lines. -pub(crate) const TIME_WIDTH: usize = 8; -pub(crate) const EVENT_CLOCK_WIDTH: usize = 8; -pub(crate) const EVENT_TITLE_WIDTH: usize = 32; -pub(crate) const EVENT_DETAIL_WIDTH: usize = 18; -pub(crate) const CARD_LABEL_WIDTH: usize = 12; +pub(crate) const PRODUCT: &str = "sqb dev"; +/// The label column of a step line. +pub(crate) const STEP_LABEL_WIDTH: usize = 22; +/// The right-aligned time column after a step's label. +pub(crate) const STEP_TIME_WIDTH: usize = 6; +/// The gap between a step's time and its detail. +pub(crate) const STEP_GAP: &str = " "; +/// Where a problem block's `at`, `why` and `fix` text starts. +pub(crate) const PROBLEM_TEXT_COLUMN: usize = 9; +/// Where the first label of a problem block or prompt starts. +pub(crate) const PROBLEM_LABEL_INDENT: usize = 2; +/// The label column inside the ready box, such as `Warehouse `. +pub(crate) const BOX_LABEL_WIDTH: usize = 11; +/// The ready box is this many cells narrower than the terminal. +pub(crate) const BOX_MARGIN: usize = 2; +/// The narrowest ready box drawn. +pub(crate) const BOX_MIN_WIDTH: usize = 24; +/// Where an event line's text starts, after `HH:MM:SS ✓ `. +pub(crate) const EVENT_TEXT_COLUMN: usize = 11; +/// The command column under `Next`. +pub(crate) const NEXT_COMMAND_WIDTH: usize = 28; +/// Lasting text never wraps narrower than this, however narrow the terminal. +pub(crate) const MIN_WRAP: usize = 20; /// Times under a minute show tenths of a second. pub(crate) const TENTHS_PER_MINUTE: u128 = 600; pub(crate) const SECONDS_PER_MINUTE: u64 = 60; diff --git a/crates/sqlbuild-core/src/screen_text/main/format_plain_line.rs b/crates/sqlbuild-core/src/screen_text/main/format_plain_line.rs deleted file mode 100644 index 4e8ea54dee..0000000000 --- a/crates/sqlbuild-core/src/screen_text/main/format_plain_line.rs +++ /dev/null @@ -1,15 +0,0 @@ -//! One stable line of the plain `sqb dev` output. - -use std::time::Duration; - -use crate::screen_text::_helpers::rows::elapsed_text; -use crate::screen_text::constants::PLAIN_PREFIX; - -/// `sqlbuild dev: `, followed by ` ()` when timed. -#[must_use] -pub fn format_plain_line(message: &str, elapsed: Option) -> String { - match elapsed { - Some(elapsed) => format!("{PLAIN_PREFIX}{message} ({})", elapsed_text(elapsed)), - None => format!("{PLAIN_PREFIX}{message}"), - } -} diff --git a/crates/sqlbuild-core/src/screen_text/main/mod.rs b/crates/sqlbuild-core/src/screen_text/main/mod.rs index b69430ad34..092272e58c 100644 --- a/crates/sqlbuild-core/src/screen_text/main/mod.rs +++ b/crates/sqlbuild-core/src/screen_text/main/mod.rs @@ -1,10 +1,13 @@ -pub mod format_plain_line; pub mod redraw_rows; pub mod render_dev_header; pub mod render_event_line; -pub mod render_frame_rule; -pub mod render_hotkey_bar; +pub mod render_key_line; +pub mod render_labelled_parts; pub mod render_log_line; -pub mod render_phase_lines; -pub mod render_ready_card; +pub mod render_problem; +pub mod render_prompt; +pub mod render_ready_box; +pub mod render_result; +pub mod render_step_line; pub mod render_tree_group; +pub mod visible_cells; diff --git a/crates/sqlbuild-core/src/screen_text/main/render_dev_header.rs b/crates/sqlbuild-core/src/screen_text/main/render_dev_header.rs index cd6f86734c..e356b8cbf8 100644 --- a/crates/sqlbuild-core/src/screen_text/main/render_dev_header.rs +++ b/crates/sqlbuild-core/src/screen_text/main/render_dev_header.rs @@ -1,23 +1,34 @@ -//! The first line of the `sqb dev` screen. +//! The `sqb dev` header, printed once. -use crate::screen_text::_helpers::rows::{render_row, span}; +use crate::screen_text::_helpers::rows::{paint, row_width, span, wrap_words}; use crate::screen_text::constants::{PRODUCT, SEPARATOR}; -use crate::screen_text::models::{DevHeader, ScreenFacts, Tone}; +use crate::screen_text::models::{DevHeader, ScreenFacts, Segment, Tone}; +use crate::text::main::cell_len::cell_len; -/// `sqlbuild dev v0.1.0 · shop · target dev`. +/// `sqb dev shop · target dev · sqb 0.256.0`, wrapped when the terminal is narrower. #[must_use] -pub fn render_dev_header(header: &DevHeader, facts: &ScreenFacts) -> String { - render_row( - vec![ - span(PRODUCT, Tone::Strong), - span( - format!( - " v{}{SEPARATOR}{}{SEPARATOR}target {}", - header.version, header.project, header.target - ), - Tone::Muted, - ), - ], - facts, - ) +pub fn render_dev_header(header: &DevHeader, facts: &ScreenFacts) -> Vec { + let mut segments: Vec = vec![ + span(PRODUCT, Tone::Strong), + span(" ", Tone::Plain), + span(header.project.as_str(), Tone::Plain), + ]; + if !header.target.is_empty() { + segments.push(span( + format!("{SEPARATOR}target {}", header.target), + Tone::Muted, + )); + } + segments.push(span( + format!("{SEPARATOR}sqb {}", header.version), + Tone::Muted, + )); + let text: String = segments + .iter() + .map(|segment| segment.text.as_str()) + .collect(); + if cell_len(&text) <= row_width(facts) { + return vec![paint(&segments, facts)]; + } + wrap_words(&text, row_width(facts)) } diff --git a/crates/sqlbuild-core/src/screen_text/main/render_event_line.rs b/crates/sqlbuild-core/src/screen_text/main/render_event_line.rs index 10f89448d3..548732b629 100644 --- a/crates/sqlbuild-core/src/screen_text/main/render_event_line.rs +++ b/crates/sqlbuild-core/src/screen_text/main/render_event_line.rs @@ -1,13 +1,13 @@ -//! One timestamped event line of the `sqb dev` screen. +//! One timestamped event of the `sqb dev` screen, wrapped in full. -use crate::screen_text::_helpers::rows::{column, elapsed_text, render_row, right, span}; +use crate::screen_text::_helpers::rows::{elapsed_text, paint, span, wrap_width, wrap_words}; use crate::screen_text::constants::{ - CHANGED_GLYPH, EVENT_CLOCK_WIDTH, EVENT_DETAIL_WIDTH, EVENT_TITLE_WIDTH, FAIL_GLYPH, OK_GLYPH, - RESTARTED_GLYPH, STARTED_GLYPH, TIME_WIDTH, WARN_GLYPH, + CHANGED_GLYPH, EVENT_TEXT_COLUMN, FAIL_GLYPH, OK_GLYPH, RESTARTED_GLYPH, STARTED_GLYPH, + WARN_GLYPH, }; -use crate::screen_text::models::{EventLine, EventMark, ScreenFacts, Segment, Tone}; +use crate::screen_text::models::{EventLine, EventMark, ScreenFacts, Tone}; -/// `09:41:03 ✓ title detail 1.4s`, then each note indented under the title. +/// `14:20:31 ▸ run r_8f3a21c0 started manually`, its text and notes wrapped under one another. #[must_use] pub fn render_event_line(event: &EventLine, facts: &ScreenFacts) -> Vec { let (glyph, tone): (&str, Tone) = match event.mark { @@ -15,41 +15,46 @@ pub fn render_event_line(event: &EventLine, facts: &ScreenFacts) -> Vec EventMark::Succeeded => (OK_GLYPH, Tone::Success), EventMark::Failed => (FAIL_GLYPH, Tone::Error), EventMark::Restarted => (RESTARTED_GLYPH, Tone::Warning), - EventMark::Started => (STARTED_GLYPH, Tone::Link), + EventMark::Started => (STARTED_GLYPH, Tone::Change), EventMark::Warning => (WARN_GLYPH, Tone::Warning), }; - let title_tone: Tone = if event.mark == EventMark::Failed { - Tone::Error - } else { - Tone::Plain - }; - let mut segments: Vec = vec![ - span(format!("{} ", event.clock), Tone::Muted), - span(format!("{glyph} "), tone), - ]; - if event.detail.is_empty() && event.elapsed.is_none() { - segments.push(span(event.title.as_str(), title_tone)); - } else { - segments.push(span( - column(&event.title, EVENT_TITLE_WIDTH - 1), - title_tone, - )); - segments.push(span( - format!(" {}", column(&event.detail, EVENT_DETAIL_WIDTH - 1)), - Tone::Muted, - )); - let time: String = event.elapsed.map(elapsed_text).unwrap_or_default(); - segments.push(span( - format!(" {}", right(&time, TIME_WIDTH - 1)), - Tone::Muted, - )); + let text: String = [ + event.title.clone(), + event.detail.clone(), + event.elapsed.map(elapsed_text).unwrap_or_default(), + ] + .into_iter() + .filter(|part| !part.is_empty()) + .collect::>() + .join(" "); + let width: usize = wrap_width(facts, EVENT_TEXT_COLUMN); + let hang: String = " ".repeat(EVENT_TEXT_COLUMN); + let mut rows: Vec = Vec::new(); + for (index, line) in wrap_words(&text, width).into_iter().enumerate() { + rows.push(if index == 0 { + paint( + &[ + span(format!("{} ", event.clock), Tone::Muted), + span(glyph, tone), + span(" ", Tone::Plain), + span(line, Tone::Plain), + ], + facts, + ) + } else { + paint( + &[span(hang.as_str(), Tone::Plain), span(line, Tone::Plain)], + facts, + ) + }); } - let mut rows: Vec = vec![render_row(segments, facts)]; for note in &event.notes { - let mut note_segments: Vec = - vec![span(" ".repeat(EVENT_CLOCK_WIDTH + 2), Tone::Plain)]; - note_segments.extend(note.iter().cloned()); - rows.push(render_row(note_segments, facts)); + for line in wrap_words(note, width) { + rows.push(paint( + &[span(hang.as_str(), Tone::Plain), span(line, Tone::Muted)], + facts, + )); + } } rows } diff --git a/crates/sqlbuild-core/src/screen_text/main/render_frame_rule.rs b/crates/sqlbuild-core/src/screen_text/main/render_frame_rule.rs deleted file mode 100644 index aad507a9d7..0000000000 --- a/crates/sqlbuild-core/src/screen_text/main/render_frame_rule.rs +++ /dev/null @@ -1,20 +0,0 @@ -//! The dim rule that frames a client's own terminal output. - -use crate::screen_text::_helpers::rows::{render_row, span}; -use crate::screen_text::constants::RULE_CHAR; -use crate::screen_text::models::{ScreenFacts, Tone}; -use crate::text::main::cell_len::cell_len; - -/// `──