6 import java.util.function.*;
7 import java.util.concurrent.*;
8 import java.util.logging.*;
11 import java.nio.channels.*;
13 public class EventServer implements Runnable {
14 private static final double timeout = 5;
15 private static final Logger log = Logger.getLogger("jagi.server");
16 private final ServerSocketChannel sk;
17 private final Function handler;
18 private final Driver ev = Driver.get();
19 private final ExecutorService handlers = new ThreadPoolExecutor(0, Runtime.getRuntime().availableProcessors() * 2,
20 5, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(64),
21 tgt -> new Thread(tgt, "Request handler thread"));
23 public EventServer(ServerSocketChannel sk, Function handler) {
25 sk.configureBlocking(false);
26 } catch(IOException e) {
27 throw(new RuntimeException(e));
30 this.handler = handler;
33 public static class Request {
34 public final Map<Object, Object> env;
35 public final SocketChannel sk;
37 public Request(Map<Object, Object> env, SocketChannel sk) {
43 ArrayList<Object> cleanup = new ArrayList<>((Collection<?>)env.get("jagi.cleanup"));
45 RuntimeException ce = null;
46 for(Object obj : cleanup) {
47 if(obj instanceof AutoCloseable) {
49 ((AutoCloseable)obj).close();
50 } catch(Exception e) {
52 ce = new RuntimeException("error(s) occurred during cleanup");
62 protected void error(Request req, Throwable error) {
63 log.log(Level.WARNING, "uncaught exception while handling request", error);
66 public static abstract class ChainWatcher implements Watcher {
67 private Runnable then;
68 public ChainWatcher then(Runnable then) {this.then = then; return(this);}
76 public static class BufferedOutput extends ChainWatcher {
77 public final SocketChannel sk;
78 public final ByteBuffer buf;
79 private double lastwrite;
81 public BufferedOutput(SocketChannel sk, ByteBuffer buf) {
86 public void added(Driver d) {lastwrite = d.time();}
87 public SelectableChannel channel() {return(sk);}
88 public int events() {return((buf.remaining() > 0) ? SelectionKey.OP_WRITE : -1);}
89 public double timeout() {return(lastwrite + timeout);}
91 public void handle(int events) throws IOException {
92 double now = Driver.current().time();
93 if((events & SelectionKey.OP_WRITE) != 0) {
97 if(now > lastwrite + timeout)
98 buf.position(buf.limit());
102 public static class TransferOutput extends ChainWatcher {
103 public final SocketChannel sk;
104 public final ReadableByteChannel in;
105 private final ByteBuffer buf;
106 private boolean eof = false;
107 private double lastwrite;
109 public TransferOutput(SocketChannel sk, ReadableByteChannel in) {
112 buf = ByteBuffer.allocate(65536);
116 public void added(Driver d) {lastwrite = d.time();}
117 public SelectableChannel channel() {return(sk);}
118 public int events() {return((eof && (buf.remaining() == 0)) ? -1 : SelectionKey.OP_WRITE);}
119 public double timeout() {return(lastwrite + timeout);}
121 public void handle(int events) throws IOException {
122 if(!eof && (buf.remaining() == 0)) {
124 while(buf.remaining() > 0) {
129 double now = Driver.current().time();
130 if((events & SelectionKey.OP_WRITE) != 0) {
131 if(sk.write(buf) > 0)
134 if(now > lastwrite + timeout) {
136 buf.position(buf.limit());
140 public void close() {
143 } catch(IOException e) {
144 log.log(Level.WARNING, "failed to close transfer channel: " + in, e);
151 public static class TransferInput extends ChainWatcher {
152 public final SocketChannel sk;
153 public final WritableByteChannel out;
154 private final ByteBuffer buf;
155 private final long max;
156 private boolean eof = false;
157 private double lastread;
158 private long cur = 0;
160 public TransferInput(SocketChannel sk, WritableByteChannel out, long max) {
164 buf = ByteBuffer.allocate(65536);
168 public void added(Driver d) {lastread = d.time();}
169 public SelectableChannel channel() {return(sk);}
170 public int events() {return(eof ? -1 : SelectionKey.OP_READ);}
171 public double timeout() {return(lastread + timeout);}
173 public void handle(int events) throws IOException {
174 double now = Driver.current().time();
175 if((events & SelectionKey.OP_READ) != 0) {
177 if(buf.remaining() > max - cur)
178 buf.limit(buf.position() + (int)Math.min(max - cur, Integer.MAX_VALUE));
179 int rv = sk.read(buf);
187 while(buf.remaining() > 0)
190 if(now > lastread + timeout) {
192 buf.position(buf.limit());
196 public void close() {
199 } catch(IOException e) {
200 log.log(Level.WARNING, "failed to close transfer channel: " + out, e);
207 protected void respond(Request req, String status, Map resp) {
208 Object output = resp.get("jagi.output");
209 ByteArrayOutputStream buf = new ByteArrayOutputStream();
211 Writer head = new OutputStreamWriter(buf, Utils.UTF8);
212 head.write("Status: ");
215 for(Iterator it = resp.entrySet().iterator(); it.hasNext();) {
216 Map.Entry ent = (Map.Entry)it.next();
217 Object val = ent.getValue();
218 if((ent.getKey() instanceof String) && (val != null)) {
219 String key = (String)ent.getKey();
220 if(key.startsWith("http.")) {
221 String nm = key.substring(5);
222 if(nm.equalsIgnoreCase("status"))
224 if(val instanceof Collection) {
225 for(Object part : (Collection)val) {
228 head.write(part.toString());
234 head.write(val.toString());
242 } catch(IOException e) {
243 throw(new RuntimeException("cannot happen"));
247 out = new BufferedOutput(req.sk, ByteBuffer.allocate(0));
248 } else if(output instanceof byte[]) {
249 out = new BufferedOutput(req.sk, ByteBuffer.wrap((byte[])output));
250 } else if(output instanceof ByteBuffer) {
251 out = new BufferedOutput(req.sk, (ByteBuffer)output);
252 } else if(output instanceof String) {
253 out = new BufferedOutput(req.sk, ByteBuffer.wrap(((String)output).getBytes(Utils.UTF8)));
254 } else if(output instanceof CharSequence) {
255 out = new BufferedOutput(req.sk, Utils.UTF8.encode(CharBuffer.wrap((CharSequence)output)));
256 } else if(output instanceof InputStream) {
257 out = new TransferOutput(req.sk, Channels.newChannel((InputStream)output));
258 } else if(output instanceof ReadableByteChannel) {
259 out = new TransferOutput(req.sk, (ReadableByteChannel)output);
261 throw(new IllegalArgumentException("response-body: " + output));
263 out.then(() -> submit(req::close));
264 ev.add(new BufferedOutput(req.sk, ByteBuffer.wrap(buf.toByteArray())).then(() -> ev.add(out)));
267 @SuppressWarnings("unchecked")
268 protected void handle(Request req, Function handler) {
269 boolean handoff = false;
271 Throwable error = null;
273 Map resp = (Map)handler.apply(req.env);
275 if((st = (String)resp.get("jagi.status")) != null) {
276 Function next = (Function)resp.get("jagi.next");
279 Object sink = resp.get("jagi.input-sink");
280 Object clen = req.env.get("HTTP_CONTENT_LENGTH");
282 if(clen instanceof String) {
284 max = Long.parseLong((String)clen);
285 } catch(NumberFormatException e) {
288 if(sink instanceof WritableByteChannel) {
289 ev.add(new TransferInput(req.sk, (WritableByteChannel)sink, max).then(() -> submit(() -> handle(req, next))));
290 } else if(sink instanceof OutputStream) {
291 ev.add(new TransferInput(req.sk, Channels.newChannel((OutputStream)sink), max).then(() -> submit(() -> handle(req, next))));
293 throw(new IllegalArgumentException("input-sink: " + sink));
298 submit(() -> handle(req, next));
302 throw(new IllegalArgumentException("jagi.status: " + st));
304 } else if((st = (String)resp.get("http.status")) != null) {
305 respond(req, st, resp);
308 throw(new IllegalArgumentException("neither http.status nor jagi.status set"));
310 } catch(Throwable t) {
317 } catch(Throwable ce) {
321 error.addSuppressed(ce);
326 } catch(Throwable t) {
331 protected void submit(Runnable task) {
332 handlers.submit(task);
335 class Client implements Watcher {
336 final SocketChannel sk;
338 boolean eof = false, handoff = false;
340 ByteBuffer head = null;
341 Map<Object, Object> env = null;
343 Client(SocketChannel sk) {
347 public void added(Driver d) {lastread = d.time();}
348 public SelectableChannel channel() {return(sk);}
349 public double timeout() {return(lastread + timeout);}
350 public int events() {
354 return(SelectionKey.OP_READ);
358 boolean readhead() throws IOException {
360 ByteBuffer buf = ByteBuffer.allocate(1);
363 int rv = sk.read(buf);
370 lastread = Driver.current().time();
372 if((c >= '0') && (c <= '9')) {
373 headlen = (headlen * 10) + (c - '0');
374 } else if(c == ':') {
375 head = ByteBuffer.allocate(headlen + 1);
385 if(head.remaining() == 0) {
386 if(head.get(head.limit() - 1) != ',') {
387 /* Unterminated netstring */
391 head.limit(head.limit() - 1);
392 env = Jagi.mkenv(Scgi.splithead(head), sk);
395 int rv = sk.read(head);
405 public void handle(int events) throws IOException {
406 if((events & SelectionKey.OP_READ) != 0) {
407 if((env == null) && !readhead())
409 Request req = new Request(env, sk);
410 submit(() -> EventServer.this.handle(req, handler));
413 if(Driver.current().time() > (lastread + timeout))
417 public void close() {
421 } catch(IOException e) {
427 class Accepter implements Watcher {
428 boolean closed = false;
430 public SelectableChannel channel() {return(sk);}
431 public int events() {return(SelectionKey.OP_ACCEPT);}
433 public void handle(int events) throws IOException {
434 if((events & SelectionKey.OP_ACCEPT) != 0) {
435 SocketChannel cl = sk.accept();
436 cl.configureBlocking(false);
437 Driver.current().add(new Client(cl));
441 public void close() {
450 Accepter main = new Accepter();
454 while(!main.closed) {
458 } catch(InterruptedException e) {
463 } catch(IOException e) {
464 throw(new RuntimeException(e));