@balena/pinejs 21.4.0-build-add-odata-actions-8d4944e07924e5cf0a69183c18610e8fd2c41d3b-1 → 21.4.0-build-add-actions-example-f26873fd527dfaaabb15c7bc21476f6b48bfc38a-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 (52) hide show
  1. package/.pinejs-cache.json +1 -1
  2. package/.versionbot/CHANGELOG.yml +49 -1
  3. package/CHANGELOG.md +6 -0
  4. package/out/config-loader/config-loader.js +8 -7
  5. package/out/config-loader/config-loader.js.map +1 -1
  6. package/out/config-loader/env.d.ts +4 -0
  7. package/out/config-loader/env.js +4 -0
  8. package/out/config-loader/env.js.map +1 -1
  9. package/out/server-glue/module.js +2 -0
  10. package/out/server-glue/module.js.map +1 -1
  11. package/out/tasks/index.d.ts +1 -0
  12. package/out/tasks/index.js +6 -1
  13. package/out/tasks/index.js.map +1 -1
  14. package/out/tasks/pine-tasks.d.ts +1 -0
  15. package/out/tasks/pine-tasks.js +7 -0
  16. package/out/tasks/pine-tasks.js.map +1 -0
  17. package/out/webresource-handler/actions/beginUpload.d.ts +3 -0
  18. package/out/webresource-handler/actions/beginUpload.js +105 -0
  19. package/out/webresource-handler/actions/beginUpload.js.map +1 -0
  20. package/out/webresource-handler/actions/canceUpload.d.ts +3 -0
  21. package/out/webresource-handler/actions/canceUpload.js +58 -0
  22. package/out/webresource-handler/actions/canceUpload.js.map +1 -0
  23. package/out/webresource-handler/actions/commitUpload.d.ts +3 -0
  24. package/out/webresource-handler/actions/commitUpload.js +85 -0
  25. package/out/webresource-handler/actions/commitUpload.js.map +1 -0
  26. package/out/webresource-handler/delete-file-task.d.ts +1 -0
  27. package/out/webresource-handler/delete-file-task.js +37 -0
  28. package/out/webresource-handler/delete-file-task.js.map +1 -0
  29. package/out/webresource-handler/index.d.ts +10 -1
  30. package/out/webresource-handler/index.js +83 -45
  31. package/out/webresource-handler/index.js.map +1 -1
  32. package/out/webresource-handler/multipartUpload.d.ts +4 -0
  33. package/out/webresource-handler/multipartUpload.js +14 -0
  34. package/out/webresource-handler/multipartUpload.js.map +1 -0
  35. package/out/webresource-handler/webresource.d.ts +42 -0
  36. package/out/webresource-handler/webresource.js +2 -0
  37. package/out/webresource-handler/webresource.js.map +1 -0
  38. package/out/webresource-handler/webresource.sbvr +60 -0
  39. package/package.json +5 -5
  40. package/src/config-loader/config-loader.ts +9 -9
  41. package/src/config-loader/env.ts +11 -0
  42. package/src/server-glue/module.ts +2 -0
  43. package/src/tasks/index.ts +9 -1
  44. package/src/tasks/pine-tasks.ts +7 -0
  45. package/src/webresource-handler/actions/beginUpload.ts +163 -0
  46. package/src/webresource-handler/actions/canceUpload.ts +92 -0
  47. package/src/webresource-handler/actions/commitUpload.ts +117 -0
  48. package/src/webresource-handler/delete-file-task.ts +42 -0
  49. package/src/webresource-handler/index.ts +117 -83
  50. package/src/webresource-handler/multipartUpload.ts +23 -0
  51. package/src/webresource-handler/webresource.sbvr +60 -0
  52. package/src/webresource-handler/webresource.ts +48 -0
@@ -0,0 +1,163 @@
1
+ import { api, type Response } from '../../sbvr-api/sbvr-utils.js';
2
+ import type { MultipartUploadHandler } from '../multipartUpload.js';
3
+ import { getMultipartUploadHandler } from '../multipartUpload.js';
4
+ import type { BeginMultipartUploadPayload } from '../index.js';
5
+ import { getWebResourceFields } from '../index.js';
6
+ import { BadRequestError, NotImplementedError } from '../../sbvr-api/errors.js';
7
+ import { permissions, sbvrUtils } from '../../server-glue/module.js';
8
+ import { randomUUID } from 'crypto';
9
+ import type { WebResourceType as WebResource } from '@balena/sbvr-types';
10
+ import type {
11
+ ODataActionArgs,
12
+ ODataActionRequest,
13
+ } from '../../sbvr-api/actions.js';
14
+ import { ajv } from '../../tasks/common.js';
15
+ import type { FromSchema } from 'json-schema-to-ts';
16
+
17
+ type FakeWebResourcePatch = {
18
+ [key: string]: Omit<WebResource, 'href'> & {
19
+ href: 'fake_patch';
20
+ };
21
+ };
22
+
23
+ const beginUploadPayloadSchema = {
24
+ type: 'object',
25
+ minProperties: 1,
26
+ maxProperties: 1,
27
+ additionalProperties: {
28
+ type: 'object',
29
+ properties: {
30
+ filename: { type: 'string' },
31
+ content_type: { type: 'string' },
32
+ size: { type: 'number' },
33
+ chunk_size: { type: 'number' },
34
+ },
35
+ required: ['filename', 'content_type', 'size'],
36
+ additionalProperties: false,
37
+ },
38
+ } as const;
39
+
40
+ const validateBeginUpload = ajv.compile<
41
+ FromSchema<typeof beginUploadPayloadSchema>
42
+ >(beginUploadPayloadSchema);
43
+
44
+ export const beginUploadAction = async ({
45
+ request,
46
+ tx,
47
+ id,
48
+ req,
49
+ }: ODataActionArgs): Promise<Response> => {
50
+ if (typeof id !== 'number') {
51
+ throw new NotImplementedError(
52
+ 'multipart upload do not yet support non-numeric ids',
53
+ );
54
+ }
55
+
56
+ const handler = getMultipartUploadHandler();
57
+ const { fieldName, beginUploadPayload } = parseBeginUpload(request, handler);
58
+
59
+ await runFakeDbPatch(request, {
60
+ [fieldName]: { ...beginUploadPayload, href: 'fake_patch' },
61
+ });
62
+
63
+ const { fileKey, uploadId, uploadParts } =
64
+ await handler.multipartUpload.begin(fieldName, beginUploadPayload);
65
+ const uuid = randomUUID();
66
+ await api.webresource.post({
67
+ resource: 'multipart_upload',
68
+ body: {
69
+ uuid,
70
+ resource_name: request.resourceName,
71
+ field_name: fieldName,
72
+ resource_id: id,
73
+ upload_id: uploadId,
74
+ file_key: fileKey,
75
+ status: 'pending',
76
+ ...beginUploadPayload,
77
+ expiry_date: Date.now() + 7 * 24 * 60 * 60 * 1000, // 7 days in ms
78
+ is_created_by__actor: req.user?.actor,
79
+ },
80
+ passthrough: {
81
+ req: permissions.root,
82
+ tx,
83
+ },
84
+ });
85
+
86
+ return {
87
+ body: { [fieldName]: { uuid, uploadParts } },
88
+ statusCode: 200,
89
+ };
90
+ };
91
+
92
+ const parseBeginUpload = (
93
+ request: ODataActionRequest,
94
+ webResourceHandler: MultipartUploadHandler,
95
+ ) => {
96
+ const { values } = request;
97
+ const isValid = validateBeginUpload(values);
98
+ if (!isValid) {
99
+ throw new BadRequestError('Invalid begin upload payload');
100
+ }
101
+
102
+ const fieldName = Object.keys(values)[0];
103
+
104
+ const webResourceFields = getWebResourceFields(request, false);
105
+ if (!webResourceFields.includes(fieldName)) {
106
+ throw new BadRequestError(
107
+ `The provided field '${fieldName}' is not a valid webresource`,
108
+ );
109
+ }
110
+ const beginUploadPayload = {
111
+ ...values[fieldName],
112
+ chunk_size:
113
+ values[fieldName].chunk_size ??
114
+ webResourceHandler.multipartUpload.getMinimumPartSize(),
115
+ } satisfies BeginMultipartUploadPayload;
116
+
117
+ if (
118
+ beginUploadPayload.chunk_size <
119
+ webResourceHandler.multipartUpload.getMinimumPartSize()
120
+ ) {
121
+ throw new BadRequestError('Chunk size is too small');
122
+ }
123
+
124
+ return {
125
+ beginUploadPayload,
126
+ fieldName,
127
+ };
128
+ };
129
+
130
+ // We want beginUpload to fail if the initial payload would already break any constraint/hooks/rule
131
+ // this serves as both an optimization and a better client experience as it avoids succeding a beginUpload
132
+ // (which could allow for potentially very large PartUploads) only for it to fail on commitUpload
133
+ // The current approach to try to achieve this behavior creates this fake database patch:
134
+ // It first tries to patch the file metadata (on a separate tx) to something similar to what it would look like
135
+ // and if it breaks any constraint, then it throws and fail to even start the upload
136
+ // Note that because the href is only generated at commitUpload time, we need to fake it for the time being
137
+ // This could potentially be a problem if an application code has a constraint on the href property
138
+ // However, because this is a internal (pine managed) property we assumed that application code won't do so
139
+ const runFakeDbPatch = async (
140
+ request: ODataActionRequest,
141
+ fakeDbPatch: FakeWebResourcePatch,
142
+ ) => {
143
+ const fakeTx = await sbvrUtils.db.transaction();
144
+ try {
145
+ const newUrl = request.url
146
+ .slice(1)
147
+ .split('?', 1)[0]
148
+ .replace(/\/beginUpload$/, '');
149
+
150
+ await api[request.vocabulary].request({
151
+ method: 'PATCH',
152
+ url: newUrl,
153
+ body: fakeDbPatch,
154
+ // it needs root as otherwise it would always fail as non-root users
155
+ // are not allowed to directly patch webresource metadata, onnly upload files
156
+ passthrough: { tx: fakeTx, req: permissions.root },
157
+ });
158
+ } finally {
159
+ if (!fakeTx.isClosed()) {
160
+ await fakeTx.rollback();
161
+ }
162
+ }
163
+ };
@@ -0,0 +1,92 @@
1
+ import type {
2
+ ODataActionArgs,
3
+ ODataActionRequest,
4
+ } from '../../sbvr-api/actions.js';
5
+ import type { Tx } from '../../database-layer/db.js';
6
+ import {
7
+ BadRequestError,
8
+ NotImplementedError,
9
+ UnauthorizedError,
10
+ } from '../../sbvr-api/errors.js';
11
+ import { api, type Response } from '../../sbvr-api/sbvr-utils.js';
12
+ import { permissions } from '../../server-glue/module.js';
13
+ import { getMultipartUploadHandler } from '../multipartUpload.js';
14
+
15
+ export const cancelUploadAction = async ({
16
+ request,
17
+ tx,
18
+ id: resourceId,
19
+ }: ODataActionArgs): Promise<Response> => {
20
+ if (typeof resourceId !== 'number') {
21
+ throw new NotImplementedError(
22
+ 'multipart upload do not yet support non-numeric ids',
23
+ );
24
+ }
25
+ const { id, fileKey, uploadId } = await getOngoingUpload(
26
+ request,
27
+ resourceId,
28
+ tx,
29
+ );
30
+ const handler = getMultipartUploadHandler();
31
+
32
+ await api.webresource.patch({
33
+ resource: 'multipart_upload',
34
+ body: {
35
+ status: 'cancelled',
36
+ },
37
+ id,
38
+ passthrough: {
39
+ tx: tx,
40
+ req: permissions.root,
41
+ },
42
+ });
43
+
44
+ // Note that different then beginUpload/commitUpload where we first do the action on the external service
45
+ // and then reflect it on the DB, for cancel upload it is the other way around
46
+ // as the worst case scenario is having a canceled upload which is marked on the DB as something else
47
+ await handler.multipartUpload.cancel({ fileKey, uploadId });
48
+
49
+ return {
50
+ statusCode: 204,
51
+ };
52
+ };
53
+
54
+ const getOngoingUpload = async (
55
+ request: ODataActionRequest,
56
+ affectedId: number,
57
+ tx: Tx,
58
+ ) => {
59
+ const { uuid } = request.values;
60
+ if (uuid == null || typeof uuid !== 'string') {
61
+ throw new BadRequestError('Invalid uuid type');
62
+ }
63
+
64
+ const [multipartUpload] = await api.webresource.get({
65
+ resource: 'multipart_upload',
66
+ options: {
67
+ $select: ['id', 'file_key', 'upload_id'],
68
+ $filter: {
69
+ // TODO: swap this into the ID to see if it works
70
+ uuid,
71
+ status: 'pending',
72
+ expiry_date: { $gt: { $now: {} } },
73
+ resource_name: request.resourceName,
74
+ resource_id: affectedId,
75
+ },
76
+ },
77
+ passthrough: {
78
+ tx,
79
+ req: permissions.rootRead,
80
+ },
81
+ });
82
+
83
+ if (multipartUpload == null) {
84
+ throw new UnauthorizedError();
85
+ }
86
+
87
+ return {
88
+ id: multipartUpload.id,
89
+ fileKey: multipartUpload.file_key,
90
+ uploadId: multipartUpload.upload_id,
91
+ };
92
+ };
@@ -0,0 +1,117 @@
1
+ import type { Tx } from '../../database-layer/db.js';
2
+ import type {
3
+ ODataActionArgs,
4
+ ODataActionRequest,
5
+ } from '../../sbvr-api/actions.js';
6
+ import {
7
+ BadRequestError,
8
+ NotImplementedError,
9
+ UnauthorizedError,
10
+ } from '../../sbvr-api/errors.js';
11
+ import type { Response } from '../../sbvr-api/sbvr-utils.js';
12
+ import { api } from '../../sbvr-api/sbvr-utils.js';
13
+ import { permissions } from '../../server-glue/module.js';
14
+ import { getMultipartUploadHandler } from '../multipartUpload.js';
15
+
16
+ export const commitUploadAction = async ({
17
+ request,
18
+ tx,
19
+ id,
20
+ api: applicationApi,
21
+ }: ODataActionArgs): Promise<Response> => {
22
+ if (typeof id !== 'number') {
23
+ throw new NotImplementedError(
24
+ 'multipart upload do not yet support non-numeric ids',
25
+ );
26
+ }
27
+
28
+ const multipartUpload = await getOngoingUpload(request, id, tx);
29
+ const handler = getMultipartUploadHandler();
30
+
31
+ const webresource = await handler.multipartUpload.commit({
32
+ fileKey: multipartUpload.fileKey,
33
+ uploadId: multipartUpload.uploadId,
34
+ filename: multipartUpload.filename,
35
+ providerCommitData: multipartUpload.providerCommitData,
36
+ });
37
+
38
+ await Promise.all([
39
+ api.webresource.patch({
40
+ resource: 'multipart_upload',
41
+ body: {
42
+ status: 'completed',
43
+ },
44
+ options: {
45
+ $filter: {
46
+ uuid: multipartUpload.uuid,
47
+ },
48
+ },
49
+ passthrough: {
50
+ tx: tx,
51
+ req: permissions.root,
52
+ },
53
+ }),
54
+ applicationApi.patch({
55
+ resource: request.resourceName,
56
+ id,
57
+ body: {
58
+ [multipartUpload.fieldName]: webresource,
59
+ },
60
+ passthrough: {
61
+ tx: tx,
62
+ // Root is needed as, if you are not root, you are not allowed to directly modify the actual metadata
63
+ req: permissions.root,
64
+ },
65
+ }),
66
+ ]);
67
+
68
+ const body = await handler.onPreRespond(webresource);
69
+
70
+ return {
71
+ body,
72
+ statusCode: 200,
73
+ };
74
+ };
75
+
76
+ const getOngoingUpload = async (
77
+ request: ODataActionRequest,
78
+ affectedId: number,
79
+ tx: Tx,
80
+ ) => {
81
+ const { uuid, providerCommitData } = request.values;
82
+ if (uuid == null || typeof uuid !== 'string') {
83
+ throw new BadRequestError('Invalid uuid type');
84
+ }
85
+
86
+ const [multipartUpload] = await api.webresource.get({
87
+ resource: 'multipart_upload',
88
+ options: {
89
+ $select: ['id', 'file_key', 'upload_id', 'field_name', 'filename'],
90
+ $filter: {
91
+ // TODO: swap this into the ID to see if it works
92
+ uuid,
93
+ status: 'pending',
94
+ expiry_date: { $gt: { $now: {} } },
95
+ resource_name: request.resourceName,
96
+ resource_id: affectedId,
97
+ },
98
+ },
99
+ passthrough: {
100
+ tx,
101
+ req: permissions.rootRead,
102
+ },
103
+ });
104
+
105
+ if (multipartUpload == null) {
106
+ throw new UnauthorizedError();
107
+ }
108
+
109
+ return {
110
+ uuid,
111
+ providerCommitData,
112
+ fileKey: multipartUpload.file_key,
113
+ uploadId: multipartUpload.upload_id,
114
+ filename: multipartUpload.filename,
115
+ fieldName: multipartUpload.field_name,
116
+ };
117
+ };
@@ -0,0 +1,42 @@
1
+ import { addTaskHandler } from '../tasks/index.js';
2
+ import { getWebresourceHandler } from './index.js';
3
+
4
+ const deleteFileSchema = {
5
+ type: 'object',
6
+ properties: {
7
+ fileKey: {
8
+ type: 'string',
9
+ },
10
+ },
11
+ required: ['fileKey'],
12
+ additionalProperties: false,
13
+ } as const;
14
+
15
+ export const addDeleteFileTaskHandler = () => {
16
+ addTaskHandler(
17
+ 'delete_webresource_file',
18
+ async (task) => {
19
+ const handler = getWebresourceHandler();
20
+ if (!handler) {
21
+ return {
22
+ error: 'Webresource handler not available',
23
+ status: 'failed',
24
+ };
25
+ }
26
+
27
+ try {
28
+ await handler.removeFile(task.params.fileKey);
29
+ return {
30
+ status: 'succeeded',
31
+ };
32
+ } catch (error) {
33
+ console.error('Error deleting file:', error);
34
+ return {
35
+ error: `${error}`,
36
+ status: 'failed',
37
+ };
38
+ }
39
+ },
40
+ deleteFileSchema,
41
+ );
42
+ };