@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,145 @@
1
+ import { ConvexClient } from "./ConvexClient.js";
2
+ import { checkpointCreate, shouldAdopt } from "./internal/Lifecycle.js";
3
+ import * as Effect from "effect/Effect";
4
+ import * as Provider from "alchemy/Provider";
5
+ import { Resource } from "alchemy/Resource";
6
+ import * as Schema from "effect/Schema";
7
+ import * as Option from "effect/Option";
8
+ import * as Array from "effect/Array";
9
+ import { OwnedBySomeoneElse, Unowned } from "alchemy/AdoptPolicy";
10
+ import { isResolved } from "alchemy/Diff";
11
+ // src/UsageLimit.ts
12
+ const UsageLimit = Resource("Convex.UsageLimit");
13
+ var UsageLimitTargetChange = class extends Schema.TaggedError()("UsageLimitTargetChange", { deploymentName: Schema.String }) {};
14
+ var AmbiguousUsageLimit = class extends Schema.TaggedError()("AmbiguousUsageLimit", {
15
+ deploymentName: Schema.String,
16
+ metric: Schema.String,
17
+ window: Schema.String,
18
+ limitType: Schema.String,
19
+ limitIds: Schema.Array(Schema.String)
20
+ }) {
21
+ get message() {
22
+ return `Usage limit ${this.metric}/${this.window}/${this.limitType} on ${this.deploymentName} matches multiple ids: ${Array.join(this.limitIds, ", ")}.`;
23
+ }
24
+ };
25
+ var InvalidUsageLimit = class extends Schema.TaggedError()("InvalidUsageLimit", { limit: Schema.String }) {
26
+ get message() {
27
+ return `Usage limit ${this.limit} must be a positive safe integer.`;
28
+ }
29
+ };
30
+ var UnsupportedLocalUsageLimit = class extends Schema.TaggedError()("UnsupportedLocalUsageLimit", {}) {
31
+ get message() {
32
+ return "Declare Convex.UsageLimit only for cloud stages.";
33
+ }
34
+ };
35
+ const validateLimit = Effect.fn("UsageLimit.validateLimit")(function* (limit) {
36
+ if (!Number.isSafeInteger(limit) || limit < 1) return yield* InvalidUsageLimit.make({ limit: String(limit) });
37
+ });
38
+ const desired = (props) => ({
39
+ metric: props.metric,
40
+ window: props.window,
41
+ limit: props.limit,
42
+ limitType: props.limitType ?? "warning",
43
+ enabled: props.enabled ?? true
44
+ });
45
+ const sameTarget = (current, props) => current.deployment.name === props.deployment.name;
46
+ const sameConfig = (current, input) => current.metric === input.metric && current.window === input.window && current.limitType === input.limitType && current.limit === input.limit && current.enabled === input.enabled;
47
+ const ownershipConflict = (input) => {
48
+ const physicalName = `${input.metric}/${input.window}/${input.limitType}`;
49
+ return new OwnedBySomeoneElse({
50
+ 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.`,
51
+ resourceType: UsageLimit.Type,
52
+ physicalName
53
+ });
54
+ };
55
+ const provider = Effect.gen(function* () {
56
+ const client = yield* ConvexClient;
57
+ const find = Effect.fn("UsageLimit.find")(function* (output, url = output.deployment.url) {
58
+ const limits = yield* client.listUsageLimits(url).pipe(Effect.catchTag("ConvexNotFound", () => Effect.succeed([])));
59
+ return Option.getOrUndefined(Array.findFirst(limits, (limit) => limit.id === output.id));
60
+ });
61
+ const findMatching = Effect.fn("UsageLimit.findMatching")(function* (deployment, input) {
62
+ const limits = yield* client.listUsageLimits(deployment.url).pipe(Effect.catchTag("ConvexNotFound", () => Effect.succeed([])));
63
+ const matches = Array.filter(limits, (limit) => limit.metric === input.metric && limit.window === input.window && limit.limitType === input.limitType);
64
+ if (matches.length > 1) return yield* AmbiguousUsageLimit.make({
65
+ deploymentName: deployment.name,
66
+ ...input,
67
+ limitIds: Array.map(matches, (limit) => limit.id)
68
+ });
69
+ return matches[0];
70
+ });
71
+ return {
72
+ diff: Effect.fn("UsageLimit.diff")(function* ({ news, output }) {
73
+ if (!isResolved(news)) return;
74
+ yield* validateLimit(news.limit);
75
+ if (output === void 0) return;
76
+ if (!sameTarget(output, news)) return { action: "replace" };
77
+ const current = yield* find(output, news.deployment.url);
78
+ if (output.deployment.url !== news.deployment.url || current === void 0 || !sameConfig(current, desired(news))) return { action: "update" };
79
+ }),
80
+ read: Effect.fn("UsageLimit.read")(function* ({ fqn, olds, output }) {
81
+ if (output === void 0) {
82
+ if (olds.limit !== void 0) yield* validateLimit(olds.limit);
83
+ if (olds.deployment === void 0 || olds.metric === void 0 || olds.window === void 0) return;
84
+ const input = {
85
+ metric: olds.metric,
86
+ window: olds.window,
87
+ limitType: olds.limitType ?? "warning"
88
+ };
89
+ const current = yield* findMatching(olds.deployment, input);
90
+ if (current !== void 0 && !(yield* shouldAdopt(fqn))) yield* Effect.logWarning(ownershipConflict(input).message);
91
+ return current === void 0 ? void 0 : Unowned({
92
+ deployment: olds.deployment,
93
+ ...current
94
+ });
95
+ }
96
+ const current = yield* find(output);
97
+ return current === void 0 ? void 0 : {
98
+ deployment: output.deployment,
99
+ ...current
100
+ };
101
+ }),
102
+ reconcile: Effect.fn("UsageLimit.reconcile")(function* ({ fqn, instanceId, news, output }) {
103
+ yield* validateLimit(news.limit);
104
+ if (output === void 0) yield* checkpointCreate(fqn, instanceId, news);
105
+ if (output !== void 0 && !sameTarget(output, news)) return yield* UsageLimitTargetChange.make({ deploymentName: output.deployment.name });
106
+ const input = desired(news);
107
+ let current = output === void 0 ? void 0 : yield* find(output, news.deployment.url);
108
+ if (current === void 0) {
109
+ const existing = yield* findMatching(news.deployment, input);
110
+ if (existing !== void 0 && !(yield* shouldAdopt(fqn))) return yield* ownershipConflict(input);
111
+ current = existing;
112
+ }
113
+ if (current !== void 0) {
114
+ yield* checkpointCreate(fqn, instanceId, news, {
115
+ deployment: news.deployment,
116
+ ...current
117
+ });
118
+ const updated = sameConfig(current, input) ? current : yield* client.updateUsageLimit(news.deployment.url, current.id, input);
119
+ return {
120
+ deployment: news.deployment,
121
+ ...updated
122
+ };
123
+ }
124
+ const created = yield* client.createUsageLimit(news.deployment.url, input);
125
+ const attributes = {
126
+ deployment: news.deployment,
127
+ ...created
128
+ };
129
+ yield* checkpointCreate(fqn, instanceId, news, attributes);
130
+ return attributes;
131
+ }),
132
+ delete: Effect.fn("UsageLimit.delete")(function* ({ output }) {
133
+ yield* client.deleteUsageLimit(output.deployment.url, output.id).pipe(Effect.catchTag("ConvexNotFound", () => Effect.void));
134
+ })
135
+ };
136
+ });
137
+ const localProvider = Effect.succeed({
138
+ reconcile: () => Effect.fail(UnsupportedLocalUsageLimit.make({})),
139
+ delete: () => Effect.void
140
+ });
141
+ const layer = Provider.effect(UsageLimit, provider);
142
+ const localLayer = Provider.effect(UsageLimit, localProvider);
143
+ export { AmbiguousUsageLimit, InvalidUsageLimit, UnsupportedLocalUsageLimit, UsageLimit, UsageLimitTargetChange, layer, localLayer, localProvider, provider };
144
+
145
+ //# sourceMappingURL=UsageLimit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"UsageLimit.js","names":[],"sources":["../src/UsageLimit.ts"],"sourcesContent":["import type {\n UsageLimitMetric,\n UsageLimitType,\n UsageLimitWindow,\n} from \"@convex-dev/platform/deploymentApi\";\nimport { OwnedBySomeoneElse, Unowned } from \"alchemy/AdoptPolicy\";\nimport { isResolved } from \"alchemy/Diff\";\nimport * as Provider from \"alchemy/Provider\";\nimport { Resource } from \"alchemy/Resource\";\nimport * as Array from \"effect/Array\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\n\nimport { ConvexClient, type UsageLimitInput } from \"./ConvexClient.js\";\nimport type { Providers } from \"./Providers.js\";\nimport { checkpointCreate, shouldAdopt } from \"./internal/Lifecycle.js\";\n\nexport interface UsageLimitProps {\n readonly deployment: { readonly name: string; readonly url: string };\n readonly metric: UsageLimitMetric;\n readonly window: UsageLimitWindow;\n readonly limit: number;\n readonly limitType?: UsageLimitType;\n readonly enabled?: boolean;\n}\n\nexport interface UsageLimitAttributes {\n readonly deployment: { readonly name: string; readonly url: string };\n readonly id: string;\n readonly metric: UsageLimitMetric;\n readonly window: UsageLimitWindow;\n readonly limit: number;\n readonly limitType: UsageLimitType;\n readonly enabled: boolean;\n}\n\nexport type UsageLimit = Resource<\n \"Convex.UsageLimit\",\n UsageLimitProps,\n UsageLimitAttributes,\n never,\n Providers\n>;\nexport const UsageLimit = Resource<UsageLimit>(\"Convex.UsageLimit\");\n\nexport class UsageLimitTargetChange extends Schema.TaggedError<\n UsageLimitTargetChange,\n { readonly brand: unique symbol }\n>()(\"UsageLimitTargetChange\", { deploymentName: Schema.String }) {}\n\nexport class AmbiguousUsageLimit extends Schema.TaggedError<\n AmbiguousUsageLimit,\n { readonly brand: unique symbol }\n>()(\"AmbiguousUsageLimit\", {\n deploymentName: Schema.String,\n metric: Schema.String,\n window: Schema.String,\n limitType: Schema.String,\n limitIds: Schema.Array(Schema.String),\n}) {\n override get message() {\n return `Usage limit ${this.metric}/${this.window}/${this.limitType} on ${this.deploymentName} matches multiple ids: ${Array.join(this.limitIds, \", \")}.`;\n }\n}\n\nexport class InvalidUsageLimit extends Schema.TaggedError<\n InvalidUsageLimit,\n { readonly brand: unique symbol }\n>()(\"InvalidUsageLimit\", { limit: Schema.String }) {\n override get message() {\n return `Usage limit ${this.limit} must be a positive safe integer.`;\n }\n}\n\nexport class UnsupportedLocalUsageLimit extends Schema.TaggedError<\n UnsupportedLocalUsageLimit,\n { readonly brand: unique symbol }\n>()(\"UnsupportedLocalUsageLimit\", {}) {\n override get message() {\n return \"Declare Convex.UsageLimit only for cloud stages.\";\n }\n}\n\nconst validateLimit = Effect.fn(\"UsageLimit.validateLimit\")(function* (\n limit: number,\n) {\n if (!Number.isSafeInteger(limit) || limit < 1)\n return yield* InvalidUsageLimit.make({ limit: String(limit) });\n});\n\nconst desired = (props: UsageLimitProps): UsageLimitInput => ({\n metric: props.metric,\n window: props.window,\n limit: props.limit,\n limitType: props.limitType ?? \"warning\",\n enabled: props.enabled ?? true,\n});\nconst sameTarget = (current: UsageLimitAttributes, props: UsageLimitProps) =>\n current.deployment.name === props.deployment.name;\nconst sameConfig = (current: UsageLimitInput, input: UsageLimitInput) =>\n current.metric === input.metric &&\n current.window === input.window &&\n current.limitType === input.limitType &&\n current.limit === input.limit &&\n current.enabled === input.enabled;\n\nconst ownershipConflict = (\n input: Pick<UsageLimitInput, \"metric\" | \"window\" | \"limitType\">,\n) => {\n const physicalName = `${input.metric}/${input.window}/${input.limitType}`;\n return new OwnedBySomeoneElse({\n 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.`,\n resourceType: UsageLimit.Type,\n physicalName,\n });\n};\n\nexport const provider = Effect.gen(function* () {\n const client = yield* ConvexClient;\n const find = Effect.fn(\"UsageLimit.find\")(function* (\n output: UsageLimitAttributes,\n url = output.deployment.url,\n ) {\n const limits = yield* client\n .listUsageLimits(url)\n .pipe(Effect.catchTag(\"ConvexNotFound\", () => Effect.succeed([])));\n return Option.getOrUndefined(\n Array.findFirst(limits, (limit) => limit.id === output.id),\n );\n });\n const findMatching = Effect.fn(\"UsageLimit.findMatching\")(function* (\n deployment: UsageLimitProps[\"deployment\"],\n input: Pick<UsageLimitInput, \"metric\" | \"window\" | \"limitType\">,\n ) {\n const limits = yield* client\n .listUsageLimits(deployment.url)\n .pipe(Effect.catchTag(\"ConvexNotFound\", () => Effect.succeed([])));\n const matches = Array.filter(\n limits,\n (limit) =>\n limit.metric === input.metric &&\n limit.window === input.window &&\n limit.limitType === input.limitType,\n );\n if (matches.length > 1)\n return yield* AmbiguousUsageLimit.make({\n deploymentName: deployment.name,\n ...input,\n limitIds: Array.map(matches, (limit) => limit.id),\n });\n return matches[0];\n });\n return {\n diff: Effect.fn(\"UsageLimit.diff\")(function* ({ news, output }) {\n if (!isResolved(news)) return;\n yield* validateLimit(news.limit);\n if (output === undefined) return;\n if (!sameTarget(output, news)) return { action: \"replace\" };\n const current = yield* find(output, news.deployment.url);\n if (\n output.deployment.url !== news.deployment.url ||\n current === undefined ||\n !sameConfig(current, desired(news))\n )\n return { action: \"update\" };\n }),\n read: Effect.fn(\"UsageLimit.read\")(function* ({ fqn, olds, output }) {\n if (output === undefined) {\n if (olds.limit !== undefined) yield* validateLimit(olds.limit);\n if (\n olds.deployment === undefined ||\n olds.metric === undefined ||\n olds.window === undefined\n )\n return;\n const input = {\n metric: olds.metric,\n window: olds.window,\n limitType: olds.limitType ?? \"warning\",\n };\n const current = yield* findMatching(olds.deployment, input);\n if (current !== undefined && !(yield* shouldAdopt(fqn)))\n yield* Effect.logWarning(ownershipConflict(input).message);\n return current === undefined\n ? undefined\n : Unowned({ deployment: olds.deployment, ...current });\n }\n const current = yield* find(output);\n return current === undefined\n ? undefined\n : { deployment: output.deployment, ...current };\n }),\n reconcile: Effect.fn(\"UsageLimit.reconcile\")(function* ({\n fqn,\n instanceId,\n news,\n output,\n }) {\n yield* validateLimit(news.limit);\n if (output === undefined) yield* checkpointCreate(fqn, instanceId, news);\n if (output !== undefined && !sameTarget(output, news))\n return yield* UsageLimitTargetChange.make({\n deploymentName: output.deployment.name,\n });\n const input = desired(news);\n let current =\n output === undefined\n ? undefined\n : yield* find(output, news.deployment.url);\n if (current === undefined) {\n const existing = yield* findMatching(news.deployment, input);\n if (existing !== undefined && !(yield* shouldAdopt(fqn)))\n return yield* ownershipConflict(input);\n current = existing;\n }\n if (current !== undefined) {\n yield* checkpointCreate(fqn, instanceId, news, {\n deployment: news.deployment,\n ...current,\n });\n const updated = sameConfig(current, input)\n ? current\n : yield* client.updateUsageLimit(\n news.deployment.url,\n current.id,\n input,\n );\n return { deployment: news.deployment, ...updated };\n }\n const created = yield* client.createUsageLimit(\n news.deployment.url,\n input,\n );\n const attributes = { deployment: news.deployment, ...created };\n yield* checkpointCreate(fqn, instanceId, news, attributes);\n return attributes;\n }),\n delete: Effect.fn(\"UsageLimit.delete\")(function* ({ output }) {\n yield* client\n .deleteUsageLimit(output.deployment.url, output.id)\n .pipe(Effect.catchTag(\"ConvexNotFound\", () => Effect.void));\n }),\n } satisfies Provider.ProviderServiceInput<UsageLimit>;\n});\n\nexport const localProvider = Effect.succeed({\n reconcile: () => Effect.fail(UnsupportedLocalUsageLimit.make({})),\n delete: () => Effect.void,\n} satisfies Provider.ProviderServiceInput<UsageLimit>);\n\nexport const layer = Provider.effect(UsageLimit, provider);\nexport const localLayer = Provider.effect(UsageLimit, localProvider);\n"],"mappings":";;;;;;;;;;;AA4CA,MAAa,aAAa,SAAqB,mBAAmB;AAElE,IAAa,yBAAb,cAA4C,OAAO,YAGjD,CAAC,CAAC,0BAA0B,EAAE,gBAAgB,OAAO,OAAO,CAAC,CAAC,CAAC,CAAC;AAElE,IAAa,sBAAb,cAAyC,OAAO,YAG9C,CAAC,CAAC,uBAAuB;CACzB,gBAAgB,OAAO;CACvB,QAAQ,OAAO;CACf,QAAQ,OAAO;CACf,WAAW,OAAO;CAClB,UAAU,OAAO,MAAM,OAAO,MAAM;AACtC,CAAC,CAAC,CAAC;CACD,IAAa,UAAU;EACrB,OAAO,eAAe,KAAK,OAAO,GAAG,KAAK,OAAO,GAAG,KAAK,UAAU,MAAM,KAAK,eAAe,yBAAyB,MAAM,KAAK,KAAK,UAAU,IAAI,EAAE;CACxJ;AACF;AAEA,IAAa,oBAAb,cAAuC,OAAO,YAG5C,CAAC,CAAC,qBAAqB,EAAE,OAAO,OAAO,OAAO,CAAC,CAAC,CAAC;CACjD,IAAa,UAAU;EACrB,OAAO,eAAe,KAAK,MAAM;CACnC;AACF;AAEA,IAAa,6BAAb,cAAgD,OAAO,YAGrD,CAAC,CAAC,8BAA8B,CAAC,CAAC,CAAC,CAAC;CACpC,IAAa,UAAU;EACrB,OAAO;CACT;AACF;AAEA,MAAM,gBAAgB,OAAO,GAAG,0BAA0B,CAAC,CAAC,WAC1D,OACA;CACA,IAAI,CAAC,OAAO,cAAc,KAAK,KAAK,QAAQ,GAC1C,OAAO,OAAO,kBAAkB,KAAK,EAAE,OAAO,OAAO,KAAK,EAAE,CAAC;AACjE,CAAC;AAED,MAAM,WAAW,WAA6C;CAC5D,QAAQ,MAAM;CACd,QAAQ,MAAM;CACd,OAAO,MAAM;CACb,WAAW,MAAM,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MAAa,gBAAgB,OAAO,QAAQ;CAC1C,iBAAiB,OAAO,KAAK,2BAA2B,KAAK,CAAC,CAAC,CAAC;CAChE,cAAc,OAAO;AACvB,CAAqD;AAErD,MAAa,QAAQ,SAAS,OAAO,YAAY,QAAQ;AACzD,MAAa,aAAa,SAAS,OAAO,YAAY,aAAa"}
@@ -20,7 +20,7 @@ const checkpointCreate = Effect.fn("Lifecycle.checkpointCreate")(function* (fqn,
20
20
  };
21
21
  const row = yield* store.get(key);
22
22
  if (row === void 0 || row.kind === "action" || row.instanceId !== instanceId) return yield* LifecycleStateError.make({ fqn });
23
- if (row.status !== "creating") return;
23
+ if (row.status !== "creating" && row.status !== "replacing") return;
24
24
  yield* store.set({
25
25
  ...key,
26
26
  value: {
@@ -1 +1 @@
1
- {"version":3,"file":"Lifecycle.js","names":[],"sources":["../../src/internal/Lifecycle.ts"],"sourcesContent":["import { AdoptPolicy } from \"alchemy/AdoptPolicy\";\nimport { AlchemyContext } from \"alchemy/AlchemyContext\";\nimport { Stack } from \"alchemy/Stack\";\nimport { State } from \"alchemy/State/State\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\n\nexport class LifecycleStateError extends Schema.TaggedError<\n LifecycleStateError,\n { readonly brand: unique symbol }\n>()(\"LifecycleStateError\", { fqn: Schema.String }) {}\n\nexport const checkpointCreate = Effect.fn(\"Lifecycle.checkpointCreate\")(\n function* (fqn: string, instanceId: string, props: object, output?: object) {\n const stack = yield* Effect.serviceOption(Stack);\n if (Option.isNone(stack)) return;\n const state = yield* Effect.serviceOption(State);\n if (Option.isNone(state)) return yield* LifecycleStateError.make({ fqn });\n const store = yield* state.value;\n const key = { stack: stack.value.name, stage: stack.value.stage, fqn };\n const row = yield* store.get(key);\n if (\n row === undefined ||\n row.kind === \"action\" ||\n row.instanceId !== instanceId\n )\n return yield* LifecycleStateError.make({ fqn });\n if (row.status !== \"creating\") return;\n yield* store.set({\n ...key,\n value: {\n ...row,\n props,\n ...(output === undefined ? {} : { attr: output }),\n },\n });\n },\n);\n\nexport const shouldAdopt = Effect.fn(\"Lifecycle.shouldAdopt\")(function* (\n fqn: string,\n) {\n const stack = yield* Effect.serviceOption(Stack);\n const resourcePolicy = Option.isSome(stack)\n ? stack.value.resources[fqn]?.Adopt\n : undefined;\n if (resourcePolicy !== undefined) return resourcePolicy;\n const policy = yield* Effect.serviceOption(AdoptPolicy);\n if (Option.isSome(policy)) return policy.value;\n const context = yield* Effect.serviceOption(AlchemyContext);\n return Option.isSome(context) && context.value.adopt;\n});\n"],"mappings":";;;;;;;;AAQA,IAAa,sBAAb,cAAyC,OAAO,YAG9C,CAAC,CAAC,uBAAuB,EAAE,KAAK,OAAO,OAAO,CAAC,CAAC,CAAC,CAAC;AAEpD,MAAa,mBAAmB,OAAO,GAAG,4BAA4B,CAAC,CACrE,WAAW,KAAa,YAAoB,OAAe,QAAiB;CAC1E,MAAM,QAAQ,OAAO,OAAO,cAAc,KAAK;CAC/C,IAAI,OAAO,OAAO,KAAK,GAAG;CAC1B,MAAM,QAAQ,OAAO,OAAO,cAAc,KAAK;CAC/C,IAAI,OAAO,OAAO,KAAK,GAAG,OAAO,OAAO,oBAAoB,KAAK,EAAE,IAAI,CAAC;CACxE,MAAM,QAAQ,OAAO,MAAM;CAC3B,MAAM,MAAM;EAAE,OAAO,MAAM,MAAM;EAAM,OAAO,MAAM,MAAM;EAAO;CAAI;CACrE,MAAM,MAAM,OAAO,MAAM,IAAI,GAAG;CAChC,IACE,QAAQ,KAAA,KACR,IAAI,SAAS,YACb,IAAI,eAAe,YAEnB,OAAO,OAAO,oBAAoB,KAAK,EAAE,IAAI,CAAC;CAChD,IAAI,IAAI,WAAW,YAAY;CAC/B,OAAO,MAAM,IAAI;EACf,GAAG;EACH,OAAO;GACL,GAAG;GACH;GACA,GAAI,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,OAAO;EACjD;CACF,CAAC;AACH,CACF;AAEA,MAAa,cAAc,OAAO,GAAG,uBAAuB,CAAC,CAAC,WAC5D,KACA;CACA,MAAM,QAAQ,OAAO,OAAO,cAAc,KAAK;CAC/C,MAAM,iBAAiB,OAAO,OAAO,KAAK,IACtC,MAAM,MAAM,UAAU,IAAI,EAAE,QAC5B,KAAA;CACJ,IAAI,mBAAmB,KAAA,GAAW,OAAO;CACzC,MAAM,SAAS,OAAO,OAAO,cAAc,WAAW;CACtD,IAAI,OAAO,OAAO,MAAM,GAAG,OAAO,OAAO;CACzC,MAAM,UAAU,OAAO,OAAO,cAAc,cAAc;CAC1D,OAAO,OAAO,OAAO,OAAO,KAAK,QAAQ,MAAM;AACjD,CAAC"}
1
+ {"version":3,"file":"Lifecycle.js","names":[],"sources":["../../src/internal/Lifecycle.ts"],"sourcesContent":["import { AdoptPolicy } from \"alchemy/AdoptPolicy\";\nimport { AlchemyContext } from \"alchemy/AlchemyContext\";\nimport { Stack } from \"alchemy/Stack\";\nimport { State } from \"alchemy/State/State\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\n\nexport class LifecycleStateError extends Schema.TaggedError<\n LifecycleStateError,\n { readonly brand: unique symbol }\n>()(\"LifecycleStateError\", { fqn: Schema.String }) {}\n\nexport const checkpointCreate = Effect.fn(\"Lifecycle.checkpointCreate\")(\n function* (fqn: string, instanceId: string, props: object, output?: object) {\n const stack = yield* Effect.serviceOption(Stack);\n if (Option.isNone(stack)) return;\n const state = yield* Effect.serviceOption(State);\n if (Option.isNone(state)) return yield* LifecycleStateError.make({ fqn });\n const store = yield* state.value;\n const key = { stack: stack.value.name, stage: stack.value.stage, fqn };\n const row = yield* store.get(key);\n if (\n row === undefined ||\n row.kind === \"action\" ||\n row.instanceId !== instanceId\n )\n return yield* LifecycleStateError.make({ fqn });\n if (row.status !== \"creating\" && row.status !== \"replacing\") return;\n yield* store.set({\n ...key,\n value: {\n ...row,\n props,\n ...(output === undefined ? {} : { attr: output }),\n },\n });\n },\n);\n\nexport const shouldAdopt = Effect.fn(\"Lifecycle.shouldAdopt\")(function* (\n fqn: string,\n) {\n const stack = yield* Effect.serviceOption(Stack);\n const resourcePolicy = Option.isSome(stack)\n ? stack.value.resources[fqn]?.Adopt\n : undefined;\n if (resourcePolicy !== undefined) return resourcePolicy;\n const policy = yield* Effect.serviceOption(AdoptPolicy);\n if (Option.isSome(policy)) return policy.value;\n const context = yield* Effect.serviceOption(AlchemyContext);\n return Option.isSome(context) && context.value.adopt;\n});\n"],"mappings":";;;;;;;;AAQA,IAAa,sBAAb,cAAyC,OAAO,YAG9C,CAAC,CAAC,uBAAuB,EAAE,KAAK,OAAO,OAAO,CAAC,CAAC,CAAC,CAAC;AAEpD,MAAa,mBAAmB,OAAO,GAAG,4BAA4B,CAAC,CACrE,WAAW,KAAa,YAAoB,OAAe,QAAiB;CAC1E,MAAM,QAAQ,OAAO,OAAO,cAAc,KAAK;CAC/C,IAAI,OAAO,OAAO,KAAK,GAAG;CAC1B,MAAM,QAAQ,OAAO,OAAO,cAAc,KAAK;CAC/C,IAAI,OAAO,OAAO,KAAK,GAAG,OAAO,OAAO,oBAAoB,KAAK,EAAE,IAAI,CAAC;CACxE,MAAM,QAAQ,OAAO,MAAM;CAC3B,MAAM,MAAM;EAAE,OAAO,MAAM,MAAM;EAAM,OAAO,MAAM,MAAM;EAAO;CAAI;CACrE,MAAM,MAAM,OAAO,MAAM,IAAI,GAAG;CAChC,IACE,QAAQ,KAAA,KACR,IAAI,SAAS,YACb,IAAI,eAAe,YAEnB,OAAO,OAAO,oBAAoB,KAAK,EAAE,IAAI,CAAC;CAChD,IAAI,IAAI,WAAW,cAAc,IAAI,WAAW,aAAa;CAC7D,OAAO,MAAM,IAAI;EACf,GAAG;EACH,OAAO;GACL,GAAG;GACH;GACA,GAAI,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,OAAO;EACjD;CACF,CAAC;AACH,CACF;AAEA,MAAa,cAAc,OAAO,GAAG,uBAAuB,CAAC,CAAC,WAC5D,KACA;CACA,MAAM,QAAQ,OAAO,OAAO,cAAc,KAAK;CAC/C,MAAM,iBAAiB,OAAO,OAAO,KAAK,IACtC,MAAM,MAAM,UAAU,IAAI,EAAE,QAC5B,KAAA;CACJ,IAAI,mBAAmB,KAAA,GAAW,OAAO;CACzC,MAAM,SAAS,OAAO,OAAO,cAAc,WAAW;CACtD,IAAI,OAAO,OAAO,MAAM,GAAG,OAAO,OAAO;CACzC,MAAM,UAAU,OAAO,OAAO,cAAc,cAAc;CAC1D,OAAO,OAAO,OAAO,OAAO,KAAK,QAAQ,MAAM;AACjD,CAAC"}
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@gaganref/confect-alchemy",
3
- "version": "10.6.0-fork.23",
3
+ "version": "10.6.0-fork.24",
4
4
  "dependencies": {
5
5
  "@convex-dev/platform": "^0.1.10"
6
6
  },
7
7
  "peerDependencies": {
8
- "@confect/cli": "npm:@gaganref/confect-cli@10.6.0-fork.23",
9
- "@confect/core": "npm:@gaganref/confect-core@10.6.0-fork.23",
8
+ "@confect/cli": "npm:@gaganref/confect-cli@10.6.0-fork.24",
9
+ "@confect/core": "npm:@gaganref/confect-core@10.6.0-fork.24",
10
10
  "alchemy": ">=2.0.0-beta.85 <2.0.0",
11
11
  "convex": "^1.32.0",
12
12
  "effect": "~4.1.4"
package/src/Convex.ts CHANGED
@@ -20,3 +20,9 @@ export {
20
20
  } from "./EnvironmentVariables.js";
21
21
  export { Code, type CodeProps, type CodeAttributes } from "./Code.js";
22
22
  export { providers, Providers } from "./Providers.js";
23
+
24
+ export {
25
+ UsageLimit,
26
+ type UsageLimitProps,
27
+ type UsageLimitAttributes,
28
+ } from "./UsageLimit.js";
@@ -66,6 +66,28 @@ export type EnvironmentVariables = Readonly<
66
66
  >
67
67
  >;
68
68
 
69
+ export type UsageLimit = DeploymentApi.UsageLimitConfigResponse;
70
+ export type UsageLimitInput = DeploymentApi.UsageLimitConfigRequest;
71
+
72
+ const UsageLimitSchema = Schema.Struct({
73
+ id: Schema.String,
74
+ metric: Schema.Literals([
75
+ "functionCalls",
76
+ "databaseIoGb",
77
+ "dataEgressGb",
78
+ "searchQueryGb",
79
+ "queryMutationComputeGbHours",
80
+ "actionComputeConvexGbHours",
81
+ "actionComputeNodeJsGbHours",
82
+ "actionComputeCpuGbHours",
83
+ "aiGatewayCostDollars",
84
+ ]),
85
+ window: Schema.Literals(["day", "month"]),
86
+ limitType: Schema.Literals(["warning", "disable"]),
87
+ limit: Schema.Finite,
88
+ enabled: Schema.Boolean,
89
+ }) satisfies Schema.Schema<UsageLimit>;
90
+
69
91
  const errorFields = {
70
92
  operation: Schema.String,
71
93
  status: Schema.optionalKey(Schema.Finite),
@@ -232,6 +254,7 @@ const maxErrorBodyBytes = 8 * 1024;
232
254
  const httpFailure = Effect.fn("ConvexClient.httpFailure")(function* (
233
255
  operation: string,
234
256
  response: HttpClientResponse.HttpClientResponse,
257
+ credentials: readonly Redacted.Redacted<string>[],
235
258
  ) {
236
259
  const fallback = ConvexApiError.make({
237
260
  operation,
@@ -258,7 +281,13 @@ const httpFailure = Effect.fn("ConvexClient.httpFailure")(function* (
258
281
  ),
259
282
  ),
260
283
  Effect.map(({ code }) =>
261
- /^[A-Za-z][A-Za-z0-9]{0,63}$/.test(code) ? code : undefined,
284
+ /^[A-Za-z][A-Za-z0-9]{0,63}$/.test(code) &&
285
+ !Array.some(
286
+ credentials,
287
+ (credential) => code === Redacted.value(credential),
288
+ )
289
+ ? code
290
+ : undefined,
262
291
  ),
263
292
  Effect.orElseSucceed(() => undefined),
264
293
  );
@@ -291,6 +320,16 @@ const make = Effect.fn("ConvexClient.make")(function* (options?: {
291
320
  ));
292
321
  return Redacted.make(`Bearer ${Redacted.value(token)}`);
293
322
  });
323
+ const deploymentAuthorization = managementAuthorization.pipe(
324
+ Effect.map((authorization) =>
325
+ pipe(
326
+ authorization,
327
+ Redacted.value,
328
+ String.replace(/^Bearer /, "Convex "),
329
+ Redacted.make,
330
+ ),
331
+ ),
332
+ );
294
333
  const baseUrl = "https://api.convex.dev/v1";
295
334
 
296
335
  const send = Effect.fn("ConvexClient.request")(function* (
@@ -323,7 +362,14 @@ const make = Effect.fn("ConvexClient.make")(function* (options?: {
323
362
  ),
324
363
  );
325
364
  if (response.status < 200 || response.status >= 300)
326
- return yield* httpFailure(operation, response);
365
+ return yield* httpFailure(operation, response, [
366
+ pipe(
367
+ authorization,
368
+ Redacted.value,
369
+ String.replace(/^(?:Bearer|Convex) /, ""),
370
+ Redacted.make,
371
+ ),
372
+ ]);
327
373
  return response;
328
374
  });
329
375
 
@@ -456,7 +502,7 @@ const make = Effect.fn("ConvexClient.make")(function* (options?: {
456
502
  );
457
503
  // Convex answers a function that threw with 560 and its message.
458
504
  if (response.status !== 200 && response.status !== 560)
459
- return yield* httpFailure(operation, response);
505
+ return yield* httpFailure(operation, response, [key]);
460
506
  const result = yield* decode(operation, response, FunctionResponse);
461
507
  if (result.status === "error")
462
508
  return yield* ConvexFunctionError.make({
@@ -465,6 +511,78 @@ const make = Effect.fn("ConvexClient.make")(function* (options?: {
465
511
  });
466
512
  return result.value;
467
513
  }),
514
+ listUsageLimits: Effect.fn("ConvexClient.listUsageLimits")(function* (
515
+ url: string,
516
+ ) {
517
+ const origin = yield* deploymentUrl("listUsageLimits", url);
518
+ const authorization = yield* deploymentAuthorization;
519
+ const response = yield* send(
520
+ "listUsageLimits",
521
+ "GET",
522
+ `${origin}/list_usage_limits`,
523
+ authorization,
524
+ );
525
+ const result = yield* decode(
526
+ "listUsageLimits",
527
+ response,
528
+ Schema.Struct({ usageLimits: Schema.Array(UsageLimitSchema) }),
529
+ );
530
+ return result.usageLimits;
531
+ }),
532
+ createUsageLimit: Effect.fn("ConvexClient.createUsageLimit")(function* (
533
+ url: string,
534
+ input: UsageLimitInput,
535
+ ) {
536
+ const origin = yield* deploymentUrl("createUsageLimit", url);
537
+ const authorization = yield* deploymentAuthorization;
538
+ const response = yield* send(
539
+ "createUsageLimit",
540
+ "POST",
541
+ `${origin}/create_usage_limit`,
542
+ authorization,
543
+ input,
544
+ );
545
+ const result = yield* decode(
546
+ "createUsageLimit",
547
+ response,
548
+ Schema.Struct({ usageLimit: UsageLimitSchema }),
549
+ );
550
+ return result.usageLimit;
551
+ }),
552
+ updateUsageLimit: Effect.fn("ConvexClient.updateUsageLimit")(function* (
553
+ url: string,
554
+ id: string,
555
+ input: UsageLimitInput,
556
+ ) {
557
+ const origin = yield* deploymentUrl("updateUsageLimit", url);
558
+ const authorization = yield* deploymentAuthorization;
559
+ const response = yield* send(
560
+ "updateUsageLimit",
561
+ "POST",
562
+ `${origin}/update_usage_limit/${encodeURIComponent(id)}`,
563
+ authorization,
564
+ input,
565
+ );
566
+ const result = yield* decode(
567
+ "updateUsageLimit",
568
+ response,
569
+ Schema.Struct({ usageLimit: UsageLimitSchema }),
570
+ );
571
+ return result.usageLimit;
572
+ }),
573
+ deleteUsageLimit: Effect.fn("ConvexClient.deleteUsageLimit")(function* (
574
+ url: string,
575
+ id: string,
576
+ ) {
577
+ const origin = yield* deploymentUrl("deleteUsageLimit", url);
578
+ const authorization = yield* deploymentAuthorization;
579
+ yield* send(
580
+ "deleteUsageLimit",
581
+ "POST",
582
+ `${origin}/delete_usage_limit/${encodeURIComponent(id)}`,
583
+ authorization,
584
+ );
585
+ }),
468
586
  listProjects: Effect.fn("ConvexClient.listProjects")(function* (
469
587
  teamId: number,
470
588
  ) {
package/src/Providers.ts CHANGED
@@ -9,6 +9,7 @@ import * as Deployment from "./Deployment.js";
9
9
  import * as DeployKey from "./DeployKey.js";
10
10
  import * as EnvironmentVariables from "./EnvironmentVariables.js";
11
11
  import * as Project from "./Project.js";
12
+ import * as UsageLimit from "./UsageLimit.js";
12
13
  import * as CommandRunner from "./internal/CommandRunner.js";
13
14
  import * as PushLock from "./internal/PushLock.js";
14
15
 
@@ -35,6 +36,7 @@ export const providers = (options?: {
35
36
  DeployKey.DeployKey,
36
37
  EnvironmentVariables.EnvironmentVariables,
37
38
  Code.Code,
39
+ UsageLimit.UsageLimit,
38
40
  ]),
39
41
  ).pipe(
40
42
  Layer.provide(
@@ -55,6 +57,10 @@ export const providers = (options?: {
55
57
  live: () => EnvironmentVariables.layer,
56
58
  local: () => EnvironmentVariables.localLayer,
57
59
  }),
60
+ ProviderLayer.dual(UsageLimit.UsageLimit, {
61
+ live: () => UsageLimit.layer,
62
+ local: () => UsageLimit.localLayer,
63
+ }),
58
64
  ProviderLayer.dual(Code.Code, {
59
65
  live: () => Code.layer,
60
66
  local: () => Code.localLayer,