Skip to content

Commit

Permalink
Merge pull request #2 from adaminglehart/configurable-max-connection-…
Browse files Browse the repository at this point in the history
…attempts

Make the maximum number of connection attempts configurable
  • Loading branch information
wei-rong-1 authored Oct 16, 2024
2 parents 231f656 + 4aa79f7 commit 981be00
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
1 change: 1 addition & 0 deletions addon.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,5 @@ export class VsockSocket {
startRecv(): void
writeText(data: string): void
writeBuffer(data: Buffer): void
setMaxConnectionAttempts(maxConnectionAttempts: number): void
}
4 changes: 4 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,10 @@ export class VsockSocket extends EventEmitter {
this.on('end', this.onEnd)
}

setMaxConnectionAttempts(maxConnectionAttempts: number) {
this.socket.setMaxConnectionAttempts(maxConnectionAttempts)
}

connect(cid: number, port: number, connectCallback?: Callback) {
this.checkDestroyed()
this.connecting = true
Expand Down
22 changes: 20 additions & 2 deletions src/socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const BUF_MAX_LEN: usize = 8192;
const BACKLOG: usize = 128;

// Maximum number of connection attempts
const MAX_CONNECTION_ATTEMPTS: usize = 5;
const MAX_CONNECTION_ATTEMPTS: u32 = 5;

#[derive(Eq, Ord, PartialEq, PartialOrd, Copy, Clone)]
enum State {
Expand All @@ -38,6 +38,7 @@ pub struct VsockSocket {
fd: RawFd,
emitter: Emitter,
state: State,
max_connection_attempts: u32,
}

#[napi]
Expand All @@ -59,6 +60,7 @@ impl VsockSocket {
fd,
emitter: Emitter::new(env, emit_fn)?,
state: State::Initialized,
max_connection_attempts: MAX_CONNECTION_ATTEMPTS,
})
}

Expand Down Expand Up @@ -101,6 +103,20 @@ impl VsockSocket {
Ok(())
}

#[napi]
pub fn set_max_connection_attempts(&mut self, max_connection_attempts: JsNumber) -> Result<()> {
let max_connection_attempts = max_connection_attempts.get_uint32()?;
if max_connection_attempts < 1 {
return Err(error(
"max_connection_attempts must be greater than 0".to_string(),
));
}

self.max_connection_attempts = max_connection_attempts;

Ok(())
}

#[napi]
pub fn connect(&mut self, cid: JsNumber, port: JsNumber) -> Result<()> {
let cid = cid.get_uint32()?;
Expand All @@ -110,9 +126,11 @@ impl VsockSocket {
let emit_error = self.thread_safe_emit_error()?;
let emit_connect = self.thread_safe_emit_connect()?;

let max_connection_attempts = self.max_connection_attempts;

thread::spawn(move || {
let mut err_msg: Option<String> = None;
for i in 0..MAX_CONNECTION_ATTEMPTS {
for i in 0..max_connection_attempts {
match connect(fd, &sockaddr) {
Ok(_) => {
emit_connect.call(Ok(()), ThreadsafeFunctionCallMode::Blocking);
Expand Down

0 comments on commit 981be00

Please sign in to comment.