Skip to content

Beautiful Open-Source Form Builder

Add telemetry instance identification and ping command

Julien Nahum55c197630cb4
diff --git a/api/app/Console/Commands/InitializeInstance.php b/api/app/Console/Commands/InitializeInstance.php
index a77c3be73..69ceca11b 100644
--- a/api/app/Console/Commands/InitializeInstance.php
+++ b/api/app/Console/Commands/InitializeInstance.php
@@ -4,6 +4,7 @@ namespace App\Console\Commands;
use App\Enums\SettingsKey;
use App\Models\Setting;
+use App\Service\Telemetry\TelemetryService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
@@ -27,7 +28,7 @@ class InitializeInstance extends Command
/**
* Execute the console command.
*/
- public function handle(): int
+ public function handle(TelemetryService $telemetryService): int
{
// Check if instance_id already exists
$instanceId = Setting::get(SettingsKey::INSTANCE_ID);
@@ -51,6 +52,13 @@ class InitializeInstance extends Command
$this->info('Instance initialized successfully. Instance ID: ' . $uuid);
+ // Identify instance in OpenPanel with version
+ if ($telemetryService->shouldSendTelemetry()) {
+ $client = $telemetryService->createClient();
+ $version = $telemetryService->getAppVersion();
+ $client->identifyInstance($uuid, $version);
+ }
+
// Track instance creation
telemetry(\App\Service\Telemetry\TelemetryEvent::INSTANCE_CREATED);
diff --git a/api/app/Console/Commands/SendTelemetryPing.php b/api/app/Console/Commands/SendTelemetryPing.php
new file mode 100644
index 000000000..23fd62635
--- /dev/null
+++ b/api/app/Console/Commands/SendTelemetryPing.php
@@ -0,0 +1,59 @@
+<?php
+
+namespace App\Console\Commands;
+
+use App\Service\Telemetry\TelemetryEvent;
+use App\Service\Telemetry\TelemetryService;
+use Illuminate\Console\Command;
+
+class SendTelemetryPing extends Command
+{
+ /**
+ * The name and signature of the console command.
+ *
+ * @var string
+ */
+ protected $signature = 'telemetry:ping';
+
+ /**
+ * The console command description.
+ *
+ * @var string
+ */
+ protected $description = 'Send a ping event to track active instances (runs hourly, sends once per day per instance)';
+
+ /**
+ * Execute the console command.
+ */
+ public function handle(TelemetryService $telemetryService): int
+ {
+ if (!$telemetryService->shouldSendTelemetry()) {
+ return Command::SUCCESS;
+ }
+
+ $instanceId = $telemetryService->getInstanceId();
+
+ if (!$instanceId) {
+ $this->warn('Telemetry ping skipped: instance_id not found');
+ return Command::SUCCESS;
+ }
+
+ // Use instance_id hash to determine which hour of the day (0-23) this instance should ping
+ // This distributes the load across all 24 hours
+ // Since the command runs hourly, each instance will only ping once per day during its assigned hour
+ $assignedHour = hexdec(substr(md5($instanceId), 0, 2)) % 24;
+ $currentHour = (int) now()->format('H');
+
+ // Only send ping if it's the assigned hour for this instance
+ if ($assignedHour !== $currentHour) {
+ return Command::SUCCESS;
+ }
+
+ // Send ping event
+ telemetry(TelemetryEvent::INSTANCE_PING);
+
+ $this->info('Telemetry ping sent successfully');
+
+ return Command::SUCCESS;
+ }
+}
diff --git a/api/app/Console/Kernel.php b/api/app/Console/Kernel.php
index 35993dc15..edb7e48a1 100644
--- a/api/app/Console/Kernel.php
+++ b/api/app/Console/Kernel.php
@@ -27,6 +27,7 @@ class Kernel extends ConsoleKernel
$schedule->command('forms:integration-events-cleanup')->daily();
if (config('app.self_hosted')) {
$schedule->command('app:scheduler-status --mode=record')->everyMinute();
+ $schedule->command('telemetry:ping')->hourly();
}
}
diff --git a/api/app/Service/Telemetry/OpenPanelClient.php b/api/app/Service/Telemetry/OpenPanelClient.php
index 7bbf9c14f..f98479205 100644
--- a/api/app/Service/Telemetry/OpenPanelClient.php
+++ b/api/app/Service/Telemetry/OpenPanelClient.php
@@ -14,26 +14,81 @@ class OpenPanelClient
) {
}
+ /**
+ * Identify an instance as a user in OpenPanel.
+ *
+ * @param string $profileId The instance ID to use as profile ID
+ * @param string|null $version The OpnForm version
+ * @param array $properties Additional properties to identify
+ * @return bool
+ */
+ public function identifyInstance(
+ string $profileId,
+ ?string $version = null,
+ array $properties = []
+ ): bool {
+ if (!$this->clientId || !$this->clientSecret) {
+ Log::warning('Telemetry skipped: missing client credentials');
+ return false;
+ }
+
+ try {
+ $identifyProperties = $properties;
+ if ($version) {
+ $identifyProperties['opnform_version'] = $version;
+ }
+
+ $payload = [
+ 'type' => 'identify',
+ 'payload' => [
+ 'profileId' => $profileId,
+ 'properties' => $identifyProperties,
+ ],
+ ];
+
+ $response = $this->sendRequest($payload);
+
+ if (!$response->successful()) {
+ Log::warning('Telemetry identify failed to send', [
+ 'profileId' => $profileId,
+ 'status' => $response->status(),
+ 'response' => $response->body(),
+ ]);
+
+ return false;
+ }
+
+ return true;
+ } catch (\Exception $e) {
+ Log::warning('Telemetry identify error', [
+ 'profileId' => $profileId,
+ 'error' => $e->getMessage(),
+ ]);
+
+ return false;
+ }
+ }
+
/**
* Send an event to OpenPanel.
*
* @param string $eventName
* @param array $properties
- * @param string|null $instanceId
+ * @param string $profileId The instance ID to use as profileId to link event to identified user
* @return bool
*/
public function sendEvent(
string $eventName,
array $properties,
- ?string $instanceId
+ string $profileId
): bool {
if (!$this->clientId || !$this->clientSecret) {
Log::warning('Telemetry skipped: missing client credentials');
return false;
}
- if (!$instanceId) {
- Log::warning('Telemetry skipped: instance_id not found');
+ if (!$profileId) {
+ Log::warning('Telemetry skipped: profileId not found');
return false;
}
@@ -42,18 +97,12 @@ class OpenPanelClient
'type' => 'track',
'payload' => [
'name' => $eventName,
- 'properties' => array_merge($properties, [
- 'instance_id' => $instanceId,
- ]),
+ 'properties' => $properties,
+ 'profileId' => $profileId,
],
];
- $response = Http::timeout(5)
- ->withHeaders([
- 'openpanel-client-id' => $this->clientId,
- 'openpanel-client-secret' => $this->clientSecret,
- ])
- ->post($this->endpoint, $payload);
+ $response = $this->sendRequest($payload);
if (!$response->successful()) {
Log::warning('Telemetry event failed to send', [
@@ -75,4 +124,20 @@ class OpenPanelClient
return false;
}
}
+
+ /**
+ * Send a request to the OpenPanel API.
+ *
+ * @param array $payload
+ * @return \Illuminate\Http\Client\Response
+ */
+ private function sendRequest(array $payload)
+ {
+ return Http::timeout(5)
+ ->withHeaders([
+ 'openpanel-client-id' => $this->clientId,
+ 'openpanel-client-secret' => $this->clientSecret,
+ ])
+ ->post($this->endpoint, $payload);
+ }
}
diff --git a/api/app/Service/Telemetry/TelemetryEvent.php b/api/app/Service/Telemetry/TelemetryEvent.php
index d7bbe0ac9..78120df49 100644
--- a/api/app/Service/Telemetry/TelemetryEvent.php
+++ b/api/app/Service/Telemetry/TelemetryEvent.php
@@ -5,6 +5,7 @@ namespace App\Service\Telemetry;
enum TelemetryEvent: string
{
case INSTANCE_CREATED = 'instance.created';
+ case INSTANCE_PING = 'instance.ping';
case USER_CREATED = 'user.created';
case FORM_CREATED = 'form.created';
case WORKSPACE_CREATED = 'workspace.created';
diff --git a/api/app/Service/Telemetry/TelemetryService.php b/api/app/Service/Telemetry/TelemetryService.php
index df8d896ab..b876fb482 100644
--- a/api/app/Service/Telemetry/TelemetryService.php
+++ b/api/app/Service/Telemetry/TelemetryService.php
@@ -76,6 +76,16 @@ class TelemetryService
return config('telemetry.client_secret');
}
+ /**
+ * Get the application version.
+ *
+ * @return string|null
+ */
+ public function getAppVersion(): ?string
+ {
+ return config('app.docker_version');
+ }
+
/**
* Create a configured OpenPanel client instance.
*
diff --git a/api/tests/Feature/Telemetry/SendTelemetryJobTest.php b/api/tests/Feature/Telemetry/SendTelemetryJobTest.php
index bd3103a9e..b065afe29 100644
--- a/api/tests/Feature/Telemetry/SendTelemetryJobTest.php
+++ b/api/tests/Feature/Telemetry/SendTelemetryJobTest.php
@@ -79,7 +79,7 @@ describe('SendTelemetryJob', function () {
Http::assertNothingSent();
});
- it('includes instance id in event properties', function () {
+ it('includes profileId in event payload', function () {
$instanceId = 'test-instance-id';
Setting::set(SettingsKey::INSTANCE_ID, $instanceId);
@@ -97,9 +97,9 @@ describe('SendTelemetryJob', function () {
);
Http::assertSent(function ($request) use ($instanceId) {
- $properties = $request['payload']['properties'];
- return $properties['instance_id'] === $instanceId
- && $properties['custom'] === 'property';
+ $payload = $request['payload'];
+ return $payload['profileId'] === $instanceId
+ && $payload['properties']['custom'] === 'property';
});
});
diff --git a/api/tests/Feature/Telemetry/UserCreatedDuringSetupTest.php b/api/tests/Feature/Telemetry/UserCreatedDuringSetupTest.php
new file mode 100644
index 000000000..c4e016f40
--- /dev/null
+++ b/api/tests/Feature/Telemetry/UserCreatedDuringSetupTest.php
@@ -0,0 +1,102 @@
+<?php
+
+use App\Enums\SettingsKey;
+use App\Models\Setting;
+use App\Models\User;
+use App\Rules\ValidReCaptcha;
+use App\Service\Telemetry\TelemetryEvent;
+use Illuminate\Support\Facades\Config;
+use Illuminate\Support\Facades\Http;
+use Illuminate\Support\Facades\Queue;
+use Illuminate\Support\Str;
+
+describe('UserCreated event during setup', function () {
+ beforeEach(function () {
+ Queue::fake();
+ Config::set('telemetry.enabled', true);
+ Config::set('app.self_hosted', true);
+ Config::set('services.re_captcha.secret_key', 'test-secret');
+
+ // Set production environment (telemetry requires both production AND self-hosted)
+ app()->detectEnvironment(fn () => 'production');
+
+ Http::fake([
+ ValidReCaptcha::RECAPTCHA_VERIFY_URL => Http::response(['success' => true])
+ ]);
+ });
+
+ it('fires UserCreated event when first user is created during setup', function () {
+ // Initialize instance first (simulating setup flow)
+ $instanceId = (string) Str::uuid();
+ Setting::set(SettingsKey::INSTANCE_ID, $instanceId);
+
+ // Ensure no users exist (setup scenario)
+ expect(User::count())->toBe(0);
+
+ // Create first user via RegisterController (simulating setup flow)
+ $response = $this->postJson('/register', [
+ 'name' => 'Admin User',
+ 'email' => '[email protected]',
+ 'hear_about_us' => 'google',
+ 'password' => 'Abcd@1234',
+ 'password_confirmation' => 'Abcd@1234',
+ 'g-recaptcha-response' => 'test-token',
+ ]);
+
+ $response->assertSuccessful();
+
+ // Assert user was created
+ $user = User::where('email', '[email protected]')->first();
+ expect($user)->not->toBeNull();
+
+ // UserCreated event is automatically fired by Eloquent when User is created
+ // We verify it by checking that the telemetry job was dispatched
+
+ // Assert telemetry job was dispatched with USER_CREATED event
+ Queue::assertPushed(\App\Service\Telemetry\SendTelemetryJob::class, function ($job) {
+ return $job->eventName === TelemetryEvent::USER_CREATED->value();
+ });
+ });
+
+ it('sends telemetry with profileId when instance is initialized', function () {
+ // Initialize instance first
+ $instanceId = (string) Str::uuid();
+ Setting::set(SettingsKey::INSTANCE_ID, $instanceId);
+
+ // Create first user
+ $this->postJson('/register', [
+ 'name' => 'Admin User',
+ 'email' => '[email protected]',
+ 'hear_about_us' => 'google',
+ 'password' => 'Abcd@1234',
+ 'password_confirmation' => 'Abcd@1234',
+ 'g-recaptcha-response' => 'test-token',
+ ])->assertSuccessful();
+
+ // Verify telemetry job was dispatched
+ Queue::assertPushed(\App\Service\Telemetry\SendTelemetryJob::class);
+ });
+
+ it('dispatches telemetry job even when instance is not initialized', function () {
+ // Don't initialize instance
+ expect(Setting::get(SettingsKey::INSTANCE_ID))->toBeNull();
+
+ // Create first user
+ $this->postJson('/register', [
+ 'name' => 'Admin User',
+ 'email' => '[email protected]',
+ 'hear_about_us' => 'google',
+ 'password' => 'Abcd@1234',
+ 'password_confirmation' => 'Abcd@1234',
+ 'g-recaptcha-response' => 'test-token',
+ ])->assertSuccessful();
+
+ // UserCreated event is automatically fired by Eloquent when User is created
+
+ // Telemetry job is still dispatched, but will check for instance_id
+ // and return early in the job handler if not found
+ Queue::assertPushed(\App\Service\Telemetry\SendTelemetryJob::class, function ($job) {
+ return $job->eventName === TelemetryEvent::USER_CREATED->value();
+ });
+ });
+});
diff --git a/api/tests/Unit/Service/Telemetry/OpenPanelClientTest.php b/api/tests/Unit/Service/Telemetry/OpenPanelClientTest.php
index d7f8496c6..a35adb6f2 100644
--- a/api/tests/Unit/Service/Telemetry/OpenPanelClientTest.php
+++ b/api/tests/Unit/Service/Telemetry/OpenPanelClientTest.php
@@ -44,7 +44,7 @@ describe('OpenPanelClient', function () {
&& $request['type'] === 'track'
&& $request['payload']['name'] === 'test.event'
&& $request['payload']['properties']['foo'] === 'bar'
- && $request['payload']['properties']['instance_id'] === 'instance-id';
+ && $request['payload']['profileId'] === 'instance-id';
});
});
@@ -130,7 +130,7 @@ describe('OpenPanelClient', function () {
->once();
});
- it('includes instance id in event properties', function () {
+ it('includes profileId in event payload', function () {
$client = new OpenPanelClient(
'https://test-endpoint.com/track',
'client-id',
@@ -148,13 +148,13 @@ describe('OpenPanelClient', function () {
);
Http::assertSent(function ($request) {
- $properties = $request['payload']['properties'];
- return $properties['instance_id'] === 'test-instance-id'
- && $properties['custom'] === 'property';
+ $payload = $request['payload'];
+ return $payload['profileId'] === 'test-instance-id'
+ && $payload['properties']['custom'] === 'property';
});
});
- it('returns false when instance id is missing', function () {
+ it('returns false when profileId is empty', function () {
$client = new OpenPanelClient(
'https://test-endpoint.com/track',
'client-id',
@@ -163,10 +163,11 @@ describe('OpenPanelClient', function () {
Http::fake();
+ // Empty string should trigger the validation
$result = $client->sendEvent(
'test.event',
[],
- null
+ ''
);
expect($result)->toBeFalse();
diff --git a/api/tests/Unit/Service/Telemetry/TelemetryEventTest.php b/api/tests/Unit/Service/Telemetry/TelemetryEventTest.php
index a03cd3f5b..c63cd8d10 100644
--- a/api/tests/Unit/Service/Telemetry/TelemetryEventTest.php
+++ b/api/tests/Unit/Service/Telemetry/TelemetryEventTest.php
@@ -4,7 +4,7 @@ use App\Service\Telemetry\TelemetryEvent;
describe('TelemetryEvent', function () {
it('has all required event cases', function () {
- expect(TelemetryEvent::cases())->toHaveCount(5);
+ expect(TelemetryEvent::cases())->toHaveCount(6);
});
it('has INSTANCE_CREATED case with correct value', function () {
@@ -27,6 +27,10 @@ describe('TelemetryEvent', function () {
expect(TelemetryEvent::FORM_SUBMISSION->value)->toBe('form.submission');
});
+ it('has INSTANCE_PING case with correct value', function () {
+ expect(TelemetryEvent::INSTANCE_PING->value)->toBe('instance.ping');
+ });
+
it('value method returns the enum value', function () {
expect(TelemetryEvent::INSTANCE_CREATED->value())->toBe('instance.created');
expect(TelemetryEvent::USER_CREATED->value())->toBe('user.created');