Skip to content

Commit

Permalink
Only send request log requests at INFO level or higher
Browse files Browse the repository at this point in the history
Building on the previous commit, avoid sending requests that might be
aborted in tests, because they're `waitUntil`ed. Without this, we
could end up with an incomplete JSON body that can't be parsed.
  • Loading branch information
mrbbot committed Nov 1, 2023
1 parent 1728637 commit e66a061
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 22 deletions.
8 changes: 2 additions & 6 deletions packages/miniflare/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -540,12 +540,7 @@ export class Miniflare {
request
);
} else if (url.pathname === "/core/log") {
if (this.#log.level < LogLevel.INFO) {
return;
}

const response = await formatResponse(request);
this.#log.log(response);
this.#log.info(await formatResponse(request));
} else {
// TODO: check for proxying/outbound fetch header first (with plans for fetch mocking)
response = await this.#handleLoopbackPlugins(request, url);
Expand Down Expand Up @@ -700,6 +695,7 @@ export class Miniflare {
allWorkerRoutes,
fallbackWorkerName: this.#workerOpts[0].core.name,
loopbackPort,
log: this.#log,
});
for (const service of globalServices) {
// Global services should all have unique names
Expand Down
18 changes: 15 additions & 3 deletions packages/miniflare/src/plugins/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,13 @@ import {
Worker_Module,
supportedCompatibilityDate,
} from "../../runtime";
import { Awaitable, JsonSchema, Log, MiniflareCoreError } from "../../shared";
import {
Awaitable,
JsonSchema,
Log,
LogLevel,
MiniflareCoreError,
} from "../../shared";
import { getCacheServiceName } from "../cache";
import { DURABLE_OBJECTS_STORAGE_SERVICE_NAME } from "../do";
import {
Expand Down Expand Up @@ -102,6 +108,7 @@ const BINDING_SERVICE_USER_FALLBACK = "MINIFLARE_USER_FALLBACK";
const BINDING_TEXT_CUSTOM_SERVICE = "MINIFLARE_CUSTOM_SERVICE";
const BINDING_JSON_CF_BLOB = "CF_BLOB";
const BINDING_JSON_ROUTES = "MINIFLARE_ROUTES";
const BINDING_JSON_LOG_LEVEL = "MINIFLARE_LOG_LEVEL";
const BINDING_DATA_LIVE_RELOAD_SCRIPT = "MINIFLARE_LIVE_RELOAD_SCRIPT";

const LIVE_RELOAD_SCRIPT_TEMPLATE = (
Expand Down Expand Up @@ -179,7 +186,8 @@ async function handleEvent(event) {
}
}
event.waitUntil(${BINDING_SERVICE_LOOPBACK}.fetch("http://localhost/core/log", {
if (${BINDING_JSON_LOG_LEVEL} >= ${LogLevel.INFO}) {
event.waitUntil(${BINDING_SERVICE_LOOPBACK}.fetch("http://localhost/core/log", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
Expand All @@ -189,7 +197,8 @@ async function handleEvent(event) {
"url": response.url,
"time": Date.now() - startTime,
}),
}));
}));
}
const liveReloadScript = globalThis.${BINDING_DATA_LIVE_RELOAD_SCRIPT};
if (
Expand Down Expand Up @@ -421,13 +430,15 @@ export interface GlobalServicesOptions {
allWorkerRoutes: Map<string, string[]>;
fallbackWorkerName: string | undefined;
loopbackPort: number;
log: Log;
}
export function getGlobalServices({
optionsVersion,
sharedOptions,
allWorkerRoutes,
fallbackWorkerName,
loopbackPort,
log,
}: GlobalServicesOptions): Service[] {
// Collect list of workers we could route to, then parse and sort all routes
const routableWorkers = [...allWorkerRoutes.keys()];
Expand All @@ -439,6 +450,7 @@ export function getGlobalServices({
{ name: BINDING_JSON_VERSION, json: optionsVersion.toString() },
{ name: BINDING_JSON_ROUTES, json: JSON.stringify(routes) },
{ name: BINDING_JSON_CF_BLOB, json: JSON.stringify(sharedOptions.cf) },
{ name: BINDING_JSON_LOG_LEVEL, json: JSON.stringify(log.level) },
{
name: BINDING_SERVICE_USER_FALLBACK,
service: { name: getUserServiceName(fallbackWorkerName) },
Expand Down
23 changes: 10 additions & 13 deletions packages/miniflare/src/shared/log.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,11 @@ export class Log {
this.#suffix = suffix ? ":" + suffix : "";
}

log(message: string): void {
protected log(message: string): void {
console.log(message);
}

logWithLevel(level: LogLevel, message: string): void {
protected logWithLevel(level: LogLevel, message: string): void {
if (level <= this.level) {
const prefix = `[${this.#prefix}${LEVEL_PREFIX[level]}${this.#suffix}]`;
this.log(LEVEL_COLOUR[level](`${prefix} ${message}`));
Expand Down Expand Up @@ -130,21 +130,17 @@ export class Log {
}

export class NoOpLog extends Log {
log(): void {}
constructor() {
super(LogLevel.NONE);
}

protected log(): void {}

error(message: Error): void {
throw message;
}
}

export interface ResponseInfo {
status: number;
statusText: string;
method: string;
url: string;
time: number;
}

const ResponseInfoSchema = z.object({
status: z.number(),
statusText: z.string(),
Expand All @@ -157,13 +153,14 @@ export async function formatResponse(request: Request) {
const info = ResponseInfoSchema.parse(await request.json());
const url = new URL(info.url);

return [
const lines = [
`${bold(info.method)} ${url.pathname} `,
colourFromHTTPStatus(info.status)(
`${bold(info.status)} ${info.statusText} `
),
grey(`(${info.time}ms)`),
].join("");
];
return reset(lines.join(""));
}

function colourFromHTTPStatus(status: number): Colorize {
Expand Down

0 comments on commit e66a061

Please sign in to comment.