Ports and adapters
A port is an interface of the domain: something the business needs from the outside world, such as keeping messages or calling an API. An adapter implements it, in the infra layer: a file, a database, an HTTP API. The handlers know only the port, so a new adapter changes nothing in the domain or the use cases.
Each port has a contract: the tests that every adapter must pass. The in-memory adapter of the tests passes the same contract as the real one, so a test that passes in memory tells the truth about production.
The files
The files of a port
src/backend/messages/
├── domain/port/message-repository/
│ ├── MessageRepository.ts the port, and its token
│ └── MessageRepository.contract.ts the tests that every adapter passes
├── infra/message-repository/
│ ├── file-message-repository.ts the adapter for production
│ ├── file-message-repository.test.ts runs the contract on it
│ ├── in-memory-message-repository.ts the adapter for the tests
│ └── in-memory-message-repository.test.ts runs the contract on it
├── di.ts binds the adapter for production
└── test.di.ts binds the adapter for the testsThe folder of a port is its name in kebab case, and its adapters use the same name in infra/: <adapter>-<port>.ts. Each adapter implements the interface that it imports from its port: the rules read that import, not the names of the classes.
The steps
- Write the interface and its token in
domain/port/<port>/<Port>.ts. Its methods take and return objects of the domain, not plain data. - Write the contract next to it, in
<Port>.contract.ts: a functiondescribe<Port>Contract(name, create). - Write each adapter in
infra/<port>/<adapter>-<port>.ts, and its test, which runs the contract. - Bind the adapter for production in
di.ts, and the one for the tests intest.di.ts. - Run
npm run check.
The port
src/backend/messages/domain/port/message-repository/MessageRepository.ts
import { Token } from "@ingenioz-it/caits/Token";
import type { Message } from "#context/domain/entity/Message.js";
/** The messages that the app keeps. */
export interface MessageRepository {
/** An id that no message has yet. */
nextId(): Promise<string>;
/** The messages, in the order they were added. */
list(): Promise<Message[]>;
find(id: string): Promise<Message | undefined>;
/** Adds the message, or replaces the message that has its id. */
save(message: Message): Promise<void>;
/** Removes the message that has this id. An id that no message has changes nothing. */
remove(id: string): Promise<void>;
}
export const MessageRepository = new Token<MessageRepository>();A handler asks for the type MessageRepository. CAITS finds the token of the same name, and gives the adapter that di.ts binds to it.
The contract
The contract takes the name of an adapter, and a function that creates a new one for each test. It pins down what an adapter could get wrong: here, removing an unknown id is not an error, and two saves at the same time both stay.
src/backend/messages/domain/port/message-repository/MessageRepository.contract.ts
import { describe, expect, test } from "@ingenioz-it/caits/testing/backend/infra";
import { Message } from "#context/domain/entity/Message.js";
import type { MessageRepository } from "./MessageRepository.js";
const contentOf = async (repository: MessageRepository) => (await repository.list()).map(({ id, text }) => [id, text]);
/** What every adapter of MessageRepository does. The test of each adapter runs it. */
export function describeMessageRepositoryContract(name: string, create: () => Promise<MessageRepository>) {
describe(`MessageRepository contract: ${name}`, () => {
test("finds a message by its id", async () => {
const repository = await create();
await repository.save(Message.create("1", "first"));
await repository.save(Message.create("2", "second"));
expect(await repository.find("2")).toStrictEqual(Message.create("2", "second"));
expect(await repository.find("3")).toBeUndefined();
});
test("saves that run at the same time keep all their messages, in the order of the calls", async () => {
const repository = await create();
const ids = Array.from({ length: 20 }, (_, index) => String(index));
await Promise.all(ids.map(id => repository.save(Message.create(id, `message ${id}`))));
expect(await contentOf(repository)).toEqual(ids.map(id => [id, `message ${id}`]));
});
// … the ids, the order, the replacement, the removals
});
}Test the adapters
Each adapter's test runs the contract, then adds tests for what only this adapter does. The file adapter gets a new temporary folder for each test, from useTempDirectories():
src/backend/messages/infra/message-repository/file-message-repository.test.ts
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, test, useTempDirectories } from "@ingenioz-it/caits/testing/backend/infra";
import { Message } from "#context/domain/entity/Message.js";
import { describeMessageRepositoryContract } from "#context/domain/port/message-repository/MessageRepository.contract.js";
import { FileMessageRepository } from "./file-message-repository.js";
const freshDirectory = useTempDirectories();
describeMessageRepositoryContract("File", async () => new FileMessageRepository(join(await freshDirectory(), "not-made-yet"), "messages.json"));
// … the tests of the file only: a damaged file, a change that fails, two repositories on the same filesrc/backend/messages/infra/message-repository/in-memory-message-repository.test.ts
describeMessageRepositoryContract("InMemory", async () => new InMemoryMessageRepository());
describe("InMemoryMessageRepository", () => {
test("gives the ids message-1, message-2…: the tests can tell them in advance", async () => {
const repository = new InMemoryMessageRepository();
expect([await repository.nextId(), await repository.nextId()]).toEqual(["message-1", "message-2"]);
});
});The bindings
src/backend/messages/di.ts
import { bind } from "@ingenioz-it/caits/di/Container";
import { DataDirectory } from "@ingenioz-it/caits/di/DataDirectory";
import { MessageRepository } from "./domain/port/message-repository/MessageRepository.js";
import { FileMessageRepository } from "./infra/message-repository/file-message-repository.js";
/** The dependencies of the context, in production. */
export default [
bind(MessageRepository).to(FileMessageRepository).with({ fileName: "messages.json" }),
bind(DataDirectory).toFactory(() => process.env.DATA_DIR || "tmp")
];src/backend/messages/test.di.ts
import { bind } from "@ingenioz-it/caits/di/Container";
import { MessageRepository } from "./domain/port/message-repository/MessageRepository.js";
import { InMemoryMessageRepository } from "./infra/message-repository/in-memory-message-repository.js";
/** The dependencies of the tests: they replace those of di.ts. */
export default [
bind(MessageRepository).to(InMemoryMessageRepository)
];- A binding is
bind(<token or class>), then.to(<class>),.toValue(<value>)or.toFactory(() => <value>)..with({ … })gives the parameters that have no token, such as a file name. DataDirectoryis the folder of the data files. The example binds it in thedi.tsofmessages. When a second context keeps files, move this binding tosrc/backend/shared/di.ts, which every backend context gets.- When a binding is missing, CAITS stops and names the class that needs it: see A dependency is missing.
To use a database, write a new adapter for the same port, run the contract on it, then bind it in di.ts. Once the contract passes, the app works with it.
An adapter that holds a resource
An adapter may hold a resource for as long as the server runs: a connection to a database, a child process, a socket. The container builds it once, when a use case first needs it. To release the resource when the server stops, the adapter implements Symbol.asyncDispose, the standard of JavaScript, or Symbol.dispose when the release doesn't wait:
src/backend/messages/infra/message-repository/database-message-repository.ts
export class DatabaseMessageRepository implements MessageRepository, AsyncDisposable {
// …
async [Symbol.asyncDispose](): Promise<void> {
await this.pool.end();
}
}On SIGTERM (docker stop) or SIGINT (Ctrl+C), the server of npm start and that of npm run dev:
- serve no new request: the connection of a request that ends closes, and a request that still comes on a connection that serves another gets a 503, which closes the connection;
- end the feeds: a feed has no end, and its client connects again once the server is back;
- stop the timer controllers: the signal of the turns that run aborts, as a work in the background stops with the server;
- let the turns, the requests and the reactions to the events that run end, until 10 seconds after the signal;
- then abort the signal of the reactions, give them and the turns one more second, and report those that still run;
- release what the containers built, the last built first: what each context built, then what
sharedbuilt.
Docker kills the server 10 seconds after docker stop by default, as long as the grace that the requests get. An app whose requests can last more than a few seconds sets stop_grace_period in its compose above these 11 seconds and the time to release what it built: else, Docker kills the server before it releases anything.
A second signal, a second or more after the first, ends the server at once. A signal that comes twice at once counts once: Ctrl+C reaches every process of the terminal, and npm passes it on to the server too.
When the code of the backend changes, npm run dev stops the backend the same way, but without waiting for the requests that run, then starts the new backend: two backends never run at once. The feeds end, and their clients connect again, to the new backend. The signal of the turns and of the reactions aborts at once, and they get one second. A request that comes meanwhile waits for the new backend. A backend that fails to start again, after a typo for one, is reported in the terminal: the server serves on, and the next change starts the backend again. When the first start fails, or when the port is in use, npm run dev ends, and tells why. A value given with .toValue(…) belongs to whoever made it: the container never releases it.
Test the bindings
The integration tests run the backend as in production: with the adapters of each di.ts, and no test.di.ts. They check a few flows again, on real files or a real database, in src/backend/<name>.integration.test.ts:
src/backend/backend.integration.test.ts
import { afterEach, assert, describe, expect, productionBackend, test, vi } from "@ingenioz-it/caits/testing/backend/integration";
test("keeps the messages in the file messages.json of the folder DATA_DIR, and a new backend finds them there", async () => {
directory = await mkdtemp(join(tmpdir(), "messages-"));
vi.stubEnv("DATA_DIR", join(directory, "data")); // the files go to a temporary folder
const first = productionBackend();
const added = await first.send(new AddMessageCommand("Hello"));
assert(added instanceof AddMessageOutput);
// …
const second = productionBackend(); // a new backend reads the same files
});send gives its answer as unknown: to read it, assert(… instanceof …) checks its class, and gives it its type.
The integration tests also kill the mutants of the bindings: when Stryker changes "messages.json" in di.ts, the test that reads that file fails. Like every test, an integration test reads one context at most.
A frontend adapter that calls the API
In the frontend, an adapter that calls the backend takes a Fetcher (@ingenioz-it/caits/di/Fetcher): a function with the parameters of fetch. CAITS gives one to each frontend context, so don't bind it. On the server, it is the fetch of the current request, in the same process; in the browser, the browser's fetch.
src/frontend/messages/infra/messages-gateway/http-messages-gateway.ts
import type { Fetcher } from "@ingenioz-it/caits/di/Fetcher";
import { failureOf } from "@ingenioz-it/caits/http/failureOf";
// … the other imports
export class HttpMessagesGateway implements MessagesGateway {
constructor(private readonly fetcher: Fetcher = (input, init) => fetch(input, init)) {}
// … list, add, edit and remove call send
private async send(path: string, init?: RequestInit): Promise<Response> {
const response = await this.fetcher(path, init);
if (!response.ok) throw await failureOf(response);
return response;
}
}- The frontend tests have no network: a request fails with
A test frontend has no network: replace the dependency that asked for …. Bind a fake of the port in thetest.di.tsof the frontend context. - The adapter's own test replaces the global
fetchwithvi.stubGlobal, and answers as the backend would. - Check the error itself,
rejects.toThrow("HTTP 503"), not only that there is one: a mutant ofif (!response.ok)would survive.
The rules of ports, adapters and contracts and of dependency injection check this page.