Skip to content
Open
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
1 change: 1 addition & 0 deletions KNOWLEDGE_BASE.md
Original file line number Diff line number Diff line change
Expand Up @@ -620,6 +620,7 @@ A signed request sees what the web shows you, such as your own pending commits a
- pin a commit to your profile, or unpin it;
- translate commits;
- suggest people to mention and /dev/null issues to reference while writing;
- suggest up to six guilds by handle or name while typing a hashtag, as the composer does, while guilds are available to you;
- sync from GitHub, save your lane color, timezone, and translation language, and turn automatic translation on or off;
- list your devices and revoke them;
- delete your account.
Expand Down
24 changes: 24 additions & 0 deletions app/Http/Controllers/Api/GuildSuggestionController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api;

use App\Http\Requests\ListApiGuildSuggestionsRequest;
use App\Http\Resources\GuildBadgeResource;
use App\Queries\GuildsQuery;
use Illuminate\Http\JsonResponse;

final readonly class GuildSuggestionController
{
/**
* The guilds the composer suggests for a #hashtag, as the web's composer suggests them: six at most whose handle
* or name contains the term, those whose handle starts with it first, each group by the most members, then handle.
*/
public function index(ListApiGuildSuggestionsRequest $request, GuildsQuery $query): JsonResponse
{
return GuildBadgeResource::collection($query->suggestions($request->term()))
->response()
->header('Cache-Control', 'private, no-store');
}
}
34 changes: 34 additions & 0 deletions app/Http/Requests/ListApiGuildSuggestionsRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

declare(strict_types=1);

namespace App\Http\Requests;

use App\Enums\Feature;
use App\Services\Features;
use Illuminate\Auth\Access\Response;
use Illuminate\Foundation\Http\FormRequest;

final class ListApiGuildSuggestionsRequest extends FormRequest
{
public function authorize(Features $features): Response
{
return $features->available(Feature::Guilds, $this->user()) ? Response::allow() : Response::denyAsNotFound();
}

/** @return array<string, list<string>> */
public function rules(): array
{
return [
'q' => ['nullable', 'string', 'max:100'],
];
}

/**
* What follows the hashtag, so an app can send the word it is completing with or without its #.
*/
public function term(): string
{
return $this->string('q')->trim()->ltrim('#')->trim()->lower()->value();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}
21 changes: 18 additions & 3 deletions app/Queries/GuildsQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,15 +62,30 @@ public function references(array $handles): Collection
public function suggestions(string $term): Collection
{
$escaped = str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $term);
$handle = $this->folded('handle');
$name = $this->folded('name');
$search = $this->folded('?');

return Guild::query()->select(['handle', 'name', 'emoji', 'icon_path', 'updated_at'])->withCount('members')
->where(fn (Builder $query): Builder => $query
->whereRaw('TRANSLATE(LOWER(handle COLLATE "pg_c_utf8"), \'ς\', \'σ\') LIKE TRANSLATE(LOWER(? COLLATE "pg_c_utf8"), \'ς\', \'σ\') ESCAPE \'!\'', ["%{$escaped}%"])
->orWhereRaw('TRANSLATE(LOWER(name COLLATE "pg_c_utf8"), \'ς\', \'σ\') LIKE TRANSLATE(LOWER(? COLLATE "pg_c_utf8"), \'ς\', \'σ\') ESCAPE \'!\'', ["%{$escaped}%"]))
->orderByRaw('CASE WHEN TRANSLATE(LOWER(handle COLLATE "pg_c_utf8"), \'ς\', \'σ\') LIKE TRANSLATE(LOWER(? COLLATE "pg_c_utf8"), \'ς\', \'σ\') ESCAPE \'!\' THEN 0 ELSE 1 END', ["{$escaped}%"])
->whereRaw("{$handle} LIKE {$search} ESCAPE '!'", ["%{$escaped}%"])
->orWhereRaw("{$name} LIKE {$search} ESCAPE '!'", ["%{$escaped}%"]))
->orderByRaw("CASE WHEN {$handle} LIKE {$search} ESCAPE '!' THEN 0 ELSE 1 END", ["{$escaped}%"])
->orderByDesc('members_count')->orderBy('handle')->limit(6)->get();
}

/**
* Lowercases for matching, folding the final sigma into σ and dropping the combining dot above: handles are
* lowercased in PHP, which turns İ into i and that dot, while the database turns İ into a plain i.
*
* @param literal-string $operand
* @return literal-string
*/
private function folded(string $operand): string
{
return "TRANSLATE(LOWER({$operand} COLLATE \"pg_c_utf8\"), 'ς\u{0307}', 'σ')";
Comment thread
shanesmithdev marked this conversation as resolved.
Resolved
}

/**
* The member count and whether the user joined or muted each guild come from one read, so they always agree.
*
Expand Down
6 changes: 5 additions & 1 deletion routes/api.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
use App\Http\Controllers\Api\GuildMuteController;
use App\Http\Controllers\Api\GuildReadController;
use App\Http\Controllers\Api\GuildReportController;
use App\Http\Controllers\Api\GuildSuggestionController;
use App\Http\Controllers\Api\HeadlineController;
use App\Http\Controllers\Api\IssueController;
use App\Http\Controllers\Api\IssueSuggestionController;
Expand Down Expand Up @@ -273,10 +274,13 @@
->middleware('throttle:120,1,guild-reads:')
->name('api-guild-read.update');

// Composer suggestions: people to mention and /dev/null issues to reference, as the web's composer suggests them...
// Composer suggestions: people to mention, guilds to tag and /dev/null issues to reference, as the web's composer suggests them...
Route::get('search/mentions', [MentionSuggestionController::class, 'index'])
->middleware('throttle:people')
->name('api-mention-suggestion.index');
Route::get('search/guilds', [GuildSuggestionController::class, 'index'])
->middleware('throttle:people')
->name('api-guild-suggestion.index');
Route::get('search/issues', [IssueSuggestionController::class, 'index'])
->middleware('throttle:issue-suggestions')
->name('api-issue-suggestion.index');
Expand Down
148 changes: 148 additions & 0 deletions tests/Feature/Controllers/Api/GuildSuggestionControllerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
<?php

declare(strict_types=1);

use App\Enums\Feature;
use App\Models\Guild;
use App\Models\User;
use App\Services\Features;

beforeEach(function (): void {
resolve(Features::class)->update(Feature::Guilds, true, adminOnly: false);

$this->user = User::factory()->create();
$this->keyPair = apiKeyPairFor($this->user);
});

it('suggests six guilds with handle prefixes before popular name matches, as the web composer does', function (): void {
Guild::factory()->count(7)->sequence(fn ($sequence): array => [
'handle' => 'group0'.$sequence->index,
'name' => 'Rust developers',
'emoji' => '🦀',
'icon_path' => null,
])->create();
Guild::query()->where('handle', 'group06')->firstOrFail()->members()->attach($this->user, ['joined_at' => now()]);
Guild::factory()->create(['handle' => 'rustaceans', 'name' => 'Systems', 'emoji' => '🦀', 'icon_path' => null]);

signedApiRequest($this->keyPair, 'GET', route('api-guild-suggestion.index', ['q' => 'RUST']))
->assertOk()
->assertHeader('Cache-Control', 'no-store, private')
->assertExactJson(['data' => collect(['rustaceans', 'group06', 'group00', 'group01', 'group02', 'group03'])
->map(fn (string $handle): array => [
'handle' => $handle,
'name' => $handle === 'rustaceans' ? 'Systems' : 'Rust developers',
'emoji' => '🦀',
'icon_url' => null,
])->all()]);
});

it('ignores a leading hashtag and surrounding spaces', function (string $query): void {
Guild::factory()->create(['handle' => 'laravel', 'name' => 'Artisans']);
Guild::factory()->create(['handle' => 'symfony', 'name' => 'Symfony']);

signedApiRequest($this->keyPair, 'GET', route('api-guild-suggestion.index', ['q' => $query]))
->assertOk()
->assertJsonPath('data.*.handle', ['laravel']);
})->with(['#lara', ' #LARA ', '# lara', '##lara']);

it('matches display names as well as handles', function (): void {
Guild::factory()->create(['handle' => 'laravel', 'name' => 'Artisans']);
Guild::factory()->create(['handle' => 'symfony', 'name' => 'Symfony']);

signedApiRequest($this->keyPair, 'GET', route('api-guild-suggestion.index', ['q' => 'ARTISANS']))
->assertOk()
->assertJsonPath('data.*.handle', ['laravel']);
});

it('suggests the six most popular guilds for a bare hashtag', function (?string $query): void {
Guild::factory()->count(7)->sequence(fn ($sequence): array => ['handle' => 'guild'.$sequence->index])->create();
$rust = Guild::factory()->create(['handle' => 'rust']);
$rust->members()->attach($this->user, ['joined_at' => now()]);

signedApiRequest($this->keyPair, 'GET', route('api-guild-suggestion.index', array_filter(['q' => $query])))
->assertOk()
->assertJsonPath('data.*.handle', ['rust', 'guild0', 'guild1', 'guild2', 'guild3', 'guild4']);
})->with([null, '#']);

it('still suggests paused guilds and guilds the user muted, as the web composer does', function (): void {
Guild::factory()->create(['handle' => 'rustpaused', 'user_id' => null]);
Guild::factory()->create(['handle' => 'rustmuted'])->muters()->attach($this->user, ['muted_at' => now()]);

signedApiRequest($this->keyPair, 'GET', route('api-guild-suggestion.index', ['q' => 'rust']))
->assertOk()
->assertJsonPath('data.*.handle', ['rustmuted', 'rustpaused']);
});

it('gives icons the API signs for the user, without private guild fields', function (): void {
$rust = Guild::factory()->create(['handle' => 'rust', 'name' => 'Rust', 'description' => 'Fearless', 'emoji' => '🦀', 'icon_path' => 'guild-icons/rust.webp']);

signedApiRequest($this->keyPair, 'GET', route('api-guild-suggestion.index', ['q' => 'rust']))
->assertOk()
->assertExactJson(['data' => [[
'handle' => 'rust',
'name' => 'Rust',
'emoji' => '🦀',
'icon_url' => $rust->apiIconUrl($this->user),
]]]);
});

it('matches literal wildcards and Unicode names', function (string $term, string $name): void {
Guild::factory()->create(['handle' => 'match', 'name' => $name]);
Guild::factory()->create(['handle' => 'other', 'name' => 'Other']);

signedApiRequest($this->keyPair, 'GET', route('api-guild-suggestion.index', ['q' => $term]))
->assertOk()
->assertJsonPath('data.*.handle', ['match']);
})->with([['%', '100%'], ['_', 'Safe_code'], ['!', 'Hello!'], ['école', 'ÉCOLE'], ['κοσμος', 'ΚΟΣΜΟΣ'], ['İstanbul', 'İstanbul'], ['istanbul', 'İSTANBUL']]);

it('matches a handle with a dotted capital I however it is typed', function (string $term): void {
Guild::factory()->create(['handle' => mb_strtolower('İstanbul'), 'name' => 'City']);
Guild::factory()->create(['handle' => 'other', 'name' => 'Other']);

signedApiRequest($this->keyPair, 'GET', route('api-guild-suggestion.index', ['q' => $term]))
->assertOk()
->assertJsonPath('data.*.handle', [mb_strtolower('İstanbul')]);
})->with(['İstanbul', 'istanbul', 'İst']);

it('suggests no guilds while guilds are not available to the user', function (bool $enabled, bool $adminOnly): void {
resolve(Features::class)->update(Feature::Guilds, $enabled, $adminOnly);
Guild::factory()->create(['handle' => 'rust']);

signedApiRequest($this->keyPair, 'GET', route('api-guild-suggestion.index', ['q' => 'rust']))->assertNotFound();
})->with([
'admin preview' => [true, true],
'switched off' => [false, false],
]);

it('suggests guilds to admins during the admin preview', function (): void {
config(['app.admins' => [$this->user->handle]]);
resolve(Features::class)->update(Feature::Guilds, true, adminOnly: true);
Guild::factory()->create(['handle' => 'rust']);

signedApiRequest($this->keyPair, 'GET', route('api-guild-suggestion.index', ['q' => 'rust']))
->assertOk()
->assertJsonPath('data.*.handle', ['rust']);
});

it('rejects an invalid search', function (mixed $query): void {
signedApiRequest($this->keyPair, 'GET', route('api-guild-suggestion.index', ['q' => $query]))
->assertUnprocessable()
->assertJsonValidationErrors('q');
})->with([
'array' => [['rust']],
'too long' => [str_repeat('x', 101)],
]);

it('shares the 120 people lookups a minute with the web', function (): void {
foreach (range(1, 120) as $lookup) {
$this->actingAs($this->user)->getJson(route('guild-suggestions.index', ['q' => 'rust']))->assertOk();
}

signedApiRequest($this->keyPair, 'GET', route('api-guild-suggestion.index', ['q' => 'rust']))
->assertTooManyRequests()
->assertExactJson(['message' => 'Too Many Attempts.', 'code' => 'rate_limited']);
});

it('requires a signed request', function (): void {
$this->getJson(route('api-guild-suggestion.index', ['q' => 'rust']))->assertUnauthorized();
});
11 changes: 10 additions & 1 deletion tests/Feature/Controllers/GuildSuggestionControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,16 @@
$this->actingAs(User::factory()->create(['handle' => 'admin']))
->getJson(route('guild-suggestions.index', ['q' => $term]))
->assertOk()->assertJsonCount(1, 'guilds')->assertJsonPath('guilds.0.handle', 'match');
})->with([['%', '100%'], ['_', 'Safe_code'], ['!', 'Hello!'], ['école', 'ÉCOLE'], ['κοσμος', 'ΚΟΣΜΟΣ']]);
})->with([['%', '100%'], ['_', 'Safe_code'], ['!', 'Hello!'], ['école', 'ÉCOLE'], ['κοσμος', 'ΚΟΣΜΟΣ'], ['i̇stanbul', 'İstanbul'], ['istanbul', 'İSTANBUL']]);

it('matches a handle with a dotted capital I however it is typed', function (string $term): void {
Guild::factory()->create(['handle' => mb_strtolower('İstanbul'), 'name' => 'City']);
Guild::factory()->create(['handle' => 'other', 'name' => 'Other']);

$this->actingAs(User::factory()->create(['handle' => 'admin']))
->getJson(route('guild-suggestions.index', ['q' => $term]))
->assertOk()->assertJsonCount(1, 'guilds')->assertJsonPath('guilds.0.handle', mb_strtolower('İstanbul'));
})->with(['i̇stanbul', 'istanbul', 'i̇st']);

it('protects suggestions behind sign in and guild feature access', function (): void {
$this->getJson(route('guild-suggestions.index'))->assertUnauthorized();
Expand Down