Repository navigation
Expand file tree
/
Copy pathalchemy.run.ts
More file actions
230 lines (215 loc) · 8.29 KB
/
Copy pathalchemy.run.ts
File metadata and controls
230 lines (215 loc) · 8.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import * as Alchemy from "alchemy"
import * as Cloudflare from "@alchemy.run/cloudflare"
import * as Command from "alchemy/Command"
import * as GitHub from "@alchemy.run/github"
import * as Output from "alchemy/Output"
import * as Mixedbread from "@website/alchemy-mixedbread"
import { TURNSTILE_TEST_KEYS } from "./apps/web/src/features/motw-vote/turnstile-test-keys.ts"
import * as Config from "effect/Config"
import * as Effect from "effect/Effect"
import * as Layer from "effect/Layer"
import * as Option from "effect/Option"
import * as Redacted from "effect/Redacted"
const productionStoreId = Config.Redacted("MXBAI_VECTOR_STORE_ID")
// Each stage counts in its own rate-limit namespace, so a preview cannot use up
// the production limit. Namespaces are numbers.
const rateLimitNamespaceId = (stage: string): number => {
let hash = 0
for (const char of stage) hash = (hash * 31 + char.charCodeAt(0)) % 90_000
return 1_000 + hash
}
const Website = (
// The store a preview searches next to production. None outside previews
// whose search content changed.
overlayStoreId: Option.Option<Output.Output<string>>,
searchApiKey: Config.Config<Redacted.Redacted<string>>,
) =>
Cloudflare.Website.Astro(
"WebsiteWorker",
Effect.gen(function* () {
const stage = yield* Alchemy.Stage
// Module of the Week votes. Previews get their own empty database, which
// goes away with the preview. Production keeps its votes if the stack is
// ever destroyed.
const motwVote = yield* Cloudflare.D1.Database("MotwVote", {
migrations: "./apps/web/migrations",
}).pipe(Alchemy.RemovalPolicy.retain(stage === "prod"))
// Signs the cookie that tells voters apart. It is made once per stage and
// kept in the deploy state.
const votesSecret = yield* Alchemy.Random("MotwVoteSecret")
// The invisible human check votes need. Production gets a real widget.
// Other stages use Cloudflare's test keys, whose check always passes,
// because a widget only runs on the hostnames it lists.
const turnstile =
stage === "prod"
? yield* Cloudflare.Turnstile.Widget("MotwVoteTurnstile", {
domains: ["effect.website"],
mode: "invisible",
})
: undefined
return {
rootDir: "./apps/web",
memo: {
include: [
".alchemy-build-input.json",
".data/api-reference/**",
"src/**",
"public/**",
"astro.config.ts",
"package.json",
"tsconfig.json",
],
exclude: ["dist/**", ".astro/**", "node_modules/**"],
lockfile: true,
workspaces: "auto" as const,
},
astro: { output: "static" as const },
assets: {
htmlHandling: "drop-trailing-slash" as const,
// Route the PostHog proxy through the Worker before the asset layer.
runWorkerFirst: ["/_ingest/*"],
},
...(stage === "prod"
? {
domain: {
name: "effect.website",
redirects: ["www.effect.website"],
},
routes: [],
}
: {}),
workersDev: true,
dev: { port: 14337, strictPort: true },
cache: {
enabled: true,
crossVersionCache: true,
},
env: {
MXBAI_API_KEY: searchApiKey,
MXBAI_VECTOR_STORE_ID: productionStoreId,
...Option.match(overlayStoreId, {
onNone: () => ({}),
onSome: (id) => ({ MXBAI_OVERLAY_STORE_ID: id }),
}),
KV_REST_API_URL: Config.Redacted("KV_REST_API_URL"),
KV_REST_API_TOKEN: Config.Redacted("KV_REST_API_TOKEN"),
DB: motwVote,
MOTW_VOTE_SECRET: votesSecret.text,
TURNSTILE_SITE_KEY: turnstile?.sitekey ?? TURNSTILE_TEST_KEYS.siteKey,
TURNSTILE_SECRET:
turnstile?.secret ?? Redacted.make(TURNSTILE_TEST_KEYS.secret),
// 20 votes a minute for each client address
MOTW_VOTE_LIMIT: Cloudflare.RateLimit("MOTW_VOTE_LIMIT", {
namespaceId: rateLimitNamespaceId(stage),
simple: { limit: 20, period: 60 },
}),
},
sessionKVBindingName: false,
prerenderEnvironment: "node" as const,
}
}),
)
export default Alchemy.Stack(
"EffectWebsite",
{
providers: Layer.mergeAll(
Cloudflare.providers(),
GitHub.providers(),
Mixedbread.providers(),
),
state: Cloudflare.state(),
},
Effect.gen(function* () {
const pullRequest = yield* Config.option(Config.Int("PULL_REQUEST"))
const previewStoreEnabled = yield* Config.Boolean(
"MXBAI_PREVIEW_STORE_ENABLED",
).pipe(Config.withDefault(false))
const sha = yield* Config.String("WEBSITE_REVISION")
let overlayStoreId = Option.none<Output.Output<string>>()
let searchApiKey = Config.Redacted("MXBAI_API_KEY")
// Set when the preview has its own search store, to the synchronization
// the preview comment waits for.
let searchSynchronized: Output.Output<unknown> | undefined
if (previewStoreEnabled && Option.isSome(pullRequest)) {
const store = yield* Mixedbread.VectorStore("PreviewSearchStore", {
name: `effect-website-pr-${pullRequest.value}`,
description: `Effect website search preview for PR ${pullRequest.value}`,
expiresAfter: { anchor: "last_active_at", days: 7 },
tags: ["effect-website-preview"],
metadata: {
lifecycle: "pull-request-preview",
pullRequest: pullRequest.value,
repository: "Effect-TS/website",
},
config: {
contextualization: {
with_file_context: true,
with_metadata: ["file_path"],
},
},
})
const synchronization = yield* Command.Exec("SynchronizePreviewSearch", {
command: `vp exec mixedbread sync --pr ${pullRequest.value} --sha ${sha}`,
env: {
MXBAI_VECTOR_STORE_ID: store.id,
MXBAI_PRODUCTION_STORE_ID: productionStoreId,
},
memo: {
include: [
"apps/web/src/content/docs/**",
"apps/web/src/content/blog/**",
"apps/web/src/content.config.ts",
"apps/web/.data/api-reference/**",
"apps/web/src/features/api-reference/**",
"apps/web/src/features/search/domain.ts",
"packages/api-reference/**",
"packages/domain/**",
"packages/mixedbread/**",
"pnpm-lock.yaml",
],
},
timeout: "30 minutes",
})
// The Worker only needs the store's ID, so the website builds while the
// store synchronizes.
overlayStoreId = Option.some(store.id)
searchSynchronized = synchronization.hash.input
// The production search key is scoped to the production store. Mixedbread
// only issues API keys from its web app, so previews share a key created
// there. It needs search on the production store and on the tag
// `effect-website-preview`, plus read on that tag for the preview store's
// metadata, which lists the production files the preview hides.
searchApiKey = Config.Redacted("MXBAI_PREVIEW_SEARCH_API_KEY")
}
const website = yield* Website(overlayStoreId, searchApiKey)
yield* Option.match(pullRequest, {
onNone: () => Effect.void,
onSome: (issueNumber) =>
Effect.gen(function* () {
// Only announce the preview once its search reflects the pull request.
const url =
searchSynchronized === undefined
? website.url
: Output.all(website.url, searchSynchronized).pipe(
Output.map(([url]) => url),
)
yield* GitHub.Comment("preview-comment", {
owner: "Effect-TS",
repository: "website",
issueNumber,
body: Output.interpolate`
## Cloudflare Preview
**URL:** ${url}
Built from commit [${sha.slice(0, 7)}](https://github.com/Effect-TS/website/commit/${sha}).
---
_This comment updates automatically with each deployment._
`,
})
}),
})
return {
workerName: website.workerName,
websiteUrl: website.url,
}
}),
)