Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache API tests #447

Merged
merged 8 commits into from
Nov 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 35 additions & 21 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion packages/tre/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,14 @@
"kleur": "^4.1.5",
"source-map-support": "0.5.21",
"stoppable": "^1.1.0",
"undici": "^5.12.0",
"undici": "^5.13.0",
"workerd": "^1.20221111.5",
"ws": "^8.11.0",
"youch": "^3.2.2",
"zod": "^3.18.0"
},
"devDependencies": {
"@cloudflare/workers-types": "^4.20221111.1",
"@types/better-sqlite3": "^7.6.2",
"@types/debug": "^4.1.7",
"@types/estree": "^1.0.0",
Expand Down
47 changes: 29 additions & 18 deletions packages/tre/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ import {
serializeConfig,
} from "./runtime";
import {
Clock,
HttpError,
Log,
MiniflareCoreError,
Expand All @@ -54,6 +55,7 @@ import {
OptionalZodTypeOf,
UnionToIntersection,
ValueOf,
defaultClock,
} from "./shared";
import { anyAbortSignal } from "./shared/signal";
import { waitForRequest } from "./wait";
Expand Down Expand Up @@ -157,6 +159,7 @@ export class Miniflare {
#sharedOpts: PluginSharedOptions;
#workerOpts: PluginWorkerOptions[];
#log: Log;
readonly #clock: Clock;

readonly #runtimeConstructor: RuntimeConstructor;
#runtime?: Runtime;
Expand Down Expand Up @@ -201,6 +204,7 @@ export class Miniflare {
this.#sharedOpts = sharedOpts;
this.#workerOpts = workerOpts;
this.#log = this.#sharedOpts.core.log ?? new NoOpLog();
this.#clock = this.#sharedOpts.core.clock ?? defaultClock;
this.#initPlugins();

// Get supported shell for executing runtime binary
Expand All @@ -220,6 +224,7 @@ export class Miniflare {
if (plugin.gateway !== undefined && plugin.router !== undefined) {
const gatewayFactory = new GatewayFactory<any>(
this.#log,
this.#clock,
this.#sharedOpts.core.cloudflareFetch,
key,
plugin.gateway,
Expand Down Expand Up @@ -350,24 +355,30 @@ export class Miniflare {
});

let response: Response | undefined;
const customService = request.headers.get(HEADER_CUSTOM_SERVICE);
if (customService !== null) {
response = await this.#handleLoopbackCustomService(
request,
customService
);
} else if (url.pathname === "/core/error") {
const workerSrcOpts = this.#workerOpts.map<SourceOptions>(
({ core }) => core
);
response = await handlePrettyErrorRequest(
this.#log,
workerSrcOpts,
request
);
} else {
// TODO: check for proxying/outbound fetch header first (with plans for fetch mocking)
response = await this.#handleLoopbackPlugins(request, url);
try {
const customService = request.headers.get(HEADER_CUSTOM_SERVICE);
if (customService !== null) {
response = await this.#handleLoopbackCustomService(
request,
customService
);
} else if (url.pathname === "/core/error") {
const workerSrcOpts = this.#workerOpts.map<SourceOptions>(
({ core }) => core
);
response = await handlePrettyErrorRequest(
this.#log,
workerSrcOpts,
request
);
} else {
// TODO: check for proxying/outbound fetch header first (with plans for fetch mocking)
response = await this.#handleLoopbackPlugins(request, url);
}
} catch (e: any) {
this.#log.error(e);
res.writeHead(500);
return res.end(e?.stack ?? String(e));
}

if (response === undefined) {
Expand Down
35 changes: 22 additions & 13 deletions packages/tre/src/plugins/cache/gateway.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import assert from "assert";
import crypto from "crypto";
import http from "http";
import { AddressInfo } from "net";
Expand Down Expand Up @@ -171,12 +172,13 @@ class HttpParser {
});
}
private listen(request: http.IncomingMessage, response: http.ServerResponse) {
if (request.url) {
response?.socket?.write(
this.responses.get(request.url) ?? new Uint8Array()
);
}
response.end();
assert(request.url !== undefined);
assert(response.socket !== null);
const array = this.responses.get(request.url);
assert(array !== undefined);
// Write response to parse directly to underlying socket
response.socket.write(array);
response.socket.end();
}
public async parse(response: Uint8Array): Promise<ParsedHttpResponse> {
await this.connected;
Expand Down Expand Up @@ -207,11 +209,12 @@ export class CacheGateway {
private readonly clock: Clock
) {}

async match(request: Request): Promise<Response> {
async match(request: Request, cacheKey?: string): Promise<Response> {
mrbbot marked this conversation as resolved.
Show resolved Hide resolved
// Never cache Workers Sites requests, so we always return on-disk files
if (isSitesRequest(request)) throw new CacheMiss();

const cached = await this.storage.get<CacheMetadata>(request.url);
cacheKey ??= request.url;
const cached = await this.storage.get<CacheMetadata>(cacheKey);
if (cached?.metadata === undefined) throw new CacheMiss();

const response = new CacheResponse(
Expand All @@ -228,11 +231,15 @@ export class CacheGateway {
);
}

async put(request: Request, value: ArrayBuffer): Promise<Response> {
async put(
request: Request,
value: Uint8Array,
cacheKey?: string
mrbbot marked this conversation as resolved.
Show resolved Hide resolved
): Promise<Response> {
// Never cache Workers Sites requests, so we always return on-disk files
if (isSitesRequest(request)) return new Response(null, { status: 204 });

const response = await HttpParser.get().parse(new Uint8Array(value));
const response = await HttpParser.get().parse(value);

const { storable, expiration, headers } = getExpiration(
this.clock,
Expand All @@ -246,7 +253,8 @@ export class CacheGateway {
throw new StorageFailure();
}

await this.storage.put<CacheMetadata>(request.url, {
cacheKey ??= request.url;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clever

await this.storage.put<CacheMetadata>(cacheKey, {
value: response.body,
expiration: millisToSeconds(this.clock() + expiration),
metadata: {
Expand All @@ -257,8 +265,9 @@ export class CacheGateway {
return new Response(null, { status: 204 });
}

async delete(request: Request): Promise<Response> {
const deleted = await this.storage.delete(request.url);
async delete(request: Request, cacheKey?: string): Promise<Response> {
cacheKey ??= request.url;
const deleted = await this.storage.delete(cacheKey);
// This is an extremely vague error, but it fits with what the cache API in workerd expects
if (!deleted) throw new PurgeFailure();
return new Response(null);
Expand Down
1 change: 1 addition & 0 deletions packages/tre/src/plugins/cache/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,3 +97,4 @@ export const CACHE_PLUGIN: Plugin<
};

export * from "./gateway";
export * from "./range";
Loading