+ req.write(data)
+ if req.status:
+ reqevent.response([req.status, req.headers])
+ req.flushreq()
+ self.ckflush(req)
+ except closed:
+ pass
+ except:
+ log.error("exception occurred when handling request", exc_info=True)
+
+ def run(self):
+ timeout = 10.0
+ th = threading.current_thread()
+ with self.clk:
+ self.current.add(th)
+ th.registered = True
+ self.ccond.notify_all()
+ try:
+ while True:
+ start = now = time.time()
+ with self.qlk:
+ while len(self.queue) < 1:
+ if len(self.waiting) >= self.waitlimit and now - self.wlstart >= timeout:
+ return
+ self.waiting.add(th)
+ try:
+ if len(self.waiting) == self.waitlimit:
+ self.wlstart = now
+ self.qfcond.wait(start + timeout - now)
+ finally:
+ self.waiting.remove(th)
+ now = time.time()
+ if now - start > timeout:
+ return
+ req = self.queue.popleft()
+ self.qecond.notify()
+ try:
+ self.handle1(req)
+ finally:
+ req.close()
+ finally:
+ with self.clk:
+ self.current.remove(th)
+
+ def close(self):
+ while True:
+ with self.clk:
+ if len(self.current) > 0:
+ th = next(iter(self.current))
+ else:
+ return
+ th.join()
+
+class resplex(handler):
+ cname = "rplex"
+
+ def __init__(self, *, max=None, **kw):
+ super().__init__(**kw)
+ self.current = set()
+ self.lk = threading.Lock()
+ self.tcond = threading.Condition(self.lk)
+ self.max = max
+ self.cqueue = queue.Queue(5)
+ self.cnpipe = os.pipe()
+ self.rthread = reqthread(name="Response thread", target=self.handle2)
+ self.rthread.start()
+
+ @classmethod
+ def parseargs(cls, *, max=None, **args):
+ ret = super().parseargs(**args)
+ if max:
+ ret["max"] = int(max)
+ return ret
+
+ def ckflush(self, req):
+ raise Exception("resplex handler does not support the write() function")
+
+ def handle(self, req):
+ with self.lk:
+ if self.max is not None:
+ while len(self.current) >= self.max:
+ self.tcond.wait()
+ th = reqthread(target=self.handle1, args=[req])
+ th.registered = False
+ th.start()
+ while not th.registered:
+ self.tcond.wait()
+
+ def handle1(self, req):
+ try:
+ th = threading.current_thread()
+ with self.lk:
+ self.current.add(th)
+ th.registered = True
+ self.tcond.notify_all()
+ try:
+ env = req.mkenv()
+ respobj = req.handlewsgi(env, req.startreq)
+ respiter = iter(respobj)
+ if not req.status:
+ log.error("request handler returned without calling start_request")
+ if hasattr(respiter, "close"):
+ respiter.close()
+ return
+ else:
+ self.cqueue.put((req, respiter))
+ os.write(self.cnpipe[1], b" ")
+ req = None