Skip to content

armgit / posta

Public Imported from GitHub
0

Self-hosted email delivery platform that enables applications to send emails via HTTP APIs while handling SMTP delivery, templates, storage, security, and analytics. Fully self-hostable alternative to services like SendGrid or Mailgun.

feat(workers): add version check and warn

Jonas Kanindadb35f7f1ddc3
diff --git a/cmd/posta/server.go b/cmd/posta/server.go
index 7195aa9..c63ebab 100644
--- a/cmd/posta/server.go
+++ b/cmd/posta/server.go
@@ -41,6 +41,7 @@ import (
"github.com/goposta/posta/internal/services/settings"
"github.com/goposta/posta/internal/services/tracking"
"github.com/goposta/posta/internal/services/webhook"
+ "github.com/goposta/posta/internal/services/workermon"
"github.com/goposta/posta/internal/services/workspacemigrate"
"github.com/goposta/posta/internal/storage"
"github.com/goposta/posta/internal/storage/blob"
@@ -441,6 +442,8 @@ func startEmbeddedWorker(db *gorm.DB,
mux.HandleFunc(worker.TypeInboundParse, parseHandler.ProcessTask)
}
+ workermon.StartHeartbeat(context.Background(), cfg.Redis.Client, config.Version, config.CommitID)
+
go func() {
if err := srv.Run(mux); err != nil {
logger.Error("embedded worker error", "error", err)
diff --git a/cmd/posta/worker.go b/cmd/posta/worker.go
index bd4680b..496afb2 100644
--- a/cmd/posta/worker.go
+++ b/cmd/posta/worker.go
@@ -18,6 +18,8 @@
package main
import (
+ "context"
+
"github.com/goposta/posta/internal/config"
"github.com/goposta/posta/internal/cron/jobs"
"github.com/goposta/posta/internal/metrics"
@@ -27,6 +29,7 @@ import (
"github.com/goposta/posta/internal/services/inbound"
"github.com/goposta/posta/internal/services/notification"
"github.com/goposta/posta/internal/services/tracking"
+ "github.com/goposta/posta/internal/services/workermon"
"github.com/goposta/posta/internal/storage/blob"
"github.com/goposta/posta/internal/storage/repositories"
"github.com/goposta/posta/internal/worker"
@@ -199,6 +202,9 @@ func runWorker() error {
mux.HandleFunc(worker.TypeInboundParse, parseHandler.ProcessTask)
}
+ // Publish worker's build info
+ workermon.StartHeartbeat(context.Background(), cfg.Redis.Client, config.Version, config.CommitID)
+
logger.Info("Posta worker started",
"version", config.Version,
"concurrency", cfg.WorkerConcurrency,
diff --git a/internal/handlers/admin_handler.go b/internal/handlers/admin_handler.go
index 5440f95..4c95f39 100644
--- a/internal/handlers/admin_handler.go
+++ b/internal/handlers/admin_handler.go
@@ -18,22 +18,26 @@
package handlers
import (
+ "context"
"fmt"
"os"
"runtime"
"time"
+ "github.com/goposta/posta/internal/config"
"github.com/goposta/posta/internal/models"
"github.com/goposta/posta/internal/services/cache"
"github.com/goposta/posta/internal/services/eventbus"
"github.com/goposta/posta/internal/services/seeder"
"github.com/goposta/posta/internal/services/session"
"github.com/goposta/posta/internal/services/settings"
+ "github.com/goposta/posta/internal/services/workermon"
"github.com/goposta/posta/internal/services/workspacemigrate"
"github.com/goposta/posta/internal/storage/repositories"
"github.com/hibiken/asynq"
"github.com/jkaninda/logger"
"github.com/jkaninda/okapi"
+ "github.com/redis/go-redis/v9"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
)
@@ -48,6 +52,7 @@ type AdminHandler struct {
workspaceRepo *repositories.WorkspaceRepository
planRepo *repositories.PlanRepository
inspector *asynq.Inspector
+ redis *redis.Client
bus *eventbus.EventBus
seeder *seeder.Seeder
migrator *workspacemigrate.Service
@@ -154,8 +159,8 @@ type UserDetailMetrics struct {
WebhookDeliveries *repositories.WebhookDeliveryStats `json:"webhook_deliveries"`
}
-func NewAdminHandler(db *gorm.DB, c *cache.Cache, userRepo *repositories.UserRepository, keyRepo *repositories.APIKeyRepository, emailRepo *repositories.EmailRepository, whDeliveryRepo *repositories.WebhookDeliveryRepository, inspector *asynq.Inspector, bus *eventbus.EventBus, seeder *seeder.Seeder, embeddedWorker bool) *AdminHandler {
- return &AdminHandler{db: db, cache: c, userRepo: userRepo, keyRepo: keyRepo, emailRepo: emailRepo, whDeliveryRepo: whDeliveryRepo, inspector: inspector, bus: bus, seeder: seeder, embeddedWorker: embeddedWorker}
+func NewAdminHandler(db *gorm.DB, c *cache.Cache, userRepo *repositories.UserRepository, keyRepo *repositories.APIKeyRepository, emailRepo *repositories.EmailRepository, whDeliveryRepo *repositories.WebhookDeliveryRepository, inspector *asynq.Inspector, redisClient *redis.Client, bus *eventbus.EventBus, seeder *seeder.Seeder, embeddedWorker bool) *AdminHandler {
+ return &AdminHandler{db: db, cache: c, userRepo: userRepo, keyRepo: keyRepo, emailRepo: emailRepo, whDeliveryRepo: whDeliveryRepo, inspector: inspector, redis: redisClient, bus: bus, seeder: seeder, embeddedWorker: embeddedWorker}
}
// SetWorkspaceRepo sets the workspace and plan repositories for workspace management.
@@ -611,8 +616,10 @@ func (h *AdminHandler) RevokeUserSessions(c *okapi.Context, req *AdminGetUserReq
// WorkerStatus is sent over SSE with the current worker count and details.
type WorkerStatus struct {
- ActiveWorkers int `json:"active_workers"`
- Workers []WorkerDetail `json:"workers"`
+ ActiveWorkers int `json:"active_workers"`
+ Workers []WorkerDetail `json:"workers"`
+ ServerVersion string `json:"server_version"`
+ VersionMismatch bool `json:"version_mismatch"`
}
type SystemStatus struct {
@@ -633,10 +640,12 @@ func buildSystemStatus() SystemStatus {
// WorkerDetail holds info about a single connected worker.
type WorkerDetail struct {
- Host string `json:"host"`
- PID int `json:"pid"`
- Queues map[string]int `json:"queues"`
- Type string `json:"type"` // "embedded" or "standalone"
+ Host string `json:"host"`
+ PID int `json:"pid"`
+ Queues map[string]int `json:"queues"`
+ Type string `json:"type"` // "embedded" or "standalone"
+ Version string `json:"version,omitempty"` // self-reported via heartbeat; empty if none yet
+ Outdated bool `json:"outdated"` // version differs from the server
}
// MetricsStream sends real-time platform metrics updates via SSE
@@ -686,7 +695,7 @@ func (h *AdminHandler) MetricsStream(c *okapi.Context) error {
}
func (h *AdminHandler) buildWorkerStatus() WorkerStatus {
- var status WorkerStatus
+ status := WorkerStatus{ServerVersion: config.Version}
if h.inspector == nil {
return status
}
@@ -694,6 +703,9 @@ func (h *AdminHandler) buildWorkerStatus() WorkerStatus {
if err != nil {
return status
}
+
+ heartbeats := workermon.ReadHeartbeats(context.Background(), h.redis)
+
selfPID := os.Getpid()
selfHost, _ := os.Hostname()
status.ActiveWorkers = len(servers)
@@ -703,12 +715,21 @@ func (h *AdminHandler) buildWorkerStatus() WorkerStatus {
if h.embeddedWorker && s.PID == selfPID && s.Host == selfHost {
wType = "embedded"
}
- status.Workers = append(status.Workers, WorkerDetail{
+ detail := WorkerDetail{
Host: s.Host,
PID: s.PID,
Queues: s.Queues,
Type: wType,
- })
+ }
+ if hb, ok := heartbeats[fmt.Sprintf("%s:%d", s.Host, s.PID)]; ok {
+ detail.Version = hb.Version
+
+ if hb.Version != "" && hb.Version != config.Version {
+ detail.Outdated = true
+ status.VersionMismatch = true
+ }
+ }
+ status.Workers = append(status.Workers, detail)
}
return status
}
diff --git a/internal/routes/routes.go b/internal/routes/routes.go
index 4fae614..cf5387a 100644
--- a/internal/routes/routes.go
+++ b/internal/routes/routes.go
@@ -253,7 +253,7 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
suppression: handlers.NewSuppressionHandler(suppressionRepo, unsubListRepo),
unsubscribeList: handlers.NewUnsubscribeListHandler(unsubListRepo),
contact: handlers.NewContactHandler(contactRepo, suppressionRepo),
- admin: handlers.NewAdminHandler(db, statsCache, userRepo, apiKeyRepo, emailRepo, webhookDeliveryRepo, inspector, bus, userSeeder, cfg.EmbeddedWorker),
+ admin: handlers.NewAdminHandler(db, statsCache, userRepo, apiKeyRepo, emailRepo, webhookDeliveryRepo, inspector, redisClient, bus, userSeeder, cfg.EmbeddedWorker),
workspace: handlers.NewWorkspaceHandler(workspaceRepo, userRepo, db),
server: handlers.NewServerHandler(serverRepo, auditLogger),
event: handlers.NewEventHandler(eventRepo, bus),
diff --git a/internal/services/workermon/heartbeat.go b/internal/services/workermon/heartbeat.go
new file mode 100644
index 0000000..7dd9c34
--- /dev/null
+++ b/internal/services/workermon/heartbeat.go
@@ -0,0 +1,105 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package workermon
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "os"
+ "strings"
+ "time"
+
+ "github.com/redis/go-redis/v9"
+)
+
+const (
+ heartbeatInterval = 15 * time.Second
+ heartbeatTTL = 45 * time.Second
+ heartbeatPrefix = "posta:worker:"
+)
+
+type WorkerHeartbeat struct {
+ Version string `json:"version"`
+ CommitID string `json:"commit_id"`
+}
+
+func heartbeatKey(host string, pid int) string {
+ return fmt.Sprintf("%s%s:%d", heartbeatPrefix, host, pid)
+}
+
+func StartHeartbeat(ctx context.Context, rdb *redis.Client, version, commitID string) {
+ if rdb == nil {
+ return
+ }
+ host, _ := os.Hostname()
+ key := heartbeatKey(host, os.Getpid())
+ payload, _ := json.Marshal(WorkerHeartbeat{Version: version, CommitID: commitID})
+
+ set := func() {
+ c, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ defer cancel()
+ _ = rdb.Set(c, key, payload, heartbeatTTL).Err()
+ }
+
+ set()
+ go func() {
+ t := time.NewTicker(heartbeatInterval)
+ defer t.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ c, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ _ = rdb.Del(c, key).Err()
+ cancel()
+ return
+ case <-t.C:
+ set()
+ }
+ }
+ }()
+}
+
+func ReadHeartbeats(ctx context.Context, rdb *redis.Client) map[string]WorkerHeartbeat {
+ out := map[string]WorkerHeartbeat{}
+ if rdb == nil {
+ return out
+ }
+ var cursor uint64
+ for {
+ keys, next, err := rdb.Scan(ctx, cursor, heartbeatPrefix+"*", 100).Result()
+ if err != nil {
+ return out
+ }
+ for _, k := range keys {
+ val, err := rdb.Get(ctx, k).Result()
+ if err != nil {
+ continue
+ }
+ var hb WorkerHeartbeat
+ if json.Unmarshal([]byte(val), &hb) == nil {
+ out[strings.TrimPrefix(k, heartbeatPrefix)] = hb
+ }
+ }
+ if next == 0 {
+ break
+ }
+ cursor = next
+ }
+ return out
+}
diff --git a/web/src/api/types.ts b/web/src/api/types.ts
index 7f7aa66..c72c2d7 100644
--- a/web/src/api/types.ts
+++ b/web/src/api/types.ts
@@ -506,6 +506,8 @@ export interface AdminMetrics {
export interface WorkerStatus {
active_workers: number
workers: WorkerDetail[]
+ server_version?: string
+ version_mismatch?: boolean
}
export interface SystemStatus {
@@ -519,6 +521,8 @@ export interface WorkerDetail {
pid: number
queues: Record<string, number>
type: 'embedded' | 'standalone'
+ version?: string
+ outdated?: boolean
}
export interface Event {
diff --git a/web/src/views/admin/Metrics.vue b/web/src/views/admin/Metrics.vue
index 49a5bee..f7c2d63 100644
--- a/web/src/views/admin/Metrics.vue
+++ b/web/src/views/admin/Metrics.vue
@@ -304,6 +304,23 @@ const avgDeliveryRate = computed(() => {
<!-- Worker Details -->
<template v-if="workerStatus && workerStatus.workers.length > 0">
<div class="metrics-section-label">Workers</div>
+
+ <div v-if="workerStatus.version_mismatch" class="app-banner app-banner--warning" style="margin-bottom: 16px;">
+ <svg class="app-banner-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
+ stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
+ <line x1="12" y1="9" x2="12" y2="13" />
+ <line x1="12" y1="17" x2="12.01" y2="17" />
+ </svg>
+ <div class="app-banner-content">
+ <p class="app-banner-title">Worker version mismatch</p>
+ <p class="app-banner-text">
+ One or more workers are running a different version than the server
+ (<strong>{{ workerStatus.server_version || 'unknown' }}</strong>).
+ </p>
+ </div>
+ </div>
+
<div class="card" style="margin-bottom: 28px;">
<div class="table-wrapper">
<table>
@@ -312,6 +329,7 @@ const avgDeliveryRate = computed(() => {
<th>Host</th>
<th>PID</th>
<th>Type</th>
+ <th>Version</th>
<th>Queues</th>
</tr>
</thead>
@@ -324,6 +342,13 @@ const avgDeliveryRate = computed(() => {
{{ w.type }}
</span>
</td>
+ <td>
+ <span v-if="w.version" class="badge" :class="w.outdated ? 'badge-warning' : 'badge-neutral'"
+ :title="w.outdated ? `Differs from server (${workerStatus.server_version})` : ''">
+ {{ w.version }}
+ </span>
+ <span v-else style="color: var(--text-muted)">—</span>
+ </td>
<td>
<span v-for="(concurrency, queue) in w.queues" :key="queue" class="badge badge-neutral" style="margin-right: 6px;">
{{ queue }}: {{ concurrency }}