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

Wasm-pack packages for pages/api aren't linked properly with Webpack5 #34940

Closed
1 task done
LeviticusNelson opened this issue Mar 1, 2022 · 2 comments
Closed
1 task done
Labels
bug Issue was opened via the bug report template. Webpack Related to Webpack with Next.js.

Comments

@LeviticusNelson
Copy link

Verify canary release

  • I verified that the issue exists in Next.js canary release

Provide environment information

Operating System:
Platform: darwin
Arch: x64
Version: Darwin Kernel Version 21.4.0: Mon Feb 14 22:26:24 PST 2022; root:xnu-8020.101.3~4/RELEASE_X86_64
Binaries:
Node: 17.6.0
npm: 8.5.2
Yarn: N/A
pnpm: N/A
Relevant packages:
next: 12.1.0
react: 17.0.2
react-dom: 17.0.2

What browser are you using? (if relevant)

No response

How are you deploying your application? (if relevant)

Vercel

Describe the Bug

Local development to do API calls on pages/api works with wasm-pack packages works great, but when deployed on Vercel: the page returns:
{"errno":-2,"code":"ENOENT","syscall":"open","path":"/var/task/.next/server/chunks/7645.wasm"}

Expected Behavior

My local API call looks like :

{"id":0,"width":50,"height":50,"pixels":[{"id":752,"is_blank":false,"r":255,"g":255,"b":255},{"id":3,"is_blank":true,"r":255,"g":255,"b":255},{"id":4,"is_blank":true,"r":255,"g":255,"b":255}...

and this is what I was expecting to see on Vercel.

To Reproduce

WASM patch from #29362

// next.config.js

module.exports = {
	webpack(config, { isServer, dev }) {
		config.output.webassemblyModuleFilename = "static/wasm/[modulehash].wasm";
		config.experiments = {
			asyncWebAssembly: true,
			layers: true,
		};

		if (!dev && isServer) {
			config.output.webassemblyModuleFilename = "chunks/[id].wasm";
			config.plugins.push(new WasmChunksFixPlugin());
		}

		return config;
	},
};

class WasmChunksFixPlugin {
	apply(compiler) {
		compiler.hooks.thisCompilation.tap("WasmChunksFixPlugin", (compilation) => {
			compilation.hooks.processAssets.tap(
				{ name: "WasmChunksFixPlugin" },
				(assets) =>
					Object.entries(assets).forEach(([pathname, source]) => {
						if (!pathname.match(/\.wasm$/)) return;
						compilation.deleteAsset(pathname);

						const name = pathname.split("/")[1];
						const info = compilation.assetsInfo.get(pathname);
						compilation.emitAsset(name, source, info);
					})
			);
		});
	}
}

Rust WASM function created in rust-wasm using wasm-pack (you could probably do a simple return of a serde-json jsvalue in rust)

#[derive(Debug, Deserialize, Serialize)]
struct ImageResult {
    id: u64,
    width: u32,
    height: u32,
}

// Returns JSON representation of Image

#[wasm_bindgen]
pub async fn get_image_from_db(url: String, key: String) -> Result<JsValue, JsError> {
    let mut authorization : String = "Bearer ".to_owned();
    authorization.push_str(&key);

    let client = Postgrest::new(url.to_string()).insert_header("apikey", key.to_string()).insert_header("Authorization", authorization.to_string()).schema("public");
    
    let image_result = client.from("Images").select("id,width,height").order("id.desc").single().execute().await?;
    let image_body = image_result.text().await?;
    
    let image_result_struct : ImageResult = serde_json::from_str(&image_body).unwrap();
    let mut final_image_struct : Image = Image::new(image_result_struct.id, image_result_struct.width, image_result_struct.height);
    
    let image_id = image_result_struct.id;
    let pixel_body = get_pixels_from_db(client, &image_id).await?;
    let pixels : Vec<Pixel> = serde_json::from_str(&pixel_body)?;
    final_image_struct.replace_pixels(pixels);
    let image_json = serde_json::to_string(&final_image_struct)?;
    Ok(JsValue::from_serde(&image_json).unwrap())
}


async fn get_pixels_from_db(client : Postgrest, image_id : &u64) -> Result<String, JsError> {
    let pixel_results = client.from("Pixels").select("id,is_blank,r,g,b").eq("image_id", image_id.to_string()).execute().await?;
    let pixel_body = pixel_results.text().await?;
    Ok(pixel_body)
}

pages/api/image.js

export default async function handler(req, res) {
	try {
		const wasm = await import("../../rust-wasm/pkg");
		const url = process.env.NEXT_PUBLIC_SUPABASE_URL + "/rest/v1";
		const image = await wasm.get_image_from_db(
			url,
			process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
		);
		await res.status(200).json(image);
	} catch (err) {
		res.json(err);
		res.status(405).end();
	}
}

@LeviticusNelson LeviticusNelson added the bug Issue was opened via the bug report template. label Mar 1, 2022
@balazsorban44 balazsorban44 added the Webpack Related to Webpack with Next.js. label Mar 9, 2022
@jankaifer
Copy link
Contributor

This seems to be tracked at #29362.

@github-actions
Copy link
Contributor

This closed issue has been automatically locked because it had no new activity for a month. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Feb 12, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
bug Issue was opened via the bug report template. Webpack Related to Webpack with Next.js.
Projects
None yet
Development

No branches or pull requests

3 participants