summaryrefslogtreecommitdiff
path: root/src/quote/app/routes.php
diff options
context:
space:
mode:
authorSaumit <justsaumit@protonmail.com>2025-09-27 02:14:26 +0530
committerSaumit <justsaumit@protonmail.com>2025-09-27 02:14:26 +0530
commit82e03978b89938219958032efb1448cc76baa181 (patch)
tree626f3e54d52ecd49be0ed3bee30abacc0453d081 /src/quote/app/routes.php
Initial snapshot - OpenTelemetry demo 2.1.3 -f
Diffstat (limited to 'src/quote/app/routes.php')
-rw-r--r--src/quote/app/routes.php74
1 files changed, 74 insertions, 0 deletions
diff --git a/src/quote/app/routes.php b/src/quote/app/routes.php
new file mode 100644
index 0000000..2c2231a
--- /dev/null
+++ b/src/quote/app/routes.php
@@ -0,0 +1,74 @@
+<?php
+// Copyright The OpenTelemetry Authors
+// SPDX-License-Identifier: Apache-2.0
+
+
+
+use OpenTelemetry\API\Globals;
+use OpenTelemetry\API\Trace\Span;
+use OpenTelemetry\API\Trace\SpanKind;
+use Psr\Http\Message\ResponseInterface as Response;
+use Psr\Http\Message\ServerRequestInterface as Request;
+use Psr\Log\LoggerInterface;
+use Slim\App;
+
+function calculateQuote($jsonObject): float
+{
+ $quote = 0.0;
+ $childSpan = Globals::tracerProvider()->getTracer('manual-instrumentation')
+ ->spanBuilder('calculate-quote')
+ ->setSpanKind(SpanKind::KIND_INTERNAL)
+ ->startSpan();
+ $childSpan->addEvent('Calculating quote');
+
+ try {
+ if (!array_key_exists('numberOfItems', $jsonObject)) {
+ throw new \InvalidArgumentException('numberOfItems not provided');
+ }
+ $numberOfItems = intval($jsonObject['numberOfItems']);
+ $costPerItem = rand(400, 1000)/10;
+ $quote = round($costPerItem * $numberOfItems, 2);
+
+ $childSpan->setAttribute('app.quote.items.count', $numberOfItems);
+ $childSpan->setAttribute('app.quote.cost.total', $quote);
+
+ $childSpan->addEvent('Quote calculated, returning its value');
+
+ //manual metrics
+ static $counter;
+ $counter ??= Globals::meterProvider()
+ ->getMeter('quotes')
+ ->createCounter('quotes', 'quotes', 'number of quotes calculated');
+ $counter->add(1, ['number_of_items' => $numberOfItems]);
+ } catch (\Exception $exception) {
+ $childSpan->recordException($exception);
+ } finally {
+ $childSpan->end();
+ return $quote;
+ }
+}
+
+return function (App $app) {
+ $app->post('/getquote', function (Request $request, Response $response, LoggerInterface $logger) {
+ $span = Span::getCurrent();
+ $span->addEvent('Received get quote request, processing it');
+
+ $jsonObject = $request->getParsedBody();
+
+ $data = calculateQuote($jsonObject);
+
+ $payload = json_encode($data);
+ $response->getBody()->write($payload);
+
+ $span->addEvent('Quote processed, response sent back', [
+ 'app.quote.cost.total' => $data
+ ]);
+ //exported as an opentelemetry log (see dependencies.php)
+ $logger->info('Calculated quote', [
+ 'total' => $data,
+ ]);
+
+ return $response
+ ->withHeader('Content-Type', 'application/json');
+ });
+};