Reduce compiler warnings when using new chronos (#149)

* Reduce compiler warnings when using new chronos

* chronos req

* Reduce more warnings
This commit is contained in:
andri lim 2024-01-22 19:08:17 +07:00 committed by GitHub
parent f8ed9b40a5
commit 282773af69
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
16 changed files with 112 additions and 76 deletions

View File

@ -95,7 +95,7 @@ proc base64Factory*(padding: bool): ExtFactory =
proc factory(isServer: bool,
args: seq[ExtParam]): Result[Ext, string] {.
gcsafe, raises: [Defect].} =
gcsafe, raises: [].} =
# you can capture configuration variables via closure
# if you want

View File

@ -83,7 +83,7 @@ proc hexFactory*(): ExtFactory =
proc factory(isServer: bool,
args: seq[ExtParam]): Result[Ext, string] {.
gcsafe, raises: [Defect].} =
gcsafe, raises: [].} =
# you can capture configuration variables via closure
# if you want

View File

@ -19,13 +19,15 @@ import pkg/[
import ../websock/websock
import ./keys
{.push gcsafe, raises: [].}
const WSPath* = when defined secure: "/wss" else: "/ws"
proc rndStr*(size: int): string =
proc rndStr*(size: int): string {.gcsafe, raises: [].} =
for _ in 0..<size:
add(result, char(rand(int('A') .. int('z'))))
proc rndBin*(size: int): seq[byte] =
proc rndBin*(size: int): seq[byte] {.gcsafe, raises: [].} =
for _ in 0..<size:
add(result, byte(rand(0 .. 255)))
@ -45,7 +47,7 @@ proc createServer*(
tlsFlags: set[TLSFlags] = {},
tlsMinVersion = TLSVersion.TLS12,
tlsMaxVersion = TLSVersion.TLS12): HttpServer
{.raises: [Defect, HttpError].} =
{.raises: [].} =
try:
let server = when defined secure:
TlsHttpServer.create(
@ -62,7 +64,7 @@ proc createServer*(
flags = flags)
when defined accepts:
proc accepts() {.async, raises: [Defect].} =
proc accepts() {.async, raises: [].} =
try:
let req = await server.accept()
await req.handler()

View File

@ -8,7 +8,6 @@
## those terms.
import
pkg/stew/byteutils,
pkg/chronos/unittest2/asynctests
include ../websock/frame
@ -17,7 +16,7 @@ include ../websock/frame
suite "Test data frames":
setup:
var maskKey: array[4, char]
var maskKey {.used.} : array[4, char]
asyncTest "# 7bit length text":
check (await Frame(
@ -254,7 +253,7 @@ suite "Test data frames":
suite "Test control frames":
setup:
var maskKey: array[4, char]
var maskKey {.used.} : array[4, char]
asyncTest "Close":
check (await Frame(

View File

@ -25,30 +25,30 @@ type
request: HttpRequest
proc clientAppendGoodToken(ctx: Hook, headers: var HttpTable):
Result[void, string] {.gcsafe, raises: [Defect].} =
Result[void, string] {.gcsafe, raises: [].} =
headers.add("auth-token", "good-token")
return ok()
proc clientAppendBadToken(ctx: Hook, headers: var HttpTable):
Result[void, string] {.gcsafe, raises: [Defect].} =
Result[void, string] {.gcsafe, raises: [].} =
headers.add("auth-token", "bad-token")
return ok()
proc clientVerify(ctx: Hook, headers: HttpTable):
Future[Result[void, string]] {.async, gcsafe, raises: [Defect].} =
Future[Result[void, string]] {.gcsafe, async: (raises: []).} =
var p = TokenHook(ctx)
p.token = headers.getString("auth-status")
return ok()
proc serverVerify(ctx: Hook, headers: HttpTable):
Future[Result[void, string]] {.async, gcsafe, raises: [Defect].} =
Future[Result[void, string]] {.gcsafe, async: (raises: []).} =
var p = TokenHook(ctx)
if headers.getString("auth-token") == "good-token":
p.status = 101
return ok()
proc serverAppend(ctx: Hook, headers: var HttpTable):
Result[void, string] {.gcsafe, raises: [Defect].} =
Result[void, string] {.gcsafe, raises: [].} =
var p = TokenHook(ctx)
if p.status == 101:
headers.add("auth-status", "accept")
@ -76,14 +76,17 @@ proc serverHook(): Hook =
)
proc serverVerifyWithCode(ctx: Hook, headers: HttpTable):
Future[Result[void, string]] {.async, gcsafe, raises: [Defect].} =
var p = TokenHook(ctx)
if headers.getString("auth-token") == "good-token":
p.status = 101
return ok()
else:
await p.request.stream.writer.sendError(Http401)
return err("authentication error")
Future[Result[void, string]] {.gcsafe, async: (raises: []).} =
try:
var p = TokenHook(ctx)
if headers.getString("auth-token") == "good-token":
p.status = 101
return ok()
else:
await p.request.stream.writer.sendError(Http401)
return err("authentication error")
except CatchableError as exc:
return err(exc.msg)
proc serverHookWithCode(request: HttpRequest): Hook =
TokenHook(
@ -96,8 +99,8 @@ suite "Test Hooks":
setup:
var
server: HttpServer
goodCP = goodClientHook()
badCP = badClientHook()
goodCP {.used.} = goodClientHook()
badCP {.used.} = badClientHook()
teardown:
if server != nil:
@ -109,7 +112,7 @@ suite "Test Hooks":
check request.uri.path == WSPath
let
server = WSServer.new()
ws = await server.handleRequest(
discard await server.handleRequest(
request,
hooks = @[serverHook()]
)
@ -133,7 +136,7 @@ suite "Test Hooks":
check request.uri.path == WSPath
let
server = WSServer.new()
ws = await server.handleRequest(
discard await server.handleRequest(
request,
hooks = @[serverHook()]
)
@ -157,7 +160,7 @@ suite "Test Hooks":
check request.uri.path == WSPath
let
server = WSServer.new()
ws = await server.handleRequest(
discard await server.handleRequest(
request,
hooks = @[serverHookWithCode(request)]
)
@ -181,7 +184,7 @@ suite "Test Hooks":
check request.uri.path == WSPath
let
server = WSServer.new()
ws = await server.handleRequest(
discard await server.handleRequest(
request,
hooks = @[serverHookWithCode(request)]
)

View File

@ -124,7 +124,7 @@ suite "UTF-8 validator in action":
check request.uri.path == "/ws"
proc onClose(status: StatusCodes, reason: string):
CloseResult {.gcsafe, raises: [Defect].} =
CloseResult {.gcsafe, raises: [].} =
try:
check status == StatusFulfilled
check reason == closeReason
@ -182,6 +182,7 @@ suite "UTF-8 validator in action":
expect WSInvalidUTF8:
let data = await session.recvMsg()
discard data
asyncTest "invalid UTF-8 sequence close code":
let closeReason = "i want to close\xc0\xaf"
@ -207,3 +208,4 @@ suite "UTF-8 validator in action":
expect WSInvalidUTF8:
let data = await session.recvMsg()
discard data

View File

@ -70,6 +70,7 @@ suite "Test handshake":
let session = await connectClient(
address = initTAddress("127.0.0.1:8888"),
version = 14)
discard session
asyncTest "Test for client headers":
proc handle(request: HttpRequest) {.async.} =
@ -457,8 +458,8 @@ suite "Test framing":
var futs: seq[Future[void]]
for i in 0 ..< numMessages:
futs.add session.send(testData, Opcode.Binary)
futs[0].cancel() # expected to complete as it already started sending
futs[^2].cancel() # expected to be canceled as it has not started yet
futs[0].cancelSoon() # expected to complete as it already started sending
futs[^2].cancelSoon() # expected to be canceled as it has not started yet
await allFutures(futs)
await session.close()
@ -531,7 +532,7 @@ suite "Test Closing":
check request.uri.path == WSPath
proc closeServer(status: StatusCodes, reason: string): CloseResult{.gcsafe,
raises: [Defect].} =
raises: [].} =
try:
check status == StatusTooLarge
check reason == "Message too big!"
@ -554,7 +555,7 @@ suite "Test Closing":
flags = {ReuseAddr})
proc clientClose(status: StatusCodes, reason: string): CloseResult {.gcsafe,
raises: [Defect].} =
raises: [].} =
try:
check status == StatusFulfilled
return (StatusTooLarge, "Message too big!")
@ -587,7 +588,7 @@ suite "Test Closing":
proc handle(request: HttpRequest) {.async.} =
check request.uri.path == WSPath
proc closeServer(status: StatusCodes, reason: string): CloseResult{.gcsafe,
raises: [Defect].} =
raises: [].} =
try:
check status == StatusFulfilled
return (StatusTooLarge, "Message too big!")
@ -608,7 +609,7 @@ suite "Test Closing":
flags = {ReuseAddr})
proc clientClose(status: StatusCodes, reason: string): CloseResult {.gcsafe,
raises: [Defect].} =
raises: [].} =
try:
check status == StatusTooLarge
check reason == "Message too big!"
@ -654,7 +655,7 @@ suite "Test Closing":
flags = {ReuseAddr})
proc closeClient(status: StatusCodes, reason: string): CloseResult
{.gcsafe, raises: [Defect].} =
{.gcsafe, raises: [].} =
try:
check status == StatusCodes(StatusLibsCodes.high)
return (StatusCodes(StatusLibsCodes.high), "Reserved StatusCodes")
@ -671,7 +672,7 @@ suite "Test Closing":
proc handle(request: HttpRequest) {.async.} =
check request.uri.path == WSPath
proc closeServer(status: StatusCodes, reason: string): CloseResult{.gcsafe,
raises: [Defect].} =
raises: [].} =
try:
check status == StatusCodes(3999)
return (StatusCodes(3999), "Reserved StatusCodes")
@ -733,7 +734,7 @@ suite "Test Closing":
suite "Test Payload":
setup:
let rng = HmacDrbgContext.new()
let rng {.used.} = HmacDrbgContext.new()
var
server: HttpServer
@ -812,7 +813,6 @@ suite "Test Payload":
await session.close()
asyncTest "Send two fragments":
var ping, pong = false
let testString = "1234567890"
let msg = toBytes(testString)
let maxFrameSize = 5
@ -1026,7 +1026,9 @@ suite "Test Binary message with Payload":
asyncTest "Send binary data with small text payload":
let testData = rndBin(10)
trace "testData", testData = testData
var ping, pong = false
var
ping = false
pong = false
proc handle(request: HttpRequest) {.async.} =
check request.uri.path == WSPath

View File

@ -15,7 +15,7 @@ license = "MIT"
skipDirs = @["examples", "tests"]
requires "nim >= 1.6.0"
requires "chronos >= 3.0.0"
requires "chronos#head"
requires "httputils >= 0.2.0"
requires "chronicles >= 0.10.2"
requires "stew >= 0.1.0"

View File

@ -140,6 +140,7 @@ proc createParams(args: seq[ExtParam],
ok(resp)
{.warning[HoleEnumConv]:off.}
proc getWindowBits(opts: DeflateOpts, isServer: bool): ZWindowBits =
if isServer:
if opts.serverMaxWindowBits == 0:
@ -152,6 +153,8 @@ proc getWindowBits(opts: DeflateOpts, isServer: bool): ZWindowBits =
else:
ZWindowBits(-opts.clientMaxWindowBits)
{.warning[HoleEnumConv]:on.}
proc getContextTakeover(opts: DeflateOpts, isServer: bool): bool =
if isServer:
opts.serverNoContextTakeOver
@ -369,7 +372,7 @@ proc deflateFactory*(
proc factory(isServer: bool,
args: seq[ExtParam]): Result[Ext, string] {.
gcsafe, raises: [Defect].} =
gcsafe, raises: [].} =
# capture user configuration via closure
var opts = DeflateOpts(

View File

@ -7,7 +7,7 @@
## This file may not be copied, modified, or distributed except according to
## those terms.
{.push raises: [Defect].}
{.push gcsafe, raises: [].}
import pkg/[
chronos,

View File

@ -7,7 +7,7 @@
## This file may not be copied, modified, or distributed except according to
## those terms.
{.push raises: [Defect].}
{.push gcsafe, raises: [].}
import std/[uri, strutils]
import pkg/[
@ -170,13 +170,17 @@ proc connect*(
tlsMinVersion = TLSVersion.TLS12,
tlsMaxVersion = TLSVersion.TLS12,
hostName = ""): Future[T]
{.async, raises: [Defect, HttpError].} =
{.async: (raises: [CatchableError, HttpError]).} =
let wantedHostName = if hostName.len > 0:
hostName
else:
host.split(":")[0]
template used(x: typed) =
# silence unused warning
discard
let addrs = resolveTAddress(host)
for a in addrs:
try:
@ -190,6 +194,7 @@ proc connect*(
return conn
except TransportError as exc:
used(exc)
trace "Error connecting to address", address = $a, exc = exc.msg
raise newException(HttpError,

View File

@ -7,7 +7,7 @@
## This file may not be copied, modified, or distributed except according to
## those terms.
{.push raises: [Defect].}
{.push gcsafe, raises: [].}
import std/[uri]
import pkg/[

View File

@ -7,7 +7,7 @@
## This file may not be copied, modified, or distributed except according to
## those terms.
{.push raises: [Defect].}
{.push gcsafe, raises: [].}
import std/uri
import pkg/[
@ -43,6 +43,10 @@ type
TlsHttpServer* = HttpServer
template used(x: typed) =
# silence unused warning
discard
proc validateRequest(
stream: AsyncStreamWriter,
header: HttpRequestHeader): Future[ReqStatus] {.async.} =
@ -69,7 +73,7 @@ proc parseRequest(
##
var buffer = newSeq[byte](MaxHttpHeadersSize)
let remoteAddr = stream.reader.tsource.remoteAddress()
let remoteAddr {.used.} = stream.reader.tsource.remoteAddress()
trace "Received connection", address = $remoteAddr
try:
let hlenfut = stream.reader.readUntil(
@ -115,11 +119,12 @@ proc parseRequest(
# remote peer disconnected
trace "Remote peer disconnected", address = $remoteAddr
except TransportOsError as exc:
used(exc)
trace "Problems with networking", address = $remoteAddr, error = exc.msg
proc handleConnCb(
server: StreamServer,
transp: StreamTransport) {.async.} =
transp: StreamTransport) {.async: (raises: []).} =
var stream: AsyncStream
try:
stream = AsyncStream(
@ -131,10 +136,15 @@ proc handleConnCb(
await httpServer.handler(request)
except CatchableError as exc:
used(exc)
debug "Exception in HttpHandler", exc = exc.msg
finally:
await stream.closeWait()
try:
await stream.closeWait()
except CatchableError as exc:
used(exc)
debug "Exception in HttpHandler closewait", exc = exc.msg
proc handleTlsConnCb(
server: StreamServer,
transp: StreamTransport) {.async.} =
@ -158,6 +168,7 @@ proc handleTlsConnCb(
await httpServer.handler(request)
except CatchableError as exc:
used(exc)
debug "Exception in HttpHandler", exc = exc.msg
finally:
await stream.closeWait()
@ -208,7 +219,7 @@ proc create*(
headersTimeout = HttpHeadersTimeout,
handshakeTimeout = 0.seconds
): HttpServer
{.raises: [Defect, CatchableError].} = # TODO: remove CatchableError
{.raises: [CatchableError].} = # TODO: remove CatchableError
## Make a new HTTP Server
##

View File

@ -7,7 +7,7 @@
## This file may not be copied, modified, or distributed except according to
## those terms.
{.push raises: [Defect].}
{.push gcsafe, raises: [].}
import std/strformat
import pkg/[chronos, chronicles, stew/byteutils, stew/endians2]
@ -18,6 +18,10 @@ import pkg/chronos/streams/asyncstream
logScope:
topics = "websock ws-session"
template used(x: typed) =
# silence unused warning
discard
proc prepareCloseBody(code: StatusCodes, reason: string): seq[byte] =
result = reason.toBytes
if ord(code) > 999:
@ -178,8 +182,7 @@ proc send*(
proc send*(
ws: WSSession,
data: string): Future[void]
{.raises: [Defect, WSClosedError].} =
data: string): Future[void] =
send(ws, data.toBytes(), Opcode.Text)
proc handleClose*(
@ -214,7 +217,7 @@ proc handleClose*(
else:
try:
code = StatusCodes(uint16.fromBytesBE(payload[0..<2]))
except RangeError:
except RangeDefect:
raise newException(WSInvalidCloseCodeError,
"Status code out of range!")
@ -241,6 +244,7 @@ proc handleClose*(
try:
(code, reason) = ws.onClose(code, reason)
except CatchableError as exc:
used(exc)
trace "Exception in Close callback, this is most likely a bug", exc = exc.msg
else:
code = StatusFulfilled
@ -253,6 +257,7 @@ proc handleClose*(
try:
await ws.send(prepareCloseBody(code, reason), Opcode.Close).wait(5.seconds)
except CatchableError as exc:
used(exc)
trace "Failed to send Close opcode", err=exc.msg
ws.readyState = ReadyState.Closed
@ -303,6 +308,7 @@ proc handleControl*(ws: WSSession, frame: Frame) {.async.} =
try:
ws.onPing(payload)
except CatchableError as exc:
used(exc)
trace "Exception in Ping callback, this is most likely a bug", exc = exc.msg
# send pong to remote
@ -312,12 +318,15 @@ proc handleControl*(ws: WSSession, frame: Frame) {.async.} =
try:
ws.onPong(payload)
except CatchableError as exc:
used(exc)
trace "Exception in Pong callback, this is most likely a bug", exc = exc.msg
of Opcode.Close:
await ws.handleClose(frame, payload)
else:
raise newException(WSInvalidOpcodeError, "Invalid control opcode!")
{.warning[HoleEnumConv]:off.}
proc readFrame*(ws: WSSession, extensions: seq[Ext] = @[]): Future[Frame] {.async.} =
## Gets a frame from the WebSocket.
## See https://tools.ietf.org/html/rfc6455#section-5.2
@ -342,10 +351,11 @@ proc readFrame*(ws: WSSession, extensions: seq[Ext] = @[]): Future[Frame] {.asyn
return frame
{.warning[HoleEnumConv]:on.}
proc ping*(
ws: WSSession,
data: seq[byte] = @[]): Future[void]
{.raises: [Defect, WSClosedError].} =
data: seq[byte] = @[]): Future[void] =
ws.send(data, opcode = Opcode.Ping)
proc recv*(
@ -462,7 +472,7 @@ proc recvMsg*(
var res: seq[byte]
while ws.readyState != ReadyState.Closed:
var buf = new(seq[byte])
let read = await ws.recv(buf, min(size, ws.frameSize))
let read {.used.} = await ws.recv(buf, min(size, ws.frameSize))
if res.len + buf[].len > size:
raise newException(WSMaxMessageSizeError, "Max message size exceeded")
@ -522,7 +532,7 @@ proc close*(
except CancelledError as exc:
raise exc
except CatchableError as exc:
discard # most likely EOF
discard exc # most likely EOF
try:
ws.readyState = ReadyState.Closing
await gentleCloser(ws, prepareCloseBody(code, reason)).wait(10.seconds)
@ -530,6 +540,7 @@ proc close*(
trace "Cancellation when closing!", exc = exc.msg
raise exc
except CatchableError as exc:
used(exc)
trace "Exception closing", exc = exc.msg
finally:
await ws.stream.closeWait()

View File

@ -7,7 +7,7 @@
## This file may not be copied, modified, or distributed except according to
## those terms.
{.push raises: [Defect].}
{.push gcsafe, raises: [].}
import std/deques
import pkg/[chronos,
@ -73,14 +73,14 @@ type
StatusCodes* = distinct range[0..4999]
ControlCb* = proc(data: openArray[byte] = [])
{.gcsafe, raises: [Defect].}
{.gcsafe, raises: [].}
CloseResult* = tuple
code: StatusCodes
reason: string
CloseCb* = proc(code: StatusCodes, reason: string):
CloseResult {.gcsafe, raises: [Defect].}
CloseResult {.gcsafe, raises: [].}
WebSocket* = ref object of RootObj
extensions*: seq[Ext]
@ -122,7 +122,7 @@ type
ExtFactoryProc* = proc(
isServer: bool,
args: seq[ExtParam]): Result[Ext, string]
{.gcsafe, raises: [Defect].}
{.gcsafe, raises: [].}
ExtFactory* = object
name*: string
@ -144,10 +144,10 @@ type
Hook* = ref object of RootObj
append*: proc(ctx: Hook,
headers: var HttpTable): Result[void, string]
{.gcsafe, raises: [Defect].}
{.gcsafe, raises: [].}
verify*: proc(ctx: Hook,
headers: HttpTable): Future[Result[void, string]]
{.closure, gcsafe, raises: [Defect].}
{.gcsafe, async: (raises: []).}
WebSocketError* = object of CatchableError
WSMalformedHeaderError* = object of WebSocketError

View File

@ -7,7 +7,7 @@
## This file may not be copied, modified, or distributed except according to
## those terms.
{.push raises: [Defect].}
{.push gcsafe, raises: [].}
import std/[tables,
strutils,
@ -38,9 +38,6 @@ type
protocols: seq[string]
factories: seq[ExtFactory]
func toException(e: string): ref WebSocketError =
(ref WebSocketError)(msg: e)
func toException(e: cstring): ref WebSocketError =
(ref WebSocketError)(msg: $e)
@ -57,7 +54,7 @@ proc getFactory(factories: openArray[ExtFactory], extName: string): ExtFactoryPr
proc selectExt(isServer: bool,
extensions: var seq[Ext],
factories: openArray[ExtFactory],
exts: openArray[string]): string {.raises: [Defect, WSExtError].} =
exts: openArray[string]): string {.raises: [WSExtError].} =
var extList: seq[AppExt]
var response = ""
@ -216,7 +213,7 @@ proc connect*(
onPong: ControlCb = nil,
onClose: CloseCb = nil,
rng = HmacDrbgContext.new()): Future[WSSession]
{.raises: [Defect, WSWrongUriSchemeError].} =
{.raises: [WSWrongUriSchemeError].} =
## Create a new websockets client
## using a Uri
##
@ -254,11 +251,12 @@ proc handleRequest*(
version: uint = WSDefaultVersion,
hooks: seq[Hook] = @[]): Future[WSSession]
{.
async,
raises: [
Defect,
async:
(raises: [
CancelledError,
CatchableError,
WSHandshakeError,
WSProtoMismatchError]
WSProtoMismatchError])
.} =
## Creates a new socket from a request.
##