rustploy-gui 0.1.3

Rustploy — desktop client (glacier-ui) for the Rustploy PaaS daemon
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
--!strict
--!nolint FunctionUnused
-- handlers/settings.luau — Settings (Web Server) e Settings → Git (provedores
-- Gitea: conectar via OAuth/PAT, atualizar lista, remover).

local State = require("../state")
local Helpers = require("../helpers")
local fmt = require("../fmt")
local Stream = require("stream")

local M = {}

-- ── Settings (Web Server) ────────────────────────────────────────────────

function settings_tab(t: string): ()
    ctx.settings_tab = t
end

function settings_save(): ()
    local api = State.api
    if not api then
        return
    end
    local email = Helpers.trim(ctx.ss_email)
    local registry_domain = Helpers.trim(ctx.ss_registry_domain)
    ctx.settings_msg = "salvando…"
    local ok, res = api:rpc_checked{ SetDaemonSettings = {
        acme_email = (email ~= "" and email or nil),
        registry_domain = (registry_domain ~= "" and registry_domain or nil),
    } }
    ctx.settings_msg = ok and "configurações salvas" or ("erro: " .. res)
    if ok then
        toast{ message = tostring("Configurações salvas"), kind = "success" }
    else
        toast{ message = tostring(res), kind = "error" }
    end
end

-- ── Settings → Git (provedores Gitea / GitHub) ───────────────────────────

function gp_mode(m: string): ()
    ctx.gp_mode = m
end

-- Alterna o tipo de provedor (gitea | github) e recomputa a redirect URI, que
-- tem path por provedor (/oauth/gitea/callback vs /oauth/github/callback).
function gp_kind(k: string): ()
    local kind = (k == "github") and "github" or "gitea"
    ctx.gp_kind = kind
    ctx.gp_redirect = Helpers.oauth_redirect_uri(ctx.ss_public_base, kind)
    -- GitHub conecta ao github.com por padrão; Base URL só p/ Enterprise.
    if kind == "github" and Helpers.trim(ctx.gp_base_url) == "" then
        ctx.gp_name = (Helpers.trim(ctx.gp_name) == "" and "GitHub" or ctx.gp_name)
    end
end

local function gp_refresh_list(): ()
    local api = State.api
    if not api then
        return
    end
    local ok, res = api:rpc("GitProviderList")
    if ok and res.GitProviders then
        ctx.gitea_providers = fmt.git_providers(res.GitProviders)
        ctx.gitea_count = tostring(#res.GitProviders)
    end
end

function gp_refresh(): ()
    if not State.api then
        return
    end
    gp_refresh_list()
end

function gp_connect(): ()
    local api = State.api
    if not api then
        return
    end
    ctx.gp_oauth_url = ""
    local is_github = (ctx.gp_kind or "gitea") == "github"
    local kind_wire = is_github and "Github" or "Gitea"
    local label = is_github and "GitHub" or "Gitea"
    local base = Helpers.trim(ctx.gp_base_url)
    -- GitHub conecta ao github.com por padrão; a Base URL só é preenchida para
    -- GitHub Enterprise Server. Gitea sempre exige a Base URL.
    if base == "" then
        if is_github then
            base = "https://github.com"
        else
            ctx.gp_msg = "informe a Base URL do Gitea";
            return
        end
    end
    local name = Helpers.trim(ctx.gp_name); if name == "" then
        name = label
    end
    local is_oauth = (ctx.gp_mode or "oauth") ~= "pat"
    local cmd: any
    if is_oauth then
        local cid = Helpers.trim(ctx.gp_client_id)
        local csec = ctx.gp_client_secret or ""
        if cid == "" or Helpers.trim(csec) == "" then
            ctx.gp_msg = "Client ID e Client Secret são obrigatórios";
            return
        end
        cmd = { GitProviderCreate = { kind = kind_wire, name = name, base_url = base,
            auth_mode = "OAuth", oauth_client_id = cid, oauth_client_secret = csec, pat = nil } }
    else
        local pat = ctx.gp_pat or ""
        if Helpers.trim(pat) == "" then
            ctx.gp_msg = "informe o Personal Access Token";
            return
        end
        cmd = {
            GitProviderCreate = {
                kind = kind_wire,
                name = name,
                base_url = base,
                auth_mode = "Pat",
                oauth_client_id = nil,
                oauth_client_secret = nil,
                pat = pat
            }
        }
    end
    ctx.gp_msg = "conectando…"
    local ok, res = api:rpc(cmd)
    if not ok or not res.GitProviderInfo then
        ctx.gp_msg = "erro: " .. (ok and "resposta inesperada" or res);
        return
    end
    local pid = res.GitProviderInfo.id
    if is_oauth then
        -- OAuth precisa de round-trip no navegador. O Luau não abre o browser;
        -- surface a URL para o usuário abrir (built-in open:<chave> no template)
        -- e depois clicar em "Atualizar lista".
        local oko, reso = api:rpc{ GitOAuthStart = { provider_id = pid } }
        if oko and reso.OAuthUrl then
            ctx.gp_oauth_url = reso.OAuthUrl
            ctx.gp_msg = "abra para autorizar: " .. reso.OAuthUrl
        else
            ctx.gp_msg = "provider criado; inicie o OAuth manualmente"
        end
    else
        ctx.gp_msg = "conta " .. label .. " conectada ✓"
    end
    ctx.gp_name = ""
    ctx.gp_base_url = ""
    ctx.gp_client_id = ""
    ctx.gp_client_secret = ""
    ctx.gp_pat = ""
    gp_refresh_list()
end

function gp_delete(id: string): ()
    local api = State.api
    if not api then
        return
    end
    local ok, res = api:rpc_checked{ GitProviderDelete = { id = id } }
    ctx.gp_msg = ok and "provider removido" or ("erro: " .. res)
    if not ok then
        toast{ message = tostring(res), kind = "error" }
    end
    gp_refresh_list()
end

-- ── Settings → Infra as Code (export/import declarativo) ─────────────────
--
-- O manifesto é um `.zip` (um ARQUIVO) com exatamente dois membros na raiz:
--   • rustploy.yml       — projetos/serviços (env vars sempre como ${VAR})
--   • rustploy.vars.toml  — os valores reais das vars (aninhado por escopo)
-- Ler/gravar o zip é `manifest_zip_read`/`manifest_zip_write` — extensão Rust
-- da camada Luau (src/manifest_zip.rs), porque o motor tem `zip_dir` mas não
-- o inverso. Exportar e importar usam os diálogos nativos do SO; o import
-- REJEITA um zip que não tenha exatamente um .yml e um .toml, sem mais nada.

-- O corpo do export DEPOIS do diálogo — separado só para o `iac_busy` ser
-- ligado/desligado em volta sem repetir o reset em cada early-return.
local function do_export(api: any, zip_path: string): ()
    ctx.iac_export_msg = "exportando…"
    local ok, res = api:rpc_checked("ManifestExportAll")
    if not ok or type(res) ~= "table" or not res.ManifestBundle then
        ctx.iac_export_msg = "erro: " .. tostring(res)
        toast{ message = tostring(tostring(res)), kind = "error" }
        return
    end

    local okz, zerr = manifest_zip_write(
        zip_path,
        res.ManifestBundle.yaml or "",
        res.ManifestBundle.dotenv or ""
    )
    if not okz then
        ctx.iac_export_msg = "erro ao gravar o zip: " .. tostring(zerr)
        toast{ message = "Falha ao gravar o zip: " .. tostring(zerr), kind = "error" }
        return
    end
    ctx.iac_export_msg = "salvo em " .. zip_path
    toast{ message = "Infra as Code exportado", kind = "success" }
end

function iac_export(): ()
    local api = State.api
    if not api then
        return
    end

    -- `save_file` (SUSPENDE): o usuário escolhe o caminho do .zip.
    local zip_path = save_file{
        title = "Exportar Infra as Code",
        default_name = "rustploy-infra.zip",
        filters = { { name = "Zip", extensions = { "zip" } } },
    }
    if not zip_path then
        return
    end
    if not string.match(zip_path, "%.zip$") then
        zip_path = zip_path .. ".zip"
    end

    ctx.iac_busy = "true"
    do_export(api, zip_path)
    ctx.iac_busy = ""
end

local function do_import(api: any, yaml: string, toml: string, prune: boolean, deploy: boolean): ()
    ctx.iac_has_missing = "false"
    ctx.iac_has_report = "false"
    ctx.iac_missing_vars = ""
    ctx.iac_report_lines = {}

    ctx.iac_import_msg = "importando…"
    local ok, res = api:rpc{
        ManifestImport = {
            yaml = yaml,
            dotenv = toml,
            prune = prune,
            deploy = deploy,
        },
    }
    if not ok then
        ctx.iac_import_msg = "erro: " .. tostring(res)
        toast{ message = tostring(tostring(res)), kind = "error" }
        return
    end

    if type(res) == "table" and res.MissingEnvVars ~= nil then
        ctx.iac_has_missing = "true"
        ctx.iac_missing_vars = table.concat(res.MissingEnvVars, ", ")
        ctx.iac_import_msg = "faltam variáveis — nada foi aplicado"
        toast{ message = tostring("Faltam variáveis no TOML: " .. ctx.iac_missing_vars), kind = "error" }
        return
    end

    if type(res) == "table" and res.Err ~= nil then
        ctx.iac_import_msg = "erro: " .. tostring(res.Err.code) .. ": " .. tostring(res.Err.message)
        toast{ message = tostring(tostring(res.Err.message)), kind = "error" }
        return
    end

    if type(res) ~= "table" or not res.ManifestReport then
        ctx.iac_import_msg = "resposta inesperada do daemon"
        return
    end

    local lines = {}
    for _, a in ipairs(res.ManifestReport.actions or {}) do
        table.insert(lines, "[" .. tostring(a.action) .. "] " .. tostring(a.kind) .. " " .. tostring(a.name))
    end
    local pruned = res.ManifestReport.pruned or res.ManifestReport.removed or {}
    if #pruned > 0 then
        table.insert(lines, "removidos (prune): " .. table.concat(pruned, ", "))
    elseif prune then
        table.insert(lines, "prune ligado — nenhum serviço ausente para remover")
    end
    if #(res.ManifestReport.deployed or {}) > 0 then
        table.insert(lines, "deploy disparado: " .. table.concat(res.ManifestReport.deployed, ", "))
    elseif deploy then
        table.insert(lines, "deploy ligado — nada mudou para disparar")
    end
    ctx.iac_report_lines = lines
    ctx.iac_has_report = "true"
    ctx.iac_import_msg = "import concluído ✓"
    toast{ message = tostring("Infra as Code importado"), kind = "success" }
    Stream.refresh_now()
end

function iac_import(): ()
    local api = State.api
    if not api then
        return
    end

    -- `open_file` (SUSPENDE): o `.zip` do manifesto. `manifest_zip_read` extrai
    -- e VALIDA — exatamente um .yml e um .toml na raiz, nada mais.
    local zip_path = open_file{
        title = "Importar Infra as Code (.zip)",
        filters = { { name = "Zip", extensions = { "zip" } } },
    }
    if not zip_path then
        return
    end

    local m = manifest_zip_read(zip_path)
    if not m.ok then
        ctx.iac_import_msg = "zip inválido: " .. tostring(m.error)
        toast{ message = tostring(m.error), kind = "error" }
        return
    end

    -- Lê os dois checkboxes AQUI e confirma o que vai acontecer — prune remove
    -- serviços, então o usuário vê exatamente o que marcou antes de aplicar.
    local prune = ctx.iac_prune == "true"
    local deploy = ctx.iac_deploy == "true"
    local ok_go = confirm{
        title = "Aplicar este manifesto?",
        message = "Do zip: "
            .. tostring(m.yaml and #m.yaml or 0) .. " B de YAML + "
            .. tostring(m.toml and #m.toml or 0) .. " B de TOML.\n\n"
            .. "• Remover serviços ausentes (prune): "
            .. (prune and "SIM" or "não") .. "\n"
            .. "• Disparar deploy dos alterados: "
            .. (deploy and "SIM" or "não"),
        confirm_label = "Aplicar",
        destructive = prune,
    }
    if not ok_go then
        ctx.iac_import_msg = "cancelado"
        return
    end

    ctx.iac_busy = "true"
    do_import(api, m.yaml or "", m.toml or "", prune, deploy)
    ctx.iac_busy = ""
end

-- ── Settings → Manutenção (limpeza automática de Docker) ─────────────────
-- Ver docs/plano-limpeza-automatica-docker.md. Config é um singleton do
-- daemon (não uma lista) — sem tabela própria, carregada/salva inteira a
-- cada Get/Set. `dc_last_run_at_raw`/`dc_next_run_at_raw` são campos "mudos"
-- (não exibidos, só round-trip): preservam o `last_run_at` real entre saves
-- pra um agendamento `IntervalHours` não reiniciar a contagem toda vez que o
-- usuário aperta "Save" sem ter mudado nada de agendamento.

-- Recorrência (Option<Recurrence>, externally-tagged) → (kind, hours, hour,
-- minute, weekday) — mesmo formato de new_job_window.luau::unpack_recurrence,
-- mas aqui a recorrência nunca é `nil` (a config sempre tem uma, mesmo com o
-- interruptor geral desligado).
local function dc_unpack_recurrence(r: any): (string, string, string, string, string)
    if r ~= nil and r.IntervalHours ~= nil then
        return "interval", tostring(r.IntervalHours), "3", "0", "0"
    end
    if r ~= nil and r.Weekly ~= nil then
        return "weekly", "6", tostring(r.Weekly.hour), tostring(r.Weekly.minute), tostring(r.Weekly.weekday)
    end
    if r ~= nil and r.Daily ~= nil then
        return "daily", "6", tostring(r.Daily.hour), tostring(r.Daily.minute), "0"
    end
    return "daily", "6", "3", "0", "0"
end

local function dc_apply_config(cfg: any): ()
    ctx.dc_enabled = tostring(cfg.enabled)
    ctx.dc_containers = tostring(cfg.containers)
    ctx.dc_images = tostring(cfg.images)
    ctx.dc_images_all = tostring(cfg.images_all)
    ctx.dc_volumes = tostring(cfg.volumes)
    ctx.dc_volumes_all = tostring(cfg.volumes_all)
    ctx.dc_networks = tostring(cfg.networks)
    ctx.dc_build_cache = tostring(cfg.build_cache)
    local kind, hours, hour, minute, weekday = dc_unpack_recurrence(cfg.recurrence)
    ctx.dc_kind = kind
    ctx.dc_hours = hours
    -- Uma chave só, "HH:MM", porque quem edita agora é o <timeedit> em home.gvb.
    -- `dc_unpack_recurrence` continua devolvendo hora e minuto separados (é o
    -- formato do daemon); a junção acontece aqui, na fronteira.
    ctx.dc_time = fmt.hm_join(hour, minute)
    ctx.dc_weekday = weekday
    ctx.dc_next_run_label = cfg.next_run_at and fmt.date_dm_hm(cfg.next_run_at) or "—"
    State.dc_last_run_at_raw = cfg.last_run_at
end

-- Carregado uma vez na conexão (handlers/connection.luau::load_settings) —
-- não faz parte do snapshot de 2s, é config, não estado que muda sozinho
-- (exceto por `last_run`, atualizado ao vivo por `Event::DockerCleanupCompleted`
-- em stream.luau, sem precisar buscar de novo).
function M.dc_load(): ()
    local api = State.api
    if not api then
        return
    end
    local ok, res = api:rpc("DockerCleanupConfigGet")
    if ok and res.DockerCleanupConfig then
        dc_apply_config(res.DockerCleanupConfig.config)
        ctx.dc_last_run_text = fmt.docker_cleanup_last_run_summary(res.DockerCleanupConfig.last_run)
    end
end

function dc_kind(k: string): ()
    ctx.dc_kind = k
end

-- Órfão desde que o seletor de dia da semana virou um <radiogroup> em home.gvb:
-- o builtin grava `dc_weekday` sozinho, no update dele em Rust, e ninguém mais
-- dispara esta ação. Fica comentado porque volta a ser necessário se algum dia
-- o grupo voltar a ser markup à mão (ex.: para recuperar a fileira de pílulas).
-- function dc_weekday(w: string): ()
--     ctx.dc_weekday = w
-- end

local function dc_build_recurrence(): any
    if ctx.dc_kind == "interval" then
        return { IntervalHours = math.max(1, tonumber(ctx.dc_hours) or 1) }
    end
    -- O caminho de volta do <timeedit>: a chave única vira os dois campos que
    -- Recurrence::Daily/Weekly declaram no daemon.
    local hora, minuto = fmt.hm_split(ctx.dc_time)
    if ctx.dc_kind == "weekly" then
        return {
            Weekly = {
                weekday = tonumber(ctx.dc_weekday) or 0,
                hour = hora,
                minute = minuto,
            },
        }
    end
    return {
        Daily = {
            hour = hora,
            minute = minuto,
        },
    }
end

function dc_save(): ()
    local api = State.api
    if not api then
        return
    end
    ctx.dc_msg = "salvando…"
    local ok, res = api:rpc_checked{
        DockerCleanupConfigSet = {
            config = {
                enabled = ctx.dc_enabled == "true",
                recurrence = dc_build_recurrence(),
                containers = ctx.dc_containers == "true",
                images = ctx.dc_images == "true",
                images_all = ctx.dc_images_all == "true",
                volumes = ctx.dc_volumes == "true",
                volumes_all = ctx.dc_volumes_all == "true",
                networks = ctx.dc_networks == "true",
                build_cache = ctx.dc_build_cache == "true",
                last_run_at = State.dc_last_run_at_raw,
            },
        },
    }
    if ok and res.DockerCleanupConfig then
        dc_apply_config(res.DockerCleanupConfig.config)
        ctx.dc_last_run_text = fmt.docker_cleanup_last_run_summary(res.DockerCleanupConfig.last_run)
        ctx.dc_msg = "configurações salvas"
        toast{ message = tostring("Limpeza automática salva"), kind = "success" }
    else
        ctx.dc_msg = "erro: " .. tostring(res)
        toast{ message = tostring(res), kind = "error" }
    end
end

-- Botão "Executar agora": roda os recursos marcados fora do horário
-- agendado, independente do interruptor geral (é um botão de teste). Roda em
-- background no daemon — `ctx.dc_running` volta a "false" quando
-- `Event::DockerCleanupCompleted` chega (stream.luau::apply_bus), não pela
-- resposta deste RPC.
function dc_run_now(): ()
    local api = State.api
    if not api then
        return
    end
    local any_selected = ctx.dc_containers == "true" or ctx.dc_images == "true"
        or ctx.dc_volumes == "true" or ctx.dc_networks == "true" or ctx.dc_build_cache == "true"
    if not any_selected then
        ctx.dc_msg = "marque pelo menos um recurso"
        return
    end
    local ok_confirm = confirm{
        title = "Executar limpeza agora?",
        message = "Roda a limpeza dos recursos marcados imediatamente, fora do horário agendado. Ação irreversível.",
        confirm_label = "Executar",
        destructive = true,
    }
    if not ok_confirm then
        return
    end
    ctx.dc_running = "true"
    ctx.dc_msg = "executando…"
    local ok, res = api:rpc_checked("DockerCleanupRunNow")
    if not ok then
        ctx.dc_running = "false"
        ctx.dc_msg = "erro: " .. tostring(res)
        toast{ message = tostring(res), kind = "error" }
    end
end

return M