CaiWuXiTong/modules/EcommerceFinance/Services/StoreReportMirrorSynchronizer.php
WuYongJie 374df29d2b 修复生产报表负载根因 (#257)
消除报表缓存穿透与后台千万级全表计数,降低同步频率并调整共享数据库资源。
2026-09-23 20:15:59 +08:00

563 lines
25 KiB
PHP

<?php
namespace Modules\EcommerceFinance\Services;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Modules\EcommerceFinance\Repositories\StoreReportRepository;
use Modules\EcommerceFinance\Repositories\StoreReportUpstreamRepository;
use RuntimeException;
use Throwable;
class StoreReportMirrorSynchronizer
{
private readonly ConnectionInterface $connection;
public function __construct(
private readonly StoreReportUpstreamRepository $upstream,
DatabaseManager $databases,
) {
$this->connection = $databases->connection(
(string) config('upstream_mirrors.connection', 'business_mirror'),
);
}
/** @return array{lifecycles:array<string,mixed>,bills:array<string,mixed>,daily:array<string,mixed>} */
public function sync(
?int $batchSize = null,
?int $maxBatches = null,
?int $dailyBatchSize = null,
?int $dailyMaxBatches = null,
): array
{
$this->assertSchemaReady();
$lifecycleBatch = min(max((int) config('upstream_mirrors.store_report.lifecycle_batch_size', 1000), 100), 5000);
$lifecycleMax = max((int) config('upstream_mirrors.store_report.lifecycle_max_batches_per_run', 5), 1);
$billBatch = min(max($batchSize ?? (int) config('upstream_mirrors.store_report.batch_size', 5000), 100), 10000);
$billMax = max($maxBatches ?? (int) config('upstream_mirrors.store_report.max_batches_per_run', 4), 1);
$lifecycles = $this->syncDataset(
StoreReportRepository::LIFECYCLES_DATASET,
'store_report_lifecycle_rows',
$lifecycleBatch,
$lifecycleMax,
fn (int $cursor, int $limit): array => $this->upstream->lifecycleBatch($cursor, $limit),
fn (array $rows, string $generation): array => $this->mapLifecycles($rows, $generation),
);
$bills = $this->syncDataset(
StoreReportRepository::BILLS_DATASET,
'store_report_bill_rows',
$billBatch,
$billMax,
fn (int $cursor, int $limit): array => $this->upstream->billBatch($cursor, $limit),
fn (array $rows, string $generation): array => $this->mapBills($rows, $generation),
);
return [
'lifecycles' => $lifecycles,
'bills' => $bills,
'daily' => $this->syncDailySummary($dailyBatchSize, $dailyMaxBatches),
];
}
/**
* @param callable(int,int):array<int,array<string,mixed>> $fetch
* @param callable(array<int,array<string,mixed>>,string):array{upserts:array<int,array<string,mixed>>,deletes:array<int,int>} $map
* @return array{status:string,mode:string,batches:int,source_rows:int,stored_rows:int,cursor_id:int}
*/
private function syncDataset(
string $dataset,
string $table,
int $batchSize,
int $maxBatches,
callable $fetch,
callable $map,
): array {
$state = $this->state($dataset);
$initial = empty($state->active_generation);
$mode = $initial ? 'full' : 'incremental';
$resume = in_array((string) $state->status, ['running', 'failed'], true)
&& (string) ($state->run_mode ?? '') === $mode;
$generation = $initial
? ($resume && ! empty($state->pending_generation)
? (string) $state->pending_generation
: (string) Str::uuid())
: (string) $state->active_generation;
$cursor = $resume
? (int) ($state->cursor_id ?? 0)
: ($initial
? 0
: max((int) ($state->cursor_id ?? 0)
- max((int) config('upstream_mirrors.store_report.overlap_rows', 50000), 0), 0));
$storedRows = $initial && ! $resume ? 0 : (int) $state->row_count;
$sourceRows = 0;
$batches = 0;
$this->connection->table('store_report_import_states')->where('dataset_key', $dataset)->update([
'status' => 'running',
'run_mode' => $mode,
'pending_generation' => $initial ? $generation : null,
'cursor_id' => $cursor,
'last_attempted_at' => now(),
'last_error_code' => null,
'updated_at' => now(),
]);
try {
while ($batches < $maxBatches) {
$rows = $fetch($cursor, $batchSize);
if ($rows === []) {
return $this->complete($dataset, $generation, $mode, $cursor, $storedRows, $batches, $sourceRows);
}
$nextCursor = max(array_map(static fn (array $row): int => (int) ($row['source_id'] ?? 0), $rows));
if ($nextCursor <= $cursor) {
throw new RuntimeException('store_report_cursor_did_not_advance');
}
$mapped = $map($rows, $generation);
$storedRows = $this->storeBatch(
$dataset,
$table,
$generation,
$nextCursor,
$mapped,
$storedRows,
);
$cursor = $nextCursor;
$sourceRows += count($rows);
$batches++;
if (count($rows) < $batchSize) {
return $this->complete($dataset, $generation, $mode, $cursor, $storedRows, $batches, $sourceRows);
}
}
return $this->result('running', $mode, $batches, $sourceRows, $storedRows, $cursor);
} catch (Throwable $exception) {
$this->connection->table('store_report_import_states')->where('dataset_key', $dataset)->update([
'status' => 'failed',
'last_error_code' => class_basename($exception),
'updated_at' => now(),
]);
throw $exception;
}
}
private function state(string $dataset): object
{
$now = now();
$this->connection->table('store_report_import_states')->insertOrIgnore([
'dataset_key' => $dataset,
'status' => 'pending',
'row_count' => 0,
'source_files_json' => json_encode(['jiansun.dbo.jst_originalBillInfo', 'jiansun.dbo.fys_shopInfo_flow']),
'created_at' => $now,
'updated_at' => $now,
]);
return $this->connection->table('store_report_import_states')->where('dataset_key', $dataset)->first();
}
/** @param array{upserts:array<int,array<string,mixed>>,deletes:array<int,int>} $mapped */
private function storeBatch(
string $dataset,
string $table,
string $generation,
int $cursor,
array $mapped,
int $storedRows,
): int {
return $this->connection->transaction(function () use (
$dataset, $table, $generation, $cursor, $mapped, $storedRows,
): int {
$upsertIds = [];
foreach ($mapped['upserts'] as $row) {
$upsertIds[(int) $row['source_id']] = true;
}
$deleteIds = array_fill_keys(array_map('intval', $mapped['deletes']), true);
$touchedIds = array_keys($upsertIds + $deleteIds);
$existingIds = [];
foreach (array_chunk($touchedIds, 1000) as $chunk) {
foreach ($this->connection->table($table)
->where('generation', $generation)
->whereIn('source_id', $chunk)
->pluck('source_id') as $sourceId) {
$existingIds[(int) $sourceId] = true;
}
}
$inserted = count(array_diff_key($upsertIds, $existingIds));
$deleted = count(array_diff_key(array_intersect_key($deleteIds, $existingIds), $upsertIds));
$nextStoredRows = max($storedRows + $inserted - $deleted, 0);
$dailyDeltas = $table === 'store_report_bill_rows' && $this->dailySummaryReady($generation)
? $this->dailyDeltas($generation, $mapped)
: [];
if ($mapped['deletes'] !== []) {
$this->connection->table($table)
->where('generation', $generation)
->whereIn('source_id', $mapped['deletes'])
->delete();
}
if ($mapped['upserts'] !== []) {
$updates = array_values(array_diff(array_keys($mapped['upserts'][0]), ['generation', 'source_id']));
// MySQL/MariaDB 对单条预处理语句的占位符数量有限,不能把
// 数千行、十余列一次塞进同一条 upsert。
$columnsPerRow = max(count($mapped['upserts'][0]), 1);
$chunkSize = max(1, min(2000, intdiv(50000, $columnsPerRow)));
foreach (array_chunk($mapped['upserts'], $chunkSize) as $chunk) {
$this->connection->table($table)->upsert(
$chunk, ['generation', 'source_id'], $updates,
);
}
}
if ($dailyDeltas !== []) {
$this->applyDailyDeltas($generation, $dailyDeltas);
}
$this->connection->table('store_report_import_states')->where('dataset_key', $dataset)->update([
'cursor_id' => $cursor,
'row_count' => $nextStoredRows,
'updated_at' => now(),
]);
return $nextStoredRows;
});
}
/** @return array{status:string,mode:string,batches:int,source_rows:int,stored_rows:int,cursor_id:int} */
private function complete(
string $dataset,
string $generation,
string $mode,
int $cursor,
int $storedRows,
int $batches,
int $sourceRows,
): array {
$now = now();
$values = [
'status' => 'succeeded',
'run_mode' => null,
'cursor_id' => $cursor,
'last_succeeded_at' => $now,
'last_error_code' => null,
'row_count' => $storedRows,
'updated_at' => $now,
];
if ($mode === 'full') {
$values += [
'active_generation' => $generation,
'pending_generation' => null,
'initial_completed_at' => $now,
];
}
$this->connection->table('store_report_import_states')->where('dataset_key', $dataset)->update($values);
return $this->result('succeeded', $mode, $batches, $sourceRows, $storedRows, $cursor);
}
/** @return array{status:string,mode:string,batches:int,source_rows:int,stored_rows:int,cursor_id:int} */
private function syncDailySummary(?int $batchSize, ?int $maxBatches): array
{
$billState = $this->state(StoreReportRepository::BILLS_DATASET);
$generation = (string) ($billState->active_generation ?? '');
if ($generation === '') {
return $this->result('pending', 'full', 0, 0, 0, 0);
}
$batchSize = min(max($batchSize ?? (int) config('upstream_mirrors.store_report.daily_batch_size', 50000), 1000), 100000);
$maxBatches = max($maxBatches ?? (int) config('upstream_mirrors.store_report.daily_max_batches_per_run', 10), 1);
$state = $this->state(StoreReportRepository::DAILY_DATASET);
if ((string) ($state->active_generation ?? '') === $generation && ! empty($state->initial_completed_at)) {
return $this->result('succeeded', 'incremental', 0, 0, (int) $state->row_count, (int) $state->cursor_id);
}
$resume = in_array((string) $state->status, ['running', 'failed'], true)
&& (string) ($state->pending_generation ?? '') === $generation;
$cursor = $resume ? (int) ($state->cursor_id ?? 0) : 0;
if (! $resume) {
$this->connection->table('store_report_daily_rows')->where('generation', $generation)->delete();
}
$this->connection->table('store_report_import_states')
->where('dataset_key', StoreReportRepository::DAILY_DATASET)
->update([
'status' => 'running', 'run_mode' => 'full', 'pending_generation' => $generation,
'cursor_id' => $cursor, 'last_attempted_at' => now(), 'last_error_code' => null,
'updated_at' => now(),
]);
$batches = 0;
$sourceRows = 0;
try {
while ($batches < $maxBatches) {
$rows = $this->connection->table('store_report_bill_rows')
->where('generation', $generation)->where('source_id', '>', $cursor)
->orderBy('source_id')->limit($batchSize)
->get(['source_id', 'store_name', 'occurred_at', 'income', 'expense'])
->map(static fn (object $row): array => (array) $row)->all();
if ($rows === []) {
return $this->completeDailySummary($generation, $cursor, $batches, $sourceRows);
}
$cursor = max(array_map(static fn (array $row): int => (int) $row['source_id'], $rows));
$deltas = $this->aggregateDailyRows($rows, 1.0);
$this->connection->transaction(function () use ($generation, $cursor, $deltas): void {
$this->applyDailyDeltas($generation, $deltas);
$this->connection->table('store_report_import_states')
->where('dataset_key', StoreReportRepository::DAILY_DATASET)
->update(['cursor_id' => $cursor, 'updated_at' => now()]);
});
$sourceRows += count($rows);
$batches++;
if (count($rows) < $batchSize) {
return $this->completeDailySummary($generation, $cursor, $batches, $sourceRows);
}
}
} catch (Throwable $exception) {
$this->connection->table('store_report_import_states')
->where('dataset_key', StoreReportRepository::DAILY_DATASET)
->update(['status' => 'failed', 'last_error_code' => class_basename($exception), 'updated_at' => now()]);
throw $exception;
}
$stored = (int) $this->connection->table('store_report_daily_rows')->where('generation', $generation)->count();
return $this->result('running', 'full', $batches, $sourceRows, $stored, $cursor);
}
/** @return array{status:string,mode:string,batches:int,source_rows:int,stored_rows:int,cursor_id:int} */
private function completeDailySummary(string $generation, int $cursor, int $batches, int $sourceRows): array
{
$rows = (int) $this->connection->table('store_report_daily_rows')->where('generation', $generation)->count();
$now = now();
$this->connection->table('store_report_import_states')
->where('dataset_key', StoreReportRepository::DAILY_DATASET)
->update([
'status' => 'succeeded', 'run_mode' => null, 'active_generation' => $generation,
'pending_generation' => null, 'cursor_id' => $cursor, 'row_count' => $rows,
'initial_completed_at' => $now, 'last_succeeded_at' => $now,
'last_error_code' => null, 'updated_at' => $now,
]);
return $this->result('succeeded', 'full', $batches, $sourceRows, $rows, $cursor);
}
private function dailySummaryReady(string $generation): bool
{
$state = $this->connection->table('store_report_import_states')
->where('dataset_key', StoreReportRepository::DAILY_DATASET)->first();
return $state !== null && (string) ($state->active_generation ?? '') === $generation
&& ! empty($state->initial_completed_at);
}
/** @param array{upserts:array<int,array<string,mixed>>,deletes:array<int,int>} $mapped */
private function dailyDeltas(string $generation, array $mapped): array
{
$ids = array_values(array_unique(array_merge(
$mapped['deletes'],
array_map(static fn (array $row): int => (int) $row['source_id'], $mapped['upserts']),
)));
$deltas = [];
foreach (array_chunk($ids, 1000) as $chunk) {
$old = $this->connection->table('store_report_bill_rows')
->where('generation', $generation)->whereIn('source_id', $chunk)
->get(['store_name', 'occurred_at', 'income', 'expense'])
->map(static fn (object $row): array => (array) $row)->all();
$deltas = $this->mergeDailyDeltas($deltas, $this->aggregateDailyRows($old, -1.0));
}
return $this->mergeDailyDeltas($deltas, $this->aggregateDailyRows($mapped['upserts'], 1.0));
}
private function aggregateDailyRows(array $rows, float $sign): array
{
$result = [];
foreach ($rows as $row) {
$store = trim((string) ($row['store_name'] ?? ''));
$date = substr((string) ($row['occurred_at'] ?? ''), 0, 10);
if ($store === '' || strlen($date) !== 10) continue;
$key = $store . "\0" . $date;
$result[$key] ??= ['store_name' => $store, 'occurred_on' => $date, 'income' => 0.0, 'expense' => 0.0];
$result[$key]['income'] += $sign * (float) ($row['income'] ?? 0);
$result[$key]['expense'] += $sign * (float) ($row['expense'] ?? 0);
}
return $result;
}
private function mergeDailyDeltas(array $left, array $right): array
{
foreach ($right as $key => $row) {
$left[$key] ??= ['store_name' => $row['store_name'], 'occurred_on' => $row['occurred_on'], 'income' => 0.0, 'expense' => 0.0];
$left[$key]['income'] += $row['income'];
$left[$key]['expense'] += $row['expense'];
}
return $left;
}
private function applyDailyDeltas(string $generation, array $deltas): void
{
if ($deltas === []) return;
if ($this->connection->getDriverName() === 'sqlite') {
foreach ($deltas as $row) {
$current = $this->connection->table('store_report_daily_rows')
->where('generation', $generation)->where('store_name', $row['store_name'])
->where('occurred_on', $row['occurred_on'])->first();
$values = ['income' => (float) ($current->income ?? 0) + $row['income'],
'expense' => (float) ($current->expense ?? 0) + $row['expense'], 'updated_at' => now()];
$current === null
? $this->connection->table('store_report_daily_rows')->insert($values + [
'generation' => $generation, 'store_name' => $row['store_name'], 'occurred_on' => $row['occurred_on'],
])
: $this->connection->table('store_report_daily_rows')->where('id', $current->id)->update($values);
}
return;
}
foreach (array_chunk(array_values($deltas), 500) as $chunk) {
$bindings = [];
$values = [];
foreach ($chunk as $row) {
$values[] = '(?,?,?,?,?,?)';
array_push($bindings, $generation, $row['store_name'], $row['occurred_on'],
$row['income'], $row['expense'], now()->format('Y-m-d H:i:s'));
}
$this->connection->statement(
'INSERT INTO store_report_daily_rows (generation,store_name,occurred_on,income,expense,updated_at) VALUES '
. implode(',', $values)
. ' ON DUPLICATE KEY UPDATE income=income+VALUES(income), expense=expense+VALUES(expense), updated_at=VALUES(updated_at)',
$bindings,
);
}
}
/** @return array{status:string,mode:string,batches:int,source_rows:int,stored_rows:int,cursor_id:int} */
private function result(string $status, string $mode, int $batches, int $sourceRows, int $storedRows, int $cursor): array
{
return [
'status' => $status,
'mode' => $mode,
'batches' => $batches,
'source_rows' => $sourceRows,
'stored_rows' => $storedRows,
'cursor_id' => $cursor,
];
}
/** @return array{upserts:array<int,array<string,mixed>>,deletes:array<int,int>} */
private function mapBills(array $rows, string $generation): array
{
$upserts = [];
$deletes = [];
foreach ($rows as $row) {
$sourceId = (int) ($row['source_id'] ?? 0);
$storeName = $this->text($row['shop_name'] ?? null, 191);
$occurredAt = $this->dateTime($row['fee_time'] ?? null);
$direction = (string) ($row['inout_type'] ?? '');
if ($sourceId < 1 || (int) ($row['del_flag'] ?? 0) !== 0 || $storeName === null
|| $occurredAt === null || ! in_array($direction, ['1', '-1'], true)) {
if ($sourceId > 0) {
$deletes[] = $sourceId;
}
continue;
}
$amount = abs((float) ($row['amount'] ?? 0));
$platform = $this->text($row['channel'] ?? null, 32) ?? 'unknown';
$business = [$sourceId, $platform, $storeName, $occurredAt, $direction, $amount];
$upserts[] = [
'generation' => $generation,
'source_id' => $sourceId,
'shop_id' => (int) ($row['shop_id'] ?? 0) ?: null,
'platform' => $platform,
'platform_label' => $this->platformLabel($platform),
'store_name' => $storeName,
'occurred_at' => $occurredAt,
'income' => $direction === '1' ? $amount : 0,
'expense' => $direction === '-1' ? $amount : 0,
'bill_item' => $this->text($row['fee_name'] ?? null, 255),
'record_code' => (string) $sourceId,
'source_file' => 'jiansun.dbo.jst_originalBillInfo',
'row_hash' => hash('sha256', json_encode($business, JSON_UNESCAPED_UNICODE)),
'source_updated_at' => $this->dateTime($row['source_updated_at'] ?? null),
'imported_at' => now(),
];
}
return ['upserts' => $upserts, 'deletes' => $deletes];
}
/** @return array{upserts:array<int,array<string,mixed>>,deletes:array<int,int>} */
private function mapLifecycles(array $rows, string $generation): array
{
$upserts = [];
$deletes = [];
foreach ($rows as $row) {
$sourceId = (int) ($row['source_id'] ?? 0);
$storeName = $this->text($row['erp_store_name'] ?? null, 191);
$creditCode = $this->text($row['unified_social_credit_code'] ?? null, 64);
$effectiveAt = $this->dateTime($row['effective_at'] ?? null);
if ($sourceId < 1 || $storeName === null || $creditCode === null || $effectiveAt === null) {
if ($sourceId > 0) {
$deletes[] = $sourceId;
}
continue;
}
$business = [$sourceId, $storeName, $creditCode, $effectiveAt];
$upserts[] = [
'generation' => $generation,
'source_id' => $sourceId,
'business_key' => hash('sha256', (string) $sourceId),
'erp_store_name' => $storeName,
'company_name' => $this->text($row['company_name'] ?? null, 191),
'unified_social_credit_code' => $creditCode,
'effective_at' => $effectiveAt,
'expires_at' => null,
'source_file' => 'jiansun.dbo.fys_shopInfo_flow',
'row_hash' => hash('sha256', json_encode($business, JSON_UNESCAPED_UNICODE)),
'imported_at' => now(),
];
}
return ['upserts' => $upserts, 'deletes' => $deletes];
}
private function platformLabel(string $channel): string
{
return match ($channel) {
'alipayCSV' => '淘系',
'TouTiaoFXGZJ' => '抖音',
'PinduoduoImport' => '拼多多',
'Jos' => '京东',
default => $channel,
};
}
private function text(mixed $value, int $length): ?string
{
$value = trim((string) ($value ?? ''));
if ($value === '') {
return null;
}
if (! mb_check_encoding($value, 'UTF-8')) {
$value = mb_convert_encoding($value, 'UTF-8', 'GB18030');
}
return mb_substr($value, 0, $length);
}
private function dateTime(mixed $value): ?string
{
$value = trim((string) ($value ?? ''));
return $value === '' ? null : str_replace('T', ' ', substr($value, 0, 26));
}
private function assertSchemaReady(): void
{
$schema = Schema::connection($this->connection->getName());
foreach (['store_report_import_states', 'store_report_bill_rows', 'store_report_lifecycle_rows', 'store_report_daily_rows'] as $table) {
if (! $schema->hasTable($table)) {
throw new RuntimeException('store_report_mirror_schema_missing:' . $table);
}
}
foreach (['run_mode', 'cursor_id', 'initial_completed_at'] as $column) {
if (! $schema->hasColumn('store_report_import_states', $column)) {
throw new RuntimeException('store_report_mirror_upgrade_missing:' . $column);
}
}
}
}