@omnitron-dev/titan-mailer 0.4.6 → 0.4.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +31 -157
  2. package/package.json +6 -6
package/README.md CHANGED
@@ -1,175 +1,49 @@
1
1
  # @omnitron-dev/titan-mailer
2
2
 
3
- Transactional email for Titan: lifecycle-managed Nodemailer SMTP pools, typed templates,
4
- a concrete email notification channel, and a durable outbox consumer using Titan Notifications.
3
+ Transactional email for Titan applications: managed SMTP pools, typed templates and optional durable delivery through Titan Notifications.
5
4
 
6
- ## Application module
5
+ ## Capabilities
7
6
 
8
- ```ts
9
- import { MailerModule, MailerService } from '@omnitron-dev/titan-mailer';
10
-
11
- const mailModule = MailerModule.forRoot({
12
- smtp: process.env.SMTP_URL!, // smtps://...:465 or smtp://...:587 with STARTTLS
13
- from: 'Research <noreply@example.org>',
14
- pool: { maxConnections: 3 },
15
- maxPending: 1000,
16
- });
17
- // Import mailModule in your Titan @Module; inject MailerService or MAILER.
18
- ```
19
-
20
- `forRootAsync({ imports, inject, useFactory })` resolves configuration through Nexus.
21
- `verifyOnStart: true` performs SMTP authentication during provider creation. Otherwise
22
- call `verify()` from a readiness probe; it sends no email. Titan disposal calls
23
- `onDestroy()`, which stops new submissions, drains accepted operations and closes the pool.
24
- SMTP timeouts and `maxPending` bound waiting work. The caller owns admission/retry policy.
7
+ - Bounded SMTP submission with lifecycle-managed connection pools.
8
+ - Typed, renderer-independent templates and explicit plaintext bodies.
9
+ - Notification workers that carry opaque delivery IDs through Redis.
10
+ - A PostgreSQL outbox adapter that uses the application's existing database executor.
25
11
 
26
- `send()` accepts **one envelope recipient**, explicit UTF-8 plaintext, optional HTML,
27
- memory-backed attachments and a stable Message-ID. It returns SMTP acceptance, not inbox
28
- delivery. Fan-out creates a separate durable delivery for each recipient, avoiding partial
29
- recipient success and accidental address disclosure. Arbitrary SMTP envelopes, filesystem
30
- paths, URL attachments, raw MIME and security overrides are not forwarded.
12
+ ## Quick start
31
13
 
32
- TLS certificate verification and TLS 1.2+ are mandatory. Cleartext is only available with
33
- `allowInsecureLocalhost: true` and a loopback host. SMTP URL query options are rejected.
34
- Public errors contain a classification, never credentials, server transcripts or bodies.
35
- `MailDeliveryError.retryable` distinguishes temporary failures from invalid/configuration/
36
- permanent failures. Nodemailer's hidden pool requeue is disabled: one queue owns retries.
37
-
38
- ## Templates
14
+ ```sh
15
+ pnpm add @omnitron-dev/titan-mailer
16
+ ```
39
17
 
40
18
  ```ts
41
- import { MailTemplates, escapeMailHtml } from '@omnitron-dev/titan-mailer';
42
- const templates = new MailTemplates<{ welcome: { name: string } }>({
43
- welcome: ({ name }) => ({
44
- subject: 'Welcome',
45
- text: `Hello, ${name}`,
46
- html: `<p>Hello, ${escapeMailHtml(name)}</p>`,
47
- }),
48
- });
49
- const rendered = templates.render('welcome', { name: 'Ada' });
19
+ import { MailerModule } from '@omnitron-dev/titan-mailer';
20
+
21
+ export function mail(smtp: string) {
22
+ return MailerModule.forRoot({
23
+ smtp,
24
+ from: 'Example <noreply@example.org>',
25
+ pool: { maxConnections: 3 },
26
+ maxPending: 1000,
27
+ });
28
+ }
50
29
  ```
51
30
 
52
- The registry is renderer-independent: Handlebars, MJML or a function may return the same
53
- `RenderedMail` contract. Render trusted templates with escaped data, then persist that
54
- result in the application's business transaction. Rendering never makes a network request.
55
- Plaintext is required; the module does not invent it by stripping arbitrary scientific HTML.
56
-
57
- ## Redis notification workers
58
-
59
- Use `NotificationsModule.forRoot({ redis })`, inject `NOTIFICATIONS_TRANSPORT`, and create
60
- `MailDeliveryWorker` from `@omnitron-dev/titan-mailer/notifications` with that bus,
61
- a `MailOutbox`, `MailerService`, and `{ channel, group }`. Start it in the supervised
62
- worker process and stop it **before** destroying its database, mailer and transport.
63
- The worker does not own injected dependencies; the Titan container disposes them.
64
-
65
- `MailOutbox` is the application's durable transaction boundary:
66
-
67
- - `pending(limit)` lists due opaque IDs, without message bodies or credentials.
68
- - `deliver(id, send)` locks/claims one due row. Completed or cancelled IDs are harmless.
69
- - SMTP acceptance and deletion/completion are recorded in the same database transaction.
70
- - A failed attempt retains the message with backoff, or records an explicit terminal failure.
71
- - Expired/replaced tokens cancel their queued mail. Database failure rejects; Redis is not ACKed.
72
-
73
- Only an ID travels through Redis. Polling reconciliation republishes due IDs after lost or
74
- trimmed wake-ups; it is bounded by `batchSize`, `intervalMs` and `maxConcurrent`. Concurrent
75
- consumers share a group. Worker health covers transport connectivity and failed reconciliation/
76
- delivery. Failed delivery policy and administrative re-drive remain in the durable store.
77
-
78
- ### PostgreSQL delivery store
79
-
80
- `@omnitron-dev/titan-mailer/postgres` exports `PostgresMailOutbox`, the database port,
81
- and `POSTGRES_MAIL_OUTBOX_SCHEMA`. Apply the schema in your application migration and
82
- pass an existing pool/transaction executor; the adapter never creates a second connection pool.
83
- An existing Titan database transaction can supply this executor. Applications with an older
84
- mail schema must migrate its columns explicitly before enabling the worker.
85
-
86
- The same entry exports `POSTGRES_MAIL_OUTBOX_REQUIREMENTS`, a plain-data readiness
87
- contract owned alongside the schema. Before starting the worker, pass an existing
88
- pool and this contract to `requirePostgresSchema` from
89
- `@omnitron-dev/titan-database/readiness` (or `@omnitron-dev/omnitron/readiness`).
90
- The check reads schema metadata; it neither migrates nor sends mail. It detects
91
- missing columns, changed retry defaults and lost delivery-ID uniqueness before
92
- delivery begins. The PostgreSQL entry and the root mailer keep their existing
93
- dependencies: the contract itself imports no database engine or driver.
94
-
95
- ```typescript
96
- const outbox = new PostgresMailOutbox(database, {
97
- messageIdDomain: 'example.org',
98
- maxAttempts: 6,
99
- retrySeconds: 30,
100
- maxRetrySeconds: 3600,
101
- });
102
- ```
31
+ Add the returned module to your Titan application and inject `MailerService` or `MAILER`. Supply an SMTP URL through application configuration. `verify()` checks the connection without sending mail; `verifyOnStart` enables that check during creation. Application shutdown drains accepted work and closes the pool.
103
32
 
104
- Insert the recipient, subject, `body` (plain text), optional HTML and expiry into `mail_outbox`
105
- inside the **same transaction as the business operation**. The application can add foreign
106
- keys to cancel queued messages when an account or one-time credential is deleted. Do not
107
- store SMTP credentials in the outbox.
33
+ `send()` accepts one envelope recipient, a plaintext body, optional HTML, memory-backed attachments and a stable Message-ID. It reports SMTP acceptance, not inbox delivery. TLS certificate verification is required; the explicit insecure option is restricted to loopback development servers.
108
34
 
109
- `status(id)` distinguishes queued, retrying, accepted, failed and expired. `failed(limit)`
110
- and `health()` return bounded operational information without addresses or message content.
111
- `health().oldestDueSeconds` identifies an overdue queue even when Redis reports connected.
112
- After repairing a terminal failure, `retry(id)` resets its retry budget, retains the stable
113
- Message-ID and cumulative attempt count, and refuses completed or expired messages.
114
- `pruneReceipts(days)` removes only old receipts with no remaining queued payload.
115
- No failed payload is silently dropped. Keep database backups and monitor failed/overdue mail.
35
+ ## Durable delivery
116
36
 
117
- The delivery contract is **at least once**, assuming durable storage, eventual recovery and retry of retained failures. An SMTP server may accept a message before a worker
118
- loses its database transaction. A stable Message-ID aids correlation but cannot make SMTP
119
- and SQL atomic, and mail clients need not deduplicate it. Do not call this exactly once.
120
- Use a dedicated Redis database/ACL, bounded streams and retention for durable delivery events.
37
+ Use `MailDeliveryWorker` from `@omnitron-dev/titan-mailer/notifications` with a notification transport, mailer and durable `MailOutbox`. Stop the worker before disposing its injected dependencies. Persist rendered messages in the application's business transaction; send only opaque IDs through Redis.
121
38
 
122
- `MailerEmailChannel` adapts the service to the standard notification channel registry.
123
- It shares, and does not close, its injected MailerService. Critical security messages use
124
- the durable outbox path, not optional marketing notification preferences.
39
+ `@omnitron-dev/titan-mailer/postgres` exports `PostgresMailOutbox`, schema SQL and schema readiness requirements. Apply the schema through your migration workflow and pass an existing database executor. The adapter does not create a second pool or migrate on startup.
125
40
 
126
- ## Delivery diagnostics
41
+ An SMTP server and a database cannot share one atomic transaction. A crash after SMTP acceptance can lead to a repeated delivery. Stable Message-IDs support reconciliation but do not guarantee recipient-side deduplication. The application owns retries, cancellation and terminal-failure handling.
127
42
 
128
- Use the `PostgresMailOutbox` option `onDelivery` to forward committed outcomes to
129
- Titan Logger and therefore Omnitron's Console and CLI:
43
+ ## Documentation
130
44
 
131
- ```ts
132
- const outbox = new PostgresMailOutbox(database, {
133
- messageIdDomain: 'example.org',
134
- onDelivery: (event) => {
135
- const level = event.state === 'failed' ? 'error'
136
- : event.state === 'accepted' ? 'info' : 'warn';
137
- logger[level](
138
- { event: 'mail.delivery', ...event },
139
- `mail.delivery ${event.state} delivery=${event.deliveryId}`,
140
- );
141
- },
142
- });
143
- ```
45
+ [Public API](src/index.ts) · [Package exports](package.json) · [Notifications](../titan-notifications/README.md) · [Omni](../../README.md)
46
+
47
+ ## License
144
48
 
145
- `MailDeliveryEvent` contains `deliveryId`, `state`, `attempts` in the current retry
146
- cycle and `errorKind`. It has no recipient, body, credential or server response.
147
- The callback runs only after the transaction commits. Async callbacks are supported;
148
- a throwing or rejected observer cannot change a committed outcome or trigger another
149
- send. These are best-effort operational logs, not a second durable event queue:
150
- `status(id)` and the SQL receipt remain authoritative if the process exits before logging.
151
-
152
- `MailDeliveryWorker.onError(stage, code)` reports `outbox_read_failed`,
153
- `notification_publish_failed`, `outbox_delivery_failed` or `notification_ack_failed`.
154
- It never passes the raw exception. A recorded SMTP rejection belongs to the outbox
155
- outcome; it is not an uncommitted worker error. Report queue counts and
156
- `oldestDueSeconds` in an application's standard health checks as well as transport
157
- connectivity; a running process or connected Redis alone is insufficient.
158
-
159
- For authentication mail, record the request's `queued` or `skipped` decision in the
160
- application **after commit**, with its opaque delivery ID. Keep the public recovery
161
- response uniform for missing, disabled and existing accounts. Use a keyed, domain-separated
162
- subject reference for operator correlation, not a raw email or unkeyed email hash.
163
- An unknown account produces no mail; `queued` means SQL committed; `accepted` means
164
- SMTP accepted the message; none of these establishes arrival in the recipient's inbox.
165
-
166
- ## Verification
167
-
168
- `pnpm test` uses a real local SMTP server and independent MIME parser, tests STARTTLS
169
- refusal, reply/header injection, mixed content, rejected recipients, queue capacity and
170
- actual Titan DI disposal. Worker contract tests cover lost wake-ups, failed commits, poison
171
- envelopes and draining. Consumer integration tests also exercise the complete PostgreSQL → Redis → SMTP path
172
- with competing workers and checks the resulting Mailpit messages.
173
-
174
- Design references: [NestJS Mailer](https://nest-modules.github.io/mailer/docs/configuration/),
175
- [Nodemailer SMTP](https://nodemailer.com/smtp), [pool lifecycle](https://nodemailer.com/smtp/pooled).
49
+ [MIT](../../LICENSE).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@omnitron-dev/titan-mailer",
3
- "version": "0.4.6",
3
+ "version": "0.4.9",
4
4
  "description": "Lifecycle-managed transactional email for Titan with Nodemailer and durable notification workers",
5
5
  "author": "LuxQuant",
6
6
  "license": "MIT",
@@ -31,8 +31,8 @@
31
31
  "reflect-metadata": "^0.2.2"
32
32
  },
33
33
  "peerDependencies": {
34
- "@omnitron-dev/titan": "0.4.6",
35
- "@omnitron-dev/titan-notifications": "0.4.6"
34
+ "@omnitron-dev/titan": "0.4.9",
35
+ "@omnitron-dev/titan-notifications": "0.4.9"
36
36
  },
37
37
  "peerDependenciesMeta": {
38
38
  "@omnitron-dev/titan-notifications": {
@@ -40,8 +40,8 @@
40
40
  }
41
41
  },
42
42
  "devDependencies": {
43
- "@omnitron-dev/titan": "0.4.6",
44
- "@omnitron-dev/titan-notifications": "0.4.6",
43
+ "@omnitron-dev/titan": "0.4.9",
44
+ "@omnitron-dev/titan-notifications": "0.4.9",
45
45
  "@types/mailparser": "^3.9.0",
46
46
  "@types/smtp-server": "^3.5.13",
47
47
  "mailparser": "^3.14.1",
@@ -55,7 +55,7 @@
55
55
  "url": "git+https://github.com/omnitron-dev/omni.git",
56
56
  "directory": "packages/titan-mailer"
57
57
  },
58
- "gitHead": "3a912fa181e97ddd238a28bb355cd7445c1b7364",
58
+ "gitHead": "c6005ff1d0cde480cfa6b0bc346c9b53b2e638bf",
59
59
  "scripts": {
60
60
  "build": "../../scripts/build-package.sh -p ./tsconfig.json",
61
61
  "test": "vitest run",