@balena/pinejs 21.4.0-build-large-file-uploads-2-56700d672d31db4406ba01ca349d69af5c8611e7-1 → 21.4.0-build-add-actions-example-c20002c2bf051233b333158f3b7a0719f6cf6e4e-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 (38) hide show
  1. package/.versionbot/CHANGELOG.yml +3 -3
  2. package/CHANGELOG.md +1 -1
  3. package/out/actions/index.d.ts +32 -0
  4. package/out/actions/index.js +67 -0
  5. package/out/actions/index.js.map +1 -0
  6. package/out/config-loader/config-loader.js +7 -6
  7. package/out/config-loader/config-loader.js.map +1 -1
  8. package/out/sbvr-api/sbvr-utils.d.ts +1 -1
  9. package/out/sbvr-api/sbvr-utils.js +9 -2
  10. package/out/sbvr-api/sbvr-utils.js.map +1 -1
  11. package/out/webresource-handler/actions/beginUpload.d.ts +3 -0
  12. package/out/webresource-handler/actions/beginUpload.js +99 -0
  13. package/out/webresource-handler/actions/beginUpload.js.map +1 -0
  14. package/out/webresource-handler/actions/canceUpload.d.ts +3 -0
  15. package/out/webresource-handler/actions/canceUpload.js +59 -0
  16. package/out/webresource-handler/actions/canceUpload.js.map +1 -0
  17. package/out/webresource-handler/actions/commitUpload.d.ts +3 -0
  18. package/out/webresource-handler/actions/commitUpload.js +85 -0
  19. package/out/webresource-handler/actions/commitUpload.js.map +1 -0
  20. package/out/webresource-handler/index.d.ts +1 -1
  21. package/out/webresource-handler/index.js +11 -6
  22. package/out/webresource-handler/index.js.map +1 -1
  23. package/out/webresource-handler/multiparUpload.d.ts +4 -0
  24. package/out/webresource-handler/multiparUpload.js +14 -0
  25. package/out/webresource-handler/multiparUpload.js.map +1 -0
  26. package/package.json +2 -2
  27. package/src/actions/index.ts +142 -0
  28. package/src/config-loader/config-loader.ts +8 -8
  29. package/src/sbvr-api/sbvr-utils.ts +11 -2
  30. package/src/webresource-handler/actions/beginUpload.ts +160 -0
  31. package/src/webresource-handler/actions/canceUpload.ts +93 -0
  32. package/src/webresource-handler/actions/commitUpload.ts +116 -0
  33. package/src/webresource-handler/index.ts +16 -14
  34. package/src/webresource-handler/multiparUpload.ts +23 -0
  35. package/out/webresource-handler/multipartUpload.d.ts +0 -12
  36. package/out/webresource-handler/multipartUpload.js +0 -297
  37. package/out/webresource-handler/multipartUpload.js.map +0 -1
  38. package/src/webresource-handler/multipartUpload.ts +0 -424
@@ -1,424 +0,0 @@
1
- import type { WebResourceType as WebResource } from '@balena/sbvr-types';
2
- import { randomUUID } from 'node:crypto';
3
- import type { AnyObject } from 'pinejs-client-core';
4
- import type {
5
- BeginMultipartUploadPayload,
6
- UploadPart,
7
- WebResourceHandler,
8
- } from './index.js';
9
- import { getWebResourceFields } from './index.js';
10
- import type { PinejsClient } from '../sbvr-api/sbvr-utils.js';
11
- import { api, getAffectedIds, getIdField } from '../sbvr-api/sbvr-utils.js';
12
- import { type ODataRequest } from '../sbvr-api/uri-parser.js';
13
- import { errors, sbvrUtils } from '../server-glue/module.js';
14
- import { webResource as webResourceEnv } from '../config-loader/env.js';
15
- import * as permissions from '../sbvr-api/permissions.js';
16
- import { TransactionClosedError, type Tx } from '../database-layer/db.js';
17
- import { UnauthorizedError } from '../sbvr-api/errors.js';
18
-
19
- type BeginUploadDbCheck = BeginMultipartUploadPayload & WebResource;
20
-
21
- export interface BeginUploadResponse {
22
- [fieldName: string]: {
23
- uuid: string;
24
- uploadParts: UploadPart[];
25
- };
26
- }
27
-
28
- // Is WebResourceHandler but with beginMultipartUpload and commitMultipartUpload as not optional
29
- type MultipartUploadHandler = WebResourceHandler &
30
- Required<Pick<WebResourceHandler, 'multipartUpload'>>;
31
-
32
- export const isMultipartUploadAvailable = (
33
- webResourceHandler: WebResourceHandler,
34
- ): webResourceHandler is MultipartUploadHandler => {
35
- return (
36
- webResourceEnv.multipartUploadEnabled &&
37
- webResourceHandler.multipartUpload != null
38
- );
39
- };
40
-
41
- export const multipartUploadHooks = (
42
- webResourceHandler: MultipartUploadHandler,
43
- ): sbvrUtils.Hooks => {
44
- return {
45
- POSTPARSE: async ({ request, tx, api: applicationApi }) => {
46
- if (request.odataQuery.property?.resource === 'beginUpload') {
47
- const uploadParams = await validateBeginUpload(
48
- request,
49
- applicationApi,
50
- webResourceHandler,
51
- );
52
-
53
- request.method = 'GET';
54
- request.odataQuery.resource = request.resourceName;
55
- delete request.odataQuery.property;
56
- request.custom.isAction = 'beginUpload';
57
- request.custom.uploadProbeParams = uploadParams;
58
- } else if (request.odataQuery.property?.resource === 'commitUpload') {
59
- const commitPayload = await validateCommitUpload(
60
- request,
61
- applicationApi,
62
- );
63
-
64
- request.method = 'PATCH';
65
- request.values = {
66
- // Set so that bindings are there but only actually set the correct value in prerun
67
- [commitPayload.metadata.fieldName]: undefined,
68
- };
69
- request.odataQuery.resource = request.resourceName;
70
-
71
- delete request.odataQuery.property;
72
- request.custom.isAction = 'commitUpload';
73
- request.custom.commitPayload = commitPayload;
74
- request.custom.fieldName = commitPayload.metadata.fieldName;
75
- } else if (request.odataQuery.property?.resource === 'cancelUpload') {
76
- const { uuid, fileKey, uploadId } = await validateCancelPayload(
77
- request,
78
- applicationApi,
79
- );
80
-
81
- await webResourceHandler.multipartUpload.cancel({ fileKey, uploadId });
82
-
83
- await api.webresource.patch({
84
- resource: 'multipart_upload',
85
- body: {
86
- status: 'cancelled',
87
- },
88
- options: {
89
- $filter: { uuid },
90
- },
91
- passthrough: {
92
- tx: tx,
93
- req: permissions.root,
94
- },
95
- });
96
-
97
- request.method = 'GET';
98
- request.odataQuery.resource = request.resourceName;
99
- delete request.odataQuery.property;
100
- request.custom.isAction = 'cancelUpload';
101
- }
102
- },
103
- PRERUN: async (args) => {
104
- const { api: applicationApi, request, tx } = args;
105
-
106
- if (request.custom.isAction === 'beginUpload') {
107
- try {
108
- await sbvrUtils.db.transaction(async (probeTx) => {
109
- const newUrl = request.url
110
- .slice(1)
111
- .replace(/(\/beginUpload|\/commitUpload|\/cancelUpload)$/, '');
112
- await applicationApi.request({
113
- method: 'PATCH',
114
- url: newUrl,
115
- body: request.custom.uploadProbeParams,
116
- passthrough: { tx: probeTx, req: permissions.root },
117
- });
118
- await probeTx.rollback();
119
- });
120
- } catch (e) {
121
- if (
122
- !(
123
- e instanceof TransactionClosedError &&
124
- e.message === 'Transaction has been rolled back.'
125
- )
126
- ) {
127
- throw e;
128
- }
129
- }
130
- } else if (request.custom.isAction === 'commitUpload') {
131
- args.request.url = args.request.url.replace(
132
- /(\/beginUpload|\/commitUpload|\/cancelUpload)$/,
133
- '',
134
- );
135
- const ids = await getAffectedIds(args);
136
- if (ids.length !== 1) {
137
- throw new UnauthorizedError();
138
- }
139
-
140
- if (ids[0] !== request.custom.commitPayload.metadata.resourceId) {
141
- throw new UnauthorizedError();
142
- }
143
-
144
- const webresource = await webResourceHandler.multipartUpload.commit({
145
- fileKey: request.custom.commitPayload.metadata.fileKey,
146
- uploadId: request.custom.commitPayload.metadata.uploadId,
147
- filename: request.custom.commitPayload.metadata.filename,
148
- providerCommitData: request.custom.commitPayload.providerCommitData,
149
- });
150
-
151
- request.values[request.custom.fieldName] = webresource;
152
-
153
- await api.webresource.patch({
154
- resource: 'multipart_upload',
155
- body: {
156
- status: 'completed',
157
- },
158
- options: {
159
- $filter: {
160
- uuid: request.custom.commitPayload.uuid,
161
- },
162
- },
163
- passthrough: {
164
- tx: tx,
165
- req: permissions.root,
166
- },
167
- });
168
- request.custom.commitUploadPayload = webresource;
169
- }
170
- },
171
- PRERESPOND: async ({ request, response, req, tx }) => {
172
- if (request.custom.isAction === 'beginUpload') {
173
- if (!response.body || typeof response.body === 'string') {
174
- throw new UnauthorizedError();
175
- }
176
- const idField = getIdField(request);
177
- const resourceId = response.body?.d?.[0]?.[idField];
178
- if (!resourceId) {
179
- throw new UnauthorizedError();
180
- }
181
-
182
- response.statusCode = 200;
183
- response.body = await beginUpload(
184
- {
185
- webResourceHandler,
186
- odataRequest: request,
187
- actorId: req.user?.actor,
188
- resourceId,
189
- },
190
- tx,
191
- );
192
- } else if (request.custom.isAction === 'commitUpload') {
193
- response.body = await webResourceHandler.onPreRespond(
194
- request.custom.commitUploadPayload,
195
- );
196
- } else if (request.custom.isAction === 'cancelUpload') {
197
- response.statusCode = 204;
198
- delete response.body;
199
- }
200
- },
201
- };
202
- };
203
-
204
- const beginUpload = async (
205
- {
206
- webResourceHandler,
207
- odataRequest,
208
- actorId,
209
- resourceId,
210
- }: {
211
- webResourceHandler: MultipartUploadHandler;
212
- odataRequest: ODataRequest;
213
- actorId?: number;
214
- resourceId: number;
215
- },
216
- tx: Tx,
217
- ): Promise<BeginUploadResponse> => {
218
- const payload = odataRequest.values as {
219
- [x: string]: BeginMultipartUploadPayload;
220
- };
221
- const fieldName = Object.keys(payload)[0];
222
- const metadata = payload[fieldName];
223
- const { fileKey, uploadId, uploadParts } =
224
- await webResourceHandler.multipartUpload.begin(fieldName, metadata);
225
- const uuid = randomUUID();
226
-
227
- await api.webresource.post({
228
- resource: 'multipart_upload',
229
- body: {
230
- uuid,
231
- resource_name: odataRequest.resourceName,
232
- field_name: fieldName,
233
- resource_id: resourceId,
234
- upload_id: uploadId,
235
- file_key: fileKey,
236
- status: 'pending',
237
- filename: metadata.filename,
238
- content_type: metadata.content_type,
239
- size: metadata.size,
240
- chunk_size: metadata.chunk_size,
241
- expiry_date: Date.now() + 7 * 24 * 60 * 60 * 1000, // 7 days in ms
242
- is_created_by__actor: actorId,
243
- },
244
- passthrough: {
245
- req: permissions.root,
246
- tx,
247
- },
248
- });
249
- return { [fieldName]: { uuid, uploadParts } };
250
- };
251
-
252
- const validateBeginUpload = async (
253
- request: ODataRequest,
254
- applicationApi: PinejsClient,
255
- webResourceHandler: MultipartUploadHandler,
256
- ) => {
257
- await canAccess(request, applicationApi);
258
-
259
- const fieldNames = Object.keys(request.values);
260
- if (fieldNames.length !== 1) {
261
- throw new errors.BadRequestError(
262
- 'You can only get upload url for one field at a time',
263
- );
264
- }
265
-
266
- const [fieldName] = fieldNames;
267
- const webResourceFields = getWebResourceFields(request);
268
- if (!webResourceFields.includes(fieldName)) {
269
- throw new errors.BadRequestError(
270
- `The provided field '${fieldName}' is not a valid webresource`,
271
- );
272
- }
273
-
274
- const beginUploadPayload = parseBeginUploadPayload(
275
- request.values[fieldName],
276
- webResourceHandler,
277
- );
278
- if (beginUploadPayload == null) {
279
- throw new errors.BadRequestError('Invalid file metadata');
280
- }
281
-
282
- const uploadMetadataCheck: BeginUploadDbCheck = {
283
- ...beginUploadPayload,
284
- // This is "probe" request. We don't actually store anything on the application table yet
285
- // We just avoid creating the application record if it would fail anyway for some other db constraint
286
- href: 'metadata_check_probe',
287
- };
288
-
289
- return { [fieldName]: uploadMetadataCheck };
290
- };
291
-
292
- const parseBeginUploadPayload = (
293
- payload: AnyObject,
294
- webResourceHandler: MultipartUploadHandler,
295
- ): BeginMultipartUploadPayload | null => {
296
- if (payload == null || typeof payload !== 'object') {
297
- return null;
298
- }
299
-
300
- let { filename, content_type, size, chunk_size } = payload;
301
- if (
302
- typeof filename !== 'string' ||
303
- typeof content_type !== 'string' ||
304
- typeof size !== 'number' ||
305
- (chunk_size != null && typeof chunk_size !== 'number') ||
306
- (chunk_size != null &&
307
- chunk_size < webResourceHandler.multipartUpload.getMinimumPartSize())
308
- ) {
309
- return null;
310
- }
311
-
312
- chunk_size ??= webResourceHandler.multipartUpload.getDefaultPartSize();
313
-
314
- return { filename, content_type, size, chunk_size };
315
- };
316
-
317
- const validateCommitUpload = async (
318
- request: ODataRequest,
319
- applicationApi: PinejsClient,
320
- ) => {
321
- await canAccess(request, applicationApi);
322
-
323
- const { uuid, providerCommitData } = request.values;
324
- if (typeof uuid !== 'string') {
325
- throw new errors.BadRequestError('Invalid uuid type');
326
- }
327
-
328
- const [multipartUpload] = await api.webresource.get({
329
- resource: 'multipart_upload',
330
- options: {
331
- $select: [
332
- 'id',
333
- 'file_key',
334
- 'upload_id',
335
- 'field_name',
336
- 'filename',
337
- 'resource_id',
338
- 'resource_name',
339
- ],
340
- $filter: {
341
- uuid,
342
- status: 'pending',
343
- expiry_date: { $gt: { $now: {} } },
344
- resource_name: request.resourceName,
345
- },
346
- },
347
- passthrough: {
348
- tx: request.tx,
349
- req: permissions.rootRead,
350
- },
351
- });
352
-
353
- if (multipartUpload == null) {
354
- throw new errors.BadRequestError(`Invalid upload for uuid ${uuid}`);
355
- }
356
-
357
- const metadata = {
358
- fileKey: multipartUpload.file_key,
359
- uploadId: multipartUpload.upload_id,
360
- filename: multipartUpload.filename,
361
- fieldName: multipartUpload.field_name,
362
- resourceName: multipartUpload.resource_name,
363
- resourceId: multipartUpload.resource_id,
364
- };
365
-
366
- return { uuid, providerCommitData, metadata };
367
- };
368
-
369
- const validateCancelPayload = async (
370
- request: ODataRequest,
371
- applicationApi: PinejsClient,
372
- ) => {
373
- await canAccess(request, applicationApi);
374
-
375
- const { uuid } = request.values;
376
- if (typeof uuid !== 'string') {
377
- throw new errors.BadRequestError('Invalid uuid type');
378
- }
379
-
380
- const [multipartUpload] = await api.webresource.get({
381
- resource: 'multipart_upload',
382
- options: {
383
- $select: ['id', 'file_key', 'upload_id'],
384
- $filter: {
385
- uuid,
386
- status: 'pending',
387
- expiry_date: { $gt: { $now: {} } },
388
- },
389
- },
390
- passthrough: {
391
- tx: request.tx,
392
- req: permissions.rootRead,
393
- },
394
- });
395
-
396
- if (multipartUpload == null) {
397
- throw new errors.BadRequestError(`Invalid upload for uuid ${uuid}`);
398
- }
399
-
400
- return {
401
- uuid,
402
- fileKey: multipartUpload.file_key,
403
- uploadId: multipartUpload.upload_id,
404
- };
405
- };
406
-
407
- const canAccess = async (
408
- request: ODataRequest,
409
- applicationApi: PinejsClient,
410
- ) => {
411
- if (request.odataQuery.key == null) {
412
- throw new errors.BadRequestError();
413
- }
414
-
415
- const canAccessUrl = request.url
416
- .slice(1)
417
- .replace(/(beginUpload|commitUpload|cancelUpload)$/, 'canAccess');
418
-
419
- await applicationApi.request({
420
- method: 'POST',
421
- url: canAccessUrl,
422
- body: { method: 'PATCH' },
423
- });
424
- };