diff --git a/.secrets.baseline b/.secrets.baseline index a08d503d4..4f5a7bde5 100644 --- a/.secrets.baseline +++ b/.secrets.baseline @@ -3,7 +3,7 @@ "files": "^package-lock.json$|^.secrets.baseline$", "lines": "(?i)^\\s*\"(?:transaction|x-couch-request|x-request)-id\": \"[^\"]+\",?$|^\\s*\"(?:last_|update_|purge_|checkpointed_source_|source_|through_)?seq\": \"[^\"]+\",?$|^\\s*\"(?:doc_)?id\": \"[^\"]+\",?$|^\\s*\"(?:signature|name|uuid)\": \"[^\"]+\",?$" }, - "generated_at": "2026-11-11T11:54:01Z", + "generated_at": "2026-11-24T17:38:09Z", "plugins_used": [ { "name": "AWSKeyDetector" @@ -222,7 +222,7 @@ "hashed_secret": "fc5177639d71196391dd9f4997bc4f240eb29366", "is_secret": false, "is_verified": false, - "line_number": 185, + "line_number": 240, "type": "Secret Keyword", "verified_result": null } diff --git a/lib/cloudantBaseService.ts b/lib/cloudantBaseService.ts index b8fbc7f9d..f2686931b 100644 --- a/lib/cloudantBaseService.ts +++ b/lib/cloudantBaseService.ts @@ -1,5 +1,5 @@ /** - * © Copyright IBM Corporation 2020, 2024. All Rights Reserved. + * © Copyright IBM Corporation 2020, 2026. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,12 @@ /* eslint max-classes-per-file: 0 */ -import { Authenticator, BaseService, UserOptions } from 'ibm-cloud-sdk-core'; +import { + Authenticator, + BaseService, + getNewLogger, + UserOptions, +} from 'ibm-cloud-sdk-core'; import { CookieJar } from 'tough-cookie'; import { Agent as HttpsAgent } from 'node:https'; import { Agent as HttpAgent } from 'node:http'; @@ -26,6 +31,19 @@ import { errorResponseStreamConverter, } from './errorResponseInterceptor'; +const logger = getNewLogger('cloudant-node-sdk'); +logger.warn.enabled = true; +logger.error.enabled = true; + +const GEN2_KNOWN_ISSUES_URL = + 'https://github.com/IBM/cloudant-node-sdk/blob/main/KNOWN_ISSUES.md#cloudant-gen-2-compatibility'; + +/** + * Set to "true" to throw an error, in addition to logging a warning, + * when an operation that is unavailable for Gen 2 is used. + */ +const CLOUDANT_SDK_GEN1_ERRORS = 'CLOUDANT_SDK_GEN1_ERRORS'; + /** * Set default timeout to 2.5 minutes (= 150 000 ms) */ @@ -67,7 +85,30 @@ const attIdRule = { operationIds: AttachmentOperations, }; -const validationRules = [docIdRule, attIdRule]; +/** + * Gen 1 operations are not available for Gen 2. + */ +const Gen1OnlyOperations = [ + 'getActivityTrackerEvents', + 'getCapacityDatabasesInformation', + 'getCapacityThroughputInformation', + 'getCorsInformation', + 'getCurrentDatabasesInformation', + 'getCurrentThroughputInformation', + 'postActivityTrackerEvents', + 'postApiKeys', + 'putCapacityThroughputConfiguration', + 'putCloudantSecurityConfiguration', + 'putCorsConfiguration', +]; + +const gen1OnlyRule = { + pathSegment: '', + errorParameterName: '', + operationIds: Gen1OnlyOperations, +}; + +const validationRules = [docIdRule, attIdRule, gen1OnlyRule]; const rulesByOperation = {}; validationRules.forEach((rule) => { rule.operationIds.forEach((operationId) => { @@ -90,6 +131,20 @@ class InvalidArgumentValueError extends Error { code?: string; } +/** + * Error for operations that are unavailable for Gen 2. + */ +class UnsupportedOperationError extends Error { + code?: string; +} + +/** + * Whether the CLOUDANT_SDK_GEN1_ERRORS environment variable is set to "true". + */ +function isGen1ErrorEnabled(): boolean { + return process.env[CLOUDANT_SDK_GEN1_ERRORS]?.toLowerCase() === 'true'; +} + /** * Cloudant specific service that extends the base service functions. * @@ -189,7 +244,8 @@ export abstract class CloudantBaseService extends BaseService { } /** - * Extend createRequest to handle document and attachment validation. + * Extend createRequest to handle document and attachment validation + * and to warn about operations that are unavailable in Gen 2. */ protected createRequest(parameters: any): Promise { let operationId = null; @@ -206,6 +262,18 @@ export abstract class CloudantBaseService extends BaseService { operationId != null && Object.keys(rulesByOperation).includes(operationId) ) { + // Warn about Gen 1 operations that are unavailable for Gen 2 plans + if (rulesByOperation[operationId].includes(gen1OnlyRule)) { + const message = + `The operation ${operationId} is unavailable for Gen 2 Cloudant plans. ` + + `See ${GEN2_KNOWN_ISSUES_URL} for more information.`; + logger.warn(message); + if (isGen1ErrorEnabled()) { + const err = new UnsupportedOperationError(message); + err.code = 'CLOUDANT_SDK_UNSUPPORTED_OPERATION'; + return Promise.reject(err); + } + } const violatedRules = rulesByOperation[operationId].filter((rule) => { // get the path segment e.g. doc_id from the response's path object if ( diff --git a/test/unit/cloudantBaseService.test.js b/test/unit/cloudantBaseService.test.js index 42942b3d6..07d55c3ce 100644 --- a/test/unit/cloudantBaseService.test.js +++ b/test/unit/cloudantBaseService.test.js @@ -1,5 +1,5 @@ /** - * © Copyright IBM Corporation 2020, 2022. All Rights Reserved. + * © Copyright IBM Corporation 2020, 2026. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -269,4 +269,103 @@ describe('Test CloudantBaseService', () => { assert.strictEqual(service.baseOptions.httpsAgent.keepAlive, true); }); }); + + describe('Gen 1 only operations', () => { + const serviceUrl = 'https://example.invalid'; + const gen1ErrorsVar = 'CLOUDANT_SDK_GEN1_ERRORS'; + const knownIssuesUrl = + 'https://github.com/IBM/cloudant-node-sdk/blob/main/KNOWN_ISSUES.md#cloudant-gen-2-compatibility'; + const gen1Operations = [ + 'getActivityTrackerEvents', + 'getCapacityDatabasesInformation', + 'getCapacityThroughputInformation', + 'getCorsInformation', + 'getCurrentDatabasesInformation', + 'getCurrentThroughputInformation', + 'postActivityTrackerEvents', + 'postApiKeys', + 'putCapacityThroughputConfiguration', + 'putCloudantSecurityConfiguration', + 'putCorsConfiguration', + ]; + const expectedMessage = (operationId) => + `The operation ${operationId} is unavailable for Gen 2 Cloudant plans. ` + + `See ${knownIssuesUrl} for more information.`; + + const params = (operationId) => ({ + defaultOptions: { + serviceUrl, + headers: { + 'X-IBMCloud-SDK-Analytics': `service_name=cloudant;service_version=v1;operation_id=${operationId}`, + }, + }, + options: { url: '/example', method: 'GET' }, + }); + + let originalGen1Errors; + let sendRequestStub; + let service; + + beforeEach(() => { + originalGen1Errors = process.env[gen1ErrorsVar]; + delete process.env[gen1ErrorsVar]; + service = new CloudantBaseService({ + authenticator: new NoAuthAuthenticator(), + serviceUrl, + }); + sendRequestStub = sinon.stub().resolves({ result: {} }); + service.requestWrapperInstance.sendRequest = sendRequestStub; + }); + + afterEach(() => { + if (originalGen1Errors === undefined) { + delete process.env[gen1ErrorsVar]; + } else { + process.env[gen1ErrorsVar] = originalGen1Errors; + } + sinon.restore(); + }); + + gen1Operations.forEach((operationId) => { + it(`Throws for ${operationId} when errors are enabled`, async () => { + process.env[gen1ErrorsVar] = 'true'; + await assert.rejects(service.createRequest(params(operationId)), { + code: 'CLOUDANT_SDK_UNSUPPORTED_OPERATION', + message: expectedMessage(operationId), + }); + assert.ok(sendRequestStub.notCalled); + }); + }); + + it('Reads the errors setting case insensitively', async () => { + process.env[gen1ErrorsVar] = 'TRUE'; + await assert.rejects( + service.createRequest(params('getCorsInformation')), + { code: 'CLOUDANT_SDK_UNSUPPORTED_OPERATION' } + ); + }); + + it('Still sends the request when errors are not enabled', async () => { + await service.createRequest(params('getCorsInformation')); + assert.ok(sendRequestStub.calledOnce); + }); + + it('Still sends the request when errors are set to false', async () => { + process.env[gen1ErrorsVar] = 'false'; + await service.createRequest(params('getCorsInformation')); + assert.ok(sendRequestStub.calledOnce); + }); + + it('Does not throw for other operations when errors are enabled', async () => { + process.env[gen1ErrorsVar] = 'true'; + await service.createRequest(params('getAllDbs')); + assert.ok(sendRequestStub.calledOnce); + }); + + it('Does not throw for an operation with a similar name', async () => { + process.env[gen1ErrorsVar] = 'true'; + await service.createRequest(params('getCorsInformationFake')); + assert.ok(sendRequestStub.calledOnce); + }); + }); });