-
Notifications
You must be signed in to change notification settings - Fork 1.3k
[server] Introduce EntitlementServiceChargbee and move relevant parts of EligibilityService into it #11831
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
Merged
Merged
[server] Introduce EntitlementServiceChargbee and move relevant parts of EligibilityService into it #11831
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
218 changes: 218 additions & 0 deletions
218
components/server/ee/src/billing/entitlement-service-chargebee.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,218 @@ | ||
/** | ||
* Copyright (c) 2022 Gitpod GmbH. All rights reserved. | ||
* Licensed under the GNU Affero General Public License (AGPL). | ||
* See License-AGPL.txt in the project root for license information. | ||
*/ | ||
|
||
import { TeamDB, TeamSubscription2DB, TeamSubscriptionDB } from "@gitpod/gitpod-db/lib"; | ||
import { Accounting, SubscriptionService } from "@gitpod/gitpod-payment-endpoint/lib/accounting"; | ||
import { | ||
User, | ||
WorkspaceInstance, | ||
WorkspaceTimeoutDuration, | ||
WORKSPACE_TIMEOUT_DEFAULT_LONG, | ||
WORKSPACE_TIMEOUT_DEFAULT_SHORT, | ||
} from "@gitpod/gitpod-protocol"; | ||
import { RemainingHours } from "@gitpod/gitpod-protocol/lib/accounting-protocol"; | ||
import { MAX_PARALLEL_WORKSPACES, Plans } from "@gitpod/gitpod-protocol/lib/plans"; | ||
import { millisecondsToHours } from "@gitpod/gitpod-protocol/lib/util/timeutil"; | ||
import { inject, injectable } from "inversify"; | ||
import { EntitlementService } from "../../../src/billing/entitlement-service"; | ||
import { Config } from "../../../src/config"; | ||
import { AccountStatementProvider, CachedAccountStatement } from "../user/account-statement-provider"; | ||
import { HitParallelWorkspaceLimit, MayStartWorkspaceResult } from "../user/eligibility-service"; | ||
|
||
@injectable() | ||
export class EntitlementServiceChargebee implements EntitlementService { | ||
@inject(Config) protected readonly config: Config; | ||
@inject(SubscriptionService) protected readonly subscriptionService: SubscriptionService; | ||
@inject(AccountStatementProvider) protected readonly accountStatementProvider: AccountStatementProvider; | ||
@inject(TeamSubscriptionDB) protected readonly teamSubscriptionDb: TeamSubscriptionDB; | ||
@inject(TeamDB) protected readonly teamDb: TeamDB; | ||
@inject(TeamSubscription2DB) protected readonly teamSubscription2Db: TeamSubscription2DB; | ||
|
||
/** | ||
* Whether a user is allowed to start a workspace | ||
* !!! This is executed on the hot path of workspace startup, be careful with async when changing !!! | ||
* @param user | ||
* @param date now | ||
* @param runningInstances | ||
*/ | ||
async mayStartWorkspace( | ||
user: User, | ||
date: Date, | ||
runningInstances: Promise<WorkspaceInstance[]>, | ||
): Promise<MayStartWorkspaceResult> { | ||
if (!this.config.enablePayment) { | ||
return { enoughCredits: true }; | ||
} | ||
|
||
const hasHitParallelWorkspaceLimit = async (): Promise<HitParallelWorkspaceLimit | undefined> => { | ||
const max = await this.getMaxParallelWorkspaces(user); | ||
const instances = (await runningInstances).filter((i) => i.status.phase !== "preparing"); | ||
const current = instances.length; // >= parallelWorkspaceAllowance; | ||
if (current >= max) { | ||
return { | ||
current, | ||
max, | ||
}; | ||
} else { | ||
return undefined; | ||
} | ||
}; | ||
const [enoughCredits, hitParallelWorkspaceLimit] = await Promise.all([ | ||
this.checkEnoughCreditForWorkspaceStart(user.id, date, runningInstances), | ||
hasHitParallelWorkspaceLimit(), | ||
]); | ||
|
||
return { | ||
enoughCredits: !!enoughCredits, | ||
hitParallelWorkspaceLimit, | ||
}; | ||
} | ||
|
||
/** | ||
* Returns the maximum number of parallel workspaces a user can run at the same time. | ||
* @param user | ||
* @param date The date for which we want to know whether the user is allowed to set a timeout (depends on active subscription) | ||
*/ | ||
protected async getMaxParallelWorkspaces(user: User, date: Date = new Date()): Promise<number> { | ||
// if payment is not enabled users can start as many parallel workspaces as they want | ||
if (!this.config.enablePayment) { | ||
return MAX_PARALLEL_WORKSPACES; | ||
} | ||
|
||
const subscriptions = await this.subscriptionService.getNotYetCancelledSubscriptions(user, date.toISOString()); | ||
return subscriptions.map((s) => Plans.getParallelWorkspacesById(s.planId)).reduce((p, v) => Math.max(p, v)); | ||
} | ||
|
||
protected async checkEnoughCreditForWorkspaceStart( | ||
userId: string, | ||
date: Date, | ||
runningInstances: Promise<WorkspaceInstance[]>, | ||
): Promise<boolean> { | ||
// As retrieving a full AccountStatement is expensive we want to cache it as much as possible. | ||
const cachedAccountStatement = this.accountStatementProvider.getCachedStatement(); | ||
const lowerBound = this.getRemainingUsageHoursLowerBound(cachedAccountStatement, date.toISOString()); | ||
if (lowerBound && (lowerBound === "unlimited" || lowerBound > Accounting.MINIMUM_CREDIT_FOR_OPEN_IN_HOURS)) { | ||
return true; | ||
} | ||
|
||
const remainingUsageHours = await this.accountStatementProvider.getRemainingUsageHours( | ||
userId, | ||
date.toISOString(), | ||
runningInstances, | ||
); | ||
return remainingUsageHours > Accounting.MINIMUM_CREDIT_FOR_OPEN_IN_HOURS; | ||
} | ||
|
||
/** | ||
* Tries to calculate the lower bound of remaining usage hours based on cached AccountStatements | ||
* with the goal to improve workspace startup times. | ||
*/ | ||
protected getRemainingUsageHoursLowerBound( | ||
cachedStatement: CachedAccountStatement | undefined, | ||
date: string, | ||
): RemainingHours | undefined { | ||
if (!cachedStatement) { | ||
return undefined; | ||
} | ||
if (cachedStatement.remainingHours === "unlimited") { | ||
return "unlimited"; | ||
} | ||
|
||
const diffInMillis = new Date(cachedStatement.endDate).getTime() - new Date(date).getTime(); | ||
const maxPossibleUsage = millisecondsToHours(diffInMillis) * MAX_PARALLEL_WORKSPACES; | ||
return cachedStatement.remainingHours - maxPossibleUsage; | ||
} | ||
|
||
/** | ||
* A user may set the workspace timeout if they have a professional subscription | ||
* @param user | ||
* @param date The date for which we want to know whether the user is allowed to set a timeout (depends on active subscription) | ||
*/ | ||
async maySetTimeout(user: User, date: Date = new Date()): Promise<boolean> { | ||
if (!this.config.enablePayment) { | ||
// when payment is disabled users can do everything | ||
return true; | ||
} | ||
|
||
const subscriptions = await this.subscriptionService.getNotYetCancelledSubscriptions(user, date.toISOString()); | ||
const eligblePlans = [ | ||
Plans.PROFESSIONAL_EUR, | ||
Plans.PROFESSIONAL_USD, | ||
Plans.PROFESSIONAL_STUDENT_EUR, | ||
Plans.PROFESSIONAL_STUDENT_USD, | ||
Plans.TEAM_PROFESSIONAL_EUR, | ||
Plans.TEAM_PROFESSIONAL_USD, | ||
Plans.TEAM_PROFESSIONAL_STUDENT_EUR, | ||
Plans.TEAM_PROFESSIONAL_STUDENT_USD, | ||
].map((p) => p.chargebeeId); | ||
|
||
return subscriptions.filter((s) => eligblePlans.includes(s.planId!)).length > 0; | ||
} | ||
|
||
/** | ||
* Returns the default workspace timeout for the given user at a given point in time | ||
* @param user | ||
* @param date The date for which we want to know the default workspace timeout (depends on active subscription) | ||
*/ | ||
async getDefaultWorkspaceTimeout(user: User, date: Date = new Date()): Promise<WorkspaceTimeoutDuration> { | ||
if (await this.maySetTimeout(user, date)) { | ||
return WORKSPACE_TIMEOUT_DEFAULT_LONG; | ||
} else { | ||
return WORKSPACE_TIMEOUT_DEFAULT_SHORT; | ||
} | ||
} | ||
|
||
/** | ||
* Returns true if the user ought to land on a workspace cluster that provides more resources | ||
* compared to the default case. | ||
*/ | ||
async userGetsMoreResources(user: User): Promise<boolean> { | ||
if (!this.config.enablePayment) { | ||
// when payment is disabled users can do everything | ||
return true; | ||
} | ||
|
||
const subscriptions = await this.subscriptionService.getNotYetCancelledSubscriptions( | ||
user, | ||
new Date().toISOString(), | ||
); | ||
const eligiblePlans = [Plans.TEAM_PROFESSIONAL_EUR, Plans.TEAM_PROFESSIONAL_USD].map((p) => p.chargebeeId); | ||
|
||
const relevantSubscriptions = subscriptions.filter((s) => eligiblePlans.includes(s.planId!)); | ||
if (relevantSubscriptions.length === 0) { | ||
// user has no subscription that grants "more resources" | ||
return false; | ||
} | ||
|
||
// some TeamSubscriptions are marked with 'excludeFromMoreResources' to convey that those are _not_ receiving more resources | ||
const excludeFromMoreResources = await Promise.all( | ||
relevantSubscriptions.map(async (s): Promise<boolean> => { | ||
if (s.teamMembershipId) { | ||
const team = await this.teamDb.findTeamByMembershipId(s.teamMembershipId); | ||
if (!team) { | ||
return true; | ||
} | ||
const ts2 = await this.teamSubscription2Db.findForTeam(team.id, new Date().toISOString()); | ||
if (!ts2) { | ||
return true; | ||
} | ||
return ts2.excludeFromMoreResources; | ||
} | ||
if (!s.teamSubscriptionSlotId) { | ||
return false; | ||
} | ||
const ts = await this.teamSubscriptionDb.findTeamSubscriptionBySlotId(s.teamSubscriptionSlotId); | ||
return !!ts?.excludeFromMoreResources; | ||
}), | ||
); | ||
if (excludeFromMoreResources.every((b) => b)) { | ||
// if all TS the user is part of are marked this way, we deny that privilege | ||
return false; | ||
} | ||
|
||
return true; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -9,8 +9,7 @@ import { DBUser, DBIdentity, UserDB, AccountingDB, TeamSubscriptionDB } from "@g | |
import { TypeORM } from "@gitpod/gitpod-db/lib/typeorm/typeorm"; | ||
import { Subscription } from "@gitpod/gitpod-protocol/lib/accounting-protocol"; | ||
import { Plans } from "@gitpod/gitpod-protocol/lib/plans"; | ||
import * as chai from "chai"; | ||
import { suite, test, timeout } from "mocha-typescript"; | ||
import { suite, timeout } from "mocha-typescript"; | ||
import { Config } from "../../../src/config"; | ||
import { EligibilityService } from "./eligibility-service"; | ||
import { DBSubscription } from "@gitpod/gitpod-db/lib/typeorm/entity/db-subscription"; | ||
|
@@ -26,8 +25,6 @@ import { EMailDomainService, EMailDomainServiceImpl } from "../auth/email-domain | |
import { TokenProvider } from "../../../src/user/token-provider"; | ||
import { AccountStatementProvider } from "./account-statement-provider"; | ||
|
||
const expect = chai.expect; | ||
|
||
const localTestContainer = testContainer.createChild(); | ||
localTestContainer.bind(EligibilityService).toSelf().inSingletonScope(); | ||
localTestContainer | ||
|
@@ -147,26 +144,27 @@ class AccountServiceSpec { | |
return { plan, sub, ts, slot }; | ||
} | ||
|
||
@timeout(5000) | ||
@test | ||
async testUserGetsMoreResources() { | ||
await this.createTsSubscription(); | ||
|
||
const actual = await this.cut.userGetsMoreResources(this.user); | ||
expect(actual, "user with Team Unleashed gets 'more resources'").to.equal(true); | ||
} | ||
|
||
@timeout(5000) | ||
@test | ||
async testUserGetsMoreResources_excludeFromMoreResources() { | ||
await this.createTsSubscription(true); | ||
|
||
const actual = await this.cut.userGetsMoreResources(this.user); | ||
expect( | ||
actual, | ||
"user with Team Unleashed but excludeFromMoreResources set does not get 'more resources'", | ||
).to.equal(false); | ||
} | ||
// TODO(gpl) These should be moved over to EntitlementService.spec.ts | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🤞🏻 |
||
// @timeout(5000) | ||
// @test | ||
// async testUserGetsMoreResources() { | ||
// await this.createTsSubscription(); | ||
|
||
// const actual = await this.cut.userGetsMoreResources(this.user); | ||
// expect(actual, "user with Team Unleashed gets 'more resources'").to.equal(true); | ||
// } | ||
|
||
// @timeout(5000) | ||
// @test | ||
// async testUserGetsMoreResources_excludeFromMoreResources() { | ||
// await this.createTsSubscription(true); | ||
|
||
// const actual = await this.cut.userGetsMoreResources(this.user); | ||
// expect( | ||
// actual, | ||
// "user with Team Unleashed but excludeFromMoreResources set does not get 'more resources'", | ||
// ).to.equal(false); | ||
// } | ||
} | ||
|
||
module.exports = new AccountServiceSpec(); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.