@ngrok/ngrok 0.0.6 → 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,38 @@
1
+ // run with: node --trace-gc --expose-gc
2
+ const SegfaultHandler = require('../node_modules/segfault-handler');
3
+ SegfaultHandler.registerHandler('crash.log');
4
+
5
+ const http = require('http');
6
+ http.createServer(
7
+ function(req,res){res.writeHead(200);
8
+ res.write('Hello');
9
+ res.end();
10
+ } ).listen(8081);
11
+
12
+ var ngrok = require('..');
13
+ // turn on debug
14
+ process.env.NGROK_LOG = 'ngrok_js=debug';
15
+ ngrok.tracingSubscriber();
16
+
17
+ new ngrok.NgrokSessionBuilder().authtokenFromEnv().connect().then((session) => {
18
+ session.httpEndpoint().listen().then((tunnel) => {
19
+ tunnel.forwardTcp('localhost:8081').await;
20
+ console.log("tunnel: " + tunnel.url() + " id: " + tunnel.id());
21
+ setTimeout(function () {
22
+ console.log('\n\n=====> running gc');
23
+ global.gc();
24
+ }, 2000);
25
+
26
+ setTimeout(function () {
27
+ console.log('\n\n=====> closing and nulling tunnel');
28
+ tunnel.close().await;
29
+ tunnel = null;
30
+ }, 4000);
31
+
32
+ setTimeout(function () {
33
+ console.log('\n\n=====> running gc');
34
+ global.gc();
35
+ }, 6000);
36
+
37
+ });
38
+ }).await;
@@ -0,0 +1,43 @@
1
+ // run with: node --trace-gc --expose-gc
2
+ const SegfaultHandler = require('segfault-handler');
3
+ SegfaultHandler.registerHandler('crash.log');
4
+
5
+ const http = require('http');
6
+ http.createServer(
7
+ function(req,res){res.writeHead(200);
8
+ res.write('Hello');
9
+ res.end();
10
+ } ).listen(8081);
11
+
12
+ var ngrok = require('/Users/bob/projects/ngrok-js/index.js');
13
+ // turn on debug
14
+ process.env.NGROK_LOG = 'ngrok_js=debug';
15
+ ngrok.tracingSubscriber();
16
+
17
+ new ngrok.NgrokSessionBuilder().authtokenFromEnv().connect().then((session) => {
18
+ session.httpEndpoint().listen().then((tunnel) => {
19
+ tunnel.forwardTcp('localhost:8081').await;
20
+ const tun_id = tunnel.id();
21
+ console.log("tunnel: " + tunnel.url() + " id: " + tun_id);
22
+ console.log('\n\n=====> nulling tunnel');
23
+ tunnel = null; // nodejs can gc
24
+
25
+ setTimeout(function () {
26
+ console.log('\n\n=====> running gc');
27
+ global.gc();
28
+ }, 2000);
29
+
30
+ setTimeout(function () {
31
+ console.log('\n\n=====> closing tunnel');
32
+ session.closeTunnel(tun_id).await;
33
+ }, 4000);
34
+
35
+ setTimeout(function () {
36
+ console.log('\n\n=====> nulling session, running gc');
37
+ session = null;
38
+ global.gc();
39
+ }, 6000);
40
+
41
+ });
42
+ }).await;
43
+
package/src/lib.rs CHANGED
@@ -1,6 +1,15 @@
1
+ use napi::{
2
+ Error,
3
+ Status,
4
+ };
5
+
1
6
  pub mod http;
2
7
  pub mod session;
3
8
  pub mod tcp;
4
9
  pub mod tls;
5
10
  pub mod tunnel;
6
11
  pub mod tunnel_builder;
12
+
13
+ pub(crate) fn napi_err(message: impl Into<String>) -> Error {
14
+ Error::new(Status::GenericFailure, message.into())
15
+ }
package/src/session.rs CHANGED
@@ -1,22 +1,41 @@
1
- use std::time::Duration;
1
+ use std::{
2
+ sync::Arc,
3
+ time::Duration,
4
+ };
2
5
 
3
- use napi::bindgen_prelude::*;
6
+ use napi::{
7
+ bindgen_prelude::*,
8
+ threadsafe_function::{
9
+ ErrorStrategy,
10
+ ThreadSafeCallContext,
11
+ ThreadsafeFunction,
12
+ ThreadsafeFunctionCallMode,
13
+ },
14
+ };
4
15
  use napi_derive::napi;
5
16
  use ngrok::{
6
- session::SessionBuilder,
17
+ session::{
18
+ SessionBuilder,
19
+ Update,
20
+ },
7
21
  Session,
8
22
  };
23
+ use tokio::sync::Mutex;
9
24
  use tracing::debug;
10
25
  use tracing_subscriber::{
11
26
  self,
12
27
  fmt::format::FmtSpan,
13
28
  };
14
29
 
15
- use crate::tunnel_builder::{
16
- NgrokHttpTunnelBuilder,
17
- NgrokLabeledTunnelBuilder,
18
- NgrokTcpTunnelBuilder,
19
- NgrokTlsTunnelBuilder,
30
+ use crate::{
31
+ napi_err,
32
+ tunnel::remove_global_tunnel,
33
+ tunnel_builder::{
34
+ NgrokHttpTunnelBuilder,
35
+ NgrokLabeledTunnelBuilder,
36
+ NgrokTcpTunnelBuilder,
37
+ NgrokTlsTunnelBuilder,
38
+ },
20
39
  };
21
40
 
22
41
  /// The builder for an ngrok session.
@@ -50,7 +69,15 @@ impl NgrokSessionBuilder {
50
69
  }
51
70
  }
52
71
 
53
- /// Authenticate the ngrok session with the given authtoken.
72
+ /// Configures the session to authenticate with the provided authtoken. You
73
+ /// can [find your existing authtoken] or [create a new one] in the ngrok
74
+ /// dashboard.
75
+ ///
76
+ /// See the [authtoken parameter in the ngrok docs] for additional details.
77
+ ///
78
+ /// [find your existing authtoken]: https://dashboard.ngrok.com/get-started/your-authtoken
79
+ /// [create a new one]: https://dashboard.ngrok.com/tunnels/authtokens
80
+ /// [authtoken parameter in the ngrok docs]: https://ngrok.com/docs/ngrok-agent/config#authtoken
54
81
  #[napi]
55
82
  pub fn authtoken(&mut self, authtoken: String) -> &Self {
56
83
  // can't put lifetimes or generics on napi structs, which limits our options.
@@ -61,17 +88,21 @@ impl NgrokSessionBuilder {
61
88
  self
62
89
  }
63
90
 
64
- /// Authenticate using the authtoken in the `NGROK_AUTHTOKEN` environment
65
- /// variable.
91
+ /// Shortcut for calling [SessionBuilder::authtoken] with the value of the
92
+ /// NGROK_AUTHTOKEN environment variable.
66
93
  #[napi]
67
94
  pub fn authtoken_from_env(&mut self) -> &Self {
68
95
  self.raw_builder = self.raw_builder.clone().authtoken_from_env();
69
96
  self
70
97
  }
71
98
 
72
- /// Set the heartbeat interval for the session.
73
- /// This value determines how often we send application level
74
- /// heartbeats to the server go check connection liveness.
99
+ /// Configures how often the session will send heartbeat messages to the ngrok
100
+ /// service to check session liveness.
101
+ ///
102
+ /// See the [heartbeat_interval parameter in the ngrok docs] for additional
103
+ /// details.
104
+ ///
105
+ /// [heartbeat_interval parameter in the ngrok docs]: https://ngrok.com/docs/ngrok-agent/config#heartbeat_interval
75
106
  #[napi]
76
107
  pub fn heartbeat_interval(&mut self, heartbeat_interval: u32) -> &Self {
77
108
  self.raw_builder = self
@@ -81,9 +112,13 @@ impl NgrokSessionBuilder {
81
112
  self
82
113
  }
83
114
 
84
- /// Set the heartbeat tolerance for the session.
85
- /// If the session's heartbeats are outside of their interval by this duration,
86
- /// the server will assume the session is dead and close it.
115
+ /// Configures the duration to wait for a response to a heartbeat before
116
+ /// assuming the session connection is dead and attempting to reconnect.
117
+ ///
118
+ /// See the [heartbeat_tolerance parameter in the ngrok docs] for additional
119
+ /// details.
120
+ ///
121
+ /// [heartbeat_tolerance parameter in the ngrok docs]: https://ngrok.com/docs/ngrok-agent/config#heartbeat_tolerance
87
122
  #[napi]
88
123
  pub fn heartbeat_tolerance(&mut self, heartbeat_tolerance: u32) -> &Self {
89
124
  self.raw_builder = self
@@ -93,24 +128,145 @@ impl NgrokSessionBuilder {
93
128
  self
94
129
  }
95
130
 
96
- /// Use the provided opaque metadata string for this session.
97
- /// Viewable from the ngrok dashboard or API.
131
+ /// Configures the opaque, machine-readable metadata string for this session.
132
+ /// Metadata is made available to you in the ngrok dashboard and the Agents API
133
+ /// resource. It is a useful way to allow you to uniquely identify sessions. We
134
+ /// suggest encoding the value in a structured format like JSON.
135
+ ///
136
+ /// See the [metdata parameter in the ngrok docs] for additional details.
137
+ ///
138
+ /// [metdata parameter in the ngrok docs]: https://ngrok.com/docs/ngrok-agent/config#metadata
98
139
  #[napi]
99
140
  pub fn metadata(&mut self, metadata: String) -> &Self {
100
141
  self.raw_builder = self.raw_builder.clone().metadata(metadata);
101
142
  self
102
143
  }
103
144
 
104
- /// Connect to the provided ngrok server address.
145
+ /// Configures the network address to dial to connect to the ngrok service.
146
+ /// Use this option only if you are connecting to a custom agent ingress.
147
+ ///
148
+ /// See the [server_addr parameter in the ngrok docs] for additional details.
149
+ ///
150
+ /// [server_addr parameter in the ngrok docs]: https://ngrok.com/docs/ngrok-agent/config#server_addr
105
151
  #[napi]
106
152
  pub fn server_addr(&mut self, addr: String) -> &Self {
107
153
  self.raw_builder = self.raw_builder.clone().server_addr(addr).clone();
108
154
  self
109
155
  }
110
156
 
157
+ /// Configures a function which is called when the ngrok service requests that
158
+ /// this [Session] stops. Your application may choose to interpret this callback
159
+ /// as a request to terminate the [Session] or the entire process.
160
+ ///
161
+ /// Errors returned by this function will be visible to the ngrok dashboard or
162
+ /// API as the response to the Stop operation.
163
+ ///
164
+ /// Do not block inside this callback. It will cause the Dashboard or API
165
+ /// stop operation to time out. Do not call [std::process::exit] inside this
166
+ /// callback, it will also cause the operation to time out.
167
+ #[napi(ts_args_type = "handler: () => void")]
168
+ pub fn handle_stop_command(&mut self, handler: JsFunction) -> &Self {
169
+ // create threadsafe function
170
+ let tsfn = create_no_io_tsfn(handler);
171
+ // register stop handler
172
+ self.raw_builder = self
173
+ .raw_builder
174
+ .clone()
175
+ .handle_stop_command(move |_req| {
176
+ let tsfn = tsfn.clone();
177
+ async move {
178
+ tsfn.clone()
179
+ .lock()
180
+ .await
181
+ .call((), ThreadsafeFunctionCallMode::NonBlocking);
182
+ Ok(())
183
+ }
184
+ })
185
+ .clone();
186
+ self
187
+ }
188
+
189
+ /// Configures a function which is called when the ngrok service requests
190
+ /// that this [Session] updates. Your application may choose to interpret
191
+ /// this callback as a request to restart the [Session] or the entire
192
+ /// process.
193
+ ///
194
+ /// Errors returned by this function will be visible to the ngrok dashboard or
195
+ /// API as the response to the Restart operation.
196
+ ///
197
+ /// Do not block inside this callback. It will cause the Dashboard or API
198
+ /// stop operation to time out. Do not call [std::process::exit] inside this
199
+ /// callback, it will also cause the operation to time out.
200
+ #[napi(ts_args_type = "handler: () => void")]
201
+ pub fn handle_restart_command(&mut self, handler: JsFunction) -> &Self {
202
+ // create threadsafe function
203
+ let tsfn = create_no_io_tsfn(handler);
204
+ // register restart handler
205
+ self.raw_builder = self
206
+ .raw_builder
207
+ .clone()
208
+ .handle_restart_command(move |_req| {
209
+ let tsfn = tsfn.clone();
210
+ async move {
211
+ tsfn.clone()
212
+ .lock()
213
+ .await
214
+ .call((), ThreadsafeFunctionCallMode::NonBlocking);
215
+ Ok(())
216
+ }
217
+ })
218
+ .clone();
219
+ self
220
+ }
221
+
222
+ /// Configures a function which is called when the ngrok service requests
223
+ /// that this [Session] updates. Your application may choose to interpret
224
+ /// this callback as a request to update its configuration, itself, or to
225
+ /// invoke some other application-specific behavior.
226
+ ///
227
+ /// Errors returned by this function will be visible to the ngrok dashboard or
228
+ /// API as the response to the Restart operation.
229
+ ///
230
+ /// Do not block inside this callback. It will cause the Dashboard or API
231
+ /// stop operation to time out. Do not call [std::process::exit] inside this
232
+ /// callback, it will also cause the operation to time out.
233
+ #[napi(ts_args_type = "handler: (update: UpdateRequest) => void")]
234
+ pub fn handle_update_command(&mut self, handler: JsFunction) -> &Self {
235
+ // create threadsafe function
236
+ let tsfn: Arc<Mutex<ThreadsafeFunction<UpdateRequest, ErrorStrategy::Fatal>>> =
237
+ Arc::new(Mutex::new(
238
+ handler
239
+ .create_threadsafe_function(0, |ctx: ThreadSafeCallContext<UpdateRequest>| {
240
+ Ok(vec![ctx.value])
241
+ })
242
+ .expect("Failed to create update callback function"),
243
+ ));
244
+ // register update handler
245
+ self.raw_builder = self
246
+ .raw_builder
247
+ .clone()
248
+ .handle_update_command(move |req: Update| {
249
+ let tsfn = tsfn.clone();
250
+ let update = UpdateRequest {
251
+ version: req.version,
252
+ permit_major_version: req.permit_major_version,
253
+ };
254
+
255
+ async move {
256
+ tsfn.clone()
257
+ .lock()
258
+ .await
259
+ .call(update, ThreadsafeFunctionCallMode::NonBlocking);
260
+ Ok(())
261
+ }
262
+ })
263
+ .clone();
264
+ self
265
+ }
266
+
111
267
  // Omitting these configurations:
112
268
  // tls_config(&mut self, config: rustls::ClientConfig)
113
- // with_connect_callback(&mut self, callback: ConnectCallback)
269
+ // connector(&mut self, connect: ConnectFn)
114
270
 
115
271
  /// Attempt to establish an ngrok session using the current configuration.
116
272
  #[napi]
@@ -119,12 +275,7 @@ impl NgrokSessionBuilder {
119
275
  .connect()
120
276
  .await
121
277
  .map(|s| NgrokSession { raw_session: s })
122
- .map_err(|e| {
123
- Error::new(
124
- Status::GenericFailure,
125
- format!("failed to connect session, {e:?}"),
126
- )
127
- })
278
+ .map_err(|e| napi_err(format!("failed to connect session, {e:?}")))
128
279
  }
129
280
  }
130
281
 
@@ -141,25 +292,41 @@ impl NgrokSession {
141
292
  /// Start building a tunnel backing an HTTP endpoint.
142
293
  #[napi]
143
294
  pub fn http_endpoint(&self) -> NgrokHttpTunnelBuilder {
144
- NgrokHttpTunnelBuilder::new(self.raw_session.http_endpoint())
295
+ NgrokHttpTunnelBuilder::new(self.raw_session.clone(), self.raw_session.http_endpoint())
145
296
  }
146
297
 
147
298
  /// Start building a tunnel backing a TCP endpoint.
148
299
  #[napi]
149
300
  pub fn tcp_endpoint(&self) -> NgrokTcpTunnelBuilder {
150
- NgrokTcpTunnelBuilder::new(self.raw_session.tcp_endpoint())
301
+ NgrokTcpTunnelBuilder::new(self.raw_session.clone(), self.raw_session.tcp_endpoint())
151
302
  }
152
303
 
153
304
  /// Start building a tunnel backing a TLS endpoint.
154
305
  #[napi]
155
306
  pub fn tls_endpoint(&self) -> NgrokTlsTunnelBuilder {
156
- NgrokTlsTunnelBuilder::new(self.raw_session.tls_endpoint())
307
+ NgrokTlsTunnelBuilder::new(self.raw_session.clone(), self.raw_session.tls_endpoint())
157
308
  }
158
309
 
159
310
  /// Start building a labeled tunnel.
160
311
  #[napi]
161
312
  pub fn labeled_tunnel(&self) -> NgrokLabeledTunnelBuilder {
162
- NgrokLabeledTunnelBuilder::new(self.raw_session.labeled_tunnel())
313
+ NgrokLabeledTunnelBuilder::new(self.raw_session.clone(), self.raw_session.labeled_tunnel())
314
+ }
315
+
316
+ #[napi]
317
+ pub async fn close_tunnel(&self, id: String) -> Result<()> {
318
+ // close tunnel
319
+ let res = self
320
+ .raw_session
321
+ .close_tunnel(id.clone())
322
+ .await
323
+ .map_err(|e| napi_err(format!("failed to close tunnel, {e:?}")));
324
+
325
+ if res.is_ok() {
326
+ // remove our reference to allow it to drop
327
+ remove_global_tunnel(&id).await;
328
+ }
329
+ res
163
330
  }
164
331
  }
165
332
 
@@ -169,3 +336,22 @@ impl ObjectFinalize for NgrokSession {
169
336
  Ok(())
170
337
  }
171
338
  }
339
+
340
+ #[derive(Clone)]
341
+ #[napi]
342
+ pub struct UpdateRequest {
343
+ /// The version that the agent is requested to update to.
344
+ pub version: String,
345
+ /// Whether or not updating to the same major version is sufficient.
346
+ pub permit_major_version: bool,
347
+ }
348
+
349
+ pub(crate) fn create_no_io_tsfn(
350
+ js_function: JsFunction,
351
+ ) -> Arc<Mutex<ThreadsafeFunction<(), ErrorStrategy::Fatal>>> {
352
+ Arc::new(Mutex::new(
353
+ js_function
354
+ .create_threadsafe_function(0, |_ctx: ThreadSafeCallContext<()>| Ok(vec![()]))
355
+ .expect("Failed to create callback function"),
356
+ ))
357
+ }
package/src/tls.rs CHANGED
@@ -24,21 +24,11 @@ impl NgrokTlsTunnelBuilder {
24
24
  }
25
25
  /// The key to use for TLS termination at the ngrok edge in PEM format.
26
26
  #[napi]
27
- pub fn key_pem(&mut self, key_pem: Uint8Array) -> &Self {
28
- self.tunnel_builder = self
29
- .tunnel_builder
30
- .clone()
31
- .key_pem(Bytes::from(key_pem.to_vec()));
32
- self
33
- }
34
- /// The certificate to use for TLS termination at the ngrok edge in PEM
35
- /// format.
36
- #[napi]
37
- pub fn cert_pem(&mut self, cert_pem: Uint8Array) -> &Self {
38
- self.tunnel_builder = self
39
- .tunnel_builder
40
- .clone()
41
- .cert_pem(Bytes::from(cert_pem.to_vec()));
27
+ pub fn termination(&mut self, cert_pem: Uint8Array, key_pem: Uint8Array) -> &Self {
28
+ self.tunnel_builder = self.tunnel_builder.clone().termination(
29
+ Bytes::from(cert_pem.to_vec()),
30
+ Bytes::from(key_pem.to_vec()),
31
+ );
42
32
  self
43
33
  }
44
34
  }
package/src/tunnel.rs CHANGED
@@ -3,6 +3,7 @@ use std::{
3
3
  sync::Arc,
4
4
  };
5
5
 
6
+ use lazy_static::lazy_static;
6
7
  use napi::bindgen_prelude::*;
7
8
  use napi_derive::napi;
8
9
  use ngrok::{
@@ -15,13 +16,24 @@ use ngrok::{
15
16
  TlsTunnel,
16
17
  UrlTunnel,
17
18
  },
19
+ Session,
18
20
  };
19
21
  use tokio::sync::Mutex;
20
22
  use tracing::debug;
21
23
 
24
+ use crate::napi_err;
25
+
26
+ lazy_static! {
27
+ // tunnel references to be kept until explicit close to prevent nodejs gc from dropping them.
28
+ // the tunnel wrapper object, and the underlying tunnel, both have references to the Session
29
+ // so the Session is safe from premature dropping.
30
+ static ref GLOBAL_TUNNELS: Mutex<HashMap<String,Arc<Mutex<dyn Tunnel>>>> = Mutex::new(HashMap::new());
31
+ }
32
+
22
33
  macro_rules! make_tunnel_type {
23
34
  // the common (non-labeled) branch
24
35
  ($(#[$outer:meta])* $wrapper:ident, $tunnel:tt, common) => {
36
+
25
37
  $(#[$outer])*
26
38
  #[napi(custom_finalize)]
27
39
  #[allow(dead_code)]
@@ -29,18 +41,26 @@ macro_rules! make_tunnel_type {
29
41
  id: String,
30
42
  url: String,
31
43
  proto: String,
32
- inner: Arc<Mutex<$tunnel>>,
44
+ session: Session,
45
+ inner: Option<Arc<Mutex<$tunnel>>>,
33
46
  }
34
47
 
35
48
  #[napi]
36
49
  #[allow(dead_code)]
37
50
  impl $wrapper {
38
- pub(crate) fn new(raw_tunnel: $tunnel) -> Self {
51
+ pub(crate) async fn new(session: Session, raw_tunnel: $tunnel) -> Self {
52
+ let id = raw_tunnel.id().to_string();
53
+ let url = raw_tunnel.url().to_string();
54
+ let proto = raw_tunnel.proto().to_string();
55
+ let arc = Arc::new(Mutex::new(raw_tunnel));
56
+ // keep a tunnel reference until an explicit call to close to prevent nodejs gc dropping it
57
+ GLOBAL_TUNNELS.lock().await.insert(id.clone(), arc.clone());
39
58
  $wrapper {
40
- id: raw_tunnel.id().to_string(),
41
- url: raw_tunnel.url().to_string(),
42
- proto: raw_tunnel.proto().to_string(),
43
- inner: Arc::new(Mutex::new(raw_tunnel)),
59
+ id,
60
+ url,
61
+ proto,
62
+ session,
63
+ inner: Some(arc),
44
64
  }
45
65
  }
46
66
 
@@ -68,17 +88,24 @@ macro_rules! make_tunnel_type {
68
88
  pub(crate) struct $wrapper {
69
89
  id: String,
70
90
  labels: HashMap<String,String>,
71
- inner: Arc<Mutex<$tunnel>>,
91
+ session: Session,
92
+ inner: Option<Arc<Mutex<$tunnel>>>,
72
93
  }
73
94
 
74
95
  #[napi]
75
96
  #[allow(dead_code)]
76
97
  impl $wrapper {
77
- pub(crate) fn new(raw_tunnel: $tunnel) -> Self {
98
+ pub(crate) async fn new(session: Session, raw_tunnel: $tunnel) -> Self {
99
+ let id = raw_tunnel.id().to_string();
100
+ let labels = raw_tunnel.labels().clone();
101
+ let arc = Arc::new(Mutex::new(raw_tunnel));
102
+ // keep a tunnel reference until an explicit call to close to prevent nodejs gc dropping it
103
+ GLOBAL_TUNNELS.lock().await.insert(id.clone(), arc.clone());
78
104
  $wrapper {
79
- id: raw_tunnel.id().to_string(),
80
- labels: raw_tunnel.labels().clone(),
81
- inner: Arc::new(Mutex::new(raw_tunnel)),
105
+ id,
106
+ labels,
107
+ session,
108
+ inner: Some(arc),
82
109
  }
83
110
  }
84
111
 
@@ -106,12 +133,18 @@ macro_rules! make_tunnel_type {
106
133
  /// Forward incoming tunnel connections to the provided TCP address.
107
134
  #[napi]
108
135
  pub async fn forward_tcp(&self, addr: String) -> Result<()> {
109
- self.inner
136
+ // we must clone the Arc before locking so we have a local reference
137
+ // to the mutex to unlock if this struct is dropped.
138
+ let res = self.inner.as_ref()
139
+ .ok_or(napi_err("Tunnel is no longer running"))?
140
+ .clone() // required clone
110
141
  .lock()
111
142
  .await
112
143
  .forward_tcp(addr)
113
144
  .await
114
- .map_err(|e| Error::new(Status::GenericFailure, format!("cannot forward tcp: {e:?}")))
145
+ .map_err(|e| napi_err(format!("cannot forward tcp: {e:?}")));
146
+ debug!("forward_tcp returning");
147
+ res
115
148
  }
116
149
 
117
150
  /// Forward incoming tunnel connections to the provided Unix socket path.
@@ -119,23 +152,54 @@ macro_rules! make_tunnel_type {
119
152
  pub async fn forward_unix(&self, addr: String) -> Result<()> {
120
153
  #[cfg(not(target_os = "windows"))]
121
154
  {
122
- self.inner
155
+ // we must clone the Arc before locking so we have a local reference
156
+ // to the mutex to unlock if this struct is dropped.
157
+ let res = self.inner.as_ref()
158
+ .ok_or(napi_err("Tunnel is no longer running"))?
159
+ .clone() // required clone
123
160
  .lock()
124
161
  .await
125
162
  .forward_unix(addr)
126
163
  .await
127
- .map_err(|e| Error::new(Status::GenericFailure, format!("cannot forward unix: {e:?}")))
164
+ .map_err(|e| napi_err(format!("cannot forward unix: {e:?}")));
165
+ debug!("forward_unix returning");
166
+ res
128
167
  }
129
168
  #[cfg(target_os = "windows")] {
130
- Err(Error::new(Status::GenericFailure, format!("forward_unix not supported on windows")))
169
+ Err(napi_err(format!("forward_unix not supported on windows")))
131
170
  }
132
171
  }
172
+
173
+ /// Close the tunnel.
174
+ #[napi]
175
+ pub async fn close(&self) -> Result<()> {
176
+ debug!("{} closing, id: {}", stringify!($wrapper), self.id);
177
+ // drop our internal reference to the tunnel, giving drop control of the tunnel back to the nodejs.
178
+ GLOBAL_TUNNELS.lock().await.remove(&self.id);
179
+
180
+ // we may not be able to lock our reference to the tunnel due to the forward_* calls which
181
+ // continuously accept-loop while the tunnel is active, so calling close on the Session.
182
+ self.session.close_tunnel(self.id.clone())
183
+ .await
184
+ .map_err(|e| napi_err(format!("error closing tunnel: {e:?}")))
185
+ }
133
186
  }
134
187
 
135
188
  impl ObjectFinalize for $wrapper {
136
- fn finalize(self, mut _env: Env) -> Result<()> {
137
- debug!("$wrapper finalize");
138
- Ok(())
189
+ fn finalize(mut self, env: Env) -> Result<()> {
190
+ debug!("{} finalize, id: {}", stringify!($wrapper), self.id);
191
+ // take control of inner Tunnel, removing the reference from this evaporating object
192
+ let inner = self.inner.take();
193
+
194
+ // send inner Tunnel into a tokio spawn to be dropped, as dropping spawns a tokio task but
195
+ // there is no tokio context here.
196
+ env.spawn_future(
197
+ async move {
198
+ debug!("{} dropping tunnel reference, id: {}", stringify!($wrapper), self.id);
199
+ drop(inner);
200
+ Ok(())
201
+ })
202
+ .map(|_| ())
139
203
  }
140
204
  }
141
205
  };
@@ -157,3 +221,8 @@ make_tunnel_type! {
157
221
  /// A labeled ngrok tunnel.
158
222
  NgrokLabeledTunnel, LabeledTunnel, label
159
223
  }
224
+
225
+ /// Delete any reference to the tunnel id
226
+ pub(crate) async fn remove_global_tunnel(id: &String) {
227
+ GLOBAL_TUNNELS.lock().await.remove(id);
228
+ }