Ecosystem
Writing your own implementation
The seam contracts, which methods are required, the shipped fakes to copy from, the starter templates, and the versioning rules downstream packages follow.
Every seam in the library is a small interface, and every official package is a separate implementation of one or more of them. If no official implementation fits — a different database, a provider nobody has wrapped, a queue your platform already runs — you write one against the same interface and the rest of the library does not notice.
When to write one
Write an implementation when you need a seam the official packages do not cover: a backend over DynamoDB or MongoDB, an adapter for Postmark or a push provider, a renderer for a template engine of your own, an attachment manager for Azure Blob or GCS, or a queue service over SQS or BullMQ. Do not write one to change how an official package behaves in one place; subclass it and override the method instead.
Start with the backend when you write several. Every other seam reads and writes through it, so a working backend is what lets you test the rest end to end.
The contract
Each seam is an abstract base class under vintasend/services/, and all but the renderer have an AsyncIO twin in the sibling asyncio_base.py:
| Seam | Sync | AsyncIO |
|---|---|---|
| Backend | notification_backends/base.py BaseNotificationBackend | AsyncIOBaseNotificationBackend |
| Adapter | notification_adapters/base.py BaseNotificationAdapter | AsyncIOBaseNotificationAdapter |
| Background adapter | notification_adapters/async_base.py BackgroundNotificationAdapter | asyncio_background_base.py AsyncIOBackgroundNotificationAdapter |
| Renderer | notification_template_renderers/base.py BaseNotificationTemplateRenderer | none: rendering has nothing to await |
| Attachment manager | attachment_managers/base.py BaseAttachmentManager | AsyncIOBaseAttachmentManager |
| Queue service | notification_queue_services/base.py BaseNotificationQueueService | AsyncIOBaseNotificationQueueService |
| Replication queue service | notification_queue_services/replication_base.py BaseNotificationReplicationQueueService | AsyncIOBaseNotificationReplicationQueueService |
| Git commit SHA provider | git_commit_sha_providers/base.py BaseGitCommitShaProvider | AsyncIOBaseGitCommitShaProvider |
@abstractmethod is enforced at instantiation: a subclass missing one raises TypeError the moment it is constructed, which is why every official package’s test suite catches a seam change at import time. Adapters are generic over the backend and renderer types, BaseNotificationAdapter(Generic[B, T], ABC), and accept either live instances or dotted import strings for both. Exceptions you raise should derive from NotificationError in vintasend/exceptions.py; a send failure that subclasses NotificationSendError is what makes the service mark the notification FAILED.
Each seam is a TypeScript type under src/services/, exported from the vintasend package. Some are interfaces you implement; some are abstract classes you extend:
| Seam | Type | Kind |
|---|---|---|
| Backend | BaseNotificationBackend<Config> | interface |
| Adapter | BaseNotificationAdapter<TemplateRenderer, Config> | abstract class |
| Renderer | BaseEmailTemplateRenderer<Config> / BaseTextNotificationTemplateRenderer<Config> | abstract class |
| Attachment manager | BaseAttachmentManager | abstract class |
| Queue service | BaseNotificationQueueService<Config> | interface |
| Replication queue service | BaseNotificationReplicationQueueService<Config> | interface |
| Git commit SHA provider | BaseGitCommitShaProvider | interface |
| Logger | BaseLogger | interface |
There is one service, and it is async throughout, so every seam method that does I/O returns a Promise. The compiler enforces the interfaces: a class missing a required member fails to type-check, and an optional member (marked ?) can be left out and the feature it gates stays off. Every implementation is generic over your Config (the BaseNotificationTypeConfig that names your notification id type and context generators), so the service can type notifications end to end.
What each seam must implement
The checklists below name the methods with no default. Read the base class for the signatures; names are what matter here, since implementations override by name.
Backend
Required on both BaseNotificationBackend and AsyncIOBaseNotificationBackend (the async class has the same names as coroutines):
get_all_pending_notifications get_pending_notifications
get_all_future_notifications get_future_notifications
get_all_future_notifications_from_user get_future_notifications_from_user
persist_notification persist_one_off_notification
persist_notification_update
mark_pending_as_sent mark_pending_as_failed
mark_sent_as_read mark_sent_as_read_bulk
cancel_notification requeue_notification
get_notification
filter_all_in_app_unread_notifications filter_in_app_unread_notifications
filter_all_in_app_notifications filter_in_app_notifications
filter_notifications
get_user_email_from_notification
store_context_used store_git_commit_sha
store_attachment_file_record get_attachment_file_record
find_attachment_file_by_checksum delete_attachment_file
get_orphaned_attachment_files get_attachments
delete_notification_attachmentrequeue_notification(notification_id, send_after=UNSET) is required since 3.7.0. It moves only a FAILED or CANCELLED notification back to PENDING_SEND, checking the status and writing in one step (a conditional UPDATE ... WHERE id = ? AND status IN (...) on SQL). It raises NotificationNotFoundError for an unknown id and NotificationRequeueError for any other status, clears sent_at, applies send_after only when it is passed (None included), and returns the full notification with its attachments. persist_notification_update must accept a FAILED or CANCELLED notification as well as a pending one, because the default repin_notification writes through it.
Since 3.8.0 a backend can also offer the conditional moves. All of it is optional, and a backend written for 3.7.0 keeps working: the service passes an option only to a backend that reports it in get_action_capabilities(), and refuses it otherwise.
requeue_notificationmay accept two keyword-only arguments:template_version, written in the sameUPDATE, andexpected_version, added to itsWHERE. Reportrequeue.templateVersionandrequeue.expectedVersion.repin_notification(notification_id, template_version, *, expected_version=None)has a default that reads, checks the status and writes throughpersist_notification_update. Override it to write in one conditionalUPDATE(statuses in theWHERE, plus the version when given, plus “not already on this version”), raisingNotificationRepinErrorfor a delivered notification andNotificationVersionChangedErrorfor a changed one, and reportrepin.expectedVersion.filter_notification_versions(filter, page, page_size)returnsNotificationVersion(id, version)entries ordered by id, reading the id and version columns and nothing else. Reportversions.filter.- The version token is an opaque string that must change on every write to the row, by anyone.
vintasend-djangoandvintasend-sqlalchemykeep anotification_versionUUIDv7 column (vintasend.utils.uuid_utils.uuid7) and set it in every write; a timestamp works too if two writes inside its precision are acceptable. When a conditionalUPDATEmatches nothing, read the row once to say why: not found, changed, or the wrong status. - Fill
notification_versionwith the row’s token on everyNotification/OneOffNotificationyou return. apply_replication_snapshot_if_newermust storesnapshot.notification_versionas the row’s token instead of issuing one, and issue one only when the snapshot carries none. That is how a replica comes to hand out tokens the primary accepts. A backend that reportsversions.filterand serves as a replica must do this, or reportwrites.notificationVersionbelow; otherwise its tokens are its own and the service reportsversions.filterasFalsewhen it is named.- Reporting
writes.notificationVersionmeans every write that changes a single notification (persist_notification,persist_one_off_notification,persist_notification_update, the threemark_*methods,cancel_notification,requeue_notification,repin_notification,store_context_used,store_git_commit_sha,store_template_version,delete_notification_attachment) accepts a keyword-onlynotification_version: str | None = None, andmark_sent_as_read_bulka keyword-onlynotification_versions: Mapping[id, str] | None = None. A given token is the one the row must hold after the write, instead of a fresh one. The keyword is not in the abstract signatures, so add it to your overrides. The service itself uses it for one write only, the stamp: after replaying a write on a replica without a token and checking that the row matches the primary’s, it callspersist_notification_update(id, {}, notification_version=<primary token>). Sopersist_notification_updatemust accept an emptyupdate_datawith anotification_versionin any status,SENTandREADincluded, as a token-only write that changes nothing else. The service never passes the keyword to the primary, and does not pass the bulk mapping, which the contract still accepts. apply_replication_snapshot_if_newerreturnsApplyResult(applied=False, superseded=True)when your row is newer than the snapshot. The service then skips its fallback, since the row already reflects a later write.- The presence filters
has_send_afterandhas_requested_template_version(IS NOT NULL/IS NULL) are reported byfields.*andnegation.*keys that default toFalse, so report themTruewhen you evaluate them. Twelve methods have working defaults you override only when the database can do better:repin_notification,filter_notification_versionsandget_action_capabilities(see above),count_in_app_notificationsandcount_in_app_unread_notifications(they iterate the filter methods),get_all_notifications,count_notifications,get_filter_capabilities(reports everything supported andpagination.oneIndexed: True; a backend that pages from 0 must override it),get_backend_identifier,apply_replication_snapshot_if_newer,store_template_versionandinject_attachment_manager. Pagination is 1-indexed:page=1is the first page.
Required members of BaseNotificationBackend<Config>:
getAllPendingNotifications getPendingNotifications
getAllFutureNotifications getFutureNotifications
getAllFutureNotificationsFromUser getFutureNotificationsFromUser
persistNotification bulkPersistNotifications
persistNotificationUpdate
getAllNotifications getNotifications
markAsSent markAsFailed
markAsRead cancelNotification
getNotification requeueNotification
filterAllInAppUnreadNotifications filterInAppUnreadNotifications
filterNotifications
getUserEmailFromNotification storeAdapterAndContextUsed
persistOneOffNotification persistOneOffNotificationUpdate
getOneOffNotification getAllOneOffNotifications
getOneOffNotificationsThe optional members each gate a feature: getFilterCapabilities (omit it and every filter is assumed supported; pagination is assumed 0-indexed, so page=0 is the first page), getBackendIdentifier and applyReplicationSnapshotIfNewer (multi-backend replication), storeTemplateVersion (template version pinning), injectLogger, and the attachment set storeAttachmentFileRecord, getAttachmentFileRecord, findAttachmentFileByChecksum, deleteAttachmentFile, getOrphanedAttachmentFiles, getAttachments and deleteNotificationAttachment. supportsAttachments(backend) and supportsTemplateVersions(backend) are the type guards the service uses to detect them.
The conditional moves are optional too: repinNotification(id, templateVersion, { expectedVersion? }), filterNotificationVersions(filter, page, pageSize) and getActionCapabilities(), plus templateVersion and expectedVersion in RequeueNotificationOptions, which a backend receives only when it reports them. A backend written for 1.0.0-alpha10 needs no change. vintasend-prisma uses updatedAt as the version token and vintasend-medplum uses meta.versionId.
Adapter
One abstract method on BaseNotificationAdapter and AsyncIOBaseNotificationAdapter: send(notification, context, headers=None). Render through self.template_renderer, deliver, and raise a NotificationSendError subclass on failure. A BackgroundNotificationAdapter inherits that send and adds one more abstract method, delayed_send(notification_id), which the worker calls after reloading the notification. supports_attachments and prepare_attachments have defaults; override the first to return True and the second to map StoredAttachment rows onto your provider’s payload.
BaseNotificationAdapter has no abstract members, but its default send only rejects when no backend was injected, so an adapter is a class that sets key, passes its notificationType and enqueueNotifications to the constructor, and overrides send(notification, context). Return what the renderer produced (an EmailTemplate or TextNotificationTemplate) so the service can record templateVersion; returning nothing is also valid. injectBackend and injectLogger are called by the service and need no override. Use isOneOffNotification(notification) to branch on recipients that have no user record.
Template renderer
Two abstract methods on BaseNotificationTemplateRenderer: render(notification, context) and render_from_template_content(notification, template_content, context). Subclass BaseTemplatedEmailRenderer (returns TemplatedEmail with subject, body and preheader) or BaseTemplatedSMSRenderer (returns TemplatedSMS with body). get_latest_template_version has a default returning None; only a renderer over a versioned store overrides it.
Extend BaseEmailTemplateRenderer<Config> or BaseTextNotificationTemplateRenderer<Config> and override render(notification, context) and renderFromTemplateContent(notification, templateContent, context); the base implementations throw. getLatestTemplateVersion is optional with a default of null, and injectLogger is inherited.
Attachment manager
Three methods with no default: upload_fileuploadFile, reconstruct_attachment_filereconstructAttachmentFile and delete_file_by_identifiersdeleteFileByIdentifiers. upload_file stores the bytes and returns an AttachmentFileRecord whose storage_identifiers carries a non-empty id plus whatever the manager needs to find the object again; the backend persists that map opaquely. reconstruct_attachment_file builds an AttachmentFile handle (read, stream, url, delete) from those identifiers without doing I/O, which is why it stays a plain method even on the AsyncIO class. detect_content_typedetectContentType, calculate_checksumcalculateChecksum and file_to_bytesfileToBuffer are provided.
Queue services
A queue service is one method: enqueue_notification(notification_id)enqueueNotification(notificationId). The payload is the id alone; the worker reloads the notification from the backend and delivers it through the adapter. A replication queue service is also one method, enqueue_replication(notification_id, backend_identifier)enqueueReplication(notificationId, backendIdentifier), and is only consulted when replication mode is queued; unset, the service falls back to inline replication.
Git commit SHA provider
One method, get_current_git_commit_shagetCurrentGitCommitSha, returning a 40-character hex SHA or Nonenull when it cannot be determined.
It may return the value synchronously or as a Promise; the service awaits either.
Logger
BaseLogger is info, warn and error, each receiving a LogMessage rather than a string. Print it with renderLogMessage(message), or read message.strings and message.values to emit structured fields. The typed interpolations (logId, logCount, logLabel, logTimestamp, logError) are what keep recipients, rendered content and context out of log lines; a logger should not undo that.
The shipped fakes
Every seam has a working fake under its stubs/ folder, and they are the reference implementations downstream authors read. They are complete rather than minimal: the test suite runs against them, and fake_backend.py is the second-largest file in the package.
| Seam | Fake (sync / AsyncIO) | Module |
|---|---|---|
| Backend | FakeFileBackend / FakeAsyncIOFileBackend | notification_backends/stubs/fake_backend.py |
| Adapter | FakeEmailAdapter / FakeAsyncIOEmailAdapter, plus FakeAsyncEmailAdapter and FakeAsyncIOBackgroundEmailAdapter for the background split | notification_adapters/stubs/fake_adapter.py |
| In-app adapter | FakeInAppAdapter / FakeAsyncIOInAppAdapter | notification_adapters/stubs/fake_in_app_adapter.py |
| Renderer | FakeTemplateRenderer | notification_template_renderers/stubs/fake_templated_email_renderer.py |
| Attachment manager | FakeAttachmentManager / FakeAsyncIOAttachmentManager | attachment_managers/stubs/fake_attachment_manager.py |
| Queue service | FakeQueueService / FakeAsyncIOQueueService | notification_queue_services/stubs/fake_queue_service.py |
| Replication queue service | FakeReplicationQueueService / FakeAsyncIOReplicationQueueService | notification_queue_services/stubs/fake_replication_queue_service.py |
| Git commit SHA provider | FakeGitCommitShaProvider / FakeAsyncIOGitCommitShaProvider | git_commit_sha_providers/stubs/fake_git_commit_sha_provider.py |
FakeFileBackend serializes to a JSON file, so it is also a usable backend for a test suite of your own: wire your real adapter against it and no database is needed.
The TypeScript package ships one real, minimal implementation rather than a set of fakes: LocalFileAttachmentManager, under the vintasend/local-file-attachment-manager entry point, writes attachments to a directory and is the reference for the attachment seam. The library’s own tests define their doubles inline (TestBackendWithAttachments in src/services/notification-backends/__tests__/base-notification-backend.test.ts, MockTemplateRenderer and TestNotificationAdapter in src/services/__tests__/notification-adapters/base-notification-adapter.test.ts), and the implementation template below carries a complete typed stub per seam. For a worked example of each seam, read the official package the template README names: vintasend-prisma for a backend, vintasend-nodemailer and vintasend-sendgrid for adapters, vintasend-pug for a renderer, vintasend-aws-s3-attachments for an attachment manager, vintasend-winston for a logger.
The starter template
templates/vintasend-implementation-template/ in the core repository is a Poetry package with one TODO stub per seam (backend.py, adapter.py, template_renderer.py, queue_service.py, attachment_manager.py, replication_queue_service.py) and a scaffold test for each that asserts the stub subclasses the right ABC with no leftover abstract methods. Its README carries the per-seam checklist, and a test in the core repository parses that checklist against the live ABCs so it cannot go stale.
Clone it with the script:
python templates/vintasend-implementation-template/scripts/clone.py /path/to/vintasend-your-integration \
--package-name vintasend-your-integration \
--description "Your integration for VintaSend"The script copies the directory, renames the distribution and the import package everywhere they appear, and sets the PyPI description. It does not rename the ImplementationTemplate* classes, which you do as you implement each seam, and it does not touch the vintasend dependency range. Then:
cd /path/to/vintasend-your-integration
poetry install
poetry run pytest
poetry run mypyImplement in the order the README gives — backend, renderer, adapter, then the optional seams — and test the real implementation the way the core suite tests its fakes: against the seam, with no mocking of it.
src/implementations/vintasend-implementation-template/ in the vintasend-ts repository is a package with one typed stub per component: backend.ts (NotificationBackend and NotificationBackendFactory), adapter.ts, template-renderer.ts, logger.ts and attachment-manager.ts (TemplateAttachmentManager and TemplateAttachmentFile), each with a matching test. Generate a package from it, keeping only the components you need:
npm run implementation:generate -- \
--dir=vintasend-aws-ses \
--package=@acme/vintasend-aws-ses \
--components=backend,adapter,template-renderer--dir is the new directory under src/implementations, --package the package.json name, --components a comma-separated list of backend, adapter, template-renderer, logger and attachment-manager; --repo sets the GitHub repository and --force overwrites an existing directory. Copying the directory by hand and deleting the unused files works too. Then rename the classes, implement them, export them from src/index.ts, and:
npm install
npm run build
npm testVersioning rules to know
The seams are a public contract, and the core repositories version them deliberately.
- A new abstract method ships as a minor release, with a mandatory
### Backwards compatibilitysection in the coreRELEASE_NOTES.mdnaming every added method and both classes it landed on (the project’s own precedent: 1.2.0 added three abstract methods this way). Strict semver would call it major; the project has chosen the release note as the warning instead, so read that section on every minor upgrade before bumping your pin. - A new method with a working default is additive. Existing implementations keep working; override it when your store can do better.
- Renaming, reordering or removing a seam method is a major release. Widening a signature with a new optional keyword argument is not.
- The official packages pin an exact
vintasendversion. When you adopt a new abstract method, release your package with its constraint widened to the core version that introduced it; the core release always lands first, since a package cannot pin a version that does not exist.
- A new required interface member is a breaking change for implementers, because a class that lacks it stops compiling. The library adds features as optional members instead —
storeTemplateVersion,getFilterCapabilities, the attachment set — so an existing backend keeps compiling and simply does not gain the feature until it implements the member. - A new member on an abstract class with a working default is additive, as
getLatestTemplateVersionwas for renderers. - Declare
vintasendas a peer dependency and keep it on the same release line as the implementation packages you ship with. When you adopt a newly added member, widen the peer range to the version that introduced it.
Found a mistake? Edit this page on GitHub.