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, *, max=None, **kw):
90 super().__init__(**kw)
92 self.lk = threading.Lock()
93 self.tcond = threading.Condition(self.lk)
97 def parseargs(cls, *, max=None, **args):
98 ret = super().parseargs(**args)
100 ret["max"] = int(max)
103 def handle(self, req):
105 while self.max is not None and len(self.current) >= self.max:
107 th = reqthread(target=self.run, args=[req])
109 while th.is_alive() and th not in self.current:
112 def ckflush(self, req):
113 while len(req.buffer) > 0:
114 rls, wls, els = select.select([], [req], [req])
119 th = threading.current_thread()
122 self.tcond.notify_all()
125 with perf.request(env) as reqevent:
126 respiter = req.handlewsgi(env, req.startreq)
127 for data in respiter:
130 reqevent.response([req.status, req.headers])
136 log.error("exception occurred when handling request", exc_info=True)
139 self.current.remove(th)
140 self.tcond.notify_all()
147 if len(self.current) > 0:
148 th = next(iter(self.current))
153 class threadpool(handler):
154 def __init__(self, *, min=0, max=20, live=300, **kw):
155 super().__init__(**kw)
158 self.lk = threading.RLock()
159 self.pcond = threading.Condition(self.lk)
160 self.rcond = threading.Condition(self.lk)
165 for i in range(self.min):
169 def parseargs(cls, *, min=None, max=None, live=None, **args):
170 ret = super().parseargs(**args)
172 ret["min"] = int(min)
174 ret["max"] = int(max)
176 ret["live"] = int(live)
181 th = reqthread(target=self.loop)
183 while not th in self.current:
186 def ckflush(self, req):
187 while len(req.buffer) > 0:
188 rls, wls, els = select.select([], [req], [req])
191 def _handle(self, req):
194 with perf.request(env) as reqevent:
195 respiter = req.handlewsgi(env, req.startreq)
196 for data in respiter:
199 reqevent.response([req.status, req.headers])
205 log.error("exception occurred when handling request", exc_info=True)
210 th = threading.current_thread()
218 self.pcond.notify_all()
219 now = start = time.time()
220 while self.wreq is None:
221 self.rcond.wait(start + self.live - now)
223 if now - start > self.live:
224 if len(self.current) > self.min:
225 self.current.remove(th)
229 req, self.wreq = self.wreq, None
230 self.pcond.notify_all()
238 self.current.remove(th)
241 self.pcond.notify_all()
243 def handle(self, req):
246 if len(self.free) < 1 and len(self.current) < self.max:
248 while self.wreq is not None:
250 if self.wreq is None:
259 while len(self.current) > 0:
260 self.rcond.notify_all()
263 names = {"free": freethread,
266 def parsehspec(spec):
269 nm, spec = spec.split(":", 1)
273 part, spec = spec.split(",", 1)
275 part, spec = spec, None
277 key, val = part.split("=", 1)