Skip to content

Commit

Permalink
fix typing issues
Browse files Browse the repository at this point in the history
  • Loading branch information
icebob committed Dec 10, 2023
1 parent e4a1f89 commit e70de43
Show file tree
Hide file tree
Showing 17 changed files with 83 additions and 34 deletions.
2 changes: 1 addition & 1 deletion src/context.js
Original file line number Diff line number Diff line change
Expand Up @@ -390,7 +390,7 @@ class Context {
);
}

let p = this.broker.mcall(def, opts);
let p = this.broker.mcall(/** @type {MCallDefinition[]} */ (def), opts);

// Merge metadata with sub context metadata
return p
Expand Down
6 changes: 4 additions & 2 deletions src/middlewares/action-hook.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@

"use strict";

/**
* @typedef {import("../service")} Service
*/

const _ = require("lodash");
const { isFunction, isString, match } = require("../utils");

Expand Down Expand Up @@ -68,8 +72,6 @@ module.exports = function actionHookMiddleware(broker) {
hooks && hooks.error ? sanitizeHooks(hooks.error["*"], action.service) : null;

// Hooks in service
/** @type {Array<String>?} List of hooks names that match the action name */

const matchHook = hookName => {
if (hookName === "*") return false;
const patterns = hookName.split("|");
Expand Down
17 changes: 12 additions & 5 deletions src/middlewares/circuit-breaker.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
/*
* moleculer
* Copyright (c) 2019 MoleculerJS (https://github.com/moleculerjs/moleculer)
* Copyright (c) 2023 MoleculerJS (https://github.com/moleculerjs/moleculer)
* MIT Licensed
*/

"use strict";

/**
* @typedef {import("../registry/endpoint-action")} ActionEndpoint
* @typedef {import("../service")} Service
* @typedef {import("../context")} Context
* @typedef {import("../service").ActionSchema} ActionSchema
*/

const C = require("../constants");
const { METRIC } = require("../metrics");

Expand Down Expand Up @@ -49,7 +56,7 @@ module.exports = function circuitBreakerMiddleware(broker) {
/**
* Get Endpoint state from store. If not exists, create it.
*
* @param {Endpoint} ep
* @param {ActionEndpoint} ep
* @param {Service} service
* @param {Object} opts
* @returns {Object}
Expand Down Expand Up @@ -170,7 +177,7 @@ module.exports = function circuitBreakerMiddleware(broker) {
* @param {Object} item
* @param {Context} ctx
*/
function halfOpen(item) {
function halfOpen(item, ctx) {

Check warning on line 180 in src/middlewares/circuit-breaker.js

View workflow job for this annotation

GitHub Actions / common

'ctx' is defined but never used
item.state = C.CIRCUIT_HALF_OPEN;
item.ep.state = true;

Expand Down Expand Up @@ -227,7 +234,7 @@ module.exports = function circuitBreakerMiddleware(broker) {
* @param {Object} item
* @param {Context} ctx
*/
function circuitClose(item) {
function circuitClose(item, ctx) {

Check warning on line 237 in src/middlewares/circuit-breaker.js

View workflow job for this annotation

GitHub Actions / common

'ctx' is defined but never used
item.state = C.CIRCUIT_CLOSE;
item.ep.state = true;
item.failures = 0;
Expand Down Expand Up @@ -269,7 +276,7 @@ module.exports = function circuitBreakerMiddleware(broker) {
* Middleware wrapper function
*
* @param {Function} handler
* @param {Action} action
* @param {ActionSchema} action
* @returns {Function}
*/
function wrapCBMiddleware(handler, action) {
Expand Down
8 changes: 7 additions & 1 deletion src/middlewares/debugging/action-logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,13 @@ module.exports = function ActionLoggerMiddleware(opts) {
call(next) {
return (actionName, params, callingOpts) => {
// Whitelist filtering
if (!isWhiteListed(isObject(actionName) ? actionName.action.name : actionName)) {
if (
!isWhiteListed(
isObject(actionName)
? /** @type {Record<string, any>} */ (actionName).action.name
: actionName
)
) {
return next(actionName, params, callingOpts);
}

Expand Down
2 changes: 2 additions & 0 deletions src/middlewares/tracing.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ module.exports = function TracingMiddleware(broker) {
requestID: ctx.requestID
};
const globalActionTags = tracer.opts.tags.action;
/** @type {Record<string, any>} */
let actionTags;
// local action tags take precedence
if (isFunction(opts.tags)) {
Expand Down Expand Up @@ -163,6 +164,7 @@ module.exports = function TracingMiddleware(broker) {
};

const globalEventTags = tracer.opts.tags.event;
/** @type {Record<string, any>} */
let eventTags;
// local event tags take precedence
if (isFunction(opts.tags)) {
Expand Down
4 changes: 2 additions & 2 deletions src/registry/action-catalog.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,9 @@ declare class ActionCatalog {

constructor(registry: Registry, broker: ServiceBroker, StrategyFactory: typeof Strategy);

add(node: Node, service: ServiceItem, action: ActionSchema): EndpointList;
add(node: Node, service: ServiceItem, action: ActionSchema): EndpointList<ActionEndpoint>;

get(actionName: string): EndpointList | undefined;
get(actionName: string): EndpointList<ActionEndpoint> | undefined;

isAvailable(actionName: string): boolean;

Expand Down
1 change: 1 addition & 0 deletions src/registry/endpoint-action.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type { ActionSchema } from "../service";
declare class ActionEndpoint extends Endpoint {
service: Service;
action: ActionSchema;
name: string;

constructor(
registry: Registry,
Expand Down
2 changes: 1 addition & 1 deletion src/registry/endpoint-list.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import type Registry = require("./registry");
import type ServiceItem = require("./service-item");
import type Context = require("../context");

declare class EndpointList<TEndpoint extends Endpoint = Endpoint> {
declare class EndpointList<TEndpoint extends Endpoint> {
registry: Registry;
broker: ServiceBroker;
strategy: typeof BaseStrategy;
Expand Down
3 changes: 3 additions & 0 deletions src/registry/endpoint-list.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const { MoleculerServerError } = require("../errors");
/**
* Endpoint list class
*
* @template TEndpoint
* @class EndpointList
* @implements {EndpointListClass}
*/
Expand All @@ -44,6 +45,7 @@ class EndpointList {
this.registry = registry;
this.broker = broker;
this.logger = registry.logger;
// @ts-ignore
this.strategy = new StrategyFactory(registry, broker, strategyOptions);
this.name = name;
this.group = group;
Expand Down Expand Up @@ -72,6 +74,7 @@ class EndpointList {
return found;
}

// @ts-ignore
const ep = new this.EndPointFactory(this.registry, this.broker, node, service, data);
this.endpoints.push(ep);

Expand Down
4 changes: 2 additions & 2 deletions src/registry/registry.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,9 @@ declare class ServiceRegistry {

hasService(fullName: string, nodeID: string): boolean;

getActionEndpoints(actionName: string): EndpointList;
getActionEndpoints(actionName: string): EndpointList<ActionEndpoint>;

getActionEndpointByNodeId(actionName: string, nodeID: string): Endpoint;
getActionEndpointByNodeId(actionName: string, nodeID: string): ActionEndpoint;

unregisterService(fullName: string, nodeID?: string | null): void;
unregisterServicesByNode(nodeID: string): void;
Expand Down
2 changes: 1 addition & 1 deletion src/registry/registry.js
Original file line number Diff line number Diff line change
Expand Up @@ -385,7 +385,7 @@ class Registry {
*
* @param {String} actionName
* @param {String} nodeID
* @returns {Endpoint}
* @returns {ActionEndpoint}
* @memberof Registry
*/
getActionEndpointByNodeId(actionName, nodeID) {
Expand Down
6 changes: 5 additions & 1 deletion src/runner.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ declare class Runner {
worker: Worker | null;
broker: ServiceBroker | null;

folders?: string[];

/**
* Watch folders for hot reload
*/
Expand Down Expand Up @@ -152,5 +154,7 @@ declare class Runner {
/**
* Start runner
*/
start(args: string[]): Promise<void>;
start(args: string[]): Promise<void|ServiceBroker>;
}

export = Runner;
26 changes: 20 additions & 6 deletions src/runner.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
/* moleculer
* Copyright (c) 2019 MoleculerJS (https://github.com/moleculerjs/moleculer)
* Copyright (c) 2023 MoleculerJS (https://github.com/moleculerjs/moleculer)
* MIT Licensed
*/

"use strict";

/**
* Import types
*
* @typedef {import("./service")} Service
* @typedef {import("cluster").Cluster} Cluster
*/

const ServiceBroker = require("./service-broker");
const utils = require("./utils");
const fs = require("fs");
Expand All @@ -13,6 +20,8 @@ const { globSync } = require("glob");
const _ = require("lodash");
const Args = require("args");
const os = require("os");
/** @type {Cluster} */
// @ts-ignore
const cluster = require("cluster");
const kleur = require("kleur");

Expand Down Expand Up @@ -542,23 +551,28 @@ class MoleculerRunner {
return this.broker
.stop()
.catch(err => {
logger.error("Error while stopping ServiceBroker", err);
logger.error(err);
})
.then(() => this._run());
} else {
return this._run();
}
}

/**
*
* @param {string[]} args
* @returns {Promise<void|ServiceBroker>}
*/
start(args) {
return Promise.resolve()
.then(() => this.processFlags(args))
.then(() => {
if (this.flags.instances !== undefined && cluster.isMaster) {
return this.startWorkers(this.flags.instances);
if (this.flags.instances !== undefined && cluster.isPrimary) {
this.startWorkers(this.flags.instances);
} else {
return this._run();
}

return this._run();
});
}
}
Expand Down
3 changes: 3 additions & 0 deletions src/service-broker.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import type MiddlewareHandler = require("./middleware");
import type ActionEndpoint = require("./registry/endpoint-action");
import type EventEndpoint = require("./registry/endpoint-event");
import type Service = require("./service");
import type Runner = require("./runner");
import type { ServiceDependency } from "./service";
import type { LoggerOptions } from "./loggers/base";
import type { TcpTransporterOptions } from "./transporters/tcp";
Expand Down Expand Up @@ -373,6 +374,8 @@ declare class ServiceBroker {
servicesStarting: boolean;
stopping: boolean;

runner?: Runner;

constructor(options?: ServiceBroker.ServiceBrokerOptions);

registerMiddlewares(userMiddlewares: MiddlewareHandler.Middleware[]): void;
Expand Down
20 changes: 13 additions & 7 deletions src/service-broker.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ const defaultOptions = {
delay: 100,
maxDelay: 1000,
factor: 2,
// @ts-ignore
check: err => err && !!err.retryable
},

Expand Down Expand Up @@ -103,6 +104,7 @@ const defaultOptions = {
windowTime: 60,
minRequestCount: 20,
halfOpenTime: 10 * 1000,
// @ts-ignore
check: err => err && err.code >= 500
},

Expand Down Expand Up @@ -1381,24 +1383,28 @@ class ServiceBroker {
mcall(def, opts = {}) {
const { settled, ...options } = opts;
if (Array.isArray(def)) {
return utils.promiseAllControl(
def.map(item => this.call(item.action, item.params, item.options || options)),
settled,
this.Promise
return /** @type {Promise<TResult[]>} */ (
utils.promiseAllControl(
def.map(item => this.call(item.action, item.params, item.options || options)),
settled,
this.Promise
)
);
} else if (utils.isObject(def)) {
let results = {};
let promises = Object.keys(def).map(name => {
/** @type {Record<string, TResult>} */
const results = {};
const promises = Object.keys(def).map(name => {
const item = def[name];
const callOptions = item.options || options;
return this.call(item.action, item.params, callOptions).then(
res => (results[name] = res)
);
});

let p = utils.promiseAllControl(promises, settled, this.Promise);
const p = utils.promiseAllControl(promises, settled, this.Promise);

// Pointer to Context
// @ts-ignore
p.ctx = promises.map(promise => promise.ctx);

return p.then(() => results);
Expand Down
10 changes: 5 additions & 5 deletions src/utils.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,15 @@ export declare function isPromise<T>(promise: unknown): promise is Promise<T>;

export declare function polyfillPromise(P: typeof Promise): void;

export declare function promiseAllControl(
promises: any[],
export declare function promiseAllControl<T>(
promises: Promise<any>[],
settled?: boolean,
promise?: any
promise?: PromiseConstructor
):
| Promise<{
[p: string]: PromiseSettledResult<any>;
[key: string]: PromiseSettledResult<T>;
}>
| Promise<unknown[]>;
| Promise<T[]>;

export declare function clearRequireCache(filename: string): void;

Expand Down
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"strict": false,
"checkJs": true,
"declaration": true,
"skipLibCheck": false,
"declarationDir": "generated-types",
"outDir": "dist",
"target": "ES2022",
Expand Down

0 comments on commit e70de43

Please sign in to comment.