Repository navigation
Expand file tree
/
Copy pathStaticGenerator.php
More file actions
988 lines (866 loc) · 35.4 KB
/
Copy pathStaticGenerator.php
File metadata and controls
988 lines (866 loc) · 35.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
<?php
namespace app\process;
use app\model\Post;
use app\service\AssetMinifyRegistry;
use app\service\EnhancedStaticCacheConfig;
use app\service\MQService;
use MatthiasMullie\Minify\CSS;
use MatthiasMullie\Minify\JS;
use PhpAmqpLib\Channel\AMQPChannel;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Exception\AMQPTimeoutException;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Wire\AMQPTable;
use RuntimeException;
use support\Log;
use Throwable;
use Workerman\Timer;
/**
* 全站静态化生成进程
* - 消费静态化任务队列,内部渲染并落盘至 public/static
* - 周期增量:每小时检查最近24小时更新的文章
* - 手动全量:向队列投递 scope=all 或具体范围
*/
class StaticGenerator
{
/** @var AMQPStreamConnection|null */
protected ?AMQPStreamConnection $mqConnection = null;
/** @var AMQPChannel|null */
protected $mqChannel = null;
// MQ 命名
private string $exchange = 'windblog_static_gen';
private string $routingKey = 'static_gen';
private string $queueName = 'windblog_static_queue';
private string $dlxExchange = 'windblog_static_dlx';
private string $dlxQueue = 'windblog_static_dlq';
public function onWorkerStart(): void
{
// 检查系统是否已安装
if (!is_installed()) {
Log::warning('StaticGenerator 检测到系统未安装,已跳过启动');
return;
}
// 检查静态缓存是否启用
if (!EnhancedStaticCacheConfig::isEnabled()) {
Log::info('StaticGenerator 检测到静态缓存已关闭,已跳过启动');
return;
}
$this->initMq();
$this->startConsumer();
// 周期增量:每小时执行一次
if (class_exists(Timer::class)) {
Timer::add(3600, function () {
$this->enqueueIncrementalPosts(24);
});
// 每60秒进行一次 MQ 健康检查
Timer::add(60, function () {
try {
MQService::checkAndHeal();
} catch (Throwable $e) {
Log::warning('MQ 健康检查异常(StaticGenerator): ' . $e->getMessage());
}
});
}
}
protected function initMq(): void
{
try {
// 使用 MQService 通道
$this->mqChannel = MQService::getChannel();
// 允许通过配置覆盖命名
$this->exchange = (string) blog_config('rabbitmq_static_exchange', $this->exchange, true) ?: $this->exchange;
$this->routingKey = (string) blog_config('rabbitmq_static_routing_key', $this->routingKey, true) ?: $this->routingKey;
$this->queueName = (string) blog_config('rabbitmq_static_queue', $this->queueName, true) ?: $this->queueName;
$this->dlxExchange = (string) blog_config('rabbitmq_static_dlx_exchange', $this->dlxExchange, true) ?: $this->dlxExchange;
$this->dlxQueue = (string) blog_config('rabbitmq_static_dlx_queue', $this->dlxQueue, true) ?: $this->dlxQueue;
// 使用 MQService 的通用初始化(专属 DLX/DLQ)
MQService::declareDlx($this->mqChannel, $this->dlxExchange, $this->dlxQueue);
MQService::setupQueueWithDlx($this->mqChannel, $this->exchange, $this->routingKey, $this->queueName, $this->dlxExchange, $this->dlxQueue);
Log::info('StaticGenerator MQ 初始化成功');
} catch (Throwable $e) {
Log::error('StaticGenerator MQ 初始化失败: ' . $e->getMessage());
}
}
protected function startConsumer(): void
{
if (!$this->mqChannel) {
return;
}
$this->mqChannel->basic_qos(0, 1, null);
$this->mqChannel->basic_consume($this->queueName, '', false, false, false, false, function (AMQPMessage $message) {
$this->handleMessage($message);
});
// 在 worker 循环中轮询消费
if (class_exists(Timer::class)) {
Timer::add(1, function () {
try {
if ($this->mqChannel === null) {
Log::warning('StaticGenerator: channel is null, reconnecting...');
$this->reconnectMq();
return;
}
// 增大超时时间并忽略超时异常
$this->mqChannel->wait(null, false, 1.0);
} catch (AMQPTimeoutException $e) {
// 无数据到达的正常超时,忽略
} catch (Throwable $e) {
$errorMsg = $e->getMessage();
Log::warning('StaticGenerator 消费轮询异常: ' . $errorMsg);
// 检测通道连接断开,触发自愈
if (str_contains($errorMsg, 'Channel connection is closed') ||
str_contains($errorMsg, 'Broken pipe') ||
str_contains($errorMsg, 'connection is closed') ||
str_contains($errorMsg, 'on null')) {
Log::warning('StaticGenerator 检测到连接断开,尝试重建连接');
$this->reconnectMq();
}
}
});
}
}
protected function handleMessage(AMQPMessage $message): void
{
try {
$payload = json_decode($message->getBody(), true);
if (!is_array($payload)) {
throw new RuntimeException('消息体不是有效JSON');
}
$type = $payload['type'] ?? 'url';
$options = $payload['options'] ?? [];
$force = (bool) ($options['force'] ?? false);
$jobId = (string) ($options['job_id'] ?? ('auto_' . date('Ymd_His')));
if ($type === 'url') {
$url = (string) $payload['value'];
$this->generateByUrl($url, $force, $jobId);
} elseif ($type === 'scope') {
$scope = (string) $payload['value'];
$pages = (int) ($options['pages'] ?? 1);
$this->generateByScope($scope, $pages, $force, $jobId);
} else {
throw new RuntimeException('未知消息类型: ' . $type);
}
$message->ack();
} catch (Throwable $e) {
Log::error('静态化消息处理失败: ' . $e->getMessage());
$this->handleFailedMessage($message);
}
}
protected function handleFailedMessage(AMQPMessage $message): void
{
$headers = $message->has('application_headers') ? $message->get('application_headers') : null;
$retry = 0;
if ($headers instanceof AMQPTable) {
$native = method_exists($headers, 'getNativeData') ? $headers->getNativeData() : (array) $headers;
$retry = (int) ($native['x-retry-count'] ?? 0);
}
if ($retry < 2) { // 第1、2次失败重试;第3次进入死信
$newHeaders = $headers ? clone $headers : new AMQPTable();
$newHeaders->set('x-retry-count', $retry + 1);
$newMsg = new AMQPMessage($message->getBody(), [
'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
'application_headers' => $newHeaders,
]);
$this->mqChannel->basic_publish($newMsg, $this->exchange, $this->routingKey);
$message->ack();
Log::warning('静态化消息重试: ' . ($retry + 1));
} else {
// 拒绝且不重入队,自动进入 DLQ(队列已配置DLX)
$message->reject(false);
Log::error('静态化消息进入死信队列');
}
}
// 生成:按URL(HTTP自调用)
protected function generateByUrl(string $url, bool $force = false, ?string $jobId = null): void
{
$path = parse_url($url, PHP_URL_PATH) ?: '/';
// 确保进度初始化(仅当不存在时)
$progressKey = $jobId ? 'static_progress_' . $jobId : null;
$shouldFinish = false;
if ($jobId) {
$existing = cache($progressKey);
if (!$existing) {
// 单URL任务,自动初始化并在结束时finish
$this->progressStart($jobId, 'url', 1);
$shouldFinish = true;
}
}
[$code, $body] = $this->httpFetch($path);
$this->writeHtml($path, $code, $body, $force);
// 生成对应的骨架页
$this->generateSkeletonPage($path, $force);
if ($jobId) {
// warmup任务由Controller初始化,这里只递增
$data = cache($progressKey);
if ($data && ($data['scope'] ?? '') === 'warmup') {
$this->progressTick($jobId, 0, $path, true);
// 检查是否全部完成
$updated = cache($progressKey);
if ($updated && ($updated['current'] ?? 0) >= ($updated['total'] ?? 0)) {
$this->progressFinish($jobId);
}
} else {
// 单URL任务
$this->progressTick($jobId, 1, $path, false);
if ($shouldFinish) {
$this->progressFinish($jobId);
}
}
}
}
// 生成:按范围(带进度)
protected function generateByScope(string $scope, int $pages = 1, bool $force = false, ?string $jobId = null, bool $skipProgress = false): void
{
// 估算总数
$total = 0;
if ($scope === 'index') {
$total = max(1, $pages) + 1; // /page/1..N + /
} elseif ($scope === 'list') {
$total = max(1, $pages) + 1; // /link/page/1..N + /link
} elseif ($scope === 'post') {
$total = (int) Post::where('status', 'published')->count('*');
} elseif ($scope === 'all') {
$total = (max(1, $pages) + 1) // index
+ (max(1, $pages) + 1) // list
+ (int) Post::where('status', 'published')->count('*')
+ 1; // /search
}
// 仅在非子任务时初始化进度
if ($jobId && !$skipProgress) {
$this->progressStart($jobId, $scope, $total);
}
$done = 0;
switch ($scope) {
case 'index':
for ($p = 1; $p <= $pages; $p++) {
$path = "/page/$p";
[$code, $body] = $this->httpFetch($path);
$this->writeHtml($path, $code, $body, $force);
$this->generateSkeletonPage($path, $force);
$done++;
if ($jobId) {
$this->progressTick($jobId, $done, $path, $skipProgress);
}
}
$path = '/';
[$code, $body] = $this->httpFetch($path);
$this->writeHtml($path, $code, $body, $force);
$this->generateSkeletonPage($path, $force);
$done++;
if ($jobId) {
$this->progressTick($jobId, $done, $path, $skipProgress);
}
break;
case 'list':
for ($p = 1; $p <= $pages; $p++) {
$path = "/link/page/$p";
[$code, $body] = $this->httpFetch($path);
$this->writeHtml($path, $code, $body, $force);
$this->generateSkeletonPage($path, $force);
$done++;
if ($jobId) {
$this->progressTick($jobId, $done, $path, $skipProgress);
}
}
$path = '/link';
[$code, $body] = $this->httpFetch($path);
$this->writeHtml($path, $code, $body, $force);
$this->generateSkeletonPage($path, $force);
$done++;
if ($jobId) {
$this->progressTick($jobId, $done, $path, $skipProgress);
}
break;
case 'post':
$posts = Post::where('status', 'published')->select(['slug', 'id'])->get();
foreach ($posts as $post) {
$keyword = $post->slug ?? $post->id;
$path = "/post/$keyword";
[$code, $body] = $this->httpFetch($path);
$this->writeHtml($path, $code, $body, $force);
$this->generateSkeletonPage($path, $force);
$done++;
if ($jobId) {
$this->progressTick($jobId, $done, $path, $skipProgress);
}
}
break;
case 'all':
// 子任务不再单独管理进度,直接累加到总进度
$this->generateByScope('index', $pages, $force, $jobId, true);
$this->generateByScope('list', $pages, $force, $jobId, true);
$this->generateByScope('post', $pages, $force, $jobId, true);
$path = '/search';
[$code, $body] = $this->httpFetch($path);
$this->writeHtml($path, $code, $body, $force);
$this->generateSkeletonPage($path, $force);
$done++;
if ($jobId) {
$this->progressTick($jobId, $done, $path, true);
}
break;
default:
Log::warning('未知静态化范围: ' . $scope);
}
// 仅在非子任务时结束进度
if ($jobId && !$skipProgress) {
$this->progressFinish($jobId);
}
}
protected function writeHtml(string $urlPath, int $code, string $body, bool $force = false, array $options = []): void
{
if ($code !== 200) {
Log::warning("渲染非200,跳过: {$urlPath}, code={$code}");
return;
}
// 处理CSRF token占位符,替换为空值,由前端JavaScript动态填充
$body = $this->processCsrfTokens($body);
// 按策略决定是否做 JS/CSS 压缩替换(若库缺失则自动跳过)
$body = $this->maybeMinifyHtml($urlPath, $body);
$target = $this->mapPath($urlPath);
// 获取缓存版本和策略
$version = EnhancedStaticCacheConfig::getCacheVersion();
$strategy = EnhancedStaticCacheConfig::getCacheStrategy($urlPath);
$strategyType = $strategy['type'] ?? 'public';
// 生成缓存键(使用虚拟 request)
$mockRequest = new \stdClass();
$mockRequest->path = function () use ($urlPath) { return $urlPath; };
$cacheKey = EnhancedStaticCacheConfig::getCacheKey($urlPath, $strategy, $mockRequest);
// 使用版本化目录结构
$versionDir = substr($cacheKey, 0, 8);
$baseDir = public_path() . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR . 'static';
// 目录:正式与临时
$final = $baseDir . DIRECTORY_SEPARATOR . $versionDir . DIRECTORY_SEPARATOR . $target;
$stage = public_path() . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR . 'static_tmp' . DIRECTORY_SEPARATOR . $versionDir . DIRECTORY_SEPARATOR . $target;
// 确保目录存在
$finalDir = dirname($final);
$stageDir = dirname($stage);
if (!is_dir($finalDir)) {
if (!mkdir($finalDir, 0o775, true)) {
throw new RuntimeException("无法创建目录: {$finalDir}");
}
}
if (!is_dir($stageDir)) {
if (!mkdir($stageDir, 0o775, true)) {
throw new RuntimeException("无法创建目录: {$stageDir}");
}
}
// 1) 将页面写入临时目录文件
if (file_exists($stage)) {
@unlink($stage);
}
file_put_contents($stage, $body);
// 2) 若非强制且正式文件已存在,则保留旧缓存,丢弃临时文件
if (!$force && file_exists($final)) {
@unlink($stage);
return;
}
// 3) 删除旧正式文件(若有),再将临时文件移动到正式目录
if (file_exists($final)) {
@unlink($final);
}
// 跨目录移动(同盘 rename 即为移动)
@rename($stage, $final);
// 记录缓存生成
EnhancedStaticCacheConfig::recordCacheGenerated();
Log::info("静态页面生成(v{$version}, {$strategyType}): {$final}");
}
/**
* 处理HTML中的CSRF token,替换为占位符
*
* @param string $html HTML内容
*
* @return string 处理后的HTML
*/
protected function processCsrfTokens(string $html): string
{
// 替换隐藏的CSRF token输入框
$html = preg_replace_callback(
'#<input[^>]+type=["\']hidden["\'][^>]+name=["\']_token["\'][^>]+value=["\'][^"\']+["\'][^>]*>#i',
function ($matches) {
// 保留原始input标签的其他属性,但将value替换为占位符
$inputTag = $matches[0];
$processedTag = preg_replace(
'/value=["\'][^"\']*["\']/i',
'value="" data-csrf-placeholder="true"',
$inputTag
);
return $processedTag;
},
$html
);
// 添加CSRF token处理脚本
$script = '<script>
(function() {
// 等待DOM加载完成
document.addEventListener("DOMContentLoaded", function() {
// 查找所有CSRF占位符
var csrfInputs = document.querySelectorAll(\'input[data-csrf-placeholder="true"]\');
if (csrfInputs.length > 0) {
// 从Cookie中获取CSRF token
function getCsrfToken() {
// 尝试从多个可能的Cookie名称获取
var cookies = document.cookie.split(\';\');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// 检查_token或XSRF-TOKEN
if (cookie.indexOf("_token=") === 0) {
return cookie.substring("_token=".length);
}
if (cookie.indexOf("XSRF-TOKEN=") === 0) {
return cookie.substring("XSRF-TOKEN=".length);
}
}
return null;
}
var token = getCsrfToken();
if (token) {
// 填充所有占位符
csrfInputs.forEach(function(input) {
input.value = token;
});
} else {
// Cookie中没有token,记录警告但不进行API请求
console.warn("CSRF token not found in cookies");
}
}
});
})();
</script>';
// 在</body>标签前插入脚本
if (strpos($html, '</body>') !== false) {
$html = str_replace('</body>', $script . '</body>', $html);
} else {
// 如果没有</body>标签,直接在末尾添加
$html .= $script;
}
return $html;
}
/**
* 若URL策略启用minify,则对HTML中的本地JS/CSS进行压缩与引用改写
* - 需要 matthiasmullie/minify 库;若不存在则跳过并记录日志
*/
protected function maybeMinifyHtml(string $urlPath, string $html): string
{
try {
$strategies = (array) (blog_config('static_url_strategies', [], true) ?: []);
$needMinify = false;
$pathVariants = [$urlPath, rtrim($urlPath, '/'), $this->mapPath($urlPath)];
foreach ($strategies as $it) {
$u = (string) ($it['url'] ?? '');
if (!$u) {
continue;
}
// 允许匹配 /path 与 /path.html 两种写法
if (in_array($u, $pathVariants, true) || $u === $urlPath) {
if (!empty($it['enabled']) && !empty($it['minify'])) {
$needMinify = true;
}
break;
}
}
if (!$needMinify) {
return $html;
}
if (!class_exists(JS::class) || !class_exists(CSS::class)) {
Log::warning('minify库未安装,已跳过JS/CSS压缩(composer require matthiasmullie/minify)');
return $html;
}
// 仅处理本地资源:/ 开头的 src/href
$public = rtrim((string) public_path(), DIRECTORY_SEPARATOR);
$minBaseUrl = '/assets/min';
$minBaseDir = $public . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . 'min';
if (!is_dir($minBaseDir)) {
@mkdir($minBaseDir, 0o775, true);
}
// 替换 <script src="..."> 与 <link rel="stylesheet" href="...">
$replaced = $html;
// JS
$replaced = preg_replace_callback('#(<script[^>]+src=["\'])(/[^"\']+?\.js)(["\'][^>]*>\s*</script>)#i', function ($m) use ($public, $minBaseDir, $minBaseUrl) {
$src = $m[2];
$srcPath = $public . str_replace('/', DIRECTORY_SEPARATOR, $src);
if (!is_file($srcPath)) {
return $m[0];
}
$hash = @md5_file($srcPath) ?: md5($srcPath . '|' . (string) @filemtime($srcPath));
$outRel = $minBaseUrl . '/' . $hash . '.js';
$outPath = $minBaseDir . DIRECTORY_SEPARATOR . $hash . '.js';
if (!file_exists($outPath)) {
try {
$minifier = new JS($srcPath);
$minifier->minify($outPath);
} catch (Throwable $e) {
Log::warning('JS压缩失败,回退原始: ' . $e->getMessage());
return $m[0];
}
}
// 记录映射
try {
$mtime = (int) @filemtime($srcPath);
AssetMinifyRegistry::put($hash, 'js', $srcPath, $mtime);
} catch (Throwable $e) {
}
return $m[1] . $outRel . $m[3];
}, $replaced);
// CSS
$replaced = preg_replace_callback('#(<link[^>]+href=["\'])(/[^"\']+?\.css)(["\'][^>]*>)#i', function ($m) use ($public, $minBaseDir, $minBaseUrl) {
$href = $m[2];
$hrefPath = $public . str_replace('/', DIRECTORY_SEPARATOR, $href);
if (!is_file($hrefPath)) {
return $m[0];
}
$hash = @md5_file($hrefPath) ?: md5($hrefPath . '|' . (string) @filemtime($hrefPath));
$outRel = $minBaseUrl . '/' . $hash . '.css';
$outPath = $minBaseDir . DIRECTORY_SEPARATOR . $hash . '.css';
if (!file_exists($outPath)) {
try {
$minifier = new CSS($hrefPath);
$minifier->minify($outPath);
} catch (Throwable $e) {
Log::warning('CSS压缩失败,回退原始: ' . $e->getMessage());
return $m[0];
}
}
// 记录映射
try {
$mtime = (int) @filemtime($hrefPath);
AssetMinifyRegistry::put($hash, 'css', $hrefPath, $mtime);
} catch (Throwable $e) {
}
return $m[1] . $outRel . $m[3];
}, $replaced);
return $replaced;
} catch (Throwable $e) {
Log::warning('HTML压缩替换异常,已回退原始: ' . $e->getMessage());
return $html;
}
}
// URL -> 相对文件路径(相对于 public/static)
protected function mapPath(string $urlPath): string
{
$path = ltrim($urlPath, '/');
if ($path === '' || $path === '/') {
return 'index.html';
}
// 去除可能的 .html 后缀
$path = preg_replace('#\.html$#', '', $path);
// 归一化
return $path . '.html';
}
// 计算基础访问地址:优先 static_base_url,其次 scheme://host[:port]
protected function getBaseUrl(): string
{
$base = (string) blog_config('static_base_url', '', true);
if ($base !== '') {
return rtrim($base, '/');
}
$scheme = (string) blog_config('site_scheme', 'http', true);
$host = (string) blog_config('site_host', '127.0.0.1', true);
$port = (int) blog_config('site_port', 8787, true);
// 常见端口省略
$portPart = ($port === 80 && $scheme === 'http') || ($port === 443 && $scheme === 'https') ? '' : ':' . $port;
return $scheme . '://' . $host . $portPart;
}
// 通过 HTTP 获取页面内容(返回 [code, body])
protected function httpFetch(string $path): array
{
$url = $this->getBaseUrl() . (str_starts_with($path, '/') ? $path : '/' . $path);
$ch = curl_init();
$headers = [
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'User-Agent: StaticGenerator/1.0',
// 添加绕过首屏快速加载的请求头
'X-INSTANT-BYPASS: 1',
];
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 15,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_SSL_VERIFYPEER => false,
]);
$body = curl_exec($ch);
if ($body === false) {
$err = curl_error($ch);
curl_close($ch);
Log::warning("HTTP 获取失败: {$url}, error={$err}");
return [0, ''];
}
$code = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
return [$code, (string) $body];
}
// 每小时增量:最近 N 小时更新的文章
protected function enqueueIncrementalPosts(int $hours): void
{
try {
$since = date('Y-m-d H:i:s', time() - $hours * 3600);
$posts = Post::where('status', 'published')
->where('updated_at', '>=', $since)
->select(['slug', 'id'])
->get();
foreach ($posts as $post) {
$keyword = $post->slug ?? $post->id;
$payload = [
'type' => 'url',
'value' => '/post/' . $keyword,
'options' => ['force' => true],
];
$this->publish($payload);
}
// 同步刷新常用页面(首页与友链页 + 分页2-5)
$this->publish([
'type' => 'url',
'value' => '/',
'options' => ['force' => true],
]);
$this->publish([
'type' => 'url',
'value' => '/link',
'options' => ['force' => true],
]);
Log::info('增量静态化任务入队: ' . count($posts) . ' 篇(含首页/友链及其分页2-5刷新)');
} catch (Throwable $e) {
Log::error('增量入队失败: ' . $e->getMessage());
}
}
// 生产消息
public function publish(array $data): void
{
if (!$this->mqChannel) {
return;
}
$msg = new AMQPMessage(json_encode($data, JSON_UNESCAPED_UNICODE), [
'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
]);
$this->mqChannel->basic_publish($msg, $this->exchange, $this->routingKey);
}
// 进度:开始
protected function progressStart(string $jobId, string $scope, int $total): void
{
$data = [
'job_id' => $jobId,
'scope' => $scope,
'total' => max(0, $total),
'current' => 0,
'status' => 'running',
'started_at' => time(),
'updated_at' => time(),
'current_path' => '',
];
// 将最新任务ID与详情写入缓存,延长TTL以便短任务仍可被查询到
cache('static_progress_latest', $jobId, true, 3600);
cache('static_progress_' . $jobId, $data, true, 900);
}
// 进度:步进
protected function progressTick(string $jobId, int $current, string $path, bool $increment = false): void
{
$key = 'static_progress_' . $jobId;
$data = cache($key) ?: [];
// increment=true 时递增,false 时直接设置
if ($increment) {
$data['current'] = ($data['current'] ?? 0) + 1;
} else {
$data['current'] = $current;
}
$data['updated_at'] = time();
$data['current_path'] = $path;
// 步进更新,刷新TTL
cache($key, $data, true, 900);
}
// 进度:结束
protected function progressFinish(string $jobId): void
{
$key = 'static_progress_' . $jobId;
$data = cache($key) ?: [];
// 防止重复结束
if (isset($data['status']) && $data['status'] === 'finished') {
return;
}
$data['status'] = 'finished';
$data['finished_at'] = time();
$data['updated_at'] = time();
// 保持完成后的进度条可查询一段时间(15分钟)
cache($key, $data, true, 900);
// 写入历史列表(保留最近10条)
$histKey = 'static_progress_history';
$history = cache($histKey) ?: [];
// 检查是否已存在该任务ID(防止重复添加)
$exists = false;
foreach ($history as $item) {
if (($item['job_id'] ?? '') === $jobId) {
$exists = true;
break;
}
}
if (!$exists) {
$summary = [
'job_id' => $data['job_id'] ?? $jobId,
'scope' => $data['scope'] ?? '',
'total' => $data['total'] ?? 0,
'finished_at' => $data['finished_at'] ?? time(),
'duration' => isset($data['started_at']) ? (($data['finished_at'] ?? time()) - $data['started_at']) : null,
'status' => $data['status'] ?? 'finished',
];
// 将最新记录插入列表头部
array_unshift($history, $summary);
// 仅保留最近10条
if (count($history) > 10) {
$history = array_slice($history, 0, 10);
}
// 历史列表保留时长更久(1小时)
cache($histKey, $history, true, 3600);
}
// 清理临时目录
$this->cleanupTempDirectory();
}
/**
* 重建 MQ 连接(自愈机制)
*/
protected function reconnectMq(): void
{
try {
$this->mqChannel = null;
$this->mqConnection = null;
// 等待短暂时间后重建
usleep(500000); // 0.5秒
// 重新初始化 MQ 并启动消费者
$this->initMq();
$this->startConsumer();
Log::info('StaticGenerator MQ连接重建成功');
} catch (Throwable $e) {
Log::error('StaticGenerator MQ连接重建失败: ' . $e->getMessage());
$this->mqChannel = null;
$this->mqConnection = null;
}
}
/**
* 清理临时目录
*/
protected function cleanupTempDirectory(): void
{
try {
$tmpDir = public_path() . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR . 'static_tmp';
if (is_dir($tmpDir)) {
$this->deleteDirectory($tmpDir);
Log::info('StaticGenerator 临时目录已清理: ' . $tmpDir);
}
} catch (Throwable $e) {
Log::warning('StaticGenerator 临时目录清理失败: ' . $e->getMessage());
}
}
/**
* 递归删除目录
*/
protected function deleteDirectory(string $dir): bool
{
if (!is_dir($dir)) {
return false;
}
$items = @scandir($dir);
if ($items === false) {
return false;
}
foreach ($items as $item) {
if ($item === '.' || $item === '..') {
continue;
}
$path = $dir . DIRECTORY_SEPARATOR . $item;
if (is_dir($path)) {
$this->deleteDirectory($path);
} else {
@unlink($path);
}
}
return @rmdir($dir);
}
/**
* 生成骨架页
*
* @param string $urlPath URL路径
* @param bool $force 是否强制重新生成
*/
protected function generateSkeletonPage(string $urlPath, bool $force = false): void
{
try {
$controller = new \app\controller\SkeletonController();
$timestamp = time();
$html = $controller->generateSkeletonHtml($urlPath, $timestamp);
$targetPath = $this->mapSkeletonPath($urlPath);
$versionDir = $this->getSkeletonVersionDir($timestamp);
$baseDir = public_path() . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR . 'skeleton';
$final = $baseDir . DIRECTORY_SEPARATOR . $versionDir . DIRECTORY_SEPARATOR . $targetPath;
$stage = public_path() . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR . 'skeleton_tmp' . DIRECTORY_SEPARATOR . $versionDir . DIRECTORY_SEPARATOR . $targetPath;
$finalDir = dirname($final);
$stageDir = dirname($stage);
if (!is_dir($finalDir)) {
if (!mkdir($finalDir, 0o775, true)) {
throw new RuntimeException("无法创建目录: {$finalDir}");
}
}
if (!is_dir($stageDir)) {
if (!mkdir($stageDir, 0o775, true)) {
throw new RuntimeException("无法创建目录: {$stageDir}");
}
}
if (file_exists($stage)) {
@unlink($stage);
}
file_put_contents($stage, $html);
if (!$force && file_exists($final)) {
@unlink($stage);
return;
}
if (file_exists($final)) {
@unlink($final);
}
@rename($stage, $final);
Log::info("骨架页生成成功: {$final}");
} catch (Throwable $e) {
Log::error('骨架页生成失败: ' . $e->getMessage());
}
}
/**
* URL 转骨架页文件路径
*
* @param string $url
*
* @return string
*/
protected function mapSkeletonPath(string $url): string
{
$path = ltrim($url, '/');
if ($path === '' || $path === '/') {
return 'index.html';
}
$path = preg_replace('#\.html$#', '', $path);
$path = str_replace('/', '_', $path);
return $path . '.html';
}
/**
* 获取骨架页版本目录
*
* @param int $timestamp
*
* @return string
*/
protected function getSkeletonVersionDir(int $timestamp): string
{
return substr(md5($timestamp), 0, 8);
}
public function onWorkerStop(): void
{
try {
if ($this->mqChannel) {
$this->mqChannel->close();
}
// 统一通过 MQService 关闭
MQService::closeConnection();
Log::info('StaticGenerator MQ连接已关闭');
} catch (Throwable $e) {
Log::warning('关闭MQ连接失败: ' . $e->getMessage());
}
}
}