Skip to content
Spools
Documentation
On this page

Adapters

A Spool runs on services you choose. Each kind of service has a port, a small contract the framework asks for, and one or more adapters that provide it. You choose them in src/spool.server.ts:

ts
import { defineSpool } from '@swirls/spools'import { swirls } from '@swirls/spools/agents/swirls'import { clerk } from '@swirls/spools/auth/clerk'import { postgres } from '@swirls/spools/database/postgres'import { resend } from '@swirls/spools/email/resend'import { drive, s3Blobs } from '@swirls/spools/files/drive'import { aes } from '@swirls/spools/vault/aes'import crm from '../crm.config.json' with { type: 'json' }import extensions from './app/extensions'export default defineSpool({  crm,  extensions,  auth: clerk(),  database: postgres(),  files: drive({ blobs: s3Blobs() }),  email: resend(),  vault: aes(),  agents: swirls(),})

When the server starts it logs which adapters it uses and what each still needs ([env] Campaign email (Resend): off (set RESEND_API_KEY, EMAIL_FROM)). A variable an adapter can't do without stops a production server from starting.

What ships#

Port Import Needs
Auth @swirls/spools/auth/clerk CLERK_PUBLISHABLE_KEY, CLERK_SECRET_KEY, @clerk/tanstack-react-start
@swirls/spools/auth/better-auth BETTER_AUTH_SECRET, APP_URL, better-auth. See Signing in
@swirls/spools/auth/dev Nothing. Refuses to run in production
Database @swirls/spools/database/postgres DATABASE_URL, @effect/sql-pg. See Database
@swirls/spools/database/pglite Nothing but @effect/sql-pglite
@swirls/spools/database/prisma DATABASE_URL, @prisma/orm-postgres
Files @swirls/spools/files/drive A Blobs: localBlobs() or s3Blobs(). See Files
@swirls/spools/files/flashdrive FLASHDRIVE_API_KEY, FLASHDRIVE_DRIVE_ID
Email @swirls/spools/email/resend RESEND_API_KEY, EMAIL_FROM, resend
Vault @swirls/spools/vault/cipherstash The CS_* variables, @cipherstash/stack
@swirls/spools/vault/aes VAULT_KEY (openssl rand -base64 32)
Agents @swirls/spools/agents/swirls SWIRLS_PROJECT_ID. See Swirls
Rate limits @swirls/spools/rate-limits/memory Nothing. The default: counts per server instance
@swirls/spools/rate-limits/store The rate_limit_slots table. Counts the same on every instance

The packages named here are optional peer dependencies: install the ones your adapters use.

Changing one#

Change its line in src/spool.server.ts. Auth also has a browser half, listed in src/spool.ui.ts; the page uses the one whose id matches the server's and says so if there is none.

Three things to know before changing one on a Spool with data in it:

  • Auth. Records keep the user ids of whoever made and owns them, and those ids are the auth provider's. A new provider means new ids: owners and "created by" will not match until they are mapped over.
  • Vault. A vault can only open what it sealed. Change it and people reconnect their accounts on the Integrations page, and what your app sealed with sealText must be sealed again.

Your app's own secrets#

The vault also seals text your app stores (a gate code, a site's alarm number), through @swirls/spools/extensions:

ts
import { openText, sealText, vaultProblem } from '@swirls/spools/extensions'const owner = `propertyRecords:${record.id}:gateCode`const sealed = await sealText(gateCode, owner) // store `sealed`, never `gateCode`const back = await openText(sealed, owner)
  • Owner. Name where the value is kept (1 to 500 characters): it is sealed with the text, and opening it for any other owner is refused, so a value copied onto another row doesn't open there. An app's owners are kept apart from the framework's (sealed as app:<owner>): no app value opens as a teammate's tokens or a kept answer, nor the other way round.
  • Never in the clear. Without a vault sealText fails, and vaultProblem() says why. openText takes only what sealText sealed for that owner: text stored in the clear, or a value sealed for another owner, is refused.
  • Files. Each record remembers which store its folder is in, so it gets a new, empty folder in the new store. Nothing is copied.

Changing the database adapter between postgres and prisma is safe: they read and write the same tables.

Rate limits#

Your own endpoints count requests through the RateLimiter port (packages/spools/src/server/runtime/rate-limit.ts, and hitLimit, peekLimit and consumeLimit in @swirls/spools/extensions, Extending): hit counts one when a key is under its limit in a sliding window, wait says how long until it would be, record counts one regardless (a failed sign-in check), and consume counts an amount against a quota in a fixed window (a UTC day, a minute on the minute): all of it when it fits, nothing when it doesn't, in one step. rateLimits in defineSpool chooses where:

ts
import { storeRateLimits } from '@swirls/spools/rate-limits/store'export default defineSpool({  // ...  rateLimits: storeRateLimits(),})

storeRateLimits() adds the rate_limit_slots table: run bun run crm:gen and bun run db:push (or plan a migration) after choosing it.

  • memoryRateLimits() (the default) keeps counts in this server's memory. Each instance has its own, so N instances allow up to N times each limit, and a restart forgets. A bucket keeps at most 10,000 keys: past that the key idle longest is dropped, and its count with it. So memory stays bounded under a flood of new keys (addresses, made-up tokens), and a key dropped that way starts again from nothing: someone who can send from more than 10,000 addresses a minute can outrun the failed-check limit on one instance. Use storeRateLimits() where that matters.
  • storeRateLimits() keeps them in the Spool's database: each key has as many slots as its limit, each taken by an update that checks and changes in one step, so no instance can let more through than the limit. It is a write or two a request (the rateLimits policy: three seconds, never retried), and relies on the instances' clocks agreeing. A bucket holds at most rowsPerBucket slots inside its window (200,000 unless storeRateLimits({ rowsPerBucket }) says): past that a hit that needs a new slot is refused and a failure is not counted, so a flood of new keys can't grow the table without bound. Slots that have left the window are removed by a new slot's hit, at most once a second per bucket on each instance, so a burst of new keys doesn't queue behind the same delete. A quota (consume) is one row per key and window, changed by an update that names the count it read, and is not held to the cap.

Tests use RateLimiter.layerTest (@swirls/spools/testing). A limiter of your own (Redis, a KV store) is an adapter like any other.

Token checks#

An auth adapter may check tokens your own front end forwards (verifyToken in @swirls/spools/extensions): give it tokens, a layer of the Tokens port (verify(token, { authorizedParties }), a user id or null, never a failure). Its cost must be bounded whatever a stranger sends: check locally, never call out per token. See Building your own door.

Write your own#

An adapter is an object with an id, a label and a layer that provides the port. Everything you need is in @swirls/spools/adapter.

An email provider#

examples/postmark.ts:

ts
import { Effect, Layer } from 'effect'import { HttpClient, HttpClientRequest } from 'effect/http'import { config, Email, EmailError, type EmailAdapter } from '@swirls/spools/adapter'/** * Email through Postmark (https://postmarkapp.com). * *   POSTMARK_TOKEN   a server token *   EMAIL_FROM       who it comes from */export const postmark = (): EmailAdapter => ({  id: 'postmark',  label: 'Postmark',  // Shown in the boot report.  features: [{ name: 'Email (Postmark)', vars: ['POSTMARK_TOKEN', 'EMAIL_FROM'] }],  layer: Layer.effect(    Email,    Effect.gen(function* () {      const http = yield* HttpClient.HttpClient      return Email.of({        send: Effect.fn('Postmark.send')(function* (email) {          const token = yield* config.variable('POSTMARK_TOKEN')          const from = yield* config.variable('EMAIL_FROM')          if (!token || !from) {            return { id: null, sent: false }          }          const request = HttpClientRequest.post('https://api.postmarkapp.com/email').pipe(            HttpClientRequest.setHeader('x-postmark-server-token', token),            HttpClientRequest.bodyJsonUnsafe({              From: from,              To: email.to,              Subject: email.subject,              TextBody: email.text,              HtmlBody: email.html,            }),          )          const response = yield* http            .execute(request)            .pipe(              Effect.mapError(() => new EmailError({ message: 'Postmark could not be reached' })),            )          if (response.status >= 300) {            return yield* new EmailError({              message: `Postmark refused the email (${response.status})`,            })          }          return { id: null, sent: true }        }),        // Bounces and complaints, posted to /api/webhooks/email.        delivery: () => Effect.succeed('unconfigured' as const),      })    }),  ),})

If all you want is to send email another way, email.send in src/app/extensions.ts takes a plain async function and no Effect (Extending).

A database#

A store answers a small set of questions about tables: find, count, insert, update, remove, plus running a program as one transaction. Implement Backend and wrap it with makeStore, which adds the time limits and typed failures every store has. For anything that speaks Postgres SQL, sqlBackend does all of it and you supply two things: a function that runs a statement, and one that runs a program as a transaction. callbackTransaction makes the second from a driver whose own transaction takes a callback:

examples/bun-postgres.ts:

ts
import { SQL } from 'bun'import { Effect, Layer } from 'effect'import {  callbackTransaction,  DatabaseError,  makeStore,  placeholders,  sqlBackend,  Store,  type StoreAdapter,} from '@swirls/spools/adapter'/** Any Postgres, through Bun's own client. */export const bunPostgres = (url: string): StoreAdapter => ({  id: 'bun-postgres',  label: 'Postgres',  layer: Layer.effect(    Store,    Effect.gen(function* () {      const sql = new SQL(url)      yield* Effect.addFinalizer(() => Effect.promise(() => sql.close()))      // Bun's transaction takes a callback, and hands it the connection to use.      const transaction = callbackTransaction<SQL>((work) => sql.begin((tx) => work(tx)))      return Store.of(        makeStore(          sqlBackend((query) => {            const { text, params } = placeholders(query)            // Inside a transaction a statement is the transaction's; otherwise the pool's.            return Effect.flatMap(transaction.current, (tx) =>              Effect.tryPromise({                try: () => (tx ?? sql).unsafe(text, [...params]),                catch: (cause) => new DatabaseError({ cause }),              }),            )          }, transaction.transact),        ),      )    }),  ),})

Four promises are easy to break:

  • update checks and changes in one step, and says how many rows it changed. Sequences rely on it so that two servers never send the same email.
  • A transaction keeps everything or nothing. Every statement a program runs inside store.transaction must go to the transaction's connection, not the pool's, and a failure or an interruption must undo it. A record and its timeline rely on it.
  • Values come back as the table describes them: money and days as strings, moments as Date. Columns are read in terms of the table, never of the driver.
  • find with perGroup cuts each group down in the database. The query a backend is handed has perGroup: { by, limit } when the caller wants no more than limit rows for each value of the column by: the first of each group in the query's order, taken after the conditions and before limit and offset (Database). sqlBackend does it. A backend you write yourself has to. On Postgres, selectSql(table, query) writes the statement (a window function), rowsOf(table, rows) reads what your driver gives back for it, and findWith makes a find of the two, included records and all: the Prisma adapter reads its groups that way and everything else through the ORM. Never read every row and cut in JavaScript, because the rows left out are the reason it is asked for: a tag may be on thirty thousand contacts. A store whose backend gives back more rows for a group than the limit stops with an error that says so.

Under record scopes#

A Spool with record scopes puts every store behind a guard (store/scope.ts). makeStore does it, so a store you build with makeStore or sqlBackend has it, and your backend is only ever handed queries the guard has already narrowed. Never hand your backend, or anything it is made of (sqlBackend, findWith, rowsOf, a selectSql statement you run yourself), to code outside the adapter: the framework's own code may not import them, and a test fails if it does. What the guard relies on your backend for:

  • Conditions through relations, both ways and nested. some and none over a relation held on this table (one) and over one that points back (many), with a condition inside that may itself hold another. A links table is narrowed through its two relations to the records it joins, inside the condition on an object's links.
  • An order by a related record under a condition ({ related, where }): a row whose related record doesn't meet it sorts as a row with none (Database). Write the condition, or refuse the order.
  • perGroup after the conditions. The scope is in the conditions. A backend that numbers the rows of each group first and applies the conditions afterwards gives a person the gaps left by rows they can't reach, and one that ignores perGroup is stopped by the store.
  • countValues under the same conditions, which is where a count of links comes from.
  • lock is a real row lock, taken in the order of primary keys, and held until the transaction ends. The guard holds a record while it checks what points at it.
  • A transaction inside another is part of the outer one. The guard wraps a check and its write in one, inside whatever the caller had open.

A backend built on sqlBackend does all of it. Run the integration tests on yours (TEST_STORE): the scope tests run every one of these against the store they are given.

Tables of its own#

An adapter may keep tables in the Spool's database. Describe them with the table definitions the framework uses, list them in tables, and they are created and migrated with the rest (bun run crm:gen):

ts
import { table } from '@swirls/spools/adapter'const Receipt = table.defineTable({  model: 'Receipt',  name: 'receipts',  columns: {    id: table.id(),    createdAt: table.createdAt(),    total: table.float(),    note: table.optional(table.text()),  },  indexes: [['createdAt']],})

Its layer may ask for the Store. Don't make tables depend on the environment, or the schema would differ between your machine and production.

Check it#

In a clone of the repository, run the framework's own tests on your adapter. packages/spools/tests/unit/store.test.ts is what a store promises, and TEST_STORE in packages/spools/tests/support/preload.ts puts one under the whole server:

sh
TEST_STORE=postgres DATABASE_URL=postgresql://localhost/spools_test bun run test:integration

How it fits together#

The framework (packages/spools/src/crm, src/server, src/pages) never imports an adapter, a vendor's SDK or your app; lint refuses it. It asks for a port (yield* Store), and the one Effect runtime per process is built from the Spool's adapters (packages/spools/src/server/runtime/app.ts). Tests build the same runtime with stand-ins.