Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add API for triggering a speedtest. #1141

Open
wants to merge 4 commits into
base: implement-an-api
Choose a base branch
from
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
2 changes: 2 additions & 0 deletions app/Console/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ protected function schedule(Schedule $schedule): void
return (new CronExpression($settings->speedtest_schedule))
->isDue(now()->timezone($settings->timezone ?? 'UTC'));
});
$schedule->command('model:prune')->daily()
->timezone($settings->timezone ?? 'UTC');
}

/**
Expand Down
44 changes: 0 additions & 44 deletions app/Http/Controllers/API/Speedtest/GetLatestController.php

This file was deleted.

99 changes: 99 additions & 0 deletions app/Http/Controllers/API/Speedtest/MeasurementController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
<?php

namespace App\Http\Controllers\API\Speedtest;

use App\Http\Controllers\Controller;
use App\Http\Resources\ResultResource;
use App\Jobs\ExecSpeedtest;
use App\Models\JobTracking;
use App\Models\JobTrackingStatusEnum;
use App\Models\Result;
use App\Settings\GeneralSettings;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;
use Str;

class MeasurementController extends Controller
{

public function createNew(): JsonResponse
{
$uuid = Str::uuid()->toString();

$config = [];
$settings = new GeneralSettings();
if (is_array($settings->speedtest_server) && count($settings->speedtest_server)) {
$config = array_merge($config, [
'ookla_server_id' => Arr::random($settings->speedtest_server),
]);
}
try {
ExecSpeedtest::dispatch(
speedtest: $config,
tracking_key: $uuid,
scheduled: false,
tracked: true
);
$this->createTracking($uuid);
} catch (\Throwable $th) {
Log::warning($th);
return response()->json(['exception' => $th]);

}

// Return the UUID to the API caller
return response()->json(['uuid' => $uuid]);
}

public function getLatest(): JsonResponse
{
$latest = Result::query()
->latest()
->first();

if (!$latest) {
return response()->json([
'message' => 'No results found.',
], 404);
}

return response()->json([
'message' => 'ok',
'data' => new ResultResource($latest),
]);
}

public function getMeasurementByTrackingId(string $uuid)
{
$trackingData = JobTracking::query()->where('tracking_key', $uuid)->first();
if ($trackingData == null) {
return response()->json([
'status' => 'Not Found',
'trackingid' => $uuid,
'message' => "The requested speedtest tracking information, could not be found."], 404);
}
if ($trackingData->status != 'complete') {
return response()->json([
'status' => $trackingData->status,
'trackingid' => $uuid,
'message' => "The requested speedtest is currently {$trackingData->status}"]);
}

$result = Result::find($trackingData->result_id);
return response(new ResultResource($result));

}


private function createTracking(string $tracking_key): void
{
JobTracking::create([
'tracking_key' => $tracking_key,
'status' => JobTrackingStatusEnum::Queued,
'result_id' => null
]);
}


}
77 changes: 77 additions & 0 deletions app/Http/Resources/ResultResource.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<?php

namespace App\Http\Resources;

use App\Models\Result;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class ResultResource extends JsonResource
{
private mixed $id;
private mixed $ping;
private mixed $download;
private mixed $upload;
private mixed $server_id;
private mixed $server_host;
private mixed $server_name;
private mixed $url;
private mixed $scheduled;
private mixed $successful;
private mixed $created_at;

/**
* @param mixed $id
* @param mixed $ping
* @param mixed $download
* @param mixed $upload
* @param mixed $server_id
* @param mixed $server_host
* @param mixed $server_name
* @param mixed $url
* @param mixed $scheduled
* @param mixed $successful
* @param mixed $created_at
*/
public function __construct(Result $result)
{
parent::__construct($result);
$this->id = $result->id;
$this->ping = $result->ping;
$this->download = $result->download;
$this->upload = $result->upload;
$this->server_id = $result->server_id;
$this->server_host = $result->server_host;
$this->server_name = $result->server_name;
$this->url = $result->url;
$this->scheduled = $result->scheduled;
$this->successful = $result->successful;
$this->created_at = $result->created_at;
}


/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'ping' => $this->ping,
'download' => !blank($this->download) ? toBits(convertSize($this->download)) : null,
'upload' => !blank($this->upload) ? toBits(convertSize($this->upload)) : null,
'server_id' => $this->server_id,
'server_host' => $this->server_host,
'server_name' => $this->server_name,
'url' => $this->url,
'scheduled' => $this->scheduled,
'failed' => !$this->successful,
'created_at' => $this->created_at->toISOString(true),
'updated_at' => $this->created_at->toISOString(true), // faking updated at to match legacy api payload
];
}


}
34 changes: 28 additions & 6 deletions app/Jobs/ExecSpeedtest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace App\Jobs;

use App\Models\JobTracking;
use App\Models\JobTrackingStatusEnum;
use App\Models\Result;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
Expand All @@ -22,23 +24,27 @@ class ExecSpeedtest implements ShouldQueue
* @return void
*/
public function __construct(
public ?array $speedtest = null,
public bool $scheduled = false
) {
public ?array $speedtest = null,
public ?string $tracking_key = '',
public bool $scheduled = false,
public bool $tracked = false,
)
{
}

/**
* Execute the job.
*/
public function handle(): void
{
$this->updateJobStatus(JobTrackingStatusEnum::Pending);
$process = new Process(
array_filter([
'speedtest',
'--accept-license',
'--accept-gdpr',
'--format=json',
optional($this->speedtest)['ookla_server_id'] ? '--server-id='.$this->speedtest['ookla_server_id'] : false,
optional($this->speedtest)['ookla_server_id'] ? '--server-id=' . $this->speedtest['ookla_server_id'] : false,
])
);

Expand All @@ -54,6 +60,7 @@ public function handle(): void
'successful' => false,
'data' => $message,
]);
$this->updateJobStatus(JobTrackingStatusEnum::Failed);

return;
}
Expand All @@ -62,19 +69,34 @@ public function handle(): void
$output = $process->getOutput();
$results = json_decode($output, true);

Result::create([
$result = Result::create([
'ping' => $results['ping']['latency'],
'download' => $results['download']['bandwidth'],
'upload' => $results['upload']['bandwidth'],
'server_id' => $results['server']['id'],
'server_name' => $results['server']['name'],
'server_host' => $results['server']['host'].':'.$results['server']['port'],
'server_host' => $results['server']['host'] . ':' . $results['server']['port'],
'url' => $results['result']['url'],
'scheduled' => $this->scheduled,
'data' => $output,
]);
$this->updateJobStatus(JobTrackingStatusEnum::Complete, $result->id);
} catch (\Exception $e) {
$this->updateJobStatus(JobTrackingStatusEnum::Failed);
Log::error($e->getMessage());
}
}

public function updateJobStatus(JobTrackingStatusEnum $status, $result_id = null): void
{
if ($this->tracked) {
JobTracking::where('tracking_key', $this->tracking_key)->
update([
'status' => $status,
'result_id' => $result_id

]);

}
}
}
21 changes: 21 additions & 0 deletions app/Models/JobTracking.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Prunable;

class JobTracking extends Model
{
use Prunable;

protected $fillable = ['tracking_key', 'status', 'result_id'];

public function prunable(): Builder
{
return static::where('created_at', '<', Carbon::now()->subDays(30))
->orWhere('status', JobTrackingStatusEnum::Failed);
}
}
12 changes: 12 additions & 0 deletions app/Models/JobTrackingStatusEnum.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

namespace App\Models;

enum JobTrackingStatusEnum: string
{
case Queued = 'queued';
case Complete = 'complete';
case Failed = 'failed';
case Pending = 'pending';

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration {
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('job_trackings', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('result_id')->nullable();
$table->string('status')->default('queued');
$table->uuid('tracking_key')->unique();
$table->foreign('result_id')->references('id')->on('results')->onDelete('cascade');
$table->timestamps();
});
}

/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('job_trackings');
}
};
Loading