@venizia/ignis 0.4.8-11 → 0.4.8-13
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.
- package/dist/esm/components/mail/common/types/queue.d.ts +8 -4
- package/dist/esm/components/mail/common/types/queue.js.map +1 -1
- package/dist/esm/components/mail/helpers/executors/bull-mq-executor.helper.d.ts +1 -1
- package/dist/esm/components/mail/helpers/executors/bull-mq-executor.helper.js +2 -16
- package/dist/esm/components/mail/helpers/executors/bull-mq-executor.helper.js.map +1 -1
- package/dist/esm/components/static-asset/common/constants.d.ts +25 -11
- package/dist/esm/components/static-asset/common/constants.js +40 -20
- package/dist/esm/components/static-asset/common/constants.js.map +1 -1
- package/dist/esm/components/static-asset/common/errors.d.ts +16 -39
- package/dist/esm/components/static-asset/common/errors.js +16 -36
- package/dist/esm/components/static-asset/common/errors.js.map +1 -1
- package/dist/esm/components/static-asset/common/index.d.ts +1 -0
- package/dist/esm/components/static-asset/common/index.js +1 -0
- package/dist/esm/components/static-asset/common/index.js.map +1 -1
- package/dist/esm/components/static-asset/common/keys.d.ts +1 -1
- package/dist/esm/components/static-asset/common/keys.js +1 -1
- package/dist/esm/components/static-asset/common/keys.js.map +1 -1
- package/dist/esm/components/static-asset/common/types.d.ts +203 -140
- package/dist/esm/components/static-asset/common/types.js.map +1 -1
- package/dist/esm/components/static-asset/common/validation.d.ts +10 -0
- package/dist/esm/components/static-asset/common/validation.js +8 -0
- package/dist/esm/components/static-asset/common/validation.js.map +1 -0
- package/dist/esm/components/static-asset/component.d.ts +1 -1
- package/dist/esm/components/static-asset/component.js +13 -55
- package/dist/esm/components/static-asset/component.js.map +1 -1
- package/dist/esm/components/static-asset/controller/factory.d.ts +185 -67
- package/dist/esm/components/static-asset/controller/factory.js +32 -821
- package/dist/esm/components/static-asset/controller/factory.js.map +1 -1
- package/dist/esm/components/static-asset/controller/routes/context.d.ts +61 -0
- package/dist/esm/components/static-asset/controller/routes/context.js +45 -0
- package/dist/esm/components/static-asset/controller/routes/context.js.map +1 -0
- package/dist/esm/components/static-asset/controller/routes/definition.d.ts +40 -0
- package/dist/esm/components/static-asset/controller/routes/definition.js +74 -0
- package/dist/esm/components/static-asset/controller/routes/definition.js.map +1 -0
- package/dist/esm/components/static-asset/controller/routes/direct-upload.d.ts +3 -0
- package/dist/esm/components/static-asset/controller/routes/direct-upload.js +131 -0
- package/dist/esm/components/static-asset/controller/routes/direct-upload.js.map +1 -0
- package/dist/esm/components/static-asset/controller/routes/labels.d.ts +16 -0
- package/dist/esm/components/static-asset/controller/routes/labels.js +19 -0
- package/dist/esm/components/static-asset/controller/routes/labels.js.map +1 -0
- package/dist/esm/components/static-asset/controller/routes/objects.d.ts +7 -0
- package/dist/esm/components/static-asset/controller/routes/objects.js +193 -0
- package/dist/esm/components/static-asset/controller/routes/objects.js.map +1 -0
- package/dist/esm/components/static-asset/controller/routes/serve.d.ts +17 -0
- package/dist/esm/components/static-asset/controller/routes/serve.js +127 -0
- package/dist/esm/components/static-asset/controller/routes/serve.js.map +1 -0
- package/dist/esm/components/static-asset/controller/routes/table.d.ts +12 -0
- package/dist/esm/components/static-asset/controller/routes/table.js +52 -0
- package/dist/esm/components/static-asset/controller/routes/table.js.map +1 -0
- package/dist/esm/components/static-asset/controller/routes/upload.d.ts +10 -0
- package/dist/esm/components/static-asset/controller/routes/upload.js +174 -0
- package/dist/esm/components/static-asset/controller/routes/upload.js.map +1 -0
- package/dist/esm/components/static-asset/models/base.model.d.ts +4 -4
- package/dist/esm/components/static-asset/models/base.model.js.map +1 -1
- package/dist/esm/components/static-asset/services/commitment.service.d.ts +53 -16
- package/dist/esm/components/static-asset/services/commitment.service.js +114 -35
- package/dist/esm/components/static-asset/services/commitment.service.js.map +1 -1
- package/dist/esm/components/static-asset/services/policy.service.d.ts +7 -3
- package/dist/esm/components/static-asset/services/policy.service.js +29 -7
- package/dist/esm/components/static-asset/services/policy.service.js.map +1 -1
- package/dist/esm/components/static-asset/utilities/commit-token.utility.d.ts +5 -1
- package/dist/esm/components/static-asset/utilities/commit-token.utility.js +58 -2
- package/dist/esm/components/static-asset/utilities/commit-token.utility.js.map +1 -1
- package/dist/esm/components/static-asset/utilities/entry.utility.d.ts +69 -0
- package/dist/esm/components/static-asset/utilities/entry.utility.js +153 -0
- package/dist/esm/components/static-asset/utilities/entry.utility.js.map +1 -0
- package/dist/esm/components/static-asset/utilities/index.d.ts +3 -0
- package/dist/esm/components/static-asset/utilities/index.js +3 -0
- package/dist/esm/components/static-asset/utilities/index.js.map +1 -1
- package/dist/esm/components/static-asset/utilities/ingest.utility.js +2 -4
- package/dist/esm/components/static-asset/utilities/ingest.utility.js.map +1 -1
- package/dist/esm/components/static-asset/utilities/key-scope.utility.d.ts +6 -2
- package/dist/esm/components/static-asset/utilities/key-scope.utility.js +24 -6
- package/dist/esm/components/static-asset/utilities/key-scope.utility.js.map +1 -1
- package/dist/esm/components/static-asset/utilities/meta-link.utility.d.ts +2 -2
- package/dist/esm/components/static-asset/utilities/meta-link.utility.js +6 -6
- package/dist/esm/components/static-asset/utilities/meta-link.utility.js.map +1 -1
- package/dist/esm/components/static-asset/utilities/object-link.utility.d.ts +2 -2
- package/dist/esm/components/static-asset/utilities/object-link.utility.js +4 -5
- package/dist/esm/components/static-asset/utilities/object-link.utility.js.map +1 -1
- package/dist/esm/components/static-asset/utilities/pinned-file.utility.d.ts +39 -0
- package/dist/esm/components/static-asset/utilities/pinned-file.utility.js +53 -0
- package/dist/esm/components/static-asset/utilities/pinned-file.utility.js.map +1 -0
- package/dist/esm/components/static-asset/utilities/route-options.utility.d.ts +20 -5
- package/dist/esm/components/static-asset/utilities/route-options.utility.js +44 -6
- package/dist/esm/components/static-asset/utilities/route-options.utility.js.map +1 -1
- package/dist/esm/components/static-asset/utilities/toggle.utility.d.ts +13 -0
- package/dist/esm/components/static-asset/utilities/toggle.utility.js +16 -0
- package/dist/esm/components/static-asset/utilities/toggle.utility.js.map +1 -0
- package/dist/presets/app/preset.json +4 -4
- package/dist/presets/lib/preset.json +3 -3
- package/dist/presets/shared/preset.json +1 -1
- package/package.json +6 -6
- package/dist/esm/components/static-asset/controller/base.definition.d.ts +0 -30
- package/dist/esm/components/static-asset/controller/base.definition.js +0 -307
- package/dist/esm/components/static-asset/controller/base.definition.js.map +0 -1
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { z } from '@hono/zod-openapi';
|
|
2
|
+
import { BaseStorageHelper, RequestUtility, } from '@venizia/ignis-helpers';
|
|
3
|
+
import { HTTP } from '@venizia/ignis-helpers/common';
|
|
4
|
+
import { getError } from '@venizia/ignis-helpers/core';
|
|
5
|
+
import { StaticAssetErrors, StaticAssetMetaLinkCodes, StaticAssetRouteKeys, } from '../../common/index.js';
|
|
6
|
+
import { StaticAssetKeyScopeUtility } from '../../utilities/key-scope.utility.js';
|
|
7
|
+
import { StaticAssetMetaLinkUtility } from '../../utilities/meta-link.utility.js';
|
|
8
|
+
import { StaticAssetRouteOptionsUtility } from '../../utilities/route-options.utility.js';
|
|
9
|
+
import { StaticAssetFeatures, StaticAssetRouteUtility, } from './context.js';
|
|
10
|
+
import { StaticAssetDefinition } from './definition.js';
|
|
11
|
+
import { StaticAssetLabelsUtility, UploadLabelsSchema } from './labels.js';
|
|
12
|
+
import { MetaLinkRowSchema } from './objects.js';
|
|
13
|
+
const MultipartBodySchema = z.object({
|
|
14
|
+
files: z.union([z.instanceof(File), z.array(z.instanceof(File))]).openapi({
|
|
15
|
+
type: 'array',
|
|
16
|
+
items: { type: 'string', format: 'binary' },
|
|
17
|
+
}),
|
|
18
|
+
...UploadLabelsSchema.shape,
|
|
19
|
+
folderPath: z.string().optional().openapi({
|
|
20
|
+
description: 'Target folder path for uploaded files (e.g., "photos/2024")',
|
|
21
|
+
example: 'photos/2024',
|
|
22
|
+
}),
|
|
23
|
+
});
|
|
24
|
+
/** What an upload or a commit says about the MetaLink row: the row, or a code when only the row failed. */
|
|
25
|
+
export const MetaLinkOutcomeSchema = z
|
|
26
|
+
.union([z.object({ data: MetaLinkRowSchema }), z.object({ error: z.string() })])
|
|
27
|
+
.optional();
|
|
28
|
+
class StaticAssetUploadHandler {
|
|
29
|
+
/**
|
|
30
|
+
* Built per request: the hook is offered the bucket, which only the route knows. A hook's key is
|
|
31
|
+
* checked against the scope, never rewritten: the application may record that key elsewhere.
|
|
32
|
+
*/
|
|
33
|
+
static buildNaming(opts) {
|
|
34
|
+
const { env, bucketName, objectKey } = opts;
|
|
35
|
+
const { helper, keyPrefix } = env;
|
|
36
|
+
if (!objectKey && keyPrefix === undefined) {
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
return (naming) => {
|
|
40
|
+
// The component's own name under a scope: the original name must stay one segment, as without one.
|
|
41
|
+
if (!objectKey && !helper.isValidSegment({ segment: naming.file.originalName })) {
|
|
42
|
+
throw getError({ message: '[upload] Invalid original file name' });
|
|
43
|
+
}
|
|
44
|
+
const defaultKey = `${keyPrefix ?? ''}${BaseStorageHelper.normalizeObjectName(naming)}`;
|
|
45
|
+
const key = objectKey
|
|
46
|
+
? objectKey({ bucket: { name: bucketName }, file: naming.file, defaultKey })
|
|
47
|
+
: defaultKey;
|
|
48
|
+
if (!StaticAssetKeyScopeUtility.isInScope({ key, keyPrefix })) {
|
|
49
|
+
throw getError({
|
|
50
|
+
error: StaticAssetErrors.OBJECT_KEY_OUT_OF_SCOPE,
|
|
51
|
+
message: `Object key is outside the key prefix of this entry | key: ${key} | keyPrefix: ${keyPrefix}`,
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
return key;
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
static async recordMetaLinks(opts) {
|
|
58
|
+
const { env, uploaded, labels } = opts;
|
|
59
|
+
const { helper, metaLink } = env;
|
|
60
|
+
if (!metaLink) {
|
|
61
|
+
return uploaded;
|
|
62
|
+
}
|
|
63
|
+
const results = [];
|
|
64
|
+
for (const uploadResult of uploaded) {
|
|
65
|
+
try {
|
|
66
|
+
const fileStat = await helper.getStat({
|
|
67
|
+
bucket: uploadResult.bucket,
|
|
68
|
+
object: uploadResult.object,
|
|
69
|
+
});
|
|
70
|
+
const data = await StaticAssetMetaLinkUtility.createRow({
|
|
71
|
+
metaLink,
|
|
72
|
+
helper,
|
|
73
|
+
storage: env.storage,
|
|
74
|
+
uploadResult,
|
|
75
|
+
fileStat,
|
|
76
|
+
labels,
|
|
77
|
+
});
|
|
78
|
+
results.push({ ...uploadResult, metaLink: { data } });
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
env.logger
|
|
82
|
+
.for('UPLOAD')
|
|
83
|
+
.error('Failed to create MetaLink | objectName: %s | Error: %s', uploadResult.object.key, error);
|
|
84
|
+
// A CODE, never the driver text: this 200 bypasses the error middleware that strips
|
|
85
|
+
// `detail`/`table`/`constraint`. The real error is logged in full above.
|
|
86
|
+
results.push({
|
|
87
|
+
...uploadResult,
|
|
88
|
+
metaLink: { error: StaticAssetMetaLinkCodes.CREATE_FAILED },
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return results;
|
|
93
|
+
}
|
|
94
|
+
static async handle(opts) {
|
|
95
|
+
const { ctx, env } = opts;
|
|
96
|
+
const serverUpload = StaticAssetRouteUtility.requireFeature({
|
|
97
|
+
value: env.serverUpload,
|
|
98
|
+
feature: StaticAssetFeatures.SERVER_UPLOAD,
|
|
99
|
+
});
|
|
100
|
+
const { bucket } = await StaticAssetRouteUtility.resolveTarget({ ctx, env });
|
|
101
|
+
const { files, fields } = await RequestUtility.parseMultipartBody({
|
|
102
|
+
context: ctx,
|
|
103
|
+
maxFiles: serverUpload.maxFiles,
|
|
104
|
+
});
|
|
105
|
+
const labels = StaticAssetLabelsUtility.parse({ fields });
|
|
106
|
+
const folderPath = fields.folderPath || undefined;
|
|
107
|
+
const uploadFiles = files.map((file) => {
|
|
108
|
+
const { buffer } = file;
|
|
109
|
+
if (!buffer?.length) {
|
|
110
|
+
throw getError({
|
|
111
|
+
error: StaticAssetErrors.FILE_EMPTY,
|
|
112
|
+
message: `Empty file content | name: ${file.originalname}`,
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
// Authoritative: `buffer.length`, not the client-declared `size`.
|
|
116
|
+
if (serverUpload.maxBytes !== undefined && buffer.length > serverUpload.maxBytes) {
|
|
117
|
+
throw getError({
|
|
118
|
+
error: StaticAssetErrors.UPLOAD_TOO_LARGE,
|
|
119
|
+
message: `File ${file.originalname} of ${buffer.length} bytes exceeds the maximum of ${serverUpload.maxBytes}`,
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
return {
|
|
123
|
+
originalName: file.originalname,
|
|
124
|
+
mimetype: file.mimetype,
|
|
125
|
+
buffer,
|
|
126
|
+
size: file.size,
|
|
127
|
+
encoding: file.encoding,
|
|
128
|
+
folderPath,
|
|
129
|
+
};
|
|
130
|
+
});
|
|
131
|
+
const uploaded = await env.helper.upload({
|
|
132
|
+
bucket,
|
|
133
|
+
files: uploadFiles,
|
|
134
|
+
normalizeNameFn: StaticAssetUploadHandler.buildNaming({
|
|
135
|
+
env,
|
|
136
|
+
bucketName: bucket.name,
|
|
137
|
+
objectKey: serverUpload.objectKey,
|
|
138
|
+
}),
|
|
139
|
+
normalizeLinkFn: env.link,
|
|
140
|
+
// The storage checks the caller's folders against `maxFolderDepth`, and the finished key, scope included, against the deeper bound.
|
|
141
|
+
maxFolderDepth: env.maxFolderDepth,
|
|
142
|
+
maxKeyDepth: env.objectKeyMaxDepth,
|
|
143
|
+
});
|
|
144
|
+
const results = await StaticAssetUploadHandler.recordMetaLinks({ env, uploaded, labels });
|
|
145
|
+
return ctx.json(results, HTTP.ResultCodes.RS_2.Ok);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
export const uploadRoute = {
|
|
149
|
+
key: StaticAssetRouteKeys.UPLOAD,
|
|
150
|
+
feature: StaticAssetFeatures.SERVER_UPLOAD,
|
|
151
|
+
build: (env) => ({
|
|
152
|
+
config: StaticAssetDefinition.multipart({
|
|
153
|
+
method: HTTP.Methods.POST,
|
|
154
|
+
path: '/objects',
|
|
155
|
+
body: MultipartBodySchema,
|
|
156
|
+
response: z.array(z.object({
|
|
157
|
+
bucket: z.object({ name: z.string() }),
|
|
158
|
+
object: z.object({ key: z.string(), size: z.number(), contentType: z.string() }),
|
|
159
|
+
link: z.string(),
|
|
160
|
+
metaLink: MetaLinkOutcomeSchema,
|
|
161
|
+
})),
|
|
162
|
+
}),
|
|
163
|
+
handler: (ctx) => StaticAssetUploadHandler.handle({ ctx, env }),
|
|
164
|
+
}),
|
|
165
|
+
// The route's body validator reads the whole multipart body, so the length check has to run before it.
|
|
166
|
+
middleware: ({ env, own }) => env.serverUpload?.maxBytes === undefined
|
|
167
|
+
? own
|
|
168
|
+
: StaticAssetRouteOptionsUtility.appendLengthGuard({
|
|
169
|
+
middleware: own,
|
|
170
|
+
maxBytes: env.serverUpload.maxBytes,
|
|
171
|
+
maxFiles: env.serverUpload.maxFiles,
|
|
172
|
+
}),
|
|
173
|
+
};
|
|
174
|
+
//# sourceMappingURL=upload.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"upload.js","sourceRoot":"","sources":["../../../../../../src/components/static-asset/controller/routes/upload.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,CAAC,EAAE,MAAM,mBAAmB,CAAC;AACtC,OAAO,EACL,iBAAiB,EACjB,cAAc,GAIf,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EACL,iBAAiB,EACjB,wBAAwB,EACxB,oBAAoB,GAGrB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,0BAA0B,EAAE,MAAM,mCAAmC,CAAC;AAC/E,OAAO,EAAE,0BAA0B,EAAE,MAAM,mCAAmC,CAAC;AAC/E,OAAO,EAAE,8BAA8B,EAAE,MAAM,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AC,MAAM,EAAE,EAAE,WAAW,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC;gBAChF,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE;gBAChB,QAAQ,EAAE,qBAAqB;aAChC,CAAC,CACH;SACF,CAAC;QACF,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,wBAAwB,CAAC,MAAM,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC;KAChE,CAAC;IACF,uGAAuG;IACvG,UAAU,EAAE,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,CAC3B,GAAG,CAAC,YAAY,EAAE,QAAQ,KAAK,SAAS;QACtC,CAAC,CAAC,GAAG;QACL,CAAC,CAAC,8BAA8B,CAAC,iBAAiB,CAAC;YAC/C,UAAU,EAAE,GAAG;YACf,QAAQ,EAAE,GAAG,CAAC,YAAY,CAAC,QAAQ;YACnC,QAAQ,EAAE,GAAG,CAAC,YAAY,CAAC,QAAQ;SACpC,CAAC;CACT,CAAC","sourcesContent":["import type { TRouteContext } from '@/base/controllers';\nimport { z } from '@hono/zod-openapi';\nimport {\n BaseStorageHelper,\n RequestUtility,\n type IUploadFile,\n type IUploadResult,\n type TUploadNaming,\n} from '@venizia/ignis-helpers';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport {\n StaticAssetErrors,\n StaticAssetMetaLinkCodes,\n StaticAssetRouteKeys,\n type TStaticAssetObjectKeyResolver,\n type TStaticAssetUploadLabels,\n} from '../../common';\nimport { StaticAssetKeyScopeUtility } from '../../utilities/key-scope.utility';\nimport { StaticAssetMetaLinkUtility } from '../../utilities/meta-link.utility';\nimport { StaticAssetRouteOptionsUtility } from '../../utilities/route-options.utility';\nimport {\n type IStaticAssetRoute,\n type IStaticAssetRouteEnv,\n StaticAssetFeatures,\n StaticAssetRouteUtility,\n} from './context';\nimport { StaticAssetDefinition } from './definition';\nimport { StaticAssetLabelsUtility, UploadLabelsSchema } from './labels';\nimport { MetaLinkRowSchema } from './objects';\n\nconst MultipartBodySchema = z.object({\n files: z.union([z.instanceof(File), z.array(z.instanceof(File))]).openapi({\n type: 'array',\n items: { type: 'string', format: 'binary' },\n }),\n ...UploadLabelsSchema.shape,\n folderPath: z.string().optional().openapi({\n description: 'Target folder path for uploaded files (e.g., \"photos/2024\")',\n example: 'photos/2024',\n }),\n});\n\n/** What an upload or a commit says about the MetaLink row: the row, or a code when only the row failed. */\nexport const MetaLinkOutcomeSchema = z\n .union([z.object({ data: MetaLinkRowSchema }), z.object({ error: z.string() })])\n .optional();\n\nclass StaticAssetUploadHandler {\n /**\n * Built per request: the hook is offered the bucket, which only the route knows. A hook's key is\n * checked against the scope, never rewritten: the application may record that key elsewhere.\n */\n static buildNaming(opts: {\n env: IStaticAssetRouteEnv;\n bucketName: string;\n objectKey?: TStaticAssetObjectKeyResolver;\n }) {\n const { env, bucketName, objectKey } = opts;\n const { helper, keyPrefix } = env;\n\n if (!objectKey && keyPrefix === undefined) {\n return undefined;\n }\n\n return (naming: { file: TUploadNaming }) => {\n // The component's own name under a scope: the original name must stay one segment, as without one.\n if (!objectKey && !helper.isValidSegment({ segment: naming.file.originalName })) {\n throw getError({ message: '[upload] Invalid original file name' });\n }\n\n const defaultKey = `${keyPrefix ?? ''}${BaseStorageHelper.normalizeObjectName(naming)}`;\n const key = objectKey\n ? objectKey({ bucket: { name: bucketName }, file: naming.file, defaultKey })\n : defaultKey;\n\n if (!StaticAssetKeyScopeUtility.isInScope({ key, keyPrefix })) {\n throw getError({\n error: StaticAssetErrors.OBJECT_KEY_OUT_OF_SCOPE,\n message: `Object key is outside the key prefix of this entry | key: ${key} | keyPrefix: ${keyPrefix}`,\n });\n }\n\n return key;\n };\n }\n\n static async recordMetaLinks(opts: {\n env: IStaticAssetRouteEnv;\n uploaded: IUploadResult[];\n labels: TStaticAssetUploadLabels;\n }): Promise<IUploadResult[]> {\n const { env, uploaded, labels } = opts;\n const { helper, metaLink } = env;\n\n if (!metaLink) {\n return uploaded;\n }\n\n const results: IUploadResult[] = [];\n\n for (const uploadResult of uploaded) {\n try {\n const fileStat = await helper.getStat({\n bucket: uploadResult.bucket,\n object: uploadResult.object,\n });\n const data = await StaticAssetMetaLinkUtility.createRow({\n metaLink,\n helper,\n storage: env.storage,\n uploadResult,\n fileStat,\n labels,\n });\n\n results.push({ ...uploadResult, metaLink: { data } });\n } catch (error) {\n env.logger\n .for('UPLOAD')\n .error(\n 'Failed to create MetaLink | objectName: %s | Error: %s',\n uploadResult.object.key,\n error,\n );\n // A CODE, never the driver text: this 200 bypasses the error middleware that strips\n // `detail`/`table`/`constraint`. The real error is logged in full above.\n results.push({\n ...uploadResult,\n metaLink: { error: StaticAssetMetaLinkCodes.CREATE_FAILED },\n });\n }\n }\n\n return results;\n }\n\n static async handle(opts: { ctx: TRouteContext; env: IStaticAssetRouteEnv }) {\n const { ctx, env } = opts;\n const serverUpload = StaticAssetRouteUtility.requireFeature({\n value: env.serverUpload,\n feature: StaticAssetFeatures.SERVER_UPLOAD,\n });\n const { bucket } = await StaticAssetRouteUtility.resolveTarget({ ctx, env });\n\n const { files, fields } = await RequestUtility.parseMultipartBody({\n context: ctx,\n maxFiles: serverUpload.maxFiles,\n });\n const labels = StaticAssetLabelsUtility.parse({ fields });\n const folderPath = fields.folderPath || undefined;\n\n const uploadFiles: IUploadFile[] = files.map((file) => {\n const { buffer } = file;\n\n if (!buffer?.length) {\n throw getError({\n error: StaticAssetErrors.FILE_EMPTY,\n message: `Empty file content | name: ${file.originalname}`,\n });\n }\n\n // Authoritative: `buffer.length`, not the client-declared `size`.\n if (serverUpload.maxBytes !== undefined && buffer.length > serverUpload.maxBytes) {\n throw getError({\n error: StaticAssetErrors.UPLOAD_TOO_LARGE,\n message: `File ${file.originalname} of ${buffer.length} bytes exceeds the maximum of ${serverUpload.maxBytes}`,\n });\n }\n\n return {\n originalName: file.originalname,\n mimetype: file.mimetype,\n buffer,\n size: file.size,\n encoding: file.encoding,\n folderPath,\n };\n });\n\n const uploaded = await env.helper.upload({\n bucket,\n files: uploadFiles,\n normalizeNameFn: StaticAssetUploadHandler.buildNaming({\n env,\n bucketName: bucket.name,\n objectKey: serverUpload.objectKey,\n }),\n normalizeLinkFn: env.link,\n // The storage checks the caller's folders against `maxFolderDepth`, and the finished key, scope included, against the deeper bound.\n maxFolderDepth: env.maxFolderDepth,\n maxKeyDepth: env.objectKeyMaxDepth,\n });\n const results = await StaticAssetUploadHandler.recordMetaLinks({ env, uploaded, labels });\n\n return ctx.json(results, HTTP.ResultCodes.RS_2.Ok);\n }\n}\n\nexport const uploadRoute: IStaticAssetRoute = {\n key: StaticAssetRouteKeys.UPLOAD,\n feature: StaticAssetFeatures.SERVER_UPLOAD,\n build: (env) => ({\n config: StaticAssetDefinition.multipart({\n method: HTTP.Methods.POST,\n path: '/objects',\n body: MultipartBodySchema,\n response: z.array(\n z.object({\n bucket: z.object({ name: z.string() }),\n object: z.object({ key: z.string(), size: z.number(), contentType: z.string() }),\n link: z.string(),\n metaLink: MetaLinkOutcomeSchema,\n }),\n ),\n }),\n handler: (ctx) => StaticAssetUploadHandler.handle({ ctx, env }),\n }),\n // The route's body validator reads the whole multipart body, so the length check has to run before it.\n middleware: ({ env, own }) =>\n env.serverUpload?.maxBytes === undefined\n ? own\n : StaticAssetRouteOptionsUtility.appendLengthGuard({\n middleware: own,\n maxBytes: env.serverUpload.maxBytes,\n maxFiles: env.serverUpload.maxFiles,\n }),\n};\n"]}
|
|
@@ -112,7 +112,7 @@ export declare class BaseMetaLinkModel extends BaseRelationalEntity<typeof BaseM
|
|
|
112
112
|
tableName: "MetaLink";
|
|
113
113
|
dataType: "json";
|
|
114
114
|
columnType: "PgJsonb";
|
|
115
|
-
data: Record<string,
|
|
115
|
+
data: Record<string, unknown>;
|
|
116
116
|
driverParam: unknown;
|
|
117
117
|
notNull: false;
|
|
118
118
|
hasDefault: false;
|
|
@@ -124,7 +124,7 @@ export declare class BaseMetaLinkModel extends BaseRelationalEntity<typeof BaseM
|
|
|
124
124
|
identity: undefined;
|
|
125
125
|
generated: undefined;
|
|
126
126
|
}, {}, {
|
|
127
|
-
$type: Record<string,
|
|
127
|
+
$type: Record<string, unknown>;
|
|
128
128
|
}>;
|
|
129
129
|
storageType: import("drizzle-orm/pg-core").PgColumn<{
|
|
130
130
|
name: "storage_type";
|
|
@@ -391,7 +391,7 @@ export declare class BaseMetaLinkModel extends BaseRelationalEntity<typeof BaseM
|
|
|
391
391
|
tableName: "MetaLink";
|
|
392
392
|
dataType: "json";
|
|
393
393
|
columnType: "PgJsonb";
|
|
394
|
-
data: Record<string,
|
|
394
|
+
data: Record<string, unknown>;
|
|
395
395
|
driverParam: unknown;
|
|
396
396
|
notNull: false;
|
|
397
397
|
hasDefault: false;
|
|
@@ -403,7 +403,7 @@ export declare class BaseMetaLinkModel extends BaseRelationalEntity<typeof BaseM
|
|
|
403
403
|
identity: undefined;
|
|
404
404
|
generated: undefined;
|
|
405
405
|
}, {}, {
|
|
406
|
-
$type: Record<string,
|
|
406
|
+
$type: Record<string, unknown>;
|
|
407
407
|
}>;
|
|
408
408
|
storageType: import("drizzle-orm/pg-core").PgColumn<{
|
|
409
409
|
name: "storage_type";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.model.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/models/base.model.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,iBAAiB,CAAC;AACxC,OAAO,EACL,oBAAoB,EACpB,kBAAkB,EAClB,kBAAkB,GAGnB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAC;AAEpF,mNAAmN;AAE5M,IAAM,iBAAiB,GAAvB,MAAM,iBAAkB,SAAQ,oBAAqD;aAC1E,WAAM,GAAG,OAAO,CAC9B,UAA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AAG,EAAE,KAAK,EAAE,EAAE,CAAC;GACxB,iBAAiB,CAqC7B","sourcesContent":["import { model } from '@/base/metadata';\nimport {\n BaseRelationalEntity,\n PostgresIdEnricher,\n PostgresTzEnricher,\n type TTableObject,\n type TTableSchemaWithId,\n} from '@venizia/ignis-connectors/postgres';\nimport { boolean, index, integer, jsonb, pgTable, text } from 'drizzle-orm/pg-core';\n\n/** One row per (object, owner) pairing, NOT per object: one product image attached to the product and to each variant is the common case, so `(bucketName, objectName)` is indexed and deliberately NOT unique. */\n@model({ migration: { use: false } })\nexport class BaseMetaLinkModel extends BaseRelationalEntity<typeof BaseMetaLinkModel.schema> {\n static override schema = pgTable(\n 'MetaLink',\n {\n ...PostgresIdEnricher.generateColumnDefs({ id: { dataType: 'string' } }),\n ...PostgresTzEnricher.generateColumnDefs(),\n bucketName: text('bucket_name').notNull(),\n objectName: text('object_name').notNull(),\n link: text().notNull(),\n mimetype: text().notNull(),\n size: integer().notNull(),\n etag: text(),\n metadata: jsonb().$type<Record<string, unknown>>(),\n storageType: text('storage_type').notNull(),\n isSynced: boolean('is_synced').notNull().default(false),\n\n /** An opaque label the caller chooses - a size, a role, a rendition name. The component stores and returns it and reads no meaning into it. */\n variant: text(),\n\n /** Display order within ONE principal. Defaults to 0 so legacy rows tie and `ORDER BY sequence, createdAt` reproduces the order they already had. */\n sequence: integer().notNull().default(0),\n\n /** A polymorphic owner: the type names the table, the id the row. Both nullable - an object may belong to nothing yet, which is how `recreate-metalink` writes one. */\n principalType: text('principal_type'),\n principalId: text('principal_id'),\n },\n (def) => [\n index(`IDX_MetaLink_bucketName`).on(def.bucketName),\n index(`IDX_MetaLink_objectName`).on(def.objectName),\n index(`IDX_MetaLink_storageType`).on(def.storageType),\n index(`IDX_MetaLink_isSynced`).on(def.isSynced),\n // Ordering runs inside a principal filter, so filter columns lead and the sort column trails.\n index(`IDX_MetaLink_principal_sequence`).on(def.principalType, def.principalId, def.sequence),\n ],\n );\n\n static override relations = () => [];\n}\n\n/** The table schema of `BaseMetaLinkModel`. */\nexport type TMetaLinkSchema = typeof BaseMetaLinkModel.schema;\n/** A MetaLink row as selected from the table. */\nexport type TMetaLink = TTableObject<TMetaLinkSchema>;\n\n/** Any table whose row carries the MetaLink fields. The component reads and writes the ROW, so the table is free to carry another name or to live in another Postgres schema. */\nexport type TMetaLinkCompatibleSchema = TTableSchemaWithId & { $inferSelect: TMetaLink };\n"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { z } from '@hono/zod-openapi';
|
|
2
|
+
import { type IBucketRef, type IObjectLocation, type IObjectRef, type IStorageHelper, type IUploadResult } from '@venizia/ignis-helpers';
|
|
2
3
|
import { BaseService } from '@venizia/ignis-kernel';
|
|
3
|
-
import type { TStaticAssetDirectUploadOptions, TMetaLinkConfig, TStaticAssetStorageType,
|
|
4
|
+
import type { IStaticAssetValidation, IStaticAssetValidateResult, TStaticAssetDirectUploadOptions, TMetaLinkConfig, TStaticAssetStorageType, TStaticAssetUploadLabels } from '../common/index.js';
|
|
4
5
|
import type { TMetaLinkCompatibleSchema, TMetaLinkSchema } from '../models/index.js';
|
|
5
6
|
/** What a commit answers. `metaLink` is absent when the entry keeps no MetaLink table. */
|
|
6
7
|
export interface IStaticAssetCommitResult {
|
|
@@ -14,34 +15,70 @@ export interface IStaticAssetUploadCommitServiceOptions<Schema extends TMetaLink
|
|
|
14
15
|
/** Names the logger; the controller's own name is the usual value. */
|
|
15
16
|
scope: string;
|
|
16
17
|
helper: IStorageHelper;
|
|
17
|
-
/** The
|
|
18
|
-
keyPrefix
|
|
19
|
-
directUpload: Pick<TStaticAssetDirectUploadOptions, 'secretKey' | 'pendingPrefix'
|
|
18
|
+
/** The entry's `keyPrefix` as configured; normalized here the way the controller does. */
|
|
19
|
+
keyPrefix: string;
|
|
20
|
+
directUpload: Pick<TStaticAssetDirectUploadOptions, 'secretKey' | 'pendingPrefix'> & {
|
|
21
|
+
/** Absent, every file is valid. */
|
|
22
|
+
validation?: IStaticAssetValidation<z.ZodType>;
|
|
23
|
+
};
|
|
20
24
|
storage: TStaticAssetStorageType;
|
|
21
|
-
useMetaLink?: boolean;
|
|
22
25
|
metaLink?: TMetaLinkConfig<Schema>;
|
|
23
|
-
/** The
|
|
24
|
-
|
|
25
|
-
rawObjectPath?: boolean;
|
|
26
|
+
/** The link a commit returns for the committed object: the entry's own, so a commit and an upload agree. */
|
|
27
|
+
link: (opts: IObjectLocation) => string;
|
|
26
28
|
}
|
|
27
29
|
/**
|
|
28
30
|
* Moves a pending upload to its final key and records it: the body of the `upload-commit` route,
|
|
29
31
|
* callable without a request. A service that saves its own record commits the upload in the same
|
|
30
32
|
* call instead of asking the client for a second request.
|
|
31
33
|
*
|
|
32
|
-
* The token proves the key was issued by a policy
|
|
33
|
-
*
|
|
34
|
+
* The token proves the key was issued by a policy. It names an owner only when
|
|
35
|
+
* `directUpload.resolveOwner` is set, and then only that owner may commit it; without one, anyone who
|
|
36
|
+
* holds the token can.
|
|
34
37
|
*/
|
|
35
38
|
export declare class StaticAssetUploadCommitService<Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema> extends BaseService {
|
|
36
39
|
private readonly options;
|
|
37
|
-
private readonly keyPrefix
|
|
40
|
+
private readonly keyPrefix;
|
|
38
41
|
private readonly pendingPrefix;
|
|
39
|
-
private readonly basePath;
|
|
40
42
|
constructor(opts: IStaticAssetUploadCommitServiceOptions<Schema>);
|
|
41
|
-
/**
|
|
43
|
+
/** The signature, the expiry, the owner and the scope: the checks every stage of a token starts with. */
|
|
44
|
+
private readPayload;
|
|
45
|
+
/**
|
|
46
|
+
* Everything `commit` checks before it touches storage, and nothing else: the signature, the
|
|
47
|
+
* expiry, the owner and the `keyPrefix` scope. Returns the PENDING object, with no storage call and
|
|
48
|
+
* no side effect, so an application can read an uploaded file and report its problems to the user
|
|
49
|
+
* before anything is committed.
|
|
50
|
+
*
|
|
51
|
+
* A token this refuses is refused the same way `commit` refuses it, and every refusal says no more
|
|
52
|
+
* than that the token is no good: a caller learns nothing about which keys exist.
|
|
53
|
+
*/
|
|
54
|
+
verify(opts: {
|
|
55
|
+
token: string;
|
|
56
|
+
owner?: string;
|
|
57
|
+
}): IObjectLocation;
|
|
58
|
+
/**
|
|
59
|
+
* `verify`, then the application's own check of the pending file, read once through a file pinned
|
|
60
|
+
* to the content that is there now. A valid file answers the token `commit` takes: it is bound to
|
|
61
|
+
* that content and dies when the incoming token does. An invalid one answers its issues and no token.
|
|
62
|
+
* A token of either stage may be validated again, which pins whatever is there at that moment.
|
|
63
|
+
*/
|
|
64
|
+
validate(opts: {
|
|
65
|
+
token: string;
|
|
66
|
+
owner?: string;
|
|
67
|
+
}): Promise<IStaticAssetValidateResult<unknown>>;
|
|
68
|
+
private runValidation;
|
|
69
|
+
/**
|
|
70
|
+
* Moves the pending object to its final key and, when the entry keeps a MetaLink table, writes the
|
|
71
|
+
* row. With a `validation` on it takes the token `validate` returned and never runs the handler; the
|
|
72
|
+
* copy then happens only if the content still matches the pin. A MetaLink failure rides the result
|
|
73
|
+
* as a code: the object IS committed by then.
|
|
74
|
+
*/
|
|
42
75
|
commit(opts: {
|
|
43
|
-
|
|
44
|
-
|
|
76
|
+
token: string;
|
|
77
|
+
/** Who is committing. A token issued to an owner commits only for that owner. */
|
|
78
|
+
owner?: string;
|
|
79
|
+
labels?: TStaticAssetUploadLabels;
|
|
45
80
|
}): Promise<IStaticAssetCommitResult>;
|
|
81
|
+
/** A pin makes the copy conditional; a failed condition is a changed upload, and nothing is written. */
|
|
82
|
+
private copyPinned;
|
|
46
83
|
}
|
|
47
84
|
//# sourceMappingURL=commitment.service.d.ts.map
|
|
@@ -1,22 +1,24 @@
|
|
|
1
|
+
import { StorageUtility, } from '@venizia/ignis-helpers';
|
|
2
|
+
import { getError } from '@venizia/ignis-helpers/core';
|
|
1
3
|
import { BaseService } from '@venizia/ignis-kernel';
|
|
2
|
-
import { StaticAssetMetaLinkCodes } from '../common/index.js';
|
|
4
|
+
import { StaticAssetErrors, StaticAssetMetaLinkCodes, StaticAssetTokenStages } from '../common/index.js';
|
|
3
5
|
import { StaticAssetCommitTokenUtility } from '../utilities/index.js';
|
|
4
6
|
import { StaticAssetKeyScopeUtility } from '../utilities/key-scope.utility.js';
|
|
5
7
|
import { StaticAssetMetaLinkUtility } from '../utilities/meta-link.utility.js';
|
|
6
|
-
import {
|
|
8
|
+
import { StaticAssetPinnedFile } from '../utilities/pinned-file.utility.js';
|
|
7
9
|
/**
|
|
8
10
|
* Moves a pending upload to its final key and records it: the body of the `upload-commit` route,
|
|
9
11
|
* callable without a request. A service that saves its own record commits the upload in the same
|
|
10
12
|
* call instead of asking the client for a second request.
|
|
11
13
|
*
|
|
12
|
-
* The token proves the key was issued by a policy
|
|
13
|
-
*
|
|
14
|
+
* The token proves the key was issued by a policy. It names an owner only when
|
|
15
|
+
* `directUpload.resolveOwner` is set, and then only that owner may commit it; without one, anyone who
|
|
16
|
+
* holds the token can.
|
|
14
17
|
*/
|
|
15
18
|
export class StaticAssetUploadCommitService extends BaseService {
|
|
16
19
|
constructor(opts) {
|
|
17
20
|
super({ scope: opts.scope });
|
|
18
21
|
this.options = opts;
|
|
19
|
-
this.basePath = StaticAssetObjectLinkUtility.normalizeBasePath({ basePath: opts.basePath });
|
|
20
22
|
const prefixes = StaticAssetKeyScopeUtility.resolveDirectUploadPrefixes({
|
|
21
23
|
keyPrefix: opts.keyPrefix,
|
|
22
24
|
pendingPrefix: opts.directUpload.pendingPrefix,
|
|
@@ -26,31 +28,91 @@ export class StaticAssetUploadCommitService extends BaseService {
|
|
|
26
28
|
this.keyPrefix = prefixes.keyPrefix;
|
|
27
29
|
this.pendingPrefix = prefixes.pendingPrefix;
|
|
28
30
|
}
|
|
29
|
-
/**
|
|
31
|
+
/** The signature, the expiry, the owner and the scope: the checks every stage of a token starts with. */
|
|
32
|
+
readPayload(opts) {
|
|
33
|
+
const payload = StaticAssetCommitTokenUtility.read({
|
|
34
|
+
token: opts.token,
|
|
35
|
+
secretKey: this.options.directUpload.secretKey,
|
|
36
|
+
});
|
|
37
|
+
// The same error as a forged token: a caller learns only that the token is no good for them.
|
|
38
|
+
if (payload.owner !== undefined && payload.owner !== opts.owner) {
|
|
39
|
+
throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);
|
|
40
|
+
}
|
|
41
|
+
// A token another controller signed with the same secret must not land outside this scope.
|
|
42
|
+
StaticAssetKeyScopeUtility.assertInScope({
|
|
43
|
+
key: payload.object.key.slice(this.pendingPrefix.length),
|
|
44
|
+
keyPrefix: this.keyPrefix,
|
|
45
|
+
});
|
|
46
|
+
return payload;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Everything `commit` checks before it touches storage, and nothing else: the signature, the
|
|
50
|
+
* expiry, the owner and the `keyPrefix` scope. Returns the PENDING object, with no storage call and
|
|
51
|
+
* no side effect, so an application can read an uploaded file and report its problems to the user
|
|
52
|
+
* before anything is committed.
|
|
53
|
+
*
|
|
54
|
+
* A token this refuses is refused the same way `commit` refuses it, and every refusal says no more
|
|
55
|
+
* than that the token is no good: a caller learns nothing about which keys exist.
|
|
56
|
+
*/
|
|
57
|
+
verify(opts) {
|
|
58
|
+
const payload = this.readPayload(opts);
|
|
59
|
+
return { bucket: payload.bucket, object: payload.object };
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* `verify`, then the application's own check of the pending file, read once through a file pinned
|
|
63
|
+
* to the content that is there now. A valid file answers the token `commit` takes: it is bound to
|
|
64
|
+
* that content and dies when the incoming token does. An invalid one answers its issues and no token.
|
|
65
|
+
* A token of either stage may be validated again, which pins whatever is there at that moment.
|
|
66
|
+
*/
|
|
67
|
+
async validate(opts) {
|
|
68
|
+
const { helper, directUpload, scope } = this.options;
|
|
69
|
+
const payload = this.readPayload(opts);
|
|
70
|
+
const location = { bucket: payload.bucket, object: payload.object };
|
|
71
|
+
const stat = await helper.getStat(location);
|
|
72
|
+
const pin = StaticAssetPinnedFile.pinOf({ stat, scope });
|
|
73
|
+
const result = await this.runValidation({ location, pin, size: stat.size, owner: opts.owner });
|
|
74
|
+
if (!result.isValid) {
|
|
75
|
+
return { isValid: false, issues: result.issues };
|
|
76
|
+
}
|
|
77
|
+
return {
|
|
78
|
+
...result,
|
|
79
|
+
commitToken: StaticAssetCommitTokenUtility.build({
|
|
80
|
+
payload: { ...payload, stage: StaticAssetTokenStages.VALIDATED, pin },
|
|
81
|
+
secretKey: directUpload.secretKey,
|
|
82
|
+
}),
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
runValidation(opts) {
|
|
86
|
+
const { helper, directUpload } = this.options;
|
|
87
|
+
if (!directUpload.validation) {
|
|
88
|
+
return { isValid: true, issues: [] };
|
|
89
|
+
}
|
|
90
|
+
const { location, pin, size, owner } = opts;
|
|
91
|
+
return directUpload.validation.handler({
|
|
92
|
+
file: new StaticAssetPinnedFile({ helper, location, pin, size }),
|
|
93
|
+
owner,
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Moves the pending object to its final key and, when the entry keeps a MetaLink table, writes the
|
|
98
|
+
* row. With a `validation` on it takes the token `validate` returned and never runs the handler; the
|
|
99
|
+
* copy then happens only if the content still matches the pin. A MetaLink failure rides the result
|
|
100
|
+
* as a code: the object IS committed by then.
|
|
101
|
+
*/
|
|
30
102
|
async commit(opts) {
|
|
31
|
-
const { helper,
|
|
103
|
+
const { helper, storage, metaLink, directUpload, link: buildLink } = this.options;
|
|
32
104
|
// Verified BEFORE any storage call. That is what keeps this from being a name prober: a forged
|
|
33
105
|
// token fails without a round trip, so timing says nothing.
|
|
34
|
-
const payload =
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
106
|
+
const payload = this.readPayload(opts);
|
|
107
|
+
const { bucket: bucketRef, object: pendingObject, pin } = payload;
|
|
108
|
+
if (directUpload.validation && payload.stage !== StaticAssetTokenStages.VALIDATED) {
|
|
109
|
+
throw getError(StaticAssetErrors.UPLOAD_NOT_VALIDATED);
|
|
110
|
+
}
|
|
38
111
|
// Labels, not authorization - the token deliberately carries no business fields, so they travel
|
|
39
112
|
// beside it rather than inside it.
|
|
40
|
-
const
|
|
41
|
-
const
|
|
42
|
-
|
|
43
|
-
const object = { key: payload.key.slice(this.pendingPrefix.length) };
|
|
44
|
-
// A token another controller signed with the same secret must not land outside this scope.
|
|
45
|
-
StaticAssetKeyScopeUtility.assertInScope({ key: object.key, keyPrefix: this.keyPrefix });
|
|
46
|
-
// Before the copy, so a hook that throws leaves the object under the pending prefix
|
|
47
|
-
// for a lifecycle rule, rather than stranding it at the final key.
|
|
48
|
-
await directUpload.onCommit?.({ bucket: bucketRef, pendingObject, object });
|
|
49
|
-
await helper.copyObject({
|
|
50
|
-
bucket: bucketRef,
|
|
51
|
-
source: pendingObject,
|
|
52
|
-
destination: object,
|
|
53
|
-
});
|
|
113
|
+
const labels = opts.labels ?? {};
|
|
114
|
+
const object = { key: pendingObject.key.slice(this.pendingPrefix.length) };
|
|
115
|
+
await this.copyPinned({ bucket: bucketRef, source: pendingObject, destination: object, pin });
|
|
54
116
|
// The copy IS the commit; removing the temporary object is cleanup. A failure here
|
|
55
117
|
// leaves one object for the lifecycle rule, and failing the request would tell the
|
|
56
118
|
// caller their upload did not work when it did.
|
|
@@ -62,17 +124,11 @@ export class StaticAssetUploadCommitService extends BaseService {
|
|
|
62
124
|
.for('UPLOAD_COMMIT')
|
|
63
125
|
.warn('Committed, but the pending object remains | key: %s | error: %s', pendingObject.key, error);
|
|
64
126
|
}
|
|
65
|
-
const link =
|
|
66
|
-
basePath: this.basePath,
|
|
67
|
-
bucket: bucketRef,
|
|
68
|
-
object,
|
|
69
|
-
hasConfiguredBucket: true,
|
|
70
|
-
rawObjectPath: this.options.rawObjectPath,
|
|
71
|
-
});
|
|
127
|
+
const link = buildLink({ bucket: bucketRef, object });
|
|
72
128
|
// The two paths have to agree: without this a client reading `metaLink` off the
|
|
73
129
|
// response renders an empty state with no error - the failure nobody reports.
|
|
74
130
|
let metaLinkResult;
|
|
75
|
-
if (
|
|
131
|
+
if (metaLink) {
|
|
76
132
|
try {
|
|
77
133
|
const fileStat = await helper.getStat({ bucket: bucketRef, object });
|
|
78
134
|
const data = await StaticAssetMetaLinkUtility.createRow({
|
|
@@ -87,7 +143,7 @@ export class StaticAssetUploadCommitService extends BaseService {
|
|
|
87
143
|
fileStat,
|
|
88
144
|
}),
|
|
89
145
|
fileStat,
|
|
90
|
-
|
|
146
|
+
labels,
|
|
91
147
|
});
|
|
92
148
|
metaLinkResult = { data };
|
|
93
149
|
}
|
|
@@ -104,8 +160,31 @@ export class StaticAssetUploadCommitService extends BaseService {
|
|
|
104
160
|
bucket: bucketRef,
|
|
105
161
|
object,
|
|
106
162
|
link,
|
|
107
|
-
|
|
163
|
+
metaLink: metaLinkResult,
|
|
108
164
|
};
|
|
109
165
|
}
|
|
166
|
+
/** A pin makes the copy conditional; a failed condition is a changed upload, and nothing is written. */
|
|
167
|
+
async copyPinned(opts) {
|
|
168
|
+
const { bucket, source, destination, pin } = opts;
|
|
169
|
+
const condition = pin ? StaticAssetPinnedFile.conditionOf({ pin }) : {};
|
|
170
|
+
try {
|
|
171
|
+
await this.options.helper.copyObject({
|
|
172
|
+
bucket,
|
|
173
|
+
source,
|
|
174
|
+
destination,
|
|
175
|
+
ifMatch: condition.ifMatch,
|
|
176
|
+
sourceVersionId: condition.versionId,
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
catch (error) {
|
|
180
|
+
// With a pin the object was there when it was validated: a miss now is a change as much as other content is.
|
|
181
|
+
if (pin &&
|
|
182
|
+
(StorageUtility.isPreconditionFailedError({ error }) ||
|
|
183
|
+
StorageUtility.isNotFoundError({ error }))) {
|
|
184
|
+
throw getError({ error: StaticAssetErrors.UPLOAD_CHANGED, cause: error });
|
|
185
|
+
}
|
|
186
|
+
throw error;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
110
189
|
}
|
|
111
190
|
//# sourceMappingURL=commitment.service.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"commitment.service.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/services/commitment.service.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EAAE,wBAAwB,EAAE,MAAM,WAAW,CAAC;AACrD,OAAO,EAAE,6BAA6B,EAAE,MAAM,cAAc,CAAC;AAO7D,OAAO,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AAC5E,OAAO,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AAC5E,OAAO,EAAE,4BAA4B,EAAE,MAAM,kCAAkC,CAAC;AA6BhF;;;;;;;GAOG;AACH,MAAM,OAAO,8BAEX,SAAQ,WAAW;IAMnB,YAAY,IAAoD;QAC9D,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;QAE7B,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;QACpB,IAAI,CAAC,QAAQ,GAAG,4BAA4B,CAAC,iBAAiB,CAAC,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,CAAC,CAAC;QAE5F,MAAM,QAAQ,GAAG,0BAA0B,CAAC,2BAA2B,CAAC;YACtE,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,aAAa,EAAE,IAAI,CAAC,YAAY,CAAC,aAAa;YAC9C,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,KAAK,EAAE,IAAI,CAAC,KAAK;SAClB,CAAC,CAAC;QACH,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC,SAAS,CAAC;QACpC,IAAI,CAAC,aAAa,GAAG,QAAQ,CAAC,aAAa,CAAC;IAC9C,CAAC;IAED,4LAA4L;IAC5L,KAAK,CAAC,MAAM,CAAC,IAGZ;QACC,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,GAAG,IAAI,C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CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,cAAc,EAAE,CAAC;SACtE,CAAC;IACJ,CAAC;CACF","sourcesContent":["import type { IBucketRef, IObjectRef, IStorageHelper, IUploadResult } from '@venizia/ignis-helpers';\nimport { BaseService } from '@venizia/ignis-kernel';\nimport { StaticAssetMetaLinkCodes } from '../common';\nimport { StaticAssetCommitTokenUtility } from '../utilities';\nimport type {\n TStaticAssetDirectUploadOptions,\n TMetaLinkConfig,\n TStaticAssetStorageType,\n TStaticAssetUploadQuery,\n} from '../common';\nimport { StaticAssetKeyScopeUtility } from '../utilities/key-scope.utility';\nimport { StaticAssetMetaLinkUtility } from '../utilities/meta-link.utility';\nimport { StaticAssetObjectLinkUtility } from '../utilities/object-link.utility';\nimport type { TMetaLinkCompatibleSchema, TMetaLinkSchema } from '../models';\n\n/** What a commit answers. `metaLink` is absent when the entry keeps no MetaLink table. */\nexport interface IStaticAssetCommitResult {\n bucket: IBucketRef;\n object: IObjectRef;\n link: string;\n metaLink?: IUploadResult['metaLink'];\n}\n\n/** `Schema` is the MetaLink table the application bound, the same type parameter the component carries. */\nexport interface IStaticAssetUploadCommitServiceOptions<\n Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema,\n> {\n /** Names the logger; the controller's own name is the usual value. */\n scope: string;\n helper: IStorageHelper;\n /** The controller's `keyPrefix` as configured; normalized here the way the controller does. */\n keyPrefix?: string;\n directUpload: Pick<TStaticAssetDirectUploadOptions, 'secretKey' | 'pendingPrefix' | 'onCommit'>;\n storage: TStaticAssetStorageType;\n useMetaLink?: boolean;\n metaLink?: TMetaLinkConfig<Schema>;\n /** The controller mount path, the base of the link a commit returns. */\n basePath: string;\n rawObjectPath?: boolean;\n}\n\n/**\n * Moves a pending upload to its final key and records it: the body of the `upload-commit` route,\n * callable without a request. A service that saves its own record commits the upload in the same\n * call instead of asking the client for a second request.\n *\n * The token proves the key was issued by a policy; it carries no owner. Whether the current caller\n * may commit that key is the application's decision, made before it calls `commit`.\n */\nexport class StaticAssetUploadCommitService<\n Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema,\n> extends BaseService {\n private readonly options: IStaticAssetUploadCommitServiceOptions<Schema>;\n private readonly keyPrefix?: string;\n private readonly pendingPrefix: string;\n private readonly basePath: string;\n\n constructor(opts: IStaticAssetUploadCommitServiceOptions<Schema>) {\n super({ scope: opts.scope });\n\n this.options = opts;\n this.basePath = StaticAssetObjectLinkUtility.normalizeBasePath({ basePath: opts.basePath });\n\n const prefixes = StaticAssetKeyScopeUtility.resolveDirectUploadPrefixes({\n keyPrefix: opts.keyPrefix,\n pendingPrefix: opts.directUpload.pendingPrefix,\n helper: opts.helper,\n scope: opts.scope,\n });\n this.keyPrefix = prefixes.keyPrefix;\n this.pendingPrefix = prefixes.pendingPrefix;\n }\n\n /** Moves the pending object to its final key and, when the entry keeps a MetaLink table, writes the row. A MetaLink failure rides the result as a code: the object IS committed by then. */\n async commit(opts: {\n commitToken: string;\n labels?: TStaticAssetUploadQuery;\n }): Promise<IStaticAssetCommitResult> {\n const { helper, directUpload, storage, useMetaLink, metaLink } = this.options;\n\n // Verified BEFORE any storage call. That is what keeps this from being a name prober: a forged\n // token fails without a round trip, so timing says nothing.\n const payload = StaticAssetCommitTokenUtility.read({\n token: opts.commitToken,\n secretKey: directUpload.secretKey,\n });\n\n // Labels, not authorization - the token deliberately carries no business fields, so they travel\n // beside it rather than inside it.\n const query = opts.labels ?? {};\n\n const bucketRef = { name: payload.bucket };\n const pendingObject = { key: payload.key };\n const object = { key: payload.key.slice(this.pendingPrefix.length) };\n\n // A token another controller signed with the same secret must not land outside this scope.\n StaticAssetKeyScopeUtility.assertInScope({ key: object.key, keyPrefix: this.keyPrefix });\n\n // Before the copy, so a hook that throws leaves the object under the pending prefix\n // for a lifecycle rule, rather than stranding it at the final key.\n await directUpload.onCommit?.({ bucket: bucketRef, pendingObject, object });\n\n await helper.copyObject({\n bucket: bucketRef,\n source: pendingObject,\n destination: object,\n });\n\n // The copy IS the commit; removing the temporary object is cleanup. A failure here\n // leaves one object for the lifecycle rule, and failing the request would tell the\n // caller their upload did not work when it did.\n try {\n await helper.removeObject({ bucket: bucketRef, object: pendingObject });\n } catch (error) {\n this.logger\n .for('UPLOAD_COMMIT')\n .warn(\n 'Committed, but the pending object remains | key: %s | error: %s',\n pendingObject.key,\n error,\n );\n }\n\n const link = StaticAssetObjectLinkUtility.build({\n basePath: this.basePath,\n bucket: bucketRef,\n object,\n hasConfiguredBucket: true,\n rawObjectPath: this.options.rawObjectPath,\n });\n\n // The two paths have to agree: without this a client reading `metaLink` off the\n // response renders an empty state with no error - the failure nobody reports.\n let metaLinkResult: IUploadResult['metaLink'];\n\n if (useMetaLink && metaLink) {\n try {\n const fileStat = await helper.getStat({ bucket: bucketRef, object });\n const data = await StaticAssetMetaLinkUtility.createRow({\n metaLink,\n helper,\n storage,\n uploadResult: StaticAssetMetaLinkUtility.buildStoredUploadResult({\n helper,\n bucket: bucketRef,\n object,\n link,\n fileStat,\n }),\n fileStat,\n query,\n });\n\n metaLinkResult = { data };\n } catch (error) {\n // The object IS committed by now. A 500 would send the caller back with a token\n // whose source no longer exists, so this rides the body as a code, like UPLOAD.\n this.logger\n .for('UPLOAD_COMMIT')\n .error('Failed to create MetaLink | objectName: %s | Error: %s', object.key, error);\n metaLinkResult = { error: StaticAssetMetaLinkCodes.CREATE_FAILED };\n }\n }\n\n return {\n bucket: bucketRef,\n object,\n link,\n ...(metaLinkResult === undefined ? {} : { metaLink: metaLinkResult }),\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"commitment.service.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/services/commitment.service.ts"],"names":[],"mappings":"AACA,OAAO,EACL,cAAc,GAMf,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EAAE,iBA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M,QAAQ,CAAC,EAAE,KAAK,EAAE,iBAAiB,CAAC,cAAc,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;YAC5E,CAAC;YAED,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;CACF","sourcesContent":["import type { z } from '@hono/zod-openapi';\nimport {\n StorageUtility,\n type IBucketRef,\n type IObjectLocation,\n type IObjectRef,\n type IStorageHelper,\n type IUploadResult,\n} from '@venizia/ignis-helpers';\nimport type { ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { BaseService } from '@venizia/ignis-kernel';\nimport { StaticAssetErrors, StaticAssetMetaLinkCodes, StaticAssetTokenStages } from '../common';\nimport { StaticAssetCommitTokenUtility } from '../utilities';\nimport type {\n IStaticAssetValidation,\n IStaticAssetCommitTokenPayload,\n IStaticAssetPin,\n IStaticAssetValidateResult,\n IStaticAssetValidationResult,\n TStaticAssetDirectUploadOptions,\n TMetaLinkConfig,\n TStaticAssetStorageType,\n TStaticAssetUploadLabels,\n} from '../common';\nimport { StaticAssetKeyScopeUtility } from '../utilities/key-scope.utility';\nimport { StaticAssetMetaLinkUtility } from '../utilities/meta-link.utility';\nimport { StaticAssetPinnedFile } from '../utilities/pinned-file.utility';\nimport type { TMetaLinkCompatibleSchema, TMetaLinkSchema } from '../models';\n\n/** What a commit answers. `metaLink` is absent when the entry keeps no MetaLink table. */\nexport interface IStaticAssetCommitResult {\n bucket: IBucketRef;\n object: IObjectRef;\n link: string;\n metaLink?: IUploadResult['metaLink'];\n}\n\n/** `Schema` is the MetaLink table the application bound, the same type parameter the component carries. */\nexport interface IStaticAssetUploadCommitServiceOptions<\n Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema,\n> {\n /** Names the logger; the controller's own name is the usual value. */\n scope: string;\n helper: IStorageHelper;\n /** The entry's `keyPrefix` as configured; normalized here the way the controller does. */\n keyPrefix: string;\n directUpload: Pick<TStaticAssetDirectUploadOptions, 'secretKey' | 'pendingPrefix'> & {\n /** Absent, every file is valid. */\n validation?: IStaticAssetValidation<z.ZodType>;\n };\n storage: TStaticAssetStorageType;\n metaLink?: TMetaLinkConfig<Schema>;\n /** The link a commit returns for the committed object: the entry's own, so a commit and an upload agree. */\n link: (opts: IObjectLocation) => string;\n}\n\n/**\n * Moves a pending upload to its final key and records it: the body of the `upload-commit` route,\n * callable without a request. A service that saves its own record commits the upload in the same\n * call instead of asking the client for a second request.\n *\n * The token proves the key was issued by a policy. It names an owner only when\n * `directUpload.resolveOwner` is set, and then only that owner may commit it; without one, anyone who\n * holds the token can.\n */\nexport class StaticAssetUploadCommitService<\n Schema extends TMetaLinkCompatibleSchema = TMetaLinkSchema,\n> extends BaseService {\n private readonly options: IStaticAssetUploadCommitServiceOptions<Schema>;\n private readonly keyPrefix: string;\n private readonly pendingPrefix: string;\n\n constructor(opts: IStaticAssetUploadCommitServiceOptions<Schema>) {\n super({ scope: opts.scope });\n\n this.options = opts;\n\n const prefixes = StaticAssetKeyScopeUtility.resolveDirectUploadPrefixes({\n keyPrefix: opts.keyPrefix,\n pendingPrefix: opts.directUpload.pendingPrefix,\n helper: opts.helper,\n scope: opts.scope,\n });\n this.keyPrefix = prefixes.keyPrefix;\n this.pendingPrefix = prefixes.pendingPrefix;\n }\n\n /** The signature, the expiry, the owner and the scope: the checks every stage of a token starts with. */\n private readPayload(opts: { token: string; owner?: string }): IStaticAssetCommitTokenPayload {\n const payload = StaticAssetCommitTokenUtility.read({\n token: opts.token,\n secretKey: this.options.directUpload.secretKey,\n });\n\n // The same error as a forged token: a caller learns only that the token is no good for them.\n if (payload.owner !== undefined && payload.owner !== opts.owner) {\n throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);\n }\n\n // A token another controller signed with the same secret must not land outside this scope.\n StaticAssetKeyScopeUtility.assertInScope({\n key: payload.object.key.slice(this.pendingPrefix.length),\n keyPrefix: this.keyPrefix,\n });\n\n return payload;\n }\n\n /**\n * Everything `commit` checks before it touches storage, and nothing else: the signature, the\n * expiry, the owner and the `keyPrefix` scope. Returns the PENDING object, with no storage call and\n * no side effect, so an application can read an uploaded file and report its problems to the user\n * before anything is committed.\n *\n * A token this refuses is refused the same way `commit` refuses it, and every refusal says no more\n * than that the token is no good: a caller learns nothing about which keys exist.\n */\n verify(opts: { token: string; owner?: string }): IObjectLocation {\n const payload = this.readPayload(opts);\n\n return { bucket: payload.bucket, object: payload.object };\n }\n\n /**\n * `verify`, then the application's own check of the pending file, read once through a file pinned\n * to the content that is there now. A valid file answers the token `commit` takes: it is bound to\n * that content and dies when the incoming token does. An invalid one answers its issues and no token.\n * A token of either stage may be validated again, which pins whatever is there at that moment.\n */\n async validate(opts: {\n token: string;\n owner?: string;\n }): Promise<IStaticAssetValidateResult<unknown>> {\n const { helper, directUpload, scope } = this.options;\n const payload = this.readPayload(opts);\n const location = { bucket: payload.bucket, object: payload.object };\n\n const stat = await helper.getStat(location);\n const pin = StaticAssetPinnedFile.pinOf({ stat, scope });\n const result = await this.runValidation({ location, pin, size: stat.size, owner: opts.owner });\n\n if (!result.isValid) {\n return { isValid: false, issues: result.issues };\n }\n\n return {\n ...result,\n commitToken: StaticAssetCommitTokenUtility.build({\n payload: { ...payload, stage: StaticAssetTokenStages.VALIDATED, pin },\n secretKey: directUpload.secretKey,\n }),\n };\n }\n\n private runValidation(opts: {\n location: IObjectLocation;\n pin: IStaticAssetPin;\n size: number;\n owner?: string;\n }): ValueOrPromise<IStaticAssetValidationResult<unknown>> {\n const { helper, directUpload } = this.options;\n\n if (!directUpload.validation) {\n return { isValid: true, issues: [] };\n }\n\n const { location, pin, size, owner } = opts;\n\n return directUpload.validation.handler({\n file: new StaticAssetPinnedFile({ helper, location, pin, size }),\n owner,\n });\n }\n\n /**\n * Moves the pending object to its final key and, when the entry keeps a MetaLink table, writes the\n * row. With a `validation` on it takes the token `validate` returned and never runs the handler; the\n * copy then happens only if the content still matches the pin. A MetaLink failure rides the result\n * as a code: the object IS committed by then.\n */\n async commit(opts: {\n token: string;\n /** Who is committing. A token issued to an owner commits only for that owner. */\n owner?: string;\n labels?: TStaticAssetUploadLabels;\n }): Promise<IStaticAssetCommitResult> {\n const { helper, storage, metaLink, directUpload, link: buildLink } = this.options;\n\n // Verified BEFORE any storage call. That is what keeps this from being a name prober: a forged\n // token fails without a round trip, so timing says nothing.\n const payload = this.readPayload(opts);\n const { bucket: bucketRef, object: pendingObject, pin } = payload;\n\n if (directUpload.validation && payload.stage !== StaticAssetTokenStages.VALIDATED) {\n throw getError(StaticAssetErrors.UPLOAD_NOT_VALIDATED);\n }\n\n // Labels, not authorization - the token deliberately carries no business fields, so they travel\n // beside it rather than inside it.\n const labels = opts.labels ?? {};\n\n const object = { key: pendingObject.key.slice(this.pendingPrefix.length) };\n\n await this.copyPinned({ bucket: bucketRef, source: pendingObject, destination: object, pin });\n\n // The copy IS the commit; removing the temporary object is cleanup. A failure here\n // leaves one object for the lifecycle rule, and failing the request would tell the\n // caller their upload did not work when it did.\n try {\n await helper.removeObject({ bucket: bucketRef, object: pendingObject });\n } catch (error) {\n this.logger\n .for('UPLOAD_COMMIT')\n .warn(\n 'Committed, but the pending object remains | key: %s | error: %s',\n pendingObject.key,\n error,\n );\n }\n\n const link = buildLink({ bucket: bucketRef, object });\n\n // The two paths have to agree: without this a client reading `metaLink` off the\n // response renders an empty state with no error - the failure nobody reports.\n let metaLinkResult: IUploadResult['metaLink'];\n\n if (metaLink) {\n try {\n const fileStat = await helper.getStat({ bucket: bucketRef, object });\n const data = await StaticAssetMetaLinkUtility.createRow({\n metaLink,\n helper,\n storage,\n uploadResult: StaticAssetMetaLinkUtility.buildStoredUploadResult({\n helper,\n bucket: bucketRef,\n object,\n link,\n fileStat,\n }),\n fileStat,\n labels,\n });\n\n metaLinkResult = { data };\n } catch (error) {\n // The object IS committed by now. A 500 would send the caller back with a token\n // whose source no longer exists, so this rides the body as a code, like UPLOAD.\n this.logger\n .for('UPLOAD_COMMIT')\n .error('Failed to create MetaLink | objectName: %s | Error: %s', object.key, error);\n metaLinkResult = { error: StaticAssetMetaLinkCodes.CREATE_FAILED };\n }\n }\n\n return {\n bucket: bucketRef,\n object,\n link,\n metaLink: metaLinkResult,\n };\n }\n\n /** A pin makes the copy conditional; a failed condition is a changed upload, and nothing is written. */\n private async copyPinned(opts: {\n bucket: IBucketRef;\n source: IObjectRef;\n destination: IObjectRef;\n pin?: IStaticAssetPin;\n }): Promise<void> {\n const { bucket, source, destination, pin } = opts;\n const condition = pin ? StaticAssetPinnedFile.conditionOf({ pin }) : {};\n\n try {\n await this.options.helper.copyObject({\n bucket,\n source,\n destination,\n ifMatch: condition.ifMatch,\n sourceVersionId: condition.versionId,\n });\n } catch (error) {\n // With a pin the object was there when it was validated: a miss now is a change as much as other content is.\n if (\n pin &&\n (StorageUtility.isPreconditionFailedError({ error }) ||\n StorageUtility.isNotFoundError({ error }))\n ) {\n throw getError({ error: StaticAssetErrors.UPLOAD_CHANGED, cause: error });\n }\n\n throw error;\n }\n }\n}\n"]}
|