@itwin/core-backend 3.7.7 → 3.7.9

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 (247) hide show
  1. package/CHANGELOG.md +13 -1
  2. package/lib/cjs/AliCloudStorageService.d.ts +23 -23
  3. package/lib/cjs/AliCloudStorageService.js +71 -71
  4. package/lib/cjs/AliCloudStorageService.js.map +1 -1
  5. package/lib/cjs/BackendHubAccess.d.ts +224 -224
  6. package/lib/cjs/BackendHubAccess.js +41 -41
  7. package/lib/cjs/BackendHubAccess.js.map +1 -1
  8. package/lib/cjs/BackendLoggerCategory.d.ts +91 -91
  9. package/lib/cjs/BackendLoggerCategory.js +99 -99
  10. package/lib/cjs/BackendLoggerCategory.js.map +1 -1
  11. package/lib/cjs/BisCoreSchema.d.ts +21 -21
  12. package/lib/cjs/BisCoreSchema.js +60 -60
  13. package/lib/cjs/BisCoreSchema.js.map +1 -1
  14. package/lib/cjs/BriefcaseManager.d.ts +170 -170
  15. package/lib/cjs/BriefcaseManager.js +414 -414
  16. package/lib/cjs/BriefcaseManager.js.map +1 -1
  17. package/lib/cjs/Category.d.ts +153 -153
  18. package/lib/cjs/Category.js +243 -243
  19. package/lib/cjs/Category.js.map +1 -1
  20. package/lib/cjs/ChangeSummaryManager.d.ts +187 -187
  21. package/lib/cjs/ChangeSummaryManager.js +447 -447
  22. package/lib/cjs/ChangeSummaryManager.js.map +1 -1
  23. package/lib/cjs/ChangedElementsDb.d.ts +99 -99
  24. package/lib/cjs/ChangedElementsDb.js +165 -165
  25. package/lib/cjs/ChangedElementsDb.js.map +1 -1
  26. package/lib/cjs/ChangedElementsManager.d.ts +39 -39
  27. package/lib/cjs/ChangedElementsManager.js +88 -88
  28. package/lib/cjs/ChangedElementsManager.js.map +1 -1
  29. package/lib/cjs/CheckpointManager.d.ts +121 -121
  30. package/lib/cjs/CheckpointManager.d.ts.map +1 -1
  31. package/lib/cjs/CheckpointManager.js +363 -352
  32. package/lib/cjs/CheckpointManager.js.map +1 -1
  33. package/lib/cjs/ClassRegistry.d.ts +79 -79
  34. package/lib/cjs/ClassRegistry.js +250 -250
  35. package/lib/cjs/ClassRegistry.js.map +1 -1
  36. package/lib/cjs/CloudSqlite.d.ts +350 -350
  37. package/lib/cjs/CloudSqlite.js +153 -153
  38. package/lib/cjs/CloudSqlite.js.map +1 -1
  39. package/lib/cjs/CloudStorageBackend.d.ts +58 -58
  40. package/lib/cjs/CloudStorageBackend.js +173 -173
  41. package/lib/cjs/CloudStorageBackend.js.map +1 -1
  42. package/lib/cjs/CodeService.d.ts +396 -396
  43. package/lib/cjs/CodeService.js +63 -63
  44. package/lib/cjs/CodeService.js.map +1 -1
  45. package/lib/cjs/CodeSpecs.d.ts +55 -55
  46. package/lib/cjs/CodeSpecs.js +124 -124
  47. package/lib/cjs/CodeSpecs.js.map +1 -1
  48. package/lib/cjs/ConcurrentQuery.d.ts +13 -13
  49. package/lib/cjs/ConcurrentQuery.js +36 -36
  50. package/lib/cjs/ConcurrentQuery.js.map +1 -1
  51. package/lib/cjs/CustomViewState3dCreator.d.ts +21 -21
  52. package/lib/cjs/CustomViewState3dCreator.js +82 -82
  53. package/lib/cjs/CustomViewState3dCreator.js.map +1 -1
  54. package/lib/cjs/DevTools.d.ts +71 -71
  55. package/lib/cjs/DevTools.js +154 -154
  56. package/lib/cjs/DevTools.js.map +1 -1
  57. package/lib/cjs/DisplayStyle.d.ts +106 -106
  58. package/lib/cjs/DisplayStyle.js +256 -256
  59. package/lib/cjs/DisplayStyle.js.map +1 -1
  60. package/lib/cjs/ECDb.d.ts +194 -194
  61. package/lib/cjs/ECDb.js +355 -355
  62. package/lib/cjs/ECDb.js.map +1 -1
  63. package/lib/cjs/ECSchemaXmlContext.d.ts +18 -18
  64. package/lib/cjs/ECSchemaXmlContext.js +41 -41
  65. package/lib/cjs/ECSchemaXmlContext.js.map +1 -1
  66. package/lib/cjs/ECSqlStatement.d.ts +473 -473
  67. package/lib/cjs/ECSqlStatement.js +791 -791
  68. package/lib/cjs/ECSqlStatement.js.map +1 -1
  69. package/lib/cjs/Element.d.ts +1109 -1109
  70. package/lib/cjs/Element.js +1427 -1427
  71. package/lib/cjs/Element.js.map +1 -1
  72. package/lib/cjs/ElementAspect.d.ts +179 -179
  73. package/lib/cjs/ElementAspect.js +211 -211
  74. package/lib/cjs/ElementAspect.js.map +1 -1
  75. package/lib/cjs/ElementGraphics.d.ts +9 -9
  76. package/lib/cjs/ElementGraphics.js +41 -41
  77. package/lib/cjs/ElementGraphics.js.map +1 -1
  78. package/lib/cjs/ElementTreeWalker.d.ts +162 -162
  79. package/lib/cjs/ElementTreeWalker.js +409 -409
  80. package/lib/cjs/ElementTreeWalker.js.map +1 -1
  81. package/lib/cjs/Entity.d.ts +106 -106
  82. package/lib/cjs/Entity.js +134 -134
  83. package/lib/cjs/Entity.js.map +1 -1
  84. package/lib/cjs/EntityReferences.d.ts +49 -49
  85. package/lib/cjs/EntityReferences.js +95 -95
  86. package/lib/cjs/EntityReferences.js.map +1 -1
  87. package/lib/cjs/ExportGraphics.d.ts +317 -317
  88. package/lib/cjs/ExportGraphics.js +208 -208
  89. package/lib/cjs/ExportGraphics.js.map +1 -1
  90. package/lib/cjs/ExternalSource.d.ts +96 -96
  91. package/lib/cjs/ExternalSource.js +131 -131
  92. package/lib/cjs/ExternalSource.js.map +1 -1
  93. package/lib/cjs/GeoCoordConfig.d.ts +19 -19
  94. package/lib/cjs/GeoCoordConfig.js +85 -85
  95. package/lib/cjs/GeoCoordConfig.js.map +1 -1
  96. package/lib/cjs/GeometrySummary.d.ts +4 -4
  97. package/lib/cjs/GeometrySummary.js +380 -380
  98. package/lib/cjs/GeometrySummary.js.map +1 -1
  99. package/lib/cjs/HubMock.d.ts +94 -94
  100. package/lib/cjs/HubMock.js +222 -222
  101. package/lib/cjs/HubMock.js.map +1 -1
  102. package/lib/cjs/IModelCloneContext.d.ts +8 -8
  103. package/lib/cjs/IModelCloneContext.js +15 -15
  104. package/lib/cjs/IModelCloneContext.js.map +1 -1
  105. package/lib/cjs/IModelDb.d.ts +1213 -1213
  106. package/lib/cjs/IModelDb.js +2392 -2392
  107. package/lib/cjs/IModelDb.js.map +1 -1
  108. package/lib/cjs/IModelElementCloneContext.d.ts +89 -89
  109. package/lib/cjs/IModelElementCloneContext.js +159 -159
  110. package/lib/cjs/IModelElementCloneContext.js.map +1 -1
  111. package/lib/cjs/IModelHost.d.ts +370 -369
  112. package/lib/cjs/IModelHost.d.ts.map +1 -1
  113. package/lib/cjs/IModelHost.js +497 -496
  114. package/lib/cjs/IModelHost.js.map +1 -1
  115. package/lib/cjs/IModelJsFs.d.ts +62 -62
  116. package/lib/cjs/IModelJsFs.js +140 -140
  117. package/lib/cjs/IModelJsFs.js.map +1 -1
  118. package/lib/cjs/IpcHost.d.ts +104 -104
  119. package/lib/cjs/IpcHost.js +278 -278
  120. package/lib/cjs/IpcHost.js.map +1 -1
  121. package/lib/cjs/LineStyle.d.ts +311 -311
  122. package/lib/cjs/LineStyle.js +295 -295
  123. package/lib/cjs/LineStyle.js.map +1 -1
  124. package/lib/cjs/LocalHub.d.ts +162 -162
  125. package/lib/cjs/LocalHub.js +585 -585
  126. package/lib/cjs/LocalHub.js.map +1 -1
  127. package/lib/cjs/LocalhostIpcHost.d.ts +21 -21
  128. package/lib/cjs/LocalhostIpcHost.js +81 -81
  129. package/lib/cjs/LocalhostIpcHost.js.map +1 -1
  130. package/lib/cjs/Material.d.ts +131 -131
  131. package/lib/cjs/Material.js +181 -181
  132. package/lib/cjs/Material.js.map +1 -1
  133. package/lib/cjs/Model.d.ts +392 -392
  134. package/lib/cjs/Model.js +485 -485
  135. package/lib/cjs/Model.js.map +1 -1
  136. package/lib/cjs/NativeAppStorage.d.ts +51 -51
  137. package/lib/cjs/NativeAppStorage.js +202 -202
  138. package/lib/cjs/NativeAppStorage.js.map +1 -1
  139. package/lib/cjs/NativeHost.d.ts +52 -52
  140. package/lib/cjs/NativeHost.js +163 -163
  141. package/lib/cjs/NativeHost.js.map +1 -1
  142. package/lib/cjs/NavigationRelationship.d.ts +156 -156
  143. package/lib/cjs/NavigationRelationship.js +225 -225
  144. package/lib/cjs/NavigationRelationship.js.map +1 -1
  145. package/lib/cjs/PromiseMemoizer.d.ts +51 -51
  146. package/lib/cjs/PromiseMemoizer.js +101 -101
  147. package/lib/cjs/PromiseMemoizer.js.map +1 -1
  148. package/lib/cjs/PropertyStore.d.ts +132 -132
  149. package/lib/cjs/PropertyStore.js +11 -11
  150. package/lib/cjs/PropertyStore.js.map +1 -1
  151. package/lib/cjs/Relationship.d.ts +416 -416
  152. package/lib/cjs/Relationship.js +494 -494
  153. package/lib/cjs/Relationship.js.map +1 -1
  154. package/lib/cjs/RpcBackend.d.ts +5 -5
  155. package/lib/cjs/RpcBackend.js +32 -32
  156. package/lib/cjs/RpcBackend.js.map +1 -1
  157. package/lib/cjs/SQLiteDb.d.ts +219 -219
  158. package/lib/cjs/SQLiteDb.js +214 -214
  159. package/lib/cjs/SQLiteDb.js.map +1 -1
  160. package/lib/cjs/Schema.d.ts +55 -55
  161. package/lib/cjs/Schema.js +83 -83
  162. package/lib/cjs/Schema.js.map +1 -1
  163. package/lib/cjs/ServerBasedLocks.d.ts +57 -57
  164. package/lib/cjs/ServerBasedLocks.js +168 -168
  165. package/lib/cjs/ServerBasedLocks.js.map +1 -1
  166. package/lib/cjs/SqliteStatement.d.ts +360 -360
  167. package/lib/cjs/SqliteStatement.js +586 -586
  168. package/lib/cjs/SqliteStatement.js.map +1 -1
  169. package/lib/cjs/Texture.d.ts +58 -58
  170. package/lib/cjs/Texture.js +82 -82
  171. package/lib/cjs/Texture.js.map +1 -1
  172. package/lib/cjs/TileStorage.d.ts +25 -18
  173. package/lib/cjs/TileStorage.d.ts.map +1 -1
  174. package/lib/cjs/TileStorage.js +102 -90
  175. package/lib/cjs/TileStorage.js.map +1 -1
  176. package/lib/cjs/TxnManager.d.ts +202 -202
  177. package/lib/cjs/TxnManager.js +356 -356
  178. package/lib/cjs/TxnManager.js.map +1 -1
  179. package/lib/cjs/ViewDefinition.d.ts +439 -439
  180. package/lib/cjs/ViewDefinition.js +646 -646
  181. package/lib/cjs/ViewDefinition.js.map +1 -1
  182. package/lib/cjs/ViewStateHydrator.d.ts +13 -13
  183. package/lib/cjs/ViewStateHydrator.js +103 -103
  184. package/lib/cjs/ViewStateHydrator.js.map +1 -1
  185. package/lib/cjs/assets/IModelChange.02.00.00.ecschema.xml +90 -90
  186. package/lib/cjs/assets/Settings/Schemas/Cloud.Schema.json +67 -67
  187. package/lib/cjs/assets/Settings/Schemas/Gcs.schema.json +31 -31
  188. package/lib/cjs/assets/Settings/Schemas/Workspace.Schema.json +52 -52
  189. package/lib/cjs/assets/Settings/backend.setting.json5 +138 -138
  190. package/lib/cjs/core-backend.d.ts +184 -184
  191. package/lib/cjs/core-backend.js +204 -204
  192. package/lib/cjs/core-backend.js.map +1 -1
  193. package/lib/cjs/domains/FunctionalElements.d.ts +101 -101
  194. package/lib/cjs/domains/FunctionalElements.js +145 -145
  195. package/lib/cjs/domains/FunctionalElements.js.map +1 -1
  196. package/lib/cjs/domains/FunctionalSchema.d.ts +13 -13
  197. package/lib/cjs/domains/FunctionalSchema.js +40 -40
  198. package/lib/cjs/domains/FunctionalSchema.js.map +1 -1
  199. package/lib/cjs/domains/GenericElements.d.ts +177 -177
  200. package/lib/cjs/domains/GenericElements.js +263 -263
  201. package/lib/cjs/domains/GenericElements.js.map +1 -1
  202. package/lib/cjs/domains/GenericSchema.d.ts +10 -10
  203. package/lib/cjs/domains/GenericSchema.js +28 -28
  204. package/lib/cjs/domains/GenericSchema.js.map +1 -1
  205. package/lib/cjs/rpc/multipart.d.ts +11 -11
  206. package/lib/cjs/rpc/multipart.js +71 -71
  207. package/lib/cjs/rpc/multipart.js.map +1 -1
  208. package/lib/cjs/rpc/tracing.d.ts +28 -28
  209. package/lib/cjs/rpc/tracing.js +74 -74
  210. package/lib/cjs/rpc/tracing.js.map +1 -1
  211. package/lib/cjs/rpc/web/logging.d.ts +9 -9
  212. package/lib/cjs/rpc/web/logging.js +43 -43
  213. package/lib/cjs/rpc/web/logging.js.map +1 -1
  214. package/lib/cjs/rpc/web/request.d.ts +6 -6
  215. package/lib/cjs/rpc/web/request.js +74 -74
  216. package/lib/cjs/rpc/web/request.js.map +1 -1
  217. package/lib/cjs/rpc/web/response.d.ts +6 -6
  218. package/lib/cjs/rpc/web/response.js +106 -106
  219. package/lib/cjs/rpc/web/response.js.map +1 -1
  220. package/lib/cjs/rpc-impl/DevToolsRpcImpl.d.ts +15 -15
  221. package/lib/cjs/rpc-impl/DevToolsRpcImpl.js +32 -32
  222. package/lib/cjs/rpc-impl/DevToolsRpcImpl.js.map +1 -1
  223. package/lib/cjs/rpc-impl/IModelReadRpcImpl.d.ts +47 -47
  224. package/lib/cjs/rpc-impl/IModelReadRpcImpl.js +294 -294
  225. package/lib/cjs/rpc-impl/IModelReadRpcImpl.js.map +1 -1
  226. package/lib/cjs/rpc-impl/IModelTileRpcImpl.d.ts +22 -22
  227. package/lib/cjs/rpc-impl/IModelTileRpcImpl.js +211 -211
  228. package/lib/cjs/rpc-impl/IModelTileRpcImpl.js.map +1 -1
  229. package/lib/cjs/rpc-impl/RpcBriefcaseUtility.d.ts +36 -36
  230. package/lib/cjs/rpc-impl/RpcBriefcaseUtility.js +168 -168
  231. package/lib/cjs/rpc-impl/RpcBriefcaseUtility.js.map +1 -1
  232. package/lib/cjs/rpc-impl/SnapshotIModelRpcImpl.d.ts +16 -16
  233. package/lib/cjs/rpc-impl/SnapshotIModelRpcImpl.js +43 -43
  234. package/lib/cjs/rpc-impl/SnapshotIModelRpcImpl.js.map +1 -1
  235. package/lib/cjs/rpc-impl/WipRpcImpl.d.ts +15 -15
  236. package/lib/cjs/rpc-impl/WipRpcImpl.js +37 -37
  237. package/lib/cjs/rpc-impl/WipRpcImpl.js.map +1 -1
  238. package/lib/cjs/workspace/Settings.d.ts +186 -186
  239. package/lib/cjs/workspace/Settings.js +155 -155
  240. package/lib/cjs/workspace/Settings.js.map +1 -1
  241. package/lib/cjs/workspace/SettingsSchemas.d.ts +75 -75
  242. package/lib/cjs/workspace/SettingsSchemas.js +191 -191
  243. package/lib/cjs/workspace/SettingsSchemas.js.map +1 -1
  244. package/lib/cjs/workspace/Workspace.d.ts +414 -414
  245. package/lib/cjs/workspace/Workspace.js +543 -543
  246. package/lib/cjs/workspace/Workspace.js.map +1 -1
  247. package/package.json +17 -16
@@ -1,353 +1,364 @@
1
- "use strict";
2
- /*---------------------------------------------------------------------------------------------
3
- * Copyright (c) Bentley Systems, Incorporated. All rights reserved.
4
- * See LICENSE.md in the project root for license terms and full copyright notice.
5
- *--------------------------------------------------------------------------------------------*/
6
- /** @packageDocumentation
7
- * @module iModels
8
- */
9
- Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.CheckpointManager = exports.V1CheckpointManager = exports.V2CheckpointManager = exports.Downloads = exports.ProgressStatus = void 0;
11
- // cspell:ignore BLOCKCACHE
12
- const path = require("path");
13
- const core_bentley_1 = require("@itwin/core-bentley");
14
- const core_common_1 = require("@itwin/core-common");
15
- const BackendLoggerCategory_1 = require("./BackendLoggerCategory");
16
- const BriefcaseManager_1 = require("./BriefcaseManager");
17
- const CloudSqlite_1 = require("./CloudSqlite");
18
- const IModelDb_1 = require("./IModelDb");
19
- const IModelHost_1 = require("./IModelHost");
20
- const IModelJsFs_1 = require("./IModelJsFs");
21
- const imodeljs_native_1 = require("@bentley/imodeljs-native");
22
- const loggerCategory = BackendLoggerCategory_1.BackendLoggerCategory.IModelDb;
23
- /** Return value from [[ProgressFunction]].
24
- * @public
25
- */
26
- var ProgressStatus;
27
- (function (ProgressStatus) {
28
- /** Continue download. */
29
- ProgressStatus[ProgressStatus["Continue"] = 0] = "Continue";
30
- /** Abort download. */
31
- ProgressStatus[ProgressStatus["Abort"] = 1] = "Abort";
32
- })(ProgressStatus = exports.ProgressStatus || (exports.ProgressStatus = {}));
33
- /** @internal */
34
- class Downloads {
35
- static async process(job, fn) {
36
- const jobName = job.request.localFile; // save this, it can change inside call to `fn`!
37
- this._active.set(jobName, job);
38
- try {
39
- return await fn(job);
40
- }
41
- finally {
42
- this._active.delete(jobName);
43
- }
44
- }
45
- static isInProgress(pathName) {
46
- return this._active.get(pathName);
47
- }
48
- static async download(request, downloadFn) {
49
- const pathName = request.localFile;
50
- let job = this.isInProgress(pathName);
51
- if (undefined !== job)
52
- return job.promise;
53
- IModelJsFs_1.IModelJsFs.recursiveMkDirSync(path.dirname(pathName));
54
- job = { request };
55
- return job.promise = this.process(job, downloadFn);
56
- }
57
- }
58
- exports.Downloads = Downloads;
59
- Downloads._active = new Map();
60
- /**
61
- * Utility class for opening V2 checkpoints from cloud containers, and also for downloading them.
62
- * @internal
63
- */
64
- class V2CheckpointManager {
65
- static getFolder() {
66
- const cloudCachePath = path.join(BriefcaseManager_1.BriefcaseManager.cacheDir, V2CheckpointManager.cloudCacheName);
67
- if (!(IModelJsFs_1.IModelJsFs.existsSync(cloudCachePath))) {
68
- IModelJsFs_1.IModelJsFs.recursiveMkDirSync(cloudCachePath);
69
- }
70
- return cloudCachePath;
71
- }
72
- /* only used by tests that reset the state of the v2checkpointmanager. all dbs should be closed before calling this function. */
73
- static cleanup() {
74
- var _a;
75
- for (const [_, value] of this.containers.entries()) {
76
- if (value.isConnected)
77
- value.detach();
78
- }
79
- (_a = this._cloudCache) === null || _a === void 0 ? void 0 : _a.destroy();
80
- this._cloudCache = undefined;
81
- this.containers.clear();
82
- }
83
- static getFileName(checkpoint) {
84
- const changesetId = checkpoint.changeset.id || "first";
85
- return path.join(this.getFolder(), `${changesetId}.bim`);
86
- }
87
- static get cloudCache() {
88
- if (!this._cloudCache) {
89
- let rootDir = process.env.CHECKPOINT_CACHE_DIR;
90
- if (!rootDir) {
91
- rootDir = this.getFolder();
92
- core_bentley_1.Logger.logWarning(loggerCategory, `No CHECKPOINT_CACHE_DIR found in process.env, using ${rootDir} instead.`);
93
- }
94
- else {
95
- // Make sure the checkpoint_cache_dir has an iTwinDaemon specific file in it, otherwise fall back to other directory.
96
- if (!(IModelJsFs_1.IModelJsFs.existsSync(path.join(rootDir, "portnumber.bcv")))) {
97
- rootDir = this.getFolder();
98
- core_bentley_1.Logger.logWarning(loggerCategory, `No evidence of the iTwinDaemon in provided CHECKPOINT_CACHE_DIR: ${process.env.CHECKPOINT_CACHE_DIR}, using ${rootDir} instead.`);
99
- }
100
- }
101
- this._cloudCache = CloudSqlite_1.CloudSqlite.createCloudCache({ name: this.cloudCacheName, rootDir });
102
- // Its fine if its not a daemon, but lets log an info message
103
- if (!this._cloudCache.isDaemon)
104
- core_bentley_1.Logger.logInfo(loggerCategory, "V2Checkpoint manager running with no iTwinDaemon.");
105
- }
106
- return this._cloudCache;
107
- }
108
- /** Member names differ slightly between the V2Checkpoint api and the CloudSqlite api. Add aliases `accessName` for `accountName` and `accessToken` for `sasToken` */
109
- static toCloudContainerProps(from) {
110
- return { ...from, accessName: from.accountName, accessToken: from.sasToken };
111
- }
112
- static getContainer(v2Props) {
113
- let container = this.containers.get(v2Props.containerId);
114
- if (!container) {
115
- container = CloudSqlite_1.CloudSqlite.createCloudContainer(this.toCloudContainerProps(v2Props));
116
- this.containers.set(v2Props.containerId, container);
117
- }
118
- return container;
119
- }
120
- static async attach(checkpoint) {
121
- let v2props;
122
- try {
123
- v2props = await IModelHost_1.IModelHost.hubAccess.queryV2Checkpoint(checkpoint);
124
- if (!v2props)
125
- throw new Error("no checkpoint");
126
- }
127
- catch (err) {
128
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.NotFound, `V2 checkpoint not found: err: ${err.message}`);
129
- }
130
- try {
131
- const container = this.getContainer(v2props);
132
- const dbName = v2props.dbName;
133
- if (!container.isConnected)
134
- container.connect(this.cloudCache);
135
- container.checkForChanges();
136
- if (IModelHost_1.IModelHost.appWorkspace.settings.getBoolean("Checkpoints/prefetch", false)) {
137
- const logPrefetch = async (prefetch) => {
138
- const stopwatch = new core_bentley_1.StopWatch(`[${container.containerId}/${dbName}]`, true);
139
- core_bentley_1.Logger.logInfo(loggerCategory, `Starting prefetch of ${stopwatch.description}`);
140
- const done = await prefetch.promise;
141
- core_bentley_1.Logger.logInfo(loggerCategory, `Prefetch of ${stopwatch.description} complete=${done} (${stopwatch.elapsedSeconds} seconds)`);
142
- };
143
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
144
- logPrefetch(CloudSqlite_1.CloudSqlite.startCloudPrefetch(container, dbName));
145
- }
146
- return { dbName, container };
147
- }
148
- catch (e) {
149
- const error = `Cloud cache connect failed: ${e.message}`;
150
- if (checkpoint.expectV2)
151
- core_bentley_1.Logger.logError(loggerCategory, error);
152
- throw new core_common_1.IModelError(e.errorNumber, error);
153
- }
154
- }
155
- static async performDownload(job) {
156
- const request = job.request;
157
- const v2props = await IModelHost_1.IModelHost.hubAccess.queryV2Checkpoint({ ...request.checkpoint, allowPreceding: true });
158
- if (!v2props)
159
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.NotFound, "V2 checkpoint not found");
160
- CheckpointManager.onDownloadV2.raiseEvent(job);
161
- const container = CloudSqlite_1.CloudSqlite.createCloudContainer(this.toCloudContainerProps(v2props));
162
- await CloudSqlite_1.CloudSqlite.transferDb("download", container, { dbName: v2props.dbName, localFileName: request.localFile, onProgress: request.onProgress });
163
- return request.checkpoint.changeset.id;
164
- }
165
- /** Fully download a V2 checkpoint to a local file that can be used to create a briefcase or to work offline.
166
- * @returns a Promise that is resolved when the download completes with the changesetId of the downloaded checkpoint (which will
167
- * be the same as the requested changesetId or the most recent checkpoint before it.)
168
- */
169
- static async downloadCheckpoint(request) {
170
- return Downloads.download(request, async (job) => this.performDownload(job));
171
- }
172
- }
173
- exports.V2CheckpointManager = V2CheckpointManager;
174
- V2CheckpointManager.cloudCacheName = "v2Checkpoints";
175
- V2CheckpointManager.containers = new Map();
176
- /** Utility class to deal with downloading V1 checkpoints from iModelHub.
177
- * @internal
178
- */
179
- class V1CheckpointManager {
180
- static getFolder(iModelId) {
181
- return path.join(BriefcaseManager_1.BriefcaseManager.getIModelPath(iModelId), "checkpoints");
182
- }
183
- static getFileName(checkpoint) {
184
- const changesetId = checkpoint.changeset.id || "first";
185
- return path.join(this.getFolder(checkpoint.iModelId), `${changesetId}.bim`);
186
- }
187
- static async getCheckpointDb(request) {
188
- const db = IModelDb_1.SnapshotDb.tryFindByKey(CheckpointManager.getKey(request.checkpoint));
189
- return (undefined !== db) ? db : Downloads.download(request, async (job) => this.downloadAndOpen(job));
190
- }
191
- /** Download a V1 checkpoint */
192
- static async downloadCheckpoint(request) {
193
- return Downloads.download(request, async (job) => this.performDownload(job));
194
- }
195
- static async downloadAndOpen(job) {
196
- const db = CheckpointManager.tryOpenLocalFile(job.request);
197
- if (db)
198
- return db;
199
- await this.performDownload(job);
200
- await CheckpointManager.updateToRequestedVersion(job.request);
201
- return IModelDb_1.SnapshotDb.openCheckpointV1(job.request.localFile, job.request.checkpoint);
202
- }
203
- static async performDownload(job) {
204
- CheckpointManager.onDownloadV1.raiseEvent(job);
205
- // eslint-disable-next-line deprecation/deprecation
206
- return (await IModelHost_1.IModelHost.hubAccess.downloadV1Checkpoint(job.request)).id;
207
- }
208
- }
209
- exports.V1CheckpointManager = V1CheckpointManager;
210
- /** @internal */
211
- class CheckpointManager {
212
- static getKey(checkpoint) { return `${checkpoint.iModelId}:${checkpoint.changeset.id}`; }
213
- static async doDownload(request) {
214
- try {
215
- // first see if there's a V2 checkpoint available.
216
- const changesetId = await V2CheckpointManager.downloadCheckpoint(request);
217
- if (changesetId !== request.checkpoint.changeset.id)
218
- core_bentley_1.Logger.logInfo(loggerCategory, `Downloaded previous v2 checkpoint because requested checkpoint not found.`, { requestedChangesetId: request.checkpoint.changeset.id, iModelId: request.checkpoint.iModelId, changesetId, iTwinId: request.checkpoint.iTwinId });
219
- else
220
- core_bentley_1.Logger.logInfo(loggerCategory, `Downloaded v2 checkpoint.`, { iModelId: request.checkpoint.iModelId, changesetId: request.checkpoint.changeset.id, iTwinId: request.checkpoint.iTwinId });
221
- return changesetId;
222
- }
223
- catch (error) {
224
- if (error.errorNumber === core_bentley_1.IModelStatus.NotFound) { // No V2 checkpoint available, try a v1 checkpoint
225
- const changeset = await V1CheckpointManager.downloadCheckpoint(request);
226
- core_bentley_1.Logger.logWarning(loggerCategory, `Got an error downloading v2 checkpoint, but downloaded v1 checkpoint successfully!`, { error, iModelId: request.checkpoint.iModelId, iTwinId: request.checkpoint.iTwinId, requestedChangesetId: request.checkpoint.changeset.id, changesetId: changeset });
227
- return changeset;
228
- }
229
- throw error; // most likely, was aborted
230
- }
231
- }
232
- static async updateToRequestedVersion(request) {
233
- var _a;
234
- const checkpoint = request.checkpoint;
235
- const targetFile = request.localFile;
236
- const traceInfo = { iTwinId: checkpoint.iTwinId, iModelId: checkpoint.iModelId, changeset: checkpoint.changeset };
237
- try {
238
- // Open checkpoint for write
239
- core_bentley_1.Logger.setLevel(imodeljs_native_1.NativeLoggerCategory.SQLite, core_bentley_1.LogLevel.None); // Ignores noisy error messages when applying changesets.
240
- const db = IModelDb_1.SnapshotDb.openForApplyChangesets(targetFile);
241
- const nativeDb = db.nativeDb;
242
- try {
243
- if (nativeDb.hasPendingTxns()) {
244
- core_bentley_1.Logger.logWarning(loggerCategory, "Checkpoint with Txns found - deleting them", () => traceInfo);
245
- nativeDb.deleteAllTxns();
246
- }
247
- if (nativeDb.getBriefcaseId() !== core_common_1.BriefcaseIdValue.Unassigned)
248
- nativeDb.resetBriefcaseId(core_common_1.BriefcaseIdValue.Unassigned);
249
- CheckpointManager.validateCheckpointGuids(checkpoint, db);
250
- // Apply change sets if necessary
251
- const currentChangeset = nativeDb.getCurrentChangeset();
252
- if (currentChangeset.id !== checkpoint.changeset.id) {
253
- const accessToken = checkpoint.accessToken;
254
- const toIndex = (_a = checkpoint.changeset.index) !== null && _a !== void 0 ? _a : (await IModelHost_1.IModelHost.hubAccess.getChangesetFromVersion({ accessToken, iModelId: checkpoint.iModelId, version: core_common_1.IModelVersion.asOfChangeSet(checkpoint.changeset.id) })).index;
255
- await BriefcaseManager_1.BriefcaseManager.pullAndApplyChangesets(db, { accessToken, toIndex });
256
- }
257
- else {
258
- // make sure the parent changeset index is saved in the file - old versions didn't have it.
259
- currentChangeset.index = checkpoint.changeset.index; // eslint-disable-line @typescript-eslint/no-non-null-assertion
260
- nativeDb.saveLocalValue("parentChangeSet", JSON.stringify(currentChangeset));
261
- }
262
- }
263
- finally {
264
- core_bentley_1.Logger.setLevel(imodeljs_native_1.NativeLoggerCategory.SQLite, core_bentley_1.LogLevel.Error); // Turn logging back on after applying changesets.
265
- db.saveChanges();
266
- db.close();
267
- }
268
- }
269
- catch (error) {
270
- core_bentley_1.Logger.logError(loggerCategory, "Error downloading checkpoint - deleting it", () => traceInfo);
271
- IModelJsFs_1.IModelJsFs.removeSync(targetFile);
272
- if (error.errorNumber === core_bentley_1.ChangeSetStatus.CorruptedChangeStream || error.errorNumber === core_bentley_1.ChangeSetStatus.InvalidId || error.errorNumber === core_bentley_1.ChangeSetStatus.InvalidVersion) {
273
- core_bentley_1.Logger.logError(loggerCategory, "Detected potential corruption of change sets. Deleting them to enable retries", () => traceInfo);
274
- BriefcaseManager_1.BriefcaseManager.deleteChangeSetsFromLocalDisk(checkpoint.iModelId);
275
- }
276
- throw error;
277
- }
278
- }
279
- /** Download a checkpoint file from iModelHub into a local file specified in the request parameters. */
280
- static async downloadCheckpoint(request) {
281
- if (this.verifyCheckpoint(request.checkpoint, request.localFile))
282
- return;
283
- if (request.aliasFiles) {
284
- for (const alias of request.aliasFiles) {
285
- if (this.verifyCheckpoint(request.checkpoint, alias)) {
286
- request.localFile = alias;
287
- return;
288
- }
289
- }
290
- }
291
- await this.doDownload(request);
292
- return this.updateToRequestedVersion(request);
293
- }
294
- /** checks a file's dbGuid & iTwinId for consistency, and updates the dbGuid when possible */
295
- static validateCheckpointGuids(checkpoint, snapshotDb) {
296
- const traceInfo = { iTwinId: checkpoint.iTwinId, iModelId: checkpoint.iModelId };
297
- const nativeDb = snapshotDb.nativeDb;
298
- const dbChangeset = nativeDb.getCurrentChangeset();
299
- const iModelId = core_bentley_1.Guid.normalize(nativeDb.getIModelId());
300
- if (iModelId !== core_bentley_1.Guid.normalize(checkpoint.iModelId)) {
301
- if (nativeDb.isReadonly())
302
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.ValidationFailed, "iModelId is not properly set up in the checkpoint");
303
- core_bentley_1.Logger.logWarning(loggerCategory, "iModelId is not properly set up in the checkpoint. Updated checkpoint to the correct iModelId.", () => ({ ...traceInfo, dbGuid: iModelId }));
304
- const iModelIdNormalized = core_bentley_1.Guid.normalize(checkpoint.iModelId);
305
- nativeDb.setIModelId(iModelIdNormalized);
306
- snapshotDb._iModelId = iModelIdNormalized;
307
- // Required to reset the ChangeSetId because setDbGuid clears the value.
308
- nativeDb.saveLocalValue("ParentChangeSetId", dbChangeset.id);
309
- if (undefined !== dbChangeset.index)
310
- nativeDb.saveLocalValue("parentChangeSet", JSON.stringify(dbChangeset));
311
- }
312
- const iTwinId = core_bentley_1.Guid.normalize(nativeDb.getITwinId());
313
- if (iTwinId !== core_bentley_1.Guid.normalize(checkpoint.iTwinId))
314
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.ValidationFailed, "iTwinId was not properly set up in the checkpoint");
315
- }
316
- /** @returns true if the file is the checkpoint requested */
317
- static verifyCheckpoint(checkpoint, fileName) {
318
- if (!IModelJsFs_1.IModelJsFs.existsSync(fileName))
319
- return false;
320
- const nativeDb = new IModelHost_1.IModelHost.platform.DgnDb();
321
- try {
322
- nativeDb.openIModel(fileName, core_bentley_1.OpenMode.Readonly);
323
- }
324
- catch (error) {
325
- return false;
326
- }
327
- const isValid = checkpoint.iModelId === nativeDb.getIModelId() && checkpoint.changeset.id === nativeDb.getCurrentChangeset().id;
328
- nativeDb.closeIModel();
329
- if (!isValid)
330
- IModelJsFs_1.IModelJsFs.removeSync(fileName);
331
- return isValid;
332
- }
333
- /** try to open an existing local file to satisfy a download request */
334
- static tryOpenLocalFile(request) {
335
- const checkpoint = request.checkpoint;
336
- if (this.verifyCheckpoint(checkpoint, request.localFile))
337
- return IModelDb_1.SnapshotDb.openCheckpointV1(request.localFile, checkpoint);
338
- // check a list of aliases for finding checkpoints downloaded to non-default locations (e.g. from older versions)
339
- if (request.aliasFiles) {
340
- for (const alias of request.aliasFiles) {
341
- if (this.verifyCheckpoint(checkpoint, alias)) {
342
- request.localFile = alias;
343
- return IModelDb_1.SnapshotDb.openCheckpointV1(alias, checkpoint);
344
- }
345
- }
346
- }
347
- return undefined;
348
- }
349
- }
350
- exports.CheckpointManager = CheckpointManager;
351
- CheckpointManager.onDownloadV1 = new core_bentley_1.BeEvent();
352
- CheckpointManager.onDownloadV2 = new core_bentley_1.BeEvent();
1
+ "use strict";
2
+ /*---------------------------------------------------------------------------------------------
3
+ * Copyright (c) Bentley Systems, Incorporated. All rights reserved.
4
+ * See LICENSE.md in the project root for license terms and full copyright notice.
5
+ *--------------------------------------------------------------------------------------------*/
6
+ /** @packageDocumentation
7
+ * @module iModels
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.CheckpointManager = exports.V1CheckpointManager = exports.V2CheckpointManager = exports.Downloads = exports.ProgressStatus = void 0;
11
+ // cspell:ignore BLOCKCACHE
12
+ const path = require("path");
13
+ const core_bentley_1 = require("@itwin/core-bentley");
14
+ const core_common_1 = require("@itwin/core-common");
15
+ const BackendLoggerCategory_1 = require("./BackendLoggerCategory");
16
+ const BriefcaseManager_1 = require("./BriefcaseManager");
17
+ const CloudSqlite_1 = require("./CloudSqlite");
18
+ const IModelDb_1 = require("./IModelDb");
19
+ const IModelHost_1 = require("./IModelHost");
20
+ const IModelJsFs_1 = require("./IModelJsFs");
21
+ const imodeljs_native_1 = require("@bentley/imodeljs-native");
22
+ const loggerCategory = BackendLoggerCategory_1.BackendLoggerCategory.IModelDb;
23
+ /** Return value from [[ProgressFunction]].
24
+ * @public
25
+ */
26
+ var ProgressStatus;
27
+ (function (ProgressStatus) {
28
+ /** Continue download. */
29
+ ProgressStatus[ProgressStatus["Continue"] = 0] = "Continue";
30
+ /** Abort download. */
31
+ ProgressStatus[ProgressStatus["Abort"] = 1] = "Abort";
32
+ })(ProgressStatus = exports.ProgressStatus || (exports.ProgressStatus = {}));
33
+ /** @internal */
34
+ class Downloads {
35
+ static async process(job, fn) {
36
+ const jobName = job.request.localFile; // save this, it can change inside call to `fn`!
37
+ this._active.set(jobName, job);
38
+ try {
39
+ return await fn(job);
40
+ }
41
+ finally {
42
+ this._active.delete(jobName);
43
+ }
44
+ }
45
+ static isInProgress(pathName) {
46
+ return this._active.get(pathName);
47
+ }
48
+ static async download(request, downloadFn) {
49
+ const pathName = request.localFile;
50
+ let job = this.isInProgress(pathName);
51
+ if (undefined !== job)
52
+ return job.promise;
53
+ IModelJsFs_1.IModelJsFs.recursiveMkDirSync(path.dirname(pathName));
54
+ job = { request };
55
+ return job.promise = this.process(job, downloadFn);
56
+ }
57
+ }
58
+ exports.Downloads = Downloads;
59
+ Downloads._active = new Map();
60
+ /**
61
+ * Utility class for opening V2 checkpoints from cloud containers, and also for downloading them.
62
+ * @internal
63
+ */
64
+ class V2CheckpointManager {
65
+ static getFolder() {
66
+ const cloudCachePath = path.join(BriefcaseManager_1.BriefcaseManager.cacheDir, V2CheckpointManager.cloudCacheName);
67
+ if (!(IModelJsFs_1.IModelJsFs.existsSync(cloudCachePath))) {
68
+ IModelJsFs_1.IModelJsFs.recursiveMkDirSync(cloudCachePath);
69
+ }
70
+ return cloudCachePath;
71
+ }
72
+ /* only used by tests that reset the state of the v2checkpointmanager. all dbs should be closed before calling this function. */
73
+ static cleanup() {
74
+ var _a;
75
+ for (const [_, value] of this.containers.entries()) {
76
+ if (value.isConnected)
77
+ value.detach();
78
+ }
79
+ (_a = this._cloudCache) === null || _a === void 0 ? void 0 : _a.destroy();
80
+ this._cloudCache = undefined;
81
+ this.containers.clear();
82
+ }
83
+ static getFileName(checkpoint) {
84
+ const changesetId = checkpoint.changeset.id || "first";
85
+ return path.join(this.getFolder(), `${changesetId}.bim`);
86
+ }
87
+ static get cloudCache() {
88
+ if (!this._cloudCache) {
89
+ let rootDir = process.env.CHECKPOINT_CACHE_DIR;
90
+ if (!rootDir) {
91
+ rootDir = this.getFolder();
92
+ core_bentley_1.Logger.logWarning(loggerCategory, `No CHECKPOINT_CACHE_DIR found in process.env, using ${rootDir} instead.`);
93
+ }
94
+ else {
95
+ // Make sure the checkpoint_cache_dir has an iTwinDaemon specific file in it, otherwise fall back to other directory.
96
+ if (!(IModelJsFs_1.IModelJsFs.existsSync(path.join(rootDir, "portnumber.bcv")))) {
97
+ rootDir = this.getFolder();
98
+ core_bentley_1.Logger.logWarning(loggerCategory, `No evidence of the iTwinDaemon in provided CHECKPOINT_CACHE_DIR: ${process.env.CHECKPOINT_CACHE_DIR}, using ${rootDir} instead.`);
99
+ }
100
+ }
101
+ this._cloudCache = CloudSqlite_1.CloudSqlite.createCloudCache({ name: this.cloudCacheName, rootDir });
102
+ // Its fine if its not a daemon, but lets log an info message
103
+ if (!this._cloudCache.isDaemon)
104
+ core_bentley_1.Logger.logInfo(loggerCategory, "V2Checkpoint manager running with no iTwinDaemon.");
105
+ }
106
+ return this._cloudCache;
107
+ }
108
+ /** Member names differ slightly between the V2Checkpoint api and the CloudSqlite api. Add aliases `accessName` for `accountName` and `accessToken` for `sasToken` */
109
+ static toCloudContainerProps(from) {
110
+ return { ...from, accessName: from.accountName, accessToken: from.sasToken };
111
+ }
112
+ static getContainer(v2Props) {
113
+ let container = this.containers.get(v2Props.containerId);
114
+ if (!container) {
115
+ container = CloudSqlite_1.CloudSqlite.createCloudContainer(this.toCloudContainerProps(v2Props));
116
+ this.containers.set(v2Props.containerId, container);
117
+ }
118
+ return container;
119
+ }
120
+ static async attach(checkpoint) {
121
+ let v2props;
122
+ try {
123
+ v2props = await IModelHost_1.IModelHost.hubAccess.queryV2Checkpoint(checkpoint);
124
+ if (!v2props)
125
+ throw new Error("no checkpoint");
126
+ }
127
+ catch (err) {
128
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.NotFound, `V2 checkpoint not found: err: ${err.message}`);
129
+ }
130
+ try {
131
+ const container = this.getContainer(v2props);
132
+ const dbName = v2props.dbName;
133
+ if (!container.isConnected)
134
+ container.connect(this.cloudCache);
135
+ container.checkForChanges();
136
+ const dbStats = container.queryDatabase(dbName);
137
+ if (IModelHost_1.IModelHost.appWorkspace.settings.getBoolean("Checkpoints/prefetch", false)) {
138
+ const getPrefetchConfig = (name, defaultVal) => IModelHost_1.IModelHost.appWorkspace.settings.getNumber(`Checkpoints/prefetch/${name}`, defaultVal);
139
+ const minRequests = getPrefetchConfig("minRequests", 3);
140
+ const maxRequests = getPrefetchConfig("maxRequests", 6);
141
+ const timeout = getPrefetchConfig("timeout", 100);
142
+ const maxBlocks = getPrefetchConfig("maxBlocks", 500); // default size of 2GB. Assumes a checkpoint block size of 4MB.
143
+ if ((dbStats === null || dbStats === void 0 ? void 0 : dbStats.totalBlocks) !== undefined && dbStats.totalBlocks <= maxBlocks) {
144
+ const logPrefetch = async (prefetch) => {
145
+ const stopwatch = new core_bentley_1.StopWatch(`[${container.containerId}/${dbName}]`, true);
146
+ core_bentley_1.Logger.logInfo(loggerCategory, `Starting prefetch of ${stopwatch.description}`, { minRequests, maxRequests, timeout });
147
+ const done = await prefetch.promise;
148
+ core_bentley_1.Logger.logInfo(loggerCategory, `Prefetch of ${stopwatch.description} complete=${done} (${stopwatch.elapsedSeconds} seconds)`, { minRequests, maxRequests, timeout });
149
+ };
150
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
151
+ logPrefetch(CloudSqlite_1.CloudSqlite.startCloudPrefetch(container, dbName, { minRequests, nRequests: maxRequests, timeout }));
152
+ }
153
+ else {
154
+ core_bentley_1.Logger.logInfo(loggerCategory, `Skipping prefetch due to size limits.`, { maxBlocks, totalBlocksInDb: dbStats === null || dbStats === void 0 ? void 0 : dbStats.totalBlocks, v2props });
155
+ }
156
+ }
157
+ return { dbName, container };
158
+ }
159
+ catch (e) {
160
+ const error = `Cloud cache connect failed: ${e.message}`;
161
+ if (checkpoint.expectV2)
162
+ core_bentley_1.Logger.logError(loggerCategory, error);
163
+ throw new core_common_1.IModelError(e.errorNumber, error);
164
+ }
165
+ }
166
+ static async performDownload(job) {
167
+ const request = job.request;
168
+ const v2props = await IModelHost_1.IModelHost.hubAccess.queryV2Checkpoint({ ...request.checkpoint, allowPreceding: true });
169
+ if (!v2props)
170
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.NotFound, "V2 checkpoint not found");
171
+ CheckpointManager.onDownloadV2.raiseEvent(job);
172
+ const container = CloudSqlite_1.CloudSqlite.createCloudContainer(this.toCloudContainerProps(v2props));
173
+ await CloudSqlite_1.CloudSqlite.transferDb("download", container, { dbName: v2props.dbName, localFileName: request.localFile, onProgress: request.onProgress });
174
+ return request.checkpoint.changeset.id;
175
+ }
176
+ /** Fully download a V2 checkpoint to a local file that can be used to create a briefcase or to work offline.
177
+ * @returns a Promise that is resolved when the download completes with the changesetId of the downloaded checkpoint (which will
178
+ * be the same as the requested changesetId or the most recent checkpoint before it.)
179
+ */
180
+ static async downloadCheckpoint(request) {
181
+ return Downloads.download(request, async (job) => this.performDownload(job));
182
+ }
183
+ }
184
+ exports.V2CheckpointManager = V2CheckpointManager;
185
+ V2CheckpointManager.cloudCacheName = "v2Checkpoints";
186
+ V2CheckpointManager.containers = new Map();
187
+ /** Utility class to deal with downloading V1 checkpoints from iModelHub.
188
+ * @internal
189
+ */
190
+ class V1CheckpointManager {
191
+ static getFolder(iModelId) {
192
+ return path.join(BriefcaseManager_1.BriefcaseManager.getIModelPath(iModelId), "checkpoints");
193
+ }
194
+ static getFileName(checkpoint) {
195
+ const changesetId = checkpoint.changeset.id || "first";
196
+ return path.join(this.getFolder(checkpoint.iModelId), `${changesetId}.bim`);
197
+ }
198
+ static async getCheckpointDb(request) {
199
+ const db = IModelDb_1.SnapshotDb.tryFindByKey(CheckpointManager.getKey(request.checkpoint));
200
+ return (undefined !== db) ? db : Downloads.download(request, async (job) => this.downloadAndOpen(job));
201
+ }
202
+ /** Download a V1 checkpoint */
203
+ static async downloadCheckpoint(request) {
204
+ return Downloads.download(request, async (job) => this.performDownload(job));
205
+ }
206
+ static async downloadAndOpen(job) {
207
+ const db = CheckpointManager.tryOpenLocalFile(job.request);
208
+ if (db)
209
+ return db;
210
+ await this.performDownload(job);
211
+ await CheckpointManager.updateToRequestedVersion(job.request);
212
+ return IModelDb_1.SnapshotDb.openCheckpointV1(job.request.localFile, job.request.checkpoint);
213
+ }
214
+ static async performDownload(job) {
215
+ CheckpointManager.onDownloadV1.raiseEvent(job);
216
+ // eslint-disable-next-line deprecation/deprecation
217
+ return (await IModelHost_1.IModelHost.hubAccess.downloadV1Checkpoint(job.request)).id;
218
+ }
219
+ }
220
+ exports.V1CheckpointManager = V1CheckpointManager;
221
+ /** @internal */
222
+ class CheckpointManager {
223
+ static getKey(checkpoint) { return `${checkpoint.iModelId}:${checkpoint.changeset.id}`; }
224
+ static async doDownload(request) {
225
+ try {
226
+ // first see if there's a V2 checkpoint available.
227
+ const changesetId = await V2CheckpointManager.downloadCheckpoint(request);
228
+ if (changesetId !== request.checkpoint.changeset.id)
229
+ core_bentley_1.Logger.logInfo(loggerCategory, `Downloaded previous v2 checkpoint because requested checkpoint not found.`, { requestedChangesetId: request.checkpoint.changeset.id, iModelId: request.checkpoint.iModelId, changesetId, iTwinId: request.checkpoint.iTwinId });
230
+ else
231
+ core_bentley_1.Logger.logInfo(loggerCategory, `Downloaded v2 checkpoint.`, { iModelId: request.checkpoint.iModelId, changesetId: request.checkpoint.changeset.id, iTwinId: request.checkpoint.iTwinId });
232
+ return changesetId;
233
+ }
234
+ catch (error) {
235
+ if (error.errorNumber === core_bentley_1.IModelStatus.NotFound) { // No V2 checkpoint available, try a v1 checkpoint
236
+ const changeset = await V1CheckpointManager.downloadCheckpoint(request);
237
+ core_bentley_1.Logger.logWarning(loggerCategory, `Got an error downloading v2 checkpoint, but downloaded v1 checkpoint successfully!`, { error, iModelId: request.checkpoint.iModelId, iTwinId: request.checkpoint.iTwinId, requestedChangesetId: request.checkpoint.changeset.id, changesetId: changeset });
238
+ return changeset;
239
+ }
240
+ throw error; // most likely, was aborted
241
+ }
242
+ }
243
+ static async updateToRequestedVersion(request) {
244
+ var _a;
245
+ const checkpoint = request.checkpoint;
246
+ const targetFile = request.localFile;
247
+ const traceInfo = { iTwinId: checkpoint.iTwinId, iModelId: checkpoint.iModelId, changeset: checkpoint.changeset };
248
+ try {
249
+ // Open checkpoint for write
250
+ core_bentley_1.Logger.setLevel(imodeljs_native_1.NativeLoggerCategory.SQLite, core_bentley_1.LogLevel.None); // Ignores noisy error messages when applying changesets.
251
+ const db = IModelDb_1.SnapshotDb.openForApplyChangesets(targetFile);
252
+ const nativeDb = db.nativeDb;
253
+ try {
254
+ if (nativeDb.hasPendingTxns()) {
255
+ core_bentley_1.Logger.logWarning(loggerCategory, "Checkpoint with Txns found - deleting them", () => traceInfo);
256
+ nativeDb.deleteAllTxns();
257
+ }
258
+ if (nativeDb.getBriefcaseId() !== core_common_1.BriefcaseIdValue.Unassigned)
259
+ nativeDb.resetBriefcaseId(core_common_1.BriefcaseIdValue.Unassigned);
260
+ CheckpointManager.validateCheckpointGuids(checkpoint, db);
261
+ // Apply change sets if necessary
262
+ const currentChangeset = nativeDb.getCurrentChangeset();
263
+ if (currentChangeset.id !== checkpoint.changeset.id) {
264
+ const accessToken = checkpoint.accessToken;
265
+ const toIndex = (_a = checkpoint.changeset.index) !== null && _a !== void 0 ? _a : (await IModelHost_1.IModelHost.hubAccess.getChangesetFromVersion({ accessToken, iModelId: checkpoint.iModelId, version: core_common_1.IModelVersion.asOfChangeSet(checkpoint.changeset.id) })).index;
266
+ await BriefcaseManager_1.BriefcaseManager.pullAndApplyChangesets(db, { accessToken, toIndex });
267
+ }
268
+ else {
269
+ // make sure the parent changeset index is saved in the file - old versions didn't have it.
270
+ currentChangeset.index = checkpoint.changeset.index; // eslint-disable-line @typescript-eslint/no-non-null-assertion
271
+ nativeDb.saveLocalValue("parentChangeSet", JSON.stringify(currentChangeset));
272
+ }
273
+ }
274
+ finally {
275
+ core_bentley_1.Logger.setLevel(imodeljs_native_1.NativeLoggerCategory.SQLite, core_bentley_1.LogLevel.Error); // Turn logging back on after applying changesets.
276
+ db.saveChanges();
277
+ db.close();
278
+ }
279
+ }
280
+ catch (error) {
281
+ core_bentley_1.Logger.logError(loggerCategory, "Error downloading checkpoint - deleting it", () => traceInfo);
282
+ IModelJsFs_1.IModelJsFs.removeSync(targetFile);
283
+ if (error.errorNumber === core_bentley_1.ChangeSetStatus.CorruptedChangeStream || error.errorNumber === core_bentley_1.ChangeSetStatus.InvalidId || error.errorNumber === core_bentley_1.ChangeSetStatus.InvalidVersion) {
284
+ core_bentley_1.Logger.logError(loggerCategory, "Detected potential corruption of change sets. Deleting them to enable retries", () => traceInfo);
285
+ BriefcaseManager_1.BriefcaseManager.deleteChangeSetsFromLocalDisk(checkpoint.iModelId);
286
+ }
287
+ throw error;
288
+ }
289
+ }
290
+ /** Download a checkpoint file from iModelHub into a local file specified in the request parameters. */
291
+ static async downloadCheckpoint(request) {
292
+ if (this.verifyCheckpoint(request.checkpoint, request.localFile))
293
+ return;
294
+ if (request.aliasFiles) {
295
+ for (const alias of request.aliasFiles) {
296
+ if (this.verifyCheckpoint(request.checkpoint, alias)) {
297
+ request.localFile = alias;
298
+ return;
299
+ }
300
+ }
301
+ }
302
+ await this.doDownload(request);
303
+ return this.updateToRequestedVersion(request);
304
+ }
305
+ /** checks a file's dbGuid & iTwinId for consistency, and updates the dbGuid when possible */
306
+ static validateCheckpointGuids(checkpoint, snapshotDb) {
307
+ const traceInfo = { iTwinId: checkpoint.iTwinId, iModelId: checkpoint.iModelId };
308
+ const nativeDb = snapshotDb.nativeDb;
309
+ const dbChangeset = nativeDb.getCurrentChangeset();
310
+ const iModelId = core_bentley_1.Guid.normalize(nativeDb.getIModelId());
311
+ if (iModelId !== core_bentley_1.Guid.normalize(checkpoint.iModelId)) {
312
+ if (nativeDb.isReadonly())
313
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.ValidationFailed, "iModelId is not properly set up in the checkpoint");
314
+ core_bentley_1.Logger.logWarning(loggerCategory, "iModelId is not properly set up in the checkpoint. Updated checkpoint to the correct iModelId.", () => ({ ...traceInfo, dbGuid: iModelId }));
315
+ const iModelIdNormalized = core_bentley_1.Guid.normalize(checkpoint.iModelId);
316
+ nativeDb.setIModelId(iModelIdNormalized);
317
+ snapshotDb._iModelId = iModelIdNormalized;
318
+ // Required to reset the ChangeSetId because setDbGuid clears the value.
319
+ nativeDb.saveLocalValue("ParentChangeSetId", dbChangeset.id);
320
+ if (undefined !== dbChangeset.index)
321
+ nativeDb.saveLocalValue("parentChangeSet", JSON.stringify(dbChangeset));
322
+ }
323
+ const iTwinId = core_bentley_1.Guid.normalize(nativeDb.getITwinId());
324
+ if (iTwinId !== core_bentley_1.Guid.normalize(checkpoint.iTwinId))
325
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.ValidationFailed, "iTwinId was not properly set up in the checkpoint");
326
+ }
327
+ /** @returns true if the file is the checkpoint requested */
328
+ static verifyCheckpoint(checkpoint, fileName) {
329
+ if (!IModelJsFs_1.IModelJsFs.existsSync(fileName))
330
+ return false;
331
+ const nativeDb = new IModelHost_1.IModelHost.platform.DgnDb();
332
+ try {
333
+ nativeDb.openIModel(fileName, core_bentley_1.OpenMode.Readonly);
334
+ }
335
+ catch (error) {
336
+ return false;
337
+ }
338
+ const isValid = checkpoint.iModelId === nativeDb.getIModelId() && checkpoint.changeset.id === nativeDb.getCurrentChangeset().id;
339
+ nativeDb.closeIModel();
340
+ if (!isValid)
341
+ IModelJsFs_1.IModelJsFs.removeSync(fileName);
342
+ return isValid;
343
+ }
344
+ /** try to open an existing local file to satisfy a download request */
345
+ static tryOpenLocalFile(request) {
346
+ const checkpoint = request.checkpoint;
347
+ if (this.verifyCheckpoint(checkpoint, request.localFile))
348
+ return IModelDb_1.SnapshotDb.openCheckpointV1(request.localFile, checkpoint);
349
+ // check a list of aliases for finding checkpoints downloaded to non-default locations (e.g. from older versions)
350
+ if (request.aliasFiles) {
351
+ for (const alias of request.aliasFiles) {
352
+ if (this.verifyCheckpoint(checkpoint, alias)) {
353
+ request.localFile = alias;
354
+ return IModelDb_1.SnapshotDb.openCheckpointV1(alias, checkpoint);
355
+ }
356
+ }
357
+ }
358
+ return undefined;
359
+ }
360
+ }
361
+ exports.CheckpointManager = CheckpointManager;
362
+ CheckpointManager.onDownloadV1 = new core_bentley_1.BeEvent();
363
+ CheckpointManager.onDownloadV2 = new core_bentley_1.BeEvent();
353
364
  //# sourceMappingURL=CheckpointManager.js.map