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
48 changes: 46 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,49 @@ up to 30s, and each attempt gets the full timeout. HTTP redirects to another
host or from https to http are refused, since they would forward headers
and the body.

## Go package

`github.com/suprbdev/noty/notify` sends notifications from a Go program
with the same config format, templates, fan-out, retries and secret masking
as the CLI (which is built on it):

```
go get github.com/suprbdev/noty@latest
```

```go
cfg, err := notify.Load("/etc/myapp/noty.yaml") // or notify.Parse(data)
if err != nil {
return err // errors.Is(err, notify.ErrInvalidConfig) for config problems
}
client, err := notify.New(cfg)
if err != nil {
return err
}
res, err := client.Send(ctx, notify.Message{
Channels: []string{"slack", "email"}, // empty: defaults.channel
Subject: "deploy finished",
Text: "api v2.4 is live", // {{ .Message }}
Vars: map[string]string{"environment": "prod"},
})
var sendErr *notify.SendError
if errors.As(err, &sendErr) {
// Some channels failed; the others were still attempted.
log.Printf("failed channels %v: %v", res.Failed(), err)
}
```

`Message` also has `To` (recipient override), `Template` (body template
file override) and `DryRun` (render and validate only; each
`ChannelResult.Description` says what would be sent). `Send` returns
`notify.ErrNoChannel` or an error wrapping `notify.ErrUnknownChannel`
before sending anything when the channels can't be resolved.

Options: `notify.WithLookupEnv` resolves `${VAR}` through your own lookup
instead of the process environment (for `Load`/`Parse`); `WithHTTPClient`,
`WithExecRunner` (fake or restrict `exec` channels), `WithTimeout`,
`WithRetries`, `WithBackoff` and `WithClock` customise the client.

## Adding a provider type

Implement the `Sender` interface and register a factory — nothing else
Expand All @@ -134,7 +177,7 @@ changes:
```go
// internal/provider/carrierpigeon.go
func init() {
Register("pigeon", func(node *yaml.Node, r *render.Renderer) (Sender, error) {
Register("pigeon", func(node *yaml.Node, deps Deps) (Sender, error) {
var cfg pigeonConfig
if err := Decode(node, "pigeon", &cfg); err != nil { return nil, err }
return &pigeonSender{cfg}, nil
Expand All @@ -143,7 +186,8 @@ func init() {
```

Each provider decodes its own YAML from the channel node, so new settings
never touch the core config code. `Decode` rejects keys that are neither
never touch the core config code. `deps.Renderer` templates the provider's
own fields. `Decode` rejects keys that are neither
provider fields nor common channel fields, so config typos fail loudly with
a line number.

Expand Down
217 changes: 37 additions & 180 deletions internal/cli/cli.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Package cli wires flags, stdin, config, templates, and providers together.
// Package cli maps flags and stdin onto the notify package.
package cli

import (
Expand All @@ -7,17 +7,12 @@ import (
"flag"
"fmt"
"io"
"maps"
"net/url"
"os"
"sort"
"strings"
"sync"
"time"

"github.com/suprbdev/noty/internal/config"
"github.com/suprbdev/noty/internal/provider"
"github.com/suprbdev/noty/internal/render"
"github.com/suprbdev/noty/notify"
)

type multiFlag []string
Expand All @@ -27,9 +22,7 @@ func (m *multiFlag) Set(v string) error { *m = append(*m, v); return nil }

// retryDelay is the backoff before retry number attempt (1-based):
// 1s, 2s, 4s, ... capped at 30s.
var retryDelay = func(attempt int) time.Duration {
return min(time.Second<<min(attempt-1, 5), 30*time.Second)
}
var retryDelay = notify.DefaultBackoff

// Version is printed by --version. main sets it from the build-time stamp.
var Version = "dev"
Expand Down Expand Up @@ -86,26 +79,21 @@ func Run(args []string, stdin *os.File, stdout, stderr io.Writer) error {
return err
}
}
cfg, err := config.Load(path)
cfg, err := notify.Load(path)
if err != nil {
return err
}
if *verbose {
fmt.Fprintf(stderr, "config: %s\n", cfg.Path)
fmt.Fprintf(stderr, "config: %s\n", cfg.Path())
}

if *list {
names := make([]string, 0, len(cfg.Channels))
for name := range cfg.Channels {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
for _, ch := range cfg.Channels() {
def := ""
if name == cfg.Defaults.Channel {
if ch.Default {
def = " (default)"
}
fmt.Fprintf(stdout, "%-20s type=%s%s\n", name, cfg.Channels[name].Type, def)
fmt.Fprintf(stdout, "%-20s type=%s%s\n", ch.Name, ch.Type, def)
}
return nil
}
Expand All @@ -120,29 +108,18 @@ func Run(args []string, stdin *os.File, stdout, stderr io.Writer) error {
}
}

// --- Channels ---
chNames := splitNonEmpty(*channels)
if len(chNames) == 0 {
if cfg.Defaults.Channel == "" {
return fmt.Errorf("no channel specified: pass --channel or set defaults.channel in %s", cfg.Path)
}
chNames = []string{cfg.Defaults.Channel}
if len(chNames) == 0 && cfg.DefaultChannel() == "" {
return fmt.Errorf("no channel specified: pass --channel or set defaults.channel in %s", cfg.Path())
}

// --- Timeout ---
to := *timeout
if to == 0 {
to = 30 * time.Second
if cfg.Defaults.Timeout != "" {
d, err := time.ParseDuration(cfg.Defaults.Timeout)
if err != nil {
return fmt.Errorf("defaults.timeout: %w", err)
}
to = d
}
opts := []notify.Option{notify.WithTimeout(*timeout), notify.WithBackoff(retryDelay)}
if set["retries"] {
opts = append(opts, notify.WithRetries(*retries))
}
if to <= 0 {
return fmt.Errorf("timeout must be positive, got %v", to)
client, err := notify.New(cfg, opts...)
if err != nil {
return err
}

// --- Flag vars ---
Expand All @@ -155,160 +132,40 @@ func Run(args []string, stdin *os.File, stdout, stderr io.Writer) error {
flagVars[k] = v
}

for _, name := range chNames {
if _, ok := cfg.Channels[name]; !ok {
return fmt.Errorf("unknown channel %q (run --list to see channels)", name)
}
}

hostname, _ := os.Hostname()
renderer := &render.Renderer{TemplateDir: cfg.TemplateDir}
mask := secretMasker(cfg.EnvValues)

send := func(name string) (string, error) {
ch := cfg.Channels[name]

// Merge vars: global < channel < flags.
vars := map[string]string{}
maps.Copy(vars, cfg.Vars)
maps.Copy(vars, ch.Common.Vars)
maps.Copy(vars, flagVars)

data := render.Data{
Message: msgText,
To: toFlags,
Channel: name,
Vars: vars,
Now: time.Now(),
Hostname: hostname,
}

// Subject: base (flag > defaults.subject), wrapped by the channel template/inline.
base := *subject
if base == "" {
var err error
if base, err = renderer.Resolve("", cfg.Defaults.Subject, "", data); err != nil {
return "", fmt.Errorf("defaults.subject: %w", err)
}
}
data.Subject = base
subj, err := renderer.Resolve(ch.Common.SubjectTemplate, ch.Common.Subject, base, data)
if err != nil {
return "", fmt.Errorf("subject: %w", err)
}
data.Subject = subj

// Body: --template flag > channel body_template > channel inline body > raw message.
bodyTmpl := *tmplPath
if bodyTmpl == "" {
bodyTmpl = ch.Common.BodyTemplate
}
body, err := renderer.Resolve(bodyTmpl, ch.Common.Body, msgText, data)
if err != nil {
return "", fmt.Errorf("body: %w", err)
}

sender, err := provider.New(ch.Type, ch.Raw, renderer)
if err != nil {
return "", err
}

msg := provider.Message{Subject: subj, Body: body, To: toFlags, Data: data}

maxRetries := cfg.Defaults.Retries
if ch.Common.Retries != nil {
maxRetries = *ch.Common.Retries
}
if set["retries"] {
maxRetries = *retries
}
if maxRetries < 0 {
return "", fmt.Errorf("retries must be >= 0, got %d", maxRetries)
}

if *dryRun {
return sender.Describe(msg)
}

for attempt := 1; ; attempt++ {
ctx, cancel := context.WithTimeout(context.Background(), to)
err = sender.Send(ctx, msg)
cancel()
if err == nil || attempt > maxRetries || !provider.IsTemporary(err) {
if err != nil && attempt > 1 {
err = fmt.Errorf("%w (after %d attempts)", err, attempt)
}
return "", err
}
time.Sleep(retryDelay(attempt))
res, err := client.Send(context.Background(), notify.Message{
Channels: chNames,
To: toFlags,
Subject: *subject,
Text: msgText,
Template: *tmplPath,
Vars: flagVars,
DryRun: *dryRun,
})
var sendErr *notify.SendError
if err != nil && !errors.As(err, &sendErr) {
if errors.Is(err, notify.ErrUnknownChannel) {
return fmt.Errorf("%w (run --list to see channels)", err)
}
return err
}

type result struct {
desc string
err error
}
results := make([]result, len(chNames))
var wg sync.WaitGroup
for i, name := range chNames {
wg.Add(1)
go func() {
defer wg.Done()
results[i].desc, results[i].err = send(name)
}()
}
wg.Wait()

var failed []string
for i, name := range chNames {
switch r := results[i]; {
case r.err != nil:
fmt.Fprintf(stderr, "channel %q: %s\n", name, mask(r.err.Error()))
failed = append(failed, name)
for _, r := range res.Channels {
switch {
case r.Err != nil:
fmt.Fprintf(stderr, "channel %q: %s\n", r.Channel, r.Err)
case *dryRun:
fmt.Fprintf(stdout, "[dry-run] channel %q:\n %s\n", name, mask(r.desc))
fmt.Fprintf(stdout, "[dry-run] channel %q:\n %s\n", r.Channel, r.Description)
case *verbose:
fmt.Fprintf(stderr, "channel %q: sent\n", name)
fmt.Fprintf(stderr, "channel %q: sent\n", r.Channel)
}
}

if len(failed) > 0 {
if failed := res.Failed(); len(failed) > 0 {
return fmt.Errorf("failed channels: %v", failed)
}
return nil
}

// secretMasker returns a function that replaces every value substituted
// from the environment, raw or URL query/path-escaped, with its ${NAME}
// reference. Values shorter than four bytes are left alone so common
// substrings aren't masked.
func secretMasker(env map[string]string) func(string) string {
type pair struct{ old, ref string }
var pairs []pair
for name, v := range env {
if len(v) < 4 {
continue
}
for _, form := range []string{v, url.QueryEscape(v), url.PathEscape(v)} {
pairs = append(pairs, pair{form, "${" + name + "}"})
}
}
if len(pairs) == 0 {
return func(s string) string { return s }
}
sort.Slice(pairs, func(i, j int) bool {
if len(pairs[i].old) != len(pairs[j].old) {
return len(pairs[i].old) > len(pairs[j].old)
}
return pairs[i].old < pairs[j].old || pairs[i].old == pairs[j].old && pairs[i].ref < pairs[j].ref
})
args := make([]string, 0, 2*len(pairs))
for _, p := range pairs {
args = append(args, p.old, p.ref)
}
return strings.NewReplacer(args...).Replace
}

// readStdin returns piped stdin text with trailing newlines removed. A nil or
// unreadable stdin and the null device yield an empty message; an interactive
// terminal is an error so a forgotten -m doesn't send a blank notification.
Expand Down
11 changes: 0 additions & 11 deletions internal/cli/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -425,17 +425,6 @@ func TestRunRejectsNonPositiveTimeout(t *testing.T) {
}
}

func TestSecretMasker(t *testing.T) {
mask := secretMasker(map[string]string{"SHORT": "abc", "TOKEN": "s3cr3t", "LONG": "s3cr3t-and-more", "ESC": "ab+cd/ef=="})
got := mask("abc s3cr3t s3cr3t-and-more ab%2Bcd%2Fef%3D%3D ab+cd%2Fef==")
if want := "abc ${TOKEN} ${LONG} ${ESC} ${ESC}"; got != want {
t.Errorf("mask = %q, want %q", got, want)
}
if got := secretMasker(nil)("unchanged"); got != "unchanged" {
t.Errorf("empty masker changed input: %q", got)
}
}

func TestRunMasksEnvSecrets(t *testing.T) {
t.Setenv("NOTY_TEST_TOKEN", "tok-123456")
cfg := `
Expand Down
Loading
Loading