apollographql / router

A configurable, high-performance routing runtime for Apollo Federation 🚀
https://www.apollographql.com/docs/router/
Other
807 stars 272 forks source link

Rhai Errors on Missing Attribute in Set #2026

Open lleadbet opened 1 year ago

lleadbet commented 1 year ago

Describe the bug Accessing an attribute in a Set/ValueMap in Rhai that doesn't exist causes the script to error unexpectedly.

To Reproduce Given this script:

fn supergraph_service(service){
  const request_callback = Fn("process_request");
  service.map_request(request_callback);
}
fn process_request(request){
    if request.headers["x-custom-header"] == () {
        throw "Error: you did not provide x-custom-header";
    }
}

Will cause an error such as:

{"timestamp":"2022-10-27T22:29:32.404770Z","level":"ERROR","fields":{"message":"map_request callback failed: Runtime error (line 11, position 29) in call to function process_request"},"target":"apollo_router::plugins::rhai"}

You can work around this by using:

fn supergraph_service(service){
  const request_callback = Fn("process_request");
  service.map_request(request_callback);
}
fn process_request(request){
    try {
        request.headers["x-opaque-token"];
    }catch(error){
        throw "Error: X-Opaque-Token is required in request header";
    }
}

However this is far less readable as it expects an error on reading the header.

Expected behavior Ideally, a missing header would simply return an empty string.

Desktop (please complete the following information):

garypen commented 1 year ago

This is working as designed on the basis that it is an error to try and access a missing header.

It may be better to have a missing header return () (not an empty string),but if we change this now it will break existing scripts and would thus be an incompatible change.

I'm going to label this with the new 2.0 label.