Files
OwnCord/Server/plugin/plugin_test.go
T
Claude a2cb224323 feat: scaffold Phase B + C (events, telemetry, plugins, Solid.js)
Phase B Step 6 — Solid.js incremental migration
  - vite-plugin-solid + solid-js + @solidjs/testing-library in package.json
  - vite.config.ts compiles src/components/solid/** as Solid TSX
  - tsconfig.json gains jsx: preserve / jsxImportSource: solid-js
  - lib/solidAdapter.ts wraps existing custom Stores as Solid signals
  - lib/solidMount.ts adapts Solid render to {mount,destroy} contract
  - components/solid/Badge.tsx (proof-of-concept leaf)
  - components/solid/ChannelListItem.tsx (store-subscribed leaf)
  - components/solid/Badge.test.tsx pipeline smoke test
  - components/solid/README.md documents the migration recipe

Phase B Step 7 — Event persistence layer
  - SQLite + Postgres migrations for the events table
  - sqlc query files for both engines
  - EventStore interface + SQLite raw-SQL impl + MemStore impl + pg stubs
  - ws.EventPersister: async batched writer (queue / flush / drain / drop)
  - ws.StartEventPruner: background retention pruner
  - hub persists every replay-buffer push and exposes reconnect-tier counters
  - serve.handleReconnect: tiered replay (buffer -> DB -> full re-sync)
  - EventPersistenceConfig + main.go wiring
  - event_persister_test.go covers batching / drops / drain

Phase B Step 8 — OpenTelemetry skeleton
  - Server/telemetry package with public Provider/Tracer/Meter/Counter API
  - telemetry_default.go (no-op build) + telemetry_otel.go (build tag otel)
  - telemetry/metrics.go declares the AppMetrics bundle
  - HTTPMiddleware mounted in Chi router (pass-through in default build)
  - PrometheusHandler optionally mounted at /metrics
  - Spans on MessageService.SendMessage, PermissionService.HasChannelPerm,
    ChannelService.ListVisibleChannels
  - Reconnect-tier counter wired into the global meter
  - TelemetryConfig defaults

Phase C Step 9 — Wazero plugin runtime skeleton
  - Server/plugin package: manifest parser, loader, registry, host APIs
    (commands, storage, events, http, ui), errors
  - sandbox_default.go (no-op) + sandbox_wazero.go (build tag wazero)
  - SQLite + Postgres migrations for plugins + plugin_kv tables
  - PluginStore interface + impls + pg stubs
  - plugin/examples/hello manifest + README
  - plugin_test.go covers manifest, loader, capability gating
  - api/plugins_handler.go admin REST surface, mounted under admin group
  - PluginsConfig + main.go wiring (disabled by default)
  - Client: lib/pluginBridge.ts iframe + postMessage host
  - Client: components/solid/PluginContainer.tsx Solid host component

Verification
  - Default build (no -tags) is intended to compile cleanly with no new
    third-party dependencies. The sandbox lacked Go 1.25.0 so go build
    could not run; PHASE_BC_LOCAL_TODO.md enumerates the local follow-up
    work (npm install, go mod tidy, sqlc-generate, real otel/wazero
    wiring, remaining service spans, full Solid migration).
2026-04-06 09:00:47 +00:00

149 lines
4.6 KiB
Go

// Phase C Step 9 — manifest + loader tests.
//
// These tests cover the default-build code path (no wazero). They confirm:
// - the JSON manifest parses and validates,
// - the loader walks a directory and surfaces well-formed plugins,
// - the registry persists discovered plugins into a PluginStore,
// - per-capability gating refuses calls when the manifest didn't grant them.
//
// Wazero-specific tests live in sandbox_wazero_test.go and only run with the
// `wazero` build tag.
package plugin
import (
"context"
"os"
"path/filepath"
"testing"
"github.com/owncord/server/store"
)
func TestParseManifestRoundTrip(t *testing.T) {
raw := []byte(`{
"name": "hello",
"version": "0.1.0",
"entrypoint": "hello.wasm",
"permissions": ["commands", "storage"],
"resources": {"max_memory_mb": 16, "cpu_budget_ms": 50}
}`)
m, err := ParseManifest(raw)
if err != nil {
t.Fatalf("ParseManifest: %v", err)
}
if m.Name != "hello" || m.Version != "0.1.0" {
t.Fatalf("unexpected manifest fields: %+v", m)
}
if !m.HasCapability(CapCommands) {
t.Fatal("expected commands capability")
}
if m.HasCapability(CapHTTP) {
t.Fatal("did not expect http capability")
}
}
func TestParseManifestRejectsBadEntrypoint(t *testing.T) {
cases := map[string]string{
"missing entrypoint": `{"name":"x","version":"1","entrypoint":""}`,
"non-wasm entrypoint": `{"name":"x","version":"1","entrypoint":"x.so"}`,
"unknown capability": `{"name":"x","version":"1","entrypoint":"x.wasm","permissions":["badperm"]}`,
"missing version": `{"name":"x","entrypoint":"x.wasm"}`,
"missing name": `{"version":"1","entrypoint":"x.wasm"}`,
}
for label, body := range cases {
t.Run(label, func(t *testing.T) {
if _, err := ParseManifest([]byte(body)); err == nil {
t.Fatalf("expected error for %s", label)
}
})
}
}
func TestScanPluginDirectoryHandlesMissing(t *testing.T) {
got, err := scanPluginDirectory(filepath.Join(t.TempDir(), "does-not-exist"))
if err != nil {
t.Fatalf("scanPluginDirectory: %v", err)
}
if len(got) != 0 {
t.Fatalf("expected empty result, got %d", len(got))
}
}
func TestScanPluginDirectoryParsesValidPlugin(t *testing.T) {
dir := t.TempDir()
pluginDir := filepath.Join(dir, "hello")
if err := os.MkdirAll(pluginDir, 0o755); err != nil {
t.Fatal(err)
}
manifest := `{"name":"hello","version":"0.1.0","entrypoint":"hello.wasm","permissions":["storage"]}`
if err := os.WriteFile(filepath.Join(pluginDir, "plugin.json"), []byte(manifest), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(pluginDir, "hello.wasm"), []byte("\x00asm\x01\x00\x00\x00"), 0o644); err != nil {
t.Fatal(err)
}
got, err := scanPluginDirectory(dir)
if err != nil {
t.Fatalf("scanPluginDirectory: %v", err)
}
if len(got) != 1 || got[0].Manifest.Name != "hello" {
t.Fatalf("unexpected scan result: %+v", got)
}
}
func TestRegistryInstallFromDisk(t *testing.T) {
dir := t.TempDir()
pluginDir := filepath.Join(dir, "hello")
_ = os.MkdirAll(pluginDir, 0o755)
_ = os.WriteFile(filepath.Join(pluginDir, "plugin.json"),
[]byte(`{"name":"hello","version":"0.1.0","entrypoint":"hello.wasm","permissions":["storage"]}`),
0o644)
_ = os.WriteFile(filepath.Join(pluginDir, "hello.wasm"), []byte("\x00asm\x01\x00\x00\x00"), 0o644)
mem := store.NewMemStore()
reg, err := NewRegistry(Config{Directory: dir, Store: mem})
if err != nil {
t.Fatal(err)
}
if err := reg.LoadAll(context.Background()); err != nil {
t.Fatalf("LoadAll: %v", err)
}
rows, err := mem.ListPlugins(context.Background())
if err != nil {
t.Fatal(err)
}
if len(rows) != 1 || rows[0].Name != "hello" {
t.Fatalf("expected hello plugin row, got %+v", rows)
}
}
func TestStorageGatedByCapability(t *testing.T) {
mem := store.NewMemStore()
reg, err := NewRegistry(Config{Store: mem})
if err != nil {
t.Fatal(err)
}
inst := &Instance{
ID: 1,
Manifest: &Manifest{Name: "x", Permissions: []string{}},
}
if err := reg.StoragePut(context.Background(), inst, "k", []byte("v")); err == nil {
t.Fatal("expected ErrCapabilityNotGranted")
}
inst.Manifest.Permissions = []string{string(CapStorage)}
// Pre-create the plugin row so the KV foreign-key-equivalent succeeds.
if _, err := mem.InstallPlugin(context.Background(), "x", "0.1", "{}"); err != nil {
t.Fatal(err)
}
if err := reg.StoragePut(context.Background(), inst, "k", []byte("v")); err != nil {
t.Fatalf("StoragePut: %v", err)
}
got, err := reg.StorageGet(context.Background(), inst, "k")
if err != nil {
t.Fatalf("StorageGet: %v", err)
}
if string(got) != "v" {
t.Fatalf("expected v, got %q", got)
}
}