@gaganref/confect-alchemy 10.6.0-fork.22 → 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.
- package/dist/Convex.d.ts +1 -0
- package/dist/Convex.d.ts.map +1 -1
- package/dist/Convex.js +3 -1
- package/dist/Convex.js.map +1 -1
- package/dist/ConvexClient.d.ts +39 -0
- package/dist/ConvexClient.d.ts.map +1 -1
- package/dist/ConvexClient.js +46 -4
- package/dist/ConvexClient.js.map +1 -1
- package/dist/EnvironmentVariables.d.ts +76 -21
- package/dist/EnvironmentVariables.d.ts.map +1 -1
- package/dist/EnvironmentVariables.js +188 -12
- package/dist/EnvironmentVariables.js.map +1 -1
- package/dist/Providers.d.ts.map +1 -1
- package/dist/Providers.js +9 -4
- package/dist/Providers.js.map +1 -1
- package/dist/UsageLimit.d.ts +140 -0
- package/dist/UsageLimit.d.ts.map +1 -0
- package/dist/UsageLimit.js +145 -0
- package/dist/UsageLimit.js.map +1 -0
- package/dist/internal/Lifecycle.js +1 -1
- package/dist/internal/Lifecycle.js.map +1 -1
- package/dist/internal/LocalBackend.d.ts +2 -0
- package/dist/internal/LocalBackend.d.ts.map +1 -1
- package/dist/internal/LocalBackend.js +2 -0
- package/dist/internal/LocalBackend.js.map +1 -1
- package/dist/internal/PushLock.d.ts +1 -0
- package/dist/internal/PushLock.d.ts.map +1 -1
- package/dist/internal/PushLock.js +3 -2
- package/dist/internal/PushLock.js.map +1 -1
- package/package.json +3 -3
- package/src/Convex.ts +6 -0
- package/src/ConvexClient.ts +121 -3
- package/src/EnvironmentVariables.ts +481 -16
- package/src/Providers.ts +6 -0
- package/src/UsageLimit.ts +253 -0
- package/src/internal/Lifecycle.ts +1 -1
- package/src/internal/LocalBackend.ts +2 -0
- package/src/internal/PushLock.ts +4 -1
|
@@ -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,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AAI,YAAY,KAAA,GAAW;IACzB,MAAM,WAAW,OAAO,aAAa,KAAK,YAAY,KAAK;IAC3D,IAAI,aAAa,KAAA,KAAa,EAAE,OAAO,YAAY,GAAG,IACpD,OAAO,OAAO,kBAAkB,KAAK;IACvC,UAAU;GACZ;GACA,IAAI,YAAY,KAAA,GAAW;IACzB,OAAO,iBAAiB,KAAK,YAAY,MAAM;KAC7C,YAAY,KAAK;KACjB,GAAG;IACL,CAAC;IACD,MAAM,UAAU,WAAW,SAAS,KAAK,IACrC,UACA,OAAO,OAAO,iBACZ,KAAK,WAAW,KAChB,QAAQ,IACR,KACF;IACJ,OAAO;KAAE,YAAY,KAAK;KAAY,GAAG;IAAQ;GACnD;GACA,MAAM,UAAU,OAAO,OAAO,iBAC5B,KAAK,WAAW,KAChB,KACF;GACA,MAAM,aAAa;IAAE,YAAY,KAAK;IAAY,GAAG;GAAQ;GAC7D,OAAO,iBAAiB,KAAK,YAAY,MAAM,UAAU;GACzD,OAAO;EACT,CAAC;EACD,QAAQ,OAAO,GAAG,mBAAmB,CAAC,CAAC,WAAW,EAAE,UAAU;GAC5D,OAAO,OACJ,iBAAiB,OAAO,WAAW,KAAK,OAAO,EAAE,CAAC,CAClD,KAAK,OAAO,SAAS,wBAAwB,OAAO,IAAI,CAAC;EAC9D,CAAC;CACH;AACF,CAAC;AAED,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,
|
|
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"}
|
|
@@ -44,6 +44,8 @@ export interface LocalBackend {
|
|
|
44
44
|
export declare const dataDirectories: Effect.Effect<(deploymentName: string) => string, never, Path.Path | Stack>;
|
|
45
45
|
/**
|
|
46
46
|
* The admin key of a local deployment, for its deploy key resource.
|
|
47
|
+
*
|
|
48
|
+
* @stability unstable
|
|
47
49
|
*/
|
|
48
50
|
export declare const adminKey: (deploymentName: string, directory: string) => Effect.Effect<Redacted.Redacted<string>, LocalBackendError, FileSystem.FileSystem | Path.Path>;
|
|
49
51
|
export declare const remove: (deploymentName: string, directory: string) => Effect.Effect<void, LocalBackendError, FileSystem.FileSystem>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"LocalBackend.d.ts","sources":["../../src/internal/LocalBackend.ts"],"names":[],"mappings":"AAEA,OAAO,EAA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I,MAAM,aAAa,CAAC;AACpC,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAC;AAE5C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AACxC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAC;AAGtC,OAAO,KAAK,UAAU,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAgB,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAUnE;;;;GAIG;AACH,eAAO,MAAM,cAAc,mCAAmC,CAAC;;;;;;oBAI3C,OAAO,MAAM;;AAFjC,qBAAa,iBAAkB,SAAQ,sBAiBrC;IACA,IAAa,OAAO,WAsBnB;CACF;AAED,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IAC7C;;;OAGG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;CACtC;AAmED;;;;;;GAMG;AACH,eAAO,MAAM,eAAe,iCAUF,MAAM,sCAC9B,CAAC;AAuBH;;;;GAIG;AACH,eAAO,MAAM,QAAQ,+IAWnB,CAAC;AAEH,eAAO,MAAM,MAAM,8GAYjB,CAAC;AA0CH;;;;;;;;;GASG;AACH,eAAO,MAAM,IAAI;;;;;oKA8Nf,CAAC"}
|
|
@@ -123,6 +123,8 @@ const readIdentity = Effect.fn("LocalBackend.readIdentity")(function* (deploymen
|
|
|
123
123
|
});
|
|
124
124
|
/**
|
|
125
125
|
* The admin key of a local deployment, for its deploy key resource.
|
|
126
|
+
*
|
|
127
|
+
* @stability unstable
|
|
126
128
|
*/
|
|
127
129
|
const adminKey = Effect.fn("LocalBackend.adminKey")(function* (deploymentName, directory) {
|
|
128
130
|
const identity = yield* readIdentity(deploymentName, directory);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"LocalBackend.js","names":["Loopback.parsePortRange","FileLock.acquire","Loopback.origin"],"sources":["../../src/internal/LocalBackend.ts"],"sourcesContent":["import { createServer, type Server } from \"node:net\";\nimport { dotAlchemyDirectory } from \"alchemy/AlchemyContext\";\nimport { Stack } from \"alchemy/Stack\";\nimport * as Config from \"effect/Config\";\nimport * as SecureRandom from \"effect/crypto/SecureRandom\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Redacted from \"effect/Redacted\";\nimport * as Schedule from \"effect/Schedule\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Stream from \"effect/Stream\";\nimport * as HttpClient from \"effect/http/HttpClient\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/process\";\nimport { processEnvironment } from \"./CommandRunner.js\";\nimport * as FileLock from \"./FileLock.js\";\nimport * as Loopback from \"./Loopback.js\";\nimport { userCache } from \"./UserCache.js\";\nimport { extract } from \"./Zip.js\";\nimport * as Str from \"effect/String\";\nimport { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\n\n/**\n * The backend release a new local deployment runs. An existing data directory\n * keeps running the release that created it, so upgrading this package never\n * opens a database with a different release.\n */\nexport const backendVersion = \"precompiled-2026-10-28-cccbade\";\n\nexport class LocalBackendError extends Schema.TaggedError<\n LocalBackendError,\n { readonly brand: unique symbol }\n>()(\"LocalBackendError\", {\n deploymentName: Schema.String,\n reason: Schema.Literals([\n \"configuration\",\n \"filesystem\",\n \"install\",\n \"identity\",\n \"ports\",\n \"running\",\n \"spawn\",\n \"exit\",\n \"timeout\",\n ]),\n exitCode: Schema.optionalKey(Schema.Finite),\n}) {\n override get message() {\n const subject = `Local backend for ${this.deploymentName}`;\n switch (this.reason) {\n case \"configuration\":\n return `${subject} needs a home directory and, when set, CONFECT_LOCAL_BACKEND_PORTS as a range such as 3300-3399`;\n case \"filesystem\":\n return `${subject} could not read or write its data directory`;\n case \"install\":\n return `${subject} could not download or install the backend binary`;\n case \"identity\":\n return `${subject} could not read, create, or save its identity`;\n case \"ports\":\n return `${subject} could not get its ports; another process is using them`;\n case \"running\":\n return `${subject} is already running: stop the other alchemy dev session, or the backend process left over from one, that serves its data directory`;\n case \"spawn\":\n return `${subject} could not be started`;\n case \"exit\":\n return `${subject} exited${this.exitCode === undefined ? \"\" : ` with code ${this.exitCode}`} before it was ready`;\n case \"timeout\":\n return `${subject} did not become ready in time`;\n }\n }\n}\n\nexport interface LocalBackend {\n readonly url: string;\n readonly siteUrl: string;\n readonly adminKey: Redacted.Redacted<string>;\n /**\n * Completes when the backend process has exited and released its data\n * directory, so the deployment can be booted again.\n */\n readonly exited: Effect.Effect<void>;\n}\n\n// Ports are saved once a backend has answered on them, so a first start that\n// fails picks fresh ports next time instead of keeping ones that never worked.\nconst Identity = Schema.fromJsonString(\n Schema.Struct({\n name: Schema.String,\n version: Schema.String,\n instanceSecret: Schema.String,\n adminKey: Schema.String,\n ports: Schema.optionalKey(\n Schema.Struct({ port: Schema.Int, sitePort: Schema.Int }),\n ),\n }),\n);\ntype Identity = typeof Identity.Type;\n\n// The release archive per platform, as the Convex CLI maps it\n// (convex-js src/cli/lib/localDeployment/download.ts getDownloadPath).\nconst artifacts: Readonly<Record<string, string>> = {\n \"darwin-arm64\": \"convex-local-backend-aarch64-apple-darwin.zip\",\n \"darwin-x64\": \"convex-local-backend-x86_64-apple-darwin.zip\",\n \"linux-arm64\": \"convex-local-backend-aarch64-unknown-linux-gnu.zip\",\n \"linux-x64\": \"convex-local-backend-x86_64-unknown-linux-gnu.zip\",\n \"win32-arm64\": \"convex-local-backend-x86_64-pc-windows-msvc.zip\",\n \"win32-x64\": \"convex-local-backend-x86_64-pc-windows-msvc.zip\",\n};\nconst executable =\n process.platform === \"win32\"\n ? \"convex-local-backend.exe\"\n : \"convex-local-backend\";\n\nconst close = (server: Server) =>\n Effect.callback<void>((resume) => {\n server.close(() => resume(Effect.void));\n });\n\n// A server listening on `port`, or undefined when the port is taken, closed\n// with the scope. Listening is uninterruptible, so an interrupted probe never\n// leaves a server bound to the port.\nconst listen = (port: number) =>\n Effect.acquireRelease(\n Effect.callback<Server | undefined>((resume) => {\n const server = createServer();\n server.once(\"error\", () => resume(Effect.undefined));\n server.listen(port, \"127.0.0.1\", () => resume(Effect.succeed(server)));\n }),\n (server) => (server !== undefined ? close(server) : Effect.void),\n );\n\nconst isFree = (port: number) =>\n listen(port).pipe(\n Effect.map((server) => server !== undefined),\n Effect.scoped,\n );\n\nconst portOf = (server: Server | undefined) => {\n const address = server?.address();\n return typeof address === \"object\" && address !== null\n ? address.port\n : undefined;\n};\n\n// Backends in one process start one at a time, so two deployments starting\n// together never probe and claim the same ports.\nconst startup = Semaphore.makeUnsafe(1);\n\n/**\n * Resolves the directory that holds one local deployment's identity, database,\n * and file storage: `.alchemy/convex/<stack>/<stage>/<deployment>`. Keyed by\n * the deployment name because a deploy key resource only knows that name.\n *\n * @internal\n */\nexport const dataDirectories = Effect.gen(function* () {\n const path = yield* Path.Path;\n const stack = yield* Stack;\n const dotAlchemyDirectoryValue = yield* dotAlchemyDirectory;\n const root = path.resolve(\n dotAlchemyDirectoryValue,\n \"convex\",\n stack.name,\n stack.stage,\n );\n return (deploymentName: string) => path.join(root, deploymentName);\n});\n\nconst readIdentity = Effect.fn(\"LocalBackend.readIdentity\")(function* (\n deploymentName: string,\n directory: string,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const file = path.join(directory, \"identity.json\");\n const invalid = () =>\n LocalBackendError.make({ deploymentName, reason: \"identity\" });\n if (!(yield* fs.exists(file).pipe(Effect.mapError(invalid))))\n return Option.none<Identity>();\n const identity = yield* fs\n .readFileString(file)\n .pipe(\n Effect.flatMap(Schema.decodeEffect(Identity)),\n Effect.mapError(invalid),\n );\n if (identity.name !== deploymentName) return yield* invalid();\n return Option.some(identity);\n});\n\n/**\n * The admin key of a local deployment, for its deploy key resource.\n */\nexport const adminKey = Effect.fn(\"LocalBackend.adminKey\")(function* (\n deploymentName: string,\n directory: string,\n) {\n const identity = yield* readIdentity(deploymentName, directory);\n if (Option.isNone(identity))\n return yield* LocalBackendError.make({\n deploymentName,\n reason: \"identity\",\n });\n return Redacted.make(identity.value.adminKey);\n});\n\nexport const remove = Effect.fn(\"LocalBackend.remove\")(function* (\n deploymentName: string,\n directory: string,\n) {\n const fs = yield* FileSystem.FileSystem;\n yield* fs\n .remove(directory, { recursive: true, force: true })\n .pipe(\n Effect.mapError(() =>\n LocalBackendError.make({ deploymentName, reason: \"filesystem\" }),\n ),\n );\n});\n\n/**\n * Install a backend release into the Convex CLI's binary cache,\n * `<cache>/convex/binaries/<version>/`, unless it is already there.\n */\nconst install = Effect.fn(\"LocalBackend.install\")(function* (\n deploymentName: string,\n version: string,\n cache: string,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const http = yield* HttpClient.HttpClient;\n const failed = () =>\n LocalBackendError.make({ deploymentName, reason: \"install\" });\n const binaries = path.join(cache, \"convex\", \"binaries\");\n const binary = path.join(binaries, version, executable);\n const artifact = artifacts[`${process.platform}-${process.arch}`];\n return yield* Effect.gen(function* () {\n if (yield* fs.exists(binary)) return binary;\n if (artifact === undefined) return yield* failed();\n yield* fs.makeDirectory(binaries, { recursive: true });\n const temp = yield* fs.makeTempDirectoryScoped({\n directory: binaries,\n prefix: \".download-\",\n });\n const archive = path.join(temp, artifact);\n const response = yield* http.get(\n `https://github.com/get-convex/convex-backend/releases/download/${version}/${artifact}`,\n );\n if (response.status !== 200) return yield* failed();\n yield* response.stream.pipe(Stream.run(fs.sink(archive)));\n const extracted = path.join(temp, executable);\n yield* extract(archive, executable, extracted);\n yield* fs.chmod(extracted, 0o755);\n yield* fs.makeDirectory(path.dirname(binary), { recursive: true });\n yield* fs.rename(extracted, binary);\n return binary;\n }).pipe(Effect.scoped, Effect.mapError(failed));\n});\n\n/**\n * Boot the local backend for one deployment and keep it running for the ambient\n * scope. The process and the data directory's `owner.lock` share a child scope\n * that closes when the boot fails or is interrupted and when the process exits,\n * so a deployment can be booted again in the same session. The first boot\n * installs the pinned release, generates an instance secret and admin key, and\n * picks two free loopback ports; later boots reuse all of them, so stored\n * credentials and URLs stay valid. A saved port that something else now holds\n * is an error rather than a move, because resources keep the URL.\n */\nexport const boot = Effect.fn(\"LocalBackend.boot\")(function* (\n deploymentName: string,\n directory: string,\n) {\n const path = yield* Path.Path;\n const fs = yield* FileSystem.FileSystem;\n const http = yield* HttpClient.HttpClient;\n const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n const random = yield* SecureRandom.SecureRandom;\n const fail = (reason: LocalBackendError[\"reason\"], exitCode?: number) =>\n LocalBackendError.make({\n deploymentName,\n reason,\n ...(exitCode === undefined ? {} : { exitCode }),\n });\n const settings = yield* Config.all({\n environment: processEnvironment,\n ports: Config.String(\"CONFECT_LOCAL_BACKEND_PORTS\").pipe(Config.option),\n }).pipe(Effect.mapError(() => fail(\"configuration\")));\n const cache = yield* userCache.pipe(\n Effect.mapError(() => fail(\"configuration\")),\n );\n if (Option.isNone(cache)) return yield* fail(\"configuration\");\n const range = Option.map(settings.ports, Loopback.parsePortRange);\n if (Option.isSome(range) && Option.isNone(range.value))\n return yield* fail(\"configuration\");\n const env = {\n ...settings.environment,\n DISABLE_BEACON: \"1\",\n DO_NOT_TRACK: \"1\",\n };\n\n const answer = (url: string) =>\n http.get(`${url}/instance_name`).pipe(\n Effect.flatMap((response) =>\n response.status === 200 ? response.text : Effect.undefined,\n ),\n Effect.orElseSucceed(() => undefined),\n );\n\n const allocate = Effect.gen(function* () {\n if (Option.isNone(range) || Option.isNone(range.value)) {\n // A closed server no longer has an address.\n const [port, sitePort] = yield* Effect.all([listen(0), listen(0)]).pipe(\n Effect.map((servers) => Array.map(servers, portOf)),\n Effect.scoped,\n );\n if (port === undefined || sitePort === undefined)\n return yield* fail(\"ports\");\n return { port, sitePort };\n }\n const free: number[] = [];\n const { from, to } = range.value.value;\n for (let port = from; port <= to && free.length < 2; port++) {\n if (yield* isFree(port)) free.push(port);\n }\n const [port, sitePort] = free;\n if (port === undefined || sitePort === undefined)\n return yield* fail(\"ports\");\n return { port, sitePort };\n });\n\n const generate = (binary: string) =>\n Effect.gen(function* () {\n const randomBytes2 = yield* random.randomBytes(32);\n const instanceSecret = Buffer.from(randomBytes2).toString(\"hex\");\n const output = yield* spawner.string(\n ChildProcess.make(\n binary,\n [\n \"keygen\",\n \"admin-key\",\n \"--instance-name\",\n deploymentName,\n \"--instance-secret\",\n instanceSecret,\n ],\n { env, extendEnv: false, stdin: \"ignore\", stderr: \"ignore\" },\n ),\n );\n const key = pipe(output, Str.trim);\n if (!pipe(key, Str.startsWith(`${deploymentName}|`)))\n return yield* fail(\"identity\");\n return { instanceSecret, adminKey: key };\n }).pipe(\n Effect.catchTag(\"PlatformError\", () => Effect.fail(fail(\"identity\"))),\n );\n\n const save = (identity: Identity) =>\n Effect.gen(function* () {\n const file = path.join(directory, \"identity.json\");\n const temp = `${file}.${process.pid}.tmp`;\n const encoded = yield* Schema.encodeEffect(Identity)(identity);\n yield* fs.writeFileString(temp, encoded, { mode: 0o600 });\n yield* fs.rename(temp, file);\n }).pipe(\n // Node cannot cancel a write or rename it has started; finishing it\n // keeps a pending rename from landing after owner.lock is released.\n Effect.uninterruptible,\n Effect.mapError(() => fail(\"identity\")),\n );\n\n const session = yield* Scope.Scope;\n const owned = yield* Scope.fork(session);\n const stopped = yield* Deferred.make<void>();\n // Registered first, so it runs after the process and owner.lock finalizers\n // however the scope closes.\n yield* Scope.addFinalizer(owned, Deferred.succeed(stopped, undefined));\n const start = Effect.gen(function* () {\n yield* FileLock.acquire(path.join(directory, \"owner.lock\")).pipe(\n Effect.mapError((error) =>\n fail(error.reason === \"held\" ? \"running\" : \"filesystem\"),\n ),\n );\n const saved = yield* readIdentity(deploymentName, directory);\n const version = Option.isSome(saved) ? saved.value.version : backendVersion;\n const binary = yield* install(deploymentName, version, cache.value);\n let identity: Identity;\n if (Option.isSome(saved)) {\n identity = saved.value;\n } else {\n identity = {\n name: deploymentName,\n version,\n ...(yield* generate(binary)),\n };\n yield* save(identity);\n }\n const ports = identity.ports ?? (yield* allocate);\n if (identity.ports !== undefined) {\n if (!(yield* isFree(ports.port)) || !(yield* isFree(ports.sitePort)))\n return yield* fail(\n (yield* answer(Loopback.origin(ports.port))) === deploymentName\n ? \"running\"\n : \"ports\",\n );\n }\n\n const url = Loopback.origin(ports.port);\n const siteUrl = Loopback.origin(ports.sitePort);\n const handle = yield* spawner\n .spawn(\n ChildProcess.make(\n binary,\n [\n \"--interface\",\n \"127.0.0.1\",\n \"--port\",\n String(ports.port),\n \"--site-proxy-port\",\n String(ports.sitePort),\n \"--instance-name\",\n deploymentName,\n \"--instance-secret\",\n identity.instanceSecret,\n \"--convex-origin\",\n url,\n \"--convex-site\",\n siteUrl,\n \"--local-storage\",\n path.join(directory, \"convex_local_storage\"),\n \"--disable-beacon\",\n path.join(directory, \"convex_local_backend.sqlite3\"),\n ],\n {\n cwd: directory,\n env,\n extendEnv: false,\n stdin: \"ignore\",\n stdout: \"ignore\",\n stderr: \"ignore\",\n forceKillAfter: \"3 seconds\",\n },\n ),\n )\n .pipe(Effect.mapError(() => fail(\"spawn\")));\n\n const ready = answer(url).pipe(\n Effect.flatMap((name) =>\n name === undefined || name === deploymentName\n ? Effect.succeed(name === deploymentName)\n : Effect.fail(fail(\"ports\")),\n ),\n Effect.repeat({\n until: (isReady) => isReady,\n schedule: Schedule.spaced(\"100 millis\"),\n }),\n );\n const exit = handle.exitCode.pipe(\n Effect.mapError(() => fail(\"exit\")),\n Effect.flatMap((code) => Effect.fail(fail(\"exit\", Number(code)))),\n );\n yield* Effect.raceFirst(ready, exit).pipe(\n Effect.timeoutOrElse({\n duration: \"60 seconds\",\n orElse: () => Effect.fail(fail(\"timeout\")),\n }),\n );\n if (identity.ports === undefined) yield* save({ ...identity, ports });\n // An exited backend releases the data directory before `exited`\n // completes, so the deployment can be booted again in this session.\n yield* handle.exitCode.pipe(\n Effect.ignore,\n Effect.andThen(Scope.close(owned, Exit.void)),\n Effect.forkIn(session),\n );\n return {\n url,\n siteUrl,\n adminKey: Redacted.make(identity.adminKey),\n exited: Deferred.await(stopped),\n } satisfies LocalBackend;\n });\n\n return yield* startup\n .withPermits(1)(start)\n .pipe(\n Scope.provide(owned),\n Effect.onExit((exit) =>\n Exit.isSuccess(exit) ? Effect.void : Scope.close(owned, exit),\n ),\n );\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,MAAa,iBAAiB;AAE9B,IAAa,oBAAb,cAAuC,OAAO,YAG5C,CAAC,CAAC,qBAAqB;CACvB,gBAAgB,OAAO;CACvB,QAAQ,OAAO,SAAS;EACtB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;CACD,UAAU,OAAO,YAAY,OAAO,MAAM;AAC5C,CAAC,CAAC,CAAC;CACD,IAAa,UAAU;EACrB,MAAM,UAAU,qBAAqB,KAAK;EAC1C,QAAQ,KAAK,QAAb;GACE,KAAK,iBACH,OAAO,GAAG,QAAQ;GACpB,KAAK,cACH,OAAO,GAAG,QAAQ;GACpB,KAAK,WACH,OAAO,GAAG,QAAQ;GACpB,KAAK,YACH,OAAO,GAAG,QAAQ;GACpB,KAAK,SACH,OAAO,GAAG,QAAQ;GACpB,KAAK,WACH,OAAO,GAAG,QAAQ;GACpB,KAAK,SACH,OAAO,GAAG,QAAQ;GACpB,KAAK,QACH,OAAO,GAAG,QAAQ,SAAS,KAAK,aAAa,KAAA,IAAY,KAAK,cAAc,KAAK,WAAW;GAC9F,KAAK,WACH,OAAO,GAAG,QAAQ;EACtB;CACF;AACF;AAeA,MAAM,WAAW,OAAO,eACtB,OAAO,OAAO;CACZ,MAAM,O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["Loopback.parsePortRange","FileLock.acquire","Loopback.origin"],"sources":["../../src/internal/LocalBackend.ts"],"sourcesContent":["import { createServer, type Server } from \"node:net\";\nimport { dotAlchemyDirectory } from \"alchemy/AlchemyContext\";\nimport { Stack } from \"alchemy/Stack\";\nimport * as Config from \"effect/Config\";\nimport * as SecureRandom from \"effect/crypto/SecureRandom\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Redacted from \"effect/Redacted\";\nimport * as Schedule from \"effect/Schedule\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Stream from \"effect/Stream\";\nimport * as HttpClient from \"effect/http/HttpClient\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/process\";\nimport { processEnvironment } from \"./CommandRunner.js\";\nimport * as FileLock from \"./FileLock.js\";\nimport * as Loopback from \"./Loopback.js\";\nimport { userCache } from \"./UserCache.js\";\nimport { extract } from \"./Zip.js\";\nimport * as Str from \"effect/String\";\nimport { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\n\n/**\n * The backend release a new local deployment runs. An existing data directory\n * keeps running the release that created it, so upgrading this package never\n * opens a database with a different release.\n */\nexport const backendVersion = \"precompiled-2026-10-28-cccbade\";\n\nexport class LocalBackendError extends Schema.TaggedError<\n LocalBackendError,\n { readonly brand: unique symbol }\n>()(\"LocalBackendError\", {\n deploymentName: Schema.String,\n reason: Schema.Literals([\n \"configuration\",\n \"filesystem\",\n \"install\",\n \"identity\",\n \"ports\",\n \"running\",\n \"spawn\",\n \"exit\",\n \"timeout\",\n ]),\n exitCode: Schema.optionalKey(Schema.Finite),\n}) {\n override get message() {\n const subject = `Local backend for ${this.deploymentName}`;\n switch (this.reason) {\n case \"configuration\":\n return `${subject} needs a home directory and, when set, CONFECT_LOCAL_BACKEND_PORTS as a range such as 3300-3399`;\n case \"filesystem\":\n return `${subject} could not read or write its data directory`;\n case \"install\":\n return `${subject} could not download or install the backend binary`;\n case \"identity\":\n return `${subject} could not read, create, or save its identity`;\n case \"ports\":\n return `${subject} could not get its ports; another process is using them`;\n case \"running\":\n return `${subject} is already running: stop the other alchemy dev session, or the backend process left over from one, that serves its data directory`;\n case \"spawn\":\n return `${subject} could not be started`;\n case \"exit\":\n return `${subject} exited${this.exitCode === undefined ? \"\" : ` with code ${this.exitCode}`} before it was ready`;\n case \"timeout\":\n return `${subject} did not become ready in time`;\n }\n }\n}\n\nexport interface LocalBackend {\n readonly url: string;\n readonly siteUrl: string;\n readonly adminKey: Redacted.Redacted<string>;\n /**\n * Completes when the backend process has exited and released its data\n * directory, so the deployment can be booted again.\n */\n readonly exited: Effect.Effect<void>;\n}\n\n// Ports are saved once a backend has answered on them, so a first start that\n// fails picks fresh ports next time instead of keeping ones that never worked.\nconst Identity = Schema.fromJsonString(\n Schema.Struct({\n name: Schema.String,\n version: Schema.String,\n instanceSecret: Schema.String,\n adminKey: Schema.String,\n ports: Schema.optionalKey(\n Schema.Struct({ port: Schema.Int, sitePort: Schema.Int }),\n ),\n }),\n);\ntype Identity = typeof Identity.Type;\n\n// The release archive per platform, as the Convex CLI maps it\n// (convex-js src/cli/lib/localDeployment/download.ts getDownloadPath).\nconst artifacts: Readonly<Record<string, string>> = {\n \"darwin-arm64\": \"convex-local-backend-aarch64-apple-darwin.zip\",\n \"darwin-x64\": \"convex-local-backend-x86_64-apple-darwin.zip\",\n \"linux-arm64\": \"convex-local-backend-aarch64-unknown-linux-gnu.zip\",\n \"linux-x64\": \"convex-local-backend-x86_64-unknown-linux-gnu.zip\",\n \"win32-arm64\": \"convex-local-backend-x86_64-pc-windows-msvc.zip\",\n \"win32-x64\": \"convex-local-backend-x86_64-pc-windows-msvc.zip\",\n};\nconst executable =\n process.platform === \"win32\"\n ? \"convex-local-backend.exe\"\n : \"convex-local-backend\";\n\nconst close = (server: Server) =>\n Effect.callback<void>((resume) => {\n server.close(() => resume(Effect.void));\n });\n\n// A server listening on `port`, or undefined when the port is taken, closed\n// with the scope. Listening is uninterruptible, so an interrupted probe never\n// leaves a server bound to the port.\nconst listen = (port: number) =>\n Effect.acquireRelease(\n Effect.callback<Server | undefined>((resume) => {\n const server = createServer();\n server.once(\"error\", () => resume(Effect.undefined));\n server.listen(port, \"127.0.0.1\", () => resume(Effect.succeed(server)));\n }),\n (server) => (server !== undefined ? close(server) : Effect.void),\n );\n\nconst isFree = (port: number) =>\n listen(port).pipe(\n Effect.map((server) => server !== undefined),\n Effect.scoped,\n );\n\nconst portOf = (server: Server | undefined) => {\n const address = server?.address();\n return typeof address === \"object\" && address !== null\n ? address.port\n : undefined;\n};\n\n// Backends in one process start one at a time, so two deployments starting\n// together never probe and claim the same ports.\nconst startup = Semaphore.makeUnsafe(1);\n\n/**\n * Resolves the directory that holds one local deployment's identity, database,\n * and file storage: `.alchemy/convex/<stack>/<stage>/<deployment>`. Keyed by\n * the deployment name because a deploy key resource only knows that name.\n *\n * @internal\n */\nexport const dataDirectories = Effect.gen(function* () {\n const path = yield* Path.Path;\n const stack = yield* Stack;\n const dotAlchemyDirectoryValue = yield* dotAlchemyDirectory;\n const root = path.resolve(\n dotAlchemyDirectoryValue,\n \"convex\",\n stack.name,\n stack.stage,\n );\n return (deploymentName: string) => path.join(root, deploymentName);\n});\n\nconst readIdentity = Effect.fn(\"LocalBackend.readIdentity\")(function* (\n deploymentName: string,\n directory: string,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const file = path.join(directory, \"identity.json\");\n const invalid = () =>\n LocalBackendError.make({ deploymentName, reason: \"identity\" });\n if (!(yield* fs.exists(file).pipe(Effect.mapError(invalid))))\n return Option.none<Identity>();\n const identity = yield* fs\n .readFileString(file)\n .pipe(\n Effect.flatMap(Schema.decodeEffect(Identity)),\n Effect.mapError(invalid),\n );\n if (identity.name !== deploymentName) return yield* invalid();\n return Option.some(identity);\n});\n\n/**\n * The admin key of a local deployment, for its deploy key resource.\n *\n * @stability unstable\n */\nexport const adminKey = Effect.fn(\"LocalBackend.adminKey\")(function* (\n deploymentName: string,\n directory: string,\n) {\n const identity = yield* readIdentity(deploymentName, directory);\n if (Option.isNone(identity))\n return yield* LocalBackendError.make({\n deploymentName,\n reason: \"identity\",\n });\n return Redacted.make(identity.value.adminKey);\n});\n\nexport const remove = Effect.fn(\"LocalBackend.remove\")(function* (\n deploymentName: string,\n directory: string,\n) {\n const fs = yield* FileSystem.FileSystem;\n yield* fs\n .remove(directory, { recursive: true, force: true })\n .pipe(\n Effect.mapError(() =>\n LocalBackendError.make({ deploymentName, reason: \"filesystem\" }),\n ),\n );\n});\n\n/**\n * Install a backend release into the Convex CLI's binary cache,\n * `<cache>/convex/binaries/<version>/`, unless it is already there.\n */\nconst install = Effect.fn(\"LocalBackend.install\")(function* (\n deploymentName: string,\n version: string,\n cache: string,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const http = yield* HttpClient.HttpClient;\n const failed = () =>\n LocalBackendError.make({ deploymentName, reason: \"install\" });\n const binaries = path.join(cache, \"convex\", \"binaries\");\n const binary = path.join(binaries, version, executable);\n const artifact = artifacts[`${process.platform}-${process.arch}`];\n return yield* Effect.gen(function* () {\n if (yield* fs.exists(binary)) return binary;\n if (artifact === undefined) return yield* failed();\n yield* fs.makeDirectory(binaries, { recursive: true });\n const temp = yield* fs.makeTempDirectoryScoped({\n directory: binaries,\n prefix: \".download-\",\n });\n const archive = path.join(temp, artifact);\n const response = yield* http.get(\n `https://github.com/get-convex/convex-backend/releases/download/${version}/${artifact}`,\n );\n if (response.status !== 200) return yield* failed();\n yield* response.stream.pipe(Stream.run(fs.sink(archive)));\n const extracted = path.join(temp, executable);\n yield* extract(archive, executable, extracted);\n yield* fs.chmod(extracted, 0o755);\n yield* fs.makeDirectory(path.dirname(binary), { recursive: true });\n yield* fs.rename(extracted, binary);\n return binary;\n }).pipe(Effect.scoped, Effect.mapError(failed));\n});\n\n/**\n * Boot the local backend for one deployment and keep it running for the ambient\n * scope. The process and the data directory's `owner.lock` share a child scope\n * that closes when the boot fails or is interrupted and when the process exits,\n * so a deployment can be booted again in the same session. The first boot\n * installs the pinned release, generates an instance secret and admin key, and\n * picks two free loopback ports; later boots reuse all of them, so stored\n * credentials and URLs stay valid. A saved port that something else now holds\n * is an error rather than a move, because resources keep the URL.\n */\nexport const boot = Effect.fn(\"LocalBackend.boot\")(function* (\n deploymentName: string,\n directory: string,\n) {\n const path = yield* Path.Path;\n const fs = yield* FileSystem.FileSystem;\n const http = yield* HttpClient.HttpClient;\n const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n const random = yield* SecureRandom.SecureRandom;\n const fail = (reason: LocalBackendError[\"reason\"], exitCode?: number) =>\n LocalBackendError.make({\n deploymentName,\n reason,\n ...(exitCode === undefined ? {} : { exitCode }),\n });\n const settings = yield* Config.all({\n environment: processEnvironment,\n ports: Config.String(\"CONFECT_LOCAL_BACKEND_PORTS\").pipe(Config.option),\n }).pipe(Effect.mapError(() => fail(\"configuration\")));\n const cache = yield* userCache.pipe(\n Effect.mapError(() => fail(\"configuration\")),\n );\n if (Option.isNone(cache)) return yield* fail(\"configuration\");\n const range = Option.map(settings.ports, Loopback.parsePortRange);\n if (Option.isSome(range) && Option.isNone(range.value))\n return yield* fail(\"configuration\");\n const env = {\n ...settings.environment,\n DISABLE_BEACON: \"1\",\n DO_NOT_TRACK: \"1\",\n };\n\n const answer = (url: string) =>\n http.get(`${url}/instance_name`).pipe(\n Effect.flatMap((response) =>\n response.status === 200 ? response.text : Effect.undefined,\n ),\n Effect.orElseSucceed(() => undefined),\n );\n\n const allocate = Effect.gen(function* () {\n if (Option.isNone(range) || Option.isNone(range.value)) {\n // A closed server no longer has an address.\n const [port, sitePort] = yield* Effect.all([listen(0), listen(0)]).pipe(\n Effect.map((servers) => Array.map(servers, portOf)),\n Effect.scoped,\n );\n if (port === undefined || sitePort === undefined)\n return yield* fail(\"ports\");\n return { port, sitePort };\n }\n const free: number[] = [];\n const { from, to } = range.value.value;\n for (let port = from; port <= to && free.length < 2; port++) {\n if (yield* isFree(port)) free.push(port);\n }\n const [port, sitePort] = free;\n if (port === undefined || sitePort === undefined)\n return yield* fail(\"ports\");\n return { port, sitePort };\n });\n\n const generate = (binary: string) =>\n Effect.gen(function* () {\n const randomBytes2 = yield* random.randomBytes(32);\n const instanceSecret = Buffer.from(randomBytes2).toString(\"hex\");\n const output = yield* spawner.string(\n ChildProcess.make(\n binary,\n [\n \"keygen\",\n \"admin-key\",\n \"--instance-name\",\n deploymentName,\n \"--instance-secret\",\n instanceSecret,\n ],\n { env, extendEnv: false, stdin: \"ignore\", stderr: \"ignore\" },\n ),\n );\n const key = pipe(output, Str.trim);\n if (!pipe(key, Str.startsWith(`${deploymentName}|`)))\n return yield* fail(\"identity\");\n return { instanceSecret, adminKey: key };\n }).pipe(\n Effect.catchTag(\"PlatformError\", () => Effect.fail(fail(\"identity\"))),\n );\n\n const save = (identity: Identity) =>\n Effect.gen(function* () {\n const file = path.join(directory, \"identity.json\");\n const temp = `${file}.${process.pid}.tmp`;\n const encoded = yield* Schema.encodeEffect(Identity)(identity);\n yield* fs.writeFileString(temp, encoded, { mode: 0o600 });\n yield* fs.rename(temp, file);\n }).pipe(\n // Node cannot cancel a write or rename it has started; finishing it\n // keeps a pending rename from landing after owner.lock is released.\n Effect.uninterruptible,\n Effect.mapError(() => fail(\"identity\")),\n );\n\n const session = yield* Scope.Scope;\n const owned = yield* Scope.fork(session);\n const stopped = yield* Deferred.make<void>();\n // Registered first, so it runs after the process and owner.lock finalizers\n // however the scope closes.\n yield* Scope.addFinalizer(owned, Deferred.succeed(stopped, undefined));\n const start = Effect.gen(function* () {\n yield* FileLock.acquire(path.join(directory, \"owner.lock\")).pipe(\n Effect.mapError((error) =>\n fail(error.reason === \"held\" ? \"running\" : \"filesystem\"),\n ),\n );\n const saved = yield* readIdentity(deploymentName, directory);\n const version = Option.isSome(saved) ? saved.value.version : backendVersion;\n const binary = yield* install(deploymentName, version, cache.value);\n let identity: Identity;\n if (Option.isSome(saved)) {\n identity = saved.value;\n } else {\n identity = {\n name: deploymentName,\n version,\n ...(yield* generate(binary)),\n };\n yield* save(identity);\n }\n const ports = identity.ports ?? (yield* allocate);\n if (identity.ports !== undefined) {\n if (!(yield* isFree(ports.port)) || !(yield* isFree(ports.sitePort)))\n return yield* fail(\n (yield* answer(Loopback.origin(ports.port))) === deploymentName\n ? \"running\"\n : \"ports\",\n );\n }\n\n const url = Loopback.origin(ports.port);\n const siteUrl = Loopback.origin(ports.sitePort);\n const handle = yield* spawner\n .spawn(\n ChildProcess.make(\n binary,\n [\n \"--interface\",\n \"127.0.0.1\",\n \"--port\",\n String(ports.port),\n \"--site-proxy-port\",\n String(ports.sitePort),\n \"--instance-name\",\n deploymentName,\n \"--instance-secret\",\n identity.instanceSecret,\n \"--convex-origin\",\n url,\n \"--convex-site\",\n siteUrl,\n \"--local-storage\",\n path.join(directory, \"convex_local_storage\"),\n \"--disable-beacon\",\n path.join(directory, \"convex_local_backend.sqlite3\"),\n ],\n {\n cwd: directory,\n env,\n extendEnv: false,\n stdin: \"ignore\",\n stdout: \"ignore\",\n stderr: \"ignore\",\n forceKillAfter: \"3 seconds\",\n },\n ),\n )\n .pipe(Effect.mapError(() => fail(\"spawn\")));\n\n const ready = answer(url).pipe(\n Effect.flatMap((name) =>\n name === undefined || name === deploymentName\n ? Effect.succeed(name === deploymentName)\n : Effect.fail(fail(\"ports\")),\n ),\n Effect.repeat({\n until: (isReady) => isReady,\n schedule: Schedule.spaced(\"100 millis\"),\n }),\n );\n const exit = handle.exitCode.pipe(\n Effect.mapError(() => fail(\"exit\")),\n Effect.flatMap((code) => Effect.fail(fail(\"exit\", Number(code)))),\n );\n yield* Effect.raceFirst(ready, exit).pipe(\n Effect.timeoutOrElse({\n duration: \"60 seconds\",\n orElse: () => Effect.fail(fail(\"timeout\")),\n }),\n );\n if (identity.ports === undefined) yield* save({ ...identity, ports });\n // An exited backend releases the data directory before `exited`\n // completes, so the deployment can be booted again in this session.\n yield* handle.exitCode.pipe(\n Effect.ignore,\n Effect.andThen(Scope.close(owned, Exit.void)),\n Effect.forkIn(session),\n );\n return {\n url,\n siteUrl,\n adminKey: Redacted.make(identity.adminKey),\n exited: Deferred.await(stopped),\n } satisfies LocalBackend;\n });\n\n return yield* startup\n .withPermits(1)(start)\n .pipe(\n Scope.provide(owned),\n Effect.onExit((exit) =>\n Exit.isSuccess(exit) ? Effect.void : Scope.close(owned, exit),\n ),\n );\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,MAAa,iBAAiB;AAE9B,IAAa,oBAAb,cAAuC,OAAO,YAG5C,CAAC,CAAC,qBAAqB;CACvB,gBAAgB,OAAO;CACvB,QAAQ,OAAO,SAAS;EACtB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;CACD,UAAU,OAAO,YAAY,OAAO,MAAM;AAC5C,CAAC,CAAC,CAAC;CACD,IAAa,UAAU;EACrB,MAAM,UAAU,qBAAqB,KAAK;EAC1C,QAAQ,KAAK,QAAb;GACE,KAAK,iBACH,OAAO,GAAG,QAAQ;GACpB,KAAK,cACH,OAAO,GAAG,QAAQ;GACpB,KAAK,WACH,OAAO,GAAG,QAAQ;GACpB,KAAK,YACH,OAAO,GAAG,QAAQ;GACpB,KAAK,SACH,OAAO,GAAG,QAAQ;GACpB,KAAK,WACH,OAAO,GAAG,QAAQ;GACpB,KAAK,SACH,OAAO,GAAG,QAAQ;GACpB,KAAK,QACH,OAAO,GAAG,QAAQ,SAAS,KAAK,aAAa,KAAA,IAAY,KAAK,cAAc,KAAK,WAAW;GAC9F,KAAK,WACH,OAAO,GAAG,QAAQ;EACtB;CACF;AACF;AAeA,MAAM,WAAW,OAAO,eACtB,OAAO,OAAO;CACZ,MAAM,OAAO;CACb,SAAS,O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
9
|
declare const PushLockError_base: Schema.Class<PushLockError, Schema.TaggedStruct<"PushLockError", {
|
|
10
10
|
readonly deploymentName: Schema.String;
|
|
11
11
|
readonly reason: Schema.Literals<readonly ["configuration", "timeout", "filesystem"]>;
|
|
12
|
+
readonly missing: Schema.optionalKey<Schema.Literals<readonly ["PushLock"]>>;
|
|
12
13
|
}>, import("effect/Cause").YieldableError & {
|
|
13
14
|
readonly brand: unique symbol;
|
|
14
15
|
}>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PushLock.d.ts","sources":["../../src/internal/PushLock.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,OAAO,MAAM,gBAAgB,CAAC;AAC1C,OAAO,KAAK,YAAY,MAAM,4BAA4B,CAAC;AAC3D,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAC;AAC5C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AACxC,OAAO,KAAK,UAAU,MAAM,mBAAmB,CAAC;AAChD,OAAO,KAAK,KAAK,MAAM,cAAc,CAAC;AAEtC,OAAO,KAAK,IAAI,MAAM,aAAa,CAAC;AACpC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC
|
|
1
|
+
{"version":3,"file":"PushLock.d.ts","sources":["../../src/internal/PushLock.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,OAAO,MAAM,gBAAgB,CAAC;AAC1C,OAAO,KAAK,YAAY,MAAM,4BAA4B,CAAC;AAC3D,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAC;AAC5C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AACxC,OAAO,KAAK,UAAU,MAAM,mBAAmB,CAAC;AAChD,OAAO,KAAK,KAAK,MAAM,cAAc,CAAC;AAEtC,OAAO,KAAK,IAAI,MAAM,aAAa,CAAC;AACpC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;;;;;;oBAOpB,OAAO,MAAM;;AAFjC,qBAAa,aAAc,SAAQ,kBAOjC;IACA,IAAa,OAAO,WAWnB;CACF;;uBAUsB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EACzB,cAAc,EAAE,MAAM,EACtB,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,KAC3B,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,GAAG,aAAa,EAAE,CAAC,CAAC;;AAX/C;;;;GAIG;AACH,qBAAa,QAAS,SAAQ,aAQW;CAAG;AAE5C;;;;;;;GAOG;AACH,eAAO,MAAM,KAAK,aAAc;IAAE,QAAQ,CAAC,OAAO,CAAC,EAAE,QAAQ,CAAC,KAAK,CAAA;CAAE,gGA6ClE,CAAC"}
|
|
@@ -17,11 +17,12 @@ var PushLockError = class extends Schema.TaggedError()("PushLockError", {
|
|
|
17
17
|
"configuration",
|
|
18
18
|
"timeout",
|
|
19
19
|
"filesystem"
|
|
20
|
-
])
|
|
20
|
+
]),
|
|
21
|
+
missing: Schema.Literals(["PushLock"]).pipe(Schema.optionalKey)
|
|
21
22
|
}) {
|
|
22
23
|
get message() {
|
|
23
24
|
switch (this.reason) {
|
|
24
|
-
case "configuration": return `Push lock for ${this.deploymentName} needs a home directory to keep its lock file in`;
|
|
25
|
+
case "configuration": return this.missing === "PushLock" ? `Push lock for ${this.deploymentName} needs the PushLock service to be provided` : `Push lock for ${this.deploymentName} needs a home directory to keep its lock file in`;
|
|
25
26
|
case "timeout": return `Timed out waiting for another push to ${this.deploymentName} to release its push lock`;
|
|
26
27
|
case "filesystem": return `Push lock for ${this.deploymentName} could not read or write its lock file`;
|
|
27
28
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PushLock.js","names":["FileLock.acquire"],"sources":["../../src/internal/PushLock.ts"],"sourcesContent":["import * as Context from \"effect/Context\";\nimport * as SecureRandom from \"effect/crypto/SecureRandom\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as FileLock from \"./FileLock.js\";\nimport { userCache } from \"./UserCache.js\";\n\nexport class PushLockError extends Schema.TaggedError<\n PushLockError,\n { readonly brand: unique symbol }\n>()(\"PushLockError\", {\n deploymentName: Schema.String,\n reason: Schema.Literals([\"configuration\", \"timeout\", \"filesystem\"]),\n}) {\n override get message() {\n switch (this.reason) {\n case \"configuration\":\n return `Push lock for ${this.deploymentName} needs a home directory to keep its lock file in`;\n case \"timeout\":\n return `Timed out waiting for another push to ${this.deploymentName} to release its push lock`;\n case \"filesystem\":\n return `Push lock for ${this.deploymentName} could not read or write its lock file`;\n }\n }\n}\n\n/**\n * Serialises pushes per deployment. Overlapping `convex deploy` runs against\n * one deployment race on `wait_for_schema`, so every push holds the lock for\n * its whole duration, whichever stack, checkout, or process it comes from.\n */\nexport class PushLock extends Context.Service<\n PushLock,\n {\n readonly withLock: <A, E, R>(\n deploymentName: string,\n effect: Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E | PushLockError, R>;\n }\n>()(\"@confect/alchemy/internal/PushLock\") {}\n\n/**\n * One lock file per deployment under the user's cache,\n * `confect/alchemy/locks/<deployment>.lock`, so every checkout on the machine\n * shares it. A lock left by a process that exited is taken over; a holder that\n * never releases ends in a typed timeout.\n *\n * @internal\n */\nexport const layer = (options?: { readonly timeout?: Duration.Input }) =>\n Layer.effect(\n PushLock,\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const random = yield* SecureRandom.SecureRandom;\n const timeout = options?.timeout ?? Duration.minutes(10);\n const lock = Effect.fn(\"PushLock.lock\")(\n function* (deploymentName: string, scope: Scope.Scope) {\n const failed = (reason: PushLockError[\"reason\"]) =>\n PushLockError.make({ deploymentName, reason });\n const cache = yield* userCache.pipe(\n Effect.mapError(() => failed(\"configuration\")),\n );\n if (Option.isNone(cache)) return yield* failed(\"configuration\");\n yield* FileLock.acquire(\n path.join(\n cache.value,\n \"confect\",\n \"alchemy\",\n \"locks\",\n `${deploymentName}.lock`,\n ),\n timeout,\n ).pipe(\n Scope.provide(scope),\n Effect.mapError((error) =>\n failed(error.reason === \"timeout\" ? \"timeout\" : \"filesystem\"),\n ),\n );\n },\n Effect.provideService(FileSystem.FileSystem, fs),\n Effect.provideService(Path.Path, path),\n Effect.provideService(SecureRandom.SecureRandom, random),\n );\n return PushLock.of({\n withLock: (deploymentName, effect) =>\n Effect.acquireUseRelease(\n Scope.make(),\n (scope) => lock(deploymentName, scope).pipe(Effect.andThen(effect)),\n (scope, exit) => Scope.close(scope, exit),\n ),\n });\n }),\n );\n"],"mappings":";;;;;;;;;;;;;AAaA,IAAa,gBAAb,cAAmC,OAAO,YAGxC,CAAC,CAAC,iBAAiB;CACnB,gBAAgB,OAAO;CACvB,QAAQ,OAAO,SAAS;EAAC;EAAiB;EAAW;CAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"PushLock.js","names":["FileLock.acquire"],"sources":["../../src/internal/PushLock.ts"],"sourcesContent":["import * as Context from \"effect/Context\";\nimport * as SecureRandom from \"effect/crypto/SecureRandom\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as FileLock from \"./FileLock.js\";\nimport { userCache } from \"./UserCache.js\";\n\nexport class PushLockError extends Schema.TaggedError<\n PushLockError,\n { readonly brand: unique symbol }\n>()(\"PushLockError\", {\n deploymentName: Schema.String,\n reason: Schema.Literals([\"configuration\", \"timeout\", \"filesystem\"]),\n missing: Schema.Literals([\"PushLock\"]).pipe(Schema.optionalKey),\n}) {\n override get message() {\n switch (this.reason) {\n case \"configuration\":\n return this.missing === \"PushLock\"\n ? `Push lock for ${this.deploymentName} needs the PushLock service to be provided`\n : `Push lock for ${this.deploymentName} needs a home directory to keep its lock file in`;\n case \"timeout\":\n return `Timed out waiting for another push to ${this.deploymentName} to release its push lock`;\n case \"filesystem\":\n return `Push lock for ${this.deploymentName} could not read or write its lock file`;\n }\n }\n}\n\n/**\n * Serialises pushes per deployment. Overlapping `convex deploy` runs against\n * one deployment race on `wait_for_schema`, so every push holds the lock for\n * its whole duration, whichever stack, checkout, or process it comes from.\n */\nexport class PushLock extends Context.Service<\n PushLock,\n {\n readonly withLock: <A, E, R>(\n deploymentName: string,\n effect: Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E | PushLockError, R>;\n }\n>()(\"@confect/alchemy/internal/PushLock\") {}\n\n/**\n * One lock file per deployment under the user's cache,\n * `confect/alchemy/locks/<deployment>.lock`, so every checkout on the machine\n * shares it. A lock left by a process that exited is taken over; a holder that\n * never releases ends in a typed timeout.\n *\n * @internal\n */\nexport const layer = (options?: { readonly timeout?: Duration.Input }) =>\n Layer.effect(\n PushLock,\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const random = yield* SecureRandom.SecureRandom;\n const timeout = options?.timeout ?? Duration.minutes(10);\n const lock = Effect.fn(\"PushLock.lock\")(\n function* (deploymentName: string, scope: Scope.Scope) {\n const failed = (reason: PushLockError[\"reason\"]) =>\n PushLockError.make({ deploymentName, reason });\n const cache = yield* userCache.pipe(\n Effect.mapError(() => failed(\"configuration\")),\n );\n if (Option.isNone(cache)) return yield* failed(\"configuration\");\n yield* FileLock.acquire(\n path.join(\n cache.value,\n \"confect\",\n \"alchemy\",\n \"locks\",\n `${deploymentName}.lock`,\n ),\n timeout,\n ).pipe(\n Scope.provide(scope),\n Effect.mapError((error) =>\n failed(error.reason === \"timeout\" ? \"timeout\" : \"filesystem\"),\n ),\n );\n },\n Effect.provideService(FileSystem.FileSystem, fs),\n Effect.provideService(Path.Path, path),\n Effect.provideService(SecureRandom.SecureRandom, random),\n );\n return PushLock.of({\n withLock: (deploymentName, effect) =>\n Effect.acquireUseRelease(\n Scope.make(),\n (scope) => lock(deploymentName, scope).pipe(Effect.andThen(effect)),\n (scope, exit) => Scope.close(scope, exit),\n ),\n });\n }),\n );\n"],"mappings":";;;;;;;;;;;;;AAaA,IAAa,gBAAb,cAAmC,OAAO,YAGxC,CAAC,CAAC,iBAAiB;CACnB,gBAAgB,OAAO;CACvB,QAAQ,OAAO,SAAS;EAAC;EAAiB;EAAW;CAAY,CAAC;CAClE,SAAS,OAAO,SAAS,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,OAAO,WAAW;AAChE,CAAC,CAAC,CAAC;CACD,IAAa,UAAU;EACrB,QAAQ,KAAK,QAAb;GACE,KAAK,iBACH,OAAO,KAAK,YAAY,aACpB,iBAAiB,KAAK,eAAe,8CACrC,iBAAiB,KAAK,eAAe;GAC3C,KAAK,WACH,OAAO,yCAAyC,KAAK,eAAe;GACtE,KAAK,cACH,OAAO,iBAAiB,KAAK,eAAe;EAChD;CACF;AACF;;;;;;AAOA,IAAa,WAAb,cAA8B,QAAQ,QAQpC,CAAC,CAAC,oCAAoC,CAAC,CAAC,CAAC;;;;;;;;;AAU3C,MAAa,SAAS,YACpB,MAAM,OACJ,UACA,OAAO,IAAI,aAAa;CACtB,MAAM,KAAK,OAAO,WAAW;CAC7B,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,SAAS,OAAO,aAAa;CACnC,MAAM,UAAU,SAAS,WAAW,SAAS,QAAQ,EAAE;CACvD,MAAM,OAAO,OAAO,GAAG,eAAe,CAAC,CACrC,WAAW,gBAAwB,OAAoB;EACrD,MAAM,UAAU,WACd,cAAc,KAAK;GAAE;GAAgB;EAAO,CAAC;EAC/C,MAAM,QAAQ,OAAO,UAAU,KAC7B,OAAO,eAAe,OAAO,eAAe,CAAC,CAC/C;EACA,IAAI,OAAO,OAAO,KAAK,GAAG,OAAO,OAAO,OAAO,eAAe;EAC9D,OAAOA,QACL,KAAK,KACH,MAAM,OACN,WACA,WACA,SACA,GAAG,eAAe,MACpB,GACA,OACF,CAAC,CAAC,KACA,MAAM,QAAQ,KAAK,GACnB,OAAO,UAAU,UACf,OAAO,MAAM,WAAW,YAAY,YAAY,YAAY,CAC9D,CACF;CACF,GACA,OAAO,eAAe,WAAW,YAAY,EAAE,GAC/C,OAAO,eAAe,KAAK,MAAM,IAAI,GACrC,OAAO,eAAe,aAAa,cAAc,MAAM,CACzD;CACA,OAAO,SAAS,GAAG,EACjB,WAAW,gBAAgB,WACzB,OAAO,kBACL,MAAM,KAAK,IACV,UAAU,KAAK,gBAAgB,KAAK,CAAC,CAAC,KAAK,OAAO,QAAQ,MAAM,CAAC,IACjE,OAAO,SAAS,MAAM,MAAM,OAAO,IAAI,CAC1C,EACJ,CAAC;AACH,CAAC,CACH"}
|
package/package.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gaganref/confect-alchemy",
|
|
3
|
-
"version": "10.6.0-fork.
|
|
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.
|
|
9
|
-
"@confect/core": "npm:@gaganref/confect-core@10.6.0-fork.
|
|
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";
|
package/src/ConvexClient.ts
CHANGED
|
@@ -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)
|
|
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
|
) {
|