Context in Chapel

Here’s the translation of the Go code to Chapel, formatted in Markdown suitable for Hugo:

Our first example demonstrates the usage of Context in Chapel for controlling cancellation in an HTTP server. A Context carries deadlines, cancellation signals, and other request-scoped values across API boundaries and tasks.

use IO;
use Time;
use Net;

proc hello(request: Request, response: Response) {
  writeln("server: hello handler started");
  defer writeln("server: hello handler ended");

  // Simulate work
  select {
    when Time.sleep(10) {
      response.write("hello\n");
    }
    when request.cancelled() {
      const err = "Request cancelled";
      writeln("server: ", err);
      response.setStatus(500);
      response.write(err);
    }
  }
}

proc main() {
  var server = new Server();
  server.addHandler("/hello", hello);
  server.listen(8090);
}

In this Chapel code, we’ve simulated the concept of a Context using Chapel’s built-in concurrency features. The select statement is used to either complete the request after a delay or respond to a cancellation.

To run the server:

$ chpl context.chpl -o server
$ ./server &

Simulate a client request to /hello, hitting Ctrl+C shortly after starting to signal cancellation:

$ curl localhost:8090/hello
server: hello handler started
^C
server: Request cancelled
server: hello handler ended

Note that Chapel doesn’t have a direct equivalent to Go’s context.Context. Instead, we’ve used Chapel’s concurrency primitives to achieve similar functionality. The select statement allows us to wait for either the completion of the simulated work or a cancellation signal.

The Request and Response objects are assumed to be part of a hypothetical HTTP server library for Chapel. The cancelled() method on Request is used to check for request cancellation.

This example demonstrates how you might handle cancellation and timeouts in a Chapel server application, providing similar functionality to Go’s context-based approach.