From 49ca25d294ba34ef5fe0ca4771ed5e4ca99f32ef Mon Sep 17 00:00:00 2001
From: Daniel Lamando <dan@danopia.net>
Date: Sat, 11 May 2024 18:52:52 +0200
Subject: [PATCH] Fix uncaught "resource closed" in http server instrumentation
 (#3)

* Try fixing uncaught 'resource closed'

* Log another potential error site

* Revert "Log another potential error site"

This reverts commit 2d352f54dd60c6b9ba734693ce2abce072d6be22.

* Improve how we report response stream errors

* Add --allow-sys to bundle-opentelemetry.ts

* Use specific versions of the bundle toolchain

* does this help?

* how about that

* why am i struggling with submodules
---
 hack/bundle-opentelemetry.ts   | 12 ++++++------
 instrumentation/http-server.ts |  3 +++
 2 files changed, 9 insertions(+), 6 deletions(-)

diff --git a/hack/bundle-opentelemetry.ts b/hack/bundle-opentelemetry.ts
index ddb7773..a9d56e7 100755
--- a/hack/bundle-opentelemetry.ts
+++ b/hack/bundle-opentelemetry.ts
@@ -1,12 +1,12 @@
-#!/usr/bin/env -S deno run --allow-run --allow-read --allow-write=. --allow-env
+#!/usr/bin/env -S deno run --allow-run --allow-read --allow-write=. --allow-env --allow-sys --allow-ffi
 
 // pass --refresh-yarn to force rerunning yarn on the opentelemetry packages
 
-import { rollup, Plugin } from 'npm:rollup';
-import { nodeResolve } from 'npm:@rollup/plugin-node-resolve';
-import commonjs from 'npm:@rollup/plugin-commonjs';
-import sourcemaps from 'npm:rollup-plugin-sourcemaps';
-import cleanup from 'npm:rollup-plugin-cleanup';
+import { rollup, Plugin } from 'npm:rollup@4.17.2';
+import { nodeResolve } from 'npm:@rollup/plugin-node-resolve@15.2.3';
+import commonjs from 'npm:@rollup/plugin-commonjs@25.0.7';
+import sourcemaps from 'npm:rollup-plugin-sourcemaps@0.6.3';
+import cleanup from 'npm:rollup-plugin-cleanup@3.2.1';
 import dts from 'npm:rollup-plugin-dts@4.2.3';
 // import { terser } from "npm:rollup-plugin-terser";
 
diff --git a/instrumentation/http-server.ts b/instrumentation/http-server.ts
index 0421faa..f5777c0 100644
--- a/instrumentation/http-server.ts
+++ b/instrumentation/http-server.ts
@@ -88,6 +88,9 @@ export function httpTracer(inner: Deno.ServeHandler, opts?: {
         const respSnoop = snoopStream(resp.body);
         respSnoop.finalSize.then(size => {
           serverSpan.setAttribute(SemanticAttributes.HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED, size);
+        }).catch(err => {
+          // NOTE: err can be "resource closed" when the client walks away mid-response.
+          serverSpan.recordException(err);
         }).finally(() => {
           inflightMetric.add(-1, reqMetricAttrs);
           serverSpan.end();