Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[NAN-676] enforce cap when activating a script #1953

Merged
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
19 changes: 18 additions & 1 deletion packages/server/lib/controllers/flow.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { IncomingPreBuiltFlowConfig, FlowDownloadBody, StandardNangoConfig
import {
flowService,
accountService,
connectionService,
getEnvironmentAndAccountId,
errorManager,
configService,
Expand Down Expand Up @@ -95,7 +96,7 @@ class FlowController {
return;
}

const { environmentId } = response;
const { environmentId, accountId } = response;

// config is an array for compatibility purposes, it will only ever have one item
const [firstConfig] = config;
Expand All @@ -111,6 +112,22 @@ class FlowController {
return;
}

const account = await accountService.getAccountById(accountId);

if (!account) {
errorManager.errRes(res, 'unknown_account');
return;
}

if (account.is_capped && firstConfig?.providerConfigKey) {
const isCapped = await connectionService.shouldCapUsage({ providerConfigKey: firstConfig?.providerConfigKey, environmentId });

if (isCapped) {
errorManager.errRes(res, 'resource_capped');
return;
}
}

const { success: preBuiltSuccess, error: preBuiltError, response: preBuiltResponse } = await deployPreBuiltSyncConfig(environmentId, config, '');

if (!preBuiltSuccess || preBuiltResponse === null) {
Expand Down
2 changes: 2 additions & 0 deletions packages/shared/lib/constants.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
export const SYNC_TASK_QUEUE = 'nango-syncs';
export const WEBHOOK_TASK_QUEUE = 'nango-webhooks';
//export const CONNECTIONS_WITH_SCRIPTS_CAP_LIMIT = 3;
export const CONNECTIONS_WITH_SCRIPTS_CAP_LIMIT = Infinity;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is that on purpose?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, very much so. We don't want to cap until we can set the account information correctly via the API

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just thought about it during the night (could not sleep). We also have to think about enterprise/community 👌🏻

10 changes: 3 additions & 7 deletions packages/shared/lib/hooks/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,10 @@ import type { Result } from '../utils/result.js';
import { resultOk, resultErr } from '../utils/result.js';
import { NangoError } from '../utils/error.js';
import { getLogger } from '../utils/temp/logger.js';
import { CONNECTIONS_WITH_SCRIPTS_CAP_LIMIT } from '../constants.js';

const logger = getLogger('hooks');

const CONNECTIONS_WITH_SCRIPTS_CAP_LIMIT = 3;

export const connectionCreationStartCapCheck = async ({
providerConfigKey,
environmentId
Expand All @@ -34,21 +33,18 @@ export const connectionCreationStartCapCheck = async ({

const scriptConfigs = await getSyncConfigsWithConnections(providerConfigKey, environmentId);

const reachedCap = false;

if (scriptConfigs.length > 0) {
for (const script of scriptConfigs) {
const { connections } = script;

if (connections.length >= CONNECTIONS_WITH_SCRIPTS_CAP_LIMIT) {
//reachedCap = true;
logger.info(`Reached cap for providerConfigKey: ${providerConfigKey} and environmentId: ${environmentId}`);
break;
return true;
}
}
}

return reachedCap;
return false;
};

export const connectionCreated = async (
Expand Down
16 changes: 16 additions & 0 deletions packages/shared/lib/services/connection.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ import { Locking } from '../utils/lock/locking.js';
import { InMemoryKVStore } from '../utils/kvstore/InMemoryStore.js';
import { RedisKVStore } from '../utils/kvstore/RedisStore.js';
import type { KVStore } from '../utils/kvstore/KVStore.js';
import { CONNECTIONS_WITH_SCRIPTS_CAP_LIMIT } from '../constants.js';

const logger = getLogger('Connection');

Expand Down Expand Up @@ -990,6 +991,21 @@ class ConnectionService {
}
}

public async shouldCapUsage({ providerConfigKey, environmentId }: { providerConfigKey: string; environmentId: number }): Promise<boolean> {
const connections = await this.getConnectionsByEnvironmentAndConfig(environmentId, providerConfigKey);

if (!connections) {
return false;
}

if (connections.length >= CONNECTIONS_WITH_SCRIPTS_CAP_LIMIT) {
logger.info(`Reached cap for providerConfigKey: ${providerConfigKey} and environmentId: ${environmentId}`);
return true;
}

return false;
}

private async getJWTCredentials(
privateKey: string,
url: string,
Expand Down
2 changes: 1 addition & 1 deletion packages/shared/lib/utils/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -563,7 +563,7 @@ export class NangoError extends Error {
this.status = 400;
// TODO docs link
this.message =
'You have reached the maximum number of integrations with active scripts. Upgrade or deactivate the scripts to create more connections (https://docs.nango.dev/relevant-link).';
'You have reached the maximum number of integrations with active scripts. Upgrade or deactivate the scripts to create more connections (https://docs.nango.dev/REPLACE-ME).';
break;

default:
Expand Down
42 changes: 37 additions & 5 deletions packages/webapp/src/components/ui/ActionModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,41 @@ interface ModalProps {
modalTitle: string;
modalAction: (() => void) | null;
setVisible: (visible: boolean) => void;
modalOkTitle?: string;
modalCancelTitle?: string;
modalOkLink?: string | null;
modalCancelLink?: string | null;
}

export default function ActionModal({ bindings, modalTitleColor, modalShowSpinner, modalContent, modalTitle, modalAction, setVisible }: ModalProps) {
export default function ActionModal({
bindings,
modalTitleColor,
modalShowSpinner,
modalContent,
modalTitle,
modalAction,
setVisible,
modalOkTitle,
modalCancelTitle,
modalOkLink,
modalCancelLink
}: ModalProps) {
const modalOkAction = () => {
if (modalOkLink) {
window.open(modalOkLink, '_blank');
} else {
modalAction && modalAction();
}
};

const modalCancelAction = () => {
if (modalCancelLink) {
window.open(modalCancelLink, '_blank');
} else {
setVisible(false);
}
};

return (
<Modal {...bindings} wrapClassName="!h-[200px] !w-[550px] !max-w-[550px] !bg-off-black no-border-modal !border !border-neutral-700">
<div className="flex justify-between text-sm">
Expand All @@ -34,12 +66,12 @@ export default function ActionModal({ bindings, modalTitleColor, modalShowSpinne
</div>
<div className="flex pb-4">
{modalAction && (
<Button className="mr-4" disabled={modalShowSpinner} variant="primary" onClick={modalAction}>
Confirm
<Button className="mr-4" disabled={modalShowSpinner} variant="primary" onClick={modalOkAction}>
{modalOkTitle || 'Confirm'}
</Button>
)}
<Button className="!text-text-light-gray" variant="zombie" onClick={() => setVisible(false)}>
Cancel
<Button className="!text-text-light-gray" variant="zombie" onClick={modalCancelAction}>
{modalCancelTitle || 'Cancel'}
</Button>
</div>
</Modal.Content>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,28 @@ export default function EnableDisableSync({

const [modalTitle, setModalTitle] = useState('');
const [modalContent, setModalContent] = useState('');
const [modalOkButtonTitle, setModalOkButtonTitle] = useState('Confirm');
const [modalCancelButtonTitle, setModalCancelButtonTitle] = useState('Cancel');
const [modalOkButtonLink, setModalOkButtonLink] = useState<string | null>(null);
const [modalCancelButtonLink, setModalCancelButtonLink] = useState<string | null>(null);
const [modalAction, setModalAction] = useState<(() => void) | null>(null);
const [modalShowSpinner, setModalShowSpinner] = useState(false);
const [modalTitleColor, setModalTitleColor] = useState('text-white');

const resetModal = () => {
setModalTitle('');
setModalContent('');
setModalOkButtonTitle('Confirm');
setModalCancelButtonTitle('Cancel');
setModalOkButtonLink(null);
setModalCancelButtonLink(null);
setModalAction(null);
setModalShowSpinner(false);
setModalTitleColor('text-white');
};

const enableSync = (flow: Flow) => {
resetModal();
setModalTitle(`Enable ${flow.type}?`);
setModalTitleColor('text-white');
const content =
Expand Down Expand Up @@ -96,9 +113,26 @@ export default function EnableDisableSync({
reload();
} else {
const payload = await res?.json();
toast.error(payload.error, {
position: toast.POSITION.BOTTOM_CENTER
});
if (payload.type === 'resource_capped') {
setModalShowSpinner(false);
setModalTitleColor('text-white');
setModalTitle('You’ve reached your connections limit!');
setModalContent(
`Scripts are a paid feature. You can only use them with 3 connections or less.
Upgrade or delete some connections to activate this script.`
);
setModalOkButtonTitle('Upgrade');
setModalCancelButtonTitle('Learn more');
setModalOkButtonLink('https://nango.dev/chat');
setModalCancelButtonLink('https://docs.nango.dev/REPLACE-ME');
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is it going to be replace later?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup, launch blocker to replace.

setVisible(true);

return;
} else {
toast.error(payload.error, {
position: toast.POSITION.BOTTOM_CENTER
});
}
}
setModalShowSpinner(false);
if (setIsEnabling) {
Expand All @@ -108,6 +142,7 @@ export default function EnableDisableSync({
};

const disableSync = (flow: Flow) => {
resetModal();
if (!flow.is_public) {
const title = 'Custom syncs cannot be disabled from the UI';
const message = flow.pre_built
Expand Down Expand Up @@ -182,6 +217,10 @@ export default function EnableDisableSync({
modalShowSpinner={modalShowSpinner}
modalTitleColor={modalTitleColor}
setVisible={setVisible}
modalOkTitle={modalOkButtonTitle}
modalCancelTitle={modalCancelButtonTitle}
modalOkLink={modalOkButtonLink}
modalCancelLink={modalCancelButtonLink}
/>
{showSpinner && (!('version' in flow) || flow.version === null) && modalShowSpinner && (
<span className="mr-2">
Expand Down
Loading