@milaboratories/pl-client 3.17.7 → 3.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/client.cjs +5 -3
- package/dist/core/client.cjs.map +1 -1
- package/dist/core/client.d.ts +5 -2
- package/dist/core/client.d.ts.map +1 -1
- package/dist/core/client.js +6 -4
- package/dist/core/client.js.map +1 -1
- package/dist/core/final.cjs +203 -70
- package/dist/core/final.cjs.map +1 -1
- package/dist/core/final.d.ts +15 -13
- package/dist/core/final.d.ts.map +1 -1
- package/dist/core/final.js +199 -69
- package/dist/core/final.js.map +1 -1
- package/dist/core/finality.cjs +84 -0
- package/dist/core/finality.cjs.map +1 -0
- package/dist/core/finality.d.ts +81 -0
- package/dist/core/finality.d.ts.map +1 -0
- package/dist/core/finality.js +82 -0
- package/dist/core/finality.js.map +1 -0
- package/dist/core/transaction.cjs +4 -4
- package/dist/core/transaction.cjs.map +1 -1
- package/dist/core/transaction.d.ts +7 -3
- package/dist/core/transaction.d.ts.map +1 -1
- package/dist/core/transaction.js +4 -4
- package/dist/core/transaction.js.map +1 -1
- package/dist/index.cjs +7 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.js +3 -2
- package/package.json +4 -4
- package/src/core/client.test.ts +38 -0
- package/src/core/client.ts +6 -4
- package/src/core/final.test.ts +103 -1
- package/src/core/final.ts +264 -123
- package/src/core/finality.test.ts +298 -0
- package/src/core/finality.ts +162 -0
- package/src/core/transaction.ts +3 -2
- package/src/index.ts +1 -0
package/dist/core/client.cjs
CHANGED
|
@@ -44,7 +44,9 @@ var PlClient = class PlClient {
|
|
|
44
44
|
_txCommittedStat = require_stat.initialTxStat();
|
|
45
45
|
_txConflictStat = require_stat.initialTxStat();
|
|
46
46
|
_txErrorStat = require_stat.initialTxStat();
|
|
47
|
-
/**
|
|
47
|
+
/** The default finality predicate of trees built on this client ({@link TreeFinality} unless
|
|
48
|
+
* given); a tree may override it, or keep its explicit roots non-final with
|
|
49
|
+
* `rootsNeverFinal`. The transaction resource cache always uses {@link CacheFinality}. */
|
|
48
50
|
finalPredicate;
|
|
49
51
|
/** Resource data cache, to minimize redundant data rereading from remote db */
|
|
50
52
|
resourceDataCache;
|
|
@@ -62,7 +64,7 @@ var PlClient = class PlClient {
|
|
|
62
64
|
};
|
|
63
65
|
this.txDelay = conf.txDelay;
|
|
64
66
|
this.forceSync = conf.forceSync;
|
|
65
|
-
this.finalPredicate = ops.finalPredicate ?? require_final.
|
|
67
|
+
this.finalPredicate = ops.finalPredicate ?? require_final.TreeFinality.predicate();
|
|
66
68
|
this.resourceDataCache = new lru_cache.LRUCache({
|
|
67
69
|
maxSize: conf.maxCacheBytes,
|
|
68
70
|
sizeCalculation: (v) => (v.basicData.data?.length ?? 0) + 64
|
|
@@ -242,7 +244,7 @@ var PlClient = class PlClient {
|
|
|
242
244
|
while (true) {
|
|
243
245
|
const release = ops?.lockId ? await require_advisory_locks.advisoryLock(ops.lockId) : () => {};
|
|
244
246
|
try {
|
|
245
|
-
const tx = new require_transaction.PlTransaction(this.ll.createTx(writable, ops), name, writable, clientRoot,
|
|
247
|
+
const tx = new require_transaction.PlTransaction(this.ll.createTx(writable, ops), name, writable, clientRoot, require_final.CacheFinality.predicate(), this.resourceDataCache);
|
|
246
248
|
if (this.ll.supportsResourceSignatures && !require_types.isNullSignedResourceId(clientRoot) && writable) {
|
|
247
249
|
const parsed = require_types.parseSignedResourceId(clientRoot);
|
|
248
250
|
if (parsed.signature) tx.setDefaultColor(parsed.signature);
|
package/dist/core/client.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.cjs","names":["initialTxStat","plAddressToConfig","LLPlClient","DefaultFinalResourceDataPredicate","LRUCache","addStat","isNullSignedResourceId","ensureSignedResourceIdNotNull","UserResources","ClientRoot","advisoryLock","PlTransaction","parseSignedResourceId","TxCommitConflict","tp"],"sources":["../../src/core/client.ts"],"sourcesContent":["import type { AuthOps, PlClientConfig, PlConnectionStatusListener, wireProtocol } from \"./config\";\nimport type { PlCallOps } from \"./ll_client\";\nimport { LLPlClient } from \"./ll_client\";\nimport { PlTransaction, TxCommitConflict } from \"./transaction\";\nimport type { Role } from \"./transaction\";\nimport type { OptionalSignedResourceId, SignedResourceId } from \"./types\";\nimport {\n ensureSignedResourceIdNotNull,\n isNullSignedResourceId,\n NullSignedResourceId,\n parseSignedResourceId,\n} from \"./types\";\nimport type { ColorProof } from \"./types\";\nimport { ClientRoot } from \"../helpers/pl\";\nimport type { MiLogger, RetryOptions } from \"@milaboratories/ts-helpers\";\nimport { assertNever, createRetryState, nextRetryStateOrError } from \"@milaboratories/ts-helpers\";\nimport type { PlDriver, PlDriverDefinition } from \"./driver\";\nimport type {\n MaintenanceAPI_Ping_Response,\n MaintenanceAPI_License_Response,\n AuthAPI_User,\n} from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api\";\nimport { MaintenanceAPI_Ping_Response_Compression } from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api\";\nimport * as tp from \"node:timers/promises\";\nimport type { Dispatcher } from \"undici\";\nimport { LRUCache } from \"lru-cache\";\nimport type { ResourceDataCacheRecord } from \"./cache\";\nimport type { FinalResourceDataPredicate } from \"./final\";\nimport { DefaultFinalResourceDataPredicate } from \"./final\";\nimport type { AllTxStat, TxStat } from \"./stat\";\nimport { addStat, initialTxStat } from \"./stat\";\nimport type { WireConnection } from \"./wire\";\nimport { advisoryLock } from \"./advisory_locks\";\nimport { plAddressToConfig } from \"./config\";\nimport { UserResources } from \"./user_resources\";\nimport type { UserDeletionReport } from \"./user_resources\";\nimport type { BackendCapability } from \"./capabilities\";\n\nexport type TxOps = PlCallOps & {\n sync?: boolean;\n retryOptions?: RetryOptions;\n name?: string;\n lockId?: string;\n};\n\nconst defaultTxOps = {\n sync: false,\n};\n\nfunction alternativeRootFieldName(alternativeRoot: string): string {\n return `alternative_root_${alternativeRoot}`;\n}\n\n/** Client to access core PL API. */\nexport class PlClient {\n private readonly drivers = new Map<string, PlDriver>();\n\n /** Artificial delay introduced after write transactions completion, to\n * somewhat throttle the load on pl. Delay introduced after sync, if requested. */\n private readonly txDelay: number;\n\n /** Last resort measure to solve complicated race conditions in pl. */\n private readonly forceSync: boolean;\n\n /** Last resort measure to solve complicated race conditions in pl. */\n private readonly defaultRetryOptions: RetryOptions;\n\n private readonly buildLLPlClient: (\n shouldUseGzip: boolean,\n wireProtocol?: wireProtocol,\n ) => Promise<LLPlClient>;\n private _ll?: LLPlClient;\n\n private get ll(): LLPlClient {\n if (this._ll === undefined) {\n throw new Error(\"LLPlClient not initialized\");\n }\n return this._ll;\n }\n\n /** Stores client root (this abstraction is intended for future implementation of the security model) */\n private _clientRoot: OptionalSignedResourceId = NullSignedResourceId;\n\n private _userResources?: UserResources;\n\n /** Cached effective role of the authenticated session, fetched once during\n * init via the GetSessionInfo RPC. `null` for an anonymous (no-auth)\n * connection — mirrors {@link authUser}. Read through {@link currentUserRole}. */\n private _currentUserRole: Role | null = null;\n\n private _txCommittedStat: TxStat = initialTxStat();\n private _txConflictStat: TxStat = initialTxStat();\n private _txErrorStat: TxStat = initialTxStat();\n\n //\n // Caching\n //\n\n /** This function determines whether resource data can be cached */\n public readonly finalPredicate: FinalResourceDataPredicate;\n\n /** Resource data cache, to minimize redundant data rereading from remote db */\n private readonly resourceDataCache: LRUCache<SignedResourceId, ResourceDataCacheRecord>;\n\n private constructor(\n configOrAddress: PlClientConfig | string,\n auth: AuthOps,\n ops: {\n statusListener?: PlConnectionStatusListener;\n finalPredicate?: FinalResourceDataPredicate;\n logger?: MiLogger;\n } = {},\n ) {\n const conf =\n typeof configOrAddress === \"string\" ? plAddressToConfig(configOrAddress) : configOrAddress;\n\n // An empty or whitespace-only asUser means \"no impersonation\"; normalize to undefined so a\n // directly-constructed { asUser: \"\" } does not slip through as an empty login.\n if (conf.asUser !== undefined && conf.asUser.trim() === \"\") conf.asUser = undefined;\n\n // asUser (impersonation) and alternativeRoot both repoint the client root, so they cannot be\n // combined. Validate here, before init() touches the network, so a misconfiguration fails fast.\n if (conf.asUser !== undefined && conf.alternativeRoot !== undefined)\n throw new Error(\"PlClient: asUser and alternativeRoot cannot be combined.\");\n\n this.buildLLPlClient = async (\n shouldUseGzip: boolean,\n wireProtocol?: wireProtocol,\n ): Promise<LLPlClient> => {\n if (wireProtocol) conf.wireProtocol = wireProtocol;\n return await LLPlClient.build(conf, { auth, ...ops, shouldUseGzip });\n };\n\n this.txDelay = conf.txDelay;\n this.forceSync = conf.forceSync;\n this.finalPredicate = ops.finalPredicate ?? DefaultFinalResourceDataPredicate;\n this.resourceDataCache = new LRUCache({\n maxSize: conf.maxCacheBytes,\n sizeCalculation: (v) => (v.basicData.data?.length ?? 0) + 64,\n });\n switch (conf.retryBackoffAlgorithm) {\n case \"exponential\":\n this.defaultRetryOptions = {\n type: \"exponentialBackoff\",\n initialDelay: conf.retryInitialDelay,\n maxAttempts: conf.retryMaxAttempts,\n backoffMultiplier: conf.retryExponentialBackoffMultiplier,\n jitter: conf.retryJitter,\n maxDelay: conf.retryMaxDelay,\n };\n break;\n case \"linear\":\n this.defaultRetryOptions = {\n type: \"linearBackoff\",\n initialDelay: conf.retryInitialDelay,\n maxAttempts: conf.retryMaxAttempts,\n backoffStep: conf.retryLinearBackoffStep,\n jitter: conf.retryJitter,\n maxDelay: conf.retryMaxDelay,\n };\n break;\n default:\n assertNever(conf.retryBackoffAlgorithm);\n }\n }\n\n public get txCommittedStat(): TxStat {\n return { ...this._txCommittedStat };\n }\n\n public get txConflictStat(): TxStat {\n return { ...this._txConflictStat };\n }\n\n public get txErrorStat(): TxStat {\n return { ...this._txErrorStat };\n }\n\n public get txTotalStat(): TxStat {\n return addStat(addStat(this._txCommittedStat, this._txConflictStat), this._txErrorStat);\n }\n\n public get allTxStat(): AllTxStat {\n return {\n committed: this.txCommittedStat,\n conflict: this.txConflictStat,\n error: this.txErrorStat,\n };\n }\n\n /** Smoothed round-trip estimate in ms from ping timings, or undefined before the first\n * ping. Exposed so latency-sensitive consumers (e.g. the tree-sync poll cadence) can scale\n * their timing to the link instead of assuming a local server. */\n public get rttEstimateMs(): number | undefined {\n return this.ll.rttEstimateMs;\n }\n\n public async ping(): Promise<MaintenanceAPI_Ping_Response> {\n return await this.ll.ping();\n }\n\n public async license(): Promise<MaintenanceAPI_License_Response> {\n return await this.ll.license();\n }\n\n /** Lists the users known to the server (login only on the wire). See {@link LLPlClient.listUsers}. */\n public async listUsers(): Promise<AuthAPI_User[]> {\n return await this.ll.listUsers();\n }\n\n /**\n * Deletes a user account and its root resource — with the root, everything still attached\n * under it. Destructive and irreversible; see {@link UserResources.deleteUser}.\n */\n public async deleteUser(login: string): Promise<UserDeletionReport> {\n return await this.userResources.deleteUser(login);\n }\n\n /**\n * Returns the user root SignedResourceId via ListUserResources.\n * @param opts.login - target user login; omit for the authenticated user.\n * @returns SignedResourceId of the user root, or undefined if the server returned no userRoot entry.\n * @throws if the backend does not implement ListUserResources (callers should catch with isUnimplementedError).\n */\n public async getUserRoot(opts: {\n login?: string;\n createIfNotExists: true;\n }): Promise<SignedResourceId>;\n public async getUserRoot(opts?: {\n login?: string;\n createIfNotExists?: boolean;\n }): Promise<SignedResourceId | undefined>;\n public async getUserRoot(\n opts: { login?: string; createIfNotExists?: boolean } = {},\n ): Promise<SignedResourceId | undefined> {\n return this.userResources.getUserRoot(opts);\n }\n\n public get conf(): PlClientConfig {\n return this.ll.conf;\n }\n\n public get httpDispatcher(): Dispatcher {\n return this.ll.httpDispatcher;\n }\n\n public get connectionOpts(): WireConnection {\n return this.ll.wireConnection;\n }\n\n private get initialized() {\n return !isNullSignedResourceId(this._clientRoot);\n }\n\n private checkInitialized() {\n if (!this.initialized) throw new Error(\"Client not initialized\");\n }\n\n public get clientRoot(): SignedResourceId {\n this.checkInitialized();\n return ensureSignedResourceIdNotNull(this._clientRoot);\n }\n\n public get serverInfo(): MaintenanceAPI_Ping_Response {\n this.checkInitialized();\n return this._ll!.serverInfo;\n }\n\n public hasCapability(capability: BackendCapability): boolean {\n this.checkInitialized();\n return this._ll!.hasCapability(capability);\n }\n\n /** Effective role of the authenticated session, resolved once during init via\n * the GetSessionInfo RPC and cached. `null` for an anonymous (no-auth)\n * connection, or when the backend predates GetSessionInfo. Mirrors\n * {@link authUser}'s null contract. */\n public get currentUserRole(): Role | null {\n this.checkInitialized();\n return this._currentUserRole;\n }\n\n /** Login of the authenticated user, or `null` for an anonymous connection. */\n public get authUser(): string | null {\n this.checkInitialized();\n return this.userResources.authUser;\n }\n\n /**\n * True if the backend honors per-file `permissions` on workdir fill rules.\n * See {@link LLPlClient.supportsWritableWorkdirFiles} for the full definition.\n */\n public get supportsWritableWorkdirFiles(): boolean {\n this.checkInitialized();\n return this._ll!.supportsWritableWorkdirFiles;\n }\n\n /** User resources index for discovering data libraries and other shared resources. */\n public get userResources(): UserResources {\n if (!this._ll) throw new Error(\"Client not initialized\");\n\n if (!this._userResources) {\n this._userResources = new UserResources(this._ll, this._withTx.bind(this), this._ll.authUser);\n }\n\n return this._userResources;\n }\n\n /** Discovers or creates the user's root resource via UserResources,\n * then handles alternativeRoot if configured. */\n private async init() {\n if (this.initialized) throw new Error(\"Already initialized\");\n\n // Initial client is created without gzip to perform server ping and detect optimal wire protocol.\n // LLPlClient.build() internally calls detectOptimalWireProtocol() which starts with default 'grpc',\n // then retries with 'rest' if ping fails, alternating until a working protocol is found.\n // We save the detected wireProtocol here because if the server supports gzip compression,\n // we'll need to reinitialize the client with gzip enabled - passing the already-detected\n // wireProtocol avoids redundant protocol detection on reinit.\n this._ll = await this.buildLLPlClient(false);\n const wireProtocol = this._ll.wireProtocol;\n\n // LLPlClient.build() guarantees a successful ping; read the cached response instead of pinging again.\n const info = this._ll.serverInfo;\n if (info.compression === MaintenanceAPI_Ping_Response_Compression.GZIP) {\n await this._ll.close();\n this._ll = await this.buildLLPlClient(true, wireProtocol);\n }\n\n // Resolve the client root. Normally the caller's own root; when `asUser` is set (admin impersonation),\n // the target user's root instead. The backend authorizes impersonation by role and silently returns the\n // caller's own root for non-admins, so no client-side role gate is needed here.\n let userRoot: SignedResourceId;\n if (this.conf.asUser === undefined) {\n userRoot = await this.userResources.getUserRoot({ createIfNotExists: true });\n } else {\n const impersonatedRoot = await this.userResources.getUserRoot({ login: this.conf.asUser });\n if (impersonatedRoot === undefined)\n throw new Error(\n `PlClient: cannot open root of user '${this.conf.asUser}': no root found (the user may have never logged in).`,\n );\n userRoot = impersonatedRoot;\n }\n\n // Resolve the caller's role once; only the publicGrants-gated share-with-everybody check uses it,\n // so skip it for anonymous connections or when publicGrants:v1 is absent. Use _ll.hasCapability,\n // not this.hasCapability: we are mid-init, so this.checkInitialized() would throw.\n if (this.userResources.authUser !== null && this._ll.hasCapability(\"publicGrants:v1\")) {\n this._currentUserRole = (await this._ll.getSessionInfo()).role;\n }\n\n if (this.conf.alternativeRoot === undefined) {\n this._clientRoot = userRoot;\n } else {\n this._clientRoot = await this._withTx(\"initialization\", true, userRoot, async (tx) => {\n const aFId = {\n resourceId: userRoot,\n fieldName: alternativeRootFieldName(this.conf.alternativeRoot!),\n };\n\n const altRoot = tx.createEphemeral(ClientRoot);\n tx.lock(altRoot);\n tx.createField(aFId, \"Dynamic\");\n tx.setField(aFId, altRoot);\n await tx.commit();\n\n return await altRoot.globalId;\n });\n }\n }\n\n /** Returns true if field existed */\n public async deleteAlternativeRoot(alternativeRootName: string): Promise<boolean> {\n this.checkInitialized();\n if (this.ll.conf.alternativeRoot !== undefined)\n throw new Error(\"Initialized with alternative root.\");\n return await this.withWriteTx(\"delete-alternative-root\", async (tx) => {\n const fId = {\n resourceId: tx.clientRoot,\n fieldName: alternativeRootFieldName(alternativeRootName),\n };\n const exists = tx.fieldExists(fId);\n tx.removeField(fId);\n await tx.commit();\n return await exists;\n });\n }\n\n private async _withTx<T>(\n name: string,\n writable: boolean,\n clientRoot: OptionalSignedResourceId,\n body: (tx: PlTransaction) => Promise<T>,\n ops?: TxOps,\n ): Promise<T> {\n // for exponential / linear backoff\n let retryState = createRetryState(ops?.retryOptions ?? this.defaultRetryOptions);\n\n while (true) {\n const release = ops?.lockId ? await advisoryLock(ops.lockId) : () => {};\n\n try {\n // opening low-level tx\n const llTx = this.ll.createTx(writable, ops);\n // wrapping it into high-level tx (this also asynchronously sends initialization message)\n const tx = new PlTransaction(\n llTx,\n name,\n writable,\n clientRoot,\n this.finalPredicate,\n this.resourceDataCache,\n );\n\n // Auto-set default color proof from the client root's signature.\n // Skip when backend doesn't implement the `set_default_color` TX request.\n if (this.ll.supportsResourceSignatures && !isNullSignedResourceId(clientRoot) && writable) {\n const parsed = parseSignedResourceId(clientRoot);\n if (parsed.signature) {\n tx.setDefaultColor(parsed.signature as ColorProof);\n }\n }\n\n let ok = false;\n let result: T | undefined = undefined;\n let txId;\n\n try {\n // executing transaction body\n result = await body(tx);\n // collecting stat\n this._txCommittedStat = addStat(this._txCommittedStat, tx.stat);\n ok = true;\n } catch (e: unknown) {\n // the only recoverable\n if (e instanceof TxCommitConflict) {\n // ignoring\n // collecting stat\n this._txConflictStat = addStat(this._txConflictStat, tx.stat);\n } else {\n // collecting stat\n this._txErrorStat = addStat(this._txErrorStat, tx.stat);\n throw e;\n }\n } finally {\n // close underlying grpc stream, if not yet done\n\n // even though we can skip two lines below for read-only transactions,\n // we don't do it to simplify reasoning about what is going on in\n // concurrent code, especially in significant latency situations\n await tx.complete();\n await tx.await();\n\n txId = await tx.getGlobalTxId();\n }\n\n if (ok) {\n // syncing on transaction if requested\n if (ops?.sync === undefined ? this.forceSync : ops?.sync) await this.ll.txSync(txId);\n\n // introducing artificial delay, if requested\n if (writable && this.txDelay > 0)\n await tp.setTimeout(this.txDelay, undefined, { signal: ops?.abortSignal });\n\n return result!;\n }\n } finally {\n release();\n }\n\n // we only get here after TxCommitConflict error,\n // all other errors terminate this loop instantly\n\n await tp.setTimeout(retryState.nextDelay, undefined, { signal: ops?.abortSignal });\n retryState = nextRetryStateOrError(retryState);\n }\n }\n\n private async withTx<T>(\n name: string,\n writable: boolean,\n body: (tx: PlTransaction) => Promise<T>,\n ops: Partial<TxOps> = {},\n ): Promise<T> {\n this.checkInitialized();\n return await this._withTx(name, writable, this.clientRoot, body, { ...ops, ...defaultTxOps });\n }\n\n public async withWriteTx<T>(\n name: string,\n body: (tx: PlTransaction) => Promise<T>,\n ops: Partial<TxOps> = {},\n ): Promise<T> {\n return await this.withTx(name, true, body, { ...ops, ...defaultTxOps });\n }\n\n /**\n * Runs a write transaction whose default color is `root`'s signature instead of the client\n * root's, and whose `tx.clientRoot` is `root`. For admin cross-root operations (e.g. copying a\n * project into another user's root so the copy is minted in that user's color). The backend\n * still authorizes the write by role.\n */\n public async withWriteTxOnRoot<T>(\n root: SignedResourceId,\n name: string,\n body: (tx: PlTransaction) => Promise<T>,\n ops: Partial<TxOps> = {},\n ): Promise<T> {\n this.checkInitialized();\n return await this._withTx(name, true, root, body, { ...ops, ...defaultTxOps });\n }\n\n public async withReadTx<T>(\n name: string,\n body: (tx: PlTransaction) => Promise<T>,\n ops: Partial<TxOps> = {},\n ): Promise<T> {\n return await this.withTx(name, false, body, { ...ops, ...defaultTxOps });\n }\n\n public getDriver<Drv extends PlDriver>(definition: PlDriverDefinition<Drv>): Drv {\n const attached = this.drivers.get(definition.name);\n if (attached !== undefined) return attached as Drv;\n const driver = definition.init(this, this.ll, this.httpDispatcher);\n this.drivers.set(definition.name, driver);\n return driver;\n }\n\n /** Closes underlying transport */\n public async close() {\n await this.ll.close();\n }\n\n public static async init(\n configOrAddress: PlClientConfig | string,\n auth: AuthOps,\n ops: {\n statusListener?: PlConnectionStatusListener;\n logger?: MiLogger;\n } = {},\n ) {\n const pl = new PlClient(configOrAddress, auth, ops);\n await pl.init();\n return pl;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA6CA,MAAM,eAAe,EACnB,MAAM,MACR;AAEA,SAAS,yBAAyB,iBAAiC;CACjE,OAAO,oBAAoB;AAC7B;;AAGA,IAAa,WAAb,MAAa,SAAS;CAC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ACX,MACA,MACA,MAAsB,CAAC,GACX;EACZ,OAAO,MAAM,KAAK,OAAO,MAAM,MAAM,MAAM;GAAE,GAAG;GAAK,GAAG;EAAa,CAAC;CACxE;;;;;;;CAQA,MAAa,kBACX,MACA,MACA,MACA,MAAsB,CAAC,GACX;EACZ,KAAK,iBAAiB;EACtB,OAAO,MAAM,KAAK,QAAQ,MAAM,MAAM,MAAM,MAAM;GAAE,GAAG;GAAK,GAAG;EAAa,CAAC;CAC/E;CAEA,MAAa,WACX,MACA,MACA,MAAsB,CAAC,GACX;EACZ,OAAO,MAAM,KAAK,OAAO,MAAM,OAAO,MAAM;GAAE,GAAG;GAAK,GAAG;EAAa,CAAC;CACzE;CAEA,UAAuC,YAA0C;EAC/E,MAAM,WAAW,KAAK,QAAQ,IAAI,WAAW,IAAI;EACjD,IAAI,aAAa,KAAA,GAAW,OAAO;EACnC,MAAM,SAAS,WAAW,KAAK,MAAM,KAAK,IAAI,KAAK,cAAc;EACjE,KAAK,QAAQ,IAAI,WAAW,MAAM,MAAM;EACxC,OAAO;CACT;;CAGA,MAAa,QAAQ;EACnB,MAAM,KAAK,GAAG,MAAM;CACtB;CAEA,aAAoB,KAClB,iBACA,MACA,MAGI,CAAC,GACL;EACA,MAAM,KAAK,IAAI,SAAS,iBAAiB,MAAM,GAAG;EAClD,MAAM,GAAG,KAAK;EACd,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"client.cjs","names":["initialTxStat","plAddressToConfig","LLPlClient","TreeFinality","LRUCache","addStat","isNullSignedResourceId","ensureSignedResourceIdNotNull","UserResources","ClientRoot","advisoryLock","PlTransaction","CacheFinality","parseSignedResourceId","TxCommitConflict","tp"],"sources":["../../src/core/client.ts"],"sourcesContent":["import type { AuthOps, PlClientConfig, PlConnectionStatusListener, wireProtocol } from \"./config\";\nimport type { PlCallOps } from \"./ll_client\";\nimport { LLPlClient } from \"./ll_client\";\nimport { PlTransaction, TxCommitConflict } from \"./transaction\";\nimport type { Role } from \"./transaction\";\nimport type { OptionalSignedResourceId, SignedResourceId } from \"./types\";\nimport {\n ensureSignedResourceIdNotNull,\n isNullSignedResourceId,\n NullSignedResourceId,\n parseSignedResourceId,\n} from \"./types\";\nimport type { ColorProof } from \"./types\";\nimport { ClientRoot } from \"../helpers/pl\";\nimport type { MiLogger, RetryOptions } from \"@milaboratories/ts-helpers\";\nimport { assertNever, createRetryState, nextRetryStateOrError } from \"@milaboratories/ts-helpers\";\nimport type { PlDriver, PlDriverDefinition } from \"./driver\";\nimport type {\n MaintenanceAPI_Ping_Response,\n MaintenanceAPI_License_Response,\n AuthAPI_User,\n} from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api\";\nimport { MaintenanceAPI_Ping_Response_Compression } from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api\";\nimport * as tp from \"node:timers/promises\";\nimport type { Dispatcher } from \"undici\";\nimport { LRUCache } from \"lru-cache\";\nimport type { ResourceDataCacheRecord } from \"./cache\";\nimport type { FinalResourceDataPredicate } from \"./final\";\nimport { CacheFinality, TreeFinality } from \"./final\";\nimport type { AllTxStat, TxStat } from \"./stat\";\nimport { addStat, initialTxStat } from \"./stat\";\nimport type { WireConnection } from \"./wire\";\nimport { advisoryLock } from \"./advisory_locks\";\nimport { plAddressToConfig } from \"./config\";\nimport { UserResources } from \"./user_resources\";\nimport type { UserDeletionReport } from \"./user_resources\";\nimport type { BackendCapability } from \"./capabilities\";\n\nexport type TxOps = PlCallOps & {\n sync?: boolean;\n retryOptions?: RetryOptions;\n name?: string;\n lockId?: string;\n};\n\nconst defaultTxOps = {\n sync: false,\n};\n\nfunction alternativeRootFieldName(alternativeRoot: string): string {\n return `alternative_root_${alternativeRoot}`;\n}\n\n/** Client to access core PL API. */\nexport class PlClient {\n private readonly drivers = new Map<string, PlDriver>();\n\n /** Artificial delay introduced after write transactions completion, to\n * somewhat throttle the load on pl. Delay introduced after sync, if requested. */\n private readonly txDelay: number;\n\n /** Last resort measure to solve complicated race conditions in pl. */\n private readonly forceSync: boolean;\n\n /** Last resort measure to solve complicated race conditions in pl. */\n private readonly defaultRetryOptions: RetryOptions;\n\n private readonly buildLLPlClient: (\n shouldUseGzip: boolean,\n wireProtocol?: wireProtocol,\n ) => Promise<LLPlClient>;\n private _ll?: LLPlClient;\n\n private get ll(): LLPlClient {\n if (this._ll === undefined) {\n throw new Error(\"LLPlClient not initialized\");\n }\n return this._ll;\n }\n\n /** Stores client root (this abstraction is intended for future implementation of the security model) */\n private _clientRoot: OptionalSignedResourceId = NullSignedResourceId;\n\n private _userResources?: UserResources;\n\n /** Cached effective role of the authenticated session, fetched once during\n * init via the GetSessionInfo RPC. `null` for an anonymous (no-auth)\n * connection — mirrors {@link authUser}. Read through {@link currentUserRole}. */\n private _currentUserRole: Role | null = null;\n\n private _txCommittedStat: TxStat = initialTxStat();\n private _txConflictStat: TxStat = initialTxStat();\n private _txErrorStat: TxStat = initialTxStat();\n\n //\n // Caching\n //\n\n /** The default finality predicate of trees built on this client ({@link TreeFinality} unless\n * given); a tree may override it, or keep its explicit roots non-final with\n * `rootsNeverFinal`. The transaction resource cache always uses {@link CacheFinality}. */\n public readonly finalPredicate: FinalResourceDataPredicate;\n\n /** Resource data cache, to minimize redundant data rereading from remote db */\n private readonly resourceDataCache: LRUCache<SignedResourceId, ResourceDataCacheRecord>;\n\n private constructor(\n configOrAddress: PlClientConfig | string,\n auth: AuthOps,\n ops: {\n statusListener?: PlConnectionStatusListener;\n finalPredicate?: FinalResourceDataPredicate;\n logger?: MiLogger;\n } = {},\n ) {\n const conf =\n typeof configOrAddress === \"string\" ? plAddressToConfig(configOrAddress) : configOrAddress;\n\n // An empty or whitespace-only asUser means \"no impersonation\"; normalize to undefined so a\n // directly-constructed { asUser: \"\" } does not slip through as an empty login.\n if (conf.asUser !== undefined && conf.asUser.trim() === \"\") conf.asUser = undefined;\n\n // asUser (impersonation) and alternativeRoot both repoint the client root, so they cannot be\n // combined. Validate here, before init() touches the network, so a misconfiguration fails fast.\n if (conf.asUser !== undefined && conf.alternativeRoot !== undefined)\n throw new Error(\"PlClient: asUser and alternativeRoot cannot be combined.\");\n\n this.buildLLPlClient = async (\n shouldUseGzip: boolean,\n wireProtocol?: wireProtocol,\n ): Promise<LLPlClient> => {\n if (wireProtocol) conf.wireProtocol = wireProtocol;\n return await LLPlClient.build(conf, { auth, ...ops, shouldUseGzip });\n };\n\n this.txDelay = conf.txDelay;\n this.forceSync = conf.forceSync;\n this.finalPredicate = ops.finalPredicate ?? TreeFinality.predicate();\n this.resourceDataCache = new LRUCache({\n maxSize: conf.maxCacheBytes,\n sizeCalculation: (v) => (v.basicData.data?.length ?? 0) + 64,\n });\n switch (conf.retryBackoffAlgorithm) {\n case \"exponential\":\n this.defaultRetryOptions = {\n type: \"exponentialBackoff\",\n initialDelay: conf.retryInitialDelay,\n maxAttempts: conf.retryMaxAttempts,\n backoffMultiplier: conf.retryExponentialBackoffMultiplier,\n jitter: conf.retryJitter,\n maxDelay: conf.retryMaxDelay,\n };\n break;\n case \"linear\":\n this.defaultRetryOptions = {\n type: \"linearBackoff\",\n initialDelay: conf.retryInitialDelay,\n maxAttempts: conf.retryMaxAttempts,\n backoffStep: conf.retryLinearBackoffStep,\n jitter: conf.retryJitter,\n maxDelay: conf.retryMaxDelay,\n };\n break;\n default:\n assertNever(conf.retryBackoffAlgorithm);\n }\n }\n\n public get txCommittedStat(): TxStat {\n return { ...this._txCommittedStat };\n }\n\n public get txConflictStat(): TxStat {\n return { ...this._txConflictStat };\n }\n\n public get txErrorStat(): TxStat {\n return { ...this._txErrorStat };\n }\n\n public get txTotalStat(): TxStat {\n return addStat(addStat(this._txCommittedStat, this._txConflictStat), this._txErrorStat);\n }\n\n public get allTxStat(): AllTxStat {\n return {\n committed: this.txCommittedStat,\n conflict: this.txConflictStat,\n error: this.txErrorStat,\n };\n }\n\n /** Smoothed round-trip estimate in ms from ping timings, or undefined before the first\n * ping. Exposed so latency-sensitive consumers (e.g. the tree-sync poll cadence) can scale\n * their timing to the link instead of assuming a local server. */\n public get rttEstimateMs(): number | undefined {\n return this.ll.rttEstimateMs;\n }\n\n public async ping(): Promise<MaintenanceAPI_Ping_Response> {\n return await this.ll.ping();\n }\n\n public async license(): Promise<MaintenanceAPI_License_Response> {\n return await this.ll.license();\n }\n\n /** Lists the users known to the server (login only on the wire). See {@link LLPlClient.listUsers}. */\n public async listUsers(): Promise<AuthAPI_User[]> {\n return await this.ll.listUsers();\n }\n\n /**\n * Deletes a user account and its root resource — with the root, everything still attached\n * under it. Destructive and irreversible; see {@link UserResources.deleteUser}.\n */\n public async deleteUser(login: string): Promise<UserDeletionReport> {\n return await this.userResources.deleteUser(login);\n }\n\n /**\n * Returns the user root SignedResourceId via ListUserResources.\n * @param opts.login - target user login; omit for the authenticated user.\n * @returns SignedResourceId of the user root, or undefined if the server returned no userRoot entry.\n * @throws if the backend does not implement ListUserResources (callers should catch with isUnimplementedError).\n */\n public async getUserRoot(opts: {\n login?: string;\n createIfNotExists: true;\n }): Promise<SignedResourceId>;\n public async getUserRoot(opts?: {\n login?: string;\n createIfNotExists?: boolean;\n }): Promise<SignedResourceId | undefined>;\n public async getUserRoot(\n opts: { login?: string; createIfNotExists?: boolean } = {},\n ): Promise<SignedResourceId | undefined> {\n return this.userResources.getUserRoot(opts);\n }\n\n public get conf(): PlClientConfig {\n return this.ll.conf;\n }\n\n public get httpDispatcher(): Dispatcher {\n return this.ll.httpDispatcher;\n }\n\n public get connectionOpts(): WireConnection {\n return this.ll.wireConnection;\n }\n\n private get initialized() {\n return !isNullSignedResourceId(this._clientRoot);\n }\n\n private checkInitialized() {\n if (!this.initialized) throw new Error(\"Client not initialized\");\n }\n\n public get clientRoot(): SignedResourceId {\n this.checkInitialized();\n return ensureSignedResourceIdNotNull(this._clientRoot);\n }\n\n public get serverInfo(): MaintenanceAPI_Ping_Response {\n this.checkInitialized();\n return this._ll!.serverInfo;\n }\n\n public hasCapability(capability: BackendCapability): boolean {\n this.checkInitialized();\n return this._ll!.hasCapability(capability);\n }\n\n /** Effective role of the authenticated session, resolved once during init via\n * the GetSessionInfo RPC and cached. `null` for an anonymous (no-auth)\n * connection, or when the backend predates GetSessionInfo. Mirrors\n * {@link authUser}'s null contract. */\n public get currentUserRole(): Role | null {\n this.checkInitialized();\n return this._currentUserRole;\n }\n\n /** Login of the authenticated user, or `null` for an anonymous connection. */\n public get authUser(): string | null {\n this.checkInitialized();\n return this.userResources.authUser;\n }\n\n /**\n * True if the backend honors per-file `permissions` on workdir fill rules.\n * See {@link LLPlClient.supportsWritableWorkdirFiles} for the full definition.\n */\n public get supportsWritableWorkdirFiles(): boolean {\n this.checkInitialized();\n return this._ll!.supportsWritableWorkdirFiles;\n }\n\n /** User resources index for discovering data libraries and other shared resources. */\n public get userResources(): UserResources {\n if (!this._ll) throw new Error(\"Client not initialized\");\n\n if (!this._userResources) {\n this._userResources = new UserResources(this._ll, this._withTx.bind(this), this._ll.authUser);\n }\n\n return this._userResources;\n }\n\n /** Discovers or creates the user's root resource via UserResources,\n * then handles alternativeRoot if configured. */\n private async init() {\n if (this.initialized) throw new Error(\"Already initialized\");\n\n // Initial client is created without gzip to perform server ping and detect optimal wire protocol.\n // LLPlClient.build() internally calls detectOptimalWireProtocol() which starts with default 'grpc',\n // then retries with 'rest' if ping fails, alternating until a working protocol is found.\n // We save the detected wireProtocol here because if the server supports gzip compression,\n // we'll need to reinitialize the client with gzip enabled - passing the already-detected\n // wireProtocol avoids redundant protocol detection on reinit.\n this._ll = await this.buildLLPlClient(false);\n const wireProtocol = this._ll.wireProtocol;\n\n // LLPlClient.build() guarantees a successful ping; read the cached response instead of pinging again.\n const info = this._ll.serverInfo;\n if (info.compression === MaintenanceAPI_Ping_Response_Compression.GZIP) {\n await this._ll.close();\n this._ll = await this.buildLLPlClient(true, wireProtocol);\n }\n\n // Resolve the client root. Normally the caller's own root; when `asUser` is set (admin impersonation),\n // the target user's root instead. The backend authorizes impersonation by role and silently returns the\n // caller's own root for non-admins, so no client-side role gate is needed here.\n let userRoot: SignedResourceId;\n if (this.conf.asUser === undefined) {\n userRoot = await this.userResources.getUserRoot({ createIfNotExists: true });\n } else {\n const impersonatedRoot = await this.userResources.getUserRoot({ login: this.conf.asUser });\n if (impersonatedRoot === undefined)\n throw new Error(\n `PlClient: cannot open root of user '${this.conf.asUser}': no root found (the user may have never logged in).`,\n );\n userRoot = impersonatedRoot;\n }\n\n // Resolve the caller's role once; only the publicGrants-gated share-with-everybody check uses it,\n // so skip it for anonymous connections or when publicGrants:v1 is absent. Use _ll.hasCapability,\n // not this.hasCapability: we are mid-init, so this.checkInitialized() would throw.\n if (this.userResources.authUser !== null && this._ll.hasCapability(\"publicGrants:v1\")) {\n this._currentUserRole = (await this._ll.getSessionInfo()).role;\n }\n\n if (this.conf.alternativeRoot === undefined) {\n this._clientRoot = userRoot;\n } else {\n this._clientRoot = await this._withTx(\"initialization\", true, userRoot, async (tx) => {\n const aFId = {\n resourceId: userRoot,\n fieldName: alternativeRootFieldName(this.conf.alternativeRoot!),\n };\n\n const altRoot = tx.createEphemeral(ClientRoot);\n tx.lock(altRoot);\n tx.createField(aFId, \"Dynamic\");\n tx.setField(aFId, altRoot);\n await tx.commit();\n\n return await altRoot.globalId;\n });\n }\n }\n\n /** Returns true if field existed */\n public async deleteAlternativeRoot(alternativeRootName: string): Promise<boolean> {\n this.checkInitialized();\n if (this.ll.conf.alternativeRoot !== undefined)\n throw new Error(\"Initialized with alternative root.\");\n return await this.withWriteTx(\"delete-alternative-root\", async (tx) => {\n const fId = {\n resourceId: tx.clientRoot,\n fieldName: alternativeRootFieldName(alternativeRootName),\n };\n const exists = tx.fieldExists(fId);\n tx.removeField(fId);\n await tx.commit();\n return await exists;\n });\n }\n\n private async _withTx<T>(\n name: string,\n writable: boolean,\n clientRoot: OptionalSignedResourceId,\n body: (tx: PlTransaction) => Promise<T>,\n ops?: TxOps,\n ): Promise<T> {\n // for exponential / linear backoff\n let retryState = createRetryState(ops?.retryOptions ?? this.defaultRetryOptions);\n\n while (true) {\n const release = ops?.lockId ? await advisoryLock(ops.lockId) : () => {};\n\n try {\n // opening low-level tx\n const llTx = this.ll.createTx(writable, ops);\n // wrapping it into high-level tx (this also asynchronously sends initialization message)\n const tx = new PlTransaction(\n llTx,\n name,\n writable,\n clientRoot,\n CacheFinality.predicate(),\n this.resourceDataCache,\n );\n\n // Auto-set default color proof from the client root's signature.\n // Skip when backend doesn't implement the `set_default_color` TX request.\n if (this.ll.supportsResourceSignatures && !isNullSignedResourceId(clientRoot) && writable) {\n const parsed = parseSignedResourceId(clientRoot);\n if (parsed.signature) {\n tx.setDefaultColor(parsed.signature as ColorProof);\n }\n }\n\n let ok = false;\n let result: T | undefined = undefined;\n let txId;\n\n try {\n // executing transaction body\n result = await body(tx);\n // collecting stat\n this._txCommittedStat = addStat(this._txCommittedStat, tx.stat);\n ok = true;\n } catch (e: unknown) {\n // the only recoverable\n if (e instanceof TxCommitConflict) {\n // ignoring\n // collecting stat\n this._txConflictStat = addStat(this._txConflictStat, tx.stat);\n } else {\n // collecting stat\n this._txErrorStat = addStat(this._txErrorStat, tx.stat);\n throw e;\n }\n } finally {\n // close underlying grpc stream, if not yet done\n\n // even though we can skip two lines below for read-only transactions,\n // we don't do it to simplify reasoning about what is going on in\n // concurrent code, especially in significant latency situations\n await tx.complete();\n await tx.await();\n\n txId = await tx.getGlobalTxId();\n }\n\n if (ok) {\n // syncing on transaction if requested\n if (ops?.sync === undefined ? this.forceSync : ops?.sync) await this.ll.txSync(txId);\n\n // introducing artificial delay, if requested\n if (writable && this.txDelay > 0)\n await tp.setTimeout(this.txDelay, undefined, { signal: ops?.abortSignal });\n\n return result!;\n }\n } finally {\n release();\n }\n\n // we only get here after TxCommitConflict error,\n // all other errors terminate this loop instantly\n\n await tp.setTimeout(retryState.nextDelay, undefined, { signal: ops?.abortSignal });\n retryState = nextRetryStateOrError(retryState);\n }\n }\n\n private async withTx<T>(\n name: string,\n writable: boolean,\n body: (tx: PlTransaction) => Promise<T>,\n ops: Partial<TxOps> = {},\n ): Promise<T> {\n this.checkInitialized();\n return await this._withTx(name, writable, this.clientRoot, body, { ...ops, ...defaultTxOps });\n }\n\n public async withWriteTx<T>(\n name: string,\n body: (tx: PlTransaction) => Promise<T>,\n ops: Partial<TxOps> = {},\n ): Promise<T> {\n return await this.withTx(name, true, body, { ...ops, ...defaultTxOps });\n }\n\n /**\n * Runs a write transaction whose default color is `root`'s signature instead of the client\n * root's, and whose `tx.clientRoot` is `root`. For admin cross-root operations (e.g. copying a\n * project into another user's root so the copy is minted in that user's color). The backend\n * still authorizes the write by role.\n */\n public async withWriteTxOnRoot<T>(\n root: SignedResourceId,\n name: string,\n body: (tx: PlTransaction) => Promise<T>,\n ops: Partial<TxOps> = {},\n ): Promise<T> {\n this.checkInitialized();\n return await this._withTx(name, true, root, body, { ...ops, ...defaultTxOps });\n }\n\n public async withReadTx<T>(\n name: string,\n body: (tx: PlTransaction) => Promise<T>,\n ops: Partial<TxOps> = {},\n ): Promise<T> {\n return await this.withTx(name, false, body, { ...ops, ...defaultTxOps });\n }\n\n public getDriver<Drv extends PlDriver>(definition: PlDriverDefinition<Drv>): Drv {\n const attached = this.drivers.get(definition.name);\n if (attached !== undefined) return attached as Drv;\n const driver = definition.init(this, this.ll, this.httpDispatcher);\n this.drivers.set(definition.name, driver);\n return driver;\n }\n\n /** Closes underlying transport */\n public async close() {\n await this.ll.close();\n }\n\n public static async init(\n configOrAddress: PlClientConfig | string,\n auth: AuthOps,\n ops: {\n statusListener?: PlConnectionStatusListener;\n logger?: MiLogger;\n } = {},\n ) {\n const pl = new PlClient(configOrAddress, auth, ops);\n await pl.init();\n return pl;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA6CA,MAAM,eAAe,EACnB,MAAM,MACR;AAEA,SAAS,yBAAyB,iBAAiC;CACjE,OAAO,oBAAoB;AAC7B;;AAGA,IAAa,WAAb,MAAa,SAAS;CACpB,0BAA2B,IAAI,IAAsB;;;CAIrD;;CAGA;;CAGA;CAEA;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X;EACZ,OAAO,MAAM,KAAK,OAAO,MAAM,MAAM,MAAM;GAAE,GAAG;GAAK,GAAG;EAAa,CAAC;CACxE;;;;;;;CAQA,MAAa,kBACX,MACA,MACA,MACA,MAAsB,CAAC,GACX;EACZ,KAAK,iBAAiB;EACtB,OAAO,MAAM,KAAK,QAAQ,MAAM,MAAM,MAAM,MAAM;GAAE,GAAG;GAAK,GAAG;EAAa,CAAC;CAC/E;CAEA,MAAa,WACX,MACA,MACA,MAAsB,CAAC,GACX;EACZ,OAAO,MAAM,KAAK,OAAO,MAAM,OAAO,MAAM;GAAE,GAAG;GAAK,GAAG;EAAa,CAAC;CACzE;CAEA,UAAuC,YAA0C;EAC/E,MAAM,WAAW,KAAK,QAAQ,IAAI,WAAW,IAAI;EACjD,IAAI,aAAa,KAAA,GAAW,OAAO;EACnC,MAAM,SAAS,WAAW,KAAK,MAAM,KAAK,IAAI,KAAK,cAAc;EACjE,KAAK,QAAQ,IAAI,WAAW,MAAM,MAAM;EACxC,OAAO;CACT;;CAGA,MAAa,QAAQ;EACnB,MAAM,KAAK,GAAG,MAAM;CACtB;CAEA,aAAoB,KAClB,iBACA,MACA,MAGI,CAAC,GACL;EACA,MAAM,KAAK,IAAI,SAAS,iBAAiB,MAAM,GAAG;EAClD,MAAM,GAAG,KAAK;EACd,OAAO;CACT;AACF"}
|
package/dist/core/client.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { SignedResourceId } from "./types.js";
|
|
2
2
|
import { AuthAPI_User, MaintenanceAPI_License_Response, MaintenanceAPI_Ping_Response } from "../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.js";
|
|
3
|
-
import { FinalResourceDataPredicate } from "./
|
|
3
|
+
import { FinalResourceDataPredicate } from "./finality.js";
|
|
4
|
+
import "./final.js";
|
|
4
5
|
import { AllTxStat, TxStat } from "./stat.js";
|
|
5
6
|
import { PlTransaction, Role } from "./transaction.js";
|
|
6
7
|
import { AuthOps, PlClientConfig, PlConnectionStatusListener } from "./config.js";
|
|
@@ -41,7 +42,9 @@ export declare class PlClient {
|
|
|
41
42
|
private _txCommittedStat;
|
|
42
43
|
private _txConflictStat;
|
|
43
44
|
private _txErrorStat;
|
|
44
|
-
/**
|
|
45
|
+
/** The default finality predicate of trees built on this client ({@link TreeFinality} unless
|
|
46
|
+
* given); a tree may override it, or keep its explicit roots non-final with
|
|
47
|
+
* `rootsNeverFinal`. The transaction resource cache always uses {@link CacheFinality}. */
|
|
45
48
|
readonly finalPredicate: FinalResourceDataPredicate;
|
|
46
49
|
/** Resource data cache, to minimize redundant data rereading from remote db */
|
|
47
50
|
private readonly resourceDataCache;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","names":[],"sources":["../../src/core/client.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"client.d.ts","names":[],"sources":["../../src/core/client.ts"],"mappings":";;;;;;;;;;;;;;;YAsCY,QAAQ;EAClB;EACA,eAAe;EACf;EACA;;;qBAYW;mBACM;;;mBAIA;;mBAGA;;mBAGA;mBAEA;UAIT;cAEI;;UAQJ;UAEA;;;;UAKA;UAEA;UACA;UACA;;;;WASQ,gBAAgB;;mBAGf;UAEV;MA8DI,mBAAmB;MAInB,kBAAkB;MAIlB,eAAe;MAIf,eAAe;MAIf,aAAa;;;;MAWb;EAIE,QAAQ,QAAQ;EAIhB,WAAW,QAAQ;;EAKnB,aAAa,QAAQ;;;;;EAQrB,WAAW,gBAAgB,QAAQ;;;;;;;EAUnC,YAAY;IACvB;IACA;MACE,QAAQ;EACC,YAAY;IACvB;IACA;MACE,QAAQ;MAOD,QAAQ;MAIR,kBAAkB;MAIlB,kBAAkB;cAIjB;UAIJ;MAIG,cAAc;MAKd,cAAc;EAKlB,cAAc,YAAY;;;;;MAStB,mBAAmB;;MAMnB;;;;;MASA;;MAMA,iBAAiB;;;UAYd;;EA8DD,sBAAsB,8BAA8B;UAgBnD;UA0FA;EAUD,YAAY,GACvB,cACA,OAAO,IAAI,kBAAkB,QAAQ,IACrC,MAAK,QAAQ,SACZ,QAAQ;;;;;;;EAUE,kBAAkB,GAC7B,MAAM,kBACN,cACA,OAAO,IAAI,kBAAkB,QAAQ,IACrC,MAAK,QAAQ,SACZ,QAAQ;EAKE,WAAW,GACtB,cACA,OAAO,IAAI,kBAAkB,QAAQ,IACrC,MAAK,QAAQ,SACZ,QAAQ;EAIJ,UAAU,YAAY,UAAU,YAAY,mBAAmB,OAAO;;EAShE,SAAK;SAIE,KAClB,iBAAiB,yBACjB,MAAM,SACN;IACE,iBAAiB;IACjB,SAAS;MACL,QAAA"}
|
package/dist/core/client.js
CHANGED
|
@@ -5,7 +5,7 @@ import { PlTransaction, TxCommitConflict } from "./transaction.js";
|
|
|
5
5
|
import { ClientRoot } from "../helpers/pl.js";
|
|
6
6
|
import { plAddressToConfig } from "./config.js";
|
|
7
7
|
import { LLPlClient } from "./ll_client.js";
|
|
8
|
-
import {
|
|
8
|
+
import { CacheFinality, TreeFinality } from "./final.js";
|
|
9
9
|
import { advisoryLock } from "./advisory_locks.js";
|
|
10
10
|
import { UserResources } from "./user_resources.js";
|
|
11
11
|
import { assertNever, createRetryState, nextRetryStateOrError } from "@milaboratories/ts-helpers";
|
|
@@ -42,7 +42,9 @@ var PlClient = class PlClient {
|
|
|
42
42
|
_txCommittedStat = initialTxStat();
|
|
43
43
|
_txConflictStat = initialTxStat();
|
|
44
44
|
_txErrorStat = initialTxStat();
|
|
45
|
-
/**
|
|
45
|
+
/** The default finality predicate of trees built on this client ({@link TreeFinality} unless
|
|
46
|
+
* given); a tree may override it, or keep its explicit roots non-final with
|
|
47
|
+
* `rootsNeverFinal`. The transaction resource cache always uses {@link CacheFinality}. */
|
|
46
48
|
finalPredicate;
|
|
47
49
|
/** Resource data cache, to minimize redundant data rereading from remote db */
|
|
48
50
|
resourceDataCache;
|
|
@@ -60,7 +62,7 @@ var PlClient = class PlClient {
|
|
|
60
62
|
};
|
|
61
63
|
this.txDelay = conf.txDelay;
|
|
62
64
|
this.forceSync = conf.forceSync;
|
|
63
|
-
this.finalPredicate = ops.finalPredicate ??
|
|
65
|
+
this.finalPredicate = ops.finalPredicate ?? TreeFinality.predicate();
|
|
64
66
|
this.resourceDataCache = new LRUCache({
|
|
65
67
|
maxSize: conf.maxCacheBytes,
|
|
66
68
|
sizeCalculation: (v) => (v.basicData.data?.length ?? 0) + 64
|
|
@@ -240,7 +242,7 @@ var PlClient = class PlClient {
|
|
|
240
242
|
while (true) {
|
|
241
243
|
const release = ops?.lockId ? await advisoryLock(ops.lockId) : () => {};
|
|
242
244
|
try {
|
|
243
|
-
const tx = new PlTransaction(this.ll.createTx(writable, ops), name, writable, clientRoot,
|
|
245
|
+
const tx = new PlTransaction(this.ll.createTx(writable, ops), name, writable, clientRoot, CacheFinality.predicate(), this.resourceDataCache);
|
|
244
246
|
if (this.ll.supportsResourceSignatures && !isNullSignedResourceId(clientRoot) && writable) {
|
|
245
247
|
const parsed = parseSignedResourceId(clientRoot);
|
|
246
248
|
if (parsed.signature) tx.setDefaultColor(parsed.signature);
|
package/dist/core/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":[],"sources":["../../src/core/client.ts"],"sourcesContent":["import type { AuthOps, PlClientConfig, PlConnectionStatusListener, wireProtocol } from \"./config\";\nimport type { PlCallOps } from \"./ll_client\";\nimport { LLPlClient } from \"./ll_client\";\nimport { PlTransaction, TxCommitConflict } from \"./transaction\";\nimport type { Role } from \"./transaction\";\nimport type { OptionalSignedResourceId, SignedResourceId } from \"./types\";\nimport {\n ensureSignedResourceIdNotNull,\n isNullSignedResourceId,\n NullSignedResourceId,\n parseSignedResourceId,\n} from \"./types\";\nimport type { ColorProof } from \"./types\";\nimport { ClientRoot } from \"../helpers/pl\";\nimport type { MiLogger, RetryOptions } from \"@milaboratories/ts-helpers\";\nimport { assertNever, createRetryState, nextRetryStateOrError } from \"@milaboratories/ts-helpers\";\nimport type { PlDriver, PlDriverDefinition } from \"./driver\";\nimport type {\n MaintenanceAPI_Ping_Response,\n MaintenanceAPI_License_Response,\n AuthAPI_User,\n} from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api\";\nimport { MaintenanceAPI_Ping_Response_Compression } from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api\";\nimport * as tp from \"node:timers/promises\";\nimport type { Dispatcher } from \"undici\";\nimport { LRUCache } from \"lru-cache\";\nimport type { ResourceDataCacheRecord } from \"./cache\";\nimport type { FinalResourceDataPredicate } from \"./final\";\nimport { DefaultFinalResourceDataPredicate } from \"./final\";\nimport type { AllTxStat, TxStat } from \"./stat\";\nimport { addStat, initialTxStat } from \"./stat\";\nimport type { WireConnection } from \"./wire\";\nimport { advisoryLock } from \"./advisory_locks\";\nimport { plAddressToConfig } from \"./config\";\nimport { UserResources } from \"./user_resources\";\nimport type { UserDeletionReport } from \"./user_resources\";\nimport type { BackendCapability } from \"./capabilities\";\n\nexport type TxOps = PlCallOps & {\n sync?: boolean;\n retryOptions?: RetryOptions;\n name?: string;\n lockId?: string;\n};\n\nconst defaultTxOps = {\n sync: false,\n};\n\nfunction alternativeRootFieldName(alternativeRoot: string): string {\n return `alternative_root_${alternativeRoot}`;\n}\n\n/** Client to access core PL API. */\nexport class PlClient {\n private readonly drivers = new Map<string, PlDriver>();\n\n /** Artificial delay introduced after write transactions completion, to\n * somewhat throttle the load on pl. Delay introduced after sync, if requested. */\n private readonly txDelay: number;\n\n /** Last resort measure to solve complicated race conditions in pl. */\n private readonly forceSync: boolean;\n\n /** Last resort measure to solve complicated race conditions in pl. */\n private readonly defaultRetryOptions: RetryOptions;\n\n private readonly buildLLPlClient: (\n shouldUseGzip: boolean,\n wireProtocol?: wireProtocol,\n ) => Promise<LLPlClient>;\n private _ll?: LLPlClient;\n\n private get ll(): LLPlClient {\n if (this._ll === undefined) {\n throw new Error(\"LLPlClient not initialized\");\n }\n return this._ll;\n }\n\n /** Stores client root (this abstraction is intended for future implementation of the security model) */\n private _clientRoot: OptionalSignedResourceId = NullSignedResourceId;\n\n private _userResources?: UserResources;\n\n /** Cached effective role of the authenticated session, fetched once during\n * init via the GetSessionInfo RPC. `null` for an anonymous (no-auth)\n * connection — mirrors {@link authUser}. Read through {@link currentUserRole}. */\n private _currentUserRole: Role | null = null;\n\n private _txCommittedStat: TxStat = initialTxStat();\n private _txConflictStat: TxStat = initialTxStat();\n private _txErrorStat: TxStat = initialTxStat();\n\n //\n // Caching\n //\n\n /** This function determines whether resource data can be cached */\n public readonly finalPredicate: FinalResourceDataPredicate;\n\n /** Resource data cache, to minimize redundant data rereading from remote db */\n private readonly resourceDataCache: LRUCache<SignedResourceId, ResourceDataCacheRecord>;\n\n private constructor(\n configOrAddress: PlClientConfig | string,\n auth: AuthOps,\n ops: {\n statusListener?: PlConnectionStatusListener;\n finalPredicate?: FinalResourceDataPredicate;\n logger?: MiLogger;\n } = {},\n ) {\n const conf =\n typeof configOrAddress === \"string\" ? plAddressToConfig(configOrAddress) : configOrAddress;\n\n // An empty or whitespace-only asUser means \"no impersonation\"; normalize to undefined so a\n // directly-constructed { asUser: \"\" } does not slip through as an empty login.\n if (conf.asUser !== undefined && conf.asUser.trim() === \"\") conf.asUser = undefined;\n\n // asUser (impersonation) and alternativeRoot both repoint the client root, so they cannot be\n // combined. Validate here, before init() touches the network, so a misconfiguration fails fast.\n if (conf.asUser !== undefined && conf.alternativeRoot !== undefined)\n throw new Error(\"PlClient: asUser and alternativeRoot cannot be combined.\");\n\n this.buildLLPlClient = async (\n shouldUseGzip: boolean,\n wireProtocol?: wireProtocol,\n ): Promise<LLPlClient> => {\n if (wireProtocol) conf.wireProtocol = wireProtocol;\n return await LLPlClient.build(conf, { auth, ...ops, shouldUseGzip });\n };\n\n this.txDelay = conf.txDelay;\n this.forceSync = conf.forceSync;\n this.finalPredicate = ops.finalPredicate ?? DefaultFinalResourceDataPredicate;\n this.resourceDataCache = new LRUCache({\n maxSize: conf.maxCacheBytes,\n sizeCalculation: (v) => (v.basicData.data?.length ?? 0) + 64,\n });\n switch (conf.retryBackoffAlgorithm) {\n case \"exponential\":\n this.defaultRetryOptions = {\n type: \"exponentialBackoff\",\n initialDelay: conf.retryInitialDelay,\n maxAttempts: conf.retryMaxAttempts,\n backoffMultiplier: conf.retryExponentialBackoffMultiplier,\n jitter: conf.retryJitter,\n maxDelay: conf.retryMaxDelay,\n };\n break;\n case \"linear\":\n this.defaultRetryOptions = {\n type: \"linearBackoff\",\n initialDelay: conf.retryInitialDelay,\n maxAttempts: conf.retryMaxAttempts,\n backoffStep: conf.retryLinearBackoffStep,\n jitter: conf.retryJitter,\n maxDelay: conf.retryMaxDelay,\n };\n break;\n default:\n assertNever(conf.retryBackoffAlgorithm);\n }\n }\n\n public get txCommittedStat(): TxStat {\n return { ...this._txCommittedStat };\n }\n\n public get txConflictStat(): TxStat {\n return { ...this._txConflictStat };\n }\n\n public get txErrorStat(): TxStat {\n return { ...this._txErrorStat };\n }\n\n public get txTotalStat(): TxStat {\n return addStat(addStat(this._txCommittedStat, this._txConflictStat), this._txErrorStat);\n }\n\n public get allTxStat(): AllTxStat {\n return {\n committed: this.txCommittedStat,\n conflict: this.txConflictStat,\n error: this.txErrorStat,\n };\n }\n\n /** Smoothed round-trip estimate in ms from ping timings, or undefined before the first\n * ping. Exposed so latency-sensitive consumers (e.g. the tree-sync poll cadence) can scale\n * their timing to the link instead of assuming a local server. */\n public get rttEstimateMs(): number | undefined {\n return this.ll.rttEstimateMs;\n }\n\n public async ping(): Promise<MaintenanceAPI_Ping_Response> {\n return await this.ll.ping();\n }\n\n public async license(): Promise<MaintenanceAPI_License_Response> {\n return await this.ll.license();\n }\n\n /** Lists the users known to the server (login only on the wire). See {@link LLPlClient.listUsers}. */\n public async listUsers(): Promise<AuthAPI_User[]> {\n return await this.ll.listUsers();\n }\n\n /**\n * Deletes a user account and its root resource — with the root, everything still attached\n * under it. Destructive and irreversible; see {@link UserResources.deleteUser}.\n */\n public async deleteUser(login: string): Promise<UserDeletionReport> {\n return await this.userResources.deleteUser(login);\n }\n\n /**\n * Returns the user root SignedResourceId via ListUserResources.\n * @param opts.login - target user login; omit for the authenticated user.\n * @returns SignedResourceId of the user root, or undefined if the server returned no userRoot entry.\n * @throws if the backend does not implement ListUserResources (callers should catch with isUnimplementedError).\n */\n public async getUserRoot(opts: {\n login?: string;\n createIfNotExists: true;\n }): Promise<SignedResourceId>;\n public async getUserRoot(opts?: {\n login?: string;\n createIfNotExists?: boolean;\n }): Promise<SignedResourceId | undefined>;\n public async getUserRoot(\n opts: { login?: string; createIfNotExists?: boolean } = {},\n ): Promise<SignedResourceId | undefined> {\n return this.userResources.getUserRoot(opts);\n }\n\n public get conf(): PlClientConfig {\n return this.ll.conf;\n }\n\n public get httpDispatcher(): Dispatcher {\n return this.ll.httpDispatcher;\n }\n\n public get connectionOpts(): WireConnection {\n return this.ll.wireConnection;\n }\n\n private get initialized() {\n return !isNullSignedResourceId(this._clientRoot);\n }\n\n private checkInitialized() {\n if (!this.initialized) throw new Error(\"Client not initialized\");\n }\n\n public get clientRoot(): SignedResourceId {\n this.checkInitialized();\n return ensureSignedResourceIdNotNull(this._clientRoot);\n }\n\n public get serverInfo(): MaintenanceAPI_Ping_Response {\n this.checkInitialized();\n return this._ll!.serverInfo;\n }\n\n public hasCapability(capability: BackendCapability): boolean {\n this.checkInitialized();\n return this._ll!.hasCapability(capability);\n }\n\n /** Effective role of the authenticated session, resolved once during init via\n * the GetSessionInfo RPC and cached. `null` for an anonymous (no-auth)\n * connection, or when the backend predates GetSessionInfo. Mirrors\n * {@link authUser}'s null contract. */\n public get currentUserRole(): Role | null {\n this.checkInitialized();\n return this._currentUserRole;\n }\n\n /** Login of the authenticated user, or `null` for an anonymous connection. */\n public get authUser(): string | null {\n this.checkInitialized();\n return this.userResources.authUser;\n }\n\n /**\n * True if the backend honors per-file `permissions` on workdir fill rules.\n * See {@link LLPlClient.supportsWritableWorkdirFiles} for the full definition.\n */\n public get supportsWritableWorkdirFiles(): boolean {\n this.checkInitialized();\n return this._ll!.supportsWritableWorkdirFiles;\n }\n\n /** User resources index for discovering data libraries and other shared resources. */\n public get userResources(): UserResources {\n if (!this._ll) throw new Error(\"Client not initialized\");\n\n if (!this._userResources) {\n this._userResources = new UserResources(this._ll, this._withTx.bind(this), this._ll.authUser);\n }\n\n return this._userResources;\n }\n\n /** Discovers or creates the user's root resource via UserResources,\n * then handles alternativeRoot if configured. */\n private async init() {\n if (this.initialized) throw new Error(\"Already initialized\");\n\n // Initial client is created without gzip to perform server ping and detect optimal wire protocol.\n // LLPlClient.build() internally calls detectOptimalWireProtocol() which starts with default 'grpc',\n // then retries with 'rest' if ping fails, alternating until a working protocol is found.\n // We save the detected wireProtocol here because if the server supports gzip compression,\n // we'll need to reinitialize the client with gzip enabled - passing the already-detected\n // wireProtocol avoids redundant protocol detection on reinit.\n this._ll = await this.buildLLPlClient(false);\n const wireProtocol = this._ll.wireProtocol;\n\n // LLPlClient.build() guarantees a successful ping; read the cached response instead of pinging again.\n const info = this._ll.serverInfo;\n if (info.compression === MaintenanceAPI_Ping_Response_Compression.GZIP) {\n await this._ll.close();\n this._ll = await this.buildLLPlClient(true, wireProtocol);\n }\n\n // Resolve the client root. Normally the caller's own root; when `asUser` is set (admin impersonation),\n // the target user's root instead. The backend authorizes impersonation by role and silently returns the\n // caller's own root for non-admins, so no client-side role gate is needed here.\n let userRoot: SignedResourceId;\n if (this.conf.asUser === undefined) {\n userRoot = await this.userResources.getUserRoot({ createIfNotExists: true });\n } else {\n const impersonatedRoot = await this.userResources.getUserRoot({ login: this.conf.asUser });\n if (impersonatedRoot === undefined)\n throw new Error(\n `PlClient: cannot open root of user '${this.conf.asUser}': no root found (the user may have never logged in).`,\n );\n userRoot = impersonatedRoot;\n }\n\n // Resolve the caller's role once; only the publicGrants-gated share-with-everybody check uses it,\n // so skip it for anonymous connections or when publicGrants:v1 is absent. Use _ll.hasCapability,\n // not this.hasCapability: we are mid-init, so this.checkInitialized() would throw.\n if (this.userResources.authUser !== null && this._ll.hasCapability(\"publicGrants:v1\")) {\n this._currentUserRole = (await this._ll.getSessionInfo()).role;\n }\n\n if (this.conf.alternativeRoot === undefined) {\n this._clientRoot = userRoot;\n } else {\n this._clientRoot = await this._withTx(\"initialization\", true, userRoot, async (tx) => {\n const aFId = {\n resourceId: userRoot,\n fieldName: alternativeRootFieldName(this.conf.alternativeRoot!),\n };\n\n const altRoot = tx.createEphemeral(ClientRoot);\n tx.lock(altRoot);\n tx.createField(aFId, \"Dynamic\");\n tx.setField(aFId, altRoot);\n await tx.commit();\n\n return await altRoot.globalId;\n });\n }\n }\n\n /** Returns true if field existed */\n public async deleteAlternativeRoot(alternativeRootName: string): Promise<boolean> {\n this.checkInitialized();\n if (this.ll.conf.alternativeRoot !== undefined)\n throw new Error(\"Initialized with alternative root.\");\n return await this.withWriteTx(\"delete-alternative-root\", async (tx) => {\n const fId = {\n resourceId: tx.clientRoot,\n fieldName: alternativeRootFieldName(alternativeRootName),\n };\n const exists = tx.fieldExists(fId);\n tx.removeField(fId);\n await tx.commit();\n return await exists;\n });\n }\n\n private async _withTx<T>(\n name: string,\n writable: boolean,\n clientRoot: OptionalSignedResourceId,\n body: (tx: PlTransaction) => Promise<T>,\n ops?: TxOps,\n ): Promise<T> {\n // for exponential / linear backoff\n let retryState = createRetryState(ops?.retryOptions ?? this.defaultRetryOptions);\n\n while (true) {\n const release = ops?.lockId ? await advisoryLock(ops.lockId) : () => {};\n\n try {\n // opening low-level tx\n const llTx = this.ll.createTx(writable, ops);\n // wrapping it into high-level tx (this also asynchronously sends initialization message)\n const tx = new PlTransaction(\n llTx,\n name,\n writable,\n clientRoot,\n this.finalPredicate,\n this.resourceDataCache,\n );\n\n // Auto-set default color proof from the client root's signature.\n // Skip when backend doesn't implement the `set_default_color` TX request.\n if (this.ll.supportsResourceSignatures && !isNullSignedResourceId(clientRoot) && writable) {\n const parsed = parseSignedResourceId(clientRoot);\n if (parsed.signature) {\n tx.setDefaultColor(parsed.signature as ColorProof);\n }\n }\n\n let ok = false;\n let result: T | undefined = undefined;\n let txId;\n\n try {\n // executing transaction body\n result = await body(tx);\n // collecting stat\n this._txCommittedStat = addStat(this._txCommittedStat, tx.stat);\n ok = true;\n } catch (e: unknown) {\n // the only recoverable\n if (e instanceof TxCommitConflict) {\n // ignoring\n // collecting stat\n this._txConflictStat = addStat(this._txConflictStat, tx.stat);\n } else {\n // collecting stat\n this._txErrorStat = addStat(this._txErrorStat, tx.stat);\n throw e;\n }\n } finally {\n // close underlying grpc stream, if not yet done\n\n // even though we can skip two lines below for read-only transactions,\n // we don't do it to simplify reasoning about what is going on in\n // concurrent code, especially in significant latency situations\n await tx.complete();\n await tx.await();\n\n txId = await tx.getGlobalTxId();\n }\n\n if (ok) {\n // syncing on transaction if requested\n if (ops?.sync === undefined ? this.forceSync : ops?.sync) await this.ll.txSync(txId);\n\n // introducing artificial delay, if requested\n if (writable && this.txDelay > 0)\n await tp.setTimeout(this.txDelay, undefined, { signal: ops?.abortSignal });\n\n return result!;\n }\n } finally {\n release();\n }\n\n // we only get here after TxCommitConflict error,\n // all other errors terminate this loop instantly\n\n await tp.setTimeout(retryState.nextDelay, undefined, { signal: ops?.abortSignal });\n retryState = nextRetryStateOrError(retryState);\n }\n }\n\n private async withTx<T>(\n name: string,\n writable: boolean,\n body: (tx: PlTransaction) => Promise<T>,\n ops: Partial<TxOps> = {},\n ): Promise<T> {\n this.checkInitialized();\n return await this._withTx(name, writable, this.clientRoot, body, { ...ops, ...defaultTxOps });\n }\n\n public async withWriteTx<T>(\n name: string,\n body: (tx: PlTransaction) => Promise<T>,\n ops: Partial<TxOps> = {},\n ): Promise<T> {\n return await this.withTx(name, true, body, { ...ops, ...defaultTxOps });\n }\n\n /**\n * Runs a write transaction whose default color is `root`'s signature instead of the client\n * root's, and whose `tx.clientRoot` is `root`. For admin cross-root operations (e.g. copying a\n * project into another user's root so the copy is minted in that user's color). The backend\n * still authorizes the write by role.\n */\n public async withWriteTxOnRoot<T>(\n root: SignedResourceId,\n name: string,\n body: (tx: PlTransaction) => Promise<T>,\n ops: Partial<TxOps> = {},\n ): Promise<T> {\n this.checkInitialized();\n return await this._withTx(name, true, root, body, { ...ops, ...defaultTxOps });\n }\n\n public async withReadTx<T>(\n name: string,\n body: (tx: PlTransaction) => Promise<T>,\n ops: Partial<TxOps> = {},\n ): Promise<T> {\n return await this.withTx(name, false, body, { ...ops, ...defaultTxOps });\n }\n\n public getDriver<Drv extends PlDriver>(definition: PlDriverDefinition<Drv>): Drv {\n const attached = this.drivers.get(definition.name);\n if (attached !== undefined) return attached as Drv;\n const driver = definition.init(this, this.ll, this.httpDispatcher);\n this.drivers.set(definition.name, driver);\n return driver;\n }\n\n /** Closes underlying transport */\n public async close() {\n await this.ll.close();\n }\n\n public static async init(\n configOrAddress: PlClientConfig | string,\n auth: AuthOps,\n ops: {\n statusListener?: PlConnectionStatusListener;\n logger?: MiLogger;\n } = {},\n ) {\n const pl = new PlClient(configOrAddress, auth, ops);\n await pl.init();\n return pl;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AA6CA,MAAM,eAAe,EACnB,MAAM,MACR;AAEA,SAAS,yBAAyB,iBAAiC;CACjE,OAAO,oBAAoB;AAC7B;;AAGA,IAAa,WAAb,MAAa,SAAS;CACpB,0BAA2B,IAAI,IAAsB;;;CAIrD;;CAGA;;CAGA;CAEA;CAIA;CAEA,IAAY,KAAiB;EAC3B,IAAI,KAAK,QAAQ,KAAA,GACf,MAAM,IAAI,MAAM,4BAA4B;EAE9C,OAAO,KAAK;CACd;;CAGA,cAAQ;CAER;;;;CAKA,mBAAwC;CAExC,mBAAmC,cAAc;CACjD,kBAAkC,cAAc;CAChD,eAA+B,cAAc;;CAO7C;;CAGA;CAEA,YACE,iBACA,MACA,MAII,CAAC,GACL;EACA,MAAM,OACJ,OAAO,oBAAoB,WAAW,kBAAkB,eAAe,IAAI;EAI7E,IAAI,KAAK,WAAW,KAAA,KAAa,KAAK,OAAO,KAAK,MAAM,IAAI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M,KAAK,GAAG,MAAM;CACtB;CAEA,aAAoB,KAClB,iBACA,MACA,MAGI,CAAC,GACL;EACA,MAAM,KAAK,IAAI,SAAS,iBAAiB,MAAM,GAAG;EAClD,MAAM,GAAG,KAAK;EACd,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"client.js","names":[],"sources":["../../src/core/client.ts"],"sourcesContent":["import type { AuthOps, PlClientConfig, PlConnectionStatusListener, wireProtocol } from \"./config\";\nimport type { PlCallOps } from \"./ll_client\";\nimport { LLPlClient } from \"./ll_client\";\nimport { PlTransaction, TxCommitConflict } from \"./transaction\";\nimport type { Role } from \"./transaction\";\nimport type { OptionalSignedResourceId, SignedResourceId } from \"./types\";\nimport {\n ensureSignedResourceIdNotNull,\n isNullSignedResourceId,\n NullSignedResourceId,\n parseSignedResourceId,\n} from \"./types\";\nimport type { ColorProof } from \"./types\";\nimport { ClientRoot } from \"../helpers/pl\";\nimport type { MiLogger, RetryOptions } from \"@milaboratories/ts-helpers\";\nimport { assertNever, createRetryState, nextRetryStateOrError } from \"@milaboratories/ts-helpers\";\nimport type { PlDriver, PlDriverDefinition } from \"./driver\";\nimport type {\n MaintenanceAPI_Ping_Response,\n MaintenanceAPI_License_Response,\n AuthAPI_User,\n} from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api\";\nimport { MaintenanceAPI_Ping_Response_Compression } from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api\";\nimport * as tp from \"node:timers/promises\";\nimport type { Dispatcher } from \"undici\";\nimport { LRUCache } from \"lru-cache\";\nimport type { ResourceDataCacheRecord } from \"./cache\";\nimport type { FinalResourceDataPredicate } from \"./final\";\nimport { CacheFinality, TreeFinality } from \"./final\";\nimport type { AllTxStat, TxStat } from \"./stat\";\nimport { addStat, initialTxStat } from \"./stat\";\nimport type { WireConnection } from \"./wire\";\nimport { advisoryLock } from \"./advisory_locks\";\nimport { plAddressToConfig } from \"./config\";\nimport { UserResources } from \"./user_resources\";\nimport type { UserDeletionReport } from \"./user_resources\";\nimport type { BackendCapability } from \"./capabilities\";\n\nexport type TxOps = PlCallOps & {\n sync?: boolean;\n retryOptions?: RetryOptions;\n name?: string;\n lockId?: string;\n};\n\nconst defaultTxOps = {\n sync: false,\n};\n\nfunction alternativeRootFieldName(alternativeRoot: string): string {\n return `alternative_root_${alternativeRoot}`;\n}\n\n/** Client to access core PL API. */\nexport class PlClient {\n private readonly drivers = new Map<string, PlDriver>();\n\n /** Artificial delay introduced after write transactions completion, to\n * somewhat throttle the load on pl. Delay introduced after sync, if requested. */\n private readonly txDelay: number;\n\n /** Last resort measure to solve complicated race conditions in pl. */\n private readonly forceSync: boolean;\n\n /** Last resort measure to solve complicated race conditions in pl. */\n private readonly defaultRetryOptions: RetryOptions;\n\n private readonly buildLLPlClient: (\n shouldUseGzip: boolean,\n wireProtocol?: wireProtocol,\n ) => Promise<LLPlClient>;\n private _ll?: LLPlClient;\n\n private get ll(): LLPlClient {\n if (this._ll === undefined) {\n throw new Error(\"LLPlClient not initialized\");\n }\n return this._ll;\n }\n\n /** Stores client root (this abstraction is intended for future implementation of the security model) */\n private _clientRoot: OptionalSignedResourceId = NullSignedResourceId;\n\n private _userResources?: UserResources;\n\n /** Cached effective role of the authenticated session, fetched once during\n * init via the GetSessionInfo RPC. `null` for an anonymous (no-auth)\n * connection — mirrors {@link authUser}. Read through {@link currentUserRole}. */\n private _currentUserRole: Role | null = null;\n\n private _txCommittedStat: TxStat = initialTxStat();\n private _txConflictStat: TxStat = initialTxStat();\n private _txErrorStat: TxStat = initialTxStat();\n\n //\n // Caching\n //\n\n /** The default finality predicate of trees built on this client ({@link TreeFinality} unless\n * given); a tree may override it, or keep its explicit roots non-final with\n * `rootsNeverFinal`. The transaction resource cache always uses {@link CacheFinality}. */\n public readonly finalPredicate: FinalResourceDataPredicate;\n\n /** Resource data cache, to minimize redundant data rereading from remote db */\n private readonly resourceDataCache: LRUCache<SignedResourceId, ResourceDataCacheRecord>;\n\n private constructor(\n configOrAddress: PlClientConfig | string,\n auth: AuthOps,\n ops: {\n statusListener?: PlConnectionStatusListener;\n finalPredicate?: FinalResourceDataPredicate;\n logger?: MiLogger;\n } = {},\n ) {\n const conf =\n typeof configOrAddress === \"string\" ? plAddressToConfig(configOrAddress) : configOrAddress;\n\n // An empty or whitespace-only asUser means \"no impersonation\"; normalize to undefined so a\n // directly-constructed { asUser: \"\" } does not slip through as an empty login.\n if (conf.asUser !== undefined && conf.asUser.trim() === \"\") conf.asUser = undefined;\n\n // asUser (impersonation) and alternativeRoot both repoint the client root, so they cannot be\n // combined. Validate here, before init() touches the network, so a misconfiguration fails fast.\n if (conf.asUser !== undefined && conf.alternativeRoot !== undefined)\n throw new Error(\"PlClient: asUser and alternativeRoot cannot be combined.\");\n\n this.buildLLPlClient = async (\n shouldUseGzip: boolean,\n wireProtocol?: wireProtocol,\n ): Promise<LLPlClient> => {\n if (wireProtocol) conf.wireProtocol = wireProtocol;\n return await LLPlClient.build(conf, { auth, ...ops, shouldUseGzip });\n };\n\n this.txDelay = conf.txDelay;\n this.forceSync = conf.forceSync;\n this.finalPredicate = ops.finalPredicate ?? TreeFinality.predicate();\n this.resourceDataCache = new LRUCache({\n maxSize: conf.maxCacheBytes,\n sizeCalculation: (v) => (v.basicData.data?.length ?? 0) + 64,\n });\n switch (conf.retryBackoffAlgorithm) {\n case \"exponential\":\n this.defaultRetryOptions = {\n type: \"exponentialBackoff\",\n initialDelay: conf.retryInitialDelay,\n maxAttempts: conf.retryMaxAttempts,\n backoffMultiplier: conf.retryExponentialBackoffMultiplier,\n jitter: conf.retryJitter,\n maxDelay: conf.retryMaxDelay,\n };\n break;\n case \"linear\":\n this.defaultRetryOptions = {\n type: \"linearBackoff\",\n initialDelay: conf.retryInitialDelay,\n maxAttempts: conf.retryMaxAttempts,\n backoffStep: conf.retryLinearBackoffStep,\n jitter: conf.retryJitter,\n maxDelay: conf.retryMaxDelay,\n };\n break;\n default:\n assertNever(conf.retryBackoffAlgorithm);\n }\n }\n\n public get txCommittedStat(): TxStat {\n return { ...this._txCommittedStat };\n }\n\n public get txConflictStat(): TxStat {\n return { ...this._txConflictStat };\n }\n\n public get txErrorStat(): TxStat {\n return { ...this._txErrorStat };\n }\n\n public get txTotalStat(): TxStat {\n return addStat(addStat(this._txCommittedStat, this._txConflictStat), this._txErrorStat);\n }\n\n public get allTxStat(): AllTxStat {\n return {\n committed: this.txCommittedStat,\n conflict: this.txConflictStat,\n error: this.txErrorStat,\n };\n }\n\n /** Smoothed round-trip estimate in ms from ping timings, or undefined before the first\n * ping. Exposed so latency-sensitive consumers (e.g. the tree-sync poll cadence) can scale\n * their timing to the link instead of assuming a local server. */\n public get rttEstimateMs(): number | undefined {\n return this.ll.rttEstimateMs;\n }\n\n public async ping(): Promise<MaintenanceAPI_Ping_Response> {\n return await this.ll.ping();\n }\n\n public async license(): Promise<MaintenanceAPI_License_Response> {\n return await this.ll.license();\n }\n\n /** Lists the users known to the server (login only on the wire). See {@link LLPlClient.listUsers}. */\n public async listUsers(): Promise<AuthAPI_User[]> {\n return await this.ll.listUsers();\n }\n\n /**\n * Deletes a user account and its root resource — with the root, everything still attached\n * under it. Destructive and irreversible; see {@link UserResources.deleteUser}.\n */\n public async deleteUser(login: string): Promise<UserDeletionReport> {\n return await this.userResources.deleteUser(login);\n }\n\n /**\n * Returns the user root SignedResourceId via ListUserResources.\n * @param opts.login - target user login; omit for the authenticated user.\n * @returns SignedResourceId of the user root, or undefined if the server returned no userRoot entry.\n * @throws if the backend does not implement ListUserResources (callers should catch with isUnimplementedError).\n */\n public async getUserRoot(opts: {\n login?: string;\n createIfNotExists: true;\n }): Promise<SignedResourceId>;\n public async getUserRoot(opts?: {\n login?: string;\n createIfNotExists?: boolean;\n }): Promise<SignedResourceId | undefined>;\n public async getUserRoot(\n opts: { login?: string; createIfNotExists?: boolean } = {},\n ): Promise<SignedResourceId | undefined> {\n return this.userResources.getUserRoot(opts);\n }\n\n public get conf(): PlClientConfig {\n return this.ll.conf;\n }\n\n public get httpDispatcher(): Dispatcher {\n return this.ll.httpDispatcher;\n }\n\n public get connectionOpts(): WireConnection {\n return this.ll.wireConnection;\n }\n\n private get initialized() {\n return !isNullSignedResourceId(this._clientRoot);\n }\n\n private checkInitialized() {\n if (!this.initialized) throw new Error(\"Client not initialized\");\n }\n\n public get clientRoot(): SignedResourceId {\n this.checkInitialized();\n return ensureSignedResourceIdNotNull(this._clientRoot);\n }\n\n public get serverInfo(): MaintenanceAPI_Ping_Response {\n this.checkInitialized();\n return this._ll!.serverInfo;\n }\n\n public hasCapability(capability: BackendCapability): boolean {\n this.checkInitialized();\n return this._ll!.hasCapability(capability);\n }\n\n /** Effective role of the authenticated session, resolved once during init via\n * the GetSessionInfo RPC and cached. `null` for an anonymous (no-auth)\n * connection, or when the backend predates GetSessionInfo. Mirrors\n * {@link authUser}'s null contract. */\n public get currentUserRole(): Role | null {\n this.checkInitialized();\n return this._currentUserRole;\n }\n\n /** Login of the authenticated user, or `null` for an anonymous connection. */\n public get authUser(): string | null {\n this.checkInitialized();\n return this.userResources.authUser;\n }\n\n /**\n * True if the backend honors per-file `permissions` on workdir fill rules.\n * See {@link LLPlClient.supportsWritableWorkdirFiles} for the full definition.\n */\n public get supportsWritableWorkdirFiles(): boolean {\n this.checkInitialized();\n return this._ll!.supportsWritableWorkdirFiles;\n }\n\n /** User resources index for discovering data libraries and other shared resources. */\n public get userResources(): UserResources {\n if (!this._ll) throw new Error(\"Client not initialized\");\n\n if (!this._userResources) {\n this._userResources = new UserResources(this._ll, this._withTx.bind(this), this._ll.authUser);\n }\n\n return this._userResources;\n }\n\n /** Discovers or creates the user's root resource via UserResources,\n * then handles alternativeRoot if configured. */\n private async init() {\n if (this.initialized) throw new Error(\"Already initialized\");\n\n // Initial client is created without gzip to perform server ping and detect optimal wire protocol.\n // LLPlClient.build() internally calls detectOptimalWireProtocol() which starts with default 'grpc',\n // then retries with 'rest' if ping fails, alternating until a working protocol is found.\n // We save the detected wireProtocol here because if the server supports gzip compression,\n // we'll need to reinitialize the client with gzip enabled - passing the already-detected\n // wireProtocol avoids redundant protocol detection on reinit.\n this._ll = await this.buildLLPlClient(false);\n const wireProtocol = this._ll.wireProtocol;\n\n // LLPlClient.build() guarantees a successful ping; read the cached response instead of pinging again.\n const info = this._ll.serverInfo;\n if (info.compression === MaintenanceAPI_Ping_Response_Compression.GZIP) {\n await this._ll.close();\n this._ll = await this.buildLLPlClient(true, wireProtocol);\n }\n\n // Resolve the client root. Normally the caller's own root; when `asUser` is set (admin impersonation),\n // the target user's root instead. The backend authorizes impersonation by role and silently returns the\n // caller's own root for non-admins, so no client-side role gate is needed here.\n let userRoot: SignedResourceId;\n if (this.conf.asUser === undefined) {\n userRoot = await this.userResources.getUserRoot({ createIfNotExists: true });\n } else {\n const impersonatedRoot = await this.userResources.getUserRoot({ login: this.conf.asUser });\n if (impersonatedRoot === undefined)\n throw new Error(\n `PlClient: cannot open root of user '${this.conf.asUser}': no root found (the user may have never logged in).`,\n );\n userRoot = impersonatedRoot;\n }\n\n // Resolve the caller's role once; only the publicGrants-gated share-with-everybody check uses it,\n // so skip it for anonymous connections or when publicGrants:v1 is absent. Use _ll.hasCapability,\n // not this.hasCapability: we are mid-init, so this.checkInitialized() would throw.\n if (this.userResources.authUser !== null && this._ll.hasCapability(\"publicGrants:v1\")) {\n this._currentUserRole = (await this._ll.getSessionInfo()).role;\n }\n\n if (this.conf.alternativeRoot === undefined) {\n this._clientRoot = userRoot;\n } else {\n this._clientRoot = await this._withTx(\"initialization\", true, userRoot, async (tx) => {\n const aFId = {\n resourceId: userRoot,\n fieldName: alternativeRootFieldName(this.conf.alternativeRoot!),\n };\n\n const altRoot = tx.createEphemeral(ClientRoot);\n tx.lock(altRoot);\n tx.createField(aFId, \"Dynamic\");\n tx.setField(aFId, altRoot);\n await tx.commit();\n\n return await altRoot.globalId;\n });\n }\n }\n\n /** Returns true if field existed */\n public async deleteAlternativeRoot(alternativeRootName: string): Promise<boolean> {\n this.checkInitialized();\n if (this.ll.conf.alternativeRoot !== undefined)\n throw new Error(\"Initialized with alternative root.\");\n return await this.withWriteTx(\"delete-alternative-root\", async (tx) => {\n const fId = {\n resourceId: tx.clientRoot,\n fieldName: alternativeRootFieldName(alternativeRootName),\n };\n const exists = tx.fieldExists(fId);\n tx.removeField(fId);\n await tx.commit();\n return await exists;\n });\n }\n\n private async _withTx<T>(\n name: string,\n writable: boolean,\n clientRoot: OptionalSignedResourceId,\n body: (tx: PlTransaction) => Promise<T>,\n ops?: TxOps,\n ): Promise<T> {\n // for exponential / linear backoff\n let retryState = createRetryState(ops?.retryOptions ?? this.defaultRetryOptions);\n\n while (true) {\n const release = ops?.lockId ? await advisoryLock(ops.lockId) : () => {};\n\n try {\n // opening low-level tx\n const llTx = this.ll.createTx(writable, ops);\n // wrapping it into high-level tx (this also asynchronously sends initialization message)\n const tx = new PlTransaction(\n llTx,\n name,\n writable,\n clientRoot,\n CacheFinality.predicate(),\n this.resourceDataCache,\n );\n\n // Auto-set default color proof from the client root's signature.\n // Skip when backend doesn't implement the `set_default_color` TX request.\n if (this.ll.supportsResourceSignatures && !isNullSignedResourceId(clientRoot) && writable) {\n const parsed = parseSignedResourceId(clientRoot);\n if (parsed.signature) {\n tx.setDefaultColor(parsed.signature as ColorProof);\n }\n }\n\n let ok = false;\n let result: T | undefined = undefined;\n let txId;\n\n try {\n // executing transaction body\n result = await body(tx);\n // collecting stat\n this._txCommittedStat = addStat(this._txCommittedStat, tx.stat);\n ok = true;\n } catch (e: unknown) {\n // the only recoverable\n if (e instanceof TxCommitConflict) {\n // ignoring\n // collecting stat\n this._txConflictStat = addStat(this._txConflictStat, tx.stat);\n } else {\n // collecting stat\n this._txErrorStat = addStat(this._txErrorStat, tx.stat);\n throw e;\n }\n } finally {\n // close underlying grpc stream, if not yet done\n\n // even though we can skip two lines below for read-only transactions,\n // we don't do it to simplify reasoning about what is going on in\n // concurrent code, especially in significant latency situations\n await tx.complete();\n await tx.await();\n\n txId = await tx.getGlobalTxId();\n }\n\n if (ok) {\n // syncing on transaction if requested\n if (ops?.sync === undefined ? this.forceSync : ops?.sync) await this.ll.txSync(txId);\n\n // introducing artificial delay, if requested\n if (writable && this.txDelay > 0)\n await tp.setTimeout(this.txDelay, undefined, { signal: ops?.abortSignal });\n\n return result!;\n }\n } finally {\n release();\n }\n\n // we only get here after TxCommitConflict error,\n // all other errors terminate this loop instantly\n\n await tp.setTimeout(retryState.nextDelay, undefined, { signal: ops?.abortSignal });\n retryState = nextRetryStateOrError(retryState);\n }\n }\n\n private async withTx<T>(\n name: string,\n writable: boolean,\n body: (tx: PlTransaction) => Promise<T>,\n ops: Partial<TxOps> = {},\n ): Promise<T> {\n this.checkInitialized();\n return await this._withTx(name, writable, this.clientRoot, body, { ...ops, ...defaultTxOps });\n }\n\n public async withWriteTx<T>(\n name: string,\n body: (tx: PlTransaction) => Promise<T>,\n ops: Partial<TxOps> = {},\n ): Promise<T> {\n return await this.withTx(name, true, body, { ...ops, ...defaultTxOps });\n }\n\n /**\n * Runs a write transaction whose default color is `root`'s signature instead of the client\n * root's, and whose `tx.clientRoot` is `root`. For admin cross-root operations (e.g. copying a\n * project into another user's root so the copy is minted in that user's color). The backend\n * still authorizes the write by role.\n */\n public async withWriteTxOnRoot<T>(\n root: SignedResourceId,\n name: string,\n body: (tx: PlTransaction) => Promise<T>,\n ops: Partial<TxOps> = {},\n ): Promise<T> {\n this.checkInitialized();\n return await this._withTx(name, true, root, body, { ...ops, ...defaultTxOps });\n }\n\n public async withReadTx<T>(\n name: string,\n body: (tx: PlTransaction) => Promise<T>,\n ops: Partial<TxOps> = {},\n ): Promise<T> {\n return await this.withTx(name, false, body, { ...ops, ...defaultTxOps });\n }\n\n public getDriver<Drv extends PlDriver>(definition: PlDriverDefinition<Drv>): Drv {\n const attached = this.drivers.get(definition.name);\n if (attached !== undefined) return attached as Drv;\n const driver = definition.init(this, this.ll, this.httpDispatcher);\n this.drivers.set(definition.name, driver);\n return driver;\n }\n\n /** Closes underlying transport */\n public async close() {\n await this.ll.close();\n }\n\n public static async init(\n configOrAddress: PlClientConfig | string,\n auth: AuthOps,\n ops: {\n statusListener?: PlConnectionStatusListener;\n logger?: MiLogger;\n } = {},\n ) {\n const pl = new PlClient(configOrAddress, auth, ops);\n await pl.init();\n return pl;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AA6CA,MAAM,eAAe,EACnB,MAAM,MACR;AAEA,SAAS,yBAAyB,iBAAiC;CACjE,OAAO,oBAAoB;AAC7B;;AAGA,IAAa,WAAb,MAAa,SAAS;CACpB,0BAA2B,IAAI,IAAsB;;;CAIrD;;CAGA;;CAGA;CAEA;CAIA;CAEA,IAAY,KAAiB;EAC3B,IAAI,KAAK,QAAQ,KAAA,GACf,MAAM,IAAI,MAAM,4BAA4B;EAE9C,OAAO,KAAK;CACd;;CAGA,cAAQ;CAER;;;;CAKA,mBAAwC;CAExC,mBAAmC,cAAc;CACjD,kBAAkC,cAAc;CAChD,eAA+B,cAAc;;;;CAS7C;;CAGA;CAEA,YACE,iBACA,MACA,MAII,CAAC,GACL;EACA,MAAM,OACJ,OAAO,oBAAoB,WAAW,kBAAkB,eAAe,IAAI;EAI7E,IAAI,KAAK,WAAW,KAAA,KAAa,KAAK,OAAO,KAAK,MAAM,IAAI,KAAK,SAAS,KAAA;EAI1E,IAAI,KAAK,WAAW,KAAA,KAAa,KAAK,oBAAoB,KAAA,GACxD,MAAM,IAAI,MAAM,0DAA0D;EAE5E,KAAK,kBAAkB,OACrB,eACA,iBACwB;GACxB,IAAI,cAAc,KAAK,eAAe;GACtC,OAAO,MAAM,WAAW,MAAM,MAAM;IAAE;IAAM,GAAG;IAAK;GAAc,CAAC;EACrE;EAEA,KAAK,UAAU,KAAK;EACpB,KAAK,YAAY,KAAK;EACtB,KAAK,iBAAiB,IAAI,kBAAkB,aAAa,UAAU;EACnE,KAAK,oBAAoB,IAAI,SAAS;GACpC,SAAS,KAAK;GACd,kBAAkB,OAAO,EAAE,UAAU,MAAM,UAAU,KAAK;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