-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathhttpleast.nim
217 lines (188 loc) · 5.85 KB
/
httpleast.nim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import std/strutils
import pkg/cps
import httpleast/eventqueue
when leastQueue == "nim-sys":
import std/[posix, os]
import sys/[sockets, handles]
type
Client = AsyncConn[TCP]
ClientAddr = IPEndpoint
else:
import std/nativesockets
import std/net
import std/os
import std/posix
type
Client = SocketHandle
ClientAddr = string
const
leastPort {.intdefine.} = 8080
leastAddress {.strdefine.} = "localhost"
leastKeepAlive {.booldefine.} = true
leastDelay {.intdefine.} = 0
when leastQueue != "nim-sys":
template errorHandler(e: OSErrorCode; s: string) =
case e.cint
of {EAGAIN, EWOULDBLOCK}: # it's the same picture
continue
else:
raiseOSError e: s
template happyPath(op: untyped; logic: untyped): untyped {.dirty.} =
## do a read or write and handle the result, else run logic.
## we inject girth, which holds the result of your operation.
let girth {.inject.} = op
case girth
of -1: # error
when leastQueue != "nim-sys":
errorHandler osLastError(): "i/o error in whassup"
else:
doAssert false, "unreachable"
of 0: # disconnect
break goodbye
else:
logic
let reply =
when leastKeepAlive:
"HTTP/1.1 200 ok\c\lContent-length: 13\c\lContent-Type: text/plain\c\l\c\lHello, World!"
else:
"HTTP/1.1 200 ok\c\lContent-length: 13\c\lContent-Type: text/plain\c\lConnection: close\c\l\c\lHello, World!"
proc whassup(client: Client; address: ClientAddr) {.cps: Cont.} =
## greet a client and find out what the fuck they want
var buffer: array[256, char] # an extra alloc is death
var pos: int
# a string large enough that we may not need a second alloc
var received = newStringOfCap 256
# iirc we inherit the flags?
#setBlocking(client, false)
##
## connection
##
block goodbye:
while true:
##
## request
##
setLen received, 0
pos = 0
while true:
when leastQueue != "nim-sys":
# wait for the client to send us something
client.iowait {Read}
# see what the client has to say for themselves
happyPath do:
when leastQueue != "nim-sys":
read(client.cint, addr buffer[0], sizeof buffer)
else:
read(client, cast[ptr UncheckedArray[byte]](addr buffer[0]), sizeof buffer)
do:
# make an efficient copy of the buffer into the received string
setLen(received, pos + girth)
copyMem(addr received[pos], addr buffer[0], girth)
pos += girth
# maybe we've read all the headers?
if received.endsWith "\c\l\c\l":
break
##
## delay
##
when leastDelay > 0:
# simulate i/o wait for benchmarking
delay leastDelay
##
## reply
##
pos = 0
while true:
when leastQueue != "nim-sys":
# wait until we can send a reply
client.iowait {Write}
happyPath do:
when leastQueue != "nim-sys":
write(client.cint, unsafeAddr reply[pos], reply.len - pos)
else:
write(client, cast[ptr UncheckedArray[byte]](unsafeAddr reply[pos]), reply.len - pos)
do:
pos += girth
if pos == reply.len:
break
# testing allocators
when not leastKeepAlive:
break goodbye
close client
when leastQueue != "nim-sys":
proc server(sock: SocketHandle) {.cps: Cont.} =
when leastQueue != "ioqueue":
sock.persist {Read}
while true:
when leastQueue == "ioqueue":
sock.iowait {Read}
# the socket is ready; compose a client
let (client, address) = accept sock
if client == osInvalidSocket:
raiseOsError osLastError()
else:
# spawn a continuation for the client
spawn: whelp whassup(client, address)
when leastQueue != "ioqueue":
# wait for the socket to be readable
dismiss()
else:
proc server(sock: AsyncListener[TCP]) {.cps: Cont.} =
while true:
let (client, address) = accept sock
# spawn a continuation for the client
spawn: whelp whassup(client, address)
when threaded:
proc serveThread(fd: SocketFD) {.thread.} =
let sock = AsyncListener[TCP] newAsyncSocket(fd)
spawn: whelp server(sock)
{.gcsafe.}:
run()
proc server() {.cps: Cont.} =
let sock = listenTcpAsync(leastAddress, leastPort.Port)
block done:
when threaded:
when defined(posix):
# We can't do threading like this on non-posix
var threads: seq[Thread[SocketFD]]
newSeq(threads, leastThreads)
for thread in threads.mitems:
let fd = SocketFD fcntl(sock.fd.cint, F_DUPFD_CLOEXEC, 0)
if fd == InvalidFD:
raiseOSError(osLastError())
createThread(thread, serveThread, fd)
for thread in threads.mitems:
joinThread thread
break
break done
server(sock)
proc serve() {.nimcall.} =
## listen for connections on the `address` and `port`
when leastQueue != "nim-sys":
var socket = newSocket()
socket.setSockOpt(OptReusePort, true)
socket.setSockOpt(OptReuseAddr, true)
socket.bindAddr(leastPort.Port, leastAddress)
listen socket
let fd = getFd socket
setBlocking(fd, false)
# spawn the server continuation
spawn: whelp server(fd)
else:
spawn: whelp server()
# run until there are no more continuations
run()
when isMainModule:
block service:
when threaded:
when leastQueue == "none" or leastQueue == "ioqueue":
# thread N servers across N threads
var threads: seq[Thread[void]]
newSeq(threads, leastThreads)
for thread in threads.mitems:
createThread(thread, serve)
for thread in threads.mitems:
joinThread thread
break service
# thread 1 dispatcher for N threads
serve()