diff --git a/.reference/server/package.json b/.reference/server/package.json new file mode 100644 index 0000000000..8df16b6766 --- /dev/null +++ b/.reference/server/package.json @@ -0,0 +1,27 @@ +{ + "name": "@effect-http-ws-cli/server", + "version": "0.1.0", + "private": true, + "type": "module", + "exports": { + "./client": "./src/client.ts", + "./contracts": "./src/contracts.ts" + }, + "scripts": { + "dev": "node src/bin.ts", + "start": "node src/bin.ts", + "test": "vitest run", + "lint": "tsc --noEmit" + }, + "dependencies": { + "@effect/platform-node": "catalog:", + "@effect/sql-sqlite-node": "catalog:", + "effect": "catalog:" + }, + "devDependencies": { + "@effect/vitest": "catalog:", + "@types/node": "^24.10.0", + "typescript": "catalog:", + "vitest": "catalog:" + } +} diff --git a/.reference/server/src/Migrations/001_TodoSchema.ts b/.reference/server/src/Migrations/001_TodoSchema.ts new file mode 100644 index 0000000000..aa6c1418e7 --- /dev/null +++ b/.reference/server/src/Migrations/001_TodoSchema.ts @@ -0,0 +1,32 @@ +import * as Effect from "effect/Effect" +import * as SqlClient from "effect/unstable/sql/SqlClient" + +export default Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient + + yield* sql` + CREATE TABLE IF NOT EXISTS todos ( + id TEXT PRIMARY KEY NOT NULL, + title TEXT NOT NULL, + completed INTEGER NOT NULL, + archived INTEGER NOT NULL, + revision INTEGER NOT NULL, + updated_at TEXT NOT NULL + ) + ` + + yield* sql` + CREATE TABLE IF NOT EXISTS todo_events ( + event_offset INTEGER PRIMARY KEY AUTOINCREMENT, + at TEXT NOT NULL, + todo_json TEXT NOT NULL, + change_json TEXT NOT NULL, + archived INTEGER NOT NULL + ) + ` + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_todo_events_archived_offset + ON todo_events (archived, event_offset) + ` +}) diff --git a/.reference/server/src/bin.ts b/.reference/server/src/bin.ts new file mode 100644 index 0000000000..647a33e519 --- /dev/null +++ b/.reference/server/src/bin.ts @@ -0,0 +1,11 @@ +#!/usr/bin/env node +import * as NodeRuntime from "@effect/platform-node/NodeRuntime" +import * as NodeServices from "@effect/platform-node/NodeServices" +import * as Effect from "effect/Effect" +import { cli } from "./cli.ts" +import { Command } from "effect/unstable/cli" + +Command.run(cli, { version: "0.1.0" }).pipe( + Effect.provide(NodeServices.layer), + NodeRuntime.runMain +) diff --git a/.reference/server/src/cli.ts b/.reference/server/src/cli.ts new file mode 100644 index 0000000000..75806c2f4e --- /dev/null +++ b/.reference/server/src/cli.ts @@ -0,0 +1,125 @@ +import * as SqliteNode from "@effect/sql-sqlite-node" +import { Command, Flag } from "effect/unstable/cli" +import * as Config from "effect/Config" +import * as Effect from "effect/Effect" +import * as FileSystem from "effect/FileSystem" +import * as Option from "effect/Option" +import * as Path from "effect/Path" +import { fileURLToPath } from "node:url" +import { ServerConfig } from "./config.ts" +import { runMigrations } from "./migrations.ts" +import { runServer } from "./server.ts" +import type { ServerConfigData } from "./config.ts" + +const defaultAssetsDir = fileURLToPath(new URL("../../public", import.meta.url)) +const defaultDbFilename = fileURLToPath(new URL("../../todo.sqlite", import.meta.url)) + +const hostFlag = Flag.string("host").pipe( + Flag.withDescription("Host interface to bind"), + Flag.optional +) + +const portFlag = Flag.integer("port").pipe( + Flag.withDescription("Port to listen on"), + Flag.optional +) + +const assetsFlag = Flag.directory("assets").pipe( + Flag.withDescription("Directory of static assets"), + Flag.optional +) + +const dbFlag = Flag.string("db").pipe( + Flag.withDescription("SQLite database filename"), + Flag.optional +) + +const requestLoggingFlag = Flag.boolean("request-logging").pipe( + Flag.withDescription("Enable request logging"), + Flag.optional +) + +const frontendDevOriginFlag = Flag.string("frontend-dev-origin").pipe( + Flag.withDescription("Redirect frontend GET requests to a Vite dev server origin"), + Flag.optional +) + +const EnvServerConfig = Config.unwrap({ + host: Config.string("HOST").pipe(Config.withDefault("127.0.0.1")), + port: Config.port("PORT").pipe(Config.withDefault(8787)), + assetsDir: Config.string("ASSETS_DIR").pipe(Config.withDefault(defaultAssetsDir)), + dbFilename: Config.string("DB_FILENAME").pipe(Config.withDefault(defaultDbFilename)), + requestLogging: Config.boolean("REQUEST_LOGGING").pipe(Config.withDefault(true)), + frontendDevOrigin: Config.string("FRONTEND_DEV_ORIGIN").pipe( + Config.option, + Config.map(Option.getOrUndefined) + ) +}) + +export interface CliServerFlags { + readonly host: Option.Option + readonly port: Option.Option + readonly assets: Option.Option + readonly db: Option.Option + readonly requestLogging: Option.Option + readonly frontendDevOrigin: Option.Option +} + +export const resolveServerConfig = ( + flags: CliServerFlags +): Effect.Effect => + Effect.gen(function*() { + const env = yield* EnvServerConfig + return { + host: Option.getOrElse(flags.host, () => env.host), + port: Option.getOrElse(flags.port, () => env.port), + assetsDir: Option.getOrElse(flags.assets, () => env.assetsDir), + dbFilename: Option.getOrElse(flags.db, () => env.dbFilename), + requestLogging: Option.getOrElse(flags.requestLogging, () => env.requestLogging), + frontendDevOrigin: Option.getOrElse(flags.frontendDevOrigin, () => env.frontendDevOrigin) + } + }) + + +export const resetDatabase = (dbFilename: string) => + Effect.gen(function*() { + const fs = yield* FileSystem.FileSystem + const path = yield* Path.Path + + if (dbFilename !== ":memory:") { + yield* fs.remove(path.resolve(dbFilename), { force: true }) + } + + const sqliteLayer = SqliteNode.SqliteClient.layer({ + filename: dbFilename + }) + + yield* runMigrations.pipe(Effect.provide(sqliteLayer)) + }) + +const commandFlags = { + host: hostFlag, + port: portFlag, + assets: assetsFlag, + db: dbFlag, + requestLogging: requestLoggingFlag, + frontendDevOrigin: frontendDevOriginFlag +} as const + +const rootCommand = Command.make("effect-http-ws-cli", commandFlags).pipe( + Command.withDescription("Run a unified Effect HTTP + WebSocket server"), + Command.withHandler((flags) => + Effect.flatMap(resolveServerConfig(flags), (config) => + runServer.pipe(Effect.provideService(ServerConfig, config)))), +) + +const resetCommand = Command.make("reset", commandFlags).pipe( + Command.withDescription("Delete the SQLite database file and rerun migrations"), + Command.withHandler((flags) => + Effect.flatMap(resolveServerConfig(flags), (config) => resetDatabase(config.dbFilename)) + ) +) + +export const cli = rootCommand.pipe( + Command.withSubcommands([resetCommand]) +) diff --git a/.reference/server/src/client.ts b/.reference/server/src/client.ts new file mode 100644 index 0000000000..4650807973 --- /dev/null +++ b/.reference/server/src/client.ts @@ -0,0 +1,58 @@ +import { NodeSocket } from "@effect/platform-node" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" +import * as RpcClient from "effect/unstable/rpc/RpcClient" +import * as RpcSerialization from "effect/unstable/rpc/RpcSerialization" +import * as Stream from "effect/Stream" +import { WsRpcGroup } from "./contracts.ts" + +export const wsRpcProtocolLayer = (wsUrl: string) => + RpcClient.layerProtocolSocket().pipe( + Layer.provide(NodeSocket.layerWebSocket(wsUrl)), + Layer.provide(RpcSerialization.layerJson) + ) + +export const makeWsRpcClient = RpcClient.make(WsRpcGroup) +type WsRpcClient = typeof makeWsRpcClient extends Effect.Effect ? Client : never + +export const withWsRpcClient = ( + wsUrl: string, + f: (client: WsRpcClient) => Effect.Effect +) => + makeWsRpcClient.pipe( + Effect.flatMap(f), + Effect.provide(wsRpcProtocolLayer(wsUrl)) + ) + +export const runClientExample = (wsUrl: string) => + Effect.scoped( + withWsRpcClient(wsUrl, (client) => + Effect.gen(function*() { + const echoed = yield* client.echo({ text: "hello from client" }) + const summed = yield* client.sum({ left: 20, right: 22 }) + const time = yield* client.time(undefined) + return { echoed, summed, time } + }) + ) + ) + +export const runSubscriptionExample = (wsUrl: string, modelId: string) => + Effect.scoped( + withWsRpcClient(wsUrl, (client) => + Effect.gen(function*() { + const snapshot = yield* client.listTodos({ includeArchived: true }) + const todo = snapshot.todos[0] + if (!todo) { + return [] + } + + yield* client.renameTodo({ id: todo.id, title: `${modelId}: first` }) + yield* client.completeTodo({ id: todo.id, completed: true }) + + return yield* client.subscribeTodos({ fromOffset: snapshot.offset, includeArchived: true }).pipe( + Stream.take(2), + Stream.runCollect + ) + }) + ) + ) diff --git a/.reference/server/src/config.ts b/.reference/server/src/config.ts new file mode 100644 index 0000000000..601135fefb --- /dev/null +++ b/.reference/server/src/config.ts @@ -0,0 +1,14 @@ +import * as ServiceMap from "effect/ServiceMap" + +export interface ServerConfigData { + readonly host: string + readonly port: number + readonly assetsDir: string + readonly dbFilename: string + readonly requestLogging: boolean + readonly frontendDevOrigin: string | undefined +} + +export class ServerConfig extends ServiceMap.Service()( + "effect-http-ws-cli/ServerConfig" +) {} diff --git a/.reference/server/src/contracts.ts b/.reference/server/src/contracts.ts new file mode 100644 index 0000000000..f2b2534f93 --- /dev/null +++ b/.reference/server/src/contracts.ts @@ -0,0 +1,132 @@ +import * as Schema from "effect/Schema" +import * as Rpc from "effect/unstable/rpc/Rpc" +import * as RpcGroup from "effect/unstable/rpc/RpcGroup" + +export const EchoPayload = Schema.Struct({ + text: Schema.String +}) + +export const EchoResult = Schema.Struct({ + text: Schema.String +}) + +export const SumPayload = Schema.Struct({ + left: Schema.Number, + right: Schema.Number +}) + +export const SumResult = Schema.Struct({ + total: Schema.Number +}) + +export const TimeResult = Schema.Struct({ + iso: Schema.String +}) + +export const Todo = Schema.Struct({ + id: Schema.String, + title: Schema.String, + completed: Schema.Boolean, + archived: Schema.Boolean, + revision: Schema.Number, + updatedAt: Schema.String +}) +export type Todo = Schema.Schema.Type + +export const TodoChange = Schema.Union([ + Schema.Struct({ + _tag: Schema.Literal("TodoCreated") + }), + Schema.Struct({ + _tag: Schema.Literal("TodoRenamed"), + title: Schema.String + }), + Schema.Struct({ + _tag: Schema.Literal("TodoCompleted"), + completed: Schema.Boolean + }), + Schema.Struct({ + _tag: Schema.Literal("TodoArchived"), + archived: Schema.Boolean + }) +]) +export type TodoChange = Schema.Schema.Type + +export const TodoEvent = Schema.Struct({ + offset: Schema.Number, + at: Schema.String, + todo: Todo, + change: TodoChange +}) +export type TodoEvent = Schema.Schema.Type + +export const TodoSnapshot = Schema.Struct({ + offset: Schema.Number, + todos: Schema.Array(Todo) +}) +export type TodoSnapshot = Schema.Schema.Type + +export const EchoRpc = Rpc.make("echo", { + payload: EchoPayload, + success: EchoResult +}) + +export const SumRpc = Rpc.make("sum", { + payload: SumPayload, + success: SumResult +}) + +export const TimeRpc = Rpc.make("time", { + success: TimeResult +}) + +export const ListTodosRpc = Rpc.make("listTodos", { + payload: Schema.Struct({ + includeArchived: Schema.Boolean + }), + success: TodoSnapshot +}) + +export const RenameTodoRpc = Rpc.make("renameTodo", { + payload: Schema.Struct({ + id: Schema.String, + title: Schema.String + }), + success: TodoEvent +}) + +export const CompleteTodoRpc = Rpc.make("completeTodo", { + payload: Schema.Struct({ + id: Schema.String, + completed: Schema.Boolean + }), + success: TodoEvent +}) + +export const ArchiveTodoRpc = Rpc.make("archiveTodo", { + payload: Schema.Struct({ + id: Schema.String, + archived: Schema.Boolean + }), + success: TodoEvent +}) + +export const SubscribeTodosRpc = Rpc.make("subscribeTodos", { + payload: Schema.Struct({ + fromOffset: Schema.Number, + includeArchived: Schema.Boolean + }), + success: TodoEvent, + stream: true +}) + +export const WsRpcGroup = RpcGroup.make( + EchoRpc, + SumRpc, + TimeRpc, + ListTodosRpc, + RenameTodoRpc, + CompleteTodoRpc, + ArchiveTodoRpc, + SubscribeTodosRpc +) diff --git a/.reference/server/src/messages.ts b/.reference/server/src/messages.ts new file mode 100644 index 0000000000..75a67efac2 --- /dev/null +++ b/.reference/server/src/messages.ts @@ -0,0 +1,73 @@ +import * as Schema from "effect/Schema" +import * as SchemaTransformation from "effect/SchemaTransformation" + +export const ClientMessage = Schema.Union([ + Schema.Struct({ + kind: Schema.Literal("echo"), + text: Schema.String + }), + Schema.Struct({ + kind: Schema.Literal("sum"), + left: Schema.Number, + right: Schema.Number + }), + Schema.Struct({ + kind: Schema.Literal("time") + }) +]) + +export type ClientMessage = Schema.Schema.Type + +export const ServerMessage = Schema.Union([ + Schema.Struct({ + kind: Schema.Literal("echo"), + text: Schema.String + }), + Schema.Struct({ + kind: Schema.Literal("sumResult"), + total: Schema.Number + }), + Schema.Struct({ + kind: Schema.Literal("time"), + iso: Schema.String + }), + Schema.Struct({ + kind: Schema.Literal("error"), + error: Schema.String + }) +]) + + +export type ServerMessage = Schema.Schema.Type + +export const decodeClientMessage = Schema.decodeUnknownEffect(ClientMessage) + +const Utf8StringFromUint8Array = Schema.Uint8Array.pipe( + Schema.decodeTo( + Schema.String, + SchemaTransformation.transform({ + decode: (bytes) => new TextDecoder().decode(bytes), + encode: (text) => new TextEncoder().encode(text) + }) + ) +) + +const ClientMessageFromWire = Schema.Union([ + Schema.String, + Utf8StringFromUint8Array +]).pipe( + Schema.decodeTo(Schema.fromJsonString(ClientMessage)) +) + +export const decodeWireClientMessage = Schema.decodeUnknownEffect(ClientMessageFromWire) + +export const routeClientMessage = (message: ClientMessage): ServerMessage => { + switch (message.kind) { + case "echo": + return { kind: "echo", text: message.text } + case "sum": + return { kind: "sumResult", total: message.left + message.right } + case "time": + return { kind: "time", iso: new Date().toISOString() } + } +} diff --git a/.reference/server/src/migrations.ts b/.reference/server/src/migrations.ts new file mode 100644 index 0000000000..65abf1a534 --- /dev/null +++ b/.reference/server/src/migrations.ts @@ -0,0 +1,41 @@ +/** + * MigrationsLive - Migration runner with inline loader + * + * Uses Migrator.make with fromRecord to define migrations inline. + * All migrations are statically imported - no dynamic file system loading. + * + * Migrations run automatically when the MigrationsLive layer is provided, + * ensuring the database schema is up-to-date before the application starts. + */ +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" +import * as ServiceMap from "effect/ServiceMap" +import * as Migrator from "effect/unstable/sql/Migrator" +import Migration0001 from "./Migrations/001_TodoSchema.ts" + +const loader = Migrator.fromRecord({ + "1_TodoSchema": Migration0001 +}) + +const run = Migrator.make({}) + +export const runMigrations = Effect.gen(function*() { + yield* Effect.log("Running migrations...") + yield* run({ loader }) + yield* Effect.log("Migrations ran successfully") +}) + +export interface MigrationsReadyApi { + readonly ready: true +} + +export class MigrationsReady extends ServiceMap.Service()( + "effect-http-ws-cli/MigrationsReady" +) {} + +export const MigrationsLive = Layer.effect( + MigrationsReady, + runMigrations.pipe( + Effect.as(MigrationsReady.of({ ready: true })) + ) +) diff --git a/.reference/server/src/model-store.ts b/.reference/server/src/model-store.ts new file mode 100644 index 0000000000..56bcc0c05a --- /dev/null +++ b/.reference/server/src/model-store.ts @@ -0,0 +1,268 @@ +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" +import * as Option from "effect/Option" +import * as PubSub from "effect/PubSub" +import * as Schema from "effect/Schema" +import * as ServiceMap from "effect/ServiceMap" +import * as Stream from "effect/Stream" +import * as SqlClient from "effect/unstable/sql/SqlClient" +import * as SqlSchema from "effect/unstable/sql/SqlSchema" +import type { Todo, TodoChange, TodoEvent, TodoSnapshot } from "./contracts.ts" +import { Todo as TodoSchema, TodoChange as TodoChangeSchema } from "./contracts.ts" +import { MigrationsReady } from "./migrations.ts" + +export interface TodoStoreApi { + readonly list: (input: { + readonly includeArchived: boolean + }) => Effect.Effect + readonly rename: (input: { + readonly id: string + readonly title: string + }) => Effect.Effect + readonly complete: (input: { + readonly id: string + readonly completed: boolean + }) => Effect.Effect + readonly archive: (input: { + readonly id: string + readonly archived: boolean + }) => Effect.Effect + readonly subscribe: (input: { + readonly fromOffset: number + readonly includeArchived: boolean + }) => Stream.Stream +} + +export class TodoStore extends ServiceMap.Service()( + "effect-http-ws-cli/TodoStore" +) {} + +const TodoRow = Schema.Struct({ + id: Schema.String, + title: Schema.String, + completed: Schema.BooleanFromBit, + archived: Schema.BooleanFromBit, + revision: Schema.Number, + updatedAt: Schema.String +}) + +const TodoEventRow = Schema.Struct({ + offset: Schema.Number, + at: Schema.String, + todo: Schema.fromJsonString(TodoSchema), + change: Schema.fromJsonString(TodoChangeSchema) +}) + +const EventInsertRequest = Schema.Struct({ + at: Schema.String, + todo: Schema.fromJsonString(TodoSchema), + change: Schema.fromJsonString(TodoChangeSchema), + archived: Schema.BooleanFromBit +}) + +const ListRequest = Schema.Struct({ + includeArchived: Schema.Boolean +}) + +const CatchupRequest = Schema.Struct({ + fromOffset: Schema.Number, + includeArchived: Schema.Boolean +}) + +const OffsetRow = Schema.Struct({ + offset: Schema.Number +}) + +const makeQueries = (sql: SqlClient.SqlClient) => { + const listTodoRows = SqlSchema.findAll({ + Request: ListRequest, + Result: TodoRow, + execute: (request) => + request.includeArchived + ? sql` + SELECT id, title, completed, archived, revision, updated_at AS updatedAt + FROM todos + ORDER BY id + ` + : sql` + SELECT id, title, completed, archived, revision, updated_at AS updatedAt + FROM todos + WHERE archived = 0 + ORDER BY id + ` + }) + + const findTodoById = SqlSchema.findOneOption({ + Request: Schema.String, + Result: TodoRow, + execute: (id) => sql` + SELECT id, title, completed, archived, revision, updated_at AS updatedAt + FROM todos + WHERE id = ${id} + ` + }) + + const upsertTodo = SqlSchema.void({ + Request: TodoRow, + execute: (todo) => sql` + INSERT INTO todos (id, title, completed, archived, revision, updated_at) + VALUES (${todo.id}, ${todo.title}, ${todo.completed}, ${todo.archived}, ${todo.revision}, ${todo.updatedAt}) + ON CONFLICT(id) DO UPDATE SET + title = excluded.title, + completed = excluded.completed, + archived = excluded.archived, + revision = excluded.revision, + updated_at = excluded.updated_at + ` + }) + + const loadEventsSince = SqlSchema.findAll({ + Request: CatchupRequest, + Result: TodoEventRow, + execute: (request) => + request.includeArchived + ? sql` + SELECT event_offset AS "offset", at, todo_json AS todo, change_json AS change + FROM todo_events + WHERE event_offset > ${request.fromOffset} + ORDER BY event_offset + ` + : sql` + SELECT event_offset AS "offset", at, todo_json AS todo, change_json AS change + FROM todo_events + WHERE event_offset > ${request.fromOffset} AND archived = 0 + ORDER BY event_offset + ` + }) + + const insertTodoEvent = SqlSchema.findOne({ + Request: EventInsertRequest, + Result: TodoEventRow, + execute: (request) => sql` + INSERT INTO todo_events (at, todo_json, change_json, archived) + VALUES (${request.at}, ${request.todo}, ${request.change}, ${request.archived}) + RETURNING event_offset AS "offset", at, todo_json AS todo, change_json AS change + ` + }) + + const currentOffset = SqlSchema.findOne({ + Request: Schema.Undefined, + Result: OffsetRow, + execute: () => sql<{ readonly offset: number }>` + SELECT COALESCE(MAX(event_offset), 0) AS "offset" + FROM todo_events + ` + }) + + return { + listTodoRows, + findTodoById, + upsertTodo, + loadEventsSince, + insertTodoEvent, + currentOffset + } as const +} + +export const layerTodoStore = Layer.effect( + TodoStore, + Effect.gen(function*() { + yield* MigrationsReady + const eventsPubSub = yield* PubSub.unbounded() + + const append = ( + todoId: string, + change: TodoChange, + update: (todo: Todo) => Todo + ): Effect.Effect => + Effect.flatMap(Effect.service(SqlClient.SqlClient), (sql) => { + const queries = makeQueries(sql) + return sql.withTransaction( + queries.findTodoById(todoId).pipe( + Effect.flatMap( + Option.match({ + onNone: () => Effect.die(`Todo not found: ${todoId}`), + onSome: (todo) => { + const updated = update(todo) + return queries.upsertTodo(updated).pipe( + Effect.flatMap(() => + queries.insertTodoEvent({ + at: updated.updatedAt, + todo: updated, + change, + archived: updated.archived + }) + ) + ) + } + }) + ) + ) + ) + }).pipe(Effect.tap((event) => PubSub.publish(eventsPubSub, event)), Effect.orDie) + + const visible = (todo: Todo, includeArchived: boolean) => includeArchived || !todo.archived + + const subscribe = (input: { + readonly fromOffset: number + readonly includeArchived: boolean + }): Stream.Stream => { + const catchup = Stream.fromIterableEffect( + Effect.flatMap(Effect.service(SqlClient.SqlClient), (sql) => makeQueries(sql).loadEventsSince(input)) + ).pipe(Stream.orDie) + + const live = Stream.fromPubSub(eventsPubSub).pipe( + Stream.filter((event) => visible(event.todo, input.includeArchived)) + ) + + return Stream.concat(catchup, live) + } + + return TodoStore.of({ + list: ({ includeArchived }) => + Effect.flatMap(Effect.service(SqlClient.SqlClient), (sql) => { + const queries = makeQueries(sql) + return Effect.all({ + todos: queries.listTodoRows({ includeArchived }), + offset: queries.currentOffset(undefined).pipe(Effect.map(({ offset }) => offset)) + }).pipe( + Effect.map(({ offset, todos }) => ({ offset, todos })) + ) + }).pipe(Effect.orDie), + rename: ({ id, title }) => + append( + id, + { _tag: "TodoRenamed", title }, + (todo) => ({ + ...todo, + title, + revision: todo.revision + 1, + updatedAt: new Date().toISOString() + }) + ), + complete: ({ id, completed }) => + append( + id, + { _tag: "TodoCompleted", completed }, + (todo) => ({ + ...todo, + completed, + revision: todo.revision + 1, + updatedAt: new Date().toISOString() + }) + ), + archive: ({ id, archived }) => + append( + id, + { _tag: "TodoArchived", archived }, + (todo) => ({ + ...todo, + archived, + revision: todo.revision + 1, + updatedAt: new Date().toISOString() + }) + ), + subscribe + }) + }) +) diff --git a/.reference/server/src/server.ts b/.reference/server/src/server.ts new file mode 100644 index 0000000000..0d1e7a16dd --- /dev/null +++ b/.reference/server/src/server.ts @@ -0,0 +1,155 @@ +import { NodeHttpServer } from "@effect/platform-node" +import * as SqliteNode from "@effect/sql-sqlite-node" +import * as Effect from "effect/Effect" +import * as FileSystem from "effect/FileSystem" +import * as Layer from "effect/Layer" +import * as Path from "effect/Path" +import * as Http from "node:http" +import { + HttpRouter, + HttpServerRequest, + HttpServerResponse +} from "effect/unstable/http" +import * as RpcSerialization from "effect/unstable/rpc/RpcSerialization" +import * as RpcServer from "effect/unstable/rpc/RpcServer" +import * as Stream from "effect/Stream" +import { + ClientMessage, + routeClientMessage, + ServerMessage +} from "./messages.ts" +import { ServerConfig } from "./config.ts" +import { WsRpcGroup } from "./contracts.ts" +import { TodoStore, layerTodoStore } from "./model-store.ts" +import { MigrationsLive } from "./migrations.ts" + +const respondMessage = HttpServerResponse.schemaJson(ServerMessage) + +const messageDispatchRoute = HttpRouter.add( + "POST", + "/api/dispatch", + HttpServerRequest.schemaBodyJson(ClientMessage).pipe( + Effect.flatMap((message) => respondMessage(routeClientMessage(message))), + Effect.catchTag( + "SchemaError", + () => Effect.succeed(HttpServerResponse.jsonUnsafe({ kind: "error", error: "Invalid message schema" }, { status: 400 })) + ), + Effect.catchTag( + "HttpServerError", + () => Effect.succeed(HttpServerResponse.jsonUnsafe({ kind: "error", error: "Invalid request body" }, { status: 400 })) + ) + ) +) + +const websocketRpcRoute = RpcServer.layerHttp({ + group: WsRpcGroup, + path: "/ws", + protocol: "websocket" + }).pipe( + Layer.provide(WsRpcGroup.toLayer({ + echo: ({ text }) => Effect.succeed({ text }), + sum: ({ left, right }) => Effect.succeed({ total: left + right }), + time: () => Effect.sync(() => ({ iso: new Date().toISOString() })), + listTodos: ({ includeArchived }) => + Effect.flatMap(Effect.service(TodoStore), (store) => store.list({ includeArchived })), + renameTodo: ({ id, title }) => + Effect.flatMap(Effect.service(TodoStore), (store) => store.rename({ id, title })), + completeTodo: ({ id, completed }) => + Effect.flatMap(Effect.service(TodoStore), (store) => store.complete({ id, completed })), + archiveTodo: ({ id, archived }) => + Effect.flatMap(Effect.service(TodoStore), (store) => store.archive({ id, archived })), + subscribeTodos: ({ fromOffset, includeArchived }) => + Stream.unwrap( + Effect.map( + Effect.service(TodoStore), + (store) => store.subscribe({ fromOffset, includeArchived }) + ) + ) + })), + Layer.provide(layerTodoStore), + Layer.provide(RpcSerialization.layerJson) + ) + +const staticRoute = HttpRouter.add( + "GET", + "*", + (request) => + Effect.gen(function*() { + const fs = yield* FileSystem.FileSystem + const path = yield* Path.Path + const config = yield* ServerConfig + const url = HttpServerRequest.toURL(request) + if (!url) { + return HttpServerResponse.text("Bad Request", { status: 400 }) + } + + if (config.frontendDevOrigin) { + return HttpServerResponse.redirect( + new URL(`${url.pathname}${url.search}`, config.frontendDevOrigin), + { + status: 307, + headers: { "cache-control": "no-store" } + } + ) + } + + const root = path.resolve(config.assetsDir) + const decodedPath = decodeURIComponent(url.pathname) + const target = decodedPath === "/" + ? "index.html" + : decodedPath.endsWith("/") + ? `${decodedPath.slice(1)}index.html` + : decodedPath.slice(1) + + const normalizedTarget = path.normalize(target) + const absoluteTarget = path.resolve(root, normalizedTarget) + const relativeToRoot = path.relative(root, absoluteTarget) + + if (relativeToRoot.startsWith("..") || path.isAbsolute(relativeToRoot)) { + return HttpServerResponse.text("Forbidden", { status: 403 }) + } + + const exists = yield* fs.exists(absoluteTarget) + if (!exists) { + return HttpServerResponse.text("Not Found", { status: 404 }) + } + + return yield* HttpServerResponse.file(absoluteTarget) + }).pipe(Effect.catchCause(() => Effect.succeed(HttpServerResponse.text("Bad Request", { status: 400 })))) +) + +export const makeRoutesLayer = + Layer.mergeAll( + HttpRouter.add( + "GET", + "/health", + HttpServerResponse.json({ ok: true }) + ), + messageDispatchRoute, + websocketRpcRoute, + staticRoute + ) + +export const makeServerLayer = Layer.unwrap( + Effect.gen(function*() { + const config = yield* ServerConfig + const sqliteLayer = SqliteNode.SqliteClient.layer({ + filename: config.dbFilename + }) + const persistenceLayer = MigrationsLive.pipe( + Layer.provideMerge(sqliteLayer) + ) + + return HttpRouter.serve(makeRoutesLayer, { + disableLogger: !config.requestLogging + }).pipe( + Layer.provideMerge(persistenceLayer), + Layer.provide(NodeHttpServer.layer(Http.createServer, { + host: config.host, + port: config.port + })) + ) + }) +) + +export const runServer = Layer.launch(makeServerLayer) diff --git a/.reference/server/test/cli-config.test.ts b/.reference/server/test/cli-config.test.ts new file mode 100644 index 0000000000..90b75857a7 --- /dev/null +++ b/.reference/server/test/cli-config.test.ts @@ -0,0 +1,79 @@ +import { describe, expect, it } from "@effect/vitest" +import * as ConfigProvider from "effect/ConfigProvider" +import * as Effect from "effect/Effect" +import * as Option from "effect/Option" +import { resolveServerConfig } from "../src/cli.ts" + +describe("cli config resolution", () => { + it.effect("falls back to effect/config values when flags are omitted", () => + Effect.gen(function*() { + const resolved = yield* resolveServerConfig({ + host: Option.none(), + port: Option.none(), + assets: Option.none(), + db: Option.none(), + requestLogging: Option.none(), + frontendDevOrigin: Option.none() + }).pipe( + Effect.provideService( + ConfigProvider.ConfigProvider, + ConfigProvider.fromEnv({ + env: { + HOST: "0.0.0.0", + PORT: "4001", + ASSETS_DIR: "public", + DB_FILENAME: "dev.sqlite", + REQUEST_LOGGING: "false", + FRONTEND_DEV_ORIGIN: "http://127.0.0.1:5173" + } + }) + ) + ) + + expect(resolved).toEqual({ + host: "0.0.0.0", + port: 4001, + assetsDir: "public", + dbFilename: "dev.sqlite", + requestLogging: false, + frontendDevOrigin: "http://127.0.0.1:5173" + }) + }) + ) + + it.effect("uses CLI flags when provided", () => + Effect.gen(function*() { + const resolved = yield* resolveServerConfig({ + host: Option.some("127.0.0.1"), + port: Option.some(8788), + assets: Option.some("public"), + db: Option.some("override.sqlite"), + requestLogging: Option.some(true), + frontendDevOrigin: Option.some("http://127.0.0.1:4173") + }).pipe( + Effect.provideService( + ConfigProvider.ConfigProvider, + ConfigProvider.fromEnv({ + env: { + HOST: "0.0.0.0", + PORT: "4001", + ASSETS_DIR: "other", + DB_FILENAME: "ignored.sqlite", + REQUEST_LOGGING: "false", + FRONTEND_DEV_ORIGIN: "http://127.0.0.1:5173" + } + }) + ) + ) + + expect(resolved).toEqual({ + host: "127.0.0.1", + port: 8788, + assetsDir: "public", + dbFilename: "override.sqlite", + requestLogging: true, + frontendDevOrigin: "http://127.0.0.1:4173" + }) + }) + ) +}) diff --git a/.reference/server/test/reset.test.ts b/.reference/server/test/reset.test.ts new file mode 100644 index 0000000000..b180538e31 --- /dev/null +++ b/.reference/server/test/reset.test.ts @@ -0,0 +1,90 @@ +import * as NodeServices from "@effect/platform-node/NodeServices" +import * as SqliteNode from "@effect/sql-sqlite-node" +import { describe, expect, it } from "@effect/vitest" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" +import * as SqlClient from "effect/unstable/sql/SqlClient" +import * as FileSystem from "node:fs" +import * as OS from "node:os" +import * as NodePath from "node:path" +import { resetDatabase } from "../src/cli.ts" +import { MigrationsLive } from "../src/migrations.ts" + +const countRows = (dbFilename: string, tableName: string) => + Effect.flatMap(Effect.service(SqlClient.SqlClient), (sql) => + sql<{ readonly count: number }>`SELECT COUNT(*) AS count FROM ${sql(tableName)}`.pipe( + Effect.map((rows) => rows[0]?.count ?? 0) + ) + ).pipe( + Effect.provide(SqliteNode.SqliteClient.layer({ filename: dbFilename })) + ) + +const insertTodo = (dbFilename: string) => + Effect.scoped( + Effect.flatMap(Effect.service(SqlClient.SqlClient), (sql) => { + const now = new Date().toISOString() + const id = "todo-reset-test" + const title = "before-reset" + return sql.withTransaction( + sql` + INSERT INTO todos (id, title, completed, archived, revision, updated_at) + VALUES (${id}, ${title}, 0, 0, 1, ${now}) + `.pipe( + Effect.flatMap(() => + sql` + INSERT INTO todo_events (at, todo_json, change_json, archived) + VALUES ( + ${now}, + ${JSON.stringify({ + id, + title, + completed: false, + archived: false, + revision: 1, + updatedAt: now + })}, + ${JSON.stringify({ _tag: "TodoCreated" })}, + 0 + ) + ` + ) + ) + ) + }).pipe( + Effect.provide(MigrationsLive.pipe(Layer.provideMerge(SqliteNode.SqliteClient.layer({ filename: dbFilename })))) + ) + ) + +describe("reset command", () => { + it.effect("deletes the database and reruns migrations without reseeding todos", () => + Effect.gen(function*() { + const dbFilename = NodePath.join( + OS.tmpdir(), + `effect-http-ws-cli-reset-${Date.now()}-${Math.random().toString(16).slice(2)}.sqlite` + ) + + yield* insertTodo(dbFilename) + + const beforeCount = yield* countRows(dbFilename, "todos") + expect(beforeCount).toBe(1) + + yield* resetDatabase(dbFilename).pipe( + Effect.provide(NodeServices.layer) + ) + + const todoCount = yield* countRows(dbFilename, "todos") + const migrationCount = yield* countRows(dbFilename, "effect_sql_migrations") + + expect(todoCount).toBe(0) + expect(migrationCount).toBe(1) + + yield* Effect.sync(() => { + try { + FileSystem.rmSync(dbFilename, { force: true }) + } catch { + // ignore cleanup failures in tests + } + }) + }) + ) +}) diff --git a/.reference/server/test/server.test.ts b/.reference/server/test/server.test.ts new file mode 100644 index 0000000000..317e2a9058 --- /dev/null +++ b/.reference/server/test/server.test.ts @@ -0,0 +1,310 @@ +import { NodeHttpServer } from "@effect/platform-node" +import * as SqliteNode from "@effect/sql-sqlite-node" +import { describe, expect, it } from "@effect/vitest" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" +import * as Stream from "effect/Stream" +import * as FileSystem from "node:fs" +import * as OS from "node:os" +import * as NodePath from "node:path" +import { + HttpBody, + HttpClient, + HttpClientResponse, + HttpServer, + HttpRouter +} from "effect/unstable/http" +import * as SqlClient from "effect/unstable/sql/SqlClient" +import { ServerConfig } from "../src/config.ts" +import { MigrationsLive } from "../src/migrations.ts" +import { ServerMessage } from "../src/messages.ts" +import { withWsRpcClient } from "../src/client.ts" +import { makeRoutesLayer } from "../src/server.ts" + +const testServerConfig = { + host: "127.0.0.1", + port: 0, + assetsDir: new URL("../../public", import.meta.url).pathname, + dbFilename: ":memory:", + requestLogging: false, + frontendDevOrigin: undefined +} + +const AppUnderTest = HttpRouter.serve( + makeRoutesLayer, + { + disableListenLog: true, + disableLogger: true + } +) + +const persistenceLayer = (dbFilename: string) => { + const sqliteLayer = SqliteNode.SqliteClient.layer({ filename: dbFilename }) + return MigrationsLive.pipe(Layer.provideMerge(sqliteLayer)) +} + +const appLayer = (dbFilename: string) => + AppUnderTest.pipe(Layer.provideMerge(persistenceLayer(dbFilename))) + +const insertTodo = (dbFilename: string, id: string, title: string) => + Effect.scoped( + Effect.flatMap(Effect.service(SqlClient.SqlClient), (sql) => { + const now = new Date().toISOString() + return sql.withTransaction( + sql` + INSERT INTO todos (id, title, completed, archived, revision, updated_at) + VALUES (${id}, ${title}, 0, 0, 1, ${now}) + `.pipe( + Effect.flatMap(() => + sql` + INSERT INTO todo_events (at, todo_json, change_json, archived) + VALUES ( + ${now}, + ${JSON.stringify({ + id, + title, + completed: false, + archived: false, + revision: 1, + updatedAt: now + })}, + ${JSON.stringify({ _tag: "TodoCreated" })}, + 0 + ) + ` + ) + ) + ) + }).pipe( + Effect.provide(persistenceLayer(dbFilename)) + ) + ) + +describe("server", () => { + it.effect("routes HTTP messages validated by Schema", () => + Effect.gen(function*() { + yield* Layer.build(appLayer(testServerConfig.dbFilename)).pipe( + Effect.provideService(ServerConfig, testServerConfig) + ) + const client = yield* HttpClient.HttpClient + const response = yield* client.post("/api/dispatch", { + body: HttpBody.jsonUnsafe({ kind: "sum", left: 20, right: 22 }) + }) + + const parsed = yield* HttpClientResponse.schemaBodyJson(ServerMessage)(response) + expect(parsed).toEqual({ kind: "sumResult", total: 42 }) + }).pipe(Effect.provide(NodeHttpServer.layerTest)) + ) + + it.effect("serves static files from local filesystem", () => + Effect.gen(function*() { + yield* Layer.build(appLayer(testServerConfig.dbFilename)).pipe( + Effect.provideService(ServerConfig, testServerConfig) + ) + const text = yield* HttpClient.get("/").pipe( + Effect.flatMap((response) => response.text) + ) + + expect(text).toContain("effect-http-ws-cli") + }).pipe(Effect.provide(NodeHttpServer.layerTest)) + ) + + it.effect("redirects frontend requests to the Vite dev server when enabled", () => + Effect.gen(function*() { + yield* Layer.build(appLayer(testServerConfig.dbFilename)).pipe( + Effect.provideService(ServerConfig, { + ...testServerConfig, + frontendDevOrigin: "http://127.0.0.1:5173" + }) + ) + + const server = yield* HttpServer.HttpServer + const address = server.address as HttpServer.TcpAddress + const response = yield* Effect.promise(() => + fetch(`http://127.0.0.1:${address.port}/todos?filter=active`, { + redirect: "manual" + }) + ) + + expect(response.status).toBe(307) + expect(response.headers.get("location")).toBe("http://127.0.0.1:5173/todos?filter=active") + }).pipe(Effect.provide(NodeHttpServer.layerTest)) + ) + + it.effect("routes WebSocket RPC messages with shared contracts", () => + Effect.gen(function*() { + yield* Layer.build(appLayer(testServerConfig.dbFilename)).pipe( + Effect.provideService(ServerConfig, testServerConfig) + ) + const server = yield* HttpServer.HttpServer + const address = server.address as HttpServer.TcpAddress + const wsUrl = `ws://127.0.0.1:${address.port}/ws` + + const response = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => client.echo({ text: "hello from ws" })) + ) + + expect(response).toEqual({ text: "hello from ws" }) + }).pipe(Effect.provide(NodeHttpServer.layerTest)) + ) + + it.effect("routes WebSocket RPC calls for multiple procedures", () => + Effect.gen(function*() { + yield* Layer.build(appLayer(testServerConfig.dbFilename)).pipe( + Effect.provideService(ServerConfig, testServerConfig) + ) + const server = yield* HttpServer.HttpServer + const address = server.address as HttpServer.TcpAddress + const wsUrl = `ws://127.0.0.1:${address.port}/ws` + + const result = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + Effect.all({ + sum: client.sum({ left: 1, right: 2 }), + time: client.time(undefined) + }) + ) + ) + + expect(result.sum).toEqual({ total: 3 }) + expect(typeof result.time.iso).toBe("string") + }).pipe(Effect.provide(NodeHttpServer.layerTest)) + ) + + it.effect("lists todos and streams todo updates from offset", () => + Effect.gen(function*() { + const dbFilename = NodePath.join( + OS.tmpdir(), + `effect-http-ws-cli-stream-${Date.now()}-${Math.random().toString(16).slice(2)}.sqlite` + ) + + yield* insertTodo(dbFilename, "todo-stream-test", "stream-seed") + + const events = yield* Effect.scoped( + Effect.gen(function*() { + yield* Layer.build(appLayer(dbFilename)).pipe( + Effect.provideService(ServerConfig, { + ...testServerConfig, + dbFilename + }) + ) + const server = yield* HttpServer.HttpServer + const address = server.address as HttpServer.TcpAddress + const wsUrl = `ws://127.0.0.1:${address.port}/ws` + + return yield* withWsRpcClient(wsUrl, (client) => + Effect.gen(function*() { + const snapshot = yield* client.listTodos({ includeArchived: true }) + const firstTodo = snapshot.todos[0] + if (!firstTodo) { + return yield* Effect.die("Expected a todo fixture") + } + + yield* client.renameTodo({ id: firstTodo.id, title: "alpha" }) + yield* client.completeTodo({ id: firstTodo.id, completed: true }) + yield* client.archiveTodo({ id: firstTodo.id, archived: true }) + + return yield* client.subscribeTodos({ + fromOffset: snapshot.offset, + includeArchived: true + }).pipe( + Stream.take(3), + Stream.runCollect + ) + }) + ) + }) + ).pipe( + Effect.ensuring( + Effect.sync(() => { + try { + FileSystem.rmSync(dbFilename, { force: true }) + } catch { + // ignore cleanup failures in tests + } + }) + ) + ) + + expect(events).toHaveLength(3) + expect(events[0]?.change).toEqual({ _tag: "TodoRenamed", title: "alpha" }) + expect(events[1]?.change).toEqual({ _tag: "TodoCompleted", completed: true }) + expect(events[2]?.change).toEqual({ _tag: "TodoArchived", archived: true }) + expect(events[0]?.todo.title).toBe("alpha") + expect(events[1]?.todo.completed).toBe(true) + expect(events[2]?.todo.archived).toBe(true) + }).pipe(Effect.provide(NodeHttpServer.layerTest)) + ) + + it.effect("persists todos across server restarts when using a file database", () => + Effect.gen(function*() { + const dbFilename = NodePath.join( + OS.tmpdir(), + `effect-http-ws-cli-${Date.now()}-${Math.random().toString(16).slice(2)}.sqlite` + ) + + yield* insertTodo(dbFilename, "todo-persist-test", "persist-seed") + + const withServer = (f: (wsUrl: string) => Effect.Effect) => + Effect.scoped( + Effect.gen(function*() { + yield* Layer.build(appLayer(dbFilename)).pipe( + Effect.provideService(ServerConfig, { + ...testServerConfig, + dbFilename + }) + ) + + const server = yield* HttpServer.HttpServer + const address = server.address as HttpServer.TcpAddress + const wsUrl = `ws://127.0.0.1:${address.port}/ws` + return yield* f(wsUrl) + }) + ) + + const renamedTodoId = yield* withServer((wsUrl) => + Effect.scoped( + withWsRpcClient(wsUrl, (client) => + Effect.gen(function*() { + const snapshot = yield* client.listTodos({ includeArchived: true }) + const firstTodo = snapshot.todos[0] + if (!firstTodo) { + return yield* Effect.die("Expected a todo fixture") + } + + yield* client.renameTodo({ id: firstTodo.id, title: "persisted-title" }) + return firstTodo.id + }) + ) + ) + ) + + const persistedTitle = yield* withServer((wsUrl) => + Effect.scoped( + withWsRpcClient(wsUrl, (client) => + Effect.gen(function*() { + const snapshot = yield* client.listTodos({ includeArchived: true }) + const persisted = snapshot.todos.find((todo) => todo.id === renamedTodoId) + if (!persisted) { + return yield* Effect.die("Expected persisted todo") + } + return persisted.title + }) + ) + ) + ).pipe( + Effect.ensuring( + Effect.sync(() => { + try { + FileSystem.rmSync(dbFilename, { force: true }) + } catch { + // ignore cleanup failures in tests + } + }) + ) + ) + + expect(persistedTitle).toBe("persisted-title") + }).pipe(Effect.provide(NodeHttpServer.layerTest)) + ) +}) diff --git a/.reference/server/tsconfig.json b/.reference/server/tsconfig.json new file mode 100644 index 0000000000..de981b3bf8 --- /dev/null +++ b/.reference/server/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "../tsconfig.json", + "include": ["src", "test", "vitest.config.ts"] +} diff --git a/.reference/server/vitest.config.ts b/.reference/server/vitest.config.ts new file mode 100644 index 0000000000..7ef18d4fc7 --- /dev/null +++ b/.reference/server/vitest.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from "vitest/config" + +export default defineConfig({ + test: { + include: ["test/**/*.test.ts"], + environment: "node" + } +})