3 changes: 3 additions & 0 deletions ProcessMaker/Facades/Metrics.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,9 @@
* @method static void setGauge(string $name, float $value, array $labelValues = [])
* @method static string renderMetrics()
* @method static \Prometheus\CollectorRegistry getCollectionRegistry()
* @method static void counterInc(string $name, string $help = null, array $labels = [])
* @method static void histogramObserve(string $name, string $help = null, array $labels = [], array $buckets = [0.1, 1, 5, 10], float $executionTime)
* @method static void clearMetrics()
*/
class Metrics extends Facade
{
Expand Down
9 changes: 1 addition & 8 deletions ProcessMaker/Jobs/CompleteActivity.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,16 +47,9 @@ public function action(ProcessRequestToken $token, ActivityInterface $element, a
$this->engine->runToNextState();
$element->complete($token);

Metrics::counter(
Metrics::counterInc(
'activity_completed_total',
'Total number of activities completed',
[
'activity_id',
'activity_name',
'process_id',
'request_id',
]
)->inc(
[
'activity_id' => $element->getId(),
'activity_name' => $element->getName(),
Expand Down
10 changes: 1 addition & 9 deletions ProcessMaker/Jobs/RunScriptTask.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -113,17 +113,9 @@ public function action(ProcessRequestToken $token = null, ScriptTaskInterface $e

$this->updateData($response);

Metrics::counter(
Metrics::counterInc(
'script_task_completed_total',
'Total number of script tasks completed',
[
'activity_id',
'activity_name',
'process_id',
'request_id',
'script_executor',
]
)->inc(
[
'activity_id' => $element->getId(),
'activity_name' => $element->getName(),
Expand Down
16 changes: 4 additions & 12 deletions ProcessMaker/Listeners/BpmnSubscriber.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -149,26 +149,18 @@ public function onActivityCompleted(ActivityCompletedEvent $event)
$startTime = $token->created_at_ms;
$completedTime = $token->completed_at_ms;
$executionTime = $completedTime->diffInMilliseconds($startTime);
Metrics::histogram(
Metrics::histogramObserve(
'activity_execution_time_seconds',
'Activity Execution Time',
[
'activity_id',
'activity_name',
'element_type',
'process_id',
'request_id',
],
[1, 10, 3600, 86400]
)->observe(
$executionTime,
[
'activity_id' => $token->element_id,
'activity_name' => $token->element_name,
'element_type' => $token->element_type,
'process_id' => $token->process_id,
'request_id' => $token->process_request_id,
]
],
[1, 10, 3600, 86400],
$executionTime,
);

if ($token->element_type == 'task') {
Expand Down
78 changes: 78 additions & 0 deletions ProcessMaker/Services/MetricsService.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,7 @@
namespace ProcessMaker\Services;

use Exception;
use ProcessMaker\Facades\Metrics;
use Prometheus\CollectorRegistry;
use Prometheus\Counter;
use Prometheus\Gauge;
Expand DownExpand Up@@ -146,4 +147,81 @@ public function renderMetrics(): string

return $renderer->render($metrics);
}

/**
* Increments a counter metric by 1.
*
* @param string $name The name of the counter.
* @param string|null $help The help text of the counter.
* @param array $labels The labels of the counter.
*
* @return void
*/
public function counterInc(string $name, string $help = null, array $labels = []): void
{
// Add system labels
$labels = $this->addSystemLabels($labels);
$labelKeys = array_keys($labels);
Metrics::counter($name, $help, $labelKeys)->inc($labels);
}

/**
* Histogram observation.
*
* @param string $name The name of the histogram.
* @param string|null $help The help text of the histogram.
* @param array $labels The labels of the histogram.
* @param array $buckets The buckets of the histogram.
* @param float $executionTime The execution
*
* @return void
*/
public function histogramObserve(string $name, string $help = null, array $labels = [], array $buckets = [0.1, 1, 5, 10], float $executionTime = 0): void
{
// Add system labels
$labels = $this->addSystemLabels($labels);
$labelKeys = array_keys($labels);
Metrics::histogram(
$name,
$help,
$labelKeys,
$buckets
)->observe(
$executionTime,
$labels
);
}

/**
* Add system labels to the provided labels.
*
* @param array $labels The labels to add system labels to.
*
* @return array The keys of the labels.
*/
public function addSystemLabels(array $labels)
{
// Add system labels
$labels['app_version'] = $this->getApplicationVersion();
$labels['app_name'] = config('app.name');
$labels['app_custom_label'] = config('app.prometheus_custom_label');
return $labels;
}

public function clearMetrics(): void
{
$this->collectionRegistry->wipeStorage();
}

/**
* Gets the version of the application.
*
* @return string The version of the application.
*/
private function getApplicationVersion()
{
$root = base_path('composer.json');
$composer_json_path = json_decode(file_get_contents($root));
return $composer_json_path->version ?? '4.0.0';
}
}
1 change: 1 addition & 0 deletions tests/Feature/Metrics/TaskMetricsTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,6 +47,7 @@ private function assertMetricWasStored(string $name, array $labels)
$metric = $adapter->getCounter($ns, $name);

$this->assertInstanceOf(Counter::class, $metric);
$labels = Metrics::addSystemLabels($labels);
$this->assertEquals($metric->getLabelNames(), array_keys($labels));
}
}
142 changes: 142 additions & 0 deletions tests/unit/MetricsServiceTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,10 +3,18 @@
namespace Tests\Unit;

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Mockery;
use ProcessMaker\Facades\Metrics;
use ProcessMaker\Services\MetricsService;
use Prometheus\CollectorRegistry;
use Prometheus\Counter;
use Prometheus\Histogram;
use Prometheus\Storage\InMemory;
use ReflectionClass;
use Tests\TestCase;


class MetricsServiceTest extends TestCase
{
/**
Expand DownExpand Up@@ -123,4 +131,138 @@ public function testSetGaugeValue(): void
$this->assertStringContainsString('test_set_gauge', $samples);
$this->assertStringContainsString('5', $samples);
}
/**
* Test that counterInc calls Metrics::counter() and then inc() with the correct labels.
*/
public function testCounterInc()
{
// Set configuration values used by addSystemLabels()
Config::set('app.name', 'TestApp');
Config::set('app.prometheus_custom_label', 'customValue');

// Create an instance of MetricsService.
$service = new MetricsService();

$counterName = 'test_counter';
$helpText = 'A test counter';
$initialLabels = ['user' => '123'];

// Determine what system labels will be added.
// (We call addSystemLabels with an empty array to extract the system values.)
$systemLabels = $service->addSystemLabels([]);
// Merge the initial labels with system labels.
$expectedLabels = array_merge($initialLabels, [
'app_version' => $systemLabels['app_version'],
'app_name' => 'TestApp',
'app_custom_label' => 'customValue',
]);
$expectedLabelKeys = array_keys($expectedLabels);

// Create a mock Counter object that expects inc() to be called once.
$mockCounter = Mockery::mock(Counter::class);
$mockCounter->shouldReceive('inc')
->once()
->with($expectedLabels);

// Expect the Metrics facade to be called with the right parameters
// and to return our mock Counter.
Metrics::shouldReceive('counter')
->once()
->with($counterName, $helpText, $expectedLabelKeys)
->andReturn($mockCounter);

// Call counterInc which should trigger the facade calls.
$service->counterInc($counterName, $helpText, $initialLabels);
}

/**
* Test that histogramObserve calls Metrics::histogram() and then observe() with the correct values.
*/
public function testHistogramObserve()
{
// Set configuration values used by addSystemLabels()
Config::set('app.name', 'TestApp');
Config::set('app.prometheus_custom_label', 'customValue');

$service = new MetricsService();

$histogramName = 'test_histogram';
$helpText = 'A test histogram';
$initialLabels = ['endpoint' => '/api/test'];
$buckets = [0.1, 1, 5, 10];
$executionTime = 2.5;

// Determine what system labels will be added.
$systemLabels = $service->addSystemLabels([]);
$expectedLabels = array_merge($initialLabels, [
'app_version' => $systemLabels['app_version'],
'app_name' => 'TestApp',
'app_custom_label' => 'customValue',
]);
$expectedLabelKeys = array_keys($expectedLabels);

// Create a mock Histogram that expects observe() to be called once.
$mockHistogram = Mockery::mock(Histogram::class);
$mockHistogram->shouldReceive('observe')
->once()
->with($executionTime, $expectedLabels);

// Expect the Metrics facade to be called with the right parameters
// and to return our mock Histogram.
Metrics::shouldReceive('histogram')
->once()
->with($histogramName, $helpText, $expectedLabelKeys, $buckets)
->andReturn($mockHistogram);

// Call histogramObserve which should trigger the facade calls.
$service->histogramObserve($histogramName, $helpText, $initialLabels, $buckets, $executionTime);
}

/**
* Test that addSystemLabels returns the input labels plus the system labels.
*/
public function testAddSystemLabels()
{
// Set configuration values used by addSystemLabels()
Config::set('app.name', 'TestApp');
Config::set('app.prometheus_custom_label', 'customValue');

$service = new MetricsService();

$inputLabels = ['label1' => 'value1'];
$result = $service->addSystemLabels($inputLabels);

// Assert that the original label is preserved.
$this->assertEquals('value1', $result['label1']);

// Assert that the system labels were added.
$this->assertArrayHasKey('app_version', $result);
$this->assertArrayHasKey('app_name', $result);
$this->assertArrayHasKey('app_custom_label', $result);
$this->assertEquals('TestApp', $result['app_name']);
$this->assertEquals('customValue', $result['app_custom_label']);
$this->assertNotEmpty($result['app_version']); // Assuming composer.json defines a version.
}

/**
* Test that clearMetrics calls wipeStorage on the collection registry.
*/
public function testClearMetrics()
{
$service = new MetricsService();

// Create a mock for the CollectorRegistry.
$mockRegistry = Mockery::mock(CollectorRegistry::class);
$mockRegistry->shouldReceive('wipeStorage')
->once();

// Use reflection to override the private property "collectionRegistry" with our mock.
$reflection = new ReflectionClass($service);
$property = $reflection->getProperty('collectionRegistry');
$property->setAccessible(true);
$property->setValue($service, $mockRegistry);

// Call clearMetrics which should call wipeStorage on the registry.
$service->clearMetrics();
}
}
17 changes: 17 additions & 0 deletions upgrades/2025_02_03_191354_clear_prometheus_metrics.php
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
<?php

use ProcessMaker\Facades\Metrics;
use ProcessMaker\Upgrades\UpgradeMigration as Upgrade;

class ClearPrometheusMetrics extends Upgrade
{
/**
* Run the upgrade migration.
*
* @return void
*/
public function up()
{
Metrics::clearMetrics();
}
}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
3 changes: 3 additions & 0 deletions ProcessMaker/Facades/Metrics.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,9 @@
* @method static void setGauge(string $name, float $value, array $labelValues = [])
* @method static string renderMetrics()
* @method static \Prometheus\CollectorRegistry getCollectionRegistry()
* @method static void counterInc(string $name, string $help = null, array $labels = [])
* @method static void histogramObserve(string $name, string $help = null, array $labels = [], array $buckets = [0.1, 1, 5, 10], float $executionTime)
* @method static void clearMetrics()
*/
class Metrics extends Facade
{
Expand Down
9 changes: 1 addition & 8 deletions ProcessMaker/Jobs/CompleteActivity.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,16 +47,9 @@ public function action(ProcessRequestToken $token, ActivityInterface $element, a
$this->engine->runToNextState();
$element->complete($token);

Metrics::counter(
Metrics::counterInc(
'activity_completed_total',
'Total number of activities completed',
[
'activity_id',
'activity_name',
'process_id',
'request_id',
]
)->inc(
[
'activity_id' => $element->getId(),
'activity_name' => $element->getName(),
Expand Down
10 changes: 1 addition & 9 deletions ProcessMaker/Jobs/RunScriptTask.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -113,17 +113,9 @@ public function action(ProcessRequestToken $token = null, ScriptTaskInterface $e

$this->updateData($response);

Metrics::counter(
Metrics::counterInc(
'script_task_completed_total',
'Total number of script tasks completed',
[
'activity_id',
'activity_name',
'process_id',
'request_id',
'script_executor',
]
)->inc(
[
'activity_id' => $element->getId(),
'activity_name' => $element->getName(),
Expand Down
16 changes: 4 additions & 12 deletions ProcessMaker/Listeners/BpmnSubscriber.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -149,26 +149,18 @@ public function onActivityCompleted(ActivityCompletedEvent $event)
$startTime = $token->created_at_ms;
$completedTime = $token->completed_at_ms;
$executionTime = $completedTime->diffInMilliseconds($startTime);
Metrics::histogram(
Metrics::histogramObserve(
'activity_execution_time_seconds',
'Activity Execution Time',
[
'activity_id',
'activity_name',
'element_type',
'process_id',
'request_id',
],
[1, 10, 3600, 86400]
)->observe(
$executionTime,
[
'activity_id' => $token->element_id,
'activity_name' => $token->element_name,
'element_type' => $token->element_type,
'process_id' => $token->process_id,
'request_id' => $token->process_request_id,
]
],
[1, 10, 3600, 86400],
$executionTime,
);

if ($token->element_type == 'task') {
Expand Down
78 changes: 78 additions & 0 deletions ProcessMaker/Services/MetricsService.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,7 @@
namespace ProcessMaker\Services;

use Exception;
use ProcessMaker\Facades\Metrics;
use Prometheus\CollectorRegistry;
use Prometheus\Counter;
use Prometheus\Gauge;
Expand DownExpand Up@@ -146,4 +147,81 @@ public function renderMetrics(): string

return $renderer->render($metrics);
}

/**
* Increments a counter metric by 1.
*
* @param string $name The name of the counter.
* @param string|null $help The help text of the counter.
* @param array $labels The labels of the counter.
*
* @return void
*/
public function counterInc(string $name, string $help = null, array $labels = []): void
{
// Add system labels
$labels = $this->addSystemLabels($labels);
$labelKeys = array_keys($labels);
Metrics::counter($name, $help, $labelKeys)->inc($labels);
}

/**
* Histogram observation.
*
* @param string $name The name of the histogram.
* @param string|null $help The help text of the histogram.
* @param array $labels The labels of the histogram.
* @param array $buckets The buckets of the histogram.
* @param float $executionTime The execution
*
* @return void
*/
public function histogramObserve(string $name, string $help = null, array $labels = [], array $buckets = [0.1, 1, 5, 10], float $executionTime = 0): void
{
// Add system labels
$labels = $this->addSystemLabels($labels);
$labelKeys = array_keys($labels);
Metrics::histogram(
$name,
$help,
$labelKeys,
$buckets
)->observe(
$executionTime,
$labels
);
}

/**
* Add system labels to the provided labels.
*
* @param array $labels The labels to add system labels to.
*
* @return array The keys of the labels.
*/
public function addSystemLabels(array $labels)
{
// Add system labels
$labels['app_version'] = $this->getApplicationVersion();
$labels['app_name'] = config('app.name');
$labels['app_custom_label'] = config('app.prometheus_custom_label');
return $labels;
}

public function clearMetrics(): void
{
$this->collectionRegistry->wipeStorage();
}

/**
* Gets the version of the application.
*
* @return string The version of the application.
*/
private function getApplicationVersion()
{
$root = base_path('composer.json');
$composer_json_path = json_decode(file_get_contents($root));
return $composer_json_path->version ?? '4.0.0';
}
}
1 change: 1 addition & 0 deletions tests/Feature/Metrics/TaskMetricsTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,6 +47,7 @@ private function assertMetricWasStored(string $name, array $labels)
$metric = $adapter->getCounter($ns, $name);

$this->assertInstanceOf(Counter::class, $metric);
$labels = Metrics::addSystemLabels($labels);
$this->assertEquals($metric->getLabelNames(), array_keys($labels));
}
}
142 changes: 142 additions & 0 deletions tests/unit/MetricsServiceTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,10 +3,18 @@
namespace Tests\Unit;

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Mockery;
use ProcessMaker\Facades\Metrics;
use ProcessMaker\Services\MetricsService;
use Prometheus\CollectorRegistry;
use Prometheus\Counter;
use Prometheus\Histogram;
use Prometheus\Storage\InMemory;
use ReflectionClass;
use Tests\TestCase;


class MetricsServiceTest extends TestCase
{
/**
Expand DownExpand Up@@ -123,4 +131,138 @@ public function testSetGaugeValue(): void
$this->assertStringContainsString('test_set_gauge', $samples);
$this->assertStringContainsString('5', $samples);
}
/**
* Test that counterInc calls Metrics::counter() and then inc() with the correct labels.
*/
public function testCounterInc()
{
// Set configuration values used by addSystemLabels()
Config::set('app.name', 'TestApp');
Config::set('app.prometheus_custom_label', 'customValue');

// Create an instance of MetricsService.
$service = new MetricsService();

$counterName = 'test_counter';
$helpText = 'A test counter';
$initialLabels = ['user' => '123'];

// Determine what system labels will be added.
// (We call addSystemLabels with an empty array to extract the system values.)
$systemLabels = $service->addSystemLabels([]);
// Merge the initial labels with system labels.
$expectedLabels = array_merge($initialLabels, [
'app_version' => $systemLabels['app_version'],
'app_name' => 'TestApp',
'app_custom_label' => 'customValue',
]);
$expectedLabelKeys = array_keys($expectedLabels);

// Create a mock Counter object that expects inc() to be called once.
$mockCounter = Mockery::mock(Counter::class);
$mockCounter->shouldReceive('inc')
->once()
->with($expectedLabels);

// Expect the Metrics facade to be called with the right parameters
// and to return our mock Counter.
Metrics::shouldReceive('counter')
->once()
->with($counterName, $helpText, $expectedLabelKeys)
->andReturn($mockCounter);

// Call counterInc which should trigger the facade calls.
$service->counterInc($counterName, $helpText, $initialLabels);
}

/**
* Test that histogramObserve calls Metrics::histogram() and then observe() with the correct values.
*/
public function testHistogramObserve()
{
// Set configuration values used by addSystemLabels()
Config::set('app.name', 'TestApp');
Config::set('app.prometheus_custom_label', 'customValue');

$service = new MetricsService();

$histogramName = 'test_histogram';
$helpText = 'A test histogram';
$initialLabels = ['endpoint' => '/api/test'];
$buckets = [0.1, 1, 5, 10];
$executionTime = 2.5;

// Determine what system labels will be added.
$systemLabels = $service->addSystemLabels([]);
$expectedLabels = array_merge($initialLabels, [
'app_version' => $systemLabels['app_version'],
'app_name' => 'TestApp',
'app_custom_label' => 'customValue',
]);
$expectedLabelKeys = array_keys($expectedLabels);

// Create a mock Histogram that expects observe() to be called once.
$mockHistogram = Mockery::mock(Histogram::class);
$mockHistogram->shouldReceive('observe')
->once()
->with($executionTime, $expectedLabels);

// Expect the Metrics facade to be called with the right parameters
// and to return our mock Histogram.
Metrics::shouldReceive('histogram')
->once()
->with($histogramName, $helpText, $expectedLabelKeys, $buckets)
->andReturn($mockHistogram);

// Call histogramObserve which should trigger the facade calls.
$service->histogramObserve($histogramName, $helpText, $initialLabels, $buckets, $executionTime);
}

/**
* Test that addSystemLabels returns the input labels plus the system labels.
*/
public function testAddSystemLabels()
{
// Set configuration values used by addSystemLabels()
Config::set('app.name', 'TestApp');
Config::set('app.prometheus_custom_label', 'customValue');

$service = new MetricsService();

$inputLabels = ['label1' => 'value1'];
$result = $service->addSystemLabels($inputLabels);

// Assert that the original label is preserved.
$this->assertEquals('value1', $result['label1']);

// Assert that the system labels were added.
$this->assertArrayHasKey('app_version', $result);
$this->assertArrayHasKey('app_name', $result);
$this->assertArrayHasKey('app_custom_label', $result);
$this->assertEquals('TestApp', $result['app_name']);
$this->assertEquals('customValue', $result['app_custom_label']);
$this->assertNotEmpty($result['app_version']); // Assuming composer.json defines a version.
}

/**
* Test that clearMetrics calls wipeStorage on the collection registry.
*/
public function testClearMetrics()
{
$service = new MetricsService();

// Create a mock for the CollectorRegistry.
$mockRegistry = Mockery::mock(CollectorRegistry::class);
$mockRegistry->shouldReceive('wipeStorage')
->once();

// Use reflection to override the private property "collectionRegistry" with our mock.
$reflection = new ReflectionClass($service);
$property = $reflection->getProperty('collectionRegistry');
$property->setAccessible(true);
$property->setValue($service, $mockRegistry);

// Call clearMetrics which should call wipeStorage on the registry.
$service->clearMetrics();
}
}
17 changes: 17 additions & 0 deletions upgrades/2025_02_03_191354_clear_prometheus_metrics.php
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
<?php

use ProcessMaker\Facades\Metrics;
use ProcessMaker\Upgrades\UpgradeMigration as Upgrade;

class ClearPrometheusMetrics extends Upgrade
{
/**
* Run the upgrade migration.
*
* @return void
*/
public function up()
{
Metrics::clearMetrics();
}
}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
3 changes: 3 additions & 0 deletions ProcessMaker/Facades/Metrics.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,9 @@
* @method static void setGauge(string $name, float $value, array $labelValues = [])
* @method static string renderMetrics()
* @method static \Prometheus\CollectorRegistry getCollectionRegistry()
* @method static void counterInc(string $name, string $help = null, array $labels = [])
* @method static void histogramObserve(string $name, string $help = null, array $labels = [], array $buckets = [0.1, 1, 5, 10], float $executionTime)
* @method static void clearMetrics()
*/
class Metrics extends Facade
{
Expand Down
9 changes: 1 addition & 8 deletions ProcessMaker/Jobs/CompleteActivity.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,16 +47,9 @@ public function action(ProcessRequestToken $token, ActivityInterface $element, a
$this->engine->runToNextState();
$element->complete($token);

Metrics::counter(
Metrics::counterInc(
'activity_completed_total',
'Total number of activities completed',
[
'activity_id',
'activity_name',
'process_id',
'request_id',
]
)->inc(
[
'activity_id' => $element->getId(),
'activity_name' => $element->getName(),
Expand Down
10 changes: 1 addition & 9 deletions ProcessMaker/Jobs/RunScriptTask.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -113,17 +113,9 @@ public function action(ProcessRequestToken $token = null, ScriptTaskInterface $e

$this->updateData($response);

Metrics::counter(
Metrics::counterInc(
'script_task_completed_total',
'Total number of script tasks completed',
[
'activity_id',
'activity_name',
'process_id',
'request_id',
'script_executor',
]
)->inc(
[
'activity_id' => $element->getId(),
'activity_name' => $element->getName(),
Expand Down
16 changes: 4 additions & 12 deletions ProcessMaker/Listeners/BpmnSubscriber.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -149,26 +149,18 @@ public function onActivityCompleted(ActivityCompletedEvent $event)
$startTime = $token->created_at_ms;
$completedTime = $token->completed_at_ms;
$executionTime = $completedTime->diffInMilliseconds($startTime);
Metrics::histogram(
Metrics::histogramObserve(
'activity_execution_time_seconds',
'Activity Execution Time',
[
'activity_id',
'activity_name',
'element_type',
'process_id',
'request_id',
],
[1, 10, 3600, 86400]
)->observe(
$executionTime,
[
'activity_id' => $token->element_id,
'activity_name' => $token->element_name,
'element_type' => $token->element_type,
'process_id' => $token->process_id,
'request_id' => $token->process_request_id,
]
],
[1, 10, 3600, 86400],
$executionTime,
);

if ($token->element_type == 'task') {
Expand Down
78 changes: 78 additions & 0 deletions ProcessMaker/Services/MetricsService.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,7 @@
namespace ProcessMaker\Services;

use Exception;
use ProcessMaker\Facades\Metrics;
use Prometheus\CollectorRegistry;
use Prometheus\Counter;
use Prometheus\Gauge;
Expand DownExpand Up@@ -146,4 +147,81 @@ public function renderMetrics(): string

return $renderer->render($metrics);
}

/**
* Increments a counter metric by 1.
*
* @param string $name The name of the counter.
* @param string|null $help The help text of the counter.
* @param array $labels The labels of the counter.
*
* @return void
*/
public function counterInc(string $name, string $help = null, array $labels = []): void
{
// Add system labels
$labels = $this->addSystemLabels($labels);
$labelKeys = array_keys($labels);
Metrics::counter($name, $help, $labelKeys)->inc($labels);
}

/**
* Histogram observation.
*
* @param string $name The name of the histogram.
* @param string|null $help The help text of the histogram.
* @param array $labels The labels of the histogram.
* @param array $buckets The buckets of the histogram.
* @param float $executionTime The execution
*
* @return void
*/
public function histogramObserve(string $name, string $help = null, array $labels = [], array $buckets = [0.1, 1, 5, 10], float $executionTime = 0): void
{
// Add system labels
$labels = $this->addSystemLabels($labels);
$labelKeys = array_keys($labels);
Metrics::histogram(
$name,
$help,
$labelKeys,
$buckets
)->observe(
$executionTime,
$labels
);
}

/**
* Add system labels to the provided labels.
*
* @param array $labels The labels to add system labels to.
*
* @return array The keys of the labels.
*/
public function addSystemLabels(array $labels)
{
// Add system labels
$labels['app_version'] = $this->getApplicationVersion();
$labels['app_name'] = config('app.name');
$labels['app_custom_label'] = config('app.prometheus_custom_label');
return $labels;
}

public function clearMetrics(): void
{
$this->collectionRegistry->wipeStorage();
}

/**
* Gets the version of the application.
*
* @return string The version of the application.
*/
private function getApplicationVersion()
{
$root = base_path('composer.json');
$composer_json_path = json_decode(file_get_contents($root));
return $composer_json_path->version ?? '4.0.0';
}
}
1 change: 1 addition & 0 deletions tests/Feature/Metrics/TaskMetricsTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,6 +47,7 @@ private function assertMetricWasStored(string $name, array $labels)
$metric = $adapter->getCounter($ns, $name);

$this->assertInstanceOf(Counter::class, $metric);
$labels = Metrics::addSystemLabels($labels);
$this->assertEquals($metric->getLabelNames(), array_keys($labels));
}
}
142 changes: 142 additions & 0 deletions tests/unit/MetricsServiceTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,10 +3,18 @@
namespace Tests\Unit;

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Mockery;
use ProcessMaker\Facades\Metrics;
use ProcessMaker\Services\MetricsService;
use Prometheus\CollectorRegistry;
use Prometheus\Counter;
use Prometheus\Histogram;
use Prometheus\Storage\InMemory;
use ReflectionClass;
use Tests\TestCase;


class MetricsServiceTest extends TestCase
{
/**
Expand DownExpand Up@@ -123,4 +131,138 @@ public function testSetGaugeValue(): void
$this->assertStringContainsString('test_set_gauge', $samples);
$this->assertStringContainsString('5', $samples);
}
/**
* Test that counterInc calls Metrics::counter() and then inc() with the correct labels.
*/
public function testCounterInc()
{
// Set configuration values used by addSystemLabels()
Config::set('app.name', 'TestApp');
Config::set('app.prometheus_custom_label', 'customValue');

// Create an instance of MetricsService.
$service = new MetricsService();

$counterName = 'test_counter';
$helpText = 'A test counter';
$initialLabels = ['user' => '123'];

// Determine what system labels will be added.
// (We call addSystemLabels with an empty array to extract the system values.)
$systemLabels = $service->addSystemLabels([]);
// Merge the initial labels with system labels.
$expectedLabels = array_merge($initialLabels, [
'app_version' => $systemLabels['app_version'],
'app_name' => 'TestApp',
'app_custom_label' => 'customValue',
]);
$expectedLabelKeys = array_keys($expectedLabels);

// Create a mock Counter object that expects inc() to be called once.
$mockCounter = Mockery::mock(Counter::class);
$mockCounter->shouldReceive('inc')
->once()
->with($expectedLabels);

// Expect the Metrics facade to be called with the right parameters
// and to return our mock Counter.
Metrics::shouldReceive('counter')
->once()
->with($counterName, $helpText, $expectedLabelKeys)
->andReturn($mockCounter);

// Call counterInc which should trigger the facade calls.
$service->counterInc($counterName, $helpText, $initialLabels);
}

/**
* Test that histogramObserve calls Metrics::histogram() and then observe() with the correct values.
*/
public function testHistogramObserve()
{
// Set configuration values used by addSystemLabels()
Config::set('app.name', 'TestApp');
Config::set('app.prometheus_custom_label', 'customValue');

$service = new MetricsService();

$histogramName = 'test_histogram';
$helpText = 'A test histogram';
$initialLabels = ['endpoint' => '/api/test'];
$buckets = [0.1, 1, 5, 10];
$executionTime = 2.5;

// Determine what system labels will be added.
$systemLabels = $service->addSystemLabels([]);
$expectedLabels = array_merge($initialLabels, [
'app_version' => $systemLabels['app_version'],
'app_name' => 'TestApp',
'app_custom_label' => 'customValue',
]);
$expectedLabelKeys = array_keys($expectedLabels);

// Create a mock Histogram that expects observe() to be called once.
$mockHistogram = Mockery::mock(Histogram::class);
$mockHistogram->shouldReceive('observe')
->once()
->with($executionTime, $expectedLabels);

// Expect the Metrics facade to be called with the right parameters
// and to return our mock Histogram.
Metrics::shouldReceive('histogram')
->once()
->with($histogramName, $helpText, $expectedLabelKeys, $buckets)
->andReturn($mockHistogram);

// Call histogramObserve which should trigger the facade calls.
$service->histogramObserve($histogramName, $helpText, $initialLabels, $buckets, $executionTime);
}

/**
* Test that addSystemLabels returns the input labels plus the system labels.
*/
public function testAddSystemLabels()
{
// Set configuration values used by addSystemLabels()
Config::set('app.name', 'TestApp');
Config::set('app.prometheus_custom_label', 'customValue');

$service = new MetricsService();

$inputLabels = ['label1' => 'value1'];
$result = $service->addSystemLabels($inputLabels);

// Assert that the original label is preserved.
$this->assertEquals('value1', $result['label1']);

// Assert that the system labels were added.
$this->assertArrayHasKey('app_version', $result);
$this->assertArrayHasKey('app_name', $result);
$this->assertArrayHasKey('app_custom_label', $result);
$this->assertEquals('TestApp', $result['app_name']);
$this->assertEquals('customValue', $result['app_custom_label']);
$this->assertNotEmpty($result['app_version']); // Assuming composer.json defines a version.
}

/**
* Test that clearMetrics calls wipeStorage on the collection registry.
*/
public function testClearMetrics()
{
$service = new MetricsService();

// Create a mock for the CollectorRegistry.
$mockRegistry = Mockery::mock(CollectorRegistry::class);
$mockRegistry->shouldReceive('wipeStorage')
->once();

// Use reflection to override the private property "collectionRegistry" with our mock.
$reflection = new ReflectionClass($service);
$property = $reflection->getProperty('collectionRegistry');
$property->setAccessible(true);
$property->setValue($service, $mockRegistry);

// Call clearMetrics which should call wipeStorage on the registry.
$service->clearMetrics();
}
}
17 changes: 17 additions & 0 deletions upgrades/2025_02_03_191354_clear_prometheus_metrics.php
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
<?php

use ProcessMaker\Facades\Metrics;
use ProcessMaker\Upgrades\UpgradeMigration as Upgrade;

class ClearPrometheusMetrics extends Upgrade
{
/**
* Run the upgrade migration.
*
* @return void
*/
public function up()
{
Metrics::clearMetrics();
}
}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
3 changes: 3 additions & 0 deletions ProcessMaker/Facades/Metrics.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,9 @@
* @method static void setGauge(string $name, float $value, array $labelValues = [])
* @method static string renderMetrics()
* @method static \Prometheus\CollectorRegistry getCollectionRegistry()
* @method static void counterInc(string $name, string $help = null, array $labels = [])
* @method static void histogramObserve(string $name, string $help = null, array $labels = [], array $buckets = [0.1, 1, 5, 10], float $executionTime)
* @method static void clearMetrics()
*/
class Metrics extends Facade
{
Expand Down
9 changes: 1 addition & 8 deletions ProcessMaker/Jobs/CompleteActivity.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,16 +47,9 @@ public function action(ProcessRequestToken $token, ActivityInterface $element, a
$this->engine->runToNextState();
$element->complete($token);

Metrics::counter(
Metrics::counterInc(
'activity_completed_total',
'Total number of activities completed',
[
'activity_id',
'activity_name',
'process_id',
'request_id',
]
)->inc(
[
'activity_id' => $element->getId(),
'activity_name' => $element->getName(),
Expand Down
10 changes: 1 addition & 9 deletions ProcessMaker/Jobs/RunScriptTask.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -113,17 +113,9 @@ public function action(ProcessRequestToken $token = null, ScriptTaskInterface $e

$this->updateData($response);

Metrics::counter(
Metrics::counterInc(
'script_task_completed_total',
'Total number of script tasks completed',
[
'activity_id',
'activity_name',
'process_id',
'request_id',
'script_executor',
]
)->inc(
[
'activity_id' => $element->getId(),
'activity_name' => $element->getName(),
Expand Down
16 changes: 4 additions & 12 deletions ProcessMaker/Listeners/BpmnSubscriber.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -149,26 +149,18 @@ public function onActivityCompleted(ActivityCompletedEvent $event)
$startTime = $token->created_at_ms;
$completedTime = $token->completed_at_ms;
$executionTime = $completedTime->diffInMilliseconds($startTime);
Metrics::histogram(
Metrics::histogramObserve(
'activity_execution_time_seconds',
'Activity Execution Time',
[
'activity_id',
'activity_name',
'element_type',
'process_id',
'request_id',
],
[1, 10, 3600, 86400]
)->observe(
$executionTime,
[
'activity_id' => $token->element_id,
'activity_name' => $token->element_name,
'element_type' => $token->element_type,
'process_id' => $token->process_id,
'request_id' => $token->process_request_id,
]
],
[1, 10, 3600, 86400],
$executionTime,
);

if ($token->element_type == 'task') {
Expand Down
78 changes: 78 additions & 0 deletions ProcessMaker/Services/MetricsService.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,7 @@
namespace ProcessMaker\Services;

use Exception;
use ProcessMaker\Facades\Metrics;
use Prometheus\CollectorRegistry;
use Prometheus\Counter;
use Prometheus\Gauge;
Expand DownExpand Up@@ -146,4 +147,81 @@ public function renderMetrics(): string

return $renderer->render($metrics);
}

/**
* Increments a counter metric by 1.
*
* @param string $name The name of the counter.
* @param string|null $help The help text of the counter.
* @param array $labels The labels of the counter.
*
* @return void
*/
public function counterInc(string $name, string $help = null, array $labels = []): void
{
// Add system labels
$labels = $this->addSystemLabels($labels);
$labelKeys = array_keys($labels);
Metrics::counter($name, $help, $labelKeys)->inc($labels);
}

/**
* Histogram observation.
*
* @param string $name The name of the histogram.
* @param string|null $help The help text of the histogram.
* @param array $labels The labels of the histogram.
* @param array $buckets The buckets of the histogram.
* @param float $executionTime The execution
*
* @return void
*/
public function histogramObserve(string $name, string $help = null, array $labels = [], array $buckets = [0.1, 1, 5, 10], float $executionTime = 0): void
{
// Add system labels
$labels = $this->addSystemLabels($labels);
$labelKeys = array_keys($labels);
Metrics::histogram(
$name,
$help,
$labelKeys,
$buckets
)->observe(
$executionTime,
$labels
);
}

/**
* Add system labels to the provided labels.
*
* @param array $labels The labels to add system labels to.
*
* @return array The keys of the labels.
*/
public function addSystemLabels(array $labels)
{
// Add system labels
$labels['app_version'] = $this->getApplicationVersion();
$labels['app_name'] = config('app.name');
$labels['app_custom_label'] = config('app.prometheus_custom_label');
return $labels;
}

public function clearMetrics(): void
{
$this->collectionRegistry->wipeStorage();
}

/**
* Gets the version of the application.
*
* @return string The version of the application.
*/
private function getApplicationVersion()
{
$root = base_path('composer.json');
$composer_json_path = json_decode(file_get_contents($root));
return $composer_json_path->version ?? '4.0.0';
}
}
1 change: 1 addition & 0 deletions tests/Feature/Metrics/TaskMetricsTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,6 +47,7 @@ private function assertMetricWasStored(string $name, array $labels)
$metric = $adapter->getCounter($ns, $name);

$this->assertInstanceOf(Counter::class, $metric);
$labels = Metrics::addSystemLabels($labels);
$this->assertEquals($metric->getLabelNames(), array_keys($labels));
}
}
142 changes: 142 additions & 0 deletions tests/unit/MetricsServiceTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,10 +3,18 @@
namespace Tests\Unit;

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Mockery;
use ProcessMaker\Facades\Metrics;
use ProcessMaker\Services\MetricsService;
use Prometheus\CollectorRegistry;
use Prometheus\Counter;
use Prometheus\Histogram;
use Prometheus\Storage\InMemory;
use ReflectionClass;
use Tests\TestCase;


class MetricsServiceTest extends TestCase
{
/**
Expand DownExpand Up@@ -123,4 +131,138 @@ public function testSetGaugeValue(): void
$this->assertStringContainsString('test_set_gauge', $samples);
$this->assertStringContainsString('5', $samples);
}
/**
* Test that counterInc calls Metrics::counter() and then inc() with the correct labels.
*/
public function testCounterInc()
{
// Set configuration values used by addSystemLabels()
Config::set('app.name', 'TestApp');
Config::set('app.prometheus_custom_label', 'customValue');

// Create an instance of MetricsService.
$service = new MetricsService();

$counterName = 'test_counter';
$helpText = 'A test counter';
$initialLabels = ['user' => '123'];

// Determine what system labels will be added.
// (We call addSystemLabels with an empty array to extract the system values.)
$systemLabels = $service->addSystemLabels([]);
// Merge the initial labels with system labels.
$expectedLabels = array_merge($initialLabels, [
'app_version' => $systemLabels['app_version'],
'app_name' => 'TestApp',
'app_custom_label' => 'customValue',
]);
$expectedLabelKeys = array_keys($expectedLabels);

// Create a mock Counter object that expects inc() to be called once.
$mockCounter = Mockery::mock(Counter::class);
$mockCounter->shouldReceive('inc')
->once()
->with($expectedLabels);

// Expect the Metrics facade to be called with the right parameters
// and to return our mock Counter.
Metrics::shouldReceive('counter')
->once()
->with($counterName, $helpText, $expectedLabelKeys)
->andReturn($mockCounter);

// Call counterInc which should trigger the facade calls.
$service->counterInc($counterName, $helpText, $initialLabels);
}

/**
* Test that histogramObserve calls Metrics::histogram() and then observe() with the correct values.
*/
public function testHistogramObserve()
{
// Set configuration values used by addSystemLabels()
Config::set('app.name', 'TestApp');
Config::set('app.prometheus_custom_label', 'customValue');

$service = new MetricsService();

$histogramName = 'test_histogram';
$helpText = 'A test histogram';
$initialLabels = ['endpoint' => '/api/test'];
$buckets = [0.1, 1, 5, 10];
$executionTime = 2.5;

// Determine what system labels will be added.
$systemLabels = $service->addSystemLabels([]);
$expectedLabels = array_merge($initialLabels, [
'app_version' => $systemLabels['app_version'],
'app_name' => 'TestApp',
'app_custom_label' => 'customValue',
]);
$expectedLabelKeys = array_keys($expectedLabels);

// Create a mock Histogram that expects observe() to be called once.
$mockHistogram = Mockery::mock(Histogram::class);
$mockHistogram->shouldReceive('observe')
->once()
->with($executionTime, $expectedLabels);

// Expect the Metrics facade to be called with the right parameters
// and to return our mock Histogram.
Metrics::shouldReceive('histogram')
->once()
->with($histogramName, $helpText, $expectedLabelKeys, $buckets)
->andReturn($mockHistogram);

// Call histogramObserve which should trigger the facade calls.
$service->histogramObserve($histogramName, $helpText, $initialLabels, $buckets, $executionTime);
}

/**
* Test that addSystemLabels returns the input labels plus the system labels.
*/
public function testAddSystemLabels()
{
// Set configuration values used by addSystemLabels()
Config::set('app.name', 'TestApp');
Config::set('app.prometheus_custom_label', 'customValue');

$service = new MetricsService();

$inputLabels = ['label1' => 'value1'];
$result = $service->addSystemLabels($inputLabels);

// Assert that the original label is preserved.
$this->assertEquals('value1', $result['label1']);

// Assert that the system labels were added.
$this->assertArrayHasKey('app_version', $result);
$this->assertArrayHasKey('app_name', $result);
$this->assertArrayHasKey('app_custom_label', $result);
$this->assertEquals('TestApp', $result['app_name']);
$this->assertEquals('customValue', $result['app_custom_label']);
$this->assertNotEmpty($result['app_version']); // Assuming composer.json defines a version.
}

/**
* Test that clearMetrics calls wipeStorage on the collection registry.
*/
public function testClearMetrics()
{
$service = new MetricsService();

// Create a mock for the CollectorRegistry.
$mockRegistry = Mockery::mock(CollectorRegistry::class);
$mockRegistry->shouldReceive('wipeStorage')
->once();

// Use reflection to override the private property "collectionRegistry" with our mock.
$reflection = new ReflectionClass($service);
$property = $reflection->getProperty('collectionRegistry');
$property->setAccessible(true);
$property->setValue($service, $mockRegistry);

// Call clearMetrics which should call wipeStorage on the registry.
$service->clearMetrics();
}
}
17 changes: 17 additions & 0 deletions upgrades/2025_02_03_191354_clear_prometheus_metrics.php
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
<?php

use ProcessMaker\Facades\Metrics;
use ProcessMaker\Upgrades\UpgradeMigration as Upgrade;

class ClearPrometheusMetrics extends Upgrade
{
/**
* Run the upgrade migration.
*
* @return void
*/
public function up()
{
Metrics::clearMetrics();
}
}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
3 changes: 3 additions & 0 deletions ProcessMaker/Facades/Metrics.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,9 @@
* @method static void setGauge(string $name, float $value, array $labelValues = [])
* @method static string renderMetrics()
* @method static \Prometheus\CollectorRegistry getCollectionRegistry()
* @method static void counterInc(string $name, string $help = null, array $labels = [])
* @method static void histogramObserve(string $name, string $help = null, array $labels = [], array $buckets = [0.1, 1, 5, 10], float $executionTime)
* @method static void clearMetrics()
*/
class Metrics extends Facade
{
Expand Down
9 changes: 1 addition & 8 deletions ProcessMaker/Jobs/CompleteActivity.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,16 +47,9 @@ public function action(ProcessRequestToken $token, ActivityInterface $element, a
$this->engine->runToNextState();
$element->complete($token);

Metrics::counter(
Metrics::counterInc(
'activity_completed_total',
'Total number of activities completed',
[
'activity_id',
'activity_name',
'process_id',
'request_id',
]
)->inc(
[
'activity_id' => $element->getId(),
'activity_name' => $element->getName(),
Expand Down
10 changes: 1 addition & 9 deletions ProcessMaker/Jobs/RunScriptTask.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -113,17 +113,9 @@ public function action(ProcessRequestToken $token = null, ScriptTaskInterface $e

$this->updateData($response);

Metrics::counter(
Metrics::counterInc(
'script_task_completed_total',
'Total number of script tasks completed',
[
'activity_id',
'activity_name',
'process_id',
'request_id',
'script_executor',
]
)->inc(
[
'activity_id' => $element->getId(),
'activity_name' => $element->getName(),
Expand Down
16 changes: 4 additions & 12 deletions ProcessMaker/Listeners/BpmnSubscriber.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -149,26 +149,18 @@ public function onActivityCompleted(ActivityCompletedEvent $event)
$startTime = $token->created_at_ms;
$completedTime = $token->completed_at_ms;
$executionTime = $completedTime->diffInMilliseconds($startTime);
Metrics::histogram(
Metrics::histogramObserve(
'activity_execution_time_seconds',
'Activity Execution Time',
[
'activity_id',
'activity_name',
'element_type',
'process_id',
'request_id',
],
[1, 10, 3600, 86400]
)->observe(
$executionTime,
[
'activity_id' => $token->element_id,
'activity_name' => $token->element_name,
'element_type' => $token->element_type,
'process_id' => $token->process_id,
'request_id' => $token->process_request_id,
]
],
[1, 10, 3600, 86400],
$executionTime,
);

if ($token->element_type == 'task') {
Expand Down
78 changes: 78 additions & 0 deletions ProcessMaker/Services/MetricsService.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,7 @@
namespace ProcessMaker\Services;

use Exception;
use ProcessMaker\Facades\Metrics;
use Prometheus\CollectorRegistry;
use Prometheus\Counter;
use Prometheus\Gauge;
Expand DownExpand Up@@ -146,4 +147,81 @@ public function renderMetrics(): string

return $renderer->render($metrics);
}

/**
* Increments a counter metric by 1.
*
* @param string $name The name of the counter.
* @param string|null $help The help text of the counter.
* @param array $labels The labels of the counter.
*
* @return void
*/
public function counterInc(string $name, string $help = null, array $labels = []): void
{
// Add system labels
$labels = $this->addSystemLabels($labels);
$labelKeys = array_keys($labels);
Metrics::counter($name, $help, $labelKeys)->inc($labels);
}

/**
* Histogram observation.
*
* @param string $name The name of the histogram.
* @param string|null $help The help text of the histogram.
* @param array $labels The labels of the histogram.
* @param array $buckets The buckets of the histogram.
* @param float $executionTime The execution
*
* @return void
*/
public function histogramObserve(string $name, string $help = null, array $labels = [], array $buckets = [0.1, 1, 5, 10], float $executionTime = 0): void
{
// Add system labels
$labels = $this->addSystemLabels($labels);
$labelKeys = array_keys($labels);
Metrics::histogram(
$name,
$help,
$labelKeys,
$buckets
)->observe(
$executionTime,
$labels
);
}

/**
* Add system labels to the provided labels.
*
* @param array $labels The labels to add system labels to.
*
* @return array The keys of the labels.
*/
public function addSystemLabels(array $labels)
{
// Add system labels
$labels['app_version'] = $this->getApplicationVersion();
$labels['app_name'] = config('app.name');
$labels['app_custom_label'] = config('app.prometheus_custom_label');
return $labels;
}

public function clearMetrics(): void
{
$this->collectionRegistry->wipeStorage();
}

/**
* Gets the version of the application.
*
* @return string The version of the application.
*/
private function getApplicationVersion()
{
$root = base_path('composer.json');
$composer_json_path = json_decode(file_get_contents($root));
return $composer_json_path->version ?? '4.0.0';
}
}
1 change: 1 addition & 0 deletions tests/Feature/Metrics/TaskMetricsTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,6 +47,7 @@ private function assertMetricWasStored(string $name, array $labels)
$metric = $adapter->getCounter($ns, $name);

$this->assertInstanceOf(Counter::class, $metric);
$labels = Metrics::addSystemLabels($labels);
$this->assertEquals($metric->getLabelNames(), array_keys($labels));
}
}
142 changes: 142 additions & 0 deletions tests/unit/MetricsServiceTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,10 +3,18 @@
namespace Tests\Unit;

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Mockery;
use ProcessMaker\Facades\Metrics;
use ProcessMaker\Services\MetricsService;
use Prometheus\CollectorRegistry;
use Prometheus\Counter;
use Prometheus\Histogram;
use Prometheus\Storage\InMemory;
use ReflectionClass;
use Tests\TestCase;


class MetricsServiceTest extends TestCase
{
/**
Expand DownExpand Up@@ -123,4 +131,138 @@ public function testSetGaugeValue(): void
$this->assertStringContainsString('test_set_gauge', $samples);
$this->assertStringContainsString('5', $samples);
}
/**
* Test that counterInc calls Metrics::counter() and then inc() with the correct labels.
*/
public function testCounterInc()
{
// Set configuration values used by addSystemLabels()
Config::set('app.name', 'TestApp');
Config::set('app.prometheus_custom_label', 'customValue');

// Create an instance of MetricsService.
$service = new MetricsService();

$counterName = 'test_counter';
$helpText = 'A test counter';
$initialLabels = ['user' => '123'];

// Determine what system labels will be added.
// (We call addSystemLabels with an empty array to extract the system values.)
$systemLabels = $service->addSystemLabels([]);
// Merge the initial labels with system labels.
$expectedLabels = array_merge($initialLabels, [
'app_version' => $systemLabels['app_version'],
'app_name' => 'TestApp',
'app_custom_label' => 'customValue',
]);
$expectedLabelKeys = array_keys($expectedLabels);

// Create a mock Counter object that expects inc() to be called once.
$mockCounter = Mockery::mock(Counter::class);
$mockCounter->shouldReceive('inc')
->once()
->with($expectedLabels);

// Expect the Metrics facade to be called with the right parameters
// and to return our mock Counter.
Metrics::shouldReceive('counter')
->once()
->with($counterName, $helpText, $expectedLabelKeys)
->andReturn($mockCounter);

// Call counterInc which should trigger the facade calls.
$service->counterInc($counterName, $helpText, $initialLabels);
}

/**
* Test that histogramObserve calls Metrics::histogram() and then observe() with the correct values.
*/
public function testHistogramObserve()
{
// Set configuration values used by addSystemLabels()
Config::set('app.name', 'TestApp');
Config::set('app.prometheus_custom_label', 'customValue');

$service = new MetricsService();

$histogramName = 'test_histogram';
$helpText = 'A test histogram';
$initialLabels = ['endpoint' => '/api/test'];
$buckets = [0.1, 1, 5, 10];
$executionTime = 2.5;

// Determine what system labels will be added.
$systemLabels = $service->addSystemLabels([]);
$expectedLabels = array_merge($initialLabels, [
'app_version' => $systemLabels['app_version'],
'app_name' => 'TestApp',
'app_custom_label' => 'customValue',
]);
$expectedLabelKeys = array_keys($expectedLabels);

// Create a mock Histogram that expects observe() to be called once.
$mockHistogram = Mockery::mock(Histogram::class);
$mockHistogram->shouldReceive('observe')
->once()
->with($executionTime, $expectedLabels);

// Expect the Metrics facade to be called with the right parameters
// and to return our mock Histogram.
Metrics::shouldReceive('histogram')
->once()
->with($histogramName, $helpText, $expectedLabelKeys, $buckets)
->andReturn($mockHistogram);

// Call histogramObserve which should trigger the facade calls.
$service->histogramObserve($histogramName, $helpText, $initialLabels, $buckets, $executionTime);
}

/**
* Test that addSystemLabels returns the input labels plus the system labels.
*/
public function testAddSystemLabels()
{
// Set configuration values used by addSystemLabels()
Config::set('app.name', 'TestApp');
Config::set('app.prometheus_custom_label', 'customValue');

$service = new MetricsService();

$inputLabels = ['label1' => 'value1'];
$result = $service->addSystemLabels($inputLabels);

// Assert that the original label is preserved.
$this->assertEquals('value1', $result['label1']);

// Assert that the system labels were added.
$this->assertArrayHasKey('app_version', $result);
$this->assertArrayHasKey('app_name', $result);
$this->assertArrayHasKey('app_custom_label', $result);
$this->assertEquals('TestApp', $result['app_name']);
$this->assertEquals('customValue', $result['app_custom_label']);
$this->assertNotEmpty($result['app_version']); // Assuming composer.json defines a version.
}

/**
* Test that clearMetrics calls wipeStorage on the collection registry.
*/
public function testClearMetrics()
{
$service = new MetricsService();

// Create a mock for the CollectorRegistry.
$mockRegistry = Mockery::mock(CollectorRegistry::class);
$mockRegistry->shouldReceive('wipeStorage')
->once();

// Use reflection to override the private property "collectionRegistry" with our mock.
$reflection = new ReflectionClass($service);
$property = $reflection->getProperty('collectionRegistry');
$property->setAccessible(true);
$property->setValue($service, $mockRegistry);

// Call clearMetrics which should call wipeStorage on the registry.
$service->clearMetrics();
}
}
17 changes: 17 additions & 0 deletions upgrades/2025_02_03_191354_clear_prometheus_metrics.php
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
<?php

use ProcessMaker\Facades\Metrics;
use ProcessMaker\Upgrades\UpgradeMigration as Upgrade;

class ClearPrometheusMetrics extends Upgrade
{
/**
* Run the upgrade migration.
*
* @return void
*/
public function up()
{
Metrics::clearMetrics();
}
}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
3 changes: 3 additions & 0 deletions ProcessMaker/Facades/Metrics.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,9 @@
* @method static void setGauge(string $name, float $value, array $labelValues = [])
* @method static string renderMetrics()
* @method static \Prometheus\CollectorRegistry getCollectionRegistry()
* @method static void counterInc(string $name, string $help = null, array $labels = [])
* @method static void histogramObserve(string $name, string $help = null, array $labels = [], array $buckets = [0.1, 1, 5, 10], float $executionTime)
* @method static void clearMetrics()
*/
class Metrics extends Facade
{
Expand Down
9 changes: 1 addition & 8 deletions ProcessMaker/Jobs/CompleteActivity.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,16 +47,9 @@ public function action(ProcessRequestToken $token, ActivityInterface $element, a
$this->engine->runToNextState();
$element->complete($token);

Metrics::counter(
Metrics::counterInc(
'activity_completed_total',
'Total number of activities completed',
[
'activity_id',
'activity_name',
'process_id',
'request_id',
]
)->inc(
[
'activity_id' => $element->getId(),
'activity_name' => $element->getName(),
Expand Down
10 changes: 1 addition & 9 deletions ProcessMaker/Jobs/RunScriptTask.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -113,17 +113,9 @@ public function action(ProcessRequestToken $token = null, ScriptTaskInterface $e

$this->updateData($response);

Metrics::counter(
Metrics::counterInc(
'script_task_completed_total',
'Total number of script tasks completed',
[
'activity_id',
'activity_name',
'process_id',
'request_id',
'script_executor',
]
)->inc(
[
'activity_id' => $element->getId(),
'activity_name' => $element->getName(),
Expand Down
16 changes: 4 additions & 12 deletions ProcessMaker/Listeners/BpmnSubscriber.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -149,26 +149,18 @@ public function onActivityCompleted(ActivityCompletedEvent $event)
$startTime = $token->created_at_ms;
$completedTime = $token->completed_at_ms;
$executionTime = $completedTime->diffInMilliseconds($startTime);
Metrics::histogram(
Metrics::histogramObserve(
'activity_execution_time_seconds',
'Activity Execution Time',
[
'activity_id',
'activity_name',
'element_type',
'process_id',
'request_id',
],
[1, 10, 3600, 86400]
)->observe(
$executionTime,
[
'activity_id' => $token->element_id,
'activity_name' => $token->element_name,
'element_type' => $token->element_type,
'process_id' => $token->process_id,
'request_id' => $token->process_request_id,
]
],
[1, 10, 3600, 86400],
$executionTime,
);

if ($token->element_type == 'task') {
Expand Down
78 changes: 78 additions & 0 deletions ProcessMaker/Services/MetricsService.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,7 @@
namespace ProcessMaker\Services;

use Exception;
use ProcessMaker\Facades\Metrics;
use Prometheus\CollectorRegistry;
use Prometheus\Counter;
use Prometheus\Gauge;
Expand DownExpand Up@@ -146,4 +147,81 @@ public function renderMetrics(): string

return $renderer->render($metrics);
}

/**
* Increments a counter metric by 1.
*
* @param string $name The name of the counter.
* @param string|null $help The help text of the counter.
* @param array $labels The labels of the counter.
*
* @return void
*/
public function counterInc(string $name, string $help = null, array $labels = []): void
{
// Add system labels
$labels = $this->addSystemLabels($labels);
$labelKeys = array_keys($labels);
Metrics::counter($name, $help, $labelKeys)->inc($labels);
}

/**
* Histogram observation.
*
* @param string $name The name of the histogram.
* @param string|null $help The help text of the histogram.
* @param array $labels The labels of the histogram.
* @param array $buckets The buckets of the histogram.
* @param float $executionTime The execution
*
* @return void
*/
public function histogramObserve(string $name, string $help = null, array $labels = [], array $buckets = [0.1, 1, 5, 10], float $executionTime = 0): void
{
// Add system labels
$labels = $this->addSystemLabels($labels);
$labelKeys = array_keys($labels);
Metrics::histogram(
$name,
$help,
$labelKeys,
$buckets
)->observe(
$executionTime,
$labels
);
}

/**
* Add system labels to the provided labels.
*
* @param array $labels The labels to add system labels to.
*
* @return array The keys of the labels.
*/
public function addSystemLabels(array $labels)
{
// Add system labels
$labels['app_version'] = $this->getApplicationVersion();
$labels['app_name'] = config('app.name');
$labels['app_custom_label'] = config('app.prometheus_custom_label');
return $labels;
}

public function clearMetrics(): void
{
$this->collectionRegistry->wipeStorage();
}

/**
* Gets the version of the application.
*
* @return string The version of the application.
*/
private function getApplicationVersion()
{
$root = base_path('composer.json');
$composer_json_path = json_decode(file_get_contents($root));
return $composer_json_path->version ?? '4.0.0';
}
}
1 change: 1 addition & 0 deletions tests/Feature/Metrics/TaskMetricsTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,6 +47,7 @@ private function assertMetricWasStored(string $name, array $labels)
$metric = $adapter->getCounter($ns, $name);

$this->assertInstanceOf(Counter::class, $metric);
$labels = Metrics::addSystemLabels($labels);
$this->assertEquals($metric->getLabelNames(), array_keys($labels));
}
}
142 changes: 142 additions & 0 deletions tests/unit/MetricsServiceTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,10 +3,18 @@
namespace Tests\Unit;

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Mockery;
use ProcessMaker\Facades\Metrics;
use ProcessMaker\Services\MetricsService;
use Prometheus\CollectorRegistry;
use Prometheus\Counter;
use Prometheus\Histogram;
use Prometheus\Storage\InMemory;
use ReflectionClass;
use Tests\TestCase;


class MetricsServiceTest extends TestCase
{
/**
Expand DownExpand Up@@ -123,4 +131,138 @@ public function testSetGaugeValue(): void
$this->assertStringContainsString('test_set_gauge', $samples);
$this->assertStringContainsString('5', $samples);
}
/**
* Test that counterInc calls Metrics::counter() and then inc() with the correct labels.
*/
public function testCounterInc()
{
// Set configuration values used by addSystemLabels()
Config::set('app.name', 'TestApp');
Config::set('app.prometheus_custom_label', 'customValue');

// Create an instance of MetricsService.
$service = new MetricsService();

$counterName = 'test_counter';
$helpText = 'A test counter';
$initialLabels = ['user' => '123'];

// Determine what system labels will be added.
// (We call addSystemLabels with an empty array to extract the system values.)
$systemLabels = $service->addSystemLabels([]);
// Merge the initial labels with system labels.
$expectedLabels = array_merge($initialLabels, [
'app_version' => $systemLabels['app_version'],
'app_name' => 'TestApp',
'app_custom_label' => 'customValue',
]);
$expectedLabelKeys = array_keys($expectedLabels);

// Create a mock Counter object that expects inc() to be called once.
$mockCounter = Mockery::mock(Counter::class);
$mockCounter->shouldReceive('inc')
->once()
->with($expectedLabels);

// Expect the Metrics facade to be called with the right parameters
// and to return our mock Counter.
Metrics::shouldReceive('counter')
->once()
->with($counterName, $helpText, $expectedLabelKeys)
->andReturn($mockCounter);

// Call counterInc which should trigger the facade calls.
$service->counterInc($counterName, $helpText, $initialLabels);
}

/**
* Test that histogramObserve calls Metrics::histogram() and then observe() with the correct values.
*/
public function testHistogramObserve()
{
// Set configuration values used by addSystemLabels()
Config::set('app.name', 'TestApp');
Config::set('app.prometheus_custom_label', 'customValue');

$service = new MetricsService();

$histogramName = 'test_histogram';
$helpText = 'A test histogram';
$initialLabels = ['endpoint' => '/api/test'];
$buckets = [0.1, 1, 5, 10];
$executionTime = 2.5;

// Determine what system labels will be added.
$systemLabels = $service->addSystemLabels([]);
$expectedLabels = array_merge($initialLabels, [
'app_version' => $systemLabels['app_version'],
'app_name' => 'TestApp',
'app_custom_label' => 'customValue',
]);
$expectedLabelKeys = array_keys($expectedLabels);

// Create a mock Histogram that expects observe() to be called once.
$mockHistogram = Mockery::mock(Histogram::class);
$mockHistogram->shouldReceive('observe')
->once()
->with($executionTime, $expectedLabels);

// Expect the Metrics facade to be called with the right parameters
// and to return our mock Histogram.
Metrics::shouldReceive('histogram')
->once()
->with($histogramName, $helpText, $expectedLabelKeys, $buckets)
->andReturn($mockHistogram);

// Call histogramObserve which should trigger the facade calls.
$service->histogramObserve($histogramName, $helpText, $initialLabels, $buckets, $executionTime);
}

/**
* Test that addSystemLabels returns the input labels plus the system labels.
*/
public function testAddSystemLabels()
{
// Set configuration values used by addSystemLabels()
Config::set('app.name', 'TestApp');
Config::set('app.prometheus_custom_label', 'customValue');

$service = new MetricsService();

$inputLabels = ['label1' => 'value1'];
$result = $service->addSystemLabels($inputLabels);

// Assert that the original label is preserved.
$this->assertEquals('value1', $result['label1']);

// Assert that the system labels were added.
$this->assertArrayHasKey('app_version', $result);
$this->assertArrayHasKey('app_name', $result);
$this->assertArrayHasKey('app_custom_label', $result);
$this->assertEquals('TestApp', $result['app_name']);
$this->assertEquals('customValue', $result['app_custom_label']);
$this->assertNotEmpty($result['app_version']); // Assuming composer.json defines a version.
}

/**
* Test that clearMetrics calls wipeStorage on the collection registry.
*/
public function testClearMetrics()
{
$service = new MetricsService();

// Create a mock for the CollectorRegistry.
$mockRegistry = Mockery::mock(CollectorRegistry::class);
$mockRegistry->shouldReceive('wipeStorage')
->once();

// Use reflection to override the private property "collectionRegistry" with our mock.
$reflection = new ReflectionClass($service);
$property = $reflection->getProperty('collectionRegistry');
$property->setAccessible(true);
$property->setValue($service, $mockRegistry);

// Call clearMetrics which should call wipeStorage on the registry.
$service->clearMetrics();
}
}
17 changes: 17 additions & 0 deletions upgrades/2025_02_03_191354_clear_prometheus_metrics.php
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
<?php

use ProcessMaker\Facades\Metrics;
use ProcessMaker\Upgrades\UpgradeMigration as Upgrade;

class ClearPrometheusMetrics extends Upgrade
{
/**
* Run the upgrade migration.
*
* @return void
*/
public function up()
{
Metrics::clearMetrics();
}
}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
3 changes: 3 additions & 0 deletions ProcessMaker/Facades/Metrics.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,9 @@
* @method static void setGauge(string $name, float $value, array $labelValues = [])
* @method static string renderMetrics()
* @method static \Prometheus\CollectorRegistry getCollectionRegistry()
* @method static void counterInc(string $name, string $help = null, array $labels = [])
* @method static void histogramObserve(string $name, string $help = null, array $labels = [], array $buckets = [0.1, 1, 5, 10], float $executionTime)
* @method static void clearMetrics()
*/
class Metrics extends Facade
{
Expand Down
9 changes: 1 addition & 8 deletions ProcessMaker/Jobs/CompleteActivity.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,16 +47,9 @@ public function action(ProcessRequestToken $token, ActivityInterface $element, a
$this->engine->runToNextState();
$element->complete($token);

Metrics::counter(
Metrics::counterInc(
'activity_completed_total',
'Total number of activities completed',
[
'activity_id',
'activity_name',
'process_id',
'request_id',
]
)->inc(
[
'activity_id' => $element->getId(),
'activity_name' => $element->getName(),
Expand Down
10 changes: 1 addition & 9 deletions ProcessMaker/Jobs/RunScriptTask.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -113,17 +113,9 @@ public function action(ProcessRequestToken $token = null, ScriptTaskInterface $e

$this->updateData($response);

Metrics::counter(
Metrics::counterInc(
'script_task_completed_total',
'Total number of script tasks completed',
[
'activity_id',
'activity_name',
'process_id',
'request_id',
'script_executor',
]
)->inc(
[
'activity_id' => $element->getId(),
'activity_name' => $element->getName(),
Expand Down
16 changes: 4 additions & 12 deletions ProcessMaker/Listeners/BpmnSubscriber.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -149,26 +149,18 @@ public function onActivityCompleted(ActivityCompletedEvent $event)
$startTime = $token->created_at_ms;
$completedTime = $token->completed_at_ms;
$executionTime = $completedTime->diffInMilliseconds($startTime);
Metrics::histogram(
Metrics::histogramObserve(
'activity_execution_time_seconds',
'Activity Execution Time',
[
'activity_id',
'activity_name',
'element_type',
'process_id',
'request_id',
],
[1, 10, 3600, 86400]
)->observe(
$executionTime,
[
'activity_id' => $token->element_id,
'activity_name' => $token->element_name,
'element_type' => $token->element_type,
'process_id' => $token->process_id,
'request_id' => $token->process_request_id,
]
],
[1, 10, 3600, 86400],
$executionTime,
);

if ($token->element_type == 'task') {
Expand Down
78 changes: 78 additions & 0 deletions ProcessMaker/Services/MetricsService.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,7 @@
namespace ProcessMaker\Services;

use Exception;
use ProcessMaker\Facades\Metrics;
use Prometheus\CollectorRegistry;
use Prometheus\Counter;
use Prometheus\Gauge;
Expand DownExpand Up@@ -146,4 +147,81 @@ public function renderMetrics(): string

return $renderer->render($metrics);
}

/**
* Increments a counter metric by 1.
*
* @param string $name The name of the counter.
* @param string|null $help The help text of the counter.
* @param array $labels The labels of the counter.
*
* @return void
*/
public function counterInc(string $name, string $help = null, array $labels = []): void
{
// Add system labels
$labels = $this->addSystemLabels($labels);
$labelKeys = array_keys($labels);
Metrics::counter($name, $help, $labelKeys)->inc($labels);
}

/**
* Histogram observation.
*
* @param string $name The name of the histogram.
* @param string|null $help The help text of the histogram.
* @param array $labels The labels of the histogram.
* @param array $buckets The buckets of the histogram.
* @param float $executionTime The execution
*
* @return void
*/
public function histogramObserve(string $name, string $help = null, array $labels = [], array $buckets = [0.1, 1, 5, 10], float $executionTime = 0): void
{
// Add system labels
$labels = $this->addSystemLabels($labels);
$labelKeys = array_keys($labels);
Metrics::histogram(
$name,
$help,
$labelKeys,
$buckets
)->observe(
$executionTime,
$labels
);
}

/**
* Add system labels to the provided labels.
*
* @param array $labels The labels to add system labels to.
*
* @return array The keys of the labels.
*/
public function addSystemLabels(array $labels)
{
// Add system labels
$labels['app_version'] = $this->getApplicationVersion();
$labels['app_name'] = config('app.name');
$labels['app_custom_label'] = config('app.prometheus_custom_label');
return $labels;
}

public function clearMetrics(): void
{
$this->collectionRegistry->wipeStorage();
}

/**
* Gets the version of the application.
*
* @return string The version of the application.
*/
private function getApplicationVersion()
{
$root = base_path('composer.json');
$composer_json_path = json_decode(file_get_contents($root));
return $composer_json_path->version ?? '4.0.0';
}
}
1 change: 1 addition & 0 deletions tests/Feature/Metrics/TaskMetricsTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,6 +47,7 @@ private function assertMetricWasStored(string $name, array $labels)
$metric = $adapter->getCounter($ns, $name);

$this->assertInstanceOf(Counter::class, $metric);
$labels = Metrics::addSystemLabels($labels);
$this->assertEquals($metric->getLabelNames(), array_keys($labels));
}
}
142 changes: 142 additions & 0 deletions tests/unit/MetricsServiceTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,10 +3,18 @@
namespace Tests\Unit;

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Mockery;
use ProcessMaker\Facades\Metrics;
use ProcessMaker\Services\MetricsService;
use Prometheus\CollectorRegistry;
use Prometheus\Counter;
use Prometheus\Histogram;
use Prometheus\Storage\InMemory;
use ReflectionClass;
use Tests\TestCase;


class MetricsServiceTest extends TestCase
{
/**
Expand DownExpand Up@@ -123,4 +131,138 @@ public function testSetGaugeValue(): void
$this->assertStringContainsString('test_set_gauge', $samples);
$this->assertStringContainsString('5', $samples);
}
/**
* Test that counterInc calls Metrics::counter() and then inc() with the correct labels.
*/
public function testCounterInc()
{
// Set configuration values used by addSystemLabels()
Config::set('app.name', 'TestApp');
Config::set('app.prometheus_custom_label', 'customValue');

// Create an instance of MetricsService.
$service = new MetricsService();

$counterName = 'test_counter';
$helpText = 'A test counter';
$initialLabels = ['user' => '123'];

// Determine what system labels will be added.
// (We call addSystemLabels with an empty array to extract the system values.)
$systemLabels = $service->addSystemLabels([]);
// Merge the initial labels with system labels.
$expectedLabels = array_merge($initialLabels, [
'app_version' => $systemLabels['app_version'],
'app_name' => 'TestApp',
'app_custom_label' => 'customValue',
]);
$expectedLabelKeys = array_keys($expectedLabels);

// Create a mock Counter object that expects inc() to be called once.
$mockCounter = Mockery::mock(Counter::class);
$mockCounter->shouldReceive('inc')
->once()
->with($expectedLabels);

// Expect the Metrics facade to be called with the right parameters
// and to return our mock Counter.
Metrics::shouldReceive('counter')
->once()
->with($counterName, $helpText, $expectedLabelKeys)
->andReturn($mockCounter);

// Call counterInc which should trigger the facade calls.
$service->counterInc($counterName, $helpText, $initialLabels);
}

/**
* Test that histogramObserve calls Metrics::histogram() and then observe() with the correct values.
*/
public function testHistogramObserve()
{
// Set configuration values used by addSystemLabels()
Config::set('app.name', 'TestApp');
Config::set('app.prometheus_custom_label', 'customValue');

$service = new MetricsService();

$histogramName = 'test_histogram';
$helpText = 'A test histogram';
$initialLabels = ['endpoint' => '/api/test'];
$buckets = [0.1, 1, 5, 10];
$executionTime = 2.5;

// Determine what system labels will be added.
$systemLabels = $service->addSystemLabels([]);
$expectedLabels = array_merge($initialLabels, [
'app_version' => $systemLabels['app_version'],
'app_name' => 'TestApp',
'app_custom_label' => 'customValue',
]);
$expectedLabelKeys = array_keys($expectedLabels);

// Create a mock Histogram that expects observe() to be called once.
$mockHistogram = Mockery::mock(Histogram::class);
$mockHistogram->shouldReceive('observe')
->once()
->with($executionTime, $expectedLabels);

// Expect the Metrics facade to be called with the right parameters
// and to return our mock Histogram.
Metrics::shouldReceive('histogram')
->once()
->with($histogramName, $helpText, $expectedLabelKeys, $buckets)
->andReturn($mockHistogram);

// Call histogramObserve which should trigger the facade calls.
$service->histogramObserve($histogramName, $helpText, $initialLabels, $buckets, $executionTime);
}

/**
* Test that addSystemLabels returns the input labels plus the system labels.
*/
public function testAddSystemLabels()
{
// Set configuration values used by addSystemLabels()
Config::set('app.name', 'TestApp');
Config::set('app.prometheus_custom_label', 'customValue');

$service = new MetricsService();

$inputLabels = ['label1' => 'value1'];
$result = $service->addSystemLabels($inputLabels);

// Assert that the original label is preserved.
$this->assertEquals('value1', $result['label1']);

// Assert that the system labels were added.
$this->assertArrayHasKey('app_version', $result);
$this->assertArrayHasKey('app_name', $result);
$this->assertArrayHasKey('app_custom_label', $result);
$this->assertEquals('TestApp', $result['app_name']);
$this->assertEquals('customValue', $result['app_custom_label']);
$this->assertNotEmpty($result['app_version']); // Assuming composer.json defines a version.
}

/**
* Test that clearMetrics calls wipeStorage on the collection registry.
*/
public function testClearMetrics()
{
$service = new MetricsService();

// Create a mock for the CollectorRegistry.
$mockRegistry = Mockery::mock(CollectorRegistry::class);
$mockRegistry->shouldReceive('wipeStorage')
->once();

// Use reflection to override the private property "collectionRegistry" with our mock.
$reflection = new ReflectionClass($service);
$property = $reflection->getProperty('collectionRegistry');
$property->setAccessible(true);
$property->setValue($service, $mockRegistry);

// Call clearMetrics which should call wipeStorage on the registry.
$service->clearMetrics();
}
}
17 changes: 17 additions & 0 deletions upgrades/2025_02_03_191354_clear_prometheus_metrics.php
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
<?php

use ProcessMaker\Facades\Metrics;
use ProcessMaker\Upgrades\UpgradeMigration as Upgrade;

class ClearPrometheusMetrics extends Upgrade
{
/**
* Run the upgrade migration.
*
* @return void
*/
public function up()
{
Metrics::clearMetrics();
}
}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
3 changes: 3 additions & 0 deletions ProcessMaker/Facades/Metrics.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,9 @@
* @method static void setGauge(string $name, float $value, array $labelValues = [])
* @method static string renderMetrics()
* @method static \Prometheus\CollectorRegistry getCollectionRegistry()
* @method static void counterInc(string $name, string $help = null, array $labels = [])
* @method static void histogramObserve(string $name, string $help = null, array $labels = [], array $buckets = [0.1, 1, 5, 10], float $executionTime)
* @method static void clearMetrics()
*/
class Metrics extends Facade
{
Expand Down
9 changes: 1 addition & 8 deletions ProcessMaker/Jobs/CompleteActivity.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,16 +47,9 @@ public function action(ProcessRequestToken $token, ActivityInterface $element, a
$this->engine->runToNextState();
$element->complete($token);

Metrics::counter(
Metrics::counterInc(
'activity_completed_total',
'Total number of activities completed',
[
'activity_id',
'activity_name',
'process_id',
'request_id',
]
)->inc(
[
'activity_id' => $element->getId(),
'activity_name' => $element->getName(),
Expand Down
10 changes: 1 addition & 9 deletions ProcessMaker/Jobs/RunScriptTask.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -113,17 +113,9 @@ public function action(ProcessRequestToken $token = null, ScriptTaskInterface $e

$this->updateData($response);

Metrics::counter(
Metrics::counterInc(
'script_task_completed_total',
'Total number of script tasks completed',
[
'activity_id',
'activity_name',
'process_id',
'request_id',
'script_executor',
]
)->inc(
[
'activity_id' => $element->getId(),
'activity_name' => $element->getName(),
Expand Down
16 changes: 4 additions & 12 deletions ProcessMaker/Listeners/BpmnSubscriber.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -149,26 +149,18 @@ public function onActivityCompleted(ActivityCompletedEvent $event)
$startTime = $token->created_at_ms;
$completedTime = $token->completed_at_ms;
$executionTime = $completedTime->diffInMilliseconds($startTime);
Metrics::histogram(
Metrics::histogramObserve(
'activity_execution_time_seconds',
'Activity Execution Time',
[
'activity_id',
'activity_name',
'element_type',
'process_id',
'request_id',
],
[1, 10, 3600, 86400]
)->observe(
$executionTime,
[
'activity_id' => $token->element_id,
'activity_name' => $token->element_name,
'element_type' => $token->element_type,
'process_id' => $token->process_id,
'request_id' => $token->process_request_id,
]
],
[1, 10, 3600, 86400],
$executionTime,
);

if ($token->element_type == 'task') {
Expand Down
78 changes: 78 additions & 0 deletions ProcessMaker/Services/MetricsService.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,6 +3,7 @@
namespace ProcessMaker\Services;

use Exception;
use ProcessMaker\Facades\Metrics;
use Prometheus\CollectorRegistry;
use Prometheus\Counter;
use Prometheus\Gauge;
Expand DownExpand Up@@ -146,4 +147,81 @@ public function renderMetrics(): string

return $renderer->render($metrics);
}

/**
* Increments a counter metric by 1.
*
* @param string $name The name of the counter.
* @param string|null $help The help text of the counter.
* @param array $labels The labels of the counter.
*
* @return void
*/
public function counterInc(string $name, string $help = null, array $labels = []): void
{
// Add system labels
$labels = $this->addSystemLabels($labels);
$labelKeys = array_keys($labels);
Metrics::counter($name, $help, $labelKeys)->inc($labels);
}

/**
* Histogram observation.
*
* @param string $name The name of the histogram.
* @param string|null $help The help text of the histogram.
* @param array $labels The labels of the histogram.
* @param array $buckets The buckets of the histogram.
* @param float $executionTime The execution
*
* @return void
*/
public function histogramObserve(string $name, string $help = null, array $labels = [], array $buckets = [0.1, 1, 5, 10], float $executionTime = 0): void
{
// Add system labels
$labels = $this->addSystemLabels($labels);
$labelKeys = array_keys($labels);
Metrics::histogram(
$name,
$help,
$labelKeys,
$buckets
)->observe(
$executionTime,
$labels
);
}

/**
* Add system labels to the provided labels.
*
* @param array $labels The labels to add system labels to.
*
* @return array The keys of the labels.
*/
public function addSystemLabels(array $labels)
{
// Add system labels
$labels['app_version'] = $this->getApplicationVersion();
$labels['app_name'] = config('app.name');
$labels['app_custom_label'] = config('app.prometheus_custom_label');
return $labels;
}

public function clearMetrics(): void
{
$this->collectionRegistry->wipeStorage();
}

/**
* Gets the version of the application.
*
* @return string The version of the application.
*/
private function getApplicationVersion()
{
$root = base_path('composer.json');
$composer_json_path = json_decode(file_get_contents($root));
return $composer_json_path->version ?? '4.0.0';
}
}
1 change: 1 addition & 0 deletions tests/Feature/Metrics/TaskMetricsTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,6 +47,7 @@ private function assertMetricWasStored(string $name, array $labels)
$metric = $adapter->getCounter($ns, $name);

$this->assertInstanceOf(Counter::class, $metric);
$labels = Metrics::addSystemLabels($labels);
$this->assertEquals($metric->getLabelNames(), array_keys($labels));
}
}
142 changes: 142 additions & 0 deletions tests/unit/MetricsServiceTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,10 +3,18 @@
namespace Tests\Unit;

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Mockery;
use ProcessMaker\Facades\Metrics;
use ProcessMaker\Services\MetricsService;
use Prometheus\CollectorRegistry;
use Prometheus\Counter;
use Prometheus\Histogram;
use Prometheus\Storage\InMemory;
use ReflectionClass;
use Tests\TestCase;


class MetricsServiceTest extends TestCase
{
/**
Expand DownExpand Up@@ -123,4 +131,138 @@ public function testSetGaugeValue(): void
$this->assertStringContainsString('test_set_gauge', $samples);
$this->assertStringContainsString('5', $samples);
}
/**
* Test that counterInc calls Metrics::counter() and then inc() with the correct labels.
*/
public function testCounterInc()
{
// Set configuration values used by addSystemLabels()
Config::set('app.name', 'TestApp');
Config::set('app.prometheus_custom_label', 'customValue');

// Create an instance of MetricsService.
$service = new MetricsService();

$counterName = 'test_counter';
$helpText = 'A test counter';
$initialLabels = ['user' => '123'];

// Determine what system labels will be added.
// (We call addSystemLabels with an empty array to extract the system values.)
$systemLabels = $service->addSystemLabels([]);
// Merge the initial labels with system labels.
$expectedLabels = array_merge($initialLabels, [
'app_version' => $systemLabels['app_version'],
'app_name' => 'TestApp',
'app_custom_label' => 'customValue',
]);
$expectedLabelKeys = array_keys($expectedLabels);

// Create a mock Counter object that expects inc() to be called once.
$mockCounter = Mockery::mock(Counter::class);
$mockCounter->shouldReceive('inc')
->once()
->with($expectedLabels);

// Expect the Metrics facade to be called with the right parameters
// and to return our mock Counter.
Metrics::shouldReceive('counter')
->once()
->with($counterName, $helpText, $expectedLabelKeys)
->andReturn($mockCounter);

// Call counterInc which should trigger the facade calls.
$service->counterInc($counterName, $helpText, $initialLabels);
}

/**
* Test that histogramObserve calls Metrics::histogram() and then observe() with the correct values.
*/
public function testHistogramObserve()
{
// Set configuration values used by addSystemLabels()
Config::set('app.name', 'TestApp');
Config::set('app.prometheus_custom_label', 'customValue');

$service = new MetricsService();

$histogramName = 'test_histogram';
$helpText = 'A test histogram';
$initialLabels = ['endpoint' => '/api/test'];
$buckets = [0.1, 1, 5, 10];
$executionTime = 2.5;

// Determine what system labels will be added.
$systemLabels = $service->addSystemLabels([]);
$expectedLabels = array_merge($initialLabels, [
'app_version' => $systemLabels['app_version'],
'app_name' => 'TestApp',
'app_custom_label' => 'customValue',
]);
$expectedLabelKeys = array_keys($expectedLabels);

// Create a mock Histogram that expects observe() to be called once.
$mockHistogram = Mockery::mock(Histogram::class);
$mockHistogram->shouldReceive('observe')
->once()
->with($executionTime, $expectedLabels);

// Expect the Metrics facade to be called with the right parameters
// and to return our mock Histogram.
Metrics::shouldReceive('histogram')
->once()
->with($histogramName, $helpText, $expectedLabelKeys, $buckets)
->andReturn($mockHistogram);

// Call histogramObserve which should trigger the facade calls.
$service->histogramObserve($histogramName, $helpText, $initialLabels, $buckets, $executionTime);
}

/**
* Test that addSystemLabels returns the input labels plus the system labels.
*/
public function testAddSystemLabels()
{
// Set configuration values used by addSystemLabels()
Config::set('app.name', 'TestApp');
Config::set('app.prometheus_custom_label', 'customValue');

$service = new MetricsService();

$inputLabels = ['label1' => 'value1'];
$result = $service->addSystemLabels($inputLabels);

// Assert that the original label is preserved.
$this->assertEquals('value1', $result['label1']);

// Assert that the system labels were added.
$this->assertArrayHasKey('app_version', $result);
$this->assertArrayHasKey('app_name', $result);
$this->assertArrayHasKey('app_custom_label', $result);
$this->assertEquals('TestApp', $result['app_name']);
$this->assertEquals('customValue', $result['app_custom_label']);
$this->assertNotEmpty($result['app_version']); // Assuming composer.json defines a version.
}

/**
* Test that clearMetrics calls wipeStorage on the collection registry.
*/
public function testClearMetrics()
{
$service = new MetricsService();

// Create a mock for the CollectorRegistry.
$mockRegistry = Mockery::mock(CollectorRegistry::class);
$mockRegistry->shouldReceive('wipeStorage')
->once();

// Use reflection to override the private property "collectionRegistry" with our mock.
$reflection = new ReflectionClass($service);
$property = $reflection->getProperty('collectionRegistry');
$property->setAccessible(true);
$property->setValue($service, $mockRegistry);

// Call clearMetrics which should call wipeStorage on the registry.
$service->clearMetrics();
}
}
17 changes: 17 additions & 0 deletions upgrades/2025_02_03_191354_clear_prometheus_metrics.php
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
<?php

use ProcessMaker\Facades\Metrics;
use ProcessMaker\Upgrades\UpgradeMigration as Upgrade;

class ClearPrometheusMetrics extends Upgrade
{
/**
* Run the upgrade migration.
*
* @return void
*/
public function up()
{
Metrics::clearMetrics();
}
}