Skip to content

Commit

Permalink
Support Queue events in tail
Browse files Browse the repository at this point in the history
Queue events have an "event" section containing two fields -- "queue"
and "batchSize", which contain the queue name and number of messages in
the batch. Queue events can be distinguished from other events by the
presence of the "queue" field, so that's what I do here.

I've followed the example of RequestEvent more closely than either
ScheduledEvent or AlarmEvent here, but am happy to change up the format
if there's a reason to do so.
  • Loading branch information
a-robinson committed Dec 14, 2022
1 parent 21bab6b commit 4fd4ca4
Show file tree
Hide file tree
Showing 5 changed files with 149 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/warm-queens-taste.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"wrangler": patch
---

Support Queue consumer events in tail
57 changes: 56 additions & 1 deletion packages/wrangler/src/__tests__/pages-deployment-tail.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import type {
RequestEvent,
ScheduledEvent,
AlarmEvent,
QueueEvent,
} from "../tail/createTail";
import type { RequestInit } from "undici";
import type WebSocket from "ws";
Expand Down Expand Up @@ -355,6 +356,20 @@ describe("pages deployment tail", () => {
expect(std.out).toMatch(deserializeToJson(serializedMessage));
});

it("logs queue messages in json format", async () => {
const api = mockTailAPIs();
await runWrangler(
"pages deployment tail mock-deployment-id --project-name mock-project --format json"
);

const event = generateMockQueueEvent();
const message = generateMockEventMessage({ event });
const serializedMessage = serialize(message);

api.ws.send(serializedMessage);
expect(std.out).toMatch(deserializeToJson(serializedMessage));
});

it("logs request messages in pretty format", async () => {
const api = mockTailAPIs();
await runWrangler(
Expand Down Expand Up @@ -436,6 +451,33 @@ describe("pages deployment tail", () => {
`);
});

it("logs queue messages in pretty format", async () => {
const api = mockTailAPIs();
await runWrangler(
"pages deployment tail mock-deployment-id --project-name mock-project --format pretty"
);

const event = generateMockQueueEvent();
const message = generateMockEventMessage({ event });
const serializedMessage = serialize(message);

api.ws.send(serializedMessage);
expect(
std.out
.replace(
new Date(mockEventTimestamp).toLocaleString(),
"[mock timestamp string]"
)
.replace(
mockTailExpiration.toLocaleString(),
"[mock expiration date]"
)
).toMatchInlineSnapshot(`
"Connected to deployment mock-deployment-id, waiting for logs...
Queue my-queue123 (7 messages) - Ok @ [mock timestamp string]"
`);
});

it("should not crash when the tail message has a void event", async () => {
const api = mockTailAPIs();
await runWrangler(
Expand Down Expand Up @@ -608,7 +650,13 @@ function serialize(message: TailEventMessage): WebSocket.RawData {
* @returns true if `event` is a RequestEvent
*/
function isRequest(
event: ScheduledEvent | RequestEvent | AlarmEvent | undefined | null
event:
| ScheduledEvent
| RequestEvent
| AlarmEvent
| QueueEvent
| undefined
| null
): event is RequestEvent {
return Boolean(event && "request" in event);
}
Expand Down Expand Up @@ -882,3 +930,10 @@ function generateMockAlarmEvent(opts?: Partial<AlarmEvent>): AlarmEvent {
scheduledTime: opts?.scheduledTime || mockEventScheduledTime,
};
}

function generateMockQueueEvent(opts?: Partial<QueueEvent>): QueueEvent {
return {
queue: opts?.queue || "my-queue123",
batchSize: opts?.batchSize || 7,
};
}
51 changes: 50 additions & 1 deletion packages/wrangler/src/__tests__/tail.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import type {
RequestEvent,
ScheduledEvent,
AlarmEvent,
QueueEvent,
} from "../tail/createTail";
import type { RequestInit } from "undici";
import type WebSocket from "ws";
Expand Down Expand Up @@ -398,6 +399,18 @@ describe("tail", () => {
expect(std.out).toMatch(deserializeToJson(serializedMessage));
});

it("logs queue messages in json format", async () => {
const api = mockWebsocketAPIs();
await runWrangler("tail test-worker --format json");

const event = generateMockQueueEvent();
const message = generateMockEventMessage({ event });
const serializedMessage = serialize(message);

api.ws.send(serializedMessage);
expect(std.out).toMatch(deserializeToJson(serializedMessage));
});

it("logs request messages in pretty format", async () => {
const api = mockWebsocketAPIs();
await runWrangler("tail test-worker --format pretty");
Expand Down Expand Up @@ -467,6 +480,29 @@ describe("tail", () => {
`);
});

it("logs queue messages in pretty format", async () => {
const api = mockWebsocketAPIs();
await runWrangler("tail test-worker --format pretty");

const event = generateMockQueueEvent();
const message = generateMockEventMessage({ event });
const serializedMessage = serialize(message);

api.ws.send(serializedMessage);
expect(
std.out
.replace(
new Date(mockEventTimestamp).toLocaleString(),
"[mock timestamp string]"
)
.replace(mockTailExpiration.toISOString(), "[mock expiration date]")
).toMatchInlineSnapshot(`
"Successfully created tail, expires at [mock expiration date]
Connected to test-worker, waiting for logs...
Queue my-queue123 (7 messages) - Ok @ [mock timestamp string]"
`);
});

it("should not crash when the tail message has a void event", async () => {
const api = mockWebsocketAPIs();
await runWrangler("tail test-worker --format pretty");
Expand Down Expand Up @@ -628,7 +664,13 @@ function serialize(message: TailEventMessage): WebSocket.RawData {
* @returns true if `event` is a RequestEvent
*/
function isRequest(
event: ScheduledEvent | RequestEvent | AlarmEvent | undefined | null
event:
| ScheduledEvent
| RequestEvent
| AlarmEvent
| QueueEvent
| undefined
| null
): event is RequestEvent {
return Boolean(event && "request" in event);
}
Expand Down Expand Up @@ -897,3 +939,10 @@ function generateMockAlarmEvent(opts?: Partial<AlarmEvent>): AlarmEvent {
scheduledTime: opts?.scheduledTime || mockEventScheduledTime,
};
}

function generateMockQueueEvent(opts?: Partial<QueueEvent>): QueueEvent {
return {
queue: opts?.queue || "my-queue123",
batchSize: opts?.batchSize || 7,
};
}
24 changes: 23 additions & 1 deletion packages/wrangler/src/tail/createTail.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,11 +242,18 @@ export type TailEventMessage = {
* The event that triggered the worker. In the case of an HTTP request,
* this will be a RequestEvent. If it's a cron trigger, it'll be a
* ScheduledEvent. If it's a durable object alarm, it's an AlarmEvent.
* If it's a Queue consumer event, it's a QueueEvent.
*
* Until workers-types exposes individual types for export, we'll have
* to just re-define these types ourselves.
*/
event: RequestEvent | ScheduledEvent | AlarmEvent | undefined | null;
event:
| RequestEvent
| ScheduledEvent
| AlarmEvent
| QueueEvent
| undefined
| null;
};

/**
Expand Down Expand Up @@ -377,3 +384,18 @@ export type AlarmEvent = {
*/
scheduledTime: string;
};

/**
* A event that was triggered by receiving a batch of messages from a Queue for consumption.
*/
export type QueueEvent = {
/**
* The name of the queue that the message batch came from.
*/
queue: string;

/**
* The number of messages in the batch.
*/
batchSize: number;
};
15 changes: 15 additions & 0 deletions packages/wrangler/src/tail/printing.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { logger } from "../logger";
import type {
AlarmEvent,
QueueEvent,
RequestEvent,
ScheduledEvent,
TailEventMessage,
Expand Down Expand Up @@ -37,6 +38,16 @@ export function prettyPrintLogs(data: WebSocket.RawData): void {
).toLocaleString();

logger.log(`Alarm @ ${datetime} - ${outcome}`);
} else if (isQueueEvent(eventMessage.event)) {
const outcome = prettifyOutcome(eventMessage.outcome);
const datetime = new Date(eventMessage.eventTimestamp).toLocaleString();
const queueName = eventMessage.event.queue;
const batchSize = eventMessage.event.batchSize;
const batchSizeMsg = `${batchSize} message${batchSize !== 1 ? "s" : ""}`;

logger.log(
`Queue ${queueName} (${batchSizeMsg}) - ${outcome} @ ${datetime}`
);
} else {
// Unknown event type
const outcome = prettifyOutcome(eventMessage.outcome);
Expand Down Expand Up @@ -74,6 +85,10 @@ function isScheduledEvent(
return Boolean(event && "cron" in event);
}

function isQueueEvent(event: TailEventMessage["event"]): event is QueueEvent {
return Boolean(event && "queue" in event);
}

/**
* Check to see if an event sent from a worker is an AlarmEvent.
*
Expand Down

0 comments on commit 4fd4ca4

Please sign in to comment.