@fluidframework/driver-web-cache 0.58.2000-58133

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 (62) hide show
  1. package/.eslintrc.js +19 -0
  2. package/LICENSE +21 -0
  3. package/README.md +56 -0
  4. package/api-extractor.json +4 -0
  5. package/dist/FluidCache.d.ts +39 -0
  6. package/dist/FluidCache.d.ts.map +1 -0
  7. package/dist/FluidCache.js +159 -0
  8. package/dist/FluidCache.js.map +1 -0
  9. package/dist/FluidCacheIndexedDb.d.ts +65 -0
  10. package/dist/FluidCacheIndexedDb.d.ts.map +1 -0
  11. package/dist/FluidCacheIndexedDb.js +65 -0
  12. package/dist/FluidCacheIndexedDb.js.map +1 -0
  13. package/dist/fluidCacheTelemetry.d.ts +19 -0
  14. package/dist/fluidCacheTelemetry.d.ts.map +1 -0
  15. package/dist/fluidCacheTelemetry.js +7 -0
  16. package/dist/fluidCacheTelemetry.js.map +1 -0
  17. package/dist/index.d.ts +7 -0
  18. package/dist/index.d.ts.map +1 -0
  19. package/dist/index.js +21 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/packageVersion.d.ts +9 -0
  22. package/dist/packageVersion.d.ts.map +1 -0
  23. package/dist/packageVersion.js +12 -0
  24. package/dist/packageVersion.js.map +1 -0
  25. package/dist/scheduleIdleTask.d.ts +22 -0
  26. package/dist/scheduleIdleTask.d.ts.map +1 -0
  27. package/dist/scheduleIdleTask.js +80 -0
  28. package/dist/scheduleIdleTask.js.map +1 -0
  29. package/jest.config.js +12 -0
  30. package/lib/FluidCache.d.ts +39 -0
  31. package/lib/FluidCache.d.ts.map +1 -0
  32. package/lib/FluidCache.js +155 -0
  33. package/lib/FluidCache.js.map +1 -0
  34. package/lib/FluidCacheIndexedDb.d.ts +65 -0
  35. package/lib/FluidCacheIndexedDb.d.ts.map +1 -0
  36. package/lib/FluidCacheIndexedDb.js +59 -0
  37. package/lib/FluidCacheIndexedDb.js.map +1 -0
  38. package/lib/fluidCacheTelemetry.d.ts +19 -0
  39. package/lib/fluidCacheTelemetry.d.ts.map +1 -0
  40. package/lib/fluidCacheTelemetry.js +6 -0
  41. package/lib/fluidCacheTelemetry.js.map +1 -0
  42. package/lib/index.d.ts +7 -0
  43. package/lib/index.d.ts.map +1 -0
  44. package/lib/index.js +7 -0
  45. package/lib/index.js.map +1 -0
  46. package/lib/packageVersion.d.ts +9 -0
  47. package/lib/packageVersion.d.ts.map +1 -0
  48. package/lib/packageVersion.js +9 -0
  49. package/lib/packageVersion.js.map +1 -0
  50. package/lib/scheduleIdleTask.d.ts +22 -0
  51. package/lib/scheduleIdleTask.d.ts.map +1 -0
  52. package/lib/scheduleIdleTask.js +76 -0
  53. package/lib/scheduleIdleTask.js.map +1 -0
  54. package/package.json +67 -0
  55. package/src/FluidCache.ts +276 -0
  56. package/src/FluidCacheIndexedDb.ts +155 -0
  57. package/src/fluidCacheTelemetry.ts +21 -0
  58. package/src/index.ts +7 -0
  59. package/src/packageVersion.ts +9 -0
  60. package/src/scheduleIdleTask.ts +119 -0
  61. package/tsconfig.esnext.json +7 -0
  62. package/tsconfig.json +15 -0
package/.eslintrc.js ADDED
@@ -0,0 +1,19 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ module.exports = {
7
+ extends: ["@fluidframework/eslint-config-fluid"],
8
+ parserOptions: {
9
+ project: ["./tsconfig.json", "./src/test/tsconfig.json"],
10
+ },
11
+ rules: {
12
+ "@typescript-eslint/no-non-null-assertion": "off",
13
+ "@typescript-eslint/no-use-before-define": "off",
14
+ "@typescript-eslint/strict-boolean-expressions": "off",
15
+ "no-null/no-null": "off",
16
+ "@typescript-eslint/promise-function-async": "off",
17
+ "@typescript-eslint/no-misused-promises": "off",
18
+ },
19
+ };
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ Copyright (c) Microsoft Corporation and contributors. All rights reserved.
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,56 @@
1
+ # @fluidframework/driver-web-cache
2
+
3
+ This package provides an implementation of the `IPersistedCache` interface in the odsp-driver package. This cache enables
4
+ storing of user content on the user's machine in order to provide faster boot experiences when opening the same Fluid
5
+ containers more than once. This implementation has a dependency on indexeddb, so it is intended to only be used in a browser
6
+ context.
7
+
8
+ ## Usage
9
+
10
+ ```typescript
11
+ import { FluidCache } from '@fluidframework/driver-web-cache';
12
+
13
+ new FluidCache({
14
+ partitionKey: userId,
15
+ logger,
16
+ maxCacheItemAge
17
+ })
18
+ ```
19
+
20
+ ### Parameters
21
+
22
+ - `partitionKey` - Used to determine what partition of the cache is being used, and can prevent multiple users on the
23
+ same machine from sharing a snapshot cache. If you absolutely know that users will not share the cache,
24
+ can also be set to `null`. Currently optional, but is proposed to be required in the next major bump.
25
+ The recommendation is to use this key to differentiate users for the cache data.
26
+ - `logger` - An optional implementation of the logger contract where diagnostic data can be logged.
27
+ - `maxCacheItemAge` - The cache tracks a timestamp with each entry. This flag specifies the maximum age (in milliseconds)
28
+ for a cache entry to be used. This flag does not control when cached content is deleted since different scenarios and
29
+ applications may have different staleness thresholds for the same data.
30
+
31
+ ## Clearing cache entries
32
+
33
+ Whenever any Fluid content is loaded with the web cache enabled, a task is scheduled to clear out all "stale" cache
34
+ entries. This task is scheduled with the `setIdleCallback` browser API. We define stale cache entries as any cache
35
+ entries that have not been used (read or written to) within the last 4 weeks. The cache is cleared of all stale cache
36
+ entries corresponding to all documents, not just the ones corresponding to the Fluid document being loaded.
37
+
38
+ The `deleteFluidCacheIndexDbInstance` API that an application can use to clear out the entire contents of the snapshot
39
+ cache at any time. We recommend calling this API when the user explicitly signs out. Hosting applications
40
+ are on point for ensuring responsible usage of the snapshot caching capability to still meet any relevant
41
+ customer promises, such as clearing out storage when appropriate or disabling snapshot caching under certain circumstances,
42
+ such as when it is known the user is logged in to a public computer.
43
+
44
+
45
+ ```typescript
46
+ import { deleteFluidCacheIndexDbInstance } from '@fluidframework/driver-web-cache';
47
+
48
+ // We put a catch here because Firefox Incognito will throw an error here. This is why we claim this method is a "best effort", since sometimes the browser won't let us access storage
49
+ deleteFluidCacheIndexDbInstance().catch(() => {});
50
+ ```
51
+
52
+ ## Trademark
53
+
54
+ This project may contain Microsoft trademarks or logos for Microsoft projects, products, or services. Use of these trademarks
55
+ or logos must follow Microsoft's [Trademark & Brand Guidelines](https://www.microsoft.com/en-us/legal/intellectualproperty/trademarks/usage/general).
56
+ Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship.
@@ -0,0 +1,4 @@
1
+ {
2
+ "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",
3
+ "extends": "@fluidframework/build-common/api-extractor-common-report.json"
4
+ }
@@ -0,0 +1,39 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+ import { IPersistedCache, ICacheEntry, IFileEntry } from "@fluidframework/odsp-driver-definitions";
6
+ import { ITelemetryBaseLogger } from "@fluidframework/common-definitions";
7
+ export interface FluidCacheConfig {
8
+ /**
9
+ * A string to specify what partition of the cache you wish to use (e.g. a user id).
10
+ * Null can be used to explicity indicate no partitioning, and has been chosen
11
+ * vs undefined so that it is clear this is an intentional choice by the caller.
12
+ * A null value should only be used when the host can ensure that the cache is not able
13
+ * to be shared with multiple users.
14
+ */
15
+ partitionKey: string | null;
16
+ /**
17
+ * A logger that can be used to get insight into cache performance and errors
18
+ */
19
+ logger?: ITelemetryBaseLogger;
20
+ /**
21
+ * A value in milliseconds that determines the maximum age of a cache entry to return.
22
+ * If an entry exists in the cache, but is older than this value, the cached value will not be returned.
23
+ */
24
+ maxCacheItemAge: number;
25
+ }
26
+ /**
27
+ * A cache that can be used by the Fluid ODSP driver to cache data for faster performance
28
+ */
29
+ export declare class FluidCache implements IPersistedCache {
30
+ private readonly logger;
31
+ private readonly partitionKey;
32
+ private readonly maxCacheItemAge;
33
+ constructor(config: FluidCacheConfig);
34
+ removeEntries(file: IFileEntry): Promise<void>;
35
+ get(cacheEntry: ICacheEntry): Promise<any>;
36
+ private getItemFromCache;
37
+ put(entry: ICacheEntry, value: any): Promise<void>;
38
+ }
39
+ //# sourceMappingURL=FluidCache.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"FluidCache.d.ts","sourceRoot":"","sources":["../src/FluidCache.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EACH,eAAe,EACf,WAAW,EACX,UAAU,EACb,MAAM,yCAAyC,CAAC;AACjD,OAAO,EACH,oBAAoB,EAEvB,MAAM,oCAAoC,CAAC;AAoB5C,MAAM,WAAW,gBAAgB;IAC7B;;;;;;OAMG;IAEH,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAE5B;;OAEG;IACH,MAAM,CAAC,EAAE,oBAAoB,CAAC;IAE9B;;;OAGG;IACH,eAAe,EAAE,MAAM,CAAC;CAC3B;AAED;;GAEG;AACH,qBAAa,UAAW,YAAW,eAAe;IAC9C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAmB;IAE1C,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAgB;IAE7C,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAS;gBAE7B,MAAM,EAAE,gBAAgB;IAiEvB,aAAa,CAAC,IAAI,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC;IA2B9C,GAAG,CAAC,UAAU,EAAE,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC;YAiBzC,gBAAgB;IAsEjB,GAAG,CAAC,KAAK,EAAE,WAAW,EAAE,KAAK,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC;CA8BlE"}
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+ /*!
3
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
4
+ * Licensed under the MIT License.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.FluidCache = void 0;
8
+ const telemetry_utils_1 = require("@fluidframework/telemetry-utils");
9
+ const scheduleIdleTask_1 = require("./scheduleIdleTask");
10
+ const FluidCacheIndexedDb_1 = require("./FluidCacheIndexedDb");
11
+ /**
12
+ * A cache that can be used by the Fluid ODSP driver to cache data for faster performance
13
+ */
14
+ class FluidCache {
15
+ constructor(config) {
16
+ this.logger = telemetry_utils_1.ChildLogger.create(config.logger);
17
+ this.partitionKey = config.partitionKey;
18
+ this.maxCacheItemAge = config.maxCacheItemAge;
19
+ scheduleIdleTask_1.scheduleIdleTask(async () => {
20
+ // Log how much storage space is currently being used by indexed db.
21
+ // NOTE: This API is not supported in all browsers and it doesn't let you see the size of a specific DB.
22
+ // Exception added when eslint rule was added, this should be revisited when modifying this code
23
+ if (navigator.storage && navigator.storage.estimate) {
24
+ const estimate = await navigator.storage.estimate();
25
+ // Some browsers have a usageDetails property that will tell you
26
+ // more detailed information on how the storage is being used
27
+ let indexedDBSize;
28
+ if ("usageDetails" in estimate) {
29
+ indexedDBSize = estimate
30
+ .usageDetails.indexedDB;
31
+ }
32
+ this.logger.sendTelemetryEvent({
33
+ eventName: "FluidCacheStorageInfo" /* FluidCacheStorageInfo */,
34
+ subCategory: "FluidCache" /* FluidCache */,
35
+ quota: estimate.quota,
36
+ usage: estimate.usage,
37
+ indexedDBSize,
38
+ });
39
+ }
40
+ });
41
+ scheduleIdleTask_1.scheduleIdleTask(async () => {
42
+ // Delete entries that have not been accessed recently to clean up space
43
+ try {
44
+ const db = await FluidCacheIndexedDb_1.getFluidCacheIndexedDbInstance(this.logger);
45
+ const transaction = db.transaction(FluidCacheIndexedDb_1.FluidDriverObjectStoreName, "readwrite");
46
+ const index = transaction.store.index("lastAccessTimeMs");
47
+ // Get items that have not been accessed in 4 weeks
48
+ const keysToDelete = await index.getAllKeys(IDBKeyRange.upperBound(new Date().getTime() - 4 * 7 * 24 * 60 * 60 * 1000));
49
+ await Promise.all(keysToDelete.map((key) => transaction.store.delete(key)));
50
+ await transaction.done;
51
+ }
52
+ catch (error) {
53
+ this.logger.sendErrorEvent({
54
+ eventName: "FluidCacheDeleteOldEntriesError" /* FluidCacheDeleteOldEntriesError */,
55
+ }, error);
56
+ }
57
+ });
58
+ }
59
+ async removeEntries(file) {
60
+ try {
61
+ const db = await FluidCacheIndexedDb_1.getFluidCacheIndexedDbInstance(this.logger);
62
+ const transaction = db.transaction(FluidCacheIndexedDb_1.FluidDriverObjectStoreName, "readwrite");
63
+ const index = transaction.store.index("fileId");
64
+ const keysToDelete = await index.getAllKeys(file.docId);
65
+ await Promise.all(keysToDelete.map((key) => transaction.store.delete(key)));
66
+ await transaction.done;
67
+ }
68
+ catch (error) {
69
+ this.logger.sendErrorEvent({
70
+ eventName: "FluidCacheDeleteOldEntriesError" /* FluidCacheDeleteOldEntriesError */,
71
+ }, error);
72
+ }
73
+ }
74
+ async get(cacheEntry) {
75
+ const startTime = performance.now();
76
+ const cachedItem = await this.getItemFromCache(cacheEntry);
77
+ this.logger.sendPerformanceEvent({
78
+ eventName: "FluidCacheAccess",
79
+ cacheHit: cachedItem !== undefined,
80
+ type: cacheEntry.type,
81
+ duration: performance.now() - startTime,
82
+ });
83
+ // Value will contain metadata like the expiry time, we just want to return the object we were asked to cache
84
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
85
+ return cachedItem === null || cachedItem === void 0 ? void 0 : cachedItem.cachedObject;
86
+ }
87
+ async getItemFromCache(cacheEntry) {
88
+ try {
89
+ const key = FluidCacheIndexedDb_1.getKeyForCacheEntry(cacheEntry);
90
+ const db = await FluidCacheIndexedDb_1.getFluidCacheIndexedDbInstance(this.logger);
91
+ const value = await db.get(FluidCacheIndexedDb_1.FluidDriverObjectStoreName, key);
92
+ if (!value) {
93
+ return undefined;
94
+ }
95
+ // If the data does not come from the same partition, don't return it
96
+ if (value.partitionKey !== this.partitionKey) {
97
+ this.logger.sendTelemetryEvent({
98
+ eventName: "FluidCachePartitionKeyMismatch" /* FluidCachePartitionKeyMismatch */,
99
+ subCategory: "FluidCache" /* FluidCache */,
100
+ });
101
+ return undefined;
102
+ }
103
+ const currentTime = new Date().getTime();
104
+ // If too much time has passed since this cache entry was used, we will also return undefined
105
+ if (currentTime - value.createdTimeMs > this.maxCacheItemAge) {
106
+ return undefined;
107
+ }
108
+ const transaction = db.transaction(FluidCacheIndexedDb_1.FluidDriverObjectStoreName, "readwrite");
109
+ // We don't want to block the get return of this function on updating the last accessed time
110
+ // We catch this promise because there is no user bad if this is rejected.
111
+ transaction.store
112
+ .get(key)
113
+ .then(async (valueToUpdate) => {
114
+ // This value in the database could have been updated concurrently by other tabs/iframes
115
+ // since we first read it. Only update the last accessed time if the current value in the
116
+ // DB was the same one we returned.
117
+ if (valueToUpdate !== undefined &&
118
+ valueToUpdate.createdTimeMs === value.createdTimeMs &&
119
+ (valueToUpdate.lastAccessTimeMs === undefined ||
120
+ valueToUpdate.lastAccessTimeMs < currentTime)) {
121
+ await transaction.store.put(Object.assign(Object.assign({}, valueToUpdate), { lastAccessTimeMs: currentTime }), key);
122
+ }
123
+ await transaction.done;
124
+ db.close();
125
+ })
126
+ .catch(() => { });
127
+ return value;
128
+ }
129
+ catch (error) {
130
+ // We can fail to open the db for a variety of reasons,
131
+ // such as the database version having upgraded underneath us. Return undefined in this case
132
+ this.logger.sendErrorEvent({ eventName: "FluidCacheGetError" /* FluidCacheGetError */ }, error);
133
+ return undefined;
134
+ }
135
+ }
136
+ async put(entry, value) {
137
+ try {
138
+ const db = await FluidCacheIndexedDb_1.getFluidCacheIndexedDbInstance(this.logger);
139
+ const currentTime = new Date().getTime();
140
+ await db.put(FluidCacheIndexedDb_1.FluidDriverObjectStoreName, {
141
+ cachedObject: value,
142
+ fileId: entry.file.docId,
143
+ type: entry.type,
144
+ cacheItemId: entry.key,
145
+ partitionKey: this.partitionKey,
146
+ createdTimeMs: currentTime,
147
+ lastAccessTimeMs: currentTime,
148
+ }, FluidCacheIndexedDb_1.getKeyForCacheEntry(entry));
149
+ db.close();
150
+ }
151
+ catch (error) {
152
+ // We can fail to open the db for a variety of reasons,
153
+ // such as the database version having upgraded underneath us
154
+ this.logger.sendErrorEvent({ eventName: "FluidCachePutError" /* FluidCachePutError */ }, error);
155
+ }
156
+ }
157
+ }
158
+ exports.FluidCache = FluidCache;
159
+ //# sourceMappingURL=FluidCache.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"FluidCache.js","sourceRoot":"","sources":["../src/FluidCache.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAWH,qEAA8D;AAC9D,yDAAsD;AACtD,+DAI+B;AAoC/B;;GAEG;AACH,MAAa,UAAU;IAOnB,YAAY,MAAwB;QAChC,IAAI,CAAC,MAAM,GAAG,6BAAW,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAChD,IAAI,CAAC,YAAY,GAAG,MAAM,CAAC,YAAY,CAAC;QACxC,IAAI,CA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YAEF,EAAE,CAAC,KAAK,EAAE,CAAC;SACd;QAAC,OAAO,KAAU,EAAE;YACjB,uDAAuD;YACvD,6DAA6D;YAC7D,IAAI,CAAC,MAAM,CAAC,cAAc,CACtB,EAAE,SAAS,+CAAyC,EAAE,EACtD,KAAK,CACR,CAAC;SACL;IACL,CAAC;CACJ;AAxND,gCAwNC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n IPersistedCache,\n ICacheEntry,\n IFileEntry,\n} from \"@fluidframework/odsp-driver-definitions\";\nimport {\n ITelemetryBaseLogger,\n ITelemetryLogger,\n} from \"@fluidframework/common-definitions\";\nimport { ChildLogger } from \"@fluidframework/telemetry-utils\";\nimport { scheduleIdleTask } from \"./scheduleIdleTask\";\nimport {\n getFluidCacheIndexedDbInstance,\n FluidDriverObjectStoreName,\n getKeyForCacheEntry,\n} from \"./FluidCacheIndexedDb\";\nimport {\n FluidCacheErrorEvent,\n FluidCacheEventSubCategories,\n FluidCacheGenericEvent,\n} from \"./fluidCacheTelemetry\";\n\n// Some browsers have a usageDetails property that will tell you more detailed information\n// on how the storage is being used\ninterface StorageQuotaUsageDetails {\n indexedDB: number | undefined;\n}\n\nexport interface FluidCacheConfig {\n /**\n * A string to specify what partition of the cache you wish to use (e.g. a user id).\n * Null can be used to explicity indicate no partitioning, and has been chosen\n * vs undefined so that it is clear this is an intentional choice by the caller.\n * A null value should only be used when the host can ensure that the cache is not able\n * to be shared with multiple users.\n */\n // eslint-disable-next-line @rushstack/no-new-null\n partitionKey: string | null;\n\n /**\n * A logger that can be used to get insight into cache performance and errors\n */\n logger?: ITelemetryBaseLogger;\n\n /**\n * A value in milliseconds that determines the maximum age of a cache entry to return.\n * If an entry exists in the cache, but is older than this value, the cached value will not be returned.\n */\n maxCacheItemAge: number;\n}\n\n/**\n * A cache that can be used by the Fluid ODSP driver to cache data for faster performance\n */\nexport class FluidCache implements IPersistedCache {\n private readonly logger: ITelemetryLogger;\n\n private readonly partitionKey: string | null;\n\n private readonly maxCacheItemAge: number;\n\n constructor(config: FluidCacheConfig) {\n this.logger = ChildLogger.create(config.logger);\n this.partitionKey = config.partitionKey;\n this.maxCacheItemAge = config.maxCacheItemAge;\n\n scheduleIdleTask(async () => {\n // Log how much storage space is currently being used by indexed db.\n // NOTE: This API is not supported in all browsers and it doesn't let you see the size of a specific DB.\n // Exception added when eslint rule was added, this should be revisited when modifying this code\n if (navigator.storage && navigator.storage.estimate) {\n const estimate = await navigator.storage.estimate();\n\n // Some browsers have a usageDetails property that will tell you\n // more detailed information on how the storage is being used\n let indexedDBSize: number | undefined;\n if (\"usageDetails\" in estimate) {\n indexedDBSize = (\n (estimate as any)\n .usageDetails as StorageQuotaUsageDetails\n ).indexedDB;\n }\n\n this.logger.sendTelemetryEvent({\n eventName: FluidCacheGenericEvent.FluidCacheStorageInfo,\n subCategory: FluidCacheEventSubCategories.FluidCache,\n quota: estimate.quota,\n usage: estimate.usage,\n indexedDBSize,\n });\n }\n });\n\n scheduleIdleTask(async () => {\n // Delete entries that have not been accessed recently to clean up space\n try {\n const db = await getFluidCacheIndexedDbInstance(this.logger);\n\n const transaction = db.transaction(\n FluidDriverObjectStoreName,\n \"readwrite\",\n );\n const index = transaction.store.index(\"lastAccessTimeMs\");\n // Get items that have not been accessed in 4 weeks\n const keysToDelete = await index.getAllKeys(\n IDBKeyRange.upperBound(\n new Date().getTime() - 4 * 7 * 24 * 60 * 60 * 1000,\n ),\n );\n\n await Promise.all(\n keysToDelete.map((key) => transaction.store.delete(key)),\n );\n await transaction.done;\n } catch (error: any) {\n this.logger.sendErrorEvent(\n {\n eventName:\n FluidCacheErrorEvent.FluidCacheDeleteOldEntriesError,\n },\n error,\n );\n }\n });\n }\n\n public async removeEntries(file: IFileEntry): Promise<void> {\n try {\n const db = await getFluidCacheIndexedDbInstance(this.logger);\n\n const transaction = db.transaction(\n FluidDriverObjectStoreName,\n \"readwrite\",\n );\n const index = transaction.store.index(\"fileId\");\n\n const keysToDelete = await index.getAllKeys(file.docId);\n\n await Promise.all(\n keysToDelete.map((key) => transaction.store.delete(key)),\n );\n await transaction.done;\n } catch (error: any) {\n this.logger.sendErrorEvent(\n {\n eventName:\n FluidCacheErrorEvent.FluidCacheDeleteOldEntriesError,\n },\n error,\n );\n }\n }\n\n public async get(cacheEntry: ICacheEntry): Promise<any> {\n const startTime = performance.now();\n\n const cachedItem = await this.getItemFromCache(cacheEntry);\n\n this.logger.sendPerformanceEvent({\n eventName: \"FluidCacheAccess\",\n cacheHit: cachedItem !== undefined,\n type: cacheEntry.type,\n duration: performance.now() - startTime,\n });\n\n // Value will contain metadata like the expiry time, we just want to return the object we were asked to cache\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return cachedItem?.cachedObject;\n }\n\n private async getItemFromCache(cacheEntry: ICacheEntry) {\n try {\n const key = getKeyForCacheEntry(cacheEntry);\n\n const db = await getFluidCacheIndexedDbInstance(this.logger);\n\n const value = await db.get(FluidDriverObjectStoreName, key);\n\n if (!value) {\n return undefined;\n }\n\n // If the data does not come from the same partition, don't return it\n if (value.partitionKey !== this.partitionKey) {\n this.logger.sendTelemetryEvent({\n eventName:\n FluidCacheGenericEvent.FluidCachePartitionKeyMismatch,\n subCategory: FluidCacheEventSubCategories.FluidCache,\n });\n\n return undefined;\n }\n\n const currentTime = new Date().getTime();\n\n // If too much time has passed since this cache entry was used, we will also return undefined\n if (currentTime - value.createdTimeMs > this.maxCacheItemAge) {\n return undefined;\n }\n\n const transaction = db.transaction(\n FluidDriverObjectStoreName,\n \"readwrite\",\n );\n // We don't want to block the get return of this function on updating the last accessed time\n // We catch this promise because there is no user bad if this is rejected.\n transaction.store\n .get(key)\n .then(async (valueToUpdate) => {\n // This value in the database could have been updated concurrently by other tabs/iframes\n // since we first read it. Only update the last accessed time if the current value in the\n // DB was the same one we returned.\n if (\n valueToUpdate !== undefined &&\n valueToUpdate.createdTimeMs === value.createdTimeMs &&\n (valueToUpdate.lastAccessTimeMs === undefined ||\n valueToUpdate.lastAccessTimeMs < currentTime)\n ) {\n await transaction.store.put(\n { ...valueToUpdate, lastAccessTimeMs: currentTime },\n key,\n );\n }\n await transaction.done;\n\n db.close();\n })\n .catch(() => { });\n return value;\n } catch (error: any) {\n // We can fail to open the db for a variety of reasons,\n // such as the database version having upgraded underneath us. Return undefined in this case\n this.logger.sendErrorEvent(\n { eventName: FluidCacheErrorEvent.FluidCacheGetError },\n error,\n );\n return undefined;\n }\n }\n\n public async put(entry: ICacheEntry, value: any): Promise<void> {\n try {\n const db = await getFluidCacheIndexedDbInstance(this.logger);\n\n const currentTime = new Date().getTime();\n\n await db.put(\n FluidDriverObjectStoreName,\n {\n cachedObject: value,\n fileId: entry.file.docId,\n type: entry.type,\n cacheItemId: entry.key,\n partitionKey: this.partitionKey,\n createdTimeMs: currentTime,\n lastAccessTimeMs: currentTime,\n },\n getKeyForCacheEntry(entry),\n );\n\n db.close();\n } catch (error: any) {\n // We can fail to open the db for a variety of reasons,\n // such as the database version having upgraded underneath us\n this.logger.sendErrorEvent(\n { eventName: FluidCacheErrorEvent.FluidCachePutError },\n error,\n );\n }\n }\n}\n"]}
@@ -0,0 +1,65 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+ import { DBSchema, IDBPDatabase } from "idb";
6
+ import { ICacheEntry } from "@fluidframework/odsp-driver-definitions";
7
+ import { ITelemetryBaseLogger } from "@fluidframework/common-definitions";
8
+ export declare const FluidDriverCacheDBName = "fluidDriverCache";
9
+ export declare const FluidDriverObjectStoreName = "driverStorage.V3";
10
+ export declare const CurrentCacheVersion = 3;
11
+ export declare const oldVersionNameMapping: Partial<{
12
+ [key: number]: string;
13
+ }>;
14
+ export declare function getKeyForCacheEntry(entry: ICacheEntry): string;
15
+ export declare function getFluidCacheIndexedDbInstance(logger?: ITelemetryBaseLogger): Promise<IDBPDatabase<FluidCacheDBSchema>>;
16
+ export declare function deleteFluidCacheIndexDbInstance(): Promise<void>;
17
+ /**
18
+ * Schema for the object store used to cache driver information
19
+ */
20
+ export interface FluidCacheDBSchema extends DBSchema {
21
+ [FluidDriverObjectStoreName]: {
22
+ /**
23
+ * A unique identifier for an item in the cache. It is a combination of file, type, and cacheItemId
24
+ */
25
+ key: string;
26
+ value: {
27
+ /**
28
+ * The identifier of the file associated with the cache entry
29
+ */
30
+ fileId: string;
31
+ /**
32
+ * Describes the type of content being cached, such as snapshot
33
+ */
34
+ type: string;
35
+ /**
36
+ * Files may have multiple cached items associated with them,
37
+ * this property uniquely identifies a specific cache entry for a file.
38
+ * This is not globally unique, but rather a unique id for this file
39
+ */
40
+ cacheItemId: string;
41
+ cachedObject: any;
42
+ /**
43
+ * A string to specify what partition of the cache you wish to use (e.g. a user id).
44
+ * Null can be used to explicity indicate no partitioning.
45
+ */
46
+ partitionKey: string | null;
47
+ /**
48
+ * The time when the cache entry was put into the cache
49
+ */
50
+ createdTimeMs: number;
51
+ /**
52
+ * The last time the cache entry was used.
53
+ * This is initially set to the time the cache entry was created Measured as ms since unix epoch.
54
+ */
55
+ lastAccessTimeMs: number;
56
+ };
57
+ indexes: {
58
+ createdTimeMs: number;
59
+ partitionKey: string;
60
+ lastAccessTimeMs: number;
61
+ fileId: string;
62
+ };
63
+ };
64
+ }
65
+ //# sourceMappingURL=FluidCacheIndexedDb.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"FluidCacheIndexedDb.d.ts","sourceRoot":"","sources":["../src/FluidCacheIndexedDb.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAU,QAAQ,EAAE,YAAY,EAAY,MAAM,KAAK,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,MAAM,yCAAyC,CAAC;AACtE,OAAO,EAAE,oBAAoB,EAAE,MAAM,oCAAoC,CAAC;AAK1E,eAAO,MAAM,sBAAsB,qBAAqB,CAAC;AAGzD,eAAO,MAAM,0BAA0B,qBAAqB,CAAC;AAE7D,eAAO,MAAM,mBAAmB,IAAI,CAAC;AAGrC,eAAO,MAAM,qBAAqB,EAAE,OAAO,CAAC;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;CAAE,CAGpE,CAAC;AAEF,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,WAAW,UAErD;AAED,wBAAgB,8BAA8B,CAC1C,MAAM,CAAC,EAAE,oBAAoB,GAC9B,OAAO,CAAC,YAAY,CAAC,kBAAkB,CAAC,CAAC,CAwD3C;AAID,wBAAgB,+BAA+B,IAAI,OAAO,CAAC,IAAI,CAAC,CAE/D;AAED;;GAEG;AACH,MAAM,WAAW,kBAAmB,SAAQ,QAAQ;IAChD,CAAC,0BAA0B,CAAC,EAAE;QAC1B;;WAEG;QACH,GAAG,EAAE,MAAM,CAAC;QAEZ,KAAK,EAAE;YACH;;eAEG;YACH,MAAM,EAAE,MAAM,CAAC;YAEf;;eAEG;YACH,IAAI,EAAE,MAAM,CAAC;YAEb;;;;eAIG;YACH,WAAW,EAAE,MAAM,CAAC;YAKpB,YAAY,EAAE,GAAG,CAAC;YAElB;;;eAGG;YAEH,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;YAE5B;;eAEG;YACH,aAAa,EAAE,MAAM,CAAC;YAEtB;;;eAGG;YACH,gBAAgB,EAAE,MAAM,CAAC;SAC5B,CAAC;QAEF,OAAO,EAAE;YACL,aAAa,EAAE,MAAM,CAAC;YACtB,YAAY,EAAE,MAAM,CAAC;YACrB,gBAAgB,EAAE,MAAM,CAAC;YACzB,MAAM,EAAE,MAAM,CAAC;SAClB,CAAC;KACL,CAAC;CACL"}
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ /*!
3
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
4
+ * Licensed under the MIT License.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.deleteFluidCacheIndexDbInstance = exports.getFluidCacheIndexedDbInstance = exports.getKeyForCacheEntry = exports.oldVersionNameMapping = exports.CurrentCacheVersion = exports.FluidDriverObjectStoreName = exports.FluidDriverCacheDBName = void 0;
8
+ const idb_1 = require("idb");
9
+ const telemetry_utils_1 = require("@fluidframework/telemetry-utils");
10
+ // The name of the database that we use for caching Fluid info.
11
+ exports.FluidDriverCacheDBName = "fluidDriverCache";
12
+ // The name of the object store within the indexed db instance that the driver will use to cache Fluid content.
13
+ exports.FluidDriverObjectStoreName = "driverStorage.V3";
14
+ exports.CurrentCacheVersion = 3;
15
+ // Note that V1 and V2 were misspelled as "diver", and we need to keep using the misspelling here.
16
+ exports.oldVersionNameMapping = {
17
+ 1: "diverStorage",
18
+ 2: "diverStorage.V2",
19
+ };
20
+ function getKeyForCacheEntry(entry) {
21
+ return `${entry.file.docId}_${entry.type}_${entry.key}`;
22
+ }
23
+ exports.getKeyForCacheEntry = getKeyForCacheEntry;
24
+ function getFluidCacheIndexedDbInstance(logger) {
25
+ return new Promise((resolve, reject) => {
26
+ idb_1.openDB(exports.FluidDriverCacheDBName, exports.CurrentCacheVersion, {
27
+ upgrade: (db, oldVersion) => {
28
+ try {
29
+ // We changed the format of the object store, so we must
30
+ // delete the old stores to create a new one in V3
31
+ const cacheToDelete = exports.oldVersionNameMapping[oldVersion];
32
+ if (cacheToDelete) {
33
+ // We don't include the old object stores in the schema, so we need to
34
+ // use a typecast here to prevent IDB from complaining
35
+ db.deleteObjectStore(cacheToDelete);
36
+ }
37
+ }
38
+ catch (error) {
39
+ // Catch any error done when attempting to delete the older version.
40
+ // If the object does not exist db will throw.
41
+ // We can now assume that the old version is no longer there regardless.
42
+ telemetry_utils_1.ChildLogger.create(logger).sendErrorEvent({
43
+ eventName: "FluidCacheDeleteOldDbError" /* FluidCacheDeleteOldDbError */,
44
+ }, error);
45
+ }
46
+ const cacheObjectStore = db.createObjectStore(exports.FluidDriverObjectStoreName);
47
+ cacheObjectStore.createIndex("createdTimeMs", "createdTimeMs");
48
+ cacheObjectStore.createIndex("lastAccessTimeMs", "lastAccessTimeMs");
49
+ cacheObjectStore.createIndex("partitionKey", "partitionKey");
50
+ cacheObjectStore.createIndex("fileId", "fileId");
51
+ },
52
+ blocked: () => {
53
+ reject(new Error("Could not open DB since it is blocked by an older client that has the DB open"));
54
+ },
55
+ }).then(resolve, reject);
56
+ });
57
+ }
58
+ exports.getFluidCacheIndexedDbInstance = getFluidCacheIndexedDbInstance;
59
+ // Deletes the indexed DB instance.
60
+ // Warning this can throw an error in Firefox incognito, where accessing storage is prohibited.
61
+ function deleteFluidCacheIndexDbInstance() {
62
+ return idb_1.deleteDB(exports.FluidDriverCacheDBName);
63
+ }
64
+ exports.deleteFluidCacheIndexDbInstance = deleteFluidCacheIndexDbInstance;
65
+ //# sourceMappingURL=FluidCacheIndexedDb.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"FluidCacheIndexedDb.js","sourceRoot":"","sources":["../src/FluidCacheIndexedDb.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,6BAA+D;AAG/D,qEAA8D;AAG9D,+DAA+D;AAClD,QAAA,sBAAsB,GAAG,kBAAkB,CAAC;AAEzD,+GAA+G;AAClG,QAAA,0BAA0B,GAAG,kBAAkB,CAAC;AAEhD,QAAA,mBAAmB,GAAG,CAAC,CAAC;AAErC,kGAAkG;AACrF,QAAA,qBAAqB,GAAuC;IACrE,CAAC,EAAE,cAAc;IACjB,CAAC,EAAE,iBAAiB;CACvB,CAAC;AAEF,SAAgB,mBAAmB,CAAC,KAAkB;IAClD,OAAO,GAAG,KAAK,CAAC,IAAI,CAAC,KAAK,IAAI,KAAK,CAAC,IAAI,IAAI,KAAK,CAAC,GAAG,EAAE,CAAC;AAC5D,CAAC;AAFD,kDAEC;AAED,SAAgB,8BAA8B,CAC1C,MAA6B;IAE7B,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACnC,YAAM,CACF,8BAAsB,EACtB,2BAAmB,EACnB;YACI,OAAO,EAAE,CAAC,EAAE,EAAE,UAAU,EAAE,EAAE;gBACxB,IAAI;oBACA,wDAAwD;oBACxD,kDAAkD;oBAClD,MAAM,aAAa,GAAG,6BAAqB,CAAC,UAAU,CAAC,CAAC;oBACxD,IAAI,aAAa,EAAE;wBACf,sEAAsE;wBACtE,sDAAsD;wBACtD,EAAE,CAAC,iBAAiB,CAAC,aAAoB,CAAC,CAAC;qBAC9C;iBACJ;gBAAC,OAAO,KAAU,EAAE;oBACjB,oEAAoE;oBACpE,8CAA8C;oBAC9C,wEAAwE;oBACxE,6BAAW,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,cAAc,CACrC;wBACI,SAAS,+DAC0C;qBACtD,EACD,KAAK,CACR,CAAC;iBACL;gBAED,MAAM,gBAAgB,GAAG,EAAE,CAAC,iBAAiB,CACzC,kCAA0B,CAC7B,CAAC;gBACF,gBAAgB,CAAC,WAAW,CACxB,eAAe,EACf,eAAe,CAClB,CAAC;gBACF,gBAAgB,CAAC,WAAW,CACxB,kBAAkB,EAClB,kBAAkB,CACrB,CAAC;gBACF,gBAAgB,CAAC,WAAW,CACxB,cAAc,EACd,cAAc,CACjB,CAAC;gBACF,gBAAgB,CAAC,WAAW,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;YACrD,CAAC;YACD,OAAO,EAAE,GAAG,EAAE;gBACV,MAAM,CACF,IAAI,KAAK,CACL,+EAA+E,CAClF,CACJ,CAAC;YACN,CAAC;SACJ,CACJ,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;IAC5B,CAAC,CAAC,CAAC;AACP,CAAC;AA1DD,wEA0DC;AAED,mCAAmC;AACnC,+FAA+F;AAC/F,SAAgB,+BAA+B;IAC3C,OAAO,cAAQ,CAAC,8BAAsB,CAAC,CAAC;AAC5C,CAAC;AAFD,0EAEC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { openDB, DBSchema, IDBPDatabase, deleteDB } from \"idb\";\nimport { ICacheEntry } from \"@fluidframework/odsp-driver-definitions\";\nimport { ITelemetryBaseLogger } from \"@fluidframework/common-definitions\";\nimport { ChildLogger } from \"@fluidframework/telemetry-utils\";\nimport { FluidCacheErrorEvent } from \"./fluidCacheTelemetry\";\n\n// The name of the database that we use for caching Fluid info.\nexport const FluidDriverCacheDBName = \"fluidDriverCache\";\n\n// The name of the object store within the indexed db instance that the driver will use to cache Fluid content.\nexport const FluidDriverObjectStoreName = \"driverStorage.V3\";\n\nexport const CurrentCacheVersion = 3;\n\n// Note that V1 and V2 were misspelled as \"diver\", and we need to keep using the misspelling here.\nexport const oldVersionNameMapping: Partial<{ [key: number]: string }> = {\n 1: \"diverStorage\",\n 2: \"diverStorage.V2\",\n};\n\nexport function getKeyForCacheEntry(entry: ICacheEntry) {\n return `${entry.file.docId}_${entry.type}_${entry.key}`;\n}\n\nexport function getFluidCacheIndexedDbInstance(\n logger?: ITelemetryBaseLogger,\n): Promise<IDBPDatabase<FluidCacheDBSchema>> {\n return new Promise((resolve, reject) => {\n openDB<FluidCacheDBSchema>(\n FluidDriverCacheDBName,\n CurrentCacheVersion,\n {\n upgrade: (db, oldVersion) => {\n try {\n // We changed the format of the object store, so we must\n // delete the old stores to create a new one in V3\n const cacheToDelete = oldVersionNameMapping[oldVersion];\n if (cacheToDelete) {\n // We don't include the old object stores in the schema, so we need to\n // use a typecast here to prevent IDB from complaining\n db.deleteObjectStore(cacheToDelete as any);\n }\n } catch (error: any) {\n // Catch any error done when attempting to delete the older version.\n // If the object does not exist db will throw.\n // We can now assume that the old version is no longer there regardless.\n ChildLogger.create(logger).sendErrorEvent(\n {\n eventName:\n FluidCacheErrorEvent.FluidCacheDeleteOldDbError,\n },\n error,\n );\n }\n\n const cacheObjectStore = db.createObjectStore(\n FluidDriverObjectStoreName,\n );\n cacheObjectStore.createIndex(\n \"createdTimeMs\",\n \"createdTimeMs\",\n );\n cacheObjectStore.createIndex(\n \"lastAccessTimeMs\",\n \"lastAccessTimeMs\",\n );\n cacheObjectStore.createIndex(\n \"partitionKey\",\n \"partitionKey\",\n );\n cacheObjectStore.createIndex(\"fileId\", \"fileId\");\n },\n blocked: () => {\n reject(\n new Error(\n \"Could not open DB since it is blocked by an older client that has the DB open\",\n ),\n );\n },\n },\n ).then(resolve, reject);\n });\n}\n\n// Deletes the indexed DB instance.\n// Warning this can throw an error in Firefox incognito, where accessing storage is prohibited.\nexport function deleteFluidCacheIndexDbInstance(): Promise<void> {\n return deleteDB(FluidDriverCacheDBName);\n}\n\n/**\n * Schema for the object store used to cache driver information\n */\nexport interface FluidCacheDBSchema extends DBSchema {\n [FluidDriverObjectStoreName]: {\n /**\n * A unique identifier for an item in the cache. It is a combination of file, type, and cacheItemId\n */\n key: string;\n\n value: {\n /**\n * The identifier of the file associated with the cache entry\n */\n fileId: string;\n\n /**\n * Describes the type of content being cached, such as snapshot\n */\n type: string;\n\n /**\n * Files may have multiple cached items associated with them,\n * this property uniquely identifies a specific cache entry for a file.\n * This is not globally unique, but rather a unique id for this file\n */\n cacheItemId: string;\n\n /*\n * Opaque object that the driver asks us to store in a cache for performance reasons\n */\n cachedObject: any;\n\n /**\n * A string to specify what partition of the cache you wish to use (e.g. a user id).\n * Null can be used to explicity indicate no partitioning.\n */\n // eslint-disable-next-line @rushstack/no-new-null\n partitionKey: string | null;\n\n /**\n * The time when the cache entry was put into the cache\n */\n createdTimeMs: number;\n\n /**\n * The last time the cache entry was used.\n * This is initially set to the time the cache entry was created Measured as ms since unix epoch.\n */\n lastAccessTimeMs: number;\n };\n\n indexes: {\n createdTimeMs: number;\n partitionKey: string;\n lastAccessTimeMs: number;\n fileId: string;\n };\n };\n}\n"]}
@@ -0,0 +1,19 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+ export declare const enum FluidCacheGenericEvent {
6
+ "FluidCacheStorageInfo" = "FluidCacheStorageInfo",
7
+ "FluidCachePartitionKeyMismatch" = "FluidCachePartitionKeyMismatch"
8
+ }
9
+ export declare const enum FluidCacheErrorEvent {
10
+ "FluidCacheDeleteOldEntriesError" = "FluidCacheDeleteOldEntriesError",
11
+ "FluidCacheGetError" = "FluidCacheGetError",
12
+ "FluidCachePutError" = "FluidCachePutError",
13
+ "FluidCacheUpdateUsageError" = "FluidCacheUpdateUsageError",
14
+ "FluidCacheDeleteOldDbError" = "FluidCacheDeleteOldDbError"
15
+ }
16
+ export declare const enum FluidCacheEventSubCategories {
17
+ "FluidCache" = "FluidCache"
18
+ }
19
+ //# sourceMappingURL=fluidCacheTelemetry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fluidCacheTelemetry.d.ts","sourceRoot":"","sources":["../src/fluidCacheTelemetry.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,0BAAkB,sBAAsB;IACpC,uBAAuB,0BAA0B;IACjD,gCAAgC,mCAAmC;CACtE;AAED,0BAAkB,oBAAoB;IAClC,iCAAiC,oCAAoC;IACrE,oBAAoB,uBAAuB;IAC3C,oBAAoB,uBAAuB;IAC3C,4BAA4B,+BAA+B;IAC3D,4BAA4B,+BAA+B;CAC9D;AAED,0BAAkB,4BAA4B;IAC1C,YAAY,eAAe;CAC9B"}
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ /*!
3
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
4
+ * Licensed under the MIT License.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ //# sourceMappingURL=fluidCacheTelemetry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fluidCacheTelemetry.js","sourceRoot":"","sources":["../src/fluidCacheTelemetry.ts"],"names":[],"mappings":";AAAA;;;GAGG","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nexport const enum FluidCacheGenericEvent {\n \"FluidCacheStorageInfo\" = \"FluidCacheStorageInfo\",\n \"FluidCachePartitionKeyMismatch\" = \"FluidCachePartitionKeyMismatch\",\n}\n\nexport const enum FluidCacheErrorEvent {\n \"FluidCacheDeleteOldEntriesError\" = \"FluidCacheDeleteOldEntriesError\",\n \"FluidCacheGetError\" = \"FluidCacheGetError\",\n \"FluidCachePutError\" = \"FluidCachePutError\",\n \"FluidCacheUpdateUsageError\" = \"FluidCacheUpdateUsageError\",\n \"FluidCacheDeleteOldDbError\" = \"FluidCacheDeleteOldDbError\",\n}\n\nexport const enum FluidCacheEventSubCategories {\n \"FluidCache\" = \"FluidCache\",\n}\n"]}
@@ -0,0 +1,7 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+ export * from "./FluidCache";
6
+ export { deleteFluidCacheIndexDbInstance } from "./FluidCacheIndexedDb";
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,cAAc,cAAc,CAAC;AAC7B,OAAO,EAAE,+BAA+B,EAAE,MAAM,uBAAuB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ /*!
3
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
4
+ * Licensed under the MIT License.
5
+ */
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.deleteFluidCacheIndexDbInstance = void 0;
18
+ __exportStar(require("./FluidCache"), exports);
19
+ var FluidCacheIndexedDb_1 = require("./FluidCacheIndexedDb");
20
+ Object.defineProperty(exports, "deleteFluidCacheIndexDbInstance", { enumerable: true, get: function () { return FluidCacheIndexedDb_1.deleteFluidCacheIndexDbInstance; } });
21
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;;;;;;;;;;;AAEH,+CAA6B;AAC7B,6DAAwE;AAA/D,sIAAA,+BAA+B,OAAA","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nexport * from \"./FluidCache\";\nexport { deleteFluidCacheIndexDbInstance } from \"./FluidCacheIndexedDb\";\n"]}
@@ -0,0 +1,9 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ *
5
+ * THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY
6
+ */
7
+ export declare const pkgName = "@fluidframework/driver-web-cache";
8
+ export declare const pkgVersion = "0.58.2000-58133";
9
+ //# sourceMappingURL=packageVersion.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"packageVersion.d.ts","sourceRoot":"","sources":["../src/packageVersion.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,eAAO,MAAM,OAAO,qCAAqC,CAAC;AAC1D,eAAO,MAAM,UAAU,oBAAoB,CAAC"}
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ /*!
3
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
4
+ * Licensed under the MIT License.
5
+ *
6
+ * THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.pkgVersion = exports.pkgName = void 0;
10
+ exports.pkgName = "@fluidframework/driver-web-cache";
11
+ exports.pkgVersion = "0.58.2000-58133";
12
+ //# sourceMappingURL=packageVersion.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"packageVersion.js","sourceRoot":"","sources":["../src/packageVersion.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAEU,QAAA,OAAO,GAAG,kCAAkC,CAAC;AAC7C,QAAA,UAAU,GAAG,iBAAiB,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n *\n * THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY\n */\n\nexport const pkgName = \"@fluidframework/driver-web-cache\";\nexport const pkgVersion = \"0.58.2000-58133\";\n"]}
@@ -0,0 +1,22 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+ declare global {
6
+ interface Window {
7
+ requestIdleCallback: ((callback: (deadline: {
8
+ readonly didTimeout: boolean;
9
+ timeRemaining: () => number;
10
+ }) => void, opts?: {
11
+ timeout: number;
12
+ }) => number) | undefined;
13
+ cancelIdleCallback: ((handle: number) => void) | undefined;
14
+ }
15
+ }
16
+ /**
17
+ * A function that schedules a non critical task to be run when the browser has cycles available
18
+ * @param task - The task to be executed
19
+ * @param options - Optional configuration for the task execution
20
+ */
21
+ export declare function scheduleIdleTask(task: () => void): void;
22
+ //# sourceMappingURL=scheduleIdleTask.d.ts.map