Skip to content

Commit c0c2443

Browse files
prototype(effect): address review of the vertical slice
Keep today's 401 body on the wire, render CLI failures as one stderr line with exit 1 and a bare --version, run the real SCHEMA_MIGRATIONS through Migrator.fromRecord, seed in layer construction, keep SqlError in the channel, hardcode the page title, and write the gotchas into the README. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent c47d404 commit c0c2443

12 files changed

Lines changed: 173 additions & 49 deletions

File tree

‎packages/effect-slice/README.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,12 @@ port PRs copy the patterns, not the files.
1111
- `src/cli.ts` — `whoami` on `effect/unstable/cli`, calling the derived `HttpApiClient`.
1212
- `src/slice.test.ts` — the copyable test patterns.
1313
- `scripts/` — esbuild bundle + the packed-CLI e2e core (real server, real Postgres, bundled CLI).
14+
15+
## Gotchas the port must carry (details on #55)
16+
17+
- **esbuild**: `@effect/platform-node`'s `NodeServices` pulls in CJS `undici`, which `require()`s node builtins. ESM output needs the `createRequire` banner in `scripts/build-cli.mjs`. `FetchHttpClient` does not avoid it.
18+
- **Migrator**: use `Migrator.make({})` from `effect/unstable/sql`, not `PgMigrator.layer` (it wants `ChildProcessSpawner`/`FileSystem`/`Path` for `pg_dump`). Ids are one global integer sequence across packages; duplicates fail. All pending steps run in one transaction under `LOCK TABLE … ACCESS EXCLUSIVE`; the ledger is `migration_id integer`, not today's TEXT ids. Today's multi-statement DDL strings run unchanged through `sql.unsafe`.
19+
- **CLI**: Effect's defaults are agent-hostile — failures log to stdout with a stack, `--version` prints `name vX`, and `--wizard`/`--completions`/`--log-level` come free. `src/cli.ts` shows the three overrides: `CliError.UserError` for every actionable failure, `CliOutput.layer` with a one-line `formatError`/bare `formatVersion`, `CliConfig.layer({ builtIns: [Help, Version] })`.
20+
- **401 body**: keep `{ ok: false, error }` — a `Schema.TaggedError` puts `_tag` on the wire. The middleware error is a plain `Schema.Struct` with `HttpApiSchema.status(401)`.
21+
- **Errors**: keep `SqlError` in the channel and catch it where the policy lives (best-effort visit); `SchemaError` on a row decode is a bug → `Effect.die`.
22+
- **One consumer → module.** `Patches` is a service here to show the shape; per the port map a capability with one consumer stays a module until a second appears.

‎packages/effect-slice/package.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
"private": true,
55
"license": "UNLICENSED",
66
"type": "module",
7-
"description": "PROTOTYPE — throwaway Effect 4 vertical slice for issue #55. Never shipped.",
7+
"description": "PROTOTYPE \u2014 throwaway Effect 4 vertical slice for issue #55. Never shipped.",
88
"scripts": {
99
"build": "node scripts/build-cli.mjs",
1010
"typecheck": "tsc -p tsconfig.json --noEmit",
@@ -15,6 +15,7 @@
1515
"@effect/platform-node": "catalog:",
1616
"@effect/sql-pg": "catalog:",
1717
"@patchy/core": "workspace:*",
18+
"@patchy/db": "workspace:*",
1819
"effect": "catalog:"
1920
},
2021
"devDependencies": {

‎packages/effect-slice/scripts/e2e.mjs‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,16 +87,25 @@ try {
8787

8888
const bad = await run(cli, ["whoami"], { PATCHY_API_URL: apiUrl, PATCHY_API_TOKEN: "wrong" });
8989
console.log("[whoami bad]", JSON.stringify(bad));
90-
assert.notEqual(bad.code, 0);
90+
assert.equal(bad.code, 1);
91+
assert.equal(bad.stdout, "");
92+
assert.match(bad.stderr, /Missing or invalid API token\./);
93+
assert.doesNotMatch(bad.stderr, /\n\s+at /, "stack trace leaked to the agent");
9194

9295
const noUrl = await run(cli, ["whoami"], { PATCHY_API_TOKEN: "x" });
9396
console.log("[whoami no url]", JSON.stringify(noUrl));
94-
assert.notEqual(noUrl.code, 0);
97+
assert.equal(noUrl.code, 1);
98+
assert.equal(noUrl.stdout, "");
99+
assert.match(noUrl.stderr, /PATCHY_API_URL/);
100+
assert.doesNotMatch(noUrl.stderr, /\n\s+at /, "stack trace leaked to the agent");
95101

96102
const help = await run(cli, ["--help"], {});
97103
console.log("[help]", JSON.stringify(help));
104+
assert.equal(help.code, 0);
105+
assert.doesNotMatch(help.stdout, /--wizard|--completions|--log-level/);
98106
const version = await run(cli, ["--version"], {});
99107
console.log("[version]", JSON.stringify(version));
108+
assert.equal(version.stdout.trim(), "0.0.1-slice");
100109
console.log("e2e core OK");
101110
} finally {
102111
server.kill("SIGTERM");

‎packages/effect-slice/src/api.ts‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
HttpApiEndpoint,
99
HttpApiGroup,
1010
HttpApiMiddleware,
11+
HttpApiSchema,
1112
HttpApiSecurity
1213
} from "effect/unstable/httpapi";
1314

@@ -20,11 +21,12 @@ export class Identity extends Schema.Class<Identity>("Identity")({
2021
scopes: Schema.Array(Schema.String)
2122
}) {}
2223

23-
export class Unauthorized extends Schema.TaggedError<Unauthorized>()(
24-
"Unauthorized",
25-
{ error: Schema.String },
26-
{ httpApiStatus: 401 }
27-
) {}
24+
/** Today's 401 body, byte for byte: `{ ok: false, error }`. Not a TaggedError — no `_tag` on the wire. */
25+
export const Unauthorized = Schema.Struct({
26+
ok: Schema.Literal(false),
27+
error: Schema.String
28+
}).pipe(HttpApiSchema.status(401));
29+
export type Unauthorized = typeof Unauthorized.Type;
2830

2931
export class CurrentIdentity extends Context.Service<CurrentIdentity, Identity>()(
3032
"@patchy/effect-slice/api/CurrentIdentity"

‎packages/effect-slice/src/auth/index.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import { sha256 } from "@patchy/core";
33
import { Effect, Layer, Redacted, Schema } from "effect";
44
import { SqlClient, SqlSchema } from "effect/unstable/sql";
5-
import { Authorization, CurrentIdentity, Identity, Unauthorized } from "../api.js";
5+
import { Authorization, CurrentIdentity, Identity } from "../api.js";
66

77
export { authMigrations } from "./migrations.js";
88

@@ -26,9 +26,12 @@ export const AuthorizationLive = Layer.effect(
2626
const findIdentity = yield* findIdentityByTokenHash;
2727
return Authorization.of({
2828
bearer: Effect.fn("Authorization.bearer")(function* (httpEffect, { credential }) {
29-
const identity = yield* findIdentity(sha256(Redacted.value(credential))).pipe(Effect.orDie);
29+
// A decode failure is a bug, not a bad token; a database failure is a 500, not a 401.
30+
const identity = yield* findIdentity(sha256(Redacted.value(credential))).pipe(
31+
Effect.catchTags({ SchemaError: Effect.die, SqlError: Effect.die })
32+
);
3033
if (identity._tag === "None") {
31-
return yield* new Unauthorized({ error: "Invalid API token." });
34+
return yield* Effect.fail({ ok: false as const, error: "Missing or invalid API token." });
3235
}
3336
return yield* Effect.provideService(httpEffect, CurrentIdentity, identity.value);
3437
})

‎packages/effect-slice/src/cli.ts‎

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44
* not this slice's question).
55
*/
66
import { NodeRuntime, NodeServices } from "@effect/platform-node";
7-
import { Config, Console, Effect, Option, Redacted } from "effect";
8-
import { Command, Flag } from "effect/unstable/cli";
7+
import { Config, Console, Effect, Layer, Option, Redacted } from "effect";
8+
import { CliConfig, CliError, CliOutput, Command, Flag, GlobalFlag } from "effect/unstable/cli";
99
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http";
1010
import { HttpApiClient, HttpApiMiddleware } from "effect/unstable/httpapi";
1111
import { Authorization, PatchyApi } from "./api.js";
@@ -22,6 +22,12 @@ const makeClient = (apiUrl: string, token: Redacted.Redacted) =>
2222
transformClient: HttpClient.mapRequest(HttpClientRequest.prependUrl(apiUrl))
2323
}).pipe(Effect.provide([authorizationClient(token), FetchHttpClient.layer]));
2424

25+
/** A missing setting is the agent's to fix: say which one, no stack. */
26+
const required = <A>(config: Config.Config<A>, userMessage: string) =>
27+
config.pipe(
28+
Effect.catchTags({ ConfigError: (cause) => new CliError.UserError({ cause, userMessage }) })
29+
);
30+
2531
const whoami = Command.make(
2632
"whoami",
2733
{
@@ -33,21 +39,42 @@ const whoami = Command.make(
3339
Effect.fn(function* ({ apiUrl }) {
3440
const resolvedUrl = Option.isSome(apiUrl)
3541
? apiUrl.value
36-
: yield* Config.string("PATCHY_API_URL");
37-
const token = yield* Config.redacted("PATCHY_API_TOKEN");
42+
: yield* required(Config.string("PATCHY_API_URL"), "Set PATCHY_API_URL or pass --api-url.");
43+
const token = yield* required(
44+
Config.redacted("PATCHY_API_TOKEN"),
45+
"Set PATCHY_API_TOKEN to the publishing token for this instance."
46+
);
3847
const client = yield* makeClient(resolvedUrl, token);
39-
const identity = yield* client
40-
.me()
41-
.pipe(Effect.catchTag("Unauthorized", (error) => Effect.die(new Error(error.error))));
48+
// Every failure an agent can act on becomes a one-line stderr message and exit 1.
49+
const identity = yield* client.me().pipe(
50+
Effect.catch(
51+
(error) =>
52+
new CliError.UserError({
53+
cause: error,
54+
userMessage:
55+
"ok" in error ? error.error : `Could not reach ${resolvedUrl}: ${error.message}`
56+
})
57+
)
58+
);
4259
yield* Console.log(`Account: ${identity.accountName} (${identity.accountId})`);
4360
yield* Console.log(`API token: ${identity.apiTokenName} (${identity.apiTokenId})`);
4461
yield* Console.log(`Scopes: ${identity.scopes.join(", ")}`);
4562
})
4663
).pipe(Command.withDescription("Check the configured Patchy Cloud credentials."));
4764

65+
/** Agent-facing surface: `--help`/`--version` only (no wizard, completions, log-level); bare version string. */
66+
const CliSurface = Layer.mergeAll(
67+
CliConfig.layer({ builtIns: [GlobalFlag.Help, GlobalFlag.Version] }),
68+
CliOutput.layer({
69+
...CliOutput.defaultFormatter(),
70+
formatVersion: (_name, version) => version,
71+
formatError: (error) => error.message
72+
})
73+
);
74+
4875
Command.make("patchy").pipe(
4976
Command.withSubcommands([whoami]),
5077
Command.run({ version: __PATCHY_VERSION__ }),
51-
Effect.provide(NodeServices.layer),
78+
Effect.provide([NodeServices.layer, CliSurface]),
5279
NodeRuntime.runMain
5380
);

‎packages/effect-slice/src/patches/index.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
/** The patches capability: find a draft's current version, record a visit. */
22
import { Context, DateTime, Effect, Layer, Option, Schema } from "effect";
33
import { SqlClient, SqlSchema } from "effect/unstable/sql";
4+
import type { SqlError } from "effect/unstable/sql/SqlError";
45

56
export { patchMigrations } from "./migrations.js";
67

@@ -14,8 +15,8 @@ export class ServedDraft extends Schema.Class<ServedDraft>("ServedDraft")({
1415
export class Patches extends Context.Service<
1516
Patches,
1617
{
17-
findCurrent(draftId: string): Effect.Effect<Option.Option<ServedDraft>>;
18-
recordVisit(draftId: string): Effect.Effect<void>;
18+
findCurrent(draftId: string): Effect.Effect<Option.Option<ServedDraft>, SqlError>;
19+
recordVisit(draftId: string): Effect.Effect<void, SqlError>;
1920
}
2021
>()("@patchy/effect-slice/patches/index/Patches") {
2122
static readonly layer = Layer.effect(
@@ -39,8 +40,9 @@ export class Patches extends Context.Service<
3940
});
4041

4142
return Patches.of({
42-
findCurrent: (draftId) => findCurrent(draftId).pipe(Effect.orDie),
43-
recordVisit: (draftId) => recordVisit(draftId).pipe(Effect.orDie)
43+
findCurrent: (draftId) =>
44+
findCurrent(draftId).pipe(Effect.catchTags({ SchemaError: Effect.die })),
45+
recordVisit
4446
});
4547
})
4648
);

‎packages/effect-slice/src/server.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,14 @@ const DraftRoute = HttpRouter.use((router) =>
3535
);
3636
}
3737
// Best-effort on purpose: a reader one header away from their page gets it.
38-
yield* patches.recordVisit(draftId!).pipe(Effect.ignoreCause);
39-
const draft = found.value;
38+
yield* patches
39+
.recordVisit(draftId!)
40+
.pipe(
41+
Effect.catchTags({ SqlError: (error) => Effect.logWarning("visit top-up failed", error) })
42+
);
43+
// The real page renders through `escapeHtml`; the headers are this slice's contract.
4044
return HttpServerResponse.html(
41-
`<!doctype html><title>${draft.title}</title><iframe src="/o/${draft.objectKey}"></iframe>`
45+
`<!doctype html><title>Patchy draft</title><p>${found.value.versionNumber}</p>`
4246
).pipe(
4347
HttpServerResponse.setHeaders({
4448
...headers,

‎packages/effect-slice/src/slice.test.ts‎

Lines changed: 61 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -14,22 +14,25 @@ import { SqlClient, SqlSchema } from "effect/unstable/sql";
1414
import { Authorization, PatchyApi } from "./api.js";
1515
import { AuthorizationLive } from "./auth/index.js";
1616
import { Patches } from "./patches/index.js";
17-
import { allMigrations, pgLayerFor, runMigrations } from "./sql.js";
17+
import { allMigrations, legacyMigrations, pgLayerFor, runMigrations } from "./sql.js";
1818
import { AppRoutes, DRAFT_CONTENT_SECURITY_POLICY, MeHandlers } from "./server.js";
1919
import { createEmptyPostgresDatabase } from "../../../test/postgres.js";
2020

21-
/** A fresh empty database, migrated by the slice's own Migrator, closed with the layer. */
22-
const MigratedPg = Layer.unwrap(
23-
Effect.gen(function* () {
24-
const database = yield* Effect.acquireRelease(
25-
Effect.promise(createEmptyPostgresDatabase),
26-
(database) => Effect.promise(database.drop)
27-
);
28-
return Layer.effectDiscard(runMigrations(allMigrations)).pipe(
29-
Layer.provideMerge(pgLayerFor(database.connectionString))
30-
);
31-
})
32-
);
21+
/** A fresh empty database, migrated by the given record through the slice's Migrator, dropped with the layer. */
22+
const migratedPg = (migrations: Parameters<typeof runMigrations>[0]) =>
23+
Layer.unwrap(
24+
Effect.gen(function* () {
25+
const database = yield* Effect.acquireRelease(
26+
Effect.promise(createEmptyPostgresDatabase),
27+
(database) => Effect.promise(database.drop)
28+
);
29+
return Layer.effectDiscard(runMigrations(migrations)).pipe(
30+
Layer.provideMerge(pgLayerFor(database.connectionString))
31+
);
32+
})
33+
);
34+
35+
const MigratedPg = migratedPg(allMigrations);
3336

3437
const seed = Effect.gen(function* () {
3538
const sql = yield* SqlClient.SqlClient;
@@ -41,6 +44,9 @@ const seed = Effect.gen(function* () {
4144
yield* sql`UPDATE drafts SET current_version_id = 'v_1' WHERE id = 'd_1'`;
4245
});
4346

47+
/** Seeded during layer construction, so no test depends on another having run. */
48+
const SeededPg = Layer.effectDiscard(seed).pipe(Layer.provideMerge(MigratedPg));
49+
4450
const bearer = (token: string) =>
4551
HttpApiMiddleware.layerClient(Authorization, ({ next, request }) =>
4652
next(HttpClientRequest.bearerToken(request, token))
@@ -75,14 +81,36 @@ it.layer(MigratedPg)("Migrator across packages", (it) => {
7581
);
7682
});
7783

84+
it.layer(migratedPg(legacyMigrations))("Migrator over today's SCHEMA_MIGRATIONS", (it) => {
85+
it.effect("runs every multi-statement DDL step and lands the current schema", () =>
86+
Effect.gen(function* () {
87+
const sql = yield* SqlClient.SqlClient;
88+
const applied =
89+
yield* sql`SELECT migration_id AS id FROM schema_migrations ORDER BY migration_id`;
90+
assert.deepStrictEqual(
91+
applied.map((row) => row.id),
92+
[1, 2, 3, 4, 5, 6]
93+
);
94+
const columns =
95+
yield* sql`SELECT column_name FROM information_schema.columns WHERE table_name = 'drafts' ORDER BY column_name`;
96+
assert.include(
97+
columns.map((row) => row.column_name),
98+
"expires_at"
99+
);
100+
assert.include(
101+
columns.map((row) => row.column_name),
102+
"pinned_at"
103+
);
104+
})
105+
);
106+
});
107+
78108
it.layer(
79109
Layer.mergeAll(MeHandlers, HttpServer.layerServices).pipe(
80110
Layer.provideMerge(AuthorizationLive),
81-
Layer.provideMerge(MigratedPg)
111+
Layer.provideMerge(SeededPg)
82112
)
83113
)("GET /api/me through HttpApiTest", (it) => {
84-
it.effect("seeds", () => seed);
85-
86114
it.effect("returns the identity for a live token", () =>
87115
Effect.gen(function* () {
88116
const client = yield* HttpApiTest.groups(PatchyApi, ["me"]);
@@ -104,22 +132,20 @@ it.layer(
104132
Effect.gen(function* () {
105133
const client = yield* HttpApiTest.groups(PatchyApi, ["me"]);
106134
const error = yield* client.me().pipe(Effect.flip);
107-
assert.strictEqual(error._tag, "Unauthorized");
135+
assert.deepStrictEqual(error, { ok: false, error: "Missing or invalid API token." });
108136
}).pipe(Effect.provide(bearer("nope")))
109137
);
110138
});
111139

112140
const ServedApp = HttpRouter.serve(AppRoutes).pipe(
113141
Layer.provideMerge(NodeHttpServer.layerTest),
114142
Layer.provideMerge(Patches.layer),
115-
Layer.provideMerge(MigratedPg)
143+
Layer.provideMerge(SeededPg)
116144
);
117145

118146
const LastVisited = Schema.Struct({ lastVisitedAt: Schema.NullOr(Schema.Date) });
119147

120148
it.layer(ServedApp)("GET /d/:draftId over a real socket", (it) => {
121-
it.effect("seeds", () => seed);
122-
123149
it.effect("serves the draft with the serving headers", () =>
124150
Effect.gen(function* () {
125151
const client = yield* HttpClient.HttpClient;
@@ -133,7 +159,7 @@ it.layer(ServedApp)("GET /d/:draftId over a real socket", (it) => {
133159
);
134160
assert.strictEqual(response.headers["cache-control"], "public, max-age=60");
135161
assert.strictEqual(response.headers["x-content-type-options"], "nosniff");
136-
assert.include(yield* response.text, "<title>Hello</title>");
162+
assert.include(yield* response.text, "<title>Patchy draft</title>");
137163
})
138164
);
139165

@@ -159,6 +185,20 @@ it.layer(ServedApp)("GET /d/:draftId over a real socket", (it) => {
159185
})
160186
);
161187

188+
it.effect("/api/me with a bad token is today's 401 body", () =>
189+
Effect.gen(function* () {
190+
const client = yield* HttpClient.HttpClient;
191+
const response = yield* client.execute(
192+
HttpClientRequest.get("/api/me").pipe(HttpClientRequest.bearerToken("nope"))
193+
);
194+
assert.strictEqual(response.status, 401);
195+
assert.deepStrictEqual(yield* response.json, {
196+
ok: false,
197+
error: "Missing or invalid API token."
198+
});
199+
})
200+
);
201+
162202
it.effect("a served page records its visit at the test clock's time", () =>
163203
Effect.gen(function* () {
164204
yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2030-01-02T03:04:05Z")));

0 commit comments

Comments
 (0)