Compare commits

...

1 Commits

17 changed files with 5854 additions and 184 deletions
+6 -6
View File
@@ -9,16 +9,16 @@ beforeAll(disableConsoleLog);
afterAll(enableConsoleLog); afterAll(enableConsoleLog);
describe("adapter", () => { describe("adapter", () => {
it("makes config", () => { it("makes config", async () => {
expect(omitKeys(adapter.makeConfig({}), ["connection"])).toEqual({}); expect(omitKeys(await adapter.makeConfig({}), ["connection"])).toEqual({});
expect(omitKeys(adapter.makeConfig({}, { env: { TEST: "test" } }), ["connection"])).toEqual( expect(
{}, omitKeys(await adapter.makeConfig({}, { env: { TEST: "test" } }), ["connection"]),
); ).toEqual({});
// merges everything returned from `app` with the config // merges everything returned from `app` with the config
expect( expect(
omitKeys( omitKeys(
adapter.makeConfig( await adapter.makeConfig(
{ app: (a) => ({ initialConfig: { server: { cors: { origin: a.env.TEST } } } }) }, { app: (a) => ({ initialConfig: { server: { cors: { origin: a.env.TEST } } } }) },
{ env: { TEST: "test" } }, { env: { TEST: "test" } },
), ),
@@ -18,7 +18,7 @@ describe("cf adapter", () => {
}); });
it("makes config", async () => { it("makes config", async () => {
const staticConfig = makeConfig( const staticConfig = await makeConfig(
{ {
connection: { url: DB_URL }, connection: { url: DB_URL },
initialConfig: { data: { basepath: DB_URL } }, initialConfig: { data: { basepath: DB_URL } },
@@ -28,7 +28,7 @@ describe("cf adapter", () => {
expect(staticConfig.initialConfig).toEqual({ data: { basepath: DB_URL } }); expect(staticConfig.initialConfig).toEqual({ data: { basepath: DB_URL } });
expect(staticConfig.connection).toBeDefined(); expect(staticConfig.connection).toBeDefined();
const dynamicConfig = makeConfig( const dynamicConfig = await makeConfig(
{ {
app: (env) => ({ app: (env) => ({
initialConfig: { data: { basepath: env.DB_URL } }, initialConfig: { data: { basepath: env.DB_URL } },
@@ -5,7 +5,6 @@ import { Hono } from "hono";
import { serveStatic } from "hono/cloudflare-workers"; import { serveStatic } from "hono/cloudflare-workers";
import { getFresh } from "./modes/fresh"; import { getFresh } from "./modes/fresh";
import { getCached } from "./modes/cached"; import { getCached } from "./modes/cached";
import { getDurable } from "./modes/durable";
import type { App } from "bknd"; import type { App } from "bknd";
import { $console } from "core/utils"; import { $console } from "core/utils";
@@ -17,10 +16,9 @@ declare global {
export type CloudflareEnv = Cloudflare.Env; export type CloudflareEnv = Cloudflare.Env;
export type CloudflareBkndConfig<Env = CloudflareEnv> = RuntimeBkndConfig<Env> & { export type CloudflareBkndConfig<Env = CloudflareEnv> = RuntimeBkndConfig<Env> & {
mode?: "warm" | "fresh" | "cache" | "durable"; mode?: "warm" | "fresh" | "cache";
bindings?: (args: Env) => { bindings?: (args: Env) => {
kv?: KVNamespace; kv?: KVNamespace;
dobj?: DurableObjectNamespace;
db?: D1Database; db?: D1Database;
}; };
d1?: { d1?: {
@@ -93,8 +91,6 @@ export function serve<Env extends CloudflareEnv = CloudflareEnv>(
case "cache": case "cache":
app = await getCached(config, context); app = await getCached(config, context);
break; break;
case "durable":
return await getDurable(config, context);
default: default:
throw new Error(`Unknown mode ${mode}`); throw new Error(`Unknown mode ${mode}`);
} }
+3 -3
View File
@@ -89,7 +89,7 @@ export function d1SessionHelper(config: CloudflareBkndConfig<any>) {
} }
let media_registered: boolean = false; let media_registered: boolean = false;
export function makeConfig<Env extends CloudflareEnv = CloudflareEnv>( export async function makeConfig<Env extends CloudflareEnv = CloudflareEnv>(
config: CloudflareBkndConfig<Env>, config: CloudflareBkndConfig<Env>,
args?: CfMakeConfigArgs<Env>, args?: CfMakeConfigArgs<Env>,
) { ) {
@@ -102,7 +102,7 @@ export function makeConfig<Env extends CloudflareEnv = CloudflareEnv>(
media_registered = true; media_registered = true;
} }
const appConfig = makeAdapterConfig(config, args?.env); const appConfig = await makeAdapterConfig(config, args?.env);
// if connection instance is given, don't do anything // if connection instance is given, don't do anything
// other than checking if D1 session is defined // other than checking if D1 session is defined
@@ -115,7 +115,7 @@ export function makeConfig<Env extends CloudflareEnv = CloudflareEnv>(
} }
// if connection is given, try to open with unified sqlite adapter // if connection is given, try to open with unified sqlite adapter
} else if (appConfig.connection) { } else if (appConfig.connection) {
appConfig.connection = sqlite(appConfig.connection); appConfig.connection = sqlite(appConfig.connection) as any;
// if connection is not given, but env is set // if connection is not given, but env is set
// try to make D1 from bindings // try to make D1 from bindings
-1
View File
@@ -3,7 +3,6 @@ import { d1Sqlite, type D1ConnectionConfig } from "./connection/D1Connection";
export * from "./cloudflare-workers.adapter"; export * from "./cloudflare-workers.adapter";
export { makeApp, getFresh } from "./modes/fresh"; export { makeApp, getFresh } from "./modes/fresh";
export { getCached } from "./modes/cached"; export { getCached } from "./modes/cached";
export { DurableBkndApp, getDurable } from "./modes/durable";
export { d1Sqlite, type D1ConnectionConfig }; export { d1Sqlite, type D1ConnectionConfig };
export { export {
getBinding, getBinding,
-134
View File
@@ -1,134 +0,0 @@
import { DurableObject } from "cloudflare:workers";
import type { App, CreateAppConfig } from "bknd";
import { createRuntimeApp, makeConfig } from "bknd/adapter";
import type { CloudflareBkndConfig, Context, CloudflareEnv } from "../index";
import { constants, registerAsyncsExecutionContext } from "../config";
import { $console } from "core/utils";
export async function getDurable<Env extends CloudflareEnv = CloudflareEnv>(
config: CloudflareBkndConfig<Env>,
ctx: Context<Env>,
) {
const { dobj } = config.bindings?.(ctx.env)!;
if (!dobj) throw new Error("durable object is not defined in cloudflare.bindings");
const key = config.key ?? "app";
if ([config.onBuilt, config.beforeBuild].some((x) => x)) {
$console.warn("onBuilt and beforeBuild are not supported with DurableObject mode");
}
const start = performance.now();
const id = dobj.idFromName(key);
const stub = dobj.get(id) as unknown as DurableBkndApp;
const create_config = makeConfig(config, ctx.env);
const res = await stub.fire(ctx.request, {
config: create_config,
keepAliveSeconds: config.keepAliveSeconds,
});
const headers = new Headers(res.headers);
headers.set("X-TTDO", String(performance.now() - start));
return new Response(res.body, {
status: res.status,
statusText: res.statusText,
headers,
});
}
export class DurableBkndApp extends DurableObject {
protected id = Math.random().toString(36).slice(2);
protected app?: App;
protected interval?: any;
async fire(
request: Request,
options: {
config: CreateAppConfig;
html?: string;
keepAliveSeconds?: number;
setAdminHtml?: boolean;
},
) {
let buildtime = 0;
if (!this.app) {
const start = performance.now();
const config = options.config;
// change protocol to websocket if libsql
if (
config?.connection &&
"type" in config.connection &&
config.connection.type === "libsql"
) {
//config.connection.config.protocol = "wss";
}
this.app = await createRuntimeApp({
...config,
onBuilt: async (app) => {
registerAsyncsExecutionContext(app, this.ctx);
app.modules.server.get(constants.do_endpoint, async (c) => {
// @ts-ignore
const context: any = c.req.raw.cf ? c.req.raw.cf : c.env.cf;
return c.json({
id: this.id,
keepAliveSeconds: options?.keepAliveSeconds ?? 0,
colo: context.colo,
});
});
await this.onBuilt(app);
},
adminOptions: { html: options.html },
beforeBuild: async (app) => {
await this.beforeBuild(app);
},
});
buildtime = performance.now() - start;
}
if (options?.keepAliveSeconds) {
this.keepAlive(options.keepAliveSeconds);
}
const res = await this.app!.fetch(request);
const headers = new Headers(res.headers);
headers.set("X-BuildTime", buildtime.toString());
headers.set("X-DO-ID", this.id);
return new Response(res.body, {
status: res.status,
statusText: res.statusText,
headers,
});
}
async onBuilt(app: App) {}
async beforeBuild(app: App) {}
protected keepAlive(seconds: number) {
if (this.interval) {
clearInterval(this.interval);
}
let i = 0;
this.interval = setInterval(() => {
i += 1;
if (i === seconds) {
console.log("cleared");
clearInterval(this.interval);
// ping every 30 seconds
} else if (i % 30 === 0) {
console.log("ping");
this.app?.modules.ctx().connection.ping();
}
}, 1000);
}
}
+1 -1
View File
@@ -7,7 +7,7 @@ export async function makeApp<Env extends CloudflareEnv = CloudflareEnv>(
args?: CfMakeConfigArgs<Env>, args?: CfMakeConfigArgs<Env>,
opts?: RuntimeOptions, opts?: RuntimeOptions,
) { ) {
return await createRuntimeApp<Env>(makeConfig(config, args), args?.env, opts); return await createRuntimeApp<Env>(await makeConfig(config, args), args?.env, opts);
} }
export async function getFresh<Env extends CloudflareEnv = CloudflareEnv>( export async function getFresh<Env extends CloudflareEnv = CloudflareEnv>(
@@ -1,4 +1,4 @@
import { registries, isDebug, guessMimeType } from "bknd"; import { registries as $registries, isDebug, guessMimeType } from "bknd";
import { getBindings } from "../bindings"; import { getBindings } from "../bindings";
import { s } from "bknd/utils"; import { s } from "bknd/utils";
import { StorageAdapter, type FileBody } from "bknd"; import { StorageAdapter, type FileBody } from "bknd";
@@ -12,7 +12,10 @@ export function makeSchema(bindings: string[] = []) {
); );
} }
export function registerMedia(env: Record<string, any>) { export function registerMedia(
env: Record<string, any>,
registries: typeof $registries = $registries,
) {
const r2_bindings = getBindings(env, "R2Bucket"); const r2_bindings = getBindings(env, "R2Bucket");
registries.media.register( registries.media.register(
+18 -10
View File
@@ -1,13 +1,21 @@
import { config as $config, App, type CreateAppConfig, Connection, guessMimeType } from "bknd"; import {
config as $config,
App,
type CreateAppConfig,
Connection,
guessMimeType,
type MaybePromise,
registries as $registries,
} from "bknd";
import { $console } from "bknd/utils"; import { $console } from "bknd/utils";
import type { Context, MiddlewareHandler, Next } from "hono"; import type { Context, MiddlewareHandler, Next } from "hono";
import type { AdminControllerOptions } from "modules/server/AdminController"; import type { AdminControllerOptions } from "modules/server/AdminController";
import type { Manifest } from "vite"; import type { Manifest } from "vite";
export type BkndConfig<Args = any> = CreateAppConfig & { export type BkndConfig<Args = any> = CreateAppConfig & {
app?: CreateAppConfig | ((args: Args) => CreateAppConfig); app?: CreateAppConfig | ((args: Args) => MaybePromise<CreateAppConfig>);
onBuilt?: (app: App) => Promise<void>; onBuilt?: (app: App) => Promise<void>;
beforeBuild?: (app: App) => Promise<void>; beforeBuild?: (app: App, registries?: typeof $registries) => Promise<void>;
buildConfig?: Parameters<App["build"]>[0]; buildConfig?: Parameters<App["build"]>[0];
}; };
@@ -30,10 +38,10 @@ export type DefaultArgs = {
[key: string]: any; [key: string]: any;
}; };
export function makeConfig<Args = DefaultArgs>( export async function makeConfig<Args = DefaultArgs>(
config: BkndConfig<Args>, config: BkndConfig<Args>,
args?: Args, args?: Args,
): CreateAppConfig { ): Promise<CreateAppConfig> {
let additionalConfig: CreateAppConfig = {}; let additionalConfig: CreateAppConfig = {};
const { app, ...rest } = config; const { app, ...rest } = config;
if (app) { if (app) {
@@ -41,7 +49,7 @@ export function makeConfig<Args = DefaultArgs>(
if (!args) { if (!args) {
throw new Error("args is required when config.app is a function"); throw new Error("args is required when config.app is a function");
} }
additionalConfig = app(args); additionalConfig = await app(args);
} else { } else {
additionalConfig = app; additionalConfig = app;
} }
@@ -60,7 +68,7 @@ export async function createAdapterApp<Config extends BkndConfig = BkndConfig, A
const id = opts?.id ?? "app"; const id = opts?.id ?? "app";
let app = apps.get(id); let app = apps.get(id);
if (!app || opts?.force) { if (!app || opts?.force) {
const appConfig = makeConfig(config, args); const appConfig = await makeConfig(config, args);
if (!appConfig.connection || !Connection.isConnection(appConfig.connection)) { if (!appConfig.connection || !Connection.isConnection(appConfig.connection)) {
let connection: Connection | undefined; let connection: Connection | undefined;
if (Connection.isConnection(config.connection)) { if (Connection.isConnection(config.connection)) {
@@ -68,7 +76,7 @@ export async function createAdapterApp<Config extends BkndConfig = BkndConfig, A
} else { } else {
const sqlite = (await import("bknd/adapter/sqlite")).sqlite; const sqlite = (await import("bknd/adapter/sqlite")).sqlite;
const conf = appConfig.connection ?? { url: ":memory:" }; const conf = appConfig.connection ?? { url: ":memory:" };
connection = sqlite(conf); connection = sqlite(conf) as any;
$console.info(`Using ${connection!.name} connection`, conf.url); $console.info(`Using ${connection!.name} connection`, conf.url);
} }
appConfig.connection = connection; appConfig.connection = connection;
@@ -98,7 +106,7 @@ export async function createFrameworkApp<Args = DefaultArgs>(
); );
} }
await config.beforeBuild?.(app); await config.beforeBuild?.(app, $registries);
await app.build(config.buildConfig); await app.build(config.buildConfig);
} }
@@ -131,7 +139,7 @@ export async function createRuntimeApp<Args = DefaultArgs>(
"sync", "sync",
); );
await config.beforeBuild?.(app); await config.beforeBuild?.(app, $registries);
await app.build(config.buildConfig); await app.build(config.buildConfig);
} }
+1 -1
View File
@@ -77,7 +77,7 @@ async function makeApp(config: MakeAppConfig) {
} }
export async function makeConfigApp(_config: CliBkndConfig, platform?: Platform) { export async function makeConfigApp(_config: CliBkndConfig, platform?: Platform) {
const config = makeConfig(_config, process.env); const config = await makeConfig(_config, process.env);
return makeApp({ return makeApp({
...config, ...config,
server: { platform }, server: { platform },
+1
View File
@@ -39,6 +39,7 @@ export { registries } from "modules/registries";
/** /**
* Core * Core
*/ */
export type { MaybePromise } from "core/types";
export { Exception, BkndError } from "core/errors"; export { Exception, BkndError } from "core/errors";
export { isDebug, env } from "core/env"; export { isDebug, env } from "core/env";
export { type PrimaryFieldType, config, type DB, type AppEntity } from "core/config"; export { type PrimaryFieldType, config, type DB, type AppEntity } from "core/config";
+2
View File
@@ -170,3 +170,5 @@ dist
.dev.vars .dev.vars
.wrangler/ .wrangler/
bknd-types.d.ts
worker-configuration.d.ts
+47
View File
@@ -0,0 +1,47 @@
/**
* The configuration below is for advanced use cases. In order to enable types generation,
* we need access to the database. However, for Cloudflare D1, we need the platform proxy.
*
* Since this configuration should serve all purposes, including usage within the worker itself,
* we need to use an environment variable to determine if we need to extract the DB from proxy.
*
* To make D1 session work in the actual worker,
*/
import { d1, registerMedia, type CloudflareBkndConfig } from "bknd/adapter/cloudflare";
import type { PlatformProxy } from "wrangler";
import process from "node:process";
const use_proxy = process.env.PROXY === "1";
let proxy: PlatformProxy | undefined;
async function getEnv(env?: Env): Promise<Env> {
if (use_proxy) {
if (!proxy) {
const getPlatformProxy = await import("wrangler").then((mod) => mod.getPlatformProxy);
proxy = await getPlatformProxy();
setTimeout(proxy?.dispose, 1000);
}
return proxy.env as unknown as Env;
}
return env!;
}
export default {
app: async (_env) => {
if (!use_proxy) return {};
const env = await getEnv(_env);
return {
connection: d1({
binding: env.DB,
}),
};
},
beforeBuild: async (app, registries) => {
if (!use_proxy) return;
registerMedia(await getEnv(), registries);
},
d1: {
session: true,
},
} satisfies CloudflareBkndConfig<Env>;
+4 -1
View File
@@ -2,10 +2,13 @@
"name": "cloudflare-worker", "name": "cloudflare-worker",
"version": "0.0.0", "version": "0.0.0",
"private": true, "private": true,
"type": "module",
"scripts": { "scripts": {
"deploy": "wrangler deploy", "deploy": "wrangler deploy",
"dev": "wrangler dev", "dev": "wrangler dev",
"typegen": "wrangler types" "bknd-typegen": "PROXY=1 npx bknd types",
"typegen": "wrangler types && npm run bknd-typegen",
"predev": "npm run typegen"
}, },
"dependencies": { "dependencies": {
"bknd": "file:../../app" "bknd": "file:../../app"
+2 -6
View File
@@ -1,8 +1,4 @@
import { serve } from "bknd/adapter/cloudflare"; import { serve } from "bknd/adapter/cloudflare";
import config from "../bknd.config";
export default serve({ export default serve(config);
mode: "warm",
d1: {
session: true,
},
});
+10 -7
View File
@@ -1,11 +1,9 @@
{ {
"compilerOptions": { "compilerOptions": {
"target": "es2021", "lib": ["ES2022"],
"lib": ["es2021"], "target": "ES2022",
"jsx": "react-jsx", "module": "ES2022",
"module": "es2022", "moduleResolution": "bundler",
"moduleResolution": "Bundler",
"types": ["./worker-configuration.d.ts"],
"resolveJsonModule": true, "resolveJsonModule": true,
"allowJs": true, "allowJs": true,
"checkJs": false, "checkJs": false,
@@ -18,5 +16,10 @@
"skipLibCheck": true "skipLibCheck": true
}, },
"exclude": ["test"], "exclude": ["test"],
"include": ["worker-configuration.d.ts", "src/**/*.ts"] "include": [
"worker-configuration.d.ts",
"bknd-types.d.ts",
"bknd.config.ts",
"src/**/*.ts"
]
} }
File diff suppressed because it is too large Load Diff