@itwin/core-backend
Version:
iTwin.js backend components
399 lines • 19.7 kB
TypeScript
/** @packageDocumentation
* @module IModelHost
*/
import "./IModelDb";
import "reflect-metadata";
import { AccessToken, BeEvent, GuidString, Mutable } from "@itwin/core-bentley";
import { AuthorizationClient, LocalDirName, SessionProps } from "@itwin/core-common";
import { ServerStorage } from "@itwin/object-storage-core";
import { BackendHubAccess, CreateNewIModelProps } from "./BackendHubAccess";
import { TileStorage } from "./TileStorage";
import { SettingsSchemas } from "./workspace/SettingsSchemas";
import { Workspace, WorkspaceOpts } from "./workspace/Workspace";
import { _getHubAccess, _hubAccess, _setHubAccess } from "./internal/Symbols";
/** @internal */
export interface CrashReportingConfigNameValuePair {
name: string;
value: string;
}
/** Configuration of the crash-reporting system.
* @internal
*/
export interface CrashReportingConfig {
/** The directory to which *.dmp and/or iModelJsNativeCrash*.properties.txt files are written. This directory will be created if it does not already exist. */
crashDir: string;
/** max # .dmp files that may exist in crashDir. The default is 50. */
maxDumpsInDir?: number;
/** Enable crash-dumps? If so, .dmp and .properties.txt files will be generated and written to crashDir in the event of an unhandled native-code exception. If not, only .properties.txt files will be written. The default is false. */
enableCrashDumps?: boolean;
/** If enableCrashDumps is true, do you want a full-memory dump? Defaults to false. */
wantFullMemoryDumps?: boolean;
/** Enable Node.js crash reporting? If so, report files will be generated in the event of an unhandled exception or fatal error and written to crashDir. The default is false. */
enableNodeReport?: boolean;
/** Additional name, value pairs to write to iModelJsNativeCrash*.properties.txt file in the event of a crash. */
params?: CrashReportingConfigNameValuePair[];
/** Run this .js file to process .dmp and Node.js crash reporting .json files in the event of a crash.
* This script will be executed with a single command-line parameter: the name of the dump or Node.js report file.
* In the case of a dump file, there will be a second file with the same basename and the extension ".properties.txt".
* Since it runs in a separate process, this script will have no access to the Javascript
* context of the exiting backend. No default.
*/
dumpProcessorScriptFileName?: string;
/** Upload crash dump and node-reports to Bentley's crash-reporting service? Defaults to false */
uploadToBentley?: boolean;
}
/** @beta */
export interface AzureBlobStorageCredentials {
account: string;
accessKey: string;
baseUrl?: string;
}
/**
* Options for [[IModelHost.startup]]
* @public
*/
export interface IModelHostOptions {
/**
* The name of the *Profile* subdirectory of [[cacheDir]] for this process. If not present, "default" is used.
* @see [[IModelHost.profileName]]
* @beta
*/
profileName?: string;
/**
* Root of the directory holding all the files that iTwin.js caches
* - If not specified at startup a platform specific default is used -
* - Windows: $(HOMEDIR)/AppData/Local/iModelJs/
* - Mac/iOS: $(HOMEDIR)/Library/Caches/iModelJs/
* - Linux: $(HOMEDIR)/.cache/iModelJs/
* where $(HOMEDIR) is documented [here](https://nodejs.org/api/os.html#os_os_homedir)
* - if specified, ensure it is set to a folder with read/write access.
* @see [[IModelHost.cacheDir]] for the value it's set to after startup
*/
cacheDir?: LocalDirName;
/** The directory where application assets are found. */
appAssetsDir?: LocalDirName;
/**
* Options for creating the [[IModelHost.appWorkspace]]
* @beta
*/
workspace?: WorkspaceOpts;
/**
* The kind of iModel hub server to use.
*/
hubAccess?: BackendHubAccess;
/** The Azure blob storage credentials to use for the tile cache service. If omitted and no external service implementation is provided, a local cache will be used.
* @beta
*/
tileCacheAzureCredentials?: AzureBlobStorageCredentials;
/**
* @beta
* @note A reference implementation is set for AzureServerStorage from @itwin/object-storage-azure if [[tileCacheAzureCredentials]] property is set. To supply a different implementation for any service provider (such as AWS),
* set this property with a custom ServerStorage.
*/
tileCacheStorage?: ServerStorage;
/** The maximum size in bytes to which a local sqlite database used for caching tiles can grow before it is purged of least-recently-used tiles.
* The local cache is used only if an external cache has not been configured via [[tileCacheStorage]], and [[tileCacheAzureCredentials]].
* Defaults to 1 GB. Must be an unsigned integer. A value of zero disables the local cache entirely.
* @beta
*/
maxTileCacheDbSize?: number;
/** Whether to restrict tile cache URLs by client IP address (if available).
* @beta
*/
restrictTileUrlsByClientIp?: boolean;
/** Whether to enable OpenTelemetry tracing.
* Defaults to `false`.
*/
enableOpenTelemetry?: boolean;
/** Whether to compress cached tiles.
* Defaults to `true`.
*/
compressCachedTiles?: boolean;
/** The time, in milliseconds, for which [IModelTileRpcInterface.requestTileTreeProps]($common) should wait before returning a "pending" status.
* @internal
*/
tileTreeRequestTimeout?: number;
/** The time, in milliseconds, for which [IModelTileRpcInterface.requestTileContent]($common) should wait before returning a "pending" status.
* @internal
*/
tileContentRequestTimeout?: number;
/** The backend will log when a tile took longer to load than this threshold in seconds.
* @internal
*/
logTileLoadTimeThreshold?: number;
/** The backend will log when a tile is loaded with a size in bytes above this threshold.
* @internal
*/
logTileSizeThreshold?: number;
/** Crash-reporting configuration
* @internal
*/
crashReportingConfig?: CrashReportingConfig;
/** The AuthorizationClient used to obtain [AccessToken]($bentley)s. */
authorizationClient?: AuthorizationClient;
/**
* Automatically enable shared channel when opening iModels for read/write (see [Working With Channels]($docs/learning/backend/Channel.md)).
* If not present, defaults to `true` for backwards compatibility. This means that the shared channel may be edited by default. Generally
* that is undesirable because it allows applications to "accidentally" modify data it shouldn't be allowed to modify. Unfortunately the
* previous versions of iTwin.js allowed it so this is necessary so they won't break.
* Will be changed to default to `false` in 5.0.
*/
allowSharedChannel?: boolean;
/**
* Setting this to true withh revert to the previous behavior of using the native side for all CRUD operations.
* While set to false, the getElement(), getModel() and getAspect() functions will use a thinned down native workflow to read the entities from the database.
* This workflow performs work previously done on the native side in the TS side, resulting in performance improvements, if errors are detected,
* this option can be set to true to revert to old workflow.
*/
disableThinnedNativeInstanceWorkflow?: boolean;
}
/** Configuration of core-backend.
* @public
*/
export declare class IModelHostConfiguration implements IModelHostOptions {
static defaultTileRequestTimeout: number;
static defaultLogTileLoadTimeThreshold: number;
static defaultLogTileSizeThreshold: number;
/** @internal */
static defaultMaxTileCacheDbSize: number;
appAssetsDir?: LocalDirName;
cacheDir?: LocalDirName;
/** @beta */
workspace?: WorkspaceOpts;
hubAccess?: BackendHubAccess;
/** The AuthorizationClient used to obtain [AccessToken]($bentley)s. */
authorizationClient?: AuthorizationClient;
/** @beta */
restrictTileUrlsByClientIp?: boolean;
compressCachedTiles?: boolean;
/** @beta */
tileCacheAzureCredentials?: AzureBlobStorageCredentials;
/** @internal */
tileTreeRequestTimeout: number;
/** @internal */
tileContentRequestTimeout: number;
/** @internal */
logTileLoadTimeThreshold: number;
/** @internal */
logTileSizeThreshold: number;
/** @internal */
crashReportingConfig?: CrashReportingConfig;
/**
* Configuration controlling whether to use the thinned down native instance functions for element, model, and aspect CRUD operations
* or use the previous behavior of using the native side for all CRUD operations. Set to true to revert to the previous behavior.
* @beta
*/
disableThinnedNativeInstanceWorkflow?: boolean;
}
/** IModelHost initializes ($backend) and captures its configuration. A backend must call [[IModelHost.startup]] before using any backend classes.
* See [the learning article]($docs/learning/backend/IModelHost.md)
* @public
*/
export declare class IModelHost {
private constructor();
/** The AuthorizationClient used to obtain [AccessToken]($bentley)s. */
static authorizationClient?: AuthorizationClient;
static backendVersion: string;
private static _profileName;
private static _cacheDir;
private static _settingsSchemas?;
private static _appWorkspace?;
static configuration?: Omit<IModelHostOptions, "hubAccess">;
/**
* The name of the *Profile* directory (a subdirectory of "[[cacheDir]]/profiles/") for this process.
*
* The *Profile* directory is used to cache data that is specific to a type-of-usage of the iTwin.js library.
* It is important that information in the profile cache be consistent but isolated across sessions (i.e.
* data for a profile is maintained between runs, but each profile is completely independent and
* unaffected by the presence or use of others.)
* @note **Only one process at a time may be using a given profile**, and an exception will be thrown by [[startup]]
* if a second process attempts to use the same profile.
* @beta
*/
static get profileName(): string;
/** The full path of the Profile directory.
* @see [[profileName]]
* @beta
*/
static get profileDir(): LocalDirName;
/** Event raised during startup to allow loading settings data */
static readonly onWorkspaceStartup: BeEvent<() => void>;
/** Event raised just after the backend IModelHost was started */
static readonly onAfterStartup: BeEvent<() => void>;
/** Event raised just before the backend IModelHost is to be shut down */
static readonly onBeforeShutdown: BeEvent<() => void>;
/** @internal */
static readonly session: Mutable<SessionProps>;
/** A uniqueId for this session */
static get sessionId(): GuidString;
static set sessionId(id: GuidString);
/** The Id of this application - needs to be set only if it is an agent application. The applicationId will otherwise originate at the frontend. */
static get applicationId(): string;
static set applicationId(id: string);
/** The version of this application - needs to be set if is an agent application. The applicationVersion will otherwise originate at the frontend. */
static get applicationVersion(): string;
static set applicationVersion(version: string);
/** A string that can identify the current user to other users when collaborating. */
static userMoniker: string;
/** Root directory holding files that iTwin.js caches */
static get cacheDir(): LocalDirName;
/** The application [[Workspace]] for this `IModelHost`
* @note this `Workspace` only holds [[WorkspaceContainer]]s and [[Settings]] scoped to the currently loaded application(s).
* All organization, iTwin, and iModel based containers or settings must be accessed through [[IModelDb.workspace]] and
* attempting to add them to this Workspace will fail.
* @beta
*/
static get appWorkspace(): Workspace;
/** The registry of schemas describing the [[Setting]]s for the application session.
* Applications should register their schemas via methods like [[SettingsSchemas.addGroup]].
* @beta
*/
static get settingsSchemas(): SettingsSchemas;
/** The optional [[FileNameResolver]] that resolves keys and partial file names for snapshot iModels.
* @deprecated in 4.10 - will not be removed until after 2026-06-13. When opening a snapshot by file name, ensure to pass already resolved path. Using a key to open a snapshot is now deprecated.
*/
static snapshotFileNameResolver?: FileNameResolver;
/** Get the current access token for this IModelHost, or a blank string if none is available.
* @note for web backends, this will *always* return a blank string because the backend itself has no token (but never needs one either.)
* For all IpcHosts, where this backend is servicing a single frontend, this will be the user's token. For ElectronHost, the backend
* obtains the token and forwards it to the frontend.
* @note accessTokens expire periodically and are automatically refreshed, if possible. Therefore tokens should not be saved, and the value
* returned by this method may change over time throughout the course of a session.
*/
static getAccessToken(): Promise<AccessToken>;
private static loadNative;
/** @internal */
static tileStorage?: TileStorage;
private static _hubAccess?;
/** @internal */
static [_setHubAccess](hubAccess: BackendHubAccess | undefined): void;
/** get the current hubAccess, if present.
* @internal
*/
static [_getHubAccess](): BackendHubAccess | undefined;
/** Provides access to the IModelHub for this IModelHost
* @internal
* @note If [[IModelHostOptions.hubAccess]] was undefined when initializing this class, accessing this property will throw an error.
* To determine whether one is present, use [[_getHubAccess]].
*/
static get [_hubAccess](): BackendHubAccess;
private static initializeWorkspace;
private static _isValid;
/** true between a successful call to [[startup]] and before [[shutdown]] */
static get isValid(): boolean;
/** This method must be called before any iTwin.js services are used.
* @param options Host configuration data.
* Raises [[onAfterStartup]].
* @see [[shutdown]].
*/
static startup(options?: IModelHostOptions): Promise<void>;
private static setupCacheDir;
/** This method must be called when an iTwin.js host is shut down. Raises [[onBeforeShutdown]] */
static shutdown(this: void): Promise<void>;
/**
* Create a new iModel.
* @returns the Guid of the newly created iModel.
* @throws [IModelError]($common) in case of errors.
* @note If [[IModelHostOptions.hubAccess]] was undefined in the call to [[startup]], this function will throw an error.
*/
static createNewIModel(arg: CreateNewIModelProps): Promise<GuidString>;
private static doShutdown;
/**
* Add or update a property that should be included in a crash report.
* @internal
*/
static setCrashReportProperty(name: string, value: string): void;
/**
* Remove a previously defined property so that will not be included in a crash report.
* @internal
*/
static removeCrashReportProperty(name: string): void;
/**
* Get all properties that will be included in a crash report.
* @internal
*/
static getCrashReportProperties(): CrashReportingConfigNameValuePair[];
/** The directory where application assets may be found */
static get appAssetsDir(): string | undefined;
/** The time, in milliseconds, for which IModelTileRpcInterface.requestTileTreeProps should wait before returning a "pending" status.
* @internal
*/
static get tileTreeRequestTimeout(): number;
/** The time, in milliseconds, for which IModelTileRpcInterface.requestTileContent should wait before returning a "pending" status.
* @internal
*/
static get tileContentRequestTimeout(): number;
/** The backend will log when a tile took longer to load than this threshold in seconds. */
static get logTileLoadTimeThreshold(): number;
/** The backend will log when a tile is loaded with a size in bytes above this threshold. */
static get logTileSizeThreshold(): number;
/** Whether external tile caching is active.
* @internal
*/
static get usingExternalTileCache(): boolean;
/** Whether to restrict tile cache URLs by client IP address.
* @internal
*/
static get restrictTileUrlsByClientIp(): boolean;
/** Whether to compress cached tiles.
* @internal
*/
static get compressCachedTiles(): boolean;
private static setupTileCache;
private static setupAzureTileCache;
/** @internal */
static computeSchemaChecksum(arg: {
schemaXmlPath: string;
referencePaths: string[];
exactMatch?: boolean;
}): string;
}
/** Information about the platform on which the app is running.
* @public
*/
export declare class Platform {
/** Get the name of the platform. */
static get platformName(): "win32" | "linux" | "darwin" | "ios" | "android" | "uwp";
}
/** Well known directories that may be used by the application.
* @public
*/
export declare class KnownLocations {
/** The directory where the imodeljs-native assets are stored. */
static get nativeAssetsDir(): LocalDirName;
/** The directory where the core-backend assets are stored. */
static get packageAssetsDir(): LocalDirName;
/** The temporary directory. */
static get tmpdir(): LocalDirName;
}
/** Extend this class to provide custom file name resolution behavior.
* @note Only `tryResolveKey` and/or `tryResolveFileName` need to be overridden as the implementations of `resolveKey` and `resolveFileName` work for most purposes.
* @see [[IModelHost.snapshotFileNameResolver]]
* @public
* @deprecated in 4.10 - will not be removed until after 2026-06-13. When opening a snapshot by file name, ensure to pass already resolved path. Using a key to open a snapshot is now deprecated.
*/
export declare abstract class FileNameResolver {
/** Resolve a file name from the specified key.
* @param _fileKey The key that identifies the file name in a `Map` or other similar data structure.
* @returns The resolved file name or `undefined` if not found.
*/
tryResolveKey(_fileKey: string): string | undefined;
/** Resolve a file name from the specified key.
* @param fileKey The key that identifies the file name in a `Map` or other similar data structure.
* @returns The resolved file name.
* @throws [[IModelError]] if not found.
*/
resolveKey(fileKey: string): string;
/** Resolve the input file name, which may be a partial name, into a full path file name.
* @param inFileName The partial file name.
* @returns The resolved full path file name or `undefined` if not found.
*/
tryResolveFileName(inFileName: string): string | undefined;
/** Resolve the input file name, which may be a partial name, into a full path file name.
* @param inFileName The partial file name.
* @returns The resolved full path file name.
* @throws [[IModelError]] if not found.
*/
resolveFileName(inFileName: string): string;
}
//# sourceMappingURL=IModelHost.d.ts.map