Skip to content

Commit 91c9737

Browse files
committed
Use ctx.waitUntil to report metrics
1 parent 4b1e860 commit 91c9737

File tree

3 files changed

+10
-21
lines changed

3 files changed

+10
-21
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,4 @@ node_modules/
1212
.wrangler
1313
data/
1414
config/
15+
wranger.toml

index.js

Lines changed: 9 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,12 @@ const INFLUX_HOST = process.env.INFLUX_HOST || 'http://localhost:8086';
44
const INFLUX_TOKEN = process.env.INFLUX_TOKEN || '';
55
const INFLUX_DATABASE = process.env.INFLUX_DATABASE || '';
66

7-
async function handleRequest(request, env, ctx) {
8-
return await fetch(request);
9-
}
10-
117
async function formatMetricPoint(request) {
128
const url = new URL(request.url);
139
const today = new Date();
14-
1510
const origin = request.headers.get("origin") ?? "";
1611
const cache = request.headers.get("cf-cache-status") ?? "unknown";
1712
const service = new URL(origin).hostname.replaceAll(".", "-");
18-
19-
2013
const point = new Point('request')
2114
.tag('url', url.toString())
2215
.tag('hostname', url.hostname)
@@ -29,19 +22,17 @@ async function formatMetricPoint(request) {
2922
return point;
3023
}
3124

32-
async function handleMetrics(events, env, ctx) {
25+
async function reportMetric(request) {
3326
const client = new InfluxDBClient({ host: INFLUX_HOST, token: INFLUX_TOKEN });
34-
for (const event of events) {
35-
const point = formatMetricPoint(event.request);
36-
37-
console.log(point)
38-
await client.write(INFLUX_DATABASE, point);
39-
}
40-
41-
await writeApi.close()
27+
const point = formatMetricPoint(request);
28+
await client.write(INFLUX_DATABASE, point);
29+
await client.close()
4230
}
4331

4432
export default {
45-
fetch: handleRequest,
46-
tail: handleMetrics,
33+
async fetch(request, env, ctx) {
34+
const resp = await fetch(request);
35+
ctx.waitUntil(reportMetric(request));
36+
return resp;
37+
}
4738
}

wrangler.toml renamed to wrangler.toml.example

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,7 @@
1-
#:schema node_modules/wrangler/config-schema.json
21
name = "cf-metrics"
3-
tail_consumers = [{service = "cf-metrics-tail"}]
42
main = "index.js"
53
compatibility_date = "2024-12-05"
64
compatibility_flags = ["nodejs_compat"]
7-
send_metrics = false
85

96
[vars]
107
INFLUX_URL = "http://localhost:8086"

0 commit comments

Comments
 (0)