Remote / An event-sourced domain behind Remote

The shortest whole path

The domain, declared as it would be for any server. Nothing here knows about Events.

ts
import { Schema } from 'effect'
import { Entity, Expr, Write } from 'foldkit-entity'
import { Guards } from 'foldkit-guard'
import { Mutation } from 'foldkit-remote'

const User = Schema.Struct({ id: Schema.String })

const ProductFields = Entity.define(
  'Product',
  Schema.Struct({
    id: Schema.String,
    ownerId: Schema.String,
    status: Schema.Literals(['draft', 'published']),
    stock: Schema.Number,
    reserved: Schema.Number,
    revision: Schema.Number,
  }),
)

const Shop = Guards.declare(
  'Shop',
  User,
  guard => ({
    isOwner: guard.row(ProductFields, user => Expr.eq(ProductFields.fields.ownerId, user.id)),
  }),
  { key: user => user.id, unguarded: 'allow' },
)

const Product = ProductFields.pipe(
  Guards.attach(Shop, { row: { Read: [Shop.isOwner], Update: [Shop.isOwner] } }),
  Entity.invariant('reservedWithinStock', ({ after }) => Expr.lte(after.reserved, after.stock), {
    message: 'Reserved stock cannot exceed the stock',
    path: ['reserved'],
  }),
)

const Policy = Shop.implement({})

const ReserveStock = Mutation.write(
  'ReserveStock',
  Write.update(
    Entity.input(
      Product,
      Schema.Struct({ id: Schema.String, revision: Schema.Number, quantity: Schema.Int }),
      { quantity: Entity.unmapped },
    ),
    {
      id: 'id',
      expect: 'revision',
      when: () => Expr.eq(Product.fields.status, 'published'),
      increment: { reserved: 'quantity' },
    },
  ),
)

The Domain model. Lower.write derives the Command, its Rejections, decide, evolve, the reply and the View's fold from ReserveStock. You write what it cannot know: the Events, who asks, and how a row comes to exist.

ts
import * as Domain from '@alchemy.run/domain'
import { Effect, Layer, Option } from 'effect'
import { RpcMiddleware } from 'effect/rpc'
import { Lower } from 'foldkit-remote-domain/lower'

class ProductListed extends Domain.Event('ProductListed', { row: Product.schema }) {}

class StockReserved extends Domain.Event('StockReserved', {
  quantity: Schema.Int,
  reservedAfter: Schema.Number,
  revisionAfter: Schema.Number,
}) {}

class CurrentUser extends Domain.RequestContext<CurrentUser>()(
  'Shop/CurrentUser',
  Schema.OptionFromNullOr(User),
) {}
class Session extends RpcMiddleware.Service<Session, { provides: CurrentUser }>()('Shop/Session') {}

const Reserved = Lower.write(ReserveStock, {
  policy: Policy,
  revision: 'revision',
  principal: CurrentUser,
  middleware: [Session],
  listed: ProductListed,
  event: StockReserved,
  record: (after, _before, input) =>
    new StockReserved({
      quantity: input.quantity,
      reservedAfter: after.reserved,
      revisionAfter: after.revision,
    }),
  apply: (row, event) => ({ ...row, reserved: event.reservedAfter, revision: event.revisionAfter }),
})

class ListProduct extends Domain.Command('ListProduct', {
  target: Schema.String,
  input: { row: Product.schema },
  events: [ProductListed],
}) {}

class ProductAggregate extends Domain.Aggregate('Product', {
  id: Schema.String,
  state: Reserved.state,
  initial: Reserved.initial,
  commands: [ListProduct, Reserved.command],
  decide: {
    ListProduct: (_, command) => [new ProductListed({ row: command.row })],
    ReserveStock: Reserved.decide,
  },
  evolve: Reserved.evolve,
  reply: { ReserveStock: Reserved.reply },
}) {}

class NotOwner extends Domain.Rejection('NotOwner') {}

class ProductRow extends Domain.View('ProductRow', {
  from: [ProductAggregate],
  key: ProductAggregate,
  middleware: [Session],
  rejects: [NotOwner],
  state: Reserved.view.state,
  initial: { id: '', ownerId: '', status: 'draft', stock: 0, reserved: 0, revision: 0 },
  evolve: Reserved.view.evolve,
}) {}

const ProductRowLive = ProductRow.toLayer(
  Effect.succeed(
    Effect.fn(function* (_request, row) {
      const user = yield* CurrentUser
      if (row !== null && !Option.exists(user, ({ id }) => id === row.ownerId))
        return yield* new NotOwner()
    }),
  ),
)

class ShopModel extends Domain.Model('Shop', {
  aggregates: [ProductAggregate],
  views: [ProductRow],
}) {}

class ShopApi extends Domain.Api('ShopApi', {
  model: ShopModel,
  commands: ['ListProduct', 'ReserveStock'],
  views: ['ProductRow'],
}) {}

The page. It is the page it would be over a SQL server, with the adapter as its RemoteClient.

ts
import { Optic } from 'effect'
import { Remote } from 'foldkit-remote'
import { DomainRemote } from 'foldkit-remote-domain'
import { ModelRef } from 'foldkit-surface'

const PageModel = Schema.Struct({ remote: Remote.Model })

const Data = Remote.make({
  model: ModelRef.fromOptic(Remote.Model, Optic.id<typeof PageModel.Type>().key('remote'), [
    'remote',
  ]),
  entities: [Product],
  mutations: [ReserveStock],
})

const client = DomainRemote.layer(ShopApi, {
  views: [Reserved.reads(ShopApi, 'ProductRow')],
  commands: [Reserved.binding(ShopApi)],
  principal: Effect.succeed(Option.some('ada')),
  denied: () => 'Unauthenticated',
})

What each call does

  • Everything in the first block declares. It is the block One domain declaration teaches, and a SQL writer reads the same values.
  • Lower.write derives, once, where the module loads. It throws there if the write does not fit one Aggregate (below). It does no I/O.
  • Reserved.decide is the write landed in memory over the Aggregate's one row, through the chain a server runs (RemoteServer.write over GuardServer.writer over RemoteServer.memoryWriter). The guard's Update rule, the expect, the when and the invariant are judged there. Each refusal leaves as the Rejection of the same tag (Conflict, Unmet, Invalid, Forbidden, Unauthenticated), and the binding turns it back into the mutation's Refusal for the page.
  • record and apply are yours because an Event is a stored contract. record says which outcome the Event carries; apply copies it onto a row and decides nothing.
  • ProductRowLive is the View's validate: who may read is the View's to say. The guard's Read rule is not lowered, so "only the owner" is stated here a second time, in Domain's terms.
  • DomainRemote.layer is the only call that performs I/O, and only once the Api's own client is provided (ShopApi.layerClientInProcess, or ShopApi.layerClientHttp(url) from a browser).