@routr/simpledata 2.0.8-alpha.9 → 2.0.13

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.
package/dist/api.d.ts CHANGED
@@ -3,14 +3,14 @@ import { CommonConnect as CC } from "@routr/common";
3
3
  /**
4
4
  * Enclosure with method to obtain a resource by reference.
5
5
  *
6
- * @param {Resource[]} resources - the resources to search from
6
+ * @param {CC.ConnectModel[]} resources - the resources to search from
7
7
  * @return {Function } enclosed method with actual "get" logic
8
8
  */
9
- export declare function get(resources: CC.Resource[]): (call: CT.GrpcCall, callback: CT.GrpcCallback) => void;
9
+ export declare function get(resources: CC.ConnectModel[]): (call: CT.GrpcCall, callback: CT.GrpcCallback) => void;
10
10
  /**
11
11
  * Enclosure with method to obtain a resource with a query.
12
12
  *
13
- * @param {Resource[]} resources - the resources to search from
14
- * @return {Function } enclosed method with actual "find" logic
13
+ * @param {CC.ConnectModel[]} resources - the resources to search from
14
+ * @return {Function} enclosed method with actual "findBy" logic
15
15
  */
16
- export declare function findBy(resources: CC.Resource[]): (call: CT.GrpcCall, callback: CT.GrpcCallback) => void;
16
+ export declare function findBy(resources: CC.ConnectModel[]): (call: CT.GrpcCall, callback: CT.GrpcCallback) => void;
package/dist/api.js CHANGED
@@ -1,34 +1,8 @@
1
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
2
  Object.defineProperty(exports, "__esModule", { value: true });
29
3
  exports.findBy = exports.get = void 0;
30
4
  /*
31
- * Copyright (C) 2022 by Fonoster Inc (https://fonoster.com)
5
+ * Copyright (C) 2023 by Fonoster Inc (https://fonoster.com)
32
6
  * http://github.com/fonoster/routr
33
7
  *
34
8
  * This file is part of Routr
@@ -45,66 +19,58 @@ exports.findBy = exports.get = void 0;
45
19
  * See the License for the specific language governing permissions and
46
20
  * limitations under the License.
47
21
  */
48
- const errors_1 = require("./errors");
49
- const utils_1 = require("./utils");
22
+ const pb_util_1 = require("pb-util");
50
23
  const common_1 = require("@routr/common");
51
- const protobufUtil = __importStar(require("pb-util"));
52
- const jsonpath_1 = __importDefault(require("jsonpath"));
53
- const jsonToStruct = protobufUtil.struct.encode;
24
+ const common_2 = require("@routr/common");
54
25
  /**
55
26
  * Enclosure with method to obtain a resource by reference.
56
27
  *
57
- * @param {Resource[]} resources - the resources to search from
28
+ * @param {CC.ConnectModel[]} resources - the resources to search from
58
29
  * @return {Function } enclosed method with actual "get" logic
59
30
  */
60
31
  function get(resources) {
61
32
  return (call, callback) => {
62
33
  if (resources == null || resources.length === 0) {
63
- return callback(new errors_1.ResourceNotFound(call.request.ref), null);
34
+ return callback(new common_1.CommonErrors.ResourceNotFoundError(call.request.ref), null);
64
35
  }
65
36
  if (call.request.ref == null) {
66
- return callback(new errors_1.BadRequest("parameter ref is required"), null);
37
+ return callback(new common_1.CommonErrors.BadRequestError("parameter ref is required"), null);
67
38
  }
68
- const resource = common_1.Helper.deepCopy(resources.find((r) => r.ref === call.request.ref));
39
+ const resource = common_2.Helper.deepCopy(resources.find((r) => r.ref === call.request.ref));
69
40
  // Serialize to protobuf
70
- if (resource)
71
- resource.spec = jsonToStruct(resource.spec);
41
+ if (resource === null || resource === void 0 ? void 0 : resource.extended) {
42
+ resource.extended = pb_util_1.struct.encode(resource.extended);
43
+ }
72
44
  resource
73
45
  ? callback(null, resource)
74
- : callback(new errors_1.ResourceNotFound(call.request.ref), null);
46
+ : callback(new common_1.CommonErrors.ResourceNotFoundError(call.request.ref), null);
75
47
  };
76
48
  }
77
49
  exports.get = get;
78
50
  /**
79
51
  * Enclosure with method to obtain a resource with a query.
80
52
  *
81
- * @param {Resource[]} resources - the resources to search from
82
- * @return {Function } enclosed method with actual "find" logic
53
+ * @param {CC.ConnectModel[]} resources - the resources to search from
54
+ * @return {Function} enclosed method with actual "findBy" logic
83
55
  */
84
56
  function findBy(resources) {
85
57
  return (call, callback) => {
86
- const filteredResources = resources.filter((resource) => { var _a, _b; return ((_a = resource.kind) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === ((_b = call.request.kind) === null || _b === void 0 ? void 0 : _b.toLowerCase()); });
87
- if (filteredResources == null || filteredResources.length === 0) {
88
- return callback(new errors_1.ResourceNotFound(""), null);
89
- }
90
- const queryObject = (0, utils_1.createQuery)(call.request);
91
- if (queryObject instanceof errors_1.BadRequest) {
92
- return callback(queryObject, null);
93
- }
94
- const queryResult = common_1.Helper.deepCopy(jsonpath_1.default.query(filteredResources, queryObject.query));
95
- try {
96
- queryResult.forEach((resource) => {
97
- // Serialize to protobuf
98
- resource.spec = jsonToStruct(resource.spec);
99
- return resource;
100
- });
101
- callback(null, {
102
- resources: queryResult
103
- });
104
- }
105
- catch (e) {
106
- callback(new errors_1.BadRequest(`invalid JSONPath expression: ${queryObject.query}`), null);
58
+ if (resources.length === 0) {
59
+ return callback(new common_1.CommonErrors.ResourceNotFoundError(""), null);
107
60
  }
61
+ const { request } = call;
62
+ const queryResult = resources.filter((r) => `${r[request.fieldName]}` ===
63
+ `${request.fieldValue}`);
64
+ queryResult.forEach((resource) => {
65
+ // Serialize to protobuf
66
+ if (resource.extended) {
67
+ resource.extended = pb_util_1.struct.encode(resource.extended);
68
+ }
69
+ return resource;
70
+ });
71
+ callback(null, {
72
+ items: queryResult
73
+ });
108
74
  };
109
75
  }
110
76
  exports.findBy = findBy;
package/dist/envs.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export declare const BIND_ADDR: string;
2
+ export declare const PATH_TO_RESOURCES: string;
package/dist/envs.js ADDED
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ var _a;
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.PATH_TO_RESOURCES = exports.BIND_ADDR = void 0;
5
+ /*
6
+ * Copyright (C) 2023 by Fonoster Inc (https://fonoster.com)
7
+ * http://github.com/fonoster
8
+ *
9
+ * This file is part of Routr.
10
+ *
11
+ * Licensed under the MIT License (the "License");
12
+ * you may not use this file except in compliance with
13
+ * the License. You may obtain a copy of the License at
14
+ *
15
+ * https://opensource.org/licenses/MIT
16
+ *
17
+ * Unless required by applicable law or agreed to in writing, software
18
+ * distributed under the License is distributed on an "AS IS" BASIS,
19
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ * See the License for the specific language governing permissions and
21
+ * limitations under the License.
22
+ */
23
+ const common_1 = require("@routr/common");
24
+ common_1.Assertions.assertEnvsAreSet(["PATH_TO_RESOURCES"]);
25
+ exports.BIND_ADDR = (_a = process.env.BIND_ADDR) !== null && _a !== void 0 ? _a : "0.0.0.0:51907";
26
+ exports.PATH_TO_RESOURCES = process.env.PATH_TO_RESOURCES;
@@ -0,0 +1,9 @@
1
+ import { CommonConnect as CC } from "@routr/common";
2
+ export declare const getLoader: (kind: string) => typeof agentLoader | typeof domainLoader | typeof peerLoader | typeof numberLoader | typeof trunkLoader | typeof credentialsLoader | typeof aclLoader;
3
+ export declare function agentLoader(config: CC.UserConfig, list: CC.UserConfig[]): CC.Agent;
4
+ export declare function domainLoader(config: CC.UserConfig, list: CC.UserConfig[]): CC.Domain;
5
+ export declare function peerLoader(config: CC.UserConfig, list: CC.UserConfig[]): CC.Peer;
6
+ export declare function numberLoader(config: CC.UserConfig, list: CC.UserConfig[]): CC.INumber;
7
+ export declare function trunkLoader(config: CC.UserConfig, list: CC.UserConfig[]): CC.Trunk;
8
+ export declare function credentialsLoader(config: CC.UserConfig): CC.Credentials;
9
+ export declare function aclLoader(config: CC.UserConfig): CC.AccessControlList;
@@ -0,0 +1,118 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.aclLoader = exports.credentialsLoader = exports.trunkLoader = exports.numberLoader = exports.peerLoader = exports.domainLoader = exports.agentLoader = exports.getLoader = void 0;
4
+ /*
5
+ * Copyright (C) 2023 by Fonoster Inc (https://fonoster.com)
6
+ * http://github.com/fonoster
7
+ *
8
+ * This file is part of Routr.
9
+ *
10
+ * Licensed under the MIT License (the "License");
11
+ * you may not use this file except in compliance with
12
+ * the License. You may obtain a copy of the License at
13
+ *
14
+ * https://opensource.org/licenses/MIT
15
+ *
16
+ * Unless required by applicable law or agreed to in writing, software
17
+ * distributed under the License is distributed on an "AS IS" BASIS,
18
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ * See the License for the specific language governing permissions and
20
+ * limitations under the License.
21
+ */
22
+ /* eslint-disable require-jsdoc */
23
+ const logger_1 = require("@fonoster/logger");
24
+ const common_1 = require("@routr/common");
25
+ const logger = (0, logger_1.getLogger)({ service: "simpledata", filePath: __filename });
26
+ const findByRef = (ref, list) => {
27
+ const resource = list.find((r) => r.ref === ref);
28
+ if (ref != null && resource == null) {
29
+ logger.error(`the resource with ref ${ref} does not exist in the configuration file; exiting`);
30
+ process.exit(1);
31
+ }
32
+ return resource ? (0, exports.getLoader)(resource.kind)(resource, list) : null;
33
+ };
34
+ const getLoader = (kind) => {
35
+ switch (kind) {
36
+ case common_1.CommonConnect.Kind.AGENT:
37
+ return agentLoader;
38
+ case common_1.CommonConnect.Kind.DOMAIN:
39
+ return domainLoader;
40
+ case common_1.CommonConnect.Kind.PEER:
41
+ return peerLoader;
42
+ case common_1.CommonConnect.Kind.NUMBER:
43
+ return numberLoader;
44
+ case common_1.CommonConnect.Kind.TRUNK:
45
+ return trunkLoader;
46
+ case common_1.CommonConnect.Kind.CREDENTIALS:
47
+ return credentialsLoader;
48
+ case common_1.CommonConnect.Kind.ACL:
49
+ return aclLoader;
50
+ }
51
+ };
52
+ exports.getLoader = getLoader;
53
+ function agentLoader(config, list) {
54
+ if (config.kind !== common_1.CommonConnect.Kind.AGENT)
55
+ throw new Error("invalid resource type `Agent`");
56
+ const agent = common_1.CommonConnect.mapToAgent(config);
57
+ agent.domain = findByRef(config.spec.domainRef, list);
58
+ agent.credentials = findByRef(config.spec.credentialsRef, list);
59
+ return agent;
60
+ }
61
+ exports.agentLoader = agentLoader;
62
+ function domainLoader(config, list) {
63
+ var _a;
64
+ if (config.kind !== common_1.CommonConnect.Kind.DOMAIN)
65
+ throw new Error("invalid resource type `Domain`");
66
+ const egressPolicies = (_a = config.spec.context.egressPolicies) === null || _a === void 0 ? void 0 : _a.map((policy) => {
67
+ return {
68
+ rule: policy.rule,
69
+ numberRef: policy.numberRef,
70
+ number: findByRef(policy.numberRef, list)
71
+ };
72
+ });
73
+ const domain = common_1.CommonConnect.mapToDomain(config);
74
+ domain.egressPolicies = egressPolicies;
75
+ domain.accessControlList = findByRef(config.spec.accessControlListRef, list);
76
+ return domain;
77
+ }
78
+ exports.domainLoader = domainLoader;
79
+ function peerLoader(config, list) {
80
+ if (config.kind !== common_1.CommonConnect.Kind.PEER)
81
+ throw new Error("invalid resource type `Peer`");
82
+ const peer = common_1.CommonConnect.mapToPeer(config);
83
+ peer.credentials = findByRef(config.spec.credentialsRef, list);
84
+ return peer;
85
+ }
86
+ exports.peerLoader = peerLoader;
87
+ function numberLoader(config, list) {
88
+ if (config.kind !== common_1.CommonConnect.Kind.NUMBER)
89
+ throw new Error("invalid resource type `Number`");
90
+ const number = common_1.CommonConnect.mapToNumber(config);
91
+ number.trunk = findByRef(config.spec.trunkRef, list);
92
+ return number;
93
+ }
94
+ exports.numberLoader = numberLoader;
95
+ function trunkLoader(config, list) {
96
+ if (config.kind !== common_1.CommonConnect.Kind.TRUNK)
97
+ throw new Error("invalid resource type `Trunk`");
98
+ const inbound = config.spec.inbound;
99
+ const outbound = config.spec.outbound;
100
+ const trunk = common_1.CommonConnect.mapToTrunk(config);
101
+ trunk.inboundCredentials = findByRef(inbound.credentialsRef, list);
102
+ trunk.outboundCredentials = findByRef(outbound.credentialsRef, list);
103
+ trunk.accessControlList = findByRef(inbound.accessControlListRef, list);
104
+ return trunk;
105
+ }
106
+ exports.trunkLoader = trunkLoader;
107
+ function credentialsLoader(config) {
108
+ if (config.kind !== common_1.CommonConnect.Kind.CREDENTIALS)
109
+ throw new Error("invalid resource type `Credentials`");
110
+ return common_1.CommonConnect.mapToCredentials(config);
111
+ }
112
+ exports.credentialsLoader = credentialsLoader;
113
+ function aclLoader(config) {
114
+ if (config.kind !== common_1.CommonConnect.Kind.ACL)
115
+ throw new Error("invalid resource type `AccessControlList`");
116
+ return common_1.CommonConnect.mapToACL(config);
117
+ }
118
+ exports.aclLoader = aclLoader;
package/dist/runner.js CHANGED
@@ -3,10 +3,9 @@
3
3
  var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  return (mod && mod.__esModule) ? mod : { "default": mod };
5
5
  };
6
- var _a;
7
6
  Object.defineProperty(exports, "__esModule", { value: true });
8
7
  /*
9
- * Copyright (C) 2022 by Fonoster Inc (https://fonoster.com)
8
+ * Copyright (C) 2023 by Fonoster Inc (https://fonoster.com)
10
9
  * http://github.com/fonoster/routr
11
10
  *
12
11
  * This file is part of Routr
@@ -26,16 +25,15 @@ Object.defineProperty(exports, "__esModule", { value: true });
26
25
  // eslint-disable-next-line @typescript-eslint/no-var-requires
27
26
  require("./tracer").init("simpleauth");
28
27
  const service_1 = __importDefault(require("./service"));
29
- const utils_1 = __importDefault(require("./utils"));
30
28
  const common_1 = require("@routr/common");
31
29
  const logger_1 = require("@fonoster/logger");
30
+ const envs_1 = require("./envs");
32
31
  const logger = (0, logger_1.getLogger)({ service: "simpledata", filePath: __filename });
33
- common_1.Assertions.assertEnvsAreSet(["PATH_TO_SCHEMAS", "PATH_TO_RESOURCES"]);
34
- const resources = (0, utils_1.default)(process.env.PATH_TO_SCHEMAS, process.env.PATH_TO_RESOURCES);
32
+ common_1.Assertions.assertEnvsAreSet(["PATH_TO_RESOURCES"]);
35
33
  try {
36
34
  (0, service_1.default)({
37
- bindAddr: (_a = process.env.BIND_ADDR) !== null && _a !== void 0 ? _a : "0.0.0.0:51907",
38
- resources
35
+ bindAddr: envs_1.BIND_ADDR,
36
+ pathToResources: envs_1.PATH_TO_RESOURCES
39
37
  });
40
38
  }
41
39
  catch (e) {
package/dist/service.js CHANGED
@@ -24,10 +24,10 @@ var __importStar = (this && this.__importStar) || function (mod) {
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
26
  const common_1 = require("@routr/common");
27
- const utils_1 = require("./utils");
27
+ const utils_1 = __importStar(require("./utils"));
28
28
  const api_1 = require("./api");
29
- const grpc = __importStar(require("@grpc/grpc-js"));
30
29
  const logger_1 = require("@fonoster/logger");
30
+ const grpc = __importStar(require("@grpc/grpc-js"));
31
31
  const logger = (0, logger_1.getLogger)({ service: "simpledata", filePath: __filename });
32
32
  /**
33
33
  * Starts a new simple data service.
@@ -38,13 +38,25 @@ function simpleDataService(config) {
38
38
  const { bindAddr } = config;
39
39
  logger.info("starting routr service", { bindAddr, name: "simpledata" });
40
40
  const server = new grpc.Server();
41
- server.addService(common_1.CommonConnect.RESOURCES_PROTO.v2draft1.Resources.service, {
42
- get: (0, api_1.get)(config.resources),
43
- findBy: (0, api_1.findBy)(config.resources),
44
- delete: utils_1.nyi,
45
- update: utils_1.nyi,
46
- create: utils_1.nyi,
47
- list: utils_1.nyi
41
+ const kinds = [
42
+ common_1.CommonConnect.Kind.AGENT,
43
+ common_1.CommonConnect.Kind.ACL,
44
+ common_1.CommonConnect.Kind.CREDENTIALS,
45
+ common_1.CommonConnect.Kind.NUMBER,
46
+ common_1.CommonConnect.Kind.TRUNK,
47
+ common_1.CommonConnect.Kind.PEER,
48
+ common_1.CommonConnect.Kind.DOMAIN
49
+ ];
50
+ kinds.forEach((kind) => {
51
+ const resources = (0, utils_1.default)(config.pathToResources, kind);
52
+ server.addService(common_1.CommonConnect.createConnectService(kind), {
53
+ get: (0, api_1.get)(resources),
54
+ findBy: (0, api_1.findBy)(resources),
55
+ delete: utils_1.nyi,
56
+ update: utils_1.nyi,
57
+ create: utils_1.nyi,
58
+ list: utils_1.nyi
59
+ });
48
60
  });
49
61
  server.bindAsync(config.bindAddr, grpc.ServerCredentials.createInsecure(), () => {
50
62
  server.start();
package/dist/tracer.js CHANGED
@@ -5,7 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.init = void 0;
7
7
  /*
8
- * Copyright (C) 2022 by Fonoster Inc (https://fonoster.com)
8
+ * Copyright (C) 2023 by Fonoster Inc (https://fonoster.com)
9
9
  * http://github.com/fonoster/routr
10
10
  *
11
11
  * This file is part of Routr
package/dist/types.d.ts CHANGED
@@ -1,5 +1,4 @@
1
- import { CommonConnect as CC } from "@routr/common";
2
1
  export interface SimpleDataConfig {
3
2
  bindAddr: string;
4
- resources: Array<CC.Resource>;
3
+ pathToResources: string;
5
4
  }
package/dist/utils.d.ts CHANGED
@@ -1,25 +1,12 @@
1
- import { BadRequest } from "./errors";
2
- import { CommonTypes as CT } from "@routr/common";
3
- import { CommonConnect as CC } from "@routr/common";
4
- /**
5
- * Creates a list of validators from the given schemas.
6
- *
7
- * @param {string} path - the path to the resource
8
- * @return {Validator} - a list of validators from the path
9
- */
10
- export declare function createValidators(path: string): Map<string, (resource: CC.Resource) => unknown>;
1
+ import { CommonConnect as CC, CommonTypes as CT } from "@routr/common";
11
2
  /**
12
3
  * Loads a list of resources from a file.
13
4
  *
14
- * @param {string} validatorsPath - the path to the validators
15
5
  * @param {string} resourcesPath - the path to the resources
6
+ * @param {string} kind - the kind of resource to load
16
7
  * @return {Resource[]} the loaded resources
17
8
  */
18
- export default function loadResources(validatorsPath: string, resourcesPath: string): CC.Resource[];
19
- export declare function createQuery(request: CC.FindParameters): {
20
- request: CC.FindParameters;
21
- query: string;
22
- } | BadRequest;
9
+ export default function loadResources(resourcesPath: string, kind?: CC.KindWithoutUnknown): CC.ConnectModel[];
23
10
  /**
24
11
  * Returns UnimplementedError via callback.
25
12
  *
package/dist/utils.js CHANGED
@@ -1,34 +1,8 @@
1
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
2
  Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.nyi = exports.createQuery = exports.createValidators = void 0;
3
+ exports.nyi = void 0;
30
4
  /*
31
- * Copyright (C) 2022 by Fonoster Inc (https://fonoster.com)
5
+ * Copyright (C) 2023 by Fonoster Inc (https://fonoster.com)
32
6
  * http://github.com/fonoster/routr
33
7
  *
34
8
  * This file is part of Routr
@@ -45,92 +19,53 @@ exports.nyi = exports.createQuery = exports.createValidators = void 0;
45
19
  * See the License for the specific language governing permissions and
46
20
  * limitations under the License.
47
21
  */
48
- const errors_1 = require("./errors");
49
- const ajv_1 = __importDefault(require("ajv"));
50
22
  const logger_1 = require("@fonoster/logger");
51
23
  const common_1 = require("@routr/common");
52
- const protobufUtil = __importStar(require("pb-util"));
53
- const jsonFromStruct = protobufUtil.struct.decode;
24
+ const fs_1 = require("fs");
25
+ const loaders_1 = require("./loaders");
54
26
  const logger = (0, logger_1.getLogger)({ service: "simpledata", filePath: __filename });
55
- const findCriteriaMap = {};
56
- findCriteriaMap[common_1.CommonConnect.FindCriteria.FIND_AGENT_BY_USERNAME] = (parameters) => `$..[?(@.spec.username=='${parameters.username}')]`;
57
- findCriteriaMap[common_1.CommonConnect.FindCriteria.FIND_CREDENTIAL_BY_REFERENCE] = (parameters) => `$..[?(@.ref=='${parameters.ref}')]`;
58
- findCriteriaMap[common_1.CommonConnect.FindCriteria.FIND_DOMAIN_BY_DOMAINURI] = (parameters) => `$..[?(@.spec.context.domainUri=='${parameters.domainUri}')]`;
59
- findCriteriaMap[common_1.CommonConnect.FindCriteria.FIND_NUMBER_BY_TELURL] = (parameters) => `$..[?(@.spec.location.telUrl=="${parameters.telUrl}")]`;
60
- findCriteriaMap[common_1.CommonConnect.FindCriteria.FIND_TRUNKS_WITH_SEND_REGISTER] = () => "$..[?(@.spec.outbound.sendRegister==true)]";
61
- findCriteriaMap[common_1.CommonConnect.FindCriteria.FIND_TRUNK_BY_REQUEST_URI] = (parameters) => `$..[?(@.spec.inbound.uri=="${parameters.requestUri}")]`;
62
- /**
63
- * Creates a list of validators from the given schemas.
64
- *
65
- * @param {string} path - the path to the resource
66
- * @return {Validator} - a list of validators from the path
67
- */
68
- function createValidators(path) {
69
- const validators = new Map();
70
- // eslint-disable-next-line @typescript-eslint/no-var-requires
71
- const files = require("fs").readdirSync(path);
72
- files.forEach((file) => {
73
- // eslint-disable-next-line @typescript-eslint/no-var-requires
74
- const schema = require(`${path}/${file}`);
75
- const ajv = new ajv_1.default();
76
- const validator = ajv.compile(schema);
77
- validators.set(schema.properties.kind.enum[0].toLowerCase(), validator);
78
- });
79
- return validators;
80
- }
81
- exports.createValidators = createValidators;
27
+ // Create function to validate reference exists for Agent
28
+ const checkReferences = (resources) => {
29
+ // Check that reference have not been duplicated
30
+ const references = resources.map((r) => r.ref);
31
+ const duplicates = references.filter((ref, index) => references.indexOf(ref) !== index);
32
+ if (duplicates.length > 0) {
33
+ logger.error(`found duplicated references: ${duplicates}; exiting`);
34
+ process.exit(1);
35
+ }
36
+ };
82
37
  /**
83
38
  * Loads a list of resources from a file.
84
39
  *
85
- * @param {string} validatorsPath - the path to the validators
86
40
  * @param {string} resourcesPath - the path to the resources
41
+ * @param {string} kind - the kind of resource to load
87
42
  * @return {Resource[]} the loaded resources
88
43
  */
89
- function loadResources(validatorsPath, resourcesPath) {
90
- const validators = createValidators(validatorsPath);
44
+ function loadResources(resourcesPath, kind) {
91
45
  const all = [];
92
- // eslint-disable-next-line @typescript-eslint/no-var-requires
93
- const files = require("fs").readdirSync(resourcesPath);
46
+ const files = (0, fs_1.readdirSync)(resourcesPath);
94
47
  files.forEach((file) => {
95
- // eslint-disable-next-line @typescript-eslint/no-var-requires
96
- const resources = require(`${resourcesPath}/${file}`);
48
+ const resources = common_1.Helper.readConfigFile(`${resourcesPath}/${file}`);
97
49
  resources.forEach((resource) => {
98
- // Check if is valid using jsonschema
99
- const validate = validators.get(resource.kind.toLocaleLowerCase());
100
- if (!validate) {
101
- logger.error(`unable to find validator for ${resource.kind}; exiting`);
102
- process.exit(1);
103
- }
104
- if (validate(resource)) {
105
- all.push(resource);
106
- }
107
- else {
108
- logger.error("found a bad resource: " +
109
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
110
- JSON.stringify(validate.errors[0].message));
50
+ resource.kind = resource.kind.toLowerCase();
51
+ // Assert the reference has no spaces
52
+ if (resource.ref.includes(" ")) {
53
+ logger.error(`resource type ${resource.kind} has spaces in the reference: "${resource.ref}"; exiting`);
111
54
  process.exit(1);
112
55
  }
56
+ all.push(resource);
113
57
  });
114
58
  });
115
- logger.verbose("loaded data resources", { total: all.length });
116
- return all;
59
+ // Referencial check
60
+ checkReferences(all);
61
+ // Convert to Resource
62
+ const allMapToResources = all
63
+ .filter((r) => !kind || r.kind.toLowerCase() == kind.toLowerCase())
64
+ .map((r) => (0, loaders_1.getLoader)(r.kind)(r, all));
65
+ logger.verbose("loaded data resources", { total: allMapToResources.length });
66
+ return allMapToResources;
117
67
  }
118
68
  exports.default = loadResources;
119
- // eslint-disable-next-line require-jsdoc
120
- function createQuery(request) {
121
- const findCriteria = request.criteria;
122
- if (!request.criteria || !request.kind || !request.parameters) {
123
- return new errors_1.BadRequest("createQuery request is missing 'criteria', 'kind', or 'parameters'");
124
- }
125
- if (!findCriteriaMap[findCriteria]) {
126
- return new errors_1.BadRequest(`invalid find criteria ${request.criteria}`);
127
- }
128
- return {
129
- query: findCriteriaMap[findCriteria](jsonFromStruct(request.parameters)),
130
- request
131
- };
132
- }
133
- exports.createQuery = createQuery;
134
69
  /**
135
70
  * Returns UnimplementedError via callback.
136
71
  *
@@ -138,6 +73,6 @@ exports.createQuery = createQuery;
138
73
  * @param {GrpcCallback} callback - the grpc callback
139
74
  */
140
75
  function nyi(call, callback) {
141
- callback(new errors_1.UnimplementedError());
76
+ callback(new common_1.CommonErrors.UnimplementedError());
142
77
  }
143
78
  exports.nyi = nyi;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@routr/simpledata",
3
- "version": "2.0.8-alpha.9",
3
+ "version": "2.0.13",
4
4
  "description": "Files-based API Server for Routr Connect",
5
5
  "author": "Pedro Sanders <psanders@fonoster.com>",
6
6
  "homepage": "https://github.com/fonoster/routr#readme",
@@ -16,11 +16,12 @@
16
16
  "build": "tsc -b tsconfig.json"
17
17
  },
18
18
  "bin": {
19
- "run_simpledata": "dist/runner.js"
19
+ "run_simpledata": "dist/runner.js",
20
+ "healthcheck_simpledata": "dist/healthcheck.js"
20
21
  },
21
22
  "dependencies": {
22
- "@fonoster/logger": "0.3.18",
23
- "@grpc/grpc-js": "^1.5.9",
23
+ "@fonoster/logger": "0.3.20",
24
+ "@grpc/grpc-js": "^1.8.4",
24
25
  "@opentelemetry/api": "^1.0.4",
25
26
  "@opentelemetry/exporter-jaeger": "^1.0.4",
26
27
  "@opentelemetry/instrumentation": "^0.27.0",
@@ -29,9 +30,8 @@
29
30
  "@opentelemetry/sdk-trace-base": "^1.0.4",
30
31
  "@opentelemetry/sdk-trace-node": "^1.0.4",
31
32
  "@opentelemetry/semantic-conventions": "^1.0.4",
32
- "@routr/common": "^2.0.8-alpha.9",
33
- "@routr/processor": "^2.0.8-alpha.9",
34
- "ajv": "^6.12.6",
33
+ "@routr/common": "^2.0.13",
34
+ "@routr/processor": "^2.0.13",
35
35
  "google-protobuf": "^3.9.2",
36
36
  "jsonpath": "^1.1.1",
37
37
  "pb-util": "^1.0.3"
@@ -53,5 +53,5 @@
53
53
  "@types/google-protobuf": "^3.15.6",
54
54
  "@types/jsonpath": "^0.2.0"
55
55
  },
56
- "gitHead": "9ebb361db74fad2b3891fc9add683ddfde2efdff"
56
+ "gitHead": "476d11cfb4fd3dc9847a0829cae6fece84d048df"
57
57
  }
package/dist/errors.d.ts DELETED
@@ -1,34 +0,0 @@
1
- /**
2
- * Thrown for unimplemented handlers.
3
- */
4
- export declare class UnimplementedError extends Error {
5
- code: number;
6
- /**
7
- * Creates an instance of UnimplementedError.
8
- */
9
- constructor();
10
- }
11
- /**
12
- * Thrown if the resource is not found.
13
- */
14
- export declare class ResourceNotFound extends Error {
15
- code: number;
16
- /**
17
- * Creates an instance of UnimplementedError.
18
- *
19
- * @param {string} ref - the reference of the resource
20
- */
21
- constructor(ref: string);
22
- }
23
- /**
24
- * Thrown if the request is invalid.
25
- */
26
- export declare class BadRequest extends Error {
27
- code: number;
28
- /**
29
- * Creates an instance of UnimplementedError.
30
- *
31
- * @param {string} message - optional message with the error. Defaults to "bad request."
32
- */
33
- constructor(message?: string);
34
- }
package/dist/errors.js DELETED
@@ -1,91 +0,0 @@
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
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.BadRequest = exports.ResourceNotFound = exports.UnimplementedError = void 0;
27
- /*
28
- * Copyright (C) 2022 by Fonoster Inc (https://fonoster.com)
29
- * http://github.com/fonoster
30
- *
31
- * This file is part of nodejs-service
32
- *
33
- * Licensed under the MIT License (the "License");
34
- * you may not use this file except in compliance with
35
- * the License. You may obtain a copy of the License at
36
- *
37
- * https://opensource.org/licenses/MIT
38
- *
39
- * Unless required by applicable law or agreed to in writing, software
40
- * distributed under the License is distributed on an "AS IS" BASIS,
41
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
42
- * See the License for the specific language governing permissions and
43
- * limitations under the License.
44
- */
45
- const grpc = __importStar(require("@grpc/grpc-js"));
46
- /**
47
- * Thrown for unimplemented handlers.
48
- */
49
- class UnimplementedError extends Error {
50
- /**
51
- * Creates an instance of UnimplementedError.
52
- */
53
- constructor() {
54
- super("this operation is not supported/enabled in this data api implementation.");
55
- this.code = grpc.status.UNIMPLEMENTED;
56
- Object.setPrototypeOf(this, UnimplementedError.prototype);
57
- }
58
- }
59
- exports.UnimplementedError = UnimplementedError;
60
- /**
61
- * Thrown if the resource is not found.
62
- */
63
- class ResourceNotFound extends Error {
64
- /**
65
- * Creates an instance of UnimplementedError.
66
- *
67
- * @param {string} ref - the reference of the resource
68
- */
69
- constructor(ref) {
70
- super(`resource not found: ${ref}`);
71
- this.code = grpc.status.NOT_FOUND;
72
- Object.setPrototypeOf(this, ResourceNotFound.prototype);
73
- }
74
- }
75
- exports.ResourceNotFound = ResourceNotFound;
76
- /**
77
- * Thrown if the request is invalid.
78
- */
79
- class BadRequest extends Error {
80
- /**
81
- * Creates an instance of UnimplementedError.
82
- *
83
- * @param {string} message - optional message with the error. Defaults to "bad request."
84
- */
85
- constructor(message) {
86
- super(message !== null && message !== void 0 ? message : "bad request");
87
- this.code = grpc.status.INVALID_ARGUMENT;
88
- Object.setPrototypeOf(this, BadRequest.prototype);
89
- }
90
- }
91
- exports.BadRequest = BadRequest;