diff --git a/.gitignore b/.gitignore index 6178f3b..0309f94 100644 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,6 @@ /deps/artifacts/ /deps/curl-*/ /deps/aws-lambda-cpp-*/ +/src/native/rust/target/ +/src/native/build/ +/src/node_modules/ diff --git a/README.md b/README.md index 6e178c1..0279d38 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,22 @@ The RIC enables communication between your Lambda function code and the Lambda R npm install aws-lambda-ric ``` +### Experimental Rust client on Linux + +This branch includes an opt-in Rust implementation of `rapid-client.node`. +The default install still builds the C++ client. To use Rust from this checkout, +install Cargo and a Linux linker, then run + +```bash +RIC_NATIVE_CLIENT=rust npm ci +npm run build +npm run test:native +npm run test:stream +``` + +See the [native client experiment](test/native/README.md) for scope, limitations +and benchmark instructions. + ## Usage ### Basic Usage diff --git a/THIRD-PARTY-LICENSES b/THIRD-PARTY-LICENSES index 14a3456..dd1d450 100644 --- a/THIRD-PARTY-LICENSES +++ b/THIRD-PARTY-LICENSES @@ -309,4 +309,55 @@ OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other dealings -in this Software without prior written authorization of the copyright holder. \ No newline at end of file +in this Software without prior written authorization of the copyright holder. + +** httparse-1.10.1 (optional Rust addon) + +Copyright (c) 2015-2025 Sean McArthur + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +** libc-0.2.191 (optional Rust addon) + +Copyright (c) The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/package.json b/package.json index 373bcc1..a6cdedd 100644 --- a/package.json +++ b/package.json @@ -19,6 +19,10 @@ "scripts": { "preinstall": "./scripts/preinstall.sh", "postinstall": "./scripts/postinstall.sh", + "build:rust": "./scripts/build-rust.sh", + "test:native": "node --test test/native/contract.mjs", + "test:stream": "node --test test/native/stream.mjs", + "bench:native": "node test/native/bench.mjs", "build:gyp": "node-gyp rebuild --directory=src/native", "clean": "rm -rf dist coverage", "build": "npm test && npm run compile && npm run pkg", @@ -41,6 +45,10 @@ "deps/*.tar.xz", "src/native/binding.gyp", "src/native/rapid-client.cc", + "src/native/rust/Cargo.toml", + "src/native/rust/Cargo.lock", + "src/native/rust/src/*.rs", + "scripts/build-rust.sh", "scripts/preinstall.sh", "scripts/postinstall.sh", "LICENSE", diff --git a/scripts/build-rust.sh b/scripts/build-rust.sh new file mode 100755 index 0000000..44af9a9 --- /dev/null +++ b/scripts/build-rust.sh @@ -0,0 +1,21 @@ +#!/bin/sh +set -eu + +cd "$(dirname "$0")/.." +if [ "$(uname -s)" != Linux ]; then + echo "The experimental Rust client requires Linux." >&2 + exit 1 +fi + +crate=src/native/rust +target="$crate/target" +case "$PWD" in + */node_modules/*) + target=$(mktemp -d) + trap 'rm -rf "$target"' EXIT + ;; +esac +cargo build --manifest-path "$crate/Cargo.toml" --target-dir "$target" --release --locked +# Rename instead of truncating a shared object that might still be mapped. +cp "$target/release/librapid_client.so" rapid-client.tmp.node +mv rapid-client.tmp.node rapid-client.node diff --git a/scripts/postinstall.sh b/scripts/postinstall.sh index f349cc5..cff5e83 100755 --- a/scripts/postinstall.sh +++ b/scripts/postinstall.sh @@ -9,6 +9,11 @@ PACKAGE_DIR=$(cd "$SCRIPT_DIR/.." && pwd) DEPS_DIR="$PACKAGE_DIR/deps" ARTIFACTS_DIR="$DEPS_DIR/artifacts" +# Opt in at install time. Keep the existing C++ build as the default. +if [ "${RIC_NATIVE_CLIENT:-}" = "rust" ]; then + exec "$SCRIPT_DIR/build-rust.sh" +fi + # OS detection - skip on macOS if [ "$(uname)" = "Darwin" ]; then echo "aws-lambda-cpp does not build on OS X. Skipping the postinstall step." diff --git a/scripts/preinstall.sh b/scripts/preinstall.sh index 1372153..6ad30f9 100755 --- a/scripts/preinstall.sh +++ b/scripts/preinstall.sh @@ -9,6 +9,11 @@ PACKAGE_DIR=$(cd "$SCRIPT_DIR/.." && pwd) DEPS_DIR="$PACKAGE_DIR/deps" ARTIFACTS_DIR="$DEPS_DIR/artifacts" +# Opt in at install time. Keep the existing C++ build as the default. +if [ "${RIC_NATIVE_CLIENT:-}" = "rust" ]; then + exit 0 +fi + # OS detection - skip on macOS if [ "$(uname)" = "Darwin" ]; then echo "aws-lambda-cpp does not build on OS X. Skipping the preinstall step." diff --git a/src/native/rust/Cargo.lock b/src/native/rust/Cargo.lock new file mode 100644 index 0000000..20f4090 --- /dev/null +++ b/src/native/rust/Cargo.lock @@ -0,0 +1,23 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "rapid-client" +version = "0.1.0" +dependencies = [ + "httparse", + "libc", +] diff --git a/src/native/rust/Cargo.toml b/src/native/rust/Cargo.toml new file mode 100644 index 0000000..ba97cce --- /dev/null +++ b/src/native/rust/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "rapid-client" +version = "0.1.0" +license = "Apache-2.0" +edition = "2024" +rust-version = "1.85" +publish = false + +[lib] +crate-type = ["cdylib"] + +[dependencies] +httparse = { version = "1.10.1", default-features = false } +libc = { version = "0.2", default-features = false } + +[profile.dev] +panic = "abort" + +[profile.release] +panic = "abort" +lto = true +codegen-units = 1 +strip = "symbols" diff --git a/src/native/rust/src/addon.rs b/src/native/rust/src/addon.rs new file mode 100644 index 0000000..f8dc5ac --- /dev/null +++ b/src/native/rust/src/addon.rs @@ -0,0 +1,280 @@ +// SPDX-License-Identifier: Apache-2.0 +use crate::{ + http::{self, Response}, + napi::*, + socket::{Endpoint, Socket}, +}; +use alloc::{boxed::Box, sync::Arc, vec::Vec}; +use core::ptr::null_mut; + +// One pool per Node environment. Only the owning JS thread touches it. +// Each async work item borrows nothing from the pool and owns its socket. +struct Pool { + endpoint: Arc, + #[allow(clippy::vec_box)] // reuse the stable addresses passed to Node + idle: Vec>, +} + +struct Session { + endpoint: Arc, + socket: Option, + bytes: Vec, + response: Option, + work: Handle, + deferred: Handle, +} + +unsafe extern "C" fn finalize(_: Env, data: Handle, _: Handle) { + drop(unsafe { Box::from_raw(data.cast::()) }); +} + +fn pool(env: Env) -> Result<*mut Pool> { + let mut data = null_mut(); + check(unsafe { napi_get_instance_data(env, &mut data) })?; + if data.is_null() { + return Err(()); + } + Ok(data.cast()) +} + +fn take(env: Env) -> Result> { + // No Node calls while this exclusive borrow is live. + let pool = unsafe { &mut *pool(env)? }; + Ok(pool.idle.pop().unwrap_or_else(|| { + Box::new(Session { + endpoint: pool.endpoint.clone(), + socket: None, + bytes: Vec::with_capacity(8192), + response: None, + work: null_mut(), + deferred: null_mut(), + }) + })) +} + +fn put(env: Env, mut session: Box) { + if let Ok(p) = pool(env) { + let pool = unsafe { &mut *p }; + if pool.idle.len() < 4 { + session.work = null_mut(); + session.deferred = null_mut(); + session.response = None; + session.bytes.clear(); + if session.bytes.capacity() > 8 * 1024 * 1024 { + session.bytes = Vec::with_capacity(8192); + } + pool.idle.push(session); + } + } +} + +impl Session { + fn exchange(&mut self, poll: bool) -> Option { + let socket = self + .socket + .take() + .filter(Socket::idle) + .or_else(|| self.endpoint.connect())?; + socket.send(if poll { + &self.endpoint.next + } else { + &self.bytes + })?; + let response = http::receive(&socket, &mut self.bytes, poll)?; + if response.reusable { + self.socket = Some(socket); + } + Some(response) + } + + fn invocation(&self, env: Env, r: &Response) -> Result { + let headers = env.object()?; + for (i, key) in http::KEYS.iter().enumerate() { + let bytes = &self.bytes[r.fields[i].clone().unwrap_or_default()]; + if i >= 4 && bytes.is_empty() { + continue; + } + let v = if i == 0 { + let ms = core::str::from_utf8(bytes) + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(0); + env.number(ms)? + } else { + env.string(bytes)? + }; + env.set(headers, key, v)?; + } + let obj = env.object()?; + env.set(obj, c"bodyJson", env.string(&self.bytes[r.body..])?)?; + env.set(obj, c"headers", headers)?; + Ok(obj) + } + + fn prepare(&mut self, env: Env, args: [Handle; 3], error: bool) -> Result<()> { + let buf = &mut self.bytes; + buf.extend_from_slice(b"POST /2018-06-01/runtime/invocation/"); + let start = buf.len(); + env.append(buf, args[0])?; + // The TS wrapper already ran encodeURIComponent. Preserve % escapes. + if !buf[start..] + .iter() + .all(|b| b.is_ascii_alphanumeric() || b"-_.!~*'()%".contains(b)) + { + return Err(()); + } + buf.extend_from_slice(if error { b"/error" } else { b"/response" }); + buf.extend_from_slice(&self.endpoint.common); + if error { + let start = buf.len(); + buf.extend_from_slice(b"Lambda-Runtime-Function-XRay-Error-Cause: "); + let val = buf.len(); + env.append(buf, args[2])?; + if buf.len() == val { + buf.truncate(start); + } else { + if buf[val..] + .iter() + .any(|b| b.is_ascii_control() && *b != b'\t') + { + return Err(()); + } + buf.extend_from_slice(b"\r\n"); + } + } + // Backfill the length into HTTP optional whitespace. The V8 string + // is encoded straight into the final packet, with no staging copy. + buf.extend_from_slice( + b"Content-Type: application/json\r\nContent-Length: \r\n\r\n", + ); + let body = buf.len(); + env.append(buf, args[1])?; + let mut n = buf.len() - body; + let mut pos = body - 4; + loop { + pos -= 1; + buf[pos] = b'0' + (n % 10) as u8; + n /= 10; + if n == 0 { + break; + } + } + Ok(()) + } +} + +fn post(env: Env, info: Handle, error: bool) -> Result { + let args = env.args(info, if error { 3 } else { 2 })?; + let mut session = take(env)?; + if session.prepare(env, args, error).is_err() { + put(env, session); + return env.invalid(c"Wrong arguments"); + } + // Upstream's synchronous methods return null even when the POST fails. + if !session + .exchange(false) + .is_some_and(|r| (200..300).contains(&r.code)) + { + let msg = b"Failed to post invocation result to the Lambda Runtime API\n"; + unsafe { libc::write(2, msg.as_ptr().cast(), msg.len()) }; + } + put(env, session); + env.null() +} + +unsafe extern "C" fn done(env: Env, info: Handle) -> Handle { + env.finish(post(env, info, false)) +} +unsafe extern "C" fn error(env: Env, info: Handle) -> Handle { + env.finish(post(env, info, true)) +} + +unsafe extern "C" fn execute(_: Env, data: Handle) { + // Node runs complete after execute. The JS thread cannot touch the + // session while queued. No Node handles are used on this thread. + let s = unsafe { &mut *data.cast::() }; + s.response = s.exchange(true); +} + +unsafe extern "C" fn complete(env: Env, status: i32, data: Handle) { + let s = unsafe { Box::from_raw(data.cast::()) }; + unsafe { napi_delete_async_work(env, s.work) }; + let deferred = s.deferred; + let result = match &s.response { + Some(r) if !(200..300).contains(&r.code) => Err(i32::from(r.code)), + Some(r) if status == 0 && r.fields[1].is_some() => s.invocation(env, r).map_err(|()| -1), + _ => Err(-1), + }; + put(env, s); + match result { + Ok(v) => { + unsafe { napi_resolve_deferred(env, deferred, v) }; + } + Err(code) => { + let _ = env.reject(deferred, code); + } + } +} + +fn queue(env: Env) -> Result { + let mut s = take(env)?; + let name = env.string(b"Lambda.next")?; + let mut promise = null_mut(); + check(unsafe { napi_create_promise(env, &mut s.deferred, &mut promise) })?; + // Transfer the box to complete only if the work was successfully queued. + // On either setup failure we still own it and must settle the promise. + let data = Box::into_raw(s); + unsafe { + let mut work = null_mut(); + if napi_create_async_work( + env, + null_mut(), + name, + execute, + complete, + data.cast(), + &mut work, + ) == 0 + { + (*data).work = work; + if napi_queue_async_work(env, work) == 0 { + return Ok(promise); + } + napi_delete_async_work(env, work); + } + let s = Box::from_raw(data); + env.reject(s.deferred, -1)?; + } + Ok(promise) +} + +unsafe extern "C" fn next(env: Env, _: Handle) -> Handle { + env.finish(queue(env)) +} + +fn register(env: Env, exports: Handle) -> Result { + let endpoint = env + .endpoint() + .ok() + .and_then(|s| Endpoint::parse(core::str::from_utf8(&s).ok()?)); + let Some(endpoint) = endpoint else { + return env.invalid(c"Expected AWS_LAMBDA_RUNTIME_API=host:port"); + }; + let data = Box::into_raw(Box::new(Pool { + endpoint: Arc::new(endpoint), + idle: Vec::new(), + })); + if unsafe { napi_set_instance_data(env, data.cast(), finalize, null_mut()) } != 0 { + drop(unsafe { Box::from_raw(data) }); + return Err(()); + } + env.register(exports, c"next", next)?; + env.register(exports, c"done", done)?; + env.register(exports, c"error", error)?; + Ok(exports) +} + +#[unsafe(no_mangle)] +unsafe extern "C" fn napi_register_module_v1(env: Env, exports: Handle) -> Handle { + env.finish(register(env, exports)) +} diff --git a/src/native/rust/src/http.rs b/src/native/rust/src/http.rs new file mode 100644 index 0000000..53387b6 --- /dev/null +++ b/src/native/rust/src/http.rs @@ -0,0 +1,176 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Parse in the receive buffer. Offsets survive reallocation and the handoff +//! from a libuv worker to the JS thread. +use crate::socket::Socket; +use alloc::vec::Vec; +use core::{ffi::CStr, ops::Range}; +use httparse::Status; + +const MAX_HEAD: usize = 128 * 1024; +const MAX_WIRE: usize = 32 * 1024 * 1024; + +pub const KEYS: [&CStr; 7] = [ + c"lambda-runtime-deadline-ms", + c"lambda-runtime-aws-request-id", + c"lambda-runtime-trace-id", + c"lambda-runtime-invoked-function-arn", + c"lambda-runtime-client-context", + c"lambda-runtime-cognito-identity", + c"lambda-runtime-aws-tenant-id", +]; + +#[derive(Default)] +pub struct Response { + pub code: u16, + pub reusable: bool, + pub body: usize, + pub fields: [Option>; KEYS.len()], +} + +fn more(s: &Socket, buf: &mut Vec, limit: usize) -> Option<()> { + (s.read(buf, limit)? > 0).then_some(()) +} + +fn fill(s: &Socket, buf: &mut Vec, end: usize) -> Option<()> { + if end > MAX_WIRE { + return None; + } + if end > buf.len() { + buf.try_reserve_exact(end - buf.len()).ok()?; + while buf.len() < end { + more(s, buf, end)?; + } + } + Some(()) +} + +pub fn receive(s: &Socket, buf: &mut Vec, poll: bool) -> Option { + buf.clear(); + more(s, buf, MAX_HEAD)?; + let mut start = 0; + loop { + let mut headers = [httparse::EMPTY_HEADER; 128]; + let mut head = httparse::Response::new(&mut headers); + let Status::Complete(n) = head.parse(&buf[start..]).ok()? else { + more(s, buf, MAX_HEAD)?; + continue; + }; + start += n; + let code = head.code?; + if code == 101 { + return None; + } + if (100..200).contains(&code) { + continue; + } + let mut r = Response { + code, + reusable: head.version == Some(1), + body: start, + ..Response::default() + }; + let mut len = None; + let mut chunked = false; + for h in head.headers { + let name = h.name.as_bytes(); + if name.eq_ignore_ascii_case(b"content-length") { + if len.is_some() || !h.value.iter().all(u8::is_ascii_digit) { + return None; + } + len = Some(core::str::from_utf8(h.value).ok()?.parse::().ok()?); + } else if name.eq_ignore_ascii_case(b"transfer-encoding") { + if chunked || !h.value.eq_ignore_ascii_case(b"chunked") { + return None; + } + chunked = true; + } else if name.eq_ignore_ascii_case(b"connection") { + if h.value + .split(|&b| b == b',') + .any(|v| v.trim_ascii().eq_ignore_ascii_case(b"close")) + { + r.reusable = false; + } + } else if poll { + if let Some(i) = KEYS + .iter() + .position(|k| name.eq_ignore_ascii_case(k.to_bytes())) + { + let pos = if h.value.is_empty() { + 0 + } else { + h.value.as_ptr() as usize - buf.as_ptr() as usize + }; + r.fields[i].get_or_insert(pos..pos + h.value.len()); + } + } + } + if chunked && len.is_some() { + return None; + } + if code == 204 || code == 304 { + if buf.len() != start { + return None; + } + } else if chunked { + chunks(s, buf, start)?; + } else if let Some(len) = len { + let end = start.checked_add(len)?; + fill(s, buf, end)?; + if buf.len() != end { + return None; + } + } else { + r.reusable = false; + while s.read(buf, MAX_WIRE + 1)? != 0 {} + } + return Some(r); + } +} + +// Decode in place. The read cursor includes chunk framing, so MAX_WIRE +// bounds total input even for many tiny chunks. +fn chunks(s: &Socket, buf: &mut Vec, mut pos: usize) -> Option<()> { + let mut out = pos; + loop { + let (n, size) = match httparse::parse_chunk_size(&buf[pos..]).ok()? { + Status::Complete(pair) => pair, + Status::Partial => { + if buf.len() - pos > MAX_HEAD { + return None; + } + more(s, buf, MAX_WIRE)?; + continue; + } + }; + pos += n; + if size == 0 { + break; + } + let end = pos.checked_add(usize::try_from(size).ok()?)?; + let next = end.checked_add(2)?; + // Let capacity grow geometrically across chunks. + if next > MAX_WIRE { + return None; + } + while buf.len() < next { + more(s, buf, MAX_WIRE)?; + } + if &buf[end..next] != b"\r\n" { + return None; + } + buf.copy_within(pos..end, out); + out += end - pos; + pos = next; + } + loop { + let mut trailers = [httparse::EMPTY_HEADER; 128]; + match httparse::parse_headers(&buf[pos..], &mut trailers).ok()? { + Status::Complete((n, _)) if pos + n == buf.len() && n <= MAX_HEAD => { + buf.truncate(out); + return Some(()); + } + Status::Partial if buf.len() - pos < MAX_HEAD => more(s, buf, MAX_WIRE)?, + _ => return None, + } + } +} diff --git a/src/native/rust/src/lib.rs b/src/native/rust/src/lib.rs new file mode 100644 index 0000000..0585a4f --- /dev/null +++ b/src/native/rust/src/lib.rs @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: Apache-2.0 +#![no_std] + +extern crate alloc; + +mod addon; +mod http; +mod napi; +mod socket; + +#[cfg(not(test))] +mod memory { + use core::alloc::{GlobalAlloc, Layout}; + + struct Heap; + + // malloc/realloc serve all fundamental alignments. Use posix_memalign for + // over-aligned layouts, which can still be freed by free(). + unsafe impl GlobalAlloc for Heap { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + if layout.align() <= align_of::() { + return unsafe { libc::malloc(layout.size()).cast() }; + } + let mut p = core::ptr::null_mut(); + unsafe { libc::posix_memalign(&mut p, layout.align(), layout.size()) }; + p.cast() + } + + unsafe fn dealloc(&self, ptr: *mut u8, _: Layout) { + unsafe { libc::free(ptr.cast()) }; + } + + unsafe fn realloc(&self, ptr: *mut u8, old: Layout, size: usize) -> *mut u8 { + if old.align() <= align_of::() { + return unsafe { libc::realloc(ptr.cast(), size).cast() }; + } + // GlobalAlloc::realloc guarantees a valid layout with the old alignment. + unsafe { + let p = self.alloc(Layout::from_size_align_unchecked(size, old.align())); + if !p.is_null() { + ptr.copy_to_nonoverlapping(p, old.size().min(size)); + self.dealloc(ptr, old); + } + p + } + } + } + + #[global_allocator] + static HEAP: Heap = Heap; + + #[panic_handler] + fn panic(_: &core::panic::PanicInfo<'_>) -> ! { + unsafe { libc::abort() } + } +} diff --git a/src/native/rust/src/napi.rs b/src/native/rust/src/napi.rs new file mode 100644 index 0000000..f5739b7 --- /dev/null +++ b/src/native/rust/src/napi.rs @@ -0,0 +1,219 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Small subset of the stable Node-API C ABI. Handles are scoped to the +//! current JS callback, except for deferreds and async work handles. +use alloc::vec::Vec; +use core::{ + ffi::{CStr, c_char, c_void}, + ptr::{null, null_mut}, +}; + +pub type Handle = *mut c_void; +pub type Result = core::result::Result; +type Callback = unsafe extern "C" fn(Env, Handle) -> Handle; +#[derive(Clone, Copy)] +#[repr(transparent)] +pub struct Env(Handle); + +unsafe extern "C" { + fn napi_create_function( + e: Env, + name: *const c_char, + len: usize, + cb: Callback, + data: Handle, + out: *mut Handle, + ) -> i32; + fn napi_get_cb_info( + e: Env, + info: Handle, + argc: *mut usize, + argv: *mut Handle, + this: *mut Handle, + data: *mut Handle, + ) -> i32; + fn napi_create_string_utf8(e: Env, bytes: *const u8, len: usize, out: *mut Handle) -> i32; + fn napi_get_value_string_utf8( + e: Env, + value: Handle, + buf: *mut u8, + len: usize, + written: *mut usize, + ) -> i32; + fn napi_create_object(e: Env, out: *mut Handle) -> i32; + fn napi_create_double(e: Env, n: f64, out: *mut Handle) -> i32; + fn napi_set_named_property(e: Env, obj: Handle, key: *const c_char, value: Handle) -> i32; + fn napi_get_named_property(e: Env, obj: Handle, key: *const c_char, out: *mut Handle) -> i32; + fn napi_get_null(e: Env, out: *mut Handle) -> i32; + fn napi_get_global(e: Env, out: *mut Handle) -> i32; + fn napi_throw_type_error(e: Env, code: *const c_char, msg: *const c_char) -> i32; + fn napi_throw_error(e: Env, code: *const c_char, msg: *const c_char) -> i32; + fn napi_create_error(e: Env, code: Handle, msg: Handle, out: *mut Handle) -> i32; + fn napi_is_exception_pending(e: Env, out: *mut bool) -> i32; + fn napi_get_and_clear_last_exception(e: Env, out: *mut Handle) -> i32; + pub fn napi_set_instance_data( + e: Env, + data: Handle, + finalize: unsafe extern "C" fn(Env, Handle, Handle), + hint: Handle, + ) -> i32; + pub fn napi_get_instance_data(e: Env, out: *mut Handle) -> i32; + pub fn napi_create_promise(e: Env, deferred: *mut Handle, out: *mut Handle) -> i32; + pub fn napi_resolve_deferred(e: Env, deferred: Handle, value: Handle) -> i32; + pub fn napi_reject_deferred(e: Env, deferred: Handle, value: Handle) -> i32; + pub fn napi_create_async_work( + e: Env, + resource: Handle, + name: Handle, + execute: unsafe extern "C" fn(Env, Handle), + complete: unsafe extern "C" fn(Env, i32, Handle), + data: Handle, + work: *mut Handle, + ) -> i32; + pub fn napi_queue_async_work(e: Env, work: Handle) -> i32; + pub fn napi_delete_async_work(e: Env, work: Handle) -> i32; +} + +pub fn check(status: i32) -> Result<()> { + if status == 0 { Ok(()) } else { Err(()) } +} + +fn value(f: impl FnOnce(*mut Handle) -> i32) -> Result { + let mut out = null_mut(); + check(f(&mut out))?; + Ok(out) +} + +impl Env { + pub fn register(self, exports: Handle, name: &CStr, cb: Callback) -> Result<()> { + let f = value(|out| unsafe { + napi_create_function( + self, + name.as_ptr(), + name.to_bytes().len(), + cb, + null_mut(), + out, + ) + })?; + self.set(exports, name, f) + } + + pub fn endpoint(self) -> Result> { + let mut v = value(|out| unsafe { napi_get_global(self, out) })?; + for key in [c"process", c"env", c"AWS_LAMBDA_RUNTIME_API"] { + v = value(|out| unsafe { napi_get_named_property(self, v, key.as_ptr(), out) })?; + } + let mut bytes = Vec::new(); + self.append(&mut bytes, v)?; + Ok(bytes) + } + + pub fn args(self, info: Handle, n: usize) -> Result<[Handle; 3]> { + let mut args = [null_mut(); 3]; + let mut argc = args.len(); + check(unsafe { + napi_get_cb_info( + self, + info, + &mut argc, + args.as_mut_ptr(), + null_mut(), + null_mut(), + ) + })?; + if argc < n { + let msg = if n == 2 { + c"Wrong number of arguments, expected 2" + } else { + c"Wrong number of arguments, expected 3" + }; + return self.invalid(msg); + } + Ok(args) + } + + // Write UTF-8 directly to the send buffer. On a warm connection the + // existing capacity usually saves a full V8 UTF-8 length scan. V8 can + // stop up to 3 bytes early at a code point boundary, plus the NUL. + pub fn append(self, buf: &mut Vec, v: Handle) -> Result<()> { + let mut n = 0; + unsafe { + let tail = buf.spare_capacity_mut(); + if tail.len() > 4 { + check(napi_get_value_string_utf8( + self, + v, + tail.as_mut_ptr().cast(), + tail.len(), + &mut n, + ))?; + if n < tail.len() - 4 { + buf.set_len(buf.len() + n); + return Ok(()); + } + } + check(napi_get_value_string_utf8(self, v, null_mut(), 0, &mut n))?; + buf.try_reserve(n + 5).map_err(|_| ())?; + let tail = buf.spare_capacity_mut(); + check(napi_get_value_string_utf8( + self, + v, + tail.as_mut_ptr().cast(), + n + 1, + &mut n, + ))?; + buf.set_len(buf.len() + n); + } + Ok(()) + } + + pub fn object(self) -> Result { + value(|out| unsafe { napi_create_object(self, out) }) + } + pub fn string(self, bytes: &[u8]) -> Result { + value(|out| unsafe { napi_create_string_utf8(self, bytes.as_ptr(), bytes.len(), out) }) + } + pub fn number(self, n: u64) -> Result { + value(|out| unsafe { napi_create_double(self, n as f64, out) }) + } + pub fn null(self) -> Result { + value(|out| unsafe { napi_get_null(self, out) }) + } + pub fn set(self, obj: Handle, key: &CStr, v: Handle) -> Result<()> { + check(unsafe { napi_set_named_property(self, obj, key.as_ptr(), v) }) + } + pub fn invalid(self, msg: &CStr) -> Result { + unsafe { napi_throw_type_error(self, null(), msg.as_ptr()) }; + Err(()) + } + fn pending(self) -> bool { + let mut pending = false; + unsafe { napi_is_exception_pending(self, &mut pending) }; + pending + } + pub fn finish(self, result: Result) -> Handle { + result.unwrap_or_else(|()| { + if !self.pending() { + unsafe { + napi_throw_error(self, null(), c"Runtime client Node-API failure".as_ptr()) + }; + } + null_mut() + }) + } + pub fn reject(self, deferred: Handle, code: i32) -> Result<()> { + let err = if self.pending() { + value(|out| unsafe { napi_get_and_clear_last_exception(self, out) })? + } else { + let msg = self.string( + &[ + b"Failed to get next invocation, error ".as_slice(), + alloc::string::ToString::to_string(&code).as_bytes(), + ] + .concat(), + )?; + value(|out| unsafe { napi_create_error(self, null_mut(), msg, out) })? + }; + check(unsafe { napi_reject_deferred(self, deferred, err) }) + } +} diff --git a/src/native/rust/src/socket.rs b/src/native/rust/src/socket.rs new file mode 100644 index 0000000..48d3b01 --- /dev/null +++ b/src/native/rust/src/socket.rs @@ -0,0 +1,173 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Blocking Linux sockets. There is deliberately no read timeout on long polls. +use alloc::{ffi::CString, vec::Vec}; +use core::{ffi::CStr, ptr}; + +pub struct Socket(i32); + +impl Drop for Socket { + fn drop(&mut self) { + unsafe { libc::close(self.0) }; + } +} + +fn errno() -> i32 { + unsafe { *libc::__errno_location() } +} + +impl Socket { + pub fn open(host: &CStr, port: &CStr) -> Option { + // getaddrinfo owns the linked list until freeaddrinfo. The socket + // does not retain any of the addresses passed to connect. + unsafe { + let mut hints: libc::addrinfo = core::mem::zeroed(); + hints.ai_socktype = libc::SOCK_STREAM; + hints.ai_flags = libc::AI_NUMERICSERV; + let mut list = ptr::null_mut(); + if libc::getaddrinfo(host.as_ptr(), port.as_ptr(), &hints, &mut list) != 0 { + return None; + } + let mut p = list; + let mut result = None; + while let Some(addr) = p.as_ref() { + p = addr.ai_next; + let fd = libc::socket(addr.ai_family, libc::SOCK_STREAM | libc::SOCK_CLOEXEC, 0); + if fd < 0 { + continue; + } + let s = Self(fd); + let mut timeout = libc::timeval { + tv_sec: 1, + tv_usec: 0, + }; + if !s.option(libc::SOL_SOCKET, libc::SO_SNDTIMEO, &timeout) + || libc::connect(fd, addr.ai_addr, addr.ai_addrlen) != 0 + { + continue; + } + timeout.tv_sec = 0; + if s.option(libc::SOL_SOCKET, libc::SO_SNDTIMEO, &timeout) + && s.option(libc::IPPROTO_TCP, libc::TCP_NODELAY, &1i32) + { + result = Some(s); + break; + } + } + libc::freeaddrinfo(list); + result + } + } + + fn option(&self, level: i32, name: i32, v: &T) -> bool { + unsafe { + libc::setsockopt( + self.0, + level, + name, + ptr::from_ref(v).cast(), + size_of::() as _, + ) == 0 + } + } + + // Reconnect on idle FIN/RST or unexpected data. Never replay a request + // after a failed exchange: the Runtime API may already have consumed it. + pub fn idle(&self) -> bool { + let mut b = 0u8; + unsafe { + libc::recv( + self.0, + ptr::from_mut(&mut b).cast(), + 1, + libc::MSG_DONTWAIT | libc::MSG_PEEK, + ) < 0 + && errno() == libc::EAGAIN + } + } + + pub fn send(&self, mut data: &[u8]) -> Option<()> { + while !data.is_empty() { + let n = + unsafe { libc::send(self.0, data.as_ptr().cast(), data.len(), libc::MSG_NOSIGNAL) }; + if n < 0 && errno() == libc::EINTR { + continue; + } + if n <= 0 { + return None; + } + data = &data[n as usize..]; + } + Some(()) + } + + /// Read directly into uninitialized spare capacity. Only expose the bytes + /// that recv actually wrote. A zero return is EOF. + pub fn read(&self, buf: &mut Vec, limit: usize) -> Option { + let room = limit.checked_sub(buf.len())?; + if room == 0 { + return None; + } + if buf.len() == buf.capacity() { + buf.try_reserve_exact(room.min(buf.len().max(8192))).ok()?; + } + loop { + let tail = buf.spare_capacity_mut(); + let n = + unsafe { libc::recv(self.0, tail.as_mut_ptr().cast(), tail.len().min(room), 0) }; + if n < 0 && errno() == libc::EINTR { + continue; + } + let n = usize::try_from(n).ok()?; + unsafe { buf.set_len(buf.len() + n) }; + return Some(n); + } + } +} + +pub struct Endpoint { + host: CString, + port: CString, + pub common: Vec, + pub next: Vec, +} + +impl Endpoint { + pub fn parse(authority: &str) -> Option { + let (host, port) = authority.rsplit_once(':')?; + let host = host + .strip_prefix('[') + .and_then(|s| s.strip_suffix(']')) + .unwrap_or(host); + if host.is_empty() + || !host + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b".-_:".contains(&b)) + || !port.bytes().all(|b| b.is_ascii_digit()) + || port.parse::().ok()? == 0 + { + return None; + } + let common = [ + b" HTTP/1.1\r\nHost: ".as_slice(), + authority.as_bytes(), + b"\r\nUser-Agent: aws-lambda-ric-rust/0.1\r\nAccept: */*\r\n", + ] + .concat(); + let next = [ + b"GET /2018-06-01/runtime/invocation/next".as_slice(), + &common, + b"\r\n", + ] + .concat(); + Some(Self { + host: CString::new(host).ok()?, + port: CString::new(port).ok()?, + common, + next, + }) + } + + pub fn connect(&self) -> Option { + Socket::open(&self.host, &self.port) + } +} diff --git a/test/native/README.md b/test/native/README.md new file mode 100644 index 0000000..c65a407 --- /dev/null +++ b/test/native/README.md @@ -0,0 +1,127 @@ +# Experimental Rust Runtime API client + +This Linux addon implements the three exports of `rapid-client.node` using +Node-API. It compiles with `#![no_std]`, uses `alloc` backed by libc, and has +two Cargo dependencies with their default features disabled. Node supplies the +worker pool. There is no Tokio runtime or libcurl dependency in the addon. + +- `next()` queues a blocking long poll on the libuv worker pool. The worker + records byte offsets for Lambda metadata in the receive buffer. On the JS + thread, Node-API creates the strings and the numeric deadline. +- `done(id, json)` and `error(id, json, cause)` synchronously post and consume + the reply. V8 encodes the JSON straight into the outgoing request buffer. + The request ID has already passed through `encodeURIComponent`. +- Each environment caches up to four idle sessions. A session owns its socket + and a reusable buffer. A queued poll owns its entire session until completion. + Buffers over 8 MiB are released on return to the pool. +- The existing JS code handles response streaming, initialization errors, and + the alternative HTTP poller. Production TypeScript is unchanged. + +## Build and switch + +Use Node 22 or later, a Linux linker and recent stable Rust with Cargo. Tested +with Rust 1.100.1. The crates are pinned in `src/native/rust/Cargo.lock`. +Run `RIC_NATIVE_CLIENT=rust npm ci` to skip the C++ and curl builds. For a +checkout with both clients, run the following at the repository root. + +```sh +# Compile the C++ baseline with optimization in the bundled AWS library. +CMAKE_BUILD_TYPE=Release npm ci +npm run build +NATIVE_ADDON=../../src/native/build/Release/rapid-client.node npm run test:native +npm run test:stream + +# Install Rust as the active addon, keeping the C++ build in src/native/build. +npm run build:rust +npm run test:native +npm run test:stream +cargo tree --manifest-path src/native/rust/Cargo.toml --locked -e features +``` + +Check `CMAKE_BUILD_TYPE` in `deps/aws-lambda-cpp-src/build/CMakeCache.txt`. +With an existing cache or older CMake, explicitly rebuild the baseline before +`npm run build:rust`. + +```sh +cmake -S deps/aws-lambda-cpp-src -B deps/aws-lambda-cpp-src/build -DCMAKE_BUILD_TYPE=Release +cmake --build deps/aws-lambda-cpp-src/build --target install +./scripts/postinstall.sh +``` + +To switch back after building both, stop the runtime and copy +`src/native/build/Release/rapid-client.node` to `rapid-client.node`. With +only the Rust build installed, run `npm ci` without `RIC_NATIVE_CLIENT`. + +## Measurements + +Both clients must be built and Rust must be active. All servers use loopback. +Results depend on the allocator, CPU, scheduler, Node version and local server. + +```sh +npm run bench:native +node test/native/memory.mjs +``` + +The latency test times a warm `next()` followed by `done()` with the same +ASCII JSON in both directions. It excludes JSON parsing, serialization, and +handler execution. Each trial starts a fresh process and server, warms up, +then reports latency percentiles and a mean. Six paired trials alternate +client order. Summary statistics are medians across trials. The range gives +the smallest and largest paired latency ratios. + +The memory test uses 12 paired trials with a separate server process. Each +client echoes 100 small events, 32 events of 6 MiB each, then 100 small events. +It reports resident memory after explicit GC at phase boundaries and peak +resident memory from Linux `VmHWM`, in MiB. `requireMs` measures loading the +addon in a fresh Node process with the filesystem cache warm. It excludes +runtime startup and does not measure Lambda cold starts. + +## Durable execution + +Install the optional test dependencies outside the checkout. The live test +uses AWS's [local test runner](https://docs.aws.amazon.com/durable-execution/testing/api-reference/) +and a loopback bridge. Each invocation envelope and result passes through the +addon. The runner's checkpoint client stays in-process. No AWS account is used. + +```sh +sdk=$(mktemp -d) +npm install --prefix "$sdk" --ignore-scripts @aws/durable-execution-sdk-js@3.2.0 @aws/durable-execution-sdk-js-testing@1.4.0 +export NODE_PATH="$sdk/node_modules" +for addon in cpp rust rust cpp cpp rust rust cpp cpp rust rust cpp; do + node test/native/durable.mjs "$addon" + STEPS_PER_WAIT=4 STEP_KIB=176 node test/native/durable.mjs "$addon" +done +MEMORY_CASE=durable STEPS_PER_WAIT=4 STEP_KIB=176 node test/native/memory.mjs +``` + +Each process runs one warmup and five measured workflows. Each workflow +completes eight waits in simulated time. The test verifies nine invocations, +the expected result, and exactly one execution of each checkpointed step. +The two cases accumulate 1 MiB and 5.5 MiB of step results. The local runner +supplies all state inline. SDK requests for additional pages in a deployed +workflow would bypass this addon. + +For each workflow, sum the nine samples before comparing medians. +`transportMs` covers the two HTTP calls and JSON parsing and serialization. +`activeMs` also includes the SDK and handler. Both exclude bridge setup and +time between invocations. Timing uses the real monotonic clock captured before +the runner installs fake timers. The separate memory test reuses nine recorded +envelopes and short replies between the two small-event phases. It includes +JSON parsing and excludes the SDK, checkpoint store and server. + +## Limits and review + +The transport is specific to the trusted HTTP/1.1 Runtime API. It supports +length-delimited, chunked and close-delimited replies, with limits of 128 +headers, 128 KiB for the response head and 32 MiB for the entire reply. It +requires a host and numeric port, sets a one-second connect timeout per +address, leaves long polls untimed, and never retries a partially completed +exchange. The user agent and diagnostic messages differ from the C++ client. +As upstream does, failed POSTs return `null`. The prototype also logs a generic +failure on stderr. + +Long polls occupy worker-pool slots and buffered POSTs block the JS thread. +The idle cap does not limit in-flight requests. Panics and unrecoverable +allocation failures abort the Node process. The C ABI, socket lifecycle, +allocation behavior, and custom HTTP framing need independent review. This +experiment has not been validated in managed Lambda or at production concurrency. diff --git a/test/native/bench.mjs b/test/native/bench.mjs new file mode 100644 index 0000000..22ae4fc --- /dev/null +++ b/test/native/bench.mjs @@ -0,0 +1,156 @@ +// An HTTP worker stands in for RAPID so synchronous POSTs cannot deadlock +// the server. Each trial runs in a fresh process with a fresh connection pool. +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { readFileSync } from "node:fs"; +import { once } from "node:events"; +import { createServer } from "node:http"; +import { createRequire } from "node:module"; +import { fileURLToPath } from "node:url"; +import { Worker, parentPort, workerData } from "node:worker_threads"; + +const script = fileURLToPath(import.meta.url); +const addons = { + cpp: "../../src/native/build/Release/rapid-client.node", + rust: "../../rapid-client.node", +}; +const cases = [ + // Payload bytes in each direction, warmup calls, measured calls. + [128, 500, 3000], + [64 * 1024, 150, 1000], + [1024 * 1024, 30, 200], + [6 * 1024 * 1024, 10, 60], +]; +const id = "b847b808-0782-4c0c-a9e1-bcb3a73b5ffe"; +const base = "/2018-06-01/runtime/invocation/"; + +function serve(size) { + const payload = Buffer.from(JSON.stringify("a".repeat(size - 2))); + let posts = 0; + let polls = 0; + const server = createServer((req, res) => { + if (req.method === "GET") { + assert.equal(req.url, base + "next"); + polls++; + res + .writeHead(200, { + "Content-Length": size, + "Content-Type": "application/json", + "Lambda-Runtime-Aws-Request-Id": id, + "Lambda-Runtime-Deadline-Ms": 1900000000000, + "Lambda-Runtime-Invoked-Function-Arn": + "arn:aws:lambda:us-east-1:123456789012:function:test", + "Lambda-Runtime-Trace-Id": "Root=1-00000000-abcdef;Sampled=0", + }) + .end(payload); + return; + } + assert.equal(req.url, base + id + "/response"); + assert.equal(Number(req.headers["content-length"]), size); + req.resume().on("end", () => { + posts++; + res.writeHead(202, { "Content-Length": 0 }).end(); + }); + }); + server.listen(0, "127.0.0.1", () => + parentPort.postMessage(server.address().port), + ); + parentPort.once("message", () => parentPort.postMessage([polls, posts])); +} + +function percentile(values, p) { + const sorted = values.toSorted((a, b) => a - b); + const x = (sorted.length - 1) * p; + return sorted[Math.floor(x)] * (1 - (x % 1)) + sorted[Math.ceil(x)] * (x % 1); +} + +async function trial(name, [size, warm, count]) { + const server = new Worker(script, { workerData: size }); + try { + const [port] = await once(server, "message"); + process.env.AWS_LAMBDA_RUNTIME_API = "127.0.0.1:" + port; + const client = createRequire(import.meta.url)(addons[name]); + const samples = []; + for (let i = -warm; i < count; i++) { + const t = performance.now(); + const { bodyJson, headers } = await client.next(); + client.done(headers["lambda-runtime-aws-request-id"], bodyJson); + const us = (performance.now() - t) * 1000; + assert.equal(bodyJson.length, size); + if (i >= 0) samples.push(us); + } + server.postMessage("counts"); + const [counts] = await once(server, "message"); + assert.deepEqual(counts, [count + warm, count + warm]); + console.log( + JSON.stringify({ + p50: percentile(samples, 0.5), + p95: percentile(samples, 0.95), + mean: samples.reduce((a, b) => a + b, 0) / count, + }), + ); + } finally { + await server.terminate(); + } +} + +function compare() { + assert( + !readFileSync(new URL(addons.cpp, import.meta.url)).equals( + readFileSync(new URL(addons.rust, import.meta.url)), + ), + "Run npm run build:rust after the C++ build", + ); + const rounds = Number(process.env.ROUNDS ?? 6); + assert(Number.isSafeInteger(rounds) && rounds > 0); + console.log( + "Warm next + done, microseconds, " + process.version + " " + process.arch, + ); + for (const [index, [size, warm, count]] of cases.entries()) { + const pairs = []; + for (let round = 0; round < rounds; round++) { + const pair = {}; + for (const name of round % 2 ? ["rust", "cpp"] : ["cpp", "rust"]) { + pair[name] = JSON.parse( + execFileSync(process.execPath, [script, name, index], { + encoding: "utf8", + timeout: 60000, + }), + ); + } + pairs.push(pair); + console.log( + JSON.stringify({ size, warm, count, round: round + 1, ...pair }), + ); + } + const median = (client, stat) => + percentile( + pairs.map((p) => p[client][stat]), + 0.5, + ); + for (const stat of ["p50", "p95", "mean"]) { + const cpp = median("cpp", stat); + const rust = median("rust", stat); + const ratios = pairs.map((p) => p.cpp[stat] / p.rust[stat]); + console.log( + [ + size, + stat, + "cpp", + cpp.toFixed(1), + "rust", + rust.toFixed(1), + "cpp/rust", + (cpp / rust).toFixed(2), + "range", + Math.min(...ratios).toFixed(2), + Math.max(...ratios).toFixed(2), + ].join(" "), + ); + } + } +} + +if (parentPort) serve(workerData); +else if (process.argv[2]) await trial(process.argv[2], cases[process.argv[3]]); +else compare(); diff --git a/test/native/contract.mjs b/test/native/contract.mjs new file mode 100644 index 0000000..921c925 --- /dev/null +++ b/test/native/contract.mjs @@ -0,0 +1,189 @@ +// Run the same observable contract against either binary. The mock server +// lives on a separate event loop because done/error wait for the HTTP reply. +import assert from "node:assert/strict"; +import { once } from "node:events"; +import { createServer } from "node:http"; +import { createRequire } from "node:module"; +import test from "node:test"; +import { Worker, parentPort } from "node:worker_threads"; + +const base = "/2018-06-01/runtime/invocation/"; +const id = "lambda-runtime-aws-request-id"; +const big = JSON.stringify("é😀".repeat(160000)); +const optional = { + "lambda-runtime-client-context": '{"client":true}', + "lambda-runtime-cognito-identity": '{"identity":1}', + "lambda-runtime-aws-tenant-id": "tenant", +}; +const defaults = { + "lambda-runtime-deadline-ms": 0, + [id]: "r", + "lambda-runtime-trace-id": "", + "lambda-runtime-invoked-function-arn": "", +}; + +function serve() { + let scenario; + const waiting = []; + parentPort.on("message", (name) => { + scenario = name; + parentPort.postMessage("ready"); + }); + const server = createServer((req, res) => { + res.setHeader("Content-Type", "application/json"); + if (req.method === "POST") { + let body = ""; + req + .setEncoding("utf8") + .on("data", (s) => (body += s)) + .on("end", () => { + res.writeHead(scenario === "post-failed" ? 500 : 202).end("{}"); + parentPort.postMessage({ url: req.url, headers: req.headers, body }); + for (const [i, pending] of waiting.splice(0).entries()) + pending.end(String(i)); + }); + return; + } + assert.equal(req.url, base + "next"); + if (scenario !== "missing") + res.setHeader("Lambda-Runtime-Aws-Request-Id", "r"); + switch (scenario) { + case "full": + res + .writeHead(200, { + ...optional, + "Lambda-Runtime-Deadline-Ms": "1930000000012", + "Lambda-Runtime-Invoked-Function-Arn": "arn", + "Lambda-Runtime-Trace-Id": "trace", + "Content-Length": Buffer.byteLength(big), + }) + .end(big); + break; + case "chunked": { + const bytes = Buffer.from(big); + res.write(bytes.subarray(0, 4)); // split a UTF-8 code point + res.addTrailers({ "X-End": "ok" }); + setImmediate(() => res.end(bytes.subarray(4))); + break; + } + case "failed": + res.writeHead(503).end("{}"); + break; + case "closed": + res.writeHead(200, { Connection: "close" }).end("{}"); + break; + case "hold": + waiting.push(res); + if (waiting.length === 2) parentPort.postMessage("both pending"); + break; + default: + res.end("{}"); + } + }); + server.listen(0, "127.0.0.1", () => + parentPort.postMessage(server.address().port), + ); +} + +if (parentPort) serve(); +else + test("native Runtime API contract", { timeout: 15000 }, async (t) => { + const server = new Worker(new URL(import.meta.url)); + t.after(() => server.terminate()); + const message = async () => (await once(server, "message"))[0]; + process.env.AWS_LAMBDA_RUNTIME_API = "127.0.0.1:" + (await message()); + const native = createRequire(import.meta.url)( + process.env.NATIVE_ADDON ?? "../../rapid-client.node", + ); + async function configure(name) { + server.postMessage(name); + assert.equal(await message(), "ready"); + } + await t.test( + "all Lambda metadata, numeric deadline and a large UTF-8 event", + async () => { + await configure("full"); + assert.deepEqual(await native.next(), { + bodyJson: big, + headers: { + ...defaults, + ...optional, + "lambda-runtime-deadline-ms": 1930000000012, + "lambda-runtime-invoked-function-arn": "arn", + "lambda-runtime-trace-id": "trace", + }, + }); + }, + ); + await t.test("chunked input and absent headers", async () => { + await configure("chunked"); + assert.deepEqual(await native.next(), { + bodyJson: big, + headers: defaults, + }); + }); + await t.test( + "HTTP and missing-ID errors, followed by reconnect", + async () => { + for (const [name, code] of [ + ["failed", 503], + ["missing", -1], + ]) { + await configure(name); + await assert.rejects(native.next(), { + message: "Failed to get next invocation, error " + code, + }); + } + await configure("closed"); + for (let i = 0; i < 2; i++) + assert.equal((await native.next()).bodyJson, "{}"); + }, + ); + await t.test( + "done and error post exact bytes and preserve encoded IDs", + async () => { + await configure("post"); + for (const body of ["", big, '{"emoji":"🪿"}']) { + assert.equal(native.done("a%2Fb", body), null); + const post = await message(); + assert.equal(post.url, base + "a%2Fb/response"); + assert.equal(post.body, body); + assert.equal( + Number(post.headers["content-length"]), + Buffer.byteLength(body), + ); + assert.equal(post.headers["content-type"], "application/json"); + } + assert.equal(native.error("r", "{}", '{"cause":1}'), null); + const post = await message(); + assert.equal(post.url, base + "r/error"); + assert.equal( + post.headers["lambda-runtime-function-xray-error-cause"], + '{"cause":1}', + ); + await configure("post-failed"); + assert.equal(native.done("r", "{}"), null); + await message(); + }, + ); + await t.test("synchronous argument validation", () => { + assert.throws(() => native.done("id"), TypeError); + assert.throws(() => native.done("id", 42), TypeError); + assert.throws(() => native.error("id", "{}"), TypeError); + assert.throws(() => native.error("id", "{}", null), TypeError); + }); + await t.test( + "two long polls do not block JS or a synchronous POST", + async () => { + await configure("hold"); + const results = Promise.all([native.next(), native.next()]); + assert.equal(await message(), "both pending"); + native.done("r", "{}"); + await message(); + assert.deepEqual((await results).map((x) => x.bodyJson).sort(), [ + "0", + "1", + ]); + }, + ); + }); diff --git a/test/native/durable.mjs b/test/native/durable.mjs new file mode 100644 index 0000000..776e060 --- /dev/null +++ b/test/native/durable.mjs @@ -0,0 +1,159 @@ +// Optional experiment. The SDK's local runner normally bypasses the Runtime +// API. Bridge just its invocation envelope and result over loopback. +import assert from "node:assert/strict"; +import { once } from "node:events"; +import { createServer } from "node:http"; +import { createRequire } from "node:module"; +import { Worker, parentPort } from "node:worker_threads"; + +const require = createRequire(import.meta.url); +const base = "/2018-06-01/runtime/invocation/"; +const id = "b847b808-0782-4c0c-a9e1-bcb3a73b5ffe"; +// Capture the real clock before skipTime installs fake timers. +const now = process.hrtime.bigint; +const waits = 8; +const perWait = Number(process.env.STEPS_PER_WAIT ?? 1); +const steps = waits * perWait; +const chunk = Number(process.env.STEP_KIB ?? 128) * 1024; + +function serve() { + let payload; + parentPort.on("message", (data) => { + payload = Buffer.from(data); + parentPort.postMessage("ready"); + }); + const server = createServer((req, res) => { + if (req.method === "GET") { + assert.equal(req.url, base + "next"); + res + .writeHead(200, { + "Content-Type": "application/json", + "Content-Length": payload.length, + "Lambda-Runtime-Aws-Request-Id": id, + "Lambda-Runtime-Deadline-Ms": Date.now() + 900000, + }) + .end(payload); + return; + } + assert.equal(req.url, base + id + "/response"); + let result = ""; + req + .setEncoding("utf8") + .on("data", (s) => (result += s)) + .on("end", () => { + res.writeHead(202, { "Content-Length": 0 }).end(); + parentPort.postMessage(result); + }); + }); + server.listen(0, "127.0.0.1", () => + parentPort.postMessage(server.address().port), + ); +} + +async function trial(name) { + const { + withDurableExecution, + DurableExecutionInvocationInputWithClient, + } = require("@aws/durable-execution-sdk-js"); + const { + LocalDurableTestRunner, + } = require("@aws/durable-execution-sdk-js-testing"); + const server = new Worker(new URL(import.meta.url)); + const [port] = await once(server, "message"); + process.env.AWS_LAMBDA_RUNTIME_API = "127.0.0.1:" + port; + assert(["rust", "cpp"].includes(name)); + const native = require( + name === "cpp" + ? "../../src/native/build/Release/rapid-client.node" + : "../../rapid-client.node", + ); + await LocalDurableTestRunner.setupTestEnvironment({ skipTime: true }); + try { + for (let run = -1; run < Number(process.env.RUNS ?? 5); run++) { + let calls = 0; + const handler = withDurableExecution(async (_, ctx) => { + let total = 0; + for (let i = 0; i < steps; i++) { + const value = await ctx.step("page-" + i, async () => { + calls++; + return String(i % 10).repeat(chunk); + }); + assert.equal(value.length, chunk); + assert.equal(value[0], String(i % 10)); + total += value.length; + if ((i + 1) % perWait === 0) await ctx.wait({ seconds: 3600 }); + } + return total; + }); + const samples = []; + const runner = new LocalDurableTestRunner({ + handlerFunction: async ( + { durableExecutionClient, ...event }, + context, + ) => { + const input = JSON.stringify(event); + assert( + !event.InitialExecutionState.NextMarker, + "expected inline state", + ); + server.postMessage(input); + await once(server, "message"); + const posted = once(server, "message"); + const t0 = now(); + const { bodyJson, headers } = await native.next(); + const parsed = JSON.parse(bodyJson); + const t1 = now(); + // Restore only the test runner's out-of-band checkpoint client. + const result = await handler( + new DurableExecutionInvocationInputWithClient( + parsed, + durableExecutionClient, + ), + context, + ); + const t2 = now(); + const output = JSON.stringify(result); + native.done(headers["lambda-runtime-aws-request-id"], output); + const t3 = now(); + const [response] = await posted; + assert.equal(response, output); + assert.equal(bodyJson, input); + samples.push({ + stateBytes: + Buffer.byteLength(input) - + Buffer.byteLength( + JSON.stringify({ ...event, InitialExecutionState: {} }), + ) + + 2, + in: Buffer.byteLength(input), + out: Buffer.byteLength(response), + transportMs: Number(t1 - t0 + (t3 - t2)) / 1e6, + activeMs: Number(t3 - t0) / 1e6, + }); + // The memory harness records one untimed workflow in a child + // process. Only these locally generated fixtures cross IPC. + if (process.send) process.send({ input, output }); + return JSON.parse(response); + }, + }); + const execution = await runner.run({ payload: { test: true } }); + if (execution.getStatus() !== "SUCCEEDED") + assert.fail(JSON.stringify(execution.getError())); + assert.equal(execution.getResult(), steps * chunk); + assert.equal( + calls, + steps, + "completed steps must not execute again on replay", + ); + assert.equal(samples.length, waits + 1); + assert(samples.at(-1).in >= steps * chunk); + if (run >= 0) console.log(JSON.stringify({ name, run, samples })); + } + } finally { + await LocalDurableTestRunner.teardownTestEnvironment(); + await server.terminate(); + } +} + +if (parentPort) serve(); +else await trial(process.argv[2] ?? "rust"); diff --git a/test/native/memory.mjs b/test/native/memory.mjs new file mode 100644 index 0000000..4b28651 --- /dev/null +++ b/test/native/memory.mjs @@ -0,0 +1,141 @@ +// Measure only the client process. The parent hosts the mock Runtime API. +import assert from "node:assert/strict"; +import { fork } from "node:child_process"; +import { once } from "node:events"; +import { readFileSync } from "node:fs"; +import { createServer } from "node:http"; +import { createRequire } from "node:module"; + +const small = 128; +const large = 6 * 1024 * 1024; +const replay = process.env.MEMORY_CASE === "durable"; +const warm = Array(100).fill(small); +function schedule(middle) { + return [...warm, ...middle, ...warm]; +} + +// Capture a real local workflow outside the measured process. The client +// receives only expected sizes and short replies over IPC. +async function record() { + const cases = []; + const runner = fork(new URL("durable.mjs", import.meta.url), ["rust"], { + env: { ...process.env, RUNS: 0 }, + timeout: 30000, + }); + runner.on("message", (fixture) => cases.push(fixture)); + const [code] = await once(runner, "exit"); + assert.equal(code, 0); + assert.equal(cases.length, 9); + return cases; +} + +async function client(name) { + function resident() { + global.gc(); + return process.memoryUsage.rss() / 2 ** 20; + } + const require = createRequire(import.meta.url); + const path = + name === "cpp" + ? "../../src/native/build/Release/rapid-client.node" + : "../../rapid-client.node"; + const cases = replay ? (await once(process, "message"))[0] : []; + const sizes = schedule( + replay ? cases.map((f) => f.size) : Array(32).fill(large), + ); + const stats = { name, baseline: resident() }; + const t = performance.now(); + const native = require(path); + stats.requireMs = performance.now() - t; + stats.loaded = resident(); + async function invoke(size, fixture) { + const { bodyJson, headers } = await native.next(); + assert.equal(bodyJson.length, size); + if (fixture) assert(JSON.parse(bodyJson).InitialExecutionState); + native.done( + headers["lambda-runtime-aws-request-id"], + fixture?.output ?? bodyJson, + ); + } + for (const [i, size] of sizes.entries()) { + await invoke(size, cases[i - warm.length]); + if (i === 99) stats.small = resident(); + if (i === sizes.length - warm.length - 1) stats.large = resident(); + } + stats.retained = resident(); + // VmHWM is reset on exec. getrusage can include the parent's pre-exec RSS. + stats.peak = + Number( + /VmHWM:\s*(\d+)/.exec(readFileSync("/proc/self/status", "utf8"))[1], + ) / 1024; + console.log(JSON.stringify(stats)); +} + +async function measure() { + let polls = 0, + posts = 0; + const payloads = new Map( + [small, large].map((size) => [ + size, + Buffer.from(JSON.stringify("a".repeat(size - 2))), + ]), + ); + const cases = replay ? await record() : []; + const plan = cases.map(({ input, output }) => { + const size = Buffer.byteLength(input); + payloads.set(size, Buffer.from(input)); + return { size, output }; + }); + const sizes = schedule( + replay ? plan.map((f) => f.size) : Array(32).fill(large), + ); + const responses = replay + ? schedule(plan.map((f) => Buffer.byteLength(f.output))) + : sizes; + const server = createServer((req, res) => { + if (req.method === "GET") { + const size = sizes[polls++]; + res + .writeHead(200, { + "Content-Type": "application/json", + "Content-Length": size, + "Lambda-Runtime-Aws-Request-Id": "test", + }) + .end(payloads.get(size)); + } else { + assert.equal(Number(req.headers["content-length"]), responses[posts++]); + req + .resume() + .on("end", () => res.writeHead(202, { "Content-Length": 0 }).end()); + } + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + try { + const rounds = Number(process.env.ROUNDS ?? 12); + assert(Number.isSafeInteger(rounds) && rounds > 0); + for (let i = 0; i < rounds; i++) { + for (const name of i % 2 ? ["rust", "cpp"] : ["cpp", "rust"]) { + polls = posts = 0; + const child = fork(new URL(import.meta.url), [name], { + execArgv: ["--expose-gc"], + timeout: 30000, + env: { + ...process.env, + AWS_LAMBDA_RUNTIME_API: "127.0.0.1:" + server.address().port, + }, + }); + if (replay) child.send(plan); + const [code] = await once(child, "exit"); + assert.equal(code, 0); + assert.equal(polls, sizes.length); + assert.equal(posts, sizes.length); + } + } + } finally { + server.close(); + } +} + +if (process.argv[2]) await client(process.argv[2]); +else await measure(); diff --git a/test/native/stream-handler.mjs b/test/native/stream-handler.mjs new file mode 100644 index 0000000..9c85833 --- /dev/null +++ b/test/native/stream-handler.mjs @@ -0,0 +1,26 @@ +// Wait for the receiver before sending the rest. A buffered response +// cannot finish this handshake. +import { once } from "node:events"; + +export const handler = globalThis.awslambda.streamifyResponse( + async (event, stream) => { + const sink = globalThis.awslambda.HttpResponseStream.from(stream, { + statusCode: 200, + }); + const ack = once(process, "message"); + sink.write("first"); + await ack; + if (event.fail) throw new Error("failed after first chunk"); + let drains = 0; + const bytes = Buffer.alloc(65536, 0x7f); + for (let i = 0; i < 128; i++) { + if (!sink.write(bytes)) { + drains++; + await once(sink, "drain"); + } + } + if (!drains) throw new Error("Did not exercise backpressure"); + sink.end("last"); + }, + { highWaterMark: 16384 }, +); diff --git a/test/native/stream.mjs b/test/native/stream.mjs new file mode 100644 index 0000000..60e8802 --- /dev/null +++ b/test/native/stream.mjs @@ -0,0 +1,109 @@ +import assert from "node:assert/strict"; +import { fork } from "node:child_process"; +import { once } from "node:events"; +import { createServer } from "node:http"; +import test from "node:test"; + +test( + "bundled RIC streams incrementally, reports failure and handles the next invoke", + { timeout: 15000 }, + async (t) => { + const prefix = Buffer.concat([ + Buffer.from('{"statusCode":200}'), + Buffer.alloc(8), + Buffer.from("first"), + ]); + const base = "/2018-06-01/runtime/invocation/"; + const finished = Promise.withResolvers(); + let calls = 0; + const server = createServer((req, res) => { + if (req.method === "GET") { + assert.equal(req.url, base + "next"); + if (calls === 2) return; + const fail = ++calls === 1; + res.setHeader("Content-Type", "application/json"); + res.setHeader("Lambda-Runtime-Aws-Request-Id", String(calls)); + res.setHeader("Lambda-Runtime-Deadline-Ms", Date.now() + 15000); + res.end(JSON.stringify({ fail })); + return; + } + const fail = calls === 1; + assert.equal(req.url, base + calls + "/response"); + assert.equal(req.headers["transfer-encoding"], "chunked"); + assert.equal( + req.headers["lambda-runtime-function-response-mode"], + "streaming", + ); + assert.equal( + req.headers["content-type"], + "application/vnd.awslambda.http-integration-response", + ); + const chunks = []; + let bytes = 0; + req.on("data", (part) => { + chunks.push(part); + bytes += part.length; + if (bytes === prefix.length) { + assert.deepEqual(Buffer.concat(chunks), prefix); + child.send("received"); + } + }); + req.on("end", () => { + res.writeHead(202).end(); + if (fail) { + assert.equal(bytes, prefix.length); + assert.equal( + req.trailers["lambda-runtime-function-error-type"], + "Error", + ); + const cause = JSON.parse( + Buffer.from( + req.trailers["lambda-runtime-function-error-body"], + "base64", + ), + ); + assert.equal(cause.errorMessage, "failed after first chunk"); + } else { + assert.deepEqual(req.trailers, {}); + const data = Buffer.concat(chunks); + assert.deepEqual( + data.subarray(prefix.length, -4), + Buffer.alloc(8 * 1024 * 1024, 0x7f), + ); + assert.equal(data.subarray(-4).toString(), "last"); + finished.resolve(); + } + }); + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const child = fork( + process.env.RIC_ENTRY ?? new URL("../../index.mjs", import.meta.url), + [], + { + execArgv: [], + env: { + ...process.env, + AWS_LAMBDA_RUNTIME_API: "127.0.0.1:" + server.address().port, + AWS_LAMBDA_NODEJS_USE_ALTERNATIVE_CLIENT_1: "false", + AWS_LAMBDA_FUNCTION_NAME: "test", + AWS_LAMBDA_FUNCTION_VERSION: "$LATEST", + AWS_LAMBDA_FUNCTION_MEMORY_SIZE: "128", + AWS_LAMBDA_LOG_GROUP_NAME: "group", + AWS_LAMBDA_LOG_STREAM_NAME: "stream", + _HANDLER: "stream-handler.handler", + LAMBDA_TASK_ROOT: import.meta.dirname, + }, + }, + ); + t.after(() => { + child.kill("SIGKILL"); + server.closeAllConnections(); + server.close(); + }); + child.once("exit", (code) => + finished.reject(new Error("runtime exited: " + code)), + ); + await finished.promise; + }, +); diff --git a/vitest.config.js b/vitest.config.js index 7e711ec..831c856 100644 --- a/vitest.config.js +++ b/vitest.config.js @@ -14,6 +14,7 @@ export default defineConfig({ "**/*.config.js", "dist", "integration-tests", + "test/native/**", "coverage", "resources", "scripts",