Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow addEventListener in modules syntax #207

Closed
Electroid opened this issue Mar 8, 2022 · 4 comments
Closed

Allow addEventListener in modules syntax #207

Electroid opened this issue Mar 8, 2022 · 4 comments
Labels
behaviour mismatch Different behaviour to Workers runtime question Further information is requested
Milestone

Comments

@Electroid
Copy link

We now allow addEventListener and dispatchEvent when using modules syntax. Therefore, we can remove the restriction that throws an error.

Let's say you invoke addEventListener("fetch"). You will not receive Cloudflare's "fetch" event, but you can dispatch the event manually, such as dispatchEvent(new Event("fetch")).

@mrbbot mrbbot added the behaviour mismatch Different behaviour to Workers runtime label Mar 8, 2022
@mrbbot mrbbot added this to the 2.4.0 milestone Mar 8, 2022
@mrbbot mrbbot modified the milestones: 2.4.0, 2.5.0 Apr 2, 2022
@mrbbot mrbbot modified the milestones: 2.5.0, 2.6.0 May 27, 2022
@mrbbot
Copy link
Contributor

mrbbot commented Jun 11, 2022

Hey! 👋 I'm having a hard time getting this to work. 😕 My test worker looks like:

addEventListener("fetch", (event) => {
  console.log("listener", event.request.url);
  event.respondWith(new Response("listener body"));
});

export default {
  async fetch(request, env, ctx) {
    console.log("export", request.url);
    return new Response("export body");
  },
};

I'm expecting export body to be returned, and the listener in addEventListener to only be called with dispatchEvent as you describe. However, I'm seeing the following error message when I try to run wrangler dev:

npx wrangler dev
 ⛅️ wrangler 2.0.9 
-------------------
⬣ Listening at http://localhost:8787
15:49:03 GET / 200
Script modified; context reset.
export https://test-worker2.mrbbot.workers.dev/
⎔ Detected changes, restarted server.
✘ [ERROR] Error on remote worker: ParseError: A request to the Cloudflare API (/accounts/87***d4/workers/scripts/test-worker2/edge-preview) failed.

      at throwFetchError
  (.../node_modules/wrangler/wrangler-dist/cli.js:118063:17)
      at fetchResult
  (.../node_modules/wrangler/wrangler-dist/cli.js:118036:5)
      at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
      at async createPreviewToken
  (.../node_modules/wrangler/wrangler-dist/cli.js:120686:29)
      at async createWorkerPreview
  (.../node_modules/wrangler/wrangler-dist/cli.js:120701:17)
      at async start
  (.../node_modules/wrangler/wrangler-dist/cli.js:121169:16) {
    text: 'A request to the Cloudflare API
  (/accounts/87***d4/workers/scripts/test-worker2/edge-preview) failed.',
    notes: [
      {
        text: 'Uncaught Error: Some functionality, such as asynchronous I/O, timeouts, and
  generating random values, can only be performed while handling a request.\n' +
          '  at line 0\n' +
          ' [code: 10021]'
      }
    ],
    location: undefined,
    kind: 'error',
    code: 10021
  }

@mrbbot mrbbot added question Further information is requested behaviour mismatch Different behaviour to Workers runtime and removed behaviour mismatch Different behaviour to Workers runtime labels Jun 11, 2022
@JustinGrote
Copy link

I bumped into the same thing using a heavily modified version of @mrbbot's template using modules. Interestingly, works fine in miniflare, but not when miniflare has a debugger (vscode) attached.

It dies at the cache.match step.

/** @format */

export async function handleRequest(
	request: Request,
	env: Bindings,
	ctx: ExecutionContext
) {
	// Match route against pattern /:name/*action
	const url = new URL(request.url);

	url.host = "www.powershellgallery.com";
	url.protocol = "https";
	const target = url.toString();
	const cache = caches.default;
	const match = await cache.match(target);
	if (match) {
		console.log("hit");
		return match;
	}

	const originResponse = await fetch(target);
	// Must use Response constructor to inherit all of response's fields
	const response = new Response(originResponse.body, originResponse);

	// Cache API respects Cache-Control headers. Setting s-max-age to 10
	// will limit the response to be in cache for 10 seconds max

	// Any changes made to the response here will be reflected in the cached value
	response.headers.append("Cache-Control", "s-maxage=3600");
	// ctx.waitUntil(cache.put(target, response));
	cache.put(target, response);
	console.log("miss");
	return response;
}

const worker: ExportedHandler<Bindings> = { fetch: handleRequest };
export default worker;

Stacktrace

mf:err] GET /api/v2/FindPackagesById()?id='exchangeonlinemanagement': Error: Some functionality, such as asynchronous I/O (fetch, Cache API, KV), timeouts (setTimeout, setInterval), and generating random values (crypto.getRandomValues, crypto.subtle.generateKey), can only be performed while handling a request.
    at assertInRequest (C:\Users\JGrote\Projects\PWSHGallery\node_modules\.pnpm\@miniflare+shared@2.5.0\node_modules\@miniflare\shared\src\context.ts:29:11)
    at Cache.match (C:\Users\JGrote\Projects\PWSHGallery\node_modules\.pnpm\@miniflare+cache@2.5.0\node_modules\@miniflare\cache\src\cache.ts:210:35)
    at Object.handleRequest [as fetch] (c:\Users\JGrote\Projects\PWSHGallery\src\index.ts:15:28)
    at C:\Users\JGrote\Projects\PWSHGallery\node_modules\.pnpm\@miniflare+core@2.5.0\node_modules\@miniflare\core\src\standards\event.ts:331:19
    at C:\Users\JGrote\Projects\PWSHGallery\node_modules\.pnpm\@miniflare+shared@2.5.0\node_modules\@miniflare\shared\src\event.ts:29:9
    at ServiceWorkerGlobalScope.<anonymous> (C:\Users\JGrote\Projects\PWSHGallery\node_modules\.pnpm\@miniflare+shared@2.5.0\node_modules\@miniflare\shared\src\event.ts:77:9)
    at ServiceWorkerGlobalScope.[nodejs.internal.kHybridDispatch] (node:internal/event_target:645:20)
    at ServiceWorkerGlobalScope.dispatchEvent (node:internal/event_target:587:26)
    at ServiceWorkerGlobalScope.dispatchEvent (C:\Users\JGrote\Projects\PWSHGallery\node_modules\.pnpm\@miniflare+shared@2.5.0\node_modules\@miniflare\shared\src\event.ts:63:18)
    at ServiceWorkerGlobalScope.dispatchEvent (C:\Users\JGrote\Projects\PWSHGallery\node_modules\.pnpm\@miniflare+shared@2.5.0\node_modules\@miniflare\shared\src\event.ts:87:26)

@JosXa
Copy link

JosXa commented Jun 20, 2022

@JustinGrote I noticed the same and opened a separate issue: #292

@mrbbot mrbbot modified the milestones: 2.6.0, 2.7.0 Jul 9, 2022
@mrbbot mrbbot modified the milestones: 2.7.0, 2.8.0 Aug 19, 2022
@mrbbot mrbbot closed this as completed in e606fca Sep 3, 2022
@JustinGrote
Copy link

@mrbbot Thank you! 💖

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
behaviour mismatch Different behaviour to Workers runtime question Further information is requested
Projects
None yet
Development

No branches or pull requests

4 participants