@balena/pinejs 21.2.1 → 21.3.0-build-large-file-uploads-2-34511cebbabc0ea17d1d3d43274abd747a7316c6-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.
@@ -0,0 +1,249 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { getWebResourceFields } from './index.js';
3
+ import { api } from '../sbvr-api/sbvr-utils.js';
4
+ import { errors, sbvrUtils } from '../server-glue/module.js';
5
+ import { webResource as webResourceEnv } from '../config-loader/env.js';
6
+ import * as permissions from '../sbvr-api/permissions.js';
7
+ export const isMultipartUploadAvailable = (webResourceHandler) => {
8
+ return (webResourceEnv.multipartUploadEnabled &&
9
+ webResourceHandler.multipartUpload != null);
10
+ };
11
+ export const multipartUploadHooks = (webResourceHandler) => {
12
+ return {
13
+ POSTPARSE: async ({ req, request, tx, api: applicationApi }) => {
14
+ if (request.odataQuery.property?.resource === 'beginUpload') {
15
+ const uploadParams = await validateBeginUpload(request, applicationApi, webResourceHandler);
16
+ tx = await sbvrUtils.db.transaction();
17
+ req.tx = tx;
18
+ request.tx = tx;
19
+ request.method = 'PATCH';
20
+ request.values = uploadParams;
21
+ request.odataQuery.resource = request.resourceName;
22
+ delete request.odataQuery.property;
23
+ request.custom.isAction = 'beginUpload';
24
+ }
25
+ else if (request.odataQuery.property?.resource === 'commitUpload') {
26
+ const commitPayload = await validateCommitUpload(request, applicationApi);
27
+ const webresource = await webResourceHandler.multipartUpload.commit({
28
+ fileKey: commitPayload.metadata.fileKey,
29
+ uploadId: commitPayload.metadata.uploadId,
30
+ filename: commitPayload.metadata.filename,
31
+ providerCommitData: commitPayload.providerCommitData,
32
+ });
33
+ await api.webresource.patch({
34
+ resource: 'multipart_upload',
35
+ body: {
36
+ status: 'completed',
37
+ },
38
+ options: {
39
+ $filter: {
40
+ uuid: commitPayload.uuid,
41
+ },
42
+ },
43
+ passthrough: {
44
+ tx: tx,
45
+ req: permissions.root,
46
+ },
47
+ });
48
+ request.method = 'PATCH';
49
+ request.values = {
50
+ [commitPayload.metadata.fieldName]: webresource,
51
+ };
52
+ request.odataQuery.resource = request.resourceName;
53
+ delete request.odataQuery.property;
54
+ request.custom.isAction = 'commitUpload';
55
+ request.custom.commitUploadPayload = webresource;
56
+ }
57
+ else if (request.odataQuery.property?.resource === 'cancelUpload') {
58
+ const { uuid, fileKey, uploadId } = await validateCancelPayload(request, applicationApi);
59
+ await webResourceHandler.multipartUpload.cancel({ fileKey, uploadId });
60
+ await api.webresource.patch({
61
+ resource: 'multipart_upload',
62
+ body: {
63
+ status: 'cancelled',
64
+ },
65
+ options: {
66
+ $filter: { uuid },
67
+ },
68
+ passthrough: {
69
+ tx: tx,
70
+ req: permissions.root,
71
+ },
72
+ });
73
+ request.method = 'GET';
74
+ request.odataQuery.resource = request.resourceName;
75
+ delete request.odataQuery.property;
76
+ request.custom.isAction = 'cancelUpload';
77
+ }
78
+ },
79
+ PRERESPOND: async ({ req, request, response, tx }) => {
80
+ if (request.custom.isAction === 'beginUpload') {
81
+ await tx.rollback();
82
+ response.statusCode = 200;
83
+ response.body = await beginUpload({
84
+ webResourceHandler,
85
+ odataRequest: request,
86
+ actorId: req.user?.actor,
87
+ });
88
+ }
89
+ else if (request.custom.isAction === 'commitUpload') {
90
+ response.body = await webResourceHandler.onPreRespond(request.custom.commitUploadPayload);
91
+ }
92
+ else if (request.custom.isAction === 'cancelUpload') {
93
+ response.statusCode = 204;
94
+ delete response.body;
95
+ }
96
+ },
97
+ };
98
+ };
99
+ const beginUpload = async ({ webResourceHandler, odataRequest, actorId, }) => {
100
+ const payload = odataRequest.values;
101
+ const fieldName = Object.keys(payload)[0];
102
+ const metadata = payload[fieldName];
103
+ const { fileKey, uploadId, uploadParts } = await webResourceHandler.multipartUpload.begin(fieldName, metadata);
104
+ const uuid = randomUUID();
105
+ return await sbvrUtils.db.transaction(async (tx) => {
106
+ try {
107
+ await api.webresource.post({
108
+ resource: 'multipart_upload',
109
+ body: {
110
+ uuid,
111
+ resource_name: odataRequest.resourceName,
112
+ field_name: fieldName,
113
+ resource_id: odataRequest.affectedIds?.[0],
114
+ upload_id: uploadId,
115
+ file_key: fileKey,
116
+ status: 'pending',
117
+ filename: metadata.filename,
118
+ content_type: metadata.content_type,
119
+ size: metadata.size,
120
+ chunk_size: metadata.chunk_size,
121
+ expiry_date: Date.now() + 7 * 24 * 60 * 60 * 1000,
122
+ is_created_by__actor: actorId,
123
+ },
124
+ passthrough: {
125
+ req: permissions.root,
126
+ tx,
127
+ },
128
+ });
129
+ return { [fieldName]: { uuid, uploadParts } };
130
+ }
131
+ catch (err) {
132
+ console.error('failed to start multipart upload', err);
133
+ throw new errors.BadRequestError('Failed to start multipart upload');
134
+ }
135
+ });
136
+ };
137
+ const validateBeginUpload = async (request, applicationApi, webResourceHandler) => {
138
+ await canAccess(request, applicationApi);
139
+ const fieldNames = Object.keys(request.values);
140
+ if (fieldNames.length !== 1) {
141
+ throw new errors.BadRequestError('You can only get upload url for one field at a time');
142
+ }
143
+ const [fieldName] = fieldNames;
144
+ const webResourceFields = getWebResourceFields(request);
145
+ if (!webResourceFields.includes(fieldName)) {
146
+ throw new errors.BadRequestError(`The provided field '${fieldName}' is not a valid webresource`);
147
+ }
148
+ const beginUploadPayload = parseBeginUploadPayload(request.values[fieldName], webResourceHandler);
149
+ if (beginUploadPayload == null) {
150
+ throw new errors.BadRequestError('Invalid file metadata');
151
+ }
152
+ const uploadMetadataCheck = {
153
+ ...beginUploadPayload,
154
+ href: 'metadata_check_probe',
155
+ };
156
+ return { [fieldName]: uploadMetadataCheck };
157
+ };
158
+ const parseBeginUploadPayload = (payload, webResourceHandler) => {
159
+ if (payload == null || typeof payload !== 'object') {
160
+ return null;
161
+ }
162
+ let { filename, content_type, size, chunk_size } = payload;
163
+ if (typeof filename !== 'string' ||
164
+ typeof content_type !== 'string' ||
165
+ typeof size !== 'number' ||
166
+ (chunk_size != null && typeof chunk_size !== 'number') ||
167
+ (chunk_size != null &&
168
+ chunk_size < webResourceHandler.multipartUpload.getMinimumPartSize())) {
169
+ return null;
170
+ }
171
+ chunk_size ??= webResourceHandler.multipartUpload.getDefaultPartSize();
172
+ return { filename, content_type, size, chunk_size };
173
+ };
174
+ const validateCommitUpload = async (request, applicationApi) => {
175
+ await canAccess(request, applicationApi);
176
+ const { uuid, providerCommitData } = request.values;
177
+ if (typeof uuid !== 'string') {
178
+ throw new errors.BadRequestError('Invalid uuid type');
179
+ }
180
+ const [multipartUpload] = await api.webresource.get({
181
+ resource: 'multipart_upload',
182
+ options: {
183
+ $select: ['id', 'file_key', 'upload_id', 'field_name', 'filename'],
184
+ $filter: {
185
+ uuid,
186
+ status: 'pending',
187
+ expiry_date: { $gt: { $now: {} } },
188
+ },
189
+ },
190
+ passthrough: {
191
+ tx: request.tx,
192
+ req: permissions.rootRead,
193
+ },
194
+ });
195
+ if (multipartUpload == null) {
196
+ throw new errors.BadRequestError(`Invalid upload for uuid ${uuid}`);
197
+ }
198
+ const metadata = {
199
+ fileKey: multipartUpload.file_key,
200
+ uploadId: multipartUpload.upload_id,
201
+ filename: multipartUpload.filename,
202
+ fieldName: multipartUpload.field_name,
203
+ };
204
+ return { uuid, providerCommitData, metadata };
205
+ };
206
+ const validateCancelPayload = async (request, applicationApi) => {
207
+ await canAccess(request, applicationApi);
208
+ const { uuid } = request.values;
209
+ if (typeof uuid !== 'string') {
210
+ throw new errors.BadRequestError('Invalid uuid type');
211
+ }
212
+ const [multipartUpload] = await api.webresource.get({
213
+ resource: 'multipart_upload',
214
+ options: {
215
+ $select: ['id', 'file_key', 'upload_id'],
216
+ $filter: {
217
+ uuid,
218
+ status: 'pending',
219
+ expiry_date: { $gt: { $now: {} } },
220
+ },
221
+ },
222
+ passthrough: {
223
+ tx: request.tx,
224
+ req: permissions.rootRead,
225
+ },
226
+ });
227
+ if (multipartUpload == null) {
228
+ throw new errors.BadRequestError(`Invalid upload for uuid ${uuid}`);
229
+ }
230
+ return {
231
+ uuid,
232
+ fileKey: multipartUpload.file_key,
233
+ uploadId: multipartUpload.upload_id,
234
+ };
235
+ };
236
+ const canAccess = async (request, applicationApi) => {
237
+ if (request.odataQuery.key == null) {
238
+ throw new errors.BadRequestError();
239
+ }
240
+ const canAccessUrl = request.url
241
+ .slice(1)
242
+ .replace(/(beginUpload|commitUpload|cancelUpload)$/, 'canAccess');
243
+ await applicationApi.request({
244
+ method: 'POST',
245
+ url: canAccessUrl,
246
+ body: { method: 'PATCH' },
247
+ });
248
+ };
249
+ //# sourceMappingURL=multipartUpload.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"multipartUpload.js","sourceRoot":"","sources":["../../src/webresource-handler/multipartUpload.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAOzC,OAAO,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAElD,OAAO,EAAE,GAAG,EAAE,MAAM,2BAA2B,CAAC;AAEhD,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EAAE,WAAW,IAAI,cAAc,EAAE,MAAM,yBAAyB,CAAC;AACxE,OAAO,KAAK,WAAW,MAAM,4BAA4B,CAAC;AAe1D,MAAM,CAAC,MAAM,0BAA0B,GAAG,CACzC,kBAAsC,EACS,EAAE;IACjD,OAAO,CACN,cAAc,CAAC,sBAAsB;QACrC,kBAAkB,CAAC,eAAe,IAAI,IAAI,CAC1C,CAAC;AACH,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,oBAAoB,GAAG,CACnC,kBAA0C,EACxB,EAAE;IACpB,OAAO;QACN,SAAS,EAAE,KAAK,EAAE,EAAE,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,GAAG,EAAE,cAAc,EAAE,EAAE,EAAE;YAC9D,IAAI,OAAO,CAAC,UAAU,CAAC,QAAQ,EAAE,QAAQ,KAAK,aAAa,EAAE,CAAC;gBAC7D,MAAM,YAAY,GAAG,MAAM,mBAA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2B,IAAI,EAAE,CAAC,CAAC;IACrE,CAAC;IAED,OAAO;QACN,IAAI;QACJ,OAAO,EAAE,eAAe,CAAC,QAAQ;QACjC,QAAQ,EAAE,eAAe,CAAC,SAAS;KACnC,CAAC;AACH,CAAC,CAAC;AAEF,MAAM,SAAS,GAAG,KAAK,EACtB,OAAqB,EACrB,cAA4B,EAC3B,EAAE;IACH,IAAI,OAAO,CAAC,UAAU,CAAC,GAAG,IAAI,IAAI,EAAE,CAAC;QACpC,MAAM,IAAI,MAAM,CAAC,eAAe,EAAE,CAAC;IACpC,CAAC;IAED,MAAM,YAAY,GAAG,OAAO,CAAC,GAAG;SAC9B,KAAK,CAAC,CAAC,CAAC;SACR,OAAO,CAAC,0CAA0C,EAAE,WAAW,CAAC,CAAC;IAEnE,MAAM,cAAc,CAAC,OAAO,CAAC;QAC5B,MAAM,EAAE,MAAM;QACd,GAAG,EAAE,YAAY;QACjB,IAAI,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE;KACzB,CAAC,CAAC;AACJ,CAAC,CAAC"}
@@ -0,0 +1,42 @@
1
+ import type { Types } from '@balena/abstract-sql-to-typescript';
2
+ export interface MultipartUpload {
3
+ Read: {
4
+ created_at: Types['Date Time']['Read'];
5
+ modified_at: Types['Date Time']['Read'];
6
+ id: Types['Serial']['Read'];
7
+ uuid: Types['Short Text']['Read'];
8
+ resource_name: Types['Short Text']['Read'];
9
+ field_name: Types['Short Text']['Read'];
10
+ resource_id: Types['Integer']['Read'];
11
+ upload_id: Types['Short Text']['Read'];
12
+ file_key: Types['Short Text']['Read'];
13
+ status: 'pending' | 'completed' | 'cancelled';
14
+ filename: Types['Short Text']['Read'];
15
+ content_type: Types['Short Text']['Read'];
16
+ size: Types['Integer']['Read'];
17
+ chunk_size: Types['Integer']['Read'];
18
+ expiry_date: Types['Date Time']['Read'];
19
+ is_created_by__actor: Types['Integer']['Read'] | null;
20
+ };
21
+ Write: {
22
+ created_at: Types['Date Time']['Write'];
23
+ modified_at: Types['Date Time']['Write'];
24
+ id: Types['Serial']['Write'];
25
+ uuid: Types['Short Text']['Write'];
26
+ resource_name: Types['Short Text']['Write'];
27
+ field_name: Types['Short Text']['Write'];
28
+ resource_id: Types['Integer']['Write'];
29
+ upload_id: Types['Short Text']['Write'];
30
+ file_key: Types['Short Text']['Write'];
31
+ status: 'pending' | 'completed' | 'cancelled';
32
+ filename: Types['Short Text']['Write'];
33
+ content_type: Types['Short Text']['Write'];
34
+ size: Types['Integer']['Write'];
35
+ chunk_size: Types['Integer']['Write'];
36
+ expiry_date: Types['Date Time']['Write'];
37
+ is_created_by__actor: Types['Integer']['Write'] | null;
38
+ };
39
+ }
40
+ export default interface $Model {
41
+ multipart_upload: MultipartUpload;
42
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=webresource.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webresource.js","sourceRoot":"","sources":["../../src/webresource-handler/webresource.ts"],"names":[],"mappings":""}
@@ -0,0 +1,60 @@
1
+ Vocabulary: webresource
2
+
3
+ Term: actor
4
+ Concept Type: Integer (Type)
5
+ Term: expiry date
6
+ Concept Type: Date Time (Type)
7
+ Term: uuid
8
+ Concept Type: Short Text (Type)
9
+ Term: resource name
10
+ Concept Type: Short Text (Type)
11
+ Term: field name
12
+ Concept Type: Short Text (Type)
13
+ Term: resource id
14
+ Concept Type: Integer (Type)
15
+ Term: upload id
16
+ Concept Type: Short Text (Type)
17
+ Term: file key
18
+ Concept Type: Short Text (Type)
19
+ Term: status
20
+ Concept Type: Short Text (Type)
21
+ Term: filename
22
+ Concept Type: Short Text (Type)
23
+ Term: content type
24
+ Concept Type: Short Text (Type)
25
+ Term: size
26
+ Concept Type: Integer (Type)
27
+ Term: chunk size
28
+ Concept Type: Integer (Type)
29
+ Term: valid until date
30
+ Concept Type: Date Time (Type)
31
+
32
+ Term: multipart upload
33
+ Fact type: multipart upload has uuid
34
+ Necessity: each multipart upload has exactly one uuid
35
+ Necessity: each uuid is of exactly one multipart upload
36
+ Fact type: multipart upload has resource name
37
+ Necessity: each multipart upload has exactly one resource name
38
+ Fact type: multipart upload has field name
39
+ Necessity: each multipart upload has exactly one field name
40
+ Fact type: multipart upload has resource id
41
+ Necessity: each multipart upload has exactly one resource id
42
+ Fact type: multipart upload has upload id
43
+ Necessity: each multipart upload has exactly one upload id
44
+ Fact type: multipart upload has file key
45
+ Necessity: each multipart upload has exactly one file key
46
+ Fact type: multipart upload has status
47
+ Necessity: each multipart upload has exactly one status
48
+ Definition: "pending" or "completed" or "cancelled"
49
+ Fact type: multipart upload has filename
50
+ Necessity: each multipart upload has exactly one filename
51
+ Fact type: multipart upload has content type
52
+ Necessity: each multipart upload has exactly one content type
53
+ Fact type: multipart upload has size
54
+ Necessity: each multipart upload has exactly one size
55
+ Fact type: multipart upload has chunk size
56
+ Necessity: each multipart upload has exactly one chunk size
57
+ Fact type: multipart upload has expiry date
58
+ Necessity: each multipart upload has exactly one expiry date
59
+ Fact type: multipart upload is created by actor
60
+ Necessity: each multipart upload is created by at most one actor
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@balena/pinejs",
3
- "version": "21.2.1",
3
+ "version": "21.3.0-build-large-file-uploads-2-34511cebbabc0ea17d1d3d43274abd747a7316c6-1",
4
4
  "main": "out/server-glue/module.js",
5
5
  "type": "module",
6
6
  "repository": "git@github.com:balena-io/pinejs.git",
@@ -20,10 +20,10 @@
20
20
  "webpack-build": "npm run webpack-browser && npm run webpack-module && npm run webpack-server",
21
21
  "lint": "balena-lint -t tsconfig.dev.json -e js -e ts src test build typings Gruntfile.cts && npx tsc --project tsconfig.dev.json --noEmit",
22
22
  "test": "npm run build && npm run lint && npm run webpack-build && npm run test:compose && npm run test:generated-types",
23
- "test:compose": "trap 'docker compose -f docker-compose.npm-test.yml down ; echo Stopped ; exit 0' INT; docker compose -f docker-compose.npm-test.yml up -d && sleep 2 && DATABASE_URL=postgres://docker:docker@localhost:5431/postgres PINEJS_WEBRESOURCE_MAXFILESIZE=1000000000 S3_ENDPOINT=http://localhost:43680 S3_ACCESS_KEY=USERNAME S3_SECRET_KEY=PASSWORD S3_STORAGE_ADAPTER_BUCKET=balena-pine-web-resources S3_REGION=us-east-1 PINEJS_QUEUE_CONCURRENCY=1 TZ=UTC npx mocha",
23
+ "test:compose": "trap 'docker compose -f docker-compose.npm-test.yml down ; echo Stopped ; exit 0' INT; docker compose -f docker-compose.npm-test.yml up -d && sleep 2 && DATABASE_URL=postgres://docker:docker@localhost:5431/postgres PINEJS_WEBRESOURCE_MAXFILESIZE=1000000000 S3_ENDPOINT=http://localhost:43680 S3_ACCESS_KEY=USERNAME S3_SECRET_KEY=PASSWORD S3_STORAGE_ADAPTER_BUCKET=balena-pine-web-resources S3_REGION=us-east-1 PINEJS_QUEUE_CONCURRENCY=1 TZ=UTC PINEJS_WEBRESOURCE_MULTIPART_ENABLED=true npx mocha",
24
24
  "test:generated-types": "npm run generate-types && git diff --exit-code ./src/sbvr-api/user.ts ./src/migrator/migrations.ts ./src/sbvr-api/dev.ts",
25
25
  "lint-fix": "balena-lint -t tsconfig.dev.json -e js -e ts --fix src test build typings Gruntfile.cts",
26
- "generate-types": "node ./bin/sbvr-compiler.js generate-types ./src/sbvr-api/user.sbvr ./src/sbvr-api/user.ts && node ./bin/sbvr-compiler.js generate-types ./src/migrator/migrations.sbvr ./src/migrator/migrations.ts && node ./bin/sbvr-compiler.js generate-types ./src/sbvr-api/dev.sbvr ./src/sbvr-api/dev.ts && node ./bin/sbvr-compiler.js generate-types ./src/tasks/tasks.sbvr ./src/tasks/tasks.ts && balena-lint -t tsconfig.dev.json --fix ./src/sbvr-api/user.ts ./src/migrator/migrations.ts ./src/sbvr-api/dev.ts"
26
+ "generate-types": "node ./bin/sbvr-compiler.js generate-types ./src/sbvr-api/user.sbvr ./src/sbvr-api/user.ts && node ./bin/sbvr-compiler.js generate-types ./src/migrator/migrations.sbvr ./src/migrator/migrations.ts && node ./bin/sbvr-compiler.js generate-types ./src/sbvr-api/dev.sbvr ./src/sbvr-api/dev.ts && node ./bin/sbvr-compiler.js generate-types ./src/tasks/tasks.sbvr ./src/tasks/tasks.ts && node ./bin/sbvr-compiler.js generate-types ./src/webresource-handler/webresource.sbvr ./src/webresource-handler/webresource.ts && balena-lint -t tsconfig.dev.json --fix ./src/sbvr-api/user.ts ./src/migrator/migrations.ts ./src/sbvr-api/dev.ts"
27
27
  },
28
28
  "dependencies": {
29
29
  "@balena/abstract-sql-compiler": "^10.2.3",
@@ -70,7 +70,7 @@
70
70
  "devDependencies": {
71
71
  "@balena/lint": "^9.1.6",
72
72
  "@balena/pinejs": "file:./",
73
- "@balena/pinejs-webresource-s3": "^1.0.4",
73
+ "@balena/pinejs-webresource-s3": "2.0.0-build-new-multiparthandle-interface-66b03581234eaa7ce15c6f389e39b5b7ed3d1bc5-1",
74
74
  "@faker-js/faker": "^9.6.0",
75
75
  "@types/busboy": "^1.5.4",
76
76
  "@types/chai": "^5.2.1",
@@ -149,6 +149,6 @@
149
149
  "recursive": true
150
150
  },
151
151
  "versionist": {
152
- "publishedAt": "2025-04-16T13:49:26.328Z"
152
+ "publishedAt": "2025-04-18T12:23:10.990Z"
153
153
  }
154
154
  }
@@ -159,6 +159,17 @@ export const tasks = {
159
159
  queueIntervalMS: intVar('PINEJS_QUEUE_INTERVAL_MS', 1000),
160
160
  };
161
161
 
162
+ export const webResource = {
163
+ multipartUploadEnabled: boolVar(
164
+ 'PINEJS_WEBRESOURCE_MULTIPART_ENABLED',
165
+ false,
166
+ ),
167
+ singleUploadMaxFilesize: intVar(
168
+ 'PINEJS_WEBRESOURCE_MAXFILESIZE',
169
+ 299 * 1024 * 1024,
170
+ ),
171
+ };
172
+
162
173
  export const guardTestMockOnly = () => {
163
174
  if (process.env.DEPLOYMENT !== 'TEST') {
164
175
  throw new Error('Attempting to use TEST_MOCK_ONLY outside of tests');
@@ -7,6 +7,7 @@ import * as configLoader from '../config-loader/config-loader.js';
7
7
  import * as migrator from '../migrator/sync.js';
8
8
  import type * as migratorUtils from '../migrator/utils.js';
9
9
  import * as tasks from '../tasks/index.js';
10
+ import * as webresource from '../webresource-handler/index.js';
10
11
 
11
12
  import * as sbvrUtils from '../sbvr-api/sbvr-utils.js';
12
13
  import { PINEJS_ADVISORY_LOCK } from '../config-loader/env.js';
@@ -66,6 +67,7 @@ export const init = async <T extends string>(
66
67
  const cfgLoader = configLoader.setup(app);
67
68
  await cfgLoader.loadConfig(migrator.config);
68
69
  await cfgLoader.loadConfig(tasks.config);
70
+ await cfgLoader.loadConfig(webresource.config);
69
71
 
70
72
  if (!process.env.CONFIG_LOADER_DISABLED) {
71
73
  await cfgLoader.loadApplicationConfig(config);
@@ -11,12 +11,20 @@ import {
11
11
  odataNameToSqlName,
12
12
  sqlNameToODataName,
13
13
  } from '@balena/odata-to-abstract-sql';
14
+ import type { ConfigLoader } from '../server-glue/module.js';
14
15
  import { errors, permissions } from '../server-glue/module.js';
15
16
  import type { WebResourceType as WebResource } from '@balena/sbvr-types';
16
17
  import { TypedError } from 'typed-error';
17
18
  import type { Resolvable } from '../sbvr-api/common-types.js';
19
+ import type WebresourceModel from './webresource.js';
20
+ import { importSBVR } from '../server-glue/sbvr-loader.js';
21
+ import {
22
+ isMultipartUploadAvailable,
23
+ multipartUploadHooks,
24
+ } from './multipartUpload.js';
18
25
 
19
26
  export * from './handlers/index.js';
27
+ export type { BeginUploadResponse } from './multipartUpload.js';
20
28
 
21
29
  export interface IncomingFile {
22
30
  fieldname: string;
@@ -31,10 +39,51 @@ export interface UploadResponse {
31
39
  filename: string;
32
40
  }
33
41
 
42
+ export interface BeginMultipartUploadPayload {
43
+ filename: string;
44
+ content_type: string;
45
+ size: number;
46
+ chunk_size: number;
47
+ }
48
+
49
+ export interface UploadPart {
50
+ url: string;
51
+ chunkSize: number;
52
+ partNumber: number;
53
+ }
54
+
55
+ export interface BeginMultipartUploadHandlerResponse {
56
+ uploadParts: UploadPart[];
57
+ fileKey: string;
58
+ uploadId: string;
59
+ }
60
+
61
+ export interface CommitMultipartUploadPayload {
62
+ fileKey: string;
63
+ uploadId: string;
64
+ filename: string;
65
+ providerCommitData?: Record<string, any>;
66
+ }
67
+
68
+ export interface CancelMultipartUploadPayload {
69
+ fileKey: string;
70
+ uploadId: string;
71
+ }
72
+
34
73
  export interface WebResourceHandler {
35
74
  handleFile: (resource: IncomingFile) => Promise<UploadResponse>;
36
75
  removeFile: (fileReference: string) => Promise<void>;
37
76
  onPreRespond: (webResource: WebResource) => Promise<WebResource>;
77
+ multipartUpload?: {
78
+ begin: (
79
+ fieldName: string,
80
+ payload: BeginMultipartUploadPayload,
81
+ ) => Promise<BeginMultipartUploadHandlerResponse>;
82
+ commit: (commitInfo: CommitMultipartUploadPayload) => Promise<WebResource>;
83
+ cancel: (cancelInfo: CancelMultipartUploadPayload) => Promise<void>;
84
+ getMinimumPartSize: () => number;
85
+ getDefaultPartSize: () => number;
86
+ };
38
87
  }
39
88
 
40
89
  export class WebResourceError extends TypedError {}
@@ -288,6 +337,9 @@ const throwIfWebresourceNotInMultipart = (
288
337
  { req, request }: HookArgs,
289
338
  ) => {
290
339
  if (
340
+ request.custom.isAction !== 'beginUpload' &&
341
+ request.custom.isAction !== 'commitUpload' &&
342
+ request.custom.isAction !== 'cancelUpload' &&
291
343
  !req.is?.('multipart') &&
292
344
  webResourceFields.some((field) => request.values[field] != null)
293
345
  ) {
@@ -484,4 +536,37 @@ export const setupUploadHooks = (
484
536
  resourceName,
485
537
  getCreateWebResourceHooks(handler),
486
538
  );
539
+
540
+ if (isMultipartUploadAvailable(handler)) {
541
+ sbvrUtils.addPureHook(
542
+ 'POST',
543
+ apiRoot,
544
+ resourceName,
545
+ multipartUploadHooks(handler),
546
+ );
547
+ }
548
+ };
549
+
550
+ const initSql = `
551
+ CREATE INDEX IF NOT EXISTS idx_multipart_upload_uuid ON "multipart upload" (uuid);
552
+ CREATE INDEX IF NOT EXISTS idx_multipart_upload_status ON "multipart upload" (status);
553
+ `;
554
+
555
+ const modelText = await importSBVR('./webresource.sbvr', import.meta);
556
+
557
+ declare module '../sbvr-api/sbvr-utils.js' {
558
+ export interface API {
559
+ webresource: PinejsClient<WebresourceModel>;
560
+ }
561
+ }
562
+
563
+ export const config: ConfigLoader.Config = {
564
+ models: [
565
+ {
566
+ modelName: 'webresource',
567
+ apiRoot: 'webresource',
568
+ modelText,
569
+ initSql,
570
+ },
571
+ ],
487
572
  };