Skip to content

Commit 2675c08

Browse files
committed
feat: schedule commits from the API
1 parent 109e171 commit 2675c08

7 files changed

Lines changed: 321 additions & 1 deletion

File tree

‎README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,8 @@ A signed profile also says `is_muting` and has the web's `achievements`, with th
9393

9494
`POST /api/v1/commits` takes a `body`, and either a `parent_id` to reply to a commit or a `quoted_commit_id` to quote one, but not both. Returns a `201` on successful commit creation.
9595

96+
`POST /api/v1/scheduled-commits` schedules a commit to be submitted later, as the web's Schedule commit does. It takes a `body` and a `scheduled_at` with its offset, like `2026-10-20T09:00:00+01:00`, after now and within 30 days, and answers `201` with the scheduled commit: its `id`, `body`, `body_segments` and `preview_segments` as a commit has them, its `poll_options` (or `null`) and `image_count`, `scheduled_at` in UTC, `submitted_at`, `status` (`scheduled` until it is submitted, then its commit's status, or `deleted`) and `commit_id`. Only the user sees it until it is due, then it is submitted for review like any commit. Like a commit from the API, it has no images or poll yet. Replies and quotes can't be scheduled, a user can have 10 scheduled commits waiting at once, and scheduling shares the limit of 10 commits a minute. As with `POST /api/v1/commits`, it is a `403` with `timed_out` while the user is in a timeout, and with `commit_rules_required` until their first commit came from the web.
97+
9698
`POST /api/v1/commits/{id}/reports` reports a commit to the moderators, privately, as the web's Report button does. It takes a `reason`, one of `spam`, `harassment`, `unsafe` or `other`, and optional `details` of up to 500 characters, and answers `204`. Reporting doesn't hide the commit. Only someone else's published commit can be reported: the user's own is a `403` with `own_commit`, and one that is pending, rejected, deleted, missing or across a block is a `404` with `commit_unavailable`. Reporting a commit again also answers `204` and keeps the first report. Each user can send 5 reports a minute.
9799

98100
`GET /api/v1/me` also has what only the user sees in the web's profile settings: `preferred_lane` (a lane, a custom `#rrggbb` color, or `null` for Automatic), the `automatic_lane` Automatic picks for them, their `sponsors_url` (or `null`), and `github_synced_at`, when their profile was last synced from GitHub (`null` if it only was when they signed in). `PUT /api/v1/me/github` syncs it from GitHub again, like Sync from GitHub on the web, and shares its limit of one sync a minute. `PUT /api/v1/me/lane` saves their color, with a `lane` from `0` to `5`, or `null` for Automatic, or a custom `color` as lowercase `#rrggbb` with a `null` lane, as the web's color picker does. Both answer like `GET /api/v1/me`.
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace App\Http\Controllers\Api;
6+
7+
use App\Actions\CreateScheduledCommit;
8+
use App\Http\Requests\CreateApiScheduledCommitRequest;
9+
use App\Http\Resources\ScheduledCommitResource;
10+
use App\Models\User;
11+
use Illuminate\Container\Attributes\CurrentUser;
12+
use Illuminate\Http\JsonResponse;
13+
14+
final readonly class ScheduledCommitController
15+
{
16+
/**
17+
* Schedules the commit, as the web's Schedule commit does. Only the user sees it until it is due, when it is
18+
* submitted for review like any commit. Answers with the scheduled commit.
19+
*/
20+
public function store(CreateApiScheduledCommitRequest $request, #[CurrentUser] User $user, CreateScheduledCommit $action): JsonResponse
21+
{
22+
$scheduled = $action->handle($user, $request->string('body')->value(), $request->scheduledAt());
23+
24+
return ScheduledCommitResource::make($scheduled)
25+
->response()
26+
->setStatusCode(201);
27+
}
28+
}

‎app/Http/Middleware/ThrottleCommits.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ private function slowDown(Request $request, int $retryAfter): Response
4949
}
5050

5151
// The mobile app reads JSON with a code...
52-
if ($request->routeIs('api-commit.store')) {
52+
if ($request->routeIs('api-commit.store', 'api-scheduled-commit.store')) {
5353
return new ApiException(ApiErrorCode::RateLimited, $message, ['Retry-After' => $retryAfter])->render();
5454
}
5555

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace App\Http\Requests;
6+
7+
use App\Models\User;
8+
use App\Rules\ScheduledCommitLimit;
9+
use Carbon\CarbonImmutable;
10+
use Illuminate\Contracts\Validation\ValidationRule;
11+
use Illuminate\Foundation\Http\FormRequest;
12+
13+
/**
14+
* A commit from the mobile app to submit later, sent as JSON, with the web's rules: a top-level commit, due within 30
15+
* days, and at most 10 waiting at once. Like a commit from the app, it has no images or poll yet.
16+
*/
17+
final class CreateApiScheduledCommitRequest extends FormRequest
18+
{
19+
public function authorize(): bool
20+
{
21+
return true;
22+
}
23+
24+
/**
25+
* Blank lines are collapsed before the body is measured, as on the web.
26+
*/
27+
public function prepareForValidation(): void
28+
{
29+
CreateCommitRequest::normalizeBody($this);
30+
}
31+
32+
/**
33+
* @return array<string, array<int, string|ValidationRule>>
34+
*/
35+
public function rules(): array
36+
{
37+
$user = $this->user();
38+
assert($user instanceof User);
39+
40+
return [
41+
'body' => CreateCommitRequest::bodyRules(),
42+
'scheduled_at' => ['required', 'date_format:Y-m-d\TH:i:sP', 'after:now', 'before_or_equal:'.now()->addDays(30)->toIso8601String(), new ScheduledCommitLimit($user)],
43+
'parent_id' => ['prohibited'],
44+
'quoted_commit_id' => ['prohibited'],
45+
];
46+
}
47+
48+
/**
49+
* When the commit is due, in UTC.
50+
*/
51+
public function scheduledAt(): CarbonImmutable
52+
{
53+
return CarbonImmutable::parse($this->string('scheduled_at')->value())->utc();
54+
}
55+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace App\Http\Resources;
6+
7+
use App\Models\ScheduledCommit;
8+
use App\Services\CommitBodies;
9+
use Illuminate\Http\Request;
10+
use Illuminate\Http\Resources\Json\JsonResource;
11+
12+
/**
13+
* A commit the user scheduled, as the web's Scheduled commits page shows it, which only they see. Until it is
14+
* submitted it has its body, split like a commit's, the options of its poll and how many images it carries. Once
15+
* submitted, those belong to the commit it became: the body is null, the status is that commit's (or deleted once it
16+
* is), and commit_id is that commit while it exists.
17+
*
18+
* @mixin ScheduledCommit
19+
*/
20+
final class ScheduledCommitResource extends JsonResource
21+
{
22+
/**
23+
* @return array<string, mixed>
24+
*/
25+
public function toArray(Request $request): array
26+
{
27+
$commit = $this->submitted_at === null || $this->commit?->trashed() !== false ? null : $this->commit;
28+
29+
return [
30+
'id' => $this->id,
31+
...($this->submitted_at === null && $this->body !== null
32+
? ['body' => $this->body, ...resolve(CommitBodies::class)->segments($this->body)]
33+
: ['body' => null, 'body_segments' => [], 'preview_segments' => null]),
34+
'poll_options' => $this->poll['options'] ?? null,
35+
'image_count' => count($this->images ?? []),
36+
'scheduled_at' => $this->scheduled_at->toIso8601ZuluString(),
37+
'submitted_at' => $this->submitted_at?->toIso8601ZuluString(),
38+
'status' => $this->submitted_at === null ? 'scheduled' : ($commit?->status->value ?? 'deleted'),
39+
'commit_id' => $commit?->id,
40+
];
41+
}
42+
}

‎routes/api.php‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
use App\Http\Controllers\Api\LogController;
1414
use App\Http\Controllers\Api\NotificationController;
1515
use App\Http\Controllers\Api\NotificationGroupController;
16+
use App\Http\Controllers\Api\ScheduledCommitController;
1617
use App\Http\Controllers\Api\StarredCommitController;
1718
use App\Http\Controllers\Api\UserBlockController;
1819
use App\Http\Controllers\Api\UserCommitController;
@@ -89,6 +90,11 @@
8990
->name('api-commit.store');
9091
Route::delete('commits/{commit}', [ApiCommitController::class, 'destroy'])->name('api-commit.destroy');
9192

93+
// Scheduled Commit...
94+
Route::post('scheduled-commits', [ScheduledCommitController::class, 'store'])
95+
->middleware([PreventPostingInTimeout::class, RequireCommitRules::class, ThrottleCommits::class])
96+
->name('api-scheduled-commit.store');
97+
9298
// Commit Reply...
9399
Route::get('commits/{commit}/replies', [CommitReplyController::class, 'index'])
94100
->withTrashed()
Lines changed: 187 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,187 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use App\Enums\ModerationReason;
6+
use App\Models\Commit;
7+
use App\Models\ScheduledCommit;
8+
use App\Models\User;
9+
use App\Models\UserTimeout;
10+
use App\Services\CommitBodies;
11+
12+
beforeEach(function (): void {
13+
$this->travelTo(now()->setDate(2026, 10, 15)->setTime(12, 0));
14+
$this->user = User::factory()->create();
15+
$this->keyPair = apiKeyPairFor($this->user);
16+
});
17+
18+
it('schedules a commit in UTC, without committing it, and answers with it', function (): void {
19+
$response = signedApiRequest($this->keyPair, 'POST', route('api-scheduled-commit.store'), [
20+
'body' => ' Shipped the parser benchmark. ',
21+
'scheduled_at' => '2026-10-16T10:30:00+05:30',
22+
]);
23+
24+
$scheduled = ScheduledCommit::query()->sole();
25+
26+
$response->assertCreated()
27+
->assertExactJson([
28+
'data' => [
29+
'id' => $scheduled->id,
30+
'body' => 'Shipped the parser benchmark.',
31+
...resolve(CommitBodies::class)->segments('Shipped the parser benchmark.'),
32+
'poll_options' => null,
33+
'image_count' => 0,
34+
'scheduled_at' => '2026-10-16T05:00:00Z',
35+
'submitted_at' => null,
36+
'status' => 'scheduled',
37+
'commit_id' => null,
38+
],
39+
]);
40+
41+
expect($scheduled->user_id)->toBe($this->user->id)
42+
->and($scheduled->scheduled_at->toIso8601String())->toBe('2026-10-16T05:00:00+00:00')
43+
->and(Commit::query()->count())->toBe(0);
44+
});
45+
46+
it('submits it for review at the due time', function (): void {
47+
signedApiRequest($this->keyPair, 'POST', route('api-scheduled-commit.store'), [
48+
'body' => 'Shipped the parser benchmark.',
49+
'scheduled_at' => '2026-10-15T13:00:00+00:00',
50+
])->assertCreated();
51+
52+
$this->travelTo(now()->setTime(13, 0));
53+
$this->artisan('commits:submit-scheduled')->assertSuccessful();
54+
55+
expect(Commit::query()->sole())
56+
->user_id->toBe($this->user->id)
57+
->body->toBe('Shipped the parser benchmark.')
58+
->and(ScheduledCommit::query()->sole()->submitted_at)->not->toBeNull();
59+
});
60+
61+
it('splits a long body like a commit, with the excerpt a list shows', function (): void {
62+
$body = str_repeat('Shipped a long changelog entry. ', 40);
63+
64+
$response = signedApiRequest($this->keyPair, 'POST', route('api-scheduled-commit.store'), [
65+
'body' => $body,
66+
'scheduled_at' => '2026-10-16T12:00:00+00:00',
67+
]);
68+
69+
$segments = resolve(CommitBodies::class)->segments(mb_trim($body));
70+
71+
$response->assertCreated()
72+
->assertJsonPath('data.body_segments', $segments['body_segments'])
73+
->assertJsonPath('data.preview_segments', $segments['preview_segments']);
74+
75+
expect($segments['preview_segments'])->not->toBeNull();
76+
});
77+
78+
it('rejects invalid times and bodies, as the web does', function (array $payload, string $field): void {
79+
$response = signedApiRequest($this->keyPair, 'POST', route('api-scheduled-commit.store'), [
80+
'body' => 'Shipped a scheduling feature.',
81+
'scheduled_at' => '2026-10-16T12:00:00+00:00',
82+
...$payload,
83+
]);
84+
85+
$response->assertUnprocessable()
86+
->assertJsonValidationErrors($field);
87+
88+
expect(ScheduledCommit::query()->count())->toBe(0);
89+
})->with([
90+
'missing time' => [['scheduled_at' => null], 'scheduled_at'],
91+
'missing offset' => [['scheduled_at' => '2026-10-16T12:00:00'], 'scheduled_at'],
92+
'invalid date' => [['scheduled_at' => '2026-10-32T12:00:00+00:00'], 'scheduled_at'],
93+
'now' => [['scheduled_at' => '2026-10-15T12:00:00+00:00'], 'scheduled_at'],
94+
'past' => [['scheduled_at' => '2026-10-15T11:59:00+00:00'], 'scheduled_at'],
95+
'beyond thirty days' => [['scheduled_at' => '2026-11-14T12:00:01+00:00'], 'scheduled_at'],
96+
'missing body' => [['body' => null], 'body'],
97+
'whitespace' => [['body' => ' '], 'body'],
98+
'too long' => [['body' => str_repeat('a', 4001)], 'body'],
99+
]);
100+
101+
it('accepts the end of the window and a unicode body', function (): void {
102+
signedApiRequest($this->keyPair, 'POST', route('api-scheduled-commit.store'), [
103+
'body' => str_repeat('é', 4000),
104+
'scheduled_at' => '2026-11-14T12:00:00+00:00',
105+
])->assertCreated();
106+
107+
expect(ScheduledCommit::query()->count())->toBe(1);
108+
});
109+
110+
it('does not schedule replies or quotes', function (string $field): void {
111+
$commit = Commit::factory()->create();
112+
113+
$response = signedApiRequest($this->keyPair, 'POST', route('api-scheduled-commit.store'), [
114+
'body' => 'This must not become a reply or a quote.',
115+
'scheduled_at' => '2026-10-16T12:00:00+00:00',
116+
$field => $commit->id,
117+
]);
118+
119+
$response->assertUnprocessable()
120+
->assertJsonValidationErrors($field);
121+
122+
expect(ScheduledCommit::query()->count())->toBe(0);
123+
})->with(['parent_id', 'quoted_commit_id']);
124+
125+
it('keeps to 10 scheduled commits waiting at once', function (): void {
126+
ScheduledCommit::factory()->for($this->user)->count(10)->create();
127+
128+
$response = signedApiRequest($this->keyPair, 'POST', route('api-scheduled-commit.store'), [
129+
'body' => 'One more scheduled commit.',
130+
'scheduled_at' => '2026-10-16T12:00:00+00:00',
131+
]);
132+
133+
$response->assertUnprocessable()
134+
->assertJsonValidationErrors(['scheduled_at' => 'You can have up to 10 scheduled commits. Cancel one before scheduling another.']);
135+
136+
expect(ScheduledCommit::query()->count())->toBe(10);
137+
});
138+
139+
it('shares the limit of 10 commits a minute', function (): void {
140+
for ($i = 0; $i < 10; $i++) {
141+
signedApiRequest($this->keyPair, 'POST', route('api-commit.store'), ['body' => 'An ordinary commit.'])->assertCreated();
142+
}
143+
144+
$response = signedApiRequest($this->keyPair, 'POST', route('api-scheduled-commit.store'), [
145+
'body' => 'Must be throttled.',
146+
'scheduled_at' => '2026-10-16T12:00:00+00:00',
147+
]);
148+
149+
$response->assertTooManyRequests()
150+
->assertJsonPath('code', 'rate_limited')
151+
->assertHeader('Retry-After');
152+
153+
expect(ScheduledCommit::query()->count())->toBe(0);
154+
});
155+
156+
it('does not schedule for a user in timeout', function (): void {
157+
UserTimeout::factory()->for($this->user)->create(['reason' => ModerationReason::Spam, 'ends_at' => now()->addDays(2)]);
158+
159+
signedApiRequest($this->keyPair, 'POST', route('api-scheduled-commit.store'), [
160+
'body' => 'It was DNS.',
161+
'scheduled_at' => '2026-10-16T12:00:00+00:00',
162+
])->assertForbidden()
163+
->assertJsonPath('code', 'timed_out');
164+
165+
expect(ScheduledCommit::query()->count())->toBe(0);
166+
});
167+
168+
it('leaves the first commit to the web, where the commit rules are read', function (): void {
169+
$user = User::factory()->firstTimePoster()->create();
170+
171+
signedApiRequest(apiKeyPairFor($user), 'POST', route('api-scheduled-commit.store'), [
172+
'body' => 'Hello, world.',
173+
'scheduled_at' => '2026-10-16T12:00:00+00:00',
174+
])->assertForbidden()
175+
->assertJsonPath('code', 'commit_rules_required');
176+
177+
expect(ScheduledCommit::query()->count())->toBe(0);
178+
});
179+
180+
it('requires a signed request', function (): void {
181+
$this->postJson(route('api-scheduled-commit.store'), [
182+
'body' => 'Shipped the parser benchmark.',
183+
'scheduled_at' => '2026-10-16T12:00:00+00:00',
184+
])->assertUnauthorized();
185+
186+
expect(ScheduledCommit::query()->count())->toBe(0);
187+
});

0 commit comments

Comments
 (0)