trellis-pg 0.3.1 → 0.4.0

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.
@@ -34,7 +34,7 @@
34
34
  //! (statuses, quarantine states, `apply` outcome kinds, `self_check` outcomes and divergence kinds), but only
35
35
  //! words from the closed sets `trellis-embed` lists, which [`init`] interns
36
36
  //! up front, never a string read from the database.
37
- //! - **Errors cross as `(code, message)`.** Ruby's `Trellis::Error.from_native`
37
+ //! - **Errors cross as `(code, error_id, message)`.** Ruby's `Trellis::Error.from_native`
38
38
  //! picks the exception class for the code, so the code-to-class map lives in
39
39
  //! one place, `lib/trellis/error.rb`.
40
40
  //!
@@ -67,11 +67,11 @@ use trellis_embed::{
67
67
  PlainDefinitionSummary, PlainDivergence, PlainDrainFailure, PlainError, PlainExtremeIndexGap,
68
68
  PlainFanOutWarning, PlainHeldKeys, PlainHiddenTable, PlainJoinBuildStep, PlainJoinStatus,
69
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,
70
+ PlainRefusedStep, PlainSamplePage, PlainSelfCheckJob, PlainSelfCheckReport,
71
+ PlainSourceIndexGap, PlainVersionHandover, SELF_CHECK_MODES, SELF_CHECK_OUTCOMES,
72
+ SELF_CHECK_STATES, capture_failure_kind_names, decode_cursor, decode_watermark,
73
+ encode_watermark, index_role_names, quarantine_state_names, require_transform_statement,
74
+ self_check_mode, 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
@@ -260,6 +260,33 @@ impl Handle {
260
260
  .map_err(|err| raise(ruby, err.into()))
261
261
  }
262
262
 
263
+ /// What `rollback` would do, read now; changes nothing
264
+ /// ([`BlockingTrellis::rollback_plan`]).
265
+ fn rollback_plan(ruby: &Ruby, rb_self: &Self, to: Option<String>) -> Result<RHash, Error> {
266
+ let plan = rb_self.call(ruby, |trellis| trellis.start_rollback_plan(to.as_deref()))?;
267
+ leave_plan_hash(ruby, plan)
268
+ }
269
+
270
+ /// Leaves this release for an earlier one ([`BlockingTrellis::rollback`]).
271
+ fn rollback(ruby: &Ruby, rb_self: &Self, to: Option<String>) -> Result<RHash, Error> {
272
+ let plan = rb_self.call(ruby, |trellis| trellis.start_rollback(to.as_deref()))?;
273
+ leave_plan_hash(ruby, plan)
274
+ }
275
+
276
+ /// What `uninstall` would do, read now; changes nothing
277
+ /// ([`BlockingTrellis::uninstall_plan`]).
278
+ fn uninstall_plan(ruby: &Ruby, rb_self: &Self) -> Result<RHash, Error> {
279
+ let plan = rb_self.call(ruby, BlockingTrellis::start_uninstall_plan)?;
280
+ leave_plan_hash(ruby, plan)
281
+ }
282
+
283
+ /// Removes everything Trellis has in the database
284
+ /// ([`BlockingTrellis::uninstall`]).
285
+ fn uninstall(ruby: &Ruby, rb_self: &Self) -> Result<RHash, Error> {
286
+ let plan = rb_self.call(ruby, BlockingTrellis::start_uninstall)?;
287
+ leave_plan_hash(ruby, plan)
288
+ }
289
+
263
290
  /// Rebuilds every applying definition that reads `source_table`
264
291
  /// (`live -> backfilling`).
265
292
  fn request_backfill(ruby: &Ruby, rb_self: &Self, source_table: String) -> Result<(), Error> {
@@ -430,6 +457,10 @@ impl Handle {
430
457
  "call_pool_wait_timeout_ms",
431
458
  ruby.into_value(config.call_pool_wait_timeout_ms),
432
459
  ),
460
+ (
461
+ "claim_grace_period_ms",
462
+ ruby.into_value(config.claim_grace_period_ms),
463
+ ),
433
464
  ],
434
465
  )
435
466
  }
@@ -476,6 +507,7 @@ fn connect(
476
507
  worker_threads: usize,
477
508
  max_call_pool_size: usize,
478
509
  call_pool_wait_timeout_ms: u64,
510
+ claim_grace_period_ms: u64,
479
511
  ) -> Result<Handle, Error> {
480
512
  engine::check().map_err(|err| forked_handle_error(ruby, forked_while_running(&err)))?;
481
513
  // Connecting can wait on the database (a staging worker installs its
@@ -497,6 +529,7 @@ fn connect(
497
529
  worker_threads: Some(worker_threads),
498
530
  max_call_pool_size,
499
531
  call_pool_wait_timeout: Duration::from_millis(call_pool_wait_timeout_ms),
532
+ claim_grace_period: Duration::from_millis(claim_grace_period_ms),
500
533
  ..Default::default()
501
534
  };
502
535
  // Can't fail after `check` passed (a process's answer never
@@ -830,7 +863,9 @@ fn trellis_module(ruby: &Ruby) -> Result<RModule, Error> {
830
863
  fn raise(ruby: &Ruby, err: PlainError) -> Error {
831
864
  let exception = trellis_module(ruby)
832
865
  .and_then(|module| module.const_get::<_, RClass>("Error"))
833
- .and_then(|class| class.funcall::<_, _, Exception>("from_native", (err.code, err.message)));
866
+ .and_then(|class| {
867
+ class.funcall::<_, _, Exception>("from_native", (err.code, err.error_id, err.message))
868
+ });
834
869
  match exception {
835
870
  Ok(exception) => exception.into(),
836
871
  Err(err) => err,
@@ -877,6 +912,50 @@ fn record<const N: usize>(ruby: &Ruby, fields: [(&str, Value); N]) -> Result<RHa
877
912
  Ok(hash)
878
913
  }
879
914
 
915
+ /// A `trellis::LeavePlan`, with `above_to` and the text every surface
916
+ /// prints for confirmation (`description`).
917
+ fn leave_plan_hash(ruby: &Ruby, plan: trellis::LeavePlan) -> Result<RHash, Error> {
918
+ let definitions = |list: Vec<&trellis::LeftDefinition>| {
919
+ array(ruby, list, |ruby, definition| {
920
+ record(
921
+ ruby,
922
+ [
923
+ ("target", ruby.into_value(definition.target.as_str())),
924
+ ("floor", ruby.into_value(definition.floor.as_str())),
925
+ ("one_to_one", ruby.into_value(definition.one_to_one)),
926
+ ],
927
+ )
928
+ })
929
+ };
930
+ let above_to = definitions(plan.above_to())?;
931
+ let all = definitions(plan.definitions.iter().collect())?;
932
+ record(
933
+ ruby,
934
+ [
935
+ ("schema", ruby.into_value(plan.schema.as_str())),
936
+ (
937
+ "captured_tables",
938
+ ruby.ary_from_iter(plan.captured_tables.iter().map(String::as_str))
939
+ .as_value(),
940
+ ),
941
+ (
942
+ "ledgers",
943
+ ruby.ary_from_iter(plan.ledgers.iter().map(String::as_str))
944
+ .as_value(),
945
+ ),
946
+ (
947
+ "targets",
948
+ ruby.ary_from_iter(plan.targets.iter().map(String::as_str))
949
+ .as_value(),
950
+ ),
951
+ ("definitions", all.as_value()),
952
+ ("above_to", above_to.as_value()),
953
+ ("to", ruby.into_value(plan.to.as_deref())),
954
+ ("description", ruby.into_value(plan.describe())),
955
+ ],
956
+ )
957
+ }
958
+
880
959
  /// `items`, each turned into a Ruby value by `convert`.
881
960
  fn array<T, V: IntoValue>(
882
961
  ruby: &Ruby,
@@ -947,6 +1026,7 @@ fn status_hash(ruby: &Ruby, status: PlainDefinitionStatus) -> Result<RHash, Erro
947
1026
  .below_catalog_floor
948
1027
  .map(|seen| below_catalog_floor_hash(ruby, seen))
949
1028
  .transpose()?;
1029
+ let maintenance_refusals = array(ruby, status.maintenance_refusals, refused_step_hash)?;
950
1030
  let join = status
951
1031
  .join
952
1032
  .map(|join| join_status_hash(ruby, join))
@@ -970,8 +1050,10 @@ fn status_hash(ruby: &Ruby, status: PlainDefinitionStatus) -> Result<RHash, Erro
970
1050
  ("build_wait_xid", ruby.into_value(status.build_wait_xid)),
971
1051
  ("version_handover", ruby.into_value(version_handover)),
972
1052
  ("below_catalog_floor", ruby.into_value(below_catalog_floor)),
1053
+ ("maintenance_refusals", maintenance_refusals.as_value()),
973
1054
  ("join", ruby.into_value(join)),
974
1055
  ("floor", ruby.into_value(status.floor)),
1056
+ ("filter", ruby.into_value(status.filter)),
975
1057
  ],
976
1058
  )
977
1059
  }
@@ -1059,22 +1141,17 @@ fn join_build_step_hash(ruby: &Ruby, step: PlainJoinBuildStep) -> Result<RHash,
1059
1141
  )
1060
1142
  }
1061
1143
 
1062
- /// Another Trellis version is live, so this binary stands by.
1144
+ /// Another Trellis version owns the instance, so this binary stands by.
1063
1145
  fn version_handover_hash(ruby: &Ruby, seen: PlainVersionHandover) -> Result<RHash, Error> {
1064
1146
  let processes = array(ruby, seen.processes, other_process_hash)?;
1065
1147
  record(
1066
1148
  ruby,
1067
1149
  [
1068
1150
  ("this_version", ruby.into_value(seen.this_version)),
1151
+ ("owner", ruby.into_value(seen.owner)),
1152
+ ("by_rollback", ruby.into_value(seen.by_rollback)),
1069
1153
  ("processes", processes.as_value()),
1070
- (
1071
- "unregistered_staging_worker",
1072
- ruby.into_value(seen.unregistered_staging_worker),
1073
- ),
1074
- (
1075
- "migrations_pending",
1076
- ruby.into_value(seen.migrations_pending),
1077
- ),
1154
+ ("claims_at_micros", ruby.into_value(seen.claims_at_micros)),
1078
1155
  ],
1079
1156
  )
1080
1157
  }
@@ -1090,6 +1167,20 @@ fn below_catalog_floor_hash(ruby: &Ruby, seen: PlainBelowCatalogFloor) -> Result
1090
1167
  )
1091
1168
  }
1092
1169
 
1170
+ /// A maintenance step the staging worker's role is refused.
1171
+ fn refused_step_hash(ruby: &Ruby, refused: PlainRefusedStep) -> Result<RHash, Error> {
1172
+ record(
1173
+ ruby,
1174
+ [
1175
+ ("step", ruby.into_value(refused.step)),
1176
+ ("role", ruby.into_value(refused.role)),
1177
+ ("object", ruby.into_value(refused.object)),
1178
+ ("missing", ruby.ary_from_iter(refused.missing).as_value()),
1179
+ ("error", ruby.into_value(refused.error)),
1180
+ ],
1181
+ )
1182
+ }
1183
+
1093
1184
  /// A live process of another version.
1094
1185
  fn other_process_hash(ruby: &Ruby, process: PlainOtherProcess) -> Result<RHash, Error> {
1095
1186
  record(
@@ -1538,7 +1629,7 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
1538
1629
  }
1539
1630
 
1540
1631
  let native = ruby.define_module("Trellis")?.define_module("Native")?;
1541
- native.define_module_function("connect", function!(connect, 8))?;
1632
+ native.define_module_function("connect", function!(connect, 9))?;
1542
1633
  native.define_module_function("error_codes", function!(error_codes, 0))?;
1543
1634
  native.define_module_function("status_names", function!(status_names, 0))?;
1544
1635
  native.define_module_function("quarantine_states", function!(quarantine_states, 0))?;
@@ -1573,6 +1664,10 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
1573
1664
  )?;
1574
1665
  handle.define_method("schema_dump", method!(Handle::schema_dump, 0))?;
1575
1666
  handle.define_method("filter_schema_dump", method!(Handle::filter_schema_dump, 1))?;
1667
+ handle.define_method("rollback_plan", method!(Handle::rollback_plan, 1))?;
1668
+ handle.define_method("rollback", method!(Handle::rollback, 1))?;
1669
+ handle.define_method("uninstall_plan", method!(Handle::uninstall_plan, 0))?;
1670
+ handle.define_method("uninstall", method!(Handle::uninstall, 0))?;
1576
1671
  handle.define_method("request_backfill", method!(Handle::request_backfill, 1))?;
1577
1672
  handle.define_method("release_key", method!(Handle::release_key, 3))?;
1578
1673
  handle.define_method("poisoned_since", method!(Handle::poisoned_since, 1))?;
data/lib/trellis/error.rb CHANGED
@@ -1,8 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Trellis
4
- # An error from Trellis: the engine's message and a stable #code, and
5
- # nothing else (ADR-0010 decision 4). Every error the binding raises is one
4
+ # An error from Trellis: the engine's message, a stable #code and the
5
+ # per-error #error_id, and nothing else (ADR-0010 decision 4). Every error the binding raises is one
6
6
  # of the subclasses below, so `rescue Trellis::Error` catches them all, and
7
7
  # `rescue Trellis::NotFoundError` just one kind.
8
8
  #
@@ -20,13 +20,23 @@ module Trellis
20
20
  self.class::CODE
21
21
  end
22
22
 
23
- # The exception for the native extension's `(code, message)` pair.
23
+ # The engine's per-error code, such as "T0042", which the message also
24
+ # starts with: the thing to look up. nil for an error the binding raises
25
+ # itself.
26
+ attr_reader :error_id
27
+
28
+ def initialize(message = nil, error_id: nil)
29
+ super(message)
30
+ @error_id = error_id
31
+ end
32
+
33
+ # The exception for the native extension's `(code, error_id, message)`.
24
34
  # Not part of the public API.
25
- def self.from_native(code, message)
35
+ def self.from_native(code, error_id, message)
26
36
  klass = BY_CODE[code]
27
- return klass.new(message) if klass
37
+ return klass.new(message, error_id: error_id) if klass
28
38
 
29
- UnknownError.new("(error code #{code.inspect}) #{message}")
39
+ UnknownError.new("(error code #{code.inspect}) #{message}", error_id: error_id)
30
40
  end
31
41
  end
32
42
 
@@ -71,11 +81,11 @@ module Trellis
71
81
  CODE = :timeout
72
82
  end
73
83
 
74
- # A Trellis process of another version is live on the instance, so this
75
- # call changed nothing: a state-changing call, or Trellis.migrate with
76
- # migrations pending, during a deploy that crosses a version boundary.
77
- # Read-only calls keep working. Retry once the other version's processes
78
- # have stopped; the message names the versions and their worker ids.
84
+ # Another Trellis version owns the instance, so this state-changing call
85
+ # changed nothing, during a deploy that crosses a version boundary.
86
+ # Read-only calls keep working. Retry under the owner's version, or run
87
+ # Trellis.migrate with this one to claim the instance; the message names
88
+ # the versions and the owner's worker ids.
79
89
  class VersionHandoverError < Error
80
90
  CODE = :version_handover
81
91
  end
@@ -70,6 +70,8 @@ module Trellis
70
70
  # - Quarantine: quarantined, quarantine_status, sample_quarantined,
71
71
  # poisoned_since, release_key. Pausing and resuming are statements:
72
72
  # instance.apply("RESUME TRANSFORM order_totals.total").
73
+ # - Leaving: rollback and uninstall, each with a _plan variant that
74
+ # changes nothing (rails trellis:rollback and trellis:uninstall).
73
75
  # - Operations: request_backfill, detect_capture_disruptions, has_live_drain_workers?,
74
76
  # has_live_staging_worker?, the read-your-writes pair watermark_token and
75
77
  # await_converged, and the audit self_check, a background job that
@@ -139,6 +141,10 @@ module Trellis
139
141
  # sized by staging and drain_threads, not by this.
140
142
  # - call_pool_wait_timeout_ms: how long a call waits for a free call-pool
141
143
  # connection before failing with a ConnectivityError.
144
+ # - claim_grace_period_ms: how long the owner version may be silent
145
+ # before a standing-by background process of another version claims
146
+ # the instance (ADR-0023, rule 6; sized in docs/embedding.md).
147
+ # Default 600_000 (10 minutes).
142
148
  #
143
149
  # The defaults (staging: false, drain_threads: 0) run nothing in the
144
150
  # background, which is what a migration step or a console wants. The
@@ -146,7 +152,7 @@ module Trellis
146
152
  # connect to an unmigrated schema fails: migrate first.
147
153
  def connect(url:, schema: "trellis", target_schema: "public", staging: false,
148
154
  drain_threads: 0, worker_threads: 2, max_call_pool_size: 20,
149
- call_pool_wait_timeout_ms: 30_000)
155
+ call_pool_wait_timeout_ms: 30_000, claim_grace_period_ms: 600_000)
150
156
  string_option!(:url, url)
151
157
  string_option!(:schema, schema)
152
158
  string_option!(:target_schema, target_schema)
@@ -173,9 +179,17 @@ module Trellis
173
179
  "#{call_pool_wait_timeout_ms.inspect}"
174
180
  end
175
181
 
182
+ unless claim_grace_period_ms.is_a?(Integer) &&
183
+ claim_grace_period_ms.between?(0, MAX_TIMEOUT_MS)
184
+ raise ValidationError,
185
+ "claim_grace_period_ms must be a non-negative Integer, got: " \
186
+ "#{claim_grace_period_ms.inspect}"
187
+ end
188
+
176
189
  LogBridge.ensure_running
177
190
  handle = Native.connect(url, schema, target_schema, staging, drain_threads, worker_threads,
178
- max_call_pool_size, call_pool_wait_timeout_ms)
191
+ max_call_pool_size, call_pool_wait_timeout_ms,
192
+ claim_grace_period_ms)
179
193
  instance = new(handle, schema)
180
194
  register(instance)
181
195
  instance
@@ -370,6 +384,44 @@ module Trellis
370
384
  handle.filter_schema_dump(pg_dump_output)
371
385
  end
372
386
 
387
+ # What rollback would do, read now, as rollback returns it; changes
388
+ # nothing. Raises what rollback raises.
389
+ def rollback_plan(to: nil)
390
+ leave_plan(handle.rollback_plan(rollback_to!(to)))
391
+ end
392
+
393
+ # Leaves this release for an earlier one, below the catalog floor
394
+ # included (docs/upgrading.md, "Below the catalog floor"). Run it with the
395
+ # release being left, which must own the instance, with its background
396
+ # processes stopped. It drops Trellis's schema, the capture triggers and
397
+ # the ledgers and empties every target, leaving a restore queue of the
398
+ # definitions and a version hold; the earlier release's migrate restores
399
+ # them and rebuilds every target. `to:` names that release (a String
400
+ # such as "0.3.1"), for the plan's :above_to.
401
+ #
402
+ # Returns what it did, a frozen Hash: :schema, :captured_tables,
403
+ # :ledgers, :targets, :definitions (each { target:, floor:, one_to_one:
404
+ # }, in restore order), :above_to (those the release named by `to:`
405
+ # won't run; every one without it), :to, and :description, the text
406
+ # `rails trellis:rollback` prints for confirmation.
407
+ def rollback(to: nil)
408
+ leave_plan(handle.rollback(rollback_to!(to)))
409
+ end
410
+
411
+ # What uninstall would do, read now, as uninstall returns it; changes
412
+ # nothing.
413
+ def uninstall_plan
414
+ leave_plan(handle.uninstall_plan)
415
+ end
416
+
417
+ # Removes everything Trellis has in the database: its schema, the
418
+ # capture triggers on the source tables, the ledgers and the targets. Run
419
+ # it with the release that owns the instance, with every Trellis process
420
+ # stopped. Returns what it did, shaped as rollback's.
421
+ def uninstall
422
+ leave_plan(handle.uninstall)
423
+ end
424
+
373
425
  # Rebuilds every definition that reads source_table (a bare table name,
374
426
  # resolved like one in a statement), and returns once that rebuild is
375
427
  # queued.
@@ -586,6 +638,23 @@ module Trellis
586
638
 
587
639
  private
588
640
 
641
+ def rollback_to!(to)
642
+ return to if to.nil? || to.is_a?(String)
643
+
644
+ raise ValidationError, "to: must be a release version String, got: #{to.inspect}"
645
+ end
646
+
647
+ def leave_plan(plan)
648
+ freeze_list = ->(list) { list.map(&:freeze).freeze }
649
+ plan.merge(
650
+ captured_tables: freeze_list.(plan[:captured_tables]),
651
+ ledgers: freeze_list.(plan[:ledgers]),
652
+ targets: freeze_list.(plan[:targets]),
653
+ definitions: freeze_list.(plan[:definitions]),
654
+ above_to: freeze_list.(plan[:above_to])
655
+ ).freeze
656
+ end
657
+
589
658
  def handle
590
659
  @handle or raise ValidationError,
591
660
  "this Trellis instance (schema #{@schema.inspect}) is not connected: " \
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Trellis
4
+ # What `rails trellis:rollback` and `rails trellis:uninstall` run: for
5
+ # the default instance (config.trellis.connect) and each of
6
+ # config.trellis.instances, connect one with no background work, print
7
+ # what the command will drop and empty, ask for confirmation, run it.
8
+ #
9
+ # Both destroy data, so confirmation is typed: the command's name at a
10
+ # terminal, or CONFIRM=yes when there isn't one. Without either nothing
11
+ # changes. Rails's protected-environment check (the one db:drop makes)
12
+ # doesn't apply: production is where these run.
13
+ module LeaveTask # :nodoc:
14
+ # Raised when the operator didn't confirm; nothing changed.
15
+ class NotConfirmed < StandardError; end
16
+
17
+ COMMANDS = %i[rollback uninstall].freeze
18
+
19
+ module_function
20
+
21
+ # Runs `command` on every configured instance. `to` is rollback's TO=,
22
+ # `confirm` the CONFIRM= value, `input`/`output` the terminal.
23
+ def run(command, to: nil, confirm: nil, input: $stdin, output: $stdout)
24
+ raise ArgumentError, "unknown command #{command.inspect}" unless COMMANDS.include?(command)
25
+ if command == :uninstall && to
26
+ raise ValidationError, "trellis:uninstall doesn't take TO="
27
+ end
28
+
29
+ instances = configured
30
+ if instances.empty?
31
+ raise ValidationError, "config.trellis.connect is not set: give it Trellis.connect's options"
32
+ end
33
+
34
+ instances.each do |what, options|
35
+ leave(command, what, options, to:, confirm:, input:, output:)
36
+ end
37
+ nil
38
+ end
39
+
40
+ # [what, options] for each configured instance, the default first.
41
+ def configured
42
+ default = Railtie.connect_options
43
+ named = Railtie.instance_options.map do |name, options|
44
+ ["config.trellis.instances[#{name.inspect}]", options]
45
+ end
46
+ (default ? [["config.trellis.connect", default]] : []) + named
47
+ end
48
+
49
+ def leave(command, what, options, to:, confirm:, input:, output:)
50
+ instance = Instance.connect(**options, staging: false, drain_threads: 0)
51
+ begin
52
+ plan = command == :rollback ? instance.rollback_plan(to:) : instance.uninstall_plan
53
+ output.puts "#{what}:", plan[:description]
54
+ confirm!(command, what, confirm, input, output)
55
+ done = command == :rollback ? instance.rollback(to:) : instance.uninstall
56
+ output.puts done_message(command, what, done)
57
+ ensure
58
+ instance.shutdown
59
+ end
60
+ end
61
+
62
+ def confirm!(command, what, confirm, input, output)
63
+ return if confirm == "yes"
64
+
65
+ unless input.respond_to?(:tty?) && input.tty?
66
+ raise NotConfirmed,
67
+ "nothing changed for #{what}: set CONFIRM=yes to run trellis:#{command} without a terminal"
68
+ end
69
+
70
+ output.print "Type `#{command}` to go on: "
71
+ output.flush
72
+ return if input.gets&.strip == command.to_s
73
+
74
+ raise NotConfirmed, "nothing changed for #{what}: not confirmed"
75
+ end
76
+
77
+ def done_message(command, what, plan)
78
+ return "#{what}: uninstalled" if command == :uninstall
79
+
80
+ "#{what}: rolled back: #{plan[:definitions].size} definitions queued. Now deploy the " \
81
+ "earlier release and run its migrate (`rails trellis:migrate`); " \
82
+ "it restores them and rebuilds every target."
83
+ end
84
+ end
85
+ end
@@ -66,13 +66,13 @@ module Trellis
66
66
  #
67
67
  # == Environments Trellis is off in
68
68
  #
69
- # A database of an environment named in config.trellis.off_in (`%w[test]`)
70
- # is built by loading the schema, which carries the targets as plain
71
- # tables, not by a migration that defines one. Run in that environment, the
72
- # three helpers raise ActiveRecord::MigrationError before running anything.
73
- # Run from an environment Trellis is on in (`db:prepare` in development
74
- # migrates the test database too), they do nothing and return nil: that
75
- # database is reloaded from the new dump the next time it is prepared.
69
+ # In an environment named in config.trellis.off_in (`%w[test]`) only the
70
+ # runtime is off: the helpers run as they do elsewhere, against the
71
+ # database being migrated, so migrating builds every target. Nothing
72
+ # builds or maintains one there: each definition stays
73
+ # `waiting_to_backfill`, and its sources get no capture triggers (the
74
+ # staging worker installs them), so writes to them capture nothing. A test
75
+ # fills a target with Trellis::TestSupport#refresh_trellis_target.
76
76
  #
77
77
  # == up and down, not change
78
78
  #
@@ -94,6 +94,13 @@ module Trellis
94
94
  # down. A migration's own handle never runs background work: staging and
95
95
  # drain_threads are always the defaults, whatever the configuration says.
96
96
  #
97
+ # A migration of another environment's database (`db:prepare` in
98
+ # development migrates the test databases too), or of a database of an
99
+ # environment Trellis is off in, never uses this process's handle: the
100
+ # helpers, and `Trellis::Railtie.with_handle` called in it, connect one to
101
+ # that environment's counterpart of the database the instance's url points
102
+ # at, or to the migrating database itself (Trellis::Railtie.with_handle).
103
+ #
97
104
  # The helpers run on the default instance. A migration for an instance
98
105
  # named in config.trellis.instances runs its statements on that instance
99
106
  # itself, in the same transaction-free way:
@@ -118,46 +125,44 @@ module Trellis
118
125
  # The guard checks the target's name, not its definition: a changed
119
126
  # statement for a target that exists is an `ALTER TRANSFORM`.
120
127
  module Migration
121
- # The helpers' Trellis::Railtie.with_handle: runs the block with this
128
+ # The helpers' Trellis::Railtie.with_handle: yields the block this
122
129
  # process's handle, or one connected from config.trellis.connect for the
123
- # length of the block, running Trellis.migrate first either way, and
130
+ # length of the block, running migrate on it first either way, and
124
131
  # returns the block's value. Without Rails, it uses this process's
125
132
  # handle. Raises ActiveRecord::MigrationError if there's neither.
126
- def self.with_handle(&)
127
- if Trellis.connected?
128
- Trellis.migrate
129
- return yield
133
+ def self.with_handle
134
+ if defined?(Trellis::Railtie) && Trellis::Railtie.connect_options
135
+ return Trellis::Railtie.with_handle { |trellis| yield trellis }
130
136
  end
131
137
 
132
- unless defined?(Trellis::Railtie) && Trellis::Railtie.connect_options
138
+ unless Trellis.connected?
133
139
  raise ActiveRecord::MigrationError,
134
140
  "there's no Trellis to run this against: set config.trellis.connect to " \
135
141
  "Trellis.connect's options (config.trellis.connect = { url: ENV.fetch(\"DATABASE_URL\") }), " \
136
142
  "or call Trellis.connect before migrating"
137
143
  end
138
144
 
139
- Trellis::Railtie.with_handle(&)
145
+ Trellis.migrate
146
+ yield Trellis.default_instance
140
147
  end
141
148
 
142
149
  # Registers a transform from a `TRANSFORM` statement and returns its
143
150
  # target table: Trellis.define, run as the migration reaches it.
144
151
  def define(statement)
145
- trellis_statement("define", statement) { Trellis.define(statement) }
152
+ trellis_statement("define", statement) { |trellis| trellis.define(statement) }
146
153
  end
147
154
 
148
155
  # Runs any statement of Trellis's grammar and returns its Applied:
149
156
  # Trellis.apply, run as the migration reaches it.
150
157
  def apply(statement)
151
- trellis_statement("apply", statement) { Trellis.apply(statement) }
158
+ trellis_statement("apply", statement) { |trellis| trellis.apply(statement) }
152
159
  end
153
160
 
154
161
  # The Status of the transform writing target_table, or nil when none
155
162
  # does: Trellis.status. A read, so it runs whether or not a transaction
156
163
  # is open.
157
164
  def status(target_table)
158
- return if off_database?("this status wasn't read: #{target_table}")
159
-
160
- Migration.with_handle { Trellis.status(target_table) }
165
+ Migration.with_handle { |trellis| trellis.status(target_table) }
161
166
  end
162
167
 
163
168
  # ActiveRecord's entry point for running this migration in a direction:
@@ -170,7 +175,9 @@ module Trellis
170
175
  "define in down with apply \"PAUSE TRANSFORM <target>\" and " \
171
176
  "apply \"DROP TRANSFORM <target>\"."
172
177
  end
173
- super
178
+ return super unless defined?(Trellis::Railtie)
179
+
180
+ Trellis::Railtie.working_on(conn.pool.db_config) { super }
174
181
  end
175
182
 
176
183
  private
@@ -181,31 +188,9 @@ module Trellis
181
188
  "cannot reverse a Trellis statement: #{statement}. Undo a define in down with " \
182
189
  "PAUSE TRANSFORM and DROP TRANSFORM statements."
183
190
  end
184
- return if off_database?("this statement wasn't applied: #{statement}")
185
-
186
191
  refuse_open_transaction!("this statement wasn't applied: #{statement}")
187
192
 
188
- say_with_time("#{helper}(#{statement.inspect})") { Migration.with_handle { yield } }
189
- end
190
-
191
- # Whether the migrating database belongs to an environment Trellis is off
192
- # in, so `what` is skipped: raises when that is also the environment
193
- # running the migration.
194
- def off_database?(what)
195
- return false unless defined?(Trellis::Railtie)
196
-
197
- environment = connection.pool.db_config.env_name
198
- return false unless Trellis::Railtie.off_in?(environment)
199
-
200
- if Trellis::Railtie.off_in?(ActiveRecord::Tasks::DatabaseTasks.env)
201
- raise ActiveRecord::MigrationError,
202
- Trellis::Railtie.off_message("#{what}. Build this database by loading the schema " \
203
- "(`bin/rails db:schema:load`, or `db:test:prepare`) rather than " \
204
- "migrating it", environment)
205
- end
206
-
207
- say Trellis::Railtie.off_message("#{what}; the next schema load of this database brings it in", environment)
208
- true
193
+ say_with_time("#{helper}(#{statement.inspect})") { Migration.with_handle { |trellis| yield trellis } }
209
194
  end
210
195
 
211
196
  def refuse_open_transaction!(what)
data/lib/trellis/pg.rb CHANGED
@@ -48,6 +48,7 @@ require_relative "metrics"
48
48
  # dump_definitions_sql.
49
49
  # - Quarantine: quarantined, quarantine_status, sample_quarantined,
50
50
  # poisoned_since, release_key.
51
+ # - Leaving: rollback, uninstall, rollback_plan, uninstall_plan.
51
52
  # - Operations: request_backfill, detect_capture_disruptions, has_live_drain_workers?,
52
53
  # has_live_staging_worker?, watermark_token, await_converged, self_check,
53
54
  # self_check_job.
@@ -100,9 +101,9 @@ module Trellis
100
101
  nil
101
102
  end
102
103
 
103
- # Whether Trellis is on in this process's Rails environment: false when
104
- # the app's config.trellis.off_in names it (`%w[test]`, so a test suite
105
- # runs without Trellis). Always true without Rails. Code that builds on
104
+ # Whether Trellis's runtime is on in this process's Rails environment:
105
+ # false when the app's config.trellis.off_in names it (`%w[test]`, so a
106
+ # test suite runs no worker). Always true without Rails. Code that builds on
106
107
  # Trellis, such as a test helper that fills a target, branches on it.
107
108
  def enabled?
108
109
  !defined?(Trellis::Railtie) || Trellis::Railtie.enabled?