/
useProtocolImport.tsx
423 lines (367 loc) · 12.7 KB
/
useProtocolImport.tsx
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
import { useCallback, useReducer, useRef } from 'react';
import { uploadFiles } from '~/lib/uploadthing-helpers';
import { api } from '~/trpc/client';
import { DatabaseError } from '~/utils/databaseError';
import { ensureError } from '~/utils/ensureError';
import { queue } from 'async';
import {
fileAsArrayBuffer,
getProtocolJson,
getProtocolAssets,
} from '~/utils/protocolImport';
import {
jobInitialState,
jobReducer,
} from '~/components/ProtocolImport/JobReducer';
import Link from '~/components/Link';
import { ErrorDetails } from '~/components/ErrorDetails';
import { XCircle } from 'lucide-react';
import type { assetInsertSchema } from '~/server/routers/protocol';
import type { z } from 'zod';
import { hash } from 'ohash';
import { AlertDialogDescription } from '~/components/ui/AlertDialog';
// Utility helper for adding artificial delay to async functions
// const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
export const useProtocolImport = () => {
const [jobs, dispatch] = useReducer(jobReducer, jobInitialState);
const utils = api.useUtils();
const { mutateAsync: insertProtocol } = api.protocol.insert.useMutation({
async onSuccess() {
await utils.protocol.get.all.invalidate();
},
});
const { mutateAsync: getProtocolExists } =
api.protocol.get.byHash.useMutation();
const { mutateAsync: getNewAssetIds } = api.asset.checkExisting.useMutation();
/**
* This is the main job processing function. Takes a file, and handles all
* the steps required to import it into the database, updating the job
* status as it goes.
*/
const processJob = async (file: File) => {
try {
const fileName = file.name;
dispatch({
type: 'UPDATE_STATUS',
payload: {
id: fileName,
status: 'Extracting protocol',
},
});
const fileArrayBuffer = await fileAsArrayBuffer(file);
// TODO: check if this causes multiple fetches by importing again for each job.
const JSZip = (await import('jszip')).default; // Dynamic import to reduce bundle size
const zip = await JSZip.loadAsync(fileArrayBuffer);
const protocolJson = await getProtocolJson(zip);
// Validating protocol...
dispatch({
type: 'UPDATE_STATUS',
payload: {
id: fileName,
status: 'Validating protocol',
},
});
const { validateProtocol } = await import('@codaco/protocol-validation');
const validationResult = await validateProtocol(protocolJson);
if (!validationResult.isValid) {
const resultAsString = JSON.stringify(validationResult, null, 2);
dispatch({
type: 'UPDATE_ERROR',
payload: {
id: fileName,
rawError: new Error('Protocol validation failed', {
cause: validationResult,
}),
error: {
title: 'The protocol is invalid!',
description: (
<>
<AlertDialogDescription>
The protocol you uploaded is invalid. See the details below
for specific validation errors that were found.
</AlertDialogDescription>
<AlertDialogDescription>
If you believe that your protocol should be valid please ask
for help via our{' '}
<Link
href="https://community.networkcanvas.com"
target="_blank"
>
community forum
</Link>
.
</AlertDialogDescription>
</>
),
additionalContent: (
<ErrorDetails errorText={resultAsString}>
<ul className="max-w-md list-inside space-y-2">
{[
...validationResult.schemaErrors,
...validationResult.logicErrors,
].map((validationError, i) => (
<li className="flex capitalize" key={i}>
<XCircle className="mr-2 h-4 w-4 text-destructive" />
<span>
{validationError.message}{' '}
<span className="text-xs italic">
({validationError.path})
</span>
</span>
</li>
))}
</ul>
</ErrorDetails>
),
},
},
});
return;
}
// After this point, assume the protocol is valid.
// Check if the protocol already exists in the database
const protocolHash = hash(protocolJson);
const exists = await getProtocolExists(protocolHash);
if (exists) {
dispatch({
type: 'UPDATE_ERROR',
payload: {
id: file.name,
rawError: new Error('Protocol already exists'),
error: {
title: 'Protocol already exists',
description: (
<AlertDialogDescription>
The protocol you attempted to import already exists in the
database. Delete the existing protocol first before attempting
to import it again.
</AlertDialogDescription>
),
},
},
});
return;
}
const assets = await getProtocolAssets(protocolJson, zip);
const newAssets: typeof assets = [];
const existingAssetIds: string[] = [];
let newAssetsWithCombinedMetadata: z.infer<typeof assetInsertSchema> = [];
// Check if the assets are already in the database.
// If yes, add them to existingAssetIds to be connected to the protocol.
// If not, add them to newAssets to be uploaded.
try {
const newAssetIds = await getNewAssetIds(
assets.map((asset) => asset.assetId),
);
assets.forEach((asset) => {
if (newAssetIds.includes(asset.assetId)) {
newAssets.push(asset);
} else {
existingAssetIds.push(asset.assetId);
}
});
} catch (e) {
throw new Error('Error checking for existing assets');
}
// Upload the new assets
if (newAssets.length > 0) {
dispatch({
type: 'UPDATE_STATUS',
payload: {
id: fileName,
status: 'Uploading assets',
},
});
/**
* To track overall upload progress we need to create two variables in
* the upper scope, one to track the total bytes to upload, and one to
* track the current bytes uploaded per file (uploads are done in
* parallel).
*/
const totalBytesToUpload = newAssets.reduce((acc, asset) => {
return acc + asset.file.size;
}, 0);
const currentBytesUploaded: Record<string, number> = {};
const files = newAssets.map((asset) => asset.file);
const uploadedFiles = await uploadFiles('assetRouter', {
files,
onUploadProgress({ progress, file }) {
const thisFileSize = newAssets.find((asset) => asset.name === file)!
.file.size; // eg. 1000
const thisCompletedBytes = thisFileSize * (progress / 100);
if (!currentBytesUploaded[file]) {
currentBytesUploaded[file] = 0;
}
currentBytesUploaded[file] = thisCompletedBytes;
// Sum all totals for all files to calculate overall progress
const totalUploadedBytes = Object.values(
currentBytesUploaded,
).reduce((acc, cur) => acc + cur, 0);
const progressPercent = Math.round(
(totalUploadedBytes / totalBytesToUpload) * 100,
);
dispatch({
type: 'UPDATE_STATUS',
payload: {
id: fileName,
status: 'Uploading assets',
progress: progressPercent,
},
});
},
});
/**
* We now need to merge the metadata from the uploaded files with the
* asset metadata from the protocol json, so that we can insert the
* newassets into the database.
*
* The 'name' prop matches across both - we can use that to merge them.
*/
newAssetsWithCombinedMetadata = newAssets.map((asset) => {
const uploadedAsset = uploadedFiles.find(
(uploadedFile) => uploadedFile.name === asset.name,
);
if (!uploadedAsset) {
throw new Error('Asset upload failed');
}
// Ensure this matches the input schema in the protocol router by
// manually constructing the object.
return {
key: uploadedAsset.key,
assetId: asset.assetId,
name: asset.name,
type: asset.type,
url: uploadedAsset.url,
size: uploadedAsset.size,
};
});
}
dispatch({
type: 'UPDATE_STATUS',
payload: {
id: fileName,
status: 'Writing to database',
},
});
const result = await insertProtocol({
protocol: protocolJson,
protocolName: fileName,
newAssets: newAssetsWithCombinedMetadata,
existingAssetIds: existingAssetIds,
});
if (result.error) {
throw new DatabaseError(result.error, result.errorDetails);
}
// Complete! 🚀
dispatch({
type: 'UPDATE_STATUS',
payload: {
id: fileName,
status: 'Complete',
},
});
return;
} catch (e) {
const error = ensureError(e);
if (error instanceof DatabaseError) {
dispatch({
type: 'UPDATE_ERROR',
payload: {
id: file.name,
rawError: error,
error: {
title: 'Database error during protocol import',
description: (
<AlertDialogDescription>{error.message}</AlertDialogDescription>
),
additionalContent: (
<ErrorDetails errorText={error.originalError.toString()}>
<pre>{error.originalError.toString()}</pre>
</ErrorDetails>
),
},
},
});
} else {
dispatch({
type: 'UPDATE_ERROR',
payload: {
id: file.name,
rawError: error,
error: {
title: 'Error importing protocol',
description: (
<AlertDialogDescription>
There was an unknown error while importing your protocol. The
information below might help us to debug the issue.
</AlertDialogDescription>
),
additionalContent: (
<ErrorDetails errorText={JSON.stringify(error, null, 2)}>
<pre>{error.message}</pre>
</ErrorDetails>
),
},
},
});
}
return;
}
};
/**
* Create an async processing que for import jobs, to allow for multiple
* protocols to be imported with a nice UX.
*
* Concurrency set to 2 for now. We can increase this because unzipping and
* validation are basically instant, but the asset upload and db insertion
* need a separate queue to avoid consuming too much bandwidth or overloading
* the database.
*/
const jobQueue = useRef(queue(processJob, 2));
const importProtocols = (files: File[]) => {
files.forEach((file) => {
// Test if there is already a job in the jobQueue with this name
const jobAlreadyExists = jobs.find((job) => job.id === file.name);
if (jobAlreadyExists) {
// eslint-disable-next-line no-console
console.warn(`Skipping duplicate job: ${file.name}`);
return;
}
dispatch({
type: 'ADD_JOB',
payload: {
file,
},
});
jobQueue.current.push(file).catch((error) => {
// eslint-disable-next-line no-console
console.log('jobQueue error', error);
});
});
};
const cancelAllJobs = useCallback(() => {
jobQueue.current.pause();
jobQueue.current.remove(() => true);
dispatch({
type: 'CLEAR_JOBS',
});
jobQueue.current.resume();
}, []);
const cancelJob = useCallback((id: string) => {
jobQueue.current.remove(({ data }) => {
return data.name === id;
});
dispatch({
type: 'REMOVE_JOB',
payload: {
id,
},
});
}, []);
return {
jobs,
importProtocols,
cancelJob,
cancelAllJobs,
};
};