forked from microsoft/FluidFramework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreateFile.ts
More file actions
374 lines (347 loc) · 11.7 KB
/
Copy pathcreateFile.ts
File metadata and controls
374 lines (347 loc) · 11.7 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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
/*!
* Copyright (c) Microsoft Corporation and contributors. All rights reserved.
* Licensed under the MIT License.
*/
import { assert } from "@fluidframework/core-utils/internal";
import type { ISummaryTree } from "@fluidframework/driver-definitions";
import type { IFileEntry, ISnapshot } from "@fluidframework/driver-definitions/internal";
import { NonRetryableError } from "@fluidframework/driver-utils/internal";
import {
type IOdspResolvedUrl,
type InstrumentedStorageTokenFetcher,
OdspErrorTypes,
type ShareLinkInfoType,
type IOdspUrlParts,
} from "@fluidframework/odsp-driver-definitions/internal";
import {
type TelemetryLoggerExt,
loggerToMonitoringContext,
PerformanceEvent,
} from "@fluidframework/telemetry-utils/internal";
import type { ICreateFileResponse, IRenameFileResponse } from "./../contracts.js";
import { ClpCompliantAppHeader } from "./../contractsPublic.js";
import { createOdspUrl } from "./../createOdspUrl.js";
import type { EpochTracker } from "./../epochTracker.js";
import { getHeadersWithAuth } from "./../getUrlAndHeadersWithAuth.js";
import { OdspDriverUrlResolver } from "./../odspDriverUrlResolver.js";
import { checkForKnownServerFarmType, getApiRoot } from "./../odspUrlHelper.js";
import {
type INewFileInfo,
appendNavParam,
buildOdspShareLinkReqParams,
createCacheSnapshotKey,
getWithRetryForTokenRefresh,
snapshotWithLoadingGroupIdSupported,
} from "./../odspUtils.js";
import { pkgVersion as driverVersion } from "./../packageVersion.js";
import { runWithRetry } from "./../retryUtils.js";
import {
convertCreateNewSummaryTreeToTreeAndBlobs,
convertSummaryIntoContainerSnapshot,
createNewFluidContainerCore,
} from "./createNewUtils.js";
const isInvalidFileName = (fileName: string): boolean => {
const invalidCharsRegex = /["*/:<>?\\|]+/g;
return invalidCharsRegex.test(fileName);
};
/**
* Creates a new Fluid file.
* Returns resolved url
*/
export async function createNewFluidFile(
getAuthHeader: InstrumentedStorageTokenFetcher,
newFileInfo: INewFileInfo,
logger: TelemetryLoggerExt,
createNewSummary: ISummaryTree | undefined,
epochTracker: EpochTracker,
fileEntry: IFileEntry,
createNewCaching: boolean,
forceAccessTokenViaAuthorizationHeader: boolean,
isClpCompliantApp?: boolean,
enableSingleRequestForShareLinkWithCreate?: boolean,
resolvedUrl?: IOdspResolvedUrl,
): Promise<IOdspResolvedUrl> {
// Check for valid filename before the request to create file is actually made.
if (isInvalidFileName(newFileInfo.filename)) {
throw new NonRetryableError(
// pre-0.58 error message: Invalid filename
"Invalid filename for createNew",
OdspErrorTypes.invalidFileNameError,
{ driverVersion },
);
}
let itemId: string;
let pendingRename: string | undefined;
let summaryHandle: string = "";
let shareLinkInfo: ShareLinkInfoType | undefined;
if (createNewSummary === undefined) {
const content = await createNewEmptyFluidFile(
getAuthHeader,
newFileInfo,
logger,
epochTracker,
);
itemId = content.itemId;
pendingRename = newFileInfo.filename;
} else {
const content = await createNewFluidFileFromSummary(
getAuthHeader,
newFileInfo,
logger,
createNewSummary,
epochTracker,
forceAccessTokenViaAuthorizationHeader,
);
itemId = content.itemId;
summaryHandle = content.id;
shareLinkInfo = extractShareLinkData(content, enableSingleRequestForShareLinkWithCreate);
}
const odspUrl = createOdspUrl({ ...newFileInfo, itemId, dataStorePath: "/" });
const resolver = new OdspDriverUrlResolver();
const odspResolvedUrl = await resolver.resolve({
url: odspUrl,
headers: { [ClpCompliantAppHeader.isClpCompliantApp]: isClpCompliantApp },
});
fileEntry.docId = odspResolvedUrl.hashedDocumentId;
fileEntry.resolvedUrl = odspResolvedUrl;
odspResolvedUrl.context = resolvedUrl?.context;
odspResolvedUrl.appName = resolvedUrl?.appName;
odspResolvedUrl.codeHint = odspResolvedUrl.codeHint?.containerPackageName
? odspResolvedUrl.codeHint
: resolvedUrl?.codeHint;
if (shareLinkInfo?.createLink?.link) {
let newWebUrl = shareLinkInfo.createLink.link.webUrl;
newWebUrl = appendNavParam(
newWebUrl,
odspResolvedUrl,
odspResolvedUrl.dataStorePath ?? "/",
odspResolvedUrl.codeHint?.containerPackageName,
);
shareLinkInfo.createLink.link.webUrl = newWebUrl;
}
odspResolvedUrl.shareLinkInfo = shareLinkInfo;
odspResolvedUrl.pendingRename = pendingRename;
if (createNewSummary !== undefined && createNewCaching) {
assert(summaryHandle !== undefined, 0x203 /* "Summary handle is undefined" */);
// converting summary and getting sequence number
const snapshot: ISnapshot = convertCreateNewSummaryTreeToTreeAndBlobs(
createNewSummary,
summaryHandle,
);
// caching the converted summary
await epochTracker.put(
createCacheSnapshotKey(
odspResolvedUrl,
snapshotWithLoadingGroupIdSupported(loggerToMonitoringContext(logger).config),
),
snapshot,
);
}
return odspResolvedUrl;
}
/**
* If user requested creation of a sharing link along with the creation of the file by providing
* createLinkScope in the request parameters then extract and save the sharing link information from
* the response if it is available.
* In case there was an error in creation of the sharing link, error is provided back in the response,
* and does not impact the creation of file in ODSP.
* @param requestedSharingLinkKind - Kind of sharing link requested to be created along with the creation of file.
* @param response - Response object received from the /snapshot api call
* @returns Sharing link information received in the response from a successful creation of a file.
*/
function extractShareLinkData(
response: ICreateFileResponse,
enableSingleRequestForShareLinkWithCreate?: boolean,
): ShareLinkInfoType | undefined {
let shareLinkInfo: ShareLinkInfoType | undefined;
if (enableSingleRequestForShareLinkWithCreate) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const { sharing } = response;
if (!sharing) {
return;
}
/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access */
shareLinkInfo = {
createLink: {
link: sharing.sharingLink
? {
scope: sharing.sharingLink.scope,
role: sharing.sharingLink.type,
webUrl: sharing.sharingLink.webUrl,
...sharing.sharingLink,
}
: undefined,
error: sharing.error,
shareId: sharing.shareId,
},
};
/* eslint-enable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access */
}
return shareLinkInfo;
}
/**
* Encodes file path so it can be embedded in the request url
* @param path - path to encode
* @returns encoded path or "" if path is undefined
*/
function encodeFilePath(path: string | undefined): string {
return path ? encodeURIComponent(path.startsWith("/") ? path : `/${path}`) : "";
}
export async function createNewEmptyFluidFile(
getAuthHeader: InstrumentedStorageTokenFetcher,
newFileInfo: INewFileInfo,
logger: TelemetryLoggerExt,
epochTracker: EpochTracker,
): Promise<{ itemId: string; fileName: string }> {
const filePath = encodeFilePath(newFileInfo.filePath);
const encodedFilename = encodeURIComponent(`${newFileInfo.filename}.tmp`);
const initialUrl = `${getApiRoot(new URL(newFileInfo.siteUrl))}/drives/${
newFileInfo.driveId
}/items/root:${filePath}/${encodedFilename}:/content?@name.conflictBehavior=rename&select=id,name,parentReference`;
return getWithRetryForTokenRefresh(async (options) => {
const url = initialUrl;
const method = "PUT";
const authHeader = await getAuthHeader(
{ ...options, request: { url, method } },
"CreateNewFile",
);
const internalFarmType = checkForKnownServerFarmType(newFileInfo.siteUrl);
return PerformanceEvent.timedExecAsync(
logger,
{
eventName: "createNewEmptyFile",
details: {
internalFarmType,
},
},
async (event) => {
const headers = getHeadersWithAuth(authHeader);
headers["Content-Type"] = "application/json";
const fetchResponse = await runWithRetry(
async () =>
epochTracker.fetchAndParseAsJSON<ICreateFileResponse>(
url,
{
body: undefined,
headers,
method,
},
"createFile",
),
"createFile",
logger,
);
const content = fetchResponse.content;
if (!content?.id) {
throw new NonRetryableError(
// pre-0.58 error message: ODSP CreateFile call returned no item ID
"ODSP CreateFile call returned no item ID (for empty file)",
OdspErrorTypes.incorrectServerResponse,
{ driverVersion },
);
}
event.end({
...fetchResponse.propsToLog,
});
return { itemId: content.id, fileName: content.name };
},
{ end: true, cancel: "error" },
);
});
}
export async function renameEmptyFluidFile(
getAuthHeader: InstrumentedStorageTokenFetcher,
odspParts: IOdspUrlParts,
requestedFileName: string,
logger: TelemetryLoggerExt,
epochTracker: EpochTracker,
): Promise<IRenameFileResponse> {
const initialUrl = `${getApiRoot(new URL(odspParts.siteUrl))}/drives/${
odspParts.driveId
}/items/${odspParts.itemId}?@name.conflictBehavior=rename`;
return getWithRetryForTokenRefresh(async (options) => {
const url = initialUrl;
const method = "PATCH";
const authHeader = await getAuthHeader(
{ ...options, request: { url, method } },
"renameFile",
);
return PerformanceEvent.timedExecAsync(
logger,
{ eventName: "renameFile" },
async (event) => {
const headers = getHeadersWithAuth(authHeader);
headers["Content-Type"] = "application/json";
const fetchResponse = await runWithRetry(
async () =>
epochTracker.fetchAndParseAsJSON<IRenameFileResponse>(
url,
{
body: JSON.stringify({
name: requestedFileName,
}),
headers,
method: "PATCH",
},
"renameFile",
),
"renameFile",
logger,
);
const content = fetchResponse.content;
if (!content?.id) {
throw new NonRetryableError(
"ODSP RenameFile call returned no item ID (for empty file)",
OdspErrorTypes.incorrectServerResponse,
{ driverVersion },
);
}
event.end({
...fetchResponse.propsToLog,
});
return content;
},
{ end: true, cancel: "error" },
);
});
}
export async function createNewFluidFileFromSummary(
getAuthHeader: InstrumentedStorageTokenFetcher,
newFileInfo: INewFileInfo,
logger: TelemetryLoggerExt,
createNewSummary: ISummaryTree,
epochTracker: EpochTracker,
forceAccessTokenViaAuthorizationHeader: boolean,
): Promise<ICreateFileResponse> {
const filePath = encodeFilePath(newFileInfo.filePath);
const encodedFilename = encodeURIComponent(newFileInfo.filename);
const baseUrl =
`${getApiRoot(new URL(newFileInfo.siteUrl))}/drives/${newFileInfo.driveId}/items/root:` +
`${filePath}/${encodedFilename}`;
const containerSnapshot = convertSummaryIntoContainerSnapshot(createNewSummary);
// Build share link parameter based on the createLinkType provided so that the
// snapshot api can create and return the share link along with creation of file in the response.
const createShareLinkParam = buildOdspShareLinkReqParams(newFileInfo.createLinkType);
const initialUrl = `${baseUrl}:/opStream/snapshots/snapshot${
createShareLinkParam ? `?${createShareLinkParam}` : ""
}`;
return createNewFluidContainerCore<ICreateFileResponse>({
containerSnapshot,
getAuthHeader,
logger,
initialUrl,
forceAccessTokenViaAuthorizationHeader,
epochTracker,
telemetryName: "CreateNewFile",
fetchType: "createFile",
validateResponseCallback: (content) => {
if (!content?.itemId) {
throw new NonRetryableError(
"ODSP CreateFile call returned no item ID",
OdspErrorTypes.incorrectServerResponse,
{ driverVersion },
);
}
},
});
}