trellis-pg 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 0a54c119078d44c6f2084ae45adbce9a8d1e99c0efe586d35b47ec819d0edcab
4
- data.tar.gz: b54b2bd9685ef4f9d055e5108a9ebb3c2132d0929024c34b115d1a827917384e
3
+ metadata.gz: 7b9aabe1cb44b52da084051347386cd0bfbeafaae2bc78fa8542ec89b06fcb60
4
+ data.tar.gz: 718bad6383958ae472881b82de1007acce1e037e62360e7c69200878cf24d981
5
5
  SHA512:
6
- metadata.gz: 6037b531512cf803a85063b9a3d17d7d412b2e154cfdb02a5c0a7ea2cce727daf339130895c3bb00a2fd9b57df089ca64800ba4fd6f6f4c7e9c0bc35ba279f9b
7
- data.tar.gz: 0d6d8191769904f73db2473cd9e7caa0510454c36c4019cf0fd8fc8eb4b13377852f514f1b89eee9c77f257ceb1eb1b32b1b87f9de1f6268c32ec006deb859ae
6
+ metadata.gz: 5872bb56236709d58964ceecb63c713b1a71485efe0778cb9d50fe571230e8ccfa5117d664333aacf474b1d91a3b48d04e2b5e483798058b488eac1687d8e6f6
7
+ data.tar.gz: 6b6af1033f671c05a44b91d5cbdd738a643816f3dafc3bd59cc29d571b69bff46a06b2929834ac33838306388d20d65f6d7890fc343578d2590782360c0e4ad5
data/README.md CHANGED
@@ -18,7 +18,7 @@ as `trellis/pg`. The module is still `Trellis`.
18
18
 
19
19
  ```ruby
20
20
  # Gemfile
21
- gem "trellis-pg", "~> 0.2.0"
21
+ gem "trellis-pg", "~> 0.3.0"
22
22
  ```
23
23
 
24
24
  `Bundler.require`, which a Rails app's `config/application.rb` runs,
@@ -60,7 +60,9 @@ Nothing in the binding uses it.
60
60
  (`:transform_defined`, `:paused`, `:resumed`, ...).
61
61
  `Trellis.define(statement)` is an `apply` that refuses anything but a
62
62
  `TRANSFORM`, and returns its fully qualified target table.
63
- - `Trellis.status(target_table)`, `Trellis.definitions`: the catalog reads.
63
+ - `Trellis.status(target_table)`, `Trellis.definitions`: the catalog reads
64
+ (each status word and field: the
65
+ [status reference](../../docs/status-reference.md)).
64
66
  - `Trellis.quarantined`, `Trellis.quarantine_status(target)`,
65
67
  `Trellis.sample_quarantined(target, limit:, after:)`,
66
68
  `Trellis.poisoned_since(time)`: the quarantine reads. Resuming is a
@@ -129,8 +131,9 @@ Nothing in the binding uses it.
129
131
  transform was dropped. With no drain worker anywhere in the fleet a job
130
132
  stays `:queued`.
131
133
  - `Trellis::Metrics.render_prometheus`: the process-wide metrics registry as
132
- Prometheus text, for a `/metrics` route the app already serves (the
133
- binding opens no port; see [Metrics](#metrics)). It needs no handle.
134
+ Prometheus text (the binding opens no port; `Trellis::Metrics::RackApp` is a
135
+ mountable route and `Trellis::Metrics::Middleware` appends it to an
136
+ exporter's; see [Metrics](#metrics)). It needs no handle.
134
137
 
135
138
  ```ruby
136
139
  require "trellis/pg"
@@ -210,21 +213,92 @@ Prometheus's text format. Every series carries a `trellis_instance` label
210
213
  shuts down. The metrics themselves are listed in
211
214
  [`docs/observability.md`](../../docs/observability.md).
212
215
 
213
- The binding opens no port, so serve the text from a route of the app's own:
216
+ The binding opens no port. `Trellis::Metrics::RackApp` is a Rack app that
217
+ serves the text from a route of its own, so a Rails app mounts it:
214
218
 
215
219
  ```ruby
216
220
  # config/routes.rb
217
- get "/metrics", to: proc {
218
- [200, { "content-type" => "text/plain; version=0.0.4" }, [Trellis::Metrics.render_prometheus]]
219
- }
221
+ mount Trellis::Metrics::RackApp, at: "/metrics/trellis"
222
+ ```
223
+
224
+ It answers `GET` and `HEAD` and needs no Rack gem; in a `config.ru` it is
225
+ `map("/metrics/trellis") { run Trellis::Metrics::RackApp }`. The mount is
226
+ unauthenticated, like any Prometheus target, and names the database, catalog
227
+ schema and transforms: keep it off a public port.
228
+
229
+ **Scrape the process that runs the worker.** The `ring_*` and
230
+ `staging_segments` gauges are set only in the process whose `staging: true`
231
+ handle leads (one per instance; the others stand by), and the latency
232
+ histograms and `changes_applied_total` only in processes with drain threads.
233
+ A web process with neither holds `trellis_instance_up` and none of these. The
234
+ gem can't yet serve a worker that runs no web server (`bin/rails runner`, a
235
+ script). Under a forking server each worker process has its own registry, so
236
+ Prometheus scrapes each. A process forked while its parent had a handle
237
+ running can't render the registry: it raises `Trellis::ForkedHandleError`
238
+ (see [Forking servers](#forking-servers)).
239
+
240
+ An app that already serves `/metrics` from `prometheus-client` or Yabeda (its
241
+ exporter is `prometheus-client`'s) adds the Trellis series to that route
242
+ rather than mounting a second one. `Trellis::Metrics::Middleware` wraps the
243
+ exporter and appends `render_prometheus` to its response:
244
+
245
+ ```ruby
246
+ # config/application.rb: outside the exporter, so before it
247
+ config.middleware.insert_before Prometheus::Middleware::Exporter,
248
+ Trellis::Metrics::Middleware, path: "/metrics"
249
+ ```
250
+
251
+ In a `config.ru` it is `use Trellis::Metrics::Middleware, path: "/metrics"`
252
+ above the exporter's `use`. For an exporter mounted as a route (Yabeda's
253
+ `mount Yabeda::Prometheus::Exporter, at: "/metrics"`), `config.middleware.use
254
+ Trellis::Metrics::Middleware, path: "/metrics"` does it, as the middleware
255
+ matches the request path before the router.
256
+
257
+ A `GET` or `HEAD` of `path` (default `/metrics`) answered 200 with an
258
+ uncompressed `text/plain` body gets the Trellis text after the exporter's,
259
+ with `Content-Length` corrected and `HEAD` bodiless. Everything else passes
260
+ through unchanged: other paths and statuses, bodies with a `Content-Encoding`
261
+ or `Transfer-Encoding` (put `Rack::Deflater` outside the middleware), an
262
+ empty registry, and a forked child that can't render it (the exporter's own
263
+ series are still served). It does not dedupe, and the text format allows each
264
+ metric name once, so don't name an app metric like one of the engine's
265
+ `trellis_` series.
266
+
267
+ `prometheus_exporter` serves no route in the app: its own server, usually a
268
+ separate process, answers the scrape and can't see the engine's registry.
269
+ Scrape the app through `Trellis::Metrics::RackApp` as a second target.
270
+
271
+ ### Logs
272
+
273
+ The engine logs through `tracing` and installs no subscriber of its own, so
274
+ nothing reaches Ruby until the app sets a logger. A Ruby thread then drains
275
+ the engine's lines into it every 100 ms (`Trellis::LogBridge`); the engine
276
+ never calls into the VM:
277
+
278
+ ```ruby
279
+ Trellis.logger = Logger.new($stderr) # before Trellis.connect, to catch connect's lines
280
+ Trellis.log_level = :info # optional: default is the logger's level now
220
281
  ```
221
282
 
222
- Under a forking server each worker process has its own registry, holding
223
- only its own handles' series, so Prometheus scrapes each worker (or the
224
- worker handle, `staging: true`, runs in a process of its own that it
225
- scrapes). A process forked while its parent had a handle running can't
226
- render the registry, as it can't connect: it raises
227
- `Trellis::ForkedHandleError` (see [Forking servers](#forking-servers)).
283
+ In a Rails app the Railtie does this with `Rails.logger`; see
284
+ [Logs in Rails](#logs-in-rails). Each line is one `Logger` call: the engine's
285
+ level as the severity, its Rust module as the progname,
286
+ and the event's text, ending in its fields. Every line names its instance as
287
+ `trellis_instance=<database>/<catalog schema>`, so instances in one process
288
+ stay apart. The lines the docs promise (a halt, a standby, a takeover's
289
+ migrations, an automatic rebuild) are among them
290
+ ([observability](../../docs/observability.md#logs-and-traces)).
291
+
292
+ The engine drops events above the level before formatting them, so a later
293
+ `Logger#level=` can make the logger stricter but can't bring back a level the
294
+ bridge filtered: use `Trellis.log_level=`. A line can be dropped, and logging
295
+ never blocks or crashes the engine: the queue holds 10,000 lines, and when it
296
+ overflows the next drain logs one warning with the count. At exit the thread
297
+ stops after the instances shut down and logs what is left.
298
+
299
+ The thread doesn't survive `fork`. After the usual hooks (see
300
+ [Forking servers](#forking-servers)), it starts again, with an empty queue,
301
+ when a handle connects in the child.
228
302
 
229
303
  ### Several instances
230
304
 
@@ -321,6 +395,10 @@ default one included.
321
395
  gem loads no Rails code and requires no gem at all; `activerecord` and
322
396
  `railties` are only ever the app's own dependencies.
323
397
 
398
+ Rails 8.0 and later are supported. Rails 7.2 is expected to work, but CI
399
+ doesn't run it and it carries no promise. `Trellis::Target` refuses the
400
+ include with a clear error on a Rails without the internals it guards (7.1).
401
+
324
402
  ### Configuration and boot
325
403
 
326
404
  The Rails integration reads `Trellis.connect`'s options from one place,
@@ -362,7 +440,8 @@ With neither set, the Railtie does nothing. Two exceptions:
362
440
  migrates without starting the app. The migration helpers connect a handle
363
441
  of their own. A rake task of your own that calls Trellis calls
364
442
  `Trellis::Railtie.connect` first. It's the running task that counts:
365
- `rails test` boots the app outside any task and connects, but tests run
443
+ `rails test` boots the app outside any task and connects (once Trellis is
444
+ on in the test environment: [Testing](#testing)), but tests run
366
445
  by a rake task (`bin/rails db:test:prepare test`, or plain `rake`) don't,
367
446
  so a test helper that needs the handles can call
368
447
  `Trellis::Railtie.connect if Trellis::Instance.connected.empty?`.
@@ -371,6 +450,23 @@ With neither set, the Railtie does nothing. Two exceptions:
371
450
  preloading Passenger, say). Connect in each child with
372
451
  `Trellis::Railtie.connect`.
373
452
 
453
+ `config.trellis.off_in` turns all of this off in the environments it names
454
+ (the `test` environment, by default): see [Testing](#testing).
455
+
456
+ ### Logs in Rails
457
+
458
+ The Railtie sends the engine's log lines to `Rails.logger`, at its level, as
459
+ the app boots:
460
+
461
+ ```ruby
462
+ config.trellis.log_level = :info # :debug, :info, :warn or :error; default: Rails.logger's level
463
+ config.trellis.log_bridge = false # forward nothing
464
+ ```
465
+
466
+ A `Trellis.logger =` in a `config/initializers` file replaces it. In an
467
+ environment `config.trellis.off_in` names, nothing connects and the bridge
468
+ isn't started.
469
+
374
470
  ### Forking servers
375
471
 
376
472
  A handle doesn't survive `fork`. A server that loads the app
@@ -465,10 +561,11 @@ end
465
561
  app uses `structure.sql`.
466
562
 
467
563
  `rails trellis:migrate` creates or upgrades Trellis's own tables the same
468
- way. The helpers run it whenever a migration defines something; run it in
469
- the deploy step as well (`bin/rails trellis:migrate db:migrate`), so a
470
- deploy that upgrades the gem without a new define still upgrades the
471
- tables before the worker restarts.
564
+ way. The helpers run it whenever a migration defines something, and a worker
565
+ of a new gem version runs it by itself once the old version's processes have
566
+ stopped. Run it in the deploy step as well (`bin/rails trellis:migrate
567
+ db:migrate`) to create the tables on a fresh database, to upgrade them before
568
+ the worker restarts, or when the worker's database role can't alter them.
472
569
 
473
570
  `Trellis::Railtie.with_handle { ... }` is what `trellis:migrate` and the
474
571
  helpers use, for a script or rake task of your own that needs Trellis the
@@ -481,10 +578,208 @@ instance and every instance of `config.trellis.instances`. Neither it nor
481
578
  Outside Rails, `require "trellis/migration"` and `Trellis.connect` before
482
579
  migrating.
483
580
 
484
- ## Fixtures and bulk loads in tests
581
+ ### Targets as models
582
+
583
+ Only Trellis writes a target. Declare a model over one with
584
+ `Trellis::Target`, and every ActiveRecord write to it raises
585
+ `Trellis::ReadOnlyTarget` (an `ActiveRecord::ReadOnlyRecord`) naming the
586
+ target:
587
+
588
+ ```ruby
589
+ class EventCount < ApplicationRecord
590
+ include Trellis::Target
591
+ self.primary_key = [:account_id, :kind] # the GROUP BY key
592
+ belongs_to :account
593
+ end
594
+
595
+ EventCount.find([42, "click"]).n
596
+ Account.find(42).event_counts.sum(:n) # with has_many :event_counts on Account
597
+ ```
598
+
599
+ - **Key.** A `GROUP BY` target has no primary key, only a unique constraint
600
+ on its group key: declare that as `primary_key`. A 1-1 target carries its
601
+ source's primary key, which ActiveRecord finds itself. A group with no
602
+ source rows has no row, so a missing row means zero.
603
+ - **What it refuses.** Record writes (`save`, `create!`, `update`,
604
+ `update_columns`, `increment!`, `touch`, `delete`, `destroy`) and bulk
605
+ writes (`insert_all`, `upsert_all`, `update_all`, `update_counters`,
606
+ `delete_all`, `destroy_all` and their variants) on the class, any scope
607
+ and any association. So is an association option that writes the target
608
+ (`dependent:`, `counter_cache:`, `touch:`): leave those off, as Trellis
609
+ keeps the target's rows in step with the source. Reads are untouched.
610
+ - **What it doesn't.** SQL sent through the connection (`execute`, fixture
611
+ loads) and other database roles. That is the database's job:
612
+ [grant application roles `SELECT` on targets](../../docs/recommendations.md#application-roles-read-targets-and-nothing-else).
613
+ - **In tests.** Where Trellis is off (the `test` environment by default:
614
+ [Testing](#testing)) the model writes like any other, with no setup. A suite that
615
+ runs Trellis writes a target in `Trellis::Target.allow_writes { ... }`.
616
+
617
+ ### Upgrading the gem
618
+
619
+ A release that changes `trellis-pg`'s version can't also define, alter,
620
+ pause, resume or drop a transform. While a worker of the old version runs,
621
+ those statements refuse with `Trellis::VersionHandoverError`
622
+ ([rolling deploys](../../docs/embedding.md#rolling-deploys)), so a deploy
623
+ that migrates before the old worker stops fails at its first Trellis
624
+ migration. Ship the version change by itself, and the migrations in the next
625
+ release.
626
+
627
+ `rails trellis:release_check` fails a build that combines the two:
628
+
629
+ ```sh
630
+ bin/rails trellis:release_check BASE=origin/main
631
+ ```
632
+
633
+ It compares the working tree with its merge base against `BASE`, and exits 1
634
+ when `trellis-pg`'s version in the lockfile changed and a migration added
635
+ since then mentions `Trellis`. It reads git and files only: it needs no
636
+ database and doesn't initialize the app.
637
+
638
+ - **On a pull request**, `BASE` is the branch it targets. The job needs the
639
+ history back to the merge base, which a shallow clone lacks:
640
+
641
+ ```yaml
642
+ - uses: actions/checkout@v4
643
+ with:
644
+ fetch-depth: 0
645
+ # ... install Ruby and the app's gems ...
646
+ - run: bin/rails trellis:release_check BASE=origin/${{ github.base_ref }}
647
+ ```
648
+ - **For a release of several merged pull requests**, `BASE` is the last
649
+ deployed ref: a version change and a migration that merged separately
650
+ still deploy together.
651
+ - It reads `db/migrate` and each database's `migrations_paths`, and sees
652
+ migrations only. A state-changing call from a script or a console is in no
653
+ file it reads; the engine still refuses it.
654
+
655
+ Outside Rails, `require "trellis/release_check"` and call
656
+ `Trellis::ReleaseCheck.call(root:, base:)`, which returns a result with
657
+ `ok?` and `message`.
658
+
659
+ ## Testing
660
+
661
+ Trellis is off in the `test` environment by default. A transactional test
662
+ (Rails' default) never commits, so capture never sees its writes and a target
663
+ never changes, whether or not a worker runs. A target is an ordinary table a
664
+ test fills itself.
665
+
666
+ `config.trellis.off_in` (`%w[test]` unless you set it) names the environments
667
+ Trellis is off in. It is read from every environment, so `db:prepare` or
668
+ `db:test:prepare` run from development leaves Trellis out of the test database
669
+ too. Where it is off:
670
+
671
+ - Nothing connects at boot. `Trellis::Railtie.connect` and `trellis:migrate`
672
+ warn and do nothing.
673
+ - A schema load creates the targets as the plain tables `structure.sql`
674
+ carries, with no capture triggers and nothing restored (the definitions
675
+ stay unread in `trellis.restore_queue`). Rails' fixture foreign-key check
676
+ passes, and the per-worker databases of `parallelize` load.
677
+ - `define`, `apply` and `status` in a migration raise
678
+ `ActiveRecord::MigrationError`: build the database by loading the schema.
679
+ Migrating it from development (`db:prepare`) skips them, and the next
680
+ `rails test` reloads it from the new dump.
681
+ - `Trellis.enabled?` is false, for code that builds on Trellis (it is true
682
+ without Rails). `Trellis.connect` itself is not gated.
683
+
684
+ Stub a target's rows by hand, as the transform would write them; a model
685
+ over the target ("Targets as models") writes here:
686
+
687
+ ```ruby
688
+ EventCount.insert_all([{ kind: "click", n: 3 }])
689
+ ```
690
+
691
+ For the real numbers, `refresh_trellis_target` fills a target from its
692
+ definition, on the test's connection and inside its transaction:
693
+
694
+ ```ruby
695
+ require "trellis/test_support"
696
+
697
+ class EventCountTest < ActiveSupport::TestCase
698
+ include Trellis::TestSupport
699
+
700
+ test "counts clicks" do
701
+ 3.times { Event.create!(kind: "click") }
702
+ refresh_trellis_target :event_counts # DELETE, then INSERT ... SELECT
703
+ assert_equal 3, EventCount.find_by!(kind: "click").n
704
+ end
705
+ end
706
+ ```
707
+
708
+ It computes the target from its sources as they stand, as a fresh build
709
+ would, with the `SELECT` the engine renders from the definition the schema
710
+ load left in `trellis.restore_queue`. It doesn't exercise capture, the drain
711
+ or any pause. A chained target refreshes its upstream first. A source the
712
+ definition names without a schema resolves on the test's `search_path`. It
713
+ raises `Trellis::ValidationError` where Trellis is on, since the engine
714
+ maintains the target there (`trellis_on: true` writes anyway).
715
+
716
+ ### Running Trellis in tests
717
+
718
+ Tests that need Trellis for real need it on in the test database. Set
719
+ `config.trellis.off_in = []` (or switch it per run:
720
+ `config.trellis.off_in = ENV["TRELLIS_TESTS"] ? [] : %w[test]`). Give the
721
+ test environment's `config.trellis.connect` the workers (`staging: true,
722
+ drain_threads: 1`), and take those tests out of the transaction:
723
+
724
+ ```ruby
725
+ require "trellis/test_support"
726
+
727
+ class EventCountTest < ActiveSupport::TestCase
728
+ include Trellis::TestSupport
729
+ self.use_transactional_tests = false # capture reads committed rows only
730
+
731
+ setup { resume_capture_disruptions } # the fixture load paused capture (below)
732
+ teardown { Event.delete_all } # plain DELETEs; a table swap or disabled triggers pause capture
733
+
734
+ test "counts clicks" do
735
+ 3.times { Event.create!(kind: "click") }
736
+ Trellis.await_converged(Trellis.watermark_token, timeout_ms: 30_000)
737
+ assert_equal 3, EventCount.find_by!(kind: "click").n
738
+ end
739
+ end
740
+ ```
741
+
742
+ Two more things need care with Trellis on in the test database:
743
+
744
+ - **Rails 8.1's fixture foreign-key check** resolves every foreign key without
745
+ Trellis's schema and fails with `PG::UndefinedTable`. Set
746
+ `config.active_record.verify_foreign_keys_for_fixtures = false`, or
747
+ `schema_search_path: "public,trellis"` on the test database. Rails 8.0
748
+ doesn't need either.
749
+ - **`parallelize(workers: n)`** loads the schema into one database per
750
+ worker (`<name>_<i>` on Rails 8.1, `<name>-<i>` on 8.0), so each worker's
751
+ `config.trellis.connect` has to name its own, and the handle does not
752
+ survive the fork. Connect after the fork, not at boot
753
+ (`config.trellis.connect_on_boot = false`), and register the hook before
754
+ `require "rails/test_help"`, which is what runs the schema load:
755
+
756
+ ```ruby
757
+ # test/test_helper.rb
758
+ require "active_support/testing/parallelization"
759
+
760
+ ActiveSupport::Testing::Parallelization.after_fork_hook do |worker|
761
+ trellis = Rails.application.config.trellis
762
+ uri = URI.parse(trellis.connect.fetch(:url))
763
+ suffix = ActiveRecord.version >= Gem::Version.new("8.1") ? "_" : "-"
764
+ uri.path = "#{uri.path}#{suffix}#{worker}"
765
+ trellis.connect = trellis.connect.merge(url: uri.to_s)
766
+ end
767
+
768
+ require "rails/test_help"
769
+
770
+ class ActiveSupport::TestCase
771
+ parallelize(workers: 2)
772
+ # In a worker, after the schema load; in the one process of a run below
773
+ # Rails' parallelization threshold, the first test. Declare it before any
774
+ # setup that needs the handle (`resume_capture_disruptions`).
775
+ setup { Trellis::Railtie.connect if Trellis::Instance.connected.empty? }
776
+ end
777
+ ```
778
+
779
+ ### Fixtures and bulk loads
485
780
 
486
- Rails fixtures load with `disable_referential_integrity`, which disables
487
- every trigger on the loaded tables, Trellis's capture triggers included, and
781
+ With Trellis on in the test database, Rails fixtures load with
782
+ `disable_referential_integrity`, which disables every trigger on the loaded tables, Trellis's capture triggers included, and
488
783
  ends with `ENABLE TRIGGER ALL`. The rows it wrote never reached a target, so
489
784
  Trellis pauses every definition that reads the table (`status.capture_failure`
490
785
  has `kind: :disruption`) instead of letting a test read silently wrong data,
@@ -566,6 +861,11 @@ How the restore works, and what it refuses, is in
566
861
  the test config's database, and its host, port, user, password and other
567
862
  libpq keywords (`sslmode`, `sslrootcert`, ...) where it names a non-blank
568
863
  value (its `url` when it has one).
864
+ - A database of an environment named in `config.trellis.off_in` loads as
865
+ plain tables and is dumped as Rails does. `db:prepare` in development
866
+ skips the dump of such a test database, which would overwrite
867
+ development's `structure.sql` with one that has no definitions
868
+ ([Testing](#testing)).
569
869
  - The hook adds each instance's exclusions (its Trellis schema, its ledgers)
570
870
  to the flags Rails passes `pg_dump`, and its `target_schema` to the
571
871
  `--schema` flags when Rails passes any. `pg_dump` can't leave out one
@@ -595,10 +895,12 @@ How the restore works, and what it refuses, is in
595
895
  ## Layout
596
896
 
597
897
  - `lib/`: the `Trellis` module and `Trellis::Instance`, its error classes and its `Data` values,
598
- `Trellis::Metrics`,
599
- the Rails integration (`trellis/railtie.rb`, `trellis/migration.rb`),
898
+ `Trellis::Metrics`, `Trellis::LogBridge`,
899
+ the Rails integration (`trellis/railtie.rb`, `trellis/migration.rb`,
900
+ `trellis/target.rb`),
600
901
  loaded only in an app that has Rails, and the test helpers
601
- (`trellis/test_support.rb`), loaded only when required.
902
+ (`trellis/test_support.rb`) and the release check
903
+ (`trellis/release_check.rb`), each loaded only when required.
602
904
  - `ext/trellis_ruby/`: the extension crate, a member of the repository's
603
905
  Cargo workspace, and the `extconf.rb` that builds it with rb-sys.
604
906
  Plain-data conversion and error codes come from `clients/embed`
@@ -1729,8 +1729,8 @@ dependencies = [
1729
1729
 
1730
1730
  [[package]]
1731
1731
  name = "trellis"
1732
- version = "0.2.1"
1733
- source = "git+https://github.com/salesforce-misc/trellis?rev=e2693e0ba3ed9cd6b6304d6418a561908ecd2d05#e2693e0ba3ed9cd6b6304d6418a561908ecd2d05"
1732
+ version = "0.3.1"
1733
+ source = "git+https://github.com/salesforce-misc/trellis?rev=dedfe5e5a25dc1ec39f9548382de7920c8e7526c#dedfe5e5a25dc1ec39f9548382de7920c8e7526c"
1734
1734
  dependencies = [
1735
1735
  "deadpool",
1736
1736
  "deadpool-postgres",
@@ -1751,8 +1751,8 @@ dependencies = [
1751
1751
 
1752
1752
  [[package]]
1753
1753
  name = "trellis-embed"
1754
- version = "0.2.1"
1755
- source = "git+https://github.com/salesforce-misc/trellis?rev=e2693e0ba3ed9cd6b6304d6418a561908ecd2d05#e2693e0ba3ed9cd6b6304d6418a561908ecd2d05"
1754
+ version = "0.3.1"
1755
+ source = "git+https://github.com/salesforce-misc/trellis?rev=dedfe5e5a25dc1ec39f9548382de7920c8e7526c#dedfe5e5a25dc1ec39f9548382de7920c8e7526c"
1756
1756
  dependencies = [
1757
1757
  "tracing",
1758
1758
  "trellis",
@@ -1760,7 +1760,7 @@ dependencies = [
1760
1760
 
1761
1761
  [[package]]
1762
1762
  name = "trellis_ruby"
1763
- version = "0.2.1"
1763
+ version = "0.3.1"
1764
1764
  dependencies = [
1765
1765
  "magnus",
1766
1766
  "rb-sys",
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "trellis_ruby"
3
- version = "0.2.1"
3
+ version = "0.3.1"
4
4
  edition = "2024"
5
5
  publish = false
6
6
 
@@ -28,8 +28,8 @@ doctest = false
28
28
  ruby = ["dep:magnus", "dep:rb-sys"]
29
29
 
30
30
  [dependencies]
31
- trellis = { git = "https://github.com/salesforce-misc/trellis", rev = "e2693e0ba3ed9cd6b6304d6418a561908ecd2d05" }
32
- trellis-embed = { git = "https://github.com/salesforce-misc/trellis", rev = "e2693e0ba3ed9cd6b6304d6418a561908ecd2d05" }
31
+ trellis = { git = "https://github.com/salesforce-misc/trellis", rev = "dedfe5e5a25dc1ec39f9548382de7920c8e7526c" }
32
+ trellis-embed = { git = "https://github.com/salesforce-misc/trellis", rev = "dedfe5e5a25dc1ec39f9548382de7920c8e7526c" }
33
33
  magnus = { version = "0.9", optional = true, default-features = false, features = ["rb-sys"] }
34
34
  rb-sys = { version = "0.9", optional = true }
35
35
 
@@ -61,17 +61,17 @@ use magnus::{
61
61
  };
62
62
  use trellis::{BlockingTrellis, Config, ErrorCode, PendingCall, TrellisOptions};
63
63
  use trellis_embed::{
64
- DIVERGENCE_KINDS, ERROR_CODES, JOIN_BUILD_STEPS, JOIN_SIDE_PARTS, JOIN_SIDES, PlainApplied,
65
- PlainBackfillFailure, PlainBelowCatalogFloor, PlainCaptureFailure, PlainCaptureWait,
66
- PlainConfig, PlainCorrectingNode, PlainDefinitionStatus, PlainDefinitionSummary,
67
- PlainDivergence, PlainDrainFailure, PlainError, PlainExtremeIndexGap, PlainFanOutWarning,
68
- PlainHeldKeys, PlainHiddenTable, PlainJoinBuildStep, PlainJoinStatus, PlainOtherProcess,
69
- PlainPartialsWarning, PlainPoisonEntry, PlainQuarantineEntry, PlainSamplePage,
70
- PlainSelfCheckJob, PlainSelfCheckReport, PlainSourceIndexGap, PlainVersionHandover,
71
- SELF_CHECK_MODES, SELF_CHECK_OUTCOMES, SELF_CHECK_STATES, capture_failure_kind_names,
72
- decode_cursor, decode_watermark, encode_watermark, index_role_names, quarantine_state_names,
73
- require_transform_statement, self_check_mode, system_time_from_epoch_micros,
74
- transform_status_names,
64
+ DIVERGENCE_KINDS, ERROR_CODES, JOIN_BUILD_STEPS, JOIN_SIDE_PARTS, JOIN_SIDES, LOG_LEVELS,
65
+ PlainApplied, PlainBackfillFailure, PlainBelowCatalogFloor, PlainCaptureFailure,
66
+ PlainCaptureWait, PlainConfig, PlainCorrectingNode, PlainDefinitionStatus,
67
+ PlainDefinitionSummary, PlainDivergence, PlainDrainFailure, PlainError, PlainExtremeIndexGap,
68
+ PlainFanOutWarning, PlainHeldKeys, PlainHiddenTable, PlainJoinBuildStep, PlainJoinStatus,
69
+ PlainOtherProcess, PlainPartialsWarning, PlainPoisonEntry, PlainQuarantineEntry,
70
+ PlainSamplePage, PlainSelfCheckJob, PlainSelfCheckReport, PlainSourceIndexGap,
71
+ PlainVersionHandover, SELF_CHECK_MODES, SELF_CHECK_OUTCOMES, SELF_CHECK_STATES,
72
+ capture_failure_kind_names, decode_cursor, decode_watermark, encode_watermark,
73
+ index_role_names, quarantine_state_names, require_transform_statement, self_check_mode,
74
+ system_time_from_epoch_micros, transform_status_names,
75
75
  };
76
76
 
77
77
  /// What a blocking call produces: its value, or the engine's error as plain
@@ -864,6 +864,7 @@ fn symbol_words() -> impl Iterator<Item = &'static str> {
864
864
  .chain(JOIN_BUILD_STEPS)
865
865
  .chain(JOIN_SIDES)
866
866
  .chain(JOIN_SIDE_PARTS)
867
+ .chain(LOG_LEVELS)
867
868
  }
868
869
 
869
870
  /// A hash from symbol keys to `fields`' values: the shape every record
@@ -1433,6 +1434,22 @@ fn statement_kinds() -> Vec<&'static str> {
1433
1434
  .collect()
1434
1435
  }
1435
1436
 
1437
+ /// The `SELECT` that computes the whole target of the stored definition
1438
+ /// `text` (written under grammar `grammar_version`), one output column per
1439
+ /// entry of `target_columns` in that order: `trellis::target_select_sql`. It
1440
+ /// needs no handle and reads no database. Raises `Trellis::ParseError` for
1441
+ /// text that doesn't parse and `Trellis::ValidationError` for a column the
1442
+ /// definition computes nothing for.
1443
+ fn target_select_sql(
1444
+ ruby: &Ruby,
1445
+ text: String,
1446
+ grammar_version: i32,
1447
+ target_columns: Vec<String>,
1448
+ ) -> Result<String, Error> {
1449
+ trellis::target_select_sql(&text, grammar_version, &target_columns)
1450
+ .map_err(|err| raise(ruby, PlainError::from(err)))
1451
+ }
1452
+
1436
1453
  /// The process-wide metrics registry in Prometheus text exposition format:
1437
1454
  /// `trellis::Metrics::render_prometheus`, the series of every handle in this
1438
1455
  /// process. It needs no handle.
@@ -1447,6 +1464,71 @@ fn render_prometheus(ruby: &Ruby) -> Result<String, Error> {
1447
1464
  Ok(trellis::Metrics::new().render_prometheus())
1448
1465
  }
1449
1466
 
1467
+ /// Every level symbol `take_log_records` can return.
1468
+ fn log_levels(ruby: &Ruby) -> RArray {
1469
+ word_symbols(ruby, LOG_LEVELS)
1470
+ }
1471
+
1472
+ /// Installs `trellis-embed`'s log bridge as the global `tracing` subscriber
1473
+ /// of this library's own copy of `tracing`, if no call has yet, and sets the
1474
+ /// most verbose level it forwards (one of `trellis_embed::LOG_LEVEL_FILTERS`).
1475
+ /// Raises `Trellis::ConflictError` if another subscriber was installed
1476
+ /// first, and `Trellis::ValidationError` for an unknown level.
1477
+ ///
1478
+ /// The bridge is pull-based: the engine's threads only append to its queue,
1479
+ /// and `take_log_records`, called from a Ruby thread, drains it. Nothing here
1480
+ /// calls into the VM from an engine thread. Installing registers `tracing`
1481
+ /// callsites behind locks the engine's threads take, so a process forked
1482
+ /// while its parent had an engine running raises `Trellis::ForkedHandleError`,
1483
+ /// as [`connect`] does.
1484
+ fn install_log_bridge(ruby: &Ruby, level: String) -> Result<(), Error> {
1485
+ engine::check().map_err(|err| forked_handle_error(ruby, forked_while_running(&err)))?;
1486
+ let bridge = trellis_embed::install_log_bridge().map_err(|err| raise(ruby, err))?;
1487
+ bridge.set_max_level(&level).map_err(|err| raise(ruby, err))
1488
+ }
1489
+
1490
+ /// Changes the most verbose level the installed bridge forwards. Raises
1491
+ /// `Trellis::ValidationError` for an unknown level, or if the bridge isn't
1492
+ /// installed.
1493
+ fn set_log_level(ruby: &Ruby, level: String) -> Result<(), Error> {
1494
+ engine::check().map_err(|err| forked_handle_error(ruby, forked_while_running(&err)))?;
1495
+ let bridge = trellis_embed::installed_log_bridge().ok_or_else(|| {
1496
+ raise(
1497
+ ruby,
1498
+ PlainError::new(
1499
+ ErrorCode::Validation,
1500
+ "the log bridge is not installed: install it first",
1501
+ ),
1502
+ )
1503
+ })?;
1504
+ bridge.set_max_level(&level).map_err(|err| raise(ruby, err))
1505
+ }
1506
+
1507
+ /// Up to `max` queued log records, oldest first, as `[level, target,
1508
+ /// message]` arrays (`level` a symbol), and how many were dropped on a full
1509
+ /// queue since the last call: `[records, dropped]`. Empty when the bridge
1510
+ /// isn't installed. It never waits, and a call is short, so it keeps the GVL.
1511
+ ///
1512
+ /// A process forked while its parent had an engine running may have inherited
1513
+ /// the queue mid-push, so it raises `Trellis::ForkedHandleError` rather than
1514
+ /// risk a hang.
1515
+ fn take_log_records(ruby: &Ruby, max: usize) -> Result<(RArray, u64), Error> {
1516
+ engine::check().map_err(|err| forked_handle_error(ruby, forked_while_running(&err)))?;
1517
+ let Some(bridge) = trellis_embed::installed_log_bridge() else {
1518
+ return Ok((ruby.ary_new(), 0));
1519
+ };
1520
+ let batch = bridge.take(max);
1521
+ let records = ruby.ary_new_capa(batch.records.len());
1522
+ for record in batch.records {
1523
+ let fields = ruby.ary_new_capa(3);
1524
+ fields.push(word_symbol(ruby, record.level))?;
1525
+ fields.push(ruby.str_new(&record.target))?;
1526
+ fields.push(ruby.str_new(&record.message))?;
1527
+ records.push(fields)?;
1528
+ }
1529
+ Ok((records, batch.dropped))
1530
+ }
1531
+
1450
1532
  #[magnus::init]
1451
1533
  fn init(ruby: &Ruby) -> Result<(), Error> {
1452
1534
  // Interns every symbol a result can carry up front, from the closed
@@ -1472,6 +1554,11 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
1472
1554
  native.define_module_function("join_side_parts", function!(join_side_parts, 0))?;
1473
1555
  native.define_module_function("statement_kinds", function!(statement_kinds, 0))?;
1474
1556
  native.define_module_function("render_prometheus", function!(render_prometheus, 0))?;
1557
+ native.define_module_function("target_select_sql", function!(target_select_sql, 3))?;
1558
+ native.define_module_function("log_levels", function!(log_levels, 0))?;
1559
+ native.define_module_function("install_log_bridge", function!(install_log_bridge, 1))?;
1560
+ native.define_module_function("set_log_level", function!(set_log_level, 1))?;
1561
+ native.define_module_function("take_log_records", function!(take_log_records, 1))?;
1475
1562
 
1476
1563
  let handle = native.define_class("Handle", ruby.class_object())?;
1477
1564
  handle.define_method("owner_pid", method!(Handle::owner_pid, 0))?;
@@ -173,6 +173,7 @@ module Trellis
173
173
  "#{call_pool_wait_timeout_ms.inspect}"
174
174
  end
175
175
 
176
+ LogBridge.ensure_running
176
177
  handle = Native.connect(url, schema, target_schema, staging, drain_threads, worker_threads,
177
178
  max_call_pool_size, call_pool_wait_timeout_ms)
178
179
  instance = new(handle, schema)
@@ -238,6 +239,9 @@ module Trellis
238
239
  shutdown_all
239
240
  rescue Error => e
240
241
  warn "trellis: shutting down at exit failed: #{e.class}: #{e.message}"
242
+ ensure
243
+ # After the instances: their shutdown lines are the last ones.
244
+ LogBridge.stop_current
241
245
  end
242
246
  end
243
247