Skip to content
This repository was archived by the owner on Nov 30, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/Commands/NewApplication.php
Original file line number Diff line number Diff line change
Expand Up @@ -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: ./<repository name>}
{--database= : Database type or alias (postgres, postgres<version>, mysql, none, or a type from `cloud database:types`). Default: postgres for Laravel kits, none otherwise}
{--database= : Database type or alias (postgres, postgres<version>, 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)}';

Expand Down
42 changes: 21 additions & 21 deletions app/Commands/Ship.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ class Ship extends BaseCommand
use UpdatesBuildDeployCommands;

protected $signature = 'ship
{--database= : Database type or alias (postgres, postgres<version>, mysql, or a type from `cloud database:types`). Unversioned aliases use the newest available version. Default: postgres}
{--database= : Database type or alias (postgres, postgres<version>, 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}
Expand Down Expand Up @@ -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)) {
Expand Down Expand Up @@ -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)) {
Expand All @@ -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(
Expand Down Expand Up @@ -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),
),
);

Expand Down
21 changes: 11 additions & 10 deletions app/Concerns/ProvisionsDefaultResources.php
Original file line number Diff line number Diff line change
Expand Up @@ -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]];
}
Expand Down Expand Up @@ -167,21 +163,26 @@ 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)];
}

/**
* @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) {
Expand All @@ -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';
Expand Down
2 changes: 1 addition & 1 deletion skills/deploying-to-cloud/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
5 changes: 3 additions & 2 deletions tests/Feature/DatabaseClusterCreateTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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',
]);
});
Expand Down Expand Up @@ -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,
]);
Expand Down
24 changes: 0 additions & 24 deletions tests/Feature/InstanceUpdateTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
44 changes: 41 additions & 3 deletions tests/Feature/ShipDatabaseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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')
Expand Down
92 changes: 92 additions & 0 deletions tests/Feature/ShipScaleToZeroTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<?php

use App\Client\Connector;
use App\Client\Resources\BackgroundProcesses\CreateBackgroundProcessRequest;
use App\Client\Resources\Instances\UpdateInstanceRequest;
use App\Commands\Ship;
use App\Dto\Environment;
use App\Git;
use Illuminate\Support\Facades\File;
use Saloon\Http\Faking\MockClient;
use Saloon\Http\Faking\MockResponse;
use Saloon\Http\PendingRequest;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\BufferedOutput;

beforeEach(function () {
$this->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']);
Loading
Loading