trellis-pg 0.2.1-x86_64-linux → 0.3.1-x86_64-linux
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 +4 -4
- data/README.md +327 -25
- data/lib/trellis/3.3/trellis_ruby.so +0 -0
- data/lib/trellis/3.4/trellis_ruby.so +0 -0
- data/lib/trellis/4.0/trellis_ruby.so +0 -0
- data/lib/trellis/instance.rb +4 -0
- data/lib/trellis/log_bridge.rb +201 -0
- data/lib/trellis/metrics.rb +129 -11
- data/lib/trellis/migration.rb +34 -0
- data/lib/trellis/pg.rb +37 -0
- data/lib/trellis/railtie.rb +119 -3
- data/lib/trellis/release_check.rb +165 -0
- data/lib/trellis/schema_dump.rb +26 -2
- data/lib/trellis/target.rb +141 -0
- data/lib/trellis/test_support.rb +176 -2
- data/lib/trellis/version.rb +1 -1
- metadata +5 -2
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 32858a579682652399d28fc37522d236b64c7d993f020d31c359360b2482e91b
|
|
4
|
+
data.tar.gz: a107d455b5653b41752d0771d65156e2c8d0805348e8db7123f1961dc540aa56
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 203c6dd57839357c21fa32c685f5b71db71015751c2d41e974a4c17fb660aa247544c545b77f3d642eebf734a64fd16c71e2dd5767154beffb322a9d86b834d7
|
|
7
|
+
data.tar.gz: 3f92eeed11565ed4ae0f7c04e6db962071850dba51218ce3e766666c44483790c0886f923606f94f3c01c7ea5a6f0f7927aea3d74ade69c69aed5835365d1e76
|
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.
|
|
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
|
|
133
|
-
|
|
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
|
|
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
|
-
|
|
218
|
-
|
|
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
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
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
|
|
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
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
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
|
-
|
|
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
|
|
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`)
|
|
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`
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
data/lib/trellis/instance.rb
CHANGED
|
@@ -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
|
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Trellis
|
|
4
|
+
# Forwards the engine's log lines to a Logger: Trellis.logger= installs
|
|
5
|
+
# trellis-embed's pull-based tracing subscriber in this extension's native
|
|
6
|
+
# library, and a Ruby thread drains its bounded queue into the Logger every
|
|
7
|
+
# 100 ms. Engine threads only append to the queue; nothing calls into the
|
|
8
|
+
# VM from them. Levels, drops, fork and exit behaviour: "Logs" in the
|
|
9
|
+
# README.
|
|
10
|
+
class LogBridge
|
|
11
|
+
# Seconds between drains.
|
|
12
|
+
INTERVAL = 0.1
|
|
13
|
+
# Records per call into the extension: one call holds the GVL for no
|
|
14
|
+
# longer than this many lines take to copy.
|
|
15
|
+
BATCH = 500
|
|
16
|
+
# Batches per drain_once: enough to empty a full queue (10,000 lines).
|
|
17
|
+
MAX_BATCHES = 21
|
|
18
|
+
|
|
19
|
+
# The engine's level words, as Logger's severity integers (written out,
|
|
20
|
+
# so the gem needs no `require "logger"`, a bundled gem since Ruby 4.0).
|
|
21
|
+
# Its trace has no Logger equivalent.
|
|
22
|
+
SEVERITIES = { error: 3, warn: 2, info: 1, debug: 0, trace: 0 }.freeze
|
|
23
|
+
|
|
24
|
+
# A Logger level, as the most verbose engine level worth forwarding. The
|
|
25
|
+
# engine has no level above error.
|
|
26
|
+
FILTERS = { debug: "debug", info: "info", warn: "warn", error: "error", fatal: "off", unknown: "off" }.freeze
|
|
27
|
+
|
|
28
|
+
@lock = Mutex.new
|
|
29
|
+
@current = nil
|
|
30
|
+
|
|
31
|
+
class << self
|
|
32
|
+
# The bridge Trellis.logger= installed, or nil.
|
|
33
|
+
attr_reader :current
|
|
34
|
+
|
|
35
|
+
# Replaces the process's bridge with one for `logger` (stopping the
|
|
36
|
+
# previous one), or with none if `logger` is nil: the engine's lines then
|
|
37
|
+
# go nowhere. `level` is the most verbose level forwarded, a Logger
|
|
38
|
+
# level (:info, "warn", 0); the default is logger.level.
|
|
39
|
+
# Returns the new bridge.
|
|
40
|
+
def install(logger, level: nil)
|
|
41
|
+
@lock.synchronize do
|
|
42
|
+
previous = @current
|
|
43
|
+
previous&.stop
|
|
44
|
+
@current = nil
|
|
45
|
+
if logger.nil?
|
|
46
|
+
Native.set_log_level("off") if previous
|
|
47
|
+
return nil
|
|
48
|
+
end
|
|
49
|
+
@current = new(logger, level: level).start
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
# Starts the bridge's thread again in a process forked since it started.
|
|
54
|
+
# What Instance.connect calls before it connects.
|
|
55
|
+
def ensure_running
|
|
56
|
+
@lock.synchronize { @current }&.ensure_running
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
# Stops the current bridge, draining what is left. Instance's at_exit
|
|
60
|
+
# hook calls it once every instance is down.
|
|
61
|
+
def stop_current
|
|
62
|
+
@lock.synchronize { @current }&.stop
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# A Logger level (Integer or word) as the engine's level filter word.
|
|
66
|
+
# Raises ValidationError for anything else.
|
|
67
|
+
def filter(level)
|
|
68
|
+
case level
|
|
69
|
+
when Integer then FILTERS.values.fetch(level.clamp(0, FILTERS.size - 1))
|
|
70
|
+
when Symbol, String
|
|
71
|
+
FILTERS.fetch(level.to_s.downcase.to_sym) { invalid_level!(level) }
|
|
72
|
+
else invalid_level!(level)
|
|
73
|
+
end
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
private
|
|
77
|
+
|
|
78
|
+
def invalid_level!(level)
|
|
79
|
+
raise ValidationError,
|
|
80
|
+
"a log level is one of #{FILTERS.keys.map(&:inspect).join(', ')} or a Logger severity " \
|
|
81
|
+
"integer, got: #{level.inspect}"
|
|
82
|
+
end
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
attr_reader :logger
|
|
86
|
+
|
|
87
|
+
def initialize(logger, level: nil)
|
|
88
|
+
unless logger.respond_to?(:add)
|
|
89
|
+
raise ValidationError, "the logger must respond to add (a Logger), got: #{logger.inspect}"
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
@logger = logger
|
|
93
|
+
@filter = self.class.filter(level || logger.level)
|
|
94
|
+
@drain_lock = Mutex.new
|
|
95
|
+
@state = Mutex.new
|
|
96
|
+
@pid = nil
|
|
97
|
+
@thread = nil
|
|
98
|
+
@stopped = false
|
|
99
|
+
@last_error = nil
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
# Installs the subscriber in the native library (once per process, however
|
|
103
|
+
# many bridges) and starts the thread. Raises ConflictError if another
|
|
104
|
+
# subscriber in that library was installed first.
|
|
105
|
+
def start
|
|
106
|
+
Native.install_log_bridge(@filter)
|
|
107
|
+
ensure_running
|
|
108
|
+
self
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
# Starts the thread if this process hasn't (it was forked since). A
|
|
112
|
+
# process forked from the one that started the bridge begins with an empty
|
|
113
|
+
# queue: the lines the parent hadn't drained yet are the parent's to log.
|
|
114
|
+
def ensure_running
|
|
115
|
+
@state.synchronize do
|
|
116
|
+
return self if @stopped || (@pid == Process.pid && @thread&.alive?)
|
|
117
|
+
|
|
118
|
+
discard_queue if @pid && @pid != Process.pid
|
|
119
|
+
@pid = Process.pid
|
|
120
|
+
@thread = Thread.new { run }
|
|
121
|
+
@thread.name = "trellis-log-bridge"
|
|
122
|
+
@thread.report_on_exception = false
|
|
123
|
+
end
|
|
124
|
+
self
|
|
125
|
+
end
|
|
126
|
+
|
|
127
|
+
# Whether this process's thread is running.
|
|
128
|
+
def running?
|
|
129
|
+
@state.synchronize { @pid == Process.pid && !!@thread&.alive? }
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
# Changes the most verbose level forwarded: a Logger level, as for
|
|
133
|
+
# install.
|
|
134
|
+
def level=(level)
|
|
135
|
+
@filter = self.class.filter(level)
|
|
136
|
+
Native.set_log_level(@filter)
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
# Forwards every line queued so far to the Logger before returning,
|
|
140
|
+
# rather than on the next tick. The thread calls it; tests and a host
|
|
141
|
+
# that wants the engine's last lines logged now can too. Returns true if
|
|
142
|
+
# lines may remain, because the queue held more than one call forwards.
|
|
143
|
+
def drain_once
|
|
144
|
+
@drain_lock.synchronize do
|
|
145
|
+
MAX_BATCHES.times do
|
|
146
|
+
records, dropped = Native.take_log_records(BATCH)
|
|
147
|
+
if dropped.positive?
|
|
148
|
+
logger.add(SEVERITIES.fetch(:warn), "Trellis dropped #{dropped} log lines: the Logger bridge fell behind", "trellis")
|
|
149
|
+
end
|
|
150
|
+
records.each { |level, target, message| logger.add(SEVERITIES.fetch(level), message, target) }
|
|
151
|
+
return false if records.size < BATCH
|
|
152
|
+
end
|
|
153
|
+
true
|
|
154
|
+
end
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
# Stops the thread and forwards what is left. Does nothing in a process
|
|
158
|
+
# forked since the bridge started and not started again: the queue it
|
|
159
|
+
# inherited isn't its own to log. A stopped bridge stays stopped.
|
|
160
|
+
def stop
|
|
161
|
+
thread = @state.synchronize do
|
|
162
|
+
@stopped = true
|
|
163
|
+
@thread if @pid == Process.pid
|
|
164
|
+
end
|
|
165
|
+
return unless thread
|
|
166
|
+
|
|
167
|
+
begin
|
|
168
|
+
thread.wakeup
|
|
169
|
+
rescue ThreadError
|
|
170
|
+
# Already finished.
|
|
171
|
+
end
|
|
172
|
+
thread.join
|
|
173
|
+
drain_safely
|
|
174
|
+
end
|
|
175
|
+
|
|
176
|
+
private
|
|
177
|
+
|
|
178
|
+
def run
|
|
179
|
+
until @stopped
|
|
180
|
+
sleep INTERVAL
|
|
181
|
+
drain_safely
|
|
182
|
+
end
|
|
183
|
+
end
|
|
184
|
+
|
|
185
|
+
# A Logger that raises (a closed stream) mustn't end the thread, or make
|
|
186
|
+
# the next drain's lines vanish: warn once per distinct failure, drop
|
|
187
|
+
# nothing it hasn't already taken, and carry on.
|
|
188
|
+
def drain_safely
|
|
189
|
+
nil while drain_once
|
|
190
|
+
@last_error = nil
|
|
191
|
+
rescue StandardError => e
|
|
192
|
+
failure = "#{e.class}: #{e.message}"
|
|
193
|
+
warn "trellis: forwarding the engine's log lines failed: #{failure}" unless failure == @last_error
|
|
194
|
+
@last_error = failure
|
|
195
|
+
end
|
|
196
|
+
|
|
197
|
+
def discard_queue
|
|
198
|
+
nil while Native.take_log_records(BATCH).first.size == BATCH
|
|
199
|
+
end
|
|
200
|
+
end
|
|
201
|
+
end
|