Skip to content

Add a channel ​

clc-app-notifications delivers through two channels: in-app over Centrifugo, and Web Push. There is no plug-in interface. A new channel is a new River job that the dispatch step queues next to Web Push. Copy the Web Push channel, which records a delivery row per target with retries and a final status.

This page uses email as the example. Code names such as emailArgs and LoadEmailSend are new; everything else exists in the repository.

How Web Push works ​

StepFileWhat it does
notification.in_app jobinternal/worker/in_app.goPublishes to Centrifugo if the user is online, then schedules dispatch.
notification.dispatch jobinternal/worker/dispatch.goSkips shown, expired or unapproved notifications. Inserts one notification_deliveries row and one push job per target.
notification.push jobinternal/worker/push.goSends one push and records the outcome.
Senderinternal/push/Calls the push service and classifies errors.
notification.reconcile jobinternal/worker/Every minute, marks deliveries whose jobs River gave up on as failed or expired.

The job and its database writes commit together through completeJob in internal/worker/worker.go.

The title and body are written in English when the bridge stores the notification. A channel sends the stored text. There are no templates.

1. Write the sender ​

Add internal/email/ with a sender that returns a provider reference or an error. Classify errors the way internal/push/errors.go does, so the worker can tell them apart:

ErrorWorker action
Permanent, such as a rejected addressRecord failed
Rate limited, with a delaySnooze the job
Anything elseReturn it. River retries.

2. Allow the channel in the database ​

Add migrations/007_email_channel.sql. notification_deliveries.channel only allows push today.

sql
ALTER TABLE notification_deliveries DROP CONSTRAINT notification_deliveries_channel_check;
ALTER TABLE notification_deliveries ADD CONSTRAINT notification_deliveries_channel_check
    CHECK (channel IN ('push', 'email'));

---- create above / drop below ----

DELETE FROM notification_deliveries WHERE channel = 'email';
ALTER TABLE notification_deliveries DROP CONSTRAINT notification_deliveries_channel_check;
ALTER TABLE notification_deliveries ADD CONSTRAINT notification_deliveries_channel_check
    CHECK (channel IN ('push'));

Add a table for the destination too, such as a verified email address per user. Nothing stores one today.

3. Add the queries ​

Queries live in internal/store/queries/*.sql, each starting with -- name: <name>. Each query also needs a matching field in store.Queries in internal/store/queries.go.

  • A query that lists a user's email targets, for dispatch.
  • A query that loads one delivery with its notification and address, like load-push-delivery.

record-delivery-status, record-delivery-accepted and reconcile-deliveries work for any channel.

Store.InsertDelivery in internal/store/delivery.go always writes push. Add a channel parameter.

4. Add the job and worker ​

Add internal/worker/email.go:

go
const emailQueue = "email"

type (
	emailArgs struct {
		DeliveryID string    `json:"delivery_id"`
		NotAfter   time.Time `json:"not_after"`
	}

	emailWorker struct {
		river.WorkerDefaults[emailArgs]
		service *Worker
	}
)

func (emailArgs) Kind() string { return "notification.email" }

func (emailArgs) InsertOpts() river.InsertOpts {
	return river.InsertOpts{Queue: emailQueue, MaxAttempts: 10}
}

func (*emailWorker) Timeout(*river.Job[emailArgs]) time.Duration { return 15 * time.Second }

func (w *emailWorker) Work(ctx context.Context, job *river.Job[emailArgs]) error {
	return w.service.sendEmail(ctx, job)
}

func (w *Worker) finishEmail(ctx context.Context, job *river.Job[emailArgs], deliveryID, status, ref string) error {
	return completeJob(ctx, w.pool, job, func(tx pgx.Tx) error {
		if status == "accepted" {
			return w.pg.RecordAccepted(ctx, tx, deliveryID, ref)
		}
		return w.pg.RecordDeliveryStatus(ctx, tx, deliveryID, status)
	})
}

sendEmail follows sendPush in internal/worker/push.go:

  1. Load the delivery with LoadEmailSend. Return nil if it is gone or no longer queued.
  2. If the notification has been shown, or not_after has passed, finish with suppressed or expired.
  3. Check that the user is still approved, with w.directory.ApprovedByID. If not, finish with suppressed.
  4. Send. Then finish with accepted and the provider reference, finish with failed for a permanent error, return river.JobSnooze(delay) when rate limited, or return the error to retry.

Every outcome except a retry goes through finishEmail, so the status and the job's completion commit together. To retry on a custom schedule, add a NextRetry method, as pushWorker does.

5. Queue deliveries from dispatch ​

In dispatch in internal/worker/dispatch.go, load the user's email targets next to EligibleSubscriptions. Inside the same completeJob call, insert a delivery row with channel email for each target, then insert its job with w.client.InsertTx, as queueDelivery does for Web Push.

Dispatch runs after the in-app step. A notification the user has already seen in the app is not emailed.

6. Wire it up ​

  • Worker dependency. Add an interface for the sender next to Pusher in internal/worker/types.go, and a field in Opts and Worker.

  • Registration. In internal/worker/worker.go, add the worker and its queue:

    go
    river.AddWorker(cfg.Workers, &emailWorker{service: w})
    go
    emailQueue: {MaxWorkers: o.EmailWorkers},
  • Config. Add an [email] section to config.toml, and to Config, fileConfig, ParseConfig and Validate in internal/util/config.go. Environment variables follow, such as NOTIFICATIONS_EMAIL__API_KEY. Add secrets to .env.example.

  • Constructor. Build the sender in initWorker in cmd/notifications/init.go, where push.NewSender is built, and pass it in worker.Opts.

  • Inbox. The delivery-summaries query reports every delivery row as push status. Filter it by channel.

7. Test ​

  • Unit-test the sender's error classification, as TestErrorClass in internal/push/push_test.go does.
  • Add an integration test with a fake sender, as countPush does in internal/worker/delivery_integration_test.go. Integration tests start PostgreSQL in a container when NOTIFICATIONS_TEST_DSN is empty.
sh
make test
make test-integration

If you add tables, add them to the TRUNCATE list in internal/store/store_test.go.