参照実装は、S06 と実装が3点異なります(保存の実装が2点、port の配置先が1点)。守るべき条件は同じで、状態と監査記録を同時に保存し、競合では何も書き込みません。
条件付き更新
examples/session-06-solution/src/adaptor/secondary/sqlite/examinationStartedStore.ts const storeAtomically = (event: ExaminationStarted) =>
database.transaction((transaction) => {
const current = findInTransaction(transaction, event.appointmentId);
if (current === undefined || current.kind !== "CheckedIn") {
return err({
kind: "AppointmentConflict",
appointmentId: event.appointmentId,
} as const);
} examples/final/src/adaptor/secondary/sqlite/store/appointmentEventStore.ts case "ExaminationStarted":
return tx.update(appointmentsTable)
.set(values)
.where(and(
eq(appointmentsTable.appointmentId, state.appointmentId),
eq(appointmentsTable.status, "CheckedIn"),
))
.run().changes; S06 は transaction の中で予約を再取得して分岐します。この形は、書き込みが直列に実行される SQLite に依存します。PostgreSQL の既定の分離レベルでは、2つの transaction がどちらも CheckedIn を取得し、どちらも書き込めます。参照実装は、status が CheckedIn の行だけを更新します。このように WHERE に条件を付けた更新を条件付き更新と呼び、更新した行が0件なら競合です。WHERE の条件で判定するため、ほかのデータベースでも成り立ちます。
競合の伝え方
examples/session-06-solution/src/adaptor/secondary/sqlite/examinationStartedStore.ts store: (event) =>
ResultAsync.fromSafePromise(
Promise.resolve().then(() => storeAtomically(event)),
).andThen((result) => result), examples/final/src/adaptor/secondary/sqlite/store/appointmentEventStore.ts if (changes !== 1) {
throw {
kind: "AppointmentConflict",
appointmentId: event.aggregateId,
} as const;
}
(cause): AppointmentStoreError => {
const conflict = AppointmentConflictSchema.safeParse(cause);
if (conflict.success) return conflict.data;
throw cause;
}, 参照実装の store は複数のイベントを1つの transaction で保存します。S06 のように err を返すと transaction が確定するため、途中のイベントで競合したときは throw でそれまでの書き込みを取り消し、fromPromise の2つ目の引数で Err に戻します。それ以外は投げ直すため、障害は Err になりません。S06「保存先の障害と例外の伝播」の、fromPromise ですべてを AppointmentConflict に変える誤った例と異なります。
port の配置先
examples/session-06-solution/src/useCase/dependencies.ts export type ExaminationStartedStore = Readonly<{
store: (event: ExaminationStarted) => ResultAsync<void, AppointmentConflict>;
}>; examples/final/src/domain/appointment/appointmentStores.ts type AppointmentStore<TEvent> = Readonly<{
store: (...events: readonly TEvent[]) => ResultAsync<void, AppointmentStoreError>;
}>;
export type AppointmentBookedStore = AppointmentStore<AppointmentBooked>;
export type AppointmentCheckedInStore = AppointmentStore<AppointmentCheckedIn>;
export type ExaminationStartedStore = AppointmentStore<ExaminationStarted>; S06 は port を useCase に配置しました。参照実装は domain に配置しました。どちらの場合も、port は外側の実装に依存しません。配置先が違っても、この依存の向きは変わりません。