UNPKG

8.44 kBJavaScriptView Raw
1"use strict";
2var __importDefault = (this && this.__importDefault) || function (mod) {
3 return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5Object.defineProperty(exports, "__esModule", { value: true });
6const path_1 = __importDefault(require("path"));
7const events_1 = require("events");
8const utils_1 = require("@terascope/utils");
9function newId(prefix) {
10 return `${prefix}-${utils_1.random(10000, 99999)}`;
11}
12function newTestSlice(request = {}) {
13 return {
14 slice_id: newId('slice-id'),
15 slicer_id: utils_1.random(0, 99999),
16 slicer_order: utils_1.random(0, 99999),
17 request,
18 _created: new Date().toISOString(),
19 };
20}
21exports.newTestSlice = newTestSlice;
22function newTestJobConfig(defaults = {}) {
23 return Object.assign({
24 name: 'test-job',
25 apis: [],
26 operations: [],
27 analytics: false,
28 assets: [],
29 lifecycle: 'once',
30 max_retries: 0,
31 probation_window: 30000,
32 recycle_worker: 0,
33 slicers: 1,
34 workers: 1,
35 }, defaults);
36}
37exports.newTestJobConfig = newTestJobConfig;
38function newTestExecutionConfig(jobConfig = {}) {
39 const exConfig = newTestJobConfig(jobConfig);
40 exConfig.slicer_hostname = 'example.com';
41 exConfig.slicer_port = utils_1.random(8000, 60000);
42 exConfig.ex_id = newId('ex-id');
43 exConfig.job_id = newId('job-id');
44 return exConfig;
45}
46exports.newTestExecutionConfig = newTestExecutionConfig;
47/**
48 * Create a new Execution Context
49 * @deprecated use the new WorkerExecutionContext and SlicerExecutionContext
50 */
51function newTestExecutionContext(type, config) {
52 if (type === 'execution_controller') {
53 return {
54 config,
55 queue: [],
56 reader: null,
57 slicer: () => { },
58 dynamicQueueLength: false,
59 queueLength: 10000,
60 reporter: null,
61 };
62 }
63 return {
64 config,
65 queue: config.operations.map(() => () => { }),
66 reader: () => { },
67 slicer: () => { },
68 dynamicQueueLength: false,
69 queueLength: 10000,
70 reporter: null,
71 };
72}
73exports.newTestExecutionContext = newTestExecutionContext;
74function getKey(opts) {
75 const { type, endpoint = 'default' } = opts;
76 if (!utils_1.isString(type))
77 throw new Error('A type must be specified when registering a Client');
78 return `${type}:${endpoint}`;
79}
80function setConnectorConfig(sysconfig, opts, config, override = true) {
81 const { type, endpoint = 'default' } = opts;
82 const { connectors } = sysconfig.terafoundation;
83 if (connectors[type] == null)
84 connectors[type] = {};
85 if (connectors[type][endpoint] == null) {
86 connectors[type][endpoint] = config;
87 }
88 else if (override) {
89 connectors[type][endpoint] = config;
90 }
91 return connectors[type][endpoint];
92}
93const _cachedClients = new WeakMap();
94const _createClientFns = new WeakMap();
95class TestContext {
96 constructor(testName, options = {}) {
97 this.assignment = 'worker';
98 this.platform = process.platform;
99 this.arch = process.arch;
100 const logger = utils_1.debugLogger(testName);
101 const events = new events_1.EventEmitter();
102 this.name = testName;
103 if (options.assignment) {
104 this.assignment = options.assignment;
105 }
106 this.logger = logger;
107 this.cluster = {
108 worker: {
109 id: newId('id'),
110 },
111 };
112 const sysconfig = {
113 terafoundation: {
114 connectors: {
115 elasticsearch: {
116 default: {},
117 },
118 },
119 },
120 teraslice: {
121 action_timeout: 10000,
122 analytics_rate: 10000,
123 assets_directory: path_1.default.join(process.cwd(), 'assets'),
124 cluster_manager_type: 'native',
125 hostname: 'localhost',
126 index_rollover_frequency: {
127 analytics: 'yearly',
128 state: 'montly',
129 },
130 master_hostname: 'localhost',
131 master: false,
132 name: testName,
133 network_latency_buffer: 100,
134 node_disconnect_timeout: 5000,
135 node_state_interval: 5000,
136 port: 55678,
137 shutdown_timeout: 10000,
138 slicer_allocation_attempts: 1,
139 slicer_port_range: '55679:56678',
140 slicer_timeout: 10000,
141 state: {
142 connection: 'default',
143 },
144 worker_disconnect_timeout: 3000,
145 workers: 1,
146 },
147 _nodeName: `${newId(testName)}__${this.cluster.worker.id}`,
148 };
149 this.sysconfig = sysconfig;
150 // tslint:disable-next-line
151 const ctx = this;
152 _cachedClients.set(this, {});
153 _createClientFns.set(this, {});
154 this.apis = {
155 foundation: {
156 makeLogger(...params) {
157 return logger.child(params[0]);
158 },
159 getConnection(opts) {
160 const { cached } = opts;
161 const cachedClients = _cachedClients.get(ctx) || {};
162 const key = getKey(opts);
163 if (cached && cachedClients[key] != null) {
164 return cachedClients[key];
165 }
166 const clientFns = _createClientFns.get(ctx) || {};
167 const create = clientFns[key];
168 if (!create)
169 throw new Error(`No client was found for connection "${key}"`);
170 if (!utils_1.isFunction(create)) {
171 const actual = utils_1.getTypeOf(create);
172 throw new Error(`Registered Client for connection "${key}" is not a function, got ${actual}`);
173 }
174 const config = setConnectorConfig(sysconfig, opts, {}, false);
175 const client = create(config, logger, opts);
176 cachedClients[key] = client;
177 _cachedClients.set(ctx, cachedClients);
178 return client;
179 },
180 getSystemEvents() {
181 return events;
182 },
183 },
184 registerAPI(namespace, apis) {
185 this[namespace] = apis;
186 },
187 setTestClients(clients = []) {
188 clients.forEach(clientConfig => {
189 const { create, config = {} } = clientConfig;
190 const clientFns = _createClientFns.get(ctx) || {};
191 const key = getKey(clientConfig);
192 if (!utils_1.isFunction(create)) {
193 const actual = utils_1.getTypeOf(create);
194 throw new Error(`Test Client for connection "${key}" is not a function, got ${actual}`);
195 }
196 logger.trace(`Setting test client for connection "${key}"`, config);
197 clientFns[key] = create;
198 _createClientFns.set(ctx, clientFns);
199 const cachedClients = _cachedClients.get(ctx) || {};
200 delete cachedClients[key];
201 _cachedClients.set(ctx, cachedClients);
202 setConnectorConfig(sysconfig, clientConfig, config, true);
203 });
204 },
205 getTestClients() {
206 const cachedClients = _cachedClients.get(ctx) || {};
207 const clients = {};
208 Object.keys(cachedClients).forEach(key => {
209 const [type, endpoint] = key.split(':');
210 if (clients[type] == null) {
211 clients[type] = {};
212 }
213 clients[type][endpoint] = cachedClients[key];
214 });
215 return clients;
216 },
217 };
218 this.foundation = {
219 getConnection: this.apis.foundation.getConnection,
220 getEventEmitter: this.apis.foundation.getSystemEvents,
221 makeLogger: this.apis.foundation.makeLogger,
222 };
223 this.apis.setTestClients(options.clients);
224 }
225}
226exports.TestContext = TestContext;
227//# sourceMappingURL=test-helpers.js.map
\No newline at end of file