Files
dpl/app/Services/RegistrationReport/Reporter.php
T

93 lines
7.4 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Services\RegistrationReport;
use App\Models\User;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Http;
use RuntimeException;
class Reporter
{
private const TERMINAL=['sent','failed','uncertain','cancelled'];
private const STATES=['queued','sending','sent','failed','uncertain','cancelled'];
public function run(?CarbonImmutable $now=null,bool $dryRun=false): array
{
$now=($now??CarbonImmutable::now())->setTimezone('Asia/Shanghai');
if($dryRun)return ['status'=>'preview','report'=>$this->snapshot($now,$now->lessThan($now->startOfDay()->setTime(8,0)))];
if(!config('registration_report.enabled',true))return ['status'=>'disabled'];
if(config('app.env')!=='production')return ['status'=>'non_production'];
$path=(string)config('registration_report.state_path');$dir=dirname($path);
if(!is_dir($dir)&&!mkdir($dir,0700,true)&&!is_dir($dir))throw new RuntimeException('report_directory_failed');
if(is_link($dir)||is_link($path)||is_link($path.'.lock'))throw new RuntimeException('unsafe_report_path');
$lock=fopen($path.'.lock','c+');if(!$lock)throw new RuntimeException('report_lock_failed');chmod($path.'.lock',0600);
try {
if(!flock($lock,LOCK_EX|LOCK_NB))return ['status'=>'locked'];
$identity=$this->identity();
$state=is_file($path)?json_decode(file_get_contents($path),true,512,JSON_THROW_ON_ERROR):['version'=>1,'identity'=>$identity,'reports'=>[]];
if(!is_array($state)||($state['version']??null)!==1||($state['identity']??null)!==$identity||!is_array($state['reports']??null))throw new RuntimeException('invalid_report_state');
$date=$now->toDateString();
if($now->hour>=8&&!isset($state['reports'][$date])) {
$state['reports'][$date]=$this->snapshot($now);
$this->save($path,$state); // Freeze the key, count and text before any external call.
}
$key=(string)config('registration_report.telehub_key');$base=rtrim((string)config('registration_report.telehub_url'),'/');
$results=[];$attention=false;
foreach($state['reports'] as $day=>&$event) {
$this->validate($event);
if(in_array($event['status'],self::TERMINAL,true)){if(in_array($event['status'],['failed','uncertain'],true))$attention=true;continue;}
if(!$key||parse_url($base,PHP_URL_SCHEME)!=='https'||!parse_url($base,PHP_URL_HOST)||parse_url($base,PHP_URL_USER)||parse_url($base,PHP_URL_PASS)){$results[$day]='telehub_not_configured';$attention=true;continue;}
if($now->timestamp<($event['retry_at']??0)){$results[$day]='waiting';continue;}
$event['attempts']=($event['attempts']??0)+1;
$event['retry_at']=$now->timestamp+max(60,(int)config('registration_report.retry_seconds',300));
$this->save($path,$state);
try {
$client=Http::withoutRedirecting()->connectTimeout(5)->timeout(15)->withToken($key);
$response=isset($event['receipt_id'])?$client->get($base.'/api/v1/messages/'.$event['receipt_id']):$client->withHeaders(['Idempotency-Key'=>$event['key']])->post($base.'/api/v1/messages',['bot'=>'info','target'=>'base','text'=>$event['text']]);
if(!in_array($response->status(),[200,202],true)) {
$event['last_error']='telehub_http_'.$response->status();
if($response->status()===429)$event['retry_at']=$now->timestamp+max(60,min(86400,(int)$response->header('Retry-After',300)));
$results[$day]=$event['last_error'];$attention=true;
} else {
$data=$response->json('data');$id=is_array($data)?($data['id']??null):null;$status=is_array($data)?($data['status']??null):null;
if(!$this->uuid($id)||!in_array($status,self::STATES,true)||(isset($event['receipt_id'])&&$event['receipt_id']!==$id)) {
$event['last_error']='telehub_response_invalid';$attention=true;$results[$day]='telehub_response_invalid';
} else {
$event['receipt_id']=$id;$event['status']=$status;unset($event['last_error']);$results[$day]=$status;
if(in_array($status,['failed','uncertain'],true))$attention=true;
}
}
} catch(\Throwable $e) {$event['last_error']='telehub_transport_unknown';$attention=true;$results[$day]='telehub_transport_unknown';}
$this->save($path,$state);
}
unset($event);
return ['status'=>$state['reports']?'processed':'not_due','reports'=>$results,'needs_attention'=>$attention];
} finally {flock($lock,LOCK_UN);fclose($lock);}
}
public function snapshot(CarbonImmutable $now,bool $previewBeforeEight=false): array
{
$end=$now->setTimezone('Asia/Shanghai')->startOfDay()->setTime(8,0);$start=$end->subDay();if($previewBeforeEight)$end=$now;
$count=User::where('created_at','>=',$start->timestamp)->where('created_at','<',$end->timestamp)->count();
$project=(string)config('registration_report.project','xb');$project=trim(preg_replace('/[\x00-\x1f\x7f]+/u',' ',$project));
if($project===''||mb_strlen($project)>100)throw new RuntimeException('invalid_report_project');
$environment=(string)config('app.env');
return ['key'=>'xb.registration.daily.'.$this->identity().'.'.$now->toDateString(),'date'=>$now->toDateString(),'bot'=>'info','target'=>'base','text'=>'【'.$project.'/'.$environment.' - 注册量日报】'."\n统计日期:".$now->toDateString()."\n统计区间:".$start->format('Y-m-d H:i')."–".$end->format('Y-m-d H:i')."(北京时间)\n注册量:".$count.' 人','count'=>$count,'start_at'=>$start->timestamp,'end_at'=>$end->timestamp,'status'=>'pending','attempts'=>0];
}
private function identity(): string
{
$driver=(string)config('database.default');
return substr(hash('sha256',implode('|',[(string)config('app.env'),(string)config('registration_report.project'),(string)config('app.url'),$driver,(string)config('database.connections.'.$driver.'.database')])),0,24);
}
private function uuid(mixed $id): bool {return is_string($id)&&preg_match('/\A[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\z/iD',$id)===1;}
private function validate(array $event): void
{
if(!is_string($event['key']??null)||!preg_match('/\A[A-Za-z0-9._:-]{1,128}\z/D',$event['key'])||($event['bot']??null)!=='info'||($event['target']??null)!=='base'||!is_string($event['text']??null)||!in_array($event['status']??null,['pending',...self::STATES],true)||(isset($event['receipt_id'])&&!$this->uuid($event['receipt_id'])))throw new RuntimeException('invalid_report_event');
}
private function save(string $path,array $state): void
{
$temp=$path.'.'.bin2hex(random_bytes(6)).'.tmp';$bytes=json_encode($state,JSON_UNESCAPED_UNICODE|JSON_THROW_ON_ERROR);
try {
$h=fopen($temp,'x');if(!$h)throw new RuntimeException('report_write_failed');chmod($temp,0600);
try {if(fwrite($h,$bytes)!==strlen($bytes))throw new RuntimeException('report_short_write');fflush($h);if(function_exists('fsync'))fsync($h);}finally{fclose($h);}
if(!rename($temp,$path))throw new RuntimeException('report_rename_failed');
}finally{if(is_file($temp))unlink($temp);}
}
}