-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathput.js
More file actions
295 lines (266 loc) · 9.83 KB
/
put.js
File metadata and controls
295 lines (266 loc) · 9.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
/*
* Copyright 2025 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
import {
S3Client,
PutObjectCommand,
} from '@aws-sdk/client-s3';
import { EMPTY_DOC_SIZE } from '../../utils/constants.js';
import getS3Config from '../utils/config.js';
import {
getUsersForMetadata, ifMatch, ifNoneMatch,
} from '../utils/version.js';
import getObject from '../object/get.js';
export function getContentLength(body) {
if (body === undefined) {
return undefined;
}
if (typeof body === 'string' || body instanceof String) {
// get string length in bytes
return new Blob([body]).size;
} else if (body instanceof File) {
return body.size;
}
return undefined;
}
export async function putVersion(config, {
Bucket, Org, Body, ID, Version, Ext, Metadata, ContentLength, ContentType,
}, noneMatch = true) {
const length = ContentLength ?? getContentLength(Body);
const client = noneMatch ? ifNoneMatch(config) : new S3Client(config);
const input = {
Bucket, Key: `${Org}/.da-versions/${ID}/${Version}.${Ext}`, Body, Metadata, ContentLength: length, ContentType,
};
const command = new PutObjectCommand(input);
try {
const resp = await client.send(command);
return { status: resp.$metadata.httpStatusCode };
} catch (e) {
const status = e.$metadata?.httpStatusCode || 500;
// eslint-disable-next-line no-console
if (status >= 500) console.error('Fail to put version', e);
return { status };
}
}
function shouldCreateVersion(contentType) {
// Only create versions for HTML and JSON files
if (!contentType) return false;
const type = contentType.toLowerCase();
return type.startsWith('text/html') || type.startsWith('application/json');
}
function buildInput({
bucket, org, key, body, type, contentLength,
}) {
const length = contentLength ?? getContentLength(body);
const Bucket = bucket;
return {
Bucket, Key: `${org}/${key}`, Body: body, ContentType: type, ContentLength: length,
};
}
export async function putObjectWithVersion(
env,
daCtx,
update,
body,
guid,
clientConditionals = null,
) {
const config = getS3Config(env);
// While we are automatically storing the body once for the 'Collab Parse' changes, we never
// do a HEAD, because we may need the content. Once we don't need to do this automatic store
// any more, we can change the 'false' argument in the next line back to !body.
const current = await getObject(env, update, false);
let ID = current.metadata?.id;
if (!ID) {
ID = guid || crypto.randomUUID();
} else if (guid && ID !== guid) {
return { status: 409, metadata: { id: ID } };
}
// Only create versions for HTML and JSON files
const contentType = update.type || current.contentType;
const createVersion = shouldCreateVersion(contentType);
const Version = current.metadata?.version || crypto.randomUUID();
const Users = JSON.stringify(getUsersForMetadata(daCtx.users));
const input = buildInput(update);
const Timestamp = `${Date.now()}`;
const Path = update.key;
// Validate conflicting conditionals - both headers present is unusual for PUT
let effectiveConditionals = clientConditionals;
if (clientConditionals?.ifMatch && clientConditionals?.ifNoneMatch) {
// Per RFC 7232, If-Match should be evaluated first for PUT/POST
// If-None-Match for PUT is less common (create-only semantics)
// eslint-disable-next-line no-console
console.warn('Both If-Match and If-None-Match provided, prioritizing If-Match per RFC 7232');
// Clear If-None-Match to prevent confusion
effectiveConditionals = { ifMatch: clientConditionals.ifMatch };
}
// Handle client-provided If-Match: * (requires resource to exist)
if (effectiveConditionals?.ifMatch === '*') {
if (current.status === 404) {
return { status: 412, metadata: { id: ID } };
}
// Resource exists, proceed with update using actual ETag
// Fall through to update logic below with current.etag
}
// Handle client-provided If-None-Match: * (requires resource NOT to exist)
if (effectiveConditionals?.ifNoneMatch === '*') {
if (current.status !== 404) {
return { status: 412, metadata: { id: ID } };
}
// Resource doesn't exist, proceed with create
// Fall through to create logic below
}
if (current.status === 404) {
const metadata = {
ID, Users, Timestamp, Path,
};
// Only include Version metadata for files that support versioning
if (createVersion) {
metadata.Version = Version;
}
// Use client conditional if provided, otherwise use internal If-None-Match: *
const client = effectiveConditionals?.ifNoneMatch
? ifNoneMatch(config, effectiveConditionals.ifNoneMatch)
: ifNoneMatch(config);
const command = new PutObjectCommand({
...input,
Metadata: metadata,
});
try {
const resp = await client.send(command);
return resp.$metadata.httpStatusCode === 200
? { status: 201, metadata: { id: ID }, etag: resp.ETag }
: { status: resp.$metadata.httpStatusCode, metadata: { id: ID }, etag: resp.ETag };
} catch (e) {
const status = e.$metadata?.httpStatusCode || 500;
if (status === 412) {
// Only retry if no client conditionals (internal operation) and under retry limit
if (!effectiveConditionals?.ifNoneMatch) {
return putObjectWithVersion(
env,
daCtx,
update,
body,
guid,
clientConditionals,
);
}
// Client conditional failed or max retries exceeded, return 412
return { status: 412, metadata: { id: ID } };
}
// eslint-disable-next-line no-console
if (status >= 500) console.error('Failed to put object (in object with version)', e);
return { status, metadata: { id: ID } };
}
}
let storeBody = false;
let Label = update.label;
if (createVersion) {
if (daCtx.method === 'PUT'
&& daCtx.ext === 'html'
&& current.contentLength > EMPTY_DOC_SIZE
&& (!update.body || update.body.size <= EMPTY_DOC_SIZE)) {
// we are about to empty the document body
// this should almost never happen but it does in some unexpectedcases
// we want then to store a version of the full document as a Restore Point
// eslint-disable-next-line no-console
console.warn(`Empty body, creating a restore point (${current.contentLength} / ${update.body?.size})`);
storeBody = true;
Label = 'Restore Point';
}
const versionResp = await putVersion(config, {
Bucket: input.Bucket,
Org: daCtx.org,
Body: (body || storeBody ? current.body : ''),
ContentLength: (body || storeBody ? current.contentLength : undefined),
ContentType: current.contentType,
ID,
Version,
Ext: daCtx.ext,
Metadata: {
Users: current.metadata?.users || JSON.stringify([{ email: 'anonymous' }]),
Timestamp: current.metadata?.timestamp || Timestamp,
Path: current.metadata?.path || Path,
Label,
},
});
if (versionResp.status !== 200 && versionResp.status !== 412) {
return { status: versionResp.status, metadata: { id: ID } };
}
}
const metadata = {
ID, Users, Timestamp, Path,
};
// Only include Version metadata for files that support versioning
if (createVersion) {
metadata.Version = crypto.randomUUID();
}
// Use client-provided If-Match if available, otherwise use current ETag
// Special case: If client sent If-Match:*, we already validated existence above,
// so now use the actual ETag for proper version control
let matchValue;
if (effectiveConditionals?.ifMatch === '*') {
matchValue = `${current.etag}`;
} else {
matchValue = effectiveConditionals?.ifMatch || `${current.etag}`;
}
const client = ifMatch(config, matchValue);
const command = new PutObjectCommand({
...input,
Metadata: metadata,
});
try {
const resp = await client.send(command);
return {
status: resp.$metadata.httpStatusCode,
metadata: { id: ID },
etag: resp.ETag,
};
} catch (e) {
const status = e.$metadata?.httpStatusCode || 500;
if (status === 412) {
// Only retry if no client conditionals (internal operation) and under retry limit
if (!effectiveConditionals?.ifMatch) {
return putObjectWithVersion(
env,
daCtx,
update,
body,
guid,
clientConditionals,
);
}
// Client conditional failed or max retries exceeded, return 412
return { status: 412, metadata: { id: ID } };
}
// eslint-disable-next-line no-console
if (status >= 500) console.error('Failed to version (in object with version)', e);
return { status, metadata: { id: ID } };
}
}
export async function postObjectVersionWithLabel(label, env, daCtx) {
const { body, contentLength, contentType } = await getObject(env, daCtx);
const { bucket, org, key } = daCtx;
const resp = await putObjectWithVersion(env, daCtx, {
bucket, org, key, body, contentLength, type: contentType, label,
}, true);
return { status: resp.status === 200 ? 201 : resp.status };
}
export async function postObjectVersion(req, env, daCtx) {
let reqJSON;
try {
reqJSON = await req.json();
} catch (e) {
// no body
}
const label = reqJSON?.label;
return /* await */ postObjectVersionWithLabel(label, env, daCtx);
}