Skip to content

Commit

Permalink
improve web kit to be more stable
Browse files Browse the repository at this point in the history
* when data is not available on nonblocking socket, retry it later
* disable SIGPIPE on web server's socket, this prevents svm crashing
  under high traffic load

fix #27
  • Loading branch information
Vincent Wang committed May 3, 2019
1 parent 268cb63 commit 4414b35
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
10 changes: 10 additions & 0 deletions src/kits/inet/native/std/inet_TcpServerSocket_std.c
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,16 @@ Cell inet_TcpServerSocket_accept(SedonaVM* vm, Cell* params)
return falseCell;
}

#ifdef SO_NOSIGPIPE
int val = 1;
if (setsockopt(acceptedSock, SOL_SOCKET, SO_NOSIGPIPE,
(void*)&val, sizeof(val)) != 0)
{
closesocket(acceptedSock);
return falseCell;
}
#endif

// mark as open
setSocket(accepted, acceptedSock);
setClosed(accepted, 0);
Expand Down
3 changes: 3 additions & 0 deletions src/kits/inet/native/std/inet_TcpSocket_std.c
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,9 @@ Cell inet_TcpSocket_write(SedonaVM* vm, Cell* params)
Cell result;

buf = buf + off;
//NOTE: MSG_NOSIGNAL is not defined under macOS(BSD like
// system?), should use `setsockopt` to set
// SO_NOSIGPIPE after socket is created
result.ival = send(sock, buf, len, MSG_NOSIGNAL);
if (result.ival >= 0) return result; // 0+ is ok
if (inet_errorIsWouldBlock()) return zeroCell;
Expand Down
12 changes: 9 additions & 3 deletions src/kits/web/Handler.sedona
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,16 @@ internal class Handler

// read request bytes
int read = socket.read(buf, pos, bufLen)
if (read <= 0)

if (read == 0) // no data available yet (nonblocking)
return true
else if (read < 0) // some error happened
{
res.writeStatus(HttpCode.badRequest).finishHeaders().close()
return true
if (socket.isClosed())
WebService.log.trace("socket has been closed, skip request handling")
else
res.writeStatus(HttpCode.badRequest).finishHeaders().close()
return false
}

// update read offset
Expand Down

0 comments on commit 4414b35

Please sign in to comment.