Skip to content

Commit

Permalink
fix(kernel): stack overflow in KernelHost.run() (#780)
Browse files Browse the repository at this point in the history
Fixes #778. This PR eliminates the mutual recursion between `KernelHost.run()` and `KernelHost.processRequest()` by scheduling the recursive `KernelHost.run()` call to run on the next iteration of the event loop.

The code change has been tested as follows:

- by running the stress-test script with and without the change to confirm that the crash occurs without the change and does not occur with the change;
- by running the unit tests to confirm that behavior is consistent;
- by synthesizing our internal CDK stack and confirming that the crash does not occur and that resources are generated correctly.
  • Loading branch information
ddinu authored and RomainMuller committed Sep 16, 2019
1 parent 7b3b059 commit 41a8c2f
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
6 changes: 5 additions & 1 deletion packages/jsii-runtime/lib/host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,11 @@ export class KernelHost {
return; // done
}

this.processRequest(req, () => this.run());
this.processRequest(req, () => {
// Schedule the call to run on the next event loop iteration to
// avoid recursion.
setImmediate(() => this.run())
});
}

private callbackHandler(callback: api.Callback) {
Expand Down
2 changes: 1 addition & 1 deletion packages/jsii-runtime/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"scripts": {
"build": "tsc --build && chmod +x bin/jsii-runtime && /bin/bash ./bundle.sh",
"watch": "tsc --build -w",
"test": "/bin/bash test/playback-test.sh",
"test": "/bin/bash test/playback-test.sh && node test/stress-test.js",
"package": "package-js"
},
"devDependencies": {
Expand Down
26 changes: 26 additions & 0 deletions packages/jsii-runtime/test/stress-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { InputOutput, Input, Output } from "../lib/in-out";
import { KernelHost } from "../lib/host";

const requestCount = 250000;

class FakeInputOutput extends InputOutput {
debug = false;
private count: number = 0;

write(_: Output) { }

read(): Input | undefined {
if(this.count == requestCount) {
return undefined;
}

++this.count;
return { api: 'stats' };
}
}

const inout = new FakeInputOutput();
const host = new KernelHost(inout, { debug: false, noStack: false });
host.run();

console.info("jsii-runtime stress test succeeded");

0 comments on commit 41a8c2f

Please sign in to comment.