Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Event timeouts #386

Merged
merged 6 commits into from
May 7, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 0 additions & 34 deletions packages/tasit-action/src/contract/Action.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import Subscription from "./Subscription";
import ProviderFactory from "../ProviderFactory";
import ConfigLoader from "../ConfigLoader";

// If necessary, we can create TransactionAction
// and/or MetaTxAction subclasses
Expand All @@ -10,20 +9,14 @@ export class Action extends Subscription {
#rawAction;
#tx;
#txConfirmations = 0;
#timeout;
#lastConfirmationTime;

constructor(rawAction, provider, signer) {
// Provider implements EventEmitter API and it's enough
// to handle with transactions events
super(provider);

const { events } = ConfigLoader.getConfig();
const { timeout } = events;

this.#rawAction = rawAction;
this.#signer = signer;
this.#timeout = timeout;
this.#provider = provider;
this.#txConfirmations = 0;
}
Expand Down Expand Up @@ -90,14 +83,6 @@ export class Action extends Subscription {
this.#addListener(eventName, listener, true);
};

getEventsTimeout = () => {
return this.#timeout;
};

setEventsTimeout = timeout => {
this.#timeout = timeout;
};

#addListener = (eventName, listener, once) => {
const events = ["confirmation", "error"];

Expand Down Expand Up @@ -159,25 +144,6 @@ export class Action extends Subscription {
return;
}

this._clearEventTimerIfExists(eventName);

this.#lastConfirmationTime = Date.now();

const timer = setTimeout(() => {
const currentTime = Date.now();
const timedOut =
currentTime - this.#lastConfirmationTime >= this.getEventsTimeout();

if (timedOut) {
this._emitErrorEventFromEventListener(
new Error(`Event ${eventName} reached timeout.`),
eventName
);
}
}, this.getEventsTimeout());

this._setEventTimer(eventName, timer);

this.#txConfirmations = confirmations;

const message = {
Expand Down
68 changes: 39 additions & 29 deletions packages/tasit-action/src/contract/Contract.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import ProviderFactory from "../ProviderFactory";
import {
accounts,
mineBlocks,
wait,
createSnapshot,
revertFromSnapshot,
} from "../testHelpers/helpers";
Expand Down Expand Up @@ -334,45 +333,30 @@ describe("TasitAction.Contract", () => {
expect(errorListener.called).to.be.false;
});

// Non-deterministic test case
it.skip("should call error listener after timeout", async () => {
it("action should call error listener after timeout", done => {
action = sampleContract.setValue("hello world");
action.setEventsTimeout(100);

const errorListener = sinon.fake(error => {
expect(error.eventName).to.equal("confirmation");
expect(error.message).to.equal("Event confirmation reached timeout.");
const { eventName, message } = error;
expect(eventName).to.equal("confirmation");
expect(message).to.equal("Event confirmation reached timeout.");
expect(action.subscribedEventNames()).to.deep.equal([
"error",
"confirmation",
]);
action.off("error");
});

const confirmationListener = sinon.fake(() => {
action.off("confirmation");
done();
});

action.on("confirmation", confirmationListener);
const confirmationListener = sinon.fake(() => {});

action.on("confirmation", confirmationListener);
action.on("error", errorListener);

await action.send();
await action.waitForOneConfirmation();

await mineBlocks(provider, 2);

// TODO: Use fake timer when Sinon/Lolex supports it.
// See more:
// https://github.com/sinonjs/sinon/issues/1739
// https://github.com/sinonjs/lolex/issues/114
// https://stackoverflow.com/a/50785284
await wait(action.getEventsTimeout() * 5);

await mineBlocks(provider, 2);

expect(errorListener.callCount).to.equal(1);
expect(confirmationListener.callCount).to.equal(1);
expect(action.subscribedEventNames()).to.deep.equal([
"error",
"confirmation",
]);
// Note: No time is necessary because no additional block will be mined
pcowgill marked this conversation as resolved.
Show resolved Hide resolved
action.send();
});

it("subscription should have one listener per event", async () => {
Expand Down Expand Up @@ -625,6 +609,32 @@ describe("TasitAction.Contract", () => {
action.send();
});

it("contract should call error listener after timeout", done => {
sampleContract.setEventsTimeout(100);
action = sampleContract.setValue("hello world");

const errorListener = sinon.fake(error => {
const { eventName, message } = error;
expect(eventName).to.equal("ValueChanged");
expect(message).to.equal("Event ValueChanged reached timeout.");
expect(sampleContract.subscribedEventNames()).to.deep.equal([
"ValueChanged",
"error",
]);
sampleContract.off("error");
sampleContract.off("ValueChanged");
done();
});

const confirmationListener = sinon.fake(() => {});

sampleContract.on("ValueChanged", confirmationListener);
sampleContract.on("error", errorListener);

// Note: No time is necessary because no additional block will be mined
action.send();
});

it("should throw error when listening on invalid event", async () => {
expect(() => {
sampleContract.on("InvalidEvent", () => {});
Expand Down
40 changes: 39 additions & 1 deletion packages/tasit-action/src/contract/Subscription.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
import ConfigLoader from "../ConfigLoader";

export class Subscription {
#ethersEventEmitter;
#eventListeners = new Map();
#timeout;

constructor(eventEmitter) {
const { events } = ConfigLoader.getConfig();
const { timeout } = events;

this.#timeout = timeout;
this.#ethersEventEmitter = eventEmitter;
}

Expand All @@ -29,6 +36,14 @@ export class Subscription {
this.#eventListeners.delete(eventName);
};

getEventsTimeout = () => {
return this.#timeout;
};

setEventsTimeout = timeout => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we call it something other than events to indicate that it can relate to confirmations too and not just “contract events”?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, setTimeout sounds good?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah!

this.#timeout = timeout;
};

// TODO: Make protected
_setEventTimer = (eventName, timer) => {
this.#decorateEventListener(eventName, { timer });
Expand Down Expand Up @@ -134,7 +149,30 @@ export class Subscription {
return;
}

this.#decorateEventListener(eventName, { isRunning: true });
this.#decorateEventListener(eventName, {
isRunning: true,
lastEmissionTime: Date.now(),
});

this._clearEventTimerIfExists(eventName);

const timer = setTimeout(() => {
const eventListener = this.#eventListeners.get(eventName);
const { lastEmissionTime } = eventListener;
const currentTime = Date.now();
const timedOut =
currentTime - lastEmissionTime >= this.getEventsTimeout();

if (timedOut) {
this._emitErrorEventFromEventListener(
new Error(`Event ${eventName} reached timeout.`),
eventName
);
}
}, this.getEventsTimeout());

this._setEventTimer(eventName, timer);

await baseListener(...args);
this.#decorateEventListener(eventName, { isRunning: false });
};
Expand Down
93 changes: 49 additions & 44 deletions packages/tasit-action/src/ethers.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const {
} = SampleContract;

import ProviderFactory from "./ProviderFactory";
import { accounts, waitForEthersEvent } from "./testHelpers/helpers";
import { accounts } from "./testHelpers/helpers";

const provider = ProviderFactory.getProvider();

Expand Down Expand Up @@ -67,55 +67,60 @@ describe("ethers.js", () => {
expect(value).to.equal(rand);
});

it("should watch contract's ValueChanged event", async () => {
const eventFakeFn = sinon.fake();

const oldValue = await sampleContract.getValue();
const newValue = `I like cats`;

const listener = event => {
const {
author: eventAuthor,
oldValue: eventOldValue,
newValue: eventNewValue,
} = event.args;

expect([eventAuthor, eventOldValue, eventNewValue]).to.deep.equal([
wallet.address,
oldValue,
newValue,
]);

event.removeListener();

eventFakeFn();
};

await sampleContract.setValue(newValue);
it("should watch contract's ValueChanged event", done => {
(async () => {
const oldValue = await sampleContract.getValue();
const newValue = `I like cats`;

const timeout = setTimeout(() => {
done(new Error("timeout"));
}, 2000);

const listener = (...args) => {
const event = args.pop();
const {
author: eventAuthor,
oldValue: eventOldValue,
newValue: eventNewValue,
} = event.args;

expect([eventAuthor, eventOldValue, eventNewValue]).to.deep.equal([
wallet.address,
oldValue,
newValue,
]);

event.removeListener();
expect(sampleContract.listenerCount("ValueChanged")).to.equal(0);
expect(sampleContract.provider._events).to.be.empty;
clearTimeout(timeout);
done();
};

await waitForEthersEvent(sampleContract, "ValueChanged", listener);
sampleContract.on("ValueChanged", listener);

expect(eventFakeFn.called).to.be.true;
expect(sampleContract.listenerCount("ValueChanged")).to.equal(0);
expect(sampleContract.provider._events).to.be.empty;
await sampleContract.setValue(newValue);
})();
});

it("should remove listener using removeAllListeners function", async () => {
const eventFakeFn = sinon.fake();

const listener = () => {
eventFakeFn();
};

await sampleContract.setValue("hello world");

await waitForEthersEvent(sampleContract, "ValueChanged", listener);
it("should remove listener using removeAllListeners function", done => {
(async () => {
const timeout = setTimeout(() => {
done(new Error("timeout"));
}, 2000);

const listener = () => {
sampleContract.removeAllListeners("ValueChanged");
expect(sampleContract.listenerCount("ValueChanged")).to.equal(0);
expect(sampleContract.provider._events).to.be.empty;
clearTimeout(timeout);
done();
};

sampleContract.removeAllListeners("ValueChanged");
sampleContract.on("ValueChanged", listener);

expect(eventFakeFn.called).to.be.true;
expect(sampleContract.listenerCount("ValueChanged")).to.equal(0);
expect(sampleContract.provider._events).to.be.empty;
await sampleContract.setValue("hello world");
})();
});

describe("message signing", () => {
Expand Down
21 changes: 0 additions & 21 deletions packages/tasit-action/src/testHelpers/helpers.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { expect } from "chai";
import { ethers } from "ethers";
import ConfigLoader from "../ConfigLoader";
import ProviderFactory from "../ProviderFactory";
import developmentConfig from "../config/default";

Expand Down Expand Up @@ -55,25 +54,6 @@ const privateKeys = [
];
export const accounts = privateKeys.map(createFromPrivateKey);

export const waitForEthersEvent = async (eventEmitter, eventName, callback) => {
return new Promise((resolve, reject) => {
const config = ConfigLoader.getConfig();
const { events } = config;
const { timeout: EVENT_TIMEOUT } = events;

const timeout = setTimeout(() => {
reject(new Error("timeout"));
}, EVENT_TIMEOUT);

eventEmitter.on(eventName, (...args) => {
const event = args.pop();
callback(event);
clearTimeout(timeout);
resolve();
});
});
};

const mineOneBlock = async provider => {
await provider.send("evm_increaseTime", [1]);
await provider.send("evm_mine", []);
Expand Down Expand Up @@ -227,7 +207,6 @@ export const duration = {
};

export const helpers = {
waitForEthersEvent,
mineBlocks,
createSnapshot,
revertFromSnapshot,
Expand Down
Loading