|
| 1 | +/** |
| 2 | + * Copyright (c) 2022 Gitpod GmbH. All rights reserved. |
| 3 | + * Licensed under the GNU Affero General Public License (AGPL). |
| 4 | + * See License-AGPL.txt in the project root for license information. |
| 5 | + */ |
| 6 | + |
| 7 | +import { TeamDB, TeamSubscription2DB, TeamSubscriptionDB } from "@gitpod/gitpod-db/lib"; |
| 8 | +import { Accounting, SubscriptionService } from "@gitpod/gitpod-payment-endpoint/lib/accounting"; |
| 9 | +import { |
| 10 | + User, |
| 11 | + WorkspaceInstance, |
| 12 | + WorkspaceTimeoutDuration, |
| 13 | + WORKSPACE_TIMEOUT_DEFAULT_LONG, |
| 14 | + WORKSPACE_TIMEOUT_DEFAULT_SHORT, |
| 15 | +} from "@gitpod/gitpod-protocol"; |
| 16 | +import { RemainingHours } from "@gitpod/gitpod-protocol/lib/accounting-protocol"; |
| 17 | +import { MAX_PARALLEL_WORKSPACES, Plans } from "@gitpod/gitpod-protocol/lib/plans"; |
| 18 | +import { millisecondsToHours } from "@gitpod/gitpod-protocol/lib/util/timeutil"; |
| 19 | +import { inject, injectable } from "inversify"; |
| 20 | +import { EntitlementService } from "../../../src/billing/entitlement-service"; |
| 21 | +import { Config } from "../../../src/config"; |
| 22 | +import { AccountStatementProvider, CachedAccountStatement } from "../user/account-statement-provider"; |
| 23 | +import { HitParallelWorkspaceLimit, MayStartWorkspaceResult } from "../user/eligibility-service"; |
| 24 | + |
| 25 | +@injectable() |
| 26 | +export class EntitlementServiceChargebee implements EntitlementService { |
| 27 | + @inject(Config) protected readonly config: Config; |
| 28 | + @inject(SubscriptionService) protected readonly subscriptionService: SubscriptionService; |
| 29 | + @inject(AccountStatementProvider) protected readonly accountStatementProvider: AccountStatementProvider; |
| 30 | + @inject(TeamSubscriptionDB) protected readonly teamSubscriptionDb: TeamSubscriptionDB; |
| 31 | + @inject(TeamDB) protected readonly teamDb: TeamDB; |
| 32 | + @inject(TeamSubscription2DB) protected readonly teamSubscription2Db: TeamSubscription2DB; |
| 33 | + |
| 34 | + /** |
| 35 | + * Whether a user is allowed to start a workspace |
| 36 | + * !!! This is executed on the hot path of workspace startup, be careful with async when changing !!! |
| 37 | + * @param user |
| 38 | + * @param date now |
| 39 | + * @param runningInstances |
| 40 | + */ |
| 41 | + async mayStartWorkspace( |
| 42 | + user: User, |
| 43 | + date: Date, |
| 44 | + runningInstances: Promise<WorkspaceInstance[]>, |
| 45 | + ): Promise<MayStartWorkspaceResult> { |
| 46 | + if (!this.config.enablePayment) { |
| 47 | + return { enoughCredits: true }; |
| 48 | + } |
| 49 | + |
| 50 | + const hasHitParallelWorkspaceLimit = async (): Promise<HitParallelWorkspaceLimit | undefined> => { |
| 51 | + const max = await this.getMaxParallelWorkspaces(user); |
| 52 | + const instances = (await runningInstances).filter((i) => i.status.phase !== "preparing"); |
| 53 | + const current = instances.length; // >= parallelWorkspaceAllowance; |
| 54 | + if (current >= max) { |
| 55 | + return { |
| 56 | + current, |
| 57 | + max, |
| 58 | + }; |
| 59 | + } else { |
| 60 | + return undefined; |
| 61 | + } |
| 62 | + }; |
| 63 | + const [enoughCredits, hitParallelWorkspaceLimit] = await Promise.all([ |
| 64 | + this.checkEnoughCreditForWorkspaceStart(user.id, date, runningInstances), |
| 65 | + hasHitParallelWorkspaceLimit(), |
| 66 | + ]); |
| 67 | + |
| 68 | + return { |
| 69 | + enoughCredits: !!enoughCredits, |
| 70 | + hitParallelWorkspaceLimit, |
| 71 | + }; |
| 72 | + } |
| 73 | + |
| 74 | + /** |
| 75 | + * Returns the maximum number of parallel workspaces a user can run at the same time. |
| 76 | + * @param user |
| 77 | + * @param date The date for which we want to know whether the user is allowed to set a timeout (depends on active subscription) |
| 78 | + */ |
| 79 | + protected async getMaxParallelWorkspaces(user: User, date: Date = new Date()): Promise<number> { |
| 80 | + // if payment is not enabled users can start as many parallel workspaces as they want |
| 81 | + if (!this.config.enablePayment) { |
| 82 | + return MAX_PARALLEL_WORKSPACES; |
| 83 | + } |
| 84 | + |
| 85 | + const subscriptions = await this.subscriptionService.getNotYetCancelledSubscriptions(user, date.toISOString()); |
| 86 | + return subscriptions.map((s) => Plans.getParallelWorkspacesById(s.planId)).reduce((p, v) => Math.max(p, v)); |
| 87 | + } |
| 88 | + |
| 89 | + protected async checkEnoughCreditForWorkspaceStart( |
| 90 | + userId: string, |
| 91 | + date: Date, |
| 92 | + runningInstances: Promise<WorkspaceInstance[]>, |
| 93 | + ): Promise<boolean> { |
| 94 | + // As retrieving a full AccountStatement is expensive we want to cache it as much as possible. |
| 95 | + const cachedAccountStatement = this.accountStatementProvider.getCachedStatement(); |
| 96 | + const lowerBound = this.getRemainingUsageHoursLowerBound(cachedAccountStatement, date.toISOString()); |
| 97 | + if (lowerBound && (lowerBound === "unlimited" || lowerBound > Accounting.MINIMUM_CREDIT_FOR_OPEN_IN_HOURS)) { |
| 98 | + return true; |
| 99 | + } |
| 100 | + |
| 101 | + const remainingUsageHours = await this.accountStatementProvider.getRemainingUsageHours( |
| 102 | + userId, |
| 103 | + date.toISOString(), |
| 104 | + runningInstances, |
| 105 | + ); |
| 106 | + return remainingUsageHours > Accounting.MINIMUM_CREDIT_FOR_OPEN_IN_HOURS; |
| 107 | + } |
| 108 | + |
| 109 | + /** |
| 110 | + * Tries to calculate the lower bound of remaining usage hours based on cached AccountStatements |
| 111 | + * with the goal to improve workspace startup times. |
| 112 | + */ |
| 113 | + protected getRemainingUsageHoursLowerBound( |
| 114 | + cachedStatement: CachedAccountStatement | undefined, |
| 115 | + date: string, |
| 116 | + ): RemainingHours | undefined { |
| 117 | + if (!cachedStatement) { |
| 118 | + return undefined; |
| 119 | + } |
| 120 | + if (cachedStatement.remainingHours === "unlimited") { |
| 121 | + return "unlimited"; |
| 122 | + } |
| 123 | + |
| 124 | + const diffInMillis = new Date(cachedStatement.endDate).getTime() - new Date(date).getTime(); |
| 125 | + const maxPossibleUsage = millisecondsToHours(diffInMillis) * MAX_PARALLEL_WORKSPACES; |
| 126 | + return cachedStatement.remainingHours - maxPossibleUsage; |
| 127 | + } |
| 128 | + |
| 129 | + /** |
| 130 | + * A user may set the workspace timeout if they have a professional subscription |
| 131 | + * @param user |
| 132 | + * @param date The date for which we want to know whether the user is allowed to set a timeout (depends on active subscription) |
| 133 | + */ |
| 134 | + async maySetTimeout(user: User, date: Date = new Date()): Promise<boolean> { |
| 135 | + if (!this.config.enablePayment) { |
| 136 | + // when payment is disabled users can do everything |
| 137 | + return true; |
| 138 | + } |
| 139 | + |
| 140 | + const subscriptions = await this.subscriptionService.getNotYetCancelledSubscriptions(user, date.toISOString()); |
| 141 | + const eligblePlans = [ |
| 142 | + Plans.PROFESSIONAL_EUR, |
| 143 | + Plans.PROFESSIONAL_USD, |
| 144 | + Plans.PROFESSIONAL_STUDENT_EUR, |
| 145 | + Plans.PROFESSIONAL_STUDENT_USD, |
| 146 | + Plans.TEAM_PROFESSIONAL_EUR, |
| 147 | + Plans.TEAM_PROFESSIONAL_USD, |
| 148 | + Plans.TEAM_PROFESSIONAL_STUDENT_EUR, |
| 149 | + Plans.TEAM_PROFESSIONAL_STUDENT_USD, |
| 150 | + ].map((p) => p.chargebeeId); |
| 151 | + |
| 152 | + return subscriptions.filter((s) => eligblePlans.includes(s.planId!)).length > 0; |
| 153 | + } |
| 154 | + |
| 155 | + /** |
| 156 | + * Returns the default workspace timeout for the given user at a given point in time |
| 157 | + * @param user |
| 158 | + * @param date The date for which we want to know the default workspace timeout (depends on active subscription) |
| 159 | + */ |
| 160 | + async getDefaultWorkspaceTimeout(user: User, date: Date = new Date()): Promise<WorkspaceTimeoutDuration> { |
| 161 | + if (await this.maySetTimeout(user, date)) { |
| 162 | + return WORKSPACE_TIMEOUT_DEFAULT_LONG; |
| 163 | + } else { |
| 164 | + return WORKSPACE_TIMEOUT_DEFAULT_SHORT; |
| 165 | + } |
| 166 | + } |
| 167 | + |
| 168 | + /** |
| 169 | + * Returns true if the user is never subject to CPU limiting |
| 170 | + */ |
| 171 | + async hasFixedWorkspaceResources(user: User, date: Date = new Date()): Promise<boolean> { |
| 172 | + const subscriptions = await this.subscriptionService.getNotYetCancelledSubscriptions(user, date.toISOString()); |
| 173 | + const eligblePlans = [ |
| 174 | + Plans.PROFESSIONAL_EUR, |
| 175 | + Plans.PROFESSIONAL_USD, |
| 176 | + Plans.TEAM_PROFESSIONAL_EUR, |
| 177 | + Plans.TEAM_PROFESSIONAL_USD, |
| 178 | + ].map((p) => p.chargebeeId); |
| 179 | + |
| 180 | + return subscriptions.filter((s) => eligblePlans.includes(s.planId!)).length > 0; |
| 181 | + } |
| 182 | + |
| 183 | + /** |
| 184 | + * Returns true if the user ought to land on a workspace cluster that provides more resources |
| 185 | + * compared to the default case. |
| 186 | + */ |
| 187 | + async userGetsMoreResources(user: User): Promise<boolean> { |
| 188 | + if (!this.config.enablePayment) { |
| 189 | + // when payment is disabled users can do everything |
| 190 | + return true; |
| 191 | + } |
| 192 | + |
| 193 | + const subscriptions = await this.subscriptionService.getNotYetCancelledSubscriptions( |
| 194 | + user, |
| 195 | + new Date().toISOString(), |
| 196 | + ); |
| 197 | + const eligiblePlans = [Plans.TEAM_PROFESSIONAL_EUR, Plans.TEAM_PROFESSIONAL_USD].map((p) => p.chargebeeId); |
| 198 | + |
| 199 | + const relevantSubscriptions = subscriptions.filter((s) => eligiblePlans.includes(s.planId!)); |
| 200 | + if (relevantSubscriptions.length === 0) { |
| 201 | + // user has no subscription that grants "more resources" |
| 202 | + return false; |
| 203 | + } |
| 204 | + |
| 205 | + // some TeamSubscriptions are marked with 'excludeFromMoreResources' to convey that those are _not_ receiving more resources |
| 206 | + const excludeFromMoreResources = await Promise.all( |
| 207 | + relevantSubscriptions.map(async (s): Promise<boolean> => { |
| 208 | + if (s.teamMembershipId) { |
| 209 | + const team = await this.teamDb.findTeamByMembershipId(s.teamMembershipId); |
| 210 | + if (!team) { |
| 211 | + return true; |
| 212 | + } |
| 213 | + const ts2 = await this.teamSubscription2Db.findForTeam(team.id, new Date().toISOString()); |
| 214 | + if (!ts2) { |
| 215 | + return true; |
| 216 | + } |
| 217 | + return ts2.excludeFromMoreResources; |
| 218 | + } |
| 219 | + if (!s.teamSubscriptionSlotId) { |
| 220 | + return false; |
| 221 | + } |
| 222 | + const ts = await this.teamSubscriptionDb.findTeamSubscriptionBySlotId(s.teamSubscriptionSlotId); |
| 223 | + return !!ts?.excludeFromMoreResources; |
| 224 | + }), |
| 225 | + ); |
| 226 | + if (excludeFromMoreResources.every((b) => b)) { |
| 227 | + // if all TS the user is part of are marked this way, we deny that privilege |
| 228 | + return false; |
| 229 | + } |
| 230 | + |
| 231 | + return true; |
| 232 | + } |
| 233 | +} |
0 commit comments