Q:

Koa.js abort running request

How can I end a request in koa.js using another request.  Lets say I'm keeping the active request contexts in an object.  Assume request A is started and takes a long time.  How can I make another request, that tells request A to end.
var requests = {};

// middleware to track requests
app.use(function*(next) {
    var reqId = crypto.randomBytes(32).toString('hex');
    requests[reqId] = {
      context: this
    }

    yield next;

    delete requests[reqId];
  }
);

  // route to kill request using ID generated from middleware above
  router.get('/kill/:reqId', function *(next) {
    var req = requests[this.params.reqId];

    if (req) {
      // abort request here
    } else {
      this.body = {
        error: 'Request not found'
      };
    }
  });

A:

You should implement a cancellation token that you check regularly.
Example:
// Factory to create a token
const cancellationToken = () => {
  let _cancelled = false;

  function check() {
    if (_cancelled == true) {
      throw new Error('Request cancelled');
    }
  }

  function cancel() {
    _cancelled = true;
  }

  return {
    check: check,
    cancel: cancel
  };
}

const reqs = {};

// Middleware to create tokens.
app.use(function *(next) {
  const reqId = crypto.randomBytes(32).toString('hex');
  const ct = cancellationToken();
  reqs[reqId] = ct;
  this.cancellationToken = ct;
  yield next;

  delete reqs[reqId];
});

// route to kill request using ID generated from middleware above
router.get('/kill/:reqId', function *(next) {
  const ct = requests[this.params.reqId];

  if (ct) {
    ct.cancel();
  } else {
    this.body = {
      error: 'Request not found'
    };
  }
});

// A request checking for cancellation.
router.get('/longrunningtask', function *(next) {
  for (let i = 0; i < 1000; i++) {
    yield someLongRunningTask(i);
    // This is where you check to see if you're done.
    // The method will throw and abort the request.
    this.cancellationToken.check();
  }
});

You could even pass along the cancellation token to the someLongRunningTask function so you can control cancellation there.

