pgbus 0.24.0 → 0.25.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.
Files changed (51) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +12 -0
  3. data/README.md +5 -3
  4. data/app/controllers/pgbus/deploy_tasks_controller.rb +11 -1
  5. data/app/helpers/pgbus/deploy_tasks_helper.rb +20 -0
  6. data/app/models/pgbus/deploy_task.rb +23 -1
  7. data/app/models/pgbus/deploy_task_run.rb +47 -5
  8. data/app/views/pgbus/deploy_tasks/_tasks_table.html.erb +3 -0
  9. data/app/views/pgbus/deploy_tasks/show.html.erb +25 -2
  10. data/config/i18n-tasks.yml +1 -0
  11. data/config/locales/da.yml +18 -0
  12. data/config/locales/de.yml +18 -0
  13. data/config/locales/en.yml +18 -0
  14. data/config/locales/es.yml +18 -0
  15. data/config/locales/fi.yml +18 -0
  16. data/config/locales/fr.yml +18 -0
  17. data/config/locales/it.yml +18 -0
  18. data/config/locales/ja.yml +18 -0
  19. data/config/locales/nb.yml +18 -0
  20. data/config/locales/nl.yml +18 -0
  21. data/config/locales/pt.yml +18 -0
  22. data/config/locales/sv.yml +18 -0
  23. data/lib/generators/pgbus/add_deploy_task_run_outcomes_generator.rb +48 -0
  24. data/lib/generators/pgbus/templates/add_deploy_task_run_outcomes.rb.erb +12 -0
  25. data/lib/generators/pgbus/templates/add_deploy_tasks_tables.rb.erb +5 -0
  26. data/lib/generators/pgbus/templates/deploy_tasks.yml.erb +6 -0
  27. data/lib/generators/pgbus/templates/migration.rb.erb +5 -0
  28. data/lib/pgbus/active_job/adapter.rb +13 -0
  29. data/lib/pgbus/active_job/deploy_task_run_id.rb +53 -0
  30. data/lib/pgbus/active_job/executor.rb +57 -0
  31. data/lib/pgbus/client.rb +2 -3
  32. data/lib/pgbus/configuration.rb +25 -11
  33. data/lib/pgbus/dedicated_connection.rb +91 -3
  34. data/lib/pgbus/deploy/dependencies.rb +115 -0
  35. data/lib/pgbus/deploy/runner.rb +103 -18
  36. data/lib/pgbus/deploy/schema.rb +65 -0
  37. data/lib/pgbus/deploy/task.rb +23 -5
  38. data/lib/pgbus/doctor.rb +24 -2
  39. data/lib/pgbus/engine.rb +1 -0
  40. data/lib/pgbus/generators/migration_detector.rb +13 -3
  41. data/lib/pgbus/mcp/tools/deploy_tasks_tool.rb +1 -1
  42. data/lib/pgbus/streams/presence.rb +104 -13
  43. data/lib/pgbus/version.rb +1 -1
  44. data/lib/pgbus/web/data_source/deploy_task_list.rb +39 -6
  45. data/lib/pgbus/web/deploy_task_state.rb +7 -5
  46. data/lib/pgbus/web/streamer/instance.rb +7 -4
  47. data/lib/pgbus/web/streamer/listener.rb +32 -17
  48. data/lib/pgbus/web/streamer/master_hub.rb +6 -1
  49. data/lib/pgbus/web/streamer/stream_event_dispatcher.rb +1 -1
  50. data/sig/pgbus/configuration.rbs +2 -0
  51. metadata +6 -1
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pgbus
4
+ module Deploy
5
+ # Whether pgbus:add_deploy_task_run_outcomes has been migrated (issue
6
+ # #660): pgbus_deploy_task_runs.completed_at / failed_at and
7
+ # pgbus_deploy_tasks.dependencies. Until then after: is rejected at load,
8
+ # sync leaves dependencies alone and the executor writes no outcome.
9
+ #
10
+ # A "yes" is kept for the process; a "no" stands for RECHECK_SECONDS, so a
11
+ # process started before the migration picks the columns up without a
12
+ # restart. A probe that raises (a database blip) is not an answer: the
13
+ # error reaches the caller and nothing is kept, so a scheduler booting
14
+ # through a blip does not skip its after: tasks as unmigrated.
15
+ module Schema
16
+ RECHECK_SECONDS = 60
17
+
18
+ @mutex = Mutex.new
19
+ @answer = nil # true, nil (never probed) or the monotonic time a "no" runs out
20
+
21
+ class << self
22
+ def outcomes?
23
+ # Double-checked: the unlocked read only skips the lock while the
24
+ # answer stands; it is written under @mutex.
25
+ known = answer(@answer) # rubocop:disable ThreadSafety/ClassInstanceVariable
26
+ return known unless known.nil?
27
+
28
+ @mutex.synchronize do
29
+ known = answer(@answer)
30
+ next known unless known.nil?
31
+
32
+ supported = probe
33
+ @answer = supported || (monotonic_now + RECHECK_SECONDS)
34
+ supported
35
+ end
36
+ end
37
+
38
+ # Clears the memoized probe: specs exercise both schema shapes.
39
+ def reset!
40
+ @mutex.synchronize { @answer = nil }
41
+ end
42
+
43
+ private
44
+
45
+ def answer(state)
46
+ return true if state == true
47
+
48
+ false if state && monotonic_now < state
49
+ end
50
+
51
+ def probe
52
+ BusRecord.connection_pool.with_connection do |conn|
53
+ conn.column_exists?(:pgbus_deploy_task_runs, :completed_at) &&
54
+ conn.column_exists?(:pgbus_deploy_task_runs, :failed_at) &&
55
+ conn.column_exists?(:pgbus_deploy_tasks, :dependencies)
56
+ end
57
+ end
58
+
59
+ def monotonic_now
60
+ ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
61
+ end
62
+ end
63
+ end
64
+ end
65
+ end
@@ -5,12 +5,13 @@ module Pgbus
5
5
  # One declared deploy task (issue #536): an entry of
6
6
  # config/deploy_tasks.yml. The sibling of Recurring::Task without a
7
7
  # schedule: it runs once per (key, version) after a rollover, or after
8
- # every rollover when every_deploy is set.
8
+ # every rollover when every_deploy is set. after: names the tasks it
9
+ # waits for (issue #660): see Deploy::Dependencies.
9
10
  class Task
10
11
  DEFAULT_VERSION = "1"
11
12
 
12
13
  attr_reader :key, :class_name, :command, :version, :every_deploy, :queue_name,
13
- :arguments, :priority, :description
14
+ :arguments, :priority, :description, :dependencies
14
15
 
15
16
  def self.from_configuration(key, **options)
16
17
  options = options.transform_keys(&:to_sym)
@@ -24,12 +25,14 @@ module Pgbus
24
25
  queue_name: options[:queue],
25
26
  arguments: options[:args].is_a?(Hash) ? [options[:args]] : Array(options[:args]),
26
27
  priority: options.fetch(:priority, 0).to_i,
27
- description: options[:description]
28
+ description: options[:description],
29
+ dependencies: options[:after]
28
30
  )
29
31
  end
30
32
 
31
33
  def initialize(key:, class_name: nil, command: nil, version: DEFAULT_VERSION, explicit_version: false,
32
- every_deploy: false, queue_name: nil, arguments: [], priority: 0, description: nil)
34
+ every_deploy: false, queue_name: nil, arguments: [], priority: 0, description: nil,
35
+ dependencies: nil)
33
36
  @key = key
34
37
  @class_name = class_name
35
38
  @command = command
@@ -40,6 +43,7 @@ module Pgbus
40
43
  @arguments = arguments || []
41
44
  @priority = priority || 0
42
45
  @description = description
46
+ @dependencies = dependency_list(dependencies)
43
47
  @errors = []
44
48
  @warnings = []
45
49
  end
@@ -74,7 +78,8 @@ module Pgbus
74
78
  def to_h
75
79
  {
76
80
  key: key, class_name: class_name, command: command, version: version, every_deploy: every_deploy,
77
- queue_name: queue_name, arguments: arguments, priority: priority, description: description
81
+ queue_name: queue_name, arguments: arguments, priority: priority, description: description,
82
+ dependencies: dependencies
78
83
  }
79
84
  end
80
85
 
@@ -86,11 +91,24 @@ module Pgbus
86
91
  validate_target!
87
92
  @errors << "Version must not be blank" if version.empty?
88
93
  @errors << "every_deploy must be true or false" unless [true, false].include?(every_deploy)
94
+ validate_dependencies!
89
95
  return unless every_deploy == true && @explicit_version
90
96
 
91
97
  @warnings << "every_deploy is set, so version is ignored (it runs after every rollover)"
92
98
  end
93
99
 
100
+ def validate_dependencies!
101
+ @errors << "after: must name task keys" unless dependencies.all? { |dep| dep.is_a?(String) && !dep.strip.empty? }
102
+ @errors << "after: cycle #{key} \u2192 #{key}" if dependencies.include?(key)
103
+ end
104
+
105
+ # nil, one key, or a list; a Symbol reads as its name. Anything else is
106
+ # kept as given, for validate_dependencies! to reject.
107
+ def dependency_list(value)
108
+ list = value.is_a?(Array) ? value : [value].compact
109
+ list.map { |dep| dep.is_a?(Symbol) ? dep.to_s : dep }.uniq.freeze
110
+ end
111
+
94
112
  def validate_target!
95
113
  { class: class_name, command: command }.each do |name, value|
96
114
  @errors << "#{name} must be a String" unless value.nil? || value.is_a?(String)
data/lib/pgbus/doctor.rb CHANGED
@@ -5,7 +5,7 @@ require "pgbus/mcp/health_analyzer"
5
5
 
6
6
  module Pgbus
7
7
  # Preflight diagnostics for a pgbus deployment — the single command that
8
- # answers "is this environment healthy enough to run?". Runs fourteen checks and
8
+ # answers "is this environment healthy enough to run?". Runs fifteen checks and
9
9
  # returns a machine-readable result plus a human report, so `pgbus doctor`
10
10
  # and `rake pgbus:doctor` can gate a deploy or CI run (exit 0 on success,
11
11
  # 1 on any failure).
@@ -44,7 +44,8 @@ module Pgbus
44
44
  "Primary affinity" => :check_primary,
45
45
  "Dedicated connections" => :check_dedicated_connections,
46
46
  "Connection budget" => :check_connection_budget,
47
- "Completion commit" => :check_completion_commit
47
+ "Completion commit" => :check_completion_commit,
48
+ "Presence seats" => :check_presence_seats
48
49
  }.freeze
49
50
 
50
51
  # Process liveness reads the pgbus_processes table (via HealthAnalyzer), so
@@ -448,6 +449,27 @@ module Pgbus
448
449
  Check.new(name: "Completion commit", status: :warn, detail: "#{e.class}: #{e.message}")
449
450
  end
450
451
 
452
+ # Presence seats (issue #665). Without the add_presence_seats migration
453
+ # presence runs member-keyed (one row per member, no seats), and every
454
+ # process re-probes information_schema with backoff. A supported degraded
455
+ # mode, so a warning; ok when the columns exist or presence is not installed.
456
+ # Read through Presence, not the Client: presence reads ActiveRecord's
457
+ # connection (Pgbus::BusRecord under connects_to), which a database_url or
458
+ # connection_params Client connection need not share.
459
+ def check_presence_seats
460
+ case Pgbus::Streams::Presence.seats_state
461
+ when :absent then Check.new(name: "Presence seats", status: :ok, detail: "presence not installed")
462
+ when :present then Check.new(name: "Presence seats", status: :ok, detail: "pgbus_presence_members migrated with seats")
463
+ else
464
+ Check.new(name: "Presence seats", status: :warn,
465
+ detail: "pgbus_presence_members has no connection_id column — presence runs member-keyed " \
466
+ "(one row per member, no seats) and each process re-probes the schema; run " \
467
+ "`#{Pgbus::Streams::Presence::SEATS_MIGRATION_FIX}`")
468
+ end
469
+ rescue StandardError => e
470
+ Check.new(name: "Presence seats", status: :warn, detail: "could not read the schema (#{e.class}: #{e.message})")
471
+ end
472
+
451
473
  # How many direct LISTEN connections this config pins at steady state
452
474
  # (issue #381) — informational (always :ok) so operators can do capacity
453
475
  # math on the pooler's direct-connection budget from the doctor output.
data/lib/pgbus/engine.rb CHANGED
@@ -92,6 +92,7 @@ module Pgbus
92
92
  include Pgbus::Concurrency
93
93
  include Pgbus::Uniqueness
94
94
  include Pgbus::ActiveJob::BatchId
95
+ include Pgbus::ActiveJob::DeployTaskRunId
95
96
  include Pgbus::ActiveJob::CurrentAttributes
96
97
  include Pgbus::VisibilityHeartbeat::JobMixin
97
98
  end
@@ -94,6 +94,7 @@ module Pgbus
94
94
  add_outbox: "pgbus:add_outbox",
95
95
  add_recurring: "pgbus:add_recurring",
96
96
  add_deploy_tasks: "pgbus:add_deploy_tasks",
97
+ add_deploy_task_run_outcomes: "pgbus:add_deploy_task_run_outcomes",
97
98
  add_workflows: "pgbus:add_workflows",
98
99
  add_workflow_signals: "pgbus:add_workflow_signals",
99
100
  add_failed_events_index: "pgbus:add_failed_events_index",
@@ -121,6 +122,7 @@ module Pgbus
121
122
  add_outbox: "outbox entries table (transactional outbox)",
122
123
  add_recurring: "recurring tasks + executions tables",
123
124
  add_deploy_tasks: "deploy tasks + runs tables (one-time jobs run after a rollover)",
125
+ add_deploy_task_run_outcomes: "deploy task run outcomes (completed_at, failed_at) and after: dependencies",
124
126
  add_workflows: "workflow tables (durable multi-step workflows: runs, step attempts, audit trail)",
125
127
  add_workflow_signals: "waiting workflow steps (fan_out, wait_for: signals, wait timeouts)",
126
128
  add_failed_events_index: "unique index on pgbus_failed_events (queue_name, msg_id)",
@@ -253,10 +255,18 @@ module Pgbus
253
255
 
254
256
  # Same shape as recurring_migrations: plain create_table in the
255
257
  # template, so the generator is queued only while a table is absent.
258
+ # The outcomes add-on (issue #660) follows the tables: its template
259
+ # adds each column if_not_exists, so queuing it after add_deploy_tasks
260
+ # also completes a half-present schema whose existing table lacks them.
256
261
  def deploy_tasks_migrations
257
- return [] if table_exists?("pgbus_deploy_tasks") && table_exists?("pgbus_deploy_task_runs")
258
-
259
- [:add_deploy_tasks]
262
+ return %i[add_deploy_tasks add_deploy_task_run_outcomes] unless
263
+ table_exists?("pgbus_deploy_tasks") && table_exists?("pgbus_deploy_task_runs")
264
+
265
+ runs = column_names("pgbus_deploy_task_runs")
266
+ outcomes = runs.include?("completed_at") && runs.include?("failed_at") &&
267
+ column_names("pgbus_deploy_tasks").include?("dependencies") &&
268
+ index_exists?("pgbus_deploy_task_runs", "idx_pgbus_deploy_task_runs_completed")
269
+ outcomes ? [] : [:add_deploy_task_run_outcomes]
260
270
  end
261
271
 
262
272
  # The add_workflows template uses if_not_exists throughout, so a
@@ -11,7 +11,7 @@ module Pgbus
11
11
  tool_name "pgbus_deploy_tasks"
12
12
  title "Pgbus Deploy Tasks"
13
13
  description <<~DESC
14
- Deploy tasks: one-time jobs the scheduler enqueues once every live pgbus process runs the new app revision. Lists each task's state (disabled, waiting, due, ran, never) and the rollover status the scheduler waits on.
14
+ Deploy tasks: one-time jobs the scheduler enqueues once every live pgbus process runs the new app revision. Lists each task's state (disabled, waiting, due, ran, never), the rollover status the scheduler waits on, and for a task with after: its dependencies and the ones it still waits on (waiting_on, each not_run, running or failed).
15
15
  Returns every task unless page or per_page is given; then it is
16
16
  paginated (per_page defaults to 100, capped at 100). The response
17
17
  carries page, per_page, total (capped at 10000 when paginated; the
@@ -65,19 +65,39 @@ module Pgbus
65
65
  RECORD_COLUMNS = "member_id, metadata, joined_at, last_seen_at"
66
66
  SEAT_RECORD_COLUMNS = "member_id, metadata, joined_at, last_seen_at, connection_id, seat, state"
67
67
 
68
- # How long a "no seats" answer is trusted before the schema is probed
69
- # again, so a table migrated under a running process is picked up.
68
+ # How long the first "no seats" answer is trusted before the schema is
69
+ # probed again, so a table migrated under a running process is picked
70
+ # up. Each further "no" doubles the wait, up to SCHEMA_RECHECK_MAX_SECONDS
71
+ # (issue #665).
70
72
  SCHEMA_RECHECK_SECONDS = 30
73
+ SCHEMA_RECHECK_MAX_SECONDS = 600
74
+
75
+ # What the doctor and the one-time warning tell an operator to run.
76
+ SEATS_MIGRATION_FIX = "rails generate pgbus:add_presence_seats && rails db:migrate"
77
+
78
+ # NULL: no pgbus_presence_members table; false: the table without the
79
+ # seat columns; true: seats. The same schema predicate as the
80
+ # seats_supported? probe.
81
+ SEATS_STATE_SQL = <<~SQL
82
+ SELECT bool_or(column_name = 'connection_id') FROM information_schema.columns
83
+ WHERE table_name = 'pgbus_presence_members' AND table_schema = ANY (current_schemas(false))
84
+ SQL
71
85
 
72
86
  @schema_mutex = Mutex.new
73
87
  @seats_supported = nil
74
88
  @probed_at = nil
89
+ @recheck_seconds = SCHEMA_RECHECK_SECONDS
75
90
  @schema_generation = 0
91
+ # Survives reset_schema_cache!: the warning is once per process.
92
+ @seats_warning_logged = false
76
93
 
77
94
  class << self
78
95
  # True when pgbus_presence_members has the seat columns (the
79
96
  # add_presence_seats migration ran). A true answer is kept for the
80
- # life of the process; a false one for SCHEMA_RECHECK_SECONDS.
97
+ # life of the process. A false one is kept for SCHEMA_RECHECK_SECONDS,
98
+ # then twice as long after each further false answer, up to
99
+ # SCHEMA_RECHECK_MAX_SECONDS (issue #665); the first one logs a
100
+ # warning naming the migration, once per process.
81
101
  #
82
102
  # The answer is read and written under @schema_mutex only (issue
83
103
  # #527). A successful probe is kept as above; a probe that raises is
@@ -90,7 +110,7 @@ module Pgbus
90
110
  # probe that a reset_schema_cache! overtook stores nothing.
91
111
  def seats_supported?
92
112
  cached, generation = @schema_mutex.synchronize do
93
- [(@seats_supported if schema_answer_fresh?(@seats_supported, @probed_at)), @schema_generation]
113
+ [(@seats_supported if schema_answer_fresh?(@seats_supported, @probed_at, @recheck_seconds)), @schema_generation]
94
114
  end
95
115
  return cached unless cached.nil?
96
116
 
@@ -100,12 +120,9 @@ module Pgbus
100
120
  AND table_schema = ANY (current_schemas(false))
101
121
  SQL
102
122
  supported = !rows.to_a.empty?
103
- @schema_mutex.synchronize do
104
- next supported unless generation == @schema_generation
105
-
106
- @probed_at = monotonic_now
107
- @seats_supported ||= supported
108
- end
123
+ answer, warn = store_schema_answer(supported, generation)
124
+ warn_seats_missing if warn
125
+ answer
109
126
  end
110
127
 
111
128
  # seats_supported?, but a cached "no seats" is probed again first.
@@ -127,6 +144,22 @@ module Pgbus
127
144
  end
128
145
  end
129
146
 
147
+ # What Pgbus::Doctor reports (issue #665): :absent (no
148
+ # pgbus_presence_members table, or no ActiveRecord database to reach
149
+ # it), :missing (add_presence_seats has not run) or :present. Read on
150
+ # the connection presence uses, leased for this statement only, and
151
+ # never cached. A database that is configured but down raises.
152
+ def seats_state
153
+ return :absent unless defined?(::ActiveRecord::Base)
154
+
155
+ value = presence_pool&.with_connection { |conn| conn.select_value(SEATS_STATE_SQL) }
156
+ case value
157
+ when nil then :absent
158
+ when true, "t" then :present
159
+ else :missing
160
+ end
161
+ end
162
+
130
163
  # Deletes every seat row (connection_id IS NOT NULL) that has not
131
164
  # been touched within its stream's ttl and returns the deleted
132
165
  # records, each with its "stream_name". Member-keyed rows are left
@@ -197,13 +230,71 @@ module Pgbus
197
230
  "Pgbus::Streams::Presence requires ActiveRecord (no AR connection available)"
198
231
  end
199
232
 
200
- Pgbus.configuration.connects_to ? Pgbus::BusRecord.connection : ::ActiveRecord::Base.connection
233
+ record_base.connection
234
+ end
235
+
236
+ def record_base
237
+ Pgbus.configuration.connects_to ? Pgbus::BusRecord : ::ActiveRecord::Base
201
238
  end
202
239
 
203
- def schema_answer_fresh?(supported, probed_at)
240
+ # The pool presence reads from, or nil when ActiveRecord has none
241
+ # defined for it (a process on database_url alone): connection_pool
242
+ # raises ConnectionNotEstablished only for a missing pool, never for
243
+ # a database that is down.
244
+ def presence_pool
245
+ record_base.connection_pool
246
+ rescue ::ActiveRecord::ConnectionNotEstablished
247
+ nil
248
+ end
249
+
250
+ def schema_answer_fresh?(supported, probed_at, recheck_seconds)
204
251
  return false if supported.nil? || probed_at.nil?
205
252
 
206
- supported || monotonic_now - probed_at < SCHEMA_RECHECK_SECONDS
253
+ supported || monotonic_now - probed_at < recheck_seconds
254
+ end
255
+
256
+ # Stores a probe's answer unless a reset_schema_cache! overtook it.
257
+ # Returns the answer to give and whether to log the missing-seats
258
+ # warning (the first "no" of the process).
259
+ #
260
+ # A "no" over a fresh "no" (two threads probed at once) keeps the
261
+ # first one's time and step, so concurrent probes are one step. A
262
+ # true answer is never taken back.
263
+ def store_schema_answer(supported, generation)
264
+ @schema_mutex.synchronize do
265
+ next [supported, false] unless generation == @schema_generation
266
+
267
+ if supported || @seats_supported
268
+ @probed_at = monotonic_now
269
+ next [@seats_supported = true, false]
270
+ end
271
+ next [false, false] if schema_answer_fresh?(@seats_supported, @probed_at, @recheck_seconds)
272
+
273
+ @recheck_seconds = next_recheck_seconds(@seats_supported, @recheck_seconds)
274
+ @probed_at = monotonic_now
275
+ @seats_supported = false
276
+ warn = !@seats_warning_logged
277
+ @seats_warning_logged = true
278
+ [false, warn]
279
+ end
280
+ end
281
+
282
+ # A "no" after a stale "no" doubles the wait, up to the cap; a "no"
283
+ # after no answer (the first probe, or after reset_schema_cache!)
284
+ # starts at SCHEMA_RECHECK_SECONDS.
285
+ def next_recheck_seconds(previous_answer, previous_seconds)
286
+ return SCHEMA_RECHECK_SECONDS if previous_answer.nil?
287
+
288
+ [previous_seconds * 2, SCHEMA_RECHECK_MAX_SECONDS].min
289
+ end
290
+
291
+ def warn_seats_missing
292
+ Pgbus.logger&.warn(
293
+ "[Pgbus::Streams::Presence] pgbus_presence_members has no seat columns (connection_id): presence " \
294
+ "runs member-keyed, one row per member, and the schema keeps being re-checked. Run `#{SEATS_MIGRATION_FIX}` to get seats " \
295
+ "(if the table does not exist, run `rails generate pgbus:add_presence && rails db:migrate` instead: " \
296
+ "it already creates the seat columns)."
297
+ )
207
298
  end
208
299
 
209
300
  def expire_stream_seats(stream_name, connection_ids, ttl)
data/lib/pgbus/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Pgbus
4
- VERSION = "0.24.0"
4
+ VERSION = "0.25.1"
5
5
  end
@@ -6,6 +6,8 @@ module Pgbus
6
6
  # The Deploy tasks page (issue #536): declared tasks with their last
7
7
  # rollover and manual runs, one task's run history, the rollover the
8
8
  # scheduler acts on, and the two actions (Run now, Enable/Disable).
9
+ # A task with after: (issue #660) also lists the dependencies it still
10
+ # waits on, judged against the scheduler's revision like the rollover.
9
11
  module DeployTaskList
10
12
  RUN_HISTORY = 25
11
13
 
@@ -15,11 +17,13 @@ module Pgbus
15
17
  def deploy_tasks(page: nil, per_page: nil)
16
18
  return [] unless DeployTask.table_exists?
17
19
 
20
+ DeployTask.refresh_dependencies_column!
18
21
  scope = DeployTask.order(:key)
19
22
  scope = scope.limit(per_page).offset(((page || 1) - 1) * per_page) if per_page
20
23
  records = scope.to_a
21
24
  runs = DeployTaskRun.latest_for(records.map(&:key)).group_by(&:task_key)
22
- records.map { |record| deploy_task_row(record, runs.fetch(record.key, [])) }
25
+ waiting = deploy_waiting_on(records)
26
+ records.map { |record| deploy_task_row(record, runs.fetch(record.key, []), waiting) }
23
27
  rescue StandardError => e
24
28
  Pgbus.logger.error { "[Pgbus::Web] Error fetching deploy tasks: #{e.class}: #{e.message}" }
25
29
  []
@@ -28,13 +32,14 @@ module Pgbus
28
32
  def deploy_task(id)
29
33
  return nil unless DeployTask.table_exists?
30
34
 
35
+ DeployTask.refresh_dependencies_column!
31
36
  record = DeployTask.find_by(id: id)
32
37
  return nil unless record
33
38
 
34
39
  # The state reads the same unbounded latest-per-trigger runs as the
35
40
  # list, so a run older than the 25 shown still counts.
36
41
  runs = DeployTaskRun.for_task(record.key).recent(RUN_HISTORY).to_a
37
- deploy_task_row(record, DeployTaskRun.latest_for([record.key]).to_a).merge(
42
+ deploy_task_row(record, DeployTaskRun.latest_for([record.key]).to_a, deploy_waiting_on([record])).merge(
38
43
  arguments: record.parsed_arguments,
39
44
  runs: runs.map { |run| deploy_run_hash(run).merge(queue_name: run.queue_name, msg_id: run.msg_id) }
40
45
  )
@@ -56,12 +61,15 @@ module Pgbus
56
61
 
57
62
  # Run now: the scheduler's enqueue path with no gate and no claim. It
58
63
  # leaves a pending rollover arm alone and records a manual run.
59
- # :enqueued or :failed, the real outcome.
60
- def enqueue_deploy_task_now(id)
64
+ # :enqueued or :failed, the real outcome; :blocked when the task waits
65
+ # on a dependency and ignore_dependencies is not set.
66
+ def enqueue_deploy_task_now(id, ignore_dependencies: false)
67
+ DeployTask.refresh_dependencies_column!
61
68
  record = DeployTask.find_by(id: id)
62
69
  return :failed unless record
63
70
  # The hidden button is not the boundary: a disabled task is not run.
64
71
  return disabled_enqueue(record) unless record.enabled
72
+ return :blocked if !ignore_dependencies && deploy_waiting_on([record]).fetch(record.key, []).any?
65
73
 
66
74
  Deploy::Runner.new(config: Pgbus.configuration).enqueue(record.to_task, triggered_by: Deploy::Runner::MANUAL)
67
75
  rescue StandardError => e
@@ -90,7 +98,25 @@ module Pgbus
90
98
  :failed
91
99
  end
92
100
 
93
- def deploy_task_row(record, latest_runs)
101
+ # { key => [{ key:, state: }] } for the +records+ with after:, one
102
+ # query for their dependencies' rows and one for their outcomes.
103
+ def deploy_waiting_on(records)
104
+ dependents = records.to_h { |record| [record.key, record.parsed_dependencies] }.select { |_, keys| keys.any? }
105
+ return {} if dependents.empty? || !Deploy::Schema.outcomes?
106
+
107
+ by_key = DeployTask.where(key: dependents.values.flatten.uniq).index_by(&:key)
108
+ dependencies = Deploy::Dependencies.load(by_key.values, revision: deploy_dependency_revision)
109
+ dependents.transform_values { |keys| dependencies.waiting_on(keys, by_key) }
110
+ end
111
+
112
+ # The revision an every_deploy dependency must have completed on: the
113
+ # newest live scheduler's, as for deploy_rollover.
114
+ def deploy_dependency_revision
115
+ scheduler, revision = Deploy::Rollover.scheduler_revision
116
+ scheduler ? revision : Deploy::Revision.current
117
+ end
118
+
119
+ def deploy_task_row(record, latest_runs, waiting = {})
94
120
  by_trigger = latest_runs.index_by(&:triggered_by)
95
121
  {
96
122
  id: record.id, key: record.key, class_name: record.class_name, command: record.command,
@@ -99,6 +125,7 @@ module Pgbus
99
125
  static: record.static, armed_at: record.armed_at, armed_for: record.armed_for,
100
126
  last_rollover_run: deploy_run_hash(by_trigger[Deploy::Runner::ROLLOVER]),
101
127
  last_manual_run: deploy_run_hash(by_trigger[Deploy::Runner::MANUAL]),
128
+ dependencies: record.parsed_dependencies, waiting_on: waiting.fetch(record.key, []),
102
129
  created_at: record.created_at, updated_at: record.updated_at
103
130
  }
104
131
  end
@@ -106,7 +133,13 @@ module Pgbus
106
133
  def deploy_run_hash(run)
107
134
  return nil unless run
108
135
 
109
- { run_at: run.run_at, revision: run.revision, version: run.version, triggered_by: run.triggered_by }
136
+ { run_at: run.run_at, revision: run.revision, version: run.version, triggered_by: run.triggered_by,
137
+ completed_at: deploy_run_outcome(run, "completed_at"), failed_at: deploy_run_outcome(run, "failed_at") }
138
+ end
139
+
140
+ # nil before the outcomes migration.
141
+ def deploy_run_outcome(run, column)
142
+ run.has_attribute?(column) ? run[column] : nil
110
143
  end
111
144
  end
112
145
  end
@@ -6,8 +6,9 @@ module Pgbus
6
6
  # its row and the rollover the scheduler acts on (DataSource#deploy_rollover),
7
7
  # so the page prints the reason the scheduler waits for. Pure.
8
8
  #
9
- # States: disabled, waiting (armed, gate closed, with the gate's reason),
10
- # due (armed, gate open), ran (not armed, has a rollover run), never. A
9
+ # States: disabled, waiting (armed, gate closed, with the gate's reason;
10
+ # or gate open and an after: dependency not completed, issue #660), due
11
+ # (armed, gate open), ran (not armed, has a rollover run), never. A
11
12
  # manual run is appended to any state through manual_args.
12
13
  module DeployTaskState
13
14
  BADGE_TONES = { "disabled" => :gray, "waiting" => :yellow, "due" => :indigo, "ran" => :green,
@@ -27,7 +28,7 @@ module Pgbus
27
28
 
28
29
  def derive(row, rollover)
29
30
  return ["disabled", row[:armed_at] ? "disabled_armed" : "disabled", {}] unless row[:enabled]
30
- return armed(rollover) if row[:armed_at]
31
+ return armed(rollover, row[:waiting_on] || []) if row[:armed_at]
31
32
 
32
33
  run = row[:last_rollover_run]
33
34
  return ["never", "never", {}] unless run
@@ -35,12 +36,13 @@ module Pgbus
35
36
  ["ran", "ran", { ago: run[:run_at], revision: run[:revision] }]
36
37
  end
37
38
 
38
- def armed(rollover)
39
+ def armed(rollover, waiting_on)
39
40
  return ["waiting", "waiting_unknown", {}] unless rollover
40
41
  return ["waiting", "waiting_no_scheduler", {}] unless rollover[:scheduler]
41
42
 
42
43
  case rollover[:reason]
43
- when :ready then ["due", "due", {}]
44
+ when :ready
45
+ waiting_on.empty? ? ["due", "due", {}] : ["waiting", "waiting_dependencies", { count: waiting_on.size }]
44
46
  when :lagging then ["waiting", "waiting_lagging", { count: rollover[:lagging].size, revision: rollover[:revision] }]
45
47
  when :no_workers then ["waiting", "waiting_no_workers", { revision: rollover[:revision] }]
46
48
  else ["waiting", "waiting_no_revision", {}]
@@ -190,12 +190,13 @@ module Pgbus
190
190
  return nil if socket_path.nil? || socket_path.empty?
191
191
 
192
192
  # The worker's ack deadline must exceed the master's own internal
193
- # ensure_listening budget (its listener's health-check cycle + 1s).
193
+ # ensure_listening budget (its listener's ack budget), so it gets
194
+ # that plus 1 s. Independent of the keepalive (issue #664).
194
195
  failover = nil
195
196
  client = HubClient.new(
196
197
  socket_path: socket_path,
197
198
  dispatch_queue: @dispatch_queue,
198
- ack_timeout: (@config.streams_listen_health_check_ms / 1000.0) + 2.0,
199
+ ack_timeout: (@config.streams_listen_ack_timeout_ms / 1000.0) + 1.0,
199
200
  # failover is assigned right below; a transport death in the gap
200
201
  # is caught by the FailoverListener's synchronous ensure path.
201
202
  on_failure: -> { failover&.fail_over! },
@@ -221,6 +222,7 @@ module Pgbus
221
222
  pg_connection: pg_connection,
222
223
  dispatch_queue: @dispatch_queue,
223
224
  health_check_ms: @config.streams_listen_health_check_ms,
225
+ ack_timeout_ms: @config.streams_listen_ack_timeout_ms,
224
226
  # Opt-in dispatch-queue backpressure (issue #315 item 3). 0 =
225
227
  # unbounded (default). The queue itself stays an unbounded
226
228
  # Queue.new so the request-thread Connect push and the dispatcher's
@@ -335,11 +337,12 @@ module Pgbus
335
337
  # runs its own PrimaryValidator (retrying on a replica) and skips the
336
338
  # probe to stay cheap, mirroring Pgbus::Process::NotifyListener.
337
339
  # String/Hash go through DedicatedConnection so a :session-mode
338
- # `:variables` key never reaches PG.connect (issue #352).
340
+ # `:variables` key never reaches PG.connect (issue #352), with TCP
341
+ # keepalives so a dead socket errors between keepalives (issue #664).
339
342
  def build_raw_pg_connection
340
343
  opts = @config.streams_connection_options
341
344
  case opts
342
- when String, Hash then Pgbus::DedicatedConnection.connect(opts)
345
+ when String, Hash then Pgbus::DedicatedConnection.connect_with_keepalives(opts)
343
346
  when Proc
344
347
  # The Proc branch in connection_options typically returns
345
348
  # ActiveRecord::Base.connection.raw_connection — a pooled