|
| 1 | +fn subgraph_service(service, subgraph) { |
| 2 | + // collect the max-age and scope values from cache-control headers and store |
| 3 | + // on the context for use in supergraph_service |
| 4 | + service.map_response(|response| { |
| 5 | + let cache_control = response.headers.values("cache-control").get(0); |
| 6 | + |
| 7 | + // if a subgraph response is uncacheable, the whole response is uncacheable |
| 8 | + if cache_control == () { |
| 9 | + response.context.cache_control_uncacheable = true; |
| 10 | + return; |
| 11 | + } |
| 12 | + |
| 13 | + let max_age = get_max_age(cache_control); |
| 14 | + |
| 15 | + // use the smallest max age |
| 16 | + response.context.upsert("cache_control_max_age", |current| { |
| 17 | + if current == () { |
| 18 | + max_age |
| 19 | + } else if max_age < current { |
| 20 | + max_age |
| 21 | + } else { |
| 22 | + current |
| 23 | + } |
| 24 | + }); |
| 25 | + |
| 26 | + let scope = if cache_control.contains("public") { |
| 27 | + "public" |
| 28 | + } else { |
| 29 | + "private" |
| 30 | + }; |
| 31 | + |
| 32 | + // if the scope is ever private, it cannot become public |
| 33 | + response.context.upsert("cache_control_scope", |current| { |
| 34 | + if current == "private" || scope == "private" { |
| 35 | + "private" |
| 36 | + } else { |
| 37 | + scope |
| 38 | + } |
| 39 | + }); |
| 40 | + }); |
| 41 | +} |
| 42 | + |
| 43 | +fn supergraph_service(service) { |
| 44 | + // attach the cache-control header if enough data is available |
| 45 | + service.map_response(|response| { |
| 46 | + let uncacheable = response.context.cache_control_uncacheable; |
| 47 | + let max_age = response.context.cache_control_max_age; |
| 48 | + let scope = response.context.cache_control_scope; |
| 49 | + |
| 50 | + if uncacheable != true && max_age != () && scope != () { |
| 51 | + response.headers["cache-control"] = `max-age=${max_age}, ${scope}`; |
| 52 | + } |
| 53 | + }); |
| 54 | +} |
| 55 | + |
| 56 | +// find the the max-age= part and parse the value into an integer |
| 57 | +fn get_max_age(str) { |
| 58 | + let max_age = 0; |
| 59 | + |
| 60 | + for part in str.split(",") { |
| 61 | + part.remove(" "); |
| 62 | + |
| 63 | + if part.starts_with("max-age=") { |
| 64 | + let num = part.split("=").get(1); |
| 65 | + |
| 66 | + if num == () || num == "" { |
| 67 | + break; |
| 68 | + } |
| 69 | + |
| 70 | + try { |
| 71 | + max_age = num.parse_int(); |
| 72 | + } catch (err) { |
| 73 | + log_error(`error parsing max-age from "${str}": ${err}`); |
| 74 | + } |
| 75 | + break; |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + max_age |
| 80 | +} |
0 commit comments