Skip to content

Commit

Permalink
add getExecParams for module, minor fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
cadgerfeast committed Jan 5, 2021
1 parent 3eec0dc commit bb1666b
Show file tree
Hide file tree
Showing 14 changed files with 182 additions and 21 deletions.
2 changes: 1 addition & 1 deletion .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@
/dist
/docs
/node_modules
/madoc.config.js
/jest.config.js
/vue.config.js
8 changes: 7 additions & 1 deletion docs/content/api/module/breaker/sliding/count.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ For example, if the count window size is 10, the circular array has always 10 me
## Events

| Name | Description | Params |
|:-----------|:-------------------------------------|:--------------- ---------------|
|:-----------|:-------------------------------------|:-------------------------------|
| `execute` | Called when the module is executed. | `Mollitia.Circuit` **circuit** |
| `state-changed` | Called when the breaker state changes. | `Mollitia.BreakerState` **state** |

## Methods

| Name | Description | Returns |
|:-----------|:-------------------------------------|:-------------------------------|
| `getExecParams` | Returns the circuit function parameters. | `any[]` **params** |
8 changes: 7 additions & 1 deletion docs/content/api/module/breaker/sliding/time.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@ For example, if the count window size is 10000, the circular array stores the re
## Events

| Name | Description | Params |
|:-----------|:-------------------------------------|:--------------- ---------------|
|:-----------|:-------------------------------------|:-------------------------------|
| `execute` | Called when the module is executed. | `Mollitia.Circuit` **circuit** |
| `state-changed` | Called when the breaker state changes. | `Mollitia.BreakerState` **state** |

## Methods

| Name | Description | Returns |
|:-----------|:-------------------------------------|:-------------------------------|
| `getExecParams` | Returns the circuit function parameters. | `any[]` **params** |
8 changes: 7 additions & 1 deletion docs/content/api/module/bulkhead.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,5 +52,11 @@ circuit.fn(myFunction).execute()
## Events

| Name | Description | Params |
|:-----------|:-------------------------------------|:--------------- ---------------|
|:-----------|:-------------------------------------|:-------------------------------|
| `execute` | Called when the module is executed. | `Mollitia.Circuit` **circuit** |

## Methods

| Name | Description | Returns |
|:-----------|:-------------------------------------|:-------------------------------|
| `getExecParams` | Returns the circuit function parameters. | `any[]` **params** |
8 changes: 7 additions & 1 deletion docs/content/api/module/cache.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,5 +67,11 @@ circuit.fn(myFirstFunction).execute(myObject)
## Events

| Name | Description | Params |
|:-----------|:-------------------------------------|:--------------- ---------------|
|:-----------|:-------------------------------------|:-------------------------------|
| `execute` | Called when the module is executed. | `Mollitia.Circuit` **circuit** |

## Methods

| Name | Description | Returns |
|:-----------|:-------------------------------------|:-------------------------------|
| `getExecParams` | Returns the circuit function parameters. | `any[]` **params** |
8 changes: 7 additions & 1 deletion docs/content/api/module/fallback.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,5 +52,11 @@ circuit.fn(myFunction).execute()
## Events

| Name | Description | Params |
|:-----------|:-------------------------------------|:--------------- ---------------|
|:-----------|:-------------------------------------|:-------------------------------|
| `execute` | Called when the module is executed. | `Mollitia.Circuit` **circuit** |

## Methods

| Name | Description | Returns |
|:-----------|:-------------------------------------|:-------------------------------|
| `getExecParams` | Returns the circuit function parameters. | `any[]` **params** |
8 changes: 7 additions & 1 deletion docs/content/api/module/ratelimit.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,5 +59,11 @@ const circuit = new Mollitia.Circuit({
## Events

| Name | Description | Params |
|:-----------|:-------------------------------------|:--------------- ---------------|
|:-----------|:-------------------------------------|:-------------------------------|
| `execute` | Called when the module is executed. | `Mollitia.Circuit` **circuit** |

## Methods

| Name | Description | Returns |
|:-----------|:-------------------------------------|:-------------------------------|
| `getExecParams` | Returns the circuit function parameters. | `any[]` **params** |
6 changes: 6 additions & 0 deletions docs/content/api/module/retry.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,9 @@ const circuit = new Circuit({
|:-----------|:-------------------------------------|:------------------------------------------------------------|
| `execute` | Called when the module is executed. | `Mollitia.Circuit` **circuit** |
| `retry` | Called when retrying. | `Mollitia.Circuit` **circuit**, `number` **currentAttempt** |

## Methods

| Name | Description | Returns |
|:-----------|:-------------------------------------|:-------------------------------|
| `getExecParams` | Returns the circuit function parameters. | `any[]` **params** |
8 changes: 7 additions & 1 deletion docs/content/api/module/timeout.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,12 @@ circuit.fn(myLongFunction).execute()
## Events

| Name | Description | Params |
|:-----------|:-------------------------------------|:--------------- ---------------|
|:-----------|:-------------------------------------|:-------------------------------|
| `execute` | Called when the module is executed. | `Mollitia.Circuit` **circuit** |
| `timeout` | Called when the module is times out. | `Mollitia.Circuit` **circuit** |

## Methods

| Name | Description | Returns |
|:-----------|:-------------------------------------|:-------------------------------|
| `getExecParams` | Returns the circuit function parameters. | `any[]` **params** |
16 changes: 10 additions & 6 deletions src/circuit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,10 @@ export class Circuit extends EventEmitter {
this.modules = factory?.options?.modules || [];
circuits.push(this);
}
// Computed
get activeModules (): Module[] {
return this.modules.filter((m) => m.active);
}
// Public Methods
/**
* Modifies the Circuit function.
Expand All @@ -110,16 +114,16 @@ export class Circuit extends EventEmitter {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public async execute<T> (...params: any[]): Promise<T> {
let _exec: Promise<T>;
if (this.modules.length) {
if (this.modules.length > 1) {
if (this.activeModules.length) {
if (this.activeModules.length > 1) {
const args = [];
for (let i = 2; i < this.modules.length; i++) {
args.push(this, this.modules[i].execute.bind(this.modules[i]));
for (let i = 2; i < this.activeModules.length; i++) {
args.push(this, this.activeModules[i].execute.bind(this.activeModules[i]));
}
args.push(this, this.func, ...params);
_exec = this.modules[0].execute(this, this.modules[1].execute.bind(this.modules[1]), ...args);
_exec = this.activeModules[0].execute(this, this.activeModules[1].execute.bind(this.activeModules[1]), ...args);
} else {
_exec = this.modules[0].execute(this, this.func, ...params);
_exec = this.activeModules[0].execute(this, this.func, ...params);
}
} else {
_exec = this.func(...params);
Expand Down
14 changes: 10 additions & 4 deletions src/helpers/map-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ export class MapCache {
public get<T> (...params: any[]): CacheItem<T>|null {
return this._getLoopMap<T>(this.map, ...params);
}
public clear (): void {
this._clearLoopMap(this.map);
public clear (): boolean {
return this._clearLoopMap(this.map);
}
// Private Methods
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand Down Expand Up @@ -67,15 +67,21 @@ export class MapCache {
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private _clearLoopMap (map: Map<any, any>): any {
private _clearLoopMap (map: Map<any, any>): boolean {
let hasDeleted = true;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
map.forEach((item: any) => {
if (item.map) {
this._clearLoopMap(item.map);
const mapHasDeleted = this._clearLoopMap(item.map);
if (mapHasDeleted === true) {
hasDeleted = true;
}
}
if (item.cache && Date.now() > item.cache.ttl) {
delete item.cache;
hasDeleted = true;
}
});
return hasDeleted;
}
}
6 changes: 4 additions & 2 deletions src/module/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,10 @@ export class Cache extends Module {
}
if (this.cacheClearInterval !== 0 && this.cacheClearInterval !== Infinity) {
this._cacheInterval = <unknown>setTimeout(() => {
this.logger?.debug(`${this.name} - Cache: Clear`);
this.cache.clear();
const hasDeleted = this.cache.clear();
if (hasDeleted) {
this.logger?.debug(`${this.name} - Cache: Clear`);
}
this._initializeInterval();
}, this.cacheClearInterval) as number;
}
Expand Down
21 changes: 20 additions & 1 deletion src/module/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { addons } from '../addon';
*/
export abstract class ModuleOptions {
name?: string;
active?: boolean;
logger?: Logger;
}

Expand All @@ -24,14 +25,19 @@ export class Module extends EventEmitter {
* The Module name.
*/
public name: string;
/**
* Whether the Module is active or not.
*/
public active: boolean;
/**
* The Module logger, for monitoring.
*/
public logger?: Logger;
// Constructor
constructor (options?: ModuleOptions) {
super();
this.name = options?.name ? options.name : `Module${modules.length}`;
this.active = (options?.active !== undefined) ? options.active : true;
this.name = (options?.name !== undefined) ? options.name : `Module${modules.length}`;
for (const addon of addons) {
if (addon.onModuleCreate) {
addon.onModuleCreate(this, options);
Expand All @@ -57,4 +63,17 @@ export class Module extends EventEmitter {
this.emit('execute', circuit, _exec);
return _exec;
}
/**
* Returns params passed to the execute method.
* @param circuit The Circuit reference.
* @param params The Eventual parameters to use with the Circuit function.
* @example
* const _params = this.getExecParams(circuit, params);
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public getExecParams (circuit: Circuit, params: any[]): any[] {
const index = circuit.modules.findIndex((m) => m === this);
const keepIndex = params.length - ((circuit.modules.length - 1 - index) * 2);
return params.filter((p, i) => (params.length - i) <= keepIndex);
}
}
82 changes: 82 additions & 0 deletions test/unit/module/index.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { CircuitFunction } from '../../../src/circuit';
import * as Mollitia from '../../../src/index';

const successAsync = jest.fn().mockImplementation((res: unknown = 'default', delay = 1) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve(res);
}, delay);
});
});



describe('Module', () => {
afterEach(() => {
successAsync.mockClear();
});
it('should be able to create a module', async () => {
class DummyModule extends Mollitia.Module {
constructor (options: Mollitia.ModuleOptions = {}) {
super(options);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async execute (circuit: Mollitia.Circuit, promise: CircuitFunction, ...params: any[]) {
const _params = this.getExecParams(circuit, params);
expect(_params[0]).toEqual('dummy1');
expect(_params[1]).toEqual('dummy2');
return promise(...params);
}
}
const dummyModule = new DummyModule();
const dummyModule2 = new DummyModule();
const dummyModule3 = new DummyModule();
const dummyModule4 = new DummyModule();
const circuit = new Mollitia.Circuit({
options: {
modules: [
dummyModule,
dummyModule2,
dummyModule3,
dummyModule4
]
}
});
await expect(circuit.fn(successAsync).execute('dummy1', 'dummy2')).resolves.toEqual('dummy1');
});
it('should not execute inactive modules', async () => {
class DummyModule extends Mollitia.Module {
constructor (options: Mollitia.ModuleOptions = {}) {
super(options);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async execute (circuit: Mollitia.Circuit, promise: CircuitFunction, ...params: any[]) {
this.emit('execute', this.name);
return promise(...params);
}
}
const onDummyModuleExecute = jest.fn();
const dummyModule = new DummyModule({ name: 'dummy1' });
const dummyModule2 = new DummyModule({ name: 'dummy2', active: true });
const dummyModule3 = new DummyModule({ name: 'dummy3', active: false });
const dummyModule4 = new DummyModule({ name: 'dummy4' });
dummyModule.on('execute', onDummyModuleExecute);
dummyModule2.on('execute', onDummyModuleExecute);
dummyModule3.on('execute', onDummyModuleExecute);
dummyModule4.on('execute', onDummyModuleExecute);
const circuit = new Mollitia.Circuit({
options: {
modules: [
dummyModule,
dummyModule2,
dummyModule3,
dummyModule4
]
}
});
await expect(circuit.fn(successAsync).execute('dummy')).resolves.toEqual('dummy');
expect(onDummyModuleExecute).toHaveBeenNthCalledWith(1, 'dummy1');
expect(onDummyModuleExecute).toHaveBeenNthCalledWith(2, 'dummy2');
expect(onDummyModuleExecute).toHaveBeenNthCalledWith(3, 'dummy4');
});
});

0 comments on commit bb1666b

Please sign in to comment.