Skip to content

Commit

Permalink
Use ctx.waitUntil to report metrics
Browse files Browse the repository at this point in the history
  • Loading branch information
pyropy committed Dec 9, 2024
1 parent 4b1e860 commit 91c9737
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 21 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ node_modules/
.wrangler
data/
config/
wranger.toml
27 changes: 9 additions & 18 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,12 @@ const INFLUX_HOST = process.env.INFLUX_HOST || 'http://localhost:8086';
const INFLUX_TOKEN = process.env.INFLUX_TOKEN || '';
const INFLUX_DATABASE = process.env.INFLUX_DATABASE || '';

async function handleRequest(request, env, ctx) {
return await fetch(request);
}

async function formatMetricPoint(request) {
const url = new URL(request.url);
const today = new Date();

const origin = request.headers.get("origin") ?? "";
const cache = request.headers.get("cf-cache-status") ?? "unknown";
const service = new URL(origin).hostname.replaceAll(".", "-");


const point = new Point('request')
.tag('url', url.toString())
.tag('hostname', url.hostname)
Expand All @@ -29,19 +22,17 @@ async function formatMetricPoint(request) {
return point;
}

async function handleMetrics(events, env, ctx) {
async function reportMetric(request) {
const client = new InfluxDBClient({ host: INFLUX_HOST, token: INFLUX_TOKEN });
for (const event of events) {
const point = formatMetricPoint(event.request);

console.log(point)
await client.write(INFLUX_DATABASE, point);
}

await writeApi.close()
const point = formatMetricPoint(request);
await client.write(INFLUX_DATABASE, point);
await client.close()
}

export default {
fetch: handleRequest,
tail: handleMetrics,
async fetch(request, env, ctx) {
const resp = await fetch(request);
ctx.waitUntil(reportMetric(request));
return resp;
}
}
3 changes: 0 additions & 3 deletions wrangler.toml → wrangler.toml.example
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
#:schema node_modules/wrangler/config-schema.json
name = "cf-metrics"
tail_consumers = [{service = "cf-metrics-tail"}]
main = "index.js"
compatibility_date = "2024-12-05"
compatibility_flags = ["nodejs_compat"]
send_metrics = false

[vars]
INFLUX_URL = "http://localhost:8086"
Expand Down

0 comments on commit 91c9737

Please sign in to comment.