Skip to content
Open
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
101 changes: 101 additions & 0 deletions docs/content/docs/integrations/ahasend.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
---
title: AhaSend
description: Configure AhaSend for email sending in Lunogram
---

[AhaSend](https://ahasend.com/) is a European transactional email service that stores message data in the EU. Lunogram delivers email through the AhaSend API v2 and ingests AhaSend's webhooks for delivery, bounce, complaint, and engagement events.

## Features

- Email sending via the AhaSend API v2, including cc, bcc, and reply-to
- Webhook ingestion for delivery, bounce, suppression, complaint, open, click, and unsubscribe events
- Optional webhook signature verification

## Setup

### 1. Create an AhaSend Account

Create an account at [ahasend.com](https://ahasend.com/). The free plan includes 1,000 emails per month.

### 2. Add and Verify Your Domain

1. Add your sending domain in the [AhaSend dashboard](https://dash.ahasend.com)
2. Publish the SPF, DKIM, and return-path DNS records AhaSend shows
3. Run the DNS check until the domain is verified

See [AhaSend's domain setup guide](https://ahasend.com/docs/domains) for details.

### 3. Create an API Key

1. Open **Credentials** in the AhaSend dashboard and click **Add**
2. Create an **API Key v2** scoped to `messages:send:{your-domain}`
3. Copy the key; it starts with `aha-sk-`

Note your **account ID** from the dashboard's account settings as well.

### 4. Configure in Lunogram

1. Open your Lunogram project settings
2. Navigate to **Integrations** and click **Add Integration**
3. Select **AhaSend** from the list of providers
4. Enter your configuration:
- **AhaSend API Key**: Your API key
- **Account ID**: Your AhaSend account ID
- **Webhook Secret** (optional): Used to verify incoming webhooks
5. Click **Save** to create the provider

## Configuration Options

| Field | Required | Description |
|-------|----------|-------------|
| AhaSend API Key | Yes | API key v2 with the `messages:send` scope for your sending domain |
| Account ID | Yes | Your AhaSend account ID |
| Webhook Secret | No | AhaSend webhook secret (`aha-whsec-…`) used to verify webhook signatures |

## Webhooks

Lunogram exposes a webhook endpoint for your AhaSend integration. Each AhaSend message event is matched to the message Lunogram sent and recorded as an event on that message's user or organization:

| AhaSend event | Lunogram event |
|---------------|----------------|
| `message.reception` | `provider.sent` |
| `message.delivered` | `provider.delivered` |
| `message.transient_error` | `provider.deferred` |
| `message.bounced` | `provider.bounced` |
| `message.failed` | `provider.bounced` |
| `message.suppressed` | `provider.dropped` |
| `message.opened` | `provider.opened` |
| `message.clicked` | `provider.clicked` |
| `message.complained` | `provider.complained` |
| `message.unsubscribed` | `provider.unsubscribed` |

Other AhaSend events, such as suppression, domain, and contact events, are acknowledged and ignored, as are events for messages Lunogram did not send.

To enable webhooks:

1. Build the webhook URL for the integration: `<public URL>/webhooks/<project ID>/providers/<provider ID>`
- `<public URL>` is your deployment's [`public_url`](/settings/configuration)
- `<project ID>` and `<provider ID>` are the IDs in the console address while you edit the AhaSend integration: `/projects/<project ID>/integrations/provider/<provider ID>`
2. In AhaSend, open **Webhooks**, click **Add Webhook**, and enter the URL
3. Select the message events you want to track
4. (Recommended) Copy the **Webhook Secret** from the webhook's details page into the integration's **Webhook Secret** field so Lunogram can verify that incoming requests originate from AhaSend

## Troubleshooting

### Emails Not Sending

1. Verify your API key is correct and scoped to the domain of the "from" address
2. Confirm the **Account ID** matches the account the key belongs to
3. Ensure the domain is verified and sending from it is not paused

### Webhooks Not Updating Status

1. Confirm the webhook URL is registered in AhaSend for the relevant events
2. If you set a webhook secret in Lunogram, make sure it is the complete secret, including the `aha-whsec-` prefix
3. Check the webhook's delivery log in the AhaSend dashboard

## Related Links

- [AhaSend Documentation](https://ahasend.com/docs)
- [Send Email with the REST API](https://ahasend.com/docs/send-api/send-email)
- [AhaSend Webhooks](https://ahasend.com/docs/integrations/webhooks)
3 changes: 3 additions & 0 deletions docs/content/docs/integrations/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ Integrations are WASM plugins that enable Lunogram to send messages through vari
<Card title="Resend" href="/integrations/resend">
Modern email API built for developers with excellent deliverability.
</Card>
<Card title="AhaSend" href="/integrations/ahasend">
European transactional email API with EU data storage.
</Card>
</Cards>

### Coming Soon
Expand Down
1 change: 1 addition & 0 deletions docs/content/docs/integrations/meta.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"mailgun",
"sendgrid",
"ses",
"ahasend",
"smtp",
"---SMS---",
"twilio",
Expand Down
2 changes: 1 addition & 1 deletion docs/content/docs/integrations/smtp.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,4 @@ Any SMTP-compatible service works. See [Sending mail](/settings/mail) for the fu

Project providers are WASM modules, and a module reaches the network through the host's HTTP function. The sandbox offers no raw TCP socket, so a provider module cannot speak SMTP.

Configure an HTTP provider instead — [Resend](/integrations/resend), [Mailgun](/integrations/mailgun), [SendGrid](/integrations/sendgrid) or [Amazon SES](/integrations/ses) — or the webhook provider, which posts each message to an endpoint of yours that may relay it however you like, SMTP included.
Configure an HTTP provider instead — [Resend](/integrations/resend), [Mailgun](/integrations/mailgun), [SendGrid](/integrations/sendgrid), [Amazon SES](/integrations/ses) or [AhaSend](/integrations/ahasend) — or the webhook provider, which posts each message to an endpoint of yours that may relay it however you like, SMTP included.
29 changes: 19 additions & 10 deletions internal/http/controllers/v1/webhooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,11 +102,17 @@ func ProviderWebhookHandler(logger *zap.Logger, mgmt *management.State, registry
// Publish each event to NATS on the provider webhooks subject.
// Events are validated against the canonical set of provider event names
// so that WASM modules cannot inject arbitrary event names into the pipeline.
// TODO(events-log-consumer): build a NATS consumer on
// schemas.ProvidersWebhook(projectID) that joins the InboxMessageID
// back to the originating inbox message and writes a row to the
// events log. Tracked as a follow-up issue.
// The providers-webhooks consumer correlates each event with its inbox
// message, resolving MessageID for providers that cannot echo the inbox
// message ID back, and records it on the message's user or organization.
for _, event := range res.Events {
if event.InboxMessageID == uuid.Nil && event.MessageID == "" {
logger.Warn("webhook event identifies no message, skipping",
zap.String("event_name", event.EventName.String()),
)
continue
}

webhookEvent := schemas.ProviderWebhookEvent{
ProjectID: projectID,
ProviderID: providerID,
Expand All @@ -119,14 +125,17 @@ func ProviderWebhookHandler(logger *zap.Logger, mgmt *management.State, registry
Data: event.Data,
}

if event.InboxMessageID == uuid.Nil {
logger.Warn("webhook event has no inbox message ID, skipping",
zap.String("event_name", event.EventName.String()),
)
continue
// A provider retrying the webhook, e.g. after a lost response,
// resends the same events; the content-derived ID lets JetStream
// drop the copies within the stream's duplicates window.
webhookEvent.ID, err = schemas.ProviderWebhookEventID(webhookEvent)
if err != nil {
logger.Error("failed to identify webhook event", zap.Error(err))
w.WriteHeader(http.StatusInternalServerError)
return
}

err = pub.Publish(ctx, schemas.ProvidersWebhook(projectID), webhookEvent)
err = pub.Publish(ctx, schemas.ProvidersWebhook(projectID), webhookEvent, pubsub.WithMsgID("provider-webhook:"+webhookEvent.ID))
if err != nil {
logger.Error("failed to publish webhook event",
zap.String("event_name", event.EventName.String()),
Expand Down
14 changes: 14 additions & 0 deletions internal/pubsub/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,4 +151,18 @@ graph TB
%% Inbox push dispatch handlers
UserInboxDispatchSubject -->|Consume| UserInboxDispatchHandler["User Inbox Dispatch Handler"]
OrgInboxDispatchSubject -->|Consume| OrgInboxDispatchHandler["Organization Inbox Dispatch Handler"]

%% Provider message mappings, for providers whose webhooks cannot echo the inbox message ID
UserInboxHandler -->|Provider Message ID| ProviderMessagesSubject["providers.messages.{project_id}"]
OrgInboxHandler -->|Provider Message ID| ProviderMessagesSubject
UserInboxDispatchHandler -->|Provider Message ID| ProviderMessagesSubject
OrgInboxDispatchHandler -->|Provider Message ID| ProviderMessagesSubject
ProviderMessagesSubject -->|Consume| ProviderMessagesHandler["Provider Messages Handler (records provider_messages)"]

%% Provider webhooks: deduplicated by a content-derived Msg-Id, correlated with the inbox message,
%% retried with DefaultBackOff while the provider message ID is unrecorded, dropped after 6 deliveries
Provider[Provider Webhook] -->|"POST /webhooks/{project_id}/providers/{provider_id}"| ProvidersWebhookSubject["providers.webhooks.{project_id}"]
ProvidersWebhookSubject -->|Consume| ProviderWebhooksHandler["Provider Webhooks Handler"]
ProviderWebhooksHandler -->|"provider.* event (user)"| EventSubject
ProviderWebhooksHandler -->|"provider.* event (organization)"| OrgEventSubject
```
32 changes: 32 additions & 0 deletions internal/pubsub/consumer/bootstrap.go
Original file line number Diff line number Diff line change
Expand Up @@ -510,6 +510,38 @@ func Bootstrap(ctx graceful.Context, logger *zap.Logger, jet jetstream.JetStream
MaxDeliver: ProcessMaxDeliver,
})

bootstrap.EnsureStream(ctx, jetstream.StreamConfig{
Name: ns.Stream(StreamProviders),
Description: "Provider message mappings and webhook events",
Subjects: []string{ns.Subject("providers.messages.>"), ns.Subject("providers.webhooks.>")},
Discard: jetstream.DiscardOld,
MaxAge: 24 * time.Hour,
Replicas: 1,
// Webhook events are published with a content-derived Msg-Id so a
// provider retrying the same webhook is recorded once. The window
// covers AhaSend's full retry schedule (about 16 minutes) and the
// early retries of providers that retry for longer.
Duplicates: 1 * time.Hour,
})

bootstrap.EnsureConsumer(ctx, ns.Stream(StreamProviders), jetstream.ConsumerConfig{
Name: ns.Consumer(ConsumerProviderMessages),
Description: "Records the provider message IDs of sent inbox messages",
AckPolicy: jetstream.AckExplicitPolicy,
FilterSubject: ns.Subject("providers.messages.>"),
BackOff: DefaultBackOff,
MaxDeliver: ProcessMaxDeliver,
})

bootstrap.EnsureConsumer(ctx, ns.Stream(StreamProviders), jetstream.ConsumerConfig{
Name: ns.Consumer(ConsumerProviderWebhooks),
Description: "Correlates provider webhook events with inbox messages",
AckPolicy: jetstream.AckExplicitPolicy,
FilterSubject: ns.Subject("providers.webhooks.>"),
BackOff: DefaultBackOff,
MaxDeliver: ProviderWebhooksMaxDeliver,
})

return bootstrap.Error()
}

Expand Down
2 changes: 2 additions & 0 deletions internal/pubsub/consumer/bootstrap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,8 @@ func TestBootstrapCreatesAllConsumers(t *testing.T) {
{ns.Stream(StreamUserEvents), ns.Consumer(ConsumerUserEventsSchema), ns.Subject("users.events.schema.>")},
{ns.Stream(StreamJourneys), ns.Consumer(ConsumerJourneysAdvance), ns.Subject("journeys.advance.>")},
{ns.Stream(StreamLists), ns.Consumer(ConsumerListsRecompute), ns.Subject("lists.recompute.>")},
{ns.Stream(StreamProviders), ns.Consumer(ConsumerProviderMessages), ns.Subject("providers.messages.>")},
{ns.Stream(StreamProviders), ns.Consumer(ConsumerProviderWebhooks), ns.Subject("providers.webhooks.>")},
}

for _, tc := range consumers {
Expand Down
5 changes: 5 additions & 0 deletions internal/pubsub/consumer/consumer.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ const (
StreamOrganizationEvents = "organizations-events"
StreamActions = "actions"
StreamProjects = "projects"
StreamProviders = "providers"
)

// Subscription subjects for NATS core subscribers.
Expand Down Expand Up @@ -83,6 +84,8 @@ const (
ConsumerActionsSchema = "actions-schema"
ConsumerScheduledBackfill = "scheduled-backfill"
ConsumerProjectEventsProcess = "projects-events-process"
ConsumerProviderMessages = "providers-messages"
ConsumerProviderWebhooks = "providers-webhooks"
)

// Serve starts all JetStream consumers and registers their handlers.
Expand Down Expand Up @@ -130,6 +133,8 @@ func Serve(ctx graceful.Context, jet jetstream.JetStream, logger *zap.Logger, ns
router.HandleStream(ns.Stream(StreamOrganizationEvents), ns.Consumer(ConsumerOrganizationEventsSchema), OrganizationEventSchemasHandler(logger, usrs))
router.HandleStream(ns.Stream(StreamOrganizationEvents), ns.Consumer(ConsumerOrganizationEventsMatch), WithInProgress(MatchOrganizationEventsHandler(logger, usrs, jrny, pub, schemaCache)))
router.HandleStream(ns.Stream(StreamActions), ns.Consumer(ConsumerActionsSchema), ActionSchemasHandler(logger, usrs))
router.HandleStream(ns.Stream(StreamProviders), ns.Consumer(ConsumerProviderMessages), ProviderMessagesHandler(logger, usrs))
router.HandleStream(ns.Stream(StreamProviders), ns.Consumer(ConsumerProviderWebhooks), ProviderWebhooksHandler(logger, usrs, pub))
router.HandleCaller(ns.Subject(SubjectActionsExecute), ActionExecuteHandler(logger, actionRegistry, pub, schemaCache))
router.HandleCaller(ns.Subject(SubjectActionsValidate), ActionValidateHandler(logger, actionRegistry))

Expand Down
29 changes: 29 additions & 0 deletions internal/pubsub/consumer/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,32 @@ func IsRateLimited(err error) (*RateLimitedError, bool) {
}
return nil, false
}

// DelayedError asks the router to redeliver the message after Delay rather
// than immediately, for a condition that is expected to clear with time.
type DelayedError struct {
err error
Delay time.Duration
}

// RetryAfter wraps err as a DelayedError.
func RetryAfter(err error, delay time.Duration) error {
return &DelayedError{err: err, Delay: delay}
}

func (e *DelayedError) Error() string {
return e.err.Error()
}

func (e *DelayedError) Unwrap() error {
return e.err
}

// IsDelayed reports whether err is (or wraps) a DelayedError.
func IsDelayed(err error) (*DelayedError, bool) {
var e *DelayedError
if errors.As(err, &e) {
return e, true
}
return nil, false
}
Loading
Loading