captive-cli 1.9.1 → 1.11.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: f2945bf5e2de69e09faee353e8e2c27e3a62a1a9865746b71dd9f179405a0c1b
4
- data.tar.gz: 70160d63a4ae4dfc3c401f121efb50c1a83e576bf327daa9088631ab51ea99e1
3
+ metadata.gz: 72b1622689b08b0eef85aaade0d3a87567f623798659fea71c2a2db35c8f2a3a
4
+ data.tar.gz: 8835974c91d69d4075d615499063887d2cd2cc2117bd960bdf199174fcc9626f
5
5
  SHA512:
6
- metadata.gz: c7e83b774d39711cf093b71a4c0436070c010a45762643159ff622e005a0dc106b139088eb4c56a89661bde4297e84b8981282e763fbdd0ad49f9868f9c8176d
7
- data.tar.gz: 27defed341c0decfcfdd47e63ac293f37af92f15daf45a627bc923202c5730436e2816b57c1b59dc32726cdc43cb462fadd85b6ffac2f0420ce682dc51190b36
6
+ metadata.gz: d701686536a48fcbc4037d3db660e087894e02cb98ebb1c6435c107807a4aa008cb1194c28182747d25347ebeacf548e832b4d7b3098ba1f8206711c72f15b77
7
+ data.tar.gz: 65a0b1ce4eb77dab427a559e3c220b81c1d33c7b82c7220370bd1621be29f5781c5c819b4c56e8ac3d9f56af558b1e84206ac930d69040bc0929ad809709dfdf
@@ -19,7 +19,6 @@ module Captive
19
19
  # passe par kubectl exec et n'est capturé nulle part, donc n'en porte pas.
20
20
  def console_opened(app, session: nil) = signaler(app, "console", session: session)
21
21
  def db_dumped(app) = signaler(app, "db_dump")
22
- def db_restored(app) = signaler(app, "db_restore")
23
22
  def db_psql_opened(app) = signaler(app, "db_psql")
24
23
 
25
24
  def db_query_run(app, sql, read_only:)
@@ -1,6 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "supabase_auth_change"
4
+ require_relative "supabase_realtime_change"
5
+ require_relative "pg_cron_change"
4
6
 
5
7
  module Captive
6
8
  module Commands
@@ -66,6 +68,38 @@ module Captive
66
68
  puts SupabaseAuthChange.new(addons: addons_api, paint: paint).run(app, options)
67
69
  end
68
70
 
71
+ desc "realtime APP", "Affiche ou modifie l'option Temps réel de l'add-on Supabase"
72
+ long_desc <<~DESC
73
+ Sans option : affiche l'option Temps réel (diffusion, présence) et Postgres Changes.
74
+ Avec --enabled (et --postgres-changes, désactivé s'il est omis) : les modifie.
75
+ Postgres Changes exige PostgreSQL 18.6. Réservé aux admins de l'Organization.
76
+
77
+ \x05Exemples :
78
+ \x05 captive addons realtime my-app-staging
79
+ \x05 captive addons realtime my-app-staging --enabled=true --postgres-changes=true
80
+ DESC
81
+ method_option :enabled, enum: %w[true false], desc: "Option Temps réel"
82
+ method_option :postgres_changes, enum: %w[true false], desc: "Écoute des changements de la base"
83
+ def realtime(app)
84
+ puts SupabaseRealtimeChange.new(addons: addons_api, paint: paint).run(app, options)
85
+ end
86
+
87
+ desc "pg-cron APP", "Affiche ou modifie l'option pg_cron et pg_net de la base"
88
+ long_desc <<~DESC
89
+ Sans option : affiche si pg_cron et pg_net sont activés sur la base.
90
+ Avec --enabled : les active ou les désactive. La base redémarre.
91
+ Exige PostgreSQL 18. Réservé aux admins de l'Organization.
92
+
93
+ \x05Exemples :
94
+ \x05 captive addons pg-cron my-app-staging
95
+ \x05 captive addons pg-cron my-app-staging --enabled=true
96
+ DESC
97
+ method_option :enabled, enum: %w[true false], desc: "Option pg_cron et pg_net"
98
+ map "pg-cron" => :pg_cron
99
+ def pg_cron(app)
100
+ puts PgCronChange.new(addons: addons_api, paint: paint).run(app, options)
101
+ end
102
+
69
103
  private
70
104
 
71
105
  def presenter = Presenter::Addon.new(paint: paint)
@@ -3,6 +3,7 @@
3
3
  require "tty-spinner"
4
4
  require_relative "db_exec"
5
5
  require_relative "db_psql"
6
+ require_relative "db_migrations_mark"
6
7
 
7
8
  module Captive
8
9
  module Commands
@@ -49,6 +50,27 @@ module Captive
49
50
  abort paint.red("✗ #{e.message}")
50
51
  end
51
52
 
53
+ desc "migrations-mark APP", "Inscrit les migrations Supabase comme jouées, sans les jouer"
54
+ long_desc <<~DESC
55
+ Pour une base migrée à la main avant que la plateforme joue les migrations au
56
+ déploiement : inscrit chaque fichier <horodatage>_<nom>.sql du dossier dans
57
+ supabase_migrations.schema_migrations, sans l'exécuter. Une version déjà inscrite
58
+ est laissée telle quelle. --up-to s'arrête à la dernière migration réellement jouée.
59
+
60
+ \x05Exemple :
61
+ \x05 captive db migrations-mark sas-seatup-staging
62
+ \x05 captive db migrations-mark sas-seatup-staging --up-to 20261020120000
63
+ DESC
64
+ method_option :dir, type: :string, default: "supabase/migrations", desc: "Dossier des migrations"
65
+ method_option :up_to, type: :string, desc: "Dernière version à inscrire (incluse)"
66
+ def migrations_mark(app)
67
+ versions = DbMigrationsMark.new(exec: DbExec.new(kubectl: kubectl, trail: trail))
68
+ .run(app, options[:dir], up_to: options[:up_to])
69
+ puts paint.green(" ✓ #{versions.size} migrations inscrites comme jouées, jusqu'à #{versions.last}.")
70
+ rescue Captive::ExecError => e
71
+ abort paint.red("✗ #{e.message}")
72
+ end
73
+
52
74
  desc "psql APP", "Ouvre une session psql sur la base, ou joue une requête avec -c"
53
75
  long_desc <<~DESC
54
76
  Session psql interactive sur la base de l'app, sous un rôle admin
@@ -69,44 +91,19 @@ module Captive
69
91
  abort paint.red("✗ #{e.message}")
70
92
  end
71
93
 
72
- desc "restore APP DUMP_FILE", "Restaure la base depuis un dump local"
94
+ desc "restore APP DUMP_FILE", "Restauration de base : passe par l'équipe plateforme"
73
95
  long_desc <<~DESC
74
- Arrête l'app, restaure la base, relance l'app.
75
- Formats : .pgsql, .dump, .tar.gz, .sql, .sql.gz.
96
+ La restauration arrête l'app et suspend Flux : elle est réservée à l'équipe
97
+ plateforme. Transmets-lui le dump et la commande à lancer.
76
98
 
77
99
  \x05Exemple :
78
100
  \x05 captive db restore my-app dump.pgsql
79
- \x05 captive db restore my-app 20260602_backup.tar.gz
80
101
  DESC
81
102
  def restore(app, dump_file)
82
- labels = {
83
- scaling_down: "Arrêt de l'app...",
84
- transferring: "Transfert du dump...",
85
- restoring: "Restauration...",
86
- scaling_up: "Relance de l'app...",
87
- }
88
- spinner = restore_spinner
89
- DbRestore.new(kubectl: kubectl, trail: trail).run(app, dump_file) do |step, elapsed = nil, info = nil|
90
- if step == :waiting
91
- spinner.auto_spin unless spinner.spinning?
92
- spinner.update(info: (info && !info.empty?) ? info : "en cours... #{elapsed.to_i}s")
93
- else
94
- spinner.success if spinner.spinning?
95
- puts paint.dim(" → #{labels[step]}")
96
- end
97
- end
98
- puts paint.green(" ✓ Restauration terminée.")
99
- rescue Errno::ENOENT => e
100
- abort paint.red("✗ Fichier introuvable : #{e.message}")
101
- rescue Captive::RestoreError => e
102
- spinner.error if spinner.spinning?
103
- abort paint.red("✗ #{e.message}")
104
- end
105
-
106
- private
107
-
108
- def restore_spinner
109
- TTY::Spinner.new(" [:spinner] :info", format: :dots)
103
+ abort paint.yellow(<<~MSG)
104
+ La restauration de base passe par l'équipe plateforme. Transmets-lui le dump et cette commande :
105
+ captive-admin db restore #{app} #{dump_file}
106
+ MSG
110
107
  end
111
108
  end
112
109
  end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "tempfile"
4
+ require_relative "../errors"
5
+
6
+ module Captive
7
+ module Commands
8
+ # Inscrit les migrations d'un dossier local dans supabase_migrations.schema_migrations sans
9
+ # les jouer : la base a été migrée à la main (captive db exec), l'initContainer de
10
+ # déploiement (BRIO-268) rejouerait tout sur une table de suivi vide. L'équivalent de
11
+ # `supabase migration repair --status applied`, joué via captive db exec.
12
+ class DbMigrationsMark
13
+ FILE = /\A([0-9]+)_(.*)\.sql\z/
14
+
15
+ # La table du CLI Supabase (supabase/cli, pkg/migration/history.go).
16
+ TABLE = <<~SQL
17
+ create schema if not exists supabase_migrations;
18
+ create table if not exists supabase_migrations.schema_migrations (version text not null primary key);
19
+ alter table supabase_migrations.schema_migrations add column if not exists statements text[];
20
+ alter table supabase_migrations.schema_migrations add column if not exists name text;
21
+ SQL
22
+
23
+ def initialize(exec:)
24
+ @exec = exec
25
+ end
26
+
27
+ def run(app, dir, up_to: nil)
28
+ migrations = read(dir).select { |version, _| up_to.nil? || version.to_i <= up_to.to_i }
29
+ raise ExecError, "aucune migration <horodatage>_<nom>.sql dans #{dir}" if migrations.empty?
30
+
31
+ Tempfile.create([ "marquage", ".sql" ]) do |file|
32
+ file.write(TABLE + inscription(migrations))
33
+ file.close
34
+ @exec.run(app, file.path)
35
+ end
36
+ migrations.map(&:first)
37
+ end
38
+
39
+ private
40
+
41
+ def read(dir)
42
+ Dir.children(dir).sort.filter_map { |name| FILE.match(name)&.captures }
43
+ rescue Errno::ENOENT
44
+ []
45
+ end
46
+
47
+ def inscription(migrations)
48
+ values = migrations.map { |version, name| "('#{version}', '#{name.gsub("'", "''")}')" }
49
+ "insert into supabase_migrations.schema_migrations (version, name) values\n " \
50
+ "#{values.join(",\n ")}\non conflict (version) do nothing;\n"
51
+ end
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Captive
4
+ module Commands
5
+ # `addons pg-cron` : sans réglage, les lignes qui décrivent l'option ; avec --enabled, l'état
6
+ # voulu envoyé au dashboard, que captive-platform applique plus tard en redémarrant la base (ADR 0041).
7
+ class PgCronChange
8
+ def initialize(addons:, paint:)
9
+ @addons = addons
10
+ @paint = paint
11
+ end
12
+
13
+ # `options` : les options Thor de la commande, `enabled` ("true"/"false").
14
+ def run(app, options)
15
+ enabled = options["enabled"]
16
+ return Presenter::PgCron.new(paint: @paint).lines(@addons.pg_cron(app), app: app) unless enabled
17
+
18
+ @addons.set_pg_cron(app, enabled: enabled == "true")
19
+ [ @paint.green(" ✓ Option pg_cron en cours de modification, la base redémarre : #{CLIDependencies::ASYNC_NOTICE}"),
20
+ @paint.dim(" Suivre : captive addons pg-cron #{app}"), ]
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../errors"
4
+
5
+ module Captive
6
+ module Commands
7
+ # `addons realtime` : sans réglage, les lignes qui décrivent l'option ; avec --enabled, l'état
8
+ # voulu complet envoyé au dashboard, que captive-platform applique plus tard (ADR 0039, 0043).
9
+ # Postgres Changes absent vaut false, comme côté dashboard.
10
+ class SupabaseRealtimeChange
11
+ def initialize(addons:, paint:)
12
+ @addons = addons
13
+ @paint = paint
14
+ end
15
+
16
+ # `options` : les options Thor de la commande, `enabled` et `postgres_changes` ("true"/"false").
17
+ def run(app, options)
18
+ enabled, postgres_changes = options.values_at("enabled", "postgres_changes")
19
+ return etat(app) unless enabled || postgres_changes
20
+ raise ValidationError, "Préciser --enabled avec --postgres-changes." unless enabled
21
+
22
+ @addons.set_supabase_realtime(app, enabled: enabled == "true", postgres_changes: postgres_changes == "true")
23
+ [ @paint.green(" ✓ Option Temps réel en cours de modification : #{CLIDependencies::ASYNC_NOTICE}"),
24
+ @paint.dim(" Suivre : captive addons realtime #{app}"), ]
25
+ end
26
+
27
+ private
28
+
29
+ def etat(app) = Presenter::SupabaseRealtime.new(paint: @paint).lines(@addons.supabase_realtime(app), app: app)
30
+ end
31
+ end
32
+ end
@@ -5,12 +5,17 @@ require "fileutils"
5
5
  module Captive
6
6
  module Commands
7
7
  class UserLogin
8
- Browser = Struct.new(:open_cmd) do
9
- def open(url) = system(open_cmd, url)
8
+ # Sous WSL, wslview ouvre le navigateur Windows ; sans aucune commande, l'URL affichée suffit.
9
+ Browser = Struct.new(:open_cmds) do
10
+ def self.for(platform = RUBY_PLATFORM)
11
+ new(platform.include?("darwin") ? %w[open] : %w[wslview xdg-open])
12
+ end
13
+
14
+ def open(url) = open_cmds.any? { |cmd| system(cmd, url) }
10
15
  end
11
16
 
12
17
  def initialize(github:, cluster:, store:, kubeconfig_path:,
13
- ui: method(:puts), browser: Browser.new("open"))
18
+ ui: method(:puts), browser: Browser.for)
14
19
  @github = github
15
20
  @cluster = cluster
16
21
  @store = store
@@ -7,6 +7,8 @@ module Captive
7
7
  class AddonsResource
8
8
  PATH = AppPath.new("addons")
9
9
  SUPABASE_AUTH_PATH = AppPath.new("addons/supabase/auth")
10
+ SUPABASE_REALTIME_PATH = AppPath.new("addons/supabase/realtime")
11
+ PG_CRON_PATH = AppPath.new("addons/supabase/pg-cron")
10
12
 
11
13
  def initialize(api:)
12
14
  @api = api
@@ -21,6 +23,15 @@ module Captive
21
23
  def set_supabase_auth(app, autoconfirm:, signup_open:)
22
24
  @api.put(SUPABASE_AUTH_PATH.call(app), { autoconfirm: autoconfirm, signup_open: signup_open })
23
25
  end
26
+
27
+ def supabase_realtime(app) = @api.get(SUPABASE_REALTIME_PATH.call(app))
28
+
29
+ def set_supabase_realtime(app, enabled:, postgres_changes:)
30
+ @api.put(SUPABASE_REALTIME_PATH.call(app), { enabled: enabled, postgres_changes: postgres_changes })
31
+ end
32
+
33
+ def pg_cron(app) = @api.get(PG_CRON_PATH.call(app))
34
+ def set_pg_cron(app, enabled:) = @api.put(PG_CRON_PATH.call(app), { enabled: enabled })
24
35
  end
25
36
  end
26
37
  end
@@ -4,7 +4,6 @@ module Captive
4
4
  class NoPodFound < StandardError; end
5
5
  class UnknownAppType < StandardError; end
6
6
  class PollTimeout < StandardError; end
7
- class RestoreError < StandardError; end
8
7
  class DumpError < StandardError; end
9
8
  class ExecError < StandardError; end
10
9
  class AuthError < StandardError; end
@@ -139,17 +139,6 @@ module Captive
139
139
  run("create", "secret", "generic", name, "-n", namespace, *literals, "--dry-run=client", "-o", "yaml")
140
140
  end
141
141
 
142
- def scale(namespace, deployment, replicas)
143
- run("scale", "deployment", deployment, "-n", namespace, "--replicas=#{replicas}")
144
- end
145
-
146
- def restore(namespace, pod, dump_file, format)
147
- cmd = format == :custom ?
148
- [ "pg_restore", "--clean", "--if-exists", "--no-owner", "--no-acl", "-d", "app" ] :
149
- [ "psql", "app" ]
150
- exec_with_file(namespace, pod, dump_file, *cmd)
151
- end
152
-
153
142
  def admin_credentials(namespace, app)
154
143
  [ ADMIN_ROLE, get_secret_password(namespace, ADMIN_SECRET) ]
155
144
  rescue RuntimeError => e
@@ -224,10 +213,6 @@ module Captive
224
213
  end
225
214
  end
226
215
 
227
- def transfer_file_to_pod(namespace, pod, stream_cmd, remote_path)
228
- system_pipe("#{stream_cmd} | #{kubectl_cmd} exec -i #{pod} -n #{namespace} -- bash -c 'cat > #{remote_path}'")
229
- end
230
-
231
216
  def dump_from_pod(namespace, pod, local_path, cmd)
232
217
  system_pipe("#{kubectl_cmd} exec #{pod} -n #{namespace} -- bash -c '#{cmd}' > #{Shellwords.escape(local_path)}")
233
218
  end
@@ -244,15 +229,6 @@ module Captive
244
229
  system("bash", "-c", cmd)
245
230
  end
246
231
 
247
- def exec_on_pod(namespace, pod, cmd)
248
- run_interactive("exec", pod, "-n", namespace, "--", "bash", "-c", cmd)
249
- end
250
-
251
- def exec_on_pod_output(namespace, pod, cmd)
252
- out, _err, status = Open3.capture3("kubectl", *kubeconfig_args, "exec", pod, "-n", namespace, "--", "bash", "-c", cmd)
253
- status.success? ? out : nil
254
- end
255
-
256
232
  def run(*args)
257
233
  out, err, status = Open3.capture3("kubectl", *kubeconfig_args, *args)
258
234
  raise AuthError, "Votre session a expiré. Reconnectez-vous avec : captive login" if err.include?("Unauthorized")
@@ -25,6 +25,8 @@ require_relative "presenter/scheduled_task"
25
25
  require_relative "presenter/domain"
26
26
  require_relative "presenter/addon"
27
27
  require_relative "presenter/supabase_auth"
28
+ require_relative "presenter/supabase_realtime"
29
+ require_relative "presenter/pg_cron"
28
30
  require_relative "presenter/edge_function"
29
31
  require_relative "activity_trail"
30
32
  require_relative "errors"
@@ -39,4 +41,3 @@ require_relative "commands/apps_restart"
39
41
  require_relative "commands/domain_wait"
40
42
  require_relative "commands/domain_announcer"
41
43
  require_relative "commands/db_dump"
42
- require_relative "commands/db_restore"
@@ -14,7 +14,8 @@ module Captive
14
14
  def function(fonction)
15
15
  erreurs = fonction["errors_24h"]
16
16
  erreurs = erreurs.positive? ? @paint.red("#{erreurs} erreurs") : "0 erreur"
17
- "#{@paint.bold(fonction["name"])} #{fonction["invocations_24h"]} appels #{erreurs} (24 h)"
17
+ ligne = "#{@paint.bold(fonction["name"])} #{fonction["invocations_24h"]} appels #{erreurs} (24 h)"
18
+ fonction["public"] ? "#{ligne} #{@paint.yellow("public")}" : ligne
18
19
  end
19
20
 
20
21
  def invocation(appel)
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Captive
4
+ module Presenter
5
+ # L'option pg_cron et pg_net de la base, comme sur la page pg_cron du dashboard (ADR 0041).
6
+ class PgCron
7
+ VALEURS = { true => "oui", false => "non" }.freeze
8
+
9
+ def initialize(paint:)
10
+ @paint = paint
11
+ end
12
+
13
+ def lines(settings, app:)
14
+ [
15
+ [ "pg_cron et pg_net #{VALEURS.fetch(settings["enabled"], "inconnu")}", indisponible(settings) ].compact.join(" "),
16
+ (@paint.yellow("Changement en cours…") if settings["pending"]),
17
+ @paint.dim(modification(settings, app)),
18
+ ].compact
19
+ end
20
+
21
+ private
22
+
23
+ def modification(settings, app)
24
+ return "Modifiable par un admin de l'Organization" unless settings["can_edit"]
25
+
26
+ "Modifier : captive addons pg-cron #{app} --enabled=true|false (redémarre la base)"
27
+ end
28
+
29
+ def indisponible(settings)
30
+ @paint.dim("(PostgreSQL 18 requis)") if settings["available"] == false
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Captive
4
+ module Presenter
5
+ # L'option Temps réel de l'Add-on Supabase, comme sur la page Realtime du dashboard.
6
+ # Postgres Changes n'est disponible qu'à partir de PostgreSQL 18.6 (ADR 0043).
7
+ class SupabaseRealtime
8
+ VALEURS = { true => "oui", false => "non" }.freeze
9
+
10
+ def initialize(paint:)
11
+ @paint = paint
12
+ end
13
+
14
+ def lines(settings, app:)
15
+ [
16
+ "Temps réel #{valeur(settings["enabled"])}",
17
+ [ "Postgres Changes #{valeur(settings["postgres_changes"] || false)}", indisponible(settings) ].compact.join(" "),
18
+ (@paint.yellow("Changement en cours…") if settings["pending"]),
19
+ @paint.dim(modification(settings, app)),
20
+ ].compact
21
+ end
22
+
23
+ private
24
+
25
+ def modification(settings, app)
26
+ return "Modifiable par un admin de l'Organization" unless settings["can_edit"]
27
+
28
+ "Modifier : captive addons realtime #{app} --enabled=true|false [--postgres-changes=true|false]"
29
+ end
30
+
31
+ def valeur(value) = VALEURS.fetch(value, "inconnu")
32
+
33
+ def indisponible(settings)
34
+ @paint.dim("(PostgreSQL 18.6 requis)") if settings["postgres_changes_available"] == false
35
+ end
36
+ end
37
+ end
38
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Captive
4
- VERSION = "1.9.1"
4
+ VERSION = "1.11.0"
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: captive-cli
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.9.1
4
+ version: 1.11.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Captive Studio
@@ -118,8 +118,8 @@ files:
118
118
  - lib/captive/commands/db_commands.rb
119
119
  - lib/captive/commands/db_dump.rb
120
120
  - lib/captive/commands/db_exec.rb
121
+ - lib/captive/commands/db_migrations_mark.rb
121
122
  - lib/captive/commands/db_psql.rb
122
- - lib/captive/commands/db_restore.rb
123
123
  - lib/captive/commands/db_target.rb
124
124
  - lib/captive/commands/domain_announcer.rb
125
125
  - lib/captive/commands/domain_wait.rb
@@ -129,9 +129,11 @@ files:
129
129
  - lib/captive/commands/functions_commands.rb
130
130
  - lib/captive/commands/logs.rb
131
131
  - lib/captive/commands/one_off_session.rb
132
+ - lib/captive/commands/pg_cron_change.rb
132
133
  - lib/captive/commands/run.rb
133
134
  - lib/captive/commands/supabase_auth_change.rb
134
135
  - lib/captive/commands/supabase_commands.rb
136
+ - lib/captive/commands/supabase_realtime_change.rb
135
137
  - lib/captive/commands/user_login.rb
136
138
  - lib/captive/credentials.rb
137
139
  - lib/captive/credentials_store.rb
@@ -146,7 +148,6 @@ files:
146
148
  - lib/captive/dashboard_client.rb
147
149
  - lib/captive/dashboard_response.rb
148
150
  - lib/captive/errors.rb
149
- - lib/captive/flux.rb
150
151
  - lib/captive/github_device_flow.rb
151
152
  - lib/captive/http_client.rb
152
153
  - lib/captive/kubectl.rb
@@ -162,8 +163,10 @@ files:
162
163
  - lib/captive/presenter/domain.rb
163
164
  - lib/captive/presenter/edge_function.rb
164
165
  - lib/captive/presenter/log_colorizer.rb
166
+ - lib/captive/presenter/pg_cron.rb
165
167
  - lib/captive/presenter/scheduled_task.rb
166
168
  - lib/captive/presenter/supabase_auth.rb
169
+ - lib/captive/presenter/supabase_realtime.rb
167
170
  - lib/captive/session_id.rb
168
171
  - lib/captive/session_token.rb
169
172
  - lib/captive/shell_completions.rb
@@ -1,145 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require "pathname"
4
- require "open3"
5
- require "shellwords"
6
- require_relative "../errors"
7
- require_relative "../poller"
8
- require_relative "../flux"
9
-
10
- module Captive
11
- module Commands
12
- class DbRestore
13
- TEMP_REMOTE = "/controller/tmp/dump.tmp"
14
- EXIT_FILE = "/controller/tmp/restore.exit"
15
- LOG_FILE = "/controller/tmp/restore.log"
16
- FLUX_KUSTOMIZATION = "services"
17
-
18
- def initialize(kubectl:, trail:, poller: nil, flux: nil)
19
- @kubectl = kubectl
20
- @trail = trail
21
- @poller = poller || Poller.new(interval: 10, timeout: 1800)
22
- @flux = flux || Flux.new
23
- end
24
-
25
- def detect_format(filename)
26
- basename = File.basename(filename)
27
- return :custom if basename.match?(/\.(pgsql|dump|custom|tar\.gz|tgz)$/)
28
-
29
- :sql
30
- end
31
-
32
- def postgres_pod(app)
33
- @kubectl.postgres_pod_name(app, app)
34
- end
35
-
36
- def run(app, dump_file)
37
- dump_file = resolve_path(dump_file)
38
- raise Errno::ENOENT, dump_file unless File.exist?(dump_file)
39
-
40
- # Après le contrôle du fichier : un dump introuvable n'a touché à rien, l'inscrire au
41
- # fil de l'app serait du bruit.
42
- @trail.db_restored(app)
43
-
44
- pg_pod = postgres_pod(app)
45
- password = @kubectl.postgres_secret_password(app, app)
46
- format = detect_format(dump_file)
47
- stream = build_stream_cmd(dump_file)
48
-
49
- yield :scaling_down if block_given?
50
- @flux.suspend_kustomization(FLUX_KUSTOMIZATION)
51
- @kubectl.scale(app, app, 0)
52
-
53
- begin
54
- yield :transferring if block_given?
55
- @kubectl.transfer_file_to_pod(app, pg_pod, stream, TEMP_REMOTE)
56
- yield :restoring if block_given?
57
- on_tick = lambda { |elapsed|
58
- activity = @kubectl.exec_on_pod_output(app, pg_pod, current_activity_cmd)
59
- yield(:waiting, elapsed, activity&.strip) if block_given?
60
- }
61
- restore_on_pod(app, pg_pod, password, format, &on_tick)
62
- cleanup_pod(app, pg_pod)
63
- ensure
64
- yield :scaling_up if block_given?
65
- @kubectl.scale(app, app, 1)
66
- @flux.resume_kustomization(FLUX_KUSTOMIZATION)
67
- end
68
- end
69
-
70
- private
71
-
72
- def inner_is_custom?(file)
73
- inner = `tar -tzf #{Shellwords.escape(file)} 2>/dev/null | grep -Ev '/$' | head -1`.strip
74
- inner.match?(/\.(pgsql|dump|custom)$/)
75
- end
76
-
77
- def build_stream_cmd(file)
78
- basename = File.basename(file)
79
- escaped = Shellwords.escape(file)
80
-
81
- if basename.match?(/\.tar\.gz$|\.tgz$/)
82
- inner = `tar -tzf #{escaped} 2>/dev/null | grep -Ev '/$' | head -1`.strip
83
- "tar -xOf #{escaped} #{Shellwords.escape(inner)}"
84
- elsif basename.match?(/\.(gz)$/)
85
- "gunzip -c #{escaped}"
86
- else
87
- "cat #{escaped}"
88
- end
89
- end
90
-
91
- def restore_on_pod(app, pg_pod, password, format, &on_tick)
92
- pgpass = Shellwords.escape(password)
93
- @kubectl.exec_on_pod(app, pg_pod,
94
- "PGPASSWORD=#{pgpass} psql -h localhost -U app -d app " \
95
- "-c 'DROP SCHEMA public CASCADE; CREATE SCHEMA public; GRANT ALL ON SCHEMA public TO app;' 2>&1")
96
-
97
- cmd = restore_cmd(password, format)
98
- inner_script = "#{cmd}; echo $? > #{EXIT_FILE}"
99
- @kubectl.exec_on_pod(app, pg_pod,
100
- "rm -f #{EXIT_FILE}; nohup bash -c #{Shellwords.escape(inner_script)} > #{LOG_FILE} 2>&1 < /dev/null &")
101
-
102
- exit_code = wait_for_exit_code(app, pg_pod, &on_tick)
103
- raise RestoreError, "La restauration a échoué (code #{exit_code})" unless exit_code == "0"
104
- end
105
-
106
- def wait_for_exit_code(app, pg_pod, &on_tick)
107
- exit_code = nil
108
- @poller.poll_until(context: "fin du restore (#{EXIT_FILE})", on_tick: on_tick) do
109
- exit_code = @kubectl.exec_on_pod_output(app, pg_pod, "cat #{EXIT_FILE} 2>/dev/null")
110
- exit_code && !exit_code.strip.empty?
111
- end
112
- exit_code.strip
113
- end
114
-
115
- def restore_cmd(password, format)
116
- pgpass = Shellwords.escape(password)
117
- if format == :custom
118
- "(PGPASSWORD=#{pgpass} pg_restore --no-owner --no-acl --verbose " \
119
- "-h localhost -U app -d app #{TEMP_REMOTE} 2>&1 | grep -v 'no privileges'; exit ${PIPESTATUS[0]})"
120
- else
121
- "PGPASSWORD=#{pgpass} psql -h localhost -U app -d app < #{TEMP_REMOTE} 2>&1"
122
- end
123
- end
124
-
125
- def current_activity_cmd
126
- "psql -U postgres -d app -tAc " \
127
- "\"SELECT query FROM pg_stat_activity WHERE datname='app' AND pid != pg_backend_pid() " \
128
- "AND state='active' AND query !~ 'autovacuum' ORDER BY query_start DESC LIMIT 1;\" 2>/dev/null"
129
- end
130
-
131
- def cleanup_pod(app, pg_pod)
132
- @kubectl.run("exec", pg_pod, "-n", app, "--", "rm", "-f", TEMP_REMOTE)
133
- rescue StandardError
134
- nil # ignore cleanup errors
135
- end
136
-
137
- def resolve_path(path)
138
- return path if Pathname.new(path).absolute?
139
-
140
- base = ENV.fetch("CAPTIVE_ORIG_DIR", Dir.pwd)
141
- File.join(base, path)
142
- end
143
- end
144
- end
145
- end
data/lib/captive/flux.rb DELETED
@@ -1,24 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require "open3"
4
- require_relative "errors"
5
-
6
- module Captive
7
- class Flux
8
- def suspend_kustomization(name)
9
- capture("suspend", "kustomization", name)
10
- end
11
-
12
- def resume_kustomization(name)
13
- capture("resume", "kustomization", name)
14
- end
15
-
16
- private
17
-
18
- def capture(*args)
19
- Open3.capture3("flux", *args)
20
- rescue Errno::ENOENT
21
- raise MissingDependencyError, "flux introuvable. Installe-le : brew install flux"
22
- end
23
- end
24
- end