@routr/dispatcher 2.0.5-alpha.2 → 2.0.5-alpha.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,3 @@
1
1
  import { MessageDispatcherConfig } from "../types";
2
- import * as E from 'fp-ts/Either';
2
+ import * as E from "fp-ts/Either";
3
3
  export declare const getConfig: (path: string) => E.Either<Error, MessageDispatcherConfig>;
@@ -1,18 +1,11 @@
1
1
  "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14
3
  if (k2 === undefined) k2 = k;
15
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
16
9
  }) : (function(o, m, k, k2) {
17
10
  if (k2 === undefined) k2 = k;
18
11
  o[k2] = m[k];
@@ -34,21 +27,21 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
34
27
  };
35
28
  Object.defineProperty(exports, "__esModule", { value: true });
36
29
  exports.getConfig = void 0;
37
- var fs_1 = __importDefault(require("fs"));
38
- var schema_1 = require("./schema");
39
- var ajv_1 = __importDefault(require("ajv"));
40
- var E = __importStar(require("fp-ts/Either"));
41
- var ajv = new ajv_1.default();
42
- var validate = ajv.compile(schema_1.schema);
43
- var getConfig = function (path) {
44
- var c = JSON.parse(fs_1.default.readFileSync(path, "utf8"));
45
- if (!validate(__assign({}, c))) {
30
+ const fs_1 = __importDefault(require("fs"));
31
+ const schema_1 = require("./schema");
32
+ const ajv_1 = __importDefault(require("ajv"));
33
+ const E = __importStar(require("fp-ts/Either"));
34
+ const ajv = new ajv_1.default();
35
+ const validate = ajv.compile(schema_1.schema);
36
+ const getConfig = (path) => {
37
+ const c = JSON.parse(fs_1.default.readFileSync(path, "utf8"));
38
+ if (!validate(Object.assign({}, c))) {
46
39
  return E.left(new Error(JSON.stringify(validate.errors[0].message)));
47
40
  }
48
41
  // convert funcMatch to actual functions
49
- var processors = c.spec.processors.map(function (p) {
50
- var ref = p.ref, isFallback = p.isFallback, addr = p.addr, methods = p.methods, matchFunc = p.matchFunc;
51
- return { ref: ref, isFallback: isFallback, addr: addr, methods: methods, matchFunc: eval("(" + p.matchFunc + ")") };
42
+ const processors = c.spec.processors.map((p) => {
43
+ const { ref, addr, methods, matchFunc } = p;
44
+ return { ref, addr, methods, matchFunc: eval(`(${matchFunc})`) };
52
45
  });
53
46
  // Re-insert processors with matchFunc now as a function
54
47
  c.spec.processors = processors;
@@ -57,9 +57,6 @@ export declare const schema: {
57
57
  ref: {
58
58
  type: string;
59
59
  };
60
- isFallback: {
61
- type: string;
62
- };
63
60
  addr: {
64
61
  type: string;
65
62
  };
@@ -20,84 +20,81 @@ exports.schema = void 0;
20
20
  * limitations under the License.
21
21
  */
22
22
  exports.schema = {
23
- "$id": "https://json-schema.org/draft/2020-12/schema",
24
- "title": "Message Dispatcher configuration",
25
- "description": "Configuration for a Message Dispatcher instance",
26
- "type": "object",
27
- "properties": {
28
- "kind": {
29
- "description": "Resouce type",
30
- "type": "string"
23
+ $id: "https://json-schema.org/draft/2020-12/schema",
24
+ title: "Message Dispatcher configuration",
25
+ description: "Configuration for a Message Dispatcher instance",
26
+ type: "object",
27
+ properties: {
28
+ kind: {
29
+ description: "Resouce type",
30
+ type: "string"
31
31
  },
32
- "apiVersion": {
33
- "description": "Resource version",
34
- "type": "string"
32
+ apiVersion: {
33
+ description: "Resource version",
34
+ type: "string"
35
35
  },
36
- "metadata": {
37
- "description": "Resource metadata",
38
- "type": "object",
39
- "properties": {
40
- "ref": {
41
- "description": "EdgePort reference",
42
- "type": "string"
36
+ metadata: {
37
+ description: "Resource metadata",
38
+ type: "object",
39
+ properties: {
40
+ ref: {
41
+ description: "EdgePort reference",
42
+ type: "string"
43
43
  }
44
44
  },
45
- "required": ["ref"]
45
+ required: ["ref"]
46
46
  },
47
- "spec": {
48
- "description": "Operations spec for EdgePort",
49
- "type": "object",
50
- "properties": {
51
- "bindAddr": {
52
- "description": "Ipv4 interface to accept request on",
53
- "type": "string"
47
+ spec: {
48
+ description: "Operations spec for EdgePort",
49
+ type: "object",
50
+ properties: {
51
+ bindAddr: {
52
+ description: "Ipv4 interface to accept request on",
53
+ type: "string"
54
54
  },
55
- "middlewares": {
56
- "description": "Middleware Processors",
57
- "type": "array",
58
- "items": {
59
- "type": "object"
55
+ middlewares: {
56
+ description: "Middleware Processors",
57
+ type: "array",
58
+ items: {
59
+ type: "object"
60
60
  },
61
- "properties": {
62
- "ref": {
63
- "type": "string"
61
+ properties: {
62
+ ref: {
63
+ type: "string"
64
64
  },
65
- "addr": {
66
- "type": "string"
65
+ addr: {
66
+ type: "string"
67
67
  }
68
68
  },
69
- "required": ["ref", "addr"]
69
+ required: ["ref", "addr"]
70
70
  },
71
- "processors": {
72
- "description": "Message Processors",
73
- "type": "array",
74
- "items": {
75
- "type": "object"
71
+ processors: {
72
+ description: "Message Processors",
73
+ type: "array",
74
+ items: {
75
+ type: "object"
76
76
  },
77
- "properties": {
78
- "ref": {
79
- "type": "string"
77
+ properties: {
78
+ ref: {
79
+ type: "string"
80
80
  },
81
- "isFallback": {
82
- "type": "boolean"
81
+ addr: {
82
+ type: "string"
83
83
  },
84
- "addr": {
85
- "type": "string"
84
+ matchFunc: {
85
+ type: "string"
86
86
  },
87
- "matchFunc": {
88
- "type": "string"
89
- },
90
- "methods": {
91
- "type": "array",
92
- "items": {
93
- "type": "string"
87
+ methods: {
88
+ type: "array",
89
+ items: {
90
+ type: "string"
94
91
  }
95
92
  }
96
93
  },
97
- "required": ["ref", "addr", "methods", "matchFunc"]
94
+ required: ["ref", "addr", "methods", "matchFunc"]
98
95
  }
99
96
  }
100
97
  }
101
98
  },
102
- "required": ["kind", "metadata", "spec", "apiVersion"]
99
+ required: ["kind", "metadata", "spec", "apiVersion"]
103
100
  };
@@ -1,10 +1,11 @@
1
1
  import { ProcessorGPRCConnection } from "./types";
2
2
  import { ProcessorConfig } from "@routr/common";
3
+ import { MiddlewareConfig } from "@routr/common/src/types";
3
4
  /**
4
5
  * Creates a connection to all the backend processors. The function will
5
6
  * fail if any of the backends is unavailable during initialization.
6
7
  *
7
- * @param processors list of backend processors
8
- * @returns list of connections
8
+ * @param {ProcessorConfig} processors list of backend processors
9
+ * @return {ProcessorGPRCConnection}
9
10
  */
10
- export default function connectToBackendProcessors(processors: ProcessorConfig[]): Map<string, ProcessorGPRCConnection>;
11
+ export default function connectToBackend(processors: ProcessorConfig[] | MiddlewareConfig[]): Map<string, ProcessorGPRCConnection>;
@@ -1,63 +1,46 @@
1
1
  "use strict";
2
- var __read = (this && this.__read) || function (o, n) {
3
- var m = typeof Symbol === "function" && o[Symbol.iterator];
4
- if (!m) return o;
5
- var i = m.call(o), r, ar = [], e;
6
- try {
7
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
7
  }
9
- catch (error) { e = { error: error }; }
10
- finally {
11
- try {
12
- if (r && !r.done && (m = i["return"])) m.call(i);
13
- }
14
- finally { if (e) throw e.error; }
15
- }
16
- return ar;
17
- };
18
- var __spreadArray = (this && this.__spreadArray) || function (to, from) {
19
- for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
20
- to[j] = from[i];
21
- return to;
22
- };
23
- var __values = (this && this.__values) || function(o) {
24
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
25
- if (m) return m.call(o);
26
- if (o && typeof o.length === "number") return {
27
- next: function () {
28
- if (o && i >= o.length) o = void 0;
29
- return { value: o && o[i++], done: !o };
30
- }
31
- };
32
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
33
24
  };
34
25
  Object.defineProperty(exports, "__esModule", { value: true });
35
- var common_1 = require("@routr/common");
36
- var grpc = require("@grpc/grpc-js");
26
+ const common_1 = require("@routr/common");
27
+ const grpc = __importStar(require("@grpc/grpc-js"));
37
28
  /**
38
29
  * Creates a connection to all the backend processors. The function will
39
30
  * fail if any of the backends is unavailable during initialization.
40
31
  *
41
- * @param processors list of backend processors
42
- * @returns list of connections
32
+ * @param {ProcessorConfig} processors list of backend processors
33
+ * @return {ProcessorGPRCConnection}
43
34
  */
44
- function connectToBackendProcessors(processors) {
45
- var e_1, _a;
46
- var procs = __spreadArray([], __read(processors));
47
- var connections = new Map();
48
- try {
49
- for (var procs_1 = __values(procs), procs_1_1 = procs_1.next(); !procs_1_1.done; procs_1_1 = procs_1.next()) {
50
- var processor = procs_1_1.value;
51
- connections.set(processor.ref, new common_1.PROCESSOR_OBJECT_PROTO.Processor(processor.addr, grpc.credentials.createInsecure()));
52
- }
53
- }
54
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
55
- finally {
56
- try {
57
- if (procs_1_1 && !procs_1_1.done && (_a = procs_1.return)) _a.call(procs_1);
58
- }
59
- finally { if (e_1) throw e_1.error; }
35
+ function connectToBackend(processors) {
36
+ const procs = processors ? [...processors] : [];
37
+ const connections = new Map();
38
+ // eslint-disable-next-line no-loops/no-loops
39
+ for (const processor of procs) {
40
+ connections.set(processor.ref,
41
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
42
+ new common_1.PROCESSOR_OBJECT_PROTO.Processor(processor.addr, grpc.credentials.createInsecure()));
60
43
  }
61
44
  return connections;
62
45
  }
63
- exports.default = connectToBackendProcessors;
46
+ exports.default = connectToBackend;
package/dist/errors.d.ts CHANGED
@@ -1,9 +1,37 @@
1
- import grpc = require("@grpc/grpc-js");
1
+ import * as grpc from "@grpc/grpc-js";
2
+ /**
3
+ * Thrown when no backened matches the request.
4
+ */
2
5
  export declare class NotMatchingProcessorFound extends Error {
3
6
  code: grpc.status;
7
+ /**
8
+ * Creates a new instance of NotMatchingProcessorFound.
9
+ *
10
+ * @param {string} ref - The reference of the processor
11
+ */
4
12
  constructor(ref: string);
5
13
  }
14
+ /**
15
+ * Thrown when the processor is not available.
16
+ */
6
17
  export declare class ProcessorUnavailableError extends Error {
7
18
  code: number;
19
+ /**
20
+ * Creates a new instance of NotMatchingProcessorFound.
21
+ *
22
+ * @param {string} ref - The reference of the processor
23
+ */
24
+ constructor(ref: string);
25
+ }
26
+ /**
27
+ * Thrown when the middleware is not available.
28
+ */
29
+ export declare class MiddlewareUnavailableError extends Error {
30
+ code: number;
31
+ /**
32
+ * Creates a new instance of NotMatchingProcessorFound.
33
+ *
34
+ * @param {string} ref - The reference of the processor
35
+ */
8
36
  constructor(ref: string);
9
37
  }
package/dist/errors.js CHANGED
@@ -1,21 +1,29 @@
1
1
  "use strict";
2
- var __extends = (this && this.__extends) || (function () {
3
- var extendStatics = function (d, b) {
4
- extendStatics = Object.setPrototypeOf ||
5
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
- return extendStatics(d, b);
8
- };
9
- return function (d, b) {
10
- if (typeof b !== "function" && b !== null)
11
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
- extendStatics(d, b);
13
- function __() { this.constructor = d; }
14
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
- };
16
- })();
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
17
25
  Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.ProcessorUnavailableError = exports.NotMatchingProcessorFound = void 0;
26
+ exports.MiddlewareUnavailableError = exports.ProcessorUnavailableError = exports.NotMatchingProcessorFound = void 0;
19
27
  /*
20
28
  * Copyright (C) 2022 by Fonoster Inc (https://fonoster.com)
21
29
  * http://github.com/fonoster/routr
@@ -34,28 +42,55 @@ exports.ProcessorUnavailableError = exports.NotMatchingProcessorFound = void 0;
34
42
  * See the License for the specific language governing permissions and
35
43
  * limitations under the License.
36
44
  */
37
- var grpc = require("@grpc/grpc-js");
38
- var NotMatchingProcessorFound = /** @class */ (function (_super) {
39
- __extends(NotMatchingProcessorFound, _super);
40
- function NotMatchingProcessorFound(ref) {
41
- var _this = _super.call(this, "not matching processor found for request ref: " + ref) || this;
42
- _this.code = grpc.status.NOT_FOUND;
45
+ const grpc = __importStar(require("@grpc/grpc-js"));
46
+ /**
47
+ * Thrown when no backened matches the request.
48
+ */
49
+ class NotMatchingProcessorFound extends Error {
50
+ /**
51
+ * Creates a new instance of NotMatchingProcessorFound.
52
+ *
53
+ * @param {string} ref - The reference of the processor
54
+ */
55
+ constructor(ref) {
56
+ super(`not matching processor found for request ref: ${ref}`);
57
+ this.code = grpc.status.NOT_FOUND;
43
58
  // Set the prototype explicitly.
44
- Object.setPrototypeOf(_this, NotMatchingProcessorFound.prototype);
45
- return _this;
59
+ Object.setPrototypeOf(this, NotMatchingProcessorFound.prototype);
46
60
  }
47
- return NotMatchingProcessorFound;
48
- }(Error));
61
+ }
49
62
  exports.NotMatchingProcessorFound = NotMatchingProcessorFound;
50
- var ProcessorUnavailableError = /** @class */ (function (_super) {
51
- __extends(ProcessorUnavailableError, _super);
52
- function ProcessorUnavailableError(ref) {
53
- var _this = _super.call(this, "processor ref = " + ref + " is unavailable") || this;
54
- _this.code = grpc.status.UNAVAILABLE;
63
+ /**
64
+ * Thrown when the processor is not available.
65
+ */
66
+ class ProcessorUnavailableError extends Error {
67
+ /**
68
+ * Creates a new instance of NotMatchingProcessorFound.
69
+ *
70
+ * @param {string} ref - The reference of the processor
71
+ */
72
+ constructor(ref) {
73
+ super(`processor ref = ${ref} is unavailable`);
74
+ this.code = grpc.status.UNAVAILABLE;
55
75
  // Set the prototype explicitly.
56
- Object.setPrototypeOf(_this, NotMatchingProcessorFound.prototype);
57
- return _this;
76
+ Object.setPrototypeOf(this, ProcessorUnavailableError.prototype);
58
77
  }
59
- return ProcessorUnavailableError;
60
- }(Error));
78
+ }
61
79
  exports.ProcessorUnavailableError = ProcessorUnavailableError;
80
+ /**
81
+ * Thrown when the middleware is not available.
82
+ */
83
+ class MiddlewareUnavailableError extends Error {
84
+ /**
85
+ * Creates a new instance of NotMatchingProcessorFound.
86
+ *
87
+ * @param {string} ref - The reference of the processor
88
+ */
89
+ constructor(ref) {
90
+ super(`middleware ref = ${ref} is unavailable`);
91
+ this.code = grpc.status.UNAVAILABLE;
92
+ // Set the prototype explicitly.
93
+ Object.setPrototypeOf(this, MiddlewareUnavailableError.prototype);
94
+ }
95
+ }
96
+ exports.MiddlewareUnavailableError = MiddlewareUnavailableError;
@@ -1,21 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.findProcessor = exports.filter = exports.hasMethod = void 0;
4
- var errors_1 = require("./errors");
5
- var hasMethod = function (config, request) {
6
- return config.methods.includes(request.method);
7
- };
4
+ const errors_1 = require("./errors");
5
+ const hasMethod = (config, request) => config.methods.includes(request.method);
8
6
  exports.hasMethod = hasMethod;
9
7
  // TODO: We need a way to test the matching function
10
- var filter = function (request, config) {
11
- return exports.hasMethod(config, request)
12
- && (config.isFallback || config.matchFunc(request));
13
- };
8
+ const filter = (request, config) => (0, exports.hasMethod)(config, request) && (config === null || config === void 0 ? void 0 : config.matchFunc(request));
14
9
  exports.filter = filter;
15
- var findProcessor = function (list) {
16
- return function (request) {
17
- return list.find(function (config) { return exports.filter(request, config); })
18
- || new errors_1.NotMatchingProcessorFound(request.ref);
19
- };
20
- };
10
+ const findProcessor = (list) => (request) => list.find((config) => (0, exports.filter)(request, config)) ||
11
+ new errors_1.NotMatchingProcessorFound(request === null || request === void 0 ? void 0 : request.ref);
21
12
  exports.findProcessor = findProcessor;
@@ -1,6 +1,13 @@
1
- import { MessageRequest, ProcessorConfig } from "@routr/common";
2
- import { NotMatchingProcessorFound, ProcessorUnavailableError } from "./errors";
3
- declare type CallbackErrors = NotMatchingProcessorFound | ProcessorUnavailableError | Error;
4
- declare type ProcessorCallback = (err: CallbackErrors, reponse?: MessageRequest) => void;
5
- export default function processor(configList: Array<ProcessorConfig>): (call: any, callback: ProcessorCallback) => void;
6
- export {};
1
+ import { ProcessorConfig } from "@routr/common";
2
+ import { RunProcessorParams } from "./types";
3
+ import { CommonTypes as CT } from "@routr/common";
4
+ /**
5
+ * Creates a new instance of Processor.
6
+ *
7
+ * @param {object} params - The parameters of the processor
8
+ * @return {Processor}
9
+ */
10
+ export default function processor(params: {
11
+ processors: ProcessorConfig[];
12
+ middlewares?: CT.MiddlewareConfig[];
13
+ }): (call: RunProcessorParams, callback: any) => void;
package/dist/processor.js CHANGED
@@ -21,31 +21,49 @@ Object.defineProperty(exports, "__esModule", { value: true });
21
21
  * See the License for the specific language governing permissions and
22
22
  * limitations under the License.
23
23
  */
24
- var find_processor_1 = require("./find_processor");
25
- var connections_1 = __importDefault(require("./connections"));
26
- var errors_1 = require("./errors");
27
- var grpc = require("@grpc/grpc-js");
28
- function processor(configList) {
29
- var connections = connections_1.default(configList);
24
+ const connections_1 = __importDefault(require("./connections"));
25
+ const run_processor_1 = require("./run_processor");
26
+ const run_middlewares_1 = require("./run_middlewares");
27
+ const logger_1 = require("@fonoster/logger");
28
+ const logger = (0, logger_1.getLogger)({ service: "dispatcher", filePath: __filename });
29
+ /**
30
+ * Creates a new instance of Processor.
31
+ *
32
+ * @param {object} params - The parameters of the processor
33
+ * @return {Processor}
34
+ */
35
+ function processor(params) {
36
+ const { processors, middlewares } = params;
37
+ const procConns = (0, connections_1.default)(processors);
38
+ const middConns = (0, connections_1.default)(middlewares);
30
39
  // Upstream request and callback
31
- return function (call, callback) {
32
- var request = call.request;
33
- var matchResult = find_processor_1.findProcessor(configList)(request);
34
- if ('ref' in matchResult) {
35
- var conn = connections.get(matchResult.ref);
36
- // Connects to downstream processor
37
- conn.processMessage(request, function (err, response) {
38
- if ((err === null || err === void 0 ? void 0 : err.code) === grpc.status.UNAVAILABLE) {
39
- // We aument the error to indicate which processor failed
40
- callback(new errors_1.ProcessorUnavailableError(matchResult.ref));
41
- return;
42
- }
43
- callback(err, response);
40
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
41
+ return (call, callback) => {
42
+ const { request } = call;
43
+ // Messages type reponse will not be sent to middleware chain
44
+ if (request.message.messageType === "responseType") {
45
+ return (0, run_processor_1.runProcessor)({
46
+ callback,
47
+ request,
48
+ processors,
49
+ connections: procConns
44
50
  });
45
51
  }
46
- else {
47
- callback(matchResult);
48
- }
52
+ (0, run_middlewares_1.runMiddlewares)({ callback, request, middlewares, connections: middConns })
53
+ .then((req) => {
54
+ // Since the chain was broken we need to skip the processor and return the updated request
55
+ if (req.message.messageType === "responseType") {
56
+ logger.silly("skipped processsing request", { ref: req.ref });
57
+ return callback(null, req);
58
+ }
59
+ (0, run_processor_1.runProcessor)({
60
+ callback,
61
+ request: req,
62
+ processors,
63
+ connections: procConns
64
+ });
65
+ })
66
+ .catch(callback);
49
67
  };
50
68
  }
51
69
  exports.default = processor;
@@ -0,0 +1,3 @@
1
+ import { RunMiddlewaresParams } from "./types";
2
+ import { MessageRequest } from "@routr/common";
3
+ export declare function runMiddlewares(params: RunMiddlewaresParams): Promise<MessageRequest>;
@@ -0,0 +1,107 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ Object.defineProperty(exports, "__esModule", { value: true });
35
+ exports.runMiddlewares = void 0;
36
+ /*
37
+ * Copyright (C) 2022 by Fonoster Inc (https://fonoster.com)
38
+ * http://github.com/fonoster/routr
39
+ *
40
+ * This file is part of Routr
41
+ *
42
+ * Licensed under the MIT License (the "License")
43
+ * you may not use this file except in compliance with
44
+ * the License. You may obtain a copy of the License at
45
+ *
46
+ * https://opensource.org/licenses/MIT
47
+ *
48
+ * Unless required by applicable law or agreed to in writing, software
49
+ * distributed under the License is distributed on an "AS IS" BASIS,
50
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
51
+ * See the License for the specific language governing permissions and
52
+ * limitations under the License.
53
+ */
54
+ const errors_1 = require("./errors");
55
+ const grpc = __importStar(require("@grpc/grpc-js"));
56
+ const logger_1 = require("@fonoster/logger");
57
+ const logger = (0, logger_1.getLogger)({ service: "dispatcher", filePath: __filename });
58
+ // eslint-disable-next-line require-jsdoc
59
+ function processMessage(middlewareRef, conn, request) {
60
+ return __awaiter(this, void 0, void 0, function* () {
61
+ return new Promise((resolve, reject) => {
62
+ conn.processMessage(request, (err, response) => {
63
+ return (err === null || err === void 0 ? void 0 : err.code) === grpc.status.UNAVAILABLE
64
+ ? reject(new errors_1.MiddlewareUnavailableError(middlewareRef))
65
+ : resolve(response);
66
+ });
67
+ });
68
+ });
69
+ }
70
+ // eslint-disable-next-line require-jsdoc
71
+ function runMiddlewares(params) {
72
+ return __awaiter(this, void 0, void 0, function* () {
73
+ const { connections, request, middlewares = [] } = params;
74
+ const req = Object.assign({}, request);
75
+ // eslint-disable-next-line no-async-promise-executor
76
+ return new Promise((resolve, rejects) => __awaiter(this, void 0, void 0, function* () {
77
+ // eslint-disable-next-line no-loops/no-loops
78
+ for (const midd of middlewares) {
79
+ logger.silly("sending request to middleware", {
80
+ ref: request.ref,
81
+ middlewareRef: midd.ref,
82
+ addr: midd.addr
83
+ });
84
+ // Get the next middleware
85
+ const conn = connections.get(midd.ref);
86
+ // Send message and re-insert response for next middleware
87
+ try {
88
+ req.message = (yield processMessage(midd.ref, conn, req))
89
+ .message;
90
+ if (req.message.messageType === "responseType") {
91
+ logger.silly("found messageType to be responseType and broke the chain", {
92
+ ref: request.ref,
93
+ middlewareRef: midd.ref,
94
+ addr: midd.addr
95
+ });
96
+ break;
97
+ }
98
+ }
99
+ catch (e) {
100
+ rejects(e);
101
+ }
102
+ }
103
+ resolve(req);
104
+ }));
105
+ });
106
+ }
107
+ exports.runMiddlewares = runMiddlewares;
@@ -0,0 +1,8 @@
1
+ import { RunProcessorParams } from "./types";
2
+ /**
3
+ * Runs the processor.
4
+ *
5
+ * @param {RunProcessorParams} params - The parameters for the run processor
6
+ * @return {Promise<any>}
7
+ */
8
+ export declare function runProcessor(params: RunProcessorParams): void;
@@ -0,0 +1,86 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.runProcessor = void 0;
30
+ /*
31
+ * Copyright (C) 2022 by Fonoster Inc (https://fonoster.com)
32
+ * http://github.com/fonoster/routr
33
+ *
34
+ * This file is part of Routr
35
+ *
36
+ * Licensed under the MIT License (the "License")
37
+ * you may not use this file except in compliance with
38
+ * the License. You may obtain a copy of the License at
39
+ *
40
+ * https://opensource.org/licenses/MIT
41
+ *
42
+ * Unless required by applicable law or agreed to in writing, software
43
+ * distributed under the License is distributed on an "AS IS" BASIS,
44
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
45
+ * See the License for the specific language governing permissions and
46
+ * limitations under the License.
47
+ */
48
+ const errors_1 = require("./errors");
49
+ const find_processor_1 = require("./find_processor");
50
+ const api_1 = __importDefault(require("@opentelemetry/api"));
51
+ const grpc = __importStar(require("@grpc/grpc-js"));
52
+ const logger_1 = require("@fonoster/logger");
53
+ const logger = (0, logger_1.getLogger)({ service: "dispatcher", filePath: __filename });
54
+ /**
55
+ * Runs the processor.
56
+ *
57
+ * @param {RunProcessorParams} params - The parameters for the run processor
58
+ * @return {Promise<any>}
59
+ */
60
+ function runProcessor(params) {
61
+ const currentSpan = api_1.default.trace.getSpan(api_1.default.context.active());
62
+ // display traceid in the terminal
63
+ logger.silly(`traceid: ${currentSpan === null || currentSpan === void 0 ? void 0 : currentSpan.spanContext().traceId}`);
64
+ const tracer = api_1.default.trace.getTracer("routr-tracer");
65
+ const span = tracer.startSpan("server.js:sayHello()", { kind: 1 });
66
+ span.addEvent("invoking sayHello() to...");
67
+ const { callback, connections, processors, request } = params;
68
+ const matchResult = (0, find_processor_1.findProcessor)(processors)(request);
69
+ if ("code" in matchResult) {
70
+ return callback(matchResult);
71
+ }
72
+ logger.silly("forwarding request to processor", {
73
+ processorRef: matchResult.ref
74
+ });
75
+ const conn = connections.get(matchResult.ref);
76
+ // Connects to downstream processor
77
+ conn.processMessage(request, (err, response) => {
78
+ if ((err === null || err === void 0 ? void 0 : err.code) === grpc.status.UNAVAILABLE) {
79
+ // We augment the error to indicate which processor failed
80
+ callback(new errors_1.ProcessorUnavailableError(matchResult.ref));
81
+ return;
82
+ }
83
+ callback(err, response);
84
+ });
85
+ }
86
+ exports.runProcessor = runProcessor;
package/dist/runner.js CHANGED
@@ -22,12 +22,16 @@ Object.defineProperty(exports, "__esModule", { value: true });
22
22
  * See the License for the specific language governing permissions and
23
23
  * limitations under the License.
24
24
  */
25
- var service_1 = __importDefault(require("./service"));
26
- var get_config_1 = require("./config/get_config");
27
- var result = get_config_1.getConfig(process.env.CONFIG_PATH);
28
- if (result._tag === 'Right') {
29
- service_1.default(result.right);
25
+ const service_1 = __importDefault(require("./service"));
26
+ const get_config_1 = require("./config/get_config");
27
+ const common_1 = require("@routr/common");
28
+ const logger_1 = require("@fonoster/logger");
29
+ const logger = (0, logger_1.getLogger)({ service: "dispatcher", filePath: __filename });
30
+ common_1.Assertions.assertEnvsAreSet(["CONFIG_PATH"]);
31
+ const result = (0, get_config_1.getConfig)(process.env.CONFIG_PATH);
32
+ if (result._tag === "Right") {
33
+ (0, service_1.default)(result.right);
30
34
  }
31
35
  else {
32
- console.log(result.left);
36
+ logger.error(result.left);
33
37
  }
package/dist/service.d.ts CHANGED
@@ -1,2 +1,7 @@
1
1
  import { MessageDispatcherConfig } from "./types";
2
- export default function MessageDispatcher(config: MessageDispatcherConfig): void;
2
+ /**
3
+ * Creates a service that can be used to dispatch messages to the backend processors.
4
+ *
5
+ * @param {MessageDispatcherConfig} config - Configuration for the dispatcher
6
+ */
7
+ export default function messageDispatcher(config: MessageDispatcherConfig): void;
package/dist/service.js CHANGED
@@ -1,9 +1,34 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- var common_1 = require("@routr/common");
4
- var util_1 = require("./util");
5
- function MessageDispatcher(config) {
6
- var bindAddr = config.bindAddr, processors = config.processors;
7
- common_1.createService(util_1.getServiceInfo(bindAddr, processors));
3
+ /*
4
+ * Copyright (C) 2022 by Fonoster Inc (https://fonoster.com)
5
+ * http://github.com/fonoster/routr
6
+ *
7
+ * This file is part of Routr
8
+ *
9
+ * Licensed under the MIT License (the "License")
10
+ * you may not use this file except in compliance with
11
+ * the License. You may obtain a copy of the License at
12
+ *
13
+ * https://opensource.org/licenses/MIT
14
+ *
15
+ * Unless required by applicable law or agreed to in writing, software
16
+ * distributed under the License is distributed on an "AS IS" BASIS,
17
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ * See the License for the specific language governing permissions and
19
+ * limitations under the License.
20
+ */
21
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
22
+ require("./tracer").init("dispatcher");
23
+ const common_1 = require("@routr/common");
24
+ const util_1 = require("./util");
25
+ /**
26
+ * Creates a service that can be used to dispatch messages to the backend processors.
27
+ *
28
+ * @param {MessageDispatcherConfig} config - Configuration for the dispatcher
29
+ */
30
+ function messageDispatcher(config) {
31
+ const { bindAddr, processors, middlewares } = config;
32
+ (0, common_1.createService)((0, util_1.getServiceInfo)(bindAddr, { processors, middlewares }));
8
33
  }
9
- exports.default = MessageDispatcher;
34
+ exports.default = messageDispatcher;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * This function registers the instrumentations for the service.
3
+ *
4
+ * @param {string} serviceName - The name of the service.
5
+ * @return {Tracer} The tracer object.
6
+ */
7
+ export declare function init(serviceName: string): import("@opentelemetry/api").Tracer;
package/dist/tracer.js ADDED
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.init = void 0;
7
+ /*
8
+ * Copyright (C) 2022 by Fonoster Inc (https://fonoster.com)
9
+ * http://github.com/fonoster/routr
10
+ *
11
+ * This file is part of Routr
12
+ *
13
+ * Licensed under the MIT License (the "License")
14
+ * you may not use this file except in compliance with
15
+ * the License. You may obtain a copy of the License at
16
+ *
17
+ * https://opensource.org/licenses/MIT
18
+ *
19
+ * Unless required by applicable law or agreed to in writing, software
20
+ * distributed under the License is distributed on an "AS IS" BASIS,
21
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22
+ * See the License for the specific language governing permissions and
23
+ * limitations under the License.
24
+ */
25
+ const api_1 = __importDefault(require("@opentelemetry/api"));
26
+ const instrumentation_1 = require("@opentelemetry/instrumentation");
27
+ const sdk_trace_node_1 = require("@opentelemetry/sdk-trace-node");
28
+ const resources_1 = require("@opentelemetry/resources");
29
+ const semantic_conventions_1 = require("@opentelemetry/semantic-conventions");
30
+ const sdk_trace_base_1 = require("@opentelemetry/sdk-trace-base");
31
+ const exporter_jaeger_1 = require("@opentelemetry/exporter-jaeger");
32
+ const instrumentation_grpc_1 = require("@opentelemetry/instrumentation-grpc");
33
+ /**
34
+ * This function registers the instrumentations for the service.
35
+ *
36
+ * @param {string} serviceName - The name of the service.
37
+ * @return {Tracer} The tracer object.
38
+ */
39
+ function init(serviceName) {
40
+ const provider = new sdk_trace_node_1.NodeTracerProvider({
41
+ resource: new resources_1.Resource({
42
+ [semantic_conventions_1.SemanticResourceAttributes.SERVICE_NAME]: serviceName
43
+ })
44
+ });
45
+ const exporter = new exporter_jaeger_1.JaegerExporter();
46
+ provider.addSpanProcessor(new sdk_trace_base_1.SimpleSpanProcessor(exporter));
47
+ provider.register();
48
+ (0, instrumentation_1.registerInstrumentations)({
49
+ instrumentations: [new instrumentation_grpc_1.GrpcInstrumentation()]
50
+ });
51
+ return api_1.default.trace.getTracer("routr-tracer");
52
+ }
53
+ exports.init = init;
package/dist/types.d.ts CHANGED
@@ -1,8 +1,27 @@
1
- import { ProcessorConfig } from "@routr/common";
1
+ import { MessageRequest, ProcessorConfig, CommonTypes as CT } from "@routr/common";
2
+ import { NotMatchingProcessorFound, ProcessorUnavailableError } from "./errors";
2
3
  export interface MessageDispatcherConfig {
3
4
  bindAddr: string;
4
- processors: Array<ProcessorConfig>;
5
+ processors: ProcessorConfig[];
6
+ middlewares: CT.MiddlewareConfig[];
5
7
  }
6
8
  export interface ProcessorGPRCConnection {
7
- processMessage: (request: unknown, callback: Function) => void;
9
+ processMessage: (request: unknown, callback: CT.GrpcCallback) => void;
10
+ }
11
+ export declare type CallbackErrors = NotMatchingProcessorFound | ProcessorUnavailableError | Error | {
12
+ code: number;
13
+ message?: string;
14
+ } | null;
15
+ export declare type ProcessorCallback = (err: CallbackErrors, reponse?: MessageRequest) => void;
16
+ export interface RunProcessorParams {
17
+ callback: CT.GrpcCallback;
18
+ connections: Map<string, ProcessorGPRCConnection>;
19
+ processors: ProcessorConfig[];
20
+ request: MessageRequest;
21
+ }
22
+ export interface RunMiddlewaresParams {
23
+ callback: CT.GrpcCallback;
24
+ connections: Map<string, ProcessorGPRCConnection>;
25
+ middlewares: CT.MiddlewareConfig[];
26
+ request: MessageRequest;
8
27
  }
package/dist/util.d.ts CHANGED
@@ -1,2 +1,12 @@
1
- import { ProcessorConfig, ServiceInfo } from "@routr/common";
2
- export declare function getServiceInfo(bindAddr: string, processors: ProcessorConfig[]): ServiceInfo;
1
+ import { ProcessorConfig, ServiceInfo, CommonTypes as CT } from "@routr/common";
2
+ /**
3
+ * Gets the service metadata for the dispatcher.
4
+ *
5
+ * @param {string} bindAddr - The address to bind to
6
+ * @param {object} backends - The backends to use
7
+ * @return {ServiceInfo}
8
+ */
9
+ export declare function getServiceInfo(bindAddr: string, backends: {
10
+ middlewares: CT.MiddlewareConfig[];
11
+ processors: ProcessorConfig[];
12
+ }): ServiceInfo;
package/dist/util.js CHANGED
@@ -22,15 +22,23 @@ exports.getServiceInfo = void 0;
22
22
  * See the License for the specific language governing permissions and
23
23
  * limitations under the License.
24
24
  */
25
- var processor_1 = __importDefault(require("./processor"));
26
- var common_1 = require("@routr/common");
27
- function getServiceInfo(bindAddr, processors) {
25
+ const processor_1 = __importDefault(require("./processor"));
26
+ const common_1 = require("@routr/common");
27
+ /**
28
+ * Gets the service metadata for the dispatcher.
29
+ *
30
+ * @param {string} bindAddr - The address to bind to
31
+ * @param {object} backends - The backends to use
32
+ * @return {ServiceInfo}
33
+ */
34
+ function getServiceInfo(bindAddr, backends) {
28
35
  return {
29
36
  name: "dispatcher",
30
- bindAddr: bindAddr,
37
+ bindAddr,
38
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
31
39
  service: common_1.PROCESSOR_OBJECT_PROTO.Processor.service,
32
40
  handlers: {
33
- processMessage: processor_1.default(processors)
41
+ processMessage: (0, processor_1.default)(backends)
34
42
  }
35
43
  };
36
44
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@routr/dispatcher",
3
- "version": "2.0.5-alpha.2",
3
+ "version": "2.0.5-alpha.21",
4
4
  "description": "Receives SIP messages and forwards them to the corresponding Message Processor",
5
5
  "author": "Pedro Sanders <psanders@fonoster.com>",
6
6
  "homepage": "https://github.com/fonoster/routr#readme",
@@ -25,7 +25,17 @@
25
25
  "access": "public"
26
26
  },
27
27
  "dependencies": {
28
- "@routr/common": "^2.0.5-alpha.2",
28
+ "@fonoster/logger": "0.3.17-alpha.2",
29
+ "@grpc/grpc-js": "^1.5.9",
30
+ "@opentelemetry/api": "^1.0.4",
31
+ "@opentelemetry/exporter-jaeger": "^1.0.4",
32
+ "@opentelemetry/instrumentation": "^0.27.0",
33
+ "@opentelemetry/instrumentation-grpc": "^0.27.0",
34
+ "@opentelemetry/resources": "^1.0.4",
35
+ "@opentelemetry/sdk-trace-base": "^1.0.4",
36
+ "@opentelemetry/sdk-trace-node": "^1.0.4",
37
+ "@opentelemetry/semantic-conventions": "^1.0.4",
38
+ "@routr/common": "^2.0.5-alpha.21",
29
39
  "ajv": "^6.12.6",
30
40
  "fp-ts": "^2.11.8"
31
41
  },
@@ -36,5 +46,5 @@
36
46
  "bugs": {
37
47
  "url": "https://github.com/fonoster/routr/issues"
38
48
  },
39
- "gitHead": "3570106be9a96cb6672de4a850a377bfa7d9bb3e"
49
+ "gitHead": "904559d8d4694e16d63f553704345a987dc0d93a"
40
50
  }