Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
444 changes: 444 additions & 0 deletions cli/cmd/notification.go

Large diffs are not rendered by default.

88 changes: 88 additions & 0 deletions cli/cmd/notification_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package cmd

import (
"os"
"path/filepath"
"testing"

"github.com/stretchr/testify/require"
)

func TestReadNotificationCreateRequest(t *testing.T) {
t.Run("valid webhook request", func(t *testing.T) {
path := writeNotificationJSON(t, `{
"eventConfigs": [{"eventType":"customer.created","filters":{}}],
"isEnabled": true,
"webhookUrl": "https://example.com/webhook"
}`)

req, err := readNotificationCreateRequest(path)
require.NoError(t, err)
require.Equal(t, "https://example.com/webhook", req.WebhookURL)
require.Len(t, req.EventConfigs, 1)
})

t.Run("missing delivery target", func(t *testing.T) {
path := writeNotificationJSON(t, `{
"eventConfigs": [{"eventType":"customer.created","filters":{}}],
"isEnabled": true
}`)

_, err := readNotificationCreateRequest(path)
require.EqualError(t, err, "one of emailAddress or webhookUrl must be set")
})

t.Run("missing event configs", func(t *testing.T) {
path := writeNotificationJSON(t, `{
"isEnabled": true,
"emailAddress": "alerts@example.com"
}`)

_, err := readNotificationCreateRequest(path)
require.EqualError(t, err, "eventConfigs must contain at least one event config")
})
}

func TestReadNotificationUpdateRequest(t *testing.T) {
t.Run("reject empty patch", func(t *testing.T) {
path := writeNotificationJSON(t, `{}`)

_, err := readNotificationUpdateRequest(path)
require.EqualError(t, err, "subscription update file must include at least one field")
})

t.Run("accept explicit false enable flag", func(t *testing.T) {
path := writeNotificationJSON(t, `{"isEnabled":false}`)

req, err := readNotificationUpdateRequest(path)
require.NoError(t, err)
require.NotNil(t, req.IsEnabled)
require.False(t, *req.IsEnabled)
})
}

func TestReadNotificationWebhookTestRequest(t *testing.T) {
t.Run("reject missing event type", func(t *testing.T) {
path := writeNotificationJSON(t, `{"webhookUrl":"https://example.com/webhook"}`)

_, err := readNotificationWebhookTestRequest(path)
require.EqualError(t, err, "eventType is required")
})

t.Run("reject invalid json", func(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "bad.json")
require.NoError(t, os.WriteFile(path, []byte(`{"webhookUrl":`), 0644))

_, err := readNotificationWebhookTestRequest(path)
require.EqualError(t, err, "file is not valid JSON")
})
}

func writeNotificationJSON(t *testing.T, body string) string {
t.Helper()
dir := t.TempDir()
path := filepath.Join(dir, "notification.json")
require.NoError(t, os.WriteFile(path, []byte(body), 0644))
return path
}
24 changes: 24 additions & 0 deletions cli/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,30 @@ func Execute(rootCmd *cobra.Command, stdin io.Reader, stdout io.Writer, stderr i
runCmds.InitPolicyRm(policyCmd)
policyCmd.PersistentPreRunE = preRunSetupAPIs

notificationCmd := runCmds.InitNotificationCommand(runCmds.rootCmd)
notificationSubscriptionCmd := runCmds.InitNotificationSubscriptionCommand(notificationCmd)
runCmds.InitNotificationSubscriptionList(notificationSubscriptionCmd)
runCmds.InitNotificationSubscriptionGet(notificationSubscriptionCmd)
runCmds.InitNotificationSubscriptionCreate(notificationSubscriptionCmd)
runCmds.InitNotificationSubscriptionUpdate(notificationSubscriptionCmd)
runCmds.InitNotificationSubscriptionRemove(notificationSubscriptionCmd)
runCmds.InitNotificationSubscriptionEvents(notificationSubscriptionCmd)

notificationEventCmd := runCmds.InitNotificationEventCommand(notificationCmd)
runCmds.InitNotificationEventList(notificationEventCmd)
runCmds.InitNotificationEventRetry(notificationEventCmd)

notificationEventTypeCmd := runCmds.InitNotificationEventTypeCommand(notificationCmd)
runCmds.InitNotificationEventTypeList(notificationEventTypeCmd)

notificationEmailCmd := runCmds.InitNotificationEmailCommand(notificationCmd)
runCmds.InitNotificationEmailResendVerification(notificationEmailCmd)
runCmds.InitNotificationEmailVerify(notificationEmailCmd)

notificationWebhookCmd := runCmds.InitNotificationWebhookCommand(notificationCmd)
runCmds.InitNotificationWebhookTest(notificationWebhookCmd)
notificationCmd.PersistentPreRunE = preRunSetupAPIs

// Add config command with init subcommand
configCmd := runCmds.InitConfigCommand(runCmds.rootCmd)
runCmds.InitInitCommand(configCmd)
Expand Down
257 changes: 257 additions & 0 deletions cli/print/notifications.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,257 @@
package print

import (
"encoding/json"
"fmt"
"strings"
"text/tabwriter"
"text/template"

"github.com/replicatedhq/replicated/pkg/types"
)

var notificationTemplateFuncs = template.FuncMap{
"notificationName": notificationName,
"subscriptionType": subscriptionType,
"subscriptionDestination": subscriptionDestination,
"subscriptionVerified": subscriptionVerified,
"webhookStatusCode": webhookStatusCode,
}

var notificationSubscriptionsTmpl = template.Must(template.New("notification-subscriptions").Funcs(notificationTemplateFuncs).Parse(`ID NAME TYPE DESTINATION ENABLED VERIFIED
{{ range . -}}
{{ .ID }} {{ notificationName . }} {{ subscriptionType . }} {{ subscriptionDestination . }} {{ .IsEnabled }} {{ subscriptionVerified . }}
{{ end }}`))

var notificationEventsTmpl = template.Must(template.New("notification-events").Funcs(funcs).Parse(`ID EVENT TYPE STATUS SUBSCRIPTION CREATED ATTEMPTS
{{ range . -}}
{{ .ID }} {{ .EventType }} {{ .Status }} {{ .SubscriptionID }} {{ localeTime .CreatedAt }} {{ len .Attempts }}
{{ end }}`))

var notificationEventTypesTmpl = template.Must(template.New("notification-event-types").Parse(`KEY DISPLAY NAME CATEGORY DESCRIPTION
{{ range . -}}
{{ .Key }} {{ .DisplayName }} {{ .Category }} {{ .Description }}
{{ end }}`))

var notificationEmailActionTmpl = template.Must(template.New("notification-email-action").Parse(`SUCCESS MESSAGE
{{ .Success }} {{ .Message }}
`))

var notificationRetryTmpl = template.Must(template.New("notification-retry").Parse(`SUCCESS MESSAGE
{{ .Success }} {{ .Message }}
`))

var notificationWebhookTestTmpl = template.Must(template.New("notification-webhook-test").Funcs(notificationTemplateFuncs).Parse(`SUCCESS STATUS CODE DURATION (MS) ERROR
{{ .Success }} {{ webhookStatusCode .StatusCode }} {{ .DurationMs }} {{ .Error }}
`))

func Notifications(outputFormat string, w *tabwriter.Writer, subscriptions []types.NotificationSubscription) error {
switch outputFormat {
case "table":
if err := notificationSubscriptionsTmpl.Execute(w, subscriptions); err != nil {
return err
}
case "json":
b, err := json.MarshalIndent(subscriptions, "", " ")
if err != nil {
return err
}
if _, err := fmt.Fprintln(w, string(b)); err != nil {
return err
}
default:
return fmt.Errorf("invalid output format: %s", outputFormat)
}
return w.Flush()
}

func Notification(outputFormat string, w *tabwriter.Writer, subscription *types.NotificationSubscription) error {
return Notifications(outputFormat, w, []types.NotificationSubscription{*subscription})
}

func NotificationEvents(outputFormat string, w *tabwriter.Writer, events []types.NotificationEvent) error {
switch outputFormat {
case "table":
if err := notificationEventsTmpl.Execute(w, events); err != nil {
return err
}
case "json":
b, err := json.MarshalIndent(events, "", " ")
if err != nil {
return err
}
if _, err := fmt.Fprintln(w, string(b)); err != nil {
return err
}
default:
return fmt.Errorf("invalid output format: %s", outputFormat)
}
return w.Flush()
}

func NotificationEventTypes(outputFormat string, w *tabwriter.Writer, response *types.NotificationEventTypesResponse) error {
switch outputFormat {
case "table":
if err := notificationEventTypesTmpl.Execute(w, response.EventTypes); err != nil {
return err
}
case "json":
b, err := json.MarshalIndent(response, "", " ")
if err != nil {
return err
}
if _, err := fmt.Fprintln(w, string(b)); err != nil {
return err
}
default:
return fmt.Errorf("invalid output format: %s", outputFormat)
}
return w.Flush()
}

func NotificationEmailAction(outputFormat string, w *tabwriter.Writer, response *types.NotificationEmailResponse) error {
switch outputFormat {
case "table":
if err := notificationEmailActionTmpl.Execute(w, response); err != nil {
return err
}
case "json":
b, err := json.MarshalIndent(response, "", " ")
if err != nil {
return err
}
if _, err := fmt.Fprintln(w, string(b)); err != nil {
return err
}
default:
return fmt.Errorf("invalid output format: %s", outputFormat)
}
return w.Flush()
}

func NotificationRetry(outputFormat string, w *tabwriter.Writer, response *types.NotificationRetryResponse) error {
switch outputFormat {
case "table":
if err := notificationRetryTmpl.Execute(w, response); err != nil {
return err
}
case "json":
b, err := json.MarshalIndent(response, "", " ")
if err != nil {
return err
}
if _, err := fmt.Fprintln(w, string(b)); err != nil {
return err
}
default:
return fmt.Errorf("invalid output format: %s", outputFormat)
}
return w.Flush()
}

func NotificationWebhookTest(outputFormat string, w *tabwriter.Writer, response *types.NotificationWebhookTestResponse) error {
switch outputFormat {
case "table":
if err := notificationWebhookTestTmpl.Execute(w, response); err != nil {
return err
}
case "json":
b, err := json.MarshalIndent(response, "", " ")
if err != nil {
return err
}
if _, err := fmt.Fprintln(w, string(b)); err != nil {
return err
}
default:
return fmt.Errorf("invalid output format: %s", outputFormat)
}
return w.Flush()
}

func NoNotifications(outputFormat string, w *tabwriter.Writer) error {
switch outputFormat {
case "table":
_, err := fmt.Fprintln(w, "No notification subscriptions found.")
if err != nil {
return err
}
case "json":
if _, err := fmt.Fprintln(w, "[]"); err != nil {
return err
}
default:
return fmt.Errorf("invalid output format: %s", outputFormat)
}
return w.Flush()
}

func NoNotificationEvents(outputFormat string, w *tabwriter.Writer) error {
switch outputFormat {
case "table":
_, err := fmt.Fprintln(w, "No notification events found.")
if err != nil {
return err
}
case "json":
if _, err := fmt.Fprintln(w, "[]"); err != nil {
return err
}
default:
return fmt.Errorf("invalid output format: %s", outputFormat)
}
return w.Flush()
}

func notificationName(sub types.NotificationSubscription) string {
if strings.TrimSpace(sub.Name) != "" {
return sub.Name
}
if len(sub.EventConfigs) == 1 {
return sub.EventConfigs[0].EventType
}
if len(sub.EventConfigs) > 1 {
return fmt.Sprintf("%d event types", len(sub.EventConfigs))
}
return "-"
}

func subscriptionType(sub types.NotificationSubscription) string {
if strings.TrimSpace(sub.WebhookURL) != "" {
return "webhook"
}
if strings.TrimSpace(sub.EmailAddress) != "" {
return "email"
}
return "unknown"
}

func subscriptionDestination(sub types.NotificationSubscription) string {
if strings.TrimSpace(sub.WebhookURL) != "" {
return sub.WebhookURL
}
if strings.TrimSpace(sub.EmailAddress) != "" {
return sub.EmailAddress
}
return "-"
}

func subscriptionVerified(sub types.NotificationSubscription) string {
if strings.TrimSpace(sub.EmailAddress) == "" {
return "-"
}
if sub.EmailVerified {
return "true"
}
if sub.RequiresVerification {
return "pending"
}
return "false"
}

func webhookStatusCode(code *int) string {
if code == nil {
return "-"
}
return fmt.Sprintf("%d", *code)
}
Loading
Loading