@things-factory/integration-base 7.0.0-alpha.9 → 7.0.1-alpha.1

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.
Files changed (50) hide show
  1. package/dist-server/engine/connection-manager.js +37 -6
  2. package/dist-server/engine/connection-manager.js.map +1 -1
  3. package/dist-server/engine/connector/graphql-connector.js +6 -6
  4. package/dist-server/engine/connector/graphql-connector.js.map +1 -1
  5. package/dist-server/engine/connector/operato-connector.js +19 -22
  6. package/dist-server/engine/connector/operato-connector.js.map +1 -1
  7. package/dist-server/engine/connector/proxy-connector.js +44 -0
  8. package/dist-server/engine/connector/proxy-connector.js.map +1 -0
  9. package/dist-server/engine/edge-client.js +38 -0
  10. package/dist-server/engine/edge-client.js.map +1 -0
  11. package/dist-server/engine/index.js +1 -0
  12. package/dist-server/engine/index.js.map +1 -1
  13. package/dist-server/engine/task/script.js +1 -0
  14. package/dist-server/engine/task/script.js.map +1 -1
  15. package/dist-server/engine/types.js.map +1 -1
  16. package/dist-server/service/connection/connection-mutation.js +4 -8
  17. package/dist-server/service/connection/connection-mutation.js.map +1 -1
  18. package/dist-server/service/connection/connection-query.js +17 -14
  19. package/dist-server/service/connection/connection-query.js.map +1 -1
  20. package/dist-server/service/connection/connection-subscription.js +1 -1
  21. package/dist-server/service/connection/connection-subscription.js.map +1 -1
  22. package/dist-server/service/connection/connection-type.js +32 -8
  23. package/dist-server/service/connection/connection-type.js.map +1 -1
  24. package/dist-server/service/scenario-instance/scenario-instance-type.js +12 -4
  25. package/dist-server/service/scenario-instance/scenario-instance-type.js.map +1 -1
  26. package/dist-server/tsconfig.tsbuildinfo +1 -1
  27. package/helps/integration/concept/script-internal-variables.ja.md +21 -1
  28. package/helps/integration/concept/script-internal-variables.ko.md +17 -0
  29. package/helps/integration/concept/script-internal-variables.md +18 -0
  30. package/helps/integration/concept/script-internal-variables.ms.md +19 -1
  31. package/helps/integration/concept/script-internal-variables.zh.md +18 -0
  32. package/helps/integration/task/script.ja.md +1 -1
  33. package/helps/integration/task/script.ko.md +1 -1
  34. package/helps/integration/task/script.md +1 -1
  35. package/helps/integration/task/script.ms.md +1 -1
  36. package/helps/integration/task/script.zh.md +1 -1
  37. package/package.json +10 -10
  38. package/server/engine/connection-manager.ts +49 -7
  39. package/server/engine/connector/graphql-connector.ts +8 -10
  40. package/server/engine/connector/operato-connector.ts +22 -32
  41. package/server/engine/connector/proxy-connector.ts +53 -0
  42. package/server/engine/edge-client.ts +45 -0
  43. package/server/engine/index.ts +1 -0
  44. package/server/engine/task/script.ts +1 -0
  45. package/server/engine/types.ts +45 -46
  46. package/server/service/connection/connection-mutation.ts +9 -29
  47. package/server/service/connection/connection-query.ts +13 -12
  48. package/server/service/connection/connection-subscription.ts +1 -1
  49. package/server/service/connection/connection-type.ts +53 -41
  50. package/server/service/scenario-instance/scenario-instance-type.ts +13 -5
@@ -6,6 +6,7 @@ const moment_timezone_1 = tslib_1.__importDefault(require("moment-timezone"));
6
6
  const winston_1 = require("winston");
7
7
  const shell_1 = require("@things-factory/shell");
8
8
  const service_1 = require("../service");
9
+ const proxy_connector_1 = require("./connector/proxy-connector");
9
10
  const { combine, timestamp, splat, printf } = winston_1.format;
10
11
  const debug = require('debug')('things-factory:integration-base:connections');
11
12
  const SYSTEM_TZ = Intl.DateTimeFormat().resolvedOptions().timeZone;
@@ -18,7 +19,7 @@ class ConnectionManager {
18
19
  static async ready() {
19
20
  const CONNECTIONS = (await (0, shell_1.getRepository)(service_1.Connection).find({
20
21
  where: { active: true },
21
- relations: ['domain', 'creator', 'updater']
22
+ relations: ['domain', 'edge', 'creator', 'updater']
22
23
  })).map(connection => {
23
24
  var params = {};
24
25
  try {
@@ -31,11 +32,18 @@ class ConnectionManager {
31
32
  return Object.assign(Object.assign({}, connection), { params });
32
33
  });
33
34
  ConnectionManager.logger.info('Initializing ConnectionManager...');
34
- return await Promise.all(Object.keys(ConnectionManager.connectors).map(type => {
35
- var connector = ConnectionManager.connectors[type];
35
+ return await Promise.all([...Object.keys(ConnectionManager.connectors), 'proxy-connector'].map(type => {
36
+ const connector = 'proxy-connector' ? proxy_connector_1.ProxyConnector.instance : ConnectionManager.getConnector(type);
36
37
  ConnectionManager.logger.info(`Connector '${type}' started to ready`);
37
38
  return connector
38
- .ready(CONNECTIONS.filter(connection => connection.type == type))
39
+ .ready(CONNECTIONS.filter(connection => {
40
+ if (type == 'proxy-connector') {
41
+ return !!connection.edge;
42
+ }
43
+ else {
44
+ return !connection.edge && connection.type == type;
45
+ }
46
+ }))
39
47
  .catch(error => {
40
48
  ConnectionManager.logger.error(error.message);
41
49
  })
@@ -62,6 +70,12 @@ class ConnectionManager {
62
70
  static unregisterConnector(type) {
63
71
  delete ConnectionManager.connectors[type];
64
72
  }
73
+ static getConnections() {
74
+ return ConnectionManager.connections;
75
+ }
76
+ static getEntities() {
77
+ return ConnectionManager.entities;
78
+ }
65
79
  static getConnectionInstance(connection) {
66
80
  var _a;
67
81
  const { domain, name } = connection;
@@ -75,35 +89,50 @@ class ConnectionManager {
75
89
  }
76
90
  return connection;
77
91
  }
92
+ static getConnectionInstanceEntityByName(domain, name) {
93
+ const entities = ConnectionManager.entities[domain.id];
94
+ return entities === null || entities === void 0 ? void 0 : entities[name];
95
+ }
78
96
  static getConnectionInstances(domain) {
79
97
  const connections = ConnectionManager.connections[domain.id];
80
98
  return Object.assign({}, connections);
81
99
  }
100
+ static getConnectionInstanceEntities(domain) {
101
+ const connections = ConnectionManager.entities[domain.id];
102
+ return Object.assign({}, connections);
103
+ }
82
104
  static addConnectionInstance(connection, instance) {
83
105
  const { domain, name } = connection;
84
106
  var connections = ConnectionManager.connections[domain.id];
85
107
  if (!connections) {
86
108
  connections = ConnectionManager.connections[domain.id] = {};
87
109
  }
110
+ var entities = ConnectionManager.entities[domain.id];
111
+ if (!entities) {
112
+ entities = ConnectionManager.entities[domain.id] = {};
113
+ }
88
114
  connections[name] = instance;
115
+ entities[name] = connection;
89
116
  ConnectionManager.publishState(connection, service_1.ConnectionStatus.CONNECTED);
90
117
  debug('add-connection', domain.subdomain, name);
91
118
  }
92
119
  static removeConnectionInstance(connection) {
93
120
  const { domain, name } = connection;
94
121
  var connections = ConnectionManager.connections[domain.id];
122
+ var entities = ConnectionManager.entities[domain.id];
95
123
  var instance = connections === null || connections === void 0 ? void 0 : connections[name];
96
124
  if (!connections || !instance) {
97
125
  debug('remove-connection', `'${name}' connection not found in domain '${domain.subdomain}'`);
98
126
  return;
99
127
  }
100
128
  delete connections[name];
129
+ delete entities[name];
101
130
  ConnectionManager.publishState(connection, service_1.ConnectionStatus.DISCONNECTED);
102
131
  debug('remove-connection', `'${name}' connection is removed from domain '${domain.subdomain}'`);
103
132
  return instance;
104
133
  }
105
- static publishState(connection, state) {
106
- const { domain, id, name, description, type } = connection;
134
+ static async publishState(connection, state) {
135
+ const { domain, id, name, description, type, edge } = connection;
107
136
  shell_1.pubsub.publish('connection-state', {
108
137
  connectionState: {
109
138
  domain,
@@ -111,6 +140,7 @@ class ConnectionManager {
111
140
  name,
112
141
  description,
113
142
  type,
143
+ edge,
114
144
  state,
115
145
  timestamp: new Date()
116
146
  }
@@ -120,6 +150,7 @@ class ConnectionManager {
120
150
  exports.ConnectionManager = ConnectionManager;
121
151
  ConnectionManager.connectors = {};
122
152
  ConnectionManager.connections = {};
153
+ ConnectionManager.entities = {};
123
154
  ConnectionManager.logFormat = printf(({ level, message, timestamp }) => {
124
155
  return `${timestamp} ${level}: ${message}`;
125
156
  });
@@ -1 +1 @@
1
- {"version":3,"file":"connection-manager.js","sourceRoot":"","sources":["../../server/engine/connection-manager.ts"],"names":[],"mappings":";;;;AAAA,8EAAoC;AACpC,qCAA0D;AAE1D,iDAAyF;AAEzF,wCAAyD;AAGzD,MAAM,EAAE,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,gBAAM,CAAA;AACpD,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC,6CAA6C,CAAC,CAA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AA9JgB,4BAAU,GAAsC,EAAE,CAAA;AAClD,6BAAW,GAAG,EAAE,CAAA;AAChB,2BAAS,GAAG,MAAM,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,EAAE,EAAE;IAClE,OAAO,GAAG,SAAS,IAAI,KAAK,KAAK,OAAO,EAAE,CAAA;AAC5C,CAAC,CAAC,CAAA;AAEY,wBAAM,GAAG,IAAA,sBAAY,EAAC;IAClC,MAAM,EAAE,OAAO,CAAC,eAAe,CAAC,EAAE,EAAE,EAAE,SAAS,EAAE,CAAC,EAAE,KAAK,EAAE,EAAE,iBAAiB,CAAC,SAAS,CAAC;IACzF,UAAU,EAAE;QACV,IAAK,oBAAkB,CAAC,eAAe,CAAC;YACtC,QAAQ,EAAE,6BAA6B;YACvC,WAAW,EAAE,eAAe;YAC5B,aAAa,EAAE,KAAK;YACpB,OAAO,EAAE,KAAK;YACd,QAAQ,EAAE,KAAK;YACf,KAAK,EAAE,MAAM;SACd,CAAC;QACF,IAAI,0BAAkB,CAAC;YACrB,KAAK,EAAE,gBAAgB;SACxB,CAAC;KACH;CACF,CAAC,CAAA","sourcesContent":["import moment from 'moment-timezone'\nimport { createLogger, format, transports } from 'winston'\n\nimport { Domain, getRepository, pubsub, PubSubLogTransport } from '@things-factory/shell'\n\nimport { Connection, ConnectionStatus } from '../service'\nimport { Connector } from './types'\n\nconst { combine, timestamp, splat, printf } = format\nconst debug = require('debug')('things-factory:integration-base:connections')\n\nconst SYSTEM_TZ = Intl.DateTimeFormat().resolvedOptions().timeZone\nconst systemTimestamp = format((info, opts) => {\n if (opts.tz) info.timestamp = moment().tz(opts.tz).format()\n return info\n})\n\nexport class ConnectionManager {\n private static connectors: { [propName: string]: Connector } = {}\n private static connections = {}\n private static logFormat = printf(({ level, message, timestamp }) => {\n return `${timestamp} ${level}: ${message}`\n })\n\n public static logger = createLogger({\n format: combine(systemTimestamp({ tz: SYSTEM_TZ }), splat(), ConnectionManager.logFormat),\n transports: [\n new (transports as any).DailyRotateFile({\n filename: `logs/connections-%DATE%.log`,\n datePattern: 'YYYY-MM-DD-HH',\n zippedArchive: false,\n maxSize: '20m',\n maxFiles: '14d',\n level: 'info'\n }),\n new PubSubLogTransport({\n topic: 'connection-log'\n })\n ]\n })\n\n static async ready() {\n const CONNECTIONS = (\n await getRepository(Connection).find({\n where: { active: true },\n relations: ['domain', 'creator', 'updater']\n })\n ).map(connection => {\n var params = {}\n try {\n params = JSON.parse(connection.params || '{}')\n } catch (ex) {\n ConnectionManager.logger.error(`connection '${connection.name}' params should be JSON format`)\n ConnectionManager.logger.error(ex)\n }\n\n return {\n ...connection,\n params\n }\n })\n\n ConnectionManager.logger.info('Initializing ConnectionManager...')\n\n return await Promise.all(\n Object.keys(ConnectionManager.connectors).map(type => {\n var connector = ConnectionManager.connectors[type]\n ConnectionManager.logger.info(`Connector '${type}' started to ready`)\n\n return connector\n .ready(CONNECTIONS.filter(connection => connection.type == type) as any)\n .catch(error => {\n ConnectionManager.logger.error(error.message)\n })\n .then(() => {\n ConnectionManager.logger.info(`All connector for '${type}' ready`)\n })\n })\n ).then(() => {\n ConnectionManager.logger.info('ConnectionManager initialization done:')\n Object.keys(ConnectionManager.connections).forEach(key => {\n var connections = ConnectionManager.connections[key]\n ConnectionManager.logger.info('For domain(%s) : %s', key, JSON.stringify(Object.keys(connections)))\n })\n })\n }\n\n static registerConnector(type: string, connector: Connector) {\n ConnectionManager.connectors[type] = connector\n }\n\n static getConnector(type: string): Connector {\n return ConnectionManager.connectors[type]\n }\n\n static getConnectors(): { [connectorName: string]: Connector } {\n return {\n ...ConnectionManager.connectors\n }\n }\n\n static unregisterConnector(type: string) {\n delete ConnectionManager.connectors[type]\n }\n\n static getConnectionInstance(connection: Connection): any {\n const { domain, name } = connection\n return ConnectionManager.connections[domain.id]?.[name]\n }\n\n static getConnectionInstanceByName(domain: Domain, name: string) {\n const connections = ConnectionManager.connections[domain.id]\n const connection = connections?.[name]\n\n if (!connection) {\n throw `The connection with the given name(${name}) cannot be found`\n }\n\n return connection\n }\n\n static getConnectionInstances(domain: Domain): { [connectionName: string]: any } {\n const connections = ConnectionManager.connections[domain.id]\n\n return {\n ...connections\n }\n }\n\n static addConnectionInstance(connection: Connection, instance: any) {\n const { domain, name } = connection\n\n var connections = ConnectionManager.connections[domain.id]\n if (!connections) {\n connections = ConnectionManager.connections[domain.id] = {}\n }\n\n connections[name] = instance\n\n ConnectionManager.publishState(connection, ConnectionStatus.CONNECTED)\n debug('add-connection', domain.subdomain, name)\n }\n\n static removeConnectionInstance(connection: Connection): any {\n const { domain, name } = connection\n var connections = ConnectionManager.connections[domain.id]\n var instance = connections?.[name]\n\n if (!connections || !instance) {\n debug('remove-connection', `'${name}' connection not found in domain '${domain.subdomain}'`)\n return\n }\n\n delete connections[name]\n\n ConnectionManager.publishState(connection, ConnectionStatus.DISCONNECTED)\n debug('remove-connection', `'${name}' connection is removed from domain '${domain.subdomain}'`)\n\n return instance\n }\n\n static publishState(connection: Connection, state) {\n const { domain, id, name, description, type } = connection\n\n pubsub.publish('connection-state', {\n connectionState: {\n domain,\n id,\n name,\n description,\n type,\n state,\n timestamp: new Date()\n }\n })\n }\n}\n"]}
1
+ {"version":3,"file":"connection-manager.js","sourceRoot":"","sources":["../../server/engine/connection-manager.ts"],"names":[],"mappings":";;;;AAAA,8EAAoC;AACpC,qCAA0D;AAE1D,iDAAyF;AAEzF,wCAAyD;AAEzD,iEAA4D;AAE5D,MAAM,EAAE,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,gBAAM,CAAA;AACpD,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC,6CAA6C,CAAC,CAAA;AAE7E,MAAM,SAAS,GAAG,IAAI,CAAC,cAAc,EAAE,CAAC,eAAe,EAAE,CAAC,QAAQ,CAAA;AAClE,MAAM,eAAe,GAAG,IAAA,gBAAM,EAAC,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE;IAC5C,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ClE,OAAO,GAAG,SAAS,IAAI,KAAK,KAAK,OAAO,EAAE,CAAA;AAC5C,CAAC,CAAC,CAAA;AAEY,wBAAM,GAAG,IAAA,sBAAY,EAAC;IAClC,MAAM,EAAE,OAAO,CAAC,eAAe,CAAC,EAAE,EAAE,EAAE,SAAS,EAAE,CAAC,EAAE,KAAK,EAAE,EAAE,iBAAiB,CAAC,SAAS,CAAC;IACzF,UAAU,EAAE;QACV,IAAK,oBAAkB,CAAC,eAAe,CAAC;YACtC,QAAQ,EAAE,6BAA6B;YACvC,WAAW,EAAE,eAAe;YAC5B,aAAa,EAAE,KAAK;YACpB,OAAO,EAAE,KAAK;YACd,QAAQ,EAAE,KAAK;YACf,KAAK,EAAE,MAAM;SACd,CAAC;QACF,IAAI,0BAAkB,CAAC;YACrB,KAAK,EAAE,gBAAgB;SACxB,CAAC;KACH;CACF,CAAC,CAAA","sourcesContent":["import moment from 'moment-timezone'\nimport { createLogger, format, transports } from 'winston'\n\nimport { Domain, getRepository, pubsub, PubSubLogTransport } from '@things-factory/shell'\n\nimport { Connection, ConnectionStatus } from '../service'\nimport { Connector } from './types'\nimport { ProxyConnector } from './connector/proxy-connector'\n\nconst { combine, timestamp, splat, printf } = format\nconst debug = require('debug')('things-factory:integration-base:connections')\n\nconst SYSTEM_TZ = Intl.DateTimeFormat().resolvedOptions().timeZone\nconst systemTimestamp = format((info, opts) => {\n if (opts.tz) info.timestamp = moment().tz(opts.tz).format()\n return info\n})\n\nexport class ConnectionManager {\n private static connectors: { [propName: string]: Connector } = {}\n private static connections: { [domainId: string]: { [name: string]: any } } = {}\n private static entities = {}\n private static logFormat = printf(({ level, message, timestamp }) => {\n return `${timestamp} ${level}: ${message}`\n })\n\n public static logger = createLogger({\n format: combine(systemTimestamp({ tz: SYSTEM_TZ }), splat(), ConnectionManager.logFormat),\n transports: [\n new (transports as any).DailyRotateFile({\n filename: `logs/connections-%DATE%.log`,\n datePattern: 'YYYY-MM-DD-HH',\n zippedArchive: false,\n maxSize: '20m',\n maxFiles: '14d',\n level: 'info'\n }),\n new PubSubLogTransport({\n topic: 'connection-log'\n })\n ]\n })\n\n static async ready() {\n const CONNECTIONS = (\n await getRepository(Connection).find({\n where: { active: true },\n relations: ['domain', 'edge', 'creator', 'updater']\n })\n ).map(connection => {\n var params = {}\n try {\n params = JSON.parse(connection.params || '{}')\n } catch (ex) {\n ConnectionManager.logger.error(`connection '${connection.name}' params should be JSON format`)\n ConnectionManager.logger.error(ex)\n }\n\n return {\n ...connection,\n params\n }\n })\n\n ConnectionManager.logger.info('Initializing ConnectionManager...')\n\n return await Promise.all(\n [...Object.keys(ConnectionManager.connectors), 'proxy-connector'].map(type => {\n const connector = 'proxy-connector' ? ProxyConnector.instance : ConnectionManager.getConnector(type)\n\n ConnectionManager.logger.info(`Connector '${type}' started to ready`)\n\n return connector\n .ready(\n CONNECTIONS.filter(connection => {\n if (type == 'proxy-connector') {\n return !!connection.edge\n } else {\n return !connection.edge && connection.type == type\n }\n }) as any\n )\n .catch(error => {\n ConnectionManager.logger.error(error.message)\n })\n .then(() => {\n ConnectionManager.logger.info(`All connector for '${type}' ready`)\n })\n })\n ).then(() => {\n ConnectionManager.logger.info('ConnectionManager initialization done:')\n Object.keys(ConnectionManager.connections).forEach(key => {\n var connections = ConnectionManager.connections[key]\n ConnectionManager.logger.info('For domain(%s) : %s', key, JSON.stringify(Object.keys(connections)))\n })\n })\n }\n\n static registerConnector(type: string, connector: Connector) {\n ConnectionManager.connectors[type] = connector\n }\n\n static getConnector(type: string): Connector {\n return ConnectionManager.connectors[type]\n }\n\n static getConnectors(): { [connectorName: string]: Connector } {\n return {\n ...ConnectionManager.connectors\n }\n }\n\n static unregisterConnector(type: string) {\n delete ConnectionManager.connectors[type]\n }\n\n static getConnections() {\n return ConnectionManager.connections\n }\n\n static getEntities() {\n return ConnectionManager.entities\n }\n\n static getConnectionInstance(connection: Connection): any {\n const { domain, name } = connection\n return ConnectionManager.connections[domain.id]?.[name]\n }\n\n static getConnectionInstanceByName(domain: Domain, name: string) {\n const connections = ConnectionManager.connections[domain.id]\n const connection = connections?.[name]\n\n if (!connection) {\n throw `The connection with the given name(${name}) cannot be found`\n }\n\n return connection\n }\n\n static getConnectionInstanceEntityByName(domain: Domain, name: string): any {\n const entities = ConnectionManager.entities[domain.id]\n return entities?.[name]\n }\n\n static getConnectionInstances(domain: Domain): { [connectionName: string]: any } {\n const connections = ConnectionManager.connections[domain.id]\n\n return {\n ...connections\n }\n }\n\n static getConnectionInstanceEntities(domain: Domain): { [connectionName: string]: any } {\n const connections = ConnectionManager.entities[domain.id]\n\n return {\n ...connections\n }\n }\n\n static addConnectionInstance(connection: Connection, instance: any) {\n const { domain, name } = connection\n\n var connections = ConnectionManager.connections[domain.id]\n if (!connections) {\n connections = ConnectionManager.connections[domain.id] = {}\n }\n\n var entities = ConnectionManager.entities[domain.id]\n if (!entities) {\n entities = ConnectionManager.entities[domain.id] = {}\n }\n\n connections[name] = instance\n entities[name] = connection\n\n ConnectionManager.publishState(connection, ConnectionStatus.CONNECTED)\n debug('add-connection', domain.subdomain, name)\n }\n\n static removeConnectionInstance(connection: Connection): any {\n const { domain, name } = connection\n var connections = ConnectionManager.connections[domain.id]\n var entities = ConnectionManager.entities[domain.id]\n\n var instance = connections?.[name]\n\n if (!connections || !instance) {\n debug('remove-connection', `'${name}' connection not found in domain '${domain.subdomain}'`)\n return\n }\n\n delete connections[name]\n delete entities[name]\n\n ConnectionManager.publishState(connection, ConnectionStatus.DISCONNECTED)\n debug('remove-connection', `'${name}' connection is removed from domain '${domain.subdomain}'`)\n\n return instance\n }\n\n private static async publishState(connection: Connection, state) {\n const { domain, id, name, description, type, edge } = connection\n\n pubsub.publish('connection-state', {\n connectionState: {\n domain,\n id,\n name,\n description,\n type,\n edge,\n state,\n timestamp: new Date()\n }\n })\n }\n}\n"]}
@@ -20,17 +20,14 @@ const defaultOptions = {
20
20
  errorPolicy: 'all'
21
21
  }
22
22
  };
23
- const cache = new core_1.InMemoryCache({
24
- addTypename: false
25
- });
26
23
  class GraphqlConnector {
27
24
  async ready(connectionConfigs) {
28
25
  await Promise.all(connectionConfigs.map(this.connect.bind(this)));
29
26
  connection_manager_1.ConnectionManager.logger.info('graphql-connector connections are ready');
30
27
  }
31
28
  async connect(connection) {
32
- var { endpoint: uri, params: { authClient } } = connection;
33
- var ERROR_HANDLER = ({ graphQLErrors, networkError }) => {
29
+ const { endpoint: uri, params: { authClient } } = connection;
30
+ const ERROR_HANDLER = ({ graphQLErrors, networkError }) => {
34
31
  if (graphQLErrors)
35
32
  graphQLErrors.map(({ message, locations, path }) => {
36
33
  connection_manager_1.ConnectionManager.logger.error(`[GraphQL error] Message: ${message}, Location: ${locations}, Path: ${path}`);
@@ -47,6 +44,9 @@ class GraphqlConnector {
47
44
  }));
48
45
  return forward(operation);
49
46
  });
47
+ const cache = new core_1.InMemoryCache({
48
+ addTypename: false
49
+ });
50
50
  connection_manager_1.ConnectionManager.addConnectionInstance(connection, new core_1.ApolloClient({
51
51
  defaultOptions,
52
52
  cache,
@@ -62,7 +62,7 @@ class GraphqlConnector {
62
62
  connection_manager_1.ConnectionManager.logger.info(`graphql-connector connection(${connection.name}:${connection.endpoint}) is connected`);
63
63
  }
64
64
  async disconnect(connection) {
65
- var client = connection_manager_1.ConnectionManager.getConnectionInstance(connection);
65
+ const client = connection_manager_1.ConnectionManager.getConnectionInstance(connection);
66
66
  client.stop();
67
67
  connection_manager_1.ConnectionManager.removeConnectionInstance(connection);
68
68
  connection_manager_1.ConnectionManager.logger.info(`graphql-connector connection(${connection.name}) is disconnected`);
@@ -1 +1 @@
1
- {"version":3,"file":"graphql-connector.js","sourceRoot":"","sources":["../../../server/engine/connector/graphql-connector.ts"],"names":[],"mappings":";;;AAAA,gCAA6B;AAE7B,8CAA6F;AAC7F,qDAAmD;AACnD,iEAA4D;AAC5D,iDAAqD;AAErD,8DAAyD;AAIzD,MAAM,cAAc,GAAQ;IAC1B,UAAU,EAAE;QACV,WAAW,EAAE,UAAU;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ED,IAAI,YAAY;QACd,OAAO,CAAC,SAAS,CAAC,CAAA;IACpB,CAAC;IAED,IAAI,WAAW;QACb,OAAO,wBAAwB,CAAA;IACjC,CAAC;IAED,IAAI,IAAI;QACN,OAAO,yCAAyC,CAAA;IAClD,CAAC;CACF;AA3FD,4CA2FC;AAED,sCAAiB,CAAC,iBAAiB,CAAC,mBAAmB,EAAE,IAAI,gBAAgB,EAAE,CAAC,CAAA","sourcesContent":["import 'cross-fetch/polyfill'\n\nimport { ApolloClient, ApolloLink, from, HttpLink, InMemoryCache } from '@apollo/client/core'\nimport { onError } from '@apollo/client/link/error'\nimport { Oauth2Client } from '@things-factory/oauth2-client'\nimport { getRepository } from '@things-factory/shell'\n\nimport { ConnectionManager } from '../connection-manager'\nimport { Connector } from '../types'\nimport { InputConnection } from '../../service/connection/connection-type'\n\nconst defaultOptions: any = {\n watchQuery: {\n fetchPolicy: 'no-cache',\n errorPolicy: 'ignore'\n },\n query: {\n fetchPolicy: 'no-cache', //'network-only'\n errorPolicy: 'all'\n },\n mutate: {\n errorPolicy: 'all'\n }\n}\n\nconst cache = new InMemoryCache({\n addTypename: false\n})\n\nexport class GraphqlConnector implements Connector {\n async ready(connectionConfigs: InputConnection[]) {\n await Promise.all(connectionConfigs.map(this.connect.bind(this)))\n\n ConnectionManager.logger.info('graphql-connector connections are ready')\n }\n\n async connect(connection: InputConnection) {\n var {\n endpoint: uri,\n params: { authClient }\n } = connection\n\n var ERROR_HANDLER: any = ({ graphQLErrors, networkError }) => {\n if (graphQLErrors)\n graphQLErrors.map(({ message, locations, path }) => {\n ConnectionManager.logger.error(`[GraphQL error] Message: ${message}, Location: ${locations}, Path: ${path}`)\n })\n\n if (networkError) {\n ConnectionManager.logger.error(`[Network error - ${networkError.statusCode}] ${networkError}`)\n }\n }\n\n const oauth2Client: Oauth2Client = await getRepository(Oauth2Client).findOneBy({ id: authClient })\n\n const authMiddleware = new ApolloLink((operation, forward) => {\n // add the authorization to the headers\n operation.setContext(({ headers = {} }) => ({\n headers: {\n ...headers,\n ...oauth2Client.getAuthHeaders()\n }\n }))\n\n return forward(operation)\n })\n\n ConnectionManager.addConnectionInstance(\n connection,\n new ApolloClient({\n defaultOptions,\n cache,\n link: from([\n authMiddleware,\n onError(ERROR_HANDLER),\n new HttpLink({\n uri,\n credentials: 'include'\n })\n ])\n })\n )\n\n ConnectionManager.logger.info(\n `graphql-connector connection(${connection.name}:${connection.endpoint}) is connected`\n )\n }\n\n async disconnect(connection: InputConnection) {\n var client = ConnectionManager.getConnectionInstance(connection)\n client.stop()\n ConnectionManager.removeConnectionInstance(connection)\n\n ConnectionManager.logger.info(`graphql-connector connection(${connection.name}) is disconnected`)\n }\n\n get parameterSpec() {\n return [\n {\n type: 'entity-selector',\n name: 'authClient',\n label: 'auth-client',\n property: {\n queryName: 'oauth2Clients'\n }\n }\n ]\n }\n\n get taskPrefixes() {\n return ['graphql']\n }\n\n get description() {\n return 'Graphql Http Connector'\n }\n\n get help() {\n return 'integration/connector/graphql-connector'\n }\n}\n\nConnectionManager.registerConnector('graphql-connector', new GraphqlConnector())\n"]}
1
+ {"version":3,"file":"graphql-connector.js","sourceRoot":"","sources":["../../../server/engine/connector/graphql-connector.ts"],"names":[],"mappings":";;;AAAA,gCAA6B;AAE7B,8CAA6F;AAC7F,qDAAmD;AACnD,iEAA4D;AAC5D,iDAAqD;AAErD,8DAAyD;AAIzD,MAAM,cAAc,GAAQ;IAC1B,UAAU,EAAE;QACV,WAAW,EAAE,UAAU;QACvB,WAAW,EAAE,QAAQ;KACtB;IACD,KAAK,EAAE;QACL,WAAW,EAAE,UAAU;QACvB,WAAW,EAAE,KAAK;KACnB;IACD,MAAM,EAAE;QACN,WAAW,EAAE,KAAK;KACnB;CACF,CAAA;AAED,MAAa,gBAAgB;IAC3B,KAAK,CAAC,KAAK,CAAC,iBAAoC;QAC9C,MAAM,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,IA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{ ApolloClient, ApolloLink, from, HttpLink, InMemoryCache } from '@apollo/client/core'\nimport { onError } from '@apollo/client/link/error'\nimport { Oauth2Client } from '@things-factory/oauth2-client'\nimport { getRepository } from '@things-factory/shell'\n\nimport { ConnectionManager } from '../connection-manager'\nimport { Connector } from '../types'\nimport { InputConnection } from '../../service/connection/connection-type'\n\nconst defaultOptions: any = {\n watchQuery: {\n fetchPolicy: 'no-cache',\n errorPolicy: 'ignore'\n },\n query: {\n fetchPolicy: 'no-cache', //'network-only'\n errorPolicy: 'all'\n },\n mutate: {\n errorPolicy: 'all'\n }\n}\n\nexport class GraphqlConnector implements Connector {\n async ready(connectionConfigs: InputConnection[]) {\n await Promise.all(connectionConfigs.map(this.connect.bind(this)))\n\n ConnectionManager.logger.info('graphql-connector connections are ready')\n }\n\n async connect(connection: InputConnection) {\n const {\n endpoint: uri,\n params: { authClient }\n } = connection\n\n const ERROR_HANDLER: any = ({ graphQLErrors, networkError }) => {\n if (graphQLErrors)\n graphQLErrors.map(({ message, locations, path }) => {\n ConnectionManager.logger.error(`[GraphQL error] Message: ${message}, Location: ${locations}, Path: ${path}`)\n })\n\n if (networkError) {\n ConnectionManager.logger.error(`[Network error - ${networkError.statusCode}] ${networkError}`)\n }\n }\n\n const oauth2Client: Oauth2Client = await getRepository(Oauth2Client).findOneBy({ id: authClient })\n\n const authMiddleware = new ApolloLink((operation, forward) => {\n // add the authorization to the headers\n operation.setContext(({ headers = {} }) => ({\n headers: {\n ...headers,\n ...oauth2Client.getAuthHeaders()\n }\n }))\n\n return forward(operation)\n })\n\n const cache = new InMemoryCache({\n addTypename: false\n })\n\n ConnectionManager.addConnectionInstance(\n connection,\n new ApolloClient({\n defaultOptions,\n cache,\n link: from([\n authMiddleware,\n onError(ERROR_HANDLER),\n new HttpLink({\n uri,\n credentials: 'include'\n })\n ])\n })\n )\n\n ConnectionManager.logger.info(`graphql-connector connection(${connection.name}:${connection.endpoint}) is connected`)\n }\n\n async disconnect(connection: InputConnection) {\n const client = ConnectionManager.getConnectionInstance(connection)\n client.stop()\n ConnectionManager.removeConnectionInstance(connection)\n\n ConnectionManager.logger.info(`graphql-connector connection(${connection.name}) is disconnected`)\n }\n\n get parameterSpec() {\n return [\n {\n type: 'entity-selector',\n name: 'authClient',\n label: 'auth-client',\n property: {\n queryName: 'oauth2Clients'\n }\n }\n ]\n }\n\n get taskPrefixes() {\n return ['graphql']\n }\n\n get description() {\n return 'Graphql Http Connector'\n }\n\n get help() {\n return 'integration/connector/graphql-connector'\n }\n}\n\nConnectionManager.registerConnector('graphql-connector', new GraphqlConnector())\n"]}
@@ -5,7 +5,6 @@ const tslib_1 = require("tslib");
5
5
  require("cross-fetch/polyfill");
6
6
  const core_1 = require("@apollo/client/core");
7
7
  const context_1 = require("@apollo/client/link/context");
8
- // for subscription
9
8
  const ws_1 = tslib_1.__importDefault(require("ws"));
10
9
  const graphql_ws_1 = require("graphql-ws");
11
10
  const subscriptions_1 = require("@apollo/client/link/subscriptions");
@@ -16,7 +15,7 @@ const scenario_1 = require("../../service/scenario/scenario");
16
15
  const scenario_instance_type_1 = require("../../service/scenario-instance/scenario-instance-type");
17
16
  const shell_1 = require("@things-factory/shell");
18
17
  const auth_base_1 = require("@things-factory/auth-base");
19
- const debug = require('debug')('things-factory:integration-base:operato-connector-subscription');
18
+ const debug = require('debug')('things-factory:integration-base:operato-connector');
20
19
  const defaultOptions = {
21
20
  watchQuery: {
22
21
  fetchPolicy: 'no-cache',
@@ -30,24 +29,19 @@ const defaultOptions = {
30
29
  errorPolicy: 'all'
31
30
  }
32
31
  };
33
- const cache = new core_1.InMemoryCache({
34
- addTypename: false
35
- });
36
32
  exports.GRAPHQL_URI = '/graphql';
37
33
  exports.SUBSCRIPTION_URI = exports.GRAPHQL_URI;
38
- ;
39
- ``;
40
34
  class OperatoConnector {
41
35
  async ready(connectionConfigs) {
42
36
  await Promise.all(connectionConfigs.map(this.connect.bind(this)));
43
- connection_manager_1.ConnectionManager.logger.info('graphql-connector connections are ready');
37
+ connection_manager_1.ConnectionManager.logger.info('operato-connector connections are ready');
44
38
  }
45
39
  async connect(connection) {
46
- var { endpoint: uri, params: { authKey, domain, subscriptionHandlers = {} } } = connection;
40
+ const { endpoint: uri, params: { authKey, domain, subscriptionHandlers = {} } } = connection;
47
41
  if (!authKey || !domain) {
48
42
  throw new Error('some connection paramter missing.');
49
43
  }
50
- var domainOwner = await (0, shell_1.getRepository)(auth_base_1.User).findOne({
44
+ const domainOwner = await (0, shell_1.getRepository)(auth_base_1.User).findOne({
51
45
  where: {
52
46
  id: connection.domain.owner
53
47
  }
@@ -88,18 +82,21 @@ class OperatoConnector {
88
82
  headers: Object.assign(Object.assign({}, headers), { 'x-things-factory-domain': domain, authorization: authKey ? `Bearer ${authKey}` : '' })
89
83
  };
90
84
  }).concat(httpLink));
91
- var client = new core_1.ApolloClient({
85
+ const cache = new core_1.InMemoryCache({
86
+ addTypename: false
87
+ });
88
+ const client = new core_1.ApolloClient({
92
89
  defaultOptions,
93
90
  cache,
94
91
  link: splitLink
95
92
  });
96
- var subscriptions = [];
93
+ const subscriptions = [];
97
94
  Object.keys(subscriptionHandlers).forEach(async (tag) => {
98
95
  if (!tag || !subscriptionHandlers[tag])
99
96
  return;
100
- let scenarioName = subscriptionHandlers[tag];
97
+ const scenarioName = subscriptionHandlers[tag];
101
98
  // fetch a scenario
102
- var selectedScenario = await (0, shell_1.getRepository)(scenario_1.Scenario).findOne({
99
+ const selectedScenario = await (0, shell_1.getRepository)(scenario_1.Scenario).findOne({
103
100
  where: {
104
101
  name: scenarioName
105
102
  },
@@ -115,7 +112,7 @@ class OperatoConnector {
115
112
  }
116
113
  `
117
114
  });
118
- var subscriptionObserver = subscription.subscribe({
115
+ const subscriptionObserver = subscription.subscribe({
119
116
  next: async (data) => {
120
117
  var _a;
121
118
  debug('received pubsub msg.:', data === null || data === void 0 ? void 0 : data.data);
@@ -138,15 +135,15 @@ class OperatoConnector {
138
135
  });
139
136
  client['subscriptions'] = subscriptions;
140
137
  connection_manager_1.ConnectionManager.addConnectionInstance(connection, client);
141
- connection_manager_1.ConnectionManager.logger.info(`graphql-connector connection(${connection.name}:${connection.endpoint}) is connected`);
138
+ connection_manager_1.ConnectionManager.logger.info(`operato-connector connection(${connection.name}:${connection.endpoint}) is connected`);
142
139
  }
143
140
  async disconnect(connection) {
144
- var client = connection_manager_1.ConnectionManager.getConnectionInstance(connection);
145
- let subscriptions = client['subscriptions'];
141
+ const client = connection_manager_1.ConnectionManager.getConnectionInstance(connection);
142
+ const subscriptions = client['subscriptions'];
146
143
  subscriptions.forEach(subscription => subscription.subscriptionObserver.unsubscribe());
147
144
  client.stop();
148
145
  connection_manager_1.ConnectionManager.removeConnectionInstance(connection);
149
- connection_manager_1.ConnectionManager.logger.info(`graphql-connector connection(${connection.name}) is disconnected`);
146
+ connection_manager_1.ConnectionManager.logger.info(`operato-connector connection(${connection.name}) is disconnected`);
150
147
  }
151
148
  async runScenario(subscriptions, variables) {
152
149
  var _a;
@@ -155,7 +152,7 @@ class OperatoConnector {
155
152
  if (!tag) {
156
153
  throw new Error(`tag is invalid - ${tag}`);
157
154
  }
158
- var scenario = (_a = subscriptions.find(subscription => subscription.tag === tag)) === null || _a === void 0 ? void 0 : _a.scenario;
155
+ const scenario = (_a = subscriptions.find(subscription => subscription.tag === tag)) === null || _a === void 0 ? void 0 : _a.scenario;
159
156
  if (!scenario) {
160
157
  throw new Error(`scenario is not found - ${tag}`);
161
158
  }
@@ -164,8 +161,8 @@ class OperatoConnector {
164
161
  throw new Error(`Unauthorized! ${category && privilege ? category + ':' + privilege + ' privilege' : 'ownership granted'} required`);
165
162
  }
166
163
  /* create a scenario instance */
167
- let instanceName = scenario.name + '-' + String(Date.now());
168
- var instance = new scenario_instance_type_1.ScenarioInstance(instanceName, scenario, {
164
+ const instanceName = scenario.name + '-' + String(Date.now());
165
+ const instance = new scenario_instance_type_1.ScenarioInstance(instanceName, scenario, {
169
166
  user,
170
167
  domain,
171
168
  variables,
@@ -1 +1 @@
1
- {"version":3,"file":"operato-connector.js","sourceRoot":"","sources":["../../../server/engine/connector/operato-connector.ts"],"names":[],"mappings":";;;;AAAA,gCAA6B;AAE7B,8CAAwF;AACxF,yDAAwD;AAExD,mBAAmB;AACnB,oDAA0B;AAC1B,2CAAyC;AACzC,qEAAiE;AACjE,wDAA4D;AAC5D,sEAA6B;AAE7B,8DAAyD;AAIzD,8DAA0D;AAC1D,mGAAyF;AAEzF,iDAAiF;AACjF,yDAAiE;AAEjE,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC,gEAAgE,CAAC,CAAA;AAEhG,MAAM,cAAc,GAAQ;IAC1B,UAAU,EAAE;QACV,WAAW,EAAE,UAAU;QACvB,WAAW,EAAE,QAAQ;KACtB;IACD,KAAK,EAAE;QACL,WAAW,EAAE,UAAU;QACvB,WAAW,EAAE,KAAK;KACnB;IACD,MAAM,EAAE;QACN,WAAW,EAAE,KAAK;KACnB;CACF,CAAA;AAED,MAAM,KAAK,GAAG,IAAI,oBAAa,CAAC;IAC9B,WAAW,EAAE,KAAK;CACnB,CAAC,CAAA;AAEW,QAAA,WAAW,GAAG,UAAU,CAAA;AACxB,QAAA,gBAAgB,GAAG,mBAAW,CAAA;AAO3C,CAAC;AAAA,EAAE,CAAA;AAEH,MAAa,gBAAgB;IAG3B,KAAK,CAAC,KAAK,CAAC,iBAAoC;QAC9C,MAAM,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;QAEjE,sCAAiB,CAAC,MAAM,CAAC,IAAI,CAAC,yCAAyC,CAAC,CAAA;IAC1E,CAAC;IAED,KAAK,CAAC,OAAO,CAAC,UAA2B;QACvC,IAAI,EACF,QAAQ,EAAE,GAAG,EACb,MAAM,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,oBAAoB,GAAG,EAAE,EAAE,EACvD,GAAG,UAAU,CAAA;QA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AQ,CAAC,IAAI,GAAG,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAA;QAC3D,IAAI,QAAQ,GAAG,IAAI,yCAAgB,CAAC,YAAY,EAAE,QAAQ,EAAE;YAC1D,IAAI;YACJ,MAAM;YACN,SAAS;YACT,MAAM,EAAE,0BAAkB,CAAC,MAAM;SAClC,CAAC,CAAA;QAEF,eAAe;QACf,MAAM,QAAQ,CAAC,GAAG,EAAE,CAAA;QACpB,OAAO,QAAQ,CAAA;IACjB,CAAC;IAED,IAAI,aAAa;QACf,OAAO;YACL;gBACE,IAAI,EAAE,QAAQ;gBACd,IAAI,EAAE,SAAS;gBACf,KAAK,EAAE,UAAU;aAClB;YACD;gBACE,IAAI,EAAE,QAAQ;gBACd,IAAI,EAAE,QAAQ;gBACd,KAAK,EAAE,QAAQ;aAChB;YACD;gBACE,IAAI,EAAE,eAAe;gBACrB,IAAI,EAAE,sBAAsB;gBAC5B,KAAK,EAAE,uBAAuB;aAC/B;SACF,CAAA;IACH,CAAC;IAED,IAAI,YAAY;QACd,OAAO,CAAC,SAAS,CAAC,CAAA;IACpB,CAAC;IAED,IAAI,IAAI;QACN,OAAO,yCAAyC,CAAA;IAClD,CAAC;IAED,IAAI,WAAW;QACb,OAAO,2BAA2B,CAAA;IACpC,CAAC;CACF;AAxND,4CAwNC;AAED,sCAAiB,CAAC,iBAAiB,CAAC,mBAAmB,EAAE,IAAI,gBAAgB,EAAE,CAAC,CAAA","sourcesContent":["import 'cross-fetch/polyfill'\n\nimport { ApolloClient, InMemoryCache, createHttpLink, split } from '@apollo/client/core'\nimport { setContext } from '@apollo/client/link/context'\n\n// for subscription\nimport WebSocket from 'ws'\nimport { createClient } from 'graphql-ws'\nimport { GraphQLWsLink } from '@apollo/client/link/subscriptions'\nimport { getMainDefinition } from '@apollo/client/utilities'\nimport gql from 'graphql-tag'\n\nimport { ConnectionManager } from '../connection-manager'\nimport { Connector } from '../types'\nimport { InputConnection } from '../../service/connection/connection-type'\n\nimport { Scenario } from '../../service/scenario/scenario'\nimport { ScenarioInstance } from '../../service/scenario-instance/scenario-instance-type'\n\nimport { getRepository, GraphqlLocalClient, Domain } from '@things-factory/shell'\nimport { User, checkPermission } from '@things-factory/auth-base'\n\nconst debug = require('debug')('things-factory:integration-base:operato-connector-subscription')\n\nconst defaultOptions: any = {\n watchQuery: {\n fetchPolicy: 'no-cache',\n errorPolicy: 'ignore'\n },\n query: {\n fetchPolicy: 'no-cache', //'network-only'\n errorPolicy: 'all'\n },\n mutate: {\n errorPolicy: 'all'\n }\n}\n\nconst cache = new InMemoryCache({\n addTypename: false\n})\n\nexport const GRAPHQL_URI = '/graphql'\nexport const SUBSCRIPTION_URI = GRAPHQL_URI\n\ninterface SubscriberData {\n tag: string\n scenario: any\n subscriptionObserver: any\n}\n;``\n\nexport class OperatoConnector implements Connector {\n private context: any\n\n async ready(connectionConfigs: InputConnection[]) {\n await Promise.all(connectionConfigs.map(this.connect.bind(this)))\n\n ConnectionManager.logger.info('graphql-connector connections are ready')\n }\n\n async connect(connection: InputConnection) {\n var {\n endpoint: uri,\n params: { authKey, domain, subscriptionHandlers = {} }\n } = connection\n\n if (!authKey || !domain) {\n throw new Error('some connection paramter missing.')\n }\n\n var domainOwner = await getRepository(User).findOne({\n where: {\n id: connection.domain.owner\n }\n })\n\n this.context = {\n domain: connection.domain,\n user: domainOwner\n /* TODO: domainOwner 대신 특정 유저를 지정할 수 있도록 개선해야함. 모든 커넥션에 유저를 지정하는 기능으로 일반화할 필요가 있는 지 고민해야함 */\n }\n\n const httpLink = createHttpLink({\n uri: uri\n })\n\n /* \n CHECKPOINT: \n 1. GraphqQLWsLink를 사용하면 setContext를 통한 추가 헤더 설정이 무시됩니다.\n 따라서, GraphQLWsLink를 사용하려면, connectionParams를 통해 헤더를 설정해야 합니다.\n \n 2. 서버에서 실행시, webSocketImpl을 명시적으로 지정해야 합니다.\n */\n const wsLink = new GraphQLWsLink(\n createClient({\n url: uri.replace(/^http/, 'ws'),\n keepAlive: 10_000,\n retryAttempts: 1_000_000,\n shouldRetry: e => true,\n webSocketImpl: WebSocket,\n connectionParams: {\n headers: {\n 'x-things-factory-domain': domain,\n authorization: authKey ? `Bearer ${authKey}` : ''\n }\n }\n })\n )\n\n const splitLink = split(\n ({ query }) => {\n const def = getMainDefinition(query)\n return def.kind === 'OperationDefinition' && def.operation === 'subscription'\n },\n wsLink,\n setContext((_, { headers }) => {\n return {\n headers: {\n ...headers,\n 'x-things-factory-domain': domain,\n authorization: authKey ? `Bearer ${authKey}` : ''\n }\n }\n }).concat(httpLink)\n )\n\n var client = new ApolloClient({\n defaultOptions,\n cache,\n link: splitLink\n })\n\n var subscriptions: SubscriberData[] = []\n Object.keys(subscriptionHandlers).forEach(async tag => {\n if (!tag || !subscriptionHandlers[tag]) return\n\n let scenarioName = subscriptionHandlers[tag]\n\n // fetch a scenario\n var selectedScenario = await getRepository(Scenario).findOne({\n where: {\n name: scenarioName\n },\n relations: ['steps', 'domain']\n })\n\n const subscription = client.subscribe({\n query: gql`\n subscription {\n data(tag: \"${tag}\") {\n tag\n data\n }\n }\n `\n })\n\n var subscriptionObserver = subscription.subscribe({\n next: async data => {\n debug('received pubsub msg.:', data?.data)\n await this.runScenario(subscriptions, data?.data?.data)\n },\n error: error => {\n ConnectionManager.logger.error(`(${connection.name}:${connection.endpoint}) subscription error: ${error}`)\n },\n complete: () => {\n ConnectionManager.logger.info(`(${connection.name}:${connection.endpoint}) subscription complete`)\n }\n })\n\n ConnectionManager.logger.info(\n `(${connection.name}:${connection.endpoint}) subscription closed flag: ${subscriptionObserver.closed}`\n )\n\n subscriptions.push({\n tag,\n scenario: selectedScenario,\n subscriptionObserver\n })\n ConnectionManager.logger.info(`(${tag}:${scenarioName}) subscription closed flag: ${subscriptionObserver.closed}`)\n })\n\n client['subscriptions'] = subscriptions\n ConnectionManager.addConnectionInstance(connection, client)\n\n ConnectionManager.logger.info(\n `graphql-connector connection(${connection.name}:${connection.endpoint}) is connected`\n )\n }\n\n async disconnect(connection: InputConnection) {\n var client = ConnectionManager.getConnectionInstance(connection)\n let subscriptions: SubscriberData[] = client['subscriptions']\n subscriptions.forEach(subscription => subscription.subscriptionObserver.unsubscribe())\n client.stop()\n ConnectionManager.removeConnectionInstance(connection)\n\n ConnectionManager.logger.info(`graphql-connector connection(${connection.name}) is disconnected`)\n }\n\n async runScenario(subscriptions: SubscriberData[], variables: any): Promise<ScenarioInstance> {\n const { domain, user, unsafeIP, prohibitedPrivileges } = this.context\n const { tag } = variables\n\n if (!tag) {\n throw new Error(`tag is invalid - ${tag}`)\n }\n\n var scenario = subscriptions.find(subscription => subscription.tag === tag)?.scenario\n if (!scenario) {\n throw new Error(`scenario is not found - ${tag}`)\n }\n\n if (!(await checkPermission(scenario.privilege, user, domain, unsafeIP, prohibitedPrivileges))) {\n const { category, privilege } = scenario.privilege || {}\n throw new Error(\n `Unauthorized! ${\n category && privilege ? category + ':' + privilege + ' privilege' : 'ownership granted'\n } required`\n )\n }\n\n /* create a scenario instance */\n let instanceName = scenario.name + '-' + String(Date.now())\n var instance = new ScenarioInstance(instanceName, scenario, {\n user,\n domain,\n variables,\n client: GraphqlLocalClient.client\n })\n\n // run scenario\n await instance.run()\n return instance\n }\n\n get parameterSpec() {\n return [\n {\n type: 'string',\n name: 'authKey',\n label: 'auth-key'\n },\n {\n type: 'string',\n name: 'domain',\n label: 'domain'\n },\n {\n type: 'tag-scenarios',\n name: 'subscriptionHandlers',\n label: 'subscription-handlers'\n }\n ]\n }\n\n get taskPrefixes() {\n return ['graphql']\n }\n\n get help() {\n return 'integration/connector/operato-connector'\n }\n\n get description() {\n return 'Operato Graphql Connector'\n }\n}\n\nConnectionManager.registerConnector('operato-connector', new OperatoConnector())\n"]}
1
+ {"version":3,"file":"operato-connector.js","sourceRoot":"","sources":["../../../server/engine/connector/operato-connector.ts"],"names":[],"mappings":";;;;AAAA,gCAA6B;AAE7B,8CAAwF;AACxF,yDAAwD;AAExD,oDAA0B;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M;YACN,SAAS;YACT,MAAM,EAAE,0BAAkB,CAAC,MAAM;SAClC,CAAC,CAAA;QAEF,eAAe;QACf,MAAM,QAAQ,CAAC,GAAG,EAAE,CAAA;QACpB,OAAO,QAAQ,CAAA;IACjB,CAAC;IAED,IAAI,aAAa;QACf,OAAO;YACL;gBACE,IAAI,EAAE,QAAQ;gBACd,IAAI,EAAE,SAAS;gBACf,KAAK,EAAE,UAAU;aAClB;YACD;gBACE,IAAI,EAAE,QAAQ;gBACd,IAAI,EAAE,QAAQ;gBACd,KAAK,EAAE,QAAQ;aAChB;YACD;gBACE,IAAI,EAAE,eAAe;gBACrB,IAAI,EAAE,sBAAsB;gBAC5B,KAAK,EAAE,uBAAuB;aAC/B;SACF,CAAA;IACH,CAAC;IAED,IAAI,YAAY;QACd,OAAO,CAAC,SAAS,CAAC,CAAA;IACpB,CAAC;IAED,IAAI,IAAI;QACN,OAAO,yCAAyC,CAAA;IAClD,CAAC;IAED,IAAI,WAAW;QACb,OAAO,2BAA2B,CAAA;IACpC,CAAC;CACF;AApND,4CAoNC;AAED,sCAAiB,CAAC,iBAAiB,CAAC,mBAAmB,EAAE,IAAI,gBAAgB,EAAE,CAAC,CAAA","sourcesContent":["import 'cross-fetch/polyfill'\n\nimport { ApolloClient, InMemoryCache, createHttpLink, split } from '@apollo/client/core'\nimport { setContext } from '@apollo/client/link/context'\n\nimport WebSocket from 'ws'\nimport { createClient } from 'graphql-ws'\nimport { GraphQLWsLink } from '@apollo/client/link/subscriptions'\nimport { getMainDefinition } from '@apollo/client/utilities'\nimport gql from 'graphql-tag'\n\nimport { ConnectionManager } from '../connection-manager'\nimport { Connector } from '../types'\nimport { InputConnection } from '../../service/connection/connection-type'\n\nimport { Scenario } from '../../service/scenario/scenario'\nimport { ScenarioInstance } from '../../service/scenario-instance/scenario-instance-type'\n\nimport { getRepository, GraphqlLocalClient, Domain } from '@things-factory/shell'\nimport { User, checkPermission } from '@things-factory/auth-base'\n\nconst debug = require('debug')('things-factory:integration-base:operato-connector')\n\nconst defaultOptions: any = {\n watchQuery: {\n fetchPolicy: 'no-cache',\n errorPolicy: 'ignore'\n },\n query: {\n fetchPolicy: 'no-cache', //'network-only'\n errorPolicy: 'all'\n },\n mutate: {\n errorPolicy: 'all'\n }\n}\n\nexport const GRAPHQL_URI = '/graphql'\nexport const SUBSCRIPTION_URI = GRAPHQL_URI\n\ninterface SubscriberData {\n tag: string\n scenario: any\n subscriptionObserver: any\n}\n\nexport class OperatoConnector implements Connector {\n private context: any\n\n async ready(connectionConfigs: InputConnection[]) {\n await Promise.all(connectionConfigs.map(this.connect.bind(this)))\n\n ConnectionManager.logger.info('operato-connector connections are ready')\n }\n\n async connect(connection: InputConnection) {\n const {\n endpoint: uri,\n params: { authKey, domain, subscriptionHandlers = {} }\n } = connection\n\n if (!authKey || !domain) {\n throw new Error('some connection paramter missing.')\n }\n\n const domainOwner = await getRepository(User).findOne({\n where: {\n id: connection.domain.owner\n }\n })\n\n this.context = {\n domain: connection.domain,\n user: domainOwner\n /* TODO: domainOwner 대신 특정 유저를 지정할 수 있도록 개선해야함. 모든 커넥션에 유저를 지정하는 기능으로 일반화할 필요가 있는 지 고민해야함 */\n }\n\n const httpLink = createHttpLink({\n uri: uri\n })\n\n /* \n CHECKPOINT: \n 1. GraphqQLWsLink를 사용하면 setContext를 통한 추가 헤더 설정이 무시됩니다.\n 따라서, GraphQLWsLink를 사용하려면, connectionParams를 통해 헤더를 설정해야 합니다.\n \n 2. 서버에서 실행시, webSocketImpl을 명시적으로 지정해야 합니다.\n */\n const wsLink = new GraphQLWsLink(\n createClient({\n url: uri.replace(/^http/, 'ws'),\n keepAlive: 10_000,\n retryAttempts: 1_000_000,\n shouldRetry: e => true,\n webSocketImpl: WebSocket,\n connectionParams: {\n headers: {\n 'x-things-factory-domain': domain,\n authorization: authKey ? `Bearer ${authKey}` : ''\n }\n }\n })\n )\n\n const splitLink = split(\n ({ query }) => {\n const def = getMainDefinition(query)\n return def.kind === 'OperationDefinition' && def.operation === 'subscription'\n },\n wsLink,\n setContext((_, { headers }) => {\n return {\n headers: {\n ...headers,\n 'x-things-factory-domain': domain,\n authorization: authKey ? `Bearer ${authKey}` : ''\n }\n }\n }).concat(httpLink)\n )\n\n const cache = new InMemoryCache({\n addTypename: false\n })\n\n const client = new ApolloClient({\n defaultOptions,\n cache,\n link: splitLink\n })\n\n const subscriptions: SubscriberData[] = []\n Object.keys(subscriptionHandlers).forEach(async tag => {\n if (!tag || !subscriptionHandlers[tag]) return\n\n const scenarioName = subscriptionHandlers[tag]\n\n // fetch a scenario\n const selectedScenario = await getRepository(Scenario).findOne({\n where: {\n name: scenarioName\n },\n relations: ['steps', 'domain']\n })\n\n const subscription = client.subscribe({\n query: gql`\n subscription {\n data(tag: \"${tag}\") {\n tag\n data\n }\n }\n `\n })\n\n const subscriptionObserver = subscription.subscribe({\n next: async data => {\n debug('received pubsub msg.:', data?.data)\n await this.runScenario(subscriptions, data?.data?.data)\n },\n error: error => {\n ConnectionManager.logger.error(`(${connection.name}:${connection.endpoint}) subscription error: ${error}`)\n },\n complete: () => {\n ConnectionManager.logger.info(`(${connection.name}:${connection.endpoint}) subscription complete`)\n }\n })\n\n ConnectionManager.logger.info(`(${connection.name}:${connection.endpoint}) subscription closed flag: ${subscriptionObserver.closed}`)\n\n subscriptions.push({\n tag,\n scenario: selectedScenario,\n subscriptionObserver\n })\n ConnectionManager.logger.info(`(${tag}:${scenarioName}) subscription closed flag: ${subscriptionObserver.closed}`)\n })\n\n client['subscriptions'] = subscriptions\n ConnectionManager.addConnectionInstance(connection, client)\n\n ConnectionManager.logger.info(`operato-connector connection(${connection.name}:${connection.endpoint}) is connected`)\n }\n\n async disconnect(connection: InputConnection) {\n const client = ConnectionManager.getConnectionInstance(connection)\n const subscriptions: SubscriberData[] = client['subscriptions']\n subscriptions.forEach(subscription => subscription.subscriptionObserver.unsubscribe())\n client.stop()\n ConnectionManager.removeConnectionInstance(connection)\n\n ConnectionManager.logger.info(`operato-connector connection(${connection.name}) is disconnected`)\n }\n\n async runScenario(subscriptions: SubscriberData[], variables: any): Promise<ScenarioInstance> {\n const { domain, user, unsafeIP, prohibitedPrivileges } = this.context\n const { tag } = variables\n\n if (!tag) {\n throw new Error(`tag is invalid - ${tag}`)\n }\n\n const scenario = subscriptions.find(subscription => subscription.tag === tag)?.scenario\n if (!scenario) {\n throw new Error(`scenario is not found - ${tag}`)\n }\n\n if (!(await checkPermission(scenario.privilege, user, domain, unsafeIP, prohibitedPrivileges))) {\n const { category, privilege } = scenario.privilege || {}\n throw new Error(`Unauthorized! ${category && privilege ? category + ':' + privilege + ' privilege' : 'ownership granted'} required`)\n }\n\n /* create a scenario instance */\n const instanceName = scenario.name + '-' + String(Date.now())\n const instance = new ScenarioInstance(instanceName, scenario, {\n user,\n domain,\n variables,\n client: GraphqlLocalClient.client\n })\n\n // run scenario\n await instance.run()\n return instance\n }\n\n get parameterSpec() {\n return [\n {\n type: 'string',\n name: 'authKey',\n label: 'auth-key'\n },\n {\n type: 'string',\n name: 'domain',\n label: 'domain'\n },\n {\n type: 'tag-scenarios',\n name: 'subscriptionHandlers',\n label: 'subscription-handlers'\n }\n ]\n }\n\n get taskPrefixes() {\n return ['graphql']\n }\n\n get help() {\n return 'integration/connector/operato-connector'\n }\n\n get description() {\n return 'Operato Graphql Connector'\n }\n}\n\nConnectionManager.registerConnector('operato-connector', new OperatoConnector())\n"]}
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ProxyConnector = void 0;
4
+ const connection_manager_1 = require("../connection-manager");
5
+ const edge_client_1 = require("../edge-client");
6
+ /**
7
+ * This connector is a proxy connector installed on the edge server to manage connections from the host.
8
+ * It interacts with connections established on the edge server and provides synchronization functionality.
9
+ */
10
+ class ProxyConnector {
11
+ async ready(connectionConfigs) {
12
+ await Promise.all(connectionConfigs.map(this.connect.bind(this)));
13
+ connection_manager_1.ConnectionManager.logger.info('proxy-connector connections are ready');
14
+ }
15
+ async connect(connection) {
16
+ // TODO 원래 커넥션과 에지설정을 참고하여, 에지 서버로 CONNECT/DISCONNECT 명령을 보낸다.
17
+ const proxy = {
18
+ disconnect: async () => {
19
+ connection_manager_1.ConnectionManager.logger.info('[proxy-connector] trying disconnect');
20
+ await (0, edge_client_1.disconnectConnections)([connection]);
21
+ }
22
+ };
23
+ await (0, edge_client_1.connectConnections)([connection]);
24
+ connection_manager_1.ConnectionManager.addConnectionInstance(connection, proxy);
25
+ connection_manager_1.ConnectionManager.logger.info(`proxy-connector connection(${connection.name}:${connection.endpoint}) is connected`);
26
+ }
27
+ async disconnect(connection) {
28
+ const proxy = connection_manager_1.ConnectionManager.removeConnectionInstance(connection);
29
+ await proxy.disconnect();
30
+ connection_manager_1.ConnectionManager.logger.info(`proxy-connector connection(${connection.name}) is disconnected`);
31
+ }
32
+ get parameterSpec() {
33
+ return [];
34
+ }
35
+ get taskPrefixes() {
36
+ return [];
37
+ }
38
+ get description() {
39
+ return 'Operato Proxy Connector';
40
+ }
41
+ }
42
+ exports.ProxyConnector = ProxyConnector;
43
+ ProxyConnector.instance = new ProxyConnector();
44
+ //# sourceMappingURL=proxy-connector.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"proxy-connector.js","sourceRoot":"","sources":["../../../server/engine/connector/proxy-connector.ts"],"names":[],"mappings":";;;AAAA,8DAAyD;AAGzD,gDAA0E;AAE1E;;;GAGG;AACH,MAAa,cAAc;IAGzB,KAAK,CAAC,KAAK,CAAC,iBAAoC;QAC9C,MAAM,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;QAEjE,sCAAiB,CAAC,MAAM,CAAC,IAAI,CAAC,uCAAuC,CAAC,CAAA;IACxE,CAAC;IAED,KAAK,CAAC,OAAO,CAAC,UAA2B;QACvC,8DAA8D;QAC9D,MAAM,KAAK,GAAG;YACZ,UAAU,EAAE,KAAK,IAAI,EAAE;gBACrB,sCAAiB,CAAC,MAAM,CAAC,IAAI,CAAC,qCAAqC,CAAC,CAAA;gBACpE,MAAM,IAAA,mCAAqB,EAAC,CAAC,UAAU,CAAC,CAAC,CAAA;YAC3C,CAAC;SACF,CAAA;QAED,MAAM,IAAA,gCAAkB,EAAC,CAAC,UAAU,CAAC,CAAC,CAAA;QAEtC,sCAAiB,CAAC,qBAAqB,CAAC,UAAU,EAAE,KAAK,CAAC,CAAA;QAE1D,sCAAiB,CAAC,MAAM,CAAC,IAAI,CAAC,8BAA8B,UAAU,CAAC,IAAI,IAAI,UAAU,CAAC,QAAQ,gBAAgB,CAAC,CAAA;IACrH,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,UAA2B;QAC1C,MAAM,KAAK,GAAG,sCAAiB,CAAC,wBAAwB,CAAC,UAAU,CAAC,CAAA;QACpE,MAAM,KAAK,CAAC,UAAU,EAAE,CAAA;QAExB,sCAAiB,CAAC,MAAM,CAAC,IAAI,CAAC,8BAA8B,UAAU,CAAC,IAAI,mBAAmB,CAAC,CAAA;IACjG,CAAC;IAED,IAAI,aAAa;QACf,OAAO,EAAE,CAAA;IACX,CAAC;IAED,IAAI,YAAY;QACd,OAAO,EAAE,CAAA;IACX,CAAC;IAED,IAAI,WAAW;QACb,OAAO,yBAAyB,CAAA;IAClC,CAAC;;AA1CH,wCA2CC;AA1Ce,uBAAQ,GAAG,IAAI,cAAc,EAAE,CAAA","sourcesContent":["import { ConnectionManager } from '../connection-manager'\nimport { Connector } from '../types'\nimport { InputConnection } from '../../service/connection/connection-type'\nimport { connectConnections, disconnectConnections } from '../edge-client'\n\n/**\n * This connector is a proxy connector installed on the edge server to manage connections from the host.\n * It interacts with connections established on the edge server and provides synchronization functionality.\n */\nexport class ProxyConnector implements Connector {\n public static instance = new ProxyConnector()\n\n async ready(connectionConfigs: InputConnection[]) {\n await Promise.all(connectionConfigs.map(this.connect.bind(this)))\n\n ConnectionManager.logger.info('proxy-connector connections are ready')\n }\n\n async connect(connection: InputConnection) {\n // TODO 원래 커넥션과 에지설정을 참고하여, 에지 서버로 CONNECT/DISCONNECT 명령을 보낸다.\n const proxy = {\n disconnect: async () => {\n ConnectionManager.logger.info('[proxy-connector] trying disconnect')\n await disconnectConnections([connection])\n }\n }\n\n await connectConnections([connection])\n\n ConnectionManager.addConnectionInstance(connection, proxy)\n\n ConnectionManager.logger.info(`proxy-connector connection(${connection.name}:${connection.endpoint}) is connected`)\n }\n\n async disconnect(connection: InputConnection) {\n const proxy = ConnectionManager.removeConnectionInstance(connection)\n await proxy.disconnect()\n\n ConnectionManager.logger.info(`proxy-connector connection(${connection.name}) is disconnected`)\n }\n\n get parameterSpec() {\n return []\n }\n\n get taskPrefixes() {\n return []\n }\n\n get description() {\n return 'Operato Proxy Connector'\n }\n}\n"]}
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.setEdgeClient = exports.disconnectConnections = exports.connectConnections = exports.syncConnections = exports.handler = void 0;
4
+ var edgeClient = {
5
+ async handler(step, scenarioContext) {
6
+ throw 'edgeClient not supported';
7
+ },
8
+ async syncConnections(connections, context) {
9
+ throw 'edgeClient not supported';
10
+ },
11
+ async connectConnections(connections, context) {
12
+ throw 'edgeClient not supported';
13
+ },
14
+ async disconnectConnections(connections, context) {
15
+ throw 'edgeClient not supported';
16
+ }
17
+ };
18
+ async function handler(step, scenarioContext) {
19
+ return await edgeClient.handler(step, scenarioContext);
20
+ }
21
+ exports.handler = handler;
22
+ async function syncConnections(connections, context) {
23
+ return await edgeClient.syncConnections(connections, context);
24
+ }
25
+ exports.syncConnections = syncConnections;
26
+ async function connectConnections(connections, context) {
27
+ return await edgeClient.connectConnections(connections, context);
28
+ }
29
+ exports.connectConnections = connectConnections;
30
+ async function disconnectConnections(connections, context) {
31
+ return await edgeClient.disconnectConnections(connections, context);
32
+ }
33
+ exports.disconnectConnections = disconnectConnections;
34
+ function setEdgeClient(edge) {
35
+ edgeClient = edge;
36
+ }
37
+ exports.setEdgeClient = setEdgeClient;
38
+ //# sourceMappingURL=edge-client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"edge-client.js","sourceRoot":"","sources":["../../server/engine/edge-client.ts"],"names":[],"mappings":";;;AAWA,IAAI,UAAU,GAAe;IAC3B,KAAK,CAAC,OAAO,CAAC,IAAU,EAAE,eAAwB;QAChD,MAAM,0BAA0B,CAAA;IAClC,CAAC;IACD,KAAK,CAAC,eAAe,CAAC,WAAyB,EAAE,OAAwB;QACvE,MAAM,0BAA0B,CAAA;IAClC,CAAC;IACD,KAAK,CAAC,kBAAkB,CAAC,WAAyB,EAAE,OAAwB;QAC1E,MAAM,0BAA0B,CAAA;IAClC,CAAC;IACD,KAAK,CAAC,qBAAqB,CAAC,WAAyB,EAAE,OAAwB;QAC7E,MAAM,0BAA0B,CAAA;IAClC,CAAC;CACF,CAAA;AAEM,KAAK,UAAU,OAAO,CAAC,IAAU,EAAE,eAAwB;IAChE,OAAO,MAAM,UAAU,CAAC,OAAO,CAAC,IAAI,EAAE,eAAe,CAAC,CAAA;AACxD,CAAC;AAFD,0BAEC;AAEM,KAAK,UAAU,eAAe,CAAC,WAAyB,EAAE,OAAyB;IACxF,OAAO,MAAM,UAAU,CAAC,eAAe,CAAC,WAAW,EAAE,OAAO,CAAC,CAAA;AAC/D,CAAC;AAFD,0CAEC;AAEM,KAAK,UAAU,kBAAkB,CAAC,WAAyB,EAAE,OAAyB;IAC3F,OAAO,MAAM,UAAU,CAAC,kBAAkB,CAAC,WAAW,EAAE,OAAO,CAAC,CAAA;AAClE,CAAC;AAFD,gDAEC;AAEM,KAAK,UAAU,qBAAqB,CAAC,WAAyB,EAAE,OAAyB;IAC9F,OAAO,MAAM,UAAU,CAAC,qBAAqB,CAAC,WAAW,EAAE,OAAO,CAAC,CAAA;AACrE,CAAC;AAFD,sDAEC;AAED,SAAgB,aAAa,CAAC,IAAgB;IAC5C,UAAU,GAAG,IAAI,CAAA;AACnB,CAAC;AAFD,sCAEC","sourcesContent":["import { Connection } from '../service/connection/connection-type'\nimport { Step } from '../service/step/step-type'\nimport { Context, TaskHandler } from './types'\n\nexport type EdgeClient = {\n handler: TaskHandler\n syncConnections(connections: Connection[], context?: ResolverContext): Promise<any>\n connectConnections(connections: Connection[], context?: ResolverContext): Promise<any>\n disconnectConnections(connections: Connection[], context?: ResolverContext): Promise<any>\n}\n\nvar edgeClient: EdgeClient = {\n async handler(step: Step, scenarioContext: Context) {\n throw 'edgeClient not supported'\n },\n async syncConnections(connections: Connection[], context: ResolverContext): Promise<any> {\n throw 'edgeClient not supported'\n },\n async connectConnections(connections: Connection[], context: ResolverContext): Promise<any> {\n throw 'edgeClient not supported'\n },\n async disconnectConnections(connections: Connection[], context: ResolverContext): Promise<any> {\n throw 'edgeClient not supported'\n }\n}\n\nexport async function handler(step: Step, scenarioContext: Context) {\n return await edgeClient.handler(step, scenarioContext)\n}\n\nexport async function syncConnections(connections: Connection[], context?: ResolverContext): Promise<any> {\n return await edgeClient.syncConnections(connections, context)\n}\n\nexport async function connectConnections(connections: Connection[], context?: ResolverContext): Promise<any> {\n return await edgeClient.connectConnections(connections, context)\n}\n\nexport async function disconnectConnections(connections: Connection[], context?: ResolverContext): Promise<any> {\n return await edgeClient.disconnectConnections(connections, context)\n}\n\nexport function setEdgeClient(edge: EdgeClient) {\n edgeClient = edge\n}\n"]}
@@ -7,4 +7,5 @@ tslib_1.__exportStar(require("./connection-manager"), exports);
7
7
  tslib_1.__exportStar(require("./scenario-engine"), exports);
8
8
  tslib_1.__exportStar(require("./task-registry"), exports);
9
9
  tslib_1.__exportStar(require("./analyzer/analyze-integration"), exports);
10
+ tslib_1.__exportStar(require("./edge-client"), exports);
10
11
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../server/engine/index.ts"],"names":[],"mappings":";;;AAAA,uBAAoB;AACpB,kBAAe;AAEf,+DAAoC;AACpC,4DAAiC;AACjC,0DAA+B;AAC/B,yEAA8C","sourcesContent":["import './connector'\nimport './task'\n\nexport * from './connection-manager'\nexport * from './scenario-engine'\nexport * from './task-registry'\nexport * from './analyzer/analyze-integration'\n\nexport { Connector } from './types'\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../server/engine/index.ts"],"names":[],"mappings":";;;AAAA,uBAAoB;AACpB,kBAAe;AAEf,+DAAoC;AACpC,4DAAiC;AACjC,0DAA+B;AAC/B,yEAA8C;AAC9C,wDAA6B","sourcesContent":["import './connector'\nimport './task'\n\nexport * from './connection-manager'\nexport * from './scenario-engine'\nexport * from './task-registry'\nexport * from './analyzer/analyze-integration'\nexport * from './edge-client'\n\nexport { Connector } from './types'\n"]}
@@ -13,6 +13,7 @@ async function Script(step, context) {
13
13
  domain,
14
14
  user,
15
15
  lng,
16
+ logger,
16
17
  data,
17
18
  variables
18
19
  }
@@ -1 +1 @@
1
- {"version":3,"file":"script.js","sourceRoot":"","sources":["../../../server/engine/task/script.ts"],"names":[],"mappings":";;AAAA,oDAA+C;AAC/C,6BAA4B;AAK5B,KAAK,UAAU,MAAM,CAAC,IAAe,EAAE,OAAgB;IACrD,IAAI,EACF,MAAM,EAAE,EAAE,MAAM,EAAE,EACnB,GAAG,IAAI,CAAA;IAER,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,OAAO,CAAA;IAE9D,MAAM,EAAE,GAAG,IAAI,YAAM,CAAC;QACpB,OAAO,EAAE,IAAI;QACb,OAAO,EAAE,MAAM;QACf,OAAO,EAAE,SAAS;QAClB,OAAO,EAAE;YACP,MAAM;YACN,IAAI;YACJ,GAAG;YACH,IAAI;YACJ,SAAS;SACV;KACF,CAAC,CAAA;IAEF,IAAI,MAAM,GAAG,MAAM,EAAE,CAAC,GAAG,CAAC,0BAA0B,MAAM,QAAQ,CAAC,CAAA;IAEnE,OAAO;QACL,IAAI,EAAE,MAAM;KACb,CAAA;AACH,CAAC;AAED,MAAM,CAAC,aAAa,GAAG;IACrB;QACE,IAAI,EAAE,UAAU;QAChB,IAAI,EAAE,QAAQ;QACd,KAAK,EAAE,QAAQ;QACf,QAAQ,EAAE;YACR,QAAQ,EAAE,YAAY;SACvB;KACF;CACF,CAAA;AAED,MAAM,CAAC,aAAa,GAAG,IAAI,CAAA;AAC3B,MAAM,CAAC,IAAI,GAAG,yBAAyB,CAAA;AAEvC,4BAAY,CAAC,mBAAmB,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAA","sourcesContent":["import { TaskRegistry } from '../task-registry'\nimport { NodeVM } from 'vm2'\n\nimport { InputStep } from '../../service/step/step-type'\nimport { Context } from '../types'\n\nasync function Script(step: InputStep, context: Context) {\n var {\n params: { script }\n } = step\n\n const { domain, user, data, variables, lng, logger } = context\n\n const vm = new NodeVM({\n timeout: 5000,\n wrapper: 'none',\n console: 'inherit',\n sandbox: {\n domain,\n user,\n lng,\n data,\n variables\n }\n })\n\n var result = await vm.run(`return (async () => {\\n${script}\\n})()`)\n\n return {\n data: result\n }\n}\n\nScript.parameterSpec = [\n {\n type: 'textarea',\n name: 'script',\n label: 'script',\n property: {\n language: 'javascript'\n }\n }\n]\n\nScript.connectorFree = true\nScript.help = 'integration/task/script'\n\nTaskRegistry.registerTaskHandler('script', Script)\n"]}
1
+ {"version":3,"file":"script.js","sourceRoot":"","sources":["../../../server/engine/task/script.ts"],"names":[],"mappings":";;AAAA,oDAA+C;AAC/C,6BAA4B;AAK5B,KAAK,UAAU,MAAM,CAAC,IAAe,EAAE,OAAgB;IACrD,IAAI,EACF,MAAM,EAAE,EAAE,MAAM,EAAE,EACnB,GAAG,IAAI,CAAA;IAER,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,OAAO,CAAA;IAE9D,MAAM,EAAE,GAAG,IAAI,YAAM,CAAC;QACpB,OAAO,EAAE,IAAI;QACb,OAAO,EAAE,MAAM;QACf,OAAO,EAAE,SAAS;QAClB,OAAO,EAAE;YACP,MAAM;YACN,IAAI;YACJ,GAAG;YACH,MAAM;YACN,IAAI;YACJ,SAAS;SACV;KACF,CAAC,CAAA;IAEF,IAAI,MAAM,GAAG,MAAM,EAAE,CAAC,GAAG,CAAC,0BAA0B,MAAM,QAAQ,CAAC,CAAA;IAEnE,OAAO;QACL,IAAI,EAAE,MAAM;KACb,CAAA;AACH,CAAC;AAED,MAAM,CAAC,aAAa,GAAG;IACrB;QACE,IAAI,EAAE,UAAU;QAChB,IAAI,EAAE,QAAQ;QACd,KAAK,EAAE,QAAQ;QACf,QAAQ,EAAE;YACR,QAAQ,EAAE,YAAY;SACvB;KACF;CACF,CAAA;AAED,MAAM,CAAC,aAAa,GAAG,IAAI,CAAA;AAC3B,MAAM,CAAC,IAAI,GAAG,yBAAyB,CAAA;AAEvC,4BAAY,CAAC,mBAAmB,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAA","sourcesContent":["import { TaskRegistry } from '../task-registry'\nimport { NodeVM } from 'vm2'\n\nimport { InputStep } from '../../service/step/step-type'\nimport { Context } from '../types'\n\nasync function Script(step: InputStep, context: Context) {\n var {\n params: { script }\n } = step\n\n const { domain, user, data, variables, lng, logger } = context\n\n const vm = new NodeVM({\n timeout: 5000,\n wrapper: 'none',\n console: 'inherit',\n sandbox: {\n domain,\n user,\n lng,\n logger,\n data,\n variables\n }\n })\n\n var result = await vm.run(`return (async () => {\\n${script}\\n})()`)\n\n return {\n data: result\n }\n}\n\nScript.parameterSpec = [\n {\n type: 'textarea',\n name: 'script',\n label: 'script',\n property: {\n language: 'javascript'\n }\n }\n]\n\nScript.connectorFree = true\nScript.help = 'integration/task/script'\n\nTaskRegistry.registerTaskHandler('script', Script)\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../server/engine/types.ts"],"names":[],"mappings":"","sourcesContent":["import { Connection, PropertySpec, ScenarioInstanceStatus, Step } from '../service'\nimport { Domain } from '@things-factory/shell'\nimport { User } from '@things-factory/auth-base'\n\nexport interface Connector {\n ready(connections: Connection[]): Promise<any>\n connect(connection: Connection): Promise<any>\n disconnect(connection: Connection): Promise<any>\n parameterSpec: PropertySpec[]\n taskPrefixes?: string[]\n description?: string\n help?: string\n}\n\nexport type Context = {\n /** \n * Represents the domain context.\n */\n domain: Domain\n\n /** \n * User information.\n */\n user: User\n\n /** \n * Language code, for example 'en', 'ko'.\n */\n lng: string\n\n /** \n * Flag to indicate if the IP is unsafe, can be undefined.\n */\n unsafeIP: boolean | undefined\n\n /** \n * List of prohibited privileges, can be undefined.\n */\n prohibitedPrivileges: { category: string; privilege: string }[] | undefined\n\n /** \n * Logger for logging purposes.\n */\n logger: any\n\n /** \n * Function to publish events or messages.\n */\n publish: Function\n\n /** \n * Function to load resources or data.\n */\n load: Function\n\n /** \n * Current status of the scenario instance.\n */\n state: ScenarioInstanceStatus\n\n /** \n * General data storage object.\n */\n data: any\n\n /** \n * Variables related to the context.\n */\n variables: Object\n\n /** \n * Local GraphQL client object.\n */\n client: any /* graphql local client */\n\n /** \n * Root object, can be used for various purposes.\n */\n root: Object\n\n /** \n * Array of function closures.\n */\n closures: Function[]\n\n /** \n * Function to check the state.\n */\n checkState: Function\n\n /**\n * MQTT subscriber context object.\n */\n __mqtt_subscriber?: any\n\n /**\n * socket listener context object.\n */\n __socket_listener?: any\n\n /**\n * csv readline context object.\n */\n __csv_resources?: any\n}\n\n\nexport type TaskHandler = (\n step: Step,\n context: Context\n) => Promise<{\n next?: string\n state?: ScenarioInstanceStatus\n data?: any\n}>\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../server/engine/types.ts"],"names":[],"mappings":"","sourcesContent":["import { Connection, PropertySpec, ScenarioInstanceStatus, Step } from '../service'\nimport { Domain } from '@things-factory/shell'\nimport { User } from '@things-factory/auth-base'\n\nexport interface Connector {\n ready(connections: Connection[]): Promise<any>\n connect(connection: Connection): Promise<any>\n disconnect(connection: Connection): Promise<any>\n parameterSpec: PropertySpec[]\n taskPrefixes?: string[]\n description?: string\n help?: string\n}\n\nexport type Context = {\n /**\n * Represents the domain context.\n */\n domain: Domain\n\n /**\n * User information.\n */\n user: User\n\n /**\n * Language code, for example 'en', 'ko'.\n */\n lng: string\n\n /**\n * Flag to indicate if the IP is unsafe, can be undefined.\n */\n unsafeIP: boolean | undefined\n\n /**\n * List of prohibited privileges, can be undefined.\n */\n prohibitedPrivileges: { category: string; privilege: string }[] | undefined\n\n /**\n * Logger for logging purposes.\n */\n logger: any\n\n /**\n * Function to publish events or messages.\n */\n publish: Function\n\n /**\n * Function to load resources or data.\n */\n load: Function\n\n /**\n * Current status of the scenario instance.\n */\n state: ScenarioInstanceStatus\n\n /**\n * General data storage object.\n */\n data: any\n\n /**\n * Variables related to the context.\n */\n variables: Object\n\n /**\n * Local GraphQL client object.\n */\n client: any /* graphql local client */\n\n /**\n * Root object, can be used for various purposes.\n */\n root: Object\n\n /**\n * Array of function closures.\n */\n closures: Function[]\n\n /**\n * Function to check the state.\n */\n checkState: Function\n\n /**\n * MQTT subscriber context object.\n */\n __mqtt_subscriber?: any\n\n /**\n * socket listener context object.\n */\n __socket_listener?: any\n\n /**\n * csv readline context object.\n */\n __csv_resources?: any\n}\n\nexport type TaskHandler = (\n step: Step,\n context: Context\n) => Promise<{\n next?: string\n state?: ScenarioInstanceStatus\n data?: any\n}>\n"]}