Take control over your live stream video by running it yourself. Streaming + chat out of the box.
HTML activitypubbroadcastingchatdecentralizedfederationfediversegolanghacktoberfesthlslivelivestreamowncastrtmpself-hostedstreaming-videovideo
Remove redundant plugin operation result flags (#5098)
Gabe Kangasf05e1432ca90
diff --git a/services/plugins/contract_test.go b/services/plugins/contract_test.goindex cf1194aede..6fb2501628 100644--- a/services/plugins/contract_test.go+++ b/services/plugins/contract_test.go@@ -161,6 +161,37 @@ func normalizeNewlines(b []byte) []byte {return []byte(strings.ReplaceAll(string(b), "\r\n", "\n"))}+func TestOperationResultsUseErrorAsTheOnlyFailureSignal(t *testing.T) {+ tests := map[string]struct {+ result any+ want string+ }{+ "filesystem write success": {FSResult{}, `{}`},+ "filesystem write failure": {FSResult{Error: "failed"}, `{"error":"failed"}`},+ "filesystem delete success": {FSResult{}, `{}`},+ "filesystem delete failure": {FSResult{Error: "failed"}, `{"error":"failed"}`},+ "SQL exec success": {SQLExecResult{RowsAffected: 1, LastInsertID: 2}, `{"rowsAffected":1,"lastInsertId":2}`},+ "SQL exec failure": {SQLExecResult{Error: "failed"}, `{"error":"failed","rowsAffected":0,"lastInsertId":0}`},+ "SQL query success": {SQLQueryResult{Columns: []string{}, Rows: [][]any{}}, `{"columns":[],"rows":[]}`},+ "SQL query failure": {SQLQueryResult{Error: "failed"}, `{"error":"failed","columns":[],"rows":[]}`},+ "video config write success": {VideoConfigWriteResult{}, `{}`},+ "video config write failure": {VideoConfigWriteResult{Error: "failed"}, `{"error":"failed"}`},+ "auth session success": {GrantSessionResult{}, `{}`},+ "auth session failure": {GrantSessionResult{Error: "failed"}, `{"error":"failed"}`},+ }+ for name, test := range tests {+ t.Run(name, func(t *testing.T) {+ got, err := json.Marshal(test.result)+ if err != nil {+ t.Fatal(err)+ }+ if string(got) != test.want {+ t.Fatalf("got %s, want %s", got, test.want)+ }+ })+ }+}+func TestPluginContractMatchesSDK(t *testing.T) {_, thisFile, _, _ := runtime.Caller(0)repoRoot := filepath.Join(filepath.Dir(thisFile), "..", "..")diff --git a/services/plugins/engines/javascript/engine.wasm b/services/plugins/engines/javascript/engine.wasmindex 47736a9423..6556e4cdac 100644Binary files a/services/plugins/engines/javascript/engine.wasm and b/services/plugins/engines/javascript/engine.wasm differdiff --git a/services/plugins/engines/python/engine.wasm b/services/plugins/engines/python/engine.wasmindex 4eed378a15..5427612e77 100644Binary files a/services/plugins/engines/python/engine.wasm and b/services/plugins/engines/python/engine.wasm differdiff --git a/services/plugins/hostfns.go b/services/plugins/hostfns.goindex 23b9ca6538..ed75f227b3 100644--- a/services/plugins/hostfns.go+++ b/services/plugins/hostfns.go@@ -68,10 +68,6 @@ const (PermUIModify = "ui.modify")-// resultErrorKey is the JSON key host functions use to return an error-// string to the plugin in their {ok, error?} result envelope.-const resultErrorKey = "error"-// ChatSendKind distinguishes how a plugin asked to post to chat. All sends// post under the plugin's own chat identity — provisioned by the host at// install time as a chat user with IsBot=true and DisplayName=plugin name.@@ -163,6 +159,11 @@ type VideoConfigUpdate struct {Variants []StreamVariant `json:"variants,omitempty"`}+// VideoConfigWriteResult reports whether a video config update failed.+type VideoConfigWriteResult struct {+ Error string `json:"error,omitempty"`+}+// SocialHandle is one entry returned by owncast.server.socials().type SocialHandle struct {Platform string `json:"platform"`@@ -269,9 +270,14 @@ type UploadResult struct {URL string `json:"url"`}-// SQLRequest is a statement, its JSON-serializable bind parameters, and an-// optional cap on how many rows a query should return. MaxRows of 0 means "no-// caller-supplied limit", which the host bounds with MaxSQLRows.+// FSResult reports whether a filesystem mutation failed.+type FSResult struct {+ Error string `json:"error,omitempty"`+}++// SQLRequest is a statement, an optional array of scalar bind parameters, and+// an optional cap on how many rows a query should return. MaxRows of 0 means+// "no caller-supplied limit", which the host bounds with MaxSQLRows.type SQLRequest struct {SQL string `json:"sql"`Params []any `json:"params,omitempty"`@@ -279,8 +285,8 @@ type SQLRequest struct {}// SQLExecResult reports the effect of one committed SQL statement batch.+// Absence of Error means success.type SQLExecResult struct {- OK bool `json:"ok"`Error string `json:"error,omitempty"`RowsAffected int64 `json:"rowsAffected"`LastInsertID int64 `json:"lastInsertId"`@@ -288,15 +294,25 @@ type SQLExecResult struct {// SQLQueryResult is a bounded set of rows returned by a plugin SQL query.// Rows use the same column order as Columns. Truncated reports that the query-// matched more rows than the caller's MaxRows.+// matched more rows than the caller's MaxRows. Absence of Error means success.type SQLQueryResult struct {- OK bool `json:"ok"`Error string `json:"error,omitempty"`Columns []string `json:"columns"`Rows [][]any `json:"rows"`Truncated bool `json:"truncated,omitempty"`}+func (r SQLQueryResult) MarshalJSON() ([]byte, error) {+ type result SQLQueryResult+ if r.Columns == nil {+ r.Columns = []string{}+ }+ if r.Rows == nil {+ r.Rows = [][]any{}+ }+ return json.Marshal(result(r))+}+// SSEConnectionEvent is the payload for the sse.connect / sse.disconnect// events, fired when a browser opens or closes one of the plugin's// Server-Sent-Events streams. ConnectionID is unique for the life of the host@@ -546,7 +562,6 @@ func hostSQLExec(env *HostEnv) extism.HostFunction {default:result = env.SQLExec(ctx, id.slug, req)}- result.OK = result.Error == ""stack[0] = writeJSON(p, result)},[]extism.ValueType{extism.ValueTypePTR},@@ -575,7 +590,6 @@ func hostSQLQuery(env *HostEnv) extism.HostFunction {default:result = env.SQLQuery(ctx, id.slug, req)}- result.OK = result.Error == ""stack[0] = writeJSON(p, result)},[]extism.ValueType{extism.ValueTypePTR},@@ -882,8 +896,8 @@ type GrantSessionRequest struct {TTL int64 `json:"ttl,omitempty"` // seconds; 0 = host default}-// authResult is the {error?} envelope returned by grantSession.-type authResult struct {+// GrantSessionResult reports whether granting an auth session failed.+type GrantSessionResult struct {Error string `json:"error,omitempty"`}@@ -958,15 +972,15 @@ func hostAuthGrantSession(env *HostEnv) extism.HostFunction {}var req GrantSessionRequestif err := json.Unmarshal([]byte(raw), &req); err != nil {- stack[0] = writeJSON(p, authResult{Error: "invalid request: " + err.Error()})+ stack[0] = writeJSON(p, GrantSessionResult{Error: "invalid request: " + err.Error()})return}if req.UserID == "" {- stack[0] = writeJSON(p, authResult{Error: "userId is required"})+ stack[0] = writeJSON(p, GrantSessionResult{Error: "userId is required"})return}if env.GrantSession == nil {- stack[0] = writeJSON(p, authResult{Error: "auth.gate is not available on this host"})+ stack[0] = writeJSON(p, GrantSessionResult{Error: "auth.gate is not available on this host"})return}// A session is only meaningful when there's an in-flight response to@@ -976,18 +990,18 @@ func hostAuthGrantSession(env *HostEnv) extism.HostFunction {// handler where no cookie is ever set.sink := authSinkFrom(ctx)if sink == nil {- stack[0] = writeJSON(p, authResult{Error: "grantSession is only available inside an on_http_request handler"})+ stack[0] = writeJSON(p, GrantSessionResult{Error: "grantSession is only available inside an on_http_request handler"})return}token, err := env.GrantSession(ident.slug, req.UserID, req.TTL)if err != nil {- stack[0] = writeJSON(p, authResult{Error: err.Error()})+ stack[0] = writeJSON(p, GrantSessionResult{Error: err.Error()})return}// Hand the freshly-minted token to the request-scoped sink so the// HTTP layer can set the cookie on the response after the wasm returns.sink.grant(token, ClampSessionTTL(req.TTL))- stack[0] = writeJSON(p, authResult{})+ stack[0] = writeJSON(p, GrantSessionResult{})},[]extism.ValueType{extism.ValueTypePTR},[]extism.ValueType{extism.ValueTypePTR},@@ -1406,7 +1420,7 @@ func hostFSRead(env *HostEnv) extism.HostFunction {// hostFSWrite backs owncast.fs.write(path, data). Creates parent// directories as needed and writes the bytes, returning a JSON-// {ok, error?} result so the plugin can react to a rejected write+// {error?} result so the plugin can react to a rejected write// (sandbox escape, oversized payload, disk error). Requires storage.fs.func hostFSWrite(env *HostEnv) extism.HostFunction {fn := extism.NewHostFunctionWithStack(@@ -1428,24 +1442,14 @@ func hostFSWrite(env *HostEnv) extism.HostFunction {stack[0] = 0return}- result := map[string]any{"ok": true}+ result := FSResult{}if env.FSWrite == nil {- result = map[string]any{"ok": false, resultErrorKey: "filesystem unavailable"}+ result.Error = "filesystem unavailable"} else if err := env.FSWrite(pluginName, path, data); err != nil {fmt.Fprintf(os.Stderr, "owncast_fs_write from %s: %v\n", pluginName, err)- result = map[string]any{"ok": false, resultErrorKey: err.Error()}- }- out, err := json.Marshal(result)- if err != nil {- stack[0] = 0- return- }- offset, err := p.WriteBytes(out)- if err != nil {- stack[0] = 0- return+ result.Error = err.Error()}- stack[0] = offset+ stack[0] = writeJSON(p, result)},[]extism.ValueType{extism.ValueTypePTR, extism.ValueTypePTR},[]extism.ValueType{extism.ValueTypePTR},@@ -1501,8 +1505,7 @@ func hostFSList(env *HostEnv) extism.HostFunction {}// hostFSDelete backs owncast.fs.delete(path). Removes a single file or-// empty directory, returning a JSON {ok, error?} result. Requires-// storage.fs.+// empty directory, returning a JSON {error?} result. Requires storage.fs.func hostFSDelete(env *HostEnv) extism.HostFunction {fn := extism.NewHostFunctionWithStack("owncast_fs_delete",@@ -1518,24 +1521,14 @@ func hostFSDelete(env *HostEnv) extism.HostFunction {stack[0] = 0return}- result := map[string]any{"ok": true}+ result := FSResult{}if env.FSDelete == nil {- result = map[string]any{"ok": false, resultErrorKey: "filesystem unavailable"}+ result.Error = "filesystem unavailable"} else if err := env.FSDelete(pluginName, path); err != nil {fmt.Fprintf(os.Stderr, "owncast_fs_delete from %s: %v\n", pluginName, err)- result = map[string]any{"ok": false, resultErrorKey: err.Error()}- }- out, err := json.Marshal(result)- if err != nil {- stack[0] = 0- return- }- offset, err := p.WriteBytes(out)- if err != nil {- stack[0] = 0- return+ result.Error = err.Error()}- stack[0] = offset+ stack[0] = writeJSON(p, result)},[]extism.ValueType{extism.ValueTypePTR},[]extism.ValueType{extism.ValueTypePTR},@@ -2014,8 +2007,8 @@ func hostVideoConfigRead(env *HostEnv) extism.HostFunction {}// hostVideoConfigWrite backs owncast.videoConfig.write(config). It applies a-// partial video/transcoding configuration change via the host. Returns a-// JSON {ok, error?} result so the plugin can react to a rejected config.+// partial video/transcoding configuration change via the host, returning an+// empty JSON object on success or an error on failure.// Requires the videoconfig.write permission.func hostVideoConfigWrite(env *HostEnv) extism.HostFunction {fn := extism.NewHostFunctionWithStack(@@ -2038,23 +2031,13 @@ func hostVideoConfigWrite(env *HostEnv) extism.HostFunction {stack[0] = 0return}- result := map[string]any{"ok": true}+ result := VideoConfigWriteResult{}if env.WriteVideoConfig != nil {if err := env.WriteVideoConfig(pluginName, update); err != nil {- result = map[string]any{"ok": false, resultErrorKey: err.Error()}+ result.Error = err.Error()}}- data, err := json.Marshal(result)- if err != nil {- stack[0] = 0- return- }- offset, err := p.WriteBytes(data)- if err != nil {- stack[0] = 0- return- }- stack[0] = offset+ stack[0] = writeJSON(p, result)},[]extism.ValueType{extism.ValueTypePTR},[]extism.ValueType{extism.ValueTypePTR},diff --git a/services/plugins/plugin-contract.json b/services/plugins/plugin-contract.jsonindex e8abb59aae..979b5c707a 100644--- a/services/plugins/plugin-contract.json+++ b/services/plugins/plugin-contract.json@@ -99,6 +99,9 @@"name": "string","url": "string"},+ "FSResult": {+ "error": "string"+ },"FederationInfo": {"enabled": "bool","isPrivate": "bool",@@ -114,6 +117,9 @@"ttl": "int64","userId": "string"},+ "GrantSessionResult": {+ "error": "string"+ },"HostChatClient": {"connectedAt": "string","displayName": "string",@@ -144,13 +150,11 @@"SQLExecResult": {"error": "string","lastInsertId": "int64",- "ok": "bool","rowsAffected": "int64"},"SQLQueryResult": {"columns": "[]string","error": "string",- "ok": "bool","rows": "[][]any","truncated": "bool"},@@ -230,7 +234,7 @@"latencyLevel": "*int","variants": "[]StreamVariant"},- "authResult": {+ "VideoConfigWriteResult": {"error": "string"}}diff --git a/services/plugins/sqlrunner.go b/services/plugins/sqlrunner.goindex 29a54986d3..4da2b4b7b4 100644--- a/services/plugins/sqlrunner.go+++ b/services/plugins/sqlrunner.go@@ -153,7 +153,7 @@ func (r SQLRunner) Exec(ctx context.Context, req SQLRequest) SQLExecResult {if err := tx.Commit(); err != nil {return SQLExecResult{Error: err.Error()}}- return SQLExecResult{OK: true, RowsAffected: rowsAffected, LastInsertID: lastInsertID}+ return SQLExecResult{RowsAffected: rowsAffected, LastInsertID: lastInsertID}}// Query runs the request and returns a bounded result set.@@ -251,10 +251,10 @@ func newSQLResultBuilder(columns []string, rowBudget int) (*sqlResultBuilder, erreturn nil, err}return &sqlResultBuilder{- result: SQLQueryResult{OK: true, Columns: columns, Rows: make([][]any, 0, min(rowBudget, 64))},+ result: SQLQueryResult{Columns: columns, Rows: make([][]any, 0, min(rowBudget, 64))},// The envelope's fixed keys, column names, and optional truncation marker// count against the budget so every encoded result stays within the cap.- used: len(encodedColumns) + len(`{"ok":true,"columns":,"rows":[]}`) + len(`,"truncated":true`),+ used: len(encodedColumns) + len(`{"columns":,"rows":[]}`) + len(`,"truncated":true`),rowBudget: rowBudget,}, nil}diff --git a/services/plugins/sqlrunner_test.go b/services/plugins/sqlrunner_test.goindex f62401b740..21aacc21e1 100644--- a/services/plugins/sqlrunner_test.go+++ b/services/plugins/sqlrunner_test.go@@ -106,9 +106,6 @@ func TestSQLRunnerRowCapIsAnErrorWhenUnbounded(t *testing.T) {if result.Error == "" || !strings.Contains(result.Error, "add a LIMIT") {t.Fatalf("expected a row-cap error, got %d rows and error %q", len(result.Rows), result.Error)}- if result.OK {- t.Fatal("a failed query must not report ok")- }}// A caller-supplied MaxRows is intent, so the host stops there and says it@@ -221,7 +218,6 @@ func TestSQLRunnerResultEncodesWithinBudget(t *testing.T) {// value would fit if the builder forgot to count `,"truncated":true`, but// the final JSON would be one byte over the advertised cap.probe, err := json.Marshal(SQLQueryResult{- OK: true,Columns: []string{"v"},Rows: [][]any{{""}},Truncated: true,@@ -247,10 +243,10 @@ func TestSQLRunnerResultEncodesWithinBudget(t *testing.T) {func TestSQLRunnerWithoutDatabaseReportsUnavailable(t *testing.T) {var runner SQLRunnerctx := context.Background()- if result := runner.Exec(ctx, SQLRequest{SQL: "SELECT 1"}); result.Error == "" || result.OK {+ if result := runner.Exec(ctx, SQLRequest{SQL: "SELECT 1"}); result.Error == "" {t.Fatalf("expected exec to report the store unavailable, got %+v", result)}- if result := runner.Query(ctx, SQLRequest{SQL: "SELECT 1"}); result.Error == "" || result.OK {+ if result := runner.Query(ctx, SQLRequest{SQL: "SELECT 1"}); result.Error == "" {t.Fatalf("expected query to report the store unavailable, got %+v", result)}}