Skip to content

Commit

Permalink
feat(core-kernel): conditional enabling and disabling of services
Browse files Browse the repository at this point in the history
  • Loading branch information
Brian Faust committed Aug 22, 2019
1 parent 9b368c9 commit 77893fd
Show file tree
Hide file tree
Showing 26 changed files with 323 additions and 171 deletions.
42 changes: 20 additions & 22 deletions packages/core-blockchain/src/blockchain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ import pluralize from "pluralize";
import { BlockProcessor, BlockProcessorResult } from "./processor";
import { stateMachine } from "./state-machine";

const logger = app.resolve<Contracts.Kernel.ILogger>("logger");
const emitter = app.resolve<Contracts.Kernel.IEventDispatcher>("events");
const { BlockFactory } = Blocks;

export class Blockchain implements Contracts.Blockchain.IBlockchain {
Expand Down Expand Up @@ -62,10 +60,10 @@ export class Blockchain implements Contracts.Blockchain.IBlockchain {
this.state.networkStart = !!options.networkStart;

if (this.state.networkStart) {
logger.warning(
app.log.warning(
"ARK Core is launched in Genesis Start mode. This is usually for starting the first node on the blockchain. Unless you know what you are doing, this is likely wrong.",
);
logger.info("Starting ARK Core for a new world, welcome aboard");
app.log.info("Starting ARK Core for a new world, welcome aboard");
}

this.actions = stateMachine.actionMap(this);
Expand All @@ -75,10 +73,10 @@ export class Blockchain implements Contracts.Blockchain.IBlockchain {
try {
return this.processBlocks(blockList.blocks.map(b => Blocks.BlockFactory.fromData(b)), cb);
} catch (error) {
logger.error(
app.log.error(
`Failed to process ${blockList.blocks.length} blocks from height ${blockList.blocks[0].height} in queue.`,
);
logger.error(error.stack);
app.log.error(error.stack);
return cb();
}
}, 1);
Expand All @@ -96,13 +94,13 @@ export class Blockchain implements Contracts.Blockchain.IBlockchain {
const nextState = stateMachine.transition(this.state.blockchain, event);

if (nextState.actions.length > 0) {
logger.debug(
app.log.debug(
`event '${event}': ${JSON.stringify(this.state.blockchain.value)} -> ${JSON.stringify(
nextState.value,
)} -> actions: [${nextState.actions.map(a => a.type).join(", ")}]`,
);
} else {
logger.debug(
app.log.debug(
`event '${event}': ${JSON.stringify(this.state.blockchain.value)} -> ${JSON.stringify(
nextState.value,
)}`,
Expand All @@ -117,7 +115,7 @@ export class Blockchain implements Contracts.Blockchain.IBlockchain {
if (action) {
setTimeout(() => action.call(this, event), 0);
} else {
logger.error(`No action '${actionKey}' found`);
app.log.error(`No action '${actionKey}' found`);
}
}

Expand All @@ -129,11 +127,11 @@ export class Blockchain implements Contracts.Blockchain.IBlockchain {
* @return {void}
*/
public async start(skipStartedCheck = false): Promise<boolean> {
logger.info("Starting Blockchain Manager :chains:");
app.log.info("Starting Blockchain Manager :chains:");

this.dispatch("START");

emitter.listenOnce("shutdown", () => this.stop());
app.events.listenOnce("shutdown", () => this.stop());

if (skipStartedCheck || process.env.CORE_SKIP_BLOCKCHAIN_STARTED_CHECK) {
return true;
Expand All @@ -150,7 +148,7 @@ export class Blockchain implements Contracts.Blockchain.IBlockchain {

public async stop(): Promise<void> {
if (!this.isStopped) {
logger.info("Stopping Blockchain Manager :chains:");
app.log.info("Stopping Blockchain Manager :chains:");

this.isStopped = true;
this.state.clearWakeUpTimeout();
Expand Down Expand Up @@ -216,19 +214,19 @@ export class Blockchain implements Contracts.Blockchain.IBlockchain {
const receivedSlot: number = Crypto.Slots.getSlotNumber(block.timestamp);

if (receivedSlot > currentSlot) {
logger.info(`Discarded block ${block.height.toLocaleString()} because it takes a future slot.`);
app.log.info(`Discarded block ${block.height.toLocaleString()} because it takes a future slot.`);
return;
}

if (this.state.started) {
this.dispatch("NEWBLOCK");
this.enqueueBlocks([block]);

emitter.dispatch(Enums.Event.State.BlockReceived, block);
app.events.dispatch(Enums.Event.State.BlockReceived, block);
} else {
logger.info(`Block disregarded because blockchain is not ready`);
app.log.info(`Block disregarded because blockchain is not ready`);

emitter.dispatch(Enums.Event.State.BlockDisregarded, block);
app.events.dispatch(Enums.Event.State.BlockDisregarded, block);
}
}

Expand Down Expand Up @@ -307,7 +305,7 @@ export class Blockchain implements Contracts.Blockchain.IBlockchain {
return;
}

logger.info(`Undoing block ${this.state.getLastBlock().data.height.toLocaleString()}`);
app.log.info(`Undoing block ${this.state.getLastBlock().data.height.toLocaleString()}`);

await revertLastBlock();
await __removeBlocks(numberOfBlocks - 1);
Expand All @@ -320,7 +318,7 @@ export class Blockchain implements Contracts.Blockchain.IBlockchain {
}

const resetHeight: number = lastBlock.data.height - nblocks;
logger.info(`Removing ${pluralize("block", nblocks, true)}. Reset to height ${resetHeight.toLocaleString()}`);
app.log.info(`Removing ${pluralize("block", nblocks, true)}. Reset to height ${resetHeight.toLocaleString()}`);

this.state.lastDownloadedBlock = lastBlock.data;

Expand All @@ -340,7 +338,7 @@ export class Blockchain implements Contracts.Blockchain.IBlockchain {
public async removeTopBlocks(count: number): Promise<void> {
const blocks: Interfaces.IBlockData[] = await this.database.getTopBlocks(count);

logger.info(
app.log.info(
`Removing ${pluralize(
"block",
blocks.length,
Expand All @@ -352,7 +350,7 @@ export class Blockchain implements Contracts.Blockchain.IBlockchain {
await this.database.deleteBlocks(blocks);
await this.database.loadBlocksFromCurrentRound();
} catch (error) {
logger.error(`Encountered error while removing blocks: ${error.message}`);
app.log.error(`Encountered error while removing blocks: ${error.message}`);
}
}

Expand Down Expand Up @@ -381,7 +379,7 @@ export class Blockchain implements Contracts.Blockchain.IBlockchain {
try {
await this.database.saveBlocks(acceptedBlocks);
} catch (error) {
logger.error(`Could not save ${acceptedBlocks.length} blocks to database : ${error.stack}`);
app.log.error(`Could not save ${acceptedBlocks.length} blocks to database : ${error.stack}`);

this.clearQueue();

Expand All @@ -392,7 +390,7 @@ export class Blockchain implements Contracts.Blockchain.IBlockchain {
const lastHeight: number = lastBlock.data.height;
const deleteRoundsAfter: number = roundCalculator.calculateRound(lastHeight).round;

logger.info(
app.log.info(
`Reverting ${pluralize("block", acceptedBlocks.length, true)} back to last height: ${lastHeight}`,
);

Expand Down
6 changes: 4 additions & 2 deletions packages/core-blockchain/src/state-machine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ import { Blockchain } from "./blockchain";

const { BlockFactory } = Blocks;
const emitter = app.resolve<Contracts.Kernel.IEventDispatcher>("events");
const logger = app.resolve<Contracts.Kernel.ILogger>("logger");

// defer initialisation to "init" due to this being resolved before the container kicks in
let stateStorage;
let logger;
let stateStorage = {} as any;

/**
* The blockchain actions.
Expand Down Expand Up @@ -117,7 +117,9 @@ blockchainMachine.actionMap = (blockchain: Blockchain) => ({
},

async init() {
logger = app.resolve<Contracts.Kernel.ILogger>("logger");
stateStorage = app.resolve<Contracts.State.IStateService>("state").getStore();
blockchainMachine.state = stateStorage;

try {
const block: Interfaces.IBlock = await blockchain.database.getLastBlock();
Expand Down
2 changes: 1 addition & 1 deletion packages/core-database/src/database-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ export class DatabaseService implements Contracts.Database.IDatabaseService {

// When called during applyRound we already know the delegates, so we don't have to query the database.
if (!delegates || delegates.length === 0) {
delegates = (await this.connection.roundsRepository.findById(round)).map(({ round, publicKey, balance }) =>
delegates = (await this.connection.roundsRepository.findById(round)).map(({ publicKey, balance }) =>
Object.assign(new Wallets.Wallet(Identities.Address.fromPublicKey(publicKey)), {
publicKey,
attributes: {
Expand Down
2 changes: 1 addition & 1 deletion packages/core-database/src/service-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export class ServiceProvider extends Support.AbstractServiceProvider {
public async register(): Promise<void> {
this.app.resolve<Contracts.Kernel.ILogger>("logger").info("Starting Database Manager");

this.app.bind("database-manager", new ConnectionManager());
this.app.singleton("database-manager", ConnectionManager);
}

public getPackageJson(): Types.PackageJson {
Expand Down
16 changes: 11 additions & 5 deletions packages/core-kernel/src/application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { AbstractBootstrapper } from "./bootstrap/bootstrapper";
import { Container } from "./container";
import { Kernel } from "./contracts";
import * as Contracts from "./contracts";
import { DirectoryNotFound } from "./errors";
import { DirectoryNotFound } from "./errors/kernel";
import { ProviderRepository } from "./repositories";

/**
Expand Down Expand Up @@ -190,7 +190,7 @@ export class Application extends Container implements Kernel.IApplication {
* @memberof Application
*/
public logPath(path: string = ""): string {
return join(this.getPath("log"), path);
return join(this.getPath("logger"), path);
}

/**
Expand Down Expand Up @@ -313,7 +313,13 @@ export class Application extends Container implements Kernel.IApplication {
public async terminate(reason?: string, error?: Error): Promise<void> {
this.booted = false;

this.log.notice(reason);
if (reason) {
this.log.notice(reason);
}

if (error) {
this.log.notice(error.stack);
}

await this.disposeServiceProviders();
}
Expand All @@ -324,7 +330,7 @@ export class Application extends Container implements Kernel.IApplication {
* @memberof Application
*/
public get log(): Contracts.Kernel.ILogger {
return this.resolve<Contracts.Kernel.ILogger>("log");
return this.resolve<Contracts.Kernel.ILogger>("logger");
}

/**
Expand All @@ -333,7 +339,7 @@ export class Application extends Container implements Kernel.IApplication {
* @memberof Application
*/
public get events(): Contracts.Kernel.IEventDispatcher {
return this.resolve<Contracts.Kernel.IEventDispatcher>("event");
return this.resolve<Contracts.Kernel.IEventDispatcher>("events");
}

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/core-kernel/src/bootstrap/app/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
// Foundation
export * from "./register-error-handler";
export * from "./register-base-configuration";
export * from "./register-base-service-providers";
export * from "./register-base-bindings";
export * from "./register-base-namespace";
export * from "./register-base-paths";
export * from "./register-application-service-providers";

// Configuration
export * from "./load-environment-variables";
Expand Down
12 changes: 6 additions & 6 deletions packages/core-kernel/src/bootstrap/app/load-configuration.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { JsonObject } from "type-fest";
import { IConfigAdapter } from "../../contracts/core-kernel";
import { ConfigManager, ConfigRepository } from "../../services/config";
import { AbstractBootstrapper } from "../bootstrapper";

Expand All @@ -12,12 +12,12 @@ export class LoadConfiguration extends AbstractBootstrapper {
* @memberof LoadConfiguration
*/
public async bootstrap(): Promise<void> {
const config: JsonObject = this.app.resolve<JsonObject>("config");
const configRepository: ConfigRepository = this.app.resolve<ConfigRepository>("config");

this.app.resolve<ConfigRepository>("config").set("options", config.options || {});

await (await this.app
const driver: IConfigAdapter = await this.app
.resolve<ConfigManager>("configManager")
.driver((config.configLoader || "local") as string)).loadConfiguration();
.driver(configRepository.get<string>("configLoader", "local"));

await driver.loadConfiguration();
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { JsonObject } from "type-fest";
import { ConfigManager, ConfigRepository } from "../../services/config";
import { AbstractBootstrapper } from "../bootstrapper";

/**
* @export
* @class RegisterBaseConfiguration
*/
export class RegisterBaseConfiguration extends AbstractBootstrapper {
/**
* @param {Kernel.IApplication} app
* @returns {Promise<void>}
* @memberof RegisterBaseConfiguration
*/
public async bootstrap(): Promise<void> {
this.app.singleton("configManager", ConfigManager);

const config: JsonObject = this.app.resolve<JsonObject>("config");
const configRepository: ConfigRepository = new ConfigRepository(config);
configRepository.set("options", config.options || {});

this.app.bind<ConfigRepository>("config", configRepository);
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { FailedNetworkDetection } from "../../errors";
import { FailedNetworkDetection } from "../../errors/kernel";
import { AbstractBootstrapper } from "../bootstrapper";

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Config, Events } from "../../services";
import { Cache, Events, Filesystem, Log, Queue } from "../../services";
import { AbstractBootstrapper } from "../bootstrapper";

/**
Expand All @@ -14,6 +14,12 @@ export class RegisterBaseServiceProviders extends AbstractBootstrapper {
public async bootstrap(): Promise<void> {
await new Events.ServiceProvider(this.app).register();

await new Config.ServiceProvider(this.app).register();
await new Log.ServiceProvider(this.app).register();

await new Filesystem.ServiceProvider(this.app).register();

await new Cache.ServiceProvider(this.app).register();

await new Queue.ServiceProvider(this.app).register();
}
}
Loading

0 comments on commit 77893fd

Please sign in to comment.