Add real-time deployment updates and refactor JavaScript

- Add deploy stats (last deploy time, total count) to dashboard
- Add recent-deployments API endpoint for real-time updates
- Add live build logs to deployments history page
- Fix git clone regression (preserve entrypoint for simple clones)
- Refactor JavaScript into shared app.js with page init functions
- Deploy button disables immediately on click
- Auto-refresh deployment list and logs during builds
- Format JavaScript with Prettier (4-space indent)
This commit is contained in:
2026-01-01 05:22:56 +07:00
parent 307955dae1
commit ab7e917b03
9 changed files with 837 additions and 398 deletions

View File

@@ -554,16 +554,20 @@ func (c *Client) createGitContainer(
// Build the git command based on whether we have a specific commit SHA
var cmd []string
var entrypoint []string
if cfg.commitSHA != "" {
// Clone without depth limit so we can checkout any commit, then checkout specific SHA
// Using sh -c to run multiple commands
// Using sh -c to run multiple commands - need to clear entrypoint
script := fmt.Sprintf(
"git clone --branch %s %s /repo && cd /repo && git checkout %s",
cfg.branch, cfg.repoURL, cfg.commitSHA,
)
entrypoint = []string{}
cmd = []string{"sh", "-c", script}
} else {
// Shallow clone of branch HEAD
// Shallow clone of branch HEAD - use default git entrypoint
entrypoint = nil
cmd = []string{"clone", "--depth", "1", "--branch", cfg.branch, cfg.repoURL, "/repo"}
}
@@ -571,7 +575,7 @@ func (c *Client) createGitContainer(
resp, err := c.docker.ContainerCreate(ctx,
&container.Config{
Image: gitImage,
Entrypoint: []string{}, // Clear entrypoint when using sh -c
Entrypoint: entrypoint,
Cmd: cmd,
Env: []string{"GIT_SSH_COMMAND=" + gitSSHCmd},
WorkingDir: "/",

View File

@@ -537,6 +537,49 @@ func (h *Handlers) HandleAppStatusAPI() http.HandlerFunc {
}
}
// HandleRecentDeploymentsAPI returns JSON with recent deployments.
func (h *Handlers) HandleRecentDeploymentsAPI() http.HandlerFunc {
return func(writer http.ResponseWriter, request *http.Request) {
appID := chi.URLParam(request, "id")
application, findErr := models.FindApp(request.Context(), h.db, appID)
if findErr != nil || application == nil {
http.NotFound(writer, request)
return
}
deployments, deployErr := application.GetDeployments(
request.Context(),
recentDeploymentsLimit,
)
if deployErr != nil {
h.log.Error("failed to get deployments", "error", deployErr, "app", appID)
deployments = []*models.Deployment{}
}
// Build response with formatted data
deploymentsData := make([]map[string]any, 0, len(deployments))
for _, d := range deployments {
deploymentsData = append(deploymentsData, map[string]any{
"id": d.ID,
"status": string(d.Status),
"duration": d.Duration(),
"shortCommit": d.ShortCommit(),
"finishedAtISO": d.FinishedAtISO(),
"finishedAtLabel": d.FinishedAtFormatted(),
})
}
writer.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(writer).Encode(map[string]any{
"deployments": deploymentsData,
})
}
}
// containerAction represents a container operation type.
type containerAction string

View File

@@ -2,17 +2,29 @@ package handlers
import (
"net/http"
"time"
"git.eeqj.de/sneak/upaas/internal/models"
"git.eeqj.de/sneak/upaas/templates"
)
// AppStats holds deployment statistics for an app.
type AppStats struct {
App *models.App
LastDeployTime *time.Time
LastDeployISO string
LastDeployLabel string
DeployCount int
}
// HandleDashboard returns the dashboard handler.
func (h *Handlers) HandleDashboard() http.HandlerFunc {
tmpl := templates.GetParsed()
return func(writer http.ResponseWriter, request *http.Request) {
apps, fetchErr := models.AllApps(request.Context(), h.db)
ctx := request.Context()
apps, fetchErr := models.AllApps(ctx, h.db)
if fetchErr != nil {
h.log.Error("failed to fetch apps", "error", fetchErr)
http.Error(writer, "Internal Server Error", http.StatusInternalServerError)
@@ -20,8 +32,41 @@ func (h *Handlers) HandleDashboard() http.HandlerFunc {
return
}
// Fetch stats for each app
appStats := make([]*AppStats, 0, len(apps))
for _, app := range apps {
stats := &AppStats{App: app}
// Get deploy count
count, countErr := models.CountDeploymentsByAppID(ctx, h.db, app.ID)
if countErr != nil {
h.log.Error("failed to count deployments", "error", countErr, "app", app.ID)
} else {
stats.DeployCount = count
}
// Get latest deployment
latest, latestErr := models.LatestDeploymentForApp(ctx, h.db, app.ID)
if latestErr != nil {
h.log.Error("failed to get latest deployment", "error", latestErr, "app", app.ID)
} else if latest != nil {
if latest.FinishedAt.Valid {
stats.LastDeployTime = &latest.FinishedAt.Time
stats.LastDeployISO = latest.FinishedAt.Time.Format(time.RFC3339)
stats.LastDeployLabel = latest.FinishedAt.Time.Format("2006-01-02 15:04:05")
} else {
stats.LastDeployTime = &latest.StartedAt
stats.LastDeployISO = latest.StartedAt.Format(time.RFC3339)
stats.LastDeployLabel = latest.StartedAt.Format("2006-01-02 15:04:05")
}
}
appStats = append(appStats, stats)
}
data := h.addGlobals(map[string]any{
"Apps": apps,
"AppStats": appStats,
})
execErr := tmpl.ExecuteTemplate(writer, "dashboard.html", data)

View File

@@ -302,3 +302,24 @@ func LatestDeploymentForApp(
return deploy, nil
}
// CountDeploymentsByAppID returns the total number of deployments for an app.
func CountDeploymentsByAppID(
ctx context.Context,
deployDB *database.Database,
appID string,
) (int, error) {
var count int
row := deployDB.QueryRow(ctx,
"SELECT COUNT(*) FROM deployments WHERE app_id = ?",
appID,
)
err := row.Scan(&count)
if err != nil {
return 0, fmt.Errorf("counting deployments: %w", err)
}
return count, nil
}

View File

@@ -69,6 +69,7 @@ func (s *Server) SetupRoutes() {
r.Get("/apps/{id}/logs", s.handlers.HandleAppLogs())
r.Get("/apps/{id}/container-logs", s.handlers.HandleContainerLogsAPI())
r.Get("/apps/{id}/status", s.handlers.HandleAppStatusAPI())
r.Get("/apps/{id}/recent-deployments", s.handlers.HandleRecentDeploymentsAPI())
r.Post("/apps/{id}/restart", s.handlers.HandleAppRestart())
r.Post("/apps/{id}/stop", s.handlers.HandleAppStop())
r.Post("/apps/{id}/start", s.handlers.HandleAppStart())