Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions .brain/data/git-snapshot.json

Large diffs are not rendered by default.

10 changes: 10 additions & 0 deletions .env.schema
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,16 @@ PREVIEW_ORIGIN=
# @sensitive=false
AUTH_ENABLED=false

# Optional absolute path to an already built Institute dist directory. Unset declares no Institute.
# @type=string
# @sensitive=false
INSTITUTE_ARTIFACT=

# Enable Mischief dispatch only if an Institute service binding is also present.
# @type=boolean
# @sensitive=false
INSTITUTE_ENABLED=false

# Native Effect tracing is opt-in. Cloudflare owns head sampling and export.
# @type=boolean
# @sensitive=false
Expand Down
51 changes: 34 additions & 17 deletions apps/infra/alchemy.run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,36 @@ import * as Redacted from "effect/Redacted";
import * as Schema from "effect/Schema";

import privateAuth from "../site/src/auth/private-worker.js";
import { instituteStage } from "../site/src/institute-mount.js";
import Mischief from "../site/src/worker.js";
import Workshop from "../site/src/workshop-worker.js";
import { Website } from "../web/src/website.js";
import { instituteWorker } from "./src/institute.js";
import { ratstackState } from "./src/state-store.js";

const gateway = Effect.gen(function* declareGateway() {
const website = yield* Website;
const mischief = yield* Mischief;

yield* mischief.bind`${website}`({
bindings: [
{ name: "WEBSITE", service: website.workerName, type: "service" },
],
});

const institute = yield* instituteWorker;

if (institute !== null) {
yield* mischief.bind`${institute}`({
bindings: [
{ name: "INSTITUTE", service: institute.workerName, type: "service" },
],
});
}

return { mischiefUrl: mischief.url, websiteUrl: website.url };
});

export default Alchemy.Stack(
"RatStack",
{
Expand All @@ -30,6 +55,12 @@ export default Alchemy.Stack(
state: ratstackState(),
},
Effect.gen(function* stack() {
const stage = yield* Stage;

if (stage === instituteStage) {
return { ...(yield* gateway), catalogUrl: undefined };
}

const dev = yield* Alchemy.ALCHEMY_DEV;

if (!dev) {
Expand Down Expand Up @@ -157,28 +188,14 @@ export default Alchemy.Stack(
);
}

const website = yield* Website;

const mischief = yield* Mischief;
const gatewayUrls = yield* gateway;

yield* Workshop;
yield* turboCache;

const catalog = yield* CatalogWorker.pipe(
retain(Stage.pipe(Effect.map((stage) => stage === "prod")))
);

yield* mischief.bind`${website}`({
bindings: [
{ name: "WEBSITE", service: website.workerName, type: "service" },
],
});
const catalog = yield* CatalogWorker.pipe(retain(stage === "prod"));

return {
catalogUrl: catalog.url,
mischiefUrl: mischief.url,
websiteUrl: website.url,
};
return { ...gatewayUrls, catalogUrl: catalog.url };
}).pipe(
Effect.provide(
Layer.unwrap(
Expand Down
35 changes: 35 additions & 0 deletions apps/infra/src/institute.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import * as Cloudflare from "@alchemy.run/cloudflare";
import { Config, Effect, Option, Path, Schema } from "effect";

import { silentObservability } from "../../site/src/observability.js";

export const instituteWorker = Effect.gen(function* declareInstitute() {
const path = yield* Path.Path;

const artifact = yield* Config.option(
Config.schema(
Schema.String.check(
Schema.makeFilter((directory) => path.isAbsolute(directory))
),
"INSTITUTE_ARTIFACT"
)
);

if (Option.isSome(artifact)) {
return yield* Cloudflare.Worker("Institute", {
assets: {
directory: path.join(artifact.value, "client"),
notFoundHandling: "none",
runWorkerFirst: ["/institute/content/*"],
},
bundle: false,
compatibility: { date: "2026-05-25", flags: ["nodejs_compat"] },
main: path.join(artifact.value, "server/index.js"),
observability: silentObservability,
rules: [{ globs: ["**/*.js", "**/*.mjs"] }],
workersDev: { enabled: false, previewsEnabled: false },
});
}

return null;
});
217 changes: 217 additions & 0 deletions apps/infra/test/institute-binding.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,217 @@
import * as Cloudflare from "@alchemy.run/cloudflare";
import { NodeServices } from "@effect/platform-node";
import { expect, it } from "@effect/vitest";
import { AuthProviders, Stage } from "alchemy";
import { AlchemyContextLive } from "alchemy/AlchemyContext";
import {
Artifacts,
createArtifactStore,
makeScopedArtifacts,
} from "alchemy/Artifacts";
import * as Output from "alchemy/Output";
import {
ConfigProvider,
Effect,
FileSystem,
Layer,
Path,
Schema,
} from "effect";
import * as Digest from "effect/crypto/Digest";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as HttpClient from "effect/http/HttpClient";

import { instituteStage } from "../../site/src/institute-mount.js";
import stack from "../alchemy.run.js";

const services = Layer.mergeAll(
AlchemyContextLive,
Layer.succeed(AuthProviders, {}),
Layer.succeed(
HttpClient.HttpClient,
HttpClient.make(() =>
Effect.die("Institute declarations must not call the provider")
)
)
).pipe(
Layer.provideMerge(
Layer.mergeAll(
NodeServices.layer,
SecureRandom.layerWebCrypto,
Digest.layerWebCrypto
)
)
);

const compile = (stage: string, artifact?: string) =>
stack.pipe(
Effect.provide(services),
Effect.provideService(Stage, stage),
Effect.provide(
ConfigProvider.layer(
ConfigProvider.fromUnknown({
EMAIL_FORWARD_TO: "forward@example.test",
INSTITUTE_ARTIFACT: artifact,
INSTITUTE_ENABLED: artifact !== undefined,
})
)
)
);

it.effect(
"does not change Mischief bindings or declare Institute without an artifact",
() =>
Effect.gen(function* checkDefault() {
const compiled = yield* compile("prod");
expect(compiled.resources.Institute).toBeUndefined();
expect(compiled.resources.Mischief?.Props).not.toHaveProperty(
"env.INSTITUTE_ENABLED"
);
expect(
compiled.bindings.Mischief?.some(
(binding) => binding.sid === "Institute"
)
).toBe(false);
})
);

const InstituteProps = Schema.Struct({
assets: Schema.Struct({
base: Schema.optionalKey(Schema.String),
directory: Schema.String,
notFoundHandling: Schema.Literal("none"),
runWorkerFirst: Schema.Array(Schema.String),
}),
bundle: Schema.Literal(false),
main: Schema.String,
rules: Schema.Array(Schema.Struct({ globs: Schema.Array(Schema.String) })),
});

it.effect(
"binds the prebuilt modules and mounted assets without creating a public stage or declaring production DNS",
() =>
Effect.gen(function* checkMount() {
const fs = yield* FileSystem.FileSystem;
const { join } = yield* Path.Path;

const artifact = yield* fs.makeTempDirectoryScoped({
prefix: "institute-dist-",
});

yield* fs.makeDirectory(join(artifact, "server/assets"), {
recursive: true,
});
yield* fs.makeDirectory(join(artifact, "client/institute/content"), {
recursive: true,
});
yield* fs.writeFileString(
join(artifact, "server/index.js"),
'export { default } from "./assets/ssr.js";'
);
yield* fs.writeFileString(
join(artifact, "server/assets/ssr.js"),
'export default { fetch: () => new Response("institute") };'
);
yield* fs.writeFileString(join(artifact, "server/index.js.map"), "{}");
yield* fs.writeFileString(join(artifact, "server/wrangler.json"), "{}");
yield* fs.writeFileString(
join(artifact, "client/institute/content/manifest.json"),
"{}"
);

const compiled = yield* compile(instituteStage, artifact);

expect(compiled.resources.Workshop).toBeUndefined();
expect(compiled.resources.Mischief?.Props).toHaveProperty(
"env.INSTITUTE_ENABLED",
"true"
);
expect(
Object.values(compiled.resources).filter((resource) =>
/^Cloudflare\.(?:DNS\.|Email\.|Zone$)/u.test(resource.Type)
)
).toEqual([]);

for (const id of ["Institute", "Mischief"]) {
const props: unknown = compiled.resources[id]?.Props;
expect(props).toMatchObject({
workersDev: { enabled: false, previewsEnabled: false },
});
expect(props).not.toHaveProperty("domain");
expect(props).not.toHaveProperty("routes");
}

const binding = yield* Schema.decodeUnknownEffect(
Schema.Struct({
bindings: Schema.Tuple([
Schema.Struct({
name: Schema.Literal("INSTITUTE"),
service: Schema.Unknown,
type: Schema.Literal("service"),
}),
]),
})
)(
compiled.bindings.Mischief?.find((entry) => entry.sid === "Institute")
?.data
);

expect(
Output.resolveUpstream(binding.bindings[0].service)
).toHaveProperty("Institute");
expect(
compiled.bindings.Mischief?.find((entry) => entry.sid === "Website")
?.data
).toMatchObject({
bindings: [{ name: "WEBSITE", type: "service" }],
});

const props = yield* Schema.decodeUnknownEffect(InstituteProps)(
compiled.resources.Institute?.Props
);

const workerProps = {
...props,
assets: {
...props.assets,
runWorkerFirst: [...props.assets.runWorkerFirst],
},
rules: [...props.rules],
} satisfies Cloudflare.Workers.WorkerProps;

const source = yield* Cloudflare.Workers.resolveSource(workerProps);

const output = yield* source.build(
Cloudflare.Workers.makeSourceContext({
compatibility: { date: "2026-05-25", flags: ["nodejs_compat"] },
fqn: "Institute",
id: "Institute",
props: workerProps,
stack: { name: "RatStack", stage: instituteStage },
workerName: "fixture-institute",
})
);

expect(output.bundle?.files.map((file) => file.path)).toEqual([
"index.js",
"assets/ssr.js",
]);

const assets = yield* Cloudflare.Workers.readAssets(workerProps.assets);

expect(Object.keys(assets.manifest)).toEqual([
"/institute/content/manifest.json",
]);
expect(workerProps.assets.runWorkerFirst).toEqual([
"/institute/content/*",
]);
}).pipe(
Effect.provide(services),
Effect.provideServiceEffect(
Artifacts,
Effect.sync(() =>
makeScopedArtifacts(createArtifactStore(), "Institute")
)
)
)
);
Loading
Loading