Skip to content

Commit

Permalink
Support unix_ms_now in rhai engine (#5181)
Browse files Browse the repository at this point in the history
Co-authored-by: Gary Pennington <gary@apollographql.com>
  • Loading branch information
shaikatzz and garypen authored Jun 6, 2024
1 parent a3d2665 commit d2de8cf
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
### Support unix_ms_now in rhai engine ([Issue #5182](https://github.com/apollographql/router/issues/5182))


By [@shaikatzz](https://github.com/shaikatzz) in https://github.com/apollographql/router/pull/5181
8 changes: 8 additions & 0 deletions apollo-router/src/plugins/rhai/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1233,6 +1233,14 @@ mod router_plugin {
.map(|x| x.as_secs() as i64)
}

#[rhai_fn(return_raw)]
pub(crate) fn unix_ms_now() -> Result<i64, Box<EvalAltResult>> {
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.map_err(|e| e.to_string().into())
.map(|x| x.as_millis() as i64)
}

// Add query plan getter to execution request
#[rhai_fn(get = "query_plan")]
pub(crate) fn execution_request_query_plan_get(
Expand Down
15 changes: 15 additions & 0 deletions apollo-router/src/plugins/rhai/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -579,6 +579,21 @@ fn it_can_create_unix_now() {
assert!(st <= unix_now && unix_now <= st + 1);
}

#[test]
fn it_can_create_unix_ms_now() {
let engine = new_rhai_test_engine();
let st = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.expect("can get system time")
.as_millis() as i64;
let unix_ms_now: i64 = engine
.eval(r#"unix_ms_now()"#)
.expect("can get unix_ms_now() timestamp");
// Always difficult to do timing tests. unix_ms_now() should execute within a second of st,
// so...
assert!(st <= unix_ms_now && unix_ms_now <= st + 1000);
}

#[test]
fn it_can_generate_uuid() {
let engine = new_rhai_test_engine();
Expand Down
10 changes: 10 additions & 0 deletions docs/source/customizations/rhai-api.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,16 @@ fn supergraph_service(service) {
}
```

## Unix timestamp (in milliseconds)

Your Rhai customization can use the function `unix_ms_now()` to obtain the current Unix timestamp in milliseconds since the Unix epoch.

```rhai
fn supergraph_service(service) {
let now = unix_ms_now();
}
```

## Unique IDs (UUID)

Your Rhai customization can use the function `uuid_v4()` to obtain a UUIDv4 ID.
Expand Down

0 comments on commit d2de8cf

Please sign in to comment.