@balena/pinejs 16.2.0-build-joshbwlng-tasks-a83c83b4c78803915d0cb6297cc8cc1862622d08-1 → 17.0.0-build-wip-large-file-uploads-0c8ef752deac19fa0d6a7dfa9f7173813cab7867-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 (60) hide show
  1. package/.pinejs-cache.json +1 -1
  2. package/.versionbot/CHANGELOG.yml +7 -7
  3. package/CHANGELOG.md +3 -3
  4. package/VERSION +1 -1
  5. package/out/config-loader/env.d.ts +0 -4
  6. package/out/config-loader/env.js +1 -5
  7. package/out/config-loader/env.js.map +1 -1
  8. package/out/database-layer/db.d.ts +0 -3
  9. package/out/database-layer/db.js +0 -14
  10. package/out/database-layer/db.js.map +1 -1
  11. package/out/migrator/utils.js +2 -2
  12. package/out/migrator/utils.js.map +1 -1
  13. package/out/sbvr-api/sbvr-utils.d.ts +0 -1
  14. package/out/sbvr-api/sbvr-utils.js +1 -6
  15. package/out/sbvr-api/sbvr-utils.js.map +1 -1
  16. package/out/server-glue/module.d.ts +0 -1
  17. package/out/server-glue/module.js +3 -2
  18. package/out/server-glue/module.js.map +1 -1
  19. package/out/webresource-handler/handlers/NoopHandler.d.ts +3 -0
  20. package/out/webresource-handler/handlers/NoopHandler.js +6 -0
  21. package/out/webresource-handler/handlers/NoopHandler.js.map +1 -1
  22. package/out/webresource-handler/handlers/S3Handler.d.ts +7 -0
  23. package/out/webresource-handler/handlers/S3Handler.js +68 -2
  24. package/out/webresource-handler/handlers/S3Handler.js.map +1 -1
  25. package/out/webresource-handler/index.d.ts +10 -1
  26. package/out/webresource-handler/index.js +25 -10
  27. package/out/webresource-handler/index.js.map +1 -1
  28. package/out/webresource-handler/multipartUpload.d.ts +39 -0
  29. package/out/webresource-handler/multipartUpload.js +187 -0
  30. package/out/webresource-handler/multipartUpload.js.map +1 -0
  31. package/out/webresource-handler/webresource.sbvr +62 -0
  32. package/package.json +4 -7
  33. package/src/config-loader/env.ts +1 -6
  34. package/src/database-layer/db.ts +0 -24
  35. package/src/migrator/utils.ts +1 -1
  36. package/src/sbvr-api/sbvr-utils.ts +1 -5
  37. package/src/server-glue/module.ts +2 -1
  38. package/src/webresource-handler/handlers/NoopHandler.ts +21 -0
  39. package/src/webresource-handler/handlers/S3Handler.ts +130 -4
  40. package/src/webresource-handler/index.ts +46 -11
  41. package/src/webresource-handler/multipartUpload.ts +286 -0
  42. package/src/webresource-handler/webresource.sbvr +62 -0
  43. package/out/tasks/common.d.ts +0 -4
  44. package/out/tasks/common.js +0 -13
  45. package/out/tasks/common.js.map +0 -1
  46. package/out/tasks/index.d.ts +0 -10
  47. package/out/tasks/index.js +0 -139
  48. package/out/tasks/index.js.map +0 -1
  49. package/out/tasks/model.sbvr +0 -60
  50. package/out/tasks/types.d.ts +0 -38
  51. package/out/tasks/types.js +0 -10
  52. package/out/tasks/types.js.map +0 -1
  53. package/out/tasks/worker.d.ts +0 -16
  54. package/out/tasks/worker.js +0 -191
  55. package/out/tasks/worker.js.map +0 -1
  56. package/src/tasks/common.ts +0 -14
  57. package/src/tasks/index.ts +0 -158
  58. package/src/tasks/model.sbvr +0 -60
  59. package/src/tasks/types.ts +0 -58
  60. package/src/tasks/worker.ts +0 -246
@@ -0,0 +1,62 @@
1
+ Vocabulary: Auth
2
+
3
+ Term: actor
4
+ Term: expiry date
5
+ Concept Type: Date Time (Type)
6
+
7
+ Vocabulary: webresource
8
+
9
+ Term: uuid
10
+ Concept Type: Short Text (Type)
11
+ Term: resource name
12
+ Concept Type: Short Text (Type)
13
+ Term: field name
14
+ Concept Type: Short Text (Type)
15
+ Term: resource id
16
+ Concept Type: Integer (Type)
17
+ Term: upload id
18
+ Concept Type: Short Text (Type)
19
+ Term: file key
20
+ Concept Type: Short Text (Type)
21
+ Term: status
22
+ Concept Type: Short Text (Type)
23
+ Term: filename
24
+ Concept Type: Short Text (Type)
25
+ Term: content type
26
+ Concept Type: Short Text (Type)
27
+ Term: size
28
+ Concept Type: Integer (Type)
29
+ Term: chunk size
30
+ Concept Type: Integer (Type)
31
+ Term: valid until date
32
+ Concept Type: Date Time (Type)
33
+
34
+ Term: multipart upload
35
+ Fact type: multipart upload has uuid
36
+ Necessity: each multipart upload has exactly one uuid
37
+ Necessity: each uuid is of exactly one multipart upload
38
+ Fact type: multipart upload has resource name
39
+ Necessity: each multipart upload has exactly one resource name
40
+ Fact type: multipart upload has field name
41
+ Necessity: each multipart upload has exactly one field name
42
+ Fact type: multipart upload has resource id
43
+ Necessity: each multipart upload has exactly one resource id
44
+ Fact type: multipart upload has upload id
45
+ Necessity: each multipart upload has exactly one upload id
46
+ Fact type: multipart upload has file key
47
+ Necessity: each multipart upload has exactly one file key
48
+ Fact type: multipart upload has status
49
+ Necessity: each multipart upload has exactly one status
50
+ Definition: "pending" or "completed" or "cancelled"
51
+ Fact type: multipart upload has filename
52
+ Necessity: each multipart upload has exactly one filename
53
+ Fact type: multipart upload has content type
54
+ Necessity: each multipart upload has exactly one content type
55
+ Fact type: multipart upload has size
56
+ Necessity: each multipart upload has exactly one size
57
+ Fact type: multipart upload has chunk size
58
+ Necessity: each multipart upload has exactly one chunk size
59
+ Fact type: multipart upload has expiry date (Auth)
60
+ Necessity: each multipart upload has exactly one expiry date (Auth)
61
+ Fact type: multipart upload is created by actor (Auth)
62
+ Necessity: each multipart upload is created by at most one actor (Auth)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@balena/pinejs",
3
- "version": "16.2.0-build-joshbwlng-tasks-a83c83b4c78803915d0cb6297cc8cc1862622d08-1",
3
+ "version": "17.0.0-build-wip-large-file-uploads-0c8ef752deac19fa0d6a7dfa9f7173813cab7867-1",
4
4
  "main": "out/server-glue/module",
5
5
  "type": "commonjs",
6
6
  "repository": "git@github.com:balena-io/pinejs.git",
@@ -20,7 +20,7 @@
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 build typings Gruntfile.ts && npx tsc --project tsconfig.dev.json --noEmit",
22
22
  "test": "npm run lint && npm run build && npm run webpack-build && npm run test:compose",
23
- "test:compose": "trap 'docker compose -f docker-compose.npm-test.yml down ; echo Stopped ; exit 0' SIGINT; 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 npm run mocha",
23
+ "test:compose": "trap 'docker compose -f docker-compose.npm-test.yml down ; echo Stopped ; exit 0' SIGINT; 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 npm run mocha",
24
24
  "mocha": "TS_NODE_FILES=true mocha",
25
25
  "prettify": "balena-lint -t tsconfig.dev.json -e js -e ts --fix src test build typings Gruntfile.ts"
26
26
  },
@@ -51,10 +51,8 @@
51
51
  "@types/pg": "^8.10.9",
52
52
  "@types/randomstring": "^1.1.11",
53
53
  "@types/websql": "^0.0.30",
54
- "ajv": "^8.12.0",
55
54
  "busboy": "^1.6.0",
56
55
  "commander": "^11.1.0",
57
- "cron-parser": "^4.9.0",
58
56
  "deep-freeze": "^0.0.1",
59
57
  "eventemitter3": "^5.0.1",
60
58
  "express-session": "^1.17.3",
@@ -91,7 +89,6 @@
91
89
  "grunt-ts": "^6.0.0-beta.22",
92
90
  "grunt-webpack": "^6.0.0",
93
91
  "husky": "^9.0.0",
94
- "json-schema-to-ts": "^3.0.1",
95
92
  "lint-staged": "^15.2.0",
96
93
  "load-grunt-tasks": "^5.1.0",
97
94
  "mocha": "^10.2.0",
@@ -126,7 +123,7 @@
126
123
  "serve-static": "^1.15.0"
127
124
  },
128
125
  "engines": {
129
- "node": ">=16.13.0",
126
+ "node": ">=18.0.0",
130
127
  "npm": ">=8.0.0"
131
128
  },
132
129
  "lint-staged": {
@@ -147,6 +144,6 @@
147
144
  "recursive": true
148
145
  },
149
146
  "versionist": {
150
- "publishedAt": "2024-04-15T01:28:03.598Z"
147
+ "publishedAt": "2024-04-18T17:52:52.724Z"
151
148
  }
152
149
  }
@@ -49,7 +49,7 @@ export const cache = {
49
49
  apiKeyActorId: false as CacheOpts,
50
50
  };
51
51
 
52
- import { boolVar, intVar } from '@balena/env-parsing';
52
+ import { boolVar } from '@balena/env-parsing';
53
53
  import memoize from 'memoizee';
54
54
  import memoizeWeak = require('memoizee/weak');
55
55
  export const createCache = <T extends (...args: any[]) => any>(
@@ -146,8 +146,3 @@ export const migrator = {
146
146
  */
147
147
  asyncMigrationIsEnabled: boolVar('PINEJS_ASYNC_MIGRATION_ENABLED', true),
148
148
  };
149
-
150
- export const tasks = {
151
- queueConcurrency: intVar('PINEJS_QUEUE_CONCURRENCY', 0),
152
- queueIntervalMS: intVar('PINEJS_QUEUE_INTERVAL_MS', 1000),
153
- };
@@ -98,13 +98,6 @@ export interface Database extends BaseDatabase {
98
98
  ) => Promise<Result>;
99
99
  transaction: TransactionFn;
100
100
  readTransaction: TransactionFn;
101
- on?: (
102
- name: 'notification',
103
- fn: (...args: any[]) => Promise<void>,
104
- options?: {
105
- channel?: string;
106
- },
107
- ) => void;
108
101
  }
109
102
 
110
103
  interface EngineParams {
@@ -696,23 +689,6 @@ if (maybePg != null) {
696
689
  return {
697
690
  engine: Engines.postgres,
698
691
  executeSql: atomicExecuteSql,
699
- on: async (name, fn, options) => {
700
- if (name === 'notification' && options?.channel === undefined) {
701
- throw new Error('Missing channel option for notification listener');
702
- }
703
-
704
- const client = await pool.connect();
705
- client.on(name, (msg) => {
706
- fn(msg).catch((error) => {
707
- console.error('Error handling message:', error);
708
- });
709
- });
710
-
711
- if (name === 'notification' && options?.channel !== undefined) {
712
- await client.query(`LISTEN "${options.channel}";`);
713
- // client.release();
714
- }
715
- },
716
692
  transaction: createTransaction(async (stackTraceErr) => {
717
693
  const client = await pool.connect();
718
694
  const tx = new PostgresTx(client, false, stackTraceErr);
@@ -1,7 +1,7 @@
1
1
  import type { Result, Tx } from '../database-layer/db';
2
2
  import type { Resolvable } from '../sbvr-api/common-types';
3
3
 
4
- import { createHash } from 'crypto';
4
+ import { createHash } from 'node:crypto';
5
5
  import { Engines } from '@balena/abstract-sql-compiler';
6
6
  import _ from 'lodash';
7
7
  import { TypedError } from 'typed-error';
@@ -42,7 +42,6 @@ import { generateODataMetadata } from '../odata-metadata/odata-metadata-generato
42
42
 
43
43
  // eslint-disable-next-line @typescript-eslint/no-var-requires
44
44
  const devModel = require('./dev.sbvr');
45
- import * as tasks from '../tasks';
46
45
  import * as permissions from './permissions';
47
46
  import {
48
47
  BadRequestError,
@@ -78,7 +77,6 @@ export {
78
77
  addPureHook,
79
78
  addSideEffectHook,
80
79
  } from './hooks';
81
- export { addTaskHandler } from '../tasks';
82
80
 
83
81
  import memoizeWeak = require('memoizee/weak');
84
82
  import * as controlFlow from './control-flow';
@@ -775,7 +773,7 @@ export const postExecuteModels = async (tx: Db.Tx): Promise<void> => {
775
773
  // Hence, skipped migrations from earlier models are not set as executed as the `migration` table is missing
776
774
  // Here the skipped migrations that haven't been set properly are covered
777
775
  // This is mostly an edge case when running on an empty database schema and migrations model hasn't been executed, yet.
778
- // One specific case are tests to run tests against migrated and unmigrated database states
776
+ // One specifc case are tests to run tests against migrated and unmigrated database states
779
777
 
780
778
  for (const modelKey of Object.keys(models)) {
781
779
  const pendingToSetExecutedMigrations =
@@ -1985,7 +1983,6 @@ export const executeStandardModels = async (tx: Db.Tx): Promise<void> => {
1985
1983
  },
1986
1984
  });
1987
1985
  await executeModels(tx, permissions.config.models);
1988
- await executeModels(tx, tasks.config.models);
1989
1986
  console.info('Successfully executed standard models.');
1990
1987
  } catch (err: any) {
1991
1988
  console.error('Failed to execute standard models.', err);
@@ -2002,7 +1999,6 @@ export const setup = async (
2002
1999
  await db.transaction(async (tx) => {
2003
2000
  await executeStandardModels(tx);
2004
2001
  await permissions.setup();
2005
- await tasks.setup($db, tx);
2006
2002
  });
2007
2003
  } catch (err: any) {
2008
2004
  console.error('Could not execute standard models', err);
@@ -5,6 +5,7 @@ import './sbvr-loader';
5
5
  import * as dbModule from '../database-layer/db';
6
6
  import * as configLoader from '../config-loader/config-loader';
7
7
  import * as migrator from '../migrator/sync';
8
+ import * as webResourceHandler from '../webresource-handler';
8
9
  import type * as migratorUtils from '../migrator/utils';
9
10
 
10
11
  import * as sbvrUtils from '../sbvr-api/sbvr-utils';
@@ -19,7 +20,6 @@ export * as errors from '../sbvr-api/errors';
19
20
  export * as env from '../config-loader/env';
20
21
  export * as types from '../sbvr-api/common-types';
21
22
  export * as hooks from '../sbvr-api/hooks';
22
- export * as tasks from '../tasks';
23
23
  export * as webResourceHandler from '../webresource-handler';
24
24
  export type { configLoader as ConfigLoader };
25
25
  export type { migratorUtils as Migrator };
@@ -64,6 +64,7 @@ export const init = async <T extends string>(
64
64
  await sbvrUtils.setup(app, db);
65
65
  const cfgLoader = await configLoader.setup(app);
66
66
  await cfgLoader.loadConfig(migrator.config);
67
+ await cfgLoader.loadConfig(webResourceHandler.config);
67
68
 
68
69
  const promises: Array<Promise<void>> = [];
69
70
  if (process.env.SBVR_SERVER_ENABLED) {
@@ -1,5 +1,10 @@
1
1
  import type { WebResourceType as WebResource } from '@balena/sbvr-types';
2
2
  import type { IncomingFile, UploadResponse, WebResourceHandler } from '..';
3
+ import type {
4
+ BeginUploadHandlerResponse,
5
+ BeginUploadPayload,
6
+ CommitUploadHandlerPayload,
7
+ } from '../multipartUpload';
3
8
 
4
9
  export class NoopHandler implements WebResourceHandler {
5
10
  public async handleFile(resource: IncomingFile): Promise<UploadResponse> {
@@ -18,4 +23,20 @@ export class NoopHandler implements WebResourceHandler {
18
23
  public async onPreRespond(webResource: WebResource): Promise<WebResource> {
19
24
  return webResource;
20
25
  }
26
+
27
+ public async beginUpload(
28
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
29
+ _fieldName: string,
30
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
31
+ _payload: BeginUploadPayload,
32
+ ): Promise<BeginUploadHandlerResponse> {
33
+ return { fileKey: 'noop', uploadId: 'noop', uploadUrls: [] };
34
+ }
35
+
36
+ public async commitUpload(
37
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
38
+ _payload: CommitUploadHandlerPayload,
39
+ ): Promise<WebResource> {
40
+ return { filename: 'noop', href: 'noop' };
41
+ }
21
42
  }
@@ -6,17 +6,27 @@ import {
6
6
  WebResourceError,
7
7
  type WebResourceHandler,
8
8
  } from '..';
9
+ import type {
10
+ BeginUploadHandlerResponse,
11
+ BeginUploadPayload,
12
+ CommitUploadHandlerPayload,
13
+ UploadUrl,
14
+ } from '../multipartUpload';
9
15
  import {
10
16
  S3Client,
11
17
  type S3ClientConfig,
12
18
  DeleteObjectCommand,
13
19
  type PutObjectCommandInput,
14
20
  GetObjectCommand,
21
+ CreateMultipartUploadCommand,
22
+ UploadPartCommand,
23
+ CompleteMultipartUploadCommand,
24
+ HeadObjectCommand,
15
25
  } from '@aws-sdk/client-s3';
16
26
  import { Upload } from '@aws-sdk/lib-storage';
17
27
  import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
18
28
 
19
- import { randomUUID } from 'crypto';
29
+ import { randomUUID } from 'node:crypto';
20
30
  import type { WebResourceType as WebResource } from '@balena/sbvr-types';
21
31
  import memoize from 'memoizee';
22
32
 
@@ -71,9 +81,7 @@ export class S3Handler implements WebResourceHandler {
71
81
 
72
82
  public async handleFile(resource: IncomingFile): Promise<UploadResponse> {
73
83
  let size = 0;
74
- const key = `${resource.fieldname}_${randomUUID()}_${
75
- resource.originalname
76
- }`;
84
+ const key = this.getFileKey(resource.fieldname, resource.originalname);
77
85
  const params: PutObjectCommandInput = {
78
86
  Bucket: this.bucket,
79
87
  Key: key,
@@ -122,6 +130,62 @@ export class S3Handler implements WebResourceHandler {
122
130
  return webResource;
123
131
  }
124
132
 
133
+ public async beginUpload(
134
+ fieldName: string,
135
+ payload: BeginUploadPayload,
136
+ ): Promise<BeginUploadHandlerResponse> {
137
+ const fileKey = this.getFileKey(fieldName, payload.filename);
138
+
139
+ const createMultiPartResponse = await this.client.send(
140
+ new CreateMultipartUploadCommand({
141
+ Bucket: this.bucket,
142
+ Key: fileKey,
143
+ ContentType: payload.content_type,
144
+ }),
145
+ );
146
+
147
+ if (createMultiPartResponse.UploadId == null) {
148
+ throw new WebResourceError('Failed to create multipart upload.');
149
+ }
150
+
151
+ const uploadUrls = await this.getPartUploadUrls(
152
+ fileKey,
153
+ createMultiPartResponse.UploadId,
154
+ payload,
155
+ );
156
+ return { fileKey, uploadId: createMultiPartResponse.UploadId, uploadUrls };
157
+ }
158
+
159
+ public async commitUpload({
160
+ fileKey,
161
+ uploadId,
162
+ filename,
163
+ multipartUploadChecksums,
164
+ }: CommitUploadHandlerPayload): Promise<WebResource> {
165
+ await this.client.send(
166
+ new CompleteMultipartUploadCommand({
167
+ Bucket: this.bucket,
168
+ Key: fileKey,
169
+ UploadId: uploadId,
170
+ MultipartUpload: multipartUploadChecksums,
171
+ }),
172
+ );
173
+
174
+ const headResult = await this.client.send(
175
+ new HeadObjectCommand({
176
+ Bucket: this.bucket,
177
+ Key: fileKey,
178
+ }),
179
+ );
180
+
181
+ return {
182
+ href: this.getS3URL(fileKey),
183
+ filename: filename,
184
+ size: headResult.ContentLength,
185
+ content_type: headResult.ContentType,
186
+ };
187
+ }
188
+
125
189
  private s3SignUrl(fileKey: string): Promise<string> {
126
190
  const command = new GetObjectCommand({
127
191
  Bucket: this.bucket,
@@ -136,8 +200,70 @@ export class S3Handler implements WebResourceHandler {
136
200
  return `${this.config.endpoint}/${this.bucket}/${key}`;
137
201
  }
138
202
 
203
+ private getFileKey(fieldName: string, fileName: string) {
204
+ return `${fieldName}_${randomUUID()}_${fileName}`;
205
+ }
206
+
139
207
  private getKeyFromHref(href: string): string {
140
208
  const hrefWithoutParams = normalizeHref(href);
141
209
  return hrefWithoutParams.substring(hrefWithoutParams.lastIndexOf('/') + 1);
142
210
  }
211
+
212
+ private async getPartUploadUrls(
213
+ fileKey: string,
214
+ uploadId: string,
215
+ payload: BeginUploadPayload,
216
+ ): Promise<UploadUrl[]> {
217
+ const chunkSizesWithParts = await this.getChunkSizesWithParts(
218
+ payload.size,
219
+ payload.chunk_size,
220
+ );
221
+ return Promise.all(
222
+ chunkSizesWithParts.map(async ({ chunkSize, partNumber }) => ({
223
+ chunkSize,
224
+ partNumber,
225
+ url: await this.getPartUploadUrl(
226
+ fileKey,
227
+ uploadId,
228
+ partNumber,
229
+ chunkSize,
230
+ ),
231
+ })),
232
+ );
233
+ }
234
+
235
+ private async getPartUploadUrl(
236
+ fileKey: string,
237
+ uploadId: string,
238
+ partNumber: number,
239
+ partSize: number,
240
+ ): Promise<string> {
241
+ const command = new UploadPartCommand({
242
+ Bucket: this.bucket,
243
+ Key: fileKey,
244
+ UploadId: uploadId,
245
+ PartNumber: partNumber,
246
+ ContentLength: partSize,
247
+ });
248
+
249
+ return getSignedUrl(this.client, command, {
250
+ expiresIn: this.signedUrlExpireTimeSeconds,
251
+ });
252
+ }
253
+
254
+ private async getChunkSizesWithParts(
255
+ size: number,
256
+ chunkSize: number,
257
+ ): Promise<Array<Pick<UploadUrl, 'chunkSize' | 'partNumber'>>> {
258
+ const chunkSizesWithParts = [];
259
+ let partNumber = 1;
260
+ let remainingSize = size;
261
+ while (remainingSize > 0) {
262
+ const currentChunkSize = Math.min(remainingSize, chunkSize);
263
+ chunkSizesWithParts.push({ chunkSize: currentChunkSize, partNumber });
264
+ remainingSize -= currentChunkSize;
265
+ partNumber += 1;
266
+ }
267
+ return chunkSizesWithParts;
268
+ }
143
269
  }
@@ -1,19 +1,25 @@
1
- import type * as Express from 'express';
2
- import busboy from 'busboy';
3
- import type * as stream from 'node:stream';
4
- import * as uriParser from '../sbvr-api/uri-parser';
5
- import * as sbvrUtils from '../sbvr-api/sbvr-utils';
6
- import type { HookArgs } from '../sbvr-api/hooks';
7
- import { getApiRoot, getModel } from '../sbvr-api/sbvr-utils';
8
- import { checkPermissions } from '../sbvr-api/permissions';
9
- import { NoopHandler } from './handlers/NoopHandler';
10
1
  import {
11
2
  odataNameToSqlName,
12
3
  sqlNameToODataName,
13
4
  } from '@balena/odata-to-abstract-sql';
14
- import { errors, permissions } from '../server-glue/module';
15
5
  import type { WebResourceType as WebResource } from '@balena/sbvr-types';
6
+ import busboy from 'busboy';
7
+ import type * as Express from 'express';
8
+ import type * as stream from 'node:stream';
16
9
  import { TypedError } from 'typed-error';
10
+ import type { HookArgs } from '../sbvr-api/hooks';
11
+ import { checkPermissions } from '../sbvr-api/permissions';
12
+ import * as sbvrUtils from '../sbvr-api/sbvr-utils';
13
+ import { getApiRoot, getModel } from '../sbvr-api/sbvr-utils';
14
+ import * as uriParser from '../sbvr-api/uri-parser';
15
+ import { errors, permissions } from '../server-glue/module';
16
+ import { NoopHandler } from './handlers/NoopHandler';
17
+ import type {
18
+ BeginUploadHandlerResponse,
19
+ BeginUploadPayload,
20
+ CommitUploadHandlerPayload,
21
+ } from './multipartUpload';
22
+ import { multipartUploadHooks } from './multipartUpload';
17
23
 
18
24
  export * from './handlers';
19
25
 
@@ -34,6 +40,14 @@ export interface WebResourceHandler {
34
40
  handleFile: (resource: IncomingFile) => Promise<UploadResponse>;
35
41
  removeFile: (fileReference: string) => Promise<void>;
36
42
  onPreRespond: (webResource: WebResource) => Promise<WebResource>;
43
+
44
+ beginUpload: (
45
+ fieldName: string,
46
+ payload: BeginUploadPayload,
47
+ ) => Promise<BeginUploadHandlerResponse>;
48
+ commitUpload: (
49
+ commitInfo: CommitUploadHandlerPayload,
50
+ ) => Promise<WebResource>;
37
51
  }
38
52
 
39
53
  export class WebResourceError extends TypedError {}
@@ -216,7 +230,7 @@ export const getUploaderMiddlware = (
216
230
  };
217
231
  };
218
232
 
219
- const getWebResourceFields = (
233
+ export const getWebResourceFields = (
220
234
  request: uriParser.ODataRequest,
221
235
  useTranslations = true,
222
236
  ): string[] => {
@@ -249,6 +263,8 @@ const throwIfWebresourceNotInMultipart = (
249
263
  { req, request }: HookArgs,
250
264
  ) => {
251
265
  if (
266
+ request.custom.isAction !== 'beginUpload' &&
267
+ request.custom.isAction !== 'commitUpload' &&
252
268
  !req.is?.('multipart') &&
253
269
  webResourceFields.some((field) => request.values[field] != null)
254
270
  ) {
@@ -447,4 +463,23 @@ export const setupUploadHooks = (
447
463
  resourceName,
448
464
  getCreateWebResourceHooks(handler),
449
465
  );
466
+
467
+ sbvrUtils.addPureHook(
468
+ 'POST',
469
+ apiRoot,
470
+ resourceName,
471
+ multipartUploadHooks(handler),
472
+ );
473
+ };
474
+
475
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
476
+ const webresourceModel: string = require('./webresource.sbvr');
477
+ export const config = {
478
+ models: [
479
+ {
480
+ apiRoot: 'webresource',
481
+ modelText: webresourceModel,
482
+ modelName: 'webresource',
483
+ },
484
+ ] as sbvrUtils.ExecutableModel[],
450
485
  };