diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5169523..ee19b18 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -35,6 +35,7 @@ go build ./examples/hello-scheduled-task go build ./examples/hello-runtime-host go build ./examples/hello-network-access go build ./examples/hello-scan-source +go build ./examples/hello-notification-channel gofmt -l . ``` diff --git a/README.md b/README.md index 65b1c22..2f325f9 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ The SDK ships protobuf contracts for every capability the host understands: - `scan_source.v1` - `watch_sync_provider.v1` - `network_access_provider.v1` +- `notification_channel.v1` (see [docs/notification-channel.md](docs/notification-channel.md)) - `audiobook_backend.v1` - `ebook_backend.v1` diff --git a/docs/compatibility.md b/docs/compatibility.md index 6caee46..331e85e 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -262,6 +262,16 @@ and ignores the field, so it applies its usual idle-stop rule. The field takes effect only on a host that both stops idle plugins and reads it; on a host that never stops idle plugins, it changes nothing. +### New capability types + +Manifest validation refuses a capability type its SDK doesn't know, and it +refuses the whole plugin, not only that capability: an older host fails to +install or load it with `plugin capability "": unknown type ""`. +A plugin that declares a newer type, such as `notification_channel.v1`, +therefore needs a host built on an SDK that knows it. Ship a new capability +type in its own plugin rather than adding it to one that must keep working +on older hosts. + ### Watch-sync batch size `WatchSyncProviderDescriptor.max_batch_size` accepts 1 to 1000 from v0.27.0; diff --git a/docs/notification-channel.md b/docs/notification-channel.md new file mode 100644 index 0000000..551e77f --- /dev/null +++ b/docs/notification-channel.md @@ -0,0 +1,272 @@ +# Notification channels + +A `notification_channel.v1` capability adds a kind of notification +destination to Silo, such as a push service or a chat app. Users add a +destination of that kind in their notification settings, next to webhooks and +email, and Silo sends it the notifications the profile receives: new +episodes, request updates, and titles from the profile's watchlist that +arrive in the library. + +The plugin does two things: it checks a destination's settings, and it sends +one message. Silo does the rest: + +- which notifications a profile gets, and each destination's two switches: + `notify_next_up` (new episodes, type `episode.available`) and + `notify_requests` (request updates, `request.*`, and watchlist arrivals, + `watchlist.available`) +- a limit of 30 new-episode and watchlist messages a minute per profile + (request updates aren't limited). Each API server counts on its own, so a + cluster of several servers can send a profile more. +- a durable delivery queue, so a notification survives restarts and a server + going away mid-send +- retries with backoff, and dropping a message after the last retry +- failure counts, shown to the destination's owner, and disabling a + destination whose settings stopped working (see the outcomes below) +- test messages from the settings page +- storing each destination's settings encrypted, and never returning secret + fields through the API + +Compare an `event_consumer.v1` plugin subscribed to `notification.created`, +which has to rebuild preferences, retries and deduplication itself. + +## Manifest + +```json +{ + "type": "notification_channel.v1", + "id": "ntfy", + "display_name": "ntfy", + "notification_channel": { + "display_name": "ntfy", + "description": "Push notifications to an ntfy topic.", + "destination_schema": { + "key": "destination", + "json_schema": "{\"type\":\"object\",\"properties\":{\"topic\":{\"type\":\"string\"},\"access_token\":{\"type\":\"string\"}},\"required\":[\"topic\"]}", + "admin_form": { + "fields": [ + { "key": "topic", "label": "Topic", "control": "ADMIN_FORM_CONTROL_TEXT", "required": true }, + { "key": "access_token", "label": "Access token", "control": "ADMIN_FORM_CONTROL_PASSWORD", "secret": true } + ] + } + } + } +} +``` + +- The capability `id` is a lowercase slug. It's stored with each destination, + so keep it stable across releases. +- `destination_schema` is a `ConfigSchema` with a flat form: one object of + string, integer, number or boolean fields, each with optional `title`, + `description`, `default` and `enum`, `minimum`/`maximum` on integer and + number fields, and `format` and `minLength`/`maxLength`/`pattern` on string + fields, plus a top-level `required` list. `additionalProperties` may only + be `false` or absent. `$schema`, `$ref`, `allOf`/`anyOf`/`oneOf`/`not`, + conditionals, nested objects and arrays are refused, because people who + aren't administrators fill the form in on every client. Silo compiles the + schema as JSON Schema draft 2020-12, the draft it uses for all plugin + configuration. +- `admin_form` is required and is one flat list of at least one field: one + form field per schema field, and every form field names a schema field. + Clients render only the form. See [Destination form](#destination-form). + `manifest.ValidateDestinationSchema` checks all of this. +- Silo checks each submitted setting against the schema before calling the + plugin: only declared fields; the value has the declared type; `required` + fields present when a destination is created (a stored secret left blank + on an edit counts as present); `enum`; `minLength`, `maxLength` and + `pattern` on strings; `minimum` and `maximum` on numbers. It doesn't check + `format` (in draft 2020-12 it's only an annotation) or anything else, so + check whatever else matters in `ValidateDestination`. +- `pattern` is Go RE2 syntax (Go's `regexp`: no lookahead, lookbehind or + backreferences), and install refuses a pattern that doesn't compile. + Clients may use it to check input as the user types; the host's check on + save is the one that counts. +- Mark credentials `secret`: the host never returns them, and on an edit the + user leaves them blank to keep the stored value. +- A manifest can declare several `notification_channel.v1` capabilities. One + server answers for all of them; each request carries its `capability_id`. + +## Destination form + +A destination form is one flat list of fields. Every Silo client has to +render it for people who aren't administrators, so it allows only what a +flat list of scalar fields needs. + +| Control | Schema field type | +|---|---| +| `ADMIN_FORM_CONTROL_TEXT` | `string` | +| `ADMIN_FORM_CONTROL_PASSWORD` | `string` | +| `ADMIN_FORM_CONTROL_NUMBER` | `integer` or `number` | +| `ADMIN_FORM_CONTROL_SWITCH` | `boolean` | +| `ADMIN_FORM_CONTROL_SELECT`, with static `options` | `string`, `integer` or `number` | + +A field must set `key`, `label` and `control`, and may set `description`, +`placeholder`, `required`, `secret` (string fields only), `default_value` +and, on a `SELECT` only, `options`. + +Every form must also be one a client can render and Silo can save, so +install refuses a form unless: + +- each field's `key` is exactly its schema property's name: a letter + followed by up to 63 letters, digits, underscores or hyphens, used once +- a field's `required` matches whether the schema's `required` list names + it +- the schema compiles as Silo compiles it, and each `pattern` is valid Go + RE2 +- `minimum` is at most `maximum`, `minLength` is at most `maxLength`, and + lengths aren't negative; an integer field's bounds hold at least one whole + number +- an integer value (an option, a default, or what a user enters) is at most + 9007199254740991 in either direction, because settings travel as JSON and + protobuf numbers. Use a string field for a larger identifier, such as a + chat ID +- a `secret` field uses the `PASSWORD` or `TEXT` control +- every option value parses as the field's type (an integer field's options + are integers), and no two options have the same value +- a field with `enum` uses a `SELECT`, and its options are exactly the + `enum` values. Every option passes the field's other checks. Without + `enum`, Silo accepts any value of the field's type that passes its + checks, not only the options; declare `enum` to hold it to them. +- a `default` in the schema and a `default_value` on the form are each a + value of the field's type that passes the field's checks and, on a + `SELECT`, is one of the options + +Refused: + +- `sections` (the generic form doesn't need them: without sections it + renders the fields in order) and `submit_label` +- `show_when`, `dynamic_options` and `exclusive_group_field`. A destination + has no options lookup; the admin `ListConfigOptions` call is for + administrators only. +- `validation`: put `minimum`, `maximum`, `minLength`, `maxLength` and + `pattern` in the JSON schema, where Silo checks them +- `ADMIN_FORM_CONTROL_TEXTAREA`, `multiline`, `rows`, + `ADMIN_FORM_CONTROL_MULTI_SELECT` and an unset control +- a `SELECT` without options, and `options` on any other control + +Loosening these rules later is additive; tightening them would break +published plugins, so they start narrow. + +## Serving + +Register the service with `runtime.WithNotificationChannel`: + +```go +sdkruntime.ServeManifestWithOptions(manifestJSON, version, sdkruntime.CapabilityServers{}, + sdkruntime.WithNotificationChannel(&channel{}), +) +``` + +`ServeManifestWithOptions` refuses to start when the manifest declares a +`notification_channel.v1` capability and no server is registered. + +### ValidateDestination + +Silo calls it before saving a destination. Check the settings and return +`valid: false` with a `message` the user can act on. Return a gRPC error only +when the check itself couldn't run. A network check, such as asking the +service whether a user key exists, is fine. Silo gives the call 10 seconds, +counted once it has reached the plugin; starting a stopped plugin comes +first and isn't part of them. When the plugin doesn't answer in time, +returns a gRPC error, or isn't running, the save fails with `503` (the +plugin isn't available) and `Retry-After: 30`. + +A valid answer doesn't mean the settings get saved: Silo checks them first +and saves afterwards, and the save can still fail, for example on the +per-profile destination limit or because another edit landed first. So +`ValidateDestination` must not create remote state, such as a subscription +or a webhook on the service, that would be a problem to leak. + +### SendNotification + +Silo calls it once per message and destination, possibly from different +servers, and again after a failure. A server claims a send for five minutes; +if that server dies, another one sends it again once the claim runs out, so +a message can arrive twice. `delivery_key` is the same on every attempt: +pass it to the service as an idempotency key where it has one. + +The message arrives rendered: `title`, `body`, `url` (opens the item in +Silo; empty when the server has no public URL set) and `image_url` (a +poster, which can expire; empty when there is none). `details` carries the +same fields as the `Notification` type in `pkg/pluginsdk/events` (the +`notification.created` event's payload; identifiers are strings), for +plugins that render their own text. `type` is `episode.available`, +`watchlist.available`, a `request.*` type, or `test` for a test message, +whose `details` are empty. The vocabulary is open. + +Map the service's answer onto an outcome: + +| Outcome | Use for | Silo then | +|---|---|---| +| `DELIVERED` (or an empty response) | The service accepted the message. | Records the success. | +| `RETRY` | A timeout, a rate limit, a 5xx. Set `retry_after_seconds` when the service says how long to wait. | Tries again later with growing delays. After ten attempts over about a day the message is dropped, and the destination may be disabled (see below). `retry_after_seconds` makes the next wait at least that long, up to a host cap of six hours; it never shortens the schedule. | +| `FAILED` | This message can't be sent, but the destination works. | Drops the message. | +| `DESTINATION_INVALID` | The service definitely refused the settings, such as a revoked token or a deleted topic. | Drops the message and disables the destination at once, until its owner turns it back on. | + +`DESTINATION_INVALID` takes effect on the first answer, so return it only when +the service's own response says the settings are wrong. A 401 from a proxy or +CDN, a timeout or a 5xx is `RETRY`. + +Because of that cap, a plugin whose service asks for a longer wait, such as +a daily quota that resets in 20 hours, is called again after six hours. It +should then answer `RETRY` again with the wait that remains. + +Silo allows 10 seconds to reach the plugin, starting it when needed, and +then 15 seconds for the call. A gRPC error your plugin returns, or no answer +within those 15 seconds, counts as `RETRY`: an ordinary failed attempt, +which retries and can lead to the destination being disabled under the "no +successful send" rule below. Only a failure to reach the plugin counts as +the plugin being unavailable (see below). Put a short reason in `message`; +the destination's owner sees it. Never include secrets. + +Silo disables a destination in two cases only: + +- the plugin answers `DESTINATION_INVALID`, or +- a message runs out of retries (ten attempts over about a day), or is still + waiting 36 hours after it was queued (for example after several long + `retry_after_seconds` waits), after failed attempts, and the destination + had no successful send and no edit by its owner in the meantime. One + message that keeps failing while others get through doesn't disable it. + +A message still waiting after 36 hours is dropped without another send. + +A failure to reach the plugin is the plugin being unavailable, not the +destination failing: the plugin is off, removed or not running, the +connection fails or closes (its process exited during the call), or the +call ends with gRPC `Unavailable`. Silo retries such a message like any +other and drops it once it's older than the retry window, but leaves the +destination enabled, so it works again once the plugin is back. Silo also +doesn't disable a destination whose owner saved new settings while the +failing send ran. + +A disabled destination is turned off and gets nothing until its owner +turns it back on. Saving new settings clears the reason shown and the +failure count but leaves the destination off. + +### What a plugin isn't told + +- **Destination changes.** Silo doesn't tell the plugin when a destination + is edited, disabled or deleted. Every call carries the destination's + current settings, so keep no per-destination state that would need + cleaning up. +- **The recipient's language.** Requests carry no locale. Silo renders + `title` and `body`; a plugin that renders its own text from `details` + has no way to pick the recipient's language. + +## Compatibility + +A Silo server whose SDK predates `notification_channel.v1` refuses to +install or load a plugin that declares it: its manifest validation rejects +the whole plugin with `plugin capability "": unknown type +"notification_channel.v1"`. The same happens to a plugin that declares any +capability type the host's SDK doesn't know, so put a notification channel +in its own plugin, not in one that must keep working on older servers. + +## Network requests + +The host's webhook client refuses private and loopback addresses. A plugin +makes its own requests, so it has to apply the same care: users who aren't +administrators fill in destination settings, so don't let a setting choose +the host a plugin connects to. Fix the service's URL in the plugin, or take +it from the plugin's administrator settings, as +[`examples/hello-notification-channel`](../examples/hello-notification-channel) +does. diff --git a/examples/hello-notification-channel/README.md b/examples/hello-notification-channel/README.md new file mode 100644 index 0000000..9c12258 --- /dev/null +++ b/examples/hello-notification-channel/README.md @@ -0,0 +1,28 @@ +# Hello Notification Channel + +A `notification_channel.v1` plugin that sends Silo notifications to an +[ntfy](https://ntfy.sh) topic. It shows: + +- declaring a destination kind and its settings form in `manifest.json` +- checking a destination's settings in `ValidateDestination` +- mapping the service's answers onto `SendNotification` outcomes, so the + host retries temporary failures and disables a destination whose token + stops working +- keeping the server URL in the administrator's settings, since users who + aren't administrators fill in destinations + +## Build + +```sh +go build -o hello-notification-channel ./examples/hello-notification-channel +./hello-notification-channel manifest +``` + +## Use + +Install the binary through **Admin > Plugins**. Optionally set the ntfy +server in the plugin's settings (the default is `https://ntfy.sh`). Each +profile then adds an ntfy destination in its notification settings and +subscribes to the topic in the ntfy app. + +See [docs/notification-channel.md](../../docs/notification-channel.md). diff --git a/examples/hello-notification-channel/main.go b/examples/hello-notification-channel/main.go new file mode 100644 index 0000000..47b7cb1 --- /dev/null +++ b/examples/hello-notification-channel/main.go @@ -0,0 +1,210 @@ +// Command hello-notification-channel is a notification_channel.v1 plugin +// that posts Silo notifications to an ntfy topic (https://ntfy.sh). +// +// The administrator picks the ntfy server in the plugin's settings; each +// destination only names a topic. Users who aren't administrators fill in +// destinations, so letting them choose the URL would let them make the +// server send requests anywhere. +package main + +import ( + "context" + _ "embed" + "encoding/json" + "fmt" + "io" + "math" + "mime" + "net/http" + "net/url" + "regexp" + "strconv" + "strings" + "sync" + "time" + + pluginv1 "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginproto/silo/plugin/v1" + sdkruntime "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/runtime" +) + +//go:embed manifest.json +var manifestJSON []byte + +// version replaces the manifest version when set with -ldflags. +var version string + +const defaultServerURL = "https://ntfy.sh" + +var topicPattern = regexp.MustCompile(`^[-_A-Za-z0-9]{1,64}$`) + +type channel struct { + pluginv1.UnimplementedNotificationChannelServer + http *http.Client + + mu sync.RWMutex + serverURL string +} + +// configure reads the administrator's server URL. +func (c *channel) configure(_ context.Context, entries []*pluginv1.ConfigEntry) error { + serverURL := defaultServerURL + for _, entry := range entries { + if entry.GetKey() != "ntfy" { + continue + } + if v := strings.TrimSpace(entry.GetValue().GetFields()["server_url"].GetStringValue()); v != "" { + serverURL = strings.TrimRight(v, "/") + } + } + c.mu.Lock() + c.serverURL = serverURL + c.mu.Unlock() + return nil +} + +func (c *channel) server() string { + c.mu.RLock() + defer c.mu.RUnlock() + return c.serverURL +} + +func (c *channel) ValidateDestination(_ context.Context, req *pluginv1.ValidateNotificationDestinationRequest) (*pluginv1.ValidateNotificationDestinationResponse, error) { + topic := req.GetConfig().GetFields()["topic"].GetStringValue() + if !topicPattern.MatchString(topic) { + return &pluginv1.ValidateNotificationDestinationResponse{ + Message: "The topic must be 1 to 64 letters, digits, hyphens or underscores.", + }, nil + } + if !validToken(req.GetConfig().GetFields()["access_token"].GetStringValue()) { + return &pluginv1.ValidateNotificationDestinationResponse{ + Message: "The access token can only contain printable ASCII characters.", + }, nil + } + if !validServerURL(c.server()) { + return &pluginv1.ValidateNotificationDestinationResponse{ + Message: "The administrator's ntfy server URL isn't valid. Ask them to fix it in the plugin's settings.", + }, nil + } + return &pluginv1.ValidateNotificationDestinationResponse{Valid: true}, nil +} + +// validServerURL reports whether raw is an absolute http or https URL, the +// only kind the HTTP client can post to. +func validServerURL(raw string) bool { + u, err := url.Parse(raw) + return err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Host != "" +} + +// validToken reports whether token can go in an HTTP header unchanged. +func validToken(token string) bool { + return !strings.ContainsFunc(token, func(r rune) bool { return r < 0x20 || r > 0x7e }) +} + +// headerValue makes text safe for an HTTP header: Go refuses control +// characters, so they become spaces, and ntfy reads non-ASCII text only +// RFC 2047 encoded. +func headerValue(text string) string { + text = strings.Map(func(r rune) rune { + if r < 0x20 || r == 0x7f { + return ' ' + } + return r + }, text) + return mime.BEncoding.Encode("utf-8", strings.TrimSpace(text)) +} + +func (c *channel) SendNotification(ctx context.Context, req *pluginv1.SendNotificationRequest) (*pluginv1.SendNotificationResponse, error) { + fields := req.GetConfig().GetFields() + topic := fields["topic"].GetStringValue() + token := fields["access_token"].GetStringValue() + if !topicPattern.MatchString(topic) || !validToken(token) { + return outcome(pluginv1.NotificationSendOutcome_NOTIFICATION_SEND_OUTCOME_DESTINATION_INVALID, "The topic or access token isn't valid."), nil + } + msg := req.GetMessage() + body := msg.GetBody() + if body == "" { + body = msg.GetTitle() + } + httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, c.server()+"/"+topic, strings.NewReader(body)) + if err != nil { + return nil, err + } + httpReq.Header.Set("Title", headerValue(msg.GetTitle())) + if msg.GetUrl() != "" { + httpReq.Header.Set("Click", headerValue(msg.GetUrl())) + } + if token != "" { + httpReq.Header.Set("Authorization", "Bearer "+token) + } + resp, err := c.http.Do(httpReq) + if err != nil { + // Network errors are temporary; the host retries. + return outcome(pluginv1.NotificationSendOutcome_NOTIFICATION_SEND_OUTCOME_RETRY, "Couldn't reach the ntfy server."), nil + } + defer resp.Body.Close() + respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10)) + + switch { + case resp.StatusCode < 300: + return outcome(pluginv1.NotificationSendOutcome_NOTIFICATION_SEND_OUTCOME_DELIVERED, ""), nil + case resp.StatusCode < 400: + // The client doesn't follow redirects: a redirect, such as to a + // proxy's login page, would turn the POST into a GET and its 200 + // would look like a delivery. + return outcome(pluginv1.NotificationSendOutcome_NOTIFICATION_SEND_OUTCOME_RETRY, fmt.Sprintf("The ntfy server redirected the message (%d).", resp.StatusCode)), nil + case refusedByNtfy(resp.StatusCode, respBody): + return outcome(pluginv1.NotificationSendOutcome_NOTIFICATION_SEND_OUTCOME_DESTINATION_INVALID, "ntfy refused the access token for this topic."), nil + case resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden: + // Not ntfy's own answer, so maybe a proxy in front of it: retry + // rather than disable a destination that may be fine. + return outcome(pluginv1.NotificationSendOutcome_NOTIFICATION_SEND_OUTCOME_RETRY, fmt.Sprintf("The ntfy server answered %d.", resp.StatusCode)), nil + case resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500: + out := outcome(pluginv1.NotificationSendOutcome_NOTIFICATION_SEND_OUTCOME_RETRY, fmt.Sprintf("ntfy answered %d.", resp.StatusCode)) + // Pass ntfy's wait through unshortened; the host applies its own cap. + if seconds, err := strconv.Atoi(resp.Header.Get("Retry-After")); err == nil && seconds > 0 { + out.RetryAfterSeconds = int32(min(seconds, math.MaxInt32)) + } + return out, nil + default: + return outcome(pluginv1.NotificationSendOutcome_NOTIFICATION_SEND_OUTCOME_FAILED, fmt.Sprintf("ntfy answered %d.", resp.StatusCode)), nil + } +} + +// refusedByNtfy reports whether a 401 or 403 is ntfy's own refusal of the +// topic's credentials, which comes as JSON such as +// {"code":40101,"http":401,"error":"unauthorized"}. A proxy or CDN in front +// of ntfy answers differently, and only ntfy's answer proves the +// destination's settings wrong. +func refusedByNtfy(status int, body []byte) bool { + if status != http.StatusUnauthorized && status != http.StatusForbidden { + return false + } + var ntfyErr struct { + Code int `json:"code"` + HTTP int `json:"http"` + } + return json.Unmarshal(body, &ntfyErr) == nil && ntfyErr.HTTP == status && ntfyErr.Code/100 == status +} + +func outcome(o pluginv1.NotificationSendOutcome, message string) *pluginv1.SendNotificationResponse { + return &pluginv1.SendNotificationResponse{Outcome: o, Message: message} +} + +// newHTTPClient returns a client that doesn't follow redirects, so +// SendNotification sees them. +func newHTTPClient() *http.Client { + return &http.Client{ + Timeout: 10 * time.Second, + CheckRedirect: func(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse + }, + } +} + +func main() { + ntfy := &channel{http: newHTTPClient(), serverURL: defaultServerURL} + sdkruntime.ServeManifestWithOptions(manifestJSON, version, sdkruntime.CapabilityServers{}, + sdkruntime.WithConfigure(ntfy.configure), + sdkruntime.WithNotificationChannel(ntfy), + ) +} diff --git a/examples/hello-notification-channel/main_test.go b/examples/hello-notification-channel/main_test.go new file mode 100644 index 0000000..ad8b7af --- /dev/null +++ b/examples/hello-notification-channel/main_test.go @@ -0,0 +1,88 @@ +package main + +import ( + "context" + "mime" + "net/http" + "net/http/httptest" + "testing" + + pluginv1 "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginproto/silo/plugin/v1" + "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/manifest" + "google.golang.org/protobuf/types/known/structpb" +) + +// TestManifestIsValid keeps the example's destination form within the rules +// hosts enforce at install. +func TestManifestIsValid(t *testing.T) { + if _, err := manifest.LoadWithChecksum(manifestJSON, "0.1.0"); err != nil { + t.Fatal(err) + } +} + +// send posts one message through a fake ntfy server and returns the outcome +// and the request the server saw. +func send(t *testing.T, title string, handler http.HandlerFunc) (*pluginv1.SendNotificationResponse, *http.Request) { + t.Helper() + var seen *http.Request + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if seen == nil { + seen = r + } + handler(w, r) + })) + t.Cleanup(srv.Close) + config, err := structpb.NewStruct(map[string]any{"topic": "alerts", "access_token": "tk_1"}) + if err != nil { + t.Fatal(err) + } + c := &channel{http: newHTTPClient(), serverURL: srv.URL} + resp, err := c.SendNotification(context.Background(), &pluginv1.SendNotificationRequest{ + Config: config, + Message: &pluginv1.NotificationMessage{Title: title, Body: "body"}, + }) + if err != nil { + t.Fatal(err) + } + return resp, seen +} + +func TestSendNotificationOutcomes(t *testing.T) { + for _, tc := range []struct { + name string + handler http.HandlerFunc + want pluginv1.NotificationSendOutcome + }{ + {"ntfy refuses the token", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusForbidden) + _, _ = w.Write([]byte(`{"code":40301,"http":403,"error":"forbidden"}`)) + }, pluginv1.NotificationSendOutcome_NOTIFICATION_SEND_OUTCOME_DESTINATION_INVALID}, + {"a proxy answers 401", func(w http.ResponseWriter, _ *http.Request) { + http.Error(w, "Sign in", http.StatusUnauthorized) + }, pluginv1.NotificationSendOutcome_NOTIFICATION_SEND_OUTCOME_RETRY}, + {"a redirect to a login page", func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/login" { + return // 200 to a GET: must not count as delivered + } + http.Redirect(w, r, "/login", http.StatusFound) + }, pluginv1.NotificationSendOutcome_NOTIFICATION_SEND_OUTCOME_RETRY}, + } { + t.Run(tc.name, func(t *testing.T) { + resp, _ := send(t, "title", tc.handler) + if resp.GetOutcome() != tc.want { + t.Fatalf("outcome = %v (%q), want %v", resp.GetOutcome(), resp.GetMessage(), tc.want) + } + }) + } +} + +func TestSendNotificationTitleHeader(t *testing.T) { + resp, seen := send(t, "Nouvel épisode\nde Severance", func(http.ResponseWriter, *http.Request) {}) + if resp.GetOutcome() != pluginv1.NotificationSendOutcome_NOTIFICATION_SEND_OUTCOME_DELIVERED { + t.Fatalf("outcome = %v (%q), want delivered", resp.GetOutcome(), resp.GetMessage()) + } + title, err := new(mime.WordDecoder).DecodeHeader(seen.Header.Get("Title")) + if err != nil || title != "Nouvel épisode de Severance" { + t.Fatalf("Title header decodes to %q (%v)", title, err) + } +} diff --git a/examples/hello-notification-channel/manifest.json b/examples/hello-notification-channel/manifest.json new file mode 100644 index 0000000..89ffa27 --- /dev/null +++ b/examples/hello-notification-channel/manifest.json @@ -0,0 +1,66 @@ +{ + "plugin_id": "example.hello-ntfy", + "version": "0.1.0", + "checksum": "__CHECKSUM__", + "silo_api_version": "v1", + "category": "Notifications", + "supported_platforms": [ + { "os": "linux", "arch": "amd64" }, + { "os": "linux", "arch": "arm64" }, + { "os": "darwin", "arch": "arm64" } + ], + "capabilities": [ + { + "type": "notification_channel.v1", + "id": "ntfy", + "display_name": "ntfy", + "description": "Sends Silo notifications to an ntfy topic.", + "notification_channel": { + "display_name": "ntfy", + "description": "Push notifications to a topic on the ntfy server your administrator chose. Subscribe to the topic in the ntfy app.", + "destination_schema": { + "key": "destination", + "title": "ntfy topic", + "json_schema": "{\"type\":\"object\",\"properties\":{\"topic\":{\"type\":\"string\"},\"access_token\":{\"type\":\"string\"}},\"required\":[\"topic\"],\"additionalProperties\":false}", + "admin_form": { + "fields": [ + { + "key": "topic", + "label": "Topic", + "description": "Letters, digits, hyphens and underscores. Anyone who knows a topic on a public server can read it, so pick one that's hard to guess.", + "control": "ADMIN_FORM_CONTROL_TEXT", + "required": true, + "placeholder": "silo-alerts-7f3k" + }, + { + "key": "access_token", + "label": "Access token (optional)", + "description": "Needed when the topic is protected.", + "control": "ADMIN_FORM_CONTROL_PASSWORD", + "secret": true + } + ] + } + } + } + } + ], + "global_config_schema": [ + { + "key": "ntfy", + "title": "ntfy server", + "json_schema": "{\"type\":\"object\",\"properties\":{\"server_url\":{\"type\":\"string\"}},\"additionalProperties\":false}", + "admin_form": { + "fields": [ + { + "key": "server_url", + "label": "Server URL", + "description": "The ntfy server every destination posts to. Leave blank for https://ntfy.sh.", + "control": "ADMIN_FORM_CONTROL_TEXT", + "placeholder": "https://ntfy.sh" + } + ] + } + } + ] +} diff --git a/pkg/pluginproto/silo/plugin/v1/common.pb.go b/pkg/pluginproto/silo/plugin/v1/common.pb.go index b8060c0..a0d4b31 100644 --- a/pkg/pluginproto/silo/plugin/v1/common.pb.go +++ b/pkg/pluginproto/silo/plugin/v1/common.pb.go @@ -988,6 +988,9 @@ type CapabilityDescriptor struct { // of type "request_router.v1". Optional: an absent descriptor declares no // optional request-router features. RequestRouter *RequestRouterDescriptor `protobuf:"bytes,12,opt,name=request_router,json=requestRouter,proto3" json:"request_router,omitempty"` + // Typed notification-channel contract metadata. Required for, and only + // meaningful on, capabilities of type "notification_channel.v1". + NotificationChannel *NotificationChannelDescriptor `protobuf:"bytes,13,opt,name=notification_channel,json=notificationChannel,proto3" json:"notification_channel,omitempty"` // Typed scheduled-task metadata. Optional, and only meaningful on // capabilities of type "scheduled_task.v1". A host that predates the field // ignores it only if it drops unknown fields wherever it reads the @@ -1113,6 +1116,13 @@ func (x *CapabilityDescriptor) GetRequestRouter() *RequestRouterDescriptor { return nil } +func (x *CapabilityDescriptor) GetNotificationChannel() *NotificationChannelDescriptor { + if x != nil { + return x.NotificationChannel + } + return nil +} + func (x *CapabilityDescriptor) GetScheduledTask() *ScheduledTaskDescriptor { if x != nil { return x.ScheduledTask @@ -1120,6 +1130,74 @@ func (x *CapabilityDescriptor) GetScheduledTask() *ScheduledTaskDescriptor { return nil } +// NotificationChannelDescriptor declares the kind of destination a +// notification_channel.v1 capability provides. The host lists it without +// starting the plugin. +type NotificationChannelDescriptor struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Name of the destination kind, shown when adding one, such as "Pushover". + DisplayName string `protobuf:"bytes,1,opt,name=display_name,json=displayName,proto3" json:"display_name,omitempty"` + // One or two sentences on what the destination is and what it needs. + Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` + // The settings form for one destination: a JSON schema and an admin_form, + // validated like any ConfigSchema. Every value is stored encrypted. Fields + // marked secret are write-only: the host never returns them. + DestinationSchema *ConfigSchema `protobuf:"bytes,3,opt,name=destination_schema,json=destinationSchema,proto3" json:"destination_schema,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *NotificationChannelDescriptor) Reset() { + *x = NotificationChannelDescriptor{} + mi := &file_silo_plugin_v1_common_proto_msgTypes[12] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *NotificationChannelDescriptor) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*NotificationChannelDescriptor) ProtoMessage() {} + +func (x *NotificationChannelDescriptor) ProtoReflect() protoreflect.Message { + mi := &file_silo_plugin_v1_common_proto_msgTypes[12] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use NotificationChannelDescriptor.ProtoReflect.Descriptor instead. +func (*NotificationChannelDescriptor) Descriptor() ([]byte, []int) { + return file_silo_plugin_v1_common_proto_rawDescGZIP(), []int{12} +} + +func (x *NotificationChannelDescriptor) GetDisplayName() string { + if x != nil { + return x.DisplayName + } + return "" +} + +func (x *NotificationChannelDescriptor) GetDescription() string { + if x != nil { + return x.Description + } + return "" +} + +func (x *NotificationChannelDescriptor) GetDestinationSchema() *ConfigSchema { + if x != nil { + return x.DestinationSchema + } + return nil +} + // ScheduledTaskDescriptor describes a scheduled_task.v1 capability. type ScheduledTaskDescriptor struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -1132,7 +1210,7 @@ type ScheduledTaskDescriptor struct { func (x *ScheduledTaskDescriptor) Reset() { *x = ScheduledTaskDescriptor{} - mi := &file_silo_plugin_v1_common_proto_msgTypes[12] + mi := &file_silo_plugin_v1_common_proto_msgTypes[13] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1144,7 +1222,7 @@ func (x *ScheduledTaskDescriptor) String() string { func (*ScheduledTaskDescriptor) ProtoMessage() {} func (x *ScheduledTaskDescriptor) ProtoReflect() protoreflect.Message { - mi := &file_silo_plugin_v1_common_proto_msgTypes[12] + mi := &file_silo_plugin_v1_common_proto_msgTypes[13] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1157,7 +1235,7 @@ func (x *ScheduledTaskDescriptor) ProtoReflect() protoreflect.Message { // Deprecated: Use ScheduledTaskDescriptor.ProtoReflect.Descriptor instead. func (*ScheduledTaskDescriptor) Descriptor() ([]byte, []int) { - return file_silo_plugin_v1_common_proto_rawDescGZIP(), []int{12} + return file_silo_plugin_v1_common_proto_rawDescGZIP(), []int{13} } func (x *ScheduledTaskDescriptor) GetDefaultTrigger() *ScheduledTaskTrigger { @@ -1186,7 +1264,7 @@ type ScheduledTaskTrigger struct { func (x *ScheduledTaskTrigger) Reset() { *x = ScheduledTaskTrigger{} - mi := &file_silo_plugin_v1_common_proto_msgTypes[13] + mi := &file_silo_plugin_v1_common_proto_msgTypes[14] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1198,7 +1276,7 @@ func (x *ScheduledTaskTrigger) String() string { func (*ScheduledTaskTrigger) ProtoMessage() {} func (x *ScheduledTaskTrigger) ProtoReflect() protoreflect.Message { - mi := &file_silo_plugin_v1_common_proto_msgTypes[13] + mi := &file_silo_plugin_v1_common_proto_msgTypes[14] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1211,7 +1289,7 @@ func (x *ScheduledTaskTrigger) ProtoReflect() protoreflect.Message { // Deprecated: Use ScheduledTaskTrigger.ProtoReflect.Descriptor instead. func (*ScheduledTaskTrigger) Descriptor() ([]byte, []int) { - return file_silo_plugin_v1_common_proto_rawDescGZIP(), []int{13} + return file_silo_plugin_v1_common_proto_rawDescGZIP(), []int{14} } func (x *ScheduledTaskTrigger) GetType() string { @@ -1264,7 +1342,7 @@ type PluginPresentation struct { func (x *PluginPresentation) Reset() { *x = PluginPresentation{} - mi := &file_silo_plugin_v1_common_proto_msgTypes[14] + mi := &file_silo_plugin_v1_common_proto_msgTypes[15] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1276,7 +1354,7 @@ func (x *PluginPresentation) String() string { func (*PluginPresentation) ProtoMessage() {} func (x *PluginPresentation) ProtoReflect() protoreflect.Message { - mi := &file_silo_plugin_v1_common_proto_msgTypes[14] + mi := &file_silo_plugin_v1_common_proto_msgTypes[15] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1289,7 +1367,7 @@ func (x *PluginPresentation) ProtoReflect() protoreflect.Message { // Deprecated: Use PluginPresentation.ProtoReflect.Descriptor instead. func (*PluginPresentation) Descriptor() ([]byte, []int) { - return file_silo_plugin_v1_common_proto_rawDescGZIP(), []int{14} + return file_silo_plugin_v1_common_proto_rawDescGZIP(), []int{15} } func (x *PluginPresentation) GetDisplayName() string { @@ -1405,7 +1483,7 @@ type PluginManifest struct { func (x *PluginManifest) Reset() { *x = PluginManifest{} - mi := &file_silo_plugin_v1_common_proto_msgTypes[15] + mi := &file_silo_plugin_v1_common_proto_msgTypes[16] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1417,7 +1495,7 @@ func (x *PluginManifest) String() string { func (*PluginManifest) ProtoMessage() {} func (x *PluginManifest) ProtoReflect() protoreflect.Message { - mi := &file_silo_plugin_v1_common_proto_msgTypes[15] + mi := &file_silo_plugin_v1_common_proto_msgTypes[16] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1430,7 +1508,7 @@ func (x *PluginManifest) ProtoReflect() protoreflect.Message { // Deprecated: Use PluginManifest.ProtoReflect.Descriptor instead. func (*PluginManifest) Descriptor() ([]byte, []int) { - return file_silo_plugin_v1_common_proto_rawDescGZIP(), []int{15} + return file_silo_plugin_v1_common_proto_rawDescGZIP(), []int{16} } func (x *PluginManifest) GetPluginId() string { @@ -1539,7 +1617,7 @@ type GetManifestRequest struct { func (x *GetManifestRequest) Reset() { *x = GetManifestRequest{} - mi := &file_silo_plugin_v1_common_proto_msgTypes[16] + mi := &file_silo_plugin_v1_common_proto_msgTypes[17] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1551,7 +1629,7 @@ func (x *GetManifestRequest) String() string { func (*GetManifestRequest) ProtoMessage() {} func (x *GetManifestRequest) ProtoReflect() protoreflect.Message { - mi := &file_silo_plugin_v1_common_proto_msgTypes[16] + mi := &file_silo_plugin_v1_common_proto_msgTypes[17] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1564,7 +1642,7 @@ func (x *GetManifestRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetManifestRequest.ProtoReflect.Descriptor instead. func (*GetManifestRequest) Descriptor() ([]byte, []int) { - return file_silo_plugin_v1_common_proto_rawDescGZIP(), []int{16} + return file_silo_plugin_v1_common_proto_rawDescGZIP(), []int{17} } type GetManifestResponse struct { @@ -1576,7 +1654,7 @@ type GetManifestResponse struct { func (x *GetManifestResponse) Reset() { *x = GetManifestResponse{} - mi := &file_silo_plugin_v1_common_proto_msgTypes[17] + mi := &file_silo_plugin_v1_common_proto_msgTypes[18] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1588,7 +1666,7 @@ func (x *GetManifestResponse) String() string { func (*GetManifestResponse) ProtoMessage() {} func (x *GetManifestResponse) ProtoReflect() protoreflect.Message { - mi := &file_silo_plugin_v1_common_proto_msgTypes[17] + mi := &file_silo_plugin_v1_common_proto_msgTypes[18] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1601,7 +1679,7 @@ func (x *GetManifestResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetManifestResponse.ProtoReflect.Descriptor instead. func (*GetManifestResponse) Descriptor() ([]byte, []int) { - return file_silo_plugin_v1_common_proto_rawDescGZIP(), []int{17} + return file_silo_plugin_v1_common_proto_rawDescGZIP(), []int{18} } func (x *GetManifestResponse) GetManifest() *PluginManifest { @@ -1620,7 +1698,7 @@ type ConfigureRequest struct { func (x *ConfigureRequest) Reset() { *x = ConfigureRequest{} - mi := &file_silo_plugin_v1_common_proto_msgTypes[18] + mi := &file_silo_plugin_v1_common_proto_msgTypes[19] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1632,7 +1710,7 @@ func (x *ConfigureRequest) String() string { func (*ConfigureRequest) ProtoMessage() {} func (x *ConfigureRequest) ProtoReflect() protoreflect.Message { - mi := &file_silo_plugin_v1_common_proto_msgTypes[18] + mi := &file_silo_plugin_v1_common_proto_msgTypes[19] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1645,7 +1723,7 @@ func (x *ConfigureRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ConfigureRequest.ProtoReflect.Descriptor instead. func (*ConfigureRequest) Descriptor() ([]byte, []int) { - return file_silo_plugin_v1_common_proto_rawDescGZIP(), []int{18} + return file_silo_plugin_v1_common_proto_rawDescGZIP(), []int{19} } func (x *ConfigureRequest) GetConfig() []*ConfigEntry { @@ -1663,7 +1741,7 @@ type ConfigureResponse struct { func (x *ConfigureResponse) Reset() { *x = ConfigureResponse{} - mi := &file_silo_plugin_v1_common_proto_msgTypes[19] + mi := &file_silo_plugin_v1_common_proto_msgTypes[20] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1675,7 +1753,7 @@ func (x *ConfigureResponse) String() string { func (*ConfigureResponse) ProtoMessage() {} func (x *ConfigureResponse) ProtoReflect() protoreflect.Message { - mi := &file_silo_plugin_v1_common_proto_msgTypes[19] + mi := &file_silo_plugin_v1_common_proto_msgTypes[20] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1688,7 +1766,7 @@ func (x *ConfigureResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ConfigureResponse.ProtoReflect.Descriptor instead. func (*ConfigureResponse) Descriptor() ([]byte, []int) { - return file_silo_plugin_v1_common_proto_rawDescGZIP(), []int{19} + return file_silo_plugin_v1_common_proto_rawDescGZIP(), []int{20} } type BindHostBrokerRequest struct { @@ -1700,7 +1778,7 @@ type BindHostBrokerRequest struct { func (x *BindHostBrokerRequest) Reset() { *x = BindHostBrokerRequest{} - mi := &file_silo_plugin_v1_common_proto_msgTypes[20] + mi := &file_silo_plugin_v1_common_proto_msgTypes[21] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1712,7 +1790,7 @@ func (x *BindHostBrokerRequest) String() string { func (*BindHostBrokerRequest) ProtoMessage() {} func (x *BindHostBrokerRequest) ProtoReflect() protoreflect.Message { - mi := &file_silo_plugin_v1_common_proto_msgTypes[20] + mi := &file_silo_plugin_v1_common_proto_msgTypes[21] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1725,7 +1803,7 @@ func (x *BindHostBrokerRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use BindHostBrokerRequest.ProtoReflect.Descriptor instead. func (*BindHostBrokerRequest) Descriptor() ([]byte, []int) { - return file_silo_plugin_v1_common_proto_rawDescGZIP(), []int{20} + return file_silo_plugin_v1_common_proto_rawDescGZIP(), []int{21} } func (x *BindHostBrokerRequest) GetBrokerId() uint32 { @@ -1743,7 +1821,7 @@ type BindHostBrokerResponse struct { func (x *BindHostBrokerResponse) Reset() { *x = BindHostBrokerResponse{} - mi := &file_silo_plugin_v1_common_proto_msgTypes[21] + mi := &file_silo_plugin_v1_common_proto_msgTypes[22] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1755,7 +1833,7 @@ func (x *BindHostBrokerResponse) String() string { func (*BindHostBrokerResponse) ProtoMessage() {} func (x *BindHostBrokerResponse) ProtoReflect() protoreflect.Message { - mi := &file_silo_plugin_v1_common_proto_msgTypes[21] + mi := &file_silo_plugin_v1_common_proto_msgTypes[22] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1768,7 +1846,7 @@ func (x *BindHostBrokerResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use BindHostBrokerResponse.ProtoReflect.Descriptor instead. func (*BindHostBrokerResponse) Descriptor() ([]byte, []int) { - return file_silo_plugin_v1_common_proto_rawDescGZIP(), []int{21} + return file_silo_plugin_v1_common_proto_rawDescGZIP(), []int{22} } var File_silo_plugin_v1_common_proto protoreflect.FileDescriptor @@ -1852,7 +1930,7 @@ const file_silo_plugin_v1_common_proto_rawDesc = "" + "\rPackagedAsset\x12\x12\n" + "\x04path\x18\x01 \x01(\tR\x04path\x12!\n" + "\fcontent_type\x18\x02 \x01(\tR\vcontentType\x12\x1c\n" + - "\tintegrity\x18\x03 \x01(\tR\tintegrity\"\xbd\x05\n" + + "\tintegrity\x18\x03 \x01(\tR\tintegrity\"\x9f\x06\n" + "\x14CapabilityDescriptor\x12\x12\n" + "\x04type\x18\x01 \x01(\tR\x04type\x12\x0e\n" + "\x02id\x18\x02 \x01(\tR\x02id\x12!\n" + @@ -1867,8 +1945,13 @@ const file_silo_plugin_v1_common_proto_rawDesc = "" + "\x13watch_sync_provider\x18\n" + " \x01(\v2+.silo.plugin.v1.WatchSyncProviderDescriptorR\x11watchSyncProvider\x12g\n" + "\x17network_access_provider\x18\v \x01(\v2/.silo.plugin.v1.NetworkAccessProviderDescriptorR\x15networkAccessProvider\x12N\n" + - "\x0erequest_router\x18\f \x01(\v2'.silo.plugin.v1.RequestRouterDescriptorR\rrequestRouter\x12N\n" + - "\x0escheduled_task\x18\x0e \x01(\v2'.silo.plugin.v1.ScheduledTaskDescriptorR\rscheduledTask\"h\n" + + "\x0erequest_router\x18\f \x01(\v2'.silo.plugin.v1.RequestRouterDescriptorR\rrequestRouter\x12`\n" + + "\x14notification_channel\x18\r \x01(\v2-.silo.plugin.v1.NotificationChannelDescriptorR\x13notificationChannel\x12N\n" + + "\x0escheduled_task\x18\x0e \x01(\v2'.silo.plugin.v1.ScheduledTaskDescriptorR\rscheduledTask\"\xb1\x01\n" + + "\x1dNotificationChannelDescriptor\x12!\n" + + "\fdisplay_name\x18\x01 \x01(\tR\vdisplayName\x12 \n" + + "\vdescription\x18\x02 \x01(\tR\vdescription\x12K\n" + + "\x12destination_schema\x18\x03 \x01(\v2\x1c.silo.plugin.v1.ConfigSchemaR\x11destinationSchema\"h\n" + "\x17ScheduledTaskDescriptor\x12M\n" + "\x0fdefault_trigger\x18\x01 \x01(\v2$.silo.plugin.v1.ScheduledTaskTriggerR\x0edefaultTrigger\"\x8b\x01\n" + "\x14ScheduledTaskTrigger\x12\x12\n" + @@ -1945,7 +2028,7 @@ func file_silo_plugin_v1_common_proto_rawDescGZIP() []byte { } var file_silo_plugin_v1_common_proto_enumTypes = make([]protoimpl.EnumInfo, 1) -var file_silo_plugin_v1_common_proto_msgTypes = make([]protoimpl.MessageInfo, 22) +var file_silo_plugin_v1_common_proto_msgTypes = make([]protoimpl.MessageInfo, 23) var file_silo_plugin_v1_common_proto_goTypes = []any{ (AdminFormControl)(0), // 0: silo.plugin.v1.AdminFormControl (*SupportedPlatform)(nil), // 1: silo.plugin.v1.SupportedPlatform @@ -1960,61 +2043,64 @@ var file_silo_plugin_v1_common_proto_goTypes = []any{ (*HttpRouteDescriptor)(nil), // 10: silo.plugin.v1.HttpRouteDescriptor (*PackagedAsset)(nil), // 11: silo.plugin.v1.PackagedAsset (*CapabilityDescriptor)(nil), // 12: silo.plugin.v1.CapabilityDescriptor - (*ScheduledTaskDescriptor)(nil), // 13: silo.plugin.v1.ScheduledTaskDescriptor - (*ScheduledTaskTrigger)(nil), // 14: silo.plugin.v1.ScheduledTaskTrigger - (*PluginPresentation)(nil), // 15: silo.plugin.v1.PluginPresentation - (*PluginManifest)(nil), // 16: silo.plugin.v1.PluginManifest - (*GetManifestRequest)(nil), // 17: silo.plugin.v1.GetManifestRequest - (*GetManifestResponse)(nil), // 18: silo.plugin.v1.GetManifestResponse - (*ConfigureRequest)(nil), // 19: silo.plugin.v1.ConfigureRequest - (*ConfigureResponse)(nil), // 20: silo.plugin.v1.ConfigureResponse - (*BindHostBrokerRequest)(nil), // 21: silo.plugin.v1.BindHostBrokerRequest - (*BindHostBrokerResponse)(nil), // 22: silo.plugin.v1.BindHostBrokerResponse - (*structpb.Value)(nil), // 23: google.protobuf.Value - (*structpb.Struct)(nil), // 24: google.protobuf.Struct - (*WatchSyncProviderDescriptor)(nil), // 25: silo.plugin.v1.WatchSyncProviderDescriptor - (*NetworkAccessProviderDescriptor)(nil), // 26: silo.plugin.v1.NetworkAccessProviderDescriptor - (*RequestRouterDescriptor)(nil), // 27: silo.plugin.v1.RequestRouterDescriptor + (*NotificationChannelDescriptor)(nil), // 13: silo.plugin.v1.NotificationChannelDescriptor + (*ScheduledTaskDescriptor)(nil), // 14: silo.plugin.v1.ScheduledTaskDescriptor + (*ScheduledTaskTrigger)(nil), // 15: silo.plugin.v1.ScheduledTaskTrigger + (*PluginPresentation)(nil), // 16: silo.plugin.v1.PluginPresentation + (*PluginManifest)(nil), // 17: silo.plugin.v1.PluginManifest + (*GetManifestRequest)(nil), // 18: silo.plugin.v1.GetManifestRequest + (*GetManifestResponse)(nil), // 19: silo.plugin.v1.GetManifestResponse + (*ConfigureRequest)(nil), // 20: silo.plugin.v1.ConfigureRequest + (*ConfigureResponse)(nil), // 21: silo.plugin.v1.ConfigureResponse + (*BindHostBrokerRequest)(nil), // 22: silo.plugin.v1.BindHostBrokerRequest + (*BindHostBrokerResponse)(nil), // 23: silo.plugin.v1.BindHostBrokerResponse + (*structpb.Value)(nil), // 24: google.protobuf.Value + (*structpb.Struct)(nil), // 25: google.protobuf.Struct + (*WatchSyncProviderDescriptor)(nil), // 26: silo.plugin.v1.WatchSyncProviderDescriptor + (*NetworkAccessProviderDescriptor)(nil), // 27: silo.plugin.v1.NetworkAccessProviderDescriptor + (*RequestRouterDescriptor)(nil), // 28: silo.plugin.v1.RequestRouterDescriptor } var file_silo_plugin_v1_common_proto_depIdxs = []int32{ 8, // 0: silo.plugin.v1.ConfigSchema.admin_form:type_name -> silo.plugin.v1.AdminFormDescriptor 0, // 1: silo.plugin.v1.AdminFormField.control:type_name -> silo.plugin.v1.AdminFormControl - 23, // 2: silo.plugin.v1.AdminFormField.default_value:type_name -> google.protobuf.Value + 24, // 2: silo.plugin.v1.AdminFormField.default_value:type_name -> google.protobuf.Value 3, // 3: silo.plugin.v1.AdminFormField.options:type_name -> silo.plugin.v1.AdminFormOption 5, // 4: silo.plugin.v1.AdminFormField.show_when:type_name -> silo.plugin.v1.AdminFormCondition 6, // 5: silo.plugin.v1.AdminFormField.validation:type_name -> silo.plugin.v1.AdminFormValidation 5, // 6: silo.plugin.v1.AdminFormSection.show_when:type_name -> silo.plugin.v1.AdminFormCondition 4, // 7: silo.plugin.v1.AdminFormDescriptor.fields:type_name -> silo.plugin.v1.AdminFormField 7, // 8: silo.plugin.v1.AdminFormDescriptor.sections:type_name -> silo.plugin.v1.AdminFormSection - 24, // 9: silo.plugin.v1.ConfigEntry.value:type_name -> google.protobuf.Struct + 25, // 9: silo.plugin.v1.ConfigEntry.value:type_name -> google.protobuf.Struct 2, // 10: silo.plugin.v1.CapabilityDescriptor.config_schema:type_name -> silo.plugin.v1.ConfigSchema - 24, // 11: silo.plugin.v1.CapabilityDescriptor.metadata:type_name -> google.protobuf.Struct - 25, // 12: silo.plugin.v1.CapabilityDescriptor.watch_sync_provider:type_name -> silo.plugin.v1.WatchSyncProviderDescriptor - 26, // 13: silo.plugin.v1.CapabilityDescriptor.network_access_provider:type_name -> silo.plugin.v1.NetworkAccessProviderDescriptor - 27, // 14: silo.plugin.v1.CapabilityDescriptor.request_router:type_name -> silo.plugin.v1.RequestRouterDescriptor - 13, // 15: silo.plugin.v1.CapabilityDescriptor.scheduled_task:type_name -> silo.plugin.v1.ScheduledTaskDescriptor - 14, // 16: silo.plugin.v1.ScheduledTaskDescriptor.default_trigger:type_name -> silo.plugin.v1.ScheduledTaskTrigger - 1, // 17: silo.plugin.v1.PluginManifest.supported_platforms:type_name -> silo.plugin.v1.SupportedPlatform - 12, // 18: silo.plugin.v1.PluginManifest.capabilities:type_name -> silo.plugin.v1.CapabilityDescriptor - 2, // 19: silo.plugin.v1.PluginManifest.global_config_schema:type_name -> silo.plugin.v1.ConfigSchema - 2, // 20: silo.plugin.v1.PluginManifest.user_config_schema:type_name -> silo.plugin.v1.ConfigSchema - 10, // 21: silo.plugin.v1.PluginManifest.http_routes:type_name -> silo.plugin.v1.HttpRouteDescriptor - 11, // 22: silo.plugin.v1.PluginManifest.assets:type_name -> silo.plugin.v1.PackagedAsset - 24, // 23: silo.plugin.v1.PluginManifest.metadata:type_name -> google.protobuf.Struct - 15, // 24: silo.plugin.v1.PluginManifest.presentation:type_name -> silo.plugin.v1.PluginPresentation - 16, // 25: silo.plugin.v1.GetManifestResponse.manifest:type_name -> silo.plugin.v1.PluginManifest - 9, // 26: silo.plugin.v1.ConfigureRequest.config:type_name -> silo.plugin.v1.ConfigEntry - 17, // 27: silo.plugin.v1.Runtime.GetManifest:input_type -> silo.plugin.v1.GetManifestRequest - 19, // 28: silo.plugin.v1.Runtime.Configure:input_type -> silo.plugin.v1.ConfigureRequest - 21, // 29: silo.plugin.v1.Runtime.BindHostBroker:input_type -> silo.plugin.v1.BindHostBrokerRequest - 18, // 30: silo.plugin.v1.Runtime.GetManifest:output_type -> silo.plugin.v1.GetManifestResponse - 20, // 31: silo.plugin.v1.Runtime.Configure:output_type -> silo.plugin.v1.ConfigureResponse - 22, // 32: silo.plugin.v1.Runtime.BindHostBroker:output_type -> silo.plugin.v1.BindHostBrokerResponse - 30, // [30:33] is the sub-list for method output_type - 27, // [27:30] is the sub-list for method input_type - 27, // [27:27] is the sub-list for extension type_name - 27, // [27:27] is the sub-list for extension extendee - 0, // [0:27] is the sub-list for field type_name + 25, // 11: silo.plugin.v1.CapabilityDescriptor.metadata:type_name -> google.protobuf.Struct + 26, // 12: silo.plugin.v1.CapabilityDescriptor.watch_sync_provider:type_name -> silo.plugin.v1.WatchSyncProviderDescriptor + 27, // 13: silo.plugin.v1.CapabilityDescriptor.network_access_provider:type_name -> silo.plugin.v1.NetworkAccessProviderDescriptor + 28, // 14: silo.plugin.v1.CapabilityDescriptor.request_router:type_name -> silo.plugin.v1.RequestRouterDescriptor + 13, // 15: silo.plugin.v1.CapabilityDescriptor.notification_channel:type_name -> silo.plugin.v1.NotificationChannelDescriptor + 14, // 16: silo.plugin.v1.CapabilityDescriptor.scheduled_task:type_name -> silo.plugin.v1.ScheduledTaskDescriptor + 2, // 17: silo.plugin.v1.NotificationChannelDescriptor.destination_schema:type_name -> silo.plugin.v1.ConfigSchema + 15, // 18: silo.plugin.v1.ScheduledTaskDescriptor.default_trigger:type_name -> silo.plugin.v1.ScheduledTaskTrigger + 1, // 19: silo.plugin.v1.PluginManifest.supported_platforms:type_name -> silo.plugin.v1.SupportedPlatform + 12, // 20: silo.plugin.v1.PluginManifest.capabilities:type_name -> silo.plugin.v1.CapabilityDescriptor + 2, // 21: silo.plugin.v1.PluginManifest.global_config_schema:type_name -> silo.plugin.v1.ConfigSchema + 2, // 22: silo.plugin.v1.PluginManifest.user_config_schema:type_name -> silo.plugin.v1.ConfigSchema + 10, // 23: silo.plugin.v1.PluginManifest.http_routes:type_name -> silo.plugin.v1.HttpRouteDescriptor + 11, // 24: silo.plugin.v1.PluginManifest.assets:type_name -> silo.plugin.v1.PackagedAsset + 25, // 25: silo.plugin.v1.PluginManifest.metadata:type_name -> google.protobuf.Struct + 16, // 26: silo.plugin.v1.PluginManifest.presentation:type_name -> silo.plugin.v1.PluginPresentation + 17, // 27: silo.plugin.v1.GetManifestResponse.manifest:type_name -> silo.plugin.v1.PluginManifest + 9, // 28: silo.plugin.v1.ConfigureRequest.config:type_name -> silo.plugin.v1.ConfigEntry + 18, // 29: silo.plugin.v1.Runtime.GetManifest:input_type -> silo.plugin.v1.GetManifestRequest + 20, // 30: silo.plugin.v1.Runtime.Configure:input_type -> silo.plugin.v1.ConfigureRequest + 22, // 31: silo.plugin.v1.Runtime.BindHostBroker:input_type -> silo.plugin.v1.BindHostBrokerRequest + 19, // 32: silo.plugin.v1.Runtime.GetManifest:output_type -> silo.plugin.v1.GetManifestResponse + 21, // 33: silo.plugin.v1.Runtime.Configure:output_type -> silo.plugin.v1.ConfigureResponse + 23, // 34: silo.plugin.v1.Runtime.BindHostBroker:output_type -> silo.plugin.v1.BindHostBrokerResponse + 32, // [32:35] is the sub-list for method output_type + 29, // [29:32] is the sub-list for method input_type + 29, // [29:29] is the sub-list for extension type_name + 29, // [29:29] is the sub-list for extension extendee + 0, // [0:29] is the sub-list for field type_name } func init() { file_silo_plugin_v1_common_proto_init() } @@ -2031,7 +2117,7 @@ func file_silo_plugin_v1_common_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_silo_plugin_v1_common_proto_rawDesc), len(file_silo_plugin_v1_common_proto_rawDesc)), NumEnums: 1, - NumMessages: 22, + NumMessages: 23, NumExtensions: 0, NumServices: 1, }, diff --git a/pkg/pluginproto/silo/plugin/v1/notification_channel.pb.go b/pkg/pluginproto/silo/plugin/v1/notification_channel.pb.go new file mode 100644 index 0000000..73e9b12 --- /dev/null +++ b/pkg/pluginproto/silo/plugin/v1/notification_channel.pb.go @@ -0,0 +1,577 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.11 +// protoc (unknown) +// source: silo/plugin/v1/notification_channel.proto + +package pluginv1 + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + structpb "google.golang.org/protobuf/types/known/structpb" + timestamppb "google.golang.org/protobuf/types/known/timestamppb" + reflect "reflect" + sync "sync" + unsafe "unsafe" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type NotificationSendOutcome int32 + +const ( + // An empty response acknowledges the message, like DELIVERED. + NotificationSendOutcome_NOTIFICATION_SEND_OUTCOME_UNSPECIFIED NotificationSendOutcome = 0 + NotificationSendOutcome_NOTIFICATION_SEND_OUTCOME_DELIVERED NotificationSendOutcome = 1 + // A temporary failure, such as a timeout or a rate limit. The host tries + // again later. + NotificationSendOutcome_NOTIFICATION_SEND_OUTCOME_RETRY NotificationSendOutcome = 2 + // This message can't be delivered, but the destination still works. The + // host drops the message. + NotificationSendOutcome_NOTIFICATION_SEND_OUTCOME_FAILED NotificationSendOutcome = 3 + // The destination's settings no longer work, such as a revoked key. The + // host drops the message and disables the destination until its owner + // fixes it. + NotificationSendOutcome_NOTIFICATION_SEND_OUTCOME_DESTINATION_INVALID NotificationSendOutcome = 4 +) + +// Enum value maps for NotificationSendOutcome. +var ( + NotificationSendOutcome_name = map[int32]string{ + 0: "NOTIFICATION_SEND_OUTCOME_UNSPECIFIED", + 1: "NOTIFICATION_SEND_OUTCOME_DELIVERED", + 2: "NOTIFICATION_SEND_OUTCOME_RETRY", + 3: "NOTIFICATION_SEND_OUTCOME_FAILED", + 4: "NOTIFICATION_SEND_OUTCOME_DESTINATION_INVALID", + } + NotificationSendOutcome_value = map[string]int32{ + "NOTIFICATION_SEND_OUTCOME_UNSPECIFIED": 0, + "NOTIFICATION_SEND_OUTCOME_DELIVERED": 1, + "NOTIFICATION_SEND_OUTCOME_RETRY": 2, + "NOTIFICATION_SEND_OUTCOME_FAILED": 3, + "NOTIFICATION_SEND_OUTCOME_DESTINATION_INVALID": 4, + } +) + +func (x NotificationSendOutcome) Enum() *NotificationSendOutcome { + p := new(NotificationSendOutcome) + *p = x + return p +} + +func (x NotificationSendOutcome) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (NotificationSendOutcome) Descriptor() protoreflect.EnumDescriptor { + return file_silo_plugin_v1_notification_channel_proto_enumTypes[0].Descriptor() +} + +func (NotificationSendOutcome) Type() protoreflect.EnumType { + return &file_silo_plugin_v1_notification_channel_proto_enumTypes[0] +} + +func (x NotificationSendOutcome) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use NotificationSendOutcome.Descriptor instead. +func (NotificationSendOutcome) EnumDescriptor() ([]byte, []int) { + return file_silo_plugin_v1_notification_channel_proto_rawDescGZIP(), []int{0} +} + +type ValidateNotificationDestinationRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + // The settings as the user entered them, keyed by destination_schema + // property. On an edit, secret fields the user left unchanged carry their + // stored values. + Config *structpb.Struct `protobuf:"bytes,1,opt,name=config,proto3" json:"config,omitempty"` + // The notification_channel.v1 capability the destination belongs to. + CapabilityId string `protobuf:"bytes,2,opt,name=capability_id,json=capabilityId,proto3" json:"capability_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ValidateNotificationDestinationRequest) Reset() { + *x = ValidateNotificationDestinationRequest{} + mi := &file_silo_plugin_v1_notification_channel_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ValidateNotificationDestinationRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ValidateNotificationDestinationRequest) ProtoMessage() {} + +func (x *ValidateNotificationDestinationRequest) ProtoReflect() protoreflect.Message { + mi := &file_silo_plugin_v1_notification_channel_proto_msgTypes[0] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ValidateNotificationDestinationRequest.ProtoReflect.Descriptor instead. +func (*ValidateNotificationDestinationRequest) Descriptor() ([]byte, []int) { + return file_silo_plugin_v1_notification_channel_proto_rawDescGZIP(), []int{0} +} + +func (x *ValidateNotificationDestinationRequest) GetConfig() *structpb.Struct { + if x != nil { + return x.Config + } + return nil +} + +func (x *ValidateNotificationDestinationRequest) GetCapabilityId() string { + if x != nil { + return x.CapabilityId + } + return "" +} + +type ValidateNotificationDestinationResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Valid bool `protobuf:"varint,1,opt,name=valid,proto3" json:"valid,omitempty"` + // Why the settings don't work, shown to the user when valid is false. + // Never include secrets. + Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ValidateNotificationDestinationResponse) Reset() { + *x = ValidateNotificationDestinationResponse{} + mi := &file_silo_plugin_v1_notification_channel_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ValidateNotificationDestinationResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ValidateNotificationDestinationResponse) ProtoMessage() {} + +func (x *ValidateNotificationDestinationResponse) ProtoReflect() protoreflect.Message { + mi := &file_silo_plugin_v1_notification_channel_proto_msgTypes[1] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ValidateNotificationDestinationResponse.ProtoReflect.Descriptor instead. +func (*ValidateNotificationDestinationResponse) Descriptor() ([]byte, []int) { + return file_silo_plugin_v1_notification_channel_proto_rawDescGZIP(), []int{1} +} + +func (x *ValidateNotificationDestinationResponse) GetValid() bool { + if x != nil { + return x.Valid + } + return false +} + +func (x *ValidateNotificationDestinationResponse) GetMessage() string { + if x != nil { + return x.Message + } + return "" +} + +type SendNotificationRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + // The destination's ID, stable for its lifetime. + DestinationId string `protobuf:"bytes,1,opt,name=destination_id,json=destinationId,proto3" json:"destination_id,omitempty"` + // The destination's saved settings, secrets included. + Config *structpb.Struct `protobuf:"bytes,2,opt,name=config,proto3" json:"config,omitempty"` + Message *NotificationMessage `protobuf:"bytes,3,opt,name=message,proto3" json:"message,omitempty"` + // Identifies this message to this destination. It is the same on every + // attempt, so pass it to the service as an idempotency key where it has + // one. + DeliveryKey string `protobuf:"bytes,4,opt,name=delivery_key,json=deliveryKey,proto3" json:"delivery_key,omitempty"` + // 1 on the first attempt. + Attempt int32 `protobuf:"varint,5,opt,name=attempt,proto3" json:"attempt,omitempty"` + // True for a test message the user asked for. The host doesn't retry it + // or count its failure. + Test bool `protobuf:"varint,6,opt,name=test,proto3" json:"test,omitempty"` + // The notification_channel.v1 capability the destination belongs to. + CapabilityId string `protobuf:"bytes,7,opt,name=capability_id,json=capabilityId,proto3" json:"capability_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SendNotificationRequest) Reset() { + *x = SendNotificationRequest{} + mi := &file_silo_plugin_v1_notification_channel_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SendNotificationRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SendNotificationRequest) ProtoMessage() {} + +func (x *SendNotificationRequest) ProtoReflect() protoreflect.Message { + mi := &file_silo_plugin_v1_notification_channel_proto_msgTypes[2] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SendNotificationRequest.ProtoReflect.Descriptor instead. +func (*SendNotificationRequest) Descriptor() ([]byte, []int) { + return file_silo_plugin_v1_notification_channel_proto_rawDescGZIP(), []int{2} +} + +func (x *SendNotificationRequest) GetDestinationId() string { + if x != nil { + return x.DestinationId + } + return "" +} + +func (x *SendNotificationRequest) GetConfig() *structpb.Struct { + if x != nil { + return x.Config + } + return nil +} + +func (x *SendNotificationRequest) GetMessage() *NotificationMessage { + if x != nil { + return x.Message + } + return nil +} + +func (x *SendNotificationRequest) GetDeliveryKey() string { + if x != nil { + return x.DeliveryKey + } + return "" +} + +func (x *SendNotificationRequest) GetAttempt() int32 { + if x != nil { + return x.Attempt + } + return 0 +} + +func (x *SendNotificationRequest) GetTest() bool { + if x != nil { + return x.Test + } + return false +} + +func (x *SendNotificationRequest) GetCapabilityId() string { + if x != nil { + return x.CapabilityId + } + return "" +} + +// NotificationMessage is one notification, rendered by the host. +type NotificationMessage struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Type of the notification, such as "episode.available", + // "watchlist.available", "request.approved", "request.declined", + // "request.fulfilled" or "test". The vocabulary is open. + Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"` + // Short title, such as "New episode of Severance". + Title string `protobuf:"bytes,2,opt,name=title,proto3" json:"title,omitempty"` + // One or two lines of plain text. + Body string `protobuf:"bytes,3,opt,name=body,proto3" json:"body,omitempty"` + // Absolute link that opens the item in Silo. Empty when the host has no + // public URL. + Url string `protobuf:"bytes,4,opt,name=url,proto3" json:"url,omitempty"` + // Absolute URL of a poster or still, when there is one. It can expire. + ImageUrl string `protobuf:"bytes,5,opt,name=image_url,json=imageUrl,proto3" json:"image_url,omitempty"` + CreatedAt *timestamppb.Timestamp `protobuf:"bytes,6,opt,name=created_at,json=createdAt,proto3" json:"created_at,omitempty"` + // The notification's details, shaped as the events package's + // Notification type, for plugins that render their own text. Empty for a + // test message. + Details *structpb.Struct `protobuf:"bytes,7,opt,name=details,proto3" json:"details,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *NotificationMessage) Reset() { + *x = NotificationMessage{} + mi := &file_silo_plugin_v1_notification_channel_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *NotificationMessage) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*NotificationMessage) ProtoMessage() {} + +func (x *NotificationMessage) ProtoReflect() protoreflect.Message { + mi := &file_silo_plugin_v1_notification_channel_proto_msgTypes[3] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use NotificationMessage.ProtoReflect.Descriptor instead. +func (*NotificationMessage) Descriptor() ([]byte, []int) { + return file_silo_plugin_v1_notification_channel_proto_rawDescGZIP(), []int{3} +} + +func (x *NotificationMessage) GetType() string { + if x != nil { + return x.Type + } + return "" +} + +func (x *NotificationMessage) GetTitle() string { + if x != nil { + return x.Title + } + return "" +} + +func (x *NotificationMessage) GetBody() string { + if x != nil { + return x.Body + } + return "" +} + +func (x *NotificationMessage) GetUrl() string { + if x != nil { + return x.Url + } + return "" +} + +func (x *NotificationMessage) GetImageUrl() string { + if x != nil { + return x.ImageUrl + } + return "" +} + +func (x *NotificationMessage) GetCreatedAt() *timestamppb.Timestamp { + if x != nil { + return x.CreatedAt + } + return nil +} + +func (x *NotificationMessage) GetDetails() *structpb.Struct { + if x != nil { + return x.Details + } + return nil +} + +type SendNotificationResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Outcome NotificationSendOutcome `protobuf:"varint,1,opt,name=outcome,proto3,enum=silo.plugin.v1.NotificationSendOutcome" json:"outcome,omitempty"` + // Short reason for a failure, shown to the destination's owner. Never + // include secrets. + Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"` + // With RETRY: wait at least this long before the next attempt, up to a + // host cap (six hours on Silo). A plugin asked to wait longer is called + // again sooner and should answer RETRY with the wait that remains. It + // never shortens the host's own delay. 0 leaves the delay to the host. + RetryAfterSeconds int32 `protobuf:"varint,3,opt,name=retry_after_seconds,json=retryAfterSeconds,proto3" json:"retry_after_seconds,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SendNotificationResponse) Reset() { + *x = SendNotificationResponse{} + mi := &file_silo_plugin_v1_notification_channel_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SendNotificationResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SendNotificationResponse) ProtoMessage() {} + +func (x *SendNotificationResponse) ProtoReflect() protoreflect.Message { + mi := &file_silo_plugin_v1_notification_channel_proto_msgTypes[4] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SendNotificationResponse.ProtoReflect.Descriptor instead. +func (*SendNotificationResponse) Descriptor() ([]byte, []int) { + return file_silo_plugin_v1_notification_channel_proto_rawDescGZIP(), []int{4} +} + +func (x *SendNotificationResponse) GetOutcome() NotificationSendOutcome { + if x != nil { + return x.Outcome + } + return NotificationSendOutcome_NOTIFICATION_SEND_OUTCOME_UNSPECIFIED +} + +func (x *SendNotificationResponse) GetMessage() string { + if x != nil { + return x.Message + } + return "" +} + +func (x *SendNotificationResponse) GetRetryAfterSeconds() int32 { + if x != nil { + return x.RetryAfterSeconds + } + return 0 +} + +var File_silo_plugin_v1_notification_channel_proto protoreflect.FileDescriptor + +const file_silo_plugin_v1_notification_channel_proto_rawDesc = "" + + "\n" + + ")silo/plugin/v1/notification_channel.proto\x12\x0esilo.plugin.v1\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto\"~\n" + + "&ValidateNotificationDestinationRequest\x12/\n" + + "\x06config\x18\x01 \x01(\v2\x17.google.protobuf.StructR\x06config\x12#\n" + + "\rcapability_id\x18\x02 \x01(\tR\fcapabilityId\"Y\n" + + "'ValidateNotificationDestinationResponse\x12\x14\n" + + "\x05valid\x18\x01 \x01(\bR\x05valid\x12\x18\n" + + "\amessage\x18\x02 \x01(\tR\amessage\"\xa6\x02\n" + + "\x17SendNotificationRequest\x12%\n" + + "\x0edestination_id\x18\x01 \x01(\tR\rdestinationId\x12/\n" + + "\x06config\x18\x02 \x01(\v2\x17.google.protobuf.StructR\x06config\x12=\n" + + "\amessage\x18\x03 \x01(\v2#.silo.plugin.v1.NotificationMessageR\amessage\x12!\n" + + "\fdelivery_key\x18\x04 \x01(\tR\vdeliveryKey\x12\x18\n" + + "\aattempt\x18\x05 \x01(\x05R\aattempt\x12\x12\n" + + "\x04test\x18\x06 \x01(\bR\x04test\x12#\n" + + "\rcapability_id\x18\a \x01(\tR\fcapabilityId\"\xf0\x01\n" + + "\x13NotificationMessage\x12\x12\n" + + "\x04type\x18\x01 \x01(\tR\x04type\x12\x14\n" + + "\x05title\x18\x02 \x01(\tR\x05title\x12\x12\n" + + "\x04body\x18\x03 \x01(\tR\x04body\x12\x10\n" + + "\x03url\x18\x04 \x01(\tR\x03url\x12\x1b\n" + + "\timage_url\x18\x05 \x01(\tR\bimageUrl\x129\n" + + "\n" + + "created_at\x18\x06 \x01(\v2\x1a.google.protobuf.TimestampR\tcreatedAt\x121\n" + + "\adetails\x18\a \x01(\v2\x17.google.protobuf.StructR\adetails\"\xa7\x01\n" + + "\x18SendNotificationResponse\x12A\n" + + "\aoutcome\x18\x01 \x01(\x0e2'.silo.plugin.v1.NotificationSendOutcomeR\aoutcome\x12\x18\n" + + "\amessage\x18\x02 \x01(\tR\amessage\x12.\n" + + "\x13retry_after_seconds\x18\x03 \x01(\x05R\x11retryAfterSeconds*\xeb\x01\n" + + "\x17NotificationSendOutcome\x12)\n" + + "%NOTIFICATION_SEND_OUTCOME_UNSPECIFIED\x10\x00\x12'\n" + + "#NOTIFICATION_SEND_OUTCOME_DELIVERED\x10\x01\x12#\n" + + "\x1fNOTIFICATION_SEND_OUTCOME_RETRY\x10\x02\x12$\n" + + " NOTIFICATION_SEND_OUTCOME_FAILED\x10\x03\x121\n" + + "-NOTIFICATION_SEND_OUTCOME_DESTINATION_INVALID\x10\x042\x85\x02\n" + + "\x13NotificationChannel\x12\x86\x01\n" + + "\x13ValidateDestination\x126.silo.plugin.v1.ValidateNotificationDestinationRequest\x1a7.silo.plugin.v1.ValidateNotificationDestinationResponse\x12e\n" + + "\x10SendNotification\x12'.silo.plugin.v1.SendNotificationRequest\x1a(.silo.plugin.v1.SendNotificationResponseBPZNgithub.com/Silo-Server/silo-plugin-sdk/pkg/pluginproto/silo/plugin/v1;pluginv1b\x06proto3" + +var ( + file_silo_plugin_v1_notification_channel_proto_rawDescOnce sync.Once + file_silo_plugin_v1_notification_channel_proto_rawDescData []byte +) + +func file_silo_plugin_v1_notification_channel_proto_rawDescGZIP() []byte { + file_silo_plugin_v1_notification_channel_proto_rawDescOnce.Do(func() { + file_silo_plugin_v1_notification_channel_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_silo_plugin_v1_notification_channel_proto_rawDesc), len(file_silo_plugin_v1_notification_channel_proto_rawDesc))) + }) + return file_silo_plugin_v1_notification_channel_proto_rawDescData +} + +var file_silo_plugin_v1_notification_channel_proto_enumTypes = make([]protoimpl.EnumInfo, 1) +var file_silo_plugin_v1_notification_channel_proto_msgTypes = make([]protoimpl.MessageInfo, 5) +var file_silo_plugin_v1_notification_channel_proto_goTypes = []any{ + (NotificationSendOutcome)(0), // 0: silo.plugin.v1.NotificationSendOutcome + (*ValidateNotificationDestinationRequest)(nil), // 1: silo.plugin.v1.ValidateNotificationDestinationRequest + (*ValidateNotificationDestinationResponse)(nil), // 2: silo.plugin.v1.ValidateNotificationDestinationResponse + (*SendNotificationRequest)(nil), // 3: silo.plugin.v1.SendNotificationRequest + (*NotificationMessage)(nil), // 4: silo.plugin.v1.NotificationMessage + (*SendNotificationResponse)(nil), // 5: silo.plugin.v1.SendNotificationResponse + (*structpb.Struct)(nil), // 6: google.protobuf.Struct + (*timestamppb.Timestamp)(nil), // 7: google.protobuf.Timestamp +} +var file_silo_plugin_v1_notification_channel_proto_depIdxs = []int32{ + 6, // 0: silo.plugin.v1.ValidateNotificationDestinationRequest.config:type_name -> google.protobuf.Struct + 6, // 1: silo.plugin.v1.SendNotificationRequest.config:type_name -> google.protobuf.Struct + 4, // 2: silo.plugin.v1.SendNotificationRequest.message:type_name -> silo.plugin.v1.NotificationMessage + 7, // 3: silo.plugin.v1.NotificationMessage.created_at:type_name -> google.protobuf.Timestamp + 6, // 4: silo.plugin.v1.NotificationMessage.details:type_name -> google.protobuf.Struct + 0, // 5: silo.plugin.v1.SendNotificationResponse.outcome:type_name -> silo.plugin.v1.NotificationSendOutcome + 1, // 6: silo.plugin.v1.NotificationChannel.ValidateDestination:input_type -> silo.plugin.v1.ValidateNotificationDestinationRequest + 3, // 7: silo.plugin.v1.NotificationChannel.SendNotification:input_type -> silo.plugin.v1.SendNotificationRequest + 2, // 8: silo.plugin.v1.NotificationChannel.ValidateDestination:output_type -> silo.plugin.v1.ValidateNotificationDestinationResponse + 5, // 9: silo.plugin.v1.NotificationChannel.SendNotification:output_type -> silo.plugin.v1.SendNotificationResponse + 8, // [8:10] is the sub-list for method output_type + 6, // [6:8] is the sub-list for method input_type + 6, // [6:6] is the sub-list for extension type_name + 6, // [6:6] is the sub-list for extension extendee + 0, // [0:6] is the sub-list for field type_name +} + +func init() { file_silo_plugin_v1_notification_channel_proto_init() } +func file_silo_plugin_v1_notification_channel_proto_init() { + if File_silo_plugin_v1_notification_channel_proto != nil { + return + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_silo_plugin_v1_notification_channel_proto_rawDesc), len(file_silo_plugin_v1_notification_channel_proto_rawDesc)), + NumEnums: 1, + NumMessages: 5, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_silo_plugin_v1_notification_channel_proto_goTypes, + DependencyIndexes: file_silo_plugin_v1_notification_channel_proto_depIdxs, + EnumInfos: file_silo_plugin_v1_notification_channel_proto_enumTypes, + MessageInfos: file_silo_plugin_v1_notification_channel_proto_msgTypes, + }.Build() + File_silo_plugin_v1_notification_channel_proto = out.File + file_silo_plugin_v1_notification_channel_proto_goTypes = nil + file_silo_plugin_v1_notification_channel_proto_depIdxs = nil +} diff --git a/pkg/pluginproto/silo/plugin/v1/notification_channel_grpc.pb.go b/pkg/pluginproto/silo/plugin/v1/notification_channel_grpc.pb.go new file mode 100644 index 0000000..f459219 --- /dev/null +++ b/pkg/pluginproto/silo/plugin/v1/notification_channel_grpc.pb.go @@ -0,0 +1,193 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.6.1 +// - protoc (unknown) +// source: silo/plugin/v1/notification_channel.proto + +package pluginv1 + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.64.0 or later. +const _ = grpc.SupportPackageIsVersion9 + +const ( + NotificationChannel_ValidateDestination_FullMethodName = "/silo.plugin.v1.NotificationChannel/ValidateDestination" + NotificationChannel_SendNotification_FullMethodName = "/silo.plugin.v1.NotificationChannel/SendNotification" +) + +// NotificationChannelClient is the client API for NotificationChannel service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +// +// NotificationChannel delivers Silo notifications to a kind of destination +// the plugin provides, such as a push service or a chat app. A user adds a +// destination of that kind in their notification settings and fills in the +// form the descriptor declares. +// +// The host owns everything else: which notifications a profile receives, the +// per-destination preferences, the delivery queue, retries with backoff, +// failure counts, and disabling a destination that keeps failing. The plugin +// checks a destination's settings and sends one message at a time. +type NotificationChannelClient interface { + // ValidateDestination checks a destination's settings before the host + // saves them, for example by asking the service whether a user key exists. + // Return valid=false with a message the user can act on; return a gRPC + // error only when the check itself couldn't run. + ValidateDestination(ctx context.Context, in *ValidateNotificationDestinationRequest, opts ...grpc.CallOption) (*ValidateNotificationDestinationResponse, error) + // SendNotification delivers one message to one destination. The host + // calls it at least once per message and destination, possibly from + // different servers, with the same delivery_key on every attempt. A gRPC + // error, or no answer within 15 seconds, counts as RETRY. + SendNotification(ctx context.Context, in *SendNotificationRequest, opts ...grpc.CallOption) (*SendNotificationResponse, error) +} + +type notificationChannelClient struct { + cc grpc.ClientConnInterface +} + +func NewNotificationChannelClient(cc grpc.ClientConnInterface) NotificationChannelClient { + return ¬ificationChannelClient{cc} +} + +func (c *notificationChannelClient) ValidateDestination(ctx context.Context, in *ValidateNotificationDestinationRequest, opts ...grpc.CallOption) (*ValidateNotificationDestinationResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(ValidateNotificationDestinationResponse) + err := c.cc.Invoke(ctx, NotificationChannel_ValidateDestination_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *notificationChannelClient) SendNotification(ctx context.Context, in *SendNotificationRequest, opts ...grpc.CallOption) (*SendNotificationResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(SendNotificationResponse) + err := c.cc.Invoke(ctx, NotificationChannel_SendNotification_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// NotificationChannelServer is the server API for NotificationChannel service. +// All implementations should embed UnimplementedNotificationChannelServer +// for forward compatibility. +// +// NotificationChannel delivers Silo notifications to a kind of destination +// the plugin provides, such as a push service or a chat app. A user adds a +// destination of that kind in their notification settings and fills in the +// form the descriptor declares. +// +// The host owns everything else: which notifications a profile receives, the +// per-destination preferences, the delivery queue, retries with backoff, +// failure counts, and disabling a destination that keeps failing. The plugin +// checks a destination's settings and sends one message at a time. +type NotificationChannelServer interface { + // ValidateDestination checks a destination's settings before the host + // saves them, for example by asking the service whether a user key exists. + // Return valid=false with a message the user can act on; return a gRPC + // error only when the check itself couldn't run. + ValidateDestination(context.Context, *ValidateNotificationDestinationRequest) (*ValidateNotificationDestinationResponse, error) + // SendNotification delivers one message to one destination. The host + // calls it at least once per message and destination, possibly from + // different servers, with the same delivery_key on every attempt. A gRPC + // error, or no answer within 15 seconds, counts as RETRY. + SendNotification(context.Context, *SendNotificationRequest) (*SendNotificationResponse, error) +} + +// UnimplementedNotificationChannelServer should be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedNotificationChannelServer struct{} + +func (UnimplementedNotificationChannelServer) ValidateDestination(context.Context, *ValidateNotificationDestinationRequest) (*ValidateNotificationDestinationResponse, error) { + return nil, status.Error(codes.Unimplemented, "method ValidateDestination not implemented") +} +func (UnimplementedNotificationChannelServer) SendNotification(context.Context, *SendNotificationRequest) (*SendNotificationResponse, error) { + return nil, status.Error(codes.Unimplemented, "method SendNotification not implemented") +} +func (UnimplementedNotificationChannelServer) testEmbeddedByValue() {} + +// UnsafeNotificationChannelServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to NotificationChannelServer will +// result in compilation errors. +type UnsafeNotificationChannelServer interface { + mustEmbedUnimplementedNotificationChannelServer() +} + +func RegisterNotificationChannelServer(s grpc.ServiceRegistrar, srv NotificationChannelServer) { + // If the following call panics, it indicates UnimplementedNotificationChannelServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&NotificationChannel_ServiceDesc, srv) +} + +func _NotificationChannel_ValidateDestination_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ValidateNotificationDestinationRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(NotificationChannelServer).ValidateDestination(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: NotificationChannel_ValidateDestination_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(NotificationChannelServer).ValidateDestination(ctx, req.(*ValidateNotificationDestinationRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _NotificationChannel_SendNotification_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(SendNotificationRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(NotificationChannelServer).SendNotification(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: NotificationChannel_SendNotification_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(NotificationChannelServer).SendNotification(ctx, req.(*SendNotificationRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// NotificationChannel_ServiceDesc is the grpc.ServiceDesc for NotificationChannel service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var NotificationChannel_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "silo.plugin.v1.NotificationChannel", + HandlerType: (*NotificationChannelServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "ValidateDestination", + Handler: _NotificationChannel_ValidateDestination_Handler, + }, + { + MethodName: "SendNotification", + Handler: _NotificationChannel_SendNotification_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "silo/plugin/v1/notification_channel.proto", +} diff --git a/pkg/pluginsdk/capability/capability.go b/pkg/pluginsdk/capability/capability.go index 8eb4698..41c089f 100644 --- a/pkg/pluginsdk/capability/capability.go +++ b/pkg/pluginsdk/capability/capability.go @@ -18,6 +18,9 @@ const ( // NetworkAccessProvider marks a resident plugin that gives the deployment // an overlay-network identity (Tailscale, NetBird, ...). Added in v0.16.0. NetworkAccessProvider = "network_access_provider.v1" + // NotificationChannel provides a kind of notification destination, such + // as a push service, that users add in their notification settings. + NotificationChannel = "notification_channel.v1" ) // KnownTypes lists every capability type recognized by this SDK version. @@ -36,4 +39,5 @@ var KnownTypes = []string{ ScanSource, WatchSyncProvider, NetworkAccessProvider, + NotificationChannel, } diff --git a/pkg/pluginsdk/config/config.go b/pkg/pluginsdk/config/config.go index 36ef902..33390a2 100644 --- a/pkg/pluginsdk/config/config.go +++ b/pkg/pluginsdk/config/config.go @@ -43,19 +43,7 @@ func ValidateValue(schema *pluginv1.ConfigSchema, kind string, key string, value schemaJSON = `{}` } - var schemaDoc any - if err := json.Unmarshal([]byte(schemaJSON), &schemaDoc); err != nil { - return fmt.Errorf("parse %s schema %q: %w", kind, key, err) - } - - compiler := jsonschema.NewCompiler() - compiler.DefaultDraft(jsonschema.Draft2020) - resourceName := "memory://config/" + key + ".schema.json" - if err := compiler.AddResource(resourceName, schemaDoc); err != nil { - return fmt.Errorf("load %s schema %q: %w", kind, key, err) - } - - compiled, err := compiler.Compile(resourceName) + compiled, err := CompileSchema(schemaJSON) if err != nil { return fmt.Errorf("compile %s schema %q: %w", kind, key, err) } @@ -70,3 +58,21 @@ func ValidateValue(schema *pluginv1.ConfigSchema, kind string, key string, value return nil } + +// CompileSchema compiles a JSON Schema the way ValidateValue does: draft +// 2020-12 unless the schema names another with $schema, and Go regexp +// (RE2) syntax for pattern. Manifest validation uses it to refuse a schema +// a host could never check values against. +func CompileSchema(schemaJSON string) (*jsonschema.Schema, error) { + var schemaDoc any + if err := json.Unmarshal([]byte(schemaJSON), &schemaDoc); err != nil { + return nil, fmt.Errorf("parse schema: %w", err) + } + compiler := jsonschema.NewCompiler() + compiler.DefaultDraft(jsonschema.Draft2020) + const resourceName = "memory://config/schema.json" + if err := compiler.AddResource(resourceName, schemaDoc); err != nil { + return nil, fmt.Errorf("load schema: %w", err) + } + return compiler.Compile(resourceName) +} diff --git a/pkg/pluginsdk/convert/convert.go b/pkg/pluginsdk/convert/convert.go index 9f52bf9..178f593 100644 --- a/pkg/pluginsdk/convert/convert.go +++ b/pkg/pluginsdk/convert/convert.go @@ -92,6 +92,17 @@ func DecodeCapability(record CapabilityRecord) (*pluginv1.CapabilityDescriptor, } descriptor.RequestRouter = &typed } + if channel, ok := record.Metadata["notification_channel"]; ok { + data, err := json.Marshal(channel) + if err != nil { + return nil, fmt.Errorf("encode notification channel descriptor: %w", err) + } + var typed pluginv1.NotificationChannelDescriptor + if err := capabilityUnmarshal.Unmarshal(data, &typed); err != nil { + return nil, fmt.Errorf("decode notification channel descriptor: %w", err) + } + descriptor.NotificationChannel = &typed + } if task, ok := record.Metadata["scheduled_task"]; ok { data, err := json.Marshal(task) if err != nil { @@ -161,6 +172,17 @@ func capabilityMetadata(descriptor *pluginv1.CapabilityDescriptor) (map[string]a } metadata["request_router"] = value } + if descriptor.GetNotificationChannel() != nil { + data, err := protojson.MarshalOptions{UseProtoNames: true}.Marshal(descriptor.GetNotificationChannel()) + if err != nil { + return nil, fmt.Errorf("encode notification channel descriptor: %w", err) + } + var value map[string]any + if err := json.Unmarshal(data, &value); err != nil { + return nil, fmt.Errorf("decode notification channel descriptor JSON: %w", err) + } + metadata["notification_channel"] = value + } if descriptor.GetScheduledTask() != nil { data, err := protojson.MarshalOptions{UseProtoNames: true}.Marshal(descriptor.GetScheduledTask()) if err != nil { diff --git a/pkg/pluginsdk/convert/notification_channel_test.go b/pkg/pluginsdk/convert/notification_channel_test.go new file mode 100644 index 0000000..cf18690 --- /dev/null +++ b/pkg/pluginsdk/convert/notification_channel_test.go @@ -0,0 +1,39 @@ +package convert_test + +import ( + "testing" + + "google.golang.org/protobuf/proto" + + pluginv1 "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginproto/silo/plugin/v1" + "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/convert" +) + +// The host lists destination kinds from stored capability records, so the +// descriptor, its form included, must survive the round trip. +func TestNotificationChannelDescriptorRoundTrip(t *testing.T) { + descriptor := &pluginv1.NotificationChannelDescriptor{ + DisplayName: "ntfy", + Description: "Push to an ntfy topic.", + DestinationSchema: &pluginv1.ConfigSchema{ + Key: "destination", + JsonSchema: `{"type":"object","properties":{"token":{"type":"string"}}}`, + AdminForm: &pluginv1.AdminFormDescriptor{Fields: []*pluginv1.AdminFormField{{ + Key: "token", Label: "Access token", Secret: true, + }}}, + }, + } + records, err := convert.CapabilityRecordsFromManifest(&pluginv1.PluginManifest{Capabilities: []*pluginv1.CapabilityDescriptor{{ + Type: "notification_channel.v1", Id: "ntfy", NotificationChannel: descriptor, + }}}) + if err != nil { + t.Fatal(err) + } + decoded, err := convert.DecodeCapability(records[0]) + if err != nil { + t.Fatal(err) + } + if !proto.Equal(decoded.GetNotificationChannel(), descriptor) { + t.Fatalf("decoded descriptor = %v, want %v", decoded.GetNotificationChannel(), descriptor) + } +} diff --git a/pkg/pluginsdk/events/payloads.go b/pkg/pluginsdk/events/payloads.go index 9ba98a2..12c27f1 100644 --- a/pkg/pluginsdk/events/payloads.go +++ b/pkg/pluginsdk/events/payloads.go @@ -165,8 +165,8 @@ type JobEvent struct { type Notification struct { ID string `json:"id"` // Type is the delivery type, such as "episode.available", - // "request.approved", "request.declined" or "request.fulfilled". The - // vocabulary is open. + // "watchlist.available", "request.approved", "request.declined" or + // "request.fulfilled". The vocabulary is open. Type string `json:"type"` // UserID is the account that owns the profile. Profile IDs repeat across // accounts, so identify a recipient by UserID and ProfileID together. diff --git a/pkg/pluginsdk/manifest/destination_schema.go b/pkg/pluginsdk/manifest/destination_schema.go new file mode 100644 index 0000000..414df7e --- /dev/null +++ b/pkg/pluginsdk/manifest/destination_schema.go @@ -0,0 +1,428 @@ +package manifest + +import ( + "encoding/json" + "fmt" + "math" + "regexp" + "slices" + "strconv" + "strings" + + pluginv1 "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginproto/silo/plugin/v1" + "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/config" +) + +// What a destination schema and form may use. People who aren't administrators fill +// in destination settings, and every client renders the form, so it stays a +// flat list of scalar fields that can always be saved. Loosening this later +// is additive; tightening it would break published plugins. +var ( + destinationSchemaKeywords = []string{"type", "title", "description", "properties", "required", "additionalProperties"} + destinationFieldKeywords = []string{"type", "title", "description", "default", "enum", "format", "minimum", "maximum", "minLength", "maxLength", "pattern"} + destinationFieldTypes = []string{"string", "integer", "number", "boolean"} + + // The keywords that apply to only some field types. + destinationStringKeywords = []string{"format", "minLength", "maxLength", "pattern"} + destinationNumberKeywords = []string{"minimum", "maximum"} + + // A field key: what first-party plugin config keys look like, and safe + // to use unchanged as a form key, an API field name and an error path. + destinationFieldKey = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9_-]{0,63}$`) + + // The form controls a destination field may use, and the field types + // each one accepts. + destinationControlTypes = map[pluginv1.AdminFormControl][]string{ + pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_TEXT: {"string"}, + pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_PASSWORD: {"string"}, + pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_NUMBER: {"integer", "number"}, + pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_SWITCH: {"boolean"}, + pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_SELECT: {"string", "integer", "number"}, + } +) + +// destinationProperty is one field of a destination schema. +type destinationProperty struct { + keywords map[string]json.RawMessage + typ string + // schema checks one value of this field, compiled as hosts compile it. + schema interface{ Validate(any) error } +} + +// ValidateDestinationSchema checks a notification_channel destination_schema: +// a valid ConfigSchema whose json_schema is one object of scalar fields and +// whose admin_form is one flat list of fields that a host can render and +// save. +// +// The json_schema compiles with config.CompileSchema (draft 2020-12; $schema +// is refused, so no other draft applies). Fields are string, integer, number +// or boolean, with optional title, description, default, enum, +// minimum/maximum (integer and number) and format/minLength/maxLength/pattern +// (string). Bounds are ordered, lengths are not negative, and a pattern is +// Go RE2 syntax. additionalProperties may only be false. $ref, +// allOf/anyOf/oneOf/not, conditionals, nested objects and arrays are refused. +// +// The admin_form is required and has at least one field, one per schema +// field and the reverse, each keyed exactly by its property name, which is +// a letter followed by up to 63 letters, digits, underscores or hyphens. A +// form field sets key, label and control and may set description, +// placeholder, required (which must match the schema's required list), +// secret (string fields), default_value and, on a select, options. Controls +// are TEXT and PASSWORD (string), NUMBER (integer or number), SWITCH +// (boolean) and SELECT (string, integer or number, with static options). +// Option values are unique and parse as the field's type, and equal the +// field's enum when it has one; only a SELECT field may declare enum. A +// default, in the schema or the form, is a value of the field's type that +// passes its checks and, on a SELECT, is one of the options. Sections, +// submit_label, show_when, dynamic_options, exclusive_group_field, +// validation, multiline, rows, TEXTAREA and MULTI_SELECT are refused. Hosts +// call it when they accept a notification_channel capability. +func ValidateDestinationSchema(schema *pluginv1.ConfigSchema) error { + if schema == nil { + return fmt.Errorf("destination_schema is required") + } + if err := validateConfigSchema(schema); err != nil { + return err + } + var root map[string]json.RawMessage + if err := json.Unmarshal([]byte(schema.GetJsonSchema()), &root); err != nil { + return fmt.Errorf("destination_schema json_schema is not a JSON object: %w", err) + } + for keyword := range root { + if keyword == "$schema" { + return fmt.Errorf("destination_schema json_schema can't set $schema; hosts compile it as draft 2020-12") + } + if !slices.Contains(destinationSchemaKeywords, keyword) { + return fmt.Errorf("destination_schema json_schema uses %q; a destination form is a flat list of fields", keyword) + } + } + var typ string + if err := json.Unmarshal(root["type"], &typ); err != nil || typ != "object" { + return fmt.Errorf("destination_schema json_schema must have type \"object\"") + } + var rawProperties map[string]json.RawMessage + if raw, ok := root["properties"]; ok { + if err := json.Unmarshal(raw, &rawProperties); err != nil { + return fmt.Errorf("destination_schema properties must map field names to objects: %w", err) + } + } + properties := make(map[string]*destinationProperty, len(rawProperties)) + for name, raw := range rawProperties { + property, err := parseDestinationProperty(name, raw) + if err != nil { + return err + } + properties[name] = property + } + // The schema must compile exactly as a host compiles it to check + // submitted settings, or no destination could ever be saved. + if _, err := config.CompileSchema(schema.GetJsonSchema()); err != nil { + return fmt.Errorf("destination_schema json_schema doesn't compile: %w", err) + } + // Hosts store only declared fields, so a schema can't allow others. + if raw, ok := root["additionalProperties"]; ok { + var allowed bool + if err := json.Unmarshal(raw, &allowed); err != nil || allowed { + return fmt.Errorf("destination_schema additionalProperties must be false or absent") + } + } + var required []string + if raw, ok := root["required"]; ok { + if err := json.Unmarshal(raw, &required); err != nil { + return fmt.Errorf("destination_schema required must be a list of field names") + } + for _, name := range required { + if _, ok := properties[name]; !ok { + return fmt.Errorf("destination_schema requires %q, which isn't a field", name) + } + } + } + return validateDestinationForm(schema.GetAdminForm(), properties, required) +} + +// parseDestinationProperty checks one schema field on its own: its +// keywords, its type, the keywords its type allows, its bounds and its +// pattern, and compiles it so values can be checked against it. +func parseDestinationProperty(name string, raw json.RawMessage) (*destinationProperty, error) { + p := &destinationProperty{} + if err := json.Unmarshal(raw, &p.keywords); err != nil { + return nil, fmt.Errorf("destination_schema field %q must be an object: %w", name, err) + } + for keyword := range p.keywords { + if !slices.Contains(destinationFieldKeywords, keyword) { + return nil, fmt.Errorf("destination_schema field %q uses %q; destination fields are plain scalars", name, keyword) + } + } + if err := json.Unmarshal(p.keywords["type"], &p.typ); err != nil || !slices.Contains(destinationFieldTypes, p.typ) { + return nil, fmt.Errorf("destination_schema field %q must have type string, integer, number or boolean", name) + } + for keyword := range p.keywords { + switch { + case slices.Contains(destinationStringKeywords, keyword) && p.typ != "string": + return nil, fmt.Errorf("destination_schema field %q uses %q, which applies only to a string field", name, keyword) + case slices.Contains(destinationNumberKeywords, keyword) && p.typ != "integer" && p.typ != "number": + return nil, fmt.Errorf("destination_schema field %q uses %q, which applies only to an integer or number field", name, keyword) + } + } + var bounds struct { + Minimum *float64 `json:"minimum"` + Maximum *float64 `json:"maximum"` + MinLength *int `json:"minLength"` + MaxLength *int `json:"maxLength"` + Pattern *string `json:"pattern"` + } + if err := json.Unmarshal(raw, &bounds); err != nil { + return nil, fmt.Errorf("destination_schema field %q has a bound of the wrong type: %w", name, err) + } + if bounds.Minimum != nil && bounds.Maximum != nil && *bounds.Minimum > *bounds.Maximum { + return nil, fmt.Errorf("destination_schema field %q has minimum %v above maximum %v", name, *bounds.Minimum, *bounds.Maximum) + } + // An integer field whose bounds hold no whole number a setting can carry + // (see MaxSafeInteger) can never be filled in. + if p.typ == "integer" { + lowest, highest := float64(-MaxSafeInteger), float64(MaxSafeInteger) + if bounds.Minimum != nil { + lowest = math.Max(lowest, math.Ceil(*bounds.Minimum)) + } + if bounds.Maximum != nil { + highest = math.Min(highest, math.Floor(*bounds.Maximum)) + } + if lowest > highest { + return nil, fmt.Errorf("destination_schema field %q has bounds that hold no whole number a setting can carry (up to %d in either direction)", name, int64(MaxSafeInteger)) + } + } + for keyword, length := range map[string]*int{"minLength": bounds.MinLength, "maxLength": bounds.MaxLength} { + if length != nil && *length < 0 { + return nil, fmt.Errorf("destination_schema field %q has a negative %s", name, keyword) + } + } + if bounds.MinLength != nil && bounds.MaxLength != nil && *bounds.MinLength > *bounds.MaxLength { + return nil, fmt.Errorf("destination_schema field %q has minLength %d above maxLength %d", name, *bounds.MinLength, *bounds.MaxLength) + } + if bounds.Pattern != nil { + if _, err := regexp.Compile(*bounds.Pattern); err != nil { + return nil, fmt.Errorf("destination_schema field %q pattern isn't Go RE2 syntax: %w", name, err) + } + } + compiled, err := config.CompileSchema(string(raw)) + if err != nil { + return nil, fmt.Errorf("destination_schema field %q doesn't compile: %w", name, err) + } + p.schema = compiled + return p, nil +} + +// MaxSafeInteger is the largest whole number a setting carries exactly: +// settings travel as JSON numbers and protobuf values, which are doubles. +// Hosts refuse an integer setting beyond it in either direction. +const MaxSafeInteger = 1<<53 - 1 + +// checkValue reports why value can't be stored in the field: it isn't a +// scalar of the field's type, or it fails the field's own checks. +func (p *destinationProperty) checkValue(value any) error { + ok := false + switch v := value.(type) { + case string: + ok = p.typ == "string" + case bool: + ok = p.typ == "boolean" + case float64: + ok = p.typ == "number" || (p.typ == "integer" && v == math.Trunc(v)) + if ok && p.typ == "integer" && math.Abs(v) > MaxSafeInteger { + return fmt.Errorf("is outside the whole numbers a setting can hold exactly (up to %d); use a string field for a larger identifier", int64(MaxSafeInteger)) + } + } + if !ok { + return fmt.Errorf("isn't of type %s", p.typ) + } + if err := p.schema.Validate(value); err != nil { + return fmt.Errorf("fails the field's checks: %#v", err) + } + return nil +} + +// optionValue parses a select option's value as the field's type, the way +// a client sends it. +func (p *destinationProperty) optionValue(raw string) (any, error) { + switch p.typ { + case "string": + return raw, nil + case "integer": + n, err := strconv.ParseInt(raw, 10, 64) + if err != nil { + return nil, fmt.Errorf("isn't an integer") + } + if n > MaxSafeInteger || n < -MaxSafeInteger { + return nil, fmt.Errorf("is outside the whole numbers a setting can hold exactly (up to %d); use a string field for a larger identifier", int64(MaxSafeInteger)) + } + return float64(n), nil + case "number": + n, err := strconv.ParseFloat(raw, 64) + if err != nil || math.IsInf(n, 0) || math.IsNaN(n) { + return nil, fmt.Errorf("isn't a number") + } + return n, nil + } + return nil, fmt.Errorf("can't be a %s option", p.typ) +} + +// validateDestinationForm checks the admin_form against the flat-form rules +// above. validateConfigSchema already checked that each form field names a +// property and that keys are unique. +func validateDestinationForm(form *pluginv1.AdminFormDescriptor, properties map[string]*destinationProperty, required []string) error { + if len(form.GetFields()) == 0 { + return fmt.Errorf("destination_schema needs an admin_form with at least one field") + } + if len(form.GetSections()) > 0 { + return fmt.Errorf("destination_schema admin_form can't use sections; a destination form is a flat list of fields") + } + if form.GetSubmitLabel() != "" { + return fmt.Errorf("destination_schema admin_form can't set submit_label; the client's dialog owns its buttons") + } + inForm := make(map[string]bool, len(form.GetFields())) + for _, field := range form.GetFields() { + if field == nil { + return fmt.Errorf("destination_schema admin_form has an empty field") + } + key := field.GetKey() + if !destinationFieldKey.MatchString(key) { + return fmt.Errorf("destination_schema field key %q must be a letter followed by up to 63 letters, digits, underscores or hyphens", key) + } + if inForm[key] { + return fmt.Errorf("destination_schema admin_form field %q is duplicated", key) + } + inForm[key] = true + property := properties[key] + if property == nil { + return fmt.Errorf("destination_schema admin_form field %q isn't a schema field", key) + } + if strings.TrimSpace(field.GetLabel()) == "" { + return fmt.Errorf("destination_schema admin_form field %q needs a label", key) + } + var refused string + switch { + case len(field.GetShowWhen()) > 0: + refused = "show_when" + case field.GetDynamicOptions(): + refused = "dynamic_options" + case field.GetExclusiveGroupField() != "": + refused = "exclusive_group_field" + case field.GetValidation() != nil: + refused = "validation (put minimum, maximum, minLength, maxLength and pattern in the json_schema)" + case field.GetMultiline(): + refused = "multiline" + case field.GetRows() != 0: + refused = "rows" + } + if refused != "" { + return fmt.Errorf("destination_schema admin_form field %q can't use %s; a destination form is a flat list of fields", key, refused) + } + control := field.GetControl() + allowed, ok := destinationControlTypes[control] + if !ok { + return fmt.Errorf("destination_schema admin_form field %q uses control %s; use TEXT, PASSWORD, NUMBER, SWITCH or SELECT", key, control) + } + if !slices.Contains(allowed, property.typ) { + return fmt.Errorf("destination_schema admin_form field %q: control %s needs a field of type %s, not %q", key, control, strings.Join(allowed, " or "), property.typ) + } + if field.GetSecret() && property.typ != "string" { + return fmt.Errorf("destination_schema admin_form field %q is secret but not a string field", key) + } + // A secret is typed, never picked: clients show it as a masked input. + if field.GetSecret() && control != pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_PASSWORD && control != pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_TEXT { + return fmt.Errorf("destination_schema admin_form field %q is secret, so its control must be PASSWORD or TEXT, not %s", key, control) + } + if field.GetRequired() != slices.Contains(required, key) { + return fmt.Errorf("destination_schema admin_form field %q: required on the form field and the schema's required list must agree", key) + } + isSelect := control == pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_SELECT + if isSelect && len(field.GetOptions()) == 0 { + return fmt.Errorf("destination_schema admin_form field %q select control requires static options", key) + } + if !isSelect && len(field.GetOptions()) > 0 { + return fmt.Errorf("destination_schema admin_form field %q has options, which only a SELECT control uses", key) + } + if _, ok := property.keywords["enum"]; ok && !isSelect { + return fmt.Errorf("destination_schema field %q declares enum, which only a SELECT control shows; use a SELECT with those options", key) + } + options, err := destinationOptions(field, property) + if err != nil { + return err + } + if err := checkDestinationDefaults(field, property, options); err != nil { + return err + } + } + for name := range properties { + if !inForm[name] { + return fmt.Errorf("destination_schema field %q has no admin_form field", name) + } + } + return nil +} + +// destinationOptions parses a select's options as the field's type and +// checks that they are unique, pass the field's checks, and equal its enum +// when it has one. It returns the parsed values. +func destinationOptions(field *pluginv1.AdminFormField, property *destinationProperty) ([]any, error) { + key := field.GetKey() + values := make([]any, 0, len(field.GetOptions())) + for _, option := range field.GetOptions() { + value, err := property.optionValue(option.GetValue()) + if err != nil { + return nil, fmt.Errorf("destination_schema admin_form field %q option %q %w", key, option.GetValue(), err) + } + if slices.Contains(values, value) { + return nil, fmt.Errorf("destination_schema admin_form field %q has option %q twice", key, option.GetValue()) + } + if err := property.checkValue(value); err != nil { + return nil, fmt.Errorf("destination_schema admin_form field %q option %q %w", key, option.GetValue(), err) + } + values = append(values, value) + } + if raw, ok := property.keywords["enum"]; ok { + var enum []any + if err := json.Unmarshal(raw, &enum); err != nil { + return nil, fmt.Errorf("destination_schema field %q enum must be a list", key) + } + // Every option already passed the enum; the enum may not offer a + // value the form can't choose. + for _, value := range enum { + if !slices.Contains(values, value) { + return nil, fmt.Errorf("destination_schema field %q enum value %v isn't one of its options; options and enum must match", key, value) + } + } + } + return values, nil +} + +// checkDestinationDefaults checks the schema's default and the form's +// default_value: each is a scalar of the field's type that passes the +// field's checks and, on a select, is one of its options. +func checkDestinationDefaults(field *pluginv1.AdminFormField, property *destinationProperty, options []any) error { + key := field.GetKey() + check := func(source string, value any) error { + if err := property.checkValue(value); err != nil { + return fmt.Errorf("destination_schema field %q %s %w", key, source, err) + } + if field.GetControl() == pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_SELECT && !slices.Contains(options, value) { + return fmt.Errorf("destination_schema field %q %s isn't one of its options", key, source) + } + return nil + } + if raw, ok := property.keywords["default"]; ok { + var value any + if err := json.Unmarshal(raw, &value); err != nil { + return fmt.Errorf("destination_schema field %q default: %w", key, err) + } + if err := check("default", value); err != nil { + return err + } + } + if value := field.GetDefaultValue(); value != nil { + if err := check("default_value", value.AsInterface()); err != nil { + return err + } + } + return nil +} diff --git a/pkg/pluginsdk/manifest/manifest.go b/pkg/pluginsdk/manifest/manifest.go index a241051..50bed72 100644 --- a/pkg/pluginsdk/manifest/manifest.go +++ b/pkg/pluginsdk/manifest/manifest.go @@ -153,6 +153,9 @@ func Validate(manifest *pluginv1.PluginManifest) error { if err := validateAuthProviderCapability(capability); err != nil { return err } + if err := validateNotificationChannelCapability(capability); err != nil { + return err + } if err := validateScheduledTaskCapability(capability); err != nil { return err } diff --git a/pkg/pluginsdk/manifest/notification_channel.go b/pkg/pluginsdk/manifest/notification_channel.go new file mode 100644 index 0000000..c53120d --- /dev/null +++ b/pkg/pluginsdk/manifest/notification_channel.go @@ -0,0 +1,32 @@ +package manifest + +import ( + "fmt" + "strings" + + pluginv1 "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginproto/silo/plugin/v1" + "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/capability" +) + +func validateNotificationChannelCapability(descriptor *pluginv1.CapabilityDescriptor) error { + channel := descriptor.GetNotificationChannel() + if descriptor.GetType() != capability.NotificationChannel { + if channel != nil { + return fmt.Errorf("plugin capability %q: notification_channel descriptor requires type %q", descriptor.GetId(), capability.NotificationChannel) + } + return nil + } + if !watchSyncSlugPattern.MatchString(descriptor.GetId()) { + return fmt.Errorf("plugin capability %q: notification channel capability id must be a path-safe lowercase slug", descriptor.GetId()) + } + if channel == nil { + return fmt.Errorf("plugin capability %q: notification_channel descriptor is required", descriptor.GetId()) + } + if strings.TrimSpace(channel.GetDisplayName()) == "" { + return fmt.Errorf("plugin capability %q: notification_channel display_name is required", descriptor.GetId()) + } + if err := ValidateDestinationSchema(channel.GetDestinationSchema()); err != nil { + return fmt.Errorf("plugin capability %q destination schema: %w", descriptor.GetId(), err) + } + return nil +} diff --git a/pkg/pluginsdk/manifest/notification_channel_test.go b/pkg/pluginsdk/manifest/notification_channel_test.go new file mode 100644 index 0000000..7f021d3 --- /dev/null +++ b/pkg/pluginsdk/manifest/notification_channel_test.go @@ -0,0 +1,367 @@ +package manifest_test + +import ( + "encoding/json" + "slices" + "strings" + "testing" + + pluginv1 "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginproto/silo/plugin/v1" + "google.golang.org/protobuf/types/known/structpb" + + publicmanifest "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/manifest" +) + +func TestLoadNotificationChannel(t *testing.T) { + manifest, err := publicmanifest.Load([]byte(`{ + "plugin_id":"silo.ntfy", "version":"1.0.0", "silo_api_version":"v1", + "capabilities":[{ + "type":"notification_channel.v1", "id":"ntfy", + "notification_channel":{ + "display_name":"ntfy", + "destination_schema":{ + "key":"destination", + "json_schema":"{\"type\":\"object\",\"properties\":{\"topic\":{\"type\":\"string\"},\"token\":{\"type\":\"string\"}}}", + "admin_form":{"fields":[{"key":"topic","label":"Topic","control":"ADMIN_FORM_CONTROL_TEXT"},{"key":"token","label":"Access token","control":"ADMIN_FORM_CONTROL_PASSWORD","secret":true}]} + } + } + }] + }`)) + if err != nil { + t.Fatal(err) + } + channel := manifest.GetCapabilities()[0].GetNotificationChannel() + if channel.GetDisplayName() != "ntfy" || len(channel.GetDestinationSchema().GetAdminForm().GetFields()) != 2 { + t.Fatalf("notification channel descriptor = %v", channel) + } +} + +func TestValidateNotificationChannel(t *testing.T) { + schema := &pluginv1.ConfigSchema{Key: "destination", JsonSchema: `{"type":"object","properties":{"topic":{"type":"string"}}}`} + for _, tc := range []struct { + name string + capability *pluginv1.CapabilityDescriptor + wantErr string + }{ + {name: "missing descriptor", capability: &pluginv1.CapabilityDescriptor{Type: "notification_channel.v1", Id: "ntfy"}, wantErr: "descriptor is required"}, + {name: "missing display name", capability: &pluginv1.CapabilityDescriptor{Type: "notification_channel.v1", Id: "ntfy", + NotificationChannel: &pluginv1.NotificationChannelDescriptor{DestinationSchema: schema}}, wantErr: "display_name"}, + {name: "missing schema", capability: &pluginv1.CapabilityDescriptor{Type: "notification_channel.v1", Id: "ntfy", + NotificationChannel: &pluginv1.NotificationChannelDescriptor{DisplayName: "ntfy"}}, wantErr: "destination_schema"}, + {name: "form field not in schema", capability: &pluginv1.CapabilityDescriptor{Type: "notification_channel.v1", Id: "ntfy", + NotificationChannel: &pluginv1.NotificationChannelDescriptor{DisplayName: "ntfy", DestinationSchema: &pluginv1.ConfigSchema{ + Key: "destination", JsonSchema: schema.JsonSchema, + AdminForm: &pluginv1.AdminFormDescriptor{Fields: []*pluginv1.AdminFormField{{Key: "server"}}}, + }}}, wantErr: "destination schema"}, + {name: "nested object field", capability: channelWithSchema(`{"type":"object","properties":{"auth":{"type":"object","properties":{"token":{"type":"string"}}}}}`), wantErr: "scalar"}, + {name: "array field", capability: channelWithSchema(`{"type":"object","properties":{"tags":{"type":"array"}}}`), wantErr: "type string, integer"}, + {name: "ref", capability: channelWithSchema(`{"type":"object","properties":{"topic":{"$ref":"#/$defs/topic"}}}`), wantErr: "plain scalars"}, + {name: "conditional", capability: channelWithSchema(`{"type":"object","properties":{"topic":{"type":"string"}},"allOf":[{"required":["topic"]}]}`), wantErr: "flat list"}, + {name: "required field without a form field", capability: channelWithForm(`{"type":"object","properties":{"topic":{"type":"string"},"token":{"type":"string"}},"required":["token"]}`, "topic"), wantErr: `"token" has no admin_form field`}, + {name: "fields without a form", capability: channelWithSchema(`{"type":"object","properties":{"topic":{"type":"string"}}}`), wantErr: "needs an admin_form"}, + {name: "no fields", capability: channelWithForm(`{"type":"object","properties":{}}`), wantErr: "needs an admin_form"}, + {name: "additional properties allowed", capability: channelWithForm(`{"type":"object","properties":{"topic":{"type":"string"}},"additionalProperties":true}`, "topic"), wantErr: "additionalProperties"}, + {name: "additional properties schema", capability: channelWithForm(`{"type":"object","properties":{"topic":{"type":"string"}},"additionalProperties":{"type":"string"}}`, "topic"), wantErr: "additionalProperties"}, + {name: "nullable field", capability: channelWithForm(`{"type":"object","properties":{"topic":{"type":["string","null"]}}}`, "topic"), wantErr: "json_schema"}, + {name: "required names no field", capability: channelWithSchema(`{"type":"object","properties":{"topic":{"type":"string"}},"required":["server"]}`), wantErr: "isn't a field"}, + {name: "id not a slug", capability: &pluginv1.CapabilityDescriptor{Type: "notification_channel.v1", Id: "Ntfy Push", + NotificationChannel: &pluginv1.NotificationChannelDescriptor{DisplayName: "ntfy", DestinationSchema: schema}}, wantErr: "slug"}, + {name: "descriptor on another type", capability: &pluginv1.CapabilityDescriptor{Type: "scheduled_task.v1", Id: "task", + NotificationChannel: &pluginv1.NotificationChannelDescriptor{DisplayName: "ntfy", DestinationSchema: schema}}, wantErr: "requires type"}, + } { + t.Run(tc.name, func(t *testing.T) { + err := publicmanifest.Validate(&pluginv1.PluginManifest{PluginId: "silo.test", Version: "1.0.0", + Capabilities: []*pluginv1.CapabilityDescriptor{tc.capability}}) + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("Validate() = %v, want error containing %q", err, tc.wantErr) + } + }) + } +} + +func channelWithSchema(jsonSchema string) *pluginv1.CapabilityDescriptor { + return &pluginv1.CapabilityDescriptor{Type: "notification_channel.v1", Id: "ntfy", + NotificationChannel: &pluginv1.NotificationChannelDescriptor{DisplayName: "ntfy", + DestinationSchema: &pluginv1.ConfigSchema{Key: "destination", JsonSchema: jsonSchema}}} +} + +// channelWithForm gives each named field the control its schema type calls for. +func channelWithForm(jsonSchema string, formKeys ...string) *pluginv1.CapabilityDescriptor { + descriptor := channelWithSchema(jsonSchema) + var parsed struct { + Properties map[string]struct { + Type any `json:"type"` + } `json:"properties"` + Required []string `json:"required"` + } + _ = json.Unmarshal([]byte(jsonSchema), &parsed) + form := &pluginv1.AdminFormDescriptor{} + for _, key := range formKeys { + control := pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_TEXT + switch parsed.Properties[key].Type { + case "integer", "number": + control = pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_NUMBER + case "boolean": + control = pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_SWITCH + } + form.Fields = append(form.Fields, &pluginv1.AdminFormField{Key: key, Label: key, Control: control, + Required: slices.Contains(parsed.Required, key)}) + } + descriptor.GetNotificationChannel().GetDestinationSchema().AdminForm = form + return descriptor +} + +// TestValidateDestinationFormRefusals covers every form feature a destination +// form can't use. Each case changes one thing on an otherwise valid form. +func TestValidateDestinationFormRefusals(t *testing.T) { + const jsonSchema = `{"type":"object","properties":{"topic":{"type":"string"},"priority":{"type":"integer"},"markdown":{"type":"boolean"}}}` + field := func(form *pluginv1.AdminFormDescriptor, key string) *pluginv1.AdminFormField { + for _, f := range form.GetFields() { + if f.GetKey() == key { + return f + } + } + t.Fatalf("no field %q", key) + return nil + } + for _, tc := range []struct { + name string + change func(form *pluginv1.AdminFormDescriptor) + wantErr string + }{ + {name: "section", change: func(form *pluginv1.AdminFormDescriptor) { + form.Sections = []*pluginv1.AdminFormSection{{Key: "all", FieldKeys: []string{"topic", "priority", "markdown"}}} + }, wantErr: "can't use sections"}, + {name: "submit label", change: func(form *pluginv1.AdminFormDescriptor) { form.SubmitLabel = "Save" }, wantErr: "submit_label"}, + {name: "show_when", change: func(form *pluginv1.AdminFormDescriptor) { + field(form, "priority").ShowWhen = []*pluginv1.AdminFormCondition{{Field: "markdown", Equals: []string{"true"}}} + }, wantErr: "show_when"}, + {name: "dynamic options", change: func(form *pluginv1.AdminFormDescriptor) { + f := field(form, "topic") + f.Control = pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_SELECT + f.DynamicOptions = true + }, wantErr: "dynamic_options"}, + {name: "dynamic options with static fallback", change: func(form *pluginv1.AdminFormDescriptor) { + f := field(form, "topic") + f.Control = pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_SELECT + f.Options = []*pluginv1.AdminFormOption{{Value: "a", Label: "A"}} + f.DynamicOptions = true + }, wantErr: "dynamic_options"}, + {name: "exclusive group", change: func(form *pluginv1.AdminFormDescriptor) { field(form, "markdown").ExclusiveGroupField = "topic" }, wantErr: "exclusive_group_field"}, + {name: "form validation", change: func(form *pluginv1.AdminFormDescriptor) { + field(form, "priority").Validation = &pluginv1.AdminFormValidation{HasMin: true, Min: 1} + }, wantErr: "validation"}, + {name: "multiline", change: func(form *pluginv1.AdminFormDescriptor) { field(form, "topic").Multiline = true }, wantErr: "multiline"}, + {name: "rows", change: func(form *pluginv1.AdminFormDescriptor) { field(form, "topic").Rows = 3 }, wantErr: "rows"}, + {name: "textarea", change: func(form *pluginv1.AdminFormDescriptor) { + field(form, "topic").Control = pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_TEXTAREA + }, wantErr: "uses control"}, + {name: "multi select", change: func(form *pluginv1.AdminFormDescriptor) { + f := field(form, "topic") + f.Control = pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_MULTI_SELECT + f.Options = []*pluginv1.AdminFormOption{{Value: "a", Label: "A"}} + }, wantErr: "multi_select"}, // an array property, which MULTI_SELECT needs, is refused too + {name: "no control", change: func(form *pluginv1.AdminFormDescriptor) { + field(form, "topic").Control = pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_UNSPECIFIED + }, wantErr: "uses control"}, + {name: "select without options", change: func(form *pluginv1.AdminFormDescriptor) { + field(form, "topic").Control = pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_SELECT + }, wantErr: "select control requires options"}, + {name: "options on a text field", change: func(form *pluginv1.AdminFormDescriptor) { + field(form, "topic").Options = []*pluginv1.AdminFormOption{{Value: "a", Label: "A"}} + }, wantErr: "only a SELECT"}, + {name: "switch on a string", change: func(form *pluginv1.AdminFormDescriptor) { + field(form, "topic").Control = pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_SWITCH + }, wantErr: "needs a field of type boolean"}, + {name: "number on a boolean", change: func(form *pluginv1.AdminFormDescriptor) { + field(form, "markdown").Control = pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_NUMBER + }, wantErr: "needs a field of type integer or number"}, + {name: "select on a boolean", change: func(form *pluginv1.AdminFormDescriptor) { + f := field(form, "markdown") + f.Control = pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_SELECT + f.Options = []*pluginv1.AdminFormOption{{Value: "true", Label: "Yes"}} + }, wantErr: "needs a field of type string or integer or number"}, + {name: "password on a number", change: func(form *pluginv1.AdminFormDescriptor) { + field(form, "priority").Control = pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_PASSWORD + }, wantErr: "needs a field of type string"}, + {name: "secret switch", change: func(form *pluginv1.AdminFormDescriptor) { field(form, "markdown").Secret = true }, wantErr: "secret but not a string"}, + {name: "no label", change: func(form *pluginv1.AdminFormDescriptor) { field(form, "topic").Label = " " }, wantErr: "needs a label"}, + {name: "empty field", change: func(form *pluginv1.AdminFormDescriptor) { form.Fields = append(form.Fields, nil) }, wantErr: "empty field"}, + } { + t.Run(tc.name, func(t *testing.T) { + capability := channelWithForm(jsonSchema, "topic", "priority", "markdown") + tc.change(capability.GetNotificationChannel().GetDestinationSchema().GetAdminForm()) + err := publicmanifest.Validate(&pluginv1.PluginManifest{PluginId: "silo.test", Version: "1.0.0", + Capabilities: []*pluginv1.CapabilityDescriptor{capability}}) + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("Validate() = %v, want error containing %q", err, tc.wantErr) + } + }) + } +} + +func TestValidateDestinationSchemaAcceptsFlatForm(t *testing.T) { + for _, jsonSchema := range []string{ + `{"type":"object","properties":{"topic":{"type":"string","minLength":1},"priority":{"type":"integer","minimum":1,"maximum":5},"markdown":{"type":"boolean"}},"required":["topic"],"additionalProperties":false}`, + `{"type":"object","properties":{"topic":{"type":"string"},"priority":{"type":"integer"},"markdown":{"type":"boolean"}}}`, + } { + err := publicmanifest.Validate(&pluginv1.PluginManifest{PluginId: "silo.test", Version: "1.0.0", + Capabilities: []*pluginv1.CapabilityDescriptor{channelWithForm(jsonSchema, "topic", "priority", "markdown")}}) + if err != nil { + t.Fatalf("Validate(%s) = %v", jsonSchema, err) + } + } +} + +// everyControlSchema and everyControlForm are a destination form that uses +// every allowed control with options, defaults, enum and bounds. +const everyControlSchema = `{"type":"object","properties":{` + + `"topic":{"type":"string","title":"Topic","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9_-]+$","default":"alerts"},` + + `"token":{"type":"string","format":"password"},` + + `"priority":{"type":"integer","minimum":1,"maximum":5,"default":3},` + + `"ratio":{"type":"number","minimum":0,"maximum":1},` + + `"markdown":{"type":"boolean","default":true},` + + `"server":{"type":"string","enum":["a","b"],"default":"a"},` + + `"level":{"type":"integer","enum":[1,2]}},` + + `"required":["topic"],"additionalProperties":false}` + +func everyControlForm() *pluginv1.AdminFormDescriptor { + return &pluginv1.AdminFormDescriptor{Fields: []*pluginv1.AdminFormField{ + {Key: "topic", Label: "Topic", Description: "Your topic.", Placeholder: "alerts", Required: true, Control: pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_TEXT, DefaultValue: structpb.NewStringValue("alerts")}, + {Key: "token", Label: "Token", Control: pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_PASSWORD, Secret: true}, + {Key: "priority", Label: "Priority", Control: pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_NUMBER, DefaultValue: structpb.NewNumberValue(3)}, + {Key: "ratio", Label: "Ratio", Control: pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_NUMBER, DefaultValue: structpb.NewNumberValue(0.5)}, + {Key: "markdown", Label: "Markdown", Control: pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_SWITCH, DefaultValue: structpb.NewBoolValue(true)}, + {Key: "server", Label: "Server", Control: pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_SELECT, Options: []*pluginv1.AdminFormOption{{Value: "a", Label: "A"}, {Value: "b", Label: "B"}}}, + {Key: "level", Label: "Level", Control: pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_SELECT, DefaultValue: structpb.NewNumberValue(2), Options: []*pluginv1.AdminFormOption{{Value: "1", Label: "Low"}, {Value: "2", Label: "High"}}}, + }} +} + +func validateChannel(jsonSchema string, form *pluginv1.AdminFormDescriptor) error { + capability := channelWithSchema(jsonSchema) + capability.GetNotificationChannel().GetDestinationSchema().AdminForm = form + return publicmanifest.Validate(&pluginv1.PluginManifest{PluginId: "silo.test", Version: "1.0.0", + Capabilities: []*pluginv1.CapabilityDescriptor{capability}}) +} + +func TestValidateDestinationSchemaAcceptsEveryAllowedControl(t *testing.T) { + if err := validateChannel(everyControlSchema, everyControlForm()); err != nil { + t.Fatal(err) + } +} + +// TestValidateDestinationSchemaRefusesUnsavableForms covers forms that would +// install but could never be rendered or saved. Each case changes one thing +// on the form TestValidateDestinationSchemaAcceptsEveryAllowedControl accepts. +func TestValidateDestinationSchemaRefusesUnsavableForms(t *testing.T) { + field := func(form *pluginv1.AdminFormDescriptor, key string) *pluginv1.AdminFormField { + for _, f := range form.GetFields() { + if f.GetKey() == key { + return f + } + } + t.Fatalf("no field %q", key) + return nil + } + for _, tc := range []struct { + name string + schema func(string) string // nil keeps the schema + form func(*pluginv1.AdminFormDescriptor) + rekey [2]string // renames a field in the schema and the form + wantErr string + }{ + {name: "pattern outside RE2", schema: replace(`"^[A-Za-z0-9_-]+$"`, `"^(?!foo)"`), wantErr: "isn't Go RE2 syntax"}, + {name: "$schema", schema: replace(`{"type":"object",`, `{"$schema":"http://json-schema.org/draft-07/schema#","type":"object",`), wantErr: "can't set $schema"}, + {name: "integer option not an integer", form: func(form *pluginv1.AdminFormDescriptor) { + field(form, "level").Options[0].Value = "abc" + }, wantErr: `option "abc" isn't an integer`}, + {name: "option outside enum", form: func(form *pluginv1.AdminFormDescriptor) { + field(form, "server").Options[1].Value = "c" + }, wantErr: `option "c" fails the field's checks`}, + {name: "enum value without an option", form: func(form *pluginv1.AdminFormDescriptor) { + f := field(form, "server") + f.Options = f.Options[:1] + }, wantErr: "options and enum must match"}, + {name: "duplicate option", form: func(form *pluginv1.AdminFormDescriptor) { + field(form, "level").Options[1].Value = "01" + }, wantErr: "twice"}, + {name: "option fails a bound", schema: replace(`"level":{"type":"integer","enum":[1,2]}`, `"level":{"type":"integer","minimum":2}`), + wantErr: `option "1" fails the field's checks`}, + {name: "enum on a text field", schema: replace(`"title":"Topic",`, `"title":"Topic","enum":["alerts"],`), wantErr: "declares enum"}, + {name: "default_value of another type", form: func(form *pluginv1.AdminFormDescriptor) { + field(form, "priority").DefaultValue = structpb.NewStringValue("3") + }, wantErr: "default_value must be numeric"}, + {name: "fractional integer default_value", form: func(form *pluginv1.AdminFormDescriptor) { + field(form, "priority").DefaultValue = structpb.NewNumberValue(2.5) + }, wantErr: "default_value isn't of type integer"}, + {name: "default_value out of range", form: func(form *pluginv1.AdminFormDescriptor) { + field(form, "priority").DefaultValue = structpb.NewNumberValue(9) + }, wantErr: "default_value fails the field's checks"}, + {name: "default_value fails pattern", form: func(form *pluginv1.AdminFormDescriptor) { + field(form, "topic").DefaultValue = structpb.NewStringValue("no spaces") + }, wantErr: "default_value fails the field's checks"}, + {name: "select default_value not an option", form: func(form *pluginv1.AdminFormDescriptor) { + field(form, "level").DefaultValue = structpb.NewNumberValue(3) + }, wantErr: "default_value fails the field's checks"}, + {name: "select default not an option without enum", schema: replace(`"level":{"type":"integer","enum":[1,2]}`, `"level":{"type":"integer","default":3}`), + wantErr: "default isn't one of its options"}, + {name: "schema default of another type", schema: replace(`"default":3`, `"default":"3"`), wantErr: "default isn't of type integer"}, + {name: "schema default object", schema: replace(`"default":"alerts"`, `"default":{}`), wantErr: "default isn't of type string"}, + {name: "schema default out of range", schema: replace(`"default":3`, `"default":0`), wantErr: "default fails the field's checks"}, + {name: "required only on the form", form: func(form *pluginv1.AdminFormDescriptor) { + field(form, "token").Required = true + }, wantErr: "must agree"}, + {name: "required only in the schema", form: func(form *pluginv1.AdminFormDescriptor) { + field(form, "topic").Required = false + }, wantErr: "must agree"}, + {name: "key with trailing space", rekey: [2]string{"token", "token "}, wantErr: "must be a letter followed by"}, + {name: "key with a dot", rekey: [2]string{"token", "a.b"}, wantErr: "must be a letter followed by"}, + {name: "key starting with a digit", rekey: [2]string{"token", "1token"}, wantErr: "must be a letter followed by"}, + {name: "duplicate key", form: func(form *pluginv1.AdminFormDescriptor) { + form.Fields = append(form.Fields, &pluginv1.AdminFormField{Key: "token", Label: "Again", Control: pluginv1.AdminFormControl_ADMIN_FORM_CONTROL_PASSWORD}) + }, wantErr: "duplicated"}, + {name: "minimum above maximum", schema: replace(`"minimum":1,"maximum":5`, `"minimum":5,"maximum":1`), wantErr: "minimum 5 above maximum 1"}, + {name: "secret select", form: func(form *pluginv1.AdminFormDescriptor) { + field(form, "server").Secret = true + }, wantErr: "its control must be PASSWORD or TEXT"}, + {name: "integer bounds holding no whole number", schema: replace(`"minimum":1,"maximum":5`, `"minimum":0.1,"maximum":0.9`), wantErr: "hold no whole number"}, + {name: "integer minimum beyond what a setting can carry", schema: replace(`"minimum":1,"maximum":5`, `"minimum":9007199254740992`), wantErr: "hold no whole number"}, + {name: "integer option too large to carry exactly", schema: replace(`"level":{"type":"integer","enum":[1,2]}`, `"level":{"type":"integer"}`), + form: func(form *pluginv1.AdminFormDescriptor) { + field(form, "level").Options[1].Value = "9007199254740993" + }, wantErr: "outside the whole numbers a setting can hold exactly"}, + {name: "minLength above maxLength", schema: replace(`"minLength":1,"maxLength":64`, `"minLength":65,"maxLength":64`), wantErr: "minLength 65 above maxLength 64"}, + {name: "negative length", schema: replace(`"minLength":1`, `"minLength":-1`), wantErr: "negative minLength"}, + {name: "minimum on a string", schema: replace(`"format":"password"`, `"minimum":1`), wantErr: "applies only to an integer or number field"}, + {name: "pattern on a number", schema: replace(`"type":"number","minimum":0`, `"type":"number","pattern":"x","minimum":0`), wantErr: "applies only to a string field"}, + {name: "format on a boolean", schema: replace(`"type":"boolean"`, `"type":"boolean","format":"date"`), wantErr: "applies only to a string field"}, + {name: "secret number", form: func(form *pluginv1.AdminFormDescriptor) { field(form, "priority").Secret = true }, wantErr: "secret but not a string"}, + } { + t.Run(tc.name, func(t *testing.T) { + jsonSchema := everyControlSchema + if tc.schema != nil { + jsonSchema = tc.schema(jsonSchema) + if jsonSchema == everyControlSchema { + t.Fatal("schema change didn't apply") + } + } + form := everyControlForm() + if from, to := tc.rekey[0], tc.rekey[1]; from != "" { + jsonSchema = strings.Replace(jsonSchema, `"`+from+`":`, `"`+to+`":`, 1) + field(form, from).Key = to + } + if tc.form != nil { + tc.form(form) + } + err := validateChannel(jsonSchema, form) + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("Validate() = %v, want error containing %q", err, tc.wantErr) + } + }) + } +} + +// replace returns a schema change that replaces old with new once. +func replace(old, new string) func(string) string { + return func(s string) string { return strings.Replace(s, old, new, 1) } +} diff --git a/pkg/pluginsdk/runtime/notification_channel_test.go b/pkg/pluginsdk/runtime/notification_channel_test.go new file mode 100644 index 0000000..6771cb7 --- /dev/null +++ b/pkg/pluginsdk/runtime/notification_channel_test.go @@ -0,0 +1,49 @@ +package runtime + +import ( + "context" + "strings" + "testing" + + pluginv1 "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginproto/silo/plugin/v1" + "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/capability" +) + +type notificationChannel struct { + pluginv1.UnimplementedNotificationChannelServer +} + +func (notificationChannel) SendNotification(_ context.Context, req *pluginv1.SendNotificationRequest) (*pluginv1.SendNotificationResponse, error) { + return &pluginv1.SendNotificationResponse{Outcome: pluginv1.NotificationSendOutcome_NOTIFICATION_SEND_OUTCOME_DELIVERED, Message: req.GetMessage().GetTitle()}, nil +} + +func notificationChannelManifest() *pluginv1.PluginManifest { + return &pluginv1.PluginManifest{ + PluginId: "silo.test", + Capabilities: []*pluginv1.CapabilityDescriptor{{Type: capability.NotificationChannel, Id: "push"}}, + } +} + +func TestManifestServeConfigServesNotificationChannel(t *testing.T) { + cfg, err := manifestServeConfig(notificationChannelManifest(), CapabilityServers{}, WithNotificationChannel(notificationChannel{})) + if err != nil { + t.Fatalf("manifestServeConfig = %v", err) + } + resp, err := serveConfigClient(t, cfg).NotificationChannel().SendNotification(context.Background(), + &pluginv1.SendNotificationRequest{Message: &pluginv1.NotificationMessage{Title: "New episode"}}) + if err != nil || resp.GetMessage() != "New episode" { + t.Fatalf("SendNotification = %v, %v", resp, err) + } +} + +func TestManifestServeConfigRejectsNotificationChannelWithoutServer(t *testing.T) { + for name, option := range map[string]ServeManifestOption{ + "no option": nil, + "typed nil": WithNotificationChannel((*notificationChannel)(nil)), + } { + _, err := manifestServeConfig(notificationChannelManifest(), CapabilityServers{}, option) + if err == nil || !strings.Contains(err.Error(), "WithNotificationChannel") { + t.Errorf("%s: manifestServeConfig = %v, want an error naming WithNotificationChannel", name, err) + } + } +} diff --git a/pkg/pluginsdk/runtime/runtime.go b/pkg/pluginsdk/runtime/runtime.go index ee1fa5f..1e61596 100644 --- a/pkg/pluginsdk/runtime/runtime.go +++ b/pkg/pluginsdk/runtime/runtime.go @@ -95,13 +95,15 @@ type optionalServices struct { authProviderChecks pluginv1.AuthProviderChecksServer networkIdentityAuth pluginv1.NetworkIdentityAuthServer configurationChecks pluginv1.ConfigurationChecksServer + notificationChannel pluginv1.NotificationChannelServer } func pluginSetWithOptionalServices(servers CapabilityServers, optional optionalServices) plugin.PluginSet { // Compare fields one by one: == on the struct would panic for a server // whose dynamic type is not comparable. if optional.watchSyncDeviceAuthorization == nil && optional.authProviderChecks == nil && - optional.networkIdentityAuth == nil && optional.configurationChecks == nil { + optional.networkIdentityAuth == nil && optional.configurationChecks == nil && + optional.notificationChannel == nil { return DefaultPluginSet(servers) } return plugin.PluginSet{ @@ -187,6 +189,12 @@ func (c *Client) ConfigurationChecks() pluginv1.ConfigurationChecksClient { return pluginv1.NewConfigurationChecksClient(c.conn) } +// NotificationChannel returns the client for notification_channel.v1 +// destinations. Plugins that don't serve it answer Unimplemented. +func (c *Client) NotificationChannel() pluginv1.NotificationChannelClient { + return pluginv1.NewNotificationChannelClient(c.conn) +} + func (c *Client) HttpRoutes() pluginv1.HttpRoutesClient { return pluginv1.NewHttpRoutesClient(c.conn) } @@ -226,6 +234,9 @@ func (p *grpcPluginWithOptionalServices) GRPCServer( if p.optional.configurationChecks != nil { pluginv1.RegisterConfigurationChecksServer(server, p.optional.configurationChecks) } + if p.optional.notificationChannel != nil { + pluginv1.RegisterNotificationChannelServer(server, p.optional.notificationChannel) + } return nil } diff --git a/pkg/pluginsdk/runtime/serve_manifest.go b/pkg/pluginsdk/runtime/serve_manifest.go index e6209c0..bddf609 100644 --- a/pkg/pluginsdk/runtime/serve_manifest.go +++ b/pkg/pluginsdk/runtime/serve_manifest.go @@ -5,6 +5,7 @@ import ( "fmt" pluginv1 "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginproto/silo/plugin/v1" + "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/capability" "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/manifest" ) @@ -46,6 +47,7 @@ type serveManifestOptions struct { authProviderChecks pluginv1.AuthProviderChecksServer networkIdentityAuth pluginv1.NetworkIdentityAuthServer configurationChecks pluginv1.ConfigurationChecksServer + notificationChannel pluginv1.NotificationChannelServer configure ConfigureFunc } @@ -97,6 +99,16 @@ func WithConfigurationChecks(server pluginv1.ConfigurationChecksServer) ServeMan } } +// WithNotificationChannel registers the NotificationChannel service for a +// plugin that declares notification_channel.v1 capabilities. One server +// answers for every such capability in the manifest; each request names its +// capability_id. +func WithNotificationChannel(server pluginv1.NotificationChannelServer) ServeManifestOption { + return func(options *serveManifestOptions) { + options.notificationChannel = server + } +} + // WithConfigure delivers Runtime.Configure entries to fn, so a plugin served by // ServeManifestWithOptions can read its settings without writing its own // Runtime server. See ConfigureFunc for what fn may reject. @@ -205,6 +217,17 @@ func manifestServeConfig( return ServeConfig{}, fmt.Errorf("plugin manifest declares %q but no ConfigurationChecks server is registered; pass runtime.WithConfigurationChecks", manifest.ConfigurationCheckKey) } + if isNilServer(resolved.notificationChannel) { + resolved.notificationChannel = nil + } + if resolved.notificationChannel == nil { + for _, descriptor := range m.GetCapabilities() { + if descriptor.GetType() == capability.NotificationChannel { + return ServeConfig{}, fmt.Errorf("plugin capability %q is %s but no NotificationChannel server is registered; pass runtime.WithNotificationChannel", + descriptor.GetId(), capability.NotificationChannel) + } + } + } servers.Runtime = &manifestRuntime{manifest: m, configure: resolved.configure} return ServeConfig{ Servers: servers, @@ -213,6 +236,7 @@ func manifestServeConfig( authProviderChecks: resolved.authProviderChecks, networkIdentityAuth: resolved.networkIdentityAuth, configurationChecks: resolved.configurationChecks, + notificationChannel: resolved.notificationChannel, }), }, nil } diff --git a/proto/silo/plugin/v1/common.proto b/proto/silo/plugin/v1/common.proto index 66f7626..cea242e 100644 --- a/proto/silo/plugin/v1/common.proto +++ b/proto/silo/plugin/v1/common.proto @@ -158,6 +158,10 @@ message CapabilityDescriptor { // optional request-router features. RequestRouterDescriptor request_router = 12; + // Typed notification-channel contract metadata. Required for, and only + // meaningful on, capabilities of type "notification_channel.v1". + NotificationChannelDescriptor notification_channel = 13; + // Typed scheduled-task metadata. Optional, and only meaningful on // capabilities of type "scheduled_task.v1". A host that predates the field // ignores it only if it drops unknown fields wherever it reads the @@ -167,6 +171,20 @@ message CapabilityDescriptor { ScheduledTaskDescriptor scheduled_task = 14; } +// NotificationChannelDescriptor declares the kind of destination a +// notification_channel.v1 capability provides. The host lists it without +// starting the plugin. +message NotificationChannelDescriptor { + // Name of the destination kind, shown when adding one, such as "Pushover". + string display_name = 1; + // One or two sentences on what the destination is and what it needs. + string description = 2; + // The settings form for one destination: a JSON schema and an admin_form, + // validated like any ConfigSchema. Every value is stored encrypted. Fields + // marked secret are write-only: the host never returns them. + ConfigSchema destination_schema = 3; +} + // ScheduledTaskDescriptor describes a scheduled_task.v1 capability. message ScheduledTaskDescriptor { // The schedule the host uses until an administrator sets one. Without it, diff --git a/proto/silo/plugin/v1/notification_channel.proto b/proto/silo/plugin/v1/notification_channel.proto new file mode 100644 index 0000000..5abc576 --- /dev/null +++ b/proto/silo/plugin/v1/notification_channel.proto @@ -0,0 +1,116 @@ +syntax = "proto3"; + +package silo.plugin.v1; + +option go_package = "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginproto/silo/plugin/v1;pluginv1"; + +import "google/protobuf/struct.proto"; +import "google/protobuf/timestamp.proto"; + +// NotificationChannel delivers Silo notifications to a kind of destination +// the plugin provides, such as a push service or a chat app. A user adds a +// destination of that kind in their notification settings and fills in the +// form the descriptor declares. +// +// The host owns everything else: which notifications a profile receives, the +// per-destination preferences, the delivery queue, retries with backoff, +// failure counts, and disabling a destination that keeps failing. The plugin +// checks a destination's settings and sends one message at a time. +service NotificationChannel { + // ValidateDestination checks a destination's settings before the host + // saves them, for example by asking the service whether a user key exists. + // Return valid=false with a message the user can act on; return a gRPC + // error only when the check itself couldn't run. + rpc ValidateDestination(ValidateNotificationDestinationRequest) returns (ValidateNotificationDestinationResponse); + + // SendNotification delivers one message to one destination. The host + // calls it at least once per message and destination, possibly from + // different servers, with the same delivery_key on every attempt. A gRPC + // error, or no answer within 15 seconds, counts as RETRY. + rpc SendNotification(SendNotificationRequest) returns (SendNotificationResponse); +} + +message ValidateNotificationDestinationRequest { + // The settings as the user entered them, keyed by destination_schema + // property. On an edit, secret fields the user left unchanged carry their + // stored values. + google.protobuf.Struct config = 1; + // The notification_channel.v1 capability the destination belongs to. + string capability_id = 2; +} + +message ValidateNotificationDestinationResponse { + bool valid = 1; + // Why the settings don't work, shown to the user when valid is false. + // Never include secrets. + string message = 2; +} + +message SendNotificationRequest { + // The destination's ID, stable for its lifetime. + string destination_id = 1; + // The destination's saved settings, secrets included. + google.protobuf.Struct config = 2; + NotificationMessage message = 3; + // Identifies this message to this destination. It is the same on every + // attempt, so pass it to the service as an idempotency key where it has + // one. + string delivery_key = 4; + // 1 on the first attempt. + int32 attempt = 5; + // True for a test message the user asked for. The host doesn't retry it + // or count its failure. + bool test = 6; + // The notification_channel.v1 capability the destination belongs to. + string capability_id = 7; +} + +// NotificationMessage is one notification, rendered by the host. +message NotificationMessage { + // Type of the notification, such as "episode.available", + // "watchlist.available", "request.approved", "request.declined", + // "request.fulfilled" or "test". The vocabulary is open. + string type = 1; + // Short title, such as "New episode of Severance". + string title = 2; + // One or two lines of plain text. + string body = 3; + // Absolute link that opens the item in Silo. Empty when the host has no + // public URL. + string url = 4; + // Absolute URL of a poster or still, when there is one. It can expire. + string image_url = 5; + google.protobuf.Timestamp created_at = 6; + // The notification's details, shaped as the events package's + // Notification type, for plugins that render their own text. Empty for a + // test message. + google.protobuf.Struct details = 7; +} + +enum NotificationSendOutcome { + // An empty response acknowledges the message, like DELIVERED. + NOTIFICATION_SEND_OUTCOME_UNSPECIFIED = 0; + NOTIFICATION_SEND_OUTCOME_DELIVERED = 1; + // A temporary failure, such as a timeout or a rate limit. The host tries + // again later. + NOTIFICATION_SEND_OUTCOME_RETRY = 2; + // This message can't be delivered, but the destination still works. The + // host drops the message. + NOTIFICATION_SEND_OUTCOME_FAILED = 3; + // The destination's settings no longer work, such as a revoked key. The + // host drops the message and disables the destination until its owner + // fixes it. + NOTIFICATION_SEND_OUTCOME_DESTINATION_INVALID = 4; +} + +message SendNotificationResponse { + NotificationSendOutcome outcome = 1; + // Short reason for a failure, shown to the destination's owner. Never + // include secrets. + string message = 2; + // With RETRY: wait at least this long before the next attempt, up to a + // host cap (six hours on Silo). A plugin asked to wait longer is called + // again sooner and should answer RETRY with the wait that remains. It + // never shortens the host's own delay. 0 leaves the delay to the host. + int32 retry_after_seconds = 3; +}