From c06d2d94f416165d5274fa392560e5f13b58f610 Mon Sep 17 00:00:00 2001 From: Joe Tannenbaum Date: Fri, 13 Nov 2026 15:14:55 -0500 Subject: [PATCH] default to scale to zero mysql --- app/Commands/NewApplication.php | 2 +- app/Commands/Ship.php | 42 +++++----- app/Concerns/ProvisionsDefaultResources.php | 21 ++--- skills/deploying-to-cloud/SKILL.md | 2 +- tests/Feature/DatabaseClusterCreateTest.php | 5 +- tests/Feature/InstanceUpdateTest.php | 24 ------ tests/Feature/ShipDatabaseTest.php | 44 +++++++++- tests/Feature/ShipScaleToZeroTest.php | 92 +++++++++++++++++++++ tests/Helpers.php | 27 +++++- 9 files changed, 196 insertions(+), 63 deletions(-) create mode 100644 tests/Feature/ShipScaleToZeroTest.php diff --git a/app/Commands/NewApplication.php b/app/Commands/NewApplication.php index 594f1d84..c001cd6f 100644 --- a/app/Commands/NewApplication.php +++ b/app/Commands/NewApplication.php @@ -53,7 +53,7 @@ class NewApplication extends BaseCommand {--name= : Application name. Default: the repository name} {--region= : Region. Default: most-used or us-east-2} {--path= : Where to clone the repository. Default: ./} - {--database= : Database type or alias (postgres, postgres, mysql, none, or a type from `cloud database:types`). Default: postgres for Laravel kits, none otherwise} + {--database= : Database type or alias (postgres, postgres, mysql, none, or a type from `cloud database:types`). Default: mysql (postgres where MySQL is not offered) for Laravel kits, none otherwise} {--database-preset= : Preset for the database, as listed by the API for the type and region (e.g. dev, prod, scale — case-insensitive). Default: dev, or the first preset offered} {--cluster= : Dedicated cluster ID to deploy to (see dedicated-cluster:list)}'; diff --git a/app/Commands/Ship.php b/app/Commands/Ship.php index 76c519a5..539f7068 100644 --- a/app/Commands/Ship.php +++ b/app/Commands/Ship.php @@ -61,7 +61,7 @@ class Ship extends BaseCommand use UpdatesBuildDeployCommands; protected $signature = 'ship - {--database= : Database type or alias (postgres, postgres, mysql, or a type from `cloud database:types`). Unversioned aliases use the newest available version. Default: postgres} + {--database= : Database type or alias (postgres, postgres, mysql, or a type from `cloud database:types`). Unversioned aliases use the newest available version. Default: mysql, or postgres where MySQL is not offered} {--database-preset= : Preset for the database, as listed by the API for the type and region (e.g. dev, prod, scale — case-insensitive). Default: dev, or the first preset offered} {--name= : Application name (non-interactive). Default: derived from repository} {--region= : Region (non-interactive). Default: most-used or us-east-2} @@ -406,13 +406,9 @@ protected function collectOptionsToEnable(Environment $environment): ?string $selectedOptions = multiselect( label: 'Enable any of the following features?', options: $enableOptions, - default: $this->requestedQueueType !== null || $this->appDispatchesQueuedJobs() ? ['queue'] : [], + default: ['scale_to_zero', ...($this->requestedQueueType !== null || $this->appDispatchesQueuedJobs() ? ['queue'] : [])], ); - if (count($selectedOptions) === 0) { - return null; - } - $queueType = in_array('queue', $selectedOptions) ? $this->promptForQueueType() : null; if ($queueType !== 'managed' && $queueType !== null && in_array('scale_to_zero', $selectedOptions)) { @@ -445,6 +441,9 @@ protected function collectOptionsToEnable(Environment $environment): ?string ); $instanceParams['hibernation_timeout'] = (int) $scaleToZeroAfter; + } else { + // Cloud turns scale to zero on for new environments, so leaving the option unticked has to switch it off. + $instanceParams['disable_hibernation'] = true; } if (in_array('database_cluster', $selectedOptions)) { @@ -470,20 +469,19 @@ protected function collectOptionsToEnable(Environment $environment): ?string } } - if (count($instanceParams) > 0) { - $this->loopUntilValid( - fn () => spin( - fn () => $this->client->instances()->update(new UpdateInstanceRequestData( - instanceId: $environment->instances[0], - usesScheduler: $instanceParams['uses_scheduler'] ?? null, - usesOctane: $instanceParams['uses_octane'] ?? null, - usesInertiaSsr: $instanceParams['uses_inertia_ssr'] ?? null, - hibernationTimeout: $instanceParams['hibernation_timeout'] ?? null, - )), - 'Updating instance...', - ), - ); - } + $this->loopUntilValid( + fn () => spin( + fn () => $this->client->instances()->update(new UpdateInstanceRequestData( + instanceId: $environment->instances[0], + usesScheduler: $instanceParams['uses_scheduler'] ?? null, + usesOctane: $instanceParams['uses_octane'] ?? null, + usesInertiaSsr: $instanceParams['uses_inertia_ssr'] ?? null, + hibernationTimeout: $instanceParams['hibernation_timeout'] ?? null, + disableHibernation: $instanceParams['disable_hibernation'] ?? false, + )), + 'Updating instance...', + ), + ); if (count($environmentParams) > 0) { $this->loopUntilValid( @@ -545,7 +543,9 @@ protected function applyOpinionatedOptions(Environment $environment, ?string $qu usesScheduler: $instanceParams['uses_scheduler'], usesOctane: $instanceParams['uses_octane'], usesInertiaSsr: null, - disableHibernation: true, + // Cloud already turns scale to zero on for new environments, but a worker on the app + // instance stops while it sleeps, so its jobs would wait for the next web request. + disableHibernation: in_array($queueType, ['worker', 'horizon'], true), ), ); diff --git a/app/Concerns/ProvisionsDefaultResources.php b/app/Concerns/ProvisionsDefaultResources.php index cda8209d..284fe030 100644 --- a/app/Concerns/ProvisionsDefaultResources.php +++ b/app/Concerns/ProvisionsDefaultResources.php @@ -101,18 +101,14 @@ protected function resolveDatabaseType(): ?array { $input = strtolower((string) $this->option('database')); - if ($input === '') { - return [DatabaseClusterPreset::NeonServerlessPostgres->value, null]; + if ($input === '' || $input === 'mysql') { + return [DatabaseClusterPreset::LaravelMysql->value, null]; } if ($input === 'postgres') { return [DatabaseClusterPreset::NeonServerlessPostgres->value, null]; } - if ($input === 'mysql') { - return [DatabaseClusterPreset::LaravelMysql->value, null]; - } - if (preg_match('/^postgres(\d+)$/', $input, $matches)) { return [DatabaseClusterPreset::NeonServerlessPostgres->value, $matches[1]]; } @@ -167,7 +163,7 @@ protected function resolveDatabasePreset(string $type, string $region): Database */ protected function validateDatabaseOptions(string $region): void { - [$type, $version] = $this->resolveDatabaseTypeAndVersion(); + [$type, $version] = $this->resolveDatabaseTypeAndVersion($region); $this->validatedDatabase = [$type, $version, $this->resolveDatabasePreset($type->type, $region)]; } @@ -175,13 +171,18 @@ protected function validateDatabaseOptions(string $region): void /** * @return array{0: DatabaseType, 1: string} */ - protected function resolveDatabaseTypeAndVersion(): array + protected function resolveDatabaseTypeAndVersion(string $region): array { $types = $this->client->databaseClusters()->types(); $types = collect($types)->filter(fn (DatabaseType $type) => DatabaseClusterPreset::tryFrom($type->type) !== null)->values(); [$resolvedType, $resolvedVersion] = $this->resolveDatabaseType(); + // MySQL isn't offered everywhere, so the default falls back to Postgres like the dashboard does. + if ((string) $this->option('database') === '' && ! in_array($region, $types->firstWhere('type', $resolvedType)->regions ?? [], true)) { + $resolvedType = DatabaseClusterPreset::NeonServerlessPostgres->value; + } + $type = $types->firstWhere('type', $resolvedType); if ($type === null) { @@ -204,12 +205,12 @@ protected function resolveDatabaseTypeAndVersion(): array protected function provisionDatabaseOpinionated(): ?string { - [$type, $version, $preset] = $this->validatedDatabase ?? [...$this->resolveDatabaseTypeAndVersion(), null]; - $defaults = $this->databaseClusterDefaults(); $name = $defaults['name'] ?? 'database'; $region = $defaults['region'] ?? 'us-east-2'; + [$type, $version, $preset] = $this->validatedDatabase ?? [...$this->resolveDatabaseTypeAndVersion($region), null]; + $clusters = $this->client->databaseClusters()->list()->collect(); $cluster = $clusters->firstWhere('name', $name); $databaseName = $this->appName ? str($this->appName)->snake()->replace('-', '_')->toString() : 'main'; diff --git a/skills/deploying-to-cloud/SKILL.md b/skills/deploying-to-cloud/SKILL.md index bd1bd1bb..07023154 100644 --- a/skills/deploying-to-cloud/SKILL.md +++ b/skills/deploying-to-cloud/SKILL.md @@ -45,7 +45,7 @@ Use the [Laravel Cloud documentation](https://cloud.laravel.com/docs/llms.txt) f - Managed queues are the recommended queue option. They provision dedicated workers and autoscale based on queued work. - Managed queues require a supported recent Laravel version and `aws/aws-sdk-php`; check the current Cloud documentation before changing dependencies. - Enable the scheduler on an App or Worker cluster to run `php artisan schedule:run` every minute. When an environment has multiple replicas, use Laravel's `onOneServer` for tasks that must run once. -- Only Flex compute sizes can scale to zero. Scale-to-zero environments wake for Laravel scheduled tasks and queued jobs, but long-running jobs may be interrupted when the sleep timeout is reached. Use managed queues for workloads that must not be interrupted. +- Only Flex compute sizes can scale to zero. Laravel scheduled tasks keep running while an environment sleeps, but queued jobs don't wake it, and a job still running when the sleep timeout is reached may be interrupted. Use managed queues for workloads that must not be interrupted. ## Domains and Storage diff --git a/tests/Feature/DatabaseClusterCreateTest.php b/tests/Feature/DatabaseClusterCreateTest.php index 5143efc0..fccf655f 100644 --- a/tests/Feature/DatabaseClusterCreateTest.php +++ b/tests/Feature/DatabaseClusterCreateTest.php @@ -295,6 +295,7 @@ function setupDatabaseClusterCreateMocks(): Closure 'retention_days' => 1, 'uses_scheduled_snapshots' => false, 'is_public' => true, + 'suspend_seconds' => 300, 'maintenance_window' => 'sun:06:00-sun:06:30', ]); }); @@ -370,8 +371,8 @@ function setupDatabaseClusterCreateMocks(): Closure Prompt::fake([ // Custom is the last configuration option. Key::UP, Key::ENTER, - // Accept the defaults for storage, retention days, scheduled snapshots, public and maintenance window. - Key::ENTER, Key::ENTER, Key::ENTER, Key::ENTER, Key::ENTER, + // Accept the defaults for storage, retention days, scheduled snapshots, public, maintenance window and suspend seconds. + Key::ENTER, Key::ENTER, Key::ENTER, Key::ENTER, Key::ENTER, Key::ENTER, // Replace the rejected size. ...array_fill(0, strlen('bogus'), Key::BACKSPACE), ...str_split('db-flex.m-1vcpu-1gb'), Key::ENTER, ]); diff --git a/tests/Feature/InstanceUpdateTest.php b/tests/Feature/InstanceUpdateTest.php index 7bc4926d..e71b2bb4 100644 --- a/tests/Feature/InstanceUpdateTest.php +++ b/tests/Feature/InstanceUpdateTest.php @@ -26,30 +26,6 @@ MockClient::destroyGlobal(); }); -function updatableInstanceResponse(array $attributes = []): array -{ - return ['data' => [ - 'id' => 'inst-1', - 'type' => 'instances', - 'attributes' => array_merge([ - 'name' => 'web', - 'type' => 'app', - 'size' => 'flex.c-1vcpu-256mb', - 'scaling_type' => 'none', - 'min_replicas' => 1, - 'max_replicas' => 1, - 'uses_scheduler' => true, - 'shutdown_timeout' => null, - 'sleep_with_app' => null, - 'hibernation_timeout' => null, - 'probes' => null, - 'retire_at' => null, - 'retired_at' => null, - ], $attributes), - 'relationships' => ['environment' => ['data' => ['id' => 'env-1', 'type' => 'environments']]], - ], 'included' => [createEnvironmentResponse()]]; -} - function setupInstanceUpdateMocks(array $attributes = []): stdClass { $sent = new stdClass; diff --git a/tests/Feature/ShipDatabaseTest.php b/tests/Feature/ShipDatabaseTest.php index 9102da86..6c56c5cf 100644 --- a/tests/Feature/ShipDatabaseTest.php +++ b/tests/Feature/ShipDatabaseTest.php @@ -51,12 +51,12 @@ function shipCommandProvisioningDatabase(array $options): Ship return $command; } -function setupShipDatabaseMocks(): Closure +function setupShipDatabaseMocks(?array $types = null): Closure { $sentBody = new stdClass; MockClient::global([ - ListDatabaseTypesRequest::class => MockResponse::make(versionlessDatabaseTypesResponse(), 200), + ListDatabaseTypesRequest::class => MockResponse::make($types ?? versionlessDatabaseTypesResponse(), 200), ListDatabasePresetsRequest::class => fn (PendingRequest $request) => MockResponse::make( databasePresetsResponse($request->query()->get('type')), 200, @@ -94,11 +94,49 @@ function setupShipDatabaseMocks(): Closure 'a retired versioned MySQL type' => ['laravel_mysql_8', 'laravel_mysql', '8.4'], ]); -it('defaults to the newest Serverless Postgres the API offers', function () { +it('defaults to Laravel MySQL that scales to zero', function () { $sentBody = setupShipDatabaseMocks(); $command = shipCommandProvisioningDatabase([]); + (fn () => $this->provisionDatabaseOpinionated())->call($command); + + expect($sentBody()['type'])->toBe('laravel_mysql') + ->and($sentBody()['version'])->toBe('8.4') + ->and($sentBody()['region'])->toBe('us-east-1') + ->and($sentBody()['config']['suspend_seconds'])->toBe(300); +}); + +it('defaults to Serverless Postgres where Laravel MySQL is not offered', function () { + $types = versionlessDatabaseTypesResponse(); + $types['data'][0]['regions'] = ['eu-central-1']; + $sentBody = setupShipDatabaseMocks($types); + + $command = shipCommandProvisioningDatabase([]); + + (fn () => $this->provisionDatabaseOpinionated())->call($command); + + expect($sentBody()['type'])->toBe('neon_serverless_postgres') + ->and($sentBody()['version'])->toBe('18'); +}); + +it('keeps an explicit MySQL choice even where the API does not list the region', function () { + $types = versionlessDatabaseTypesResponse(); + $types['data'][0]['regions'] = ['eu-central-1']; + $sentBody = setupShipDatabaseMocks($types); + + $command = shipCommandProvisioningDatabase(['--database' => 'mysql']); + + (fn () => $this->provisionDatabaseOpinionated())->call($command); + + expect($sentBody()['type'])->toBe('laravel_mysql'); +}); + +it('provisions the newest Serverless Postgres the API offers', function () { + $sentBody = setupShipDatabaseMocks(); + + $command = shipCommandProvisioningDatabase(['--database' => 'postgres']); + $schemaId = (fn () => $this->provisionDatabaseOpinionated())->call($command); expect($schemaId)->toBe('schema-1') diff --git a/tests/Feature/ShipScaleToZeroTest.php b/tests/Feature/ShipScaleToZeroTest.php new file mode 100644 index 00000000..e8632e94 --- /dev/null +++ b/tests/Feature/ShipScaleToZeroTest.php @@ -0,0 +1,92 @@ +repo = sys_get_temp_dir().'/ship-s2z-'.uniqid(); + File::ensureDirectoryExists($this->repo.'/project'); + File::put($this->repo.'/project/composer.json', json_encode(['require' => []])); + + $this->sentInstance = new stdClass; + + MockClient::global([ + UpdateInstanceRequest::class => function (PendingRequest $request) { + $this->sentInstance->body = $request->body()->all(); + + return MockResponse::make(updatableInstanceResponse(), 200); + }, + CreateBackgroundProcessRequest::class => MockResponse::make(['data' => ['id' => 'bp-1', 'type' => 'background_processes', 'attributes' => ['type' => 'worker']]], 201), + ]); +}); + +afterEach(function () { + MockClient::destroyGlobal(); + File::deleteDirectory($this->repo); +}); + +function shipWithoutDatabase(string $repo): Ship +{ + // The database has its own tests, so this keeps the run to the instance update. + $command = new class extends Ship + { + protected function provisionDatabaseOpinionated(): ?string + { + return null; + } + }; + + $definition = $command->getDefinition(); + $definition->addOption(new InputOption('no-interaction', 'n', InputOption::VALUE_NONE)); + + $input = new ArrayInput(['--root-directory' => 'project', '--no-interaction' => true], $definition); + $input->setInteractive(false); + + $git = Mockery::mock(Git::class); + $git->shouldReceive('getRoot')->andReturn($repo); + + (function () use ($input, $git) { + $this->input = $input; + $this->output = new BufferedOutput; + $this->client = new Connector('test-api-token'); + $this->git = $git; + })->call($command); + + return $command; +} + +function shipScaleToZeroEnvironment(): Environment +{ + return Environment::createFromResponse(['data' => createEnvironmentResponse([ + 'relationships' => ['instances' => ['data' => [['id' => 'inst-1', 'type' => 'instances']]]], + ])]); +} + +it('leaves the scale to zero Cloud turns on for new environments', function () { + $command = shipWithoutDatabase($this->repo); + + (fn () => $this->applyOpinionatedOptions(shipScaleToZeroEnvironment()))->call($command); + + expect($this->sentInstance->body)->not->toHaveKey('hibernation_timeout') + ->and($this->sentInstance->body['uses_scheduler'])->toBeTrue(); +}); + +it('turns scale to zero off when a queue worker runs on the app instance', function (string $queue) { + $command = shipWithoutDatabase($this->repo); + + (fn () => $this->applyOpinionatedOptions(shipScaleToZeroEnvironment(), $queue))->call($command); + + expect($this->sentInstance->body)->toHaveKey('hibernation_timeout') + ->and($this->sentInstance->body['hibernation_timeout'])->toBeNull(); +})->with(['worker', 'horizon']); diff --git a/tests/Helpers.php b/tests/Helpers.php index 6df4d00c..3d93c7ed 100644 --- a/tests/Helpers.php +++ b/tests/Helpers.php @@ -478,6 +478,7 @@ function versionlessDatabaseTypesResponse(): array ['name' => 'uses_scheduled_snapshots', 'type' => 'boolean', 'required' => true, 'example' => 'false'], ['name' => 'is_public', 'type' => 'boolean', 'required' => true, 'example' => 'false'], ['name' => 'maintenance_window', 'type' => 'string', 'required' => false, 'nullable' => true, 'example' => 'sun:06:00-sun:06:30'], + ['name' => 'suspend_seconds', 'type' => 'integer', 'required' => false, 'example' => '300'], ], ], [ @@ -522,7 +523,7 @@ function databasePresetsResponse(string $type): array { $presets = match ($type) { 'laravel_mysql' => [ - ['key' => 'dev', 'label' => 'Dev', 'config' => ['size' => 'mysql-flex-512mb', 'storage' => 5, 'retention_days' => 1, 'uses_scheduled_snapshots' => false, 'is_public' => false]], + ['key' => 'dev', 'label' => 'Dev', 'config' => ['size' => 'mysql-flex-512mb', 'storage' => 5, 'retention_days' => 1, 'uses_scheduled_snapshots' => false, 'is_public' => false, 'suspend_seconds' => 300]], ['key' => 'prod', 'label' => 'Prod', 'config' => ['size' => 'mysql-flex-2gb', 'storage' => 20, 'retention_days' => 7, 'uses_scheduled_snapshots' => false, 'is_public' => false]], ], 'neon_serverless_postgres' => [ @@ -748,3 +749,27 @@ function createQueuedDeploymentResponse(string $status = 'pending', ?string $fai 'included' => $deployment ? [$deployment] : [], ]; } + +function updatableInstanceResponse(array $attributes = []): array +{ + return ['data' => [ + 'id' => 'inst-1', + 'type' => 'instances', + 'attributes' => array_merge([ + 'name' => 'web', + 'type' => 'app', + 'size' => 'flex.c-1vcpu-256mb', + 'scaling_type' => 'none', + 'min_replicas' => 1, + 'max_replicas' => 1, + 'uses_scheduler' => true, + 'shutdown_timeout' => null, + 'sleep_with_app' => null, + 'hibernation_timeout' => null, + 'probes' => null, + 'retire_at' => null, + 'retired_at' => null, + ], $attributes), + 'relationships' => ['environment' => ['data' => ['id' => 'env-1', 'type' => 'environments']]], + ], 'included' => [createEnvironmentResponse()]]; +}