Skip to content
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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
## Unreleased

- Change how a session waits between reconnect attempts after it loses its connection, for every session: the wait starts at 50 ms and doubles up to 30 s, each wait scaled by a random factor in [0, 1). Before, the wait grew 50-fold per attempt with no cap and no random factor: about 2 minutes before the fourth attempt and 1 h 44 min before the fifth.
- Add `SessionBuilder.reconnectBackoff(initialMs, maxMs)`, which sets the first wait between reconnect attempts and the cap the doubling waits stop at, and `SessionBuilder.reconnectJitter(enabled)`, which turns off or on the random scaling of each wait. The defaults are 50 ms, 30 s and jitter on. `reconnectBackoff` refuses a value that is not a whole number of milliseconds, such as a fraction, NaN or Infinity, with an error naming the argument.
- Add `SessionBuilder.reconnectMaxAttempts(attempts)`, which stops a session reconnecting after that many failed attempts in one outage; every listener then stops forwarding, and its `forward()` and `join()` reject with the last attempt's error. `listenAndServe`, `ngrok.listen` and `net.Server.listen(listener)` log that error with `console.error` and leave the process running. It refuses anything but a whole number from 1 to 4294967295. By default a session never stops reconnecting on its own.

## 1.7.0

- Add support for CEL filtering when listing resources.
Expand Down
5 changes: 2 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@
lazy_static = "1.4.0"
# pin mio until all dependencies are also on windows-sys 0.48
# https://github.com/microsoft/windows-rs/issues/2410#issuecomment-1490802715
mio = { version = "=0.8.6" }

Check warning on line 16 in Cargo.toml

View workflow job for this annotation

GitHub Actions / Clippy

unused dependency `mio`
# Default enable napi4 feature, see https://nodejs.org/api/n-api.html#node-api-version-matrix
napi = { version = "2.12.1", default-features = false, features = ["napi4", "tokio_rt"] }
napi-derive = "2.12.1"
ngrok = {version = "0.19.0", features = ["hyper", "axum"]}
ngrok = {version = "0.19.1", features = ["hyper", "axum"]}
parking_lot = "0.12.1"
regex = "1.9.5"
rustls = "0.23.25"
Expand Down
124 changes: 124 additions & 0 deletions __test__/online.spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,130 @@ test("connect heartbeat callbacks", async () => {
expect(undefined).toBe(disconn_addr);
});

// The limits are ngrok-rust's; the binding passes its error through, after
// the call and its arguments.
test.each([
["a start of 0 ms", 0, 1000, "the start must be at least 1 ms"],
["a start above the cap", 2000, 1000, "the start must not be above the cap"],
["a cap above one day", 1, 86_400_001, "the cap must be at most one day"],
// Above 2**32, so a u32 argument would wrap these to 50 ms and accept them.
["a start of 2**32 + 50 ms", 2 ** 32 + 50, 1000, "the start must not be above the cap"],
["a cap of 2**32 + 50 ms", 1, 2 ** 32 + 50, "the cap must be at most one day"],
])("session reconnect backoff rejects %s", (_, initialMs, maxMs, rule) => {
const builder = new ngrok.SessionBuilder();
expect(() => builder.reconnectBackoff(initialMs, maxMs)).toThrow(
new RegExp(`^reconnectBackoff\\(initialMs: ${initialMs}, maxMs: ${maxMs}\\): .*${rule}$`),
);
});

// The binding refuses what is not a whole number of milliseconds, naming the
// argument, before ngrok-rust sees it.
test.each([
["a negative start", -1, 1000, "initialMs", "-1"],
["a negative cap", 1, -1, "maxMs", "-1"],
["a fractional start", 0.5, 1000, "initialMs", "0.5"],
["a fractional cap", 1, 1000.5, "maxMs", "1000.5"],
["a NaN start", NaN, 1000, "initialMs", "NaN"],
["an infinite cap", 1, Infinity, "maxMs", "Infinity"],
])("session reconnect backoff rejects %s", (_, initialMs, maxMs, name, shown) => {
const builder = new ngrok.SessionBuilder();
expect(() => builder.reconnectBackoff(initialMs, maxMs)).toThrow(
`${name} must be a whole number of milliseconds, at least 0, got ${shown}`,
);
});

test("session reconnect backoff accepts 1 ms to one day", () => {
const builder = new ngrok.SessionBuilder();
expect(builder.reconnectBackoff(1, 86_400_000)).toBe(builder);
});

test.each([
["0", 0, "0"],
["-1", -1, "-1"],
["2**32 + 1", 2 ** 32 + 1, "4294967297"],
["2.5", 2.5, "2.5"],
["NaN", NaN, "NaN"],
["Infinity", Infinity, "Infinity"],
])("session reconnect max attempts rejects %s", (_, attempts, shown) => {
const builder = new ngrok.SessionBuilder();
expect(() => builder.reconnectMaxAttempts(attempts)).toThrow(
`attempts must be a whole number from 1 to 4294967295, got ${shown}`,
);
});

test("session reconnect max attempts accepts 3", () => {
const builder = new ngrok.SessionBuilder();
expect(builder.reconnectMaxAttempts(3)).toBe(builder);
});

test("session reconnect options connect", async () => {
const session = await new ngrok.SessionBuilder()
.authtoken(process.env["NGROK_AUTHTOKEN"])
.reconnectBackoff(100, 5000)
.reconnectJitter(false)
.reconnectMaxAttempts(5)
.connect();
const httpServer = await makeHttp();
const listener = await session.httpEndpoint().listen();
expect(listener.url().startsWith("https://")).toBeTruthy();
await forwardValidateShutdown(httpServer, listener, listener.url());
await session.close();
});

// A listener's forward() rejects once its session stops reconnecting, which no
// test here can bring about, so a fake builder and listener stand in for the
// native ones.
function givenUpBuilder() {
const listener = {
id: () => "given-up-" + Math.floor(Math.random() * 1000000),
forward: () => Promise.reject(new Error("error forwarding: session gave up")),
};
return { _listen: async () => listener };
}

async function errorsLoggedDuring(run) {
const logged = [];
const consoleError = console.error;
console.error = (message) => logged.push(String(message));
try {
await run();
// let the rejection's handler run
await new Promise((resolve) => setImmediate(resolve));
} finally {
console.error = consoleError;
}
return logged;
}

test("listenAndServe logs forwarding that ends with an error", async () => {
const server = createHttpServer();
const logged = await errorsLoggedDuring(() =>
ngrok.HttpListenerBuilder.prototype.listenAndServe.call(givenUpBuilder(), server),
);
server.close();
expect(logged).toEqual([
expect.stringMatching(
/^ngrok listener stopped forwarding to \S+: Error: error forwarding: session gave up$/,
),
]);
});

test("net.Server.listen(listener) logs forwarding that ends with an error", async () => {
const server = createHttpServer();
let listener;
const logged = await errorsLoggedDuring(async () => {
listener = await ngrok.HttpListenerBuilder.prototype.listen.call(givenUpBuilder());
server.listen(listener);
});
server.close();
listener.socket.close();
expect(logged).toEqual([
expect.stringMatching(
/^ngrok listener stopped forwarding to localhost:\d+: Error: error forwarding: session gave up$/,
),
]);
});

test("session ca_cert", async () => {
const builder = new ngrok.SessionBuilder();
try {
Expand Down
50 changes: 50 additions & 0 deletions index.d.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 12 additions & 3 deletions index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

108 changes: 108 additions & 0 deletions src/session.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::{
env,
num::NonZeroU32,
sync::Arc,
time::Duration,
};
Expand Down Expand Up @@ -182,6 +183,94 @@ impl SessionBuilder {
Ok(self)
}

/// Configures how long the session waits between attempts to reconnect
/// after it loses its connection to the ngrok service, in milliseconds.
///
/// The first attempt is immediate. After it, the session waits `initialMs`,
/// then twice as long before each attempt, up to `maxMs`. Each wait is
/// scaled by a random factor in [0, 1) unless
/// [SessionBuilder::reconnectJitter] turns that off. The defaults are
/// 50 ms and 30 s. For a fixed wait between every attempt, pass the same
/// value for both and turn jitter off.
///
/// These waits never stop the session from reconnecting on their own:
/// [SessionBuilder::reconnectMaxAttempts], or closing the session, does.
///
/// A value that is not a whole number of milliseconds of at least 0 (a
/// fraction, a negative number, NaN or Infinity) is refused with an error
/// naming the argument. The ngrok Rust SDK then checks the range: it
/// rejects an `initialMs` below 1 or above `maxMs`, and a `maxMs` above one
/// day (86400000), with an error that starts with the call and its
/// arguments, as in "reconnectBackoff(initialMs: 2000, maxMs: 1000): ",
/// and names the rule broken. A refused call leaves the builder unchanged.
#[napi]
pub fn reconnect_backoff(&mut self, initial_ms: f64, max_ms: f64) -> Result<&Self> {
let millis = |name: &str, ms: f64| {
whole_number(ms).map(Duration::from_millis).ok_or_else(|| {
napi_err(format!(
"{name} must be a whole number of milliseconds, at least 0, got {}",
js_number(ms)
))
})
};
let initial = millis("initialMs", initial_ms)?;
let max = millis("maxMs", max_ms)?;
let mut builder = self.raw_builder.lock();
builder.reconnect_backoff(initial, max).map_err(|e| {
napi_err(format!(
"reconnectBackoff(initialMs: {}, maxMs: {}): {e}",
js_number(initial_ms),
js_number(max_ms)
))
})?;
Ok(self)
}

/// Configures whether each wait between reconnect attempts is scaled by a
/// random factor in [0, 1). On by default, so that sessions that lose
/// their connections together don't all reconnect at the same moment.
#[napi]
pub fn reconnect_jitter(&mut self, enabled: bool) -> &Self {
let mut builder = self.raw_builder.lock();
builder.reconnect_jitter(enabled);
self
}

/// Configures the session to stop reconnecting after `attempts` failed
/// attempts in one outage, counting the immediate first attempt. Each new
/// outage starts the count again. By default the session never stops on
/// its own.
///
/// When the session stops, every listener stops forwarding with the last
/// attempt's error: [Listener::forward] rejects with an error whose message
/// starts "error forwarding:", and [Listener::join] with one that starts
/// "error on join:". Nothing rejects for the forwarding that `ngrok.forward`
/// starts. The forwarding that `listenAndServe`, `ngrok.listen` and
/// `net.Server.listen(listener)` start logs the error with `console.error`
/// and leaves the process running. The
/// [SessionBuilder::handleDisconnection] handler is called before each
/// attempt, and not again once the session stops.
///
/// `attempts` must be a whole number from 1 to 4294967295; anything else,
/// a fraction, NaN or Infinity included, is refused with an error naming
/// the argument.
#[napi]
pub fn reconnect_max_attempts(&mut self, attempts: f64) -> Result<&Self> {
let attempts = whole_number(attempts)
.and_then(|n| u32::try_from(n).ok())
.and_then(NonZeroU32::new)
.ok_or_else(|| {
napi_err(format!(
"attempts must be a whole number from 1 to {}, got {}",
u32::MAX,
js_number(attempts)
))
})?;
let mut builder = self.raw_builder.lock();
builder.reconnect_max_attempts(attempts);
Ok(self)
}

/// Configures the opaque, machine-readable metadata string for this session.
/// Metadata is made available to you in the ngrok dashboard and the Agents API
/// resource. It is a useful way to allow you to uniquely identify sessions. We
Expand Down Expand Up @@ -527,6 +616,25 @@ impl ObjectFinalize for Session {
}
}

/// `n` as a u64 if it is a whole number from 0 to u64::MAX, else None.
fn whole_number(n: f64) -> Option<u64> {
// 2^64 itself is exactly representable, and the first value out of range.
(n.fract() == 0.0 && (0.0..18_446_744_073_709_551_616.0).contains(&n)).then_some(n as u64)
}

/// `n` for error messages: NaN and Infinity spelled as JavaScript spells them,
/// other values as Rust prints them, which differs from JavaScript for -0 and
/// for values JavaScript writes with an exponent.
fn js_number(n: f64) -> String {
if n.is_nan() {
"NaN".to_string()
} else if n.is_infinite() {
if n > 0.0 { "Infinity" } else { "-Infinity" }.to_string()
} else {
n.to_string()
}
}

/// Container for UpdateRequest information.
#[derive(Clone)]
#[napi]
Expand Down
Loading
Loading