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

Support unix_ms_now in rhai engine #5181

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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...
garypen marked this conversation as resolved.
Show resolved Hide resolved
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
Loading