Skip to content

Commit

Permalink
refactor(core-kernel): remove app.events and all of its usages (#3835)
Browse files Browse the repository at this point in the history
  • Loading branch information
rainydio authored Jun 27, 2020
1 parent 196c501 commit 35ef592
Show file tree
Hide file tree
Showing 29 changed files with 185 additions and 176 deletions.
51 changes: 27 additions & 24 deletions __tests__/unit/core-database/database-service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,18 +91,18 @@ const triggers = {
call: jest.fn(),
};

const events = {
call: jest.fn(),
dispatch: jest.fn(),
};

const logger = {
error: jest.fn(),
warning: jest.fn(),
info: jest.fn(),
debug: jest.fn(),
};

const emitter = {
call: jest.fn(),
dispatch: jest.fn(),
};

const container = new Container.Container();
container.bind(Container.Identifiers.Application).toConstantValue(app);
container.bind(Container.Identifiers.DatabaseConnection).toConstantValue(connection);
Expand All @@ -118,8 +118,8 @@ container.bind(Container.Identifiers.BlockState).toConstantValue(blockState);
container.bind(Container.Identifiers.DposState).toConstantValue(dposState);
container.bind(Container.Identifiers.DposPreviousRoundStateProvider).toConstantValue(getDposPreviousRoundState);
container.bind(Container.Identifiers.TriggerService).toConstantValue(triggers);
container.bind(Container.Identifiers.EventDispatcherService).toConstantValue(events);
container.bind(Container.Identifiers.LogService).toConstantValue(logger);
container.bind(Container.Identifiers.EventDispatcherService).toConstantValue(emitter);

beforeEach(() => {
app.get.mockReset();
Expand Down Expand Up @@ -183,15 +183,15 @@ beforeEach(() => {
logger.info.mockReset();
logger.debug.mockReset();

emitter.call.mockReset();
emitter.dispatch.mockReset();
events.call.mockReset();
events.dispatch.mockReset();
});

describe("DatabaseService.initialize", () => {
it("should dispatch starting event", async () => {
const databaseService = container.resolve(DatabaseService);
await databaseService.initialize();
expect(emitter.dispatch).toBeCalledWith(Enums.StateEvent.Starting);
expect(events.dispatch).toBeCalledWith(Enums.StateEvent.Starting);
});

it("should reset database when CORE_RESET_DATABASE variable is set", async () => {
Expand Down Expand Up @@ -292,8 +292,8 @@ describe("DatabaseService.disconnect", () => {
it("should emit disconnect events", async () => {
const databaseService = container.resolve(DatabaseService);
await databaseService.disconnect();
expect(emitter.dispatch).toBeCalledWith("database.preDisconnect");
expect(emitter.dispatch).toBeCalledWith("database.postDisconnect");
expect(events.dispatch).toBeCalledWith("database.preDisconnect");
expect(events.dispatch).toBeCalledWith("database.postDisconnect");
});
});

Expand Down Expand Up @@ -325,7 +325,10 @@ describe("DatabaseService.restoreCurrentRound", () => {

expect(getDposPreviousRoundState).not.toBeCalled(); // restoring current round should not need previous round state
// important: getActiveDelegates should be called with only roundInfo (restoreCurrentRound does *not* provide delegates to it)
expect(triggers.call).toHaveBeenLastCalledWith("getActiveDelegates", { roundInfo: expect.anything(), delegates: undefined });
expect(triggers.call).toHaveBeenLastCalledWith("getActiveDelegates", {
roundInfo: expect.anything(),
delegates: undefined,
});
expect(databaseService.forgingDelegates).toEqual(forgingDelegates);
});
});
Expand Down Expand Up @@ -371,9 +374,9 @@ describe("DatabaseService.applyBlock", () => {
expect(stateStore.getLastBlock).toBeCalledTimes(1);
expect(blockState.applyBlock).toBeCalledWith(block);
expect(databaseService.blocksInCurrentRound).toEqual([block]);
expect(emitter.dispatch).toBeCalledWith("forger.missing", { delegate: delegateWallet });
expect(handler.emitEvents).toBeCalledWith(transaction, emitter);
expect(emitter.dispatch).toBeCalledWith("block.applied", block.data);
expect(events.dispatch).toBeCalledWith("forger.missing", { delegate: delegateWallet });
expect(handler.emitEvents).toBeCalledWith(transaction, events);
expect(events.dispatch).toBeCalledWith("block.applied", block.data);
});

it("should apply block, not apply round, and not detect missed blocks when last block height is 1", async () => {
Expand All @@ -393,8 +396,8 @@ describe("DatabaseService.applyBlock", () => {
await databaseService.applyBlock(block as any);

expect(stateStore.getLastBlock).toBeCalledTimes(1);
expect(handler.emitEvents).toBeCalledWith(transaction, emitter);
expect(emitter.dispatch).toBeCalledWith("block.applied", block.data);
expect(handler.emitEvents).toBeCalledWith(transaction, events);
expect(events.dispatch).toBeCalledWith("block.applied", block.data);
});
});

Expand Down Expand Up @@ -433,7 +436,7 @@ describe("DatabaseService.applyRound", () => {
maxDelegates: 51,
});
expect(roundRepository.save).toBeCalledWith(dposStateRoundDelegates);
expect(emitter.dispatch).toBeCalledWith("round.applied");
expect(events.dispatch).toBeCalledWith("round.applied");
});

it("should build delegates, save round, dispatch events when height is 1", async () => {
Expand Down Expand Up @@ -470,7 +473,7 @@ describe("DatabaseService.applyRound", () => {
maxDelegates: 51,
});
expect(roundRepository.save).toBeCalledWith(dposStateRoundDelegates);
expect(emitter.dispatch).toBeCalledWith("round.applied");
expect(events.dispatch).toBeCalledWith("round.applied");
});

it("should build delegates, save round, dispatch events, and skip missing round checks when first round has genesis block only", async () => {
Expand Down Expand Up @@ -507,7 +510,7 @@ describe("DatabaseService.applyRound", () => {
maxDelegates: 51,
});
expect(roundRepository.save).toBeCalledWith(dposStateRoundDelegates);
expect(emitter.dispatch).toBeCalledWith("round.applied");
expect(events.dispatch).toBeCalledWith("round.applied");
});

it("should delete round and rethrow error when error was thrown", async () => {
Expand Down Expand Up @@ -957,9 +960,9 @@ describe("DatabaseService.revertBlock", () => {
await databaseService.revertBlock(block as any);

expect(blockState.revertBlock).toBeCalledWith(block);
expect(emitter.dispatch).toBeCalledWith("transaction.reverted", transaction1.data);
expect(emitter.dispatch).toBeCalledWith("transaction.reverted", transaction2.data);
expect(emitter.dispatch).toBeCalledWith("block.reverted", block.data);
expect(events.dispatch).toBeCalledWith("transaction.reverted", transaction1.data);
expect(events.dispatch).toBeCalledWith("transaction.reverted", transaction2.data);
expect(events.dispatch).toBeCalledWith("block.reverted", block.data);
});
});

Expand Down Expand Up @@ -1022,7 +1025,7 @@ describe("DatabaseService.saveRound", () => {

expect(delegate1.getAttribute).toBeCalledWith("delegate.round");
expect(roundRepository.save).toBeCalledWith(activeDelegates);
expect(emitter.dispatch).toBeCalledWith("round.created", activeDelegates);
expect(events.dispatch).toBeCalledWith("round.created", activeDelegates);
});
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,17 @@ import "jest-extended";

import { Application } from "@packages/core-kernel/src/application";
import { Container, Identifiers } from "@packages/core-kernel/src/ioc";
import { MemoryEventDispatcher } from "@packages/core-kernel/src/services/events/drivers/memory";
import { ServiceProvider } from "@packages/core-kernel/src/services/queue";
import { MemoryQueue } from "@packages/core-kernel/src/services/queue/drivers/memory";
import { QueueFactory } from "@packages/core-kernel/src/types";

let app: Application;

beforeEach(() => (app = new Application(new Container())));
beforeEach(() => {
app = new Application(new Container());
app.bind(Identifiers.EventDispatcherService).to(MemoryEventDispatcher);
});

describe("QueueServiceProvider", () => {
it("should register the service", async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ beforeEach(() => {
container.snapshot();

app = new Application(container);
app.bind(Identifiers.EventDispatcherService).to(MemoryEventDispatcher);

scheduleService = app.resolve<Schedule>(Schedule);
});
Expand All @@ -26,10 +27,6 @@ describe("Schedule", () => {
});

it("should return a block job instance", () => {
app.bind(Identifiers.EventDispatcherService).toConstantValue(
app.resolve<MemoryEventDispatcher>(MemoryEventDispatcher),
);

expect(scheduleService.block()).toBeInstanceOf(BlockJob);
});
});
9 changes: 2 additions & 7 deletions __tests__/unit/core-manager/watcher-wallet.test.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,19 @@
import "jest-extended";

import { Container, Services } from "@arkecosystem/core-kernel";
import { Services } from "@arkecosystem/core-kernel";
import { WatcherWallet } from "@arkecosystem/core-manager/src/watcher-wallet";
import { Utils } from "@arkecosystem/crypto";
import { Sandbox } from "@packages/core-test-framework";
import { getWalletAttributeSet } from "@packages/core-test-framework/src/internal/wallet-attributes";

let sandbox: Sandbox;
let wallet: WatcherWallet;
const mockEventDispatcher = {
dispatchSync: jest.fn(),
};

beforeEach(() => {
sandbox = new Sandbox();
sandbox.app.bind(Container.Identifiers.EventDispatcherService).toConstantValue(mockEventDispatcher);

const attributeMap = new Services.Attributes.AttributeMap(getWalletAttributeSet());

wallet = new WatcherWallet(sandbox.app, "123", attributeMap);
wallet = new WatcherWallet(mockEventDispatcher as any, "123", attributeMap);
});

afterEach(() => {
Expand Down
10 changes: 5 additions & 5 deletions packages/core-blockchain/src/blockchain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export class Blockchain implements Contracts.Blockchain.Blockchain {
private readonly stateMachine!: StateMachine;

@Container.inject(Container.Identifiers.EventDispatcherService)
private readonly emitter!: Contracts.Kernel.EventDispatcher;
private readonly events!: Contracts.Kernel.EventDispatcher;

@Container.inject(Container.Identifiers.LogService)
private readonly logger!: Contracts.Kernel.Logger;
Expand Down Expand Up @@ -115,9 +115,9 @@ export class Blockchain implements Contracts.Blockchain.Blockchain {
peerCount: 10,
});

this.emitter.listen(Enums.ForgerEvent.Missing, { handle: this.checkMissingBlocks });
this.events.listen(Enums.ForgerEvent.Missing, { handle: this.checkMissingBlocks });

this.emitter.listen(Enums.RoundEvent.Applied, { handle: this.resetMissedBlocks });
this.events.listen(Enums.RoundEvent.Applied, { handle: this.resetMissedBlocks });

return true;
}
Expand Down Expand Up @@ -202,11 +202,11 @@ export class Blockchain implements Contracts.Blockchain.Blockchain {
this.dispatch("NEWBLOCK");
this.enqueueBlocks([block]);

this.app.events.dispatch(Enums.BlockEvent.Received, block);
this.events.dispatch(Enums.BlockEvent.Received, block);
} else {
this.logger.info(`Block disregarded because blockchain is not ready`);

this.app.events.dispatch(Enums.BlockEvent.Disregarded, block);
this.events.dispatch(Enums.BlockEvent.Disregarded, block);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@ export class BlockchainReady implements Action {
private readonly stateStore!: Contracts.State.StateStore;

@Container.inject(Container.Identifiers.EventDispatcherService)
private readonly eventDispatcher!: Contracts.Kernel.EventDispatcher;
private readonly events!: Contracts.Kernel.EventDispatcher;

public async handle(): Promise<void> {
if (!this.stateStore.started) {
this.stateStore.started = true;

this.eventDispatcher.dispatch(Enums.StateEvent.Started, true);
this.events.dispatch(Enums.StateEvent.Started, true);
}
}
}
26 changes: 13 additions & 13 deletions packages/core-database/src/database-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export class DatabaseService {
private readonly logger!: Contracts.Kernel.Logger;

@Container.inject(Container.Identifiers.EventDispatcherService)
private readonly emitter!: Contracts.Kernel.EventDispatcher;
private readonly events!: Contracts.Kernel.EventDispatcher;

// TODO: make private readonly
public blocksInCurrentRound: Interfaces.IBlock[] | undefined = undefined;
Expand All @@ -75,7 +75,7 @@ export class DatabaseService {

public async initialize(): Promise<void> {
try {
this.emitter.dispatch(Enums.StateEvent.Starting);
this.events.dispatch(Enums.StateEvent.Starting);

const genesisBlockJson = Managers.configManager.get("genesisBlock");
const blockTimeLookup = await AppUtils.forgingInfoCalculator.getBlockTimeLookup(
Expand All @@ -100,11 +100,11 @@ export class DatabaseService {
public async disconnect(): Promise<void> {
this.logger.debug("Disconnecting from database");

this.emitter.dispatch(DatabaseEvent.PRE_DISCONNECT);
this.events.dispatch(DatabaseEvent.PRE_DISCONNECT);

await this.connection.close();

this.emitter.dispatch(DatabaseEvent.POST_DISCONNECT);
this.events.dispatch(DatabaseEvent.POST_DISCONNECT);
this.logger.debug("Disconnected from database");
}

Expand Down Expand Up @@ -134,7 +134,7 @@ export class DatabaseService {
await this.emitTransactionEvents(transaction);
}

this.emitter.dispatch(Enums.BlockEvent.Applied, block.data);
this.events.dispatch(Enums.BlockEvent.Applied, block.data);
}

// TODO: move out of core-database to get rid of WalletState dependency
Expand Down Expand Up @@ -169,7 +169,7 @@ export class DatabaseService {
// ! set it to empty array and why it can be undefined at all?
this.blocksInCurrentRound!.length = 0;

this.emitter.dispatch(Enums.RoundEvent.Applied);
this.events.dispatch(Enums.RoundEvent.Applied);
} catch (error) {
// trying to leave database state has it was
// ! this.saveRound may not have been called
Expand Down Expand Up @@ -479,10 +479,10 @@ export class DatabaseService {
assert(this.blocksInCurrentRound!.pop()!.data.id === block.data.id);

for (let i = block.transactions.length - 1; i >= 0; i--) {
this.emitter.dispatch(Enums.TransactionEvent.Reverted, block.transactions[i].data);
this.events.dispatch(Enums.TransactionEvent.Reverted, block.transactions[i].data);
}

this.emitter.dispatch(Enums.BlockEvent.Reverted, block.data);
this.events.dispatch(Enums.BlockEvent.Reverted, block.data);
}

public async revertRound(height: number): Promise<void> {
Expand Down Expand Up @@ -510,7 +510,7 @@ export class DatabaseService {

await this.roundRepository.save(activeDelegates);

this.emitter.dispatch(Enums.RoundEvent.Created, activeDelegates);
this.events.dispatch(Enums.RoundEvent.Created, activeDelegates);
}

public async deleteRound(round: number): Promise<void> {
Expand Down Expand Up @@ -605,7 +605,7 @@ export class DatabaseService {
`Delegate ${delegate.getAttribute("delegate.username")} (${delegate.publicKey}) just missed a block.`,
);

this.emitter.dispatch(Enums.ForgerEvent.Missing, {
this.events.dispatch(Enums.ForgerEvent.Missing, {
delegate,
});
}
Expand Down Expand Up @@ -732,7 +732,7 @@ export class DatabaseService {
`Delegate ${wallet.getAttribute("delegate.username")} (${wallet.publicKey}) just missed a round.`,
);

this.emitter.dispatch(Enums.RoundEvent.Missed, {
this.events.dispatch(Enums.RoundEvent.Missed, {
delegate: wallet,
});
}
Expand Down Expand Up @@ -778,9 +778,9 @@ export class DatabaseService {
}

private async emitTransactionEvents(transaction: Interfaces.ITransaction): Promise<void> {
this.emitter.dispatch(Enums.TransactionEvent.Applied, transaction.data);
this.events.dispatch(Enums.TransactionEvent.Applied, transaction.data);
const handler = await this.handlerRegistry.getActivatedHandlerForData(transaction.data);
// ! no reason to pass this.emitter
handler.emitEvents(transaction, this.emitter);
handler.emitEvents(transaction, this.events);
}
}
Loading

0 comments on commit 35ef592

Please sign in to comment.