@elastic/synthetics 1.0.0-beta.39 → 1.0.0-beta.40

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 (104) hide show
  1. package/dist/cli.js +11 -3
  2. package/dist/cli.js.map +1 -1
  3. package/dist/common_types.d.ts +1 -2
  4. package/dist/common_types.d.ts.map +1 -1
  5. package/dist/core/browser-service.js +3 -2
  6. package/dist/core/browser-service.js.map +1 -1
  7. package/dist/core/gatherer.js +1 -0
  8. package/dist/core/gatherer.js.map +1 -1
  9. package/dist/core/runner.d.ts.map +1 -1
  10. package/dist/core/runner.js +27 -40
  11. package/dist/core/runner.js.map +1 -1
  12. package/dist/core/transform.d.ts +37 -0
  13. package/dist/core/transform.d.ts.map +1 -0
  14. package/dist/core/transform.js +148 -0
  15. package/dist/core/transform.js.map +1 -0
  16. package/dist/dsl/journey.d.ts.map +1 -1
  17. package/dist/dsl/journey.js +9 -2
  18. package/dist/dsl/journey.js.map +1 -1
  19. package/dist/dsl/monitor.d.ts +14 -1
  20. package/dist/dsl/monitor.d.ts.map +1 -1
  21. package/dist/dsl/monitor.js +26 -0
  22. package/dist/dsl/monitor.js.map +1 -1
  23. package/dist/dsl/step.js +4 -0
  24. package/dist/dsl/step.js.map +1 -1
  25. package/dist/formatter/javascript.js +3 -0
  26. package/dist/formatter/javascript.js.map +1 -1
  27. package/dist/generator/index.d.ts.map +1 -1
  28. package/dist/generator/index.js +12 -9
  29. package/dist/generator/index.js.map +1 -1
  30. package/dist/helpers.d.ts +5 -5
  31. package/dist/helpers.d.ts.map +1 -1
  32. package/dist/helpers.js +30 -17
  33. package/dist/helpers.js.map +1 -1
  34. package/dist/loader.d.ts +7 -0
  35. package/dist/loader.d.ts.map +1 -1
  36. package/dist/loader.js +16 -19
  37. package/dist/loader.js.map +1 -1
  38. package/dist/locations/index.d.ts.map +1 -1
  39. package/dist/locations/index.js +4 -11
  40. package/dist/locations/index.js.map +1 -1
  41. package/dist/options.d.ts.map +1 -1
  42. package/dist/options.js +21 -5
  43. package/dist/options.js.map +1 -1
  44. package/dist/plugins/browser-console.js +28 -27
  45. package/dist/plugins/browser-console.js.map +1 -1
  46. package/dist/plugins/network.js +5 -3
  47. package/dist/plugins/network.js.map +1 -1
  48. package/dist/plugins/performance.js +1 -0
  49. package/dist/plugins/performance.js.map +1 -1
  50. package/dist/plugins/plugin-manager.js +8 -7
  51. package/dist/plugins/plugin-manager.js.map +1 -1
  52. package/dist/plugins/tracing.js +2 -0
  53. package/dist/plugins/tracing.js.map +1 -1
  54. package/dist/push/bundler.d.ts.map +1 -1
  55. package/dist/push/bundler.js +10 -17
  56. package/dist/push/bundler.js.map +1 -1
  57. package/dist/push/index.d.ts +1 -30
  58. package/dist/push/index.d.ts.map +1 -1
  59. package/dist/push/index.js +76 -66
  60. package/dist/push/index.js.map +1 -1
  61. package/dist/push/kibana_api.d.ts +56 -0
  62. package/dist/push/kibana_api.d.ts.map +1 -0
  63. package/dist/push/kibana_api.js +135 -0
  64. package/dist/push/kibana_api.js.map +1 -0
  65. package/dist/push/monitor.d.ts +14 -6
  66. package/dist/push/monitor.d.ts.map +1 -1
  67. package/dist/push/monitor.js +61 -18
  68. package/dist/push/monitor.js.map +1 -1
  69. package/dist/push/plugin.d.ts +7 -7
  70. package/dist/push/plugin.d.ts.map +1 -1
  71. package/dist/push/plugin.js +25 -136
  72. package/dist/push/plugin.js.map +1 -1
  73. package/dist/push/request.d.ts +4 -2
  74. package/dist/push/request.d.ts.map +1 -1
  75. package/dist/push/request.js +28 -3
  76. package/dist/push/request.js.map +1 -1
  77. package/dist/push/utils.d.ts +31 -0
  78. package/dist/push/utils.d.ts.map +1 -0
  79. package/dist/push/utils.js +64 -0
  80. package/dist/push/utils.js.map +1 -0
  81. package/dist/reporters/base.js +7 -5
  82. package/dist/reporters/base.js.map +1 -1
  83. package/dist/reporters/junit.js +11 -21
  84. package/dist/reporters/junit.js.map +1 -1
  85. package/package.json +5 -5
  86. package/src/cli.ts +10 -4
  87. package/src/common_types.ts +1 -2
  88. package/src/core/runner.ts +0 -3
  89. package/src/core/transform.ts +160 -0
  90. package/src/dsl/journey.ts +1 -0
  91. package/src/dsl/monitor.ts +27 -1
  92. package/src/generator/index.ts +10 -12
  93. package/src/helpers.ts +31 -17
  94. package/src/loader.ts +15 -19
  95. package/src/locations/index.ts +6 -19
  96. package/src/options.ts +21 -5
  97. package/src/push/bundler.ts +8 -15
  98. package/src/push/index.ts +111 -85
  99. package/src/push/kibana_api.ts +191 -0
  100. package/src/push/monitor.ts +72 -35
  101. package/src/push/plugin.ts +23 -125
  102. package/src/push/request.ts +38 -3
  103. package/src/push/utils.ts +77 -0
  104. package/dist/tsconfig.tsbuildinfo +0 -1
package/src/push/index.ts CHANGED
@@ -22,118 +22,107 @@
22
22
  * THE SOFTWARE.
23
23
  *
24
24
  */
25
-
25
+ import semver from 'semver';
26
26
  import { readFile, writeFile } from 'fs/promises';
27
27
  import { prompt } from 'enquirer';
28
28
  import { bold, grey } from 'kleur/colors';
29
29
  import {
30
- ok,
31
- formatAPIError,
32
- formatFailedMonitors,
33
- formatNotFoundError,
34
- formatStaleMonitors,
35
- } from './request';
36
- import { buildMonitorSchema, createMonitors, MonitorSchema } from './monitor';
30
+ getLocalMonitors,
31
+ buildMonitorSchema,
32
+ diffMonitors as diffMonitorHashIDs,
33
+ MonitorSchema,
34
+ } from './monitor';
37
35
  import { ALLOWED_SCHEDULES, Monitor } from '../dsl/monitor';
38
36
  import {
39
37
  progress,
40
- apiProgress,
38
+ liveProgress,
41
39
  write,
42
40
  error,
43
41
  warn,
44
42
  indent,
45
- safeNDJSONParse,
46
43
  done,
47
44
  getMonitorManagementURL,
48
- getArrayChunks,
49
45
  } from '../helpers';
50
46
  import type { PushOptions, ProjectSettings } from '../common_types';
51
47
  import { findSyntheticsConfig, readConfig } from '../config';
48
+ import {
49
+ bulkDeleteMonitors,
50
+ bulkGetMonitors,
51
+ bulkPutMonitors,
52
+ getVersion,
53
+ createMonitorsLegacy,
54
+ CHUNK_SIZE,
55
+ } from './kibana_api';
56
+ import { getChunks, logDiff } from './utils';
52
57
 
53
58
  export async function push(monitors: Monitor[], options: PushOptions) {
54
- let schemas: MonitorSchema[] = [];
55
- if (monitors.length > 0) {
56
- const duplicates = trackDuplicates(monitors);
57
- if (duplicates.size > 0) {
58
- throw error(formatDuplicateError(duplicates));
59
- }
59
+ const duplicates = trackDuplicates(monitors);
60
+ if (duplicates.size > 0) {
61
+ throw error(formatDuplicateError(duplicates));
62
+ }
63
+ progress(`Pushing monitors for project: ${options.id}`);
60
64
 
61
- progress(`preparing all monitors`);
62
- schemas = await buildMonitorSchema(monitors);
65
+ const stackVersion = await getVersion(options);
66
+ const isV2 = semver.satisfies(stackVersion, '>=8.6.0');
67
+ if (!isV2) {
68
+ return await pushLegacy(monitors, options, stackVersion);
69
+ }
70
+
71
+ const local = getLocalMonitors(monitors);
72
+ const { monitors: remote } = await bulkGetMonitors(options);
73
+ const { newIDs, changedIDs, removedIDs, unchangedIDs } = diffMonitorHashIDs(
74
+ local,
75
+ remote
76
+ );
77
+ logDiff(newIDs, changedIDs, removedIDs, unchangedIDs);
63
78
 
64
- progress(`creating all monitors`);
65
- const chunks = getArrayChunks(schemas, 10);
79
+ const updatedMonitors = new Set<string>([...changedIDs, ...newIDs]);
80
+ if (updatedMonitors.size > 0) {
81
+ const toBundle = monitors.filter(m => updatedMonitors.has(m.config.id));
82
+ progress(`bundling ${toBundle.length} monitors`);
83
+ const schemas = await buildMonitorSchema(toBundle, true);
84
+ const chunks = getChunks(schemas, CHUNK_SIZE);
66
85
  for (const chunk of chunks) {
67
- await pushMonitors({ schemas: chunk, keepStale: true, options });
86
+ await liveProgress(
87
+ bulkPutMonitors(options, chunk),
88
+ `creating or updating ${chunk.length} monitors`
89
+ );
68
90
  }
69
- } else {
70
- write('');
71
- const { deleteAll } = await prompt<{ deleteAll: boolean }>({
72
- type: 'confirm',
73
- skip() {
74
- if (options.yes) {
75
- this.initial = process.env.TEST_OVERRIDE ?? true;
76
- return true;
77
- }
78
- return false;
79
- },
80
- name: 'deleteAll',
81
- message: `Pushing without any monitors will delete all monitors associated with the project.\n Do you want to continue?`,
82
- initial: false,
83
- });
84
- if (!deleteAll) {
85
- throw warn('Push command Aborted');
91
+ }
92
+
93
+ if (removedIDs.size > 0) {
94
+ if (updatedMonitors.size === 0 && unchangedIDs.size === 0) {
95
+ await promptConfirmDeleteAll(options);
96
+ }
97
+ const chunks = getChunks(Array.from(removedIDs), CHUNK_SIZE);
98
+ for (const chunk of chunks) {
99
+ await liveProgress(
100
+ bulkDeleteMonitors(options, chunk),
101
+ `deleting ${chunk.length} monitors`
102
+ );
86
103
  }
87
104
  }
88
- progress(`deleting all stale monitors`);
89
- await pushMonitors({ schemas, keepStale: false, options });
90
105
 
91
106
  done(`Pushed: ${grey(getMonitorManagementURL(options.url))}`);
92
107
  }
93
108
 
94
- export async function pushMonitors({
95
- schemas,
96
- keepStale,
97
- options,
98
- }: {
99
- schemas: MonitorSchema[];
100
- keepStale: boolean;
101
- options: PushOptions;
102
- }) {
103
- const { body, statusCode } = await createMonitors(
104
- schemas,
105
- options,
106
- keepStale
107
- );
108
- if (statusCode === 404) {
109
- throw formatNotFoundError(await body.text());
110
- }
111
- if (!ok(statusCode)) {
112
- const { error, message } = await body.json();
113
- throw formatAPIError(statusCode, error, message);
114
- }
115
- const allchunks = [];
116
- for await (const data of body) {
117
- allchunks.push(Buffer.from(data));
118
- }
119
- const chunks = safeNDJSONParse(Buffer.concat(allchunks).toString('utf-8'));
120
- // Its kind of hacky for now where Kibana streams the response by
121
- // writing the data as NDJSON events (data can be interleaved), we
122
- // distinguish the final data by checking if the event was a progress vs complete event
123
- for (const chunk of chunks) {
124
- if (typeof chunk === 'string') {
125
- // TODO: add progress back for all states once we get the fix
126
- // on kibana side
127
- keepStale && apiProgress(chunk);
128
- continue;
129
- }
130
- const { failedMonitors, failedStaleMonitors } = chunk;
131
- if (failedMonitors && failedMonitors.length > 0) {
132
- throw formatFailedMonitors(failedMonitors);
133
- }
134
- if (failedStaleMonitors.length > 0) {
135
- throw formatStaleMonitors(failedStaleMonitors);
136
- }
109
+ async function promptConfirmDeleteAll(options: PushOptions) {
110
+ write('');
111
+ const { deleteAll } = await prompt<{ deleteAll: boolean }>({
112
+ type: 'confirm',
113
+ skip() {
114
+ if (options.yes) {
115
+ this.initial = process.env.TEST_OVERRIDE ?? true;
116
+ return true;
117
+ }
118
+ return false;
119
+ },
120
+ name: 'deleteAll',
121
+ message: `Pushing without any monitors will delete all monitors associated with the project.\n Do you want to continue?`,
122
+ initial: false,
123
+ });
124
+ if (!deleteAll) {
125
+ throw warn('Push command Aborted');
137
126
  }
138
127
  }
139
128
 
@@ -174,7 +163,7 @@ export async function loadSettings() {
174
163
  }
175
164
  return config.project || ({} as ProjectSettings);
176
165
  } catch (e) {
177
- throw error(`Aborted (missing synthetics config file), Project not set up corrrectly.
166
+ throw error(`Aborted (missing synthetics config file), Project not set up correctly.
178
167
 
179
168
  ${INSTALLATION_HELP}`);
180
169
  }
@@ -254,3 +243,40 @@ export async function catchIncorrectSettings(
254
243
  await overrideSettings(settings.id, options.id);
255
244
  }
256
245
  }
246
+
247
+ export async function pushLegacy(
248
+ monitors: Monitor[],
249
+ options: PushOptions,
250
+ version: number
251
+ ) {
252
+ const noLightWeightSupport = semver.satisfies(version, '<8.5.0');
253
+ if (
254
+ noLightWeightSupport &&
255
+ monitors.some(monitor => monitor.type !== 'browser')
256
+ ) {
257
+ throw error(
258
+ `Aborted: Lightweight monitors are not supported in ${version}. Please upgrade to 8.5.0 or above.`
259
+ );
260
+ }
261
+
262
+ let schemas: MonitorSchema[] = [];
263
+ if (monitors.length > 0) {
264
+ progress(`bundling ${monitors.length} monitors`);
265
+ schemas = await buildMonitorSchema(monitors, false);
266
+ const chunks = getChunks(schemas, 10);
267
+ for (const chunk of chunks) {
268
+ await liveProgress(
269
+ createMonitorsLegacy({ schemas: chunk, keepStale: true, options }),
270
+ `creating or updating ${chunk.length} monitors`
271
+ );
272
+ }
273
+ } else {
274
+ await promptConfirmDeleteAll(options);
275
+ }
276
+ await liveProgress(
277
+ createMonitorsLegacy({ schemas, keepStale: false, options }),
278
+ `deleting all stale monitors`
279
+ );
280
+
281
+ done(`Pushed: ${grey(getMonitorManagementURL(options.url))}`);
282
+ }
@@ -0,0 +1,191 @@
1
+ /**
2
+ * MIT License
3
+ *
4
+ * Copyright (c) 2020-present, Elastic NV
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in
14
+ * all copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
+ * THE SOFTWARE.
23
+ *
24
+ */
25
+
26
+ import { PushOptions } from '../common_types';
27
+ import { safeNDJSONParse } from '../helpers';
28
+ import { MonitorHashID, MonitorSchema } from './monitor';
29
+ import {
30
+ formatFailedMonitors,
31
+ formatStaleMonitors,
32
+ handleError,
33
+ sendReqAndHandleError,
34
+ sendRequest,
35
+ APIMonitorError,
36
+ } from './request';
37
+ import { generateURL } from './utils';
38
+
39
+ // Default chunk size for bulk put / delete
40
+ export const CHUNK_SIZE = 100;
41
+
42
+ export type PutResponse = {
43
+ createdMonitors: string[];
44
+ updatedMonitors: string[];
45
+ failedMonitors: APIMonitorError[];
46
+ };
47
+
48
+ export async function bulkPutMonitors(
49
+ options: PushOptions,
50
+ schemas: MonitorSchema[]
51
+ ) {
52
+ const resp = await sendReqAndHandleError<PutResponse>({
53
+ url: generateURL(options, 'bulk_update') + '/_bulk_update',
54
+ method: 'PUT',
55
+ auth: options.auth,
56
+ body: JSON.stringify({ monitors: schemas }),
57
+ });
58
+ const { failedMonitors } = resp;
59
+ if (failedMonitors && failedMonitors.length > 0) {
60
+ throw formatFailedMonitors(failedMonitors);
61
+ }
62
+ return resp;
63
+ }
64
+
65
+ export type GetResponse = {
66
+ total: number;
67
+ monitors: MonitorHashID[];
68
+ after_key?: string;
69
+ };
70
+
71
+ export async function bulkGetMonitors(
72
+ options: PushOptions
73
+ ): Promise<GetResponse> {
74
+ const allMonitors: MonitorHashID[] = [];
75
+
76
+ const resp = await fetchMonitors(options);
77
+ allMonitors.push(...resp.monitors);
78
+ let afterKey = resp.afterKey;
79
+ const total = resp.total;
80
+
81
+ while (allMonitors.length < total) {
82
+ const resp = await fetchMonitors(options, afterKey);
83
+ allMonitors.push(...resp.monitors);
84
+ afterKey = resp.afterKey;
85
+ }
86
+
87
+ return {
88
+ total,
89
+ monitors: allMonitors,
90
+ };
91
+ }
92
+
93
+ const fetchMonitors = async (options: PushOptions, afterKey?: string) => {
94
+ let url = generateURL(options, 'bulk_get');
95
+ if (afterKey) {
96
+ url += `?search_after=${afterKey}`;
97
+ }
98
+ const resp = await sendReqAndHandleError<GetResponse>({
99
+ url,
100
+ method: 'GET',
101
+ auth: options.auth,
102
+ });
103
+ return {
104
+ afterKey: resp.after_key,
105
+ total: resp.total,
106
+ monitors: resp.monitors,
107
+ };
108
+ };
109
+
110
+ export type DeleteResponse = {
111
+ deleted_monitors: string[];
112
+ };
113
+
114
+ export async function bulkDeleteMonitors(
115
+ options: PushOptions,
116
+ monitorIDs: string[]
117
+ ) {
118
+ return await sendReqAndHandleError<DeleteResponse>({
119
+ url: generateURL(options, 'bulk_delete') + '/_bulk_delete',
120
+ method: 'DELETE',
121
+ auth: options.auth,
122
+ body: JSON.stringify({ monitors: monitorIDs }),
123
+ });
124
+ }
125
+
126
+ type StatusResponse = {
127
+ version: {
128
+ number: number;
129
+ };
130
+ };
131
+
132
+ export async function getVersion(options: PushOptions) {
133
+ const data = await sendReqAndHandleError<StatusResponse>({
134
+ url: generateURL(options, 'status'),
135
+ method: 'GET',
136
+ auth: options.auth,
137
+ });
138
+ return data.version.number;
139
+ }
140
+
141
+ export type LegacyAPISchema = {
142
+ project: string;
143
+ keep_stale: boolean;
144
+ monitors: MonitorSchema[];
145
+ };
146
+
147
+ export async function createMonitorsLegacy({
148
+ schemas,
149
+ keepStale,
150
+ options,
151
+ }: {
152
+ schemas: MonitorSchema[];
153
+ keepStale: boolean;
154
+ options: PushOptions;
155
+ }) {
156
+ const schema: LegacyAPISchema = {
157
+ project: options.id,
158
+ keep_stale: keepStale,
159
+ monitors: schemas,
160
+ };
161
+ const url = generateURL(options, 'legacy');
162
+ const { body, statusCode } = await sendRequest({
163
+ url,
164
+ method: 'PUT',
165
+ auth: options.auth,
166
+ body: JSON.stringify(schema),
167
+ });
168
+
169
+ const resBody = await handleError(statusCode, url, body);
170
+ const allchunks = [];
171
+ for await (const data of resBody) {
172
+ allchunks.push(Buffer.from(data));
173
+ }
174
+ const chunks = safeNDJSONParse(Buffer.concat(allchunks).toString('utf-8'));
175
+ // Its kind of hacky for now where Kibana streams the response by
176
+ // writing the data as NDJSON events (data can be interleaved), we
177
+ // distinguish the final data by checking if the event was a progress vs complete event
178
+ for (const chunk of chunks) {
179
+ if (typeof chunk === 'string') {
180
+ // Ignore the progress from Kibana as we chunk the requests
181
+ continue;
182
+ }
183
+ const { failedMonitors, failedStaleMonitors } = chunk;
184
+ if (failedMonitors && failedMonitors.length > 0) {
185
+ throw formatFailedMonitors(failedMonitors);
186
+ }
187
+ if (failedStaleMonitors.length > 0) {
188
+ throw formatStaleMonitors(failedStaleMonitors);
189
+ }
190
+ }
191
+ }
@@ -28,14 +28,7 @@ import { join } from 'path';
28
28
  import { LineCounter, parseDocument, YAMLSeq, YAMLMap } from 'yaml';
29
29
  import { bold, red } from 'kleur/colors';
30
30
  import { Bundler } from './bundler';
31
- import { sendRequest } from './request';
32
- import {
33
- removeTrailingSlash,
34
- SYNTHETICS_PATH,
35
- totalist,
36
- indent,
37
- warn,
38
- } from '../helpers';
31
+ import { SYNTHETICS_PATH, totalist, indent, warn } from '../helpers';
39
32
  import { LocationsMap } from '../locations/public-locations';
40
33
  import { ALLOWED_SCHEDULES, Monitor, MonitorConfig } from '../dsl/monitor';
41
34
  import { PushOptions } from '../common_types';
@@ -44,12 +37,14 @@ export type MonitorSchema = Omit<MonitorConfig, 'locations'> & {
44
37
  locations: string[];
45
38
  content?: string;
46
39
  filter?: Monitor['filter'];
40
+ hash?: string;
47
41
  };
48
42
 
49
- export type APISchema = {
50
- project: string;
51
- keep_stale: boolean;
52
- monitors: MonitorSchema[];
43
+ // Abbreviated monitor info, as often returned by the API,
44
+ // just the journey ID and hash
45
+ export type MonitorHashID = {
46
+ journey_id?: string;
47
+ hash?: string;
53
48
  };
54
49
 
55
50
  function translateLocation(locations?: MonitorConfig['locations']) {
@@ -57,7 +52,67 @@ function translateLocation(locations?: MonitorConfig['locations']) {
57
52
  return locations.map(loc => LocationsMap[loc] || loc).filter(Boolean);
58
53
  }
59
54
 
60
- export async function buildMonitorSchema(monitors: Monitor[]) {
55
+ class RemoteDiffResult {
56
+ // The set of monitor IDs that have been added
57
+ newIDs = new Set<string>();
58
+ // Monitor IDs that are different locally than remotely
59
+ changedIDs = new Set<string>();
60
+ // Monitor IDs that are no longer present locally
61
+ removedIDs = new Set<string>();
62
+ // Monitor IDs that are identical on the remote server
63
+ unchangedIDs = new Set<string>();
64
+ }
65
+
66
+ export function diffMonitors(
67
+ local: MonitorHashID[],
68
+ remote: MonitorHashID[]
69
+ ): RemoteDiffResult {
70
+ const result = new RemoteDiffResult();
71
+ const localMonitorsIDToHash = new Map<string, string>();
72
+ for (const hashID of local) {
73
+ localMonitorsIDToHash.set(hashID.journey_id, hashID.hash);
74
+ }
75
+ const remoteMonitorsIDToHash = new Map<string, string>();
76
+ for (const hashID of remote) {
77
+ remoteMonitorsIDToHash.set(hashID.journey_id, hashID.hash);
78
+ }
79
+
80
+ // Compare local to remote
81
+ for (const [localID, localHash] of localMonitorsIDToHash) {
82
+ // Hash is reset to '' when a monitor is edited on the UI
83
+ if (!remoteMonitorsIDToHash.has(localID)) {
84
+ result.newIDs.add(localID);
85
+ } else {
86
+ const remoteHash = remoteMonitorsIDToHash.get(localID);
87
+ if (remoteHash != localHash) {
88
+ result.changedIDs.add(localID);
89
+ } else if (remoteHash === localHash) {
90
+ result.unchangedIDs.add(localID);
91
+ }
92
+ }
93
+ // We no longer need to process this ID, removing it here
94
+ // reduces the numbers considered in the next phase
95
+ remoteMonitorsIDToHash.delete(localID);
96
+ }
97
+
98
+ for (const [id] of remoteMonitorsIDToHash) {
99
+ result.removedIDs.add(id);
100
+ }
101
+ return result;
102
+ }
103
+
104
+ export function getLocalMonitors(monitors: Monitor[]) {
105
+ const data: MonitorHashID[] = [];
106
+ for (const monitor of monitors) {
107
+ data.push({
108
+ journey_id: monitor.config.id,
109
+ hash: monitor.hash(),
110
+ });
111
+ }
112
+ return data;
113
+ }
114
+
115
+ export async function buildMonitorSchema(monitors: Monitor[], isV2: boolean) {
61
116
  /**
62
117
  * Set up the bundle artifacts path which can be used to
63
118
  * create the bundles required for uploading journeys
@@ -69,10 +124,13 @@ export async function buildMonitorSchema(monitors: Monitor[]) {
69
124
 
70
125
  for (const monitor of monitors) {
71
126
  const { source, config, filter, type } = monitor;
72
- const schema = {
127
+ const schema: MonitorSchema = {
73
128
  ...config,
74
129
  locations: translateLocation(config.locations),
75
130
  };
131
+ if (isV2) {
132
+ schema.hash = monitor.hash();
133
+ }
76
134
  if (type === 'browser') {
77
135
  const outPath = join(bundlePath, config.name + '.zip');
78
136
  const content = await bundler.build(source.file, outPath);
@@ -216,24 +274,3 @@ export function nearestSchedule(schedule: number) {
216
274
  }
217
275
  return ALLOWED_SCHEDULES[end];
218
276
  }
219
-
220
- export async function createMonitors(
221
- monitors: MonitorSchema[],
222
- options: PushOptions,
223
- keepStale: boolean
224
- ) {
225
- const schema: APISchema = {
226
- project: options.id,
227
- keep_stale: keepStale,
228
- monitors,
229
- };
230
-
231
- return await sendRequest({
232
- url:
233
- removeTrailingSlash(options.url) +
234
- `/s/${options.space}/api/synthetics/service/project/monitors`,
235
- method: 'PUT',
236
- auth: options.auth,
237
- body: JSON.stringify(schema),
238
- });
239
- }