Skip to content

Add binding type that takes value from system environment variable. - #786

Merged
kentonv merged 1 commit into
mainfrom
kenton/env-var-binding
Jun 19, 2023
Merged

kentonv merged 1 commit into
mainfrom
kenton/env-var-binding

Conversation

@kentonv

@kentonv kentonv commented Jun 18, 2023

Copy link
Copy Markdown
Member

See discussion on #70

Fixes #70

@kentonv
kentonv force-pushed the kenton/env-var-binding branch from 512c92e to 5620ae9 Compare June 18, 2023 22:51
@pmbanugo

Copy link
Copy Markdown

To use that binding, it'll be fromEnvironment :Text = NODE_ENV for example? And I should repeat that multiple times in the Cap'nProto file?

@kentonv

kentonv commented Jun 19, 2023

Copy link
Copy Markdown
Member Author

@pmbanugo To use it, when declaring bindings in your workerd config, you'd declare a binding like:

( name = "bindingName", fromEnvironment = "ENV_VAR_NAME" ),

if (value == nullptr) {
// TODO(cleanup): Maybe make a Global::Null? (Can't use nullptr_t in OneOf.) For now,
// using JSON gets the job done hackily.
return makeGlobal(Global::Json { kj::str("null") });

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Setting the value to an empty string would at least have the value test falsy.

console.log('' || 'hello') // 'hello'
console.log('null' || 'hello') // 'null'

@jasnell jasnell Jun 19, 2023 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh, unless Global::Json is setting the value explicitly to null and not 'null'?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, this is a hack to get the value null, not the string "null".

@kentonv
kentonv merged commit d49f209 into main Jun 19, 2023
@kentonv
kentonv deleted the kenton/env-var-binding branch June 19, 2023 22:25
@SagarM21

SagarM21 commented Aug 12, 2024 •

Copy link
Copy Markdown

Hey, I am trying to run the functions using workerd binary and in those functions I want to use env variables but I am using wrong key value pair or I don't know exactly. Sharing the files, if anyone could help:

.Capnp file:

using Workerd = import "/workerd/workerd.capnp";

const config :Workerd.Config = (
  services = [
    (name = "2891521454938061814", worker = .v2891521454938061814Worker),
  ],

  sockets = [
    (
      name = "2891521454938061814",
      address = "localhost:55511",
      http = (),
      service = "2891521454938061814",
    ),
  ]

);

const v2891521454938061814Worker :Workerd.Worker = (
  serviceWorkerScript = embed "src/entry.js",
  compatibilityDate = "2023-04-03",
  bindings = [
    
    (name = "API_URL", fromEnvironment = "https://dummyjson.com/products"),
    
  ],
);

JS CODE:

addEventListener("fetch", (event) => {
    event.respondWith(handleRequest(event.request, event));
});

async function handleRequest(request, { env }) {
    try {
        // Access the API_URL from the env object
        const apiUrl = env.API_URL;

        // Fetch data from the Dummy JSON API using the URL from the environment variable
        const response = await fetch(apiUrl);

        // Check if the fetch was successful
        if (!response.ok) {
            throw new Error(`Failed to fetch data: ${response.statusText}`);
        }

        // Parse the response as JSON
        const data = await response.json();

        // Return the data as a JSON response
        return new Response(JSON.stringify(data), {
            headers: { "Content-Type": "application/json" },
        });
    } catch (e) {
        return new Response(e.message, { status: 500 });
    }
}

What am I doing wrong??

@kentonv

kentonv commented Aug 12, 2024

Copy link
Copy Markdown
Member Author

(name = "API_URL", fromEnvironment = "https://dummyjson.com/products"),

This looks like you are just trying to set the value to https://dummyjson.com/products. If that's what you want, you should use the text type instead of fromEnvironment:

(name = "API_URL", text = "https://dummyjson.com/products"),

The purpose of fromEnvironment is if you want the value to come from a system environment variable. When using it, you should provide the name of the system environment variable to read, not the value:

(name = "API_URL", fromEnvironment = "MY_ENV_VAR"),

@SagarM21

SagarM21 commented Aug 12, 2024 •

Copy link
Copy Markdown

I tried that, but that js code is not able to pick the value, can you look at the js code once, if you have any idea regarding this. The error I get when I run it: Cannot read properties of undefined (reading 'API_URL')"

@kentonv

kentonv commented Aug 12, 2024

Copy link
Copy Markdown
Member Author

@SagarM21 Oh, looking again I see your code is in Service Worker syntax. It looks like you are expecting to find the env as event.env, but this is not the case. In service workers syntax, environment variables are placed on the global scope. So you should replace env.API_URL with just API_URL.

However, we recommend using ES Modules syntax for all new code: https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/

@SagarM21

Copy link
Copy Markdown

It worked, and also I have changed the code to ES Modules but after changing the code to ES Modules, its not working, if you can take a look. (the error I get: "Unexpected token export")

Below is the updated JS code:
`
export default {
async fetch(request) {
try {
// Access the API_URL from the environment variable
const apiUrl = API_URL;

  // Fetch data from the Dummy JSON API using the URL from the environment variable
  const response = await fetch(apiUrl);

  // Check if the fetch was successful
  if (!response.ok) {
    throw new Error(`Failed to fetch data: ${response.statusText}`);
  }

  // Parse the response as JSON
  const data = await response.json();

  // Return the data as a JSON response
  return new Response(JSON.stringify(data), {
    headers: { "Content-Type": "application/json" },
  });
} catch (e) {
  return new Response(e.message, { status: 500 });
}

},
};

`

@kentonv

kentonv commented Aug 14, 2024

Copy link
Copy Markdown
Member Author

@SagarM21 Environment variables only show up as globals in service workers syntax. In ES modules syntax, they are on the env object. Your fetch handler should be declared as fetch(request, env, ctx). Please read the docs I linked above.

@SagarM21

SagarM21 commented Aug 19, 2024 •

Copy link
Copy Markdown

Thanks for the info, I am trying to run the wasm file through workerd binary as well, I have written the code in rust and created a wasm file through it and appended it in capnp and its working.
But when I try to append the wasm file whose code is written in golang that does not works, I have checked that golang requires wasm_exec.js file to run it and I have provided that also in capnp but there are errors, sharing the code with you, if you can take a look:

capnp
`using Workerd = import "/workerd/workerd.capnp";

const config :Workerd.Config = (
services = [
(name = "2892476153958761139", worker = .v2892476153958761139Worker),
],

sockets = [
(
name = "2892476153958761139",
address = "localhost:64874",
http = (),
service = "2892476153958761139",
),
]

);

const v2892476153958761139Worker :Workerd.Worker = (
serviceWorkerScript = embed "src/entry.js",
modules = [
(name = "entry.js", esModule = embed "src/entry.js"),
(name = "wasm_exec.js", esModule = embed "src/wasm_exec.js"),

(name = "test.wasm", wasm = embed "src/test.wasm"),

],
compatibilityDate = "2024-04-03",
bindings = [

],
);
`

JS CODE TO RUN :

`import './wasm_exec.js'; // Import wasm_exec.js to setup the Go WebAssembly runtime

import wasmModule from './test.wasm'; // Import your WebAssembly module

// Create an instance of the Go WebAssembly runtime
const go = new Go();

const instance = await WebAssembly.instantiate(wasmModule, go.importObject);
export default {
async fetch(req) {
// Instantiate the WebAssembly module with Go runtime

// Start the Go runtime
go.run(instance);

// Call the exported `add` function with two integers
console.log("INSTANCE", instance)
const result = instance.exports.add(1000, 2);

// Return the result as a response
return new Response(`The result of adding 1000 and 2 is: ${result}`);

}
}
`

test.wasm file which is created through the below code:

`//go:build js && wasm
// +build js,wasm

package main

import (
"syscall/js"
)

func add(this js.Value, p []js.Value) interface{} {
num1 := p[0].Int()
num2 := p[1].Int()
sum := num1 + num2
return js.ValueOf(sum)
}

func main() {
js.Global().Set("add", js.FuncOf(add))
select {}
}
`

Error
workerd/io/worker.c++:1925: info: uncaught exception; source = Uncaught (in promise); stack = TypeError: instance.exports.add is not a function at Object.fetch (entry.js:17:37) workerd/util/symbolizer.c++:96: warning: Not symbolizing stack traces because $LLVM_SYMBOLIZER is not set. To symbolize stack traces, set $LLVM_SYMBOLIZER to the location of the llvm-symbolizer binary. When running tests under bazel, use --test_env=LLVM_SYMBOLIZER=. workerd/io/io-context.c++:355: info: uncaught exception; exception = workerd/jsg/_virtual_includes/jsg/workerd/jsg/value.h:1355: failed: jsg.TypeError: instance.exports.add is not a function stack: 100f347c0 100f35686 10322e19f 100dacf20 100dad490

From the error its clear that, its not able to find add function but what is missing in the code, unable to identify it.

@SagarM21

SagarM21 commented Aug 19, 2024 •

Copy link
Copy Markdown

Changed the code a bit and now getting different error:

`import './wasm_exec.js'; // Import wasm_exec.js to set up the Go WebAssembly runtime

const go = new Go(); // Create a new instance of the Go WebAssembly runtime

async function initializeWasm() {
// Instantiate the WebAssembly module with Go runtime
const response = await fetch('./test.wasm');
const wasmModule = await WebAssembly.compileStreaming(response);
const instance = await WebAssembly.instantiate(wasmModule, go.importObject);

// Start the Go runtime
go.run(instance);

// Use the exported add function
if (typeof window.add === 'function') {
const result = window.add(1000, 2);
console.log(The result of adding 1000 and 2 is: ${result});
} else {
console.error('Function add is not available.');
}
}

initializeWasm();`

workerd/server/server.c++:3360: error: Uncaught exception: kj/async-io-unix.c++:1645: failed: worker_do_not_log; Request failed due to internal error stack: 103090000 103090950 103082a90 103082e80 1017f9897 1017fa4d5 1017fc0ea 1017d5d10 1017dd860 1017f5de0 1005e73a0 1017f5de0 100bd51a0 10060380c 101800b27 101801d68 1018027bf 1017c5bf0 workerd/io/worker-entrypoint.c++:338: error: e = kj/async-io-unix.c++:1645: failed: connect() blocked by restrictPeers() stack: 103090000 103090950 103082a90 103082e80 1017f9897 1017fa4d5 1017fc0ea 1017d5d10 1017dd860 1017f5de0 1005e73a0 1017f5de0 100bd51a0; sentryErrorContext = workerEntrypoint

@SagarM21

Copy link
Copy Markdown

@kentonv can you help me with the above wasm problem?

@kentonv

kentonv commented Aug 27, 2024

Copy link
Copy Markdown
Member Author

@SagarM21 This is off-topic for this thread. Please open a discussion thread.

@SagarM21

Copy link
Copy Markdown

@SagarM21 This is off-topic for this thread. Please open a discussion thread.

@kentonv Sorry for that, there is already a discussion thread but there is no response on that. I have added the query there as well.
Sharing the link: #774
Please take a look, whenever possible.
Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feature(proposal): Bindings for system environment variable

5 participants