1 import sys, os, threading, time, logging, select
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):
83 def parseargs(cls, **args):
85 raise ValueError("unknown handler argument: " + next(iter(args)))
88 class freethread(handler):
89 def __init__(self, **kw):
90 super().__init__(**kw)
92 self.lk = threading.Lock()
94 def handle(self, req):
95 reqthread(target=self.run, args=[req]).start()
97 def ckflush(self, req):
98 while len(req.buffer) > 0:
99 rls, wls, els = select.select([], [req], [req])
104 th = threading.current_thread()
109 with perf.request(env) as reqevent:
110 respiter = req.handlewsgi(env, req.startreq)
111 for data in respiter:
114 reqevent.response([req.status, req.headers])
120 log.error("exception occurred when handling request", exc_info=True)
123 self.current.remove(th)
130 if len(self.current) > 0:
131 th = next(iter(self.current))
136 class threadpool(handler):
137 def __init__(self, *, min=0, max=20, live=300, **kw):
138 super().__init__(**kw)
141 self.lk = threading.RLock()
142 self.pcond = threading.Condition(self.lk)
143 self.rcond = threading.Condition(self.lk)
148 for i in range(self.min):
152 def parseargs(cls, *, min=None, max=None, live=None, **args):
153 ret = super().parseargs(**args)
155 ret["min"] = int(min)
157 ret["max"] = int(max)
159 ret["live"] = int(live)
164 th = reqthread(target=self.loop)
166 while not th in self.current:
169 def ckflush(self, req):
170 while len(req.buffer) > 0:
171 rls, wls, els = select.select([], [req], [req])
174 def _handle(self, req):
177 with perf.request(env) as reqevent:
178 respiter = req.handlewsgi(env, req.startreq)
179 for data in respiter:
182 reqevent.response([req.status, req.headers])
188 log.error("exception occurred when handling request", exc_info=True)
193 th = threading.current_thread()
201 self.pcond.notify_all()
202 now = start = time.time()
203 while self.wreq is None:
204 self.rcond.wait(start + self.live - now)
206 if now - start > self.live:
207 if len(self.current) > self.min:
208 self.current.remove(th)
212 req, self.wreq = self.wreq, None
213 self.pcond.notify_all()
221 self.current.remove(th)
224 self.pcond.notify_all()
226 def handle(self, req):
229 if len(self.free) < 1 and len(self.current) < self.max:
231 while self.wreq is not None:
233 if self.wreq is None:
242 while len(self.current) > 0:
243 self.rcond.notify_all()
246 names = {"free": freethread,
249 def parsehspec(spec):
252 nm, spec = spec.split(":", 1)
256 part, spec = spec.split(",", 1)
258 part, spec = spec, None
260 key, val = part.split("=", 1)