@gaganref/confect-alchemy 10.6.0-fork.23 → 10.6.0-fork.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,253 @@
1
+ import type {
2
+ UsageLimitMetric,
3
+ UsageLimitType,
4
+ UsageLimitWindow,
5
+ } from "@convex-dev/platform/deploymentApi";
6
+ import { OwnedBySomeoneElse, Unowned } from "alchemy/AdoptPolicy";
7
+ import { isResolved } from "alchemy/Diff";
8
+ import * as Provider from "alchemy/Provider";
9
+ import { Resource } from "alchemy/Resource";
10
+ import * as Array from "effect/Array";
11
+ import * as Effect from "effect/Effect";
12
+ import * as Option from "effect/Option";
13
+ import * as Schema from "effect/Schema";
14
+
15
+ import { ConvexClient, type UsageLimitInput } from "./ConvexClient.js";
16
+ import type { Providers } from "./Providers.js";
17
+ import { checkpointCreate, shouldAdopt } from "./internal/Lifecycle.js";
18
+
19
+ export interface UsageLimitProps {
20
+ readonly deployment: { readonly name: string; readonly url: string };
21
+ readonly metric: UsageLimitMetric;
22
+ readonly window: UsageLimitWindow;
23
+ readonly limit: number;
24
+ readonly limitType?: UsageLimitType;
25
+ readonly enabled?: boolean;
26
+ }
27
+
28
+ export interface UsageLimitAttributes {
29
+ readonly deployment: { readonly name: string; readonly url: string };
30
+ readonly id: string;
31
+ readonly metric: UsageLimitMetric;
32
+ readonly window: UsageLimitWindow;
33
+ readonly limit: number;
34
+ readonly limitType: UsageLimitType;
35
+ readonly enabled: boolean;
36
+ }
37
+
38
+ export type UsageLimit = Resource<
39
+ "Convex.UsageLimit",
40
+ UsageLimitProps,
41
+ UsageLimitAttributes,
42
+ never,
43
+ Providers
44
+ >;
45
+ export const UsageLimit = Resource<UsageLimit>("Convex.UsageLimit");
46
+
47
+ export class UsageLimitTargetChange extends Schema.TaggedError<
48
+ UsageLimitTargetChange,
49
+ { readonly brand: unique symbol }
50
+ >()("UsageLimitTargetChange", { deploymentName: Schema.String }) {}
51
+
52
+ export class AmbiguousUsageLimit extends Schema.TaggedError<
53
+ AmbiguousUsageLimit,
54
+ { readonly brand: unique symbol }
55
+ >()("AmbiguousUsageLimit", {
56
+ deploymentName: Schema.String,
57
+ metric: Schema.String,
58
+ window: Schema.String,
59
+ limitType: Schema.String,
60
+ limitIds: Schema.Array(Schema.String),
61
+ }) {
62
+ override get message() {
63
+ return `Usage limit ${this.metric}/${this.window}/${this.limitType} on ${this.deploymentName} matches multiple ids: ${Array.join(this.limitIds, ", ")}.`;
64
+ }
65
+ }
66
+
67
+ export class InvalidUsageLimit extends Schema.TaggedError<
68
+ InvalidUsageLimit,
69
+ { readonly brand: unique symbol }
70
+ >()("InvalidUsageLimit", { limit: Schema.String }) {
71
+ override get message() {
72
+ return `Usage limit ${this.limit} must be a positive safe integer.`;
73
+ }
74
+ }
75
+
76
+ export class UnsupportedLocalUsageLimit extends Schema.TaggedError<
77
+ UnsupportedLocalUsageLimit,
78
+ { readonly brand: unique symbol }
79
+ >()("UnsupportedLocalUsageLimit", {}) {
80
+ override get message() {
81
+ return "Declare Convex.UsageLimit only for cloud stages.";
82
+ }
83
+ }
84
+
85
+ const validateLimit = Effect.fn("UsageLimit.validateLimit")(function* (
86
+ limit: number,
87
+ ) {
88
+ if (!Number.isSafeInteger(limit) || limit < 1)
89
+ return yield* InvalidUsageLimit.make({ limit: String(limit) });
90
+ });
91
+
92
+ const desired = (props: UsageLimitProps): UsageLimitInput => ({
93
+ metric: props.metric,
94
+ window: props.window,
95
+ limit: props.limit,
96
+ limitType: props.limitType ?? "warning",
97
+ enabled: props.enabled ?? true,
98
+ });
99
+ const sameTarget = (current: UsageLimitAttributes, props: UsageLimitProps) =>
100
+ current.deployment.name === props.deployment.name;
101
+ const sameConfig = (current: UsageLimitInput, input: UsageLimitInput) =>
102
+ current.metric === input.metric &&
103
+ current.window === input.window &&
104
+ current.limitType === input.limitType &&
105
+ current.limit === input.limit &&
106
+ current.enabled === input.enabled;
107
+
108
+ const ownershipConflict = (
109
+ input: Pick<UsageLimitInput, "metric" | "window" | "limitType">,
110
+ ) => {
111
+ const physicalName = `${input.metric}/${input.window}/${input.limitType}`;
112
+ return new OwnedBySomeoneElse({
113
+ message: `Usage limit ${physicalName} already exists on this deployment. Declare one limit per metric, window and type. Re-run with --adopt or adopt(true) to take it over.`,
114
+ resourceType: UsageLimit.Type,
115
+ physicalName,
116
+ });
117
+ };
118
+
119
+ export const provider = Effect.gen(function* () {
120
+ const client = yield* ConvexClient;
121
+ const find = Effect.fn("UsageLimit.find")(function* (
122
+ output: UsageLimitAttributes,
123
+ url = output.deployment.url,
124
+ ) {
125
+ const limits = yield* client
126
+ .listUsageLimits(url)
127
+ .pipe(Effect.catchTag("ConvexNotFound", () => Effect.succeed([])));
128
+ return Option.getOrUndefined(
129
+ Array.findFirst(limits, (limit) => limit.id === output.id),
130
+ );
131
+ });
132
+ const findMatching = Effect.fn("UsageLimit.findMatching")(function* (
133
+ deployment: UsageLimitProps["deployment"],
134
+ input: Pick<UsageLimitInput, "metric" | "window" | "limitType">,
135
+ ) {
136
+ const limits = yield* client
137
+ .listUsageLimits(deployment.url)
138
+ .pipe(Effect.catchTag("ConvexNotFound", () => Effect.succeed([])));
139
+ const matches = Array.filter(
140
+ limits,
141
+ (limit) =>
142
+ limit.metric === input.metric &&
143
+ limit.window === input.window &&
144
+ limit.limitType === input.limitType,
145
+ );
146
+ if (matches.length > 1)
147
+ return yield* AmbiguousUsageLimit.make({
148
+ deploymentName: deployment.name,
149
+ ...input,
150
+ limitIds: Array.map(matches, (limit) => limit.id),
151
+ });
152
+ return matches[0];
153
+ });
154
+ return {
155
+ diff: Effect.fn("UsageLimit.diff")(function* ({ news, output }) {
156
+ if (!isResolved(news)) return;
157
+ yield* validateLimit(news.limit);
158
+ if (output === undefined) return;
159
+ if (!sameTarget(output, news)) return { action: "replace" };
160
+ const current = yield* find(output, news.deployment.url);
161
+ if (
162
+ output.deployment.url !== news.deployment.url ||
163
+ current === undefined ||
164
+ !sameConfig(current, desired(news))
165
+ )
166
+ return { action: "update" };
167
+ }),
168
+ read: Effect.fn("UsageLimit.read")(function* ({ fqn, olds, output }) {
169
+ if (output === undefined) {
170
+ if (olds.limit !== undefined) yield* validateLimit(olds.limit);
171
+ if (
172
+ olds.deployment === undefined ||
173
+ olds.metric === undefined ||
174
+ olds.window === undefined
175
+ )
176
+ return;
177
+ const input = {
178
+ metric: olds.metric,
179
+ window: olds.window,
180
+ limitType: olds.limitType ?? "warning",
181
+ };
182
+ const current = yield* findMatching(olds.deployment, input);
183
+ if (current !== undefined && !(yield* shouldAdopt(fqn)))
184
+ yield* Effect.logWarning(ownershipConflict(input).message);
185
+ return current === undefined
186
+ ? undefined
187
+ : Unowned({ deployment: olds.deployment, ...current });
188
+ }
189
+ const current = yield* find(output);
190
+ return current === undefined
191
+ ? undefined
192
+ : { deployment: output.deployment, ...current };
193
+ }),
194
+ reconcile: Effect.fn("UsageLimit.reconcile")(function* ({
195
+ fqn,
196
+ instanceId,
197
+ news,
198
+ output,
199
+ }) {
200
+ yield* validateLimit(news.limit);
201
+ if (output === undefined) yield* checkpointCreate(fqn, instanceId, news);
202
+ if (output !== undefined && !sameTarget(output, news))
203
+ return yield* UsageLimitTargetChange.make({
204
+ deploymentName: output.deployment.name,
205
+ });
206
+ const input = desired(news);
207
+ let current =
208
+ output === undefined
209
+ ? undefined
210
+ : yield* find(output, news.deployment.url);
211
+ if (current === undefined) {
212
+ const existing = yield* findMatching(news.deployment, input);
213
+ if (existing !== undefined && !(yield* shouldAdopt(fqn)))
214
+ return yield* ownershipConflict(input);
215
+ current = existing;
216
+ }
217
+ if (current !== undefined) {
218
+ yield* checkpointCreate(fqn, instanceId, news, {
219
+ deployment: news.deployment,
220
+ ...current,
221
+ });
222
+ const updated = sameConfig(current, input)
223
+ ? current
224
+ : yield* client.updateUsageLimit(
225
+ news.deployment.url,
226
+ current.id,
227
+ input,
228
+ );
229
+ return { deployment: news.deployment, ...updated };
230
+ }
231
+ const created = yield* client.createUsageLimit(
232
+ news.deployment.url,
233
+ input,
234
+ );
235
+ const attributes = { deployment: news.deployment, ...created };
236
+ yield* checkpointCreate(fqn, instanceId, news, attributes);
237
+ return attributes;
238
+ }),
239
+ delete: Effect.fn("UsageLimit.delete")(function* ({ output }) {
240
+ yield* client
241
+ .deleteUsageLimit(output.deployment.url, output.id)
242
+ .pipe(Effect.catchTag("ConvexNotFound", () => Effect.void));
243
+ }),
244
+ } satisfies Provider.ProviderServiceInput<UsageLimit>;
245
+ });
246
+
247
+ export const localProvider = Effect.succeed({
248
+ reconcile: () => Effect.fail(UnsupportedLocalUsageLimit.make({})),
249
+ delete: () => Effect.void,
250
+ } satisfies Provider.ProviderServiceInput<UsageLimit>);
251
+
252
+ export const layer = Provider.effect(UsageLimit, provider);
253
+ export const localLayer = Provider.effect(UsageLimit, localProvider);
@@ -26,7 +26,7 @@ export const checkpointCreate = Effect.fn("Lifecycle.checkpointCreate")(
26
26
  row.instanceId !== instanceId
27
27
  )
28
28
  return yield* LifecycleStateError.make({ fqn });
29
- if (row.status !== "creating") return;
29
+ if (row.status !== "creating" && row.status !== "replacing") return;
30
30
  yield* store.set({
31
31
  ...key,
32
32
  value: {