One `EventSource` for the whole dashboard, held in a single slot: a view that re-renders itself would otherwise register a second listener each time and double the work on every event. A refresh landing under someone's fingers is worse than data a few seconds old, so it waits while a dialog is open or a field has focus, a burst of writes collapses into one reload, and a background tab closes its stream. The Discord page stays off the tick because listing members calls the Discord API. When the stream cannot be established a timer takes over. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
373 lines
13 KiB
JavaScript
373 lines
13 KiB
JavaScript
import { api } from '../core/api.js';
|
||
import { autoRefresh } from '../core/live.js';
|
||
import { formatRelative, h, mount } from '../core/dom.js';
|
||
import {
|
||
badge,
|
||
button,
|
||
card,
|
||
confirmAction,
|
||
field,
|
||
input,
|
||
modal,
|
||
notice,
|
||
renderAsync,
|
||
select,
|
||
table,
|
||
toast,
|
||
toggle,
|
||
} from '../core/ui.js';
|
||
|
||
/** Deploy targets and deployment history — the operations side of the SaaS (M16-T06). */
|
||
|
||
const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 };
|
||
|
||
const STATUS_TONE = {
|
||
success: 'success',
|
||
failed: 'danger',
|
||
running: 'warning',
|
||
pending: 'neutral',
|
||
cancelled: 'neutral',
|
||
};
|
||
|
||
const KINDS = [
|
||
{ value: 'webhook', label: 'Webhook signé (recommandé)' },
|
||
{ value: 'gitea-action', label: 'Workflow Gitea Actions' },
|
||
{ value: 'command', label: 'Commande shell sur l’hôte du bot' },
|
||
];
|
||
|
||
const KIND_HELP = {
|
||
webhook:
|
||
'Le bot envoie une requête POST signée en HMAC-SHA256 à ton serveur. C’est la méthode la plus sûre : rien ne s’exécute sur la machine du bot.',
|
||
'gitea-action':
|
||
'Le bot déclenche un workflow Gitea Actions. Le workflow doit accepter `workflow_dispatch`.',
|
||
command:
|
||
'Le bot exécute une commande shell sur sa propre machine. À réserver à des personnes de confiance : c’est une exécution de code arbitraire.',
|
||
};
|
||
|
||
async function editTarget(existing, repositories, commandsAllowed, level, reload) {
|
||
const name = input({ value: existing?.name ?? '', placeholder: 'production-web' });
|
||
|
||
// A webhook or a shell command needs no Gitea at all, so an unreachable forge
|
||
// must not stand between the user and a deploy target: the repository then
|
||
// falls back to a free-text field.
|
||
const repository =
|
||
repositories.length > 0
|
||
? select(
|
||
repositories.map((item) => ({ value: item.fullName, label: item.fullName })),
|
||
{ value: existing?.repository ?? repositories[0]?.fullName },
|
||
)
|
||
: input({ value: existing?.repository ?? '', placeholder: 'FWS/FWS-Arch' });
|
||
const environment = input({ value: existing?.environment ?? 'production' });
|
||
const kindOptions = KINDS.filter(
|
||
(kind) => kind.value !== 'command' || (commandsAllowed && level >= LEVELS.OWNER),
|
||
);
|
||
const kind = select(kindOptions, { value: existing?.kind ?? 'webhook' });
|
||
|
||
const url = input({ value: existing?.config?.url ?? '', placeholder: 'https://deploy.exemple.org/hook' });
|
||
const secret = input({
|
||
type: 'password',
|
||
placeholder: existing?.config?.hasSecret ? 'Inchangé' : 'Secret HMAC',
|
||
});
|
||
const command = input({
|
||
value: existing?.config?.command ?? '',
|
||
placeholder: 'systemctl restart fws-arch',
|
||
});
|
||
const cwd = input({
|
||
value: existing?.config?.cwd ?? '',
|
||
placeholder: 'Répertoire de travail (facultatif)',
|
||
});
|
||
const workflow = input({ value: existing?.config?.workflow ?? '', placeholder: 'deploy.yml' });
|
||
const ref = input({ value: existing?.config?.ref ?? '', placeholder: 'main' });
|
||
|
||
let autoDeploy = existing?.autoDeploy ?? false;
|
||
let enabled = existing?.enabled ?? true;
|
||
|
||
const specific = h('div', { class: 'stack' });
|
||
const help = h('p', { class: 'muted' });
|
||
|
||
const drawSpecific = () => {
|
||
help.textContent = KIND_HELP[kind.value];
|
||
const fields = {
|
||
webhook: [
|
||
field('URL', url),
|
||
field('Secret partagé', secret, {
|
||
help: 'Envoyé en en-tête `X-FWS-Signature` (HMAC-SHA256 du corps JSON).',
|
||
}),
|
||
],
|
||
command: [field('Commande', command), field('Répertoire de travail', cwd)],
|
||
'gitea-action': [
|
||
field('Fichier de workflow', workflow, { help: 'Nom du fichier dans `.gitea/workflows/`.' }),
|
||
field('Référence', ref, { help: 'Branche ou tag sur lequel déclencher le workflow.' }),
|
||
],
|
||
};
|
||
mount(specific, fields[kind.value] ?? []);
|
||
};
|
||
kind.addEventListener('change', drawSpecific);
|
||
drawSpecific();
|
||
|
||
const confirmed = await modal(
|
||
existing ? `Modifier « ${existing.name} »` : 'Nouvelle cible de déploiement',
|
||
() => ({
|
||
node: h(
|
||
'div',
|
||
{ class: 'stack' },
|
||
field('Nom', name),
|
||
field('Dépôt', repository, {
|
||
help:
|
||
repositories.length > 0
|
||
? undefined
|
||
: 'Format `organisation/depot`. La liste est vide : Gitea est injoignable ou non configuré.',
|
||
}),
|
||
field('Environnement', environment, { help: 'production, staging, preview…' }),
|
||
field('Type', kind),
|
||
help,
|
||
specific,
|
||
toggle(
|
||
autoDeploy,
|
||
(checked) => (autoDeploy = checked),
|
||
'Déployer automatiquement à chaque release publiée',
|
||
),
|
||
toggle(enabled, (checked) => (enabled = checked), 'Cible active'),
|
||
),
|
||
submit: () => name.value.trim() !== '' && repository.value.trim() !== '',
|
||
}),
|
||
{ confirmLabel: existing ? 'Enregistrer' : 'Créer', tone: 'primary' },
|
||
);
|
||
if (!confirmed) return;
|
||
|
||
const config = {};
|
||
if (kind.value === 'webhook') {
|
||
config.url = url.value.trim();
|
||
if (secret.value) config.secret = secret.value;
|
||
} else if (kind.value === 'command') {
|
||
config.command = command.value.trim();
|
||
config.cwd = cwd.value.trim();
|
||
} else {
|
||
config.workflow = workflow.value.trim();
|
||
config.ref = ref.value.trim();
|
||
}
|
||
|
||
const payload = {
|
||
name: name.value.trim(),
|
||
repository: repository.value,
|
||
environment: environment.value.trim(),
|
||
kind: kind.value,
|
||
config,
|
||
autoDeploy,
|
||
enabled,
|
||
};
|
||
|
||
if (existing) await api.patch(`/api/deploy/targets/${existing.id}`, payload);
|
||
else await api.post('/api/deploy/targets', payload);
|
||
|
||
toast(existing ? 'Cible mise à jour.' : 'Cible créée.');
|
||
reload();
|
||
}
|
||
|
||
async function runTarget(target, requireConfirmation, reload) {
|
||
const releaseTag = input({ placeholder: 'v1.2.3 (facultatif)' });
|
||
const ref = input({ placeholder: 'main (facultatif)' });
|
||
|
||
const confirmed = await modal(
|
||
`Déployer « ${target.name} »`,
|
||
() => ({
|
||
node: h(
|
||
'div',
|
||
{ class: 'stack' },
|
||
h('p', {}, 'Environnement : ', h('strong', { text: target.environment })),
|
||
h('p', { class: 'muted', text: target.summary }),
|
||
field('Version à déployer', releaseTag),
|
||
field('Référence git', ref),
|
||
requireConfirmation && h('p', { class: 'muted', text: 'Le déploiement démarre dès la validation.' }),
|
||
),
|
||
submit: () => true,
|
||
}),
|
||
{ confirmLabel: 'Déployer', tone: 'primary' },
|
||
);
|
||
if (!confirmed) return;
|
||
|
||
toast('Déploiement lancé…', 'info');
|
||
const result = await api.post(`/api/deploy/targets/${target.id}/run`, {
|
||
releaseTag: releaseTag.value.trim() || undefined,
|
||
ref: ref.value.trim() || undefined,
|
||
});
|
||
|
||
toast(
|
||
result.status === 'success'
|
||
? 'Déploiement réussi.'
|
||
: `Déploiement en échec : ${result.error ?? 'raison inconnue'}`,
|
||
result.status === 'success' ? 'success' : 'error',
|
||
);
|
||
reload();
|
||
}
|
||
|
||
const showLog = (deployment) =>
|
||
modal(`Déploiement #${deployment.id}`, () => ({
|
||
node: h(
|
||
'div',
|
||
{ class: 'stack' },
|
||
h('p', {}, h('strong', { text: deployment.target_name }), ` · ${deployment.environment}`),
|
||
h('p', {
|
||
class: 'muted',
|
||
text: `${deployment.repository} · ${deployment.release_tag ?? deployment.ref ?? '—'}`,
|
||
}),
|
||
deployment.error && h('p', { class: 'field-error-text', text: deployment.error }),
|
||
h('pre', {}, h('code', { text: deployment.log || 'Aucune sortie.' })),
|
||
),
|
||
submit: () => true,
|
||
}));
|
||
|
||
export function render(host, { state }) {
|
||
const level = state.me.accessLevel;
|
||
const reload = () => render(host, { state });
|
||
|
||
// A running deployment reports itself, so the log lands without a reload.
|
||
autoRefresh(reload, { topics: ['deployments', 'tick'], minIntervalMs: 2000 });
|
||
|
||
return renderAsync(
|
||
host,
|
||
async () => {
|
||
// The repository list is a convenience, not a prerequisite: a Gitea that
|
||
// answers 403 must not take the whole deployment page down with it.
|
||
const [targets, deployments, repositories] = await Promise.all([
|
||
api.get('/api/deploy/targets'),
|
||
api.get('/api/deployments', { limit: 40 }),
|
||
api.get('/api/repositories').catch((error) => ({ repositories: [], error: error.message })),
|
||
]);
|
||
return {
|
||
...targets,
|
||
deployments: deployments.deployments,
|
||
repositories: repositories.repositories ?? [],
|
||
repositoriesError: repositories.error ?? null,
|
||
};
|
||
},
|
||
(data) =>
|
||
h(
|
||
'div',
|
||
{ class: 'stack' },
|
||
h(
|
||
'div',
|
||
{ class: 'page-head' },
|
||
h(
|
||
'div',
|
||
{},
|
||
h('h1', { text: 'Déploiements' }),
|
||
h('p', {
|
||
class: 'muted',
|
||
text: 'Déclare où livrer chaque dépôt, puis déploie à la demande ou automatiquement à chaque release.',
|
||
}),
|
||
),
|
||
level >= LEVELS.DEV &&
|
||
button(
|
||
'Nouvelle cible',
|
||
() => editTarget(null, data.repositories, data.commandDeploysAllowed, level, reload),
|
||
{ tone: 'primary' },
|
||
),
|
||
),
|
||
|
||
data.repositoriesError &&
|
||
notice(
|
||
`Liste des dépôts indisponible (${data.repositoriesError}). Tu peux quand même créer une cible en saisissant le dépôt à la main ; seules les cibles Gitea Actions ont réellement besoin de la forge.`,
|
||
'warning',
|
||
),
|
||
|
||
!data.commandDeploysAllowed &&
|
||
notice(
|
||
'Les déploiements par commande shell sont désactivés (`WEB_ALLOW_COMMAND_DEPLOYS=false`). Les cibles webhook et Gitea Actions restent disponibles.',
|
||
'info',
|
||
),
|
||
|
||
card(
|
||
'Cibles',
|
||
{ subtitle: `${data.targets.length} cible(s) configurée(s)` },
|
||
table(
|
||
[
|
||
{
|
||
label: 'Cible',
|
||
render: (target) =>
|
||
h(
|
||
'div',
|
||
{},
|
||
h('strong', { text: target.name }),
|
||
h('div', { class: 'muted', text: target.summary }),
|
||
),
|
||
},
|
||
{ label: 'Dépôt', key: 'repository' },
|
||
{ label: 'Environnement', render: (target) => badge(target.environment, 'info') },
|
||
{
|
||
label: 'Type',
|
||
className: 'advanced-only',
|
||
render: (target) => badge(target.kind, target.kind === 'command' ? 'warning' : 'neutral'),
|
||
},
|
||
{
|
||
label: 'Auto',
|
||
render: (target) =>
|
||
target.autoDeploy ? badge('Auto', 'success') : badge('Manuel', 'neutral'),
|
||
},
|
||
{
|
||
label: 'Actif',
|
||
render: (target) => (target.enabled ? badge('Oui', 'success') : badge('En pause', 'neutral')),
|
||
},
|
||
{
|
||
label: '',
|
||
render: (target) =>
|
||
h(
|
||
'div',
|
||
{ class: 'row' },
|
||
level >= LEVELS.DEV &&
|
||
button('Déployer', () => runTarget(target, true, reload), {
|
||
tone: 'primary',
|
||
disabled: !target.enabled,
|
||
}),
|
||
level >= LEVELS.DEV &&
|
||
button(
|
||
'Modifier',
|
||
() =>
|
||
editTarget(target, data.repositories, data.commandDeploysAllowed, level, reload),
|
||
{ tone: 'ghost' },
|
||
),
|
||
level >= LEVELS.OWNER &&
|
||
button(
|
||
'Supprimer',
|
||
async () => {
|
||
if (!(await confirmAction('Supprimer la cible', `Supprimer « ${target.name} » ?`)))
|
||
return;
|
||
await api.delete(`/api/deploy/targets/${target.id}`);
|
||
toast('Cible supprimée.');
|
||
reload();
|
||
},
|
||
{ tone: 'danger' },
|
||
),
|
||
),
|
||
},
|
||
],
|
||
data.targets,
|
||
{ empty: 'Aucune cible pour l’instant. Crée-en une pour déployer depuis ce site.' },
|
||
),
|
||
),
|
||
|
||
card(
|
||
'Historique',
|
||
{ subtitle: 'Les 40 derniers déploiements, réussis comme échoués.' },
|
||
table(
|
||
[
|
||
{ label: '#', className: 'num', key: 'id' },
|
||
{ label: 'Cible', key: 'target_name' },
|
||
{ label: 'Environnement', key: 'environment' },
|
||
{ label: 'Version', render: (row) => row.release_tag ?? row.ref ?? '—' },
|
||
{
|
||
label: 'État',
|
||
render: (row) => badge(row.status, STATUS_TONE[row.status] ?? 'neutral'),
|
||
},
|
||
{ label: 'Source', className: 'advanced-only', key: 'source' },
|
||
{ label: 'Quand', className: 'nowrap', render: (row) => formatRelative(row.created_at) },
|
||
{ label: '', render: (row) => button('Journal', () => showLog(row), { tone: 'ghost' }) },
|
||
],
|
||
data.deployments,
|
||
{ empty: 'Aucun déploiement enregistré.' },
|
||
),
|
||
),
|
||
),
|
||
);
|
||
}
|