mirror of
https://github.com/J3vb/OwnCord.git
synced 2026-09-03 03:50:00 +03:00
Phase B Step 8 (OpenTelemetry) and Phase C Step 9 (Wazero plugin runtime)
were structurally scaffolded but the tagged builds were placeholders that
errored at runtime. This commit lands the real implementations behind the
existing build tags, plus three review passes worth of fixes across the
plugin admin handler, plugin registry, telemetry adapter, and Solid client.
Telemetry (Phase B Step 8)
- Add real go.opentelemetry.io/otel{,/sdk,/exporters/{prometheus,otlp...}}
modules to go.mod plus contrib/instrumentation/net/http/otelhttp.
- Replace the telemetry_otel.go skeleton with a working Provider that
wires Prometheus + OTLP/gRPC exporters, otelhttp middleware, span and
meter adapters, and an idempotent Shutdown.
- AppMetrics cache is now reset *before* SetGlobal to close a race where
a concurrent NewAppMetrics() could observe a swapped provider but read
stale no-op instruments.
- Init releases the trace provider on a later prometheus exporter
failure so Init never leaks gRPC connections.
- convertAttrs handles int32/uint/uint32/uint64/float32 explicitly;
uint64 values that exceed math.MaxInt64 fall back to a STRING attr
rather than wrapping into a negative int64 and corrupting metrics.
- Tests under -tags otel cover the prometheus scrape, span lifecycle,
histogram recording, shutdown idempotency, AppMetrics rebind, and
the uint64 overflow fallback.
Plugin runtime (Phase C Step 9)
- Add github.com/tetratelabs/wazero v1.11.0 to go.mod.
- platformInit creates a shared wazero.Runtime with WASI preview1
pre-instantiated; activateWithRuntime compiles + instantiates each
plugin module under that runtime; platformDeactivate closes per-
plugin modules without tearing down the runtime.
- DisablePlugin now calls platformDeactivate so the wazero module is
freed immediately instead of leaking until registry Close.
- activate() captures runtimePlatform under r.mu.RLock and passes it as
a parameter to activateWithRuntime; the call no longer re-reads the
field, closing a race with concurrent Close.
- invokeCommand calls the plugin's command_dispatch export when
present; missing/broken exports return a user-facing diagnostic
instead of crashing the dispatcher.
- Tests under -tags wazero cover registry creation, module compilation,
re-enable after disable (verifies the leak fix), close-twice safety,
invalid wasm rejection, and DispatchCommand with a missing export.
Fixture is a 41-byte embedded add.wasm; no external asset required.
Plugin admin handler hardening
- /api/v1/admin/plugins/install now rejects uploads whose multipart
Content-Type is not application/zip|x-zip-compressed|octet-stream
(415) and uploads whose body lacks the PK\\x03\\x04 / PK\\x05\\x06
zip magic (400). The 16 MiB cap and registry-side zip-slip / symlink
/ size-bomb defences are still applied as before.
- New plugins_handler_test.go covers list-empty, install-503-when-nil,
content-type rejection, magic rejection, happy path, lifecycle 503,
invalid id, and isZipContentType / hasZipMagic helpers.
Solid client (Phase B Step 6) cleanup
- vitest.config.ts now wires vite-plugin-solid and broadens the test
glob to include src/**/*.test.tsx so Badge.test.tsx is actually
discovered (it was silently skipped).
- pluginBridge.ts targets postMessage at window.location.origin
instead of "*", and exposes a destroy() that detaches the message
listener and clears mounted frames.
- solidMount.ts imports the JSX type from "solid-js" instead of
"solid-js/web" (the latter does not re-export it), unblocking
npx tsc --noEmit.
Build/test status
- go build succeeds on default, -tags otel, -tags wazero, and
-tags otel,wazero.
- go test passes on every tag combination across telemetry, plugin,
api, ws, service, store, and the rest of the tree.
- Client: npx tsc --noEmit clean; vitest 3188/3188 across 112 files.
PHASE_BC_LOCAL_TODO.md is updated to mark the OTel modules + real Init,
the wazero module + real platformInit, and the test coverage that
landed in this commit as completed.
https://claude.ai/code/session_01AZni6CDSQeu67WSWY1YCDX
80 lines
3.5 KiB
Go
80 lines
3.5 KiB
Go
// Phase B Step 8 — declared application metrics.
|
|
//
|
|
// Instruments are constructed lazily against the global Provider so callers
|
|
// don't need to thread a Meter through every constructor. Hot-path callers
|
|
// should cache the returned instrument in a struct field rather than calling
|
|
// these helpers per request — they take a sync.RWMutex to read the global
|
|
// provider and the cost adds up at high throughput.
|
|
package telemetry
|
|
|
|
import "sync"
|
|
|
|
const (
|
|
scopeWS = "github.com/owncord/server/ws"
|
|
scopeService = "github.com/owncord/server/service"
|
|
scopeDB = "github.com/owncord/server/db"
|
|
scopeVoice = "github.com/owncord/server/voice"
|
|
)
|
|
|
|
// AppMetrics is the canonical bundle of meters used across the server. Build
|
|
// it once at startup with NewAppMetrics() and stash it on the relevant
|
|
// long-lived structs (Hub, services, etc).
|
|
type AppMetrics struct {
|
|
WSMessagesTotal Counter
|
|
WSActiveConnections Gauge
|
|
WSBroadcastLatency Histogram
|
|
WSReconnectTierTotal Counter
|
|
WSEventsPersisted Counter
|
|
WSEventsDropped Counter
|
|
WSEventsPersistErrors Counter
|
|
DBQueryDurationSec Histogram
|
|
VoiceActiveSessions Gauge
|
|
VoiceParticipants Gauge
|
|
ServiceCallDurationSec Histogram
|
|
}
|
|
|
|
var (
|
|
appMetricsMu sync.Mutex
|
|
appMetricsInst *AppMetrics
|
|
)
|
|
|
|
// NewAppMetrics returns a process-wide AppMetrics, lazily constructed against
|
|
// the current global provider. Calling it multiple times returns the same
|
|
// instance until resetAppMetricsForInit() is called (which Init uses after
|
|
// swapping the global provider so instruments re-bind to the new meter).
|
|
func NewAppMetrics() *AppMetrics {
|
|
appMetricsMu.Lock()
|
|
defer appMetricsMu.Unlock()
|
|
if appMetricsInst != nil {
|
|
return appMetricsInst
|
|
}
|
|
ws := GlobalMeter(scopeWS)
|
|
svc := GlobalMeter(scopeService)
|
|
db := GlobalMeter(scopeDB)
|
|
voice := GlobalMeter(scopeVoice)
|
|
appMetricsInst = &AppMetrics{
|
|
WSMessagesTotal: ws.Counter("ws_messages_total", "WebSocket messages broadcast"),
|
|
WSActiveConnections: ws.Gauge("ws_active_connections", "Currently connected WebSocket clients"),
|
|
WSBroadcastLatency: ws.Histogram("ws_broadcast_latency_seconds", "Wall-clock seconds from enqueue to fanout completion", "s"),
|
|
WSReconnectTierTotal: ws.Counter("ws_reconnect_tier_total", "Reconnection replay tier hits, attribute tier=buffer|db|full"),
|
|
WSEventsPersisted: ws.Counter("ws_events_persisted_total", "Events written to the cold-tier event log"),
|
|
WSEventsDropped: ws.Counter("ws_events_dropped_total", "Events dropped because the persister queue was full"),
|
|
WSEventsPersistErrors: ws.Counter("ws_events_persist_errors_total", "PersistEvent calls that returned an error from the underlying store"),
|
|
DBQueryDurationSec: db.Histogram("db_query_duration_seconds", "Per-query wall time", "s"),
|
|
VoiceActiveSessions: voice.Gauge("voice_active_sessions", "Active LiveKit rooms"),
|
|
VoiceParticipants: voice.Gauge("voice_participants", "Connected LiveKit participants across all rooms"),
|
|
ServiceCallDurationSec: svc.Histogram("service_call_duration_seconds", "Service-layer method execution time", "s"),
|
|
}
|
|
return appMetricsInst
|
|
}
|
|
|
|
// resetAppMetricsForInit drops the cached AppMetrics bundle so the next
|
|
// NewAppMetrics() call re-binds instruments against whatever provider is now
|
|
// global. The real OTel Init uses this to migrate from the no-op provider
|
|
// installed by the package-level init() to the SDK-backed one.
|
|
func resetAppMetricsForInit() {
|
|
appMetricsMu.Lock()
|
|
defer appMetricsMu.Unlock()
|
|
appMetricsInst = nil
|
|
}
|