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.
Go email-relayemail-routinghttp-to-smtpmail-deliverymailchimp-alternativemailgun-alternativemailsendermailservermailtemplatemailtestpostmark-alternativesend-emailsendgrid-alternativesendmailtransactional-emailtransactional-outbox
feat: add system status metrics sse stream and security metrics
Jonas Kanindac50512f37c28
diff --git a/docs/docs/admin/platform-metrics.md b/docs/docs/admin/platform-metrics.mdindex 633bb70..31cc54f 100644--- a/docs/docs/admin/platform-metrics.md+++ b/docs/docs/admin/platform-metrics.md@@ -55,12 +55,15 @@ Stream platform events in real-time:GET /api/v1/admin/events/stream?token=<jwt-token>```-### Worker Status Stream (SSE)+### Metrics Stream (SSE)-Monitor background worker activity:+Monitor background worker activity and API server runtime stats:```-GET /api/v1/admin/workers/stream?token=<jwt-token>+GET /api/v1/admin/metrics/stream?token=<jwt-token>```-Returns real-time worker count and processing details.+Emits two event types:++- `worker.status` — real-time worker count and processing details.+- `system.status` — server uptime, current goroutine count, and heap memory usage.diff --git a/internal/handlers/admin_handler.go b/internal/handlers/admin_handler.goindex d63fa14..284f649 100644--- a/internal/handlers/admin_handler.go+++ b/internal/handlers/admin_handler.go@@ -20,6 +20,7 @@ package handlersimport ("fmt""os"+ "runtime""time""github.com/goposta/posta/internal/models"@@ -73,25 +74,37 @@ type AdminDeleteUserRequest struct {// PlatformMetrics holds aggregate platform metrics.type PlatformMetrics struct {- TotalUsers int64 `json:"total_users"`- TotalEmails int64 `json:"total_emails"`- QueuedEmails int64 `json:"queued_emails"`- ProcessingEmails int64 `json:"processing_emails"`- SentEmails int64 `json:"sent_emails"`- FailedEmails int64 `json:"failed_emails"`- SuppressedEmails int64 `json:"suppressed_emails"`- FailureRate float64 `json:"failure_rate"`- TotalAPIKeys int64 `json:"total_api_keys"`- ActiveAPIKeys int64 `json:"active_api_keys"`- TotalBounces int64 `json:"total_bounces"`- TotalSuppressions int64 `json:"total_suppressions"`- ActiveWorkers int `json:"active_workers"`- SharedSmtpServers int64 `json:"shared_smtp_servers"`- TotalDomains int64 `json:"total_domains"`- TotalWorkspaces int64 `json:"total_workspaces"`- WebhookDeliveries *repositories.WebhookDeliveryStats `json:"webhook_deliveries"`+ TotalUsers int64 `json:"total_users"`+ TotalEmails int64 `json:"total_emails"`+ QueuedEmails int64 `json:"queued_emails"`+ ProcessingEmails int64 `json:"processing_emails"`+ SentEmails int64 `json:"sent_emails"`+ FailedEmails int64 `json:"failed_emails"`+ SuppressedEmails int64 `json:"suppressed_emails"`+ FailureRate float64 `json:"failure_rate"`+ TotalAPIKeys int64 `json:"total_api_keys"`+ ActiveAPIKeys int64 `json:"active_api_keys"`+ TotalBounces int64 `json:"total_bounces"`+ TotalSuppressions int64 `json:"total_suppressions"`+ ActiveWorkers int `json:"active_workers"`+ SharedSmtpServers int64 `json:"shared_smtp_servers"`+ TotalDomains int64 `json:"total_domains"`+ TotalWorkspaces int64 `json:"total_workspaces"`+ WebhookDeliveries *repositories.WebhookDeliveryStats `json:"webhook_deliveries"`+ ServerUptime float64 `json:"server_uptime_seconds"`+ CurrentGoroutines int `json:"current_goroutines"`+ CurrentMemoryUsage uint64 `json:"current_memory_usage"`++ // Security+ ActiveSessions int64 `json:"active_sessions"`+ FailedLoginsLast24h int64 `json:"failed_logins_last_24h"`+ TwoFactorAdoptionRate float64 `json:"two_factor_adoption_rate"`+ TwoFactorUsers int64 `json:"two_factor_users"`}+// processStartTime records when the process started, for uptime reporting.+var processStartTime = time.Now()+type AdminRevokeKeyRequest struct {ID int `param:"id"`}@@ -326,6 +339,7 @@ func (h *AdminHandler) Metrics(c *okapi.Context) error {m.ActiveWorkers = len(servers)}}+ fillRuntimeStats(&m)return ok(c, m)}@@ -359,11 +373,30 @@ func (h *AdminHandler) Metrics(c *okapi.Context) error {m.WebhookDeliveries = whStats}+ // Security stats+ now := time.Now()+ h.db.Model(&models.Session{}).Where("revoked = false AND expires_at > ?", now).Count(&m.ActiveSessions)+ h.db.Model(&models.Event{}).Where("type = ? AND created_at > ?", "user.login_failed", now.Add(-24*time.Hour)).Count(&m.FailedLoginsLast24h)+ h.db.Model(&models.User{}).Where("two_factor_enabled = ? AND active = ?", true, true).Count(&m.TwoFactorUsers)+ if m.TotalUsers > 0 {+ m.TwoFactorAdoptionRate = float64(m.TwoFactorUsers) / float64(m.TotalUsers) * 100+ }+h.cache.Set(ctx, cacheKey, m, cache.AdminMetricsTTL)+ fillRuntimeStats(&m)+return ok(c, m)}+func fillRuntimeStats(m *PlatformMetrics) {+ m.ServerUptime = time.Since(processStartTime).Seconds()+ m.CurrentGoroutines = runtime.NumGoroutine()+ var ms runtime.MemStats+ runtime.ReadMemStats(&ms)+ m.CurrentMemoryUsage = ms.Alloc+}+// UserMetrics returns detailed metrics for a specific user (admin only).func (h *AdminHandler) UserMetrics(c *okapi.Context, req *AdminGetUserRequest) error {ctx := c.Request().Context()@@ -531,6 +564,22 @@ type WorkerStatus struct {Workers []WorkerDetail `json:"workers"`}+type SystemStatus struct {+ ServerUptime float64 `json:"server_uptime_seconds"`+ CurrentGoroutines int `json:"current_goroutines"`+ CurrentMemoryUsage uint64 `json:"current_memory_usage"`+}++func buildSystemStatus() SystemStatus {+ var ms runtime.MemStats+ runtime.ReadMemStats(&ms)+ return SystemStatus{+ ServerUptime: time.Since(processStartTime).Seconds(),+ CurrentGoroutines: runtime.NumGoroutine(),+ CurrentMemoryUsage: ms.Alloc,+ }+}+// WorkerDetail holds info about a single connected worker.type WorkerDetail struct {Host string `json:"host"`@@ -539,20 +588,27 @@ type WorkerDetail struct {Type string `json:"type"` // "embedded" or "standalone"}-// WorkerStream sends real-time worker status updates via SSE.-func (h *AdminHandler) WorkerStream(c *okapi.Context) error {+// MetricsStream sends real-time platform metrics updates via SSE+func (h *AdminHandler) MetricsStream(c *okapi.Context) error {ctx := c.Request().Context()w := c.ResponseWriter()sendStatus := func() error {- status := h.buildWorkerStatus()- msg := okapi.Message{+ workerMsg := okapi.Message{Event: "worker.status",- Data: status,+ Data: h.buildWorkerStatus(),+ Serializer: &okapi.JSONSerializer{},+ }+ if _, err := workerMsg.Send(w); err != nil {+ return err+ }+ systemMsg := okapi.Message{+ Event: "system.status",+ Data: buildSystemStatus(),Serializer: &okapi.JSONSerializer{},}- if _, err := msg.Send(w); err != nil {+ if _, err := systemMsg.Send(w); err != nil {return err}return nildiff --git a/internal/handlers/user_handler.go b/internal/handlers/user_handler.goindex 55340db..e862fae 100644--- a/internal/handlers/user_handler.go+++ b/internal/handlers/user_handler.go@@ -288,17 +288,29 @@ func (h *UserHandler) ChangePassword(c *okapi.Context, req *ChangePasswordRequesreturn ok(c, okapi.M{"message": "password updated successfully"})}+func (h *UserHandler) publishLoginFailed(actorID *uint, email, ip, reason string) {+ if h.bus == nil {+ return+ }+ h.bus.PublishSimple(models.EventCategoryUser, "user.login_failed", actorID, email, ip,+ fmt.Sprintf("Failed login attempt for %q (%s)", email, reason),+ map[string]any{"reason": reason})+}+func (h *UserHandler) Login(c *okapi.Context, req *LoginRequest) error {user, err := h.repo.FindByEmail(req.Body.Email)if err != nil {+ h.publishLoginFailed(nil, req.Body.Email, c.RealIP(), "unknown_email")return c.AbortUnauthorized("invalid credentials")}if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Body.Password)); err != nil {+ h.publishLoginFailed(&user.ID, user.Email, c.RealIP(), "bad_password")return c.AbortUnauthorized("invalid credentials")}if !user.Active {+ h.publishLoginFailed(&user.ID, user.Email, c.RealIP(), "inactive")return c.AbortForbidden("account is disabled")}@@ -314,6 +326,7 @@ func (h *UserHandler) Login(c *okapi.Context, req *LoginRequest) error {})}if !twofactor.ValidateCode(user.TwoFactorSecret, req.Body.TwoFactorCode) {+ h.publishLoginFailed(&user.ID, user.Email, c.RealIP(), "bad_2fa")return c.AbortUnauthorized("invalid 2FA code")}}diff --git a/internal/routes/admin_routes.go b/internal/routes/admin_routes.goindex 7a2b81b..9f0896b 100644--- a/internal/routes/admin_routes.go+++ b/internal/routes/admin_routes.go@@ -491,11 +491,11 @@ func (r *Router) adminSSERoutes() []okapi.RouteDefinition {},{Method: http.MethodGet,- Path: "/workers/stream",- Handler: r.h.admin.WorkerStream,+ Path: "/metrics/stream",+ Handler: r.h.admin.MetricsStream,Group: adminSSE,- Summary: "Stream worker status (SSE)",- Description: "Real-time worker count and details via Server-Sent Events. Pass JWT token as ?token= query parameter.",+ Summary: "Stream platform metrics (SSE)",+ Description: "Real-time worker status and system runtime stats via Server-Sent Events. Emits worker.status and system.status events. Pass JWT token as ?token= query parameter.",Options: []okapi.RouteOption{okapi.DocHide()},},}diff --git a/web/src/api/types.ts b/web/src/api/types.tsindex 94de1b0..bf281a5 100644--- a/web/src/api/types.ts+++ b/web/src/api/types.ts@@ -413,6 +413,13 @@ export interface AdminMetrics {total_domains: numbertotal_workspaces: numberwebhook_deliveries: WebhookDeliveryStats | null+ server_uptime_seconds: number+ current_goroutines: number+ current_memory_usage: number+ active_sessions: number+ failed_logins_last_24h: number+ two_factor_adoption_rate: number+ two_factor_users: number}export interface WorkerStatus {@@ -420,6 +427,12 @@ export interface WorkerStatus {workers: WorkerDetail[]}+export interface SystemStatus {+ server_uptime_seconds: number+ current_goroutines: number+ current_memory_usage: number+}+export interface WorkerDetail {host: stringpid: numberdiff --git a/web/src/views/admin/Metrics.vue b/web/src/views/admin/Metrics.vueindex 9f9a260..7b8cf1f 100644--- a/web/src/views/admin/Metrics.vue+++ b/web/src/views/admin/Metrics.vue@@ -3,7 +3,7 @@ import { ref, computed, onMounted, onBeforeUnmount } from 'vue'import { adminApi } from '../../api/admin'import { analyticsApi } from '../../api/analytics'import { useAuthStore } from '../../stores/auth'-import type { AdminMetrics, WorkerStatus, AnalyticsResponse, DashboardAnalyticsResponse } from '../../api/types'+import type { AdminMetrics, WorkerStatus, SystemStatus, AnalyticsResponse, DashboardAnalyticsResponse } from '../../api/types'const auth = useAuthStore()const loading = ref(true)@@ -39,7 +39,7 @@ function startWorkerStream() {const baseUrl = import.meta.env.VITE_API_URL || '/api/v1'const token = auth.tokenif (!token) return- const url = `${baseUrl}/admin/workers/stream?token=${encodeURIComponent(token)}`+ const url = `${baseUrl}/admin/metrics/stream?token=${encodeURIComponent(token)}`workerSSE = new EventSource(url)workerSSE.addEventListener('worker.status', (e) => {@@ -54,6 +54,19 @@ function startWorkerStream() {}})+ workerSSE.addEventListener('system.status', (e) => {+ try {+ const status: SystemStatus = JSON.parse((e as MessageEvent).data)+ if (metrics.value) {+ metrics.value.server_uptime_seconds = status.server_uptime_seconds+ metrics.value.current_goroutines = status.current_goroutines+ metrics.value.current_memory_usage = status.current_memory_usage+ }+ } catch {+ // ignore parse errors+ }+ })+workerSSE.onerror = () => {// Connection lost; will auto-reconnect via EventSource}@@ -84,6 +97,12 @@ function failureColor(rate: number): string {return 'var(--danger-600, #dc2626)'}+function failedLoginColor(count: number): string {+ if (count === 0) return 'var(--success-600, #16a34a)'+ if (count < 10) return 'var(--warning-600, #ca8a04)'+ return 'var(--danger-600, #dc2626)'+}+// Analytics helpersconst maxDailyCount = computed(() => {if (!analytics.value?.daily_counts?.length) return 1@@ -144,6 +163,31 @@ function formatLatency(seconds: number): string {return `${(seconds / 60).toFixed(1)}m`}+function formatUptime(seconds: number): string {+ if (!seconds || seconds < 0) return '—'+ const s = Math.floor(seconds)+ const days = Math.floor(s / 86400)+ const hours = Math.floor((s % 86400) / 3600)+ const minutes = Math.floor((s % 3600) / 60)+ const secs = s % 60+ if (days > 0) return `${days}d ${hours}h ${minutes}m`+ if (hours > 0) return `${hours}h ${minutes}m`+ if (minutes > 0) return `${minutes}m ${secs}s`+ return `${secs}s`+}++function formatBytes(bytes: number): string {+ if (!bytes || bytes < 0) return '—'+ const units = ['B', 'KB', 'MB', 'GB', 'TB']+ let i = 0+ let n = bytes+ while (n >= 1024 && i < units.length - 1) {+ n /= 1024+ i+++ }+ return `${n.toFixed(n >= 100 || i === 0 ? 0 : 1)} ${units[i]}`+}+const avgDeliveryRate = computed(() => {if (!dashAnalytics.value) return 0const points = dashAnalytics.value.delivery_rate_trends.filter(d => d.total > 0)@@ -225,6 +269,38 @@ const avgDeliveryRate = computed(() => {</div></div>+ <!-- System -->+ <div class="metrics-section-label">System Status</div>+ <div class="stats-grid">+ <div class="stat-card">+ <div class="stat-header">+ <div class="stat-label">Server Uptime</div>+ <div class="stat-icon stat-icon-success">+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>+ </div>+ </div>+ <div class="stat-value">{{ formatUptime(metrics.server_uptime_seconds) }}</div>+ </div>+ <div class="stat-card">+ <div class="stat-header">+ <div class="stat-label">Current Goroutines</div>+ <div class="stat-icon stat-icon-info">+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>+ </div>+ </div>+ <div class="stat-value">{{ metrics.current_goroutines.toLocaleString() }}</div>+ </div>+ <div class="stat-card">+ <div class="stat-header">+ <div class="stat-label">Current Memory Usage</div>+ <div class="stat-icon stat-icon-primary">+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="4" width="16" height="16" rx="2"/><rect x="9" y="9" width="6" height="6"/><line x1="9" y1="2" x2="9" y2="4"/><line x1="15" y1="2" x2="15" y2="4"/><line x1="9" y1="20" x2="9" y2="22"/><line x1="15" y1="20" x2="15" y2="22"/><line x1="20" y1="9" x2="22" y2="9"/><line x1="20" y1="14" x2="22" y2="14"/><line x1="2" y1="9" x2="4" y2="9"/><line x1="2" y1="14" x2="4" y2="14"/></svg>+ </div>+ </div>+ <div class="stat-value">{{ formatBytes(metrics.current_memory_usage) }}</div>+ <div class="stat-sub">heap allocated</div>+ </div>+ </div><!-- Worker Details --><template v-if="workerStatus && workerStatus.workers.length > 0"><div class="metrics-section-label">Workers</div>@@ -260,6 +336,39 @@ const avgDeliveryRate = computed(() => {</div></template>+ <!-- Security -->+ <div class="metrics-section-label">Security</div>+ <div class="stats-grid">+ <div class="stat-card">+ <div class="stat-header">+ <div class="stat-label">Active Sessions</div>+ <div class="stat-icon stat-icon-primary">+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>+ </div>+ </div>+ <div class="stat-value">{{ metrics.active_sessions.toLocaleString() }}</div>+ </div>+ <div class="stat-card">+ <div class="stat-header">+ <div class="stat-label">Failed Logins (24h)</div>+ <div class="stat-icon" :class="metrics.failed_logins_last_24h > 0 ? 'stat-icon-warning' : 'stat-icon-success'">+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 9.9-1"/></svg>+ </div>+ </div>+ <div class="stat-value" :style="{ color: failedLoginColor(metrics.failed_logins_last_24h) }">{{ metrics.failed_logins_last_24h.toLocaleString() }}</div>+ </div>+ <div class="stat-card">+ <div class="stat-header">+ <div class="stat-label">2FA Adoption</div>+ <div class="stat-icon" :class="metrics.two_factor_adoption_rate >= 50 ? 'stat-icon-success' : 'stat-icon-warning'">+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="m9 12 2 2 4-4"/></svg>+ </div>+ </div>+ <div class="stat-value">{{ metrics.two_factor_adoption_rate.toFixed(1) }}%</div>+ <div class="stat-sub">{{ metrics.two_factor_users }} of {{ metrics.total_users }} users</div>+ </div>+ </div>+<!-- Email Delivery --><div class="metrics-section-label">Email Delivery</div><div class="stats-grid">