1 import sys, os, threading, time, logging, select, queue
4 log = logging.getLogger("ashd.serve")
6 seqlk = threading.Lock()
15 class closed(IOError):
17 super().__init__("The client has closed the connection.")
19 class reqthread(threading.Thread):
20 def __init__(self, *, name=None, **kw):
22 name = "Request handler %i" % reqseq()
23 super().__init__(name=name, **kw)
25 class wsgirequest(object):
26 def __init__(self, handler):
30 self.handler = handler
31 self.buffer = bytearray()
37 def writehead(self, status, headers):
43 def writedata(self, data):
44 self.buffer.extend(data)
49 raise Exception("Cannot send response body before starting response.")
51 self.writehead(self.status, self.headers)
53 def write(self, data):
58 self.handler.ckflush(self)
60 def startreq(self, status, headers, exc_info=None):
69 raise Exception("Can only start responding once.")
71 self.headers = headers
74 class handler(object):
75 def handle(self, request):
77 def ckflush(self, req):
78 while len(req.buffer) > 0:
79 rls, wls, els = select.select([], [req], [req])
85 def parseargs(cls, **args):
87 raise ValueError("unknown handler argument: " + next(iter(args)))
90 class single(handler):
91 def handle(self, req):
94 with perf.request(env) as reqevent:
95 respiter = req.handlewsgi(env, req.startreq)
99 reqevent.response([req.status, req.headers])
105 log.error("exception occurred when handling request", exc_info=True)
109 class freethread(handler):
110 def __init__(self, *, max=None, timeout=None, **kw):
111 super().__init__(**kw)
113 self.lk = threading.Lock()
114 self.tcond = threading.Condition(self.lk)
116 self.timeout = timeout
119 def parseargs(cls, *, max=None, abort=None, **args):
120 ret = super().parseargs(**args)
122 ret["max"] = int(max)
124 ret["timeout"] = int(abort)
127 def handle(self, req):
129 if self.max is not None:
130 if self.timeout is not None:
131 now = start = time.time()
132 while len(self.current) >= self.max:
133 self.tcond.wait(start + self.timeout - now)
135 if now - start > self.timeout:
138 while len(self.current) >= self.max:
140 th = reqthread(target=self.run, args=[req])
142 while th.is_alive() and th not in self.current:
147 th = threading.current_thread()
150 self.tcond.notify_all()
153 with perf.request(env) as reqevent:
154 respiter = req.handlewsgi(env, req.startreq)
155 for data in respiter:
158 reqevent.response([req.status, req.headers])
164 log.error("exception occurred when handling request", exc_info=True)
167 self.current.remove(th)
168 self.tcond.notify_all()
175 if len(self.current) > 0:
176 th = next(iter(self.current))
181 class resplex(handler):
182 def __init__(self, *, max=None, **kw):
183 super().__init__(**kw)
185 self.lk = threading.Lock()
186 self.tcond = threading.Condition(self.lk)
188 self.cqueue = queue.Queue(5)
189 self.cnpipe = os.pipe()
190 self.rthread = reqthread(name="Response thread", target=self.handle2)
194 def parseargs(cls, *, max=None, **args):
195 ret = super().parseargs(**args)
197 ret["max"] = int(max)
200 def ckflush(self, req):
201 raise Exception("resplex handler does not support the write() function")
203 def handle(self, req):
205 if self.max is not None:
206 while len(self.current) >= self.max:
208 th = reqthread(target=self.handle1, args=[req])
210 while th.is_alive() and th not in self.current:
213 def handle1(self, req):
215 th = threading.current_thread()
218 self.tcond.notify_all()
221 respobj = req.handlewsgi(env, req.startreq)
222 respiter = iter(respobj)
224 log.error("request handler returned without calling start_request")
225 if hasattr(respiter, "close"):
229 self.cqueue.put((req, respiter))
230 os.write(self.cnpipe[1], b" ")
234 self.current.remove(th)
235 self.tcond.notify_all()
239 log.error("exception occurred when handling request", exc_info=True)
250 respiter = current[req]
252 if respiter is not None and hasattr(respiter, "close"):
255 log.error("exception occurred when closing iterator", exc_info=True)
259 log.error("exception occurred when closing request", exc_info=True)
262 respiter = current[req]
263 if respiter is not None:
266 data = next(respiter)
267 except StopIteration:
272 log.error("exception occurred when iterating response", exc_info=True)
280 if hasattr(respiter, "close"):
283 log.error("exception occurred when closing iterator", exc_info=True)
285 if respiter is None and not req.buffer:
289 bufl = list(req for req in current.keys() if req.buffer)
290 rls, wls, els = select.select([rp], bufl, [rp] + bufl)
292 ret = os.read(rp, 1024)
298 req, respiter = self.cqueue.get(False)
299 current[req] = respiter
309 log.error("exception occurred when writing response", exc_info=True)
312 if len(req.buffer) < 65536:
315 log.critical("unexpected exception occurred in response handler thread", exc_info=True)
321 if len(self.current) > 0:
322 th = next(iter(self.current))
326 os.close(self.cnpipe[1])
329 names = {"single": single,
333 def parsehspec(spec):
336 nm, spec = spec.split(":", 1)
340 part, spec = spec.split(",", 1)
342 part, spec = spec, None
344 key, val = part.split("=", 1)