Skip to content

Commit

Permalink
Resource provisioning
Browse files Browse the repository at this point in the history
  • Loading branch information
penalosa committed Oct 3, 2024
1 parent eb48c7c commit f544b2a
Show file tree
Hide file tree
Showing 8 changed files with 302 additions and 115 deletions.
18 changes: 14 additions & 4 deletions fixtures/worker-ts/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
*/
export interface Env {
// Example binding to KV. Learn more at https://developers.cloudflare.com/workers/runtime-apis/kv/
// MY_KV_NAMESPACE: KVNamespace;
MY_KV_NAMESPACE: KVNamespace;
//
// Example binding to Durable Object. Learn more at https://developers.cloudflare.com/workers/runtime-apis/durable-objects/
// MY_DURABLE_OBJECT: DurableObjectNamespace;
Expand All @@ -27,8 +27,18 @@ export default {
env: Env,
ctx: ExecutionContext
): Promise<Response> {
const url = new URL(request.url);
if (url.pathname === "/error") throw new Error("Hello Error");
return new Response("Hello World!");
try {
await env.MY_KV_NAMESPACE.put("KEY", "VALUE");
const value = await env.MY_KV_NAMESPACE.get("KEY");
if (value === null) {
return new Response("Value not found", { status: 404 });
}
return new Response(value);
} catch (err) {
// In a production application, you could instead choose to retry your KV
// read or fall back to a default code path.
console.error(`KV returned error: ${err}`);
return new Response(err, { status: 500 });
}
},
};
30 changes: 16 additions & 14 deletions fixtures/worker-ts/wrangler.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,26 @@ main = "src/index.ts"
compatibility_date = "2023-05-04"

[vars]
HELLO = "WORLD"
HELLO2 = "WORLD"
HELLO3 = "WORLD"
HELLO4 = "WORLD"
HELLO5 = "WORLD"
HELLO="WORLD"

# Bind a D1 database. D1 is Cloudflare’s native serverless SQL database.
# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#d1-databases
[[d1_databases]]
binding = "MY_DB"
# database_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"

# Bind a KV Namespace. Use KV as persistent storage for small key-value pairs.
# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#kv-namespaces
[[kv_namespaces]]
binding = "SOME_BINDING"
id = "0408d79206d54e859284b605fb19bff4"
binding = "MY_KV_NAMESPACE"

[[kv_namespaces]]
binding = "BINDING2"
id = "01962077d09242c5b0978a12bccaa5ed"
binding = "MY_KV_NAMESPACE_2"

[[kv_namespaces]]
binding = "SOME_BINDING2"
id = "06e46ea96ab9494dae07a2f745f7adc1"

[[kv_namespaces]]
binding = "BINDING45"
# id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

# Bind an R2 Bucket. Use R2 to store arbitrarily large blobs of data, such as files.
# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#r2-buckets
[[r2_buckets]]
binding = "MY_BUCKET2"
17 changes: 12 additions & 5 deletions packages/wrangler/src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,10 @@ export function findWranglerToml(
/**
* Print all the bindings a worker using a given config would have access to
*/
export function printBindings(bindings: CfWorkerInit["bindings"]) {
export function printBindings(
bindings: CfWorkerInit["bindings"],
creation: boolean
) {
const truncate = (item: string | Record<string, unknown>) => {
const s = typeof item === "string" ? item : JSON.stringify(item);
const maxLength = 40;
Expand All @@ -207,7 +210,7 @@ export function printBindings(bindings: CfWorkerInit["bindings"]) {

const output: {
type: string;
entries: { key: string; value: string | boolean }[];
entries: { key: string; value: string | boolean | undefined }[];
}[] = [];

const {
Expand Down Expand Up @@ -313,7 +316,7 @@ export function printBindings(bindings: CfWorkerInit["bindings"]) {
type: "D1 Databases",
entries: d1_databases.map(
({ binding, database_name, database_id, preview_database_id }) => {
let databaseValue = `${database_id}`;
let databaseValue = database_id;
if (database_name) {
databaseValue = `${database_name} (${database_id})`;
}
Expand Down Expand Up @@ -542,12 +545,16 @@ export function printBindings(bindings: CfWorkerInit["bindings"]) {
}

const message = [
`Your worker has access to the following bindings:`,
creation
? `The following resources need provisioned:`
: `Your worker has access to the following bindings:`,
...output
.map((bindingGroup) => {
return [
`- ${bindingGroup.type}:`,
bindingGroup.entries.map(({ key, value }) => ` - ${key}: ${value}`),
bindingGroup.entries.map(({ key, value }) =>
creation || !value ? ` - ${key}` : ` - ${key}: ${value}`
),
];
})
.flat(2),
Expand Down
12 changes: 3 additions & 9 deletions packages/wrangler/src/config/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2387,10 +2387,7 @@ const validateKVBinding: ValidatorFn = (diagnostics, field, value) => {
);
isValid = false;
}
if (
!isRequiredProperty(value, "id", "string") ||
(value as { id: string }).id.length === 0
) {
if (!isOptionalProperty(value, "id", "string")) {
diagnostics.errors.push(
`"${field}" bindings should have a string "id" field but got ${JSON.stringify(
value
Expand Down Expand Up @@ -2549,10 +2546,7 @@ const validateR2Binding: ValidatorFn = (diagnostics, field, value) => {
);
isValid = false;
}
if (
!isRequiredProperty(value, "bucket_name", "string") ||
(value as { bucket_name: string }).bucket_name.length === 0
) {
if (!isOptionalProperty(value, "bucket_name", "string")) {
diagnostics.errors.push(
`"${field}" bindings should have a string "bucket_name" field but got ${JSON.stringify(
value
Expand Down Expand Up @@ -2610,7 +2604,7 @@ const validateD1Binding: ValidatorFn = (diagnostics, field, value) => {
if (
// TODO: allow name only, where we look up the ID dynamically
// !isOptionalProperty(value, "database_name", "string") &&
!isRequiredProperty(value, "database_id", "string")
!isOptionalProperty(value, "database_id", "string")
) {
diagnostics.errors.push(
`"${field}" bindings must have a "database_id" field but got ${JSON.stringify(
Expand Down
45 changes: 26 additions & 19 deletions packages/wrangler/src/d1/create.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,31 @@ import type {
} from "../yargs-types";
import type { DatabaseCreationResult } from "./types";

export async function createD1Database(
accountId: string,
name: string,
location?: string
) {
let db: DatabaseCreationResult;
try {
db = await fetchResult(`/accounts/${accountId}/d1/database`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
name,
...(location && { primary_location_hint: location }),
}),
});
} catch (e) {
if ((e as { code: number }).code === 7502) {
throw new UserError("A database with that name already exists");
}
throw e;
}
return db;
}
export function Options(yargs: CommonYargsArgv) {
return yargs
.positional("name", {
Expand Down Expand Up @@ -42,25 +67,7 @@ export const Handler = withConfig<HandlerOptions>(
);
}
}

let db: DatabaseCreationResult;
try {
db = await fetchResult(`/accounts/${accountId}/d1/database`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
name,
...(location && { primary_location_hint: location }),
}),
});
} catch (e) {
if ((e as { code: number }).code === 7502) {
throw new UserError("A database with that name already exists");
}
throw e;
}
const db = await createD1Database(accountId, name, location);

logger.log(
renderToString(
Expand Down
Loading

0 comments on commit f544b2a

Please sign in to comment.