@fluidframework/odsp-driver 1.2.1 → 2.0.0-internal.1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/compactSnapshotParser.d.ts.map +1 -1
- package/dist/compactSnapshotParser.js +4 -1
- package/dist/compactSnapshotParser.js.map +1 -1
- package/dist/compactSnapshotWriter.d.ts.map +1 -1
- package/dist/compactSnapshotWriter.js +6 -3
- package/dist/compactSnapshotWriter.js.map +1 -1
- package/dist/epochTracker.d.ts +1 -0
- package/dist/epochTracker.d.ts.map +1 -1
- package/dist/epochTracker.js +24 -5
- package/dist/epochTracker.js.map +1 -1
- package/dist/fetchSnapshot.d.ts.map +1 -1
- package/dist/fetchSnapshot.js +15 -12
- package/dist/fetchSnapshot.js.map +1 -1
- package/dist/getFileLink.d.ts +3 -6
- package/dist/getFileLink.d.ts.map +1 -1
- package/dist/getFileLink.js +27 -38
- package/dist/getFileLink.js.map +1 -1
- package/dist/odspDeltaStorageService.d.ts +2 -1
- package/dist/odspDeltaStorageService.d.ts.map +1 -1
- package/dist/odspDeltaStorageService.js +5 -4
- package/dist/odspDeltaStorageService.js.map +1 -1
- package/dist/odspDocumentService.d.ts +1 -0
- package/dist/odspDocumentService.d.ts.map +1 -1
- package/dist/odspDocumentService.js +11 -5
- package/dist/odspDocumentService.js.map +1 -1
- package/dist/odspDocumentStorageManager.d.ts +4 -3
- package/dist/odspDocumentStorageManager.d.ts.map +1 -1
- package/dist/odspDocumentStorageManager.js +67 -60
- package/dist/odspDocumentStorageManager.js.map +1 -1
- package/dist/odspDriverUrlResolverForShareLink.d.ts.map +1 -1
- package/dist/odspDriverUrlResolverForShareLink.js +4 -4
- package/dist/odspDriverUrlResolverForShareLink.js.map +1 -1
- package/dist/odspLocationRedirection.d.ts +14 -0
- package/dist/odspLocationRedirection.d.ts.map +1 -0
- package/dist/odspLocationRedirection.js +24 -0
- package/dist/odspLocationRedirection.js.map +1 -0
- package/dist/odspSummaryUploadManager.d.ts +2 -1
- package/dist/odspSummaryUploadManager.d.ts.map +1 -1
- package/dist/odspSummaryUploadManager.js +3 -4
- package/dist/odspSummaryUploadManager.js.map +1 -1
- package/dist/odspUrlHelper.js +2 -1
- package/dist/odspUrlHelper.js.map +1 -1
- package/dist/odspUtils.d.ts.map +1 -1
- package/dist/odspUtils.js +10 -2
- package/dist/odspUtils.js.map +1 -1
- package/dist/packageVersion.d.ts +1 -1
- package/dist/packageVersion.d.ts.map +1 -1
- package/dist/packageVersion.js +1 -1
- package/dist/packageVersion.js.map +1 -1
- package/dist/retryUtils.d.ts.map +1 -1
- package/dist/retryUtils.js +8 -4
- package/dist/retryUtils.js.map +1 -1
- package/lib/compactSnapshotParser.d.ts.map +1 -1
- package/lib/compactSnapshotParser.js +4 -1
- package/lib/compactSnapshotParser.js.map +1 -1
- package/lib/compactSnapshotWriter.d.ts.map +1 -1
- package/lib/compactSnapshotWriter.js +6 -3
- package/lib/compactSnapshotWriter.js.map +1 -1
- package/lib/epochTracker.d.ts +1 -0
- package/lib/epochTracker.d.ts.map +1 -1
- package/lib/epochTracker.js +26 -7
- package/lib/epochTracker.js.map +1 -1
- package/lib/fetchSnapshot.d.ts.map +1 -1
- package/lib/fetchSnapshot.js +15 -12
- package/lib/fetchSnapshot.js.map +1 -1
- package/lib/getFileLink.d.ts +3 -6
- package/lib/getFileLink.d.ts.map +1 -1
- package/lib/getFileLink.js +29 -40
- package/lib/getFileLink.js.map +1 -1
- package/lib/odspDeltaStorageService.d.ts +2 -1
- package/lib/odspDeltaStorageService.d.ts.map +1 -1
- package/lib/odspDeltaStorageService.js +5 -4
- package/lib/odspDeltaStorageService.js.map +1 -1
- package/lib/odspDocumentService.d.ts +1 -0
- package/lib/odspDocumentService.d.ts.map +1 -1
- package/lib/odspDocumentService.js +13 -7
- package/lib/odspDocumentService.js.map +1 -1
- package/lib/odspDocumentStorageManager.d.ts +4 -3
- package/lib/odspDocumentStorageManager.d.ts.map +1 -1
- package/lib/odspDocumentStorageManager.js +68 -61
- package/lib/odspDocumentStorageManager.js.map +1 -1
- package/lib/odspDriverUrlResolverForShareLink.d.ts.map +1 -1
- package/lib/odspDriverUrlResolverForShareLink.js +4 -4
- package/lib/odspDriverUrlResolverForShareLink.js.map +1 -1
- package/lib/odspLocationRedirection.d.ts +14 -0
- package/lib/odspLocationRedirection.d.ts.map +1 -0
- package/lib/odspLocationRedirection.js +20 -0
- package/lib/odspLocationRedirection.js.map +1 -0
- package/lib/odspSummaryUploadManager.d.ts +2 -1
- package/lib/odspSummaryUploadManager.d.ts.map +1 -1
- package/lib/odspSummaryUploadManager.js +3 -4
- package/lib/odspSummaryUploadManager.js.map +1 -1
- package/lib/odspUrlHelper.js +2 -1
- package/lib/odspUrlHelper.js.map +1 -1
- package/lib/odspUtils.d.ts.map +1 -1
- package/lib/odspUtils.js +11 -3
- package/lib/odspUtils.js.map +1 -1
- package/lib/packageVersion.d.ts +1 -1
- package/lib/packageVersion.d.ts.map +1 -1
- package/lib/packageVersion.js +1 -1
- package/lib/packageVersion.js.map +1 -1
- package/lib/retryUtils.d.ts.map +1 -1
- package/lib/retryUtils.js +9 -5
- package/lib/retryUtils.js.map +1 -1
- package/package.json +16 -16
- package/src/compactSnapshotParser.ts +3 -1
- package/src/compactSnapshotWriter.ts +6 -3
- package/src/epochTracker.ts +47 -7
- package/src/fetchSnapshot.ts +29 -15
- package/src/getFileLink.ts +33 -46
- package/src/odspDeltaStorageService.ts +4 -2
- package/src/odspDocumentService.ts +16 -12
- package/src/odspDocumentStorageManager.ts +49 -41
- package/src/odspDriverUrlResolverForShareLink.ts +2 -5
- package/src/odspLocationRedirection.ts +23 -0
- package/src/odspSummaryUploadManager.ts +3 -3
- package/src/odspUrlHelper.ts +1 -1
- package/src/odspUtils.ts +15 -4
- package/src/packageVersion.ts +1 -1
- package/src/retryUtils.ts +8 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compactSnapshotParser.d.ts","sourceRoot":"","sources":["../src/compactSnapshotParser.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAa/C,eAAO,MAAM,sBAAsB,QAAQ,CAAC;AAC5C,eAAO,MAAM,kBAAkB,QAAQ,CAAC;
|
|
1
|
+
{"version":3,"file":"compactSnapshotParser.d.ts","sourceRoot":"","sources":["../src/compactSnapshotParser.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAa/C,eAAO,MAAM,sBAAsB,QAAQ,CAAC;AAC5C,eAAO,MAAM,kBAAkB,QAAQ,CAAC;AAkGxC;;;;GAIG;AACH,wBAAgB,4BAA4B,CAAC,MAAM,EAAE,UAAU,GAAG,iBAAiB,CA2BlF"}
|
|
@@ -60,10 +60,13 @@ function readTreeSection(node) {
|
|
|
60
60
|
(0, zipItDataRepresentationUtils_1.assertBlobCoreInstance)(records.value, "Blob value should be BlobCore");
|
|
61
61
|
snapshotTree.blobs[path] = records.value.toString();
|
|
62
62
|
}
|
|
63
|
-
else {
|
|
63
|
+
else if (records.children !== undefined) {
|
|
64
64
|
(0, zipItDataRepresentationUtils_1.assertNodeCoreInstance)(records.children, "Trees should be of type NodeCore");
|
|
65
65
|
snapshotTree.trees[path] = readTreeSection(records.children);
|
|
66
66
|
}
|
|
67
|
+
else {
|
|
68
|
+
snapshotTree.trees[path] = { blobs: {}, commits: {}, trees: {} };
|
|
69
|
+
}
|
|
67
70
|
if (records.unreferenced !== undefined) {
|
|
68
71
|
(0, zipItDataRepresentationUtils_1.assertBoolInstance)(records.unreferenced, "Unreferenced flag should be bool");
|
|
69
72
|
const unreferenced = records.unreferenced.valueOf();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"comp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,eAAe,CAAC,OAAO,CAAC,KAAK,CAAC,EACrC,GAAG,EAAE,OAAO,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,cAAc,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,EACvE,oBAAoB,EAAE,OAAO,CAAC,GAAG,IACnC;AACN,CAAC;AA3BD,oEA2BC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { assert } from \"@fluidframework/common-utils\";\nimport { ISequencedDocumentMessage, ISnapshotTree } from \"@fluidframework/protocol-definitions\";\nimport { ISnapshotContents } from \"./odspPublicUtils\";\nimport { ReadBuffer } from \"./ReadBufferUtils\";\nimport { ISnapshotTreeEx } from \"./contracts\";\nimport {\n assertBlobCoreInstance,\n assertBoolInstance,\n assertNodeCoreInstance,\n assertNumberInstance,\n getAndValidateNodeProps,\n NodeCore,\n NodeTypes,\n TreeBuilder,\n} from \"./zipItDataRepresentationUtils\";\n\nexport const snapshotMinReadVersion = \"1.0\";\nexport const currentReadVersion = \"1.0\";\n\ninterface ISnapshotSection {\n snapshotTree: ISnapshotTree;\n sequenceNumber: number;\n}\n\n/**\n * Recreates blobs section of the tree.\n * @param node - tree node to read blob section from\n */\nfunction readBlobSection(node: NodeTypes) {\n assertNodeCoreInstance(node, \"TreeBlobs should be of type NodeCore\");\n const blobs: Map<string, ArrayBuffer> = new Map();\n for (let count = 0; count < node.length; ++count) {\n const blob = node.getNode(count);\n const records = getAndValidateNodeProps(blob, [\"id\", \"data\"]);\n assertBlobCoreInstance(records.data, \"data should be of BlobCore type\");\n assertBlobCoreInstance(records.id, \"blob id should be of BlobCore type\");\n blobs.set(records.id.toString(), records.data.arrayBuffer);\n }\n return blobs;\n}\n\n/**\n * Recreates ops section of the tree.\n * @param node - tree node to read ops section from\n */\nfunction readOpsSection(node: NodeTypes) {\n assertNodeCoreInstance(node, \"Deltas should be of type NodeCore\");\n const ops: ISequencedDocumentMessage[] = [];\n const records = getAndValidateNodeProps(node, [\"firstSequenceNumber\", \"deltas\"]);\n assertNumberInstance(records.firstSequenceNumber, \"Seq number should be a number\");\n assertNodeCoreInstance(records.deltas, \"Deltas should be a Node\");\n for (let i = 0; i < records.deltas.length; ++i) {\n ops.push(JSON.parse(records.deltas.getString(i)));\n }\n assert(records.firstSequenceNumber.valueOf() === ops[0].sequenceNumber,\n 0x280 /* \"Validate first op seq number\" */);\n return ops;\n}\n\n/**\n * Recreates snapshot tree out of tree representation.\n * @param node - tree node to de-serialize from\n */\nfunction readTreeSection(node: NodeCore) {\n const snapshotTree: ISnapshotTreeEx = {\n blobs: {},\n commits: {},\n trees: {},\n };\n for (let count = 0; count < node.length; count++) {\n const treeNode = node.getNode(count);\n const records = getAndValidateNodeProps(treeNode,\n [\"name\", \"value\", \"children\", \"unreferenced\"], false);\n assertBlobCoreInstance(records.name, \"Path should be of BlobCore\");\n const path = records.name.toString();\n if (records.value !== undefined) {\n assertBlobCoreInstance(records.value, \"Blob value should be BlobCore\");\n snapshotTree.blobs[path] = records.value.toString();\n } else {\n assertNodeCoreInstance(records.children, \"Trees should be of type NodeCore\");\n snapshotTree.trees[path] = readTreeSection(records.children);\n }\n if (records.unreferenced !== undefined) {\n assertBoolInstance(records.unreferenced, \"Unreferenced flag should be bool\");\n const unreferenced = records.unreferenced.valueOf();\n assert(unreferenced, 0x281 /* \"Unreferenced if present should be true\" */);\n snapshotTree.unreferenced = unreferenced;\n }\n }\n return snapshotTree;\n}\n\n/**\n * Recreates snapshot tree out of tree representation.\n * @param node - tree node to de-serialize from\n */\nfunction readSnapshotSection(node: NodeTypes): ISnapshotSection {\n assertNodeCoreInstance(node, \"Snapshot should be of type NodeCore\");\n const records = getAndValidateNodeProps(node,\n [\"id\", \"sequenceNumber\", \"treeNodes\"]);\n\n assertNodeCoreInstance(records.treeNodes, \"TreeNodes should be of type NodeCore\");\n assertNumberInstance(records.sequenceNumber, \"sequenceNumber should be of type number\");\n assertBlobCoreInstance(records.id, \"snapshotId should be BlobCore\");\n const snapshotTree: ISnapshotTree = readTreeSection(records.treeNodes);\n snapshotTree.id = records.id.toString();\n const sequenceNumber = records.sequenceNumber.valueOf();\n return {\n sequenceNumber,\n snapshotTree,\n };\n}\n\n/**\n * Converts snapshot from binary compact representation to tree/blobs/ops.\n * @param buffer - Compact snapshot to be parsed into tree/blobs/ops.\n * @returns - tree, blobs and ops from the snapshot.\n */\nexport function parseCompactSnapshotResponse(buffer: ReadBuffer): ISnapshotContents {\n const builder = TreeBuilder.load(buffer);\n assert(builder.length === 1, 0x219 /* \"1 root should be there\" */);\n const root = builder.getNode(0);\n\n const records = getAndValidateNodeProps(root,\n [\"mrv\", \"cv\", \"lsn\", \"snapshot\", \"blobs\", \"deltas\"], false);\n\n assertBlobCoreInstance(records.mrv, \"minReadVersion should be of BlobCore type\");\n assertBlobCoreInstance(records.cv, \"createVersion should be of BlobCore type\");\n if (records.lsn !== undefined) {\n assertNumberInstance(records.lsn, \"lsn should be a number\");\n }\n\n assert(parseFloat(snapshotMinReadVersion) >= parseFloat(records.mrv.toString()),\n 0x20f /* \"Driver min read version should >= to server minReadVersion\" */);\n assert(parseFloat(records.cv.toString()) >= parseFloat(snapshotMinReadVersion),\n 0x210 /* \"Snapshot should be created with minReadVersion or above\" */);\n assert(currentReadVersion === records.cv.toString(),\n 0x2c2 /* \"Create Version should be equal to currentReadVersion\" */);\n\n return {\n ...readSnapshotSection(records.snapshot),\n blobs: readBlobSection(records.blobs),\n ops: records.deltas !== undefined ? readOpsSection(records.deltas) : [],\n latestSequenceNumber: records.lsn,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"compactSnapshotParser.js","sourceRoot":"","sources":["../src/compactSnapshotParser.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,+DAAsD;AAKtD,iFASwC;AAE3B,QAAA,sBAAsB,GAAG,KAAK,CAAC;AAC/B,QAAA,kBAAkB,GAAG,KAAK,CAAC;AAOxC;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CAAC,OAAO,CAAC,KAAK,CAAC,EACrC,GAAG,EAAE,OAAO,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,cAAc,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,EACvE,oBAAoB,EAAE,OAAO,CAAC,GAAG,IACnC;AACN,CAAC;AA3BD,oEA2BC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { assert } from \"@fluidframework/common-utils\";\nimport { ISequencedDocumentMessage, ISnapshotTree } from \"@fluidframework/protocol-definitions\";\nimport { ISnapshotContents } from \"./odspPublicUtils\";\nimport { ReadBuffer } from \"./ReadBufferUtils\";\nimport { ISnapshotTreeEx } from \"./contracts\";\nimport {\n assertBlobCoreInstance,\n assertBoolInstance,\n assertNodeCoreInstance,\n assertNumberInstance,\n getAndValidateNodeProps,\n NodeCore,\n NodeTypes,\n TreeBuilder,\n} from \"./zipItDataRepresentationUtils\";\n\nexport const snapshotMinReadVersion = \"1.0\";\nexport const currentReadVersion = \"1.0\";\n\ninterface ISnapshotSection {\n snapshotTree: ISnapshotTree;\n sequenceNumber: number;\n}\n\n/**\n * Recreates blobs section of the tree.\n * @param node - tree node to read blob section from\n */\nfunction readBlobSection(node: NodeTypes) {\n assertNodeCoreInstance(node, \"TreeBlobs should be of type NodeCore\");\n const blobs: Map<string, ArrayBuffer> = new Map();\n for (let count = 0; count < node.length; ++count) {\n const blob = node.getNode(count);\n const records = getAndValidateNodeProps(blob, [\"id\", \"data\"]);\n assertBlobCoreInstance(records.data, \"data should be of BlobCore type\");\n assertBlobCoreInstance(records.id, \"blob id should be of BlobCore type\");\n blobs.set(records.id.toString(), records.data.arrayBuffer);\n }\n return blobs;\n}\n\n/**\n * Recreates ops section of the tree.\n * @param node - tree node to read ops section from\n */\nfunction readOpsSection(node: NodeTypes) {\n assertNodeCoreInstance(node, \"Deltas should be of type NodeCore\");\n const ops: ISequencedDocumentMessage[] = [];\n const records = getAndValidateNodeProps(node, [\"firstSequenceNumber\", \"deltas\"]);\n assertNumberInstance(records.firstSequenceNumber, \"Seq number should be a number\");\n assertNodeCoreInstance(records.deltas, \"Deltas should be a Node\");\n for (let i = 0; i < records.deltas.length; ++i) {\n ops.push(JSON.parse(records.deltas.getString(i)));\n }\n assert(records.firstSequenceNumber.valueOf() === ops[0].sequenceNumber,\n 0x280 /* \"Validate first op seq number\" */);\n return ops;\n}\n\n/**\n * Recreates snapshot tree out of tree representation.\n * @param node - tree node to de-serialize from\n */\nfunction readTreeSection(node: NodeCore) {\n const snapshotTree: ISnapshotTreeEx = {\n blobs: {},\n commits: {},\n trees: {},\n };\n for (let count = 0; count < node.length; count++) {\n const treeNode = node.getNode(count);\n const records = getAndValidateNodeProps(treeNode,\n [\"name\", \"value\", \"children\", \"unreferenced\"], false);\n assertBlobCoreInstance(records.name, \"Path should be of BlobCore\");\n const path = records.name.toString();\n if (records.value !== undefined) {\n assertBlobCoreInstance(records.value, \"Blob value should be BlobCore\");\n snapshotTree.blobs[path] = records.value.toString();\n } else if (records.children !== undefined) {\n assertNodeCoreInstance(records.children, \"Trees should be of type NodeCore\");\n snapshotTree.trees[path] = readTreeSection(records.children);\n } else {\n snapshotTree.trees[path] = { blobs: {}, commits: {}, trees: {} };\n }\n if (records.unreferenced !== undefined) {\n assertBoolInstance(records.unreferenced, \"Unreferenced flag should be bool\");\n const unreferenced = records.unreferenced.valueOf();\n assert(unreferenced, 0x281 /* \"Unreferenced if present should be true\" */);\n snapshotTree.unreferenced = unreferenced;\n }\n }\n return snapshotTree;\n}\n\n/**\n * Recreates snapshot tree out of tree representation.\n * @param node - tree node to de-serialize from\n */\nfunction readSnapshotSection(node: NodeTypes): ISnapshotSection {\n assertNodeCoreInstance(node, \"Snapshot should be of type NodeCore\");\n const records = getAndValidateNodeProps(node,\n [\"id\", \"sequenceNumber\", \"treeNodes\"]);\n\n assertNodeCoreInstance(records.treeNodes, \"TreeNodes should be of type NodeCore\");\n assertNumberInstance(records.sequenceNumber, \"sequenceNumber should be of type number\");\n assertBlobCoreInstance(records.id, \"snapshotId should be BlobCore\");\n const snapshotTree: ISnapshotTree = readTreeSection(records.treeNodes);\n snapshotTree.id = records.id.toString();\n const sequenceNumber = records.sequenceNumber.valueOf();\n return {\n sequenceNumber,\n snapshotTree,\n };\n}\n\n/**\n * Converts snapshot from binary compact representation to tree/blobs/ops.\n * @param buffer - Compact snapshot to be parsed into tree/blobs/ops.\n * @returns - tree, blobs and ops from the snapshot.\n */\nexport function parseCompactSnapshotResponse(buffer: ReadBuffer): ISnapshotContents {\n const builder = TreeBuilder.load(buffer);\n assert(builder.length === 1, 0x219 /* \"1 root should be there\" */);\n const root = builder.getNode(0);\n\n const records = getAndValidateNodeProps(root,\n [\"mrv\", \"cv\", \"lsn\", \"snapshot\", \"blobs\", \"deltas\"], false);\n\n assertBlobCoreInstance(records.mrv, \"minReadVersion should be of BlobCore type\");\n assertBlobCoreInstance(records.cv, \"createVersion should be of BlobCore type\");\n if (records.lsn !== undefined) {\n assertNumberInstance(records.lsn, \"lsn should be a number\");\n }\n\n assert(parseFloat(snapshotMinReadVersion) >= parseFloat(records.mrv.toString()),\n 0x20f /* \"Driver min read version should >= to server minReadVersion\" */);\n assert(parseFloat(records.cv.toString()) >= parseFloat(snapshotMinReadVersion),\n 0x210 /* \"Snapshot should be created with minReadVersion or above\" */);\n assert(currentReadVersion === records.cv.toString(),\n 0x2c2 /* \"Create Version should be equal to currentReadVersion\" */);\n\n return {\n ...readSnapshotSection(records.snapshot),\n blobs: readBlobSection(records.blobs),\n ops: records.deltas !== undefined ? readOpsSection(records.deltas) : [],\n latestSequenceNumber: records.lsn,\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compactSnapshotWriter.d.ts","sourceRoot":"","sources":["../src/compactSnapshotWriter.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAKH,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"compactSnapshotWriter.d.ts","sourceRoot":"","sources":["../src/compactSnapshotWriter.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAKH,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAqH/C;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,gBAAgB,EAAE,iBAAiB,GAAG,UAAU,CAyBxF"}
|
|
@@ -57,9 +57,12 @@ function writeTreeSectionCore(treesNode, snapshotTree) {
|
|
|
57
57
|
if (snapshotTree.unreferenced) {
|
|
58
58
|
(0, zipItDataRepresentationUtils_1.addBoolProperty)(treeNode, "unreferenced", snapshotTree.unreferenced);
|
|
59
59
|
}
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
60
|
+
// Only write children prop if either blobs or trees are present.
|
|
61
|
+
if (Object.keys(value.blobs).length > 0 || Object.keys(value.trees).length > 0) {
|
|
62
|
+
treeNode.addString("children", true);
|
|
63
|
+
const childNode = treeNode.addNode("list");
|
|
64
|
+
writeTreeSectionCore(childNode, value);
|
|
65
|
+
}
|
|
63
66
|
}
|
|
64
67
|
if (snapshotTree.blobs) {
|
|
65
68
|
for (const [path, id] of Object.entries(snapshotTree.blobs)) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compactSnapshotWriter.js","sourceRoot":"","sources":["../src/compactSnapshotWriter.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,+DAAsE;AAEtE,mEAAiE;AAGjE,yDAA2D;AAC3D,iFAAiH;AAEjH;;;;EAIE;AACF,SAAS,kBAAkB,CAAC,IAAc,EAAE,oBAA4B;IACpE,IAAA,gDAAiB,EAAC,IAAI,EAAE,KAAK,EAAE,8CAAsB,CAAC,CAAC;IACvD,IAAA,gDAAiB,EAAC,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AgB,CAAC,cAAc,KAAK,SAAS,EAAE,KAAK,CAAC,qCAAqC,CAAC,CAAC;IAEnG,MAAM,oBAAoB,GAAG,CAAA,MAAA,gBAAgB,CAAC,oBAAoB,mCAC9D,gBAAgB,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,EAAC,CAAC;QACjC,gBAAgB,CAAC,GAAG,CAAC,gBAAgB,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,gBAAgB,CAAC,cAAc,CAAC;IAE3G,kBAAkB,CAAC,QAAQ,EAAE,oBAAoB,CAAC,CAAC;IAEnD,oBAAoB,CAChB,QAAQ,EACR,gBAAgB,CAAC,YAAY,EAC7B,gBAAgB,CAAC,cAAc,CAClC,CAAC;IAEF,YAAY;IACZ,iBAAiB,CAAC,QAAQ,EAAE,gBAAgB,CAAC,KAAK,CAAC,CAAC;IAEpD,2BAA2B;IAC3B,eAAe,CAAC,QAAQ,EAAE,gBAAgB,CAAC,GAAG,CAAC,CAAC;IAEhD,OAAO,OAAO,CAAC,SAAS,EAAE,CAAC;AAC/B,CAAC;AAzBD,4DAyBC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { assert, stringToBuffer } from \"@fluidframework/common-utils\";\nimport { IBlob, ISequencedDocumentMessage, ISnapshotTree } from \"@fluidframework/protocol-definitions\";\nimport { snapshotMinReadVersion } from \"./compactSnapshotParser\";\nimport { ISnapshotContents } from \"./odspPublicUtils\";\nimport { ReadBuffer } from \"./ReadBufferUtils\";\nimport { TreeBuilderSerializer } from \"./WriteBufferUtils\";\nimport { addBoolProperty, addNumberProperty, addStringProperty, NodeCore } from \"./zipItDataRepresentationUtils\";\n\n/**\n * Writes header section of the snapshot.\n * @param node - snapshot node to serialize to\n * @param latestSequenceNumber - latest seq number of the container.\n*/\nfunction writeSnapshotProps(node: NodeCore, latestSequenceNumber: number) {\n addStringProperty(node, \"mrv\", snapshotMinReadVersion);\n addStringProperty(node, \"cv\", snapshotMinReadVersion);\n addNumberProperty(node, \"lsn\", latestSequenceNumber);\n}\n\n/**\n * Represents blobs in the tree.\n * @param snapshotNode - node to serialize to.\n * @param blobs - blobs that is being serialized\n*/\nfunction writeBlobsSection(snapshotNode: NodeCore, blobs: Map<string, IBlob | ArrayBuffer>) {\n snapshotNode.addString(\"blobs\", true);\n const blobsNode = snapshotNode.addNode(\"list\");\n for (const [storageBlobId, blob] of blobs) {\n const blobNode = blobsNode.addNode();\n addStringProperty(blobNode, \"id\", storageBlobId, true);\n blobNode.addString(\"data\", true);\n if (blob instanceof ArrayBuffer) {\n blobNode.addBlob(new Uint8Array(blob), false);\n } else {\n blobNode.addBlob(new Uint8Array(stringToBuffer(blob.contents, blob.encoding ?? \"utf-8\")), false);\n }\n }\n}\n\n/**\n * Represents and serializes tree part of the snapshot\n * @param snapshotNode - tree node to serialize to\n * @param snapshotTree - snapshot tree that is being serialized\n*/\nfunction writeTreeSection(snapshotNode: NodeCore, snapshotTree: ISnapshotTree) {\n snapshotNode.addString(\"treeNodes\", true);\n const treesNode = snapshotNode.addNode(\"list\");\n writeTreeSectionCore(treesNode, snapshotTree);\n}\n\nfunction writeTreeSectionCore(treesNode: NodeCore, snapshotTree: ISnapshotTree) {\n for (const [path, value] of Object.entries(snapshotTree.trees)) {\n const treeNode = treesNode.addNode();\n addStringProperty(treeNode, \"name\", path);\n if (snapshotTree.unreferenced) {\n addBoolProperty(treeNode, \"unreferenced\", snapshotTree.unreferenced);\n }\n treeNode.addString(\"children\", true);\n const childNode = treeNode.addNode(\"list\");\n writeTreeSectionCore(childNode, value);\n }\n\n if (snapshotTree.blobs) {\n for (const [path, id] of Object.entries(snapshotTree.blobs)) {\n const blobNode = treesNode.addNode();\n addStringProperty(blobNode, \"name\", path);\n addStringProperty(blobNode, \"value\", id, true);\n }\n }\n}\n\n/**\n * Represents (serializes) snapshot tree as generalizes tree\n * @param rootNode - tree node to serialize to\n * @param snapshotTree - snapshot tree that is being serialized\n * @param blobs - blobs mapping of the snapshot\n * @param snapshotSequenceNumber - seq number at which snapshot is taken\n*/\nfunction writeSnapshotSection(\n rootNode: NodeCore,\n snapshotTree: ISnapshotTree,\n snapshotSequenceNumber: number,\n) {\n rootNode.addString(\"snapshot\", true);\n const snapshotNode = rootNode.addNode();\n\n const snapshotId = snapshotTree.id;\n assert(snapshotId !== undefined, 0x21b /* \"Snapshot id should be provided\" */);\n addStringProperty(snapshotNode, \"id\", snapshotId);\n addStringProperty(snapshotNode, \"message\", `Snapshot@${snapshotSequenceNumber}`);\n addNumberProperty(snapshotNode, \"sequenceNumber\", snapshotSequenceNumber);\n\n // Add Trees\n writeTreeSection(snapshotNode, snapshotTree);\n}\n\n/**\n * Represents ops in the tree.\n * @param rootNode - node to serialize to.\n * @param ops - ops that is being serialized\n*/\nfunction writeOpsSection(rootNode: NodeCore, ops: ISequencedDocumentMessage[]) {\n let firstSequenceNumber: number | undefined;\n if (ops.length > 0) {\n firstSequenceNumber = ops[0].sequenceNumber;\n }\n if (firstSequenceNumber !== undefined) {\n rootNode.addString(\"deltas\", true);\n const opsNode = rootNode.addNode();\n addNumberProperty(opsNode, \"firstSequenceNumber\", firstSequenceNumber);\n opsNode.addString(\"deltas\", true);\n const deltaNode = opsNode.addNode(\"list\");\n ops.forEach((op) => {\n deltaNode.addString(JSON.stringify(op), false);\n });\n }\n}\n\n/**\n * Converts trees/blobs/ops to binary compact representation.\n * @param snapshotContents - snapshot tree contents to serialize\n * @returns - ReadBuffer - binary representation of the data.\n */\nexport function convertToCompactSnapshot(snapshotContents: ISnapshotContents): ReadBuffer {\n const builder = new TreeBuilderSerializer();\n // Create the root node.\n const rootNode = builder.addNode();\n assert(snapshotContents.sequenceNumber !== undefined, 0x21c /* \"Seq number should be provided\" */);\n\n const latestSequenceNumber = snapshotContents.latestSequenceNumber ??\n snapshotContents.ops.length > 0 ?\n snapshotContents.ops[snapshotContents.ops.length - 1].sequenceNumber : snapshotContents.sequenceNumber;\n\n writeSnapshotProps(rootNode, latestSequenceNumber);\n\n writeSnapshotSection(\n rootNode,\n snapshotContents.snapshotTree,\n snapshotContents.sequenceNumber,\n );\n\n // Add Blobs\n writeBlobsSection(rootNode, snapshotContents.blobs);\n\n // Then write the ops node.\n writeOpsSection(rootNode, snapshotContents.ops);\n\n return builder.serialize();\n}\n"]}
|
|
1
|
+
{"version":3,"file":"compactSnapshotWriter.js","sourceRoot":"","sources":["../src/compactSnapshotWriter.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,+DAAsE;AAEtE,mEAAiE;AAGjE,yDAA2D;AAC3D,iFAAiH;AAEjH;;;;EAIE;AACF,SAAS,kBAAkB,CAAC,IAAc,EAAE,oBAA4B;IACpE,IAAA,gDAAiB,EAAC,IAAI,EAAE,KAAK,EAAE,8CAAsB,CAAC,CAAC;IACvD,IAAA,gDAAiB,EAAC,IAAI,EAAE,IAAI,EAAE,8CAAsB,CAAC,CAAC;IACtD,IAAA,gDAAiB,EAAC,IAAI,EAAE,KAAK,EAAE,oBAAoB,CAAC,CAAC;AACzD,CAAC;AAED;;;;EAIE;AACF,SAAS,iBAAiB,CAAC,YAAsB,EAAE,KAAuC;;IACtF,YAAY,CAAC,SAAS,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IACtC,MAAM,SAAS,GAAG,YAAY,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IAC/C,KAAK,MAAM,CAAC,aAAa,EAAE,IAAI,CAAC,IAAI,KAAK,EAAE;QACvC,MAAM,QAAQ,GAAG,SAAS,CAAC,OAAO,EAAE,CAAC;QACrC,IAAA,gDAAiB,EAAC,QAAQ,EAAE,IAAI,EAAE,aAAa,EAAE,IAAI,CAAC,CAAC;QACvD,QAAQ,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QACjC,IAAI,IAAI,YAAY,WAAW,EAAE;YAC7B,QAAQ,CAAC,OAAO,CAAC,IAAI,UAAU,C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AClC,CAAC;IAEF,YAAY;IACZ,iBAAiB,CAAC,QAAQ,EAAE,gBAAgB,CAAC,KAAK,CAAC,CAAC;IAEpD,2BAA2B;IAC3B,eAAe,CAAC,QAAQ,EAAE,gBAAgB,CAAC,GAAG,CAAC,CAAC;IAEhD,OAAO,OAAO,CAAC,SAAS,EAAE,CAAC;AAC/B,CAAC;AAzBD,4DAyBC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { assert, stringToBuffer } from \"@fluidframework/common-utils\";\nimport { IBlob, ISequencedDocumentMessage, ISnapshotTree } from \"@fluidframework/protocol-definitions\";\nimport { snapshotMinReadVersion } from \"./compactSnapshotParser\";\nimport { ISnapshotContents } from \"./odspPublicUtils\";\nimport { ReadBuffer } from \"./ReadBufferUtils\";\nimport { TreeBuilderSerializer } from \"./WriteBufferUtils\";\nimport { addBoolProperty, addNumberProperty, addStringProperty, NodeCore } from \"./zipItDataRepresentationUtils\";\n\n/**\n * Writes header section of the snapshot.\n * @param node - snapshot node to serialize to\n * @param latestSequenceNumber - latest seq number of the container.\n*/\nfunction writeSnapshotProps(node: NodeCore, latestSequenceNumber: number) {\n addStringProperty(node, \"mrv\", snapshotMinReadVersion);\n addStringProperty(node, \"cv\", snapshotMinReadVersion);\n addNumberProperty(node, \"lsn\", latestSequenceNumber);\n}\n\n/**\n * Represents blobs in the tree.\n * @param snapshotNode - node to serialize to.\n * @param blobs - blobs that is being serialized\n*/\nfunction writeBlobsSection(snapshotNode: NodeCore, blobs: Map<string, IBlob | ArrayBuffer>) {\n snapshotNode.addString(\"blobs\", true);\n const blobsNode = snapshotNode.addNode(\"list\");\n for (const [storageBlobId, blob] of blobs) {\n const blobNode = blobsNode.addNode();\n addStringProperty(blobNode, \"id\", storageBlobId, true);\n blobNode.addString(\"data\", true);\n if (blob instanceof ArrayBuffer) {\n blobNode.addBlob(new Uint8Array(blob), false);\n } else {\n blobNode.addBlob(new Uint8Array(stringToBuffer(blob.contents, blob.encoding ?? \"utf-8\")), false);\n }\n }\n}\n\n/**\n * Represents and serializes tree part of the snapshot\n * @param snapshotNode - tree node to serialize to\n * @param snapshotTree - snapshot tree that is being serialized\n*/\nfunction writeTreeSection(snapshotNode: NodeCore, snapshotTree: ISnapshotTree) {\n snapshotNode.addString(\"treeNodes\", true);\n const treesNode = snapshotNode.addNode(\"list\");\n writeTreeSectionCore(treesNode, snapshotTree);\n}\n\nfunction writeTreeSectionCore(treesNode: NodeCore, snapshotTree: ISnapshotTree) {\n for (const [path, value] of Object.entries(snapshotTree.trees)) {\n const treeNode = treesNode.addNode();\n addStringProperty(treeNode, \"name\", path);\n if (snapshotTree.unreferenced) {\n addBoolProperty(treeNode, \"unreferenced\", snapshotTree.unreferenced);\n }\n // Only write children prop if either blobs or trees are present.\n if (Object.keys(value.blobs).length > 0 || Object.keys(value.trees).length > 0) {\n treeNode.addString(\"children\", true);\n const childNode = treeNode.addNode(\"list\");\n writeTreeSectionCore(childNode, value);\n }\n }\n\n if (snapshotTree.blobs) {\n for (const [path, id] of Object.entries(snapshotTree.blobs)) {\n const blobNode = treesNode.addNode();\n addStringProperty(blobNode, \"name\", path);\n addStringProperty(blobNode, \"value\", id, true);\n }\n }\n}\n\n/**\n * Represents (serializes) snapshot tree as generalizes tree\n * @param rootNode - tree node to serialize to\n * @param snapshotTree - snapshot tree that is being serialized\n * @param blobs - blobs mapping of the snapshot\n * @param snapshotSequenceNumber - seq number at which snapshot is taken\n*/\nfunction writeSnapshotSection(\n rootNode: NodeCore,\n snapshotTree: ISnapshotTree,\n snapshotSequenceNumber: number,\n) {\n rootNode.addString(\"snapshot\", true);\n const snapshotNode = rootNode.addNode();\n\n const snapshotId = snapshotTree.id;\n assert(snapshotId !== undefined, 0x21b /* \"Snapshot id should be provided\" */);\n addStringProperty(snapshotNode, \"id\", snapshotId);\n addStringProperty(snapshotNode, \"message\", `Snapshot@${snapshotSequenceNumber}`);\n addNumberProperty(snapshotNode, \"sequenceNumber\", snapshotSequenceNumber);\n\n // Add Trees\n writeTreeSection(snapshotNode, snapshotTree);\n}\n\n/**\n * Represents ops in the tree.\n * @param rootNode - node to serialize to.\n * @param ops - ops that is being serialized\n*/\nfunction writeOpsSection(rootNode: NodeCore, ops: ISequencedDocumentMessage[]) {\n let firstSequenceNumber: number | undefined;\n if (ops.length > 0) {\n firstSequenceNumber = ops[0].sequenceNumber;\n }\n if (firstSequenceNumber !== undefined) {\n rootNode.addString(\"deltas\", true);\n const opsNode = rootNode.addNode();\n addNumberProperty(opsNode, \"firstSequenceNumber\", firstSequenceNumber);\n opsNode.addString(\"deltas\", true);\n const deltaNode = opsNode.addNode(\"list\");\n ops.forEach((op) => {\n deltaNode.addString(JSON.stringify(op), false);\n });\n }\n}\n\n/**\n * Converts trees/blobs/ops to binary compact representation.\n * @param snapshotContents - snapshot tree contents to serialize\n * @returns - ReadBuffer - binary representation of the data.\n */\nexport function convertToCompactSnapshot(snapshotContents: ISnapshotContents): ReadBuffer {\n const builder = new TreeBuilderSerializer();\n // Create the root node.\n const rootNode = builder.addNode();\n assert(snapshotContents.sequenceNumber !== undefined, 0x21c /* \"Seq number should be provided\" */);\n\n const latestSequenceNumber = snapshotContents.latestSequenceNumber ??\n snapshotContents.ops.length > 0 ?\n snapshotContents.ops[snapshotContents.ops.length - 1].sequenceNumber : snapshotContents.sequenceNumber;\n\n writeSnapshotProps(rootNode, latestSequenceNumber);\n\n writeSnapshotSection(\n rootNode,\n snapshotContents.snapshotTree,\n snapshotContents.sequenceNumber,\n );\n\n // Add Blobs\n writeBlobsSection(rootNode, snapshotContents.blobs);\n\n // Then write the ops node.\n writeOpsSection(rootNode, snapshotContents.ops);\n\n return builder.serialize();\n}\n"]}
|
package/dist/epochTracker.d.ts
CHANGED
|
@@ -24,6 +24,7 @@ export declare class EpochTracker implements IPersistedFileCache {
|
|
|
24
24
|
protected readonly logger: ITelemetryLogger;
|
|
25
25
|
protected readonly clientIsSummarizer?: boolean | undefined;
|
|
26
26
|
private _fluidEpoch;
|
|
27
|
+
private readonly snapshotCacheExpiryTimeoutMs;
|
|
27
28
|
readonly rateLimiter: RateLimiter;
|
|
28
29
|
private readonly driverId;
|
|
29
30
|
private networkCallNumber;
|
|
@@ -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,
|
|
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,EAEH,WAAW,EAGd,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,UAAU,EAAE,MAAM,sCAAsC,CAAC;AAClE,OAAO,EAGH,MAAM,EACN,UAAU,EACV,eAAe,EAIlB,MAAM,yCAAyC,CAAC;AAQjD,OAAO,EAA0E,aAAa,EAAE,MAAM,aAAa,CAAC;AACpH,OAAO,EACH,UAAU,EACV,mBAAmB,EACnB,mBAAmB,EACrB,MAAM,aAAa,CAAC;AAMtB,oBAAY,SAAS,GAAG,MAAM,GAAG,YAAY,GAAG,YAAY,GAAG,aAAa,GAAG,KAAK,GAAG,MAAM,GAAG,cAAc,GAC1G,aAAa,GAAG,eAAe,GAAG,MAAM,GAAG,UAAU,CAAC;AAE1D,oBAAY,iBAAiB,GAAG,SAAS,GAAG,OAAO,CAAC;AAEpD,eAAO,MAAM,YAAY,iBAAiB,CAAC;AAG3C,eAAO,MAAM,2BAA2B,EAAE,MAAgC,CAAC;AAE3E;;;;;GAKG;AACH,qBAAa,YAAa,YAAW,mBAAmB;IAShD,SAAS,CAAC,QAAQ,CAAC,KAAK,EAAE,eAAe;IACzC,SAAS,CAAC,QAAQ,CAAC,SAAS,EAAE,UAAU;IACx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
|
|
|
15
15
|
const contracts_1 = require("./contracts");
|
|
16
16
|
const contractsPublic_1 = require("./contractsPublic");
|
|
17
17
|
const packageVersion_1 = require("./packageVersion");
|
|
18
|
+
const odspLocationRedirection_1 = require("./odspLocationRedirection");
|
|
18
19
|
exports.Odsp409Error = "Odsp409Error";
|
|
19
20
|
// Please update the README file in odsp-driver-definitions if you change the defaultCacheExpiryTimeoutMs.
|
|
20
21
|
exports.defaultCacheExpiryTimeoutMs = 2 * 24 * 60 * 60 * 1000;
|
|
@@ -35,6 +36,11 @@ class EpochTracker {
|
|
|
35
36
|
this.networkCallNumber = 1;
|
|
36
37
|
// Limits the max number of concurrent requests to 24.
|
|
37
38
|
this.rateLimiter = new driver_utils_1.RateLimiter(24);
|
|
39
|
+
// We need this for GC testing until we properly plumb through the snapshot expiration policy (see PR #11168)
|
|
40
|
+
this.snapshotCacheExpiryTimeoutMs =
|
|
41
|
+
(0, telemetry_utils_1.loggerToMonitoringContext)(logger).config.getBoolean("Fluid.Driver.Odsp.TestOverride.DisableSnapshotCache")
|
|
42
|
+
? 0
|
|
43
|
+
: exports.defaultCacheExpiryTimeoutMs;
|
|
38
44
|
}
|
|
39
45
|
// public for UT purposes only!
|
|
40
46
|
setEpoch(epoch, fromCache, fetchType) {
|
|
@@ -66,16 +72,16 @@ class EpochTracker {
|
|
|
66
72
|
else if (this._fluidEpoch !== value.fluidEpoch) {
|
|
67
73
|
return undefined;
|
|
68
74
|
}
|
|
69
|
-
// Expire the cached snapshot if it's older than
|
|
75
|
+
// Expire the cached snapshot if it's older than snapshotCacheExpiryTimeoutMs and immediately
|
|
70
76
|
// expire all old caches that do not have cacheEntryTime
|
|
71
77
|
if (entry.type === odsp_driver_definitions_1.snapshotKey) {
|
|
72
78
|
const cacheTime = (_a = value.value) === null || _a === void 0 ? void 0 : _a.cacheEntryTime;
|
|
73
79
|
const currentTime = Date.now();
|
|
74
|
-
if (cacheTime === undefined || currentTime - cacheTime >=
|
|
80
|
+
if (cacheTime === undefined || currentTime - cacheTime >= this.snapshotCacheExpiryTimeoutMs) {
|
|
75
81
|
this.logger.sendTelemetryEvent({
|
|
76
82
|
eventName: "odspVersionsCacheExpired",
|
|
77
83
|
duration: currentTime - cacheTime,
|
|
78
|
-
maxCacheAgeMs:
|
|
84
|
+
maxCacheAgeMs: this.snapshotCacheExpiryTimeoutMs,
|
|
79
85
|
});
|
|
80
86
|
await this.removeEntries();
|
|
81
87
|
return undefined;
|
|
@@ -92,8 +98,8 @@ class EpochTracker {
|
|
|
92
98
|
async put(entry, value) {
|
|
93
99
|
var _a;
|
|
94
100
|
(0, common_utils_1.assert)(this._fluidEpoch !== undefined, 0x1dd /* "no epoch" */);
|
|
95
|
-
// For snapshots, the value should have the cacheEntryTime.
|
|
96
|
-
// than
|
|
101
|
+
// For snapshots, the value should have the cacheEntryTime.
|
|
102
|
+
// This will be used to expire snapshots older than snapshotCacheExpiryTimeoutMs.
|
|
97
103
|
if (entry.type === odsp_driver_definitions_1.snapshotKey) {
|
|
98
104
|
value.cacheEntryTime = (_a = value.cacheEntryTime) !== null && _a !== void 0 ? _a : Date.now();
|
|
99
105
|
}
|
|
@@ -170,6 +176,19 @@ class EpochTracker {
|
|
|
170
176
|
}
|
|
171
177
|
await this.checkForEpochError(error, epochFromResponse, fetchType);
|
|
172
178
|
throw error;
|
|
179
|
+
}).catch((error) => {
|
|
180
|
+
// If the error is about location redirection, then we need to generate new resolved url with correct
|
|
181
|
+
// location info.
|
|
182
|
+
if ((0, telemetry_utils_1.isFluidError)(error) && error.errorType === driver_definitions_1.DriverErrorType.fileNotFoundOrAccessDeniedError) {
|
|
183
|
+
const redirectLocation = error.redirectLocation;
|
|
184
|
+
if (redirectLocation !== undefined) {
|
|
185
|
+
const redirectUrl = (0, odspLocationRedirection_1.patchOdspResolvedUrl)(this.fileEntry.resolvedUrl, redirectLocation);
|
|
186
|
+
const locationRedirectionError = new driver_utils_1.LocationRedirectionError(error.message, redirectUrl, { driverVersion: packageVersion_1.pkgVersion, redirectLocation });
|
|
187
|
+
locationRedirectionError.addTelemetryProperties(error.getTelemetryProperties());
|
|
188
|
+
throw locationRedirectionError;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
throw error;
|
|
173
192
|
}).catch((error) => {
|
|
174
193
|
const fluidError = (0, telemetry_utils_1.normalizeError)(error, { props: { XRequestStatsHeader: clientCorrelationId } });
|
|
175
194
|
throw fluidError;
|
package/dist/epochTracker.js.map
CHANGED
|
@@ -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,EACxB,kBAA4B;QAH5B,UAAK,GAAL,KAAK,CAAiB;QACtB,cAAS,GAAT,SAAS,CAAY;QACrB,WAAM,GAAN,MAAM,CAAkB;QACxB,uBAAkB,GAAlB,kBAAkB,CAAU;QAPlC,aAAQ,GAAG,IAAA,SAAI,GAAE,CAAC;QACnC,8DAA8D;QACtD,sBAAiB,GAAG,CAAC,CAAC;QAO1B,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,IAAA,qBAAM,EAAC,IAAI,CAAC,WAAW,KAAK,SAAS,EAAE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["/*!\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 protected readonly clientIsSummarizer?: boolean,\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[] = [\n `driverId=${this.driverId}`,\n `RequestNumber=${this.networkCallNumber++}`,\n `driverVersion=${driverVersion}`,\n `isSummarizer=${this.clientIsSummarizer}`,\n ];\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,\n clientIsSummarizer?: boolean): ICacheAndTracker {\n const epochTracker = new EpochTrackerWithRedemption(persistedCacheArg, fileEntry, logger, clientIsSummarizer);\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,+DAKsC;AAEtC,qFASiD;AACjD,2EAAqE;AACrE,qEAKyC;AACzC,2CAAoH;AAMpH,2CAAmF;AACnF,uDAA0D;AAC1D,qDAA+D;AAC/D,uEAAiE;AAOpD,QAAA,YAAY,GAAG,cAAc,CAAC;AAE3C,0GAA0G;AAC7F,QAAA,2BAA2B,GAAW,CAAC,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,kBAA4B;IAC5B,MAAM,YAAY,GAAG,IAAI,0BAA0B,CAAC,iBAAiB,EAAE,SAAS,EAAE,MAAM,EAAE,kBAAkB,CAAC,CAAC;IAC9G,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 {\n ThrottlingError,\n RateLimiter,\n NonRetryableError,\n LocationRedirectionError,\n} from \"@fluidframework/driver-utils\";\nimport { IConnected } from \"@fluidframework/protocol-definitions\";\nimport {\n snapshotKey,\n ICacheEntry,\n IEntry,\n IFileEntry,\n IPersistedCache,\n IOdspError,\n IOdspErrorAugmentations,\n IOdspResolvedUrl,\n} from \"@fluidframework/odsp-driver-definitions\";\nimport { DriverErrorType } from \"@fluidframework/driver-definitions\";\nimport {\n PerformanceEvent,\n isFluidError,\n normalizeError,\n loggerToMonitoringContext,\n} 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\";\nimport { patchOdspResolvedUrl } from \"./odspLocationRedirection\";\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 private readonly snapshotCacheExpiryTimeoutMs: number;\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 protected readonly clientIsSummarizer?: boolean,\n ) {\n // Limits the max number of concurrent requests to 24.\n this.rateLimiter = new RateLimiter(24);\n\n // We need this for GC testing until we properly plumb through the snapshot expiration policy (see PR #11168)\n this.snapshotCacheExpiryTimeoutMs =\n loggerToMonitoringContext(logger).config.getBoolean(\"Fluid.Driver.Odsp.TestOverride.DisableSnapshotCache\")\n ? 0\n : defaultCacheExpiryTimeoutMs;\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 snapshotCacheExpiryTimeoutMs 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 >= this.snapshotCacheExpiryTimeoutMs) {\n this.logger.sendTelemetryEvent(\n {\n eventName: \"odspVersionsCacheExpired\",\n duration: currentTime - cacheTime,\n maxCacheAgeMs: this.snapshotCacheExpiryTimeoutMs,\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.\n // This will be used to expire snapshots older than snapshotCacheExpiryTimeoutMs.\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 // If the error is about location redirection, then we need to generate new resolved url with correct\n // location info.\n if (isFluidError(error) && error.errorType === DriverErrorType.fileNotFoundOrAccessDeniedError) {\n const redirectLocation = (error as IOdspErrorAugmentations).redirectLocation;\n if (redirectLocation !== undefined) {\n const redirectUrl: IOdspResolvedUrl = patchOdspResolvedUrl(\n this.fileEntry.resolvedUrl,\n redirectLocation,\n );\n const locationRedirectionError = new LocationRedirectionError(\n error.message,\n redirectUrl,\n { driverVersion, redirectLocation },\n );\n locationRedirectionError.addTelemetryProperties(error.getTelemetryProperties());\n throw locationRedirectionError;\n }\n }\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[] = [\n `driverId=${this.driverId}`,\n `RequestNumber=${this.networkCallNumber++}`,\n `driverVersion=${driverVersion}`,\n `isSummarizer=${this.clientIsSummarizer}`,\n ];\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,\n clientIsSummarizer?: boolean): ICacheAndTracker {\n const epochTracker = new EpochTrackerWithRedemption(persistedCacheArg, fileEntry, logger, clientIsSummarizer);\n return {\n cache: {\n ...nonpersistentCache,\n persistedCache: epochTracker,\n },\n epochTracker,\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetchSnapshot.d.ts","sourceRoot":"","sources":["../src/fetchSnapshot.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAE9D,OAAO,EAAE,gBAAgB,EAAE,MAAM,oCAAoC,CAAC;AAItE,OAAO,EACH,gBAAgB,EAChB,gBAAgB,EAEhB,+BAA+B,EAClC,MAAM,yCAAyC,CAAC;AAGjD,OAAO,EAAE,aAAa,EAAwB,wBAAwB,EAA8B,MAAM,aAAa,CAAC;AAGxH,OAAO,EAKH,aAAa,EAChB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAItD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAG9C;;GAEG;AACH,oBAAY,yBAAyB;IACjC,IAAI,IAAI;IACR,MAAM,IA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CAAC,IAAI,CAAC,EAClC,oBAAoB,CAAC,EAAE,OAAO,GAC/B,OAAO,CAAC,iBAAiB,CAAC,CAsD5B;AAwRD,MAAM,WAAW,kCAAkC;IAC/C,YAAY,EAAE,aAAa,CAAC,QAAQ,CAAC,CAAC;IACtC,UAAU,EAAE,MAAM,CAAC;IACnB,cAAc,EAAE;QAAE,CAAC,KAAK,EAAE,MAAM,GAAG,GAAG,CAAC;KAAE,CAAC;CAC7C;AAiDD,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,aAAa,QAK5D;AAWD;;;;;;;;;;GAUG;AACH,wBAAsB,gBAAgB,CAClC,eAAe,EAAE,gBAAgB,EACjC,YAAY,EAAE,MAAM,EACpB,MAAM,EAAE,gBAAgB,EACxB,eAAe,EAAE,gBAAgB,GAAG,SAAS,EAC7C,uBAAuB,CAAC,EAAE,yBAAyB,EACnD,UAAU,CAAC,EAAE,eAAe,EAC5B,YAAY,CAAC,EAAE,YAAY,EAC3B,YAAY,CAAC,EAAE,MAAM,GACtB,OAAO,CAAC,kCAAkC,CAAC,CA0C7C"}
|
package/dist/fetchSnapshot.js
CHANGED
|
@@ -138,13 +138,15 @@ async function fetchLatestSnapshotCore(odspResolvedUrl, storageTokenFetcher, sna
|
|
|
138
138
|
const response = await snapshotDownloader(odspResolvedUrl, storageToken, snapshotOptions, controller);
|
|
139
139
|
const odspResponse = response.odspResponse;
|
|
140
140
|
const contentType = odspResponse.headers.get("content-type");
|
|
141
|
-
|
|
141
|
+
const propsToLog = Object.assign(Object.assign({}, odspResponse.propsToLog), { contentType, accept: response.requestHeaders.accept, driverVersion: packageVersion_1.pkgVersion });
|
|
142
|
+
// Measure how much time we spend processing payload
|
|
143
|
+
const snapshotParseEvent = telemetry_utils_1.PerformanceEvent.start(logger, Object.assign({ eventName: "SnapshotParse" }, propsToLog));
|
|
142
144
|
let parsedSnapshotContents;
|
|
143
145
|
try {
|
|
144
146
|
switch (contentType) {
|
|
145
147
|
case "application/json": {
|
|
146
148
|
const text = await odspResponse.content.text();
|
|
147
|
-
|
|
149
|
+
propsToLog.bodySize = text.length;
|
|
148
150
|
const content = JSON.parse(text);
|
|
149
151
|
validateBlobsAndTrees(content);
|
|
150
152
|
const snapshotContents = (0, odspSnapshotParser_1.convertOdspSnapshotToSnapshotTreeAndBlobs)(content);
|
|
@@ -153,29 +155,30 @@ async function fetchLatestSnapshotCore(odspResolvedUrl, storageTokenFetcher, sna
|
|
|
153
155
|
}
|
|
154
156
|
case "application/ms-fluid": {
|
|
155
157
|
const content = await odspResponse.content.arrayBuffer();
|
|
156
|
-
|
|
158
|
+
propsToLog.bodySize = content.byteLength;
|
|
157
159
|
const snapshotContents = (0, compactSnapshotParser_1.parseCompactSnapshotResponse)(new ReadBufferUtils_1.ReadBuffer(new Uint8Array(content)));
|
|
158
160
|
if (snapshotContents.snapshotTree.trees === undefined ||
|
|
159
161
|
snapshotContents.snapshotTree.blobs === undefined) {
|
|
160
|
-
throw new driver_utils_1.NonRetryableError("Returned odsp snapshot is malformed. No trees or blobs!", driver_definitions_1.DriverErrorType.incorrectServerResponse,
|
|
162
|
+
throw new driver_utils_1.NonRetryableError("Returned odsp snapshot is malformed. No trees or blobs!", driver_definitions_1.DriverErrorType.incorrectServerResponse, propsToLog);
|
|
161
163
|
}
|
|
162
164
|
parsedSnapshotContents = Object.assign(Object.assign({}, odspResponse), { content: snapshotContents });
|
|
163
165
|
break;
|
|
164
166
|
}
|
|
165
167
|
default:
|
|
166
|
-
throw new driver_utils_1.NonRetryableError("Unknown snapshot content type", driver_definitions_1.DriverErrorType.incorrectServerResponse,
|
|
168
|
+
throw new driver_utils_1.NonRetryableError("Unknown snapshot content type", driver_definitions_1.DriverErrorType.incorrectServerResponse, propsToLog);
|
|
167
169
|
}
|
|
168
170
|
}
|
|
169
171
|
catch (error) {
|
|
170
172
|
if ((0, telemetry_utils_1.isFluidError)(error)) {
|
|
171
|
-
error.addTelemetryProperties(
|
|
173
|
+
error.addTelemetryProperties(propsToLog);
|
|
172
174
|
throw error;
|
|
173
175
|
}
|
|
174
|
-
const enhancedError = (0, telemetry_utils_1.wrapError)(error, (errorMessage) => new driver_utils_1.NonRetryableError(`Error parsing snapshot response: ${errorMessage}`, driver_definitions_1.DriverErrorType.genericError,
|
|
176
|
+
const enhancedError = (0, telemetry_utils_1.wrapError)(error, (errorMessage) => new driver_utils_1.NonRetryableError(`Error parsing snapshot response: ${errorMessage}`, driver_definitions_1.DriverErrorType.genericError, propsToLog));
|
|
175
177
|
throw enhancedError;
|
|
176
178
|
}
|
|
177
179
|
(0, common_utils_1.assert)(parsedSnapshotContents !== undefined, 0x312 /* snapshot should be parsed */);
|
|
178
180
|
const snapshot = parsedSnapshotContents.content;
|
|
181
|
+
const { trees, numBlobs, encodedBlobsSize } = evalBlobsAndTrees(snapshot);
|
|
179
182
|
// From: https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming
|
|
180
183
|
// fetchStart: immediately before the browser starts to fetch the resource.
|
|
181
184
|
// requestStart: immediately before the browser starts requesting the resource from the server
|
|
@@ -226,7 +229,6 @@ async function fetchLatestSnapshotCore(odspResolvedUrl, storageTokenFetcher, sna
|
|
|
226
229
|
break;
|
|
227
230
|
}
|
|
228
231
|
}
|
|
229
|
-
const { numTrees, numBlobs, encodedBlobsSize } = evalBlobsAndTrees(parsedSnapshotContents.content);
|
|
230
232
|
// There are some scenarios in ODSP where we cannot cache, trees/latest will explicitly tell us when we
|
|
231
233
|
// cannot cache using an HTTP response header.
|
|
232
234
|
const canCache = odspResponse.headers.get("disablebrowsercachingofusercontent") !== "true";
|
|
@@ -251,7 +253,8 @@ async function fetchLatestSnapshotCore(odspResolvedUrl, storageTokenFetcher, sna
|
|
|
251
253
|
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
|
252
254
|
putInCache(valueWithEpoch);
|
|
253
255
|
}
|
|
254
|
-
|
|
256
|
+
snapshotParseEvent.end();
|
|
257
|
+
event.end(Object.assign({ trees, blobs: (_e = (_d = snapshot.blobs) === null || _d === void 0 ? void 0 : _d.size) !== null && _e !== void 0 ? _e : 0, leafNodes: numBlobs, encodedBlobsSize,
|
|
255
258
|
sequenceNumber, ops: (_g = (_f = snapshot.ops) === null || _f === void 0 ? void 0 : _f.length) !== null && _g !== void 0 ? _g : 0, userOps: (_j = (_h = snapshot.ops) === null || _h === void 0 ? void 0 : _h.filter((op) => (0, driver_utils_1.isRuntimeMessage)(op)).length) !== null && _j !== void 0 ? _j : 0, headers: Object.keys(response.requestHeaders).length !== 0 ? true : undefined,
|
|
256
259
|
// Interval between the first fetch until the last byte of the last redirect.
|
|
257
260
|
redirectTime,
|
|
@@ -274,7 +277,7 @@ async function fetchLatestSnapshotCore(odspResolvedUrl, storageTokenFetcher, sna
|
|
|
274
277
|
// Azure Fluid Relay service; desc=S, FRP; desc=False. Here, FRL is the duration taken for redeem,
|
|
275
278
|
// Azure Fluid Relay service is the redeem status (S means success), and FRP is a flag to indicate
|
|
276
279
|
// if the permission has changed.
|
|
277
|
-
sltelemetry: odspResponse.headers.get("x-fluid-sltelemetry") },
|
|
280
|
+
sltelemetry: odspResponse.headers.get("x-fluid-sltelemetry") }, propsToLog));
|
|
278
281
|
return snapshot;
|
|
279
282
|
}).catch((error) => {
|
|
280
283
|
// We hit these errors in stress tests, under load
|
|
@@ -320,13 +323,13 @@ function getFormBodyAndHeaders(odspResolvedUrl, storageToken, snapshotOptions, h
|
|
|
320
323
|
return { body: postBody, headers: header };
|
|
321
324
|
}
|
|
322
325
|
function evalBlobsAndTrees(snapshot) {
|
|
323
|
-
const
|
|
326
|
+
const trees = countTreesInSnapshotTree(snapshot.snapshotTree);
|
|
324
327
|
const numBlobs = snapshot.blobs.size;
|
|
325
328
|
let encodedBlobsSize = 0;
|
|
326
329
|
for (const [_, blobContent] of snapshot.blobs) {
|
|
327
330
|
encodedBlobsSize += blobContent.byteLength;
|
|
328
331
|
}
|
|
329
|
-
return {
|
|
332
|
+
return { trees, numBlobs, encodedBlobsSize };
|
|
330
333
|
}
|
|
331
334
|
function validateBlobsAndTrees(snapshot) {
|
|
332
335
|
(0, common_utils_1.assert)(snapshot.trees !== undefined, 0x200 /* "Returned odsp snapshot is malformed. No trees!" */);
|