From d13b157f85736f578cdfc27d4e5485ed6e3cc2dc Mon Sep 17 00:00:00 2001 From: Amin Ehterami Date: Wed, 4 Nov 2026 22:23:58 +0330 Subject: [PATCH 1/3] update the deploy command --- src/base.ts | 2 + src/commands/app/logs.ts | 17 +- src/commands/deploy.ts | 238 +++++-- src/commands/init.ts | 15 +- src/constants.ts | 5 + src/errors/bundle-plan.ts | 37 +- src/services/get-platform-version.ts | 106 +++- src/types/bundle-plan.ts | 5 + src/utils/get-supported-versions.ts | 46 +- test/app/logs.unit.test.ts | 60 ++ test/deploy/deploy.unit.test.ts | 600 +++++++++++++++++- test/init/init.unit.test.ts | 49 ++ .../get-platform-version.unit.test.ts | 190 ++++++ 13 files changed, 1261 insertions(+), 109 deletions(-) create mode 100644 src/types/bundle-plan.ts create mode 100644 test/init/init.unit.test.ts create mode 100644 test/services/get-platform-version.unit.test.ts diff --git a/src/base.ts b/src/base.ts index 7c20fa48..17a95fae 100644 --- a/src/base.ts +++ b/src/base.ts @@ -127,6 +127,8 @@ export interface IProjectDetails { type: string; status: string; defaultSubdomain: boolean; + defaultSubdomainExpired?: boolean; + keepDefaultSubdomain?: boolean; zeroDowntime: boolean; scale: number; envs: IEnvs[]; diff --git a/src/commands/app/logs.ts b/src/commands/app/logs.ts index dd66a599..764999fc 100644 --- a/src/commands/app/logs.ts +++ b/src/commands/app/logs.ts @@ -105,6 +105,10 @@ export default class AppLogs extends Command { static aliases = ['logs']; + // Set by `liara deploy`, which has already loaded the plans by the time it + // streams the logs. It isn't a flag so that it can't be set by users. + static maxLogsRetention?: number; + #timestamps = false; #colorize = false; #releaseTagMap: Map = new Map(); // cache to store releaseId with it's tag @@ -143,11 +147,16 @@ export default class AppLogs extends Command { process.exit(1); } - const { plans } = await this.got('v1/me').json<{ plans: any }>(); + let { maxLogsRetention } = AppLogs; + + if (maxLogsRetention === undefined) { + const { plans } = await this.got('v1/me').json<{ plans: any }>(); + + maxLogsRetention = plans.projectBundlePlans[planID][bundlePlanID] + .maxLogsRetention as number; + } - const maxSince: number = - now - - plans.projectBundlePlans[planID][bundlePlanID].maxLogsRetention * 86400; + const maxSince: number = now - maxLogsRetention * 86400; let start: number = flags.since ? this.getStart(`${flags.since}`) diff --git a/src/commands/deploy.ts b/src/commands/deploy.ts index 6aa47624..49c61ee7 100644 --- a/src/commands/deploy.ts +++ b/src/commands/deploy.ts @@ -10,6 +10,7 @@ import { Flags, Errors } from '@oclif/core'; import Command, { IGetDomainsResponse, + IProjectDetails, IProjectDetailsResponse, } from '../base.js'; @@ -18,6 +19,7 @@ import IFlags from '../types/flags.js'; import Poller from '../utils/poller.js'; import upload from '../services/upload.js'; import IRelease from '../types/release.js'; +import IBundlePlan from '../types/bundle-plan.js'; import checkPath from '../utils/check-path.js'; import onInterupt from '../utils/on-intrupt.js'; import ILiaraJSON from '../types/liara-json.js'; @@ -35,7 +37,11 @@ import collectGitInfo from '../utils/collect-git-info.js'; import ICreatedRelease from '../types/created-release.js'; import { BundlePlanError } from '../errors/bundle-plan.js'; import buildArgsParser from '../utils/build-args-parser.js'; -import { DEV_MODE, MAX_SOURCE_SIZE } from '../constants.js'; +import { + DEFAULT_SUBDOMAIN_EXPIRY_SINCE, + DEV_MODE, + MAX_SOURCE_SIZE, +} from '../constants.js'; import DeployException from '../errors/deploy-exception.js'; import IDeploymentConfig from '../types/deployment-config.js'; import { getPort, getDefaultPort } from '../utils/get-port.js'; @@ -45,6 +51,10 @@ import IGetProjectsResponse from '../types/get-project-response.js'; import ReachedMaxSourceSizeError from '../errors/max-source-size.js'; import getPlatformVersion from '../services/get-platform-version.js'; import parseJSON from '../utils/json-parse.js'; +import { + getDeprecatedVersionMessage, + isDeprecatedVersion, +} from '../utils/get-supported-versions.js'; export default class Deploy extends Command { static description = 'deploy an app'; @@ -187,6 +197,7 @@ export default class Deploy extends Command { } let bundlePlanID: string; + let bundlePlan: IBundlePlan | undefined; try { const { project } = await this.got( `v1/projects/${config.app}`, @@ -221,7 +232,11 @@ export default class Deploy extends Command { this.logKeyValue('Platform', config.platform); this.logKeyValue('Port', String(config.port)); - const response = await this.deploy(config); + if (!flags.detach && !flags['no-app-logs'] && project.network) { + bundlePlan = await this.getBundlePlan(project); + } + + const response = await this.deploy(config, bundlePlan?.maxSourceSize); if (flags.detach) { this.log(chalk.green('Deployment created successfully.')); @@ -231,32 +246,15 @@ export default class Deploy extends Command { this.log(); this.log(chalk.green('Deployment finished successfully.')); - this.log(chalk.white('Open up the url below in your browser:')); - this.log(); - - const defaultSubdomain: string = - config.region === 'iran' && !Boolean(project.network) - ? '.iran.liara.run' - : '.liara.run'; - const urlLogMessage = DEV_MODE - ? // tslint:disable-next-line: no-http-string - ` ${`http://${config.app}.liara.localhost`}` - : ` ${`https://${config.app}${defaultSubdomain}`}`; - - const { domains } = await this.got( - `v1/domains?project=${config.app}`, - ).json(); - if (!domains.length || project.defaultSubdomain) - this.log(urlLogMessage); - - const firstFiveDomains = domains.reverse().slice(0, 5); - - for (const domain of firstFiveDomains) { - const protocol: string = - domain.certificatesStatus === 'ACTIVE' ? 'https' : 'http'; - - this.log(chalk.white(` ${protocol}://${domain.name}`)); + // The deployment already succeeded, so a failed lookup must not fail it. + try { + await this.logAppUrls(config.app, project); + } catch (error) { + this.debug(error.stack); + this.warn( + `Could not load the app's URLs. You can find them at https://console.liara.ir/apps/${config.app}/domains`, + ); } this.log(); @@ -266,6 +264,7 @@ export default class Deploy extends Command { } this.log('Reading app logs...'); + Logs.maxLogsRetention = bundlePlan?.maxLogsRetention; await Logs.run([ '--app', config.app, @@ -293,7 +292,17 @@ export default class Deploy extends Command { : {}; if (error.message === 'TIMEOUT') { - this.error('Build timed out. It took about 20 minutes.'); + const allowedTime = bundlePlan + ? `the ${bundlePlan.buildTimeout} minutes` + : 'the time'; + const message = `Build timed out. It took longer than ${allowedTime} your feature bundle plan allows. +Please review the following options: + + 1. Upgrade your feature bundle plan: https://console.liara.ir/apps/${config.app}/resize + 2. Try the Germany build location: liara deploy --build-location germany + +If the issue persists, please submit a ticket at https://console.liara.ir/tickets for further assistance.`; + return this.error(message); } if (error.response && error.response.statusCode === 404) { @@ -342,7 +351,7 @@ Please open up https://console.liara.ir/apps and unfreeze the app.`; error.response.statusCode === 428 && responseBody?.data?.code === 'germany_builder_not_allowed' ) { - const message = `To use builder locations, upgrade your feature bundle plan, first. + const message = `To use builder locations, upgrade your feature bundle plan, first. Then try again. https://console.liara.ir/apps/${config.app}/resize`; @@ -383,12 +392,19 @@ You may also want to switch to another region. Your current region is: ${chalk.c return this.error(error.message); } - if ( - error instanceof ReachedMaxSourceSizeError || - (error.response && error.response.statusCode === 413) - ) { - this.error( - BundlePlanError.max_source_size(bundlePlanID!) || error.message, + if (error instanceof DeployException) { + return this.error(error.message); + } + + if (error instanceof ReachedMaxSourceSizeError) { + return this.error(error.message); + } + + // Without the bundle plan, the app's limit may be lower than ours, so the + // message doesn't name a size. + if (error.response && error.response.statusCode === 413) { + return this.error( + BundlePlanError.max_source_size(bundlePlan?.maxSourceSize), ); } @@ -400,7 +416,28 @@ Additionally, you can also retry the build with the debug flag: } } - async deploy(config: IDeploymentConfig) { + async getBundlePlan( + project: IProjectDetails, + ): Promise { + try { + // Nothing here may stop the deployment. Without throwHttpErrors, a 401 + // would exit the process in the interceptor, before the upload. + const { plans } = await this.got('v1/me', { + retry: { limit: 0 }, + throwHttpErrors: false, + }).json<{ plans: any }>(); + + return plans.projectBundlePlans[project.planID]?.[project.bundlePlanID]; + } catch (error) { + this.debug(error.stack); + return undefined; + } + } + + /** + * @param maxSourceSize the largest source the app can upload, in MB + */ + async deploy(config: IDeploymentConfig, maxSourceSize?: number) { let body: { [k: string]: any } = { build: { cache: config.buildCache, @@ -454,14 +491,20 @@ Additionally, you can also retry the build with the debug flag: )}`, ); - if (sourceSize > MAX_SOURCE_SIZE) { + const sourceLimit = maxSourceSize + ? maxSourceSize * 1024 * 1024 + : MAX_SOURCE_SIZE; + + if (sourceSize > sourceLimit) { try { fs.removeSync(sourcePath); } catch (error) { this.debug(error.stack); } finally { // eslint-disable-next-line no-unsafe-finally - throw new ReachedMaxSourceSizeError(); + throw new ReachedMaxSourceSizeError( + BundlePlanError.max_source_size(sourceLimit / 1024 / 1024), + ); } } @@ -557,6 +600,7 @@ Additionally, you can also retry the build with the debug flag: this.spinner.succeed('Build finished.'); isPushingStart = !isPushingStart; } + if (output.line) { this.spinner.clear().frame(); this.spinner.start(output.line); @@ -583,7 +627,7 @@ Additionally, you can also retry the build with the debug flag: if (error instanceof DeployException) { this.spinner.fail(); - throw new Error(this.parseFailReason(error.message)); + throw new DeployException(this.parseFailReason(error.message)); } if (error instanceof ReleaseFailed) { @@ -596,6 +640,25 @@ Additionally, you can also retry the build with the debug flag: } async __detectPlatformVersion(config: any, body: any) { + const configuredVersion = + body.platformConfig.pythonVersion || + body.platformConfig.version || + body.platformConfig.phpVersion || + body.platformConfig.nodeVersion; + + if ( + configuredVersion && + isDeprecatedVersion(config.platform, configuredVersion) + ) { + throw new DeployException( + getDeprecatedVersionMessage( + config.platform, + configuredVersion, + 'your liara.json', + ), + ); + } + if (body.platformConfig.pythonVersion) { // django, flask this.logKeyValue('Python version', body.platformConfig.pythonVersion); @@ -724,6 +787,87 @@ Additionally, you can also retry the build with the debug flag: }); } + async logAppUrls(app: string, project: IProjectDetails) { + const { domains } = await this.got( + `v1/domains?project=${app}`, + ).json(); + + const urls = domains + .filter((domain) => domain.status === 'ACTIVE') + .reverse() + .slice(0, 5) + .map((domain) => { + const protocol: string = + domain.certificatesStatus === 'ACTIVE' ? 'https' : 'http'; + + return `${protocol}://${domain.name}`; + }); + const hasActiveDomain = urls.length > 0; + + const isSubdomainExpired = + project.defaultSubdomainExpired && !project.keepDefaultSubdomain; + + if (project.defaultSubdomain && !isSubdomainExpired) { + const defaultSubdomain = project.network + ? '.liara.run' + : '.iran.liara.run'; + + urls.push( + DEV_MODE + ? // tslint:disable-next-line: no-http-string + `http://${app}.liara.localhost` + : `https://${app}${defaultSubdomain}`, + ); + } + + if (urls.length) { + this.log(chalk.white('Open up the url below in your browser:')); + this.log(); + + for (const url of urls) { + this.log(chalk.white(` ${url}`)); + } + } + + const domainsPage = `https://console.liara.ir/apps/${app}/domains`; + + if (!urls.length) { + const reason = isSubdomainExpired + ? 'The default subdomain expired one week after the first deployment and is no longer available.' + : 'The default subdomain is disabled.'; + + this.warn( + `${reason}\nTo make your app reachable, add a domain or finish setting one up at ${domainsPage}`, + ); + } else if ( + !hasActiveDomain && + !project.keepDefaultSubdomain && + (await this.isDefaultSubdomainExpiring(app)) + ) { + this.warn( + `The default subdomain is only valid for one week after the first deployment.\nTo keep your app reachable, add a domain at ${domainsPage}`, + ); + } + } + + async isDefaultSubdomainExpiring(app: string): Promise { + try { + const { total } = await this.got( + `v1/projects/${app}/releases?page=1&count=1`, + ).json<{ total: number }>(); + + // Releases are listed newest first, so the last page holds the first one. + const { releases } = await this.got( + `v1/projects/${app}/releases?page=${total}&count=1`, + ).json<{ releases: { createdAt: string }[] }>(); + + return new Date(releases[0].createdAt) >= DEFAULT_SUBDOMAIN_EXPIRY_SINCE; + } catch (error) { + this.debug(error.stack); + return false; + } + } + parseFailReason(reason: string) { const [errorName, ...data] = reason.split(' '); @@ -731,6 +875,22 @@ Additionally, you can also retry the build with the debug flag: return `Could not find disk \`${data[0]}\`.`; } + if (errorName === 'APP_CRASHED') { + return 'Your app crashed after it started. Please check its logs.'; + } + + if (errorName === 'DISK_IS_NOT_DIRECTORY') { + return 'A disk can only be mounted to a directory, not a file.'; + } + + if (errorName === 'ENTRYPOINT_NOT_FOUND') { + return 'The ENTRYPOINT command was not found. Please check its logs.'; + } + + if (errorName === 'IMAGE_NOT_FOUND') { + return 'Could not find the image. Please make sure it is accessible.'; + } + return reason; } diff --git a/src/commands/init.ts b/src/commands/init.ts index a89c92c9..e9010871 100644 --- a/src/commands/init.ts +++ b/src/commands/init.ts @@ -12,7 +12,10 @@ import { promptPort } from '../utils/prompt-port.js'; import { AVAILABLE_PLATFORMS } from '../constants.js'; import IHealthConfig from '../types/health-config.js'; import detectPlatform from '../utils/detect-platform.js'; -import supportedVersions from '../utils/get-supported-versions.js'; +import supportedVersions, { + getDeprecatedVersionMessage, + isDeprecatedVersion, +} from '../utils/get-supported-versions.js'; import IGetProjectsResponse from '../types/get-project-response.js'; import { IDisk, IGetDiskResponse } from '../types/get-disk-response.js'; import IGetTeamsResponse from '../types/get-teams.js'; @@ -254,6 +257,16 @@ You can still create a sample 'liara.json' file using the 'liara init -y' comman flagValue: string | undefined, ): Promise { if (flagValue) { + if (isDeprecatedVersion(platform, flagValue)) { + this.error( + getDeprecatedVersionMessage( + platform, + flagValue, + 'the --version flag', + ), + ); + } + return flagValue; } diff --git a/src/constants.ts b/src/constants.ts index eb81c9be..0762a617 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -27,6 +27,11 @@ export const OBJECT_STORAGE_API_URL_DEV = 'http://localhost:3001'; export const FALLBACK_REGION = 'iran'; export const MAX_SOURCE_SIZE = 256 * 1024 * 1024; // 256 MiB +// Apps first deployed after this date lose their default subdomain one week +// after that deployment. +export const DEFAULT_SUBDOMAIN_EXPIRY_SINCE = new Date( + '2026-08-15T00:00:00.000Z', +); export const AVAILABLE_PLATFORMS = [ 'node', diff --git a/src/errors/bundle-plan.ts b/src/errors/bundle-plan.ts index 4dc31a4b..b70cc85c 100644 --- a/src/errors/bundle-plan.ts +++ b/src/errors/bundle-plan.ts @@ -1,3 +1,5 @@ +import { MAX_SOURCE_SIZE } from '../constants.js'; + export const BundlePlanError = { max_deploy_per_day(bundlePlan: string) { switch (bundlePlan) { @@ -10,34 +12,17 @@ export const BundlePlanError = { } }, - max_source_size(bundlePlan: string) { - switch (bundlePlan) { - case 'free': - return `The maximum source size is 128MB on the Free plan. Please reduce your source code size or consider upgrading your feature bundle plan.`; - case 'standard': - return `The maximum source size is 256MB on the Standard plan. Please reduce your source code size or consider upgrading your feature bundle plan.`; - default: - return `Maximum source size limit reached. Please reduce your source code size.`; + max_source_size(maxSourceSize?: number) { + if (!maxSourceSize) { + return `Maximum source size limit reached. Please reduce your source code size.`; } - }, - max_build_time(bundlePlan: string) { - switch (bundlePlan) { - case 'free': - return `The build timed out after 5 minutes on the Free plan. - Solutions: - 1. Try again later. - 2. Upgrade your feature bundle plan for more build time.`; - case 'standard': - return `The build timed out after 10 minutes on the Standard plan. - Solutions: - 1. Try again later. - 2. Upgrade your feature bundle plan for more build time.`; - case 'enterprise': - return `The build timed out after 20 minutes. Please Try again later.`; - default: - return `Build timed out. Please try again or consider upgrading your feature bundle plan for more build time.`; - } + const upgrade = + maxSourceSize * 1024 * 1024 < MAX_SOURCE_SIZE + ? ' or consider upgrading your feature bundle plan' + : ''; + + return `The maximum source size is ${maxSourceSize}MB. Please reduce your source code size${upgrade}.`; }, germany_builder_not_allowed(bundlePlan: string) { diff --git a/src/services/get-platform-version.ts b/src/services/get-platform-version.ts index 3c4503a8..43a79588 100644 --- a/src/services/get-platform-version.ts +++ b/src/services/get-platform-version.ts @@ -5,6 +5,11 @@ import findFile from '../utils/find-file.js'; import { execSync } from 'node:child_process'; import { DebugLogger } from '../utils/output.js'; import { platform } from 'node:os'; +import DeployException from '../errors/deploy-exception.js'; +import supportedVersions, { + getDeprecatedVersionMessage, + isDeprecatedVersion, +} from '../utils/get-supported-versions.js'; interface IPlatformConfig { [key: string]: string | null; @@ -102,6 +107,13 @@ async function getPlatformVersion( try { pureVersion = platformsVersionTrim[platform](dirtyVersion); debug(`The version is: ${pureVersion}`); + + // This is only what the developer has installed, not what the app requires. + if (isDeprecatedVersion(platform, pureVersion)) { + debug(`Ignoring the deprecated local version: ${pureVersion}`); + return null; + } + return pureVersion; } catch (error) { debug('Could not trim founded version'); @@ -175,19 +187,40 @@ function getPythonVersion(projectPath: string, debug: DebugLogger) { return null; } -function getNodeVersion(projectPath: string, debug: DebugLogger) { - const supportedNodeVersion = [ - '8', - '10', - '12', - '14', - '16', - '18', - '20', - '22', - '24', - ]; +// The supported versions a range allows, lowest first, ex: [22, 24] for >=18 +function findSupportedVersions( + platform: string, + range: string, + source: string, +): string[] { + if (!semver.validRange(range, { loose: true })) { + return []; + } + + const { allVersions } = supportedVersions(platform); + + const rangeVersions = allVersions + .filter((version) => + semver.intersects(`${version}.x`, range, { loose: true }), + ) + .sort((a, b) => semver.compare(semver.coerce(a)!, semver.coerce(b)!)); + + const isRangeDeprecated = + !rangeVersions.length && + allVersions.every((version) => + semver.gtr(semver.coerce(version)!, range, { loose: true }), + ); + + if (isRangeDeprecated) { + throw new DeployException( + getDeprecatedVersionMessage(platform, range, source), + ); + } + + return rangeVersions; +} +function getNodeVersion(projectPath: string, debug: DebugLogger) { const packageJson = path.join(projectPath, 'package.json'); const packageJsonData = fs.readJsonSync(packageJson); const requiredNode = packageJsonData.engines?.node; @@ -196,10 +229,28 @@ function getNodeVersion(projectPath: string, debug: DebugLogger) { const pureVersion = semver .coerce(requiredNode, { loose: true }) ?.version.split('.')[0]; // ex: extracts 18 from 18.0.0 - if (pureVersion && supportedNodeVersion.find((v) => v === pureVersion)) { + + if ( + pureVersion && + supportedVersions('node').allVersions.includes(pureVersion) + ) { return pureVersion; } - debug(`This node version is not suppurted: ${pureVersion}`); + + // Only a range starting from a deprecated version has to change, and it + // moves as little as it can, ex: 22 for >=18 + if (pureVersion && isDeprecatedVersion('node', pureVersion)) { + const [closestVersion] = findSupportedVersions( + 'node', + requiredNode, + 'engines.node in your package.json', + ); + if (closestVersion) { + return closestVersion; + } + } + + debug(`This node version is not suppurted: ${requiredNode}`); return -1; } return null; @@ -209,19 +260,6 @@ function getRequiredPHPVersion( projectPath: string, debug: DebugLogger, ): string | null { - // semver forces us to use the full semver syntax, - // but before returning the final result, we remove the last .0 part - const supportedPHPVersions = [ - '8.4.0', - '8.3.0', - '8.2.0', - '8.1.0', - '8.0.0', - '7.4.0', - '7.3.0', - '7.2.0', - ]; - try { const composerJson = fs.readJSONSync( path.join(projectPath, 'composer.json'), @@ -229,16 +267,22 @@ function getRequiredPHPVersion( if (composerJson?.config?.platform?.php) { const range = convertSinglePipeToDouble(composerJson.config.platform.php); - return normalizeVersion( - semver.maxSatisfying(supportedPHPVersions, range), + const versions = findSupportedVersions( + 'php', + range, + 'config.platform.php in your composer.json', ); + return versions.pop() ?? null; } if (composerJson?.require?.php) { const range = convertSinglePipeToDouble(composerJson.require.php); - return normalizeVersion( - semver.maxSatisfying(supportedPHPVersions, range), + const versions = findSupportedVersions( + 'php', + range, + 'require.php in your composer.json', ); + return versions.pop() ?? null; } return null; diff --git a/src/types/bundle-plan.ts b/src/types/bundle-plan.ts new file mode 100644 index 00000000..309bc041 --- /dev/null +++ b/src/types/bundle-plan.ts @@ -0,0 +1,5 @@ +export default interface IBundlePlan { + buildTimeout: number; + maxLogsRetention: number; + maxSourceSize: number; +} diff --git a/src/utils/get-supported-versions.ts b/src/utils/get-supported-versions.ts index 8e31e3ae..a2ae9bf6 100644 --- a/src/utils/get-supported-versions.ts +++ b/src/utils/get-supported-versions.ts @@ -1,3 +1,5 @@ +import semver from 'semver'; + interface IVersions { [platform: string]: { defaultVersion: string; @@ -21,17 +23,17 @@ const versions: IVersions = { ], }, node: { - defaultVersion: '22', - allVersions: ['14', '16', '18', '20', '22', '24'], + defaultVersion: '24', + allVersions: ['22', '24'], }, - next: { defaultVersion: '22', allVersions: ['20', '22', '24'] }, + next: { defaultVersion: '24', allVersions: ['22', '24'] }, laravel: { - defaultVersion: '8.2', - allVersions: ['8.4', '8.3', '8.2', '8.1', '8.0', '7.4', '7.3', '7.2'], + defaultVersion: '8.4', + allVersions: ['8.4', '8.3', '8.2'], }, php: { - defaultVersion: '8.0', - allVersions: ['8.4', '8.3', '8.2', '8.1', '8.0', '7.4', '7.3', '7.2'], + defaultVersion: '8.4', + allVersions: ['8.4', '8.3', '8.2'], }, python: { defaultVersion: '3.12', @@ -54,3 +56,33 @@ const versions: IVersions = { export default function supportedVersions(platform: string) { return versions[platform as keyof typeof versions]; } + +// Only versions older than every supported one are deprecated, so a newer +// version the API starts supporting doesn't need a CLI release. +export function isDeprecatedVersion( + platform: string, + version: number | string, +): boolean { + const parsedVersion = semver.coerce(version); + const platformVersions = supportedVersions(platform); + + if (!parsedVersion || !platformVersions) { + return false; + } + + return platformVersions.allVersions.every((supported) => + semver.lt(parsedVersion, semver.coerce(supported)!), + ); +} + +export function getDeprecatedVersionMessage( + platform: string, + version: number | string, + source: string, +): string { + const { allVersions } = supportedVersions(platform); + + return `Version ${version} is no longer supported on the ${platform} platform. +Supported versions: ${allVersions.join(', ')} +Please update ${source}.`; +} diff --git a/test/app/logs.unit.test.ts b/test/app/logs.unit.test.ts index 094e17ee..e3869d49 100644 --- a/test/app/logs.unit.test.ts +++ b/test/app/logs.unit.test.ts @@ -331,6 +331,66 @@ describe('app:logs', function () { }); } + describe('when deploy has already loaded the plans', () => { + afterEach(() => { + AppLogs.maxLogsRetention = undefined; + }); + + it('does not load them again', async () => { + AppLogs.maxLogsRetention = 7; + expectProject(); + expectLogs([]); + + const { error } = await runCommand(['app:logs', '--app', app]); + + expect(error).to.equal(undefined); + }); + + it('accepts a retention shorter than a day', async () => { + AppLogs.maxLogsRetention = 0.05; + expectProject(); + expectLogs([]); + + const { error } = await runCommand([ + 'app:logs', + '--app', + app, + '--since', + '"1 hour ago"', + ]); + + expect(error).to.equal(undefined); + }); + + it('still enforces the retention', async () => { + AppLogs.maxLogsRetention = 0.05; + stubProcessExit(); + expectProject(); + + const { error } = await runCommand([ + 'app:logs', + '--app', + app, + '--since', + '"2 hours ago"', + ]); + + expect(error?.message).to.equal('process.exit(2)'); + }); + }); + + it('does not let users set the retention', async () => { + const { error } = await runCommand([ + 'app:logs', + '--app', + app, + '--max-logs-retention', + '9999', + ]); + + expect(error?.message).to.contain('Nonexistent flag'); + }); + it('throws an error if the app runs on the old infrastructure', async () => { stubProcessExit(); expectProject({ ...getNodeProject.project, network: undefined }); diff --git a/test/deploy/deploy.unit.test.ts b/test/deploy/deploy.unit.test.ts index fe079af6..ce9d83c5 100644 --- a/test/deploy/deploy.unit.test.ts +++ b/test/deploy/deploy.unit.test.ts @@ -2,17 +2,42 @@ import { expect } from 'chai'; import sinon from 'sinon'; import { runCommand } from '@oclif/test'; import deploy from '../../src/commands/deploy.ts'; +import Logs from '../../src/commands/app/logs.ts'; import nock from 'nock'; import fs from 'fs-extra'; import { getNodeProject, getDockerProject, } from '../fixtures/projects/fixture.ts'; -import { stubGlobalConfig } from '../helpers/stubs.ts'; +import { stubGlobalConfig, stubProcessExit } from '../helpers/stubs.ts'; describe('deploy', () => { const api = nock('https://api.liara.ir'); + const mockBundlePlan = (bundlePlan: object) => + api + .get('/v1/me') + .query({ teamID: '' }) + .reply(200, { + plans: { + projectBundlePlans: { + [getNodeProject.project.planID]: { + [getNodeProject.project.bundlePlanID]: bundlePlan, + }, + }, + }, + }); + + // For tests where loading the plans would be an extra request to a heavy + // endpoint. Call expectPlansNotLoaded() at the end of the test. + const mockUnexpectedPlans = () => + api.get('/v1/me').query(true).reply(200, {}); + + const expectPlansNotLoaded = () => { + expect(api.pendingMocks().join()).to.contain('/v1/me'); + nock.cleanAll(); + }; + let getConfigs: sinon.SinonStub; beforeEach(() => { stubGlobalConfig(); @@ -20,6 +45,7 @@ describe('deploy', () => { }); afterEach(() => { sinon.restore(); + Logs.maxLogsRetention = undefined; }); it('should thorw an error when project path is empty and image flag is specified', async () => { fs.mkdirSync('test/fixtures/empty-project'); @@ -158,4 +184,576 @@ describe('deploy', () => { 'Maximum source size limit reached. Please reduce your source code size.', ); }); + + describe('when the release finishes', () => { + const app = getNodeProject.project.project_id; + const defaultUrl = `https://${app}.liara.run`; + const domainsPage = `https://console.liara.ir/apps/${app}/domains`; + + const domain = (name: string, overrides = {}) => ({ + name, + status: 'ACTIVE', + certificatesStatus: 'ACTIVE', + ...overrides, + }); + + const mockProject = (overrides = {}) => + api + .get(`/v1/projects/${app}`) + .query({ teamID: '' }) + .reply(200, { project: { ...getNodeProject.project, ...overrides } }); + + const mockDomains = (domains: object[]) => + api + .get('/v1/domains') + .query({ project: app, teamID: '' }) + .reply(200, { domains }); + + const mockFirstRelease = (createdAt: string) => { + api + .get(`/v1/projects/${app}/releases`) + .query({ page: 1, count: 1, teamID: '' }) + .reply(200, { total: 3, releases: [] }); + api + .get(`/v1/projects/${app}/releases`) + .query({ page: 3, count: 1, teamID: '' }) + .reply(200, { total: 3, releases: [{ createdAt }] }); + }; + + beforeEach(() => { + nock.disableNetConnect(); + sinon + .stub(deploy.prototype, 'deploy') + .resolves({ releaseID: 'release-id' } as any); + }); + + afterEach(() => { + api.done(); + nock.cleanAll(); + nock.enableNetConnect(); + }); + + describe('successfully', () => { + beforeEach(() => { + getConfigs.returns({ + path: 'test/fixtures/docker-platform', + app, + image: 'nginx', + port: 80, + }); + sinon.stub(deploy.prototype, 'showReleaseLogs').resolves(); + sinon.stub(Logs, 'run').resolves(); + }); + + it('shows the active domains instead of an expired subdomain', async () => { + mockProject({ defaultSubdomainExpired: true }); + mockDomains([domain('example.com')]); + + const { stdout, stderr } = await runCommand(['deploy']); + + expect(stdout).to.contain('https://example.com'); + expect(stdout).not.to.contain('liara.run'); + expect(stderr).not.to.contain('Warning'); + }); + + it('warns instead of showing a url when the subdomain expired and no domain is active', async () => { + mockProject({ defaultSubdomainExpired: true }); + mockDomains([ + domain('pending.example.com', { + status: 'PENDING', + certificatesStatus: 'PENDING', + }), + ]); + + const { stdout, stderr, error } = await runCommand(['deploy']); + + expect(error).to.equal(undefined); + expect(stdout).to.contain('Deployment finished successfully.'); + expect(stdout).not.to.contain('Open up the url'); + expect(stdout).not.to.contain('liara.run'); + expect(stdout).not.to.contain('pending.example.com'); + expect(stderr).to.contain('expired'); + expect(stderr).to.contain(domainsPage); + }); + + it('shows an expired subdomain the project keeps', async () => { + mockProject({ + defaultSubdomainExpired: true, + keepDefaultSubdomain: true, + }); + mockDomains([]); + + const { stdout, stderr } = await runCommand(['deploy']); + + expect(stdout).to.contain(defaultUrl); + expect(stderr).not.to.contain('Warning'); + }); + + it('shows the domains first, then a subdomain that is still valid', async () => { + mockProject(); + mockDomains([domain('old.example.com'), domain('new.example.com')]); + + const { stdout, stderr } = await runCommand(['deploy']); + + const urls = stdout.match(/https?:\/\/\S+/g); + expect(urls).to.deep.equal([ + 'https://new.example.com', + 'https://old.example.com', + defaultUrl, + ]); + expect(stderr).not.to.contain('Warning'); + }); + + it('uses http for a domain without an active certificate', async () => { + mockProject(); + mockDomains([domain('example.com', { certificatesStatus: 'PENDING' })]); + + const { stdout } = await runCommand(['deploy']); + + expect(stdout).to.contain('http://example.com'); + }); + + it('does not show a disabled subdomain', async () => { + mockProject({ defaultSubdomain: false }); + mockDomains([]); + + const { stdout, stderr } = await runCommand(['deploy']); + + expect(stdout).not.to.contain('liara.run'); + expect(stderr).to.contain('disabled'); + expect(stderr).to.contain(domainsPage); + }); + + it('uses the iran subdomain for an app without a network', async () => { + mockProject({ network: undefined }); + mockDomains([]); + mockFirstRelease('2026-01-01T00:00:00.000Z'); + + const { stdout } = await runCommand(['deploy']); + + expect(stdout).to.contain(`https://${app}.iran.liara.run`); + }); + + it('warns that a subdomain will expire when no domain is active', async () => { + mockProject(); + mockDomains([]); + mockFirstRelease('2026-09-01T00:00:00.000Z'); + + const { stdout, stderr } = await runCommand(['deploy']); + + expect(stdout).to.contain(defaultUrl); + expect(stderr).to.contain('one week'); + expect(stderr).to.contain(domainsPage); + }); + + it('does not warn about expiry for an app first deployed before the rollout', async () => { + mockProject(); + mockDomains([]); + mockFirstRelease('2026-01-01T00:00:00.000Z'); + + const { stdout, stderr } = await runCommand(['deploy']); + + expect(stdout).to.contain(defaultUrl); + expect(stderr).not.to.contain('Warning'); + }); + + it('still shows the url when the first release can not be loaded', async () => { + mockProject(); + mockDomains([]); + api + .get(`/v1/projects/${app}/releases`) + .query({ page: 1, count: 1, teamID: '' }) + .reply(403); + + const { stdout, stderr, error } = await runCommand(['deploy']); + + expect(error).to.equal(undefined); + expect(stdout).to.contain(defaultUrl); + expect(stderr).not.to.contain('Warning'); + }); + + it('does not fail the deployment when the domains can not be loaded', async () => { + mockProject(); + api.get('/v1/domains').query({ project: app, teamID: '' }).reply(403); + + const { stdout, stderr, error } = await runCommand(['deploy']); + + expect(error).to.equal(undefined); + expect(stdout).to.contain('Deployment finished successfully.'); + expect(stdout).to.contain('Reading app logs...'); + expect(stderr).to.contain(domainsPage); + }); + + it('passes the log retention of the bundle plan to the app logs', async () => { + mockProject(); + mockDomains([domain('example.com')]); + mockBundlePlan({ maxLogsRetention: 0.05 }); + + await runCommand(['deploy']); + + expect(Logs.maxLogsRetention).to.equal(0.05); + }); + + it('lets the app logs load the plans if they could not be loaded', async () => { + mockProject(); + mockDomains([domain('example.com')]); + api.get('/v1/me').query({ teamID: '' }).reply(403); + + await runCommand(['deploy']); + + expect(Logs.maxLogsRetention).to.equal(undefined); + }); + + it('does not load the plans with --no-app-logs', async () => { + stubProcessExit({ throws: false }); + mockProject(); + mockDomains([domain('example.com')]); + mockUnexpectedPlans(); + + await runCommand(['deploy', '--no-app-logs']); + + expectPlansNotLoaded(); + }); + + it('does not load the plans for an app on the old infrastructure', async () => { + mockProject({ network: undefined }); + mockDomains([domain('example.com')]); + mockUnexpectedPlans(); + + await runCommand(['deploy']); + + expectPlansNotLoaded(); + }); + }); + + describe('unsuccessfully', () => { + const mockBuildLogs = (release: object) => { + api + .get('/v1/releases/release-id') + .query({ teamID: '' }) + .reply(200, { release: {} }); + api + .get('/v2/releases/release-id/build-logs') + .query(true) + .reply(200, { release, buildOutput: [] }); + }; + + beforeEach(() => { + getConfigs.returns({ + path: 'test/fixtures/simple-gitignore', + app, + platform: 'static', + }); + mockProject(); + }); + + it('shows why a build release failed', async () => { + mockBuildLogs({ state: 'FAILED', failReason: 'disk_not_found media' }); + + const { error } = await runCommand(['deploy']); + + expect(error?.message).to.equal('Could not find disk `media`.'); + }); + + it('shows why an image release failed', async () => { + getConfigs.returns({ + path: 'test/fixtures/docker-platform', + app, + image: 'nginx', + port: 80, + }); + api + .get('/v1/releases/release-id') + .query({ teamID: '' }) + .reply(200, { + release: { state: 'FAILED', failReason: 'IMAGE_NOT_FOUND' }, + }); + + const { error } = await runCommand(['deploy']); + + expect(error?.message).to.equal( + 'Could not find the image. Please make sure it is accessible.', + ); + }); + + it('explains the options when the build times out', async () => { + mockBuildLogs({ state: 'TIMEDOUT' }); + + const { error } = await runCommand(['deploy']); + + expect(error?.message).to.contain('Build timed out.'); + expect(error?.message).not.to.contain('20 minutes'); + expect(error?.message).to.contain( + `https://console.liara.ir/apps/${app}/resize`, + ); + }); + + it('shows the build time the bundle plan allows', async () => { + mockBundlePlan({ buildTimeout: 15 }); + mockBuildLogs({ state: 'TIMEDOUT' }); + + const { error } = await runCommand(['deploy']); + + expect(error?.message).to.contain( + 'It took longer than the 15 minutes your feature bundle plan allows.', + ); + }); + }); + + it('explains every known fail reason', () => { + const { parseFailReason } = deploy.prototype; + + for (const reason of [ + 'APP_CRASHED', + 'DISK_IS_NOT_DIRECTORY', + 'ENTRYPOINT_NOT_FOUND', + 'IMAGE_NOT_FOUND', + ]) { + expect(parseFailReason(reason)).not.to.contain(reason); + } + + expect(parseFailReason('some other reason')).to.equal( + 'some other reason', + ); + }); + }); + + describe('before creating the release', () => { + const app = getNodeProject.project.project_id; + + const mockUpload = () => + api + .post(`/v2/projects/${app}/sources`) + .query({ teamID: '' }) + .reply(200, { sourceID: 'source-id' }); + + const mockRelease = () => + api + .post(`/v2/projects/${app}/releases`) + .query({ teamID: '' }) + .reply(200, { releaseID: 'release-id' }); + + beforeEach(() => { + nock.disableNetConnect(); + getConfigs.returns({ + path: 'test/fixtures/simple-gitignore', + app, + platform: 'static', + }); + api + .get(`/v1/projects/${app}`) + .query({ teamID: '' }) + .reply(200, getNodeProject); + }); + + afterEach(() => { + api.done(); + nock.cleanAll(); + nock.enableNetConnect(); + }); + + describe('source size', () => { + const MB = 1024 * 1024; + + // Reports the archive as this size, without having to build a huge one. + const stubSourceSize = (size: number) => { + const { statSync } = fs; + sinon + .stub(fs, 'statSync') + .callsFake(((file: string) => + file.endsWith('.tar.gz') ? { size } : statSync(file)) as any); + }; + + describe('with --detach', () => { + it('rejects a source over 256MB without uploading it', async () => { + stubSourceSize(256 * MB + 1); + + const { error } = await runCommand(['deploy', '--detach']); + + expect(error?.message).to.equal( + 'The maximum source size is 256MB. Please reduce your source code size.', + ); + }); + + it('uploads a source of exactly 256MB', async () => { + stubSourceSize(256 * MB); + mockUpload(); + mockRelease(); + + const { stdout } = await runCommand(['deploy', '--detach']); + + expect(stdout).to.contain('Deployment created successfully.'); + }); + + it('does not load the plans', async () => { + mockUnexpectedPlans(); + mockUpload(); + mockRelease(); + + await runCommand(['deploy', '--detach']); + + expectPlansNotLoaded(); + }); + }); + + describe('when the app logs will load the plans anyway', () => { + beforeEach(() => { + sinon.stub(deploy.prototype, 'showBuildLogs').resolves(); + sinon.stub(deploy.prototype, 'logAppUrls').resolves(); + sinon.stub(Logs, 'run').resolves(); + }); + + it('rejects a source over the limit of the bundle plan', async () => { + mockBundlePlan({ maxSourceSize: 128 }); + stubSourceSize(128 * MB + 1); + + const { error } = await runCommand(['deploy']); + + expect(error?.message).to.equal( + 'The maximum source size is 128MB. Please reduce your source code size or consider upgrading your feature bundle plan.', + ); + }); + + it('uploads a source of exactly the limit of the bundle plan', async () => { + mockBundlePlan({ maxSourceSize: 128 }); + stubSourceSize(128 * MB); + mockUpload(); + mockRelease(); + + const { stdout, error } = await runCommand(['deploy']); + + expect(error).to.equal(undefined); + expect(stdout).to.contain('Deployment finished successfully.'); + }); + + it('allows more than 256MB if the bundle plan does', async () => { + mockBundlePlan({ maxSourceSize: 512 }); + stubSourceSize(300 * MB); + mockUpload(); + mockRelease(); + + const { error } = await runCommand(['deploy']); + + expect(error).to.equal(undefined); + }); + + it('names the limit of the bundle plan when the API rejects the size', async () => { + mockBundlePlan({ maxSourceSize: 128 }); + api + .post(`/v2/projects/${app}/sources`) + .query({ teamID: '' }) + .reply(413, '

413 Request Entity Too Large

'); + + const { error } = await runCommand(['deploy']); + + expect(error?.message).to.contain( + 'The maximum source size is 128MB.', + ); + }); + + it('falls back to 256MB if the plans can not be loaded', async () => { + api.get('/v1/me').query({ teamID: '' }).reply(403); + stubSourceSize(256 * MB + 1); + + const { error } = await runCommand(['deploy']); + + expect(error?.message).to.contain( + 'The maximum source size is 256MB.', + ); + }); + + for (const [type, body] of [ + ['JSON', { message: 'unauthorized' }], + ['text', 'unauthorized'], + ] as const) { + it(`still deploys if loading the plans gets a 401 with a ${type} body`, async () => { + const { stub: exit } = stubProcessExit(); + api.get('/v1/me').query({ teamID: '' }).reply(401, body); + mockUpload(); + mockRelease(); + + const { stdout, error } = await runCommand(['deploy']); + + expect(exit.called).to.equal(false); + expect(error).to.equal(undefined); + expect(stdout).to.contain('Deployment finished successfully.'); + }); + } + + it('falls back to 256MB if the bundle plan has no limit', async () => { + mockBundlePlan({ maxSourceSize: null }); + stubSourceSize(10 * MB); + mockUpload(); + mockRelease(); + + const { error } = await runCommand(['deploy']); + + expect(error).to.equal(undefined); + }); + + it('falls back to 256MB for a plan without a bundle plan', async () => { + api + .get('/v1/me') + .query({ teamID: '' }) + .reply(200, { plans: { projectBundlePlans: {} } }); + stubSourceSize(256 * MB + 1); + + const { error } = await runCommand(['deploy']); + + expect(error?.message).to.contain( + 'The maximum source size is 256MB.', + ); + }); + }); + }); + + describe('platform version in liara.json', () => { + for (const [platform, platformConfig, version] of [ + ['php', { version: '7.4' }, '7.4'], + ['laravel', { phpVersion: '8.1' }, '8.1'], + ['next', { nodeVersion: '20' }, '20'], + ['next', { nodeVersion: 20 }, '20'], + ['django', { pythonVersion: '3.6' }, '3.6'], + ['go', { version: '1.20' }, '1.20'], + ] as const) { + it(`rejects ${platform} ${version}`, async () => { + getConfigs.returns({ + path: 'test/fixtures/simple-gitignore', + app, + platform, + port: 80, + [platform]: platformConfig, + }); + + const { error } = await runCommand(['deploy', '--detach']); + + expect(error?.message).to.contain( + `Version ${version} is no longer supported on the ${platform} platform.`, + ); + expect(error?.message).to.contain('liara.json'); + }); + } + + it('sends a supported version', async () => { + getConfigs.returns({ + path: 'test/fixtures/simple-gitignore', + app, + platform: 'php', + php: { version: '8.4' }, + }); + mockUpload(); + api + .post( + `/v2/projects/${app}/releases`, + (body) => body.platformConfig.version === '8.4', + ) + .query({ teamID: '' }) + .reply(200, { releaseID: 'release-id' }); + + const { stdout } = await runCommand(['deploy', '--detach']); + + expect(stdout).to.contain('Deployment created successfully.'); + }); + }); + }); }); diff --git a/test/init/init.unit.test.ts b/test/init/init.unit.test.ts new file mode 100644 index 00000000..e2444129 --- /dev/null +++ b/test/init/init.unit.test.ts @@ -0,0 +1,49 @@ +import sinon from 'sinon'; +import inquirer from 'inquirer'; +import { expect } from 'chai'; +import Init from '../../src/commands/init.ts'; + +describe('init', function () { + const promptPlatformVersion = (platform: string, version?: string) => + Init.prototype.promptPlatformVersion.call( + Object.create(Init.prototype), + platform, + version, + ); + + afterEach(() => { + sinon.restore(); + }); + + it('rejects a deprecated version from the flag', async () => { + const error = await promptPlatformVersion('node', '18').catch( + (error) => error, + ); + + expect(error.message).to.contain('Version 18 is no longer supported'); + expect(error.message).to.contain('--version'); + }); + + it('accepts a supported version from the flag', async () => { + expect(await promptPlatformVersion('node', '24')).to.equal('24'); + }); + + for (const [platform, defaultVersion, versions] of [ + ['node', '24', ['22', '24']], + ['next', '24', ['22', '24']], + ['php', '8.4', ['8.4', '8.3', '8.2']], + ['laravel', '8.4', ['8.4', '8.3', '8.2']], + ] as const) { + it(`only offers the supported ${platform} versions`, async () => { + const prompt = sinon + .stub(inquirer, 'prompt') + .resolves({ version: defaultVersion }); + + await promptPlatformVersion(platform); + + const question = prompt.firstCall.args[0] as any; + expect(question.choices).to.deep.equal(versions); + expect(question.default).to.equal(defaultVersion); + }); + } +}); diff --git a/test/services/get-platform-version.unit.test.ts b/test/services/get-platform-version.unit.test.ts new file mode 100644 index 00000000..1b698f80 --- /dev/null +++ b/test/services/get-platform-version.unit.test.ts @@ -0,0 +1,190 @@ +import os from 'node:os'; +import path from 'node:path'; +import fs from 'fs-extra'; +import { expect } from 'chai'; +import getPlatformVersion from '../../src/services/get-platform-version.ts'; +import DeployException from '../../src/errors/deploy-exception.ts'; +import { isDeprecatedVersion } from '../../src/utils/get-supported-versions.ts'; + +describe('getPlatformVersion', () => { + const originalPath = process.env.PATH; + let projectPath: string; + + beforeEach(() => { + projectPath = fs.mkdtempSync(path.join(os.tmpdir(), 'liara-version-')); + }); + + afterEach(() => { + process.env.PATH = originalPath; + fs.removeSync(projectPath); + }); + + // Makes a runtime report the given version, as if the developer installed it. + const stubLocalRuntime = (command: string, output: string) => { + const bin = path.join(projectPath, 'bin'); + fs.ensureDirSync(bin); + fs.writeFileSync(path.join(bin, command), `#!/bin/sh\necho "${output}"\n`, { + mode: 0o755, + }); + process.env.PATH = `${bin}${path.delimiter}${originalPath}`; + }; + + const writeEngines = (node?: string) => + fs.writeJsonSync(path.join(projectPath, 'package.json'), { + engines: node ? { node } : undefined, + }); + + const writeComposer = (composer: object) => + fs.writeJsonSync(path.join(projectPath, 'composer.json'), composer); + + describe('node', () => { + for (const [range, version] of [ + ['24', '24'], + ['22.x', '22'], + ['22.1.0', '22'], + // A supported app stays on the version the range starts from. + ['>=22', '22'], + ['^22 || ^24', '22'], + ['<=24', '24'], + // Otherwise it moves to the closest version the range allows. + ['>=18', '22'], + ['^20 || ^22', '22'], + ['^20 || ^24', '24'], + ]) { + it(`uses ${version} for engines.node ${range}`, async () => { + writeEngines(range); + + expect(await getPlatformVersion('node', projectPath)).to.equal(version); + }); + } + + for (const range of ['18', '18.x', '^20.0.0', '<=20']) { + it(`rejects engines.node ${range}`, async () => { + writeEngines(range); + + const error = await getPlatformVersion('node', projectPath).catch( + (error) => error, + ); + + expect(error).to.be.instanceOf(DeployException); + expect(error.message).to.contain(`Version ${range} is no longer`); + expect(error.message).to.contain('22, 24'); + expect(error.message).to.contain('engines.node'); + }); + } + + it('leaves a newer engines.node to the API', async () => { + writeEngines('26'); + + expect(await getPlatformVersion('node', projectPath)).to.equal(null); + }); + + for (const range of ['lts', '*']) { + it(`leaves engines.node ${range} to the API`, async () => { + writeEngines(range); + + expect(await getPlatformVersion('node', projectPath)).to.equal(null); + }); + } + + it('does not send a deprecated local version', async () => { + writeEngines(); + stubLocalRuntime('node', 'v18.20.0'); + + expect(await getPlatformVersion('node', projectPath)).to.equal(null); + }); + + it('sends a supported local version', async () => { + writeEngines(); + stubLocalRuntime('node', 'v24.1.0'); + + expect(await getPlatformVersion('node', projectPath)).to.equal('24'); + }); + }); + + for (const platform of ['php', 'laravel']) { + describe(platform, () => { + for (const [range, version] of [ + ['^8.1', '8.4'], + ['^7.4|^8.0', '8.4'], + ['>=7.4', '8.4'], + ['8.2.5', '8.2'], + ]) { + it(`uses ${version} for require.php ${range}`, async () => { + writeComposer({ require: { php: range } }); + + expect(await getPlatformVersion(platform, projectPath)).to.equal( + version, + ); + }); + } + + it('prefers config.platform.php', async () => { + writeComposer({ + config: { platform: { php: '8.3.1' } }, + require: { php: '^8.2' }, + }); + + expect(await getPlatformVersion(platform, projectPath)).to.equal('8.3'); + }); + + for (const range of ['^7.4', '8.1.*', '<8.2']) { + it(`rejects require.php ${range}`, async () => { + writeComposer({ require: { php: range } }); + + const error = await getPlatformVersion(platform, projectPath).catch( + (error) => error, + ); + + expect(error).to.be.instanceOf(DeployException); + expect(error.message).to.contain('8.4, 8.3, 8.2'); + expect(error.message).to.contain('composer.json'); + }); + } + + it('does not send a deprecated local version', async () => { + writeComposer({}); + stubLocalRuntime('php', 'PHP 7.4.33 (cli)'); + + expect(await getPlatformVersion(platform, projectPath)).to.equal(null); + }); + }); + } + + it('does not send a deprecated local python version', async () => { + stubLocalRuntime('python', 'Python 3.6.9'); + + expect(await getPlatformVersion('python', projectPath)).to.equal(null); + }); +}); + +describe('isDeprecatedVersion', () => { + for (const [platform, version] of [ + ['node', 20], + ['node', '18'], + ['next', '20'], + ['php', '8.1'], + ['laravel', '7.4'], + ['python', '3.6'], + ['go', '1.20'], + ] as const) { + it(`treats ${platform} ${version} as deprecated`, () => { + expect(isDeprecatedVersion(platform, version)).to.equal(true); + }); + } + + for (const [platform, version] of [ + ['node', 22], + ['node', '26'], + ['next', '24'], + ['php', '8.2'], + ['python', '3.10'], + ['go', '1.25'], + ['node', 'latest'], + ['docker', '1'], + ] as const) { + it(`does not treat ${platform} ${version} as deprecated`, () => { + expect(isDeprecatedVersion(platform, version)).to.equal(false); + }); + } +}); From 60f4905d55afa8a42ab8db44c0e118f2d91ad532 Mon Sep 17 00:00:00 2001 From: Amin Ehterami Date: Thu, 5 Nov 2026 16:41:02 +0330 Subject: [PATCH 2/3] fix: show the new release's startup logs after deploy --- src/commands/app/logs.ts | 5 ++++- src/commands/deploy.ts | 8 +++++++- test/app/logs.unit.test.ts | 29 +++++++++++++++++++++++++++++ test/deploy/deploy.unit.test.ts | 33 +++++++++++++++++++++++++++++++++ 4 files changed, 73 insertions(+), 2 deletions(-) diff --git a/src/commands/app/logs.ts b/src/commands/app/logs.ts index 764999fc..0450c7a5 100644 --- a/src/commands/app/logs.ts +++ b/src/commands/app/logs.ts @@ -109,6 +109,9 @@ export default class AppLogs extends Command { // streams the logs. It isn't a flag so that it can't be set by users. static maxLogsRetention?: number; + // Also set by `liara deploy`, to show only the release it just created. + static releaseId?: string; + #timestamps = false; #colorize = false; #releaseTagMap: Map = new Map(); // cache to store releaseId with it's tag @@ -172,7 +175,7 @@ export default class AppLogs extends Command { } // Get releaseId if release flag is provided - let releaseId: string | undefined; + let { releaseId } = AppLogs; if (release) { releaseId = await this.getReleaseIdFromTag(project, release); if (!releaseId) { diff --git a/src/commands/deploy.ts b/src/commands/deploy.ts index 49c61ee7..b98001ac 100644 --- a/src/commands/deploy.ts +++ b/src/commands/deploy.ts @@ -236,6 +236,10 @@ export default class Deploy extends Command { bundlePlan = await this.getBundlePlan(project); } + // The app's startup output is written before the health check finishes, + // so the logs shown afterwards have to start from before the deployment. + const deployStartedAt = new Date().toISOString(); + const response = await this.deploy(config, bundlePlan?.maxSourceSize); if (flags.detach) { @@ -265,11 +269,12 @@ export default class Deploy extends Command { this.log('Reading app logs...'); Logs.maxLogsRetention = bundlePlan?.maxLogsRetention; + Logs.releaseId = response.releaseID; await Logs.run([ '--app', config.app, '--since', - '10s ago', + deployStartedAt, '--follow', '--timestamps', '--colorize', @@ -277,6 +282,7 @@ export default class Deploy extends Command { config['api-token'] || '', '--team-id', config['team-id'] || '', + ...(flags.debug ? ['--debug'] : []), ]); } } catch (error) { diff --git a/test/app/logs.unit.test.ts b/test/app/logs.unit.test.ts index e3869d49..62403625 100644 --- a/test/app/logs.unit.test.ts +++ b/test/app/logs.unit.test.ts @@ -248,6 +248,35 @@ describe('app:logs', function () { expect(stdout).to.equal('from v2\n'); }); + describe('when deploy has just created a release', () => { + afterEach(() => { + AppLogs.releaseId = undefined; + }); + + it('fetches only the logs of that release', async () => { + const t = now() - 60; + AppLogs.releaseId = 'release-2'; + expectProject(); + expectPlans(); + expectLogs( + [ + { + metaData: { releaseId: 'release-2' }, + values: [line(t, 'from v2')], + }, + ], + (q) => q.releaseId === 'release-2', + ); + expectReleases(); + expectLogs([], (q) => q.releaseId === 'release-2'); + + const { stdout, error } = await runCommand(['app:logs', '--app', app]); + + expect(error).to.equal(undefined); + expect(stdout).to.equal('from v2\n'); + }); + }); + it('throws an error if the release does not exist', async () => { stubProcessExit(); expectProject(); diff --git a/test/deploy/deploy.unit.test.ts b/test/deploy/deploy.unit.test.ts index ce9d83c5..625d1edf 100644 --- a/test/deploy/deploy.unit.test.ts +++ b/test/deploy/deploy.unit.test.ts @@ -46,6 +46,7 @@ describe('deploy', () => { afterEach(() => { sinon.restore(); Logs.maxLogsRetention = undefined; + Logs.releaseId = undefined; }); it('should thorw an error when project path is empty and image flag is specified', async () => { fs.mkdirSync('test/fixtures/empty-project'); @@ -404,6 +405,38 @@ describe('deploy', () => { expect(Logs.maxLogsRetention).to.equal(undefined); }); + it('shows the logs of the new release from before it was created', async () => { + let releaseCreatedAt = 0; + (deploy.prototype.deploy as sinon.SinonStub).callsFake(async () => { + await new Promise((resolve) => setTimeout(resolve, 5)); + releaseCreatedAt = Date.now(); + return { releaseID: 'release-id' }; + }); + mockProject(); + mockDomains([domain('example.com')]); + + await runCommand(['deploy']); + + const args = (Logs.run as sinon.SinonStub).firstCall + .args[0] as string[]; + const since = Date.parse(args[args.indexOf('--since') + 1]); + + expect(Logs.releaseId).to.equal('release-id'); + expect(since).to.be.below(releaseCreatedAt); + expect(args).not.to.include('--debug'); + }); + + it('passes --debug on to the app logs', async () => { + mockProject(); + mockDomains([domain('example.com')]); + + await runCommand(['deploy', '--debug']); + + expect((Logs.run as sinon.SinonStub).firstCall.args[0]).to.include( + '--debug', + ); + }); + it('does not load the plans with --no-app-logs', async () => { stubProcessExit({ throws: false }); mockProject(); From 6615bfb6b5f2e3fb66ae4fc15a45e5865a5495e9 Mon Sep 17 00:00:00 2001 From: Amin Ehterami Date: Thu, 5 Nov 2026 16:55:32 +0330 Subject: [PATCH 3/3] update deploy bugs --- test/deploy/deploy.unit.test.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/test/deploy/deploy.unit.test.ts b/test/deploy/deploy.unit.test.ts index 625d1edf..31c5d523 100644 --- a/test/deploy/deploy.unit.test.ts +++ b/test/deploy/deploy.unit.test.ts @@ -437,6 +437,20 @@ describe('deploy', () => { ); }); + // The GitHub Actions workflow in the docs deploys with this flag, so the + // job has to finish here instead of following the logs. + it('exits without reading the app logs with --no-app-logs', async () => { + const { stub: exit } = stubProcessExit(); + mockProject(); + mockDomains([domain('example.com')]); + + await runCommand(['deploy', '--no-app-logs']); + + expect(exit.firstCall.args).to.deep.equal([0]); + expect((Logs.run as sinon.SinonStub).called).to.equal(false); + expect(Logs.releaseId).to.equal(undefined); + }); + it('does not load the plans with --no-app-logs', async () => { stubProcessExit({ throws: false }); mockProject();