Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .secrets.baseline

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

76 changes: 72 additions & 4 deletions lib/cloudantBaseService.ts
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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';
Expand All @@ -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)
*/
Expand Down Expand Up @@ -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) => {
Expand All @@ -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.
*
Expand Down Expand Up @@ -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<any> {
let operationId = null;
Expand All @@ -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 (
Expand Down
101 changes: 100 additions & 1 deletion test/unit/cloudantBaseService.test.js
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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);
});
});
});