-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathvalidate-sgid-index.mjs
394 lines (326 loc) · 10.2 KB
/
validate-sgid-index.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import axiosRetry from 'axios-retry';
import { GoogleAuth, auth } from 'google-auth-library';
import { GoogleSpreadsheet } from 'google-spreadsheet';
import jsonToMarkdown from 'json-to-markdown-table';
import ky from 'ky';
import random from 'lodash/random.js';
import ProgressBar from 'progress';
import * as tsImport from 'ts-import';
import { v4 as uuid } from 'uuid';
import { slugify, validateOpenDataUrl, validateOpenSgidTableName, validateUrl } from './utilities.mjs';
function retry(client) {
axiosRetry(client, {
retries: 7,
retryDelay: (retryCount) => {
const randomNumberMS = random(1000, 8000);
return Math.min(4 ** retryCount + randomNumberMS, 20000);
},
retryCondition: (error) => error.response.status === 429,
});
}
const downloadMetadata = await tsImport.load('../src/data/downloadMetadata.ts');
const spreadsheetId = '11ASS7LnxgpnD0jN4utzklREgMf1pcvYjcXcIcESHweQ';
const ourWebSite = 'https://gis.utah.gov';
const scopes = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive'];
let client;
if (process.env.GITHUB_ACTIONS) {
console.log('using ci credentials');
client = auth.fromJSON(JSON.parse(process.env.GOOGLE_PRIVATE_KEY));
client.scopes = scopes;
} else {
client = new GoogleAuth({
scopes,
});
}
console.log('loading spreadsheet');
const spreadsheet = new GoogleSpreadsheet(spreadsheetId, client);
retry(spreadsheet.sheetsApi);
retry(spreadsheet.driveApi);
await spreadsheet.loadInfo();
const worksheet = spreadsheet.sheetsByTitle['SGID Index'];
const fieldNames = {
displayName: 'displayName',
hubName: 'hubName',
id: 'id',
inActionUrl: 'inActionUrl',
itemId: 'itemId',
openSgid: 'openSgid',
openSgidTableName: 'openSgidTableName',
productPage: 'productPage',
serverLayerId: 'serverLayerId',
indexStatus: 'indexStatus',
};
function getFieldName(name) {
const fieldName = fieldNames[name];
if (!fieldName) {
throw new Error(`field name "${name}" not found`);
}
return fieldName;
}
const errors = [];
function recordError(message, row) {
errors.push({
displayName: row.get(getFieldName('displayName')),
id: row.get(getFieldName('id')),
Error: message,
});
}
function toBoolean(value) {
return value === 'TRUE';
}
async function openSGIDTableName(row) {
if (!toBoolean(row.get(getFieldName('openSgid')))) {
return;
}
const cellValue = row.get(getFieldName('openSgidTableName'));
if (!cellValue) {
recordError('openSgidTableName is empty', row);
return;
}
const [schema, tableName] = cellValue.split('.');
const result = await validateOpenSgidTableName(tableName, schema);
if (!result.valid) {
recordError(result.message, row);
}
}
function trimFields(row) {
let changed = false;
for (const field in fieldNames) {
const cellValue = row.get(getFieldName(field));
if (cellValue && cellValue.trim() !== cellValue) {
console.log(`cell trim update ${field}: "${cellValue}" != "${cellValue.trim()}" in ${row.get('displayName')}`);
row.set(getFieldName(field), cellValue.trim());
changed = true;
}
}
return changed;
}
async function productPage(row) {
const cellValue = row.get(getFieldName('productPage'));
if (!cellValue) {
// productPage is not a required field
return;
}
const url = cellValue.startsWith('/') ? `${ourWebSite}${cellValue}` : cellValue;
let result = await validateUrl(url);
if (result.valid && /\/datasets\//.test(url)) {
result = await validateOpenDataUrl(url);
}
if (!result.valid) {
recordError(`productPage: ${result.message}`, row);
}
}
async function inActionUrl(row) {
const url = row.get(getFieldName('inActionUrl'));
if (!url) {
// inActionUrl is not a required field
return;
}
let result = await validateUrl(url);
if (result.valid && /\/datasets\//.test(url)) {
result = await validateOpenDataUrl(url);
}
if (!result.valid) {
recordError(`inActionUrl: ${result.message}`, row);
}
}
async function idGuid(row) {
const cellValue = row.get(getFieldName('id'));
if (!cellValue) {
console.log(`item id update in ${row.get('displayName')}`);
row.set('id', uuid());
return true;
}
}
async function itemId(row) {
const cellValue = row.get(getFieldName('itemId'));
let layerId = row.get(getFieldName('serverLayerId'));
if (!layerId) {
layerId = 0;
}
if (!cellValue) {
// TODO: internal datasets _should_ have an itemId
// also, check for deprecated and openSgid/arcGisOnline field values
// itemId is not a required field
return;
}
if (cellValue.length !== 32 || cellValue.indexOf(' ') !== -1) {
recordError('itemId is not a valid AGOL item id', row);
return;
}
let hubData;
let serviceParts;
try {
hubData = await ky(`https://opendata.arcgis.com/api/v3/datasets/${cellValue}_${layerId}`).json();
serviceParts = hubData.data.attributes.url.split('/rest/services/');
} catch (error) {
try {
// maybe this is something other than a feature service such as a WMTS base map service
hubData = await ky(`https://opendata.arcgis.com/api/v3/datasets/${cellValue}`).json();
} catch (error) {
recordError(`itemId hub request error: ${error.message}`, row);
return;
}
}
const orgLookup = {
'Utah DNR Online Maps': 'utahDNR',
'Utah Automated Geographic Reference Center (AGRC)': 'utah',
'Wasatch Front Regional Council': 'wfrc',
'UPlan Map Center': 'uplan',
'Utah Department of Environmental Quality': 'utahdeq',
'Utah SHPO': 'UtahSHPO',
};
const slug = hubData.data.attributes.slug;
const correctSlug = slugify(hubData.data.attributes.name);
if (slug.split('::')[1] !== correctSlug) {
recordError(
`slug: "${slug}" does not match hub name: "${hubData.data.attributes.name}". You may need to temporarily rename the item in Hub and then change it back to fix it.`,
row,
);
}
const org = slug ? slug.split('::')[0] : orgLookup[hubData.data.attributes.organization];
if (!org) {
recordError(
`No hubOrganization could be found! slug: "${slug}" organization: "${hubData.data.attributes.organization}"`,
row,
);
}
const newData = {
hubName: hubData.data.attributes.name,
hubOrganization: org,
serverHost: serviceParts && serviceParts[0],
serverServiceName: serviceParts && serviceParts[1].split(/\/(FeatureServer|MapServer)\//)[0],
serverLayerId: serviceParts && layerId,
};
let changed = false;
for (const field in newData) {
if (row.get(field) !== (newData[field] ?? '')) {
console.log(`item id updates ${field}: "${row.get(field)}" != "${newData[field]}" in ${row.get('displayName')}`);
row.set(field, newData[field]);
changed = true;
}
}
return changed;
}
async function duplicates(row) {
for (const field in duplicateLookups) {
const value = row.get(field);
if (!value) {
continue;
}
if (duplicateLookups[field][value]?.length > 1) {
recordError(`duplicate ${field}: "${value}" found`, row);
}
}
}
async function downloadMetadataCheck(row) {
const name = row.get(getFieldName('hubName'));
const metadata = downloadMetadata.dataPages[name];
if (!metadata || metadata.featureServiceId === undefined) {
return;
}
const metadataChecks = [
// sgid index field, metadata field
['itemId', 'itemId'],
['hubName', 'name'],
['serverServiceName', 'featureServiceId'],
['openSgidTableName', 'openSgid'],
['serverLayerId', 'layerId'],
];
for (const [sgidIndexField, metadataField] of metadataChecks) {
const sgidIndexValue = row.get(sgidIndexField)?.toString();
const metadataValue = metadata[metadataField]?.toString();
if (sgidIndexValue !== metadataValue) {
recordError(
`downloadMetadata(${name}): "${metadataField}" does not match SGID Index column "${sgidIndexField}"`,
row,
);
}
}
}
async function productPageOrItemId(row) {
if (!row.get(getFieldName('productPage')) && !row.get(getFieldName('itemId'))) {
recordError(`No "${getFieldName('productPage')}" or "${getFieldName('itemId')}"`, row);
}
}
const duplicateLookups = {
openSgidTableName: {},
itemId: {},
id: {},
displayName: {},
};
function buildDuplicateLookups(rows) {
console.log('building duplicate lookups');
for (const field in duplicateLookups) {
for (const row of rows) {
const value = row.get(field);
if (!value) {
continue;
}
if (duplicateLookups[field][value]) {
duplicateLookups[field][value].push(row);
} else {
duplicateLookups[field][value] = [row];
}
}
}
}
const checks = [
// these functions must return a promise
openSGIDTableName,
productPage,
idGuid,
itemId,
duplicates,
downloadMetadataCheck,
productPageOrItemId,
inActionUrl,
];
const rows = await worksheet.getRows();
buildDuplicateLookups(rows);
// useful for debugging specific rows
let testId;
try {
testId = process.argv[2];
} catch (error) {
pass;
}
let updatedRowsCount = 0;
console.log(`checking ${rows.length} rows`);
const progressBar = new ProgressBar(':bar :percent ETA: :etas ', { total: rows.length });
const skipStatuses = ['removed', 'draft'];
for (const row of rows) {
progressBar.tick();
if (testId && row.get(getFieldName('id')) !== testId) {
continue;
}
if (skipStatuses.includes(row.get(getFieldName('indexStatus'))?.toLowerCase())) {
continue;
}
let changed;
try {
changed = trimFields(row); // we want trim to run first
const checksChanged = (await Promise.all(checks.map((check) => check(row)))).some((result) => result);
changed = changed || checksChanged;
} catch (error) {
recordError(`message: ${error.message} stack: ${error.stack.replaceAll('\n', '<br/>')}`, row);
}
if (changed) {
try {
await row.save();
updatedRowsCount++;
} catch (error) {
recordError(`save error: ${error.message}`, row);
}
}
}
if (errors.length > 0) {
errors.sort((a, b) => a.displayName.localeCompare(b.displayName));
console.error(jsonToMarkdown(errors, ['displayName', 'id', 'Error']));
console.log(`\ntotal errors: ${errors.length}`);
console.log(`updated ${updatedRowsCount} rows`);
process.exit(1);
}
console.log('All rows validated successfully');
console.log(`updated ${updatedRowsCount} rows`);
process.exit(0);