Skip to content

Commit

Permalink
Fix invocations of fetch with Worker service bindings (#385)
Browse files Browse the repository at this point in the history
* Fix invocations of fetch with service bound workers

* Update examples/service-bindings/woof/src/index.ts
  • Loading branch information
brettimus authored Dec 3, 2024
1 parent fd15933 commit f1a2c26
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 4 deletions.
11 changes: 11 additions & 0 deletions examples/service-bindings/meow/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,15 @@ app.get("/", async (c) => {
return c.text(`Meow from above! ☁️🪿🐈 (But dog says "${bark}")`);
});

app.get("/geese-to-bark-at", async (c) => {
const geeseResponse = await c.env.WOOF.fetch(c.req.raw);
try {
const geese = await geeseResponse.json();
console.log(geese);
return c.json(geese as Array<unknown>);
} catch (_e) {
return c.json({ error: "Failed to parse geese response as JSON" }, 500);
}
});

export default instrument(app);
4 changes: 2 additions & 2 deletions examples/service-bindings/woof/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ export class WoofWorker extends WorkerEntrypoint {

// From Cloudflare docs: "Currently, entrypoints without a named handler are not supported"
// TODO - Check if this is still the case that we need a fetch handler?
async fetch() {
return new Response(null, { status: 404 });
async fetch(_request: Request | string) {
return fetch("https://placegoose.mies.workers.dev/geese");
}
}

Expand Down
2 changes: 1 addition & 1 deletion packages/client-library-otel/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"author": "Fiberplane<info@fiberplane.com>",
"type": "module",
"main": "dist/index.js",
"version": "0.5.0",
"version": "0.5.1",
"dependencies": {
"@opentelemetry/api": "~1.9.0",
"@opentelemetry/exporter-trace-otlp-http": "^0.52.1",
Expand Down
7 changes: 6 additions & 1 deletion packages/client-library-otel/src/patch/cf-bindings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,11 @@ function proxyServiceBinding(o: object, bindingName: string) {
// The name for the span, which will show up in the UI
const name = `${bindingName}.${serviceMethod}`;

// For the `fetch` method, we need to bind `this` (the javascript `this` keyword) to the service target,
// otherwise `fetch` will fail!
// For RPC calls we do not need to do any special `this` binding
const shouldBindThis = serviceMethod === "fetch";

const measuredBinding = measure(
{
name,
Expand All @@ -181,7 +186,7 @@ function proxyServiceBinding(o: object, bindingName: string) {
},
onError: handleError,
},
serviceValue,
shouldBindThis ? serviceValue.bind(serviceTarget) : serviceValue,
);

return measuredBinding;
Expand Down

0 comments on commit f1a2c26

Please sign in to comment.