Skip to content

Take control over your live stream video by running it yourself. Streaming + chat out of the box.

feat(plugins): namespace custom event hooks (#5119)

Gabe Kangas6691f16a5e23
diff --git a/docs/plugins.md b/docs/plugins.md
index 2e85086280..af280b7810 100644
--- a/docs/plugins.md
+++ b/docs/plugins.md
@@ -145,8 +145,12 @@ Owncast and plugins communicate through a shared dispatcher
- For chat, `pluginhost` registers a **filter** (`newPluginChatFilter`) so
plugins' `filterChatMessage` handlers run on inbound messages before they're
broadcast (redact, drop, rewrite).
-- Plugins can also **emit** custom events to each other; `env.Emit` is wired to
- the runtime's live dispatcher after the manager starts.
+- Plugins can also **emit** custom events to each other. The manager prefixes
+ each custom notification hook with its declaring plugin's slug, so a plugin
+ declaring `foo` owns `<slug>.foo`. Emitters target that fully qualified name.
+ The dispatcher removes the owner prefix before calling the plugin's local
+ handler. A custom hook that would collide with a built-in event is rejected.
+ `env.Emit` is wired to the runtime's live dispatcher after the manager starts.
## Lifecycle, persistence, and HTTP
diff --git a/services/plugins/custom_event_namespacing_test.go b/services/plugins/custom_event_namespacing_test.go
new file mode 100644
index 0000000000..7ec6ce53ff
--- /dev/null
+++ b/services/plugins/custom_event_namespacing_test.go
@@ -0,0 +1,94 @@
+package plugins
+
+import (
+ "context"
+ "strings"
+ "testing"
+)
+
+func TestCustomEventHooksBelongToDeclaringPlugin(t *testing.T) {
+ ctx := context.Background()
+ compiledEngines.resetForTest(ctx)
+ t.Cleanup(func() { compiledEngines.resetForTest(ctx) })
+
+ env, sends, mu := captureEnv()
+ emitter := loadShared(t, ctx, env, RuntimeJavaScript, "emitter", `
+const { definePlugin, owncast } = require("@owncast/plugin-sdk");
+module.exports = definePlugin({
+ onChatMessage() { owncast.events.emit("plugin-one.foo", {}); }
+});`, []string{PermEmitEvent})
+ defer emitter.Close(ctx)
+
+ pluginOne := loadShared(t, ctx, env, RuntimeJavaScript, "plugin-one", `
+const { definePlugin, owncast } = require("@owncast/plugin-sdk");
+module.exports = definePlugin({
+ on: { foo() { owncast.chat.send("plugin-one"); } }
+});`, []string{PermChatSend})
+ defer pluginOne.Close(ctx)
+
+ pluginTwo := loadShared(t, ctx, env, RuntimeJavaScript, "plugin-two", `
+const { definePlugin, owncast } = require("@owncast/plugin-sdk");
+module.exports = definePlugin({
+ on: { "plugin-one.foo"() { owncast.chat.send("plugin-two"); } }
+});`, []string{PermChatSend})
+ defer pluginTwo.Close(ctx)
+
+ if !subscribed(pluginOne.Manifest.Subscriptions.Notify, "plugin-one.foo") {
+ t.Fatalf("plugin-one subscriptions = %+v", pluginOne.Manifest.Subscriptions.Notify)
+ }
+ if subscribed(pluginTwo.Manifest.Subscriptions.Notify, "plugin-one.foo") ||
+ !subscribed(pluginTwo.Manifest.Subscriptions.Notify, "plugin-two.plugin-one.foo") {
+ t.Fatalf("plugin-two subscriptions = %+v", pluginTwo.Manifest.Subscriptions.Notify)
+ }
+
+ d := NewLiveDispatcher(func() []*Loaded { return []*Loaded{emitter, pluginOne, pluginTwo} })
+ env.Emit = d.Dispatch
+ d.Dispatch(ctx, EventChatMessageReceived, chatPayload("alice", "run"))
+
+ mu.Lock()
+ if len(*sends) != 1 || (*sends)[0].Text != "plugin-one" {
+ t.Fatalf("plugin-one.foo deliveries = %+v", *sends)
+ }
+ *sends = nil
+ mu.Unlock()
+
+ // The attempted squat is still a valid hook, but only under plugin-two's
+ // own namespace.
+ d.Dispatch(ctx, "plugin-two.plugin-one.foo", map[string]any{})
+ mu.Lock()
+ defer mu.Unlock()
+ if len(*sends) != 1 || (*sends)[0].Text != "plugin-two" {
+ t.Fatalf("plugin-two.plugin-one.foo deliveries = %+v", *sends)
+ }
+}
+
+func TestCustomEventHookCannotCollideWithBuiltIn(t *testing.T) {
+ subs := Subscriptions{Notify: []Subscription{{Event: "message.received"}}}
+ if err := namespaceCustomSubscriptions("chat", &subs); err == nil ||
+ !strings.Contains(err.Error(), EventChatMessageReceived) {
+ t.Fatalf("expected %q collision, got %v", EventChatMessageReceived, err)
+ }
+}
+
+func TestBuiltInSubscriptionKeepsCanonicalName(t *testing.T) {
+ ctx := context.Background()
+ compiledEngines.resetForTest(ctx)
+ t.Cleanup(func() { compiledEngines.resetForTest(ctx) })
+
+ env, sends, mu := captureEnv()
+ loaded := loadShared(t, ctx, env, RuntimeJavaScript, "chat", `
+const { definePlugin, owncast } = require("@owncast/plugin-sdk");
+module.exports = definePlugin({
+ onChatMessage() { owncast.chat.send("received"); }
+});`, []string{PermChatSend})
+ defer loaded.Close(ctx)
+
+ d := NewLiveDispatcher(func() []*Loaded { return []*Loaded{loaded} })
+ d.Dispatch(ctx, EventChatMessageReceived, chatPayload("alice", "run"))
+
+ mu.Lock()
+ defer mu.Unlock()
+ if len(*sends) != 1 || (*sends)[0].Text != "received" {
+ t.Fatalf("%s deliveries for chat slug = %+v", EventChatMessageReceived, *sends)
+ }
+}
diff --git a/services/plugins/dispatcher.go b/services/plugins/dispatcher.go
index 7d035e9055..d2d393042c 100644
--- a/services/plugins/dispatcher.go
+++ b/services/plugins/dispatcher.go
@@ -7,6 +7,7 @@ import (
"fmt"
"os"
"sort"
+ "strings"
"sync"
"time"
)
@@ -240,8 +241,17 @@ func (d *Dispatcher) Notify(ctx context.Context, eventType string, payload any)
// not receive its own in-call emission.
continue
}
+ input := encoded
+ if !reservedEventTypes[eventType] {
+ localEventType := strings.TrimPrefix(eventType, p.Manifest.Slug+".")
+ input, err = json.Marshal(Envelope{EventType: localEventType, Payload: payload})
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "dispatcher: marshal envelope for %s: %v\n", eventType, err)
+ continue
+ }
+ }
wg.Add(1)
- go func(p *Loaded) {
+ go func(p *Loaded, input []byte) {
defer wg.Done()
// A plugin must never take down the host. A panic in this goroutine
// can't be recovered by the caller, so recover it here.
@@ -250,11 +260,11 @@ func (d *Dispatcher) Notify(ctx context.Context, eventType string, payload any)
fmt.Fprintf(os.Stderr, "plugin %s: on_event(%s) panicked: %v\n", p.Manifest.Slug, eventType, rec)
}
}()
- if err := callOnEvent(ctx, p, encoded); err != nil &&
+ if err := callOnEvent(ctx, p, input); err != nil &&
!errors.Is(err, errPluginNotLoaded) && !errors.Is(err, errPluginNoSuchExport) {
fmt.Fprintf(os.Stderr, "plugin %s: on_event(%s) failed: %v\n", p.Manifest.Slug, eventType, err)
}
- }(p)
+ }(p, input)
}
wg.Wait()
}
diff --git a/services/plugins/manager.go b/services/plugins/manager.go
index df58a9e584..afbb246070 100644
--- a/services/plugins/manager.go
+++ b/services/plugins/manager.go
@@ -1648,6 +1648,9 @@ func loadFromBytes(ctx context.Context, env *HostEnv, manifestBytes, artifactByt
if err := requireSubscriptionPermissions(manifest, runtime.Subscriptions); err != nil {
return nil, fail(err)
}
+ if err := namespaceCustomSubscriptions(manifest.Slug, &runtime.Subscriptions); err != nil {
+ return nil, fail(err)
+ }
manifest.Subscriptions = runtime.Subscriptions
// Command registrations are derived by the SDK. They have no sidecar
// counterpart for AgreesWith to compare. Core uses them for matching,
@@ -1820,6 +1823,23 @@ func requireSubscriptionPermissions(manifest *Manifest, subs Subscriptions) erro
return nil
}
+// namespaceCustomSubscriptions gives each plugin exclusive ownership of its
+// custom notification hooks. Built-in subscriptions keep their canonical
+// names.
+func namespaceCustomSubscriptions(slug string, subs *Subscriptions) error {
+ for i := range subs.Notify {
+ if reservedEventTypes[subs.Notify[i].Event] {
+ continue
+ }
+ qualified := slug + "." + subs.Notify[i].Event
+ if reservedEventTypes[qualified] {
+ return fmt.Errorf("custom event hook %q collides with a built-in event", qualified)
+ }
+ subs.Notify[i].Event = qualified
+ }
+ return nil
+}
+
// registryMetaSuffix names the sidecar file the host writes next to a
// plugin installed from the registry ("<base>.registry.json"), carrying
// registry-sourced metadata that has no home in the plugin's own
diff --git a/services/plugins/shared_engine_test.go b/services/plugins/shared_engine_test.go
index d2061bd381..047a75b333 100644
--- a/services/plugins/shared_engine_test.go
+++ b/services/plugins/shared_engine_test.go
@@ -293,11 +293,12 @@ func TestEmitSelfSubscriptionDoesNotDeadlock(t *testing.T) {
t.Cleanup(func() { compiledEngines.resetForTest(ctx) })
env, _, _ := captureEnv()
- // Emits "ping" on every chat message AND subscribes (notify) to "ping".
+ // Emits its fully qualified hook on every chat message AND subscribes
+ // (notify) to the local "ping" hook.
script := `
const { definePlugin, owncast } = require("@owncast/plugin-sdk");
module.exports = definePlugin({
- onChatMessage(msg) { owncast.events.emit("ping", {}); },
+ onChatMessage(msg) { owncast.events.emit("echoer.ping", {}); },
on: { ping(payload) {} },
});`
loaded := loadShared(t, ctx, env, RuntimeJavaScript, "echoer", script, []string{PermEmitEvent})
@@ -313,7 +314,7 @@ module.exports = definePlugin({
}()
select {
case <-done:
- case <-time.After(10 * time.Second):
+ case <-time.After(NotifyTimeout / 2):
t.Fatal("Dispatch deadlocked on a re-entrant self-subscribed emit")
}
}