Open History to see the last commit
1import * as DynamoDB from "alchemy/AWS/DynamoDB";
2import * as Lambda from "alchemy/AWS/Lambda";
3import * as S3 from "alchemy/AWS/S3";
4import * as SQS from "alchemy/AWS/SQS";
5import * as RemovalPolicy from "alchemy/RemovalPolicy";
6import { Stack } from "alchemy/Stack";
7import * as Console from "effect/Console";
8import * as Context from "effect/Context";
9import * as Data from "effect/Data";
10import * as Effect from "effect/Effect";
11import * as Layer from "effect/Layer";
12import * as Stream from "effect/Stream";
13
14import type { Job } from "./Job.ts";
15
16export class PutJobError extends Data.TaggedError("PutJobError")<{
17 readonly message: string;
18 readonly cause?: unknown;
19}> {}
20
21export class GetJobError extends Data.TaggedError("GetJobError")<{
22 readonly message: string;
23 readonly cause?: unknown;
24}> {}
25
26export class JobStorage extends Context.Service<
27 JobStorage,
28 {
29 putJob(job: Job): Effect.Effect<Job, PutJobError>;
30 getJob(jobId: string): Effect.Effect<Job | undefined, GetJobError>;
31 }
32>()("JobStorage") {}
33
34export const JobStorageDynamoDB = Layer.provideMerge(
35 Layer.effect(
36 JobStorage,
37 Effect.gen(function* () {
38 const stack = yield* Stack;
39 const table = yield* DynamoDB.Table("JobsTable", {
40 partitionKey: "id",
41 attributes: {
42 id: "S",
43 },
44 });
45 const queue = yield* SQS.Queue("JobsQueue").pipe(
46 RemovalPolicy.retain(stack.stage === "prod"),
47 );
48
49 const getItem = yield* DynamoDB.GetItem.bind(table);
50 const putItem = yield* DynamoDB.PutItem.bind(table);
51 const sink = yield* SQS.QueueSink.bind(queue);
52
53 yield* DynamoDB.stream(table, {
54 streamViewType: "NEW_AND_OLD_IMAGES",
55 startingPosition: "LATEST",
56 batchSize: 10,
57 }).process((stream) =>
58 stream.pipe(
59 Stream.map((record) =>
60 JSON.stringify({
61 eventName: record.eventName,
62 keys: record.dynamodb.Keys,
63 newImage: record.dynamodb.NewImage,
64 oldImage: record.dynamodb.OldImage,
65 }),
66 ),
67 Stream.run(sink),
68 ),
69 );
70
71 const putJob = (job: Job) =>
72 putItem({
73 Item: {
74 id: { S: job.id },
75 content: { S: job.content },
76 },
77 }).pipe(
78 Effect.map(() => job),
79 Effect.tapError(Console.log),
80 Effect.catchCause((cause) =>
81 Effect.fail(
82 new PutJobError({
83 message: `Failed to store job "${job.id}": ${cause}`,
84 cause,
85 }),
86 ),
87 ),
88 );
89
90 const getJob = (jobId: string) =>
91 getItem({
92 Key: {
93 id: { S: jobId },
94 },
95 }).pipe(
96 Effect.flatMap((item) =>
97 item.Item
98 ? Effect.try({
99 try: () =>
100 ({
101 id: item.Item?.id?.S ?? jobId,
102 content: item.Item?.content?.S ?? "",
103 }) as Job,
104 catch: (cause) =>
105 new GetJobError({
106 message: `Failed to parse job "${jobId}": ${cause}`,
107 cause,
108 }),
109 })
110 : Effect.succeed(undefined),
111 ),
112 Effect.tapError(Console.log),
113 Effect.catchCause((cause) =>
114 Effect.fail(
115 new GetJobError({
116 message: `Failed to load job "${jobId}": ${cause}`,
117 cause,
118 }),
119 ),
120 ),
121 );
122
123 return JobStorage.of({
124 putJob,
125 getJob,
126 });
127 }),
128 ),
129 Layer.mergeAll(Lambda.TableEventSource, SQS.QueueSinkLive).pipe(
130 Layer.provideMerge(
131 Layer.mergeAll(
132 DynamoDB.GetItemLive,
133 DynamoDB.PutItemLive,
134 SQS.SendMessageBatchLive,
135 ),
136 ),
137 ),
138);
139
140export const JobStorageS3 = Layer.provideMerge(
141 Layer.effect(
142 JobStorage,
143 Effect.gen(function* () {
144 const stack = yield* Stack;
145 const bucket = yield* S3.Bucket("JobsBucket");
146 const queue = yield* SQS.Queue("JobsQueue").pipe(
147 RemovalPolicy.retain(stack.stage === "prod"),
148 );
149
150 const getObject = yield* S3.GetObject.bind(bucket);
151 const putObject = yield* S3.PutObject.bind(bucket);
152 const sink = yield* SQS.QueueSink.bind(queue);
153
154 const putJob = (job: Job) =>
155 putObject({
156 Key: job.id,
157 Body: JSON.stringify(job),
158 }).pipe(
159 Effect.map(() => job),
160 Effect.tapError(Console.log),
161 Effect.catchCause((cause) =>
162 Effect.fail(
163 new PutJobError({
164 message: `Failed to store job "${job.id}": ${cause}`,
165 cause,
166 }),
167 ),
168 ),
169 );
170
171 const getJob = (jobId: string) =>
172 getObject({
173 Key: jobId,
174 }).pipe(
175 Effect.catchTag("NoSuchKey", () => Effect.succeed(undefined)),
176 Effect.flatMap(
177 (item) =>
178 item?.Body?.pipe(
179 Stream.decodeText,
180 Stream.mkString,
181 Effect.flatMap((body) =>
182 Effect.try({
183 try: () => JSON.parse(body) as Job,
184 catch: (cause) =>
185 new GetJobError({
186 message: `Failed to parse job "${jobId}": ${cause}`,
187 cause,
188 }),
189 }),
190 ),
191 ) ?? Effect.succeed(undefined),
192 ),
193 Effect.tapError(Console.log),
194 Effect.catchCause((cause) =>
195 Effect.fail(
196 new GetJobError({
197 message: `Failed to load job "${jobId}": ${cause}`,
198 cause,
199 }),
200 ),
201 ),
202 );
203
204 yield* S3.notifications(bucket).subscribe((stream) =>
205 stream.pipe(
206 Stream.flatMap((item) =>
207 Stream.fromEffect(getJob(item.key).pipe(Effect.orDie)),
208 ),
209 Stream.filter((job): job is Job => job !== undefined),
210 Stream.map((job) => JSON.stringify(job)),
211 Stream.run(sink),
212 ),
213 );
214
215 return JobStorage.of({
216 putJob,
217 getJob,
218 });
219 }),
220 ),
221 Layer.mergeAll(Lambda.BucketEventSource, SQS.QueueSinkLive).pipe(
222 Layer.provideMerge(
223 Layer.mergeAll(
224 S3.GetObjectLive,
225 S3.PutObjectLive,
226 SQS.SendMessageBatchLive,
227 ),
228 ),
229 ),
230);