@fluidframework/odsp-driver 0.59.2001 → 0.59.3000

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 (165) hide show
  1. package/.eslintrc.js +0 -1
  2. package/dist/ReadBufferUtils.js +2 -2
  3. package/dist/ReadBufferUtils.js.map +1 -1
  4. package/dist/WriteBufferUtils.js +14 -14
  5. package/dist/WriteBufferUtils.js.map +1 -1
  6. package/dist/checkUrl.js +1 -1
  7. package/dist/checkUrl.js.map +1 -1
  8. package/dist/compactSnapshotParser.js +27 -27
  9. package/dist/compactSnapshotParser.js.map +1 -1
  10. package/dist/compactSnapshotWriter.js +15 -15
  11. package/dist/compactSnapshotWriter.js.map +1 -1
  12. package/dist/contracts.d.ts +0 -1
  13. package/dist/contracts.d.ts.map +1 -1
  14. package/dist/contracts.js.map +1 -1
  15. package/dist/createFile.js +15 -15
  16. package/dist/createFile.js.map +1 -1
  17. package/dist/createNewUtils.js +4 -4
  18. package/dist/createNewUtils.js.map +1 -1
  19. package/dist/epochTracker.d.ts.map +1 -1
  20. package/dist/epochTracker.js +11 -11
  21. package/dist/epochTracker.js.map +1 -1
  22. package/dist/fetch.js +1 -1
  23. package/dist/fetch.js.map +1 -1
  24. package/dist/fetchSnapshot.d.ts.map +1 -1
  25. package/dist/fetchSnapshot.js +19 -19
  26. package/dist/fetchSnapshot.js.map +1 -1
  27. package/dist/getFileLink.js +19 -19
  28. package/dist/getFileLink.js.map +1 -1
  29. package/dist/getQueryString.d.ts.map +1 -1
  30. package/dist/getQueryString.js.map +1 -1
  31. package/dist/getUrlAndHeadersWithAuth.d.ts.map +1 -1
  32. package/dist/getUrlAndHeadersWithAuth.js.map +1 -1
  33. package/dist/odspCache.d.ts.map +1 -1
  34. package/dist/odspCache.js.map +1 -1
  35. package/dist/odspDeltaStorageService.d.ts.map +1 -1
  36. package/dist/odspDeltaStorageService.js +5 -5
  37. package/dist/odspDeltaStorageService.js.map +1 -1
  38. package/dist/odspDocumentDeltaConnection.d.ts.map +1 -1
  39. package/dist/odspDocumentDeltaConnection.js +12 -12
  40. package/dist/odspDocumentDeltaConnection.js.map +1 -1
  41. package/dist/odspDocumentService.js +9 -8
  42. package/dist/odspDocumentService.js.map +1 -1
  43. package/dist/odspDocumentServiceFactory.js +1 -1
  44. package/dist/odspDocumentServiceFactory.js.map +1 -1
  45. package/dist/odspDocumentServiceFactoryCore.d.ts.map +1 -1
  46. package/dist/odspDocumentServiceFactoryCore.js +20 -12
  47. package/dist/odspDocumentServiceFactoryCore.js.map +1 -1
  48. package/dist/odspDocumentStorageManager.d.ts +1 -0
  49. package/dist/odspDocumentStorageManager.d.ts.map +1 -1
  50. package/dist/odspDocumentStorageManager.js +34 -32
  51. package/dist/odspDocumentStorageManager.js.map +1 -1
  52. package/dist/odspDriverUrlResolver.js +10 -10
  53. package/dist/odspDriverUrlResolver.js.map +1 -1
  54. package/dist/odspDriverUrlResolverForShareLink.js +10 -10
  55. package/dist/odspDriverUrlResolverForShareLink.js.map +1 -1
  56. package/dist/odspError.d.ts +1 -1
  57. package/dist/odspError.d.ts.map +1 -1
  58. package/dist/odspError.js +1 -1
  59. package/dist/odspError.js.map +1 -1
  60. package/dist/odspFluidFileLink.js +2 -2
  61. package/dist/odspFluidFileLink.js.map +1 -1
  62. package/dist/odspPublicUtils.js +1 -1
  63. package/dist/odspPublicUtils.js.map +1 -1
  64. package/dist/odspSnapshotParser.js +3 -3
  65. package/dist/odspSnapshotParser.js.map +1 -1
  66. package/dist/odspSummaryUploadManager.js +7 -7
  67. package/dist/odspSummaryUploadManager.js.map +1 -1
  68. package/dist/odspUtils.js +9 -9
  69. package/dist/odspUtils.js.map +1 -1
  70. package/dist/opsCaching.js.map +1 -1
  71. package/dist/packageVersion.d.ts +1 -1
  72. package/dist/packageVersion.js +1 -1
  73. package/dist/packageVersion.js.map +1 -1
  74. package/dist/prefetchLatestSnapshot.js +7 -7
  75. package/dist/prefetchLatestSnapshot.js.map +1 -1
  76. package/dist/retryErrorsStorageAdapter.d.ts.map +1 -1
  77. package/dist/retryErrorsStorageAdapter.js +1 -1
  78. package/dist/retryErrorsStorageAdapter.js.map +1 -1
  79. package/dist/retryUtils.js +4 -4
  80. package/dist/retryUtils.js.map +1 -1
  81. package/dist/vroom.js +3 -3
  82. package/dist/vroom.js.map +1 -1
  83. package/dist/zipItDataRepresentationUtils.d.ts.map +1 -1
  84. package/dist/zipItDataRepresentationUtils.js +21 -12
  85. package/dist/zipItDataRepresentationUtils.js.map +1 -1
  86. package/lib/WriteBufferUtils.js +1 -1
  87. package/lib/WriteBufferUtils.js.map +1 -1
  88. package/lib/compactSnapshotParser.js.map +1 -1
  89. package/lib/compactSnapshotWriter.js.map +1 -1
  90. package/lib/contracts.d.ts +0 -1
  91. package/lib/contracts.d.ts.map +1 -1
  92. package/lib/contracts.js.map +1 -1
  93. package/lib/createFile.js.map +1 -1
  94. package/lib/epochTracker.d.ts.map +1 -1
  95. package/lib/epochTracker.js +1 -1
  96. package/lib/epochTracker.js.map +1 -1
  97. package/lib/fetchSnapshot.d.ts.map +1 -1
  98. package/lib/fetchSnapshot.js.map +1 -1
  99. package/lib/getFileLink.js +6 -6
  100. package/lib/getFileLink.js.map +1 -1
  101. package/lib/getQueryString.d.ts.map +1 -1
  102. package/lib/getQueryString.js.map +1 -1
  103. package/lib/getUrlAndHeadersWithAuth.d.ts.map +1 -1
  104. package/lib/getUrlAndHeadersWithAuth.js.map +1 -1
  105. package/lib/odspCache.d.ts.map +1 -1
  106. package/lib/odspCache.js.map +1 -1
  107. package/lib/odspDeltaStorageService.d.ts.map +1 -1
  108. package/lib/odspDeltaStorageService.js.map +1 -1
  109. package/lib/odspDocumentDeltaConnection.d.ts.map +1 -1
  110. package/lib/odspDocumentDeltaConnection.js +1 -1
  111. package/lib/odspDocumentDeltaConnection.js.map +1 -1
  112. package/lib/odspDocumentService.js +2 -1
  113. package/lib/odspDocumentService.js.map +1 -1
  114. package/lib/odspDocumentServiceFactoryCore.d.ts.map +1 -1
  115. package/lib/odspDocumentServiceFactoryCore.js +10 -2
  116. package/lib/odspDocumentServiceFactoryCore.js.map +1 -1
  117. package/lib/odspDocumentStorageManager.d.ts +1 -0
  118. package/lib/odspDocumentStorageManager.d.ts.map +1 -1
  119. package/lib/odspDocumentStorageManager.js +17 -15
  120. package/lib/odspDocumentStorageManager.js.map +1 -1
  121. package/lib/odspDriverUrlResolver.js +5 -5
  122. package/lib/odspDriverUrlResolver.js.map +1 -1
  123. package/lib/odspDriverUrlResolverForShareLink.js.map +1 -1
  124. package/lib/odspError.d.ts +1 -1
  125. package/lib/odspError.d.ts.map +1 -1
  126. package/lib/odspFluidFileLink.js.map +1 -1
  127. package/lib/odspSnapshotParser.js +1 -1
  128. package/lib/odspSnapshotParser.js.map +1 -1
  129. package/lib/odspUtils.js.map +1 -1
  130. package/lib/opsCaching.js.map +1 -1
  131. package/lib/packageVersion.d.ts +1 -1
  132. package/lib/packageVersion.js +1 -1
  133. package/lib/packageVersion.js.map +1 -1
  134. package/lib/retryErrorsStorageAdapter.d.ts.map +1 -1
  135. package/lib/retryErrorsStorageAdapter.js.map +1 -1
  136. package/lib/retryUtils.js +1 -1
  137. package/lib/retryUtils.js.map +1 -1
  138. package/lib/vroom.js.map +1 -1
  139. package/lib/zipItDataRepresentationUtils.d.ts.map +1 -1
  140. package/lib/zipItDataRepresentationUtils.js +12 -3
  141. package/lib/zipItDataRepresentationUtils.js.map +1 -1
  142. package/package.json +14 -13
  143. package/src/compactSnapshotParser.ts +2 -2
  144. package/src/contracts.ts +4 -5
  145. package/src/createFile.ts +2 -2
  146. package/src/epochTracker.ts +9 -10
  147. package/src/fetchSnapshot.ts +10 -10
  148. package/src/getFileLink.ts +10 -10
  149. package/src/getQueryString.ts +1 -1
  150. package/src/getUrlAndHeadersWithAuth.ts +1 -1
  151. package/src/odspCache.ts +2 -2
  152. package/src/odspDeltaStorageService.ts +4 -5
  153. package/src/odspDocumentDeltaConnection.ts +2 -2
  154. package/src/odspDocumentService.ts +5 -5
  155. package/src/odspDocumentServiceFactoryCore.ts +13 -1
  156. package/src/odspDocumentStorageManager.ts +25 -18
  157. package/src/odspDriverUrlResolver.ts +2 -2
  158. package/src/odspDriverUrlResolverForShareLink.ts +1 -1
  159. package/src/odspSnapshotParser.ts +2 -2
  160. package/src/odspUtils.ts +6 -6
  161. package/src/opsCaching.ts +2 -2
  162. package/src/packageVersion.ts +1 -1
  163. package/src/retryErrorsStorageAdapter.ts +1 -1
  164. package/src/vroom.ts +1 -1
  165. package/src/zipItDataRepresentationUtils.ts +15 -13
@@ -49,7 +49,7 @@ async function createNewFluidFile(getStorageToken, newFileInfo, logger, createNe
49
49
  sharingLink = content.sharingLink;
50
50
  sharingLinkErrorReason = content.sharingLinkErrorReason;
51
51
  }
52
- const odspUrl = createOdspUrl_1.createOdspUrl(Object.assign(Object.assign({}, newFileInfo), { itemId, dataStorePath: "/" }));
52
+ const odspUrl = (0, createOdspUrl_1.createOdspUrl)(Object.assign(Object.assign({}, newFileInfo), { itemId, dataStorePath: "/" }));
53
53
  const resolver = new odspDriverUrlResolver_1.OdspDriverUrlResolver();
54
54
  const odspResolvedUrl = await resolver.resolve({ url: odspUrl });
55
55
  fileEntry.docId = odspResolvedUrl.hashedDocumentId;
@@ -64,11 +64,11 @@ async function createNewFluidFile(getStorageToken, newFileInfo, logger, createNe
64
64
  };
65
65
  }
66
66
  if (createNewSummary !== undefined && createNewCaching) {
67
- common_utils_1.assert(summaryHandle !== undefined, 0x203 /* "Summary handle is undefined" */);
67
+ (0, common_utils_1.assert)(summaryHandle !== undefined, 0x203 /* "Summary handle is undefined" */);
68
68
  // converting summary and getting sequence number
69
- const snapshot = createNewUtils_1.convertCreateNewSummaryTreeToTreeAndBlobs(createNewSummary, summaryHandle);
69
+ const snapshot = (0, createNewUtils_1.convertCreateNewSummaryTreeToTreeAndBlobs)(createNewSummary, summaryHandle);
70
70
  // caching the converted summary
71
- await epochTracker.put(odspUtils_1.createCacheSnapshotKey(odspResolvedUrl), snapshot);
71
+ await epochTracker.put((0, odspUtils_1.createCacheSnapshotKey)(odspResolvedUrl), snapshot);
72
72
  }
73
73
  return odspResolvedUrl;
74
74
  }
@@ -77,13 +77,13 @@ async function createNewEmptyFluidFile(getStorageToken, newFileInfo, logger, epo
77
77
  const filePath = newFileInfo.filePath ? encodeURIComponent(`/${newFileInfo.filePath}`) : "";
78
78
  // add .tmp extension to empty file (host is expected to rename)
79
79
  const encodedFilename = encodeURIComponent(`${newFileInfo.filename}.tmp`);
80
- const initialUrl = `${odspUrlHelper_1.getApiRoot(odspUtils_1.getOrigin(newFileInfo.siteUrl))}/drives/${newFileInfo.driveId}/items/root:/${filePath}/${encodedFilename}:/content?@name.conflictBehavior=rename&select=id,name,parentReference`;
81
- return odspUtils_1.getWithRetryForTokenRefresh(async (options) => {
80
+ const initialUrl = `${(0, odspUrlHelper_1.getApiRoot)((0, odspUtils_1.getOrigin)(newFileInfo.siteUrl))}/drives/${newFileInfo.driveId}/items/root:/${filePath}/${encodedFilename}:/content?@name.conflictBehavior=rename&select=id,name,parentReference`;
81
+ return (0, odspUtils_1.getWithRetryForTokenRefresh)(async (options) => {
82
82
  const storageToken = await getStorageToken(options, "CreateNewFile");
83
83
  return telemetry_utils_1.PerformanceEvent.timedExecAsync(logger, { eventName: "createNewEmptyFile" }, async (event) => {
84
- const { url, headers } = getUrlAndHeadersWithAuth_1.getUrlAndHeadersWithAuth(initialUrl, storageToken, forceAccessTokenViaAuthorizationHeader);
84
+ const { url, headers } = (0, getUrlAndHeadersWithAuth_1.getUrlAndHeadersWithAuth)(initialUrl, storageToken, forceAccessTokenViaAuthorizationHeader);
85
85
  headers["Content-Type"] = "application/json";
86
- const fetchResponse = await retryUtils_1.runWithRetry(async () => epochTracker.fetchAndParseAsJSON(url, {
86
+ const fetchResponse = await (0, retryUtils_1.runWithRetry)(async () => epochTracker.fetchAndParseAsJSON(url, {
87
87
  body: undefined,
88
88
  headers,
89
89
  method: "PUT",
@@ -103,17 +103,17 @@ exports.createNewEmptyFluidFile = createNewEmptyFluidFile;
103
103
  async function createNewFluidFileFromSummary(getStorageToken, newFileInfo, logger, createNewSummary, epochTracker, forceAccessTokenViaAuthorizationHeader) {
104
104
  const filePath = newFileInfo.filePath ? encodeURIComponent(`/${newFileInfo.filePath}`) : "";
105
105
  const encodedFilename = encodeURIComponent(newFileInfo.filename);
106
- const baseUrl = `${odspUrlHelper_1.getApiRoot(odspUtils_1.getOrigin(newFileInfo.siteUrl))}/drives/${newFileInfo.driveId}/items/root:` +
106
+ const baseUrl = `${(0, odspUrlHelper_1.getApiRoot)((0, odspUtils_1.getOrigin)(newFileInfo.siteUrl))}/drives/${newFileInfo.driveId}/items/root:` +
107
107
  `${filePath}/${encodedFilename}`;
108
108
  const containerSnapshot = convertSummaryIntoContainerSnapshot(createNewSummary);
109
109
  const initialUrl = `${baseUrl}:/opStream/snapshots/snapshot${newFileInfo.createLinkType ?
110
110
  `?createLinkType=${newFileInfo.createLinkType}` : ""}`;
111
- return odspUtils_1.getWithRetryForTokenRefresh(async (options) => {
111
+ return (0, odspUtils_1.getWithRetryForTokenRefresh)(async (options) => {
112
112
  const storageToken = await getStorageToken(options, "CreateNewFile");
113
113
  return telemetry_utils_1.PerformanceEvent.timedExecAsync(logger, { eventName: "createNewFile" }, async (event) => {
114
- const { url, headers } = getUrlAndHeadersWithAuth_1.getUrlAndHeadersWithAuth(initialUrl, storageToken, forceAccessTokenViaAuthorizationHeader);
114
+ const { url, headers } = (0, getUrlAndHeadersWithAuth_1.getUrlAndHeadersWithAuth)(initialUrl, storageToken, forceAccessTokenViaAuthorizationHeader);
115
115
  headers["Content-Type"] = "application/json";
116
- const fetchResponse = await retryUtils_1.runWithRetry(async () => epochTracker.fetchAndParseAsJSON(url, {
116
+ const fetchResponse = await (0, retryUtils_1.runWithRetry)(async () => epochTracker.fetchAndParseAsJSON(url, {
117
117
  body: JSON.stringify(containerSnapshot),
118
118
  headers,
119
119
  method: "POST",
@@ -135,7 +135,7 @@ function convertSummaryIntoContainerSnapshot(createNewSummary) {
135
135
  if (!(appSummary && protocolSummary)) {
136
136
  throw new Error("App and protocol summary required for create new path!!");
137
137
  }
138
- const documentAttributes = driver_utils_1.getDocAttributesFromProtocolSummary(protocolSummary);
138
+ const documentAttributes = (0, driver_utils_1.getDocAttributesFromProtocolSummary)(protocolSummary);
139
139
  const attributesSummaryBlob = {
140
140
  type: protocol_definitions_1.SummaryType.Blob,
141
141
  content: JSON.stringify(documentAttributes),
@@ -182,7 +182,7 @@ function convertSummaryToSnapshotTreeForCreateNew(summary) {
182
182
  }
183
183
  case protocol_definitions_1.SummaryType.Blob: {
184
184
  const content = typeof summaryObject.content === "string" ?
185
- summaryObject.content : common_utils_1.Uint8ArrayToString(summaryObject.content, "base64");
185
+ summaryObject.content : (0, common_utils_1.Uint8ArrayToString)(summaryObject.content, "base64");
186
186
  const encoding = typeof summaryObject.content === "string" ? "utf-8" : "base64";
187
187
  value = {
188
188
  type: "blob",
@@ -200,7 +200,7 @@ function convertSummaryToSnapshotTreeForCreateNew(summary) {
200
200
  }
201
201
  const entry = {
202
202
  path: encodeURIComponent(key),
203
- type: protocol_base_1.getGitType(summaryObject),
203
+ type: (0, protocol_base_1.getGitType)(summaryObject),
204
204
  value,
205
205
  unreferenced,
206
206
  };
@@ -1 +1 @@
1
- {"version":3,"file":"createFile.js","sourceRoot":"","sources":["../src/createFile.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,+DAA0E;AAC1E,+DAAsG;AACtG,iEAA2D;AAC3D,+EAA+F;AAE/F,qEAAmE;AACnE,qFAKiD;AACjD,2EAAqE;AAQrE,yEAAsE;AACtE,2CAMqB;AACrB,mDAAgD;AAChD,mDAA6C;AAE7C,mEAAgE;AAChE,qDAA6E;AAC7E,6CAA4C;AAC5C,qDAA+D;AAE/D,MAAM,iBAAiB,GAAG,CAAC,QAAgB,EAAW,EAAE;IACpD,MAAM,iBAAiB,GAAG,gBAAgB,CAAC;IAC3C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AAO,EAAE,QAAQ,CAAC,CAAC;gBAChF,MAAM,QAAQ,GAAG,OAAO,aAAa,CAAC,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ,CAAC;gBAEhF,KAAK,GAAG;oBACJ,IAAI,EAAE,MAAM;oBACZ,OAAO;oBACP,QAAQ;iBACX,CAAC;gBACF,MAAM;aACT;YACD,KAAK,kCAAW,CAAC,MAAM,CAAC,CAAC;gBACrB,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;aACtE;YACD,OAAO,CAAC,CAAC;gBACL,MAAM,IAAI,KAAK,CAAC,qBAAqB,aAAa,CAAC,IAAI,EAAE,CAAC,CAAC;aAC9D;SACJ;QAED,MAAM,KAAK,GAAyB;YAChC,IAAI,EAAE,kBAAkB,CAAC,GAAG,CAAC;YAC7B,IAAI,EAAE,0BAAU,CAAC,aAAa,CAAC;YAC/B,KAAK;YACL,YAAY;SACf,CAAC;QACF,MAAA,YAAY,CAAC,OAAO,0CAAE,IAAI,CAAC,KAAK,EAAE;KACrC;IAED,OAAO,YAAY,CAAC;AACxB,CAAC;AApDD,4FAoDC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { assert, Uint8ArrayToString } from \"@fluidframework/common-utils\";\nimport { getDocAttributesFromProtocolSummary, NonRetryableError } from \"@fluidframework/driver-utils\";\nimport { getGitType } from \"@fluidframework/protocol-base\";\nimport { SummaryType, ISummaryTree, ISummaryBlob } from \"@fluidframework/protocol-definitions\";\nimport { ITelemetryLogger } from \"@fluidframework/common-definitions\";\nimport { PerformanceEvent } from \"@fluidframework/telemetry-utils\";\nimport {\n IFileEntry,\n InstrumentedStorageTokenFetcher,\n IOdspResolvedUrl,\n OdspErrorType,\n} from \"@fluidframework/odsp-driver-definitions\";\nimport { DriverErrorType } from \"@fluidframework/driver-definitions\";\nimport {\n IOdspSummaryTree,\n OdspSummaryTreeValue,\n OdspSummaryTreeEntry,\n ICreateFileResponse,\n IOdspSummaryPayload,\n} from \"./contracts\";\nimport { getUrlAndHeadersWithAuth } from \"./getUrlAndHeadersWithAuth\";\nimport {\n createCacheSnapshotKey,\n getWithRetryForTokenRefresh,\n INewFileInfo,\n getOrigin,\n ISnapshotContents,\n} from \"./odspUtils\";\nimport { createOdspUrl } from \"./createOdspUrl\";\nimport { getApiRoot } from \"./odspUrlHelper\";\nimport { EpochTracker } from \"./epochTracker\";\nimport { OdspDriverUrlResolver } from \"./odspDriverUrlResolver\";\nimport { convertCreateNewSummaryTreeToTreeAndBlobs } from \"./createNewUtils\";\nimport { runWithRetry } from \"./retryUtils\";\nimport { pkgVersion as driverVersion } from \"./packageVersion\";\n\nconst isInvalidFileName = (fileName: string): boolean => {\n const invalidCharsRegex = /[\"*/:<>?\\\\|]+/g;\n return !!fileName.match(invalidCharsRegex);\n};\n\n/**\n * Creates a new Fluid file.\n * Returns resolved url\n */\nexport async function createNewFluidFile(\n getStorageToken: InstrumentedStorageTokenFetcher,\n newFileInfo: INewFileInfo,\n logger: ITelemetryLogger,\n createNewSummary: ISummaryTree | undefined,\n epochTracker: EpochTracker,\n fileEntry: IFileEntry,\n createNewCaching: boolean,\n forceAccessTokenViaAuthorizationHeader: boolean,\n): Promise<IOdspResolvedUrl> {\n // Check for valid filename before the request to create file is actually made.\n if (isInvalidFileName(newFileInfo.filename)) {\n throw new NonRetryableError(\n // pre-0.58 error message: Invalid filename\n \"Invalid filename for createNew\", OdspErrorType.invalidFileNameError, { driverVersion });\n }\n\n let itemId: string;\n let summaryHandle: string = \"\";\n let sharingLink: string | undefined;\n let sharingLinkErrorReason: string | undefined;\n if (createNewSummary === undefined) {\n itemId = await createNewEmptyFluidFile(\n getStorageToken, newFileInfo, logger, epochTracker, forceAccessTokenViaAuthorizationHeader);\n } else {\n const content = await createNewFluidFileFromSummary(\n getStorageToken,\n newFileInfo,\n logger,\n createNewSummary,\n epochTracker,\n forceAccessTokenViaAuthorizationHeader,\n );\n itemId = content.itemId;\n summaryHandle = content.id;\n sharingLink = content.sharingLink;\n sharingLinkErrorReason = content.sharingLinkErrorReason;\n }\n\n const odspUrl = createOdspUrl({... newFileInfo, itemId, dataStorePath: \"/\"});\n const resolver = new OdspDriverUrlResolver();\n const odspResolvedUrl = await resolver.resolve({ url: odspUrl });\n fileEntry.docId = odspResolvedUrl.hashedDocumentId;\n fileEntry.resolvedUrl = odspResolvedUrl;\n\n if(sharingLink || sharingLinkErrorReason) {\n odspResolvedUrl.shareLinkInfo = {\n createLink: {\n type: newFileInfo.createLinkType,\n link: sharingLink,\n error: sharingLinkErrorReason,\n },\n };\n }\n\n if (createNewSummary !== undefined && createNewCaching) {\n assert(summaryHandle !== undefined, 0x203 /* \"Summary handle is undefined\" */);\n // converting summary and getting sequence number\n const snapshot: ISnapshotContents = convertCreateNewSummaryTreeToTreeAndBlobs(createNewSummary, summaryHandle);\n // caching the converted summary\n await epochTracker.put(createCacheSnapshotKey(odspResolvedUrl), snapshot);\n }\n return odspResolvedUrl;\n}\n\nexport async function createNewEmptyFluidFile(\n getStorageToken: InstrumentedStorageTokenFetcher,\n newFileInfo: INewFileInfo,\n logger: ITelemetryLogger,\n epochTracker: EpochTracker,\n forceAccessTokenViaAuthorizationHeader: boolean,\n): Promise<string> {\n const filePath = newFileInfo.filePath ? encodeURIComponent(`/${newFileInfo.filePath}`) : \"\";\n // add .tmp extension to empty file (host is expected to rename)\n const encodedFilename = encodeURIComponent(`${newFileInfo.filename}.tmp`);\n const initialUrl =\n `${getApiRoot(getOrigin(newFileInfo.siteUrl))}/drives/${newFileInfo.driveId}/items/root:/${filePath\n }/${encodedFilename}:/content?@name.conflictBehavior=rename&select=id,name,parentReference`;\n\n return getWithRetryForTokenRefresh(async (options) => {\n const storageToken = await getStorageToken(options, \"CreateNewFile\");\n\n return PerformanceEvent.timedExecAsync(\n logger,\n { eventName: \"createNewEmptyFile\" },\n async (event) => {\n const { url, headers } = getUrlAndHeadersWithAuth(\n initialUrl, storageToken, forceAccessTokenViaAuthorizationHeader);\n headers[\"Content-Type\"] = \"application/json\";\n\n const fetchResponse = await runWithRetry(\n async () => epochTracker.fetchAndParseAsJSON<ICreateFileResponse>(\n url,\n {\n body: undefined,\n headers,\n method: \"PUT\",\n },\n \"createFile\",\n ),\n \"createFile\",\n logger,\n );\n\n const content = fetchResponse.content;\n if (!content || !content.id) {\n throw new NonRetryableError(\n // pre-0.58 error message: ODSP CreateFile call returned no item ID\n \"ODSP CreateFile call returned no item ID (for empty file)\",\n DriverErrorType.incorrectServerResponse,\n { driverVersion });\n }\n event.end({\n headers: Object.keys(headers).length !== 0 ? true : undefined,\n ...fetchResponse.propsToLog,\n });\n return content.id;\n },\n { end: true, cancel: \"error\" });\n });\n}\n\nexport async function createNewFluidFileFromSummary(\n getStorageToken: InstrumentedStorageTokenFetcher,\n newFileInfo: INewFileInfo,\n logger: ITelemetryLogger,\n createNewSummary: ISummaryTree,\n epochTracker: EpochTracker,\n forceAccessTokenViaAuthorizationHeader: boolean,\n): Promise<ICreateFileResponse> {\n const filePath = newFileInfo.filePath ? encodeURIComponent(`/${newFileInfo.filePath}`) : \"\";\n const encodedFilename = encodeURIComponent(newFileInfo.filename);\n const baseUrl =\n `${getApiRoot(getOrigin(newFileInfo.siteUrl))}/drives/${newFileInfo.driveId}/items/root:` +\n `${filePath}/${encodedFilename}`;\n\n const containerSnapshot = convertSummaryIntoContainerSnapshot(createNewSummary);\n const initialUrl = `${baseUrl}:/opStream/snapshots/snapshot${newFileInfo.createLinkType ?\n `?createLinkType=${newFileInfo.createLinkType}` : \"\"}`;\n\n return getWithRetryForTokenRefresh(async (options) => {\n const storageToken = await getStorageToken(options, \"CreateNewFile\");\n\n return PerformanceEvent.timedExecAsync(\n logger,\n { eventName: \"createNewFile\" },\n async (event) => {\n const { url, headers } = getUrlAndHeadersWithAuth(\n initialUrl, storageToken, forceAccessTokenViaAuthorizationHeader);\n headers[\"Content-Type\"] = \"application/json\";\n\n const fetchResponse = await runWithRetry(\n async () => epochTracker.fetchAndParseAsJSON<ICreateFileResponse>(\n url,\n {\n body: JSON.stringify(containerSnapshot),\n headers,\n method: \"POST\",\n },\n \"createFile\",\n ),\n \"createFile\",\n logger,\n );\n\n const content = fetchResponse.content;\n if (!content || !content.itemId) {\n throw new NonRetryableError(\n \"ODSP CreateFile call returned no item ID\",\n DriverErrorType.incorrectServerResponse,\n { driverVersion });\n }\n event.end({\n headers: Object.keys(headers).length !== 0 ? true : undefined,\n attempts: options.refresh ? 2 : 1,\n ...fetchResponse.propsToLog,\n });\n return content;\n },\n );\n });\n}\n\nfunction convertSummaryIntoContainerSnapshot(createNewSummary: ISummaryTree) {\n const appSummary = createNewSummary.tree[\".app\"] as ISummaryTree;\n const protocolSummary = createNewSummary.tree[\".protocol\"] as ISummaryTree;\n if (!(appSummary && protocolSummary)) {\n throw new Error(\"App and protocol summary required for create new path!!\");\n }\n const documentAttributes = getDocAttributesFromProtocolSummary(protocolSummary);\n const attributesSummaryBlob: ISummaryBlob = {\n type: SummaryType.Blob,\n content: JSON.stringify(documentAttributes),\n };\n protocolSummary.tree.attributes = attributesSummaryBlob;\n const convertedCreateNewSummary: ISummaryTree = {\n type: SummaryType.Tree,\n tree: {\n \".protocol\": protocolSummary,\n \".app\": appSummary,\n },\n };\n const snapshotTree = convertSummaryToSnapshotTreeForCreateNew(convertedCreateNewSummary);\n const snapshot: IOdspSummaryPayload = {\n entries: snapshotTree.entries ?? [],\n message: \"app\",\n sequenceNumber: documentAttributes.sequenceNumber,\n type: \"container\",\n };\n return snapshot;\n}\n\n/**\n * Converts a summary tree to ODSP tree\n */\nexport function convertSummaryToSnapshotTreeForCreateNew(summary: ISummaryTree): IOdspSummaryTree {\n const snapshotTree: IOdspSummaryTree = {\n type: \"tree\",\n entries: [],\n };\n\n const keys = Object.keys(summary.tree);\n for (const key of keys) {\n const summaryObject = summary.tree[key];\n\n let value: OdspSummaryTreeValue;\n // Tracks if an entry is unreferenced. Currently, only tree entries can be marked as unreferenced. If the\n // property is not present, the tree entry is considered referenced. If the property is present and is true,\n // the tree entry is considered unreferenced.\n let unreferenced: true | undefined;\n\n switch (summaryObject.type) {\n case SummaryType.Tree: {\n value = convertSummaryToSnapshotTreeForCreateNew(summaryObject);\n unreferenced = summaryObject.unreferenced;\n break;\n }\n case SummaryType.Blob: {\n const content = typeof summaryObject.content === \"string\" ?\n summaryObject.content : Uint8ArrayToString(summaryObject.content, \"base64\");\n const encoding = typeof summaryObject.content === \"string\" ? \"utf-8\" : \"base64\";\n\n value = {\n type: \"blob\",\n content,\n encoding,\n };\n break;\n }\n case SummaryType.Handle: {\n throw new Error(\"No handle should be present for first summary!!\");\n }\n default: {\n throw new Error(`Unknown tree type ${summaryObject.type}`);\n }\n }\n\n const entry: OdspSummaryTreeEntry = {\n path: encodeURIComponent(key),\n type: getGitType(summaryObject),\n value,\n unreferenced,\n };\n snapshotTree.entries?.push(entry);\n }\n\n return snapshotTree;\n}\n"]}
1
+ {"version":3,"file":"createFile.js","sourceRoot":"","sources":["../src/createFile.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,+DAA0E;AAC1E,+DAAsG;AACtG,iEAA2D;AAC3D,+EAA+F;AAE/F,qEAAmE;AACnE,qFAKiD;AACjD,2EAAqE;AAQrE,yEAAsE;AACtE,2CAMqB;AACrB,mDAAgD;AAChD,mDAA6C;AAE7C,mEAAgE;AAChE,qDAA6E;AAC7E,6CAA4C;AAC5C,qDAA+D;AAE/D,MAAM,iBAAiB,GAAG,CAAC,QAAgB,EAAW,EAAE;IACpD,MAAM,iBAAiB,GAAG,gBAAgB,CAAC;IAC3C,OAAO,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC;AAC/C,CAAC,CAAC;AAEF;;;GAGG;AACI,KAAK,UAAU,kBAAkB,CACpC,eAAgD,EAChD,WAAyB,EACzB,MAAwB,EACxB,gBAA0C,EAC1C,YAA0B,EAC1B,SAAqB,EACr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AC,OAAO,CAAC,CAAC,CAAC,QAAQ,CAAC;gBAEhF,KAAK,GAAG;oBACJ,IAAI,EAAE,MAAM;oBACZ,OAAO;oBACP,QAAQ;iBACX,CAAC;gBACF,MAAM;aACT;YACD,KAAK,kCAAW,CAAC,MAAM,CAAC,CAAC;gBACrB,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;aACtE;YACD,OAAO,CAAC,CAAC;gBACL,MAAM,IAAI,KAAK,CAAC,qBAAqB,aAAa,CAAC,IAAI,EAAE,CAAC,CAAC;aAC9D;SACJ;QAED,MAAM,KAAK,GAAyB;YAChC,IAAI,EAAE,kBAAkB,CAAC,GAAG,CAAC;YAC7B,IAAI,EAAE,IAAA,0BAAU,EAAC,aAAa,CAAC;YAC/B,KAAK;YACL,YAAY;SACf,CAAC;QACF,MAAA,YAAY,CAAC,OAAO,0CAAE,IAAI,CAAC,KAAK,CAAC,CAAC;KACrC;IAED,OAAO,YAAY,CAAC;AACxB,CAAC;AApDD,4FAoDC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { assert, Uint8ArrayToString } from \"@fluidframework/common-utils\";\nimport { getDocAttributesFromProtocolSummary, NonRetryableError } from \"@fluidframework/driver-utils\";\nimport { getGitType } from \"@fluidframework/protocol-base\";\nimport { SummaryType, ISummaryTree, ISummaryBlob } from \"@fluidframework/protocol-definitions\";\nimport { ITelemetryLogger } from \"@fluidframework/common-definitions\";\nimport { PerformanceEvent } from \"@fluidframework/telemetry-utils\";\nimport {\n IFileEntry,\n InstrumentedStorageTokenFetcher,\n IOdspResolvedUrl,\n OdspErrorType,\n} from \"@fluidframework/odsp-driver-definitions\";\nimport { DriverErrorType } from \"@fluidframework/driver-definitions\";\nimport {\n IOdspSummaryTree,\n OdspSummaryTreeValue,\n OdspSummaryTreeEntry,\n ICreateFileResponse,\n IOdspSummaryPayload,\n} from \"./contracts\";\nimport { getUrlAndHeadersWithAuth } from \"./getUrlAndHeadersWithAuth\";\nimport {\n createCacheSnapshotKey,\n getWithRetryForTokenRefresh,\n INewFileInfo,\n getOrigin,\n ISnapshotContents,\n} from \"./odspUtils\";\nimport { createOdspUrl } from \"./createOdspUrl\";\nimport { getApiRoot } from \"./odspUrlHelper\";\nimport { EpochTracker } from \"./epochTracker\";\nimport { OdspDriverUrlResolver } from \"./odspDriverUrlResolver\";\nimport { convertCreateNewSummaryTreeToTreeAndBlobs } from \"./createNewUtils\";\nimport { runWithRetry } from \"./retryUtils\";\nimport { pkgVersion as driverVersion } from \"./packageVersion\";\n\nconst isInvalidFileName = (fileName: string): boolean => {\n const invalidCharsRegex = /[\"*/:<>?\\\\|]+/g;\n return !!fileName.match(invalidCharsRegex);\n};\n\n/**\n * Creates a new Fluid file.\n * Returns resolved url\n */\nexport async function createNewFluidFile(\n getStorageToken: InstrumentedStorageTokenFetcher,\n newFileInfo: INewFileInfo,\n logger: ITelemetryLogger,\n createNewSummary: ISummaryTree | undefined,\n epochTracker: EpochTracker,\n fileEntry: IFileEntry,\n createNewCaching: boolean,\n forceAccessTokenViaAuthorizationHeader: boolean,\n): Promise<IOdspResolvedUrl> {\n // Check for valid filename before the request to create file is actually made.\n if (isInvalidFileName(newFileInfo.filename)) {\n throw new NonRetryableError(\n // pre-0.58 error message: Invalid filename\n \"Invalid filename for createNew\", OdspErrorType.invalidFileNameError, { driverVersion });\n }\n\n let itemId: string;\n let summaryHandle: string = \"\";\n let sharingLink: string | undefined;\n let sharingLinkErrorReason: string | undefined;\n if (createNewSummary === undefined) {\n itemId = await createNewEmptyFluidFile(\n getStorageToken, newFileInfo, logger, epochTracker, forceAccessTokenViaAuthorizationHeader);\n } else {\n const content = await createNewFluidFileFromSummary(\n getStorageToken,\n newFileInfo,\n logger,\n createNewSummary,\n epochTracker,\n forceAccessTokenViaAuthorizationHeader,\n );\n itemId = content.itemId;\n summaryHandle = content.id;\n sharingLink = content.sharingLink;\n sharingLinkErrorReason = content.sharingLinkErrorReason;\n }\n\n const odspUrl = createOdspUrl({ ... newFileInfo, itemId, dataStorePath: \"/\" });\n const resolver = new OdspDriverUrlResolver();\n const odspResolvedUrl = await resolver.resolve({ url: odspUrl });\n fileEntry.docId = odspResolvedUrl.hashedDocumentId;\n fileEntry.resolvedUrl = odspResolvedUrl;\n\n if (sharingLink || sharingLinkErrorReason) {\n odspResolvedUrl.shareLinkInfo = {\n createLink: {\n type: newFileInfo.createLinkType,\n link: sharingLink,\n error: sharingLinkErrorReason,\n },\n };\n }\n\n if (createNewSummary !== undefined && createNewCaching) {\n assert(summaryHandle !== undefined, 0x203 /* \"Summary handle is undefined\" */);\n // converting summary and getting sequence number\n const snapshot: ISnapshotContents = convertCreateNewSummaryTreeToTreeAndBlobs(createNewSummary, summaryHandle);\n // caching the converted summary\n await epochTracker.put(createCacheSnapshotKey(odspResolvedUrl), snapshot);\n }\n return odspResolvedUrl;\n}\n\nexport async function createNewEmptyFluidFile(\n getStorageToken: InstrumentedStorageTokenFetcher,\n newFileInfo: INewFileInfo,\n logger: ITelemetryLogger,\n epochTracker: EpochTracker,\n forceAccessTokenViaAuthorizationHeader: boolean,\n): Promise<string> {\n const filePath = newFileInfo.filePath ? encodeURIComponent(`/${newFileInfo.filePath}`) : \"\";\n // add .tmp extension to empty file (host is expected to rename)\n const encodedFilename = encodeURIComponent(`${newFileInfo.filename}.tmp`);\n const initialUrl =\n `${getApiRoot(getOrigin(newFileInfo.siteUrl))}/drives/${newFileInfo.driveId}/items/root:/${filePath\n }/${encodedFilename}:/content?@name.conflictBehavior=rename&select=id,name,parentReference`;\n\n return getWithRetryForTokenRefresh(async (options) => {\n const storageToken = await getStorageToken(options, \"CreateNewFile\");\n\n return PerformanceEvent.timedExecAsync(\n logger,\n { eventName: \"createNewEmptyFile\" },\n async (event) => {\n const { url, headers } = getUrlAndHeadersWithAuth(\n initialUrl, storageToken, forceAccessTokenViaAuthorizationHeader);\n headers[\"Content-Type\"] = \"application/json\";\n\n const fetchResponse = await runWithRetry(\n async () => epochTracker.fetchAndParseAsJSON<ICreateFileResponse>(\n url,\n {\n body: undefined,\n headers,\n method: \"PUT\",\n },\n \"createFile\",\n ),\n \"createFile\",\n logger,\n );\n\n const content = fetchResponse.content;\n if (!content || !content.id) {\n throw new NonRetryableError(\n // pre-0.58 error message: ODSP CreateFile call returned no item ID\n \"ODSP CreateFile call returned no item ID (for empty file)\",\n DriverErrorType.incorrectServerResponse,\n { driverVersion });\n }\n event.end({\n headers: Object.keys(headers).length !== 0 ? true : undefined,\n ...fetchResponse.propsToLog,\n });\n return content.id;\n },\n { end: true, cancel: \"error\" });\n });\n}\n\nexport async function createNewFluidFileFromSummary(\n getStorageToken: InstrumentedStorageTokenFetcher,\n newFileInfo: INewFileInfo,\n logger: ITelemetryLogger,\n createNewSummary: ISummaryTree,\n epochTracker: EpochTracker,\n forceAccessTokenViaAuthorizationHeader: boolean,\n): Promise<ICreateFileResponse> {\n const filePath = newFileInfo.filePath ? encodeURIComponent(`/${newFileInfo.filePath}`) : \"\";\n const encodedFilename = encodeURIComponent(newFileInfo.filename);\n const baseUrl =\n `${getApiRoot(getOrigin(newFileInfo.siteUrl))}/drives/${newFileInfo.driveId}/items/root:` +\n `${filePath}/${encodedFilename}`;\n\n const containerSnapshot = convertSummaryIntoContainerSnapshot(createNewSummary);\n const initialUrl = `${baseUrl}:/opStream/snapshots/snapshot${newFileInfo.createLinkType ?\n `?createLinkType=${newFileInfo.createLinkType}` : \"\"}`;\n\n return getWithRetryForTokenRefresh(async (options) => {\n const storageToken = await getStorageToken(options, \"CreateNewFile\");\n\n return PerformanceEvent.timedExecAsync(\n logger,\n { eventName: \"createNewFile\" },\n async (event) => {\n const { url, headers } = getUrlAndHeadersWithAuth(\n initialUrl, storageToken, forceAccessTokenViaAuthorizationHeader);\n headers[\"Content-Type\"] = \"application/json\";\n\n const fetchResponse = await runWithRetry(\n async () => epochTracker.fetchAndParseAsJSON<ICreateFileResponse>(\n url,\n {\n body: JSON.stringify(containerSnapshot),\n headers,\n method: \"POST\",\n },\n \"createFile\",\n ),\n \"createFile\",\n logger,\n );\n\n const content = fetchResponse.content;\n if (!content || !content.itemId) {\n throw new NonRetryableError(\n \"ODSP CreateFile call returned no item ID\",\n DriverErrorType.incorrectServerResponse,\n { driverVersion });\n }\n event.end({\n headers: Object.keys(headers).length !== 0 ? true : undefined,\n attempts: options.refresh ? 2 : 1,\n ...fetchResponse.propsToLog,\n });\n return content;\n },\n );\n });\n}\n\nfunction convertSummaryIntoContainerSnapshot(createNewSummary: ISummaryTree) {\n const appSummary = createNewSummary.tree[\".app\"] as ISummaryTree;\n const protocolSummary = createNewSummary.tree[\".protocol\"] as ISummaryTree;\n if (!(appSummary && protocolSummary)) {\n throw new Error(\"App and protocol summary required for create new path!!\");\n }\n const documentAttributes = getDocAttributesFromProtocolSummary(protocolSummary);\n const attributesSummaryBlob: ISummaryBlob = {\n type: SummaryType.Blob,\n content: JSON.stringify(documentAttributes),\n };\n protocolSummary.tree.attributes = attributesSummaryBlob;\n const convertedCreateNewSummary: ISummaryTree = {\n type: SummaryType.Tree,\n tree: {\n \".protocol\": protocolSummary,\n \".app\": appSummary,\n },\n };\n const snapshotTree = convertSummaryToSnapshotTreeForCreateNew(convertedCreateNewSummary);\n const snapshot: IOdspSummaryPayload = {\n entries: snapshotTree.entries ?? [],\n message: \"app\",\n sequenceNumber: documentAttributes.sequenceNumber,\n type: \"container\",\n };\n return snapshot;\n}\n\n/**\n * Converts a summary tree to ODSP tree\n */\nexport function convertSummaryToSnapshotTreeForCreateNew(summary: ISummaryTree): IOdspSummaryTree {\n const snapshotTree: IOdspSummaryTree = {\n type: \"tree\",\n entries: [],\n };\n\n const keys = Object.keys(summary.tree);\n for (const key of keys) {\n const summaryObject = summary.tree[key];\n\n let value: OdspSummaryTreeValue;\n // Tracks if an entry is unreferenced. Currently, only tree entries can be marked as unreferenced. If the\n // property is not present, the tree entry is considered referenced. If the property is present and is true,\n // the tree entry is considered unreferenced.\n let unreferenced: true | undefined;\n\n switch (summaryObject.type) {\n case SummaryType.Tree: {\n value = convertSummaryToSnapshotTreeForCreateNew(summaryObject);\n unreferenced = summaryObject.unreferenced;\n break;\n }\n case SummaryType.Blob: {\n const content = typeof summaryObject.content === \"string\" ?\n summaryObject.content : Uint8ArrayToString(summaryObject.content, \"base64\");\n const encoding = typeof summaryObject.content === \"string\" ? \"utf-8\" : \"base64\";\n\n value = {\n type: \"blob\",\n content,\n encoding,\n };\n break;\n }\n case SummaryType.Handle: {\n throw new Error(\"No handle should be present for first summary!!\");\n }\n default: {\n throw new Error(`Unknown tree type ${summaryObject.type}`);\n }\n }\n\n const entry: OdspSummaryTreeEntry = {\n path: encodeURIComponent(key),\n type: getGitType(summaryObject),\n value,\n unreferenced,\n };\n snapshotTree.entries?.push(entry);\n }\n\n return snapshotTree;\n}\n"]}
@@ -14,7 +14,7 @@ const common_utils_1 = require("@fluidframework/common-utils");
14
14
  */
15
15
  function convertCreateNewSummaryTreeToTreeAndBlobs(summary, treeId) {
16
16
  const protocolSummary = summary.tree[".protocol"];
17
- const documentAttributes = driver_utils_1.getDocAttributesFromProtocolSummary(protocolSummary);
17
+ const documentAttributes = (0, driver_utils_1.getDocAttributesFromProtocolSummary)(protocolSummary);
18
18
  const sequenceNumber = documentAttributes.sequenceNumber;
19
19
  const blobs = new Map();
20
20
  const snapshotTree = convertCreateNewSummaryTreeToTreeAndBlobsCore(summary, blobs);
@@ -45,8 +45,8 @@ function convertCreateNewSummaryTreeToTreeAndBlobsCore(summary, blobs) {
45
45
  }
46
46
  case protocol_definitions_1.SummaryType.Blob: {
47
47
  const contentBuffer = typeof summaryObject.content === "string" ?
48
- common_utils_1.stringToBuffer(summaryObject.content, "utf8") : summaryObject.content;
49
- const blobId = uuid_1.v4();
48
+ (0, common_utils_1.stringToBuffer)(summaryObject.content, "utf8") : summaryObject.content;
49
+ const blobId = (0, uuid_1.v4)();
50
50
  treeNode.blobs[key] = blobId;
51
51
  blobs.set(blobId, contentBuffer);
52
52
  break;
@@ -56,7 +56,7 @@ function convertCreateNewSummaryTreeToTreeAndBlobsCore(summary, blobs) {
56
56
  throw new Error(`No ${summaryObject.type} should be present for detached summary!`);
57
57
  }
58
58
  default: {
59
- common_utils_1.unreachableCase(summaryObject, `Unknown tree type ${summaryObject.type}`);
59
+ (0, common_utils_1.unreachableCase)(summaryObject, `Unknown tree type ${summaryObject.type}`);
60
60
  }
61
61
  }
62
62
  }
@@ -1 +1 @@
1
- {"version":3,"file":"createNewUtils.js","sourceRoot":"","sources":["../src/createNewUtils.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,+BAAkC;AAClC,+EAAgG;AAChG,+DAAmF;AACnF,+DAA+E;AAG/E;;GAEG;AACH,SAAgB,yCAAyC,CAAC,OAAqB,EAAE,MAAc;IAC3F,MAAM,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC,WAAW,CAAiB,CAAC;IAClE,MAAM,kBAAkB,GAAG,kDAAmC,CAAC,eAAe,CAAC,CAAC;IAChF,MAAM,cAAc,GAAG,kBAAkB,CAAC,cAAc,CAAC;IACzD,MAAM,KAAK,GAAG,IAAI,GAAG,EAAuB,CAAC;IAC7C,MAAM,YAAY,GAAG,6CAA6C,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IACnF,YAAY,CAAC,EAAE,GAAG,MAAM,CAAC;IACzB,MAAM,iBAAiB,GAAsB;QACzC,YAAY;QACZ,KAAK;QACL,GAAG,EAAE,EAAE;QACP,cAAc;KACjB,CAAC;IAEF,OAAO,iBAAiB,CAAC;AAC7B,CAAC;AAfD,8FAeC;AAED,SAAS,6CAA6C,CAClD,OAAqB,EACrB,KAA+B;IAE/B,MAAM,QAAQ,GAAkB;QAC5B,KAAK,EAAE,EAAE;QACT,KAAK,EAAE,EAAE;QACT,YAAY,EAAE,OAAO,CAAC,YAAY;KACrC,CAAC;IACF,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IACvC,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE;QACpB,MAAM,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAExC,QAAQ,aAAa,CAAC,IAAI,EAAE;YACxB,KAAK,kCAAW,CAAC,IAAI,CAAC,CAAC;gBACnB,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC;oBACf,6CAA6C,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC;gBACxE,MAAM;aACT;YACD,KAAK,kCAAW,CAAC,IAAI,CAAC,CAAC;gBACnB,MAAM,aAAa,GAAG,OAAO,aAAa,CAAC,OAAO,KAAK,QAAQ,CAAC,CAAC;oBAC7D,6BAAc,CAAC,aAAa,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,OAAO,CAAC;gBAC1E,MAAM,MAAM,GAAG,SAAI,EAAE,CAAC;gBACtB,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC;gBAC7B,KAAK,CAAC,GAAG,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;gBACjC,MAAM;aACT;YACD,KAAK,kCAAW,CAAC,MAAM,CAAC;YACxB,KAAK,kCAAW,CAAC,UAAU,CAAC,CAAC;gBACzB,MAAM,IAAI,KAAK,CAAC,MAAM,aAAa,CAAC,IAAI,0CAA0C,CAAC,CAAC;aACvF;YACD,OAAO,CAAC,CAAC;gBACL,8BAAe,CAAC,aAAa,EAAE,qBAAsB,aAAqB,CAAC,IAAI,EAAE,CAAC,CAAC;aACtF;SACJ;KACJ;IACD,OAAO,QAAQ,CAAC;AACpB,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { v4 as uuid } from \"uuid\";\nimport { ISnapshotTree, ISummaryTree, SummaryType } from \"@fluidframework/protocol-definitions\";\nimport { getDocAttributesFromProtocolSummary } from \"@fluidframework/driver-utils\";\nimport { stringToBuffer, unreachableCase } from \"@fluidframework/common-utils\";\nimport { ISnapshotContents } from \"./odspUtils\";\n\n/**\n * Converts a summary(ISummaryTree) taken in detached container to snapshot tree and blobs\n */\nexport function convertCreateNewSummaryTreeToTreeAndBlobs(summary: ISummaryTree, treeId: string): ISnapshotContents {\n const protocolSummary = summary.tree[\".protocol\"] as ISummaryTree;\n const documentAttributes = getDocAttributesFromProtocolSummary(protocolSummary);\n const sequenceNumber = documentAttributes.sequenceNumber;\n const blobs = new Map<string, ArrayBuffer>();\n const snapshotTree = convertCreateNewSummaryTreeToTreeAndBlobsCore(summary, blobs);\n snapshotTree.id = treeId;\n const snapshotTreeValue: ISnapshotContents = {\n snapshotTree,\n blobs,\n ops: [],\n sequenceNumber,\n };\n\n return snapshotTreeValue;\n}\n\nfunction convertCreateNewSummaryTreeToTreeAndBlobsCore(\n summary: ISummaryTree,\n blobs: Map<string, ArrayBuffer>,\n) {\n const treeNode: ISnapshotTree = {\n blobs: {},\n trees: {},\n unreferenced: summary.unreferenced,\n };\n const keys = Object.keys(summary.tree);\n for (const key of keys) {\n const summaryObject = summary.tree[key];\n\n switch (summaryObject.type) {\n case SummaryType.Tree: {\n treeNode.trees[key] =\n convertCreateNewSummaryTreeToTreeAndBlobsCore(summaryObject, blobs);\n break;\n }\n case SummaryType.Blob: {\n const contentBuffer = typeof summaryObject.content === \"string\" ?\n stringToBuffer(summaryObject.content, \"utf8\") : summaryObject.content;\n const blobId = uuid();\n treeNode.blobs[key] = blobId;\n blobs.set(blobId, contentBuffer);\n break;\n }\n case SummaryType.Handle:\n case SummaryType.Attachment: {\n throw new Error(`No ${summaryObject.type} should be present for detached summary!`);\n }\n default: {\n unreachableCase(summaryObject, `Unknown tree type ${(summaryObject as any).type}`);\n }\n }\n }\n return treeNode;\n}\n"]}
1
+ {"version":3,"file":"createNewUtils.js","sourceRoot":"","sources":["../src/createNewUtils.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,+BAAkC;AAClC,+EAAgG;AACh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,CAAC,CAAC;oBAC7D,IAAA,6BAAc,EAAC,aAAa,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,OAAO,CAAC;gBAC1E,MAAM,MAAM,GAAG,IAAA,SAAI,GAAE,CAAC;gBACtB,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC;gBAC7B,KAAK,CAAC,GAAG,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;gBACjC,MAAM;aACT;YACD,KAAK,kCAAW,CAAC,MAAM,CAAC;YACxB,KAAK,kCAAW,CAAC,UAAU,CAAC,CAAC;gBACzB,MAAM,IAAI,KAAK,CAAC,MAAM,aAAa,CAAC,IAAI,0CAA0C,CAAC,CAAC;aACvF;YACD,OAAO,CAAC,CAAC;gBACL,IAAA,8BAAe,EAAC,aAAa,EAAE,qBAAsB,aAAqB,CAAC,IAAI,EAAE,CAAC,CAAC;aACtF;SACJ;KACJ;IACD,OAAO,QAAQ,CAAC;AACpB,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { v4 as uuid } from \"uuid\";\nimport { ISnapshotTree, ISummaryTree, SummaryType } from \"@fluidframework/protocol-definitions\";\nimport { getDocAttributesFromProtocolSummary } from \"@fluidframework/driver-utils\";\nimport { stringToBuffer, unreachableCase } from \"@fluidframework/common-utils\";\nimport { ISnapshotContents } from \"./odspUtils\";\n\n/**\n * Converts a summary(ISummaryTree) taken in detached container to snapshot tree and blobs\n */\nexport function convertCreateNewSummaryTreeToTreeAndBlobs(summary: ISummaryTree, treeId: string): ISnapshotContents {\n const protocolSummary = summary.tree[\".protocol\"] as ISummaryTree;\n const documentAttributes = getDocAttributesFromProtocolSummary(protocolSummary);\n const sequenceNumber = documentAttributes.sequenceNumber;\n const blobs = new Map<string, ArrayBuffer>();\n const snapshotTree = convertCreateNewSummaryTreeToTreeAndBlobsCore(summary, blobs);\n snapshotTree.id = treeId;\n const snapshotTreeValue: ISnapshotContents = {\n snapshotTree,\n blobs,\n ops: [],\n sequenceNumber,\n };\n\n return snapshotTreeValue;\n}\n\nfunction convertCreateNewSummaryTreeToTreeAndBlobsCore(\n summary: ISummaryTree,\n blobs: Map<string, ArrayBuffer>,\n) {\n const treeNode: ISnapshotTree = {\n blobs: {},\n trees: {},\n unreferenced: summary.unreferenced,\n };\n const keys = Object.keys(summary.tree);\n for (const key of keys) {\n const summaryObject = summary.tree[key];\n\n switch (summaryObject.type) {\n case SummaryType.Tree: {\n treeNode.trees[key] =\n convertCreateNewSummaryTreeToTreeAndBlobsCore(summaryObject, blobs);\n break;\n }\n case SummaryType.Blob: {\n const contentBuffer = typeof summaryObject.content === \"string\" ?\n stringToBuffer(summaryObject.content, \"utf8\") : summaryObject.content;\n const blobId = uuid();\n treeNode.blobs[key] = blobId;\n blobs.set(blobId, contentBuffer);\n break;\n }\n case SummaryType.Handle:\n case SummaryType.Attachment: {\n throw new Error(`No ${summaryObject.type} should be present for detached summary!`);\n }\n default: {\n unreachableCase(summaryObject, `Unknown tree type ${(summaryObject as any).type}`);\n }\n }\n }\n return treeNode;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"epochTracker.d.ts","sourceRoot":"","sources":["../src/epochTracker.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,EAAE,gBAAgB,EAAE,MAAM,oCAAoC,CAAC;AACtE,OAAO,EAAmB,WAAW,EAAqB,MAAM,8BAA8B,CAAC;AAC/F,OAAO,EAAE,UAAU,EAAE,MAAM,sCAAsC,CAAC;AAClE,OAAO,EAGH,MAAM,EACN,UAAU,EACV,eAAe,EAElB,MAAM,yCAAyC,CAAC;AAGjD,OAAO,EAA0E,aAAa,EAAE,MAAM,aAAa,CAAC;AACpH,OAAO,EACH,UAAU,EACV,mBAAmB,EACnB,mBAAmB,EACrB,MAAM,aAAa,CAAC;AAKtB,oBAAY,SAAS,GAAG,MAAM,GAAG,YAAY,GA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SAAS,GAAE,OAAe;YAahB,kBAAkB;IA6BhC,OAAO,CAAC,sBAAsB;IAY9B,OAAO,CAAC,kBAAkB;CAG7B;AAED,qBAAa,0BAA2B,SAAQ,YAAY;IACxD,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAAwB;IAE5D,SAAS,CAAC,yBAAyB,CAC/B,iBAAiB,EAAE,MAAM,GAAG,SAAS,EACrC,SAAS,EAAE,SAAS,EACpB,SAAS,GAAE,OAAe;IAUjB,GAAG,CACZ,KAAK,EAAE,MAAM,GACd,OAAO,CAAC,GAAG,CAAC;IAuBF,mBAAmB,CAAC,CAAC,EAC9B,GAAG,EAAE,MAAM,EACX,YAAY,EAAE;QAAE,CAAC,KAAK,EAAE,MAAM,GAAG,GAAG,CAAC;KAAE,EACvC,SAAS,EAAE,SAAS,EACpB,SAAS,GAAE,OAAe,EAC1B,WAAW,CAAC,EAAE,MAAM,GACrB,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;CAgD/B;AAED,MAAM,WAAW,gBAAgB;IAC7B,KAAK,EAAE,UAAU,CAAC;IAClB,YAAY,EAAE,YAAY,CAAC;CAC9B;AAED,wBAAgB,yBAAyB,CACrC,iBAAiB,EAAE,eAAe,EAClC,kBAAkB,EAAE,mBAAmB,EACvC,SAAS,EAAE,UAAU,EACrB,MAAM,EAAE,gBAAgB,GAAG,gBAAgB,CAS9C"}
@@ -29,7 +29,7 @@ class EpochTracker {
29
29
  this.cache = cache;
30
30
  this.fileEntry = fileEntry;
31
31
  this.logger = logger;
32
- this.driverId = uuid_1.v4();
32
+ this.driverId = (0, uuid_1.v4)();
33
33
  // This tracks the request number made by the driver instance.
34
34
  this.networkCallNumber = 1;
35
35
  // Limits the max number of concurrent requests to 24.
@@ -37,7 +37,7 @@ class EpochTracker {
37
37
  }
38
38
  // public for UT purposes only!
39
39
  setEpoch(epoch, fromCache, fetchType) {
40
- common_utils_1.assert(this._fluidEpoch === undefined, 0x1db /* "epoch exists" */);
40
+ (0, common_utils_1.assert)(this._fluidEpoch === undefined, 0x1db /* "epoch exists" */);
41
41
  this._fluidEpoch = epoch;
42
42
  this.logger.sendTelemetryEvent({
43
43
  eventName: "EpochLearnedFirstTime",
@@ -56,7 +56,7 @@ class EpochTracker {
56
56
  if (value === undefined || value.version !== contracts_1.persistedCacheValueVersion) {
57
57
  return undefined;
58
58
  }
59
- common_utils_1.assert(value.fluidEpoch !== undefined, 0x1dc /* "all entries have to have epoch" */);
59
+ (0, common_utils_1.assert)(value.fluidEpoch !== undefined, 0x1dc /* "all entries have to have epoch" */);
60
60
  if (this._fluidEpoch === undefined) {
61
61
  this.setEpoch(value.fluidEpoch, true, "cache");
62
62
  // Epoch mismatch, the cached value is considerably different from what the current state of
@@ -90,7 +90,7 @@ class EpochTracker {
90
90
  }
91
91
  async put(entry, value) {
92
92
  var _a;
93
- common_utils_1.assert(this._fluidEpoch !== undefined, 0x1dd /* "no epoch" */);
93
+ (0, common_utils_1.assert)(this._fluidEpoch !== undefined, 0x1dd /* "no epoch" */);
94
94
  // For snapshots, the value should have the cacheEntryTime. This will be used to expire snapshots older
95
95
  // than the defaultCacheExpiryTimeoutMs.
96
96
  if (entry.type === odsp_driver_definitions_1.snapshotKey) {
@@ -120,7 +120,7 @@ class EpochTracker {
120
120
  }
121
121
  async validateEpochFromPush(details) {
122
122
  const epoch = details.epoch;
123
- common_utils_1.assert(epoch !== undefined, 0x09d /* "Connection details should contain epoch" */);
123
+ (0, common_utils_1.assert)(epoch !== undefined, 0x09d /* "Connection details should contain epoch" */);
124
124
  try {
125
125
  this.validateEpochFromResponse(epoch, "push");
126
126
  }
@@ -170,7 +170,7 @@ class EpochTracker {
170
170
  await this.checkForEpochError(error, epochFromResponse, fetchType);
171
171
  throw error;
172
172
  }).catch((error) => {
173
- const fluidError = telemetry_utils_1.normalizeError(error, { props: { XRequestStatsHeader: clientCorrelationId } });
173
+ const fluidError = (0, telemetry_utils_1.normalizeError)(error, { props: { XRequestStatsHeader: clientCorrelationId } });
174
174
  throw fluidError;
175
175
  });
176
176
  }
@@ -186,7 +186,7 @@ class EpochTracker {
186
186
  return this.fetchCore(url, fetchOptions, odspUtils_1.fetchArray, fetchType, addInBody, fetchReason);
187
187
  }
188
188
  addEpochInRequest(fetchOptions, addInBody, clientCorrelationId) {
189
- const isClpCompliantApp = odspUtils_1.getOdspResolvedUrl(this.fileEntry.resolvedUrl).isClpCompliantApp;
189
+ const isClpCompliantApp = (0, odspUtils_1.getOdspResolvedUrl)(this.fileEntry.resolvedUrl).isClpCompliantApp;
190
190
  if (addInBody) {
191
191
  const headers = {};
192
192
  headers["X-RequestStats"] = clientCorrelationId;
@@ -201,7 +201,7 @@ class EpochTracker {
201
201
  else {
202
202
  const addHeader = (key, val) => {
203
203
  fetchOptions.headers = Object.assign({}, fetchOptions.headers);
204
- common_utils_1.assert(fetchOptions.headers !== undefined, 0x282 /* "Headers should be present now" */);
204
+ (0, common_utils_1.assert)(fetchOptions.headers !== undefined, 0x282 /* "Headers should be present now" */);
205
205
  fetchOptions.headers[key] = val;
206
206
  };
207
207
  addHeader("X-RequestStats", clientCorrelationId);
@@ -217,10 +217,10 @@ class EpochTracker {
217
217
  // We use multi part form request for post body where we want to use this.
218
218
  // So extract the form boundary to mark the end of form.
219
219
  const body = fetchOptions.body;
220
- common_utils_1.assert(typeof body === "string", 0x21d /* "body is not string" */);
220
+ (0, common_utils_1.assert)(typeof body === "string", 0x21d /* "body is not string" */);
221
221
  const splitBody = body.split("\r\n");
222
222
  const firstLine = splitBody.shift();
223
- common_utils_1.assert(firstLine !== undefined && firstLine.startsWith("--"), 0x21e /* "improper boundary format" */);
223
+ (0, common_utils_1.assert)((firstLine === null || firstLine === void 0 ? void 0 : firstLine.startsWith("--")) === true, 0x21e /* "improper boundary format" */);
224
224
  const formParams = [firstLine];
225
225
  Object.entries(headers).forEach(([key, value]) => {
226
226
  formParams.push(`${key}: ${value}`);
@@ -249,7 +249,7 @@ class EpochTracker {
249
249
  }
250
250
  }
251
251
  async checkForEpochError(error, epochFromResponse, fetchType, fromCache = false) {
252
- if (telemetry_utils_1.isFluidError(error) && error.errorType === driver_definitions_1.DriverErrorType.fileOverwrittenInStorage) {
252
+ if ((0, telemetry_utils_1.isFluidError)(error) && error.errorType === driver_definitions_1.DriverErrorType.fileOverwrittenInStorage) {
253
253
  const epochError = this.checkForEpochErrorCore(epochFromResponse);
254
254
  if (epochError !== undefined) {
255
255
  epochError.addTelemetryProperties({
@@ -1 +1 @@
1
- {"version":3,"file":"epochTracker.js","sourceRoot":"","sources":["../src/epochTracker.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,+BAAkC;AAClC,+DAAgE;AAEhE,+DAA+F;AAE/F,qFAOiD;AACjD,2EAAqE;AACrE,qEAAiG;AACjG,2CAAoH;AAMpH,2CAAmF;AACnF,uDAA0D;AAC1D,qDAA+D;AAOlD,QAAA,YAAY,GAAG,cAAc,CAAC;AAE3C,0GAA0G;AAC7F,QAAA,2BAA2B,GAAW,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAE3E;;;;;GAKG;AACH,MAAa,YAAY;IAOrB,YACuB,KAAsB,EACtB,SAAqB,EACrB,MAAwB;QAFxB,UAAK,GAAL,KAAK,CAAiB;QACtB,cAAS,GAAT,SAAS,CAAY;QACrB,WAAM,GAAN,MAAM,CAAkB;QAN9B,aAAQ,GAAG,SAAI,EAAE,CAAC;QACnC,8DAA8D;QACtD,sBAAiB,GAAG,CAAC,CAAC;QAM1B,sDAAsD;QACtD,IAAI,CAAC,WAAW,GAAG,IAAI,0BAAW,CAAC,EAAE,CAAC,CAAC;IAC3C,CAAC;IAED,+BAA+B;IACxB,QAAQ,CAAC,KAAa,EAAE,SAAkB,EAAE,SAA4B;QAC3E,qBAAM,CAAC,IAAI,CAAC,WAAW,KAAK,SAAS,EAAE,KAAK,CAAC,oBAAoB,CAAC,CAAC;QACnE,IAAI,CAAC,WAAW,GAAG,KAAK,CAAC;QAEzB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EAAE,EAAE;gBAC7C,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;YAC9D,CAAC,CAAC,CAAC;YACH,MAAM,GAAG,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC;gBAC3B,QAAQ;gBACR,kFAAkF;gBAClF,IAAI,CAAC,mBAAmB,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;aAAC,CAAC,CAAC;YAC1E,IAAI,GAAG,KAAK,UAAU,EAAE;gBACpB,KAAK,CAAC,MAAM,EAAE,CAAC;aAClB;QACL,CAAC,EACD,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC;QACnD,OAAO,KAAK,CAAC,mBAAmB,CAAI,GAAG,EAAE,YAAY,EAAE,SAAS,EAAE,SAAS,CAAC,CAAC;IACjF,CAAC;CACJ;AA/FD,gEA+FC;AAOD,SAAgB,yBAAyB,CACrC,iBAAkC,EAClC,kBAAuC,EACvC,SAAqB,EACrB,MAAwB;IAExB,MAAM,YAAY,GAAG,IAAI,0BAA0B,CAAC,iBAAiB,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC;IAC1F,OAAO;QACH,KAAK,kCACE,kBAAkB,KACrB,cAAc,EAAE,YAAY,GAC/B;QACD,YAAY;KACf,CAAC;AACN,CAAC;AAdD,8DAcC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { v4 as uuid } from \"uuid\";\nimport { assert, Deferred } from \"@fluidframework/common-utils\";\nimport { ITelemetryLogger } from \"@fluidframework/common-definitions\";\nimport { ThrottlingError, RateLimiter, NonRetryableError } from \"@fluidframework/driver-utils\";\nimport { IConnected } from \"@fluidframework/protocol-definitions\";\nimport {\n snapshotKey,\n ICacheEntry,\n IEntry,\n IFileEntry,\n IPersistedCache,\n IOdspError,\n} from \"@fluidframework/odsp-driver-definitions\";\nimport { DriverErrorType } from \"@fluidframework/driver-definitions\";\nimport { PerformanceEvent, isFluidError, normalizeError } from \"@fluidframework/telemetry-utils\";\nimport { fetchAndParseAsJSONHelper, fetchArray, fetchHelper, getOdspResolvedUrl, IOdspResponse } from \"./odspUtils\";\nimport {\n IOdspCache,\n INonPersistentCache,\n IPersistedFileCache,\n } from \"./odspCache\";\nimport { IVersionedValueWithEpoch, persistedCacheValueVersion } from \"./contracts\";\nimport { ClpCompliantAppHeader } from \"./contractsPublic\";\nimport { pkgVersion as driverVersion } from \"./packageVersion\";\n\nexport type FetchType = \"blob\" | \"createBlob\" | \"createFile\" | \"joinSession\" | \"ops\" | \"test\" | \"snapshotTree\" |\n \"treesLatest\" | \"uploadSummary\" | \"push\" | \"versions\";\n\nexport type FetchTypeInternal = FetchType | \"cache\";\n\nexport const Odsp409Error = \"Odsp409Error\";\n\n// Please update the README file in odsp-driver-definitions if you change the defaultCacheExpiryTimeoutMs.\nexport const defaultCacheExpiryTimeoutMs: number = 2 * 24 * 60 * 60 * 1000;\n\n/**\n * This class is a wrapper around fetch calls. It adds epoch to the request made so that the\n * server can match it with its epoch value in order to match the version.\n * It also validates the epoch value received in response of fetch calls. If the epoch does not match,\n * then it also clears all the cached entries for the given container.\n */\nexport class EpochTracker implements IPersistedFileCache {\n private _fluidEpoch: string | undefined;\n\n public readonly rateLimiter: RateLimiter;\n private readonly driverId = uuid();\n // This tracks the request number made by the driver instance.\n private networkCallNumber = 1;\n constructor(\n protected readonly cache: IPersistedCache,\n protected readonly fileEntry: IFileEntry,\n protected readonly logger: ITelemetryLogger,\n ) {\n // Limits the max number of concurrent requests to 24.\n this.rateLimiter = new RateLimiter(24);\n }\n\n // public for UT purposes only!\n public setEpoch(epoch: string, fromCache: boolean, fetchType: FetchTypeInternal) {\n assert(this._fluidEpoch === undefined, 0x1db /* \"epoch exists\" */);\n this._fluidEpoch = epoch;\n\n this.logger.sendTelemetryEvent(\n {\n eventName: \"EpochLearnedFirstTime\",\n epoch,\n fetchType,\n fromCache,\n },\n );\n }\n\n public async get(\n entry: IEntry,\n ): Promise<any> {\n try {\n // Return undefined so that the ops/snapshots are grabbed from the server instead of the cache\n const value: IVersionedValueWithEpoch = await this.cache.get(this.fileEntryFromEntry(entry));\n // Version mismatch between what the runtime expects and what it recieved.\n // The cached value should not be used\n if (value === undefined || value.version !== persistedCacheValueVersion) {\n return undefined;\n }\n assert(value.fluidEpoch !== undefined, 0x1dc /* \"all entries have to have epoch\" */);\n if (this._fluidEpoch === undefined) {\n this.setEpoch(value.fluidEpoch, true, \"cache\");\n // Epoch mismatch, the cached value is considerably different from what the current state of\n // the runtime and should not be used\n } else if (this._fluidEpoch !== value.fluidEpoch) {\n return undefined;\n }\n // Expire the cached snapshot if it's older than the defaultCacheExpiryTimeoutMs and immediately\n // expire all old caches that do not have cacheEntryTime\n if (entry.type === snapshotKey) {\n const cacheTime = value.value?.cacheEntryTime;\n const currentTime = Date.now();\n if (cacheTime === undefined || currentTime - cacheTime >= defaultCacheExpiryTimeoutMs) {\n this.logger.sendTelemetryEvent(\n {\n eventName: \"odspVersionsCacheExpired\",\n duration: currentTime - cacheTime,\n maxCacheAgeMs: defaultCacheExpiryTimeoutMs,\n });\n await this.removeEntries();\n return undefined;\n }\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return value.value;\n } catch (error) {\n this.logger.sendErrorEvent({ eventName: \"cacheFetchError\", type: entry.type }, error);\n return undefined;\n }\n }\n\n public async put(entry: IEntry, value: any) {\n assert(this._fluidEpoch !== undefined, 0x1dd /* \"no epoch\" */);\n // For snapshots, the value should have the cacheEntryTime. This will be used to expire snapshots older\n // than the defaultCacheExpiryTimeoutMs.\n if (entry.type === snapshotKey) {\n value.cacheEntryTime = value.cacheEntryTime ?? Date.now();\n }\n const data: IVersionedValueWithEpoch = {\n value,\n version: persistedCacheValueVersion,\n fluidEpoch: this._fluidEpoch,\n };\n return this.cache.put(this.fileEntryFromEntry(entry), data)\n .catch((error) => {\n this.logger.sendErrorEvent({ eventName: \"cachePutError\", type: entry.type }, error);\n throw error;\n });\n }\n\n public async removeEntries(): Promise<void> {\n try {\n return await this.cache.removeEntries(this.fileEntry);\n } catch (error) {\n this.logger.sendErrorEvent({ eventName: \"removeCacheEntries\" }, error);\n }\n }\n\n public get fluidEpoch() {\n return this._fluidEpoch;\n }\n\n public async validateEpochFromPush(details: IConnected) {\n const epoch = details.epoch;\n assert(epoch !== undefined, 0x09d /* \"Connection details should contain epoch\" */);\n try {\n this.validateEpochFromResponse(epoch, \"push\");\n } catch (error) {\n await this.checkForEpochError(error, epoch, \"push\");\n throw error;\n }\n }\n\n /**\n * Api to fetch the response for given request and parse it as json.\n * @param url - url of the request\n * @param fetchOptions - fetch options for request containing body, headers etc.\n * @param fetchType - method for which fetch is called.\n * @param addInBody - Pass True if caller wants to add epoch in post body.\n * @param fetchReason - fetch reason to add to the request.\n */\n public async fetchAndParseAsJSON<T>(\n url: string,\n fetchOptions: RequestInit,\n fetchType: FetchType,\n addInBody: boolean = false,\n fetchReason?: string,\n ): Promise<IOdspResponse<T>> {\n return this.fetchCore<T>(url, fetchOptions, fetchAndParseAsJSONHelper, fetchType, addInBody, fetchReason);\n }\n\n /**\n * Api to fetch the response for given request and parse it as json.\n * @param url - url of the request\n * @param fetchOptions - fetch options for request containing body, headers etc.\n * @param fetchType - method for which fetch is called.\n * @param addInBody - Pass True if caller wants to add epoch in post body.\n * @param fetchReason - fetch reason to add to the request.\n */\n public async fetch(\n url: string,\n fetchOptions: RequestInit,\n fetchType: FetchType,\n addInBody: boolean = false,\n fetchReason?: string,\n ) {\n return this.fetchCore<Response>(url, fetchOptions, fetchHelper, fetchType, addInBody, fetchReason);\n }\n\n private async fetchCore<T>(\n url: string,\n fetchOptions: {[index: string]: any},\n fetcher: (url: string, fetchOptions: {[index: string]: any}) => Promise<IOdspResponse<T>>,\n fetchType: FetchType,\n addInBody: boolean = false,\n fetchReason?: string,\n ) {\n const clientCorrelationId = this.formatClientCorrelationId(fetchReason);\n // Add epoch in fetch request.\n this.addEpochInRequest(fetchOptions, addInBody, clientCorrelationId);\n let epochFromResponse: string | undefined;\n return this.rateLimiter.schedule(\n async () => fetcher(url, fetchOptions),\n ).then((response) => {\n epochFromResponse = response.headers.get(\"x-fluid-epoch\");\n this.validateEpochFromResponse(epochFromResponse, fetchType);\n response.propsToLog.XRequestStatsHeader = clientCorrelationId;\n return response;\n }).catch(async (error) => {\n // Get the server epoch from error in case we don't have it as if undefined we won't be able\n // to mark it as epoch error.\n if (epochFromResponse === undefined) {\n epochFromResponse = (error as IOdspError).serverEpoch;\n }\n await this.checkForEpochError(error, epochFromResponse, fetchType);\n throw error;\n }).catch((error) => {\n const fluidError = normalizeError(error, { props: { XRequestStatsHeader: clientCorrelationId }});\n throw fluidError;\n });\n }\n\n /**\n * Api to fetch the response as it is for given request.\n * @param url - url of the request\n * @param fetchOptions - fetch options for request containing body, headers etc.\n * @param fetchType - method for which fetch is called.\n * @param addInBody - Pass True if caller wants to add epoch in post body.\n * @param fetchReason - fetch reason to add to the request.\n */\n public async fetchArray(\n url: string,\n fetchOptions: {[index: string]: any},\n fetchType: FetchType,\n addInBody: boolean = false,\n fetchReason?: string,\n ) {\n return this.fetchCore<ArrayBuffer>(url, fetchOptions, fetchArray, fetchType, addInBody, fetchReason);\n }\n\n private addEpochInRequest(\n fetchOptions: RequestInit,\n addInBody: boolean,\n clientCorrelationId: string,\n ) {\n const isClpCompliantApp = getOdspResolvedUrl(this.fileEntry.resolvedUrl).isClpCompliantApp;\n if (addInBody) {\n const headers: {[key: string]: string} = {};\n headers[\"X-RequestStats\"] = clientCorrelationId;\n if (this.fluidEpoch !== undefined) {\n headers[\"x-fluid-epoch\"] = this.fluidEpoch;\n }\n if (isClpCompliantApp) {\n headers[ClpCompliantAppHeader.isClpCompliantApp] = isClpCompliantApp.toString();\n }\n this.addParamInBody(fetchOptions, headers);\n } else {\n const addHeader = (key: string, val: string) => {\n fetchOptions.headers = {\n ...fetchOptions.headers,\n };\n assert(fetchOptions.headers !== undefined, 0x282 /* \"Headers should be present now\" */);\n fetchOptions.headers[key] = val;\n };\n addHeader(\"X-RequestStats\", clientCorrelationId);\n if (this.fluidEpoch !== undefined) {\n addHeader(\"x-fluid-epoch\", this.fluidEpoch);\n }\n if (isClpCompliantApp) {\n addHeader(ClpCompliantAppHeader.isClpCompliantApp, isClpCompliantApp.toString());\n }\n }\n }\n\n private addParamInBody(fetchOptions: RequestInit, headers: {[key: string]: string}) {\n // We use multi part form request for post body where we want to use this.\n // So extract the form boundary to mark the end of form.\n const body = fetchOptions.body;\n assert(typeof body === \"string\", 0x21d /* \"body is not string\" */);\n const splitBody = body.split(\"\\r\\n\");\n const firstLine = splitBody.shift();\n assert(firstLine !== undefined && firstLine.startsWith(\"--\"), 0x21e /* \"improper boundary format\" */);\n const formParams = [firstLine];\n Object.entries(headers).forEach(([key, value]) => {\n formParams.push(`${key}: ${value}`);\n });\n splitBody.forEach((value: string) => {\n formParams.push(value);\n });\n fetchOptions.body = formParams.join(\"\\r\\n\");\n }\n\n private formatClientCorrelationId(fetchReason?: string) {\n const items: string[] = [`driverId=${this.driverId}`, `RequestNumber=${this.networkCallNumber++}`];\n if (fetchReason !== undefined) {\n items.push(`fetchReason=${fetchReason}`);\n }\n return items.join(\", \");\n }\n\n protected validateEpochFromResponse(\n epochFromResponse: string | undefined,\n fetchType: FetchTypeInternal,\n fromCache: boolean = false,\n ) {\n const error = this.checkForEpochErrorCore(epochFromResponse);\n if (error !== undefined) {\n throw error;\n }\n if (epochFromResponse !== undefined) {\n if (this._fluidEpoch === undefined) {\n this.setEpoch(epochFromResponse, fromCache, fetchType);\n }\n }\n }\n\n private async checkForEpochError(\n error: unknown,\n epochFromResponse: string | null | undefined,\n fetchType: FetchTypeInternal,\n fromCache: boolean = false,\n ) {\n if (isFluidError(error) && error.errorType === DriverErrorType.fileOverwrittenInStorage) {\n const epochError = this.checkForEpochErrorCore(epochFromResponse);\n if (epochError !== undefined) {\n epochError.addTelemetryProperties({\n fromCache,\n clientEpoch: this.fluidEpoch,\n fetchType,\n });\n this.logger.sendErrorEvent({ eventName: \"fileOverwrittenInStorage\" }, epochError);\n // If the epoch mismatches, then clear all entries for such file entry from cache.\n await this.removeEntries();\n throw epochError;\n }\n // If it was categorized as epoch error but the epoch returned in response matches with the client epoch\n // then it was coherency 409, so rethrow it as throttling error so that it can retried. Default throttling\n // time is 1s.\n throw new ThrottlingError(\n `Coherency 409: ${error.message}`,\n 1 /* retryAfterSeconds */,\n { [Odsp409Error]: true, driverVersion });\n }\n }\n\n private checkForEpochErrorCore(epochFromResponse: string | null | undefined) {\n // If epoch is undefined, then don't compare it because initially for createNew or TreesLatest\n // initializes this value. Sometimes response does not contain epoch as it is still in\n // implementation phase at server side. In that case also, don't compare it with our epoch value.\n if (this.fluidEpoch && epochFromResponse && (this.fluidEpoch !== epochFromResponse)) {\n // This is similar in nature to how fluidEpochMismatchError (409) is handled.\n // Difference - client detected mismatch, instead of server detecting it.\n return new NonRetryableError(\n \"Epoch mismatch\", DriverErrorType.fileOverwrittenInStorage, { driverVersion });\n }\n }\n\n private fileEntryFromEntry(entry: IEntry): ICacheEntry {\n return { ...entry, file: this.fileEntry };\n }\n}\n\nexport class EpochTrackerWithRedemption extends EpochTracker {\n private readonly treesLatestDeferral = new Deferred<void>();\n\n protected validateEpochFromResponse(\n epochFromResponse: string | undefined,\n fetchType: FetchType,\n fromCache: boolean = false,\n ) {\n super.validateEpochFromResponse(epochFromResponse, fetchType, fromCache);\n\n // Any successful call means we have access to a file, i.e. any redemption that was required already happened.\n // That covers cases of \"treesLatest\" as well as \"getVersions\" or \"createFile\" - all the ways we can start\n // exploring a file.\n this.treesLatestDeferral.resolve();\n }\n\n public async get(\n entry: IEntry,\n ): Promise<any> {\n let result = super.get(entry);\n\n // equivalence of what happens in fetchAndParseAsJSON()\n if (entry.type === snapshotKey) {\n result = result\n .then((value) => {\n // If there is nothing in cache, we need to wait for network call to complete (and do redemption)\n // Otherwise file was redeemed in prior session, so if joinSession failed, we should not retry\n if (value !== undefined) {\n this.treesLatestDeferral.resolve();\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return value;\n })\n .catch((error) => {\n this.treesLatestDeferral.reject(error);\n throw error;\n });\n }\n return result;\n }\n\n public async fetchAndParseAsJSON<T>(\n url: string,\n fetchOptions: {[index: string]: any},\n fetchType: FetchType,\n addInBody: boolean = false,\n fetchReason?: string,\n ): Promise<IOdspResponse<T>> {\n // Optimize the flow if we know that treesLatestDeferral was already completed by the timer we started\n // joinSession call. If we did - there is no reason to repeat the call as it will fail with same error.\n const completed = this.treesLatestDeferral.isCompleted;\n\n try {\n return await super.fetchAndParseAsJSON<T>(url, fetchOptions, fetchType, addInBody, fetchReason);\n } catch (error: any) {\n // Only handling here treesLatest. If createFile failed, we should never try to do joinSession.\n // Similar, if getVersions failed, we should not do any further storage calls.\n // So treesLatest is the only call that can have parallel joinSession request.\n if (fetchType === \"treesLatest\") {\n this.treesLatestDeferral.reject(error);\n }\n if (fetchType !== \"joinSession\" || error.statusCode < 401 || error.statusCode > 404 || completed) {\n throw error;\n }\n }\n\n // It is joinSession failing with 401..404 error\n // Repeat after waiting for treeLatest succeeding (or fail if it failed).\n // No special handling after first call - if file has been deleted, then it's game over.\n\n // Ensure we have some safety here - we do not want to deadlock if we got logic somewhere wrong.\n // If we waited too long, we will log error event and proceed with call.\n // It may result in failure for user, but refreshing document would address it.\n // Thus we use rather long timeout (not to get these failures as much as possible), but not large enough\n // to unblock the process.\n await PerformanceEvent.timedExecAsync(\n this.logger,\n { eventName: \"JoinSessionSyncWait\" },\n async (event) => {\n const timeoutRes = 51; // anything will work here\n let timer: ReturnType<typeof setTimeout>;\n const timeoutP = new Promise<number>((resolve) => {\n timer = setTimeout(() => { resolve(timeoutRes); }, 15000);\n });\n const res = await Promise.race([\n timeoutP,\n // cancel timeout to unblock UTs (otherwise Node process does not exit for 15 sec)\n this.treesLatestDeferral.promise.finally(() => clearTimeout(timer))]);\n if (res === timeoutRes) {\n event.cancel();\n }\n },\n { start: true, end: true, cancel: \"generic\" });\n return super.fetchAndParseAsJSON<T>(url, fetchOptions, fetchType, addInBody);\n }\n}\n\nexport interface ICacheAndTracker {\n cache: IOdspCache;\n epochTracker: EpochTracker;\n}\n\nexport function createOdspCacheAndTracker(\n persistedCacheArg: IPersistedCache,\n nonpersistentCache: INonPersistentCache,\n fileEntry: IFileEntry,\n logger: ITelemetryLogger): ICacheAndTracker\n{\n const epochTracker = new EpochTrackerWithRedemption(persistedCacheArg, fileEntry, logger);\n return {\n cache: {\n ...nonpersistentCache,\n persistedCache: epochTracker,\n },\n epochTracker,\n };\n}\n"]}
1
+ {"version":3,"file":"epochTracker.js","sourceRoot":"","sources":["../src/epochTracker.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,+BAAkC;AAClC,+DAAgE;AAEhE,+DAA+F;AAE/F,qFAOiD;AACjD,2EAAqE;AACrE,qEAAiG;AACjG,2CAAoH;AAMpH,2CAAmF;AACnF,uDAA0D;AAC1D,qDAA+D;AAOlD,QAAA,YAAY,GAAG,cAAc,CAAC;AAE3C,0GAA0G;AAC7F,QAAA,2BAA2B,GAAW,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAE3E;;;;;GAKG;AACH,MAAa,YAAY;IAOrB,YACuB,KAAsB,EACtB,SAAqB,EACrB,MAAwB;QAFxB,UAAK,GAAL,KAAK,CAAiB;QACtB,cAAS,GAAT,SAAS,CAAY;QACrB,WAAM,GAAN,MAAM,CAAkB;QAN9B,aAAQ,GAAG,IAAA,SAAI,GAAE,CAAC;QACnC,8DAA8D;QACtD,sBAAiB,GAAG,CAAC,CAAC;QAM1B,sDAAsD;QACtD,IAAI,CAAC,WAAW,GAAG,IAAI,0BAAW,CAAC,EAAE,CAAC,CAAC;IA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AC;AACN,CAAC;AAbD,8DAaC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { v4 as uuid } from \"uuid\";\nimport { assert, Deferred } from \"@fluidframework/common-utils\";\nimport { ITelemetryLogger } from \"@fluidframework/common-definitions\";\nimport { ThrottlingError, RateLimiter, NonRetryableError } from \"@fluidframework/driver-utils\";\nimport { IConnected } from \"@fluidframework/protocol-definitions\";\nimport {\n snapshotKey,\n ICacheEntry,\n IEntry,\n IFileEntry,\n IPersistedCache,\n IOdspError,\n} from \"@fluidframework/odsp-driver-definitions\";\nimport { DriverErrorType } from \"@fluidframework/driver-definitions\";\nimport { PerformanceEvent, isFluidError, normalizeError } from \"@fluidframework/telemetry-utils\";\nimport { fetchAndParseAsJSONHelper, fetchArray, fetchHelper, getOdspResolvedUrl, IOdspResponse } from \"./odspUtils\";\nimport {\n IOdspCache,\n INonPersistentCache,\n IPersistedFileCache,\n } from \"./odspCache\";\nimport { IVersionedValueWithEpoch, persistedCacheValueVersion } from \"./contracts\";\nimport { ClpCompliantAppHeader } from \"./contractsPublic\";\nimport { pkgVersion as driverVersion } from \"./packageVersion\";\n\nexport type FetchType = \"blob\" | \"createBlob\" | \"createFile\" | \"joinSession\" | \"ops\" | \"test\" | \"snapshotTree\" |\n \"treesLatest\" | \"uploadSummary\" | \"push\" | \"versions\";\n\nexport type FetchTypeInternal = FetchType | \"cache\";\n\nexport const Odsp409Error = \"Odsp409Error\";\n\n// Please update the README file in odsp-driver-definitions if you change the defaultCacheExpiryTimeoutMs.\nexport const defaultCacheExpiryTimeoutMs: number = 2 * 24 * 60 * 60 * 1000;\n\n/**\n * This class is a wrapper around fetch calls. It adds epoch to the request made so that the\n * server can match it with its epoch value in order to match the version.\n * It also validates the epoch value received in response of fetch calls. If the epoch does not match,\n * then it also clears all the cached entries for the given container.\n */\nexport class EpochTracker implements IPersistedFileCache {\n private _fluidEpoch: string | undefined;\n\n public readonly rateLimiter: RateLimiter;\n private readonly driverId = uuid();\n // This tracks the request number made by the driver instance.\n private networkCallNumber = 1;\n constructor(\n protected readonly cache: IPersistedCache,\n protected readonly fileEntry: IFileEntry,\n protected readonly logger: ITelemetryLogger,\n ) {\n // Limits the max number of concurrent requests to 24.\n this.rateLimiter = new RateLimiter(24);\n }\n\n // public for UT purposes only!\n public setEpoch(epoch: string, fromCache: boolean, fetchType: FetchTypeInternal) {\n assert(this._fluidEpoch === undefined, 0x1db /* \"epoch exists\" */);\n this._fluidEpoch = epoch;\n\n this.logger.sendTelemetryEvent(\n {\n eventName: \"EpochLearnedFirstTime\",\n epoch,\n fetchType,\n fromCache,\n },\n );\n }\n\n public async get(\n entry: IEntry,\n ): Promise<any> {\n try {\n // Return undefined so that the ops/snapshots are grabbed from the server instead of the cache\n const value: IVersionedValueWithEpoch = await this.cache.get(this.fileEntryFromEntry(entry));\n // Version mismatch between what the runtime expects and what it recieved.\n // The cached value should not be used\n if (value === undefined || value.version !== persistedCacheValueVersion) {\n return undefined;\n }\n assert(value.fluidEpoch !== undefined, 0x1dc /* \"all entries have to have epoch\" */);\n if (this._fluidEpoch === undefined) {\n this.setEpoch(value.fluidEpoch, true, \"cache\");\n // Epoch mismatch, the cached value is considerably different from what the current state of\n // the runtime and should not be used\n } else if (this._fluidEpoch !== value.fluidEpoch) {\n return undefined;\n }\n // Expire the cached snapshot if it's older than the defaultCacheExpiryTimeoutMs and immediately\n // expire all old caches that do not have cacheEntryTime\n if (entry.type === snapshotKey) {\n const cacheTime = value.value?.cacheEntryTime;\n const currentTime = Date.now();\n if (cacheTime === undefined || currentTime - cacheTime >= defaultCacheExpiryTimeoutMs) {\n this.logger.sendTelemetryEvent(\n {\n eventName: \"odspVersionsCacheExpired\",\n duration: currentTime - cacheTime,\n maxCacheAgeMs: defaultCacheExpiryTimeoutMs,\n });\n await this.removeEntries();\n return undefined;\n }\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return value.value;\n } catch (error) {\n this.logger.sendErrorEvent({ eventName: \"cacheFetchError\", type: entry.type }, error);\n return undefined;\n }\n }\n\n public async put(entry: IEntry, value: any) {\n assert(this._fluidEpoch !== undefined, 0x1dd /* \"no epoch\" */);\n // For snapshots, the value should have the cacheEntryTime. This will be used to expire snapshots older\n // than the defaultCacheExpiryTimeoutMs.\n if (entry.type === snapshotKey) {\n value.cacheEntryTime = value.cacheEntryTime ?? Date.now();\n }\n const data: IVersionedValueWithEpoch = {\n value,\n version: persistedCacheValueVersion,\n fluidEpoch: this._fluidEpoch,\n };\n return this.cache.put(this.fileEntryFromEntry(entry), data)\n .catch((error) => {\n this.logger.sendErrorEvent({ eventName: \"cachePutError\", type: entry.type }, error);\n throw error;\n });\n }\n\n public async removeEntries(): Promise<void> {\n try {\n return await this.cache.removeEntries(this.fileEntry);\n } catch (error) {\n this.logger.sendErrorEvent({ eventName: \"removeCacheEntries\" }, error);\n }\n }\n\n public get fluidEpoch() {\n return this._fluidEpoch;\n }\n\n public async validateEpochFromPush(details: IConnected) {\n const epoch = details.epoch;\n assert(epoch !== undefined, 0x09d /* \"Connection details should contain epoch\" */);\n try {\n this.validateEpochFromResponse(epoch, \"push\");\n } catch (error) {\n await this.checkForEpochError(error, epoch, \"push\");\n throw error;\n }\n }\n\n /**\n * Api to fetch the response for given request and parse it as json.\n * @param url - url of the request\n * @param fetchOptions - fetch options for request containing body, headers etc.\n * @param fetchType - method for which fetch is called.\n * @param addInBody - Pass True if caller wants to add epoch in post body.\n * @param fetchReason - fetch reason to add to the request.\n */\n public async fetchAndParseAsJSON<T>(\n url: string,\n fetchOptions: RequestInit,\n fetchType: FetchType,\n addInBody: boolean = false,\n fetchReason?: string,\n ): Promise<IOdspResponse<T>> {\n return this.fetchCore<T>(url, fetchOptions, fetchAndParseAsJSONHelper, fetchType, addInBody, fetchReason);\n }\n\n /**\n * Api to fetch the response for given request and parse it as json.\n * @param url - url of the request\n * @param fetchOptions - fetch options for request containing body, headers etc.\n * @param fetchType - method for which fetch is called.\n * @param addInBody - Pass True if caller wants to add epoch in post body.\n * @param fetchReason - fetch reason to add to the request.\n */\n public async fetch(\n url: string,\n fetchOptions: RequestInit,\n fetchType: FetchType,\n addInBody: boolean = false,\n fetchReason?: string,\n ) {\n return this.fetchCore<Response>(url, fetchOptions, fetchHelper, fetchType, addInBody, fetchReason);\n }\n\n private async fetchCore<T>(\n url: string,\n fetchOptions: { [index: string]: any; },\n fetcher: (url: string, fetchOptions: { [index: string]: any; }) => Promise<IOdspResponse<T>>,\n fetchType: FetchType,\n addInBody: boolean = false,\n fetchReason?: string,\n ) {\n const clientCorrelationId = this.formatClientCorrelationId(fetchReason);\n // Add epoch in fetch request.\n this.addEpochInRequest(fetchOptions, addInBody, clientCorrelationId);\n let epochFromResponse: string | undefined;\n return this.rateLimiter.schedule(\n async () => fetcher(url, fetchOptions),\n ).then((response) => {\n epochFromResponse = response.headers.get(\"x-fluid-epoch\");\n this.validateEpochFromResponse(epochFromResponse, fetchType);\n response.propsToLog.XRequestStatsHeader = clientCorrelationId;\n return response;\n }).catch(async (error) => {\n // Get the server epoch from error in case we don't have it as if undefined we won't be able\n // to mark it as epoch error.\n if (epochFromResponse === undefined) {\n epochFromResponse = (error as IOdspError).serverEpoch;\n }\n await this.checkForEpochError(error, epochFromResponse, fetchType);\n throw error;\n }).catch((error) => {\n const fluidError = normalizeError(error, { props: { XRequestStatsHeader: clientCorrelationId } });\n throw fluidError;\n });\n }\n\n /**\n * Api to fetch the response as it is for given request.\n * @param url - url of the request\n * @param fetchOptions - fetch options for request containing body, headers etc.\n * @param fetchType - method for which fetch is called.\n * @param addInBody - Pass True if caller wants to add epoch in post body.\n * @param fetchReason - fetch reason to add to the request.\n */\n public async fetchArray(\n url: string,\n fetchOptions: { [index: string]: any; },\n fetchType: FetchType,\n addInBody: boolean = false,\n fetchReason?: string,\n ) {\n return this.fetchCore<ArrayBuffer>(url, fetchOptions, fetchArray, fetchType, addInBody, fetchReason);\n }\n\n private addEpochInRequest(\n fetchOptions: RequestInit,\n addInBody: boolean,\n clientCorrelationId: string,\n ) {\n const isClpCompliantApp = getOdspResolvedUrl(this.fileEntry.resolvedUrl).isClpCompliantApp;\n if (addInBody) {\n const headers: { [key: string]: string; } = {};\n headers[\"X-RequestStats\"] = clientCorrelationId;\n if (this.fluidEpoch !== undefined) {\n headers[\"x-fluid-epoch\"] = this.fluidEpoch;\n }\n if (isClpCompliantApp) {\n headers[ClpCompliantAppHeader.isClpCompliantApp] = isClpCompliantApp.toString();\n }\n this.addParamInBody(fetchOptions, headers);\n } else {\n const addHeader = (key: string, val: string) => {\n fetchOptions.headers = {\n ...fetchOptions.headers,\n };\n assert(fetchOptions.headers !== undefined, 0x282 /* \"Headers should be present now\" */);\n fetchOptions.headers[key] = val;\n };\n addHeader(\"X-RequestStats\", clientCorrelationId);\n if (this.fluidEpoch !== undefined) {\n addHeader(\"x-fluid-epoch\", this.fluidEpoch);\n }\n if (isClpCompliantApp) {\n addHeader(ClpCompliantAppHeader.isClpCompliantApp, isClpCompliantApp.toString());\n }\n }\n }\n\n private addParamInBody(fetchOptions: RequestInit, headers: { [key: string]: string; }) {\n // We use multi part form request for post body where we want to use this.\n // So extract the form boundary to mark the end of form.\n const body = fetchOptions.body;\n assert(typeof body === \"string\", 0x21d /* \"body is not string\" */);\n const splitBody = body.split(\"\\r\\n\");\n const firstLine = splitBody.shift();\n assert(firstLine?.startsWith(\"--\") === true, 0x21e /* \"improper boundary format\" */);\n const formParams = [firstLine];\n Object.entries(headers).forEach(([key, value]) => {\n formParams.push(`${key}: ${value}`);\n });\n splitBody.forEach((value: string) => {\n formParams.push(value);\n });\n fetchOptions.body = formParams.join(\"\\r\\n\");\n }\n\n private formatClientCorrelationId(fetchReason?: string) {\n const items: string[] = [`driverId=${this.driverId}`, `RequestNumber=${this.networkCallNumber++}`];\n if (fetchReason !== undefined) {\n items.push(`fetchReason=${fetchReason}`);\n }\n return items.join(\", \");\n }\n\n protected validateEpochFromResponse(\n epochFromResponse: string | undefined,\n fetchType: FetchTypeInternal,\n fromCache: boolean = false,\n ) {\n const error = this.checkForEpochErrorCore(epochFromResponse);\n if (error !== undefined) {\n throw error;\n }\n if (epochFromResponse !== undefined) {\n if (this._fluidEpoch === undefined) {\n this.setEpoch(epochFromResponse, fromCache, fetchType);\n }\n }\n }\n\n private async checkForEpochError(\n error: unknown,\n epochFromResponse: string | null | undefined,\n fetchType: FetchTypeInternal,\n fromCache: boolean = false,\n ) {\n if (isFluidError(error) && error.errorType === DriverErrorType.fileOverwrittenInStorage) {\n const epochError = this.checkForEpochErrorCore(epochFromResponse);\n if (epochError !== undefined) {\n epochError.addTelemetryProperties({\n fromCache,\n clientEpoch: this.fluidEpoch,\n fetchType,\n });\n this.logger.sendErrorEvent({ eventName: \"fileOverwrittenInStorage\" }, epochError);\n // If the epoch mismatches, then clear all entries for such file entry from cache.\n await this.removeEntries();\n throw epochError;\n }\n // If it was categorized as epoch error but the epoch returned in response matches with the client epoch\n // then it was coherency 409, so rethrow it as throttling error so that it can retried. Default throttling\n // time is 1s.\n throw new ThrottlingError(\n `Coherency 409: ${error.message}`,\n 1 /* retryAfterSeconds */,\n { [Odsp409Error]: true, driverVersion });\n }\n }\n\n private checkForEpochErrorCore(epochFromResponse: string | null | undefined) {\n // If epoch is undefined, then don't compare it because initially for createNew or TreesLatest\n // initializes this value. Sometimes response does not contain epoch as it is still in\n // implementation phase at server side. In that case also, don't compare it with our epoch value.\n if (this.fluidEpoch && epochFromResponse && (this.fluidEpoch !== epochFromResponse)) {\n // This is similar in nature to how fluidEpochMismatchError (409) is handled.\n // Difference - client detected mismatch, instead of server detecting it.\n return new NonRetryableError(\n \"Epoch mismatch\", DriverErrorType.fileOverwrittenInStorage, { driverVersion });\n }\n }\n\n private fileEntryFromEntry(entry: IEntry): ICacheEntry {\n return { ...entry, file: this.fileEntry };\n }\n}\n\nexport class EpochTrackerWithRedemption extends EpochTracker {\n private readonly treesLatestDeferral = new Deferred<void>();\n\n protected validateEpochFromResponse(\n epochFromResponse: string | undefined,\n fetchType: FetchType,\n fromCache: boolean = false,\n ) {\n super.validateEpochFromResponse(epochFromResponse, fetchType, fromCache);\n\n // Any successful call means we have access to a file, i.e. any redemption that was required already happened.\n // That covers cases of \"treesLatest\" as well as \"getVersions\" or \"createFile\" - all the ways we can start\n // exploring a file.\n this.treesLatestDeferral.resolve();\n }\n\n public async get(\n entry: IEntry,\n ): Promise<any> {\n let result = super.get(entry);\n\n // equivalence of what happens in fetchAndParseAsJSON()\n if (entry.type === snapshotKey) {\n result = result\n .then((value) => {\n // If there is nothing in cache, we need to wait for network call to complete (and do redemption)\n // Otherwise file was redeemed in prior session, so if joinSession failed, we should not retry\n if (value !== undefined) {\n this.treesLatestDeferral.resolve();\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return value;\n })\n .catch((error) => {\n this.treesLatestDeferral.reject(error);\n throw error;\n });\n }\n return result;\n }\n\n public async fetchAndParseAsJSON<T>(\n url: string,\n fetchOptions: { [index: string]: any; },\n fetchType: FetchType,\n addInBody: boolean = false,\n fetchReason?: string,\n ): Promise<IOdspResponse<T>> {\n // Optimize the flow if we know that treesLatestDeferral was already completed by the timer we started\n // joinSession call. If we did - there is no reason to repeat the call as it will fail with same error.\n const completed = this.treesLatestDeferral.isCompleted;\n\n try {\n return await super.fetchAndParseAsJSON<T>(url, fetchOptions, fetchType, addInBody, fetchReason);\n } catch (error: any) {\n // Only handling here treesLatest. If createFile failed, we should never try to do joinSession.\n // Similar, if getVersions failed, we should not do any further storage calls.\n // So treesLatest is the only call that can have parallel joinSession request.\n if (fetchType === \"treesLatest\") {\n this.treesLatestDeferral.reject(error);\n }\n if (fetchType !== \"joinSession\" || error.statusCode < 401 || error.statusCode > 404 || completed) {\n throw error;\n }\n }\n\n // It is joinSession failing with 401..404 error\n // Repeat after waiting for treeLatest succeeding (or fail if it failed).\n // No special handling after first call - if file has been deleted, then it's game over.\n\n // Ensure we have some safety here - we do not want to deadlock if we got logic somewhere wrong.\n // If we waited too long, we will log error event and proceed with call.\n // It may result in failure for user, but refreshing document would address it.\n // Thus we use rather long timeout (not to get these failures as much as possible), but not large enough\n // to unblock the process.\n await PerformanceEvent.timedExecAsync(\n this.logger,\n { eventName: \"JoinSessionSyncWait\" },\n async (event) => {\n const timeoutRes = 51; // anything will work here\n let timer: ReturnType<typeof setTimeout>;\n const timeoutP = new Promise<number>((resolve) => {\n timer = setTimeout(() => { resolve(timeoutRes); }, 15000);\n });\n const res = await Promise.race([\n timeoutP,\n // cancel timeout to unblock UTs (otherwise Node process does not exit for 15 sec)\n this.treesLatestDeferral.promise.finally(() => clearTimeout(timer))]);\n if (res === timeoutRes) {\n event.cancel();\n }\n },\n { start: true, end: true, cancel: \"generic\" });\n return super.fetchAndParseAsJSON<T>(url, fetchOptions, fetchType, addInBody);\n }\n}\n\nexport interface ICacheAndTracker {\n cache: IOdspCache;\n epochTracker: EpochTracker;\n}\n\nexport function createOdspCacheAndTracker(\n persistedCacheArg: IPersistedCache,\n nonpersistentCache: INonPersistentCache,\n fileEntry: IFileEntry,\n logger: ITelemetryLogger): ICacheAndTracker {\n const epochTracker = new EpochTrackerWithRedemption(persistedCacheArg, fileEntry, logger);\n return {\n cache: {\n ...nonpersistentCache,\n persistedCache: epochTracker,\n },\n epochTracker,\n };\n}\n"]}
package/dist/fetch.js CHANGED
@@ -12,6 +12,6 @@ const node_fetch_1 = __importDefault(require("node-fetch"));
12
12
  // The only purpose of this helper is to work around the slight misalignments between the
13
13
  // Browser's fetch API and the 'node-fetch' package by wrapping the call to the 'node-fetch' API
14
14
  // in the browser's types from 'lib.dom.d.ts'.
15
- const fetch = async (request, config) => node_fetch_1.default(request, config);
15
+ const fetch = async (request, config) => (0, node_fetch_1.default)(request, config);
16
16
  exports.fetch = fetch;
17
17
  //# sourceMappingURL=fetch.js.map
package/dist/fetch.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.js","sourceRoot":"","sources":["../src/fetch.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;;;;AAEH,4DAIoB;AAEpB,yFAAyF;AACzF,gGAAgG;AAChG,8CAA8C;AACvC,MAAM,KAAK,GAAG,KAAK,EAAE,OAAoB,EAAE,MAAoB,EAAqB,EAAE,CACzF,oBAAS,CAAC,OAA2B,EAAE,MAA0B,CAAwB,CAAC;AADjF,QAAA,KAAK,SAC4E","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n default as nodeFetch,\n RequestInfo as FetchRequestInfo,\n RequestInit as FetchRequestInit,\n} from \"node-fetch\";\n\n// The only purpose of this helper is to work around the slight misalignments between the\n// Browser's fetch API and the 'node-fetch' package by wrapping the call to the 'node-fetch' API\n// in the browser's types from 'lib.dom.d.ts'.\nexport const fetch = async (request: RequestInfo, config?: RequestInit): Promise<Response> =>\n nodeFetch(request as FetchRequestInfo, config as FetchRequestInit) as unknown as Response;\n"]}
1
+ {"version":3,"file":"fetch.js","sourceRoot":"","sources":["../src/fetch.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;;;;AAEH,4DAIoB;AAEpB,yFAAyF;AACzF,gGAAgG;AAChG,8CAA8C;AACvC,MAAM,KAAK,GAAG,KAAK,EAAE,OAAoB,EAAE,MAAoB,EAAqB,EAAE,CACzF,IAAA,oBAAS,EAAC,OAA2B,EAAE,MAA0B,CAAwB,CAAC;AADjF,QAAA,KAAK,SAC4E","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n default as nodeFetch,\n RequestInfo as FetchRequestInfo,\n RequestInit as FetchRequestInit,\n} from \"node-fetch\";\n\n// The only purpose of this helper is to work around the slight misalignments between the\n// Browser's fetch API and the 'node-fetch' package by wrapping the call to the 'node-fetch' API\n// in the browser's types from 'lib.dom.d.ts'.\nexport const fetch = async (request: RequestInfo, config?: RequestInit): Promise<Response> =>\n nodeFetch(request as FetchRequestInfo, config as FetchRequestInit) as unknown as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