@milaboratories/pl-client 3.12.0 → 3.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/core/capabilities.cjs.map +1 -1
  2. package/dist/core/capabilities.d.ts +2 -3
  3. package/dist/core/capabilities.d.ts.map +1 -1
  4. package/dist/core/capabilities.js.map +1 -1
  5. package/dist/core/client.cjs +20 -3
  6. package/dist/core/client.cjs.map +1 -1
  7. package/dist/core/client.d.ts +14 -4
  8. package/dist/core/client.d.ts.map +1 -1
  9. package/dist/core/client.js +20 -3
  10. package/dist/core/client.js.map +1 -1
  11. package/dist/core/errors.cjs +1 -0
  12. package/dist/core/errors.cjs.map +1 -1
  13. package/dist/core/errors.d.ts.map +1 -1
  14. package/dist/core/errors.js +1 -0
  15. package/dist/core/errors.js.map +1 -1
  16. package/dist/core/final.cjs +4 -1
  17. package/dist/core/final.cjs.map +1 -1
  18. package/dist/core/final.d.ts.map +1 -1
  19. package/dist/core/final.js +4 -1
  20. package/dist/core/final.js.map +1 -1
  21. package/dist/core/ll_client.cjs +47 -8
  22. package/dist/core/ll_client.cjs.map +1 -1
  23. package/dist/core/ll_client.d.ts +22 -7
  24. package/dist/core/ll_client.d.ts.map +1 -1
  25. package/dist/core/ll_client.js +48 -9
  26. package/dist/core/ll_client.js.map +1 -1
  27. package/dist/core/transaction.cjs +82 -1
  28. package/dist/core/transaction.cjs.map +1 -1
  29. package/dist/core/transaction.d.ts +52 -2
  30. package/dist/core/transaction.d.ts.map +1 -1
  31. package/dist/core/transaction.js +80 -2
  32. package/dist/core/transaction.js.map +1 -1
  33. package/dist/core/user_resources.cjs +54 -0
  34. package/dist/core/user_resources.cjs.map +1 -1
  35. package/dist/core/user_resources.d.ts +55 -1
  36. package/dist/core/user_resources.d.ts.map +1 -1
  37. package/dist/core/user_resources.js +54 -0
  38. package/dist/core/user_resources.js.map +1 -1
  39. package/dist/index.cjs +3 -0
  40. package/dist/index.d.ts +3 -3
  41. package/dist/index.js +2 -2
  42. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.cjs +6 -6
  43. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.cjs.map +1 -1
  44. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.d.ts +6 -6
  45. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.d.ts.map +1 -1
  46. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.js +6 -6
  47. package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.js.map +1 -1
  48. package/package.json +2 -2
  49. package/src/core/capabilities.ts +10 -3
  50. package/src/core/client.ts +30 -3
  51. package/src/core/errors.ts +2 -0
  52. package/src/core/final.ts +4 -0
  53. package/src/core/ll_client.test.ts +15 -2
  54. package/src/core/ll_client.ts +59 -9
  55. package/src/core/transaction.ts +103 -3
  56. package/src/core/user_resources.ts +85 -0
  57. package/src/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.ts +9 -9
@@ -1 +1 @@
1
- {"version":3,"file":"capabilities.cjs","names":[],"sources":["../../src/core/capabilities.ts"],"sourcesContent":["/**\n * Backend capability tokens advertised by pl in\n * `MaintenanceAPI.Ping.Response.capabilities`.\n * Capabilities affect behaviour of inner ML mechanisms and allow\n * to detect incompatibilities between blocks and backend via\n * via `TemplateDataV3.requiredCapabilities`.\n *\n * Mirror of `pl/platform/api/plapiserver/server_capabilities.go` — keep\n * tokens in sync with the backend's advertised list. Format is\n * `<feature>:<version>`; bump the version when wire semantics change.\n *\n * Shared across:\n * - `@milaboratories/pl-client` — client-side capability checks\n * - `@platforma-sdk/tengo-builder` — populates `requiredCapabilities` at compile time\n * - `@platforma-sdk/block-tools` — copies it onto the published manifest\n * - `@milaboratories/pl-middle-layer` — checks it at install time\n */\nexport type BackendCapability = \"auth:v2\" | \"treeFilter:v2\" | \"wasm:v1\";\n\n/** True iff `capabilities` advertises the requested token. */\nexport function hasCapability(\n capabilities: readonly string[] | undefined,\n capability: BackendCapability,\n): boolean {\n return capabilities?.includes(capability) ?? false;\n}\n"],"mappings":";;AAoBA,SAAgB,cACd,cACA,YACS;CACT,OAAO,cAAc,SAAS,UAAU,KAAK;AAC/C"}
1
+ {"version":3,"file":"capabilities.cjs","names":[],"sources":["../../src/core/capabilities.ts"],"sourcesContent":["/**\n * Backend capability tokens advertised by pl in\n * `MaintenanceAPI.Ping.Response.capabilities`.\n * Capabilities affect behaviour of inner ML mechanisms and allow\n * to detect incompatibilities between blocks and backend via\n * via `TemplateDataV3.requiredCapabilities`.\n *\n * Keep tokens in sync with the backend's advertised list. Format is\n * `<feature>:<version>`; bump the version when wire semantics change.\n *\n * Shared across:\n * - `@milaboratories/pl-client` — client-side capability checks\n * - `@platforma-sdk/tengo-builder` — populates `requiredCapabilities` at compile time\n * - `@platforma-sdk/block-tools` — copies it onto the published manifest\n * - `@milaboratories/pl-middle-layer` — checks it at install time\n */\nexport type BackendCapability =\n | \"auth:v2\"\n | \"treeFilter:v2\"\n | \"wasm:v1\"\n // Project-sharing capability tokens.\n | \"crossTreeRefs:v1\" // cross-color field attach (accept a foreign-colored shared envelope)\n | \"userListing:v1\" // list users for the recipient picker\n | \"publicGrants:v1\" // public (everyone) grants allowed for any role\n | \"txListGrants:v1\"; // list grants inside a transaction (batched recipient reads)\n\n/** True iff `capabilities` advertises the requested token. */\nexport function hasCapability(\n capabilities: readonly string[] | undefined,\n capability: BackendCapability,\n): boolean {\n return capabilities?.includes(capability) ?? false;\n}\n"],"mappings":";;AA2BA,SAAgB,cACd,cACA,YACS;CACT,OAAO,cAAc,SAAS,UAAU,KAAK;AAC/C"}
@@ -6,8 +6,7 @@
6
6
  * to detect incompatibilities between blocks and backend via
7
7
  * via `TemplateDataV3.requiredCapabilities`.
8
8
  *
9
- * Mirror of `pl/platform/api/plapiserver/server_capabilities.go` — keep
10
- * tokens in sync with the backend's advertised list. Format is
9
+ * Keep tokens in sync with the backend's advertised list. Format is
11
10
  * `<feature>:<version>`; bump the version when wire semantics change.
12
11
  *
13
12
  * Shared across:
@@ -16,7 +15,7 @@
16
15
  * - `@platforma-sdk/block-tools` — copies it onto the published manifest
17
16
  * - `@milaboratories/pl-middle-layer` — checks it at install time
18
17
  */
19
- type BackendCapability = "auth:v2" | "treeFilter:v2" | "wasm:v1";
18
+ type BackendCapability = "auth:v2" | "treeFilter:v2" | "wasm:v1" | "crossTreeRefs:v1" | "userListing:v1" | "publicGrants:v1" | "txListGrants:v1";
20
19
  /** True iff `capabilities` advertises the requested token. */
21
20
  declare function hasCapability(capabilities: readonly string[] | undefined, capability: BackendCapability): boolean;
22
21
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"capabilities.d.ts","names":[],"sources":["../../src/core/capabilities.ts"],"mappings":";;AAiBA;;;;AAA6B;AAG7B;;;;;;;;AAE+B;;;KALnB,iBAAA;;iBAGI,aAAA,CACd,YAAA,iCACA,UAAA,EAAY,iBAAiB"}
1
+ {"version":3,"file":"capabilities.d.ts","names":[],"sources":["../../src/core/capabilities.ts"],"mappings":";;AAgBA;;;;AAA6B;AAW7B;;;;;;;;AAE+B;;KAbnB,iBAAA;;iBAWI,aAAA,CACd,YAAA,iCACA,UAAA,EAAY,iBAAiB"}
@@ -1 +1 @@
1
- {"version":3,"file":"capabilities.js","names":[],"sources":["../../src/core/capabilities.ts"],"sourcesContent":["/**\n * Backend capability tokens advertised by pl in\n * `MaintenanceAPI.Ping.Response.capabilities`.\n * Capabilities affect behaviour of inner ML mechanisms and allow\n * to detect incompatibilities between blocks and backend via\n * via `TemplateDataV3.requiredCapabilities`.\n *\n * Mirror of `pl/platform/api/plapiserver/server_capabilities.go` — keep\n * tokens in sync with the backend's advertised list. Format is\n * `<feature>:<version>`; bump the version when wire semantics change.\n *\n * Shared across:\n * - `@milaboratories/pl-client` — client-side capability checks\n * - `@platforma-sdk/tengo-builder` — populates `requiredCapabilities` at compile time\n * - `@platforma-sdk/block-tools` — copies it onto the published manifest\n * - `@milaboratories/pl-middle-layer` — checks it at install time\n */\nexport type BackendCapability = \"auth:v2\" | \"treeFilter:v2\" | \"wasm:v1\";\n\n/** True iff `capabilities` advertises the requested token. */\nexport function hasCapability(\n capabilities: readonly string[] | undefined,\n capability: BackendCapability,\n): boolean {\n return capabilities?.includes(capability) ?? false;\n}\n"],"mappings":";;AAoBA,SAAgB,cACd,cACA,YACS;CACT,OAAO,cAAc,SAAS,UAAU,KAAK;AAC/C"}
1
+ {"version":3,"file":"capabilities.js","names":[],"sources":["../../src/core/capabilities.ts"],"sourcesContent":["/**\n * Backend capability tokens advertised by pl in\n * `MaintenanceAPI.Ping.Response.capabilities`.\n * Capabilities affect behaviour of inner ML mechanisms and allow\n * to detect incompatibilities between blocks and backend via\n * via `TemplateDataV3.requiredCapabilities`.\n *\n * Keep tokens in sync with the backend's advertised list. Format is\n * `<feature>:<version>`; bump the version when wire semantics change.\n *\n * Shared across:\n * - `@milaboratories/pl-client` — client-side capability checks\n * - `@platforma-sdk/tengo-builder` — populates `requiredCapabilities` at compile time\n * - `@platforma-sdk/block-tools` — copies it onto the published manifest\n * - `@milaboratories/pl-middle-layer` — checks it at install time\n */\nexport type BackendCapability =\n | \"auth:v2\"\n | \"treeFilter:v2\"\n | \"wasm:v1\"\n // Project-sharing capability tokens.\n | \"crossTreeRefs:v1\" // cross-color field attach (accept a foreign-colored shared envelope)\n | \"userListing:v1\" // list users for the recipient picker\n | \"publicGrants:v1\" // public (everyone) grants allowed for any role\n | \"txListGrants:v1\"; // list grants inside a transaction (batched recipient reads)\n\n/** True iff `capabilities` advertises the requested token. */\nexport function hasCapability(\n capabilities: readonly string[] | undefined,\n capability: BackendCapability,\n): boolean {\n return capabilities?.includes(capability) ?? false;\n}\n"],"mappings":";;AA2BA,SAAgB,cACd,cACA,YACS;CACT,OAAO,cAAc,SAAS,UAAU,KAAK;AAC/C"}
@@ -37,6 +37,10 @@ var PlClient = class PlClient {
37
37
  /** Stores client root (this abstraction is intended for future implementation of the security model) */
38
38
  _clientRoot = "";
39
39
  _userResources;
40
+ /** Cached effective role of the authenticated session, fetched once during
41
+ * init via the GetSessionInfo RPC. `null` for an anonymous (no-auth)
42
+ * connection — mirrors {@link authUser}. Read through {@link currentUserRole}. */
43
+ _currentUserRole = null;
40
44
  _txCommittedStat = require_stat.initialTxStat();
41
45
  _txConflictStat = require_stat.initialTxStat();
42
46
  _txErrorStat = require_stat.initialTxStat();
@@ -138,10 +142,22 @@ var PlClient = class PlClient {
138
142
  this.checkInitialized();
139
143
  return this._ll.hasCapability(capability);
140
144
  }
145
+ /** Effective role of the authenticated session, resolved once during init via
146
+ * the GetSessionInfo RPC and cached. `null` for an anonymous (no-auth)
147
+ * connection, or when the backend predates GetSessionInfo. Mirrors
148
+ * {@link authUser}'s null contract. */
149
+ get currentUserRole() {
150
+ this.checkInitialized();
151
+ return this._currentUserRole;
152
+ }
153
+ /** Login of the authenticated user, or `null` for an anonymous connection. */
154
+ get authUser() {
155
+ this.checkInitialized();
156
+ return this.userResources.authUser;
157
+ }
141
158
  /**
142
- * True if the backend honors per-file `permissions` on workdir fill rules
143
- * (PR #1830 in milaboratory/pl). See `LLPlClient.supportsWritableWorkdirFiles`
144
- * for the full definition.
159
+ * True if the backend honors per-file `permissions` on workdir fill rules.
160
+ * See {@link LLPlClient.supportsWritableWorkdirFiles} for the full definition.
145
161
  */
146
162
  get supportsWritableWorkdirFiles() {
147
163
  this.checkInitialized();
@@ -164,6 +180,7 @@ var PlClient = class PlClient {
164
180
  this._ll = await this.buildLLPlClient(true, wireProtocol);
165
181
  }
166
182
  const userRoot = await this.userResources.getUserRoot({ createIfNotExists: true });
183
+ if (this.userResources.authUser !== null && this._ll.hasCapability("publicGrants:v1")) this._currentUserRole = (await this._ll.getSessionInfo()).role;
167
184
  if (this.conf.alternativeRoot === void 0) this._clientRoot = userRoot;
168
185
  else this._clientRoot = await this._withTx("initialization", true, userRoot, async (tx) => {
169
186
  const aFId = {
@@ -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 { 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} 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 { 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 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 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 };\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 };\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 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 /**\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 /**\n * True if the backend honors per-file `permissions` on workdir fill rules\n * (PR #1830 in milaboratory/pl). See `LLPlClient.supportsWritableWorkdirFiles`\n * 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 const userRoot = await this.userResources.getUserRoot({ createIfNotExists: true });\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 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":";;;;;;;;;;;;;;;;AA0CA,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;CAEA,mBAAmCA,aAAAA,cAAc;CACjD,kBAAkCA,aAAAA,cAAc;CAChD,eAA+BA,aAAAA,cAAc;;CAO7C;;CAGA;CAEA,YACE,iBACA,MACA,MAII,CAAC,GACL;EACA,MAAM,OACJ,OAAO,oBAAoB,WAAWC,eAAAA,kBAAkB,eAAe,IAAI;EAE7E,KAAK,kBAAkB,OACrB,eACA,iBACwB;GACxB,IAAI,cAAc,KAAK,eAAe;GACtC,OAAO,MAAMC,kBAAAA,WAAW,MAAM,MAAM;IAAE;IAAM,GAAG;IAAK;GAAc,CAAC;EACrE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K,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","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} 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 { 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 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 };\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 };\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 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 /**\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 const userRoot = await this.userResources.getUserRoot({ createIfNotExists: true });\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 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":";;;;;;;;;;;;;;;;AA2CA,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,mBAAmCA,aAAAA,cAAc;CACjD,kBAAkCA,aAAAA,cAAc;CAChD,eAA+BA,aAAAA,cAAc;;CAO7C;;CAGA;CAEA,YACE,iBACA,MACA,MAII,CAAC,GACL;EACA,MAAM,OACJ,OAAO,oBAAoB,WAAWC,eAAAA,kBAAkB,eAAe,IAAI;EAE7E,KAAK,kBAAkB,OACrB,eACA,iBACwB;GACxB,IAAI,cAAc,KAAK,eAAe;GACtC,OAAO,MAAMC,kBAAAA,WAAW,MAAM,MAAM;IAAE;IAAM,GAAG;IAAK;GAAc,CAAC;EACrE;EAEA,KAAK,UAAU,KAAK;EACpB,KAAK,YAAY,KAAK;EACtB,KAAK,iBAAiB,IAAI,kBAAkBC,cAAAA;EAC5C,KAAK,oBAAoB,IAAIC,UAAAA,SAAS;GACpC,SAAS,KAAK;G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AEA,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"}
@@ -2,7 +2,7 @@ import { SignedResourceId } from "./types.js";
2
2
  import { MaintenanceAPI_License_Response, MaintenanceAPI_Ping_Response } from "../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.js";
3
3
  import { FinalResourceDataPredicate } from "./final.js";
4
4
  import { AllTxStat, TxStat } from "./stat.js";
5
- import { PlTransaction } from "./transaction.js";
5
+ import { PlTransaction, Role } from "./transaction.js";
6
6
  import { AuthOps, PlClientConfig, PlConnectionStatusListener } from "./config.js";
7
7
  import { BackendCapability } from "./capabilities.js";
8
8
  import { WireConnection } from "./wire.js";
@@ -35,6 +35,10 @@ declare class PlClient {
35
35
  /** Stores client root (this abstraction is intended for future implementation of the security model) */
36
36
  private _clientRoot;
37
37
  private _userResources?;
38
+ /** Cached effective role of the authenticated session, fetched once during
39
+ * init via the GetSessionInfo RPC. `null` for an anonymous (no-auth)
40
+ * connection — mirrors {@link authUser}. Read through {@link currentUserRole}. */
41
+ private _currentUserRole;
38
42
  private _txCommittedStat;
39
43
  private _txConflictStat;
40
44
  private _txErrorStat;
@@ -72,10 +76,16 @@ declare class PlClient {
72
76
  get clientRoot(): SignedResourceId;
73
77
  get serverInfo(): MaintenanceAPI_Ping_Response;
74
78
  hasCapability(capability: BackendCapability): boolean;
79
+ /** Effective role of the authenticated session, resolved once during init via
80
+ * the GetSessionInfo RPC and cached. `null` for an anonymous (no-auth)
81
+ * connection, or when the backend predates GetSessionInfo. Mirrors
82
+ * {@link authUser}'s null contract. */
83
+ get currentUserRole(): Role | null;
84
+ /** Login of the authenticated user, or `null` for an anonymous connection. */
85
+ get authUser(): string | null;
75
86
  /**
76
- * True if the backend honors per-file `permissions` on workdir fill rules
77
- * (PR #1830 in milaboratory/pl). See `LLPlClient.supportsWritableWorkdirFiles`
78
- * for the full definition.
87
+ * True if the backend honors per-file `permissions` on workdir fill rules.
88
+ * See {@link LLPlClient.supportsWritableWorkdirFiles} for the full definition.
79
89
  */
80
90
  get supportsWritableWorkdirFiles(): boolean;
81
91
  /** User resources index for discovering data libraries and other shared resources. */
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","names":[],"sources":["../../src/core/client.ts"],"mappings":";;;;;;;;;;;;;;;KAmCY,KAAA,GAAQ,SAAA;EAClB,IAAA;EACA,YAAA,GAAe,YAAY;EAC3B,IAAA;EACA,MAAA;AAAA;;cAYW,QAAA;EAAA,iBACM,OAAA;EAfF;;EAAA,iBAmBE,OAAA;EAjBX;EAAA,iBAoBW,SAAA;EARN;EAAA,iBAWM,mBAAA;EAAA,iBAEA,eAAA;EAAA,QAIT,GAAA;EAAA,YAEI,EAAA;EAiFiB;EAAA,QAzErB,WAAA;EAAA,QAEA,cAAA;EAAA,QAEA,gBAAA;EAAA,QACA,eAAA;EAAA,QACA,YAAA;EA2FwB;EAAA,SApFhB,cAAA,EAAgB,0BAAA;EAiGpB;EAAA,iBA9FK,iBAAA;EAAA,QAEV,WAAA;EAAA,IAmDI,eAAA,IAAmB,MAAA;EAAA,IAInB,cAAA,IAAkB,MAAA;EAAA,IAIlB,WAAA,IAAe,MAAA;EAAA,IA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AKlB,aAAA,CAAc,UAAA,EAAY,iBAAA;EAkPzB;;;;EAAA,IAzOG,eAAA,IAAmB,IAAA;EAxLb;EAAA,IA8LN,QAAA;EAzLM;;;;EAAA,IAkMN,4BAAA;EA7KH;EAAA,IAmLG,aAAA,IAAiB,aAAA;EAhLpB;;EAAA,QA4LM,IAAA;EApLkB;EAqOnB,qBAAA,CAAsB,mBAAA,WAA8B,OAAA;EAAA,QAgBnD,OAAA;EAAA,QA0FA,MAAA;EAUD,WAAA,IACX,IAAA,UACA,IAAA,GAAO,EAAA,EAAI,aAAA,KAAkB,OAAA,CAAQ,CAAA,GACrC,GAAA,GAAK,OAAA,CAAQ,KAAA,IACZ,OAAA,CAAQ,CAAA;EAIE,UAAA,IACX,IAAA,UACA,IAAA,GAAO,EAAA,EAAI,aAAA,KAAkB,OAAA,CAAQ,CAAA,GACrC,GAAA,GAAK,OAAA,CAAQ,KAAA,IACZ,OAAA,CAAQ,CAAA;EAIJ,SAAA,aAAsB,QAAA,EAAU,UAAA,EAAY,kBAAA,CAAmB,GAAA,IAAO,GAAA;EAzSlE;EAkTE,KAAA,IAAK,OAAA;EAAA,OAIE,IAAA,CAClB,eAAA,EAAiB,cAAA,WACjB,IAAA,EAAM,OAAA,EACN,GAAA;IACE,cAAA,GAAiB,0BAAA;IACjB,MAAA,GAAS,QAAA;EAAA,IACL,OAAA,CAAA,QAAA;AAAA"}
@@ -35,6 +35,10 @@ var PlClient = class PlClient {
35
35
  /** Stores client root (this abstraction is intended for future implementation of the security model) */
36
36
  _clientRoot = "";
37
37
  _userResources;
38
+ /** Cached effective role of the authenticated session, fetched once during
39
+ * init via the GetSessionInfo RPC. `null` for an anonymous (no-auth)
40
+ * connection — mirrors {@link authUser}. Read through {@link currentUserRole}. */
41
+ _currentUserRole = null;
38
42
  _txCommittedStat = initialTxStat();
39
43
  _txConflictStat = initialTxStat();
40
44
  _txErrorStat = initialTxStat();
@@ -136,10 +140,22 @@ var PlClient = class PlClient {
136
140
  this.checkInitialized();
137
141
  return this._ll.hasCapability(capability);
138
142
  }
143
+ /** Effective role of the authenticated session, resolved once during init via
144
+ * the GetSessionInfo RPC and cached. `null` for an anonymous (no-auth)
145
+ * connection, or when the backend predates GetSessionInfo. Mirrors
146
+ * {@link authUser}'s null contract. */
147
+ get currentUserRole() {
148
+ this.checkInitialized();
149
+ return this._currentUserRole;
150
+ }
151
+ /** Login of the authenticated user, or `null` for an anonymous connection. */
152
+ get authUser() {
153
+ this.checkInitialized();
154
+ return this.userResources.authUser;
155
+ }
139
156
  /**
140
- * True if the backend honors per-file `permissions` on workdir fill rules
141
- * (PR #1830 in milaboratory/pl). See `LLPlClient.supportsWritableWorkdirFiles`
142
- * for the full definition.
157
+ * True if the backend honors per-file `permissions` on workdir fill rules.
158
+ * See {@link LLPlClient.supportsWritableWorkdirFiles} for the full definition.
143
159
  */
144
160
  get supportsWritableWorkdirFiles() {
145
161
  this.checkInitialized();
@@ -162,6 +178,7 @@ var PlClient = class PlClient {
162
178
  this._ll = await this.buildLLPlClient(true, wireProtocol);
163
179
  }
164
180
  const userRoot = await this.userResources.getUserRoot({ createIfNotExists: true });
181
+ if (this.userResources.authUser !== null && this._ll.hasCapability("publicGrants:v1")) this._currentUserRole = (await this._ll.getSessionInfo()).role;
165
182
  if (this.conf.alternativeRoot === void 0) this._clientRoot = userRoot;
166
183
  else this._clientRoot = await this._withTx("initialization", true, userRoot, async (tx) => {
167
184
  const aFId = {
@@ -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 { 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} 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 { 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 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 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 };\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 };\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 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 /**\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 /**\n * True if the backend honors per-file `permissions` on workdir fill rules\n * (PR #1830 in milaboratory/pl). See `LLPlClient.supportsWritableWorkdirFiles`\n * 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 const userRoot = await this.userResources.getUserRoot({ createIfNotExists: true });\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 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(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GAAW,EAAE,QAAQ,KAAK,YAAY,CAAC;GACjF,aAAa,sBAAsB,UAAU;EAC/C;CACF;CAEA,MAAc,OACZ,MACA,UACA,MACA,MAAsB,CAAC,GACX;EACZ,KAAK,iBAAiB;EACtB,OAAO,MAAM,KAAK,QAAQ,MAAM,UAAU,KAAK,YAAY,MAAM;GAAE,GAAG;GAAK,GAAG;EAAa,CAAC;CAC9F;CAEA,MAAa,YACX,MACA,MACA,MAAsB,CAAC,GACX;EACZ,OAAO,MAAM,KAAK,OAAO,MAAM,MAAM,MAAM;GAAE,GAAG;GAAK,GAAG;EAAa,CAAC;CACxE;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.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} 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 { 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 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 };\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 };\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 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 /**\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 const userRoot = await this.userResources.getUserRoot({ createIfNotExists: true });\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 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":";;;;;;;;;;;;;;AA2CA,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;EAE7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EACZ,OAAO,MAAM,KAAK,OAAO,MAAM,MAAM,MAAM;GAAE,GAAG;GAAK,GAAG;EAAa,CAAC;CACxE;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"}
@@ -13,6 +13,7 @@ function isUnauthenticated(err, nested = false) {
13
13
  if (err instanceof UnauthenticatedError) return true;
14
14
  if (err.name == "RpcError" && err.code == "UNAUTHENTICATED") return true;
15
15
  if (err.name == "RESTError" && err.status.code == 16) return true;
16
+ if (err instanceof PlError && err.status?.code === 16) return true;
16
17
  if (err.cause !== void 0 && !nested) return isUnauthenticated(err.cause, true);
17
18
  return false;
18
19
  }
@@ -1 +1 @@
1
- {"version":3,"file":"errors.cjs","names":["Aborted"],"sources":["../../src/core/errors.ts"],"sourcesContent":["import type { Status } from \"../proto-grpc/github.com/googleapis/googleapis/google/rpc/status\";\nimport { Aborted } from \"@milaboratories/ts-helpers\";\nimport { Code } from \"../proto-grpc/google/rpc/code\";\n\nexport function isConnectionProblem(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if (err instanceof DisconnectedError) return true;\n if ((err as any).name == \"RpcError\" && (err as any).code == \"UNAVAILABLE\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.UNAVAILABLE) return true;\n if ((err as any).cause !== undefined && !nested)\n return isConnectionProblem((err as any).cause, true);\n return false;\n}\n\nexport function isUnauthenticated(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if (err instanceof UnauthenticatedError) return true;\n if ((err as any).name == \"RpcError\" && (err as any).code == \"UNAUTHENTICATED\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.UNAUTHENTICATED)\n return true;\n if ((err as any).cause !== undefined && !nested)\n return isUnauthenticated((err as any).cause, true);\n return false;\n}\n\nexport function isPermissionDenied(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if (err instanceof PermissionDeniedError) return true;\n if ((err as any).name == \"RpcError\" && (err as any).code == \"PERMISSION_DENIED\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.PERMISSION_DENIED)\n return true;\n if ((err as any).cause !== undefined && !nested)\n return isPermissionDenied((err as any).cause, true);\n return false;\n}\n\nexport function isTimeoutError(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if ((err as any).name == \"TimeoutError\") return true;\n if ((err as any).name == \"RpcError\" && (err as any).code == \"DEADLINE_EXCEEDED\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.DEADLINE_EXCEEDED)\n return true;\n if ((err as any).cause !== undefined && !nested) return isTimeoutError((err as any).cause, true);\n return false;\n}\n\nexport function isCancelError(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if ((err as any).name == \"RpcError\" && (err as any).code == \"CANCELLED\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.CANCELLED) return true;\n if ((err as any).cause !== undefined && !nested) return isCancelError((err as any).cause, true);\n return false;\n}\n\nexport function isAbortedError(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if (err instanceof Aborted || (err as any).name == \"AbortError\") return true;\n if ((err as any).code == \"ABORT_ERR\") return true;\n if (err instanceof DOMException && err.code === DOMException.ABORT_ERR) return true; // WebSocket error\n if ((err as any).name == \"RpcError\" && (err as any).code == \"ABORTED\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.ABORTED) return true;\n if ((err as any).cause !== undefined && !nested) return isAbortedError((err as any).cause, true);\n return false;\n}\n\nexport function isTimeoutOrCancelError(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if (isAbortedError(err, true)) return true;\n if (isTimeoutError(err, true)) return true;\n if (isCancelError(err, true)) return true;\n if ((err as any).cause !== undefined && !nested)\n return isTimeoutOrCancelError((err as any).cause, true);\n return false;\n}\n\nexport function isUnimplementedError(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if ((err as any).name == \"RpcError\" && (err as any).code == \"UNIMPLEMENTED\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.UNIMPLEMENTED)\n return true;\n if ((err as any).cause !== undefined && !nested)\n return isUnimplementedError((err as any).cause, true);\n return false;\n}\n\nexport function isNotFoundError(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if ((err as any).name == \"RpcError\" && (err as any).code == \"NOT_FOUND\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.NOT_FOUND) return true;\n if ((err as any).cause !== undefined && !nested) return isNotFoundError((err as any).cause, true);\n return err instanceof RecoverablePlError && err.status.code === PlErrorCodeNotFound;\n}\n\nexport const PlErrorCodeNotFound: number = Code.NOT_FOUND;\n\nexport class PlError extends Error {\n name = \"PlError\";\n constructor(\n public readonly status: Status,\n opts?: ErrorOptions,\n ) {\n super(`code=${status.code} ${status.message}`, opts);\n }\n}\n\nexport function throwPlNotFoundError(message: string): never {\n throw new RecoverablePlError({ code: PlErrorCodeNotFound, message, details: [] });\n}\n\nexport class RecoverablePlError extends PlError {\n name = \"RecoverablePlError\";\n constructor(status: Status) {\n super(status);\n }\n}\n\nexport class UnrecoverablePlError extends PlError {\n name = \"UnrecoverablePlError\";\n constructor(status: Status) {\n super(status);\n }\n}\n\nexport class UnauthenticatedError extends Error {\n name = \"UnauthenticatedError\";\n constructor(message: string) {\n super(\"LoginFailed: \" + message);\n }\n}\n\nexport class PermissionDeniedError extends Error {\n name = \"PermissionDeniedError\";\n constructor(message: string) {\n super(\"PermissionDenied: \" + message);\n }\n}\n\nexport class DisconnectedError extends Error {\n name = \"DisconnectedError\";\n constructor(message: string) {\n super(\"Disconnected: \" + message);\n }\n}\n\nexport class RESTError extends PlError {\n name = \"RESTError\";\n constructor(status: Status, opts?: ErrorOptions) {\n super(status, opts);\n }\n}\n\nexport function rethrowMeaningfulError(error: any, wrapIfUnknown: boolean = false): never {\n if (isUnauthenticated(error)) {\n if (error instanceof UnauthenticatedError) throw error;\n throw new UnauthenticatedError(error.message);\n }\n if (isPermissionDenied(error)) {\n if (error instanceof PermissionDeniedError) throw error;\n throw new PermissionDeniedError(error.message);\n }\n if (isConnectionProblem(error)) {\n if (error instanceof DisconnectedError) throw error;\n throw new DisconnectedError(error.message);\n }\n if (isTimeoutOrCancelError(error)) throw new Aborted(error);\n if (wrapIfUnknown) {\n const message = error.message || String(error) || \"Unknown error\";\n throw new Error(message, { cause: error });\n } else throw error;\n}\n"],"mappings":";;AAIA,SAAgB,oBAAoB,KAAc,SAAkB,OAAgB;CAClF,IAAI,QAAQ,KAAA,KAAa,QAAQ,MAAM,OAAO;CAE9C,IAAI,eAAe,mBAAmB,OAAO;CAC7C,IAAK,IAAY,QAAQ,cAAe,IAAY,QAAQ,eAAe,OAAO;CAClF,IAAK,IAAY,QAAQ,eAAgB,IAAY,OAAO,QAAA,IAA0B,OAAO;CAC7F,IAAK,IAAY,UAAU,KAAA,KAAa,CAAC,QACvC,OAAO,oBAAqB,IAAY,OAAO,IAAI;CACrD,OAAO;AACT;AAEA,SAAgB,kBAAkB,KAAc,SAAkB,OAAgB;CAChF,IAA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kB,KAAK,GAAG;EAC5B,IAAI,iBAAiB,sBAAsB,MAAM;EACjD,MAAM,IAAI,qBAAqB,MAAM,OAAO;CAC9C;CACA,IAAI,mBAAmB,KAAK,GAAG;EAC7B,IAAI,iBAAiB,uBAAuB,MAAM;EAClD,MAAM,IAAI,sBAAsB,MAAM,OAAO;CAC/C;CACA,IAAI,oBAAoB,KAAK,GAAG;EAC9B,IAAI,iBAAiB,mBAAmB,MAAM;EAC9C,MAAM,IAAI,kBAAkB,MAAM,OAAO;CAC3C;CACA,IAAI,uBAAuB,KAAK,GAAG,MAAM,IAAIA,2BAAAA,QAAQ,KAAK;CAC1D,IAAI,eAAe;EACjB,MAAM,UAAU,MAAM,WAAW,OAAO,KAAK,KAAK;EAClD,MAAM,IAAI,MAAM,SAAS,EAAE,OAAO,MAAM,CAAC;CAC3C,OAAO,MAAM;AACf"}
1
+ {"version":3,"file":"errors.cjs","names":["Aborted"],"sources":["../../src/core/errors.ts"],"sourcesContent":["import type { Status } from \"../proto-grpc/github.com/googleapis/googleapis/google/rpc/status\";\nimport { Aborted } from \"@milaboratories/ts-helpers\";\nimport { Code } from \"../proto-grpc/google/rpc/code\";\n\nexport function isConnectionProblem(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if (err instanceof DisconnectedError) return true;\n if ((err as any).name == \"RpcError\" && (err as any).code == \"UNAVAILABLE\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.UNAVAILABLE) return true;\n if ((err as any).cause !== undefined && !nested)\n return isConnectionProblem((err as any).cause, true);\n return false;\n}\n\nexport function isUnauthenticated(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if (err instanceof UnauthenticatedError) return true;\n if ((err as any).name == \"RpcError\" && (err as any).code == \"UNAUTHENTICATED\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.UNAUTHENTICATED)\n return true;\n // PlError (e.g. UnrecoverablePlError from a failed streaming tx) carries the status code numerically.\n if (err instanceof PlError && err.status?.code === Code.UNAUTHENTICATED) return true;\n if ((err as any).cause !== undefined && !nested)\n return isUnauthenticated((err as any).cause, true);\n return false;\n}\n\nexport function isPermissionDenied(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if (err instanceof PermissionDeniedError) return true;\n if ((err as any).name == \"RpcError\" && (err as any).code == \"PERMISSION_DENIED\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.PERMISSION_DENIED)\n return true;\n if ((err as any).cause !== undefined && !nested)\n return isPermissionDenied((err as any).cause, true);\n return false;\n}\n\nexport function isTimeoutError(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if ((err as any).name == \"TimeoutError\") return true;\n if ((err as any).name == \"RpcError\" && (err as any).code == \"DEADLINE_EXCEEDED\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.DEADLINE_EXCEEDED)\n return true;\n if ((err as any).cause !== undefined && !nested) return isTimeoutError((err as any).cause, true);\n return false;\n}\n\nexport function isCancelError(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if ((err as any).name == \"RpcError\" && (err as any).code == \"CANCELLED\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.CANCELLED) return true;\n if ((err as any).cause !== undefined && !nested) return isCancelError((err as any).cause, true);\n return false;\n}\n\nexport function isAbortedError(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if (err instanceof Aborted || (err as any).name == \"AbortError\") return true;\n if ((err as any).code == \"ABORT_ERR\") return true;\n if (err instanceof DOMException && err.code === DOMException.ABORT_ERR) return true; // WebSocket error\n if ((err as any).name == \"RpcError\" && (err as any).code == \"ABORTED\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.ABORTED) return true;\n if ((err as any).cause !== undefined && !nested) return isAbortedError((err as any).cause, true);\n return false;\n}\n\nexport function isTimeoutOrCancelError(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if (isAbortedError(err, true)) return true;\n if (isTimeoutError(err, true)) return true;\n if (isCancelError(err, true)) return true;\n if ((err as any).cause !== undefined && !nested)\n return isTimeoutOrCancelError((err as any).cause, true);\n return false;\n}\n\nexport function isUnimplementedError(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if ((err as any).name == \"RpcError\" && (err as any).code == \"UNIMPLEMENTED\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.UNIMPLEMENTED)\n return true;\n if ((err as any).cause !== undefined && !nested)\n return isUnimplementedError((err as any).cause, true);\n return false;\n}\n\nexport function isNotFoundError(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if ((err as any).name == \"RpcError\" && (err as any).code == \"NOT_FOUND\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.NOT_FOUND) return true;\n if ((err as any).cause !== undefined && !nested) return isNotFoundError((err as any).cause, true);\n return err instanceof RecoverablePlError && err.status.code === PlErrorCodeNotFound;\n}\n\nexport const PlErrorCodeNotFound: number = Code.NOT_FOUND;\n\nexport class PlError extends Error {\n name = \"PlError\";\n constructor(\n public readonly status: Status,\n opts?: ErrorOptions,\n ) {\n super(`code=${status.code} ${status.message}`, opts);\n }\n}\n\nexport function throwPlNotFoundError(message: string): never {\n throw new RecoverablePlError({ code: PlErrorCodeNotFound, message, details: [] });\n}\n\nexport class RecoverablePlError extends PlError {\n name = \"RecoverablePlError\";\n constructor(status: Status) {\n super(status);\n }\n}\n\nexport class UnrecoverablePlError extends PlError {\n name = \"UnrecoverablePlError\";\n constructor(status: Status) {\n super(status);\n }\n}\n\nexport class UnauthenticatedError extends Error {\n name = \"UnauthenticatedError\";\n constructor(message: string) {\n super(\"LoginFailed: \" + message);\n }\n}\n\nexport class PermissionDeniedError extends Error {\n name = \"PermissionDeniedError\";\n constructor(message: string) {\n super(\"PermissionDenied: \" + message);\n }\n}\n\nexport class DisconnectedError extends Error {\n name = \"DisconnectedError\";\n constructor(message: string) {\n super(\"Disconnected: \" + message);\n }\n}\n\nexport class RESTError extends PlError {\n name = \"RESTError\";\n constructor(status: Status, opts?: ErrorOptions) {\n super(status, opts);\n }\n}\n\nexport function rethrowMeaningfulError(error: any, wrapIfUnknown: boolean = false): never {\n if (isUnauthenticated(error)) {\n if (error instanceof UnauthenticatedError) throw error;\n throw new UnauthenticatedError(error.message);\n }\n if (isPermissionDenied(error)) {\n if (error instanceof PermissionDeniedError) throw error;\n throw new PermissionDeniedError(error.message);\n }\n if (isConnectionProblem(error)) {\n if (error instanceof DisconnectedError) throw error;\n throw new DisconnectedError(error.message);\n }\n if (isTimeoutOrCancelError(error)) throw new Aborted(error);\n if (wrapIfUnknown) {\n const message = error.message || String(error) || \"Unknown error\";\n throw new Error(message, { cause: error });\n } else throw error;\n}\n"],"mappings":";;AAIA,SAAgB,oBAAoB,KAAc,SAAkB,OAAgB;CAClF,IAAI,QAAQ,KAAA,KAAa,QAAQ,MAAM,OAAO;CAE9C,IAAI,eAAe,mBAAmB,OAAO;CAC7C,IAAK,IAAY,QAAQ,cAAe,IAAY,QAAQ,eAAe,OAAO;CAClF,IAAK,IAAY,QAAQ,eAAgB,IAAY,OAAO,QAAA,IAA0B,OAAO;CAC7F,IAAK,IAAY,UAAU,KAAA,KAAa,CAAC,QACvC,OAAO,oBAAqB,IAAY,OAAO,IAAI;CACrD,OAAO;AACT;AAEA,SAAgB,kBAAkB,KAAc,SAAkB,OAAgB;CAChF,IAAI,QAAQ,KAAA,KAAa,QAAQ,MAAM,OAAO;CAE9C,IAAI,eAAe,sBAAsB,OAAO;CAChD,IAAK,IAAY,QAAQ,cAAe,IAAY,QAAQ,mBAAmB,OAAO;CACtF,IAAK,IAAY,QAAQ,eAAgB,IAAY,OAAO,QAAA,IAC1D,OAAO;CAET,IAAI,eAAe,WAAW,IAAI,QAAQ,SAAA,IAA+B,OAAO;CAChF,IAAK,IAAY,UAAU,KAAA,KAAa,CAA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Y,OAAA;AAAA;AAAA,cAKD,SAAA,SAAkB,OAAA;EAC7B,IAAA;cACY,MAAA,EAAQ,MAAA,EAAQ,IAAA,GAAO,YAAA;AAAA;AAAA,iBAKrB,sBAAA,CAAuB,KAAA,OAAY,aAA8B"}
@@ -13,6 +13,7 @@ function isUnauthenticated(err, nested = false) {
13
13
  if (err instanceof UnauthenticatedError) return true;
14
14
  if (err.name == "RpcError" && err.code == "UNAUTHENTICATED") return true;
15
15
  if (err.name == "RESTError" && err.status.code == 16) return true;
16
+ if (err instanceof PlError && err.status?.code === 16) return true;
16
17
  if (err.cause !== void 0 && !nested) return isUnauthenticated(err.cause, true);
17
18
  return false;
18
19
  }
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","names":[],"sources":["../../src/core/errors.ts"],"sourcesContent":["import type { Status } from \"../proto-grpc/github.com/googleapis/googleapis/google/rpc/status\";\nimport { Aborted } from \"@milaboratories/ts-helpers\";\nimport { Code } from \"../proto-grpc/google/rpc/code\";\n\nexport function isConnectionProblem(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if (err instanceof DisconnectedError) return true;\n if ((err as any).name == \"RpcError\" && (err as any).code == \"UNAVAILABLE\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.UNAVAILABLE) return true;\n if ((err as any).cause !== undefined && !nested)\n return isConnectionProblem((err as any).cause, true);\n return false;\n}\n\nexport function isUnauthenticated(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if (err instanceof UnauthenticatedError) return true;\n if ((err as any).name == \"RpcError\" && (err as any).code == \"UNAUTHENTICATED\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.UNAUTHENTICATED)\n return true;\n if ((err as any).cause !== undefined && !nested)\n return isUnauthenticated((err as any).cause, true);\n return false;\n}\n\nexport function isPermissionDenied(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if (err instanceof PermissionDeniedError) return true;\n if ((err as any).name == \"RpcError\" && (err as any).code == \"PERMISSION_DENIED\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.PERMISSION_DENIED)\n return true;\n if ((err as any).cause !== undefined && !nested)\n return isPermissionDenied((err as any).cause, true);\n return false;\n}\n\nexport function isTimeoutError(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if ((err as any).name == \"TimeoutError\") return true;\n if ((err as any).name == \"RpcError\" && (err as any).code == \"DEADLINE_EXCEEDED\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.DEADLINE_EXCEEDED)\n return true;\n if ((err as any).cause !== undefined && !nested) return isTimeoutError((err as any).cause, true);\n return false;\n}\n\nexport function isCancelError(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if ((err as any).name == \"RpcError\" && (err as any).code == \"CANCELLED\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.CANCELLED) return true;\n if ((err as any).cause !== undefined && !nested) return isCancelError((err as any).cause, true);\n return false;\n}\n\nexport function isAbortedError(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if (err instanceof Aborted || (err as any).name == \"AbortError\") return true;\n if ((err as any).code == \"ABORT_ERR\") return true;\n if (err instanceof DOMException && err.code === DOMException.ABORT_ERR) return true; // WebSocket error\n if ((err as any).name == \"RpcError\" && (err as any).code == \"ABORTED\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.ABORTED) return true;\n if ((err as any).cause !== undefined && !nested) return isAbortedError((err as any).cause, true);\n return false;\n}\n\nexport function isTimeoutOrCancelError(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if (isAbortedError(err, true)) return true;\n if (isTimeoutError(err, true)) return true;\n if (isCancelError(err, true)) return true;\n if ((err as any).cause !== undefined && !nested)\n return isTimeoutOrCancelError((err as any).cause, true);\n return false;\n}\n\nexport function isUnimplementedError(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if ((err as any).name == \"RpcError\" && (err as any).code == \"UNIMPLEMENTED\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.UNIMPLEMENTED)\n return true;\n if ((err as any).cause !== undefined && !nested)\n return isUnimplementedError((err as any).cause, true);\n return false;\n}\n\nexport function isNotFoundError(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if ((err as any).name == \"RpcError\" && (err as any).code == \"NOT_FOUND\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.NOT_FOUND) return true;\n if ((err as any).cause !== undefined && !nested) return isNotFoundError((err as any).cause, true);\n return err instanceof RecoverablePlError && err.status.code === PlErrorCodeNotFound;\n}\n\nexport const PlErrorCodeNotFound: number = Code.NOT_FOUND;\n\nexport class PlError extends Error {\n name = \"PlError\";\n constructor(\n public readonly status: Status,\n opts?: ErrorOptions,\n ) {\n super(`code=${status.code} ${status.message}`, opts);\n }\n}\n\nexport function throwPlNotFoundError(message: string): never {\n throw new RecoverablePlError({ code: PlErrorCodeNotFound, message, details: [] });\n}\n\nexport class RecoverablePlError extends PlError {\n name = \"RecoverablePlError\";\n constructor(status: Status) {\n super(status);\n }\n}\n\nexport class UnrecoverablePlError extends PlError {\n name = \"UnrecoverablePlError\";\n constructor(status: Status) {\n super(status);\n }\n}\n\nexport class UnauthenticatedError extends Error {\n name = \"UnauthenticatedError\";\n constructor(message: string) {\n super(\"LoginFailed: \" + message);\n }\n}\n\nexport class PermissionDeniedError extends Error {\n name = \"PermissionDeniedError\";\n constructor(message: string) {\n super(\"PermissionDenied: \" + message);\n }\n}\n\nexport class DisconnectedError extends Error {\n name = \"DisconnectedError\";\n constructor(message: string) {\n super(\"Disconnected: \" + message);\n }\n}\n\nexport class RESTError extends PlError {\n name = \"RESTError\";\n constructor(status: Status, opts?: ErrorOptions) {\n super(status, opts);\n }\n}\n\nexport function rethrowMeaningfulError(error: any, wrapIfUnknown: boolean = false): never {\n if (isUnauthenticated(error)) {\n if (error instanceof UnauthenticatedError) throw error;\n throw new UnauthenticatedError(error.message);\n }\n if (isPermissionDenied(error)) {\n if (error instanceof PermissionDeniedError) throw error;\n throw new PermissionDeniedError(error.message);\n }\n if (isConnectionProblem(error)) {\n if (error instanceof DisconnectedError) throw error;\n throw new DisconnectedError(error.message);\n }\n if (isTimeoutOrCancelError(error)) throw new Aborted(error);\n if (wrapIfUnknown) {\n const message = error.message || String(error) || \"Unknown error\";\n throw new Error(message, { cause: error });\n } else throw error;\n}\n"],"mappings":";;AAIA,SAAgB,oBAAoB,KAAc,SAAkB,OAAgB;CAClF,IAAI,QAAQ,KAAA,KAAa,QAAQ,MAAM,OAAO;CAE9C,IAAI,eAAe,mBAAmB,OAAO;CAC7C,IAAK,IAAY,QAAQ,cAAe,IAAY,QAAQ,eAAe,OAAO;CAClF,IAAK,IAAY,QAAQ,eAAgB,IAAY,OAAO,QAAA,IAA0B,OAAO;CAC7F,IAAK,IAAY,UAAU,KAAA,KAAa,CAAC,QACvC,OAAO,oBAAqB,IAAY,OAAO,IAAI;CACrD,OAAO;AACT;AAEA,SAAgB,kBAAkB,KAAc,SAAkB,OAAgB;CAChF,IAAI,QAAQ,KAAA,KAAa,QAAQ,MAAM,OAAO;CAE9C,IAAI,eAAe,sBAAsB,OAAO;CAChD,IAAK,IAAY,QAAQ,cAAe,IAAY,QAAQ,mBAAmB,OAAO;CACtF,IAAK,IAAY,QAAQ,eAAgB,IAAY,OAAO,QAAA,IAC1D,OAAO;CACT,IAAK,IAAY,UAAU,KAAA,KAAa,CAAC,QACvC,OAAO,kBAAmB,IAAY,OAAO,IAAI;CACnD,OAAO;AACT;AAEA,SAAgB,mBAAmB,KAAc,SAAkB,OAAgB;CACjF,IAAI,QAAQ,KAAA,KAAa,QAAQ,MAAM,OAAO;CAE9C,IAAI,eAAe,uBAAuB,OAAO;CACjD,IAAK,IAAY,QAAQ,cAAe,IAAY,QAAQ,qBAAqB,OAAO;CACxF,IAAK,IAAY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C3C,OAAO,MAAM;AACf"}
1
+ {"version":3,"file":"errors.js","names":[],"sources":["../../src/core/errors.ts"],"sourcesContent":["import type { Status } from \"../proto-grpc/github.com/googleapis/googleapis/google/rpc/status\";\nimport { Aborted } from \"@milaboratories/ts-helpers\";\nimport { Code } from \"../proto-grpc/google/rpc/code\";\n\nexport function isConnectionProblem(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if (err instanceof DisconnectedError) return true;\n if ((err as any).name == \"RpcError\" && (err as any).code == \"UNAVAILABLE\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.UNAVAILABLE) return true;\n if ((err as any).cause !== undefined && !nested)\n return isConnectionProblem((err as any).cause, true);\n return false;\n}\n\nexport function isUnauthenticated(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if (err instanceof UnauthenticatedError) return true;\n if ((err as any).name == \"RpcError\" && (err as any).code == \"UNAUTHENTICATED\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.UNAUTHENTICATED)\n return true;\n // PlError (e.g. UnrecoverablePlError from a failed streaming tx) carries the status code numerically.\n if (err instanceof PlError && err.status?.code === Code.UNAUTHENTICATED) return true;\n if ((err as any).cause !== undefined && !nested)\n return isUnauthenticated((err as any).cause, true);\n return false;\n}\n\nexport function isPermissionDenied(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if (err instanceof PermissionDeniedError) return true;\n if ((err as any).name == \"RpcError\" && (err as any).code == \"PERMISSION_DENIED\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.PERMISSION_DENIED)\n return true;\n if ((err as any).cause !== undefined && !nested)\n return isPermissionDenied((err as any).cause, true);\n return false;\n}\n\nexport function isTimeoutError(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if ((err as any).name == \"TimeoutError\") return true;\n if ((err as any).name == \"RpcError\" && (err as any).code == \"DEADLINE_EXCEEDED\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.DEADLINE_EXCEEDED)\n return true;\n if ((err as any).cause !== undefined && !nested) return isTimeoutError((err as any).cause, true);\n return false;\n}\n\nexport function isCancelError(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if ((err as any).name == \"RpcError\" && (err as any).code == \"CANCELLED\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.CANCELLED) return true;\n if ((err as any).cause !== undefined && !nested) return isCancelError((err as any).cause, true);\n return false;\n}\n\nexport function isAbortedError(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if (err instanceof Aborted || (err as any).name == \"AbortError\") return true;\n if ((err as any).code == \"ABORT_ERR\") return true;\n if (err instanceof DOMException && err.code === DOMException.ABORT_ERR) return true; // WebSocket error\n if ((err as any).name == \"RpcError\" && (err as any).code == \"ABORTED\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.ABORTED) return true;\n if ((err as any).cause !== undefined && !nested) return isAbortedError((err as any).cause, true);\n return false;\n}\n\nexport function isTimeoutOrCancelError(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if (isAbortedError(err, true)) return true;\n if (isTimeoutError(err, true)) return true;\n if (isCancelError(err, true)) return true;\n if ((err as any).cause !== undefined && !nested)\n return isTimeoutOrCancelError((err as any).cause, true);\n return false;\n}\n\nexport function isUnimplementedError(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if ((err as any).name == \"RpcError\" && (err as any).code == \"UNIMPLEMENTED\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.UNIMPLEMENTED)\n return true;\n if ((err as any).cause !== undefined && !nested)\n return isUnimplementedError((err as any).cause, true);\n return false;\n}\n\nexport function isNotFoundError(err: unknown, nested: boolean = false): boolean {\n if (err === undefined || err === null) return false;\n\n if ((err as any).name == \"RpcError\" && (err as any).code == \"NOT_FOUND\") return true;\n if ((err as any).name == \"RESTError\" && (err as any).status.code == Code.NOT_FOUND) return true;\n if ((err as any).cause !== undefined && !nested) return isNotFoundError((err as any).cause, true);\n return err instanceof RecoverablePlError && err.status.code === PlErrorCodeNotFound;\n}\n\nexport const PlErrorCodeNotFound: number = Code.NOT_FOUND;\n\nexport class PlError extends Error {\n name = \"PlError\";\n constructor(\n public readonly status: Status,\n opts?: ErrorOptions,\n ) {\n super(`code=${status.code} ${status.message}`, opts);\n }\n}\n\nexport function throwPlNotFoundError(message: string): never {\n throw new RecoverablePlError({ code: PlErrorCodeNotFound, message, details: [] });\n}\n\nexport class RecoverablePlError extends PlError {\n name = \"RecoverablePlError\";\n constructor(status: Status) {\n super(status);\n }\n}\n\nexport class UnrecoverablePlError extends PlError {\n name = \"UnrecoverablePlError\";\n constructor(status: Status) {\n super(status);\n }\n}\n\nexport class UnauthenticatedError extends Error {\n name = \"UnauthenticatedError\";\n constructor(message: string) {\n super(\"LoginFailed: \" + message);\n }\n}\n\nexport class PermissionDeniedError extends Error {\n name = \"PermissionDeniedError\";\n constructor(message: string) {\n super(\"PermissionDenied: \" + message);\n }\n}\n\nexport class DisconnectedError extends Error {\n name = \"DisconnectedError\";\n constructor(message: string) {\n super(\"Disconnected: \" + message);\n }\n}\n\nexport class RESTError extends PlError {\n name = \"RESTError\";\n constructor(status: Status, opts?: ErrorOptions) {\n super(status, opts);\n }\n}\n\nexport function rethrowMeaningfulError(error: any, wrapIfUnknown: boolean = false): never {\n if (isUnauthenticated(error)) {\n if (error instanceof UnauthenticatedError) throw error;\n throw new UnauthenticatedError(error.message);\n }\n if (isPermissionDenied(error)) {\n if (error instanceof PermissionDeniedError) throw error;\n throw new PermissionDeniedError(error.message);\n }\n if (isConnectionProblem(error)) {\n if (error instanceof DisconnectedError) throw error;\n throw new DisconnectedError(error.message);\n }\n if (isTimeoutOrCancelError(error)) throw new Aborted(error);\n if (wrapIfUnknown) {\n const message = error.message || String(error) || \"Unknown error\";\n throw new Error(message, { cause: error });\n } else throw error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a,uBAAb,cAA0C,MAAM;CAC9C,OAAO;CACP,YAAY,SAAiB;EAC3B,MAAM,kBAAkB,OAAO;CACjC;AACF;AAEA,IAAa,wBAAb,cAA2C,MAAM;CAC/C,OAAO;CACP,YAAY,SAAiB;EAC3B,MAAM,uBAAuB,OAAO;CACtC;AACF;AAEA,IAAa,oBAAb,cAAuC,MAAM;CAC3C,OAAO;CACP,YAAY,SAAiB;EAC3B,MAAM,mBAAmB,OAAO;CAClC;AACF;AAEA,IAAa,YAAb,cAA+B,QAAQ;CACrC,OAAO;CACP,YAAY,QAAgB,MAAqB;EAC/C,MAAM,QAAQ,IAAI;CACpB;AACF;AAEA,SAAgB,uBAAuB,OAAY,gBAAyB,OAAc;CACxF,IAAI,kBAAkB,KAAK,GAAG;EAC5B,IAAI,iBAAiB,sBAAsB,MAAM;EACjD,MAAM,IAAI,qBAAqB,MAAM,OAAO;CAC9C;CACA,IAAI,mBAAmB,KAAK,GAAG;EAC7B,IAAI,iBAAiB,uBAAuB,MAAM;EAClD,MAAM,IAAI,sBAAsB,MAAM,OAAO;CAC/C;CACA,IAAI,oBAAoB,KAAK,GAAG;EAC9B,IAAI,iBAAiB,mBAAmB,MAAM;EAC9C,MAAM,IAAI,kBAAkB,MAAM,OAAO;CAC3C;CACA,IAAI,uBAAuB,KAAK,GAAG,MAAM,IAAI,QAAQ,KAAK;CAC1D,IAAI,eAAe;EACjB,MAAM,UAAU,MAAM,WAAW,OAAO,KAAK,KAAK;EAClD,MAAM,IAAI,MAAM,SAAS,EAAE,OAAO,MAAM,CAAC;CAC3C,OAAO,MAAM;AACf"}
@@ -56,7 +56,10 @@ const DefaultFinalResourceDataPredicate = (r) => {
56
56
  case _milaboratories_pl_model_common.ResourceTypeName.WorkingDirectory: return true;
57
57
  case _milaboratories_pl_model_common.ResourceTypeName.UserProject:
58
58
  case _milaboratories_pl_model_common.ResourceTypeName.Projects:
59
- case _milaboratories_pl_model_common.ResourceTypeName.ClientRoot: return false;
59
+ case _milaboratories_pl_model_common.ResourceTypeName.ClientRoot:
60
+ case _milaboratories_pl_model_common.ResourceTypeName.SharingOutbox:
61
+ case _milaboratories_pl_model_common.ResourceTypeName.SharingState:
62
+ case _milaboratories_pl_model_common.ResourceTypeName.SharedEnvelope: return false;
60
63
  default: if (r.type.name.startsWith(_milaboratories_pl_model_common.ResourceTypePrefix.Blob) || r.type.name.startsWith(_milaboratories_pl_model_common.ResourceTypePrefix.LS) || r.type.name.startsWith(_milaboratories_pl_model_common.ResourceTypePrefix.WorkingDirectory) || r.type.name.startsWith(_milaboratories_pl_model_common.ResourceTypePrefix.StorageSpaceAllocation)) return true;
61
64
  else if (r.type.name.startsWith(_milaboratories_pl_model_common.ResourceTypePrefix.BlobUpload) || r.type.name.startsWith(_milaboratories_pl_model_common.ResourceTypePrefix.BlobIndex)) return readyAndHasAllOutputsFilled(r);
62
65
  else if (r.type.name.startsWith(_milaboratories_pl_model_common.ResourceTypePrefix.PColumnData)) return readyOrDuplicateOrError(r);