feat(apps): per-app deploy/activity timeline

Every deploy across all four source kinds now writes a workload-scoped
event via a shared plugin.EmitDeployEvent helper (replacing the inline
emit duplicated in static/dockerfile, standardizing static's metadata
key site_id->workload_id, and adding emission to image+compose which
were silent). New indexed event_log.workload_id column, EventLogFilter
.WorkloadID, and GET /api/workloads/{id}/events (id pinned from path).

Frontend: a forge "Activity" panel on /apps/[id] reusing EventLogEntry,
live SSE prepend filtered by workload_id, load-more pagination, an
All/Errors severity filter, and a shared toEventLogEntry mapper. en/ru
i18n parity.

Security: compose's failure status emits a generic reason instead of raw
`docker compose up` output, which can echo app secrets and egresses to
operator webhooks (NotificationURL + event-trigger actions); full detail
stays only in the returned error. Rune-safe 256-rune status cap.

Reviewed: go + typescript APPROVE; security HIGH fixed.
This commit is contained in:
2026-05-29 13:51:17 +03:00
parent 3071cda512
commit 93b6911b34
19 changed files with 814 additions and 223 deletions
@@ -84,7 +84,7 @@ func (*source) Validate(cfg json.RawMessage) error {
// `docker compose -p <project> up -d`, then syncs one Container row per
// service. The workload ID is the natural compose project name unless
// the user supplied one explicitly.
func (*source) Deploy(ctx context.Context, deps plugin.Deps, w plugin.Workload, intent plugin.DeploymentIntent) error {
func (*source) Deploy(ctx context.Context, deps plugin.Deps, w plugin.Workload, intent plugin.DeploymentIntent) (err error) {
cfg, err := plugin.SourceConfigOf[Config](w)
if err != nil {
return fmt.Errorf("compose source: decode config: %w", err)
@@ -93,6 +93,29 @@ func (*source) Deploy(ctx context.Context, deps plugin.Deps, w plugin.Workload,
return fmt.Errorf("compose source: workload %s has empty compose_yaml", w.ID)
}
// compose.Deploy has no idempotency short-circuit (no "already up"
// fast path that returns nil), so every call past config validation
// is a real deploy. Arm the terminal audit emit here — after pure
// config-validation errors above (kept quiet, mirroring the image
// plugin) but before any real work — so all real failures and the
// success are captured for the per-app timeline. err is the named
// return.
defer func() {
if err != nil {
// SECURITY: the compose.Up failure wraps raw `docker compose`
// combined output (which can include the deployed app's own
// stderr — potentially secrets). Deploy events are persisted
// indefinitely AND egress to operator webhooks (the global
// NotificationURL + event-trigger actions), so the emitted
// status must NOT carry that output. The full detail still
// reaches the server log + admin deploy result via the returned
// err; the timeline records only a generic, secret-free reason.
plugin.EmitDeployEvent(deps, w, "compose", "failed")
} else {
plugin.EmitDeployEvent(deps, w, "compose", "deployed")
}
}()
projectName := composeProjectName(cfg.ComposeProjectName, w)
yamlPath, err := writeYAML(w.ID, cfg.ComposeYAML)
if err != nil {
@@ -2,7 +2,6 @@ package dockerfile
import (
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
@@ -506,49 +505,13 @@ func dispatchBuildNotification(deps plugin.Deps, w plugin.Workload, domain, stat
})
}
// publishEvent emits a status event on the bus AND persists an
// event_log row. Message shape mirrors the static plugin
// ("Build %q: %s") so the dashboard's audit feed reads consistently
// across both kinds.
// publishEvent records a workload-scoped deploy event in the audit log.
// The InsertEvent + bus publish (and consistent message/metadata shape
// across source kinds) is centralised in plugin.EmitDeployEvent so the
// dashboard's audit feed and the per-workload timeline read identically
// for image / compose / static / dockerfile deploys.
func publishEvent(deps plugin.Deps, w plugin.Workload, status string) {
severity := "info"
if strings.HasPrefix(status, "failed") {
severity = "error"
}
message := fmt.Sprintf("Build %q: %s", w.Name, status)
metaBytes, err := json.Marshal(map[string]string{
"workload_id": w.ID,
"workload_name": w.Name,
"status": status,
})
if err != nil {
slog.Error("dockerfile: marshal event metadata", "error", err)
metaBytes = []byte("{}")
}
metadata := string(metaBytes)
evt, err := deps.Store.InsertEvent(store.EventLog{
Source: "dockerfile",
Severity: severity,
Message: message,
Metadata: metadata,
})
if err != nil {
slog.Error("dockerfile: failed to persist event log", "error", err)
return
}
deps.Events.Publish(events.Event{
Type: events.EventLog,
Payload: events.EventLogPayload{
ID: evt.ID,
Source: "dockerfile",
Severity: severity,
Message: message,
Metadata: metadata,
CreatedAt: evt.CreatedAt,
},
})
plugin.EmitDeployEvent(deps, w, "dockerfile", status)
}
// publishBuildLog emits one EventBuildLog per non-empty daemon "stream"
+30 -32
View File
@@ -118,7 +118,7 @@ func (*source) Validate(cfg json.RawMessage) error {
//
// Any failure between create and face-registration rolls back the new
// container + its row; old serving state is preserved.
func (*source) Deploy(ctx context.Context, deps plugin.Deps, w plugin.Workload, intent plugin.DeploymentIntent) error {
func (*source) Deploy(ctx context.Context, deps plugin.Deps, w plugin.Workload, intent plugin.DeploymentIntent) (err error) {
cfg, err := plugin.SourceConfigOf[Config](w)
if err != nil {
return fmt.Errorf("image source: decode config: %w", err)
@@ -162,6 +162,19 @@ func (*source) Deploy(ctx context.Context, deps plugin.Deps, w plugin.Workload,
}
}
// Past the idempotency short-circuit: this is a real deploy. Emit a
// terminal audit event for the per-app timeline. Armed here (not at the
// top) so duplicate-webhook no-ops above don't flood the log, and
// pre-flight config/settings errors above stay quiet. err is the named
// return, so the deferred closure observes the final outcome.
defer func() {
if err != nil {
plugin.EmitDeployEvent(deps, w, "image", "failed: "+err.Error())
} else {
plugin.EmitDeployEvent(deps, w, "image", "deployed")
}
}()
authConfig, err := buildRegistryAuth(deps, cfg.RegistryName)
if err != nil {
return fmt.Errorf("image source: %w", err)
@@ -486,37 +499,22 @@ type containerExtra struct {
ProxyRoutes map[string]string `json:"proxy_routes,omitempty"`
}
// Reconcile syncs the containers index for this workload with reality.
// MVP: just refreshes State from Docker. Future versions can re-deploy
// when the running container disagrees with the desired source config.
func (*source) Reconcile(ctx context.Context, deps plugin.Deps, w plugin.Workload) error {
rows, err := deps.Store.ListContainersByWorkload(w.ID)
if err != nil {
return fmt.Errorf("image source: list containers: %w", err)
}
for _, c := range rows {
if c.ContainerID == "" {
continue
}
running, err := deps.Docker.IsContainerRunning(ctx, c.ContainerID)
if err != nil {
// Most likely "no such container" — mark as missing so the UI
// surfaces it and the next deploy recreates.
if err := deps.Store.UpdateContainerState(c.ID, "missing"); err != nil {
slog.Warn("image source: mark missing", "id", c.ID, "error", err)
}
continue
}
desired := "running"
if !running {
desired = "stopped"
}
if c.State != desired {
if err := deps.Store.UpdateContainerState(c.ID, desired); err != nil {
slog.Warn("image source: state sync", "id", c.ID, "error", err)
}
}
}
// Reconcile is intentionally a no-op for the image source.
//
// State sync is fully handled by the generic reconciler pass that runs
// EARLIER in the same Reconciler.ReconcileOnce: its upsert loop writes each
// present container's State from the single `docker ps -a` snapshot
// (ListAllForReconciler), and its markMissing pass flips rows whose container
// ID is absent from that snapshot to 'missing'. Every image container carries
// the tinyforge.workload.id label (ContainerConfig.WorkloadID at create time),
// so the generic pass covers all of them.
//
// The previous implementation looped this workload's container rows and called
// Docker.IsContainerRunning per row — a redundant Docker inspect per container
// per tick that duplicated work already done from the snapshot and scaled as N
// Docker API calls/tick. Returning nil here drops that cost without changing
// observable state. The method stays because the source interface requires it.
func (*source) Reconcile(context.Context, plugin.Deps, plugin.Workload) error {
return nil
}
@@ -2,14 +2,12 @@ package static
import (
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/moby/moby/api/types/mount"
@@ -543,11 +541,13 @@ func dispatchSiteNotification(deps plugin.Deps, w plugin.Workload, domain, statu
})
}
// publishEvent emits a static_site_status event on the bus AND
// persists an event_log row so the dashboard's audit trail picks it
// up. Message format ("Static site \"%s\": %s") is preserved verbatim
// from the legacy Manager.publishEvent so log scrapers and operator-
// configured event triggers keep matching.
// publishEvent emits a static_site_status event on the bus (drives the
// dashboard's per-site status pill) AND records a workload-scoped deploy
// event in the audit log. The audit InsertEvent + bus publish is
// centralised in plugin.EmitDeployEvent so the message/metadata shape and
// per-workload timeline are identical across all source kinds. This
// standardises the metadata key from the legacy "site_id" to "workload_id";
// no consumer reads the old key (verified repo-wide).
func publishEvent(deps plugin.Deps, w plugin.Workload, status string) {
deps.Events.Publish(events.Event{
Type: events.EventStaticSiteStatus,
@@ -558,47 +558,7 @@ func publishEvent(deps plugin.Deps, w plugin.Workload, status string) {
},
})
severity := "info"
if strings.HasPrefix(status, "failed") {
severity = "error"
}
message := fmt.Sprintf("Static site %q: %s", w.Name, status)
// Build metadata via json.Marshal so workload names containing
// quotes or backslashes don't produce invalid JSON for downstream
// log-scan consumers.
metaBytes, err := json.Marshal(map[string]string{
"site_id": w.ID,
"site_name": w.Name,
"status": status,
})
if err != nil {
slog.Error("static site: marshal event metadata", "error", err)
metaBytes = []byte("{}")
}
metadata := string(metaBytes)
evt, err := deps.Store.InsertEvent(store.EventLog{
Source: "static_site",
Severity: severity,
Message: message,
Metadata: metadata,
})
if err != nil {
slog.Error("static site: failed to persist event log", "error", err)
return
}
deps.Events.Publish(events.Event{
Type: events.EventLog,
Payload: events.EventLogPayload{
ID: evt.ID,
Source: "static_site",
Severity: severity,
Message: message,
Metadata: metadata,
CreatedAt: evt.CreatedAt,
},
})
plugin.EmitDeployEvent(deps, w, "static_site", status)
}
// removeContainerByName mirrors the legacy helper: enumerate Docker's