polish the api route, response, health, cache, and metrics

This commit is contained in:
dwindown
2025-08-31 20:45:24 +07:00
parent ce001bf9ce
commit 726f5a842f
12 changed files with 627 additions and 97 deletions

View File

@@ -0,0 +1,17 @@
<?php
// app/helpers/cors.php
function cors_allow() {
$allowed = cfg('allowed_origins', []);
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if ($origin && in_array($origin, $allowed, true)) {
header("Access-Control-Allow-Origin: {$origin}");
header("Vary: Origin");
}
header("Access-Control-Allow-Headers: Content-Type, X-Account-Id, X-License-Key, X-Dewemoji-Frontend, X-Dewemoji-Plan");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
}
function cors_preflight() {
cors_allow();
http_response_code(204);
}
cors_allow();

34
app/helpers/http.php Normal file
View File

@@ -0,0 +1,34 @@
<?php
// app/helpers/http.php
function http_post_form($url, array $fields, array $headers = [], $timeout = 10) {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($fields),
CURLOPT_HTTPHEADER => $headers,
CURLOPT_TIMEOUT => $timeout,
]);
$body = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
curl_close($ch);
return [$code, $body, $err];
}
function http_post_json($url, array $json, array $headers = [], $timeout = 10) {
$hdrs = array_merge(['Content-Type: application/json'], $headers);
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($json),
CURLOPT_HTTPHEADER => $hdrs,
CURLOPT_TIMEOUT => $timeout,
]);
$body = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
curl_close($ch);
return [$code, $body, $err];
}

0
app/helpers/json.php Normal file
View File

28
app/helpers/logger.php Normal file
View File

@@ -0,0 +1,28 @@
<?php
// Simple file logger
function log_start() {
$id = bin2hex(random_bytes(4));
$GLOBALS['req_start'] = microtime(true);
header("X-Request-Id: $id");
return $id;
}
function log_end($id, $status=200) {
$ms = round((microtime(true)-$GLOBALS['req_start'])*1000);
$ip = $_SERVER['REMOTE_ADDR'] ?? '-';
$path = $_SERVER['REQUEST_URI'] ?? '-';
$plan = $_SERVER['HTTP_X_DEWEMOJI_PLAN'] ?? ($GLOBALS['bucket_plan'] ?? '-');
$bucket = $GLOBALS['bucket_id'] ?? '-';
$ua = $_SERVER['HTTP_USER_AGENT'] ?? '-';
$ref = $_SERVER['HTTP_REFERER'] ?? '-';
$errorMsg = '';
if ($status >= 400) {
$errorMsg = $GLOBALS['json_error_msg'] ?? '';
}
$line = sprintf("[%s] %s %s %s plan=%s bucket=%s %d %dms ua=\"%s\" ref=\"%s\"%s\n",
gmdate('c'), $id, $ip, $path, $plan, $bucket, $status, $ms, $ua, $ref,
$errorMsg ? " error=\"".addslashes($errorMsg)."\"" : ''
);
$logFile = __DIR__.'/../../storage/logs/access.log';
@mkdir(dirname($logFile), 0775, true);
error_log($line, 3, $logFile);
}